text
stringlengths
15
59.8k
meta
dict
Q: Json file to Room Db I am a newbie on Android Development.I have a json file formatted like this: "users": [{ "id": "1", "name": "Vanessa", "profilepic": "https://.." },... ] I am creating room database but how can I record this user json file into it. I heard about gson but I could not find any solution for my problem A: For this you need to first create a model that can parse this kind of json for you. you can use a pretty neat plugin that I have been sing called json to kotlin class. Steps to install: * *Go to file->settings->plugins *search for json to kotlin and install *now just like you make a new file there will be a new option paste your json and give it a name and now it automatically generates a model for you. *Also I will recommend you to watch some tutorials on youtube, my favorite content creator is Philip Lackener he has a very good tutorial on roomdb I am also new to android development so i get it. I recommend you to go through a beginner playlist it will really help you get the basics. you also need to see basics of roomdb because what you are asking is really basics of roomdb.
{ "language": "en", "url": "https://stackoverflow.com/questions/75137960", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NiFi ListenHTTP processor: Uses an unsupported protocol I have configured a ListenHTTP 1.7.0 processor in NiFi 1.7.0-RC1. It is listening on a custom port behind a reverse proxy. I have configured a StandardRestrictedSSLContextService with a JKS keystore and have added the keystore password. We have not configured the truststore as we don't expect to need mutual TLS. The certificate is signed by an internal enterprise CA and is (or should be!) trusted by the client. When I test this with Chrome I receive the following: This site can’t provide a secure connection my.server uses an unsupported protocol. ERR_SSL_VERSION_OR_CIPHER_MISMATCH Unsupported protocol The client and server don't support a common SSL protocol version or cipher suite. Troubleshooting: * *We have tried both TLS and TLSv1.2 in the ListenHTTP processor. *We have treid using curl (Linux) and Invoke-WebRequest (Windows) but have received variations on the bad cipher/SSL version message above. *I don't see anything in the release notes suggesting that the ListenHTTP processor changed much since 1.7.0, so I'm assuming that I don't need to upgrade NiFi. Can anyone suggest what to try next or explain why we see this error? I have read the following: * *https://www.simonellistonball.com/technology/nifi-ssl-listenhttp/ *https://cwiki.apache.org/confluence/display/NIFI/Release+Notes *Nifi: how to make ListenHTTP work with SSL A: What version of Java are you running on? Java 11 provides TLSv1.3, which is the default offering if you have generic TLS selected, but NiFi 1.7.0 doesn't support TLSv1.3 (and doesn't run on Java 11). So assuming you are running on Java 8, recent updates have introduced TLSv1.3 but should still provide for TLSv1.2. This can also indicate that the certificate you have provided is invalid or incompatible with the cipher suite list provided by the client. You can use $ openssl s_client -connect <host:port> -debug -state -CAfile <path_to_your_CA_cert.pem> to try diagnosing the available cipher suites & protocol versions. Adding -tls1_2 or -tls1_3, etc. will restrict the connection attempt to the specified protocol version as well. You should definitely upgrade from NiFi 1.7.0 -- it was released over 2 years ago, has known issues, and there have been close to 2000 bug fixes and features added since, including numerous security issues. NiFi 1.12.1 is the latest released version.
{ "language": "en", "url": "https://stackoverflow.com/questions/64646057", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to clear facebook stream cache I am using facebook publish_stream method to post feed on facebook user timeline. The post is containing the image URL and title with some description. However the posted image could be change later but that change couldn't reflect on facebook side as they had cached the image. So I wanted to be know how could clear the facebook cache on publish stream so they can show the latest image on user timeline. A: Once a image has been published on Facebook, FB will always show the cached version. if, however, you want to update the image for a new post, try running the URL to the Debug Tool to update Facebook's cache. Any existing posts that use this image won't be updated. It's to prevent people from changing content once it's already shared - otherwise it won't represent what the user originally shared. This would be something spammers could easily abuse.
{ "language": "en", "url": "https://stackoverflow.com/questions/12178497", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: custom dialog border is always white <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@color/yellow" android:orientation="vertical" > <LinearLayout android:id="@+id/progresscontent" android:layout_width="266dp" android:layout_height="52dp" android:layout_margin="8dp" android:background="@color/red" android:orientation="horizontal" > <ProgressBar android:id="@+id/progress" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="12dip" android:visibility="visible" android:padding="5dp" style="@android:style/Widget.ProgressBar.Inverse"/> <TextView android:id="@+id/progressmessage" style="@style/DialogText.Title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingBottom="10dip" android:paddingLeft="40dip" android:paddingTop="10dip" android:textColor="@color/codeFont" android:textSize="15dip" /> </LinearLayout> </LinearLayout> I am trying create my own custom dialog but there is one problem here. Custom dialog border is always showing white color, what's the problem here. Any help please. A: If you want the Dialog Border to appear in any colour you wish you have to use layout style and a theme. There is an excellent article about it here: http://blog.androgames.net/10/custom-android-dialog/
{ "language": "en", "url": "https://stackoverflow.com/questions/8239161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: C++ : Reading file and store data in multi-vector I am trying to read data file with the this format T1: I1,I2,I5 T2: I2,I4 T3: I2,I3 T4: I1,I2,I4 T5: I1,I3 T6: I2,I3 T7: I1,I3 T8: I1,I2,I3,I5 T9: I1,I2,I3 I don't want to read the first column T1,T2,T3 ...... , but each line will be a dataset I want to start read after (space ' ' ) and end with each line and how can I separate the data according to (comma ',') I wrote this code but it didn't work correctly and it reads the first column anyway string CItem; // set of elements set< CItem > CItemSet; //Transactions CItemSet CTransaction; // set of transactions vector< CTransaction > CTransactionSet; ifstream inFile(inFileName); if (!inFile) { cout << "Failed to open input file filename:." << inFileName; } CTransactionSet transSet; CTransaction tran; string txtLine; // read every line from the stream while (getline(inFile, txtLine)) { istringstream txtStream(txtLine); string txtElement; // read every element from the line that is seperated by commas // and put it into the vector or strings while (getline(txtStream, txtElement, ',')) { if (txtElement == ": ") break; else tran.insert(txtElement); } transSet.push_back(tran); } A: Since you have CTransaction tran; outside the first while loop, items keep getting added to it. Move it inside the while loop. CTransactionSet transSet; string txtLine; // read every line from the stream while (getline(inFile, txtLine)) { CTransaction tran; A: I solve the problem by doing what you said R Sahu but the most important solution is by using .ignore so we don't read the part before the ' ' CTransactionSet transSet; string txtLine; // read every line from the stream while (getline(inFile, txtLine)) { istringstream txtStream(txtLine); txtStream.ignore(txtLine.length(), ' '); // read every element from the line that is seperated by commas // and put it into the vector or strings string txtElement; CTransaction tran; while (getline(txtStream, txtElement, ',')) { tran.insert(txtElement); } transSet.push_back(tran); }
{ "language": "en", "url": "https://stackoverflow.com/questions/32834518", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: System has not been booted with systemd ERROR when updating Postgresql in Ubuntu I've been following this link to update Postgresql on my Ubuntu-18.04 (VM running on Windows 10) https://computingforgeeks.com/install-postgresql-12-on-ubuntu/ However, Im getting the below error, so I cannot proceed. .../desktop/my_app$ systemctl status postgresql.service System has not been booted with systemd as init system (PID 1). Can't operate. What can I do? A: service postgresql status or systemctl status postgresql Must work.
{ "language": "en", "url": "https://stackoverflow.com/questions/69663496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: broken pipe when installing NodeJS 16 on Ubuntu 22.04 Trying to install NodeJS 16 on ubuntu 22.04. Ran the official installation instructions: sudo apt-get install -y nodejs Got the following error: The following NEW packages will be installed: nodejs 0 upgraded, 1 newly installed, 0 to remove and 4 not upgraded. Need to get 0 B/27.1 MB of archives. After this operation, 128 MB of additional disk space will be used. Selecting previously unselected package nodejs. (Reading database ... 218989 files and directories currently installed.) Preparing to unpack .../nodejs_16.17.0-deb-1nodesource1_amd64.deb ... Unpacking nodejs (16.17.0-deb-1nodesource1) ... dpkg: error processing archive /var/cache/apt/archives/nodejs_16.17.0-deb-1nodesource1_amd64.deb (--unpack): trying to overwrite '/usr/include/node/common.gypi', which is also in package libnode-dev 12.22.9~dfsg-1ubuntu3 dpkg-deb: error: paste subprocess was killed by signal (Broken pipe) Errors were encountered while processing: /var/cache/apt/archives/nodejs_16.17.0-deb-1nodesource1_amd64.deb E: Sub-process /usr/bin/dpkg returned an error code (1) A: Various versions of Node.js are using a same file (one from apt install, one from manually download), which caused the conflict, resulting the error. Remove your Node.js 12.22.9 first.
{ "language": "en", "url": "https://stackoverflow.com/questions/73698505", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java modulus operator and PreIncrement - SCJA Im revising for my SCJA exam at the minute and im confused by this question and answer. The question is what is the result of running and compiling the code. public class Test{ public static void main(String args[]){ int counter = 0; for(int i=0; i< 4; ++i){ for(int k=0; k< 4; ++k){ system.out.println("Hello - "+ ++counter); if((k % 4) == 0) break; } } } } So the answer they give is "Hello-1" because 0 % 4 = 0 But my question is should k not be 1 because its been pre-incremented? Thanks in advance! A: A for loop has the following structure: for (initialization; condition; update) The update is executed after every execution of the loop. Therefore the following two loops are identical: for (int i = 0; i < 10; i++) { and for (int i = 0; i < 10; ++i) { A: my question is should k not be 1 because its been pre-incremented? The ++k happens at the end of the loop iteration, i.e. after the if statement. It makes no difference whether it's ++k or k++; in either case the first value of k is zero. So the answer they give is "Hello-1" This is clearly incorrect, since counter is never incremented and stays at zero throughout the program. A: k cannot be 1. This is because when a for loop runs, it only updates after it has executed all the code within the loop. Since the loop breaks even before the first iteration is completed, k remains 0.
{ "language": "en", "url": "https://stackoverflow.com/questions/14912487", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java scanner hasNextLine returns null after an object is constructed only once(?) first post. I have a list file with user information I'm trying to create objects out of, to then put into an array list. When it has read the first 4 lines it constructs the object once, and when it loops to continue reading the file it stops because hasNextResult = null. (proof) List file: Lilly Lilly Anderson 193.164.85.111 avatar.img Johnny Jonathan Anderson 224.12.8.94 avatar.img Constructor: public Friend(String nickname, String fullname, String lastip, String image){ this.nickname = nickname; this.fullname =fullname; this.lastip =lastip; this.image =image; } @Override public String toString(){ return nickname + ", " + fullname + ", " + lastip + ", " + image; } Scanner: public static Friend build(InputStream in){ Friend friend; Scanner reader = new Scanner(in, StandardCharsets.UTF_8); if(reader.hasNextLine()){ friend = new Friend(reader.nextLine(), null, null, null); }else{ return null; } if(reader.hasNextLine()){ friend.setFullname(reader.nextLine()); } if(reader.hasNextLine()){ friend.setIp(reader.nextLine()); } if(reader.hasNextLine()){ friend.setImg(reader.nextLine()); } return friend; } Main: public static void main(String[] args) throws FileNotFoundException { List<Friend> al = new ArrayList<>(); FileInputStream reader = new FileInputStream("Friends.list"); Friend f; while((f = Friend.build(reader))!= null){ al.add(f); } Collections.sort(al); printCollection(al.iterator()); } Output: run: Lilly, Lilly Anderson, 193.164.85.111, avatar.img BUILD SUCCESSFUL (total time: 0 seconds) Thanks for reading. A: It tries to read the next line after the last line, Try this: Change the code for the scanner to this: Scanner: public static Friend build(InputStream in, int counter){ Friend friend; Scanner reader = new Scanner(in, StandardCharsets.UTF_8); if(reader.hasNextLine()){ friend = new Friend(reader.nextLine(), null, null, null); }else if(counter < 0){ if(true){ friend.setFullname(reader.readLine()); } if(reader.hasNextLine()){ friend.setIp(reader.nextLine()); } if(reader.hasNextLine()){ friend.setImg(reader.nextLine()); } return friend; } else { return null; } if(reader.hasNextLine()){ friend.setFullname(reader.nextLine()); } if(reader.hasNextLine()){ friend.setIp(reader.nextLine()); } if(reader.hasNextLine()){ friend.setImg(reader.nextLine()); } return friend; } Main: public static void main(String[] args) throws FileNotFoundException { List<Friend> al = new ArrayList<>(); FileInputStream reader = new FileInputStream("Friends.list"); Friend f; int counter = 0; while((f = Friend.build(reader, counter))!= null){ al.add(f); counter++; } Collections.sort(al); printCollection(al.iterator()); } A: Do not create a new Scanner for each friend, try this: public static Friend build(Scanner reader){ Friend friend; if(reader.hasNextLine()){ friend = new Friend(reader.nextLine(), null, null, null); }else{ return null; } if(reader.hasNextLine()){ friend.setFullname(reader.nextLine()); } if(reader.hasNextLine()){ friend.setIp(reader.nextLine()); } if(reader.hasNextLine()){ friend.setImg(reader.nextLine()); } return friend; } and call it like in: ... FileInputStream in = new FileInputStream("Friends.list"); Scanner reader = new Scanner(in, StandardCharsets.UTF_8.name()); Friend f; while((f = Friend.build(reader))!= null){ al.add(f); } ... Reason: Scanner kind of does read ahead the next token(s), so it is/they are already consumed when the next Scanner is created. From its source code: // Internal buffer used to hold input private CharBuffer buf; // Size of internal character buffer private static final int BUFFER_SIZE = 1024; // change to 1024; I would use a BufferedReader instead of Scanner (for reading just lines)
{ "language": "en", "url": "https://stackoverflow.com/questions/66136686", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Excel VBA - CountIfs - Moving from one spreadsheet to another I'm working on a CountIfs formula for a project and am having a little trouble. I'm pulling data from worksheet HR Data Detail and pasting it onto worksheet HR Data Summary. At the end of my CountIfs formula I have the range Z2:Z, which contains the years 2017, 2018, 2019, from worksheet HR Data Summary. I want Cell C2 on HR Data Summary to be a box that I can auto-fill in any year. For example, if I put 2018 into C2 then I want the CountIfs formula to pull the data for that specific year. Sub Linking () 'Defining finRow Sheets("HR Data Detail". Activate) Dim finRow As String finRow = Sheets("HR Data Detail").Range("A50000").End(xlUp).Row With Sheets ("HR Data Detail") 'Division 21 Employees Sheets("HR Data Summary").Range("L4") = _ Application.WorksheetFunction.CountIfs(.Range("V2:V" & finRow), ">0", _ .Range("S2:S" & finRow), "=21", .Range("L2:L" & finRow), "=January", _ .Range("H2:H" & finRow), "=Employee", _ Sheets("HR Data Detail").Range("Z2:Z" & finRow), "'HR Data Summary'!C2") A: Assuming I'm understanding the purpose of this complex COUNTIFS formula - It seems the problem is with the last range/criteria combo. Try changing Sheets("HR Data Detail").Range("Z2:Z" & finRow), "'HR Data Summary'!C2") to the following: .Range("Z2:Z" & finRow), "=" & Sheets("HR Data Summary").Range("$C$2").Value
{ "language": "en", "url": "https://stackoverflow.com/questions/53157003", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to implement monkey patch in C++? Is it possible to implement monkey patching in C++? Or any other similar approach to that? Thanks. A: To add to other answers, consider that any function exposed through a shared object or DLL (depending on platform) can be overridden at run-time. Linux provides the LD_PRELOAD environment variable, which can specify a shared object to load after all others, which can be used to override arbitrary function definitions. It's actually about the best way to provide a "mock object" for unit-testing purposes, since it is not really invasive. However, unlike other forms of monkey-patching, be aware that a change like this is global. You can't specify one particular call to be different, without impacting other calls. A: Considering the "guerilla third-party library use" aspect of monkey-patching, C++ offers a number of facilities: * *const_cast lets you work around zealous const declarations. *#define private public prior to header inclusion lets you access private members. *subclassing and use Parent::protected_field lets you access protected members. *you can redefine a number of things at link time. If the third party content you're working around is provided already compiled, though, most of the things feasible in dynamic languages isn't as easy, and often isn't possible at all. A: I suppose it depends what you want to do. If you've already linked your program, you're gonna have a hard time replacing anything (short of actually changing the instructions in memory, which might be a stretch as well). However, before this happens, there are options. If you have a dynamically linked program, you can alter the way the linker operates (e.g. LD_LIBRARY_PATH environment variable) and have it link something else than the intended library. Have a look at valgrind for example, which replaces (among alot of other magic stuff it's dealing with) the standard memory allocation mechanisms. A: Not portably so, and due to the dangers for larger projects you better have good reason. The Preprocessor is probably the best candidate, due to it's ignorance of the language itself. It can be used to rename attributes, methods and other symbol names - but the replacement is global at least for a single #include or sequence of code. I've used that before to beat "library diamonds" into submission - Library A and B both importing an OS library S, but in different ways so that some symbols of S would be identically named but different. (namespaces were out of the question, for they'd have much more far-reaching consequences). Similary, you can replace symbol names with compatible-but-superior classes. e.g. in VC, #import generates an import library that uses _bstr_t as type adapter. In one project I've successfully replaced these _bstr_t uses with a compatible-enough class that interoperated better with other code, just be #define'ing _bstr_t as my replacement class for the #import. Patching the Virtual Method Table - either replacing the entire VMT or individual methods - is somethign else I've come across. It requires good understanding of how your compiler implements VMTs. I wouldn't do that in a real life project, because it depends on compiler internals, and you don't get any warning when thigns have changed. It's a fun exercise to learn about the implementation details of C++, though. One application would be switching at runtime from an initializer/loader stub to a full - or even data-dependent - implementation. Generating code on the fly is common in certain scenarios, such as forwarding/filtering COM Interface calls or mapping OS Window Handles to library objects. I'm not sure if this is still "monkey-patching", as it isn't really toying with the language itself. A: As monkey patching refers to dynamically changing code, I can't imagine how this could be implemented in C++...
{ "language": "en", "url": "https://stackoverflow.com/questions/1584907", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to calculate the rank of a list without pandas and numpy? i've written the following code: s = [2,1,-99,100,45,-2] li=[] for i in range(len(s)): li.append([s[i],i]) li.sort() sort_index = [] for x in li: sort_index.append(x[1]) print(sort_index) this gives the output as :[2, 5, 1, 0, 4, 3] required output : [4,3,1,6,5,2] I need the rank such that the output is the rank of the first element of s what are the suggested changes in my code to find the rank. And we shouldn't use numpy and pandas A: Ranking in this context appears to be in terms of sorted order. For that purpose one can compare the position of the elements in the original list against a sorted list to get the correct answer. Example: s = [2,1,-99,100,45,-2] sorted_s = sorted(s) ranked_s = [ sorted_s.index(value) + 1 for value in s ] print(rank) Output: [4, 3, 1, 6, 5, 2]
{ "language": "en", "url": "https://stackoverflow.com/questions/66412446", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: something wrong with this jquery? There is a debugging syntax error, but I can’t see it! im a bit of a newbie, so excuse my code!! $(document).ready(function(){ /* fetch elements and stop form event */ $("form.follow-form").submit(function (e) { /* stop event */ e.preventDefault(); /* "on request" */ $(this).find('i').addClass('active'); /* send ajax request */ $.ajax({ type: "POST", url: "ajax_more.php", data: $(this).serialize(), cache: false, success: function(html){ $("ul.statuses").append(html); $("form.follow-form").remove(); } }); else { $(".morebox").html('The End'); } return false; }); }); A: Try this $(document).ready(function() { /* fetch elements and stop form event */ $("form.follow-form").submit(function(e) { /* stop event */ e.preventDefault(); /* "on request" */ $(this).find('i').addClass('active'); /* send ajax request */ $.ajax({ type: "POST", url: "ajax_more.php", data: $(this).serialize(), cache: false, success: function(html) { $("ul.statuses").append(html); $("form.follow-form").remove(); } }); $(".morebox").html('The End'); return false; }); });​ A: You’ve got an else, but no if. Here’s the code with some proper indentation — indentation makes the code much easier to understand, so you spot errors more quickly. $(document).ready(function(){ /* fetch elements and stop form event */ $("form.follow-form").submit(function (e) { /* stop event */ e.preventDefault(); /* "on request" */ $(this).find('i').addClass('active'); /* send ajax request */ $.ajax({ type: "POST", url: "ajax_more.php", data: $(this).serialize(), cache: false, success: function(html){ $("ul.statuses").append(html); $("form.follow-form").remove(); } }); ======> /* HERE’S THE ELSE WITHOUT AN IF */ else { $(".morebox").html('The End'); } return false; }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/3769649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Perl - How to change every $variable occurrence of ";" in a string Very new here so be gentle. :) Here is the jist of what I want to do: I want to take a string that is made up of numbers separated by semi-colons (ex. 6;7;8;9;1;17;4;5;90) and replace every "X" number of semicolons with a "\n" instead. The "X" number will be defined by the user. So if: $string = "6;7;8;9;1;17;4;5;90"; $Nth_number_of_semicolons_to_replace = 3; The output should be: 6;7;8\n9;1;17\n4;5;90 I've found lots on changing the Nth occurrence of something but I haven't been able to find anything on changing every Nth occurrence of something like I am trying to describe above. Thanks for all your help! A: use List::MoreUtils qw(natatime); my $input_string = "6;7;8;9;1;17;4;5;90"; my $it = natatime 3, split(";", $input_string); my $output_string; while (my @vals = $it->()) { $output_string .= join(";", @vals)."\n"; } A: Here is a quick and dirty answer. my $input_string = "6;7;8;9;1;17;4;5;90"; my $count = 0; $input_string =~ s/;/++$count % 3 ? ";" : "\n"/eg; A: Don't have time for a full answer now, but this should get you started. $string = "6;7;8;9;1;17;4;5;90"; $Nth_number_of_semicolons_to_replace = 3; my $regexp = '(' . ('\d+;' x ($Nth_number_of_semicolons_to_replace - 1)) . '\d+);'; $string =~ s{ $regexp ) ; }{$1\n}xsmg A: sub split_x{ my($str,$num,$sep) = @_; return unless defined $str; $num ||= 1; $sep = ';' unless defined $sep; my @return; my @tmp = split $sep, $str; while( @tmp >= $num ){ push @return, join $sep, splice @tmp, 0, $num; } push @return, join $sep, @tmp if @tmp; return @return; } print "$_\n" for split_x '6;7;8;9;1;17;4;5;90', 3 print join( ',', split_x( '6;7;8;9;1;17;4;5;90', 3 ) ), "\n"; A: my $string = "6;7;8;9;1;17;4;5;90"; my $Nth_number_of_semicolons_to_replace = 3; my $num = $Nth_number_of_semicolons_to_replace - 1; $string =~ s{ ( (?:[^;]+;){$num} [^;]+ ) ; }{$1\n}gx; print $string; prints: 6;7;8 9;1;17 4;5;90 The regex explained: s{ ( # start of capture group 1 (?:[^;]+;){$num} # any number of non ';' characters followed by a ';' # repeated $num times [^;]+ # any non ';' characters ) # end of capture group ; # the ';' to replace }{$1\n}gx; # replace with capture group 1 followed by a new line A: If you've got 5.10 or higher, this could do the trick: #!/usr/bin/perl use strict; use warnings; my $string = '1;2;3;4;5;6;7;8;9;0'; my $n = 3; my $search = ';.*?' x ($n -1); print "string before: [$string]\n"; $string =~ s/$search\K;/\n/g; print "print string after: [$string]\n"; HTH, Paul
{ "language": "en", "url": "https://stackoverflow.com/questions/5032927", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Set button and textView weight programmatically I'm creating a basic to-do app, when the event addRow is called, I want to programmatically add the XML layout below (a new row containing a text and button) How can I create the following layout programmatically? <TableLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/main_table" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintHorizontal_bias="0.466" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toTopOf="@+id/ll_component_container"> <TableRow android:layout_width="match_parent" android:layout_marginTop="30dp" android:id="@+id/tab1" android:weightSum="5" android:layout_height="84dp"> <TextView android:id="@+id/textView1" android:layout_width="fill_parent" android:layout_weight="4" android:paddingLeft="20dp" android:textColor="#FFFFFF" android:layout_height="wrap_content" android:text="Value1" android:textAppearance="?android:attr/textAppearanceSmall"/> <Button android:text="Remove" android:background="#fc032c" android:layout_marginRight="20dp" android:layout_weight="1" android:layout_height="40dp" android:id="@+id/button1"/> </TableRow> </TableLayout> I've tried this, but I can't find how to change neither the weight nor the button marginRight. private fun addRow(content: Editable) { val tl = findViewById<TableLayout>(R.id.main_table) val _id = View.generateViewId() val tr_head = TableRow(this) tr_head.id = _id tr_head.layoutParams = TableRow.LayoutParams( TableRow.LayoutParams.MATCH_PARENT, 84, 5f ) val label = TextView(this) label.id = View.generateViewId() label.text = content label.setTextColor(Color.WHITE) label.setPadding(20, 0,0,0) tr_head.addView(label) val btn = Button(this) btn.id = _id + 1 btn.setBackgroundColor(Color.RED) btn.setText("Remove") tr_head.addView(label) tr_head.addView(btn) tl.addView( tr_head, TableLayout.LayoutParams( TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT ) ) } A: I found another way around to accomplish what I wanted, so instead of using weight I used the screen width in order to get a relative width. and to add margin, I just added an empty row before the row that contains the button and text. Here is the full code for the interested. private fun addRow(content: Editable) { val tl = findViewById<TableLayout>(R.id.main_table) val margin = TableRow(this) val tr_head = TableRow(this) margin.id = View.generateViewId() tr_head.id = View.generateViewId() val tabParams = TableRow.LayoutParams( TableRow.LayoutParams.MATCH_PARENT, 84 ) tr_head.setLayoutParams(tabParams) val label = TextView(this) label.id = View.generateViewId() label.text = content label.setTextColor(Color.WHITE) val displayMetrics = DisplayMetrics() windowManager.defaultDisplay.getMetrics(displayMetrics) label.width = (displayMetrics.widthPixels / 3)*2 label.setPadding(50, 0,0,0) tr_head.addView(label) val btn = Button(this) btn.id = View.generateViewId() btn.width = (displayMetrics.widthPixels / 3) - 50 btn.setBackgroundColor(Color.RED) btn.setText("Remove") btn.setOnClickListener { tl.removeView(tr_head) tl.removeView(margin) } label.id = View.generateViewId() val filler = TextView(this) filler.id = View.generateViewId() margin.addView(filler) tr_head.addView(btn) tl.addView( margin, TableLayout.LayoutParams( TableRow.LayoutParams.MATCH_PARENT, 20 ) ) tl.addView( tr_head, tabParams ) }
{ "language": "en", "url": "https://stackoverflow.com/questions/61432562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Which Thread will a Service run in? I have an Activity A that starts a service S via startService method. Now as per the documentation Service S will run on main thread or the UI thread Now my question is when activity A is destroyed will the UI thread still exist? What will happen if I reopen the Activity A through its launcher icon will there be two UI threads spawned in total? Thanks in Advance. A: On Android platform: MainThread == UiThread == "ApplicationThread" (it doesn't really exists), so in your case the new Activity will NOT start a new Service but Service's OnStartCommand() method will be raised. The Service will continue to run in the "ApplicationThread". A: According to the Android Developer Doc, A service runs in the main thread of its hosting process; the service does not create its own thread and does not run in a separate process unless you specify otherwise. A: When you start an app by clicking on app's icon on launcher or home screen, Android will create a process for the app with a single thread (aka main or UI thread) of execution. This thread will exist even though there is no component started, such as Activity, Service, BroadcastReceiver, ContentProvider. Then, it will find and start the default or entry activity for the app (which defined in AndroidManifest.xml file). I have an Activity A that starts a service S via startService method. Now as per the documentation Service S will run on main thread or the UI thread Now my question is when activity A is destroyed will the UI thread still exist? Yes, UI thread still exist. What will happen if I reopen the Activity A through its launcher icon will there be two UI threads spawned in total? When you finish Activity A, Android does not destroy the process for the application at that time. It will keep the application in the memory for faster loading if you start the app later. So when you reopen the Activity A, if there is a process for that application exists already, then the Activity A is started within that process and uses the same thread of execution. Otherwise, Android will create a new process for the application. Which Thread will a Service run in? By default, all components (including Service) of the same application run in the same process and thread (called the main or UI thread). You can find more details in this link: https://developer.android.com/guide/components/processes-and-threads
{ "language": "en", "url": "https://stackoverflow.com/questions/55226363", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CMake subdirectory install/uninstall targets I've got a project with two subdirectory projects (added with add_subdirectory), each with their own libraries, binaries and install/uninstall targets. So: main_project | |--CMakeLists.txt |--src/ |--CMakeLists.txt (with binary target, install() | |--project_a |--CMakeLists.txt |--src/ |--CMakeLists.txt (with library, install()) | |--project_b |--CMakeLists.txt |--src/ |--CMakeLists.txt (with library, install()) I'd like for the top-level project (main_project) to automatically install the libraries a and b (included in main_project from target_link_libraries()). So, I'd like to be able to go: cd main_project/build cmake .. make sudo make install and have the main_project binary and project_a/b libraries installed automatically. I've tried this: main_project/src/CMakeLists.txt ... install(FILES main project_a project_b DESTINATION bin LIBRARY DESTINATION lib) but a cmake .. results in install TARGETS given target "project_a" which does not exist in this directory. as expected. I've also tried specifying a path: main_project/src/CMakeLists.txt ... install(FILES main ${CMAKE_SOURCE_DIR}/project_a/ ${CMAKE_SOURCE_DIR}/project_b DESTINATION bin LIBRARY DESTINATION lib) which also complains that project_a/b are not in this directory (also expected, I guess?) I've also tried installing the libraries "manually" with the FILES option in install(), and that works just fine, but that seems very kludgy considering there are perfectly good install()s in the subprojects. One additional issue: since project_a and project_b also have uninstall() custom targets, I can't add an uninstall target to the main_project without CMake complaining about the custom target already existing. When I try adding an uninstall directive to the top dir CMakeLists: add_custom_target(uninstall COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake) But, since my project_a has an uninstall directive, I get: CMake Error at CMakeLists.txt:37 (add_custom_target): add_custom_target cannot create target "uninstall" because another target with the same name already exists. The existing target is a custom target created in source directory "/main_project/project_a". See documentation for policy CMP0002 for more details. So, how do I install and uninstall the necessary library files from my subproject alongside my main_project? A: I found the problem. I am adding the subdirectory I want to install with EXCLUDE_FROM_ALL such that it doesn't build everything in the subdirectory, only the library I need. That flag seems to prevent the subdirectory install() from happening. Perhaps ExternalProject_Add is indeed the best way to go here... Also, RE overriding custom targets, this worked for me: http://public.kitware.com/pipermail/cmake/2011-July/045269.html
{ "language": "en", "url": "https://stackoverflow.com/questions/39361089", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Getting distance from Google Direction API in Android http://maps.googleapis.com/maps/api/directions/json?origin=-20.291825,57.448668&destination=-20.179724,57.613463&sensor=false&mode=%22DRIVING%22 For example this link generate the following: "routes" : [ { "bounds" : { "northeast" : { "lat" : -20.1765204, "lng" : 57.6137001 }, "southwest" : { "lat" : -20.2921672, "lng" : 57.4472155 } }, "copyrights" : "Map data ©2014 Google", "legs" : [ { "distance" : { "text" : "24.6 km", "value" : 24628 }, i want to extract only the distance and display it in android A: To get a distance from a Google Maps you can use Google Directions API and JSON parser to retrieve the distance value. Sample Method private double getDistanceInfo(double lat1, double lng1, String destinationAddress) { StringBuilder stringBuilder = new StringBuilder(); Double dist = 0.0; try { destinationAddress = destinationAddress.replaceAll(" ","%20"); String url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + latFrom + "," + lngFrom + "&destination=" + latTo + "," + lngTo + "&mode=driving&sensor=false"; HttpPost httppost = new HttpPost(url); HttpClient client = new DefaultHttpClient(); HttpResponse response; stringBuilder = new StringBuilder(); response = client.execute(httppost); HttpEntity entity = response.getEntity(); InputStream stream = entity.getContent(); int b; while ((b = stream.read()) != -1) { stringBuilder.append((char) b); } } catch (ClientProtocolException e) { } catch (IOException e) { } JSONObject jsonObject = new JSONObject(); try { jsonObject = new JSONObject(stringBuilder.toString()); JSONArray array = jsonObject.getJSONArray("routes"); JSONObject routes = array.getJSONObject(0); JSONArray legs = routes.getJSONArray("legs"); JSONObject steps = legs.getJSONObject(0); JSONObject distance = steps.getJSONObject("distance"); Log.i("Distance", distance.toString()); dist = Double.parseDouble(distance.getString("text").replaceAll("[^\\.0123456789]","") ); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return dist; } For details on parameters and more details on what are the different options available, please refer this. https://developers.google.com/maps/documentation/directions/ A: public class ApiDirectionsAsyncTask extends AsyncTask<URL, Integer, StringBuilder> { private static final String TAG = makeLogTag(ApiDirectionsAsyncTask.class); private static final String DIRECTIONS_API_BASE = "https://maps.googleapis.com/maps/api/directions"; private static final String OUT_JSON = "/json"; // API KEY of the project Google Map Api For work private static final String API_KEY = "YOUR_API_KEY"; @Override protected StringBuilder doInBackground(URL... params) { Log.i(TAG, "doInBackground of ApiDirectionsAsyncTask"); HttpURLConnection mUrlConnection = null; StringBuilder mJsonResults = new StringBuilder(); try { StringBuilder sb = new StringBuilder(DIRECTIONS_API_BASE + OUT_JSON); sb.append("?origin=" + URLEncoder.encode("Your origin address", "utf8")); sb.append("&destination=" + URLEncoder.encode("Your destination address", "utf8")); sb.append("&key=" + API_KEY); URL url = new URL(sb.toString()); mUrlConnection = (HttpURLConnection) url.openConnection(); InputStreamReader in = new InputStreamReader(mUrlConnection.getInputStream()); // Load the results into a StringBuilder int read; char[] buff = new char[1024]; while ((read = in.read(buff)) != -1){ mJsonResults.append(buff, 0, read); } } catch (MalformedURLException e) { Log.e(TAG, "Error processing Distance Matrix API URL"); return null; } catch (IOException e) { System.out.println("Error connecting to Distance Matrix"); return null; } finally { if (mUrlConnection != null) { mUrlConnection.disconnect(); } } return mJsonResults; } } I hope that help you! A: Just check below link. You will probably get idea of it and try it on your own. http://about-android.blogspot.in/2010/03/sample-google-map-driving-direction.html Also you can use Google Distance Matrix API https://developers.google.com/maps/documentation/distancematrix/ A: String url = getDirectionsUrl(pickupLatLng, dropLatLng); new GetDisDur().execute(url); Create URL using latlng private String getDirectionsUrl(LatLng origin, LatLng dest) { String str_origin = "origin=" + origin.latitude + "," + origin.longitude; String str_dest = "destination=" + dest.latitude + "," + dest.longitude; String sensor = "sensor=false"; String mode = "mode=driving"; String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + mode; String output = "json"; return "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters; } Class GetDisDur private class GetDisDur extends AsyncTask<String, String, String> { @Override protected String doInBackground(String... url) { String data = ""; try { data = downloadUrl(url[0]); } catch (Exception e) { Log.d("Background Task", e.toString()); } return data; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); try { JSONObject jsonObject = new JSONObject(result); JSONArray routes = jsonObject.getJSONArray("routes"); JSONObject routes1 = routes.getJSONObject(0); JSONArray legs = routes1.getJSONArray("legs"); JSONObject legs1 = legs.getJSONObject(0); JSONObject distance = legs1.getJSONObject("distance"); JSONObject duration = legs1.getJSONObject("duration"); distanceText = distance.getString("text"); durationText = duration.getString("text"); } catch (JSONException e) { e.printStackTrace(); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/20979853", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: what is difference between TDF and PCEF? In the PCC architecture there is is TDF and PCEF that they are same. What is difference between TDF and PCEF? HowTDF and PCEF work with together? A: Firstly it is worth also mentioning the PCRF, the Policy and Charging Rules Function, which is the entity that defines and manages the policies. It will often group sets of rules into profiles. The TDF, Traffic Detection Function, is 'is a functional entity that performs application detection and reporting of detected application and its service data flow description to the PCRF'. The PCEF 'encompasses service data flow detection, policy enforcement and flow based charging functionalities.' From the above descriptions, all from the 3GPP spec the distinction seem quite clear - the PCRF is the brains, the TDF detects application flow and the PCEF enforces policy. However, the TDF definition goes on to say that a TDF: For solicited application reporting, the PCRF can request the TDF to also perform enforcement actions and usage monitoring. For those cases where service data flow description is not possible to be provided by the TDF to the PCRF, the TDF performs: * *Gating; *Redirection; *Bandwidth limitation. for the detected applications. and to also note that a PCEF can be extended to include TDF functionality: NOTE: The PCEF can be enhanced with application detection and control feature as specified in clause 6.2.2.5 So, your question is a good one, there is clearly some potential for overlap, and it is quite common for vendors to actually offer a single combined TDF/PCEF product. A: TDF was introduced as a functional entity from Release 11 and the related information are present in the specification. Let met touch upon few key points w.r.t TDF, PCEF and PCRF for setting the context for the differences between them. TDF : The TDF is a functional entity that performs application detection and reporting of detected application and its service data flow description to the PCRF. The TDF supports solicited application reporting and/or unsolicited application reporting. PCEF : The PCEF encompasses service data flow detection, policy enforcement and flow based charging functionalities. It also provides user plane traffic handling, triggering control plane session management (where the IP-CAN permits), QoS handling, and service data flow measurement as well as online and offline charging interactions. Policy Control is enforced by PCEF as indicated by the PCRF in two different ways: a.Gate enforcement and b.QoS enforcement. Charging control is enforced by PCEF in the following way: - For a service data flow (defined by an active PCC rule) that is subject to charging control, the PCEF shall allow the service data flow to pass through the PCEF if and only if there is a corresponding active PCC rule with and, for online charging the OCS has authorized credit for the charging key. PCRF : The PCRF that uses usage monitoring for making dynamic policy decisions shall set and send the applicable thresholds to the PCEF or TDF for monitoring. The usage monitoring thresholds shall be based on volume. The PCEF or TDF shall notify the PCRF when a threshold is reached and report the accumulated usage since the last report for usage monitoring. Other points to note : * *PCEF interacts with PCRF and OCS. The TDF interacts only with PCRF and not with charging system (Online or Offline CS). *PCEF resides with-in the PDN GW. The TDF resides as a separate entity outside PGW. *Interfaces : The Sd reference point enables a PCRF to have dynamic control over the ADC (Application Detection and Control) behaviour at a TDF. The Gx reference point enables a PCRF to have dynamic control over the PCC(Policy Charging and Control)/ADC (Application Detection and Control) behaviour at a PCEF. ADC - This is present in TDF or in some scenario along with PCEF in which case, the PCEF is termed as PCEF enhanced with ADC. In Application Detection and Control(ADC), two models may be applied, depending on operator requirements: solicited and unsolicited application reporting Solicited application reporting: The PCRF shall instruct the TDF, or the PCEF enhanced with ADC, on which applications to detect and whether to report start or stop event to the PCRF by activating the appropriate ADC rules. Unsolicited application reporting: The TDF is pre-configured on which applications to detect and report. The enforcement is done in the PCEF The report to the PCRF shall include the same information for solicited and unsolicited application reporting that is whether the report is for start or stop, the detected Application Identifier and, if deducible, the service data flow descriptions for the application user plane traffic. The PCRF shall accept input for PCC decision-making from the PCEF, the TDF if present and other entities. High level Information obtained from the PCEF via the Gx reference point, e.g. IP-CAN bearer attributes, request type, subscriber related information, IP flow mobility routing rules (if IP flow mobility is supported) and detected application’s traffic information, if the PCEF supports Application Detection and Control feature (Detected Application Identifier, Allocated Application Instance Identifier, Detected service data flow descriptions.) PCC procedures over Gx reference point Request for PCC rules Provisioning of PCC rules Provisioning of Event Triggers Provisioning of charging related information for the IP-CAN session Provisioning and Policy Enforcement of Authorized QoS Requesting Usage Monitoring Control Reporting Accumulated Usage ADC procedures over Gx reference point : Request for ADC rules Provisioning of ADC rules Requesting Usage Monitoring Control for applications Reporting applications' Accumulated Usage Application Detection Information High level Information obtained from the TDF via the Sd reference point, e.g. report on application’s traffic detection start/stop, Detected Application Identifier, Allocated Application Instance Identifier, Detected service data flow descriptions. ADC procedures over Sd reference point for solicited application reporting : Provisioning of ADC rules Request for ADC rules Provisioning of Event Triggers Requesting Usage Monitoring Control Reporting Accumulated Usage Application Detection Information ADC procedures over Sd reference point for unsolicited application reporting : Provisioning of ADC rules Application Detection Information TDF session to Gx session linking
{ "language": "en", "url": "https://stackoverflow.com/questions/54059134", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: SonarQube giving unused private method issue for lambda usage I have the following logic; .. if(list.stream() .filter(MyClass::isEnabled) .filter(this::isActive) .count() > 0) { //do smth } .. private boolean isActive(MyClass obj) { return bool; } As you see, isActive method is being used in the stream structure, but when I build this class on Jenkins, I get the unused private method issue from SonarQube, it says you should delete this redundant private method. Is this a bug? If not, why haven't they still included lambda logic in their analyze structure? Only solution is, obviously, to do this; .filter(obj -> isActive(obj)), but it destroys the uniformity, and even the readability (imo). A: This is a known issue of SonarQube java analyzer : https://jira.sonarsource.com/browse/SONARJAVA-583 This is due to a lack of semantic analysis to resolve properly method reference (thus identify to which method this::isActive refers to).
{ "language": "en", "url": "https://stackoverflow.com/questions/35643062", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Material UI Typography & Media Queries in below in the typography component, i wanted to make the variant prop dynamic in accordance to the different screen widths , how it can be done?? appreciate your feedback import { useTheme, useMediaQuery } from "@material-ui/core"; const Home = () => { const classes = useStyles(); const theme = useTheme(); const MQlg = useMediaQuery(theme.breakpoints.down("lg")); const MQmd = useMediaQuery(theme.breakpoints.down("md")); const MQsm = useMediaQuery(theme.breakpoints.down("sm")); <Typography variant={`${MQsm && "h4"} ${MQmd && "h3"} $ {MQlg && "h2"} `} className={classes.text} gutterBottom > pioneering </Typography> A: Following the example on this MUI page for useMediaQuery, please see what I have created to assist you: import * as React from "react"; import { createTheme, ThemeProvider, useTheme } from "@mui/material/styles"; import useMediaQuery from "@mui/material/useMediaQuery"; import { Typography } from "@material-ui/core"; function MyComponent() { const theme = useTheme(); const large = useMediaQuery(theme.breakpoints.up("lg")); const medium = useMediaQuery(theme.breakpoints.up("md")); const small = useMediaQuery(theme.breakpoints.up("sm")); return ( <> <div>{`large: ${large}`}</div> <div>{`medium: ${medium}`}</div> <div>{`small: ${small}`}</div> <Typography variant={large ? "h1" : medium ? "h2" : small ? "h3" : "body1"} > Font Size Change </Typography> </> ); } const theme = createTheme(); export default function ThemeHelper() { return ( <ThemeProvider theme={theme}> <MyComponent /> </ThemeProvider> ); } Inspect the page, and change the sizes for the screen. Some will appear true, whilst other's false.
{ "language": "en", "url": "https://stackoverflow.com/questions/71394111", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: AttributeError: 'module' object has no attribute 'point' When I try to run this code: import arcpy, os arcpy.env.overwriteOutput = True def polylineArea(x, y): # this is your function definition count=len(xlist) area=0 j=count-1 for i in range (0, count): area+=((x[j]+x[i])*(y[j]-y[i])) j=i return area*.5 infile=open("C:/KateFiles/Courses/SIE510/ParcelStuff/parcel15.txt", "r") outputname = "C:/KateFiles/Courses/SIE510/ParcelStuff/P_12/ParcelPolys2.shp" sr=arcpy.SpatialReference(102683) arcpy.CreateFeatureclass_management(os.path.dirname(outputname),os.path.basename(outputname),"POLYLINE", spatial_reference=sr) arcpy.AddField_management(outputname, "ParcelID", "LONG", field_precision=8) arcpy.AddField_management(outputname, "Map", "TEXT", field_length=4) arcpy.AddField_management(outputname, "Lot", "TEXT", field_length=4) arcpy.AddField_management(outputname, "point", "Float", field_precision=10, field_scale=2) cursor1 = arcpy.da.InsertCursor(outputname,("ParcelID","SHAPE@", "Map","Lot", "point")) header1 = infile.readline() print header1 # print this out so you can see what this contains header2 =header1.split()# split the header parts by white space parcelID=header2[1]#assign parcel ID Mapno=header2[2]# assign the Mapno Lotno=header2[3]# assign the Lotno xlist=[] ylist=[] #poly =[] # A list that will hold each of the Polygon objects #point=arcpy.point parray=arcpy.Array() # Loop over lines and extract variables of interest for line in infile: segments=line.split() x=float(segments[0]) # gets x y=float(segments[1]) # gets y print x, y pt=arcpy.point(x, y) parray.add(pt) xlist.append(x) ylist.append(y) area=polylineArea(x, y) # this is your function call print area point=arcpy.polyline(parray) row=(parcelID, poly, Mapno, Lotno, point) # these match the fields in your insert cursor specification cursor1.insertRow(row) infile.close() I got this Error: Traceback (most recent call last): File "C:/Users/Ahmed A. Jasim/Desktop/Q3_Lb8.py", line 45, in <module> pt=arcpy.point(xlist, ylist) AttributeError: 'module' object has no attribute 'point' A: The ArcPy module is case sensitive, so you need to capitalize those objects, e.g. pt=arcpy.Point(x, y) point=arcpy.Polyline(parray)
{ "language": "en", "url": "https://stackoverflow.com/questions/49736368", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: CBCharacteristic value in swift3 I am beginner in swift development. I was working on BLE based application. Today I updated Xcode 8, iOS 10 and convert my code to swift3. Then some of my syntax are need to convert. After fixing this , I found one issue on CBCharacteristic. Issue Inside didUpdateValueforCharacteristic , I can get updated CBCharacteristic object. If I print out whole object, it show correctly. -> value = <3a02> When I retrieved value from CBCharacteristic , characteristic.value -> 2bytes (size of this value) func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { if (characteristic.uuid.description == LED_WAVELENGTH_CHARACTERISTIC_UUID) { print("Characteristic - \(characteristic)") print("Data for characteristic Wavelength - \ (characteristic.value)") } } Log Result : Characteristic - <CBCharacteristic: 0x1742a50a0, UUID = 2C14, properties = 0xE, value = <3a02>, notifying = NO> Data for characteristic Wavelength - Optional(2 bytes) PS : This code is completely working fine on previous version. Thanks for attention and hope someone can help me to fix this issue. A: It seems that you have been relying on the description of NSData returning a string of the form <xxxx> in order to retrieve the value of your data. This is fragile, as you have found, since the description function is only meant for debugging and can change without warning. The correct approach is to access the byte array that is wrapped in the Data object. This has been made a little bit more tricky, since Swift 2 would let you copy UInt8 values into a single element UInt16 array. Swift 3 won't let you do this, so you need to do the math yourself. var wavelength: UInt16? if let data = characteristic.value { var bytes = Array(repeating: 0 as UInt8, count:someData.count/MemoryLayout<UInt8>.size) data.copyBytes(to: &bytes, count:data.count) let data16 = bytes.map { UInt16($0) } wavelength = 256 * data16[1] + data16[0] } print(wavelength) A: Now, you can use String(bytes: characteristic.value!, encoding: String.Encoding.utf8), to get the string value of the characteristic.
{ "language": "en", "url": "https://stackoverflow.com/questions/39487553", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Construct .htaccess file to cover set of cases This is what I need to do: I need to write an .htaccess file that: * *Redirect all http requests to https *Redirect all https://example.com to https://www.example.com *Block bad bots *Prevent access to .htaccess *Add compression to ALL file types on the site This is all I need to do, yet no matter how many thousands of different ways I try, it doesn't work. Do I need the rewrite engine 'on' with every rule? I have read 100's of sites telling me how, however everyone seems to have a different solution, yet whatever I try, it DOESN'T work. When I use the redirect tool in Godaddy it does redirect my site from http to https, but that is all. When I try to add more to the htaccess file, it stops working. Even the original redirect no long works. Can anyone tell me how to put together all these codes so they work? I started a small business website, but no one told me there would be so little technical help or examples of all the 'other' things you need to do to get your website ready for all the search engine requirements. Please, please, can someone help me? The site name is billionairemailinglist.com, can anyone give me or help me create these codes to use in my htaccess file? I would be forever grateful and would be glad to offer you the products we sell for free for helping me. A: The blocking of bad bots is a non discrete, nebulous task so I'll deal with that at the end of this answer. After each itemized question I'll adjust the .htaccess to cover the solution along with all previous questions. The final solution will address all questions. 1. Switches my site from http to https RewriteEngine On RewriteCond %{HTTPS} off RewriteRule (.*) https://www.example.com [R=301,L] 2. Switches my site from https://with no www to https://with www. RewriteEngine On RewriteCond %{HTTPS} off [OR] RewriteCond %{HTTP_HOST} !^www\. RewriteRule (.*) https://www.example.com [R=301,L] 4. Prevent viewing of .htaccess file Taken from How to deny access to a file in .htaccess <Files ~ "^.*\.([Hh][Tt][Aa])"> order allow,deny deny from all satisfy all </Files> RewriteEngine On RewriteCond %{HTTPS} off [OR] RewriteCond %{HTTP_HOST} !^www\. RewriteRule (.*) https://www.example.com [R=301,L] 5. Add compression to ALL file types on the site* <Files ~ "^.*\.([Hh][Tt][Aa])"> order allow,deny deny from all satisfy all </Files> RewriteEngine On RewriteCond %{HTTPS} off [OR] RewriteCond %{HTTP_HOST} !^www\. RewriteRule (.*) https://www.example.com [R=301,L] <ifmodule mod_deflate.c> AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml text/css application/x-javascript application/javascript </ifmodule> *Note that not all file types should/could be compressed. I've added the boilerplate that we used to use above which seemed to work well. If you're interested in truly maximizing compression opportunities without the complexities of browser compatibility, look into ModPagespeed 3. block bad bots I wish it was easy as BlockBadBots yes. If you'd prefer to not analyze bandwidth usage and blocking of bots based on consumption etc., I would recommend that you put your site behind CloudFlare. This service has a good reputation for dealing with high profile DDOS attacks, limiting harmful bots, and keeping sites alive even as demand increases. Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/34366389", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: LEFT JOIN doesn't work with count I have a problem with my query: SELECT table1.Name, COUNT(*) FROM table1 LEFT JOIN table2 ON table2.Name_all = table1.Name GROUP BY table1.Name It shows and counts a names from table1. I want to join all names from table2 which do not exist in table1. Maybe someone knows what I am doing wrong? Thanks in advance A: From your description you seem to mean this, which is a list of name_all that does not match table1 name. SELECT table2.Name_all FROM table2 LEFT JOIN table1 ON table2.Name_all = table1.Name WHERE table1.Name Is Null If you need a count as well, you can say: SELECT table2.Name_all, Count(table2.Name_all) AS CountOf FROM table2 LEFT JOIN table1 ON table2.Name_all= table1.Name WHERE table1.Name Is Null GROUP BY table2.Name_all; A: Try this This query will fetch common names from table 1 and table 2. It will also fetch names from table 2 which are not there in table 1. SELECT table1.Name, table2.Name, COUNT(*) FROM table2 LEFT JOIN table1 ON table2.Name_all = table1.Name GROUP BY table1.Name, table2.Name Let me if this works. A: I would do a simple in check then SELECT table1.Name, FROM table1 WHERE table1.Name In (SELECT table2.Name_all FROM table2) GROUP BY table1.Name There are other ways, but without more information this is a simple way t
{ "language": "en", "url": "https://stackoverflow.com/questions/12578436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: when i call str.replace() in javascript it goes to error ir is not defined See my code for (var i = 0; i < allTextLines.length; i++) { var row_data = allTextLines[i]; console.log(row_data); row_data = row_data.replace(/ /g,''); try { ir(row_data == "") { continue; } if (document.getElementById("devicesList").value.length > 0) { document.getElementById("devicesList").value += ","; } document.getElementById("devicesList").value += row_data; } catch (oErr) { not_read += 1; console.log(oErr.message); str_error_detail_rows += "<tr><td colspan='2'>Error :" + oErr.message + " could not read line# " + i + " while reading from file.</td></tr>"; } } when i run the code, in the console i got "ir is not defind" please someone help me. the code goes smooth when i remove str.replace. thanks. A: ir(row_data == "") should be if(row_data == "") A: The ir should be an if, I reckon - it's a typo. To be perfectly frank, you really could have read through and practically immediately noticed the problem while paying attention.
{ "language": "en", "url": "https://stackoverflow.com/questions/27744072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: ASP.NET MVC3 Using Areas I'm having some troubles setting up two Areas in my project, I created both Areas by right clicking my project -> Add -> Area using VS 2010 Professional, The code it generated in the *AreaRegistration.cs files is exactly as I'd expect it. Both my areas have multiple controllers. I've checked my global.asax.cs file and it contains what I'd expect, the following is at the bottom: // Generated code AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); When I change the default generated routing info I can get it to work for a Single controller: context.MapRoute( "CommunityCourses_default", "CommunityCourses/{controller}/{action}/{id}", new {controller="NameOfController", action = "Index", id = UrlParameter.Optional } ); The controller="NameOfController" is what I've tried adding to the generated code, but it only works for a single controller. Edit: I renamed the namespace of my files to use PROJECTNAME.AREANAME within an area, is this causing issues? I thought it'd simplify my imports in a non-convention-breaking way. What am I missing? I've noticed a lot of problems about areas on SO and tried to follow the answers without success. This issue has bothered eluded me for the majority of the day, any help would be greatly appreciated! A: If you moved files from the Controllers folder or the VIews folder in the root of the project into Controllers or View folders contained in the {AreaName} folder, then all of those files moved need their namespaces changed from {ProjectName}.{*etCetera} to: {ProjectName}.Areas.{AreaName}.{*etCetera} A: Turns out what was wrong was that the order or routing was incorrect, it was processing {controller}/{action}/{id} first which was breaking my areas. Moving the AreaRegistration.RegisterAllAreas(); to the top of my application_start fixed my problem. http://haacked.com/archive/2011/04/13/routedebugger-2.aspx Link to the tool I used to find the problem, unfortunately the current version of the tool doesn't work on the default 404 pages, so I also had to create a custom 404 page for it to work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7745228", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using sed (or other command line programs) to delete every other X lines I have a huge text file that has several iterations of the same thing at different times, with a basic structure of: Header (5 lines) Data (thousands of lines) Header (5 lines) Data (thousands of lines) Header (5 lines) Data (thousands of lines) This repeats and goes on for a while. I want to cull this file, by removing every other set of Header + Data. I was thinking I'd use sed, but I can't figure out how. It might be of help that each "cycle" starts with the same line (for the purpose of this example, imagine it says Program X output) and that exact line only appears once, at the beginning of each "cycle". Thanks A: Sounds like all you need is: awk '/Program X output/ && c++{exit} 1' file e.g. $ seq 50 | awk '/2/ && c++{exit} 1' 1 2 3 4 5 6 7 8 9 10 11 If that's not all you need then edit your question to clarify your requirements and show us concise, testable sample input and expected output. A: Keep track of how often you see the keywords, and print only when this count is an odd number: awk '/Program X output/ {n++} n%2 == 1' <<END Program X output a b c Program X output d e Program X output f g h i j Program X output m n o END Program X output a b c Program X output f g h i j A: This might work for you (GNU sed): sed -r '/Program X output/{x;s/^/x/;x};G;/\n(x{2})*$/!P;d' file When encountering a header line, add 1 to a counter in the hold space (HS). Append the HS to every line and only print the first line in the pattern space (PS) if the counter is a multiple of the required amount.
{ "language": "en", "url": "https://stackoverflow.com/questions/50705049", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I merge the multiple If Else using decode in PL/SQL? The code goes like- If X=x1 then select a,b from tab where zz=yy; elsif X=x2 or X=x3 then select a,b from tab where zz=yy and yy= 123; elsif X=x4 then select a,b from tab where zz=yy and yy= 456; end if; The code in select is being repeated. How should i merge it? A: At first I thought that a CASE statement would be appropriate, but then I noticed that your logic always conditionally selects the same two columns a and b. So I think that what you need here is a WHERE clause to handle all the cases. SELECT a, b FROM tab WHERE (x = 'x1' OR ((x = 'x2' OR x = 'x3') AND yy = 123) OR (x = 'x4' AND yy = 456)) AND zz = yy A: You can use dynamic SQL and compose your query from different parts. For example: -- common part of query common_query := 'SELECT a, b FROM tab WHERE zz= yy'; -- set additional condition IF X=x1 THEN add_where := ''; ELSIF X=x2 OR X=x3 THEN add_where := ' AND yy= 123'; ELSIF X=x4 THEN add_where := ' AND yy= 456'; END IF; -- compose final query final_query:= common_query||add_where; EXECUTE IMMEDIATE final_query; Of couse when you use dynamic SQL you can use bind variables and you need to remember about return values.
{ "language": "en", "url": "https://stackoverflow.com/questions/39685158", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Extracting last occurrence of a certain string from each row in a pandas series from each row i want to extract the last occurrence of the word "user" + the number that follow right after it from a pandas series. everything else can be discarded. how would you perform this action? thanks!!! here's an example of the series : 0 1 - Unassigned, 2 - User 397335 1 1 - Unassigned, 2 - User 525767, 3 - Unassigned 2 1 - Unassigned 3 1 - Unassigned 4 1 - Unassigned ... 163678 1 - Unassigned 163679 1 - Unassigned, 2 - User 347991, 3 - Unassigned 163680 1 - Unassigned 163681 1 - Unassigned 163682 1 - Unassigned, 2 - User 663455, 3 - Unassigned A: Use str.findall: >>> df['A'].str.findall(r'User \d+').str[-1] 0 User 397335 1 User 525767 2 NaN 3 NaN 4 NaN 163678 NaN 163679 User 347991 163680 NaN 163681 NaN 163682 User 663455 Name: A, dtype: object
{ "language": "en", "url": "https://stackoverflow.com/questions/70881436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Read from named piped I have to write a program which monitors two named pipes and prints the information sent through either. When the write end of one of the pipes is closed, the program will detect this and close and open the pipe again. This is what I have written so far: #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #define BUF_SIZE 200 int main(void) { fd_set rfds; struct timeval tv; int retval; ssize_t n_read; char buf[BUF_SIZE]; /* Open pipes */ int tuberia1_fd = open("tuberia1",O_RDONLY); int tuberia2_fd = open("tuberia2",O_RDONLY); while(1){ /* Watch stdin (fd 0) to see when it has input. */ FD_ZERO(&rfds); FD_SET(0, &rfds); /* Wait for an indefinite amount of time. */ tv.tv_sec = 0; tv.tv_usec = 0; retval = select(2, &rfds, NULL, NULL, &tv); /* Don't rely on the value of tv now! */ if (retval == -1) perror("select()"); exit(EXIT_FAILURE); if(FD_ISSET(tuberia1_fd, &rfds)){ n_read = read(tuberia1_fd, &buf, BUF_SIZE); if (n_read == 0){ close(tuberia1_fd); tuberia1_fd = open("tuberia1", O_RDONLY); }else{ buf[n_read] = '\0'; printf("tuberia1: %s", buf); } } else if (FD_ISSET(tuberia2_fd, &rfds)){ n_read = read(tuberia2_fd, &buf, BUF_SIZE); if (n_read == 0){ close(tuberia2_fd); tuberia2_fd = open("tuberia2", O_RDONLY); }else{ buf[n_read] = '\0'; printf("tuberia2: %s", buf); } } } } When I run it, the program locks, which is the expected behavior. But when I echo hello_world > tuberia1 there is no response from the program. What is going on? EDIT: As observed by GM below, I was incorrectly passing arguments to select. After fixing that my program looks like this: #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #define BUF_SIZE 200 int main(void) { fd_set rfds; struct timeval tv; int retval; ssize_t n_read; char buf[BUF_SIZE]; /* Open pipes */ printf("Opening tuberia1"); int tuberia1_fd = open("tuberia1",O_RDONLY); printf("Opening tuberia2"); int tuberia2_fd = open("tuberia2",O_RDONLY); while(1){ printf("Enter the loop"); /* Watch stdin (fd 0) to see when it has input. */ FD_ZERO(&rfds); FD_SET(tuberia1_fd, &rfds); FD_SET(tuberia2_fd, &rfds); /* Wait for an indefinite amount of time. */ tv.tv_sec = 5; tv.tv_usec = 0; int fd_max = (tuberia1_fd > tuberia2_fd) ? tuberia1_fd : tuberia2_fd; retval = select(fd_max, &rfds, NULL, NULL, &tv); /* Don't rely on the value of tv now! */ if (retval == -1) perror("select()"); exit(EXIT_FAILURE); if(FD_ISSET(tuberia1_fd, &rfds)){ n_read = read(tuberia1_fd, &buf, BUF_SIZE); if (n_read == 0){ close(tuberia1_fd); tuberia1_fd = open("tuberia1", O_RDONLY); }else{ buf[n_read] = '\0'; printf("tuberia1: %s", buf); } } else if (FD_ISSET(tuberia2_fd, &rfds)){ n_read = read(tuberia2_fd, &buf, BUF_SIZE); if (n_read == 0){ close(tuberia2_fd); tuberia2_fd = open("tuberia2", O_RDONLY); }else{ buf[n_read] = '\0'; printf("tuberia2: %s", buf); } } } } It still does not work. Running it under GDB shows that the program never progresses past the first open. A: You need to use FD_SET on the file descriptors you're actually interested in -- namely tuberia1_fd and tuberia2_fd. So something like... while (1) { FD_ZERO(&rfds); FD_SET(tuberia1_fd, &rfds); FD_SET(tuberia2_fd, &rfds); int max; if (tuberia1_fd > tuberia2_fd) { max = tuberia1_fd; } else { max = tuberia2_fd; } tv.tv_sec = 0; tv.tv_usec = 0; retval = select(max + 1, &rfds, NULL, NULL, &tv);
{ "language": "en", "url": "https://stackoverflow.com/questions/54098904", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to convert String to its resource ID (Android Studio) I have an xml string in my values/strings.xml file <string name="pokemon_d">150</string> And I have the String "150" in my controller MainActivity.java. In my MainActivity, how can I convert that String to the resource ID of the pokemon_d String in the xml file? Is this even possible? A: You can not get identifier by value, but you can make your identifier name look like a value and get it by string name, So what I suggest, use your String resource name something like, resource_150 <string name="resource_150">150</string> Now here resource_ is common for your string entries in string.xml file, so in your code, String value = "150"; int resourceId = this.getResources(). getIdentifier("resource_"+value, "string", this.getPackageName()); Now resourceId value is as equivalent to R.string.resource_150 Just make sure here this represent your application context. In your case MainActivity.this will work. A: EDIT You can't search for a resource Id by the string value. You could make your own Map of the values and resourceIds and use that as a look up table, but I believe just choosing an intelligent naming convention like in the accepted answer is the best solution. A: I have found some tips here: Android, getting resource ID from string? Below an example how to get strings and their values defined in strings.xml. The only thing you have to do is making a loop and test which string is holding your value. If you need to repeat this many times it might be better to build an array. //--------- String strField = ""; int resourceId = -1; String sClassName = getPackageName() + ".R$string"; try { Class classToInvestigate = Class.forName(sClassName); Field fields[] = classToInvestigate.getDeclaredFields(); strField = fields[0].getName(); resourceId = getResourceId(strField,"string",getPackageName()); String test = getResources().getString(resourceId); Toast.makeText(this, "Field: " + strField + " value: " + test , Toast.LENGTH_SHORT).show(); } catch (ClassNotFoundException e) { Toast.makeText(this, "Class not found" , Toast.LENGTH_SHORT).show(); } catch (Exception e) { Toast.makeText(this, "Error: " + e.getMessage() , Toast.LENGTH_SHORT).show(); } } public int getResourceId(String pVariableName, String pResourcename, String pPackageName) { try { return getResources().getIdentifier(pVariableName, pResourcename, pPackageName); } catch (Exception e) { e.printStackTrace(); return -1; } } A: In addition to user370305, you could make an extension and use it the same was as with int ids. import android.app.Activity fun Activity.getString(id: String): String { val resourceId = this.resources.getIdentifier(id, "string", this.packageName) return getString(resourceId) }
{ "language": "en", "url": "https://stackoverflow.com/questions/34957155", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Print narrow strings using swprintf in C++Builder The following lines both "work as intended": wchar_t u[50], v[50]; swprintf(u, 50, L"%s", L"hello"); swprintf(v, 50, L"%ls", L"goodbye"); MessageBoxW(NULL, u, v, MB_OK); // output: MessageBox showing "hello" and "goodbye" Is there any way to print a narrow string, and where is the documentation for this? E.g. swprintf(u, 50, L"%?", "hello"); The C++ Standard specifies (by reference to the C standard) that in the wprintf family of functions, %s specifies a string of char (in multibyte encoding, e.g. UTF-8), and %ls specifies a string of wchar_t. So the RTL (run-time library implementation supplied with C++Builder) is apparently not standards-compliant here. Background: I'm actually trying to use UnicodeString::sprintf, however that delegates the heavy lifting to vswprintf. A: This is not really an answer, but more of a compilation of elements. Reference : The site http://www.cplusplus.com/ is clear: for the wprintf family : ... all format specifiers have the same meaning as in printf; therefore, %lc shall be used to write a wide character (and not %c), as well as %ls shall be used for wide strings (and not %s) Implementations : gcc and clang both conform to above specification MSVC and according to OP Borland C++ do not conform and accept %s for a wide string. A: I managed to find this in the vprinter.c file in the RTL source code (C++Builder comes with its own RTL, it doesn't reference MS): /* The 's' conversion takes a string (char *) as * argument and copies the string to the output * buffer. * * Note: We must handle both narrow and wide versions * depending on the flags specified and the version called: * * Format printf wprintf * ---------------------------------------- * %s narrow wide * %S wide narrow * %hs narrow narrow * %hS narrow narrow * %ls wide wide * %lS wide wide * */ so the code: swprintf(v, 50, L"%hs", "hello"); generates the correct output. However, this doesn't do any UTF-8 conversion; narrow characters are "widened" by attaching a null byte. (Confirmed by inspecting the resut of the source).
{ "language": "en", "url": "https://stackoverflow.com/questions/27920229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Imagemagick transparency not working in 6.9 but works in 7.0 I'm running this command to crop an image and retain (alpha?) transparency: convert bigger.png -crop 2048x2048 -gravity northwest \ -extent 2048x2048 -transparent white \ -set 'filename:tile' '%[fx:page.x/2048]_%[fx:page.y/2048]' 'tile_%[filename:tile].png' I'm using the exact same command, but on three different versions. * *6.7.2-7 2017-03-23 Q16 (Linux, not sure which dist) *6.9.7-4 Q16 x86_64 20170114 (Linux/Ubuntu) *7.0.8-42 Q16 x86_64 (Mac Os Mojave) On 7.0 it works perfectly, but on 6.x, the background is black after conversion. Is there some option that was changed in 7.0 that I can try in the old versions? Thanks! EDIT: I tried different combination of these parameters and adding PNG32 to force an alpha channel: -alpha on -background none -transparent white PNG32:bigger.png
{ "language": "en", "url": "https://stackoverflow.com/questions/56049530", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UnknownHostException with HTTPConnection in Android An UnknownHostException arises when I attempt to execute the following code... String line; String url = "http://mywebsite.com"; URL theURL = new URL(url); HttpURLConnection conn = (HttpURLConnection) theURL.openConnection(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); line = rd.readLine(); conn.disconnect(); I have followed suggestions from former posts to ensure that the Internet Permission Tag appears properly in the manifest. I also made sure that my Android has WIFI access, and that the website I am attempting to use is correct. This usually appeared to be a popular resource on StackOverflow: http://guerrarj.hubpages.com/hub/Tips-to-solve-the-UnknownHostException-on-Android The stack trace is... java.net.UnknownHostException: the_website.com at java.net.InetAddress.lookupHostByName(InetAddress.java:512) at java.net.InetAddress.getAllByNameImpl(InetAddress.java:300) at java.net.InetAddress.getAllByName(InetAddress.java:259) at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:69) at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:48) at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection$Address.connect(HttpConnection.java:322) at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionPool.get(HttpConnectionPool.java:89) at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHttpConnection(HttpURLConnectionImpl.java:285) at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.makeConnection(HttpURLConnectionImpl.java:267) at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.retrieveResponse(HttpURLConnectionImpl.java:1018) at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:512) at com.example.privacyapp.MainActivity.scrapWeb(MainActivity.java:127) at com.example.privacyapp.MainActivity.checkLocation(MainActivity.java:148) at com.example.privacyapp.MainActivity$1.onLocationChanged(MainActivity.java:93) at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:227) at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:160) at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:176) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:150) at android.app.ActivityThread.main(ActivityThread.java:4263) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:507) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) at dalvik.system.NativeStart.main(Native Method) Update: It appeared that my WIFI connection was faulty. Without a connection, the UnknownHostException arises. A: Somtimes we have to write ip address instead of "http://mywebsite.com"; so try onece using Ip address. check also The INTERNET permission tag is a child of the manifest tag, not the application tag.! and check this once hope this helpful to you
{ "language": "en", "url": "https://stackoverflow.com/questions/16954053", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to calculate sum of dynamically named model names in a ng-repeat I have a dynamic table with dynamic inputs. Each input has an unique number added to the end of the model name. There are 10 inputs per table with the last being the total. I need to watch the first 9 inputs and calculate the sum. Here is what the json looks like after dynamically assigning unique model names. [ { "section_id": 3155, "subdivision_id": 3500, "section_name": "Ph 1(P)-Mercedes", "sectionInputs": [ { "model": "price_min-3155" }, { "model": "price_max-3155" }, { "model": "units_occ-3155" }, { "model": "inv_mod-3155" }, { "model": "inv_fin-3155" }, { "model": "inv_vdl-3155" }, { "model": "inv_uc-3155" }, { "model": "inv_fut-3155" }, { "model": "inv_con-3155" }, { "model": "units_total-3155" } ] }, { "section_id": 12863, "subdivision_id": 3500, "section_name": "Ph 1(P)-Adams", "sectionInputs": [ { "model": "price_min-12863" }, { "model": "price_max-12863" }, { "model": "units_occ-12863" }, { "model": "inv_mod-12863" }, { "model": "inv_fin-12863" }, { "model": "inv_vdl-12863" }, { "model": "inv_uc-12863" }, { "model": "inv_fut-12863" }, { "model": "inv_con-12863" }, { "model": "units_total-12863" } ] }, { "section_id": 16152, "subdivision_id": 3500, "section_name": "Ph 1(P)-Unassigned", "sectionInputs": [ { "model": "price_min-16152" }, { "model": "price_max-16152" }, { "model": "units_occ-16152" }, { "model": "inv_mod-16152" }, { "model": "inv_fin-16152" }, { "model": "inv_vdl-16152" }, { "model": "inv_uc-16152" }, { "model": "inv_fut-16152" }, { "model": "inv_con-16152" }, { "model": "units_total-16152" } ] } ] The units_total needs to hold the sum value for each array. I was looking at using a watchgroup function but not sure how I could do this with possibly needing a for loop? I'm open to suggestions on the best way to handle this. javascript, jquery, lodash, linq.js are what is currently being used in project. Here is working plunker $scope.model = {}; function prepareDataForView() { for (var i = 0; i < sections.length; i++) { sections[i].sectionInputs = sectionInputSvc.sectionInputs(sections[i]); sections[i].sectionInputLabels = sectionInputLabels; } $scope.sections = sections; } prepareDataForView(); A: One way to implement this is to calculate the total whenever input ng-changes: var sum = function(acc,cur){ return acc+cur; } $scope.modelChanged = function(section, input){ var inputsCount = section.sectionInputs.length; var totalInput = section.sectionInputs[inputsCount-1]; if(input === totalInput){ return; } var total = section.sectionInputs.slice(0, inputsCount - 1).map(function(input){ return $scope.model[input.model]; }).filter(angular.isDefined).reduce(sum, 0); $scope.model[totalInput.model] = total; }; Which can then be invoked on each input: <input ng-model="model[input.model]" ng-change="modelChanged(section, input)" type="number" /> Here's an updated plunker. A: Well, I have solved it with jQuery, maybe this answer doesn't fit you because it's inconsistent with your angular app, but I hope it can be helpful to someone else. $(document).on("change", "input", function() { $tr = $(this).parent().parent(); $tds = $tr.find("td"); var sum = 0; $.each($tds, function(index, td){ var valueInput = $(td).find("input").val(); if(index < 9 ){ sum += parseFloat((valueInput != "") ? valueInput : 0 ); } }); $tds.eq(9).find("input").val(sum); }); Here is the updated plunker
{ "language": "en", "url": "https://stackoverflow.com/questions/34729065", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Xpages get a handle on next rowData or Doc in a repeat In my repeat control I want to be able to get a handle on data in the next row in order to modify what data is displayed in my current row (I have move up and down actions, and I don't want to display them if the move is not possible). It seems I should be able to do this. Probably I cannot from within in the repeat itself, as when it is writing the repeat it will not know the data for the next repeat. But shouldn't there be a fairly easy way to get the next document? Here is a reduced version of my repeat control: <?xml version="1.0" encoding="UTF-8"?> <xp:view xmlns:xp="http://www.ibm.com/xsp/core"> <xp:repeat id="repeat1" var="rowData" indexVar="repeatIndex" value="#{view1}"><xp:this.facets> <xp:text disableTheme="true" xp:key="header" escape="false" > <xp:this.value><![CDATA[<table class='lotusTable repeatRowColors' border='0' cellspacing='0' cellpadding='0' width='800px'> <tr class ='lotusFirst lotusSort scope='col'> <th class ='loutsFirstCell'></th> <th class ='loutsFirstCell'>Category</th> <th class ='lotusCenter'>Move</th> <th>Task</th> </tr> </thead>]]></xp:this.value> </xp:text> <xp:text disableTheme="true" xp:key="footer" escape="false" > <xp:this.value><![CDATA[</table>]]></xp:this.value> </xp:text> </xp:this.facets> <xp:this.rows><![CDATA[#{javascript:var rows:Integer = viewScope.get("rows"); if (rows == null) {return 5} else {return rows}}]]></xp:this.rows> <xp:tr id="rowDataContainer"> <xp:td style="width:55px;min-width:55px;max-width: 55px;"> <xp:text escape="true" id="computedField2"> <xp:this.value><![CDATA[#{javascript:rowData.getColumnValue("category");}]]> </xp:this.value> </xp:text> </xp:td> </xp:tr> </xp:repeat> </xp:view> A: You can get view's next row within the repeat with var nextRow = view1.getAllEntries().getNthEntry(repeatIndex + 2); "view1" is the xp:dominoView assigned to repeat control and "repeatIndex" is the indexVar of xp:repeat. You can get next row document's UniqueID then with nextRow ? nextRow.getUniversalID() : "" and the e.g. Form field with nextRow ? nextRow.getDocument().getItemValueString("Form") : "" Accordingly, you get the previous row with var prevRow = view1.getAllEntries().getNthEntry(repeatIndex);
{ "language": "en", "url": "https://stackoverflow.com/questions/29905981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why does my program loop without receiving any new input? I am trying to make is so that my program will start over once the answer is given. It just won't function again once I run it once. I want to make it functional to where the user doesn't have to start the program up again. Thanks! #include <stdio.h> #include <math.h> int main() { float firstnum, secondnum, answer; char function; printf("\nHello and welcome to my calculator!\n"); //Intro start: //Area to loop to when program completes printf("\nPlease input the function you would like to use. These include +, -, *, /.\n"); //Asking for function input scanf("%c", &function); //Receiving Function Input printf("\nNow please input the two variables.\n"); //Asking for variables scanf("%f", &firstnum); scanf("%f", &secondnum); //Receiving Input for Variables if (function == '+') //Doing calculation { answer = firstnum+secondnum; } else if (function == '-') { answer = firstnum-secondnum; } else if (function == '*') { answer = firstnum*secondnum; } else if (function == '/') { answer = firstnum/secondnum; } else { printf("Sorry that was an incorrect function. The correct inputs are +, -, *, /."); //If they don't follow the directions } printf("Your answer is %f \n", answer); //Answer goto start; //Loop return 0; } A: It's the [enter] key. Your first scanf is reading the enter key you pressed to terminate the previous iteration. So you need to add another scanf("%c", &function); or getchar(); just before the goto to eat the newline. When reading in numbers, scanf will eat any initial whitespace; but when reading characters, it won't. It gives you the very next byte in the stream. A better way, perhaps, would be to tell `scanf` where to expect all the newlines. This way you don't need that *weird* mystery line that doesn't appear to do anything but isn't commented (!); because that's gonna cause problems when you play with this code again months from now. //scanf("%c\n", &function); /* read a character followed by newline DOESN'T WORK */ ... //scanf("%f\n", &secondnum); /* read a number followed by newline DOESN'T WORK */ This way, trailing newlines are consumed. Which is, I think, the more intuitive behavior (from the User side). Nope. Doesn't work. Wish it did, cause I'd look less foolish. I'm not upset by the goto. It's nice to see an old friend. This is an appropriate use of it if ever there was one. It is exactly equivalent to the while form. So you should certainly be aware that most people will prefer to see while(1) because it tells you more about what's going on than label:. But for an infinite loop in a function smaller than a screen, why not? Have fun. No baby seals will be harmed. :) A: This is why you use loops. (And try not to use goto for this). #include <stdio.h> #include <math.h> int main() { float firstnum, secondnum, answer; char function, buffer[2]; while(1) { printf("\nHello and welcome to my calculator!\n"); printf("\nPlease input the function you would like to use. These include +, -, *, /.\n"); scanf("%s", &buffer); function = buffer[0]; printf("\nNow please input the two variables.\n"); scanf("%f", &firstnum); scanf("%f", &secondnum); if (function == '+') answer = firstnum+secondnum; else if (function == '-') answer = firstnum-secondnum; else if (function == '*') answer = firstnum*secondnum; else if (function == '/') answer = firstnum/secondnum; else printf("Sorry that was an incorrect function. The correct inputs are +, -, *, /."); printf("Your answer is %f \n", answer); } return 0; } This should go in an infinite loop, so use an input from the user to break; the loop to exit the program Note : I have replaced the scanf %c with %s indicating an input of a string & used a buffer. scanf("%s",&buffer); function = buffer[0]; (Updated as per discussion in comments) A: One "best practise" regarding scanf is to check it's return value. In regards to the return value of scanf, I suggest reading this scanf manual carefully and answering the following questions: * *int x = scanf("%d", &foo); What do you suppose x will be if I enter "fubar\n" as input? *Where do you suppose the 'f' from "fubar\n" will go? *If it remains in stdin, would you expect a second scanf("%d", &foo); to be successful? *int x = scanf("%d", &foo); What do you suppose x will be if I run this code on Windows and press CTRL+Z to send EOF to stdin? *Would it be safe to use foo if x is less than 1? Why not? *int x = scanf("%d %d", &foo, &bar); What would you expect x to be if I enter "123 456\n" as input? *Do you suppose the '\n' will still be on stdin? What value would char_variable hold following scanf("%c", &char_variable);? EOF can be sent through stdin in Windows by CTRL+Z, and in Linux and friends by CTRL+D, in addition to using pipes and redirection to redirect input from other programs and files. By using code like int function; for (function = getchar(); function >= 0 && isspace(function); function = getchar()); assert(function >= 0); or char function; assert(scanf("%*[ \n]%c", &function) == 1); you can discard leading whitespace before assigning to function.
{ "language": "en", "url": "https://stackoverflow.com/questions/14993841", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why is there an error about headers and authorization in a Stripe dependency? Stripe HTTP request dependency returns an error about headers, but these are not configurable. Using a GET request seems fine, but a post route fails with the error: error [err_invalid_char]: invalid character in header content ["authorization"] app.post('/charge',function(req,res){ stripe.charges.create({ amount: 10, description: 'Charge', currency: 'gbp', customer: 'cus_EXgisfTr7LuiO9' },function(err,result){ if(err){ res.status(400); res.send(err); } else{ res.status(201); res.send(result); } }); }); Hitting the endpoint https://myapp.herokuapp.com/charge with an HTTP POST request returns this to the console: error [err_invalid_char]: invalid character in header content ["authorization"] This is a Stripe dependency however and not configured by the developer. A: The above error occurs when the Stripe Secret API key is passed incorrectly. Just for the help, const Stripe = require('stripe'); const stripe = Stripe(env.STRIPE_TEST_SECRET_KEY); make sure you change the key as per the production/development environment. Cheers.
{ "language": "en", "url": "https://stackoverflow.com/questions/54728437", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Server.MapPath behaves differently with IIS Server and ASP.Net Development Server? Why does Server.MapPath("~") return different results with IIS Express and ASP.Net Development server? When I run my application with ASP.Net Development Server, my path returns like "D:\\MyProject\\Web\\WWWRoot\\ISuite5" but when i run using IIS Express , path comes as "D:\\MyProject\\Web\\WWWRoot\\ISuite5\\". There is a difference of "\\" between both. I am not able to figure out the reason behind it or how to resolve it so that IIS Server also returns the same result as ASP.Net Development Server.
{ "language": "en", "url": "https://stackoverflow.com/questions/37545861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Arrays inside of Object JavaScript I want to create an array inside of an object with values that refer to properties of the same object containing the array. The only problem I am having is that the results inside of the array are undefined instead of what they are supposed to be. Am I even referring to the properties correctly? Here is my JavaScript for the object. var cc_cd = { name: "CC Waterbound", date: "Summer 1995", t1name: "Intro", t1url: "https://www.youtube.com/embed/Rsh5oQ6JCTI", t1length: "0:40", t2name: "Bout 2 Go Down", t2url: "https://www.youtube.com/embed/XgJ6DdIaXd0", t2length: "4:44", t3name: "Dope and money", t3url: "https://www.youtube.com/embed/cruY77l99_M", t3length: "3:51", t4name: "Looking Down the Barrel", t4url: "https://www.youtube.com/embed/jmLgcnUlgfk", t4length: "4:33", t5name: "Playa Hatas", t5url: "https://www.youtube.com/embed/ZY8eCUuuqJY", t5length: "5:18", t6name: "4 Real Nigga Possie", t6url: "https://www.youtube.com/embed/A-syQCa3iN0", t6length: "6:14", t7name: "CC Waaterbound", t7url: "https://www.youtube.com/embed/eIAOcKg8xfk", t7length: "5:25", t8name: "Creepin", t9url: "https://www.youtube.com/embed/MpBB7rnaw_Q", t9length: "3:56", t10name: "Hood Cord", t10url: "https://www.youtube.com/embed/PNMiP67NhcM", t10length: "4:11", t11name: "All This Dick", t11url: "https://www.youtube.com/embed/a5zWyURBIjE", t11length: "5:25", array:[this.t1name,this.t1date,this.t1url,this.t2name,this.t2date,this.t2url,this.t3name,this.t3date,this.t3url,this.t4name,this.t4date,this.t4url,this.t5name,this.t5date,this.t5url,this.t6name,this.t6date,this.t6url,this.t7name,this.t7date,this.t7url,this.t8name,this.t8date,this.t8url,this.t9name,this.t9date,this.t9url,this.t10name,this.t10date,this.t10url,this.t11name,this.t11date,this.t11url] } A: I wouldn't know what could be going wrong, but I do know an easy solution could be creating a global array and then setting the property to the global array. Code: var array = [ your array] ; var cc_cd = { List : array, Other properties }; Please mark answered or vote to let me know if this helped!
{ "language": "en", "url": "https://stackoverflow.com/questions/34459484", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How to use Oraclize in solidity to pass arguments to the data source? My aim is to pass some string to the data source and then process there and get back the result. Below given code works in solidity oraclize_query("URL", "json(https://clever-ape-38.localtunnel.me).a","sfdg"); But when i try to fetch some value from blockchain and use it, if fails string memory st = arr[msg.sender]; oraclize_query("URL", "json(https://clever-ape-38.localtunnel.me).a",st); everything compiles properly. Even truffle migrate --reset works fine. I feel that the fetching from blockchain takes some time and oraclize_query() is called before the fetch. Below there is mentioned the error. [2019-05-28T08:54:50.206Z] INFO new HTTP query created, id: 72e3a263387ed365d97bc97a64c601380a5b4e8bbd1b3740bcc2af1e2bc97b19 [2019-05-28T08:54:50.215Z] INFO checking HTTP query 72e3a263387ed365d97bc97a64c601380a5b4e8bbd1b3740bcc2af1e2bc97b19 status in 0 seconds [2019-05-28T08:54:50.215Z] INFO checking HTTP query 72e3a263387ed365d97bc97a64c601380a5b4e8bbd1b3740bcc2af1e2bc97b19 status every 5 seconds... [2019-05-28T08:54:56.634Z] INFO 72e3a263387ed365d97bc97a64c601380a5b4e8bbd1b3740bcc2af1e2bc97b19 HTTP query result: { "result": { "_timestamp": 1559033691, "id": "72e3a263387ed365d97bc97a64c601380a5b4e8bbd1b3740bcc2af1e2bc97b19", "daterange": [ 1559033689, 1559035489 ], "_lock": false, "id2": "72fdf59adf3ecc92244e3b173ce1657252ab5eb877c3569a393599d34dd2c848", "actions": [], "interval": 3600, "checks": [ { "errors": [ "TypeError", "parsing_helper.wrong_path" ], "success": true, "timestamp": 1559033691, "results": [ "" ], "proofs": [ null ], "match": true } ], "version": 3, "_timestamp_creation": 1559033689, "context": { "protocol": "eth", "relative_timestamp": 1559033687, "type": "blockchain", "name": "eth_AB65E563DB" }, "active": false, "hidden": false, "payload": { "conditions": [ { "query": [ "json(https://purple-squid-54.localtunnel.me).a", "28189689" ], "proof_type": 0, "check_op": "tautology", "datasource": "URL", "value": null } ] } }, "success": true } [2019-05-28T08:54:56.637Z] ERROR HTTP query error [ "TypeError", "parsing_helper.wrong_path" ] [2019-05-28T08:54:56.639Z] INFO sending __callback tx... { "contract_myid": "0x72fdf59adf3ecc92244e3b173ce1657252ab5eb877c3569a393599d34dd2c848", "contract_address": "0x481a276d14a6a74e1ec1f74b64c2af226ba7033c" } [2019-05-28T08:55:01.853Z] INFO contract 0x481a276d14a6a74e1ec1f74b64c2af226ba7033c __callback tx sent, transaction hash: 0xfada229b6f9860e0717b3a098dd93aaef280852dbf75109c830b555c488e6c81 { "myid": "0x72fdf59adf3ecc92244e3b173ce1657252ab5eb877c3569a393599d34dd2c848", "result": "", "proof": null, "proof_type": "0x00", "contract_address": "0x481a276d14a6a74e1ec1f74b64c2af226ba7033c", "gas_limit": 200000, "gas_price": null } Please help to solve this. A: Thank you for adding the error logs. Actual answer: If you're adding POST data as a string but that's in a valid JSON format, it will be parsed as such. In order to preserve it as a string, you need to add a newline char or whitespace so the beginning of the string: "\n<post-data-here" Original answer re the parsing-error which proved not to be the main issue in the end... You're hitting a parsing error in the ethereum-bridge due to it trying but failing to parse the returned json from your query. However at the time of writing, your local tunnel is returning a 404 error rather than the data it originally returned. Then, as the ethereum-bridgeattempts to parse thejsonto pluck the value from thea` key, per your query: json(https://purple-squid-54.localtunnel.me).a ...it can't because there is not json and so no a field and so you get a parsing error. To fix it, ensure your local tunnel is working and that the data returned is in correct json format, and that there is an a key present for the parser to work with.
{ "language": "en", "url": "https://stackoverflow.com/questions/56337630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trying to write Java program to play mp3 file I am trying to write a program that plays an mp3 file. For some reason, I am getting the error "package.javafx.scene.media does not exist." How can I fix this? A: You need e(fx)clipse or you need to add the jfxrt.jar to your classpath. It comes with your JDK. How do I work with JavaFX in Eclipse Juno? should sort it out for you. NetBeans and IntelliJ come with built-in support for JavaFX. A: You could also work with Java 8 as JavaFX is already included there. It also provides a lot of improvements on JavaFX components.
{ "language": "en", "url": "https://stackoverflow.com/questions/21837050", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JAX-RS @Path() custom format I'm Regex newbie. What I trying to do here is, I have 2 @PathParam so the user can either type in "/session" or "/requester" or anything but these two. If the user type "/session" or "/requester" this input will go to pathparam 1 else the pathparam 2. Here is my regex. @Path("/generateotp{session:(/session[^\\w&&[^\\W]]|/requester[^\\w&& [^\\W]])?}{senderid:(/[^/&&\\w]|(?:(?!requester|session).))?}") I know I'm kind of redundant the [^\w&&[^\W]] part but the [^.+] just don works. Extra things here. How can I cut the "/" when the input will go to the senderid pathparam. I need the user to input it in because of the generateotp there but when it process and throw to the pathparam, that is where i don't need it. I can use substring after that to cut it but is there anyway i can do it in the regex?
{ "language": "en", "url": "https://stackoverflow.com/questions/44645081", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What service can be used to limit the number of IoT device connections to a database? I have an IoT system with about 2000 devices. I would like each of the devices to upload data to a MongoDB instance. Each device connects every 8-12 seconds and makes a single entry. The actual entry writing takes about 50ms. My MongoDB has a maximum connection count of 100. Even though it's unlikely, there's always the chance that all 2000 devices will simultaneously connect and be rejected by the db due to max connection count. Is there a pre-existing queuing service that all my devices can send data to? I don't want to have to write a middle-man server to collect all the data from IoT devices and forward it onto the db. So basically instead of: |device| --------> Database I need: |device|-------> service ------> Database I'm just not sure what this 'service' is. Does such a thing exist? What should i be looking for? I tried using AWS SQS but I couldn't quite figure out how to make entries to the mongo db from the AWS SQS. Is this the right tool or is there another service out there? A: You can try using Message Queues. Rabbit MQ is a good option as it supports MQTT (which is great for device to cloud communication) as well as AMQP (0.9.1) (which is great for cloud to cloud communication) You can also use any standard MQTT broker (EMQTT, Mosquito, Hive etc) and implement an MQTT to MongoDB client in between. Setting the MQTT clean_session flag to false will make the broker act as a cache.
{ "language": "en", "url": "https://stackoverflow.com/questions/54659949", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Resize an image before uploading it to firebase Firebase storage looks very cool and easy to use, but I'm wondering if there's a way to resize an image before uploading it to Firebase Storage, e.g., run a proccess using ImageMagick in a server and then run the uploading process using Firebase SDK but I notice there aren't storage functions for Firebase SDK Server. A: Resize using JavaScript Client-Side-Processing We're using JavaScript resizing, which uses clients device processing power to resize the image, and works GREAT, saving us space and money, saving the netwrok unnecesary bandwidth, and saving the client a bunch of time and also money in most mobile cases. The original script we are using came from here, and the procedure to use it is as simple as this: <input type="file" id="select"> <img id="preview"> <script> document.getElementById('select').onchange = function(evt) { ImageTools.resize(this.files[0], { width: 320, // maximum width height: 240 // maximum height }, function(blob, didItResize) { // didItResize will be true if it managed to resize it, otherwise false (and will return the original file as 'blob') document.getElementById('preview').src = window.URL.createObjectURL(blob); // you can also now upload this blob using an XHR. }); }; </script> I believe that guy (dcollien) deserves a LOT of merit, so I would recommend you to vote his answer up. A: You can also use Firebase Storage + Google Cloud Functions to upload an image, resize the image (using ImageMagick or similar), and write it back to Firebase Storage. I have an example using these together here (though I trigger the Cloud Vision API, rather than an image resizer). A quick side note: Firebase Storage doesn't have a Node.js client, instead we recommend using the GCloud-Node library. A: You could also use Firebase Storage + the official Firebase Resize Image extension: https://firebase.google.com/products/extensions/firebase-storage-resize-images. The downside here is that "To install an extension, your project must be on the Blaze (pay as you go) plan". Bc basically what it will do is spin up a Firebase Function App for you, and it'll get triggered every time you upload a file to the path you specify. You can configure things like the desired size as well as the format or if you want to keep a copy of the original file or not. Good thing you won't need to worry about the underlying implementation.
{ "language": "en", "url": "https://stackoverflow.com/questions/37557343", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: varnish - regexp to edit x-forward-for header inbound / outbound I am curious if anyone knows, is it possible to build a varnish config which * *looks at inbound headers from clients *and does regexp match, to build a certain header - that is passed on to backed web server? Context: -- Varnish server deployed in front of 3-(apache)-webserver pool, acting as cache and LB -- 3rd party service DDOS proxy was dropped in front of varnish recently -- now all inbound requests to varnish have an X-Forwarded-For: header already present, indicating what the 'real' client IP address is. -- the back-end PHP web app running on the apache hosts - wants to see only one IP address, not a 'proper' X-F-F header which shows a comma-delimited list IP1, IP2, IP3 (for external proxy; varnish as proxy, original client IP - for example) -- ideally what I would like to do: is get Varnish to do regexp pattern match:rebuild on the existing inbound X-F-F headers; and strip away the external DDOS proxy IP address I had tried something like this in the 'default.vcl' file, set req.http.X-Forwarded-For = regsub(req.http.X-Forwarded-For, "123.123.123.123"," "); where 123.123.123.123 is the IP address of the external DDOS / proxy but this most certainly is not working / is not the correct syntax. I'm having trouble finding good resources online that explain regexp in varnish / or good clear examples that people use. If anyone can provide a kick in the right direction, certainly it would be greatly appreciated. Thanks for comment below - I have adjusted my config now as follows, if (req.http.x-forwarded-for) { set req.http.X-Forwarded-For = regsub(req.http.X-Forwarded-For, "\, 123\.123\.123\.123",""); } else { set req.http.X-Forwarded-For = client.ip; } and now I find in my apache logs, for example, client.ip.real.here, 123.123.123.123 - - [22/Dec/2013:07:45:17 -0800] "GET /PATH/TO/STUFF" "Mozilla/5.0.... like Gecko" which suggests to me the regexp is not actually doing what I thought I wanted. Is there any way to 'test' varnish interactively, ie, feed a given VCL rule set some defined input, and then get varnish to feed out specific output; kind of a 'dry run' processing as a way to facilitate debug ? Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/20684576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to restrict user to use 1 email id or phone number in only 1 device I'm developing an Android app with Android studio and firebase authentication and I want to restrict user to use 1 email id or 1 phone number in only 1 device .any suggestion how can I archive this functionality. A: Firebase Authentication was not designed to support this case. It's intended for users to be able to use a Firebase app on multiple devices. It's also expected that a user could create multiple accounts. There is no way of limiting the number of accounts a person can create.
{ "language": "en", "url": "https://stackoverflow.com/questions/61823002", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding Items onto Observable Collection I'm trying to add ontop of a Observable COlleciton. But When I do it doesnt add 2 distinct records, Instead it just adds 2 duplicates of the latest Records. using (var ctx = DB.Get()) { var Indepth = from z in ctx.Interactions where z.ActivityDate >= start && z.ActivityDate <= end && z.Indepth == true select new { Indepth = z.Indepth }; info.SectionInfo = "Indepth Inquiries"; info.Result = Indepth.Count(); QuarterlyInfo.Add(info); var general = from z in ctx.Interactions where z.ActivityDate >= start && z.ActivityDate <= end && z.Indepth == false select new { Indepth = z.Indepth }; info.SectionInfo = "General Inquiries"; info.Result = general.Count(); QuarterlyInfo.Add(info); } A: Not sure what the info object is but you're adding it in both queries: info.SectionInfo = "Indepth Inquiries"; info.Result = Indepth.Count(); QuarterlyInfo.Add(info); info.SectionInfo = "Indepth Inquiries"; info.Result = Indepth.Count(); QuarterlyInfo.Add(info); that might account for the dupes?
{ "language": "en", "url": "https://stackoverflow.com/questions/21999273", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Encryption and decryption with PHP I'm trying to implement encryption and decryption functions in PHP but it is not just working right. Here is the algorithm: * *Encryption key is a master code: 1234567890. *Encryption alphabet is a-z, A-Z, 0-9, = *Encrypt each symbol after the signature that belongs to the encryption alphabet. Skip the others. *Symbol is encrypted by a shift (to the right) in the encrypted alphabet. The shift amount is given by the current digit of the encryption key. The current digit of the encryption key is shifted to the right after each usage and cycled from the end to beginning. Here is my current code: function tnsencrypt($master_code,$text) { //the text to be encrypted $plain_text= $text; //letters of alphabet array $alphabet=array('0','1','2','3','4','5','6','7','8','9','=','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'); //$alphabet_len = count($alphabet); //$signature_len = 17; // signature=TnpMsgE //$master_code_len = 10; $mcursor = 0; //positions of the letters in alphabet : The array_flip() function returns an array with all the original keys as values, and all original values as keys. $flip=array_flip($alphabet); //plaintext array $plain_text=str_split($plain_text); $master_code=str_split($master_code); $n=count($plain_text); $encrypted_text=''; for ($i=0; $i } } //echo $encrypted_text; return $encrypted_text; } function tnsdecrypt($master_code,$text) { //the text to be decrypted $encrypted_text= $text; //letters of alphabet array $alphabet=array('0','1','2','3','4','5','6','7','8','9','=','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'); //positions of the letters in alphabet : The array_flip() function returns an array with all the original keys as values, and all original values as keys. $flip=array_flip($alphabet); //plaintext array $encrypted_text=str_split($encrypted_text); $master_code=str_split($master_code); $n=count($encrypted_text); $decrypted_text=''; for ($i=0; $i } else { $decrypted_text.= $encrypted_text[$i]; } //move mcursor $mcursor = ($mcursor+1)%10; } //echo $encrypted_text; return $decrypted_text; } if(isset($_POST["text"])) { $text = $_POST["text"]; $shifttext = $_POST["shifttext"]; echo " Encrypted Text: ".tnsencrypt($shifttext,$text); echo " Decrypted Text: ".tnsdecrypt($shifttext,tnsencrypt($shifttext,$text)); } ?> Here is my result: Original text: val1=1234567 val2=abcdef val3=ABCDEF Encrypted text: vjt8F666666F 3hr7Dddddnn 2gq7CCCCMMM Encrypted Text: vjt8F666666F hr7Dddddnn gq7CCCCMMM Decrypted Text: val1=1234567 al2=abcdef al3=ABCDEF As you can see, a couple of characters are missing on the encryption and that affected the decryption as well. The missing ones are v on line 2 and v on line 3 Any ideas why? A: Why are you doing this? There are several one- and two-way encryption solutions you could be using instead, if this is for actual use and not just an academic exercise: One-Way: crypt() Two-Way: mcrypt Encryption is pretty much a solved problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/12572986", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to connect php code to database table I am editing a laravel project and I would like to add a signature feature. I have this code down below that is mobile responsive. But I couldn't figure out how to connect it to an existing Lets say for example that server name: localhost. username: db_test. password:db123. database name:db_test the table I want to insert it in is $booking->signature. <?php if(isset($_POST['signaturesubmit'])){ $signature = $_POST['signature']; $signatureFileName = uniqid().'.png'; $signature = str_replace('data:image/png;base64,', '', $signature); $signature = str_replace(' ', '+', $signature); $data = base64_decode($signature); $file = 'signatures/'.$signatureFileName; file_put_contents($file, $data); $msg = "<div class='alert alert-success'>Signature Uploaded</div>"; } ?> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <style> #canvasDiv{ position: relative; border: 2px dashed grey; height:300px; } </style> </head> <body> <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <br> <?php echo isset($msg)?$msg:''; ?> <h2>Sign Here</h2> <hr> <div id="canvasDiv"></div> <br> <button type="button" class="btn btn-danger" id="reset-btn">Clear</button> <button type="button" class="btn btn-success" id="btn-save">Save</button> </div> <form id="signatureform" action="" style="display:none" method="post"> <input type="hidden" id="signature" name="signature"> <input type="hidden" name="signaturesubmit" value="1"> </form> </div> </div> </body> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha256-pasqAKBDmFT4eHoN2ndd6lN370kFiGUFyTiUHWhU7k8=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.5.0-beta4/html2canvas.min.js"></script> <script> $(document).ready(() => { var canvasDiv = document.getElementById('canvasDiv'); var canvas = document.createElement('canvas'); canvas.setAttribute('id', 'canvas'); canvasDiv.appendChild(canvas); $("#canvas").attr('height', $("#canvasDiv").outerHeight()); $("#canvas").attr('width', $("#canvasDiv").width()); if (typeof G_vmlCanvasManager != 'undefined') { canvas = G_vmlCanvasManager.initElement(canvas); } context = canvas.getContext("2d"); $('#canvas').mousedown(function(e) { var offset = $(this).offset() var mouseX = e.pageX - this.offsetLeft; var mouseY = e.pageY - this.offsetTop; paint = true; addClick(e.pageX - offset.left, e.pageY - offset.top); redraw(); }); $('#canvas').mousemove(function(e) { if (paint) { var offset = $(this).offset() //addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, true); addClick(e.pageX - offset.left, e.pageY - offset.top, true); console.log(e.pageX, offset.left, e.pageY, offset.top); redraw(); } }); $('#canvas').mouseup(function(e) { paint = false; }); $('#canvas').mouseleave(function(e) { paint = false; }); var clickX = new Array(); var clickY = new Array(); var clickDrag = new Array(); var paint; function addClick(x, y, dragging) { clickX.push(x); clickY.push(y); clickDrag.push(dragging); } $("#reset-btn").click(function() { context.clearRect(0, 0, window.innerWidth, window.innerWidth); clickX = []; clickY = []; clickDrag = []; }); $(document).on('click', '#btn-save', function() { var mycanvas = document.getElementById('canvas'); var img = mycanvas.toDataURL("image/png"); anchor = $("#signature"); anchor.val(img); $("#signatureform").submit(); }); var drawing = false; var mousePos = { x: 0, y: 0 }; var lastPos = mousePos; canvas.addEventListener("touchstart", function(e) { mousePos = getTouchPos(canvas, e); var touch = e.touches[0]; var mouseEvent = new MouseEvent("mousedown", { clientX: touch.clientX, clientY: touch.clientY }); canvas.dispatchEvent(mouseEvent); }, false); canvas.addEventListener("touchend", function(e) { var mouseEvent = new MouseEvent("mouseup", {}); canvas.dispatchEvent(mouseEvent); }, false); canvas.addEventListener("touchmove", function(e) { var touch = e.touches[0]; var offset = $('#canvas').offset(); var mouseEvent = new MouseEvent("mousemove", { clientX: touch.clientX, clientY: touch.clientY }); canvas.dispatchEvent(mouseEvent); }, false); // Get the position of a touch relative to the canvas function getTouchPos(canvasDiv, touchEvent) { var rect = canvasDiv.getBoundingClientRect(); return { x: touchEvent.touches[0].clientX - rect.left, y: touchEvent.touches[0].clientY - rect.top }; } var elem = document.getElementById("canvas"); var defaultPrevent = function(e) { e.preventDefault(); } elem.addEventListener("touchstart", defaultPrevent); elem.addEventListener("touchmove", defaultPrevent); function redraw() { // lastPos = mousePos; for (var i = 0; i < clickX.length; i++) { context.beginPath(); if (clickDrag[i] && i) { context.moveTo(clickX[i - 1], clickY[i - 1]); } else { context.moveTo(clickX[i] - 1, clickY[i]); } context.lineTo(clickX[i], clickY[i]); context.closePath(); context.stroke(); } } }) </script> </html> A: You have to set the DB credentials in .env file. It's in the root of your project. If it does not exists, you can rename .env.example and make changes to it. Based on your code (interaction with database in view is not standard in an MVC framework, atleast), I think it's better to get familiar with laravel first. There are a lot resources to learn it.
{ "language": "en", "url": "https://stackoverflow.com/questions/72341948", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: How to match columns which starts with particular string and ends with other particular string? I have code: import pandas as pd data = {'spike_starts': [1,2,3], 'ends_spike_starts': [4,5,6], 'ends_spike': [7,8,9], 'not': [10,11,12], 'castle': [13,14,15]} df = pd.DataFrame(data) print("\n") print("----------------------------------------") colNames_starts = df.columns[df.columns.str.contains(pat = '^spike')].tolist() print("Starts") print(colNames_starts) print("\n") print("----------------------------------------") colNames_ends = df.columns[df.columns.str.contains(pat = 'spike$')].tolist() print("Ends") print(colNames_ends) colNames_starts - list contains column names which name starts with spike. colNames_ends - list contains column names which name ends with spike. Question: How to modify regex part of above code to get column names in list which are starting with ca and ending with le? So in my example list should contain castle.
{ "language": "en", "url": "https://stackoverflow.com/questions/61281390", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery Cycle - randomizing multiple elements in sync I am trying to cycle the content of two elements on a page in random order but synced to each other. I have two div containers with a set of nested divs: (div class=text (.textA, .textB, .textC)), (div class=image (.imageA, .imageB, .imageC)) I am using this to start the simultaneous transition: $('.text, .image').cycle({ fx: 'fade', delay: -2000, speed: 'slow', random: 1 }); but I get always other order in both div-elements: (.text .textB) -> (.image .imageA) and so on. How do I get the both nested elements to display in sync? A: Only set the cycle on one of the slideshows; then use the after callback to transition the other one to the corresponding slide: after: function(currSlideElement, nextSlideElement, options, forwardFlag) { // your code here }
{ "language": "en", "url": "https://stackoverflow.com/questions/8226755", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Dropping floats-- basic CSS layout issue I'm wrestling with a frustrating-- and profoundly basic-- CSS issue that's illustrated by the diagram below, and a js fiddle here. I'm trying to achieve a fluid grid layout with floated block elements defined by percentage widths and varying heights, that will linearize-- i.e. change to width: 100% at a certain breakpoint (in the fiddle there's a media query @ 768px max-width.) Note that I need the blocks to linearize in a way that "weaves" the two main colunmns together, as shown in the fiddle. I'm having a problem with the floated elements "dropping" and not aligning vertically as desired-- as indicated by the "news/speaking" block in my diagram. I have tried every masonry-type jquery plugin I can find, and none of them seem to perform in a consistent or reliable way with fluid layouts. I'm also aware of the inline-block method, but the quirks/limitations pose their own problems. Additionally, flexbox looks fantastic, but the current limited support is a problem for this project in particular. I am open to a jquery-based approach-- i.e. forcing certain blocks to align to the bottom of others, but would prefer a css-based one. I realize I can always apply a negative margin to the "dropping" elements, but this is not a very elegant solution. Any help with this "float dropping" issue is most appreciated. A: I'm unsure what "quirks/limitations" you're running into using inline-block, but if you apply it to .item.w1 only, it seems to work. You'll also need to remove float: none here: @media only screen and (max-width : 768px) and (orientation : portrait) { .item.w1, .item.w2 { float: none; width: 100%; } } Fiddle
{ "language": "en", "url": "https://stackoverflow.com/questions/30489317", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Django Read png image from url then pass it to HttpResponse I want to to read png image from private url then write it to HttpResponse. I have this view that will get a layer from geoServer as a png image then open it and read it then return it as HttpResponse: def get_layer(request): #this url will return png image url='https://example.com/geoserver/layer/wms?.......' r = requests.get(url) with open(r, "rb") as fp: img = Image.open(fp) return HttpResponse(img) I am getting an error: Exception Type: TypeError Exception Value: invalid file: Response [200] /main/views.py in test1 with open(r, "rb") as fp: ... ▼ Local vars Variable Value r <Response [200]> request <WSGIRequest: GET '/test/'> url 'https://example.com/geoserver/layer/wms?.......' All want I want is get the png file from the url then pass it the the HttpResponse so when one call my view, he/she will get the image only with my Django path. I do not want to save the image locally I just want to assign it to a variable and pass it. I am using: Django 1.11, python3.5. A: Does this work? def get_layer(request): #this url will return png image url='https://example.com/geoserver/layer/wms?.......' r = requests.get(url) return HttpResponse(r.content, content_type="image/png")
{ "language": "en", "url": "https://stackoverflow.com/questions/48512892", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get user Seesion id from SugarCRM using Email ID/User Id I have one sugarCRM installation. When I pass the email id/user id, is it possible to9 get the user session id in sugarCRM? Please suggest.Because based on user identity I need to create Leads, campaigns etc using REST API A: Logged in user details are store in global variable current_user. And Yes. You will get session id once you call login method from REST. $proxy is the object of your rest $credentials = array( 'user_name' => 'username', 'password' => md5('password') ); $result = $proxy->login($credentials, 'your_application_name'); $session_id = $result['id']; A: Sachin is right, there is a global variable for currently logged in user. And you can access its properties straightforward : Its an instance of the user bean. global $current_user; echo $current_user->id; echo $current_user->user_name;
{ "language": "en", "url": "https://stackoverflow.com/questions/30618205", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: FutureBuilder, The getter 'variable' isn't defined for the type 'Object' Im trying to get the values from the Future object, but vsc always says The getter 'wetter' isn't defined for the type 'Object'. Try importing the library that defines 'wetter', correcting the name to the name of an existing getter, or defining a getter or field named 'wetter'.dartundefined_getter Thats my code, the Error appears at grad = snapshot.data!.wetter void refreshWeather() { final Future<Wetter> wetter = Wetterapi.fetchWetter(); FutureBuilder( future: wetter, builder: (context, snapshot) { if (snapshot.hasData) { grad = snapshot.data!.wetter; } throw ''; }); } The wetter class looks like this class Wetter { final String wetter; final double temperatur; final String wind; Wetter({ required this.wetter, required this.temperatur, required this.wind, }); factory Wetter.fromJson(Map<String, dynamic> json) { return Wetter( wetter: json['weather.main'], temperatur: json['main.temp'], wind: json['wind.speed'], ); } String get gewetter { return wetter; } } Am I missing something? A: Define the type parameter of FutureBuilder: // vvvvvvvv FutureBuilder<Wetter>( future: wetter, builder: (context, snapshot) { if (snapshot.hasData) { grad = snapshot.data!.wetter; } throw ''; }, );
{ "language": "en", "url": "https://stackoverflow.com/questions/68184617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error executing "docker ps --format". Error: flag provided but not defined: --format I have install docker using following command: sudo apt-get install docker.io for testing purpose, I run a Ubuntu image in detached mode using sudo docker run -d -it Ubuntu But when I tried to execute docker ps command like sudo docker ps --format I got some error. According to the error, the flag --format is not defined. Following is the error message. flag provided but not defined: --format See 'docker ps --help'. When I check for the help page I found this Usage: docker ps [OPTIONS] List containers -a, --all=false Show all containers (default shows just running) --before= Show only container created before Id or Name -f, --filter=[] Filter output based on conditions provided --help=false Print usage -l, --latest=false Show the latest created container, include non-running -n=-1 Show n last created containers, include non-running --no-trunc=false Don't truncate output -q, --quiet=false Only display numeric IDs -s, --size=false Display total file sizes --since= Show created since Id or Name, include non-running According to help page, there is no flag --format is defined. But according to the reference in https://docs.docker.com/engine/reference/commandline/ps/ , I should be able to run the command with --format flag. What could be the reason ? Supplementary Information * *OS: Ubuntu 14.04 *docker version : Docker version 1.6.2, build 7c8fca2 -Thank you A: The --format option was only added to docker ps in version 1.8.0 so unless you are able to upgrade then you won't be able to use it. It would be quite handy if this was made clear in the documentation page you linked to but I think probably docker just expect you to use the latest version - they are not known for providing long term support for older versions.
{ "language": "en", "url": "https://stackoverflow.com/questions/40550258", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: My logged in user gets logged out every time I refresh the page. -JS, REACT, JWT, socket.io I'm a student and I'm trying to create a chat app with login/registration with React, but I cannot seem to keep the user logged on whenever I refresh the page. Can anyone please help me out? Thank you in advance. Login.jsx import React, { useEffect, useState, useContext } from "react"; import { useNavigate, Link } from "react-router-dom"; import logo1 from "../images/logo1.png"; import Chat from "./Chat"; import man from "../images/aolemoji.png"; import { UserContext } from "../context/UserContext"; import axios from "axios"; import App from "../App"; import io from "socket.io-client"; const Login = (props) => { const { user, setUser, socket } = useContext(UserContext); const [userToken, setuserToken] = useState(""); const navigate = useNavigate(); const [state, setState] = useState({ login: { email: "", password: "", }, }); const [errors, setErrors] = useState([]); const { login } = state; const handleLoginInputs = (e) => { props.setAuthorized(""); setState({ ...state, login: { ...state.login, [e.target.name]: e.target.value }, }); }; const handleLogin = async (e) => { e.preventDefault(); const errorArr = []; axios .post("http://localhost:8000/api/users/login", login, { withCredentials: true, }) .then((res,req) => { setUser({ id: res.data.userInfo.id, screenName: res.data.userInfo.screenName, }); console.log("Printing out res.data during login", res.data); console.log("User has been successfully logged in"); console.log("What is my token?", res.data.token); navigate("/chat"); }) .catch((err) => { console.log("is it even catching an error?", err); const errorResponse = err.response.data; console.log("errorArr", errorArr); console.log("errorResponse", errorResponse); errorArr.push( "Ooops, something went wrong with logging in. Try again!" ); setErrors(errorArr); console.log("what is my error arr?", errorArr); }); }; return ( <> <div className=""> <nav className=" whitespace-nowrap m-2 border-gray-200 px-2 sm:px-4 py-2.5 rounded-sm shadow-lg fill-indigo-400border-2 bg-blue-400"> <div className="container flex flex-wrap items-center justify-between mx-auto"> <div className="flex items-center"> <img src={man} className=" h-20 w-25" alt="Flowbite Logo" /> <h1 className="text-4xl content-centerfont-extrabold text-white dark:text-white"> SAIM - MESSENGER </h1> </div> <p className="tracking-tighter text-gray-900 md:text-lg dark:text-gray-900"> A space where millennials can chat and share their hilarious away messages </p> <div className="hidden w-full md:block md:w-auto" id="navbar-default" ></div> </div> </nav> </div> <div className="items-center flexm-2"> <span className=" block max-w-xs max-h-sm p-2 bg-white border border-gray-200 rounded-lg shadow hover:bg-gray-100 dark:border-gray-700 mt-2 m-auto"> <img src={logo1} style={{}} alt="logo1" /> <hr /> <form onSubmit={handleLogin}> {errors.length > 0 && errors.map((error, i) => ( <> <p className=" text-red-600" key={i}> {error} </p> </> ))} <div className="mb-6 mt-0"> <label className="block"> <span className="after:content-['*'] after:ml-0.5 after:text-red-500 flex text-sm font-medium text-black"> eMail! </span> <input onChange={handleLoginInputs} type="email" name="email" className="mt-1 px-3 py-2 bg-white border shadow-sm border-slate-300 placeholder-slate-400 focus:outline-none focus:border-sky-500 focus:ring-sky-500 block w-full rounded-md sm:text-sm focus:ring-1" placeholder="you@example.com" /> <Link className=" text-blue-700 underline" to={"/register"} > No account? Sign Up! </Link> </label> </div> <div> <label className="block"> <span className="after:content-['*'] after:ml-0.5 after:text-red-500 block text-sm font-medium text-black"> PaSsWoRd: </span> <input onChange={handleLoginInputs} type="text" name="password" className="mt-1 px-3 py-2 bg-white border shadow-sm border-slate-300 placeholder-slate-400 focus:outline-none focus:border-sky-500 focus:ring-sky-500 block w-full rounded-md sm:text-sm focus:ring-1" placeholder="Enter Your Password" /> </label> </div> <button type="submit" className="m-8 flex"> <a href="#_" className="relative px-6 py-3 font-bold text-black group" type="submit" > <span className="absolute inset-0 w-full h-full transition duration-300 ease-out transform -translate-x-2 -translate-y-2 bg-blue-300 group-hover:translate-x-0 group-hover:translate-y-0"></span> <span className="absolute inset-0 w-full h-full border-4 border-black"></span> <span className="relative">Sign On</span> </a> </button> <hr /> <span className="text-sm text-gray-500 sm:text-center dark:text-gray-400"> © 2023{" "} <a href="https://flowbite.com/" className="hover:underline" > SAIM MESSENGER™ </a> . All Rights Reserved.{" "} </span> </form> </span> </div> </> ); }; export default Login; user.controller.js const User = require("../models/user.models"); const jwt = require("jsonwebtoken"); const bcrypt = require("bcrypt"); function helper(message, value) { console.log(message, value); return value; } module.exports = { findAllUsers: (req, res) => { User.find() .then((allUsers) => res.json({ allUsers, message: "Here are all users" }) ) .catch((err) => res.status(400).json({ message: "Something went wrong while trying to view all users", error: err, }) ); }, updateUser: (req, res) => { User.findByIdAndUpdate(req.params.id, req.body, { new: true, runValidators: true, }) .then((updatedAwayMessage) => res.json({ updatedAwayMessage, message: "You have successfully updated a user profile.", }) ) .catch((err) => res.status(400).json({ message: "Something went wrong while user update.", error: err, }) ); }, findOneUser: (req, res) => { User.findById(req.params.id) .then((user) => res.json({ user, message: "Yay you have found a specific user", }) ) .catch((err) => res.status(400).json({ message: "Something went wrong while trying to find details of a user", error: err, }) ); }, register: (req, res) => { User.create(req.body) .then((user) => { const userToken = jwt.sign( { id: user._id, }, process.env.SECRET_KEY ); res.cookie("usertoken", userToken, { httpOnly: true, // secure: true, // sameSite: 'none', // expires: new Date(Date.now() + 24 * 60 * 60 * 1000) // 24 hours }).json({ msg: "Successful Registration!", user: user }); }) .catch((err) => res.json({ message: "Problem with registration", error: err }) ); }, deleteUser: (req, res) => { User.findByIdAndDelete(req.params.id) .then((deletedUser) => res.json({ deletedUser, message: "Successfully deleted user." }) ) .catch((err) => res.status(400).json({ message: "Something went wrong while deleting/adopting.", error: err, }) ); }, login: async (req, res) => { const user = await User.findOne({ email: req.body.email }); if (user === null) { // email not found in users collection return res .sendStatus(400) .json({ message: "Invalid email address" }); } // if we made it this far, we found a user with this email address // let's compare the supplied password to the hashed password in the database const correctPassword = await bcrypt.compare( req.body.password, user.password ); if (!correctPassword) { // password wasn't a match! return res.sendStatus(400).json({ message: "Invalid password" }); } // if we made it this far, the password was correct const userToken = jwt.sign({ id: user._id }, process.env.SECRET_KEY); // Set the maxAge property of the cookie to 24 hours (in seconds) res.cookie("usertoken", userToken, { httpOnly: true, maxAge: 24 * 60 * 60, // 24 hours in seconds }).json({ msg: "You have successfully logged in.", userInfo: { id: user._id, screenName: user.screenName, }, }); }, // //CODING DOJO METHOD // login: async (req, res) => { // const user = await User.findOne({ email: req.body.email }); // if (user === null) { // // email not found in users collection // return res // .sendStatus(400) // .json({ message: "Invalid email address" }); // } // // if we made it this far, we found a user with this email address // // let's compare the supplied password to the hashed password in the database // const correctPassword = await bcrypt.compare( // req.body.password, // user.password // ); // if (!correctPassword) { // // password wasn't a match! // return res.sendStatus(400).json({ message: "Invalid password" }); // } // // if we made it this far, the password was correct // const userToken = jwt.sign({ id: user._id }, process.env.SECRET_KEY); // console.log("userToken", userToken); // console.log( // "Yay! You have successfully signed in. Here's your usertoken: ", // userToken, // "User's information: ", // req.body // ); // // note that the response object allows chained calls to cookie and json // res.cookie("usertoken", userToken, { // httpOnly: true, // // maxAge: maxAge * 1000 // // sameSite:'none' // }).json({ // msg: "You have successfully logged in.", // userInfo: { // id: user._id, // screenName: user.screenName, // }, // }); // }, logout: (req, res) => { // localStorage.removeItem('userDetails'); localStorage.removeItem("usertoken", userToken); res.clearCookie("usertoken"); res.sendStatus(200).json({ message: "You have logged out!" }); }, }; UserContext.js import {useState, createContext} from 'react'; import io from 'socket.io-client'; const UserContext = createContext(); const UserProvider = ({children}) => { const [user, setUser] = useState({ id: 0, screenName: "", // room: "" }) const [socket] = useState(() => io(":8000")) return ( <UserContext.Provider value={{user, setUser, socket}}> {children} </UserContext.Provider> ) } export {UserProvider, UserContext} server.js const express = require('express'); const app = express(); const cors = require('cors') const cookieParser = require('cookie-parser'); const dotenv = require('dotenv'); const bcrypt = require('bcrypt'); const jwt = require('jsonwebtoken'); require('dotenv').config(); const myFirstSecret = process.env.FIRST_SECRET_KEY; const http = require('http'); const port = 8000; const server = app.listen(port, () => console.log("Listening on port", port)); const socketio = require('socket.io') require('./config/mongoose.config') app.use(cors({credentials: true, origin: 'http://localhost:3000'})); app.use(express.json()); app.use(cookieParser()); app.use(express.urlencoded({ extended: true })); require("./routes/awayMessage.routes")(app); const UserRoutes = require('./routes/user.routes') UserRoutes(app); const io = socketio(server,{ cors: { origin: "http://localhost:3000", methods: ["GET", "POST"], allowedHeaders: ['*'], credentials: true } }) app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html'); }); console.log(JSON.stringify(socketio)) io.on("connection", (socket) => { console.log(" server io ...on") console.log("Socket:", socket.id, "connected to the server"); console.log(`Message sent from ${socket.id}: ${socket}`); // console.log("Is io on from server printing data?", data); socket.on("send_message", (data) => { io.emit("message_received", data) console.log("io:", io); console.log("emit:", emit); }) // socket.on("join_room", (data) => { // console.log("Joined room:", data); // socket.join(data) // }) socket.on("private_message", (data) => { console.log(data); // io.to(data.room).emit("private_message_response", data) //try this out later to add rooms io.emit("private_message_response", data) }) }) jwt.config.js const jwt = require("jsonwebtoken"); secret="secret"; module.exports.secret = secret; module.exports.authenticate = (req, res, next) => { jwt.verify(req.cookies.usertoken, secret, (err, payload) => { if (err) { res.status(401).json({verified: false}); } else { next(); } }); } I have tried to look into storing my token into local storage, but I am not sure if I am doing it correctly since I obviously break things while trying. :(
{ "language": "en", "url": "https://stackoverflow.com/questions/75523973", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can two or more lists be traversed in O(N) I have a question that doesn't seem possible to me. I have 2+ arrays which I have to compare for common values. I am supposed to do this in O(N) comparisons but can't think of a way. Specifically (k-1)N comparisons where k is the number of arrays. I've narrowed down how I can take multiple arrays and just merge them into a single array. I've gotten that the smallest array is the limiting factor so if I sort that I can save the most comparisons. After spending half the day staring at my screen I've even come up with a way to do this linearly if I discount any duplicates, but I have to keep duplicates So, as far as I know in order to compare any arrays you need at least 2 for loops which would be O(N^2) wouldn't it? I'm also not allowed to hash anything. For example if I had {1,3,4,3,4,5} as a master and {1,1,3,5,9,3,7} and {3,5,8,4,0,3,2} as arrays to be compared I'd need to have a final of {3,3,5} since I can't get rid of any dupiclates. I don't want anyone to write the code, I just need to know what I should be doing in the first place. A: If the lists are sorted, then it's relatively straightforward if you do something like this: List<Integer> intersection = new ArrayList<>(); int i = 0; int j = 0; while (i < list1.size() && j < list2.size()) { int a = list1.get(i); int b = list2.get(j); if (a < b) { i++; } else if (b < a) { j++; } else { // a == b intersection.add(a); i++; j++; } } On each iteration of the loop, the quantity i + j increases by at least 1, and the loop is guaranteed to be done when i + j >= list1.size() + list2.size(), so the whole thing does at most O(list1.size() + list2.size()) comparisons. A: Use an array of ints. Taking your first list, for each element, set the value at that index to 1. So if the first element is 3, put 1 in array[3]. Now, we know that 3 is present in first list. Putting 1 will help you distinguish from a 3 that is present in the earlier list versus a 3 which is repeated in current list. * *Iterate through all the other k-1 lists *For every element, check the value in array for that index *If the value is 0, set it to this list number *If the value is a number less than this list number, this number is a duplicate and has already appeared in a previous list. *If this number is equal to this list index it means this number already occurred in this list but not in previous lists, so not yet a duplicate. *The numbers that you are getting as duplicates, add them to another list. *Finish all iterations Finally print the duplicates. Original Wrong Answer * *Create a HashSet<int> *Take all values from master and add to it - O(master list count) *Now just iterate through first and second arrays and see if their elements are in that HashSet - O(each list count)
{ "language": "en", "url": "https://stackoverflow.com/questions/32772071", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Auth0 is failing localauthsetup 3 times and later i am able to route to the home page When I login through auth0 - the localauthsetup is failing 3 times and next it is returning true to login, can you please help me with this? localauthsetup and handleAuthCallback are called in the appcomponent which is similar calling in construction. Domain id and client id is imported from the config file and it is also working as expected and the code working is almost same as it is there in the link provide: https://auth0.com/docs/quickstart/spa/angular2/01-login#add-the-authentication-service auth0Client$ = (from( createAuth0Client({ domain: AuthConfig.domain, client_id: AuthConfig.clientId, redirect_uri: `${window.location.origin}` }) ) as Observable<Auth0Client>).pipe( shareReplay(1), // Every subscription receives the same shared value catchError(err => _throw(err)) ); // Define observables for SDK methods that return promises by default // For each Auth0 SDK method, first ensure the client instance is ready // concatMap: Using the client instance, call SDK method; SDK returns a promise // from: Convert that resulting promise into an observable isAuthenticated$ = this.auth0Client$.pipe( concatMap((client: Auth0Client) => from(client.isAuthenticated())), tap(res => this.loggedIn = res) ); handleRedirectCallback$ = this.auth0Client$.pipe( concatMap((client: Auth0Client) => from(client.handleRedirectCallback())) ); // Create subject and public observable of user profile data private userProfileSubject$ = new BehaviorSubject<any>(null); userProfile$ = this.userProfileSubject$.asObservable(); // Create a local property for login status loggedIn: boolean = null; constructor(private router: Router) { console.log('service called'); //calling localauthsetup and handleAuthCallback here } // When calling, options can be passed if desired // https://auth0.github.io/auth0-spa-js/classes/auth0client.html#getuser getUser$(options?): Observable<any> { return this.auth0Client$.pipe( concatMap((client: Auth0Client) => from(client.getUser(options))), tap(user => this.userProfileSubject$.next(user)) ); } localAuthSetup() { // This should only be called on app initialization // Set up local authentication streams const checkAuth$ = this.isAuthenticated$.pipe( concatMap((loggedIn: boolean) => { console.log('localauthsetup',loggedIn); if (loggedIn) { // If authenticated, get user and set in app // NOTE: you could pass options here if needed return this.getUser$(); } // If not authenticated, return stream that emits 'false' return of(loggedIn); }) ); checkAuth$.subscribe((res)=>{ console.log('subscripbe',res) }); } login(redirectPath: string = '/') { console.log('login called',redirectPath); // A desired redirect path can be passed to login method // (e.g., from a route guard) // Ensure Auth0 client instance exists this.auth0Client$.subscribe((client: Auth0Client) => { // Call method to log in client.loginWithRedirect({ redirect_uri: `${window.location.origin}`, appState: { target: redirectPath } }); }); } handleAuthCallback() { console.log('handleauth called'); // Call when app reloads after user logs in with Auth0 const params = window.location.search; if (params.includes('code=') && params.includes('state=')) { let targetRoute: string; // Path to redirect to after login processsed const authComplete$ = this.handleRedirectCallback$.pipe( // Have client, now call method to handle auth callback redirect tap(cbRes => { // Get and set target redirect route from callback results targetRoute = cbRes.appState && cbRes.appState.target ? cbRes.appState.target : '/'; }), concatMap(() => { // Redirect callback complete; get user and login status return combineLatest([ this.getUser$(), this.isAuthenticated$ ]); }) ); // Subscribe to authentication completion observable // Response will be an array of user and login status authComplete$.subscribe(([user, loggedIn]) => { // Redirect to target route after callback processing this.router.navigate([targetRoute]); }); } } logout() { // Ensure Auth0 client instance exists this.auth0Client$.subscribe((client: Auth0Client) => { // Call method to log out client.logout({ client_id: AuthConfig.clientId, returnTo: `${window.location.origin}` }); }); } A: It's Konrad here. I'm Auth0 Community Engineer. Not an Angular expert but as I can see looking at our quickstart and your code snippet you're not invoking localAuthSetup methood anywhere you just have it defined as well as handleAuthCallback. Can you try calling both in the constructor as it's suggested in the quickstart? A: Login to your tenant, go to the spa app, settings. Find the Allowed Callback URLs and make sure you have something like this there` your_domain, your_domain/login """ PS "/login" is the same path of Application Login URI
{ "language": "en", "url": "https://stackoverflow.com/questions/59386132", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: get black screen after popScene I just started learning Cocos2dx, and use the basic HelloWorld project. I added a SecondScene and and a button in it to change scene. But once the popScene method executed, screen became black and it didn't pop to first scene. I don't have any idea what's wrong. Here's the code I modified a little in HelloWorld.cpp: #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) CCDirector::sharedDirector()->pushScene(SecondScence::scene()); #endif Code in SecondScene: #include "SecondScence.h" USING_NS_CC; CCScene* SecondScence::scene(){ CCScene* scene=CCScene::create(); SecondScence* layer = SecondScence::create(); scene->addChild(layer); return scene; bool SecondScence::init(){ CCLabelTTF* label = CCLabelTTF::create("hfiejfeiojfoej", "Arial", 30); label->setPosition(ccp(200,200)); this->addChild(label); CCMenuItemImage *pCloseItem = CCMenuItemImage::create( "CloseNormal.png","CloseSelected.png",this,menu_selector(SecondScence::popScene)); pCloseItem->setPosition(ccp(CCDirector::sharedDirector()->getWinSize().width-20, 20)); CCMenu *pMenu = CCMenu::create(pCloseItem,NULL); pMenu->setPosition(CCPointZero); this->addChild(pMenu,1); return true; } void SecondScence::popScene(CCObject* pSender){ CCDirector::sharedDirector()->popScene(); } By the way, I use cocos2dx 2.2 and xcode5, the the console print a message:Cocos2d: cocos2d: deallocing CCDirector 0x6906f0 A: Verify that the popScene method isn't run twice, perhaps by the user quickly tapping the menu item (or a bug). That would pop both the current and the HelloWorld scene, leaving the director with no scene to display. It would also explain the director deallocating. You can prevent this by first checking whether the director's runningScene is identical to this (as in: the SecondScene instance), and only then call popScene. A: I have same problem too, but I solved, I think you may have removed all children from the scene, check you onExit or destructor to see if any release/remove options available in these two functions. if the scene has no children, it would be black.
{ "language": "en", "url": "https://stackoverflow.com/questions/21285166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ListView scroll position not maintained after loading content using CWAC Endless Adapter update Basically, bbrakenhoff has answered my question but there is just one more thing left to fix. How can I update the contents of my EndlessFeedAdapter (mEndlsFidAdptr)? I need to clear the item and then reload. I'm using the CWAC EndlessAdapater. Is there a trick to clear the contents or would it be easier to just program a method? After this is done the scroll position should be maintaind. I am getting data from a server and updating my EndlessFeedAdapter when content changes. Each time I am updating my adapter and reloading content. The problem is that after reloading my list jumps right back to the top as my scroll position is not maintained. I have tried setSelection and setSelectionFromTop extensively, but without positive results. How do I maintain scroll position after the adapter has been updated? I have been going through the forums searching for an answer but nothing seems to be working. I have tried all these: Maintain/Save/Restore scroll position when returning to a ListView This didn't work: int index = mList.getFirstVisiblePosition(); View v = mList.getChildAt(0); int top = (v == null) ? 0 : v.getTop(); // restore index and position mList.setSelectionFromTop(index, top); Nor this: // Save ListView state Parcelable state = listView.onSaveInstanceState(); // Set new items listView.setAdapter(adapter); // Restore previous state (including selected item index and scroll position) listView.onRestoreInstanceState(state); Nor the other solutions such as setting up a runnable or setting the scrollPositionY. Setting notifyDataChanged didn't work as I am loading from different lists. My code: private void showFeed() { if (mFeedActivity.mInFeed) { mQuickReturnView.setVisibility(View.VISIBLE); } else { mQuickReturnView.setVisibility(View.GONE); } Activity actvt= getActivity(); if (actvt == null || mFeedListView == null) return; actvt.invalidateOptionsMenu(); mFeedListView.setVisibility(View.VISIBLE); //updated with help from response if (mAdapter == null){ mAdapter = new FeedAdapter(actvt, 0, mFeed.getItems().getFeedItemList(), this); } else { mAdapter.clear(); mAdapter.addAll(mFeed.getItems().getFeedItemList()); mAdapter.notifyDataSetChanged(); } mEndlsFidAdptr = new EndlessFeedAdapter(actvt, mAdapter, R.layout.progress_row, mFeed.isShowMoreBar(), mEndlsFidAdptr.setRunInBackground(false); //Parcelable state = mFeedListView.onSaveInstanceState(); mFeedListView.setAdapter(mEndlsFidAdptr); //mFeedListView.onRestoreInstanceState(state); mFeedListView.setSelectionFromTop(mFirstVisibleItem, mVisibleItemOffset); if(!(mFeedScope.equalsIgnoreCase(FeedScope.BOOKMARKS.xmlValue()) || mFeedScope.equalsIgnoreCase(FeedScope.DOCUMENT.xmlValue()) || mFeedScope.equalsIgnoreCase(FeedScope.NOTIFICATIONS.xmlValue()) || mFeedScope.equalsIgnoreCase(FeedScope.RECEIVED_TASKS.xmlValue()) || mFeedScope.equalsIgnoreCase(FeedScope.SEND_TASKS.xmlValue()))) { mFeedListView.getViewTreeObserver().addOnGlobalLayoutListener(mGlobalLayoutListener); mFeedListView.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { mCanShowHide = scrollState == SCROLL_STATE_FLING; } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { View v = mFeedListView.getChildAt(0); //View v = null; if(!mFeedActivity.mInFeed || v == null) return; int top = v.getTop(); if(mIsAnimating) { mVisibleItemOffset = top; mFirstVisibleItem = firstVisibleItem; return; } boolean hide = false; boolean show = false; float stickyHeight = getResources().getDimension(R.dimen.sticky_height); if(firstVisibleItem == mFirstVisibleItem) { if((top + stickyHeight) < mVisibleItemOffset) { // Content scrolled down // if shown then hide quickactionview if(mQuickReturnShown) { hide = true; } } else if (top > mVisibleItemOffset) { // Content scrolled up // if hidden then show quickactionview if(!mQuickReturnShown) { show = true; } } } else if(firstVisibleItem > mFirstVisibleItem) { // Content scrolled down // if shown then hide quickactionview if(mQuickReturnShown) { hide = true; } } else if (firstVisibleItem < mFirstVisibleItem) { // Content scrolled up // if hidden then show quickactionview if(!mQuickReturnShown) { show = true; } } if((show && mCanShowHide) || (top == 0 && !mQuickReturnShown)) { mTranslateAnimation = new TranslateAnimation(0, 0, -mQuickReturnHeight, 0); mTranslateAnimation.setDuration(DURATION_MILLIS); mTranslateAnimation.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { mIsAnimating = true; } @Override public void onAnimationEnd(Animation animation) { mIsAnimating = false; mQuickReturnShown = true; mQuickReturnView.setVisibility(View.VISIBLE); } @Override public void onAnimationRepeat(Animation animation) { } }); mQuickReturnView.startAnimation(mTranslateAnimation); } if(hide) { mTranslateAnimation = new TranslateAnimation(0, 0, 0, -mQuickReturnHeight); mTranslateAnimation.setDuration(DURATION_MILLIS); mTranslateAnimation.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { mIsAnimating = true; } @Override public void onAnimationEnd(Animation animation) { mIsAnimating = false; mQuickReturnShown = false; mQuickReturnView.setVisibility(View.GONE); } @Override public void onAnimationRepeat(Animation animation) { } }); mQuickReturnView.startAnimation(mTranslateAnimation); } mVisibleItemOffset = top; mFirstVisibleItem = firstVisibleItem; } }); } else { mFeedListView.setOnScrollListener(null); } mFeedListView.setSelectionFromTop(mFirstVisibleItem, mVisibleItemOffset); //mFeedListView.scrollTo(mCurrentX,mCurrentY); if(mFeed.getItems().getFeedItemList().size() == 0) { mEmptyFeedView.setVisibility(View.VISIBLE); } } A: Are you calling the method showFeed() everytime you received new data? If yes, then maybe you could try to refill the adapter instead of assigning a new one every time. I don't know exactly what you are doing in your adapter, so I'll show you how I did it in one of my apps. In my Activity/Fragment I do this when I want to update the list with new items: private void refreshCalendar(ArrayList<CalendarDay> newCalendar) { if (mAdapter == null) { mAdapter = new CalendarAdapter(getActivity(), newCalendar); mExpandableListView.setAdapter(mAdapter); } else { mAdapter.refill(newCalendar); } restoreInstanceState(); } And in the adapter: public void refill(ArrayList<CalendarDay> newCalendar) { mCalendar.clear(); mCalendar.addAll(newCalendar); notifyDataSetChanged(); } A: Maybe you could try and remove this line? mFeedListView.setSelectionFromTop(mFirstVisibleItem, mVisibleItemOffset); Edit: You are using this line twice in your code. Edit: In the code in your question you are only refreshing mAdapter and not mEndlsFidAdptr . That one is still assigned a new one. Everytime you assign a new adapter to you ListView it scrolls back to the top. A: So the solution wasn't the logical place where I was looking. Thanks a lot to bbrakenhoff for pointing me in the right direction! My class showFeed() was called from another class called downloadFeed() my scroll position wasn't maintained because downloadFeed() was only loading 5 items when it refreshed, hence even if I maintained the correct scroll position it was not visible. Although it may be a long shot if someone else has this problem - to fix simply create a variable to hold the total size of your scrollable list when the user performs an onClick event. Then when downloadFeed() is called again, there are more items to download instead the default 5. Then the scroll position is able to be maintained as the visible items are now present. I ended up using mFeedListView.setSelectionFromTop(firstVisibleItem, positionOffset)
{ "language": "en", "url": "https://stackoverflow.com/questions/25363372", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Dynamic data on chart (Charts pod) I started to work with Charts pod (swift 4 language) and I'm going to create a very simple app that uses the line chart. In the examples I downloaded from the Charts web page, a list of random entries is created and then they call a method to display everything in the chart in a single shot. There is a more efficient way to put in the graph only one single record and updated the graph dynamically for example like in oscilloscope without redesign the full graph all the times? Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/52303408", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use python pandas to find a specific string in various rows I am trying to do my taxes. I have over 2,000 rows of data in a CSV of orders. I am trying to just count and print the rows that contain "CA" so I know the ones I need to pay sales tax on. I understand I can do this with python using the pandas library. I am stuck trying to get it to work though. Any help is appreciated. A: import pandas as pd d = {'tax_info': ["CA", "CA", "CB", "CD", "CA"]} df = pd.DataFrame(d) taxable_rows = df[ df["tax_info"].str.contains("CA")] print(taxable_rows) Running the code above will yield tax_info 0 CA 1 CA 4 CA A: You can try this code below: import pandas as pd df = pd.read_csv(r'your csv file path') res = df[(df.apply(lambda s: s.eq('CA').any(), axis=1))] print(res)
{ "language": "en", "url": "https://stackoverflow.com/questions/70794940", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: How do I obtain the ASCII code of a character? I have a char variable, declared for example as: char a = 's'; How can I get the ASCII code of this symbol? Thank you. A: a holds the ascii value of 's' (115). Think of a char as just a small integer. If you want it in an integer for whatever reason, just cast it. char a = 's'; int code = a; //or (int)a; A: Use QChar? :) http://doc.trolltech.com/4.6/qchar.html
{ "language": "en", "url": "https://stackoverflow.com/questions/2447760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jquery post and get methods not working on remote server the following jquery code works fine on local server but doesn't work on remote server. FYI remote server is recognizing jquery. I got that working through My Stackoverflow Q Please checkout the problem page at Merry Flowers Admission Page. When I enter banana8@gmail.com as email id (in Parent Info) and press the tab key, all the subsequent form elements should be automatically filled. But it is not doing that here. The following are the network headers from chrome's developer tools for /students/get_parent_info: Request URL:http://www.merryflowers.com/students/get_parent_info Request Method:POST Status Code:200 OK Request Headersview source Accept:*/* Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3 Accept-Encoding:gzip,deflate,sdch Accept-Language:en-US,en;q=0.8 Connection:keep-alive Content-Length:52 Content-Type:application/x-www-form-urlencoded; charset=UTF-8 Cookie:CAKEPHP=b0103aa50047806a7063301569298541 Host:www.merryflowers.com Origin:http://www.merryflowers.com Referer:http://www.merryflowers.com/students/add User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19 X-Requested-With:XMLHttpRequest Form Dataview URL encoded data[MerryParent][email]:banana8@gmail.com Response Headersview source Connection:Keep-Alive Content-Type:text/html; charset=UTF-8 Date:Fri, 20 Apr 2012 18:56:03 GMT Keep-Alive:timeout=5, max=100 P3P:CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM" Server:Apache Transfer-Encoding:chunked X-Powered-By:PHP/5.2.17 network response and preview: **************************************** FYI, I've already verified that there is existing record for banana8@gmail.com. After reading lazerblade's answer, I checked index.php and test.php on www and public_html folders. My root on remote server is /home/aquinto1. I made changes to these files long back. I didn't modify anything here now. Below are my codes: index.php if (!defined('ROOT')) { define('ROOT', DS.'home'.DS.'aquinto1'); //define('ROOT', dirname(dirname(dirname(__FILE__)))); } /** * The actual directory name for the "app". * */ if (!defined('APP_DIR')) { define('APP_DIR','app'); //define('APP_DIR', basename(dirname(dirname(__FILE__)))); } /** * The absolute path to the "cake" directory, WITHOUT a trailing DS. * */ if (!defined('CAKE_CORE_INCLUDE_PATH')) { //define('CAKE_CORE_INCLUDE_PATH', ROOT); define('CAKE_CORE_INCLUDE_PATH', DS.'home'.DS.'aquinto1'); } test.php if (!defined('ROOT')) { define('ROOT', DS.'home'.DS.'aquinto1'); //define('ROOT', dirname(dirname(dirname(__FILE__)))); } /** * The actual directory name for the "app". * */ if (!defined('APP_DIR')) { define('APP_DIR','app'); //define('APP_DIR', basename(dirname(dirname(__FILE__)))); } /** * The absolute path to the "cake" directory, WITHOUT a trailing DS. * */ if (!defined('CAKE_CORE_INCLUDE_PATH')) { //define('CAKE_CORE_INCLUDE_PATH', ROOT); define('CAKE_CORE_INCLUDE_PATH', DS.'home'.DS.'aquinto1'); } <script type="text/javascript"> //var j=jQuery.noConflict(); $(document).ready(function(){ $("#MerryParentEmail").change(function(){ //txt=$("#MerryParentEmail").val(); email_id=$("#MerryParentEmail").serialize(); $.post("/students/get_parent_info",email_id,function(result_str){ result_array=result_str.split('*****'); $("#MerryParentInitial").val(result_array[0]); $("#MerryParentName").val(result_array[1]); $("#MerryParentLandline").val(result_array[2]); $("#MerryParentMobile").val(result_array[3]); $("#MerryParentAddress").val(result_array[4]); $("#MerryParentStateId").val(result_array[5]); state=result_array[5]; txt_str="state_id="+state; $.get("/students/getcities",txt_str,function(result){ $("#MerryParentCityId").html(result).show(); $("#MerryParentCityId").val(result_array[6]); }); $("#MerryParentPostalCode").val(result_array[7]); }); }); $("#MerryParentStateId").change(function(){ state=$(this).val(); txt_str="state_id="+state; $.get("/students/getcities",txt_str,function(result){ $("#MerryParentCityId").html(result).show(); }); }); }); </script> students_controller's get_parent_info func and getcities func: function get_parent_info(){ //$this->layout=false; if (!empty($this->data)){ $merryparent_info=$this->Student->MerryParent->getMerryParents($this->data['MerryParent']['email']); print_r($merryparent_info); echo $merryparent_info['MerryParent']['initial'].'*****'; echo $merryparent_info['MerryParent']['name'].'*****'; echo $merryparent_info['MerryParent']['landline'].'*****'; echo $merryparent_info['MerryParent']['mobile'].'*****'; echo $merryparent_info['MerryParent']['address'].'*****'; echo $merryparent_info['MerryParent']['state_id'].'*****'; echo $merryparent_info['MerryParent']['city_id'].'*****'; echo $merryparent_info['MerryParent']['postal_code'].'*****'; } } function getcities(){ $this->data['MerryParent']['state_id']=$_GET['state_id']; if (!empty($this->data['MerryParent']['state_id'])){ $cities = $this->Student->MerryParent->City->getCities($this->data['MerryParent']['state_id']); //print_r($cities); foreach ($cities as $k=>$v){ echo '<option value="'.$k.'">'.$v.'</option>'; } /* foreach($cities as $optionValue){ echo '<option>' . $optionValue . '</option>'; }*/ }else{ $this->Session->setFlash('You didn\'t select a state!'); } } A: By default, you can't make XHR requests across different domains. You'll need to dynamically generate script tags and use JSONP. Here's an article that seems to cover how to do it: http://cjihrig.com/blog/remote-ajax-calls-using-jsonp/ Also, it's important to note that this can cause security issues. A: I believe the issue here has a lot to do with the differences between your localhost file structure and root path location and your remote server file structure and root path location. First, your url, even for AJAX calls, shouldn't be pathed from root. Your public folder (www, public_html) should redirect traffic into your framework, so you maintain SEO-friendly urls and a more secure site, in the event that PHP should somehow fail. That being said, your AJAX url should still be www.merryflowers.com/students/get_parent_info, where students is your controller and get_parent_info is your function in your students controller. If it's working locally, then it should work remotely, but it needs the correct pathway to get where it needs to go. I'm guessing your local setup includes an htdocs folder, whereas your remote server, as you stated, includes www and public_html folders (possibly simlinked). Start by checking your code for pathway reference differences - pathways locally that don't exist remotely, differences in folder structure, etc... Then go through your config, bootstrap, and any other files that define pathways and alter them accordingly. I'd also retag your question with MVC, PHP, Apache (if you're using Apache, or ISAPI, or whatever), htaccess, and path. A: Ok, the problem was with the code in MerryParent Model. There was nothing wrong in my jquery code. In MerryParent model, function getMerryParents($field_value){ if (is_int($field_value)) $conditions=array('merryParent.id'=>$field_value); else $conditions=array('merryParent.email'=>$field_value); //debug($conditions); $merryparent_info=$this->find('first',array( 'conditions'=>$conditions, 'recursive'=>-1 //fetches merry_parents table data only not the associated data )); debug($merryparent_info); return $merryparent_info; } I changed merryParent.id to MerryParent.id and merryParent.email to MerryParent.email and it works now on the remote server. :) A: This worked for me.. i faced same problem but get it solved by following two steps 1). while referring jquery and other js files I changed to IP address instead relative path 2) in all http get requests i replaced localhost with correct IP address. Thanks Lazerblade. You helped me a lot. Mukharjee
{ "language": "en", "url": "https://stackoverflow.com/questions/10214383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Edit HTML in text edit field in C# I have a text string with basic HTML tags like <b> <i> <ul> <ol> tags. Now I want to display it parsed in a editable text box and allow user to edit in a WYSIWYG way. How can I do it in C#? Right now I have a RichTextBox but it uses RTF tags under the hood not HTML, so instead of formated text I see html code. A: The easiest solution is using a WebBrowser control, showing editable div: private void Form1_Load(object sender, EventArgs e) { webBrowser1.DocumentText = @" <div contenteditable=""true""> This is a sample: <ul> <li>test</li> <li><b>test</b></li> <li><a href=""https://stackoverflow.com"">stackoverflow</a></li> </ul> </ div >"; } You can also have some toolbar buttons for setting text bold, italic, or insert <ul> or ol and other commands. For example, the following command, makes the selection bold: webBrowser1.Document.ExecCommand("Bold", false, null); Or the following command inserts ordered list: webBrowser1.Document.ExecCommand("InsertOrderedList", false, null); You may also want to take a look at following post: Windows Forms HTML Editor
{ "language": "en", "url": "https://stackoverflow.com/questions/32444953", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: cast function is extremely memory consuming, how to handle it? I have a table looks like: date item_id store_id sale_num 1/1/15 33 1 10 1/1/15 33 2 12 1/1/15 33 3 15 1/1/15 44 1 54 1/1/15 44 3 66 1/2/15 33 1 14 .... I want to cast the table, in order to put store_id into multiple columns, and value is the sale_num. The table should be like: date item_id store1 store2 store3 1/1/15 33 10 12 15 1/1/15 44 54 NA 66 1/2/15 33 14 NA NA ...... When I do this using cast function in a small scale, 1000 rows in original table, there is no problem. However, the original table has 38,000,000 rows and comsumes 1.5 GB memory in R. When I use cast function, the function cost around 34 GB memory, and it runs endlessly. What is the problem of it? Is there any alternative way? A: We can use the dcast from data.table. It should be more efficient than the cast from reshape. We convert the 'data.frame' to 'data.table' (setDT(df1)) and then use dcast. library(data.table) dcast(setDT(df1), date+item_id~ paste0("store", store_id), value.var="sale_num") # date item_id store1 store2 store3 #1: 1/1/15 33 10 12 15 #2: 1/1/15 44 54 NA 66 #3: 1/2/15 33 14 NA NA
{ "language": "en", "url": "https://stackoverflow.com/questions/36075880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: javascript - show match item onkeyup this one already works, but I have a problem on changing the content of the array. I wanted to query on my database and use that data as an element of my array. how can I do that guys? <script type="text/javascript" language="javascript"> function ShowMe(obj) { var lbl = document.getElementById('divContent'); var myArray = new Array(); myArray[0] = "Football"; myArray[1] = "Baseball"; myArray[2] = "Cricket"; myArray[3] = "Fast"; var s2 = obj.value.toLowerCase(); for (i = 0; i < myArray.length; i++) { if (myArray[i].toLowerCase().indexOf(s2) != -1) { lbl.innerHTML = myArray[i]; } } } </script> <div> <h1>JS Test</h1> <input id="txtInput" onkeyup="javascript:ShowMe(this)" /> <div id="divContent"> </div> the main problem is... how can I pass my array into the script? let say I already have $myquery_array; A: You should try reading about Ajax A: Do you want this? http://jqueryui.com/demos/autocomplete/
{ "language": "en", "url": "https://stackoverflow.com/questions/12746524", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sorting associative array with variable keys in PHP i have the following associative array word => count where word is an english word ('more', 'creme', 'car' and so on), while count is the number of times that word appeared in a given string. I want to sort by count. Thx. Ps. I tried usort but didn't work A: <?php $fruits = array("d" => 4, "a" => 3, "b" => 2, "c" => 1); asort($fruits, SORT_NUMERIC); foreach ($fruits as $key => $val) { echo "$key = $val\n"; } ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7952744", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dismiss current modal view controller curl effect and open MFMailComposeViewController I have a menu loaded from a tableview using the modal curl page effect. So once the user hit's a certain button, this effect will show up. When the user hits the contact us button, an email compose will show up, but since it's a modal curl effect, the send and cancel button are hidden. I am pretty aware that apple will reject the app if any size changing has been done, so i am looking for an alternative : close current modal effect, and push a new MFMailComposeView. How can i do that? EDIT : CODE SO FAR - (IBAction)sendEmail:(id)sender { // Email Subject // NSString *emailTitle = @"Test Email"; // Email Content // NSString *messageBody = @"iOS programming is so fun!"; // To address NSArray *toRecipents = [NSArray arrayWithObject:@"eli@gmail.com"]; MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init]; mc.mailComposeDelegate = self; [mc setSubject:@"Email"]; [mc setMessageBody:message.text isHTML:NO]; [mc setToRecipients:toRecipents]; // self.view.superview.bounds = CGRectMake(0, 0, self.view.bounds.size.width, 200); // Present mail view controller on screen [self presentViewController:mc animated:YES completion:NULL]; //[self dismissViewControllerAnimated:YES completion:nil]; } A: I figured it out , it's a bit a handful but its worth it. First of all, at the ViewController where the action of sending an email should be called, put an NSNotification, like this : [self dismissViewControllerAnimated:YES completion:^{ [[NSNotificationCenter defaultCenter] postNotificationName:@"email" object:nil]; }]; Later on, when that view disappears, an original view controller will show up, since it was called through a modal view controller, in that one put : -(void)createEmail{ MFMailComposeViewController * mc = [[MFMailComposeViewController alloc] init]; NSArray *toRecipents = [NSArray arrayWithObject:@"elias@gmail.com"]; mc.mailComposeDelegate = self; [mc setSubject:_emailSubject]; [mc setMessageBody:_emailMessage isHTML:NO]; [mc setToRecipients:toRecipents]; [self presentViewController:mc animated:YES completion:nil]; } And, in the viewDidload, add the following line : [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(createEmail) name:@"email" object:nil]; That way, we are telling the original view controller, in her did load phase, to listen for a notification called email, and when we call it in the Email view controller, the app will know that a triggered notification has been fired, and will search for her following action, which is the delegate of the MFMailComposeViewController.That way, for any future developer, you will accomplish the designated target
{ "language": "en", "url": "https://stackoverflow.com/questions/23333688", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to differentiate application code from system code in dalvik In android dalvik, at every function call site, I want to check whether the caller is application code and the callee is system code. I know a way to do this from an article: Vetting Undesirable Behaviors in Android Apps with Permission Use Analysis in the end of chapter 3.1.1. Fortunately, we find an efficient way to differentiate application code from system code by checking their class loader, because system code is loaded by a distinct class loader in Dalvik to ensure the VM integrity” I add this in the dalvik code dalvik/vm/mterp/out/InterpC-portable.cpp: ALOGD("ClassLoader:%s", methodToCall->clazz->classLoader->clazz->descriptor); but the result is always : ClassLoader:Ldalvik/system/PathClassLoader; It seems that the classloaders are the same. Is there something I did wrong? Any suggestions or resources I can learn from are welcome!
{ "language": "en", "url": "https://stackoverflow.com/questions/29114602", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C# Delimiter not showing I'm trying to concatenate with delimiter the value from datagridview. Unfortunately, I'm lost using string join. Thanks, if someone can correct my mistake. private void Button_Click(object sender, EventArgs e) { string message = string.Empty; foreach (DataGridViewRow row in dataGridView1.Rows) { bool isSelected = Convert.ToBoolean(row.Cells["Column1"].Value); if (isSelected) { message += String.Join(", ", row.Cells["pk_pspatitem"].Value.ToString()); } } MessageBox.Show(message); } A: Or you can query it with LINQ: string message = String.Join(", ", from DataGridViewRow r in dataGridView1.Rows where true.Equals(r.Cells["Column1"].Value) select r.Cells["pk_pspatitem"].Value); With pattern matching in C# 7.0 (comes with Visual Studio 2017) string message = String.Join(", ", from DataGridViewRow r in dataGridView1.Rows where r.Cells["Column1"].Value is true select r.Cells["pk_pspatitem"].Value); A: The delimiter will only show to separate multiple items. If there is only one then it will not show. Try collecting all the values and then using the String.Join with the delimiter. List<string> values = new List<string>(); foreach (DataGridViewRow row in dataGridView1.Rows) { bool isSelected = Convert.ToBoolean(row.Cells["Column1"].Value); if (isSelected) { values.Add(row.Cells["pk_pspatitem"].Value.ToString()); } } string message = String.Join(", ", values); MessageBox.Show(message); A: String.Join is used to concatenate an array. You're just adding a string to another string. Use the standard concatenation operator, +. message += ", " + row.Cells["pk_pspatitem"].Value.ToString(); Consider also that this will cause your message to start with a comma, which can be fixed like this: MessageBox.Show(message.Substring(2)); Of course, you could convert the rows into an array and then use String.Join, but I don't see any value in that.
{ "language": "en", "url": "https://stackoverflow.com/questions/44642000", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: CSS: How to prevent div from overlapping parent height or parent border I am new to CSS and hope someone can help me with this. I am trying to create a simple progress bar (for later use with JS) that contains three separate color blocks (red, yellow, green). So far I have the below which works in general but the height of the color blocks (class "progressBar") is always overlapping the parent div (class="progressWrapper") by several pixels. What I would like to have is one bar where the color blocks just fill out its background but don't overlap it or its border and a visible border around the parent div. In my code the parent div doesn't seem to control the child divs. Can someone tell me what I am doing wrong here ? My CSS (relevant parts): .bgGreen { background-color: green; } .bgRed { background-color: red; } .bgYellow { background-color: yellow; } .progressWrapper { border: 1px solid #ccc; height: 16px; line-height: 16px; padding: 0; } .progressBar { height: 100%; line-height: 100%; margin: 0; max-height: 100%; } My HTML: <div class="col-12 progressWrapper"> <div class="col-4 progressBar bgRed"></div> <div class="col-4 progressBar bgYellow"></div> <div class="col-4 progressBar bgGreen"></div> </div> Update: .col-4 { width: 33.33%; } .col-12 { width: 100%; } [class*="col-"] { float: left; padding: 15px; } Many thanks in advance, Mike A: This got resolved by add overflow: hidden; - thanks to Akshay ! A: Check it out here Calculate the height of .progressbar by using the CSS calc() function, more information about this here. height: calc(56px / 3); /* Height of wrapper devided by number of divs */
{ "language": "en", "url": "https://stackoverflow.com/questions/30830998", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: why some asset files are too many redirects in https? htaccess file: DirectoryIndex index.php #Options -Indexes # enable apache rewrite engine RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php [QSA] I have used this htaccess in root directory. after that all requests are handle index.php. here, some js/jpg files are redirects too many times with https url (https://example.com or https://www.example.com). but in http it works fine. why this was happen? anybody help to solve this problem. modernizer.js file redirects like this, (test it from gtmatrix tool result and also developer tools) https://www.example.com/assets/js/modernizer.js https://example.com/assets/js/modernizer.js https://example.com/assets/js/modernizer.js actually i cannot understand what happens. hostgator linux hosting is used for this. it works fine in http (not https). suppose if i open in new tab this file then https://www.example.com/assets/js/modernizer.js url is redirect to https://example.com/assets/js/modernizer.js A: Finally, I try One solution to solve this issue (this is not exact solution i try only to solve cached file redirects), actually problem occurs due to browser cache memory not in above htaccess. (Preciously I had try in both incognito and cache cleared browser but it still these redirects happens in some files) so i try to change name of these files in above screen shoot then reload it after that this problem is solved. my guess is this problem is happens due to cache. because previously we used leverage browser caching in htaccess after that this was removed due to solve the problem. above htaccess is worked fine now.
{ "language": "en", "url": "https://stackoverflow.com/questions/64463140", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: tatelerik for asp net mvc requires nuget package manager I downloaded telerik and installed it , i got the visual studio 2013 already installed on my PC . now when i click on new project -> c# -> web -> "telerik ASP.NET MVC Application" opotion"talerik for asp net mvc requires nuget package manager" A: I installed the following NuGet package Manager for visual studio 2013 - which solved my problem -hopefully someone will find it helpfull . Note : for visual studio 2010,2012 there are links available in the related page https://visualstudiogallery.msdn.microsoft.com/4ec1526c-4a8c-4a84-b702-b21a8f5293ca
{ "language": "en", "url": "https://stackoverflow.com/questions/31100680", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Detect when upload finishes I am uploading an image file to a server in android. I want to know when the upload completes.Is there any way to know that. if there any state in android that automatically calls when the upload completes. OR how to check this state. A: If you're using HttpClient.execute(), it's a synchronous method - it returns once the upload is done. EDIT: there's no asynchronous HTTP client on Android, as far as I know. For non-blocking upload, use HttpClient is a worker thread, and use Handler.post(Runnable) to process the completion back in the main thread. EDIT2: the async HTTP looks like this: final Handler Ha = new Handler(); //Used to post the results back to the main thread new Thread(new Runnable(){ public void run() { HttpPost pr = new HttpPost(MyURL); pr.setEntity(MyUploadData); //More request setup... HttpResponse Resp = new DefaultHttpClient().execute(pr); //Process response here... detect errors, for one thing Ha.post(new Runnable(){ public void run() { //This executes back in the main thread! } }); } }).start();
{ "language": "en", "url": "https://stackoverflow.com/questions/5719919", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: vue-router route param to component prop? I thought this would work: { path: '/course/:id', component: Course.extend({ props: { course: params.id } }) }, Sadly, it's not that simple (it's not id either). How do I do this? (I just took a course on vue, can't believe I can't remember this) A: As it is in the docs, you have to make props option true in the routes, see below code to understand it: const User = { props: ['id'], template: '<div>User {{ id }}</div>' } const router = new VueRouter({ routes: [ { path: '/user/:id', component: User, props: true } ] })
{ "language": "en", "url": "https://stackoverflow.com/questions/42012063", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Distribute Swift app without Swift framework I read in the blog post about the Swift 5.0 release that [...] applications written in Swift no longer need to be distributed with the Swift runtime libraries, reducing download size. When I tried to archive and export an app it still had the framework. macOS Deployment Target set to macOS 10.14, Swift Language Version is Swift 5. How can I export a Swift 5 app without bundling the Swift framework? Edit: I created a Cocoa app using the wizard, and exported it. The export contains the Frameworks folder with the Swift libraries. I was, however, able to delete the Frameworks folder. The app still runs, and the bundle size went from ~11 MB to ~83kB.
{ "language": "en", "url": "https://stackoverflow.com/questions/55664077", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: I want to load images from specific folder from internal storage, how to load images? as well as video too public class ImageAdapter extends BaseAdapter { private File currentDir; String SCAN_PATH; File allFiles ; private Context context; public Integer[] images={ //I want to load images here }; public ImageAdapter(Context c){ context = c; } @Override public int getCount() { return images.length; } @Override public Object getItem(int position) { return images[position]; } @Override public long getItemId(int position) { return 0; } I want to load Images. I can simply add images using ID's but I want to load images from Internal/sd card storage. I want to know how to add images A: Try loading images into imageview as bitmap try { File f=new File(filepath, "imagename.jpg"); // internal or external storage path Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f)); ImageView img=(ImageView)findViewById(R.id.imgPicker); img.setImageBitmap(b); } catch (FileNotFoundException e) { e.printStackTrace(); } Hope this may work!
{ "language": "en", "url": "https://stackoverflow.com/questions/46743544", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How to make a loading animation in Console Application written in JavaScript or NodeJs? How to make a loading animation in Console Application written in JavaScript or NodeJs? Example animation or other animation. 1. -- 2. \ 3. | 4. / 5. -- A: The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds) at each 250 ms the value in the p array is printed on the console. The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds. setInterval is used as a loop here. Using the clearInterval, the loop is breaked after 5000 ms using setTimeout. const P = ['\\', '|', '/', '-']; let x = 0; const loader = setInterval(() => { process.stdout.write(`\r${P[x++]}`); x %= P.length; }, 250); setTimeout(() => { clearInterval(loader); }, 5000); A: Not really possible in browser console. In Node.js: var twirlTimer = (function() { var P = ["\\", "|", "/", "-"]; var x = 0; return setInterval(function() { process.stdout.write("\r" + P[x++]); x &= 3; }, 250); })(); A: You can do it in the browser console as well: var loading = (function() { var h = ['|', '/', '-', '\\']; var i = 0; return setInterval(() => { i = (i > 3) ? 0 : i; console.clear(); console.log(h[i]); i++; }, 300); })(); // clearInterval(loading) to stop it. A: You can try this package: https://github.com/ErAz7/Termination it supports * *promise based tranition *easing transition functions *looped transition *frame rate control *playback speed control *canvas size options *colors and some other useful features to create animations on terminal like a piece of cake!
{ "language": "en", "url": "https://stackoverflow.com/questions/34848505", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: Writing own phone gap plugin for iOS step by step It been a day scratching my head for this setup. I m feeling writing a plugin code is much easier than the setup. I followed the below steps to to write a simple phone gap plugin for ios. But unfortunately, unable to locate where I missed. Kindly do printout the missing/confusing/erroneous part of the code. PhoneGap Setup: 1) Closed Xcode. [ i have Xcode 4.3.3 ] 2) Downloaded latest phone gap. version 2.0 3) in phonegap-phonegap-2dbbdab-1 directory, install Cordova-2.0.0.pkg 4) Ran the following code: $ ./path/to/cordova-ios/bin/create /path/to/my_new_cordova_project com.example.cordova_project_name CordovaProjectName Followed: http://docs.phonegap.com/en/2.0.0/guide_command-line_index.md.html#Command-Line%20Usage 5) Opened Xcode project. 6) created HelloPlugin.js file under www directory that contains.. var HelloPlugin = { callNativeFunction: function (success, fail, resultType) { return Cordova.exec(success, fail, "com.tricedesigns.HelloPlugin", "nativeFunction", [resultType]); } }; 7) IN PLUGIN DIRECTORY HelloPlugin.h contains: #import "CDVPlugin.h" @interface HelloPlugin : CDVPlugin { NSString* callbackID; } @property (nonatomic, copy) NSString* callbackID; - (void) nativeFunction:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options; @end HelloPlugin.m contains: #import "HelloPlugin.h" @implementation HelloPlugin @synthesize callbackID; - (void) nativeFunction:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options { //get the callback id NSString *callbackId = [arguments pop]; NSLog(@"Hello, this i s a native function called from PhoneGap/Cordova!"); NSString *resultType = [arguments objectAtIndex:0]; CDVPluginResult *result; if ( [resultType isEqualToString:@"success"] ) { result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString: @"Success :)"]; [self writeJavascript:[result toSuccessCallbackString:callbackId]]; } else { result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString: @"Error :("]; [self writeJavascript:[result toErrorCallbackString:callbackId]]; } } @end in Cordova.plist: Have added com.tricedesigns.HelloPlugin, HelloPlugin as key/value and type is string. in index.html: <script type="text/javascript" charset="utf-8" src="HelloPlugin.js"></script> <script type="text/javascript"> function callNativePlugin( returnSuccess ) { alert("Inside callNativePlugin"); HelloPlugin.callNativeFunction( nativePluginResultHandler, nativePluginErrorHandler, returnSuccess ); alert("End of Hello PLugin"); } function nativePluginResultHandler (result) { alert("SUCCESS: \r\n"+result ); } function nativePluginErrorHandler (error) { alert("ERROR: \r\n"+error ); } </script> Now when i click the button, the native function is not invoked. How to move forward? A: I wrote a tutorial with step-by-step instructions on how to write a PhoneGap plugin for iOS. It might be helpful for you. Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/11760236", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: List of commits relative to pushes (remote) I'd like to get a list of pushes relative to some remote branch, and if that's possible, I'd like to be able to list the commits relative to any specific push operation. I've tried searching all over but to no avail so far. A: The "push" is just a synching between two git repositories. In a typical case its the synching between the copy of the git repo on your local machine to a central repo. AFAIK the push is not really recorded as an artifact in the git meta data. So you cannot refer a push by any identifier. So to get to your question, you will be able to find differences between two different commits, or two different states of the same branch assuming it has not been pushed/synced. Here are a few commands that will help you do that: git log --oneline --name-only develop..origin/develop This will give you a list of all commits between the local develop branch and the remote develop branch, this will also give you list of all the files changed in that commit. If you dont want file names just remove the --name-only arg. And if you want to visualize, you can use git log --oneline --name-only --graph develop..origin/develop. THe develop..origin/develop``` can be tags, commits or branches. In git speak ```tree-ish. You can potentially tag pushes and then figure out the diff between tags.
{ "language": "en", "url": "https://stackoverflow.com/questions/56628711", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Collecting edges in a set from shortestPath iGraph Object I am trying to collect all the unique edges from object created from shortest_paths iGraph function. > data<-as.matrix(data) > data Q W E R T Y U I Q 0 4 7 5 0 4 0 0 W 2 0 5 7 3 2 4 9 E 2 4 0 9 2 2 7 2 R 2 2 2 0 6 0 5 8 T 0 8 8 5 0 5 9 0 Y 4 7 2 6 0 0 5 7 U 0 0 0 0 2 0 0 9 I 2 0 6 7 0 2 0 0 network<-graph.adjacency(adjmatrix = data,weighted = TRUE, mode="directed" , diag = FALSE ) shortestPath<-shortest_paths(graph = network, from = 1, to = 1:8,mode = "out", output = "epath") > shortestPaths$epath [[1]] + 0/41 edges from b068eeb (vertex names): [[2]] + 1/41 edge from b068eeb (vertex names): [1] Q->W [[3]] + 2/41 edges from b068eeb (vertex names): [1] Q->Y Y->E [[4]] + 1/41 edge from b068eeb (vertex names): [1] Q->R [[5]] + 2/41 edges from b068eeb (vertex names): [1] Q->W W->T [[6]] + 1/41 edge from b068eeb (vertex names): [1] Q->Y [[7]] + 2/41 edges from b068eeb (vertex names): [1] Q->W W->U [[8]] + 3/41 edges from b068eeb (vertex names): [1] Q->Y Y->E E->I I want to calculate the number of unique edges in the shortest path so that i can compute the density of the graph defined as - Density = (Number of unique edges on shortest paths)/ (total number of edges) This needs to be done for all pair shortest path in the graph. How can i Count the number of unique edges that are on shortest path in an all pair setting. Thanks A: You can unlist, find the unique edges and take the length of the resulting vector: length(unique(unlist(shortestPath$epath)))
{ "language": "en", "url": "https://stackoverflow.com/questions/48919340", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: bash script modify to take parameter from echo command I have this small bash script(sendmail.sh) to send emails using mandril which works super when used like this ./sendmail.sh "my@email.com" "Email Subject" "Email body". Thanks to black @ LET However I want this script to take its email body from echo command like the linux mail commands works . echo "email body" | mail -s "email subject" email@any.com When I use the below script with this command echo "email body" |./sendmail.sh "my@email.com" "Email Subject" it prints the error specified in else block(since only 2 arguments are given but 3 needed) /sendmail.sh requires 3 arguments - to address, subject, content Example: ././sendmail.sh "to-address@mail-address.com" "test" "hello this is a test message" Surprised to see why echo commands output is not being taken as input for $3 argument in the script. #!/bin/bash #created by black @ LET #MIT license, please give credit if you use this for your own projects #depends on curl key="" #your maildrill API key from_email="" #who is sending the email reply_to="$from_email" #reply email address from_name="curl sender" #from name if [ $# -eq 3 ]; then msg='{ "async": false, "key": "'$key'", "message": { "from_email": "'$from_email'", "from_name": "'$from_name'", "headers": { "Reply-To": "'$reply_to'" }, "return_path_domain": null, "subject": "'$2'", "text": "'$3'", "to": [ { "email": "'$1'", "type": "to" } ] } }' results=$(curl -A 'Mandrill-Curl/1.0' -d "$msg" 'https://mandrillapp.com/api/1.0/messages/send.json' -s 2>&1); echo "$results" | grep "sent" -q; if [ $? -ne 0 ]; then echo "An error occured: $results"; exit 2; fi else echo "$0 requires 3 arguments - to address, subject, content"; echo "Example: ./$0 \"to-address@mail-address.com\" \"test\" \"hello this is a test message\"" exit 1; fi A: Why is that surprising? You are mixing arguments and standard input, which are fundamentally completely different. However, it's not hard to accommodate this requirement. case $# in 3) text="$3" ;; 2) text=$(cat) ;; esac : .... do stuff with "$text" Your script has slightly sloppy indentation and quoting, so here is a somewhat refactored version. key="" #your maildrill API key from_email="" #who is sending the email from_name="curl sender" #from name case $# in 3) text="$3";; 2) text="$(cat)";; *) echo "$0: oops! Need 2 or 3 arguments -- aborting" >&2; exit 1 ;; esac msg='{ "async": false, "key": "'"$key"'", "message": { "from_email": "'"$from_email"'", "from_name": "'"$from_name"'", "return_path_domain": null, "subject": "'"$2"'", "text": "'"$text"'", "to": [ { "email": "'"$1"'", "type": "to" } ] } }' result=$(curl -A 'Mandrill-Curl/1.0' -d "$msg" 'https://mandrillapp.com/api/1.0/messages/send.json' -s 2>&1) case $results in *"sent"*) exit 0;; *) echo "$0: error: $results" >&2; exit 2;; esac Notice in particular how any user-supplied string absolutely must be within double quotes. (I took out Reply-To: because it's completely superfluous when it's equal to the From: header.)
{ "language": "en", "url": "https://stackoverflow.com/questions/28479168", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get a List of Drive Files Into a Google Sheet var folder = DriveApp.getFolderById('1_gA4D7dfybJ60IdfgsnqdfdsgVoo9D76fgsdgf9cqmAnJI7g7'); var contents = folder.getFiles(); var file; var name; var sheet = SpreadsheetApp.getActiveSheet(); var date; var size; sheet.clear(); sheet.appendRow(["Nome", "Data", "Dimensione"]); while(contents.hasNext()) { file = contents.next(); name = file.getName(); date = file.getDateCreated(); size = file.getSize(); id = file.getUrl(); data = [name, date, size,id] sheet.appendRow(data); } }; Every time all the data is cleared, after that the data is added from the starting. sheet.clear();sheet.appendRow(["Nome", "Data", "Dimensione"]); Is there any way to check the data? if the same data present Already then the function does not work on the row. If a new record is added, it should also be added, but the function does not start again from one. If I have 20 PDFs in my folder, and add one more PDF in folder, then add the function 21 pdf and do not run the function from the beginning. A: Explanation: The logic behind the following script is the following: * *We get all the URLs of the files that are currently in column D of the sheet. These are the URLs of the files that have been recorder so far. We can safely assume that the URLs are always unique: const aURLs = sheet.getRange('D2:D'+sheet.getLastRow()).getValues().flat(); *The second step is to iterate through the files as the original script would do and check if the URL of a file is in aURLs. If the file URL is not in aURLs or in other words in column D, then add it to the newFiles array: if(!uNames.includes(name)){ newFiles.push(data); } *After we checked all the files, we can add, after the last row of sheet, only the new files: sheet.getRange(sheet.getLastRow()+1,1,newFiles.length,newFiles[0].length).setValues(newFiles); Solution: Manually add the headers in the file for the first time only: and then execute the script every next time: function myFunction() { const folder = DriveApp.getFolderById('1_gA4D7dfybJ60IdfgsnqdfdsgVoo9D76fgsdgf9cqmAnJI7g7'); const contents = folder.getFiles(); const sheet = SpreadsheetApp.getActiveSheet(); const aURLs = sheet.getRange('D2:D'+sheet.getLastRow()).getValues().flat(); const newFiles = []; while(contents.hasNext()) { let file = contents.next(); let name = file.getName(); let date = file.getDateCreated(); let size = file.getSize(); let id = file.getUrl(); let data = [name, date, size,id] if(!aURLs.includes(id)){ newFiles.push(data); } } sheet.getRange(sheet.getLastRow()+1,1,newFiles.length,newFiles[0].length).setValues(newFiles); }
{ "language": "en", "url": "https://stackoverflow.com/questions/64365601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Spring LDAP + @Entry + base attribute - not working I have the following directory structure and am using ODM with Spring LDAP (v 2.3.1.RELEASE). The below is the directory structure am dealing with. dc=example,dc=com dc=studentBase,dc=example,dc=com I declared the base for the ldap context source in the config.xml as follows: <ldap:context-source id="ldapContextSource" url="ldap://ldaphost:389" username="cn=ldaptestadmin,cn=Administrators,cn=config" password="abcxyz" base="dc=studentBase,dc=example,dc=com"/> <ldap:ldap-template id="ldapTemplate" context-source- ref="ldapContextSource"/> To explain the context of the problem, here are the details: I have two organizational units under studentBase as follows: ou=groups,dc=studentBase,dc=example,dc=com ou=people,dc=studentBase,dc=example,dc=com Each entry inside the ou=people is as follows: objectclass: inetorgperson (structural) objectclass: organizationalPerson (structural) objectclass: person (structural) objectclass: top (abstract) cn: Test Name sn: Test givenName: TestName uid: test1234 userPassword: <SSHA hashed password> I created a bean annotated with @Entry as follows: @Entry(objectClasses = {"inetOrgPerson", "organizationalPerson", "person", "top" }, base = "ou=people") public class Student { @Id private Name dn; ... ... ... } Now when I try create the student entry inside the LDAP like below Student objStudent = new Student(); String dn = "uid=testUserName"; Name dnName = new LdapName(dn); objStudent.setDn(dnName); ldapTemplate.create(objStudent); it is not getting created under the ou=people but instead getting created in the base dn which is (dc=studentBase,dc=example,dc=com) as mentioned in the config.xml. Per Entry javadocs, it says for the base attribute as follows : The base DN of this entry. If specified, this will be prepended to all calculated distinguished names for entries of the annotated class. Doesn't it mean it should prepend ou=people for the @Id field of the Student?? However, in the above code, if I explicitly set the ou=person for the dn attribute, it is getting created under ou=person, no matter if I have the base attribute in @Entry or not. String dn = "uid=testUserName,ou=person"; Name dnName = new LdapName(dn); Am I not using the "base" attribute of @Entry annotation in the right perspective? Or can someone explain what am getting wrong here? Or is this used along with @DnAttribute? Thanks. A: I have seen the same issue. However, I suggest this answer : https://stackoverflow.com/a/25658026/6157415 The "@Entry base=" parameter is used by LdapRepository not by LdapTemplate.
{ "language": "en", "url": "https://stackoverflow.com/questions/43792804", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How does Mercurial stack up against GIT and SVN? With Phil Haack and others recently tweeting about CodePlex's move to support Mercurial as a DVCS, I thought it might be worth a look. As someone who currently uses SVN for personal projects and TFS at The Office, how does Mercurial compare in terms of usability, features and what are some of the better Mercurial hosting services available? A: Compared to SVN, for which I recently worked with again after quite awhile, Mercurial is amazing. It gave me a feeling of "Why would anyone use SVN anymore". SVN is pretty good, but Mercurial really does just work better. For personal projects I would switch without a doubt to a DVCS. It does everything SVN does but better, and much faster. The "learning curve" is just understanding some terminology. In reality the difference between SVN and a DVCS is that everyone has a full working repository on their system. If you decide to have a "master server", it is exactly the same as what you have, except it is setup to continually serve over a network. To sync these all you do is send/receive(push/pull) the changes between these repositories. A: About comparing Mercurial with Git - see this SO question: Git and Mercurial - Compare and Contrast (and my long answer there). About comparing Mercurial with svn - see this SO question: For home projects, can Mercurial or Git (or other DVCS) provide more advantages over Subversion? (theoretically this question is limited in range, though; I wrote about Git vs Subversion in my answer). A: As far as comparing to Git, Google recently published an interesting comparison of Git and Mercurial based on their evaluation: http://code.google.com/p/support/wiki/DVCSAnalysis A: One thing not mentioned in the Google comparison was that Git appears to be much faster. Mercurial seems fast enough (with small projects at least) but Git is simply lightning-fast no matter what size the project. A: It's probably just me, but I have been using Mercurial for six months, after several years of using SVN exclusively, and for some reason it just doesn't fit my mental model as well. I know exactly what I'm doing in SVN, and if something goes wrong, I pretty much always know how to fix it. Conceptually I have no problem with Mercurial - love that I have a local copy of the repository, for example - but in practise I am always losing things. I think it might be because a merge in SVN is quite a big deal, whereas in Hg it's the normal way of things. I want more control over my merges. In SVN it's always clear which changeset precedes which, but Mercurial seems to lack this. Even TortoiseHg, which is quite nice visually, doesn't seem to offer enough opportunities to see exactly what's being merged. A: SVN has lots of support by 3rd party tools including IDE and bug tracking systems etc including the rather nice TortoiseSVN. Most developers have used SVN in the past, so getting new developers up to speed on your team is quicker with SVN. How important this sort of thing is to you, only you can decide.
{ "language": "en", "url": "https://stackoverflow.com/questions/2126400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: PHP - deciding a function to fire without condition I have developed a new technique for my future programs to decide which function is to be fired without if/else statements. It is to create an associative array of functions and call them by a function according to argument given. I think actual representation will be better. $_functions = array( "names" => function() { .... }, "orders" => function() { .... } ); function doLoad($toLoad) { global $_functions; $_functions[$toLoad](); } Now, a user has to write only: doLoad("names"); wherever they want to print out names. Question: I will be creating a script and it will be distributed among other fellas to use it their way. Is it better to do it like this way for my script? Is there any drawbacks of this technique? A: I don't really understand what you are looking for, but I would have done it this way, for more readability. It may also be more efficient : function doLoadNames() { } function doLoadOther() { } function doLoad($toLoad) { $functionName = 'doLoad'.ucfirst($toLoad); if (function_exists($functionName)) { $functionName(); return true; } return false; } A: all you need is a function called call_user_func or call_user_func_array, manuals are here call_user_func, call_user_func_array
{ "language": "en", "url": "https://stackoverflow.com/questions/18416690", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: .htaccess redirect all but not two I'm trying to redirect like this using .htaccess: * -> index.html /affiliate -> affiliate.html /ref/* -> ref.html But the problem is, that all links are redirected to index, how I can exclude several links from this rule? I have this code for now: <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L] </IfModule> A: With your shown samples/attempts please try following htaccess rules file. Please make sure to clear your browser cache before testing your URLs. RewriteEngine ON ##Rules for uris which starts from affiliate rewrite to affiliate.html here.. RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^affiliate/?$ affiliate.html [QSA,NC,L] ##Rules for uris which starts from ref rewrite it to ref.html here.. RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^ref ref.html [QSA,NC,L] ##Rules for rest of the non-existing pages to rewrite to index.html here... RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^ index.html [L] A: Have your rules like this instead: Options -MultiViews DirectoryIndex index.html RewriteEngine On # Prevent further processing if request maps to a static resource RewriteRule ^((index|affiliate|ref)\.html)?$ - [L] RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule . - [L] # /affiliate -> affiliate.html RewriteRule ^affiliate$ affiliate.html [L] # /ref/* -> ref.html RewriteRule ^ref/ ref.html [L] # * -> index.html RewriteRule . index.html [L] You do not need the RewriteBase directive here. (Or the <IfModule> wrapper.)
{ "language": "en", "url": "https://stackoverflow.com/questions/70879080", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: raw bitmap data to jpeg or png C++ I have bytearray where every three bytes describes 1 pixel (RGB). The task is to convert it to jpeg or png. Actually, I am using Zint (open source lib for generating barcodes) that uses libpng to generate image file and save it to file system, but in Zintthe function png_plot() except generating image also save it on disk which is undesirable. As result I think there two ways: 1. from bitmap bytearray to bmp -> jpeg / png (using some other lib) 2. writing hook or some similar to png_plot() Can you give me some advices? Thank you. Upd: for @peacemaker FILE *f; zint_symbol *my_symbol; my_symbol = ZBarcode_Create(); ZBarcode_Encode_and_Buffer(my_symbol, (unsigned char *)argv[1], 0, 0); f = fopen("bitmap.bmp", "w"); fwrite(my_symbol->bitmap, sizeof(*(my_symbol->bitmap)), my_symbol->bitmap_height * my_symbol->bitmap_width, f); ZBarcode_Delete(my_symbol); fclose(f); A: In order to convert between image formats, the easiest way would be using the class CImage shared by MFC and ATL and defined in the header file atlimage.h. CImage image; HRESULT res = image.Load("in.bmp"); image.Save("out.jpg"); image.Save("out.gif"); image.Save("out.png"); image.Save("out.tif"); If you have a RGB buffer and want to create a bitmap: just create and save a bitmap header into a file and add the RGB buffer to it. To create the header you can use the BITMAPFILEHEADER, BITMAPINFOHEADER and RGBQUAD structures from GDI defined in the header WinGDI.h Here is an example on how to fill the header data: BITMAPINFOHEADER bmpInfoHdr; bmpInfoHdr.biSize = sizeof(BITMAPINFOHEADER); bmpInfoHdr.biHeight = nHeight; bmpInfoHdr.biWidth = nWidthPadded; bmpInfoHdr.biPlanes = 1; bmpInfoHdr.biBitCount = bitsPerPixel; bmpInfoHdr.biSizeImage = nHeight * nWidthPadded * nSPP; bmpInfoHdr.biCompression = BI_RGB; bmpInfoHdr.biClrImportant = 0; bmpInfoHdr.biClrUsed = 0; bmpInfoHdr.biXPelsPerMeter = 0; bmpInfoHdr.biYPelsPerMeter = 0; bmpFileHdr.bfType = BITMAP_FORMAT_BMP; bmpFileHdr.bfSize = (DWORD) (sizeof(BITMAPFILEHEADER) + bmpInfoHdr.biSize + sizeof(RGBQUAD)*numColors + bmpInfoHdr.biSizeImage); bmpFileHdr.bfReserved1 = 0; bmpFileHdr.bfReserved2 = 0; bmpFileHdr.bfOffBits = (DWORD) (sizeof(BITMAPFILEHEADER) + bmpInfoHdr.biSize + sizeof(RGBQUAD)*numColors); Keep into account that the bitmaps are stored upside-down and that the width of the image must be aligned on a DWORD except for RLE-compressed bitmaps.(they must be multiple of 4 bytes, add a padding if necessary). if ((nWidth%4) != 0) nPadding = ((nWidth/4) + 1) * 4; When saving your buffer, add the needed padding to each row... Summarizing, these are the needed steps to create a bitmap file from a rgb buffer: //1. create bmp header //2. save header to file: write(file, &bmpFileHdr, sizeof(BITMAPFILEHEADER)); write(file, &bmpInfoHdr, sizeof(BITMAPINFOHEADER)); write(file, &colorTable, numColors * sizeof(RGBQUAD)); //3. add rgb buffer to file: for(int h=0; h<nHeight; h++) { for(int w=0; w<nWidth; w++) { //3.a) add row to file //3.b) add padding for this row to file } } A: I used the CImage Class from ATL. int width=0, height=0; char * val = "9788994774480"; zint_symbol *my_symbol; my_symbol = ZBarcode_Create(); //ZBarcode_Encode_and_Buffer(my_symbol,(unsigned char *) val, 0, 0); ZBarcode_Encode(my_symbol, (unsigned char *) val, 0); ZBarcode_Buffer(my_symbol, 0); height = my_symbol->bitmap_height; width = my_symbol->bitmap_width; char * imgBits = my_symbol->bitmap; CImage img; img.Create(width, height, 24 /* bpp */, 0 /* No alpha channel */); int nPixel = 0; for(int row = 0; row < height; row++) { for(int col = 0; col < width; col++) { BYTE r = (BYTE)imgBits[nPixel]; BYTE g = (BYTE)imgBits[nPixel+1]; BYTE b = (BYTE)imgBits[nPixel+2]; img.SetPixel(col, row , RGB(r, g, b)); nPixel += 3; } } img.Save("CImage.bmp", Gdiplus::ImageFormatBMP); ZBarcode_Delete(my_symbol); A: is there anyway to do this other than using SetPixel? I am experiencing major performance issues with SetPixel and need an alternative method... I have tried using CreateDIBSection to no avail. The barcode displays slanted and is unusable. here is my code for that: void *bits = (unsigned char*)(my_symbol->bitmap); HBITMAP hBitmap = CreateDIBSection(pDC->GetSafeHdc(), &info, DIB_RGB_COLORS, (void **)&pDestData, NULL, 0); memcpy(pDestData, my_symbol->bitmap, info.bmiHeader.biSizeImage); img.Attach(hBitmap); Another option that produces the same result is this: BITMAPINFO info; BITMAPINFOHEADER BitmapInfoHeader; BitmapInfoHeader.biSize = sizeof(BITMAPINFOHEADER); BitmapInfoHeader.biWidth = my_symbol->bitmap_width; BitmapInfoHeader.biHeight = -(my_symbol->bitmap_height); BitmapInfoHeader.biPlanes = 1; BitmapInfoHeader.biBitCount = 24; BitmapInfoHeader.biCompression = BI_RGB; BitmapInfoHeader.biSizeImage = 0; BitmapInfoHeader.biXPelsPerMeter = 0; BitmapInfoHeader.biYPelsPerMeter = 0; BitmapInfoHeader.biClrUsed = 0; BitmapInfoHeader.biClrImportant = 0; info.bmiHeader = BitmapInfoHeader; HBITMAP hbmp = CreateDIBitmap(dc, &BitmapInfoHeader, CBM_INIT, (LPVOID *)my_symbol->bitmap, (LPBITMAPINFO)&info, DIB_RGB_COLORS); img.Attach(hbmp);
{ "language": "en", "url": "https://stackoverflow.com/questions/11350752", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to forbid Google Chrome change minimal font-size of my web-page? I'm making responsive sites, and in html tag I have this: font: normal 10px/1.5 "proxima-nova-soft", sans-serif; So, in other tags I'm use rem for font-size.It's works pretty good and I don't have problems earlier.But today I find issue(my client find).If in Google Chrome settings we change minimal font-size - all pages will be crushed. Of course I can change web site font to 10px, but it's very bad approach...
{ "language": "en", "url": "https://stackoverflow.com/questions/32775197", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Tracking the meeting invitation response in OutLook and Gmail I, have a requirement where I, have to send an email invitation to the mail. The user can Accept and decline the response in the email. I, have completed the user email invitation and adding to the calendar either in Gmail or outlook using the .ics file. Here is the code for the inviation email filePath = Path.Combine(HttpRuntime.AppDomainAppPath, "Email/calenderInvitation.ics"); fileContent = System.IO.File.OpenText(filePath).ReadToEnd(); fileContent = fileContent.Replace("#TO#", receiver); fileContent = fileContent.Replace("#FROM#", fromAddress.Address); fileContent = fileContent.Replace("#LOCATION#", eventVenue); fileContent = fileContent.Replace("#UID#", Guid.NewGuid().ToString().Replace("-", "")); fileContent = fileContent.Replace("#CREATED-AT#", Convert.ToDateTime(meetingDate).ToString(TimeFormat)); fileContent = fileContent.Replace("#DTSTART#", Convert.ToDateTime(startTime).ToString(TimeFormat)); fileContent = fileContent.Replace("#DTEND#", Convert.ToDateTime(finishTime).ToString(TimeFormat)); MailMessage message = new MailMessage(); message.From = new MailAddress(fromAddress.Address); message.To.Add(new MailAddress(receiver)); message.Subject = string.Format("{0} {1} @ {2} {3} {4} {5} - {6}", "Invitation: ", meetingTypeName, Convert.ToDateTime(meetingDate).ToString("dddd"), Convert.ToDateTime(startTime).ToString("MMMM"), Convert.ToDateTime(startTime).ToString("yyyy"), startTime, finishTime); var iCalendarContentType = new ContentType("text/calendar; method=REQUEST"); var calendarView = AlternateView.CreateAlternateViewFromString(fileContent, iCalendarContentType); calendarView.TransferEncoding = TransferEncoding.SevenBit; message.AlternateViews.Add(calendarView); smtp.Send(message); Here is the screen shot of the email. Now I want to track the response from the user whether they have click ACCEPT/DECLINE While research I found this links https://msdn.microsoft.com/en-us/library/office/dd633669(v=exchg.80).aspx However this will work on outlook or office 365. But I need the response from other email as well like GMAIL etc Here is the .ics file format BEGIN:VCALENDAR VERSION:2.0 PRODID:-//A//B//EN CALSCALE:GREGORIAN METHOD:REQUEST BEGIN:VEVENT ORGANIZER;CN="Organizer":mailto:#FROM# ATTENDEE;CN="Attendee";CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT= NEEDS-ACTION;RSVP=TRUE:mailto:#TO# DTSTART:#DTSTART# DTEND:#DTEND# LOCATION:#LOCATION# SUMMARY: Invitation for Meeting TRANSP:OPAQUE SEQUENCE:0 UID:#UID# DTSTAMP:#CREATED-AT# CREATED:#CREATED-AT# LAST-MODIFIED:#CREATED-AT# DESCRIPTION:Test description\n PRIORITY:5 CLASS:PUBLIC END:VEVENT END:VCALENDAR
{ "language": "en", "url": "https://stackoverflow.com/questions/47626355", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: dynamic ContextMenu in TreeView vs. MVVM I have a tree of ViewModels displayed as a TreeView (using HierarchicalDataTemplate). Each ViewModel instance has different commands that can be executed on it wich again are exposed as a list of command ViewModels for each item ViewModel. How can I create a single ContextMenu that opens at the TreeViewItem that was rightclicked and that populates its commands from the underlying item ViewModel's command ViewModels list? All in a decent MVVM fashion ... A: I think I understand your question. I think that you could structure your ViewModels like this: interface ICommandViewModel : ICommand { string Name {get;} } interface INodeViewModel { IEnumerable<ICommandViewModel> CommandList {get;} } public class NodeViewModel : INodeViewModel { public NodeViewModel() { //Init commandList //Populate commandList here(you could also do lazy loading) } public NodeViewModel(IEnumerable<ICommandViewModel> commands) { CommandList = commands; } public IEnumerable<ICommandViewModel> CommandList {get;private set;} } and then in xaml <TreeViewItem> <TreeViewItem.ContextMenu Items={Binding CommandList}> <ContextMenu.ItemTemplate> <DataTemplate> <MenuItem Header="{Binding Name}" Command="{Binding}"/> </DataTemplate> </ContextMenu.ItemTemplate> </TreeViewItem.ContextMenu> </TreeViewItem> I don't have much experience with hierarchical datatemplate but you get the gist from the above. You could also do the above with a style in the but I don't have a xaml editor in front of me to give you right syntax. Hope that helps
{ "language": "en", "url": "https://stackoverflow.com/questions/2508367", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Sum based on two columns from another table I've got this table named "A" and I want to fill the Sales SUM column with the sum of sales from another table group by date and country. The other table is named "B" and got also Date, Country and Sales columns however the number of dates and countries differ. I don't want to join this tables I would like to achieve this in DAX. Is it possible? A: Yes you can do that with DAX and virtual relationship: SumSales = calculate( sum('B'[Sales]) , TREATAS(SUMMARIZE('A','A'[Date],'A'[Country]), 'B'[Date],'B'[Country]) )
{ "language": "en", "url": "https://stackoverflow.com/questions/64696668", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Start point have different stroke width than other points Why stroke width differs for start point and other points? Please refer the code below: <svg> <polyline points="10 0, 30 0,10 10,30 10" fill="none" stroke-width="2px" stroke="#19af5c"></polyline> </svg> I don't want to achieve by duplicating poly-line for other points. i.e each points have different polyline/line element A: That is because of how the stroke is done in SVG. It is done something like half-and-half, that is, the stroke is half from 0 to 1 and the other half is -1 to 0 (if you get what I mean) and so you see a thinner stroke. You can refer the Stroke section in this MDN page to see what I mean. They've put it as follows: Strokes are drawn centered around the path If you make the points as 10,1 and 30,1 you would see the same stroke width. Reason for this is that the stroke is now kind of between 0 to 2 on the Y-axis (half of the stroke is on top of the point and half is on the bottom). <svg> <polyline points="10 1, 30 1,10 10,30 10" fill="none" stroke-width="2px" stroke="#19af5c"></polyline> </svg>
{ "language": "en", "url": "https://stackoverflow.com/questions/41032673", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to use OneDrive CSharp SDK as a Service or daemon app? I am coding against the OneDrive C# SDKand I have a few questions. Question 1. Does the OneDrive C# SDK use the Microsoft Graph API under the hood? ... If so, how can I use the SDK to pass in my client_Id and client_secret and authenticate as a service or daemon app instead of a traditional OAuth for a user? I have proofed out the authentication for a service with REST calls but I am trying to proof out if it is still possible to use a C# SDK instead. Question 2. I found this article Azure Active Directory Graph Service Tutorial. After following the example I am able to create an HTTP POST call and return an access_token. My question is there a way to use this token in conjunction with the Microsoft Graph CSharp SDK or OneDrive CSharp SDK to serve as the authentication process? Update: Okay, I was able to proof out some more and having a working code, but I am now getting an error around {Code: InvalidAuthenticationTokenMessage: Access token validation failure. I did the exact same call with Postman and was able to get data back with REST calls, is REST the only way to achieve this? I created a gist for my attempt: Code A: Solved On line 62 in the gist, I was hitting the wrong resource. The correct resource is https://graph.microsoft.com
{ "language": "en", "url": "https://stackoverflow.com/questions/42093299", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: need help solving sorl-thumbnail error: "'thumbnail' is not a valid tag library:" I've been pulling my hair out trying to solve this problem and I've tried everything and I have no ideas left. I keep seeing this error: Exception Value: 'thumbnail' is not a valid tag library: Could not load template library from django.templatetags.thumbnail, No module named sorl.thumbnail.main $DJANGO_PACKAGES/sorl/thumbnail/main.py DOES exist. Here's what I did to setup, * *downloaded latest sorl-thumbnail and added its location to the python path in .bash_profile *included 'sorl.thumbnail' in INSTALLED_APPS (in django's settings.py) *used the {% load thumbnail %} tag in a django template It would seem obvious sorl-thumbnail is not installed correctly, but I'm able to import thumbnail from the python shell and the django shell (when I use {% load thumbnail %} it brings this error). Also, there are no typos in related files (I've checked many many times). A: I would venture to guess this is a $PYTHONPATH issue. Is it possible that the "thumbnail" directory is on the path and not "sorl"? I suspect this is the issue because you do not want to be able to type "import thumbnail" on the Python interpreter. You should instead have to type "import sorl.thumbnail". Another thing to check is to print the module name after importing: >>> import thumbnail >>> print thumbnail This will display the filesystem location where the module was found, in case it's loading another copy from somewhere you do not expect. You also want to make sure your current working directory is not the root ../sorl/ location (ie. don't run python from the sorl folder). This will allow you to import thumbnail straight-away. You should check your full Python path (it will be more than $PYTHONPATH) from within the python interpreter to verify your package locations: >>> import sys >>> print sys.path It might also be helpful to learn more about Python importing A: Problem solved. When following the django book, it is suggested to create apps within a project directory and to refer to these apps in the INSTALLED APPS statement with a path that begins from the directory containing the project, for example, 'siteproject.books'. I was not able to give django access to apps without appending that directory name to the file path, so, for example, I was not able to simply use 'books', but needed to use 'siteproject.books' in the INSTALLED APPS statement and this was the case with sorl.thumbnail, which needed to be referred to as siteproject.sorl.thumbnail. Other attempts to include 'sorl.thumbnail' would yield a very ugly un-formatted and confusing purple-colored error page (yes, the sorl directory was in $PYTHONPATH, so who knows why these attempts didn't work...). Unfortunately, Django was yielding the 'undefined tag' error, which is a generalized error that it gives in many situations. It doesn't really mean anything and isn't useful for locating problems. The problem was solved when I opened the files in the sorl directory and edited the python files. I found import statements that imported objects from the sorl directory and I appended the 'siteproject.*' to those paths and everything began to work. A: Here's another general tip on the unhelpful 'not a valid tag library' message: for tags that you create, it could be as simple as a syntax error. Hat tip: 'Rock' on Django-users: http://groups.google.com/group/django-users/browse_thread/thread/d65db3940acf16c3?tvc=2
{ "language": "en", "url": "https://stackoverflow.com/questions/1356334", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: HQL subqueries in hibernate I have to write hql for one of the subquery. I am getting querysyntax exception. Below is my code. public List<URPTempSensor> findTempSensorObjs(String systemId, Character isLatest) { Map<String,Object> params = new HashMap<String,Object>(); List<URPTempSensor> tSensorList = new ArrayList<URPTempSensor>(); params.put("systemId", systemId); params.put("status", isLatest); String sql = "select * from " + "(select tsensor.time, tsensor.tId from URPTempSensor tsensor where " + "tsensor.isLatest=\'"+isLatest+"\' and tsensor.urpTempSystemId.systemId=\'"+systemId+"\' order by time desc)where rownum<=3"; tSensorList = this.urpTempDao.find(sql,params); return tSensorList; } can anyone help on this A: Probably you are receiving a syntax error because the HQL not support a SELECT after a the FROM clause: "select * from " + "(select You need to rethink your SQL to write it on HQL.
{ "language": "en", "url": "https://stackoverflow.com/questions/49996926", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }