text
stringlengths
15
59.8k
meta
dict
Q: Want to know the number of times a value appears on a given date I will try to explain this in as simple a way as possible. I want to be able to count how many times a value is entered into my database table for each day. Basically, if the data is entered once it would count as a single, if the data was entered twice it would count as a double and if the data was entered three times it would count as a treble. I then want to be able to count how many singles, doubles and trebles appear within a certain time frame (April to April each year). Then of course echo them out on to the php page like so: Singles - 23 Doubles - 69 Trebles - 3 I tried adding a round_id column in the database table as I thought if that was default 1 and I could somehow count each day how many 1's appeared that would work but I am totally stuck. Any help would be greatly appreciated! A: If I'm understanding you right, to start, we can get a count by day: SELECT COUNT(*) AS cnt, `date` FROM `table` GROUP BY `date` That will give you the count of records for each day. Then we can wrap that in another query: SELECT dailycount.daycnt AS `type`, COUNT(*) AS cnt FROM ( SELECT COUNT(*) AS daycnt, `date` FROM `table` GROUP BY `date` ) dailycount WHERE `date` BETWEEN start_date AND end_date GROUP BY daycnt This will give you something like this: type cnt 1 23 2 69 3 3 where type would be your singles, doubles, etc. A: Without knowing the structure, here's the best SQL I could come out with: SELECT COUNT(DISTINCT field) FROM table GROUP BY field That will count the number of field appearances for each value.
{ "language": "en", "url": "https://stackoverflow.com/questions/9893348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# Regex specify allowed start and end condtions I'm trying to create a regex expression with the following requirements: The value: * *Must start with a-z or _, numbers are OK after the first character *Can have parentheses if they are opened and closed with number inside at the end of string, i.e SomeVar(10) is OK, SomeVar(10 is not OK. *Can have a . but only one at a time, and only between letters or numbers. SomeVar.InnerVar is OK, SomeVar..Innevar is not OK. My try at the regex: * *[a-zA-Z_] *?? *?? A: Assuming you want to match an entire string, you may use something like the following: ^[a-zA-Z_](?:\w|(?<=\w)\.(?=\w))*(?:\(\d+\))?$ Demo. If you want to match partial strings, you'd need to decide what boundaries are allowed. Otherwise, "SomeVar(10" would have a match (i.e., what comes before (), for example. Notes: * *\w matches a lowercase/uppercase letter, a digit, or an underscore. But it also matches Unicode letters and numbers. If you don't want that, you could use [a-zA-Z0-9_] instead. *Similarly, \d matches any Unicode digit. You either use it or use [0-9] depending on your requirements. A: Use ^[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*(\([^()]*\))?$ See proof. * *[a-zA-Z_][a-zA-Z0-9_]* - a letter or underscore, then zero or more letters, digits, underscores *(\([^()]*\))? - optional group, parens may be present or absent *(\.[a-zA-Z_][a-zA-Z0-9_]*)* - dot is allowed between letter/digit/underscore.
{ "language": "en", "url": "https://stackoverflow.com/questions/62204471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Delete a row javascript using row id Hi guys I have a table created by php in this way: foreach ($query as $row): ?> <tr id="<?php echo $row->aic;?>" > <td><?php echo $row->aic; ?></td> <td><?php echo $row->denominazione ?></td> <td><?php echo $row->quantita; ?></td> <td><?php echo $row->alert; ?></td> <td> <a id="bt_modifica" class="btn btn-default btn-xs" data-toggle="tooltip" data-placement="top" title="" data-original-title="Modifica"> <img src="<?php echo base_url(); ?>template/images/Modifica.png"> </a> <a id="bt_elimina>" class="btn btn-default btn-xs" data-toggle="tooltip" data-placement="top" title="" data-original-title="Elimina" onclick="deleteRow(<?php echo $row->aic ?>))"> <img src="<?php echo base_url(); ?>template/images/Elimina.png"> </a> </td> </tr> <?php endforeach; ?> </tbody> I need to delete row by rowId. This table has the dynamics id. The columns ids are the same id of the sql table; in effect aic is id of sql table! In this way I are sure that the HTML row id is unique. This is script function deleteRow(rowID) { var row = document.getElementById(rowID); row.parentElement.removeChild(row); alert(rowID); } } this code don't delete row. A: Change this: onclick="deleteRow(deleteRow(<?php echo $row->aic ?>))"> to onclick="deleteRow(<?php echo $row->aic ?>)"> Another potential issue is that this: <?php echo $row->aic ?> may not be a number. So, you need to quote it. That is, change: onclick="deleteRow(<?php echo $row->aic ?>)"> to: onclick="deleteRow(\"<?php echo $row->aic ?>\")"> A: 2 issues - * *The one that might be causing issue - Incorrect Function Name *Other one - Calling deleteRow() twice - within each other (this should not cause any issue though) So, just change - function eliminaProdotto(rowID) to - function deleteRow(rowID) Edit: Based on modified question - Is $row->aic a string? If yes, then add quotes around it... onclick="deleteRow('<?php echo $row->aic ?>')"
{ "language": "en", "url": "https://stackoverflow.com/questions/24344176", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Undefined Reference to vtable with abstract class When building my C++ program, I'm getting the error message. undefined reference to vtable I have two virtual abstract classes called and I can't quite figure out what I'm doing wrong if I'm doing anything wrong. I'm getting errors from both of the classes that are inheriting from the abstract class. My abstract class is undefined reference to `vtable for hittable_list' undefined reference to `vtable for sphere' hittable.h #ifndef HITTABLE_H #define HITTABLE_H #include "ray.h" struct hit_record { hit_record() {} ~hit_record() {} float t; vecfloat p; vecfloat normal; float MAXFLOAT = 100.0; }; //Abstract Class containing Sphere and hittablelist class hittable { public: virtual ~hittable() = 0; virtual bool hit(const ray &r, float t_min, float t_max, hit_record &rec) const = 0; }; #endif Classes inherting from my abstract class are. sphere.h #ifndef SPHERE_H #define SPHERE_H #include "hittable.h" class sphere : public hittable { public: sphere() {} ~sphere() {} sphere(vecfloat cen, float r) : center(cen), radius(r) {} bool hit(const ray &r, float t_min, float t_max, hit_record &rec) const; protected: vecfloat center; float radius; }; #endif sphere.cc #include "include/sphere.h" bool sphere::hit(const ray &r, float t_min, float t_max, hit_record &rec) const { vecfloat oc = r.origin() - center; float a = oc.dot_product(r.direction()); float b = oc.dot_product(oc) - radius * radius; float c = oc.dot_product(oc) - radius * radius; float discriminant = b * b - a * c; if (discriminant > 0) { float temp = (-b - sqrt(b * b - a * c)) / a; if (temp < t_max && temp > t_min) { rec.t = temp; rec.p = r.point_at_parameter(rec.t); rec.normal = (rec.p - center) / radius; return true; } temp = (-b + sqrt(b * b - a * c)) / a; if (temp < t_max && temp > t_min) { rec.t = temp; rec.p = r.point_at_parameter(rec.t); rec.normal = (rec.p - center) / radius; return true; } } return false; } hittable.h #ifndef HITTABLELIST_H #define HITTABLELIST_H #include "hittable.h" class hittable_list : public hittable { public: hittable_list() {} hittable_list(hittable **l, int n) { list = l; list_size = n; } bool hit(const ray &r, float t_min, float t_max, hit_record &rec) const; ~hittable_list() {} protected: hittable **list; int list_size; }; #endif hittable.cc #include "include/hittablelist.h" bool hittable_list::hit(const ray &r, float t_min, float t_max, hit_record &rec) const { hit_record temp_rec; auto hit_anything = false; auto closet_so_far = t_max; for (int i = 0; i < list_size; i++) { if (list[i]->hit(r, t_min, closet_so_far, temp_rec)) { hit_anything = true; closet_so_far = temp_rec.t; rec = temp_rec; } } return hit_anything; } A: Solution Change virtual ~hittable() = 0; into virtual ~hittable() = default; or virtual ~hittable() { // does nothing } The destructor can remain pure virtual, but it must have a definition. hittable::~hittable() { // does nothing } So what happened? We can crush the given code down to the following example (Note I can't reproduce the missing vtable with this code or the given code, but regardless, the above will fix it) Minimal example: class hittable { public: virtual ~hittable() = 0; // here we have a destructor, // but there's no implementation // so there is nothing for the // destructors of derived classes // to call virtual bool hit() const = 0; }; class sphere: public hittable { public: bool hit() const; }; bool sphere::hit() const { return false; } destructors call any base class destructors, and when shpere goes to call ~hittable, it finds that while ~hittableis declared, there is no implementation. Nothing to call.
{ "language": "en", "url": "https://stackoverflow.com/questions/63532266", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: query: get author of a song and count total of songs for that author I'm not sure how to do the following query. I have 3 tables: song (song_id, title, is_draft) author (author_id, name) song_author (song_id, author_id, display_order) There are songs, and a song can have multiple authors and an author can write multiple songs I want to output the authors of a specific song with the total numbers of songs that each author wrote. So, if i pick song_id: 598, i want to have a result set like this author_id name total songs he wrote ------------------------------------------------ 234 Michael Lord 58 589 Lama Turc 12 NOTE: The total number of songs each author wrote must exclude songs were song.is_draft equals 1 and order the result set by song_author.displayorder From my research, i think i have to do 2 queries (sub queries) but that's as far as i got... Thanks A: SELECT author.author_id, author.name, count(song.song_id) FROM song, author, song_author, WHERE song.song_id = $id AND song.song_id = song_author.song_id AND song_author.author_id = author.author_id AND song_author.display_order != 1 GROUP BY song_author.author_id, author.name ORDER BY author.author_id asc; A: try this.. select b.author_Id, b.name, COUNT(a.Song_Id) as 'total' FROm song_author as a INNER JOIN author as b ON a.author_id = b.author_id where a.song_id IN (select s.song_id From songs as s Where s.Song_Id = 598 AnD s.is_draft = 1) GROUP bY b.author_Id, b.name A: New to SQL too, but off the top of my head maybe this? This doesn't explicitly spell out joins, but I've found it works for my purposes. Maybe someone can let me know if this is bad practice? Select author.author_id , author.name , count(author.author_id) from song, author, song_author where song.song_id = song_author.song_id and author.author_id = song_author.author_id group by author.authorid, author.name order by author.author_id asc;
{ "language": "en", "url": "https://stackoverflow.com/questions/17458601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: stub random value in rspec with secure_random I am trying to write specs for my gem, which generates otp and saves it in db. Now i am writing specs for it. so basically i have three methods generate_otp!, regenerate_otp!, verify_otp(otp). what generate_otp! does is it calls a method generate_otp which contains three variables * *otp_code - basically a random value generated using secure_random *otp_verified - a boolean value to set the status whether otp is verified or not *otp_expiry_time - sets expiry time for otp which can be set by rails app in configuration. these all three are columns of my db also. Now after generate_otp i am calling active_records's save method to save values to db. Now for testing i am using in :memory: and storing values in table. after testing i am dropping the db. Now i am not getting how to stub the randomly generated value and test whether value is assigned or not to all three columns, i.e, otp_code , otp_verified, otp_expiry_time. Here is code for my methods which i need to test. def generate_otp self.otp_verified = false self.otp_expiry_time = OtpGenerator::configuration.otp_expiry_time self.otp_code = SecureRandom.hex(4) end def generate_otp! generate_otp save end Any help with this ? I have also checked this question, but not much helpful. It's first time i am writing specs and really don't have that much experience with rspecs. I have also studied the official documentation for mock and stub, but i am really getting confused. update : otp_spec code require 'spec_helper' describe OtpGenerator do let(:user) { build_mock_class.new() } before(:all) { create_table } after(:all) { drop_table } describe '#generate_otp' do it 'generate otp and save it' do user.generate_otp! end end describe '#regenerate_otp' do it 'regenerate otp and save it' do end end describe '#verify_otp' do it 'verifies otp' do end end def build_mock_class Class.new(ActiveRecord::Base) do self.table_name = 'mock_table' include OtpGenerator end end def create_table ActiveRecord::Base.connection.create_table :mock_table do |t| t.string :otp_code t.boolean :otp_verified t.datetime :otp_expiry_time end end def drop_table ActiveRecord::Base.connection.drop_table :mock_table end end A: A direct approach to stubbing out the SecureRandom method in rspec would be as follows: before { allow(SecureRandom).to receive(:hex).with(4).and_return('abcd1234') } You can then check that 'abcd1234' is stored in the database. In order to keep the test DRY, you may also wish to reference this as a variable, e.g. let(:random_value) { 'abcd1234' }.
{ "language": "en", "url": "https://stackoverflow.com/questions/38370512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Pygame: Character Centered Movement System (Diablo II like click-to-move) I am currently working on a new RPG game using Pygame (my aim here is really to learn how to use object oriented programming). I started a few days ago and developed a movement system where the player clicks a location and the character sprite goes to that location and stops when it get's there by checking if the sprite 'collides' with the mouse position. I quickly found however that this greatly limited the world size (to the app window size). I started having a look into making a movement system where the background would move with respect to the player, hence providing the illusion of movement. I managed to achieve this by creating a variable keeping track of my background map position. The map is much bigger than the app window. And each time I want my player to move I offset the background by the speed of the player in the opposite direction. My next problem now is that I can't get my character to stop moving... because the character sprite never actually reaches the last position clicked by the mouse, since it is the background that is moving, not the character sprite. I was thinking of spending some time coding in a variable that would keep track of how many displacements it would take the character sprite to reach the mouse clicked position if it was to move. Since the background moves at the character sprite's speed it would take as many displacement of the background in the x and y directions to center the clicked position on the background to the character sprite at the center of the screen. It would be something like that: If MOUSEBUTTON clicked: NM = set number of moves needed to reach the clicked position based on character sprite distance to click and character sprite speed. If NM != 0: Move background image Else: pass This would mean that when my background has moved enough for the character sprite to now be just over the area of the background that was originally clicked by the player, the movement would stop since NM == 0. I guess that my question is: Does that sound like a good idea or will it be a nightmare to handle the movement of other sprites and collisions ? And are there better tools in Pygame to achieve this movement system ? I could also maybe use a clock and work out how many seconds the movements would take. I guess that ultimately the whole challenge is dealing with a fixed reference point and make everything move around it, both with respect to this fixed reference, but also to their own. e.g. If two other sprites move toward one another, and the character of the player also "moves" then the movement of the other two sprites will have to depend both on the position of the other sprite and also on the offset of the background caused by the movement of the player's character. An interesting topic which has been frying my brain for a few nights ! Thank you for your suggestions ! A: You actually asking for an opinion on game design. The way I look at it, nothing is impossible so go ahead and try your coding. Also it would be wise to look around at similar projects scattered around the net. You may be able to pick up a lot of tips without re inventing the wheel. Here is a good place to start. scrolling mini map
{ "language": "en", "url": "https://stackoverflow.com/questions/36860334", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android Open and Save files to/from Google Drive SDK I've spent the last six hours pouring over documents from Google and I still don't know how to get started with this. All I want to do is make it so my existing Android app can read files from Google Drive, upload new files to Google Drive, and edit existing files on Google Drive. I've read that Drive SDK v2 was focused solely on making it easy for Android (and mobile in general) developers to use it, and yet there seems to be virtually nothing in their documentation about it. Ideally, I'd like someone to point at some decent documentation, example, or tutorial covering how to do this (keep in mind I'm using Android. They have plenty of stuff on how to use Drive with the Google App Engine; I have already looked at it and I have no idea how to go from that to an Android app.) I need to know which libraries I need to download and add to my project, what I need to add to my manifest, and how I can ultimately get a list of files from Google Drive, download one, and then upload a modified version. Ideally, I'd like it to handle accounts automatically, the way that the officially Google Drive app does. A: Edit: Claudio Cherubino says that Google Play Services is now available and will make this process a lot easier. However, there's no sample code available (yet, he says it's coming soon... they said Google Play Services was "coming soon" 4 months ago, so there's a good chance this answer will continue to be the only completely working example of accessing Google Drive from your Android application into 2013.) Edit 2X: Looks like I was off by about a month when I said Google wouldn't have a working example until next year. The official guide from Google is over here: https://developers.google.com/drive/quickstart-android I haven't tested their methods yet, so it's possible that my solutions from September 2012 (below) are still the best: Google Play Services is NOT REQUIRED for this. It's a pain in the butt, and I spent well over 50 hours (edit: 100+ hours) figuring it all out, but here's a lot of things that it'll help to know: THE LIBRARIES For Google's online services in general you'll need these libraries in your project: (Instructions and Download Link) * *google-api-client-1.11.0-beta.jar *google-api-client-android-1.11.0-beta.jar *google-http-client-1.11.0-beta.jar *google-http-client-android-1.11.0-beta.jar *google-http-client-jackson-1.11.0-beta.jar *google-oauth-client-1.11.0-beta.jar *guava-11.0.1.jar *jackson-core-asl-1.9.9.jar *jsr305-1.3.9.jar For Google Drive in particular you'll also need this: * *google-api-services-drive-v2-rev9-1.8.0-beta.jar (Download Link) SETTING UP THE CONSOLE Next, go to Google Console. Make a new project. Under Services, you'll need to turn on two things: DRIVE API and DRIVE SDK! They are separate, one does not automatically turn the other on, and YOU MUST TURN BOTH ON! (Figuring this out wasted at least 20 hours of my time alone.) Still on the console, go to API Access. Create a client, make it an Android app. Give it your bundle ID. I don't think the fingerprints thing is actually important, as I'm pretty sure I used the wrong one, but try to get that right anyways (Google provides instructions for it.) It'll generate a Client ID. You're going to need that. Hold onto it. Edit: I've been told that I'm mistaken and that you only need to turn on Drive API, Drive SDK doesn't need to be turned on at all, and that you just need to use the Simple API Key, not set up something for Android. I'm looking into that right now and will probably edit this answer in a few minutes if i figure it out... THE ANDROID CODE - Set Up and Uploading First, get an auth token: AccountManager am = AccountManager.get(activity); am.getAuthToken(am.getAccounts())[0], "oauth2:" + DriveScopes.DRIVE, new Bundle(), true, new OnTokenAcquired(), null); Next, OnTokenAcquired() needs to be set up something like this: private class OnTokenAcquired implements AccountManagerCallback<Bundle> { @Override public void run(AccountManagerFuture<Bundle> result) { try { final String token = result.getResult().getString(AccountManager.KEY_AUTHTOKEN); HttpTransport httpTransport = new NetHttpTransport(); JacksonFactory jsonFactory = new JacksonFactory(); Drive.Builder b = new Drive.Builder(httpTransport, jsonFactory, null); b.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() { @Override public void initialize(JSonHttpRequest request) throws IOException { DriveRequest driveRequest = (DriveRequest) request; driveRequest.setPrettyPrint(true); driveRequest.setKey(CLIENT ID YOU GOT WHEN SETTING UP THE CONSOLE BEFORE YOU STARTED CODING) driveRequest.setOauthToken(token); } }); final Drive drive = b.build(); final com.google.api.services.drive.model.File body = new com.google.api.services.drive.model.File(); body.setTitle("My Test File"); body.setDescription("A Test File"); body.setMimeType("text/plain"); final FileContent mediaContent = new FileContent("text/plain", an ordinary java.io.File you'd like to upload. Make it using a FileWriter or something, that's really outside the scope of this answer.) new Thread(new Runnable() { public void run() { try { com.google.api.services.drive.model.File file = drive.files().insert(body, mediaContent).execute(); alreadyTriedAgain = false; // Global boolean to make sure you don't repeatedly try too many times when the server is down or your code is faulty... they'll block requests until the next day if you make 10 bad requests, I found. } catch (IOException e) { if (!alreadyTriedAgain) { alreadyTriedAgain = true; AccountManager am = AccountManager.get(activity); am.invalidateAuthToken(am.getAccounts()[0].type, null); // Requires the permissions MANAGE_ACCOUNTS & USE_CREDENTIALS in the Manifest am.getAuthToken (same as before...) } else { // Give up. Crash or log an error or whatever you want. } } } }).start(); Intent launch = (Intent)result.getResult().get(AccountManager.KEY_INTENT); if (launch != null) { startActivityForResult(launch, 3025); return; // Not sure why... I wrote it here for some reason. Might not actually be necessary. } } catch (OperationCanceledException e) { // Handle it... } catch (AuthenticatorException e) { // Handle it... } catch (IOException e) { // Handle it... } } } THE ANDROID CODE - Downloading private java.io.File downloadGFileToJFolder(Drive drive, String token, File gFile, java.io.File jFolder) throws IOException { if (gFile.getDownloadUrl() != null && gFile.getDownloadUrl().length() > 0 ) { if (jFolder == null) { jFolder = Environment.getExternalStorageDirectory(); jFolder.mkdirs(); } try { HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(gFile.getDownloadUrl()); get.setHeader("Authorization", "Bearer " + token); HttpResponse response = client.execute(get); InputStream inputStream = response.getEntity().getContent(); jFolder.mkdirs(); java.io.File jFile = new java.io.File(jFolder.getAbsolutePath() + "/" + getGFileName(gFile)); // getGFileName() is my own method... it just grabs originalFilename if it exists or title if it doesn't. FileOutputStream fileStream = new FileOutputStream(jFile); byte buffer[] = new byte[1024]; int length; while ((length=inputStream.read(buffer))>0) { fileStream.write(buffer, 0, length); } fileStream.close(); inputStream.close(); return jFile; } catch (IOException e) { // Handle IOExceptions here... return null; } } else { // Handle the case where the file on Google Drive has no length here. return null; } } One last thing... if that intent gets sent off, you'll need to handle when it returns with a result. @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 3025) { switch (resultCode) { case RESULT_OK: AccountManager am = AccountManager.get(activity); am.getAuthToken(Same as the other two times... it should work this time though, because now the user is actually logged in.) break; case RESULT_CANCELED: // This probably means the user refused to log in. Explain to them why they need to log in. break; default: // This isn't expected... maybe just log whatever code was returned. break; } } else { // Your application has other intents that it fires off besides the one for Drive's log in if it ever reaches this spot. Handle it here however you'd like. } } THE ANDROID CODE - Updating Two quick notes on updating the last modified date of a file on Google Drive: * *You must provide a fully initialized DateTime. If you do not, you'll get a response of "Bad Request" from Google Drive. *You must use both setModifiedDate() on the File from Google Drive and setSetModifiedDate(true) on the update request itself. (Fun name, huh? "setSet[...]", there's no way people could mistype that one...) Here's some brief sample code showing how to do an update, including updating the file time: public void updateGFileFromJFile(Drive drive, File gFile, java.io.File jFile) throws IOException { FileContent gContent = new FileContent("text/csv", jFile); gFile.setModifiedDate(new DateTime(false, jFile.lastModified(), 0)); gFile = drive.files().update(gFile.getId(), gFile, gContent).setSetModifiedDate(true).execute(); } THE MANIFEST You'll need the following permissions: GET_ACCOUNTS, USE_CREDENTIALS, MANAGE_ACCOUNTS, INTERNET, and there's a good chance you'll need WRITE_EXTERNAL_STORAGE as well, depending on where you'd like to store the local copies of your files. YOUR BUILD TARGET Right click your project, go into it's properties, and under Android change the build target to Google APIs if you must. If they aren't there, download them from the android download manager. If you're testing on an emulator, make sure its target is Google APIs, not generic Android. You'll need a Google Account set up on your test device. The code as written will automatically use the first Google Account it finds (that's what the [0] is.) IDK if you need to have downloaded the Google Drive app for this to have worked. I was using API Level 15, I don't know how far back this code will work. THE REST The above should get you started and hopefully you can figure your way out from there... honestly, this is just about as far as I've gotten so far. I hope this helps A LOT of people and saves them A LOT of time. I'm fairly certain I've just written the most comprehensive set up guide to setting up an Android app to use Google Drive. Shame on Google for spreading the necessary material across at least 6 different pages that don't link to each other at all. A: Check this video from Google I/O to learn how to integrate your Android app with Drive: http://www.youtube.com/watch?v=xRGyzqD-vRg Please be aware that what you see in the video is based on Google Play Services: https://developers.google.com/android/google-play-services/ A: It's 2015, things have changed! Get the 'Drive API for Android' with gradle: compile 'com.google.android.gms:play-services-drive:7.8.0' There's some new doco (although still lackluster IMO): https://developers.google.com/drive/web/quickstart/android And for those about to go caving...the biggest problem I encountered thus far is that there is absolutely no way of distinguishing folders that have been permanently deleted from folders that are normal...you can find them, you can create folders and files within them, only writing to the file DriveContents will always fail. A: Take a look at Google's DrEdit Example, which has a folder called android/. Copy it, follow the readme, and it should work (works for me on an Android emulator with KitKat). . P.S. Sorry for reviving this, but the new Google Drive Android API doesn't support full Drive access, only drive.file and drive.appdata authorization scopes, so if you need full access you have to go back to the good 'ol Google API's Client for Java (which the DrEdit example uses).
{ "language": "en", "url": "https://stackoverflow.com/questions/12164024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "62" }
Q: How to create an rray of composites strings Hi everyone: I have a collection of 50 strings that represent comments in a text file where each line represents a separate comment with different sentences . Each string is a user review of a product, and each string or review has several several sentences. How could I to create an array with these strings using Python? Example of reviews: Review 1. "I was disapointed with the product. The quality was reality bad and the price was not fair. Never in my life I'll buy again this brand. Review 2. "I'm really happy with this product. It's all what i desired. Thanks brand J" .... and so far. Desired Results: * *[('disappointed', 'product'), ('quality', 'really', 'bad', 'price', 'fair')] *[('happy', 'product'), ('all', 'desired'), ('thanks', 'brand')] *... I want each processed comment in a separate line to save it in a csv file A: One of my first projects was similar to this. I believe your asking for help in getting the text file lines as an array. To open the file for reading: file = open("/path/to/file", "r") I would then split on spaces so: for line in file: print line.split(' ') this would give you an array of words from each line in the txt file. Then use the csv module in python to input into a csv file. References: * *Python the Hard Way - Opening and Closting Files *split() function *CSV Module
{ "language": "en", "url": "https://stackoverflow.com/questions/39539230", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to allocate 4k aligned Memory malloc() allocates a memory chunk which is virtually contiguous inside the process memory space. malloc() takes a size as a parameter in bytes and returns pointer to that allocated memory space but what if the requirement is to allocate memory which is 4k aligned? A: That would almost certainly be achieved using something like posix_memalign. A: Since 4Kbytes is often the size of a page (see sysconf(3) with _SC_PAGESIZE or the old getpagesize(2) syscall) you could use mmap(2) syscall (which is used by malloc and posix_memalign) to get 4Kaligned memory. A: you can not allocate physically contiguous memory in user space. Because in User space kernel always allocates memory from highmem zone. But if you are writing a kernel module or a system space code then you can use _get_page() or _get_pages().
{ "language": "en", "url": "https://stackoverflow.com/questions/17440498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Django can't multiply sequence by non-int of type 'str' I have this logic in my views and models, in my views i get the data of what the user inputted, and in my models, i have an automatic computation of discount_price_formula, and other_discount_price_formula why i am having this error? can't multiply sequence by non-int of type 'str'. how do i solve this problem? this is my views.py otherdiscountpercentage = request.POST.get("otherdiscountpercentage") S_price = request.POST.get("price") otherdiscountprice = request.POST.get("otherdiscountprice") discountpercentage = request.POST.get("discountpercentage") discountprice = request.POST.get("discountprice") insert_data = Product( price=S_price, discount_percentage=discountpercentage, discount_price=discountprice, Other_discount_percentage=otherdiscountpercentage, Other_discount_price=otherdiscountprice, ) this is my models.py class Product(models.Model): price = models.FloatField(null=True, blank=True, verbose_name="Unit Price") discount_percentage = models.FloatField(max_length=500, null=True, blank=True) discount_price = models.FloatField(null=True, blank=True) Other_discount_percentage = models.FloatField(null=True, blank=True) Other_discount_price = models.FloatField(null=True, blank=True, default=0.0) discount_price_formula = models.FloatField(null=True, blank=True) other_discount_price_formula = models.FloatField(null=True, blank=True) def save(self, *args, **kwargs): self.discount_price_formula = self.price - (self.price * self.discount_percentage) self.other_discount_price_formula = (self.price - (self.price * self.discount_percentage)) - ((self.price - (self.price * self.discount_percentage)) * self.Other_discount_percentage) return super(Product, self).save(*args, **kwargs) def __str__(self): suser = '{0.product}' return suser.format(self) this is my traceback Traceback: File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Desktop\onlinestoreapp\customAdmin\views.py" in InsertProduct 293. insert_data.save() File "C:\Users\Desktop\onlinestoreapp\customAdmin\models.py" in save 209. self.discount_price_formula = self.price - (self.price * self.discount_percentage) Exception Type: TypeError at /InsertProduct/ Exception Value: can't multiply sequence by non-int of type 'str' A: Values coming from a request are by default str type but Django does the conversion directly. Since you're overwriting the save method, you need to convert them to int, like this: otherdiscountpercentage = request.POST.get("otherdiscountpercentage") if otherdiscountpercentage: otherdiscountpercentage = float(otherdiscountpercentage) Beware that using request.POST.get('param_name') means the param is optional. So you should put some condition or give a default float value before any calculation. A: you can do this otherdiscountpercentage = request.POST.get("otherdiscountpercentage") S_price = request.POST.get("price") otherdiscountprice = request.POST.get("otherdiscountprice") discountpercentage = request.POST.get("discountpercentage") discountprice = request.POST.get("discountprice") insert_data = Product( price=float(S_price), discount_percentage=float(discountpercentage), discount_price=float(discountprice), Other_discount_percentage=float(otherdiscountpercentage), Other_discount_price=float(otherdiscountprice), )
{ "language": "en", "url": "https://stackoverflow.com/questions/64748558", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get Country name from ip address using ipinfo? I am using Laravel package for getting location using IP Address. composer require ipinfo/ipinfolaravel But when I hit request to get data of location it return null for local host. I have use this, public function index(Request $request) { dd($request->ipinfo->all); } and get out put as, array:5 [▼ "ip" => "127.0.0.1" "bogon" => true "country_name" => null "latitude" => null "longitude" => null ] and if I use code like this public function index(Request $request) { dd($request->ipinfo->country_name); } it return null How can i solve this issue?
{ "language": "en", "url": "https://stackoverflow.com/questions/67296110", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: tKinter How disable the Entry while checkbutton is unchecked and enable it while the checkbutton is checked from tkinter import * window=Tk() nac = {} ent = {} for i in range(10): de = IntVar() nac[i]=IntVar() na=Checkbutton(window, text='%s' % (i), borderwidth=1,variable = nac[i], onvalue = 1, offvalue = 0,command=lambda e=ent, v=nac[i]:naccheck(e,v)) na.grid(row=i, column=0) ent[i]=Entry(window,textvariable=de, state = DISABLED) ent[i].grid(column=1,row=i,padx=20) window.mainloop() A: Try this: from tkinter import * def entry(): ent[i].configure(state = NORMAL) window=Tk() nac = {} ent = {} for i in range(10): de = IntVar() nac[i]=IntVar() na=Checkbutton(window, text='%s' % (i), borderwidth=1,variable = nac[i], onvalue = 1, offvalue = 0,command=entry) na.grid(row=i, column=0) ent[i]=Entry(window,textvariable=de, state = DISABLED) ent[i].grid(column=1,row=i,padx=20) window.mainloop()
{ "language": "en", "url": "https://stackoverflow.com/questions/55009541", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: What is universal binary for iOS how iOS work at run time with them? A universal binary in ios contains executable for both armv7 and arm64. How iOS run architecture based executable.what is the concept of universal binary? Xcode creates the universal by compiling for both architecture armv7 and arm64 then create the universal binary that contains executable for both in a single file. So my question is what happens when this universal file will run in deep, if anyone have any document related to it please share the link. thanks in advance.
{ "language": "en", "url": "https://stackoverflow.com/questions/38320853", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ExtJs(4.2): Persist Time While Displaying Date time in DateColumn I have datecolumn in a grid. I am getting value from backend in following format: Y-m-d H:i:s. I have to display it as d.m.Y. And While sending back I have to again send it as Y-m-d H:i:s. My code is as following: Model { name: 'REA_LIT_URSPR', type: 'date', dateFormat:'Y-m-d H:i:s.0' } View { xtype: 'datecolumn', format:'d.m.Y', text: 'Ursp. LT', align: 'center', flex:1, dataIndex: 'REA_LIT_URSPR', editor: { xtype: 'datefield', format:'d.m.Y', editable: false } } Now issue is that if I get this value 2016-04-05 23:15:03.0, it is displayed properly. But as soon as I click it to edit it(and cancel it without selecting new date), I lose the Time 23:15:03.0 and it is changed to 00:00:00.0. I want to persist this time, in case when user click on cell to change date but change his mind and click somewhere else without changing date. I am using Ext.grid.plugin.CellEditing for making grid editable. Can someone tell me what I am doing wrong or how can I achieve my goal? A: ExtJS CellEditing plugin does not support "canceling" an edit by the user - whenever you click into the field and then leave, the field is validated, and if that does not fail, it is "edited". This is different in RowEditing, where a cancel button is shown that would cancel the edit and fire the canceledit event without validating the input. So you would have to use the beforeedit and validateedit events on the CellEditing plugin. How to use them is described very well in the ExtJS docs, which documents how to access the date field, the record and the store all at the same time. Example code: beforeedit:function( editor, context, eOpts ) { editor.oldTime = context.record.data.REA_LIT_URSPR;// Save old value. }, validateedit:function ( editor, context, eOpts ) { if(editor.context.value == editor.oldTime) // Compare Values and decide context.cancel = true; // whether to save it or not } A: { xtype: 'datecolumn', format:'Y-m-d g:i:s A', text: 'Ursp. LT', align: 'center', flex:1, dataIndex: 'REA_LIT_URSPR', editor: { xtype: 'datefield', format:'Y-m-d g:i:s A', editable: false } } Ok so the problem is on column date format, maybe you lose a part of date because g:i:s aren't saved from the datecolumn. I haven't tryed the code, but if it doesn't work try to create a new date format using these docs http://docs.sencha.com/extjs/5.1/5.1.1-apidocs/#!/api/Ext.Date-method-parse (same on extjs 4) sorry for first answer, just not clear question
{ "language": "en", "url": "https://stackoverflow.com/questions/35317367", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Check list to see if element greater than specified number I'm trying to check if a specific element in the list is greater than a set value. So x=22 list=[10,20,30] # check if anything in list is greater than x # do something to the list I'm just not sure what commands to use in this scenario to check every list element or if it's even possible in one line. A: You ask for "if any element in the list is greater than x". If you just want one element, you could just find the greatest element in the list using the max() function, and check if it's larger than x: if max(list) > x: ... There's also a one-liner you can do to make a list of all elements in the list greater than x, using list comprehensions (here's a tutorial, if you want one): >>> x = 22 >>> list = [10, 20, 30, 40] >>> greater = [i for i in list if i > x] >>> print(greater) [30, 40] This code generates a list greater of all the elements in list that are greater than x. You can see the code responsible for this: [i for i in list if i > x] This means, "Iterate over list and, if the condition i > x is true for any element i, add that element to a new list. At the end, return that new list." A: Use any, Python's natural way of checking if a condition holds for, well, any out of many: x = 22 lst = [10, 20, 30] # do NOT use list as a variable anme if any(y > x for y in lst): # do stuff with lst any will terminate upon the first truthy element of the iterable it is passed and, thus, not perform any spurious iterations which makes it preferable to max or list comprehension based approaches that have to always iterate the entire list. Asymptotically however, its time complexity is, of course, still linear. Also, you should not shadow built-in names like list. A: You could use filter and filter your list for items greater than 22, if the len of this filtered list is > 0 that means your original list contains a value larger than 22 n = 22 lst = [10,20,30] if len(list(filter(lambda x: x > n, lst))) > 0: # do something to lst A: List comprehension would suit your use case. In [1]: x=22 In [2]: l=[10,20,30] In [3]: exist = [n for n in l if n > x] In [4]: if exist: ...: print "elements {} are greater than x".format(exist) ...: elements [30] are greater than x If your list is very long, use generator so that you do not have to iterate through all elements of the list. In [5]: exist = next(n for n in l if n > x) In [6]: if exist: print "Element {} is greater than x".format(exist) ...: Element 30 is greater than x
{ "language": "en", "url": "https://stackoverflow.com/questions/52747716", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to get App's Permission for each app? how to do it programmatically on Android? How to get App's Permission Detail for each app? how to do it programmatically? I want to display "App's Permission Detail for each app" on TextView. But I try it but Not Ok?? Hello.java import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ListView; import android.content.Intent; import android.content.Context; import android.content.pm.*; import android.widget.TextView; import java.util.*; public class HelloSakez extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); final ListView lw = (ListView) findViewById(R.id.listView1); final List<ResolveInfo> pkglist = lw.getContext().getPackageManager().queryIntentActivities(mainIntent, 0); final TextView tw = (TextView) findViewById(R.id.textView1); Iterator it = pkglist.iterator(); while(it.hasNext()){ ResolveInfo rf = (ResolveInfo)it.next(); tw.append(rf.toString()); } } } main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:text="Button" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button> <ListView android:id="@+id/listView1" android:layout_height="wrap_content" android:layout_width="fill_parent"></ListView> <TextView android:text="TextView" android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView> </LinearLayout> A: You need to use PackageManager's GET_PERMISSIONS flag. Check this question. A: Use the following code in your activity: I created StringBuffer appNameAndPermissions = new StringBuffer(); to append all the apps and permisssions info. It's working fine. I tested it already. If you have any issues, please let me know. StringBuffer appNameAndPermissions = new StringBuffer(); PackageManager pm = getPackageManager(); List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA); for (ApplicationInfo applicationInfo : packages) { Log.d("test", "App: " + applicationInfo.name + " Package: " + applicationInfo.packageName); try { PackageInfo packageInfo = pm.getPackageInfo(applicationInfo.packageName, PackageManager.GET_PERMISSIONS); appNameAndPermissions.append(packageInfo.packageName+"*******:\n"); //Get Permissions String[] requestedPermissions = packageInfo.requestedPermissions; if(requestedPermissions != null) { for (int i = 0; i < requestedPermissions.length; i++) { Log.d("test", requestedPermissions[i]); appNameAndPermissions.append(requestedPermissions[i]+"\n"); } appNameAndPermissions.append("\n"); } catch (NameNotFoundException e) { e.printStackTrace(); } Use the following permission in your AndroidManifest.xml file: <uses-permission android:name="android.permission.GET_TASKS"/> A: Zhocker To uninstall any app use below code Intent i = new Intent(Intent.ACTION_DELETE); i.setData(Uri.parse("package:com.package name")); startActivity(i); And to get permissions use getInstalledPackages(int) with the flag GET_PERMISSIONS A: * *For App's permission go to Manifest file ans see. 2.for uninstall the app follow the below points:- a. go to setting b. then Open Application c. then open Manage Application d. then choose the app which you want to Uninstall e. then click on Uninstall and Uninstall the app.
{ "language": "en", "url": "https://stackoverflow.com/questions/5385957", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: How to prevent batch from skipping certain FOR loops? I'm currently working on a casual game in batch, and I'm running into a slight issue when recovering save data. All the save data is stored in custom INI files (idea from fourth answer here, other code from first answer here). The INI file is first created when the user inputs the name for the save, and said name is set as a variable called savename. The INI file is made when a template, sdata.text, is copied over through type sdata.txt > saves\%savename%.ini. The variable loadsave, of which is used when a user is loading a previous save file, is then set equal to savename (set loadsave=%savename%). The file then calls a separate file called lsdata.bat, and lsdata.bat takes values from the INI file and assigns them as variables for use in the game. An example of the INI file would be: [GameData] lastfile=expo lastsection=INTROGAME nextsection=SECTWO [PlayerData] held=none name=none lname=none` and lsdata.bat looks like for /f "delims=" %%a in ('call get.bat saves\%loadsave%.ini GameData lastfile') do ( set lastfile=%%a echo setting var lastfile... ) for /f "delims=" %%a in ('call get.bat saves\%loadsave%.ini GameData lastsection') do ( set lastsection=%%a echo setting var lastsection... ) for /f "delims=" %%a in ('call get.bat saves\%loadsave%.ini GameData nextsection') do ( set nextsection=%%a echo setting var nextsection... ) Et cetera. The file get.bat is the exact same as ini.bat from the second link I mentioned up there. The problem arises when recalling a modified save file. When creating a new save, lsdata.bat is called and everything runs smoothly (I can tell from the echoed lines of text that help me confirm the FOR loop was completed). However, when using a modified save file where all the values are not the defaulted ones, all of the FOR loops are skipped and the file skips to an ECHO and a CECHO I have at the bottom. If the save file is created and exited before the game has a chance to overwrite some values, everything is recovered as it should. If even one value has been changed, though, it skips all the FOR loops and the variables are all equal to NUL. When the game first loads, all variables are set to NUL for testing purposes, and then can be reassigned values when a new save is created or an old one is loaded. Delayed expansion is on, and if you try to call variables (with ! or %), it still shows them set equal to NUL. How can I prevent the modified files from causing this weird bug?
{ "language": "en", "url": "https://stackoverflow.com/questions/48134094", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Special IF/THEN Statement And Data Validation List In VBA The best way I can explain what I need is this: * *If A1 = "" and A3 = "", then put a data validation list in cell A2. *If A1 = "" and A3 <> "", then A2 = A3. *If A1 <> "" and A3 = "", then A2 = A1 *If A1 <> "" and A3 <> "", then A2 = A1 I know I'm leaving out a lot of information, but if anyone could write this in VBA Code where it automatically updates when A1 or A3 are changes, I would appreciate it. I already have a named range that I want to use for the Data Validation List. I am working in Excel 2016, but I need this to work with Excel 2010 as well. I know, quite literally, nothing when it comes to coding. Edit: If it were possible to write this in a formula in cell A2, it would go as follows: =if(and(A1="",A3=""),Named_Range,if(and(A1="",A3<>""),A3,if(and(A1<>"",A3=""),,A1,if(and(A1<>"",A3<>""),A1,"")))) Whereas "Named_Range" would make the cell a data validation list with the named range "Example 1". In every other instance, the data validation list would be deleted and would equal the respective cell. However, I know that this is not possible (I think) without using Worksheet Change in VBA Code. I am not familiar with writing VBA code, but I do know you can write If/Then statements and Data Validation Lists in VBA code. I just need to make that "Formula" in VBA Code in excel. A: For a non-coding solution you could add two additional rows (and swap row 2 & 3) to allow for the automation: Row 1: Values Row 2: Values Row 3: =if(and(A1="",A2=""),"SELECT FROM DROPDOWN BELOW",if(and(A1="",A2<>""),A2,if(and(A1<>"",A2=""),,A1,if(and(A1<>"",A2<>""),A1,"")))) Row 4: Dropdown list where the first option is blank "" Row 5: =IF(A3<>"SELECT FROM DROPDOWN BELOW", A3, IF(A4<>"",A4,"SELECTION NEEDED")) Much taller, but fits the given requirements.
{ "language": "en", "url": "https://stackoverflow.com/questions/53983102", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How to set a custom npm directory for global packages in Dockerfile? I've just read the best practices about Global npm dependencies and tried to utilize this approach in my Dockerfile: FROM node:carbon ... ENV NPM_CONFIG_PREFIX=/home/node/.npm-global ENV PATH="/home/node/.npm-global:${PATH}" ... RUN npm install -g nodemon ... CMD ["nodemon", "server.js"] USER node But when I try to start the container I get: ERROR: for my_project_node_1 Cannot start service my_project_node: OCI runtime create failed: container_linux.go:296: starting container process caused "exec: \"nodemon\": executable file not found in $PATH": unknown ERROR: for my_project_node Cannot start service my_project_node: OCI runtime create failed: container_linux.go:296: starting container process caused "exec: \"nodemon\": executable file not found in $PATH": unknown I just don't understand what I do incorrectly.. How to set PATH environment variable in a Dockerfile I get from here https://stackoverflow.com/a/38742545/202550
{ "language": "en", "url": "https://stackoverflow.com/questions/48541511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Common Lisp: Using (let) for evaluating recursive function So I wrote something that returns a maximal subset sum given a list of positive integers. However, I would like to use the (let) so that I make the code more efficient. I would like to know if or how that is possible. (defun subset-sum1 (numbers capacity) (subset-sum numbers capacity 0)) (defun subset-sum (numbers capacity counter) (cond ((null numbers) counter) ((= counter capacity) counter) ;; return if counter 'hits' the capacity ((< capacity (+ (car numbers) counter)) (subset-sum (cdr numbers) capacity counter)) ;; cdr if car branch exceeds capacity ((<= (subset-sum (cdr numbers) capacity counter) (subset-sum (cdr numbers) capacity (+ (car numbers) counter))) (subset-sum (cdr numbers) capacity (+ (car numbers) counter))) ;; choose car (t (subset-sum (cdr numbers) capacity counter)))) ;; choose cdr The above code works fine in common lisp. But, I would like to do something like below, because I feel like using let will make the code better. But what I wrote goes into an infinite loop :( This is an assignment for an introductory AI class... help out a novice please! (defun subset-sum (numbers capacity counter) (let ((exclude (subset-sum (cdr numbers) capacity counter)) (include (subset-sum (cdr numbers) capacity (+ (car numbers) counter)))) (cond ((null numbers) counter) ((= counter capacity) counter) ((< capacity (+ (car numbers) counter)) exclude) ((<= exclude include) include) (t (exclude))))) A: You get an infinite loop because of these lines: (defun subset-sum (numbers capacity counter) (let ((exclude (subset-sum (cdr numbers) capacity counter)) You keep calling subset-sum recursively, and it never terminates. Even when you get to the end of the list, and numbers is (), you keep going, because (cdr '()) is '(). You handled this in the original by checking (null numbers) (though it might be more idiomatic to use (endp numbers)). Now you can do something like: (defun subset-sum (numbers capacity counter) (if (endp numbers) counter (let ((exclude (subset-sum (cdr numbers) capacity counter)) ;... ) (cond ; ... ))))
{ "language": "en", "url": "https://stackoverflow.com/questions/30928241", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How does mmap interract with Go's garbage collector? Go has a garbage collector for slices that only frees the slice when all references to it are dead. It also has an Mmap function that returns a []byte that can be explicitly freed with Munmap(). So how does this work with Go's garbage collector. What happens if I do this? m := syscall.Mmap(...) m2 = m[10:100] syscall.Munmap(m) a = m2[0]
{ "language": "en", "url": "https://stackoverflow.com/questions/38438951", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to sort gridview item in flutter I know how to sort in listview while streaming from firebase by using orderBy properties, but when I try in in GridView.builder, it is not working. can any body please help final CollectionReference _productss = FirebaseFirestore.instance.collection('donation'); return StreamBuilder( stream: _productss .where('status', isEqualTo: "Approved")snapshots(), builder: (context, AsyncSnapshot<QuerySnapshot> streamSnapshot) { if (streamSnapshot.hasData) { return GridView.builder( itemCount: streamSnapshot.data!.docs.length, gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, mainAxisSpacing: kDefaultPaddin, crossAxisSpacing: 10, childAspectRatio: 0.75, ), itemBuilder: (context, index) {
{ "language": "en", "url": "https://stackoverflow.com/questions/73117678", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NivoSlider IE7 push my CPU to 100% even after fade effect finishes I am using NivoSlider to create a nice rotating banner animation. In particular, I am using the "fade" animation. It works well in all browsers except IE7. In IE7, when the fade out / fade in effect occurred, the CPU on my computer goes to 100% and stays there. In all other browser the CPU goes at 100% only while the effect is processing but goes back to a normal level afterwards. Do what can I do to resolve this issue?
{ "language": "en", "url": "https://stackoverflow.com/questions/8232606", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Overriding previously set CSS My css: .pic img:hover { border: 1px black solid; } My html: <div class="pic"> <img src="hey.jpg"> <img class="overlay" src="overlay.jpg"> </div> I have an "overlay.jpg" that is placed in the bottom corner of the first image. Problem with the css is that the overlay gets the :hover effect too. The actual code is very complicated, I know the best solution would be to add a class to the first image and hover only that, but that will take more time than what i currently have to get this fixed. The code has a class for the overlay images though, so I'm asking if theres a way to override the hover by setting some other css for the overlay class. However .overlay:hover { border: none; } does not do the trick, even if i put it after the css above. A: Your rule is less specific than the previous one so it is getting overridden. You have to change it to: .pic .overlay:hover { border: none; } The concept Specificity is the means by which a browser decides which property values are the most relevant to an element and gets to be applied. Specificity is only based on the matching rules which are composed of selectors of different sorts. How is it calculated? The specificity is calculated on the concatenation of the count of each selectors type. It is not a weight that is applied to the corresponding matching expression. In case of specificity equality, the latest declaration found in the CSS is applied to the element. Reference: Specificity A: As long as overlay always comes after the first image, you can use :first-child to pick only the first image: .pic img:first-child:hover { border: 1px black solid; } It's supported in everything (excluding IE6, but I don't count that as a thing.) A: You can also use the :not selector: .pic img:not(.overlay):hover { border: 1px black solid; } This way you won't have to worry about the order of the images and also don't have to worry about specificity by including another reset style.
{ "language": "en", "url": "https://stackoverflow.com/questions/26969904", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Reminder Email User for Password Expiration in AWS SES I am using AWS SES to send mail from my website (Using Laravel). I want to set password expiry reminder before expiring (SES) password. I have gone through some articles and documentation but did not get any solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/57309031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Installing Google Cloud SDK on Azure Web Apps I need to install https://cloud.google.com/sdk/ on my Azure Web App so we can execute > gcloud auth application-default loginand have our application running with communication between Google and Azure. How can I install https://cloud.google.com/sdk/ to the Azure Web App container? been looking for a command configuration (as in linux) but can't seem to find any info.
{ "language": "en", "url": "https://stackoverflow.com/questions/44711254", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Arrays in array How can I create an array with Ruby (on Rails) in this form: [[0,5], [1,5], [3,7]] Edit: I know how to define simple array and add some data: posts = Array[] # or Array.new posts << data.id # e.g. posts[1,2,3,4] BUT i wanna know how to add (push) data to the array that is more complexive like in first array [[],[]]. Try to understand me, please. :) A: num = [[0,5], [1,5], [3,7]] isn't working? A: There is a lot of ways to resolve your issue. You're looking for an array of arrays. I think you're confused by how an array can be inside an array. You should keep in mind that an array is just an ordered list of objects. So storing in array in each index is not as foreign as a concept as it may seem. A = [] #an empty array A[0] = [1, 2] A[1] = 1 A # => [[1,2], 1] If you want to initialize an array with a default value as an array try A = Array.new(2) {Array.new(2){0}} #This creates an array of size 2 with default values of arrays of size 2 with 0 in each entry. A[0][1] # returns 0 A[0] # returns [0, 0] A #returns [[0,0], [0,0]]
{ "language": "en", "url": "https://stackoverflow.com/questions/9436885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: Do bluetooth smart (4.0) provide the same services as plain old Bluetooth? What I want to ask is - Will a BLE device be able to answer calls, play music, etc... or that Bluetooth 4.0 is intended for a kind of NFC alternative? A: Bluetooth 4.0 has all backwards compatibility with it's older versions. BLE is a form of connect using low energy technology. BLE = Bluetooth Low energy. They are different technologies with different proposes. BLE tend to be used in heart rate monitors, bike computers, medicinal applications and etc. Whenever the power supply is limited. BLE intent is not for headsets and similar devices. That's why you see on phone specifications Bluetooh 4.0 + BLE (or LE). Bluetooh is a technology, BLE is a 'protocol of communication' A: Bluetooth Low Energy is part of the Bluetooth 4.0 specification. Bluetooth 4.0 includes Classic Bluetooth, Bluetooth Low Energy and Bluetooth High Speed. Bluetooth Low Energy (BLE) uses a different radio protocol with fewer, wider channels and a lower transmission rate and power than Bluetooth Classic (although it uses the same frequencies) and most importantly it implements a different set of profiles. Classic Bluetooth has profiles such as Serial Port Profile (SPP) and Handsfree Profile (HFP) while the most commonly used profile in BLE is the Generic Attribute profile (GATT). This profile allows for the transfer of small amounts of data at relatively low speeds and is not suitable high-bandwidth time-critical applications such as audio streaming. Dual-mode Bluetooth chipsets that support Classic Bluetooth and BLE are available although often they can only operate in one mode at a time. Many BLE chipsets are BLE only, however as it reduces cost and complexity. The short answer is that BLE can't support the classic Bluetooth functions you described.
{ "language": "en", "url": "https://stackoverflow.com/questions/31816103", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting textbox value from X-editable How do you get the value of the textbox field and send as data inside of ajaxOptions? I tested my view and it prints out the test variable successfully from my Django views. I am using X-editable for Jquery. Heres what textbox input looks like: http://jsfiddle.net/xBB5x/197/ views.py def create_post(request): print request.POST.get("test", ""); return HttpResponse(json,content_type="application/json") HTML <a id="other1" data-pk="First Name" data-name="test">First Name</a> AJAX $(document).ready(function() { $('#other1').editable({ type: 'text', pk: 1, url: '/create_post/', ajaxOptions: { data: { csrfmiddlewaretoken: '{{ csrf_token }}', test: "hi", }, }, placement: 'top', title: 'New Expense', success: function(response, newValue) { if(response.status == 'error') return response.msg; //ms }, }); }); A: Instead of ajaxOptions, use params. If I remember correctly, test and its value will be included in your POST request by x-editable. Try something like this: Html <a id="other1" data-pk="1" data-name="test">First Name</a> AJAX $(document).ready(function() { $('#other1').editable({ type: 'text', url: '/create_post/', params : function(params) { params.csrfmiddlewaretoken = '{{ csrf_token }}'; return params; }, placement: 'top', title: 'New Expense', success: function(response, newValue) { if(response.status == 'error') return response.msg; //ms }, }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/28083388", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Bit confused with cloudfront and why my cert for the CNAME is not working I am getting this message on my main site, after I setup a CloudFront distribution. I created a certificate for cdn.example.com, chose custom and entered cdn.example.com for use with HTTPS. I created a CNAME in my DNS configuration for cdn.example.com, and I added the validation record as requested by AWS. The certificate shows up as issued and validated. Failed to load resource: The certificate for this server is invalid. You might be connecting to a server that is pretending to be “cdn.example.com”, which could put your confidential information at risk. No images get loaded and the site does not render as it should. If I use the cloudfront url (i.e. d12345.cloudfront.net), all works fine. Do I need to add a SAN to my certificate, such as the main domain (i.e. example.com) in addition to cdn.example.com? If so, how does that work as I already use a SSL certificate for my www.example.com and example.com from Let's Encrypt. I am using WordPress and wpfastestcache to integrate CloudFront with the website, where I specified cdn.example.com and the origin as example.com. A: This question was confusing, since it seemed to describe a very unlikely condition. How could a newly-configured CloudFront distribution with a new certificate from ACM offer an invalid certificate? In truth, I was distracted by part of the "helpful" browser error message, "You might be connecting to a server that is pretending to be..." I mistakenly assumed that this implied that the hostname in the certificate was correct ("pretending to be") but that the certificate was invalid for some other reason. As it turns out, the certificate being offered was the default, generic *.cloudfront.net certificate, so the hostname in the cert didn't match the custom domain name. After creating a certificate in ACM, it needs to be associated with the CloudFront distribution, as mentioned at https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesSSLCertificate. Another hint to the nature of the problem would have been observable in the ACM console. There, the certificate would have shown In Use? No. In Use? – Whether the ACM Certificate is actively associated with an AWS service such as Elastic Load Balancing or CloudFront. The value can be No or Yes. https://docs.aws.amazon.com/acm/latest/userguide/gs-acm-list.html#gs-acm-list-console
{ "language": "en", "url": "https://stackoverflow.com/questions/53053751", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Upload file to drive with reactjs and nextjs I am using this https://github.com/rpldy/drive-uploady to update files but this library only shows an example where you have to upload files from local. If i have a file (base64 url) or a blob (which i get from a pdf file i got from google drive before) how can i use this. I have tried multiple resource but no thing can give me result. Here: https://github.com/rpldy/react-uploady/tree/master/packages/ui/uploady A: Drive-Uploady is mainly a sender for Uploady. Therefore, you are able to use most of Uploady's functionality. In this case, the upload context method - import React from "react"; import DriveUploady, { useUploady } from "drive-uploady"; const MyButton = () => { const { upload } = useUploady(); const onUpload = async () => { const myBlob = await getBlobFromSomewhere(); upload(myBlob); }; return <button onClick={onUpload}>Upload</button> }; const App = () => { return <DriveUploady ... > <MyButton /> </DriveUploady> }; This will initiate the upload process once the button is clicked. Where you get the blob is your responsibility of course.
{ "language": "en", "url": "https://stackoverflow.com/questions/71674853", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Angular 5 view not displaying updated property value after initial change My view isn't showing the updated property value of a local property, bound model property, nor a value from observable. Logging from console shows all the values are updated. This is a multi-step form and works great with exception of this annoying issue: The first time I click on booth, clickBooth(e) is fired as expected and the view updates with the value. I click on another booth to 'add' it, all the same code fires, but the view doesn't reflect the new updated value of selectedboothlabels or newbookingform.booths Move on in the form, (using a continue button that fires a 'changeStep' method), then go back to this particular section of the form, the correct values of selectedboothlabels and newbookingform.booths are displayed in the view. Tried so many things. I think I'm running in circles now. This is the latest of many versions of code: Service: import { Injectable } from '@angular/core'; import { Subject } from 'rxjs/Subject'; import { Observable } from 'rxjs'; @Injectable() export class SelectedBoothService { public boothlist = new Subject<string[]>(); setBoothList(value: string[]) { this.boothlist.next(value); } getBoothList(): Observable<any> { return this.boothlist.asObservable(); } } Relevant from View (very, very simplified): {{selectedboothlabels}}<br> {{newbookingform.booths}} NOTE: I tried binding newbookingform.booths (which is part of the BookingForm ngModel on a form) to a simple text input. However the value is NOT updated through the input, so don't believe this does anything. Relevant Code from Component: import { SelectedBoothService } from '../../services/selectedbooths.service'; import { Subscription } from 'rxjs/Subscription'; import { BookingForm } from '../../models/booking.interface'; @Component({ selector: 'reserve-booth', templateUrl: './reserve-booth.component.html' }) export class ReserveBoothComponent implements OnInit { selectedboothlabels: string[] = []; boothlistsubscription: Subscription; newbookingform: BookingForm = new BookingForm(); constructor( private _changedetector: ChangeDetectorRef, private _selectedboothService: SelectedBoothService) { this.boothlistsubscription = this._selectedboothService.getBoothList().subscribe(list => { console.log("Subscribing to the boothlist: " + list); //shows most recent values perfectly this.selectedboothlabels = list; this._changedetector.markForCheck(); //no affect... }); } //fired from an custom component. Works great. clickBooth(e) { let boothindex = -1; let targetid = e.currentTarget.id; //check our list of selectedbooths. if (this.selectedboothlabels != undefined) { boothindex = this.selectedboothlabels.indexOf(targetid); } if (boothindex == -1) { //add to our list this.selectedboothlabels.push(targetid); boothindex = this.selectedboothlabels.indexOf(targetid); this.newbookingform.booths = this.selectedboothlabels; this._selectedboothService.setBoothList(this.selectedboothlabels); } else { //already here. Remove it. this.selectedboothlabels.splice(boothindex, 1); this.newbookingform.booths = this.selectedboothlabels; this._selectedboothService.setBoothList(this.selectedboothlabels); boothindex = this.selectedboothlabels.indexOf(targetid); } this._changedetector.detectChanges(); //seems to have no affect } }
{ "language": "en", "url": "https://stackoverflow.com/questions/51252616", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there (and what are) a differences in developing in html5 and by using phonegap? What is the difference if we develop android apps in pure html5 without using phonegap libraries and what if we use Phonegap? This might sound noob but I'm really not getting the connection between these two? Why do I need phonegap? Why not just creating html5 files and provide the path to it ? A: PhoneGap give you a layer of abstraction so that you app is going to have access to non browserView accessible functionality like the camera for example. And those will be the same on all mobile plateforme. A: You can create application with pure html5 with webview and piece of java methods used to handle mobile events like Calling, Messaging, Sensors, etc,. When you are using phonegap libraries, no need to do much work with java methods. The phonegap libraries will handle the java and you can only work with html5 and java script with little bit help of jquery mobile framework. All mobile events you can call directly in the javascript of html page. A: Using HTML5 and PhoneGap you can implement different kinds of applications: * *Mobile applications using HTML5. You will need a server to back up your application and the users will run it through the device's browser. *Native application using HTML5 and WebView. Using a server isn't necessary. In this case you write HTML5 code (HTML, CSS, Javascript) and you use a WebView to display it. You can interact with Java using a special interface. *PhoneGap makes the above case easier. You don't need to know the details of WebView. You need PhoneGap APIs to interact with the phone's resources. As an added bonus you can easily port the application to other platforms. PhoneGap also creates native applications.
{ "language": "en", "url": "https://stackoverflow.com/questions/12173182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: why does height: auto not provide content area large enough to fit my content? When a user is logged out, the header shows a logo and a log-in form, which the header needs to be large enough to accommodate. When a user logs in, they see the full navigation on a header that no longer needs to be quite so large. I'd think that setting height:auto to "site-header" would accomplish this, but this just makes the form float over the header's bottom border. html: <header> <div class="site-header"> <%= link_to full_title(yield(:title)), root_path, class: "logo" %> <nav> <% if user_signed_in? %> <%= link_to "Sell", new_item_path %> <%= link_to "FAQ", pages_faq_path %> <%= link_to "Settings", edit_user_registration_path %> <%= link_to "Log out", destroy_user_session_path %> <% end %> </nav> <div class="log-in"> <% if !user_signed_in? %> <%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %> <div class="form"> <%= f.label :email %><br /> <%= f.email_field :email, autofocus: true, class: 'peach' %> </div> <div class="form"> <%= f.label :password %><br /> <%= f.password_field :password, autocomplete: "off", class: 'peach' %> <%= f.submit "LOG IN", class: 'button-functional' %><br> <%= render "devise/shared/forgotpass" %> </div> <% end %> <% end %> </div> </div> </header> css: header { background-color: white; top: 0; left: 0; right: 0; z-index: 0; border-bottom: 1px dashed black; .site-header { margin: 0 2em; padding: 1em 0; height: auto; nav { float: right; a { margin-right: 2em; } a:last-child { margin-right: 0; } } .log-in { float: right; .form { float: left; } input { margin-right: 1em; } } } } A: I made a Plunker with your example and it does fill the space. https://plnkr.co/edit/QMiHzA89NZrDkpsrCefF HTML <header> <div class="site-header"> <%= link_to full_title(yield(:title)), root_path, class: "logo" %> <nav> <% if user_signed_in? %> <%= link_to "Sell", new_item_path %> <%= link_to "FAQ", pages_faq_path %> <%= link_to "Settings", edit_user_registration_path %> <%= link_to "Log out", destroy_user_session_path %> <% end %> </nav> <div class="log-in"> <% if !user_signed_in? %> <%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %> <div class="form"> <%= f.label :email %><br /> <%= f.email_field :email, autofocus: true, class: 'peach' %> </div> <div class="form"> <%= f.label :password %><br /> <%= f.password_field :password, autocomplete: "off", class: 'peach' %> <%= f.submit "LOG IN", class: 'button-functional' %><br> <%= render "devise/shared/forgotpass" %> </div> <% end %> <% end %> </div> </div> </header> CSS header { background-color: white; top: 0; left: 0; right: 0; z-index: 0; border-bottom: 1px dashed black; .site-header { margin: 0 2em; padding: 1em 0; height: auto; nav { float: right; a { margin-right: 2em; } a:last-child { margin-right: 0; } } .log-in { float: right; .form { float: left; } input { margin-right: 1em; } } } } Maybe you have some other CSS messing around.
{ "language": "en", "url": "https://stackoverflow.com/questions/37535993", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why 'return' is not working in generator method? def function(list): for x in list: yield x return 4 list = [1,2,3] object = function(list) print(next(object)) print(next(object)) print(next(object)) print(next(object)) In this code when I'm calling function for the 4th time I'm getting error. But when I replace return 4 to yield 4 then it's working properly. Why that's happening? On the 4th call the for loop get exited and next line return 4 executed. Then what's the problem? A: If you want to yield, and prematurely exit the function, you can use a bare return after you yielded: def function(ls): for x in ls: yield x yield 4 return some_code(that_wont, be_executed) Generators don't return values, they yield them. The only reason to use return in a generator is to abort the execution / raise a StopIteration to signal to the caller that there are no more values.
{ "language": "en", "url": "https://stackoverflow.com/questions/62532796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Do not refresh Inner Update Panel in asp.net I am using 2 Update Panel in Asp.net. Second Update Panel is inside main Update Panel. It is like as below : <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional"> <ContentTemplate> <asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional"> <ContentTemplate> // Google Map... </ContentTemplate> </asp:UpdatePanel> </ContentTemplate> </asp:UpdatePanel> UpdatePanel1 contains Dropdown and It is Autupostback=true so if user selects any Dropdown then it refreshs Google Map which is inside. I do not want to refresh inside Update Panel anyway. Is it possible to do this ? A: People often misunderstand the way UpdatePanel works. They mistakenly think that, there's no page reload when anything triggering postback occurs inside an UpdatePanel. This is totally wrong. In fact a full page reload is taken place. It's not a coincidence that UpdatePanel is located under category called AJAX controls of the toolbox. But it does not work the same as AJAX does, it just imitates it. What you get when you use UpdatePanel is that the page does not flicker to the top of the page, which is the normal behavior of any full page reload, so you get a feeling of partial refresh. That's why, the Google Maps you're talking about gets refreshed. Using real AJAX will help you do just what you want. Jquery library has a very convenient way of doing AJAX. Or you can just use plain javascript.
{ "language": "en", "url": "https://stackoverflow.com/questions/27502597", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I open default browser to home page in C#? The question below has the answer to "How do I open the default Browser to a URL in C#?" But how do I open the default browser in C# without navigating to a URL? Desired behavior is for the default browser to open to the home page, or use the startup behavior (for example, defined in the Firefox option "When Firefox starts"). How to open in default browser in C# A: This should do it: Process p = new Process(); p.StartInfo = new StartInfo(url) {UseShellExecute = true}; p.Start(); EDIT: This will work for a valid URL. As the comment above say this will not work for http://about:home. EDIT #2: I will keep the previous code in case it's helpful for anybody. Since the comment above I've been looking how to do it, and in deed was not so trivial, this is what I did in order to launch the default browser without navigating to any URL. using (var assoc = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice")) { using (var cr = Registry.ClassesRoot.OpenSubKey(assoc.GetValue("ProgId") + @"\shell\open\command")) { string loc = cr.GetValue("").ToString().Split('"')[1]; // In windows 10 if Microsoft edge is the default browser // loc=C:\Windows\system32\LaunchWinApp.exe, so launch Microsoft Edge manually // 'cause didn't figured it out how to launc ME with that exe if (Path.GetFileNameWithoutExtension(loc) == "LaunchWinApp") Process.Start("explorer", @"shell:Appsfolder\Microsoft.MicrosoftEdge_8wekyb3d8bbwe!MicrosoftEdge"); else Process.Start(loc); } } I tested it in my machine (Win10) and worked out for every default browser switch. Hope it helps now.
{ "language": "en", "url": "https://stackoverflow.com/questions/43376033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Executing arbitrary javascript from Android WebView callback/interface I have set up a very simple javascript implementation using Android's WebView: index.html <!DOCTYPE html> <html> <head> <title></title> <script type="text/javascript" charset="utf-8" src="Test.js"></script> </head> </html> MyJavaScript.java public class MyJavaScript { public MyJavaScript() { // create the WebView mWebView = new WebView(mContext); // enable javaScript WebSettings webSettings = mWebView.getSettings(); webSettings.setJavaScriptEnabled(true); // add javaScript interface mWebView.addJavascriptInterface(new JavaScriptTest, "_test"); // load our dummy page mWebView.loadUrl("file:///android_asset/javascript/index.html"); } public void exec(String script) { mWebView.loadUrl("javascript:" + script); } } Test.js function Test() { }; Test.prototype.foo = function() { window._test.foo(); }; Test.prototype.bar = function() { window._test.bar(); }; var test = new Test(); JavaScriptTest.java public class JavaScriptTest { public void foo() { Log.d("Test", "foo"); } public void bar() { Log.d("Test", "bar"); } } When a caller calls something like: MyJavaScript.exec("foo();"); Execution is ultimately propagated to JavaScriptTest.foo(). This execution is in the WebView's worker thread. What I would like to do in JavaScriptTest.foo(), is something like eval("bar();");. I basically want to synchronously execute more javascript from the java callback/interface. That is, I want the javascript bar() method to fully execute before returning to JavaScriptTest.foo(). I can not figure out how to do this. If I back up one layer, it is trivial to call bar(); from the foo method in Test.js. However, this doesn't really meet my needs. I need to be able to execute arbitrary javascript discovered by JavaScriptTest.foo() within JavaScriptTest.foo(). And because JavaScripTest.foo() is executing in the WebView's worker thread, passing the arbitrary javascript discovered by JavaScriptTest.foo() to WebView.loadUrl(...) won't work because you need call that API from the UI thread. Ideally there would be a way to execute some arbitrary javascript while in the java callback/interface stub which is executing in WebView's worker thread. I can probably solve the problem by passing the arbitrary javascript back to foo() in Test.js, but it would be a less generic and uglier solution than my first choice. If my first choice doesn't exist, then I don't have an option. A: Because of the threading requirements of the WebView, I don't think that you can achieve what you want I'm afraid. The only way to start a new javascript execution in Java from the background thread would be to post a task back to the UI thread, but that break your synchronous needs. I think your only option is to have the Java object return a String back to your JavaScript and then eval it (as you are suggesting, I think). A: You could modify your JavaScriptTest interface to return the javascript you want to evaluate. public class JavaScriptTest { public String foo() { return "bar();" } public void bar() { Log.d("Test", "bar"); } } Then in your javascript: function Test() { }; Test.prototype.foo = function() { eval(window._test.foo()); }; Test.prototype.bar = function() { window._test.bar(); }; var test = new Test(); You wouldn't have bar() evaluated before returning but you could do it immediately afterwards.
{ "language": "en", "url": "https://stackoverflow.com/questions/22236313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: mysql: UNION GROUP BY without subquery I have a problem. I want to wrap a query into a view. For this I have to transform the subqueries inside the FROM. My query is this: SELECT b.id, b.summe, getBauNrKomplett(b.id) as bauNrKomplett, b.parent_id FROM ( SELECT pt.id, pt.parent_id, SUM(m.menge*p.preis_kostenanschlag) as summe FROM menge m join projektposition p ON (m.projektposition_id=p.id) join positionstyp pt on (p.positionstyp_id=pt.id) GROUP BY pt.id UNION SELECT pt2.id, pt2.parent_id, null as summe FROM positionstyp pt2 ) b GROUP BY b.id I don't find another possility. I need to wrap the UNION statement because of the GROUP BY. Does someone can imagine another workaround? Thanks a lot and best regards, Tobias A: I beleive this is equal. If not - could you provide sqlfiddle with some data and explanation? SELECT pt.id, pt.parent_id, SUM(IF(m.menge IS NULL,0,m.menge*p.preis_kostenanschlag)) as summe, getBauNrKomplett(p.id) as bauNrKomplett, FROM positionstyp pt LEFT JOIN projektposition p ON (p.positionstyp_id=pt.id) LEFT JOIN menge m ON (m.projektposition_id=p.id) GROUP BY pt.id
{ "language": "en", "url": "https://stackoverflow.com/questions/30107916", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: DocuSign Carbon Copy Doesn't Receive Note I'm using DocuSign's API in an iOS application to sign documents. Everything is going fine, except for the Carbon Copy experience. I have two signers, with routing orders 1 and 2. Then, I have several CC recipients, all with routing order 3. When the document is signed, the CC recipients receive an email alerting them that the document was signed, but they don't receive the note they should be getting. I know I'm setting this property well: when the CC recipients have a routing order of 1 or 2, they receive an email with the note, and then they receive an email when the document is signed. How can I get my CC recipients to receive their email at the right point in time, with the note I want them to see? Here's the log from DocuSign: POST https://na2.docusign.net:8822/restapi/v2/accounts/6580857/envelopes Content-Length: 284777 Content-Type: application/json Connection: keep-alive Accept: application/json Accept-Language: en-US; q=1.0 Host: na2.docusign.net User-Agent: Sales/1.0(iPhone; iOS 9.3.2; Scale/2.00) X-DocuSign-Authentication: {"Username":"[email1]","Password":"[omitted]","IntegratorKey":"[omitted]"} X-DocuSign-SDK: Obj-C X-Forwarded-For: 69.74.21.33 X-SecurityProtocol-Version: TLSv1.2 X-SecurityProtocol-CipherSuite: ECDHE-RSA-AES256-GCM-SHA384 {"status":"sent","documents":[{"documentId":"1","documentBase64":"[omitted]","name":"Test Name"}],"emailSubject":"Subject","emailBlurb":"","recipients":{"signers":[{"email":"[email1]","routingOrder":"1","clientUserId":"1001","tabs":"[omitted]", recipientId":"1","name":"John Doe"},{"note":"This is a note that appears during the signing experience","tabs":"[omitted]","email":"[email2]","clientUserId":"1002","routingOrder":"2","recipientId":"2","name":"Jane Doe"}],"carbonCopies":[{"roleName":"Carbon Copy","routingOrder":"3","email":"[email3]","recipientId":"3","note":"This note does not appear in the email sent to the address.","name":"John Smith"}]}} 201 Created Content-Type: application/json; charset=utf-8 { "envelopeId": "f3421750-6884-4f84-a318-d4637151222c", "uri": "/envelopes/f3421750-6884-4f84-a318-d4637151222c", "statusDateTime": "2016-07-12T12:51:24.4870000Z", "status": "sent" } I notice that I'm leaving the email blurb section empty. Could this be a potential solution, or does that field's content get displayed to all parties involved in the signing? In practice, I need to be able to have several different notes for several CC recipients. As far as I know, this can be achieved on DocuSign's website, so I don't see why it couldn't be done through the API. A: In fact, it seems my problem was caused by a misunderstanding of DocuSign's API. The note field is designed to provide a note that only appears during the signing experience, while the "emailNotification":{"emailSubject":"TEST","emailBody":"TEST"} field is designed to do what I was trying to achieve.
{ "language": "en", "url": "https://stackoverflow.com/questions/38310829", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: A nil pointer is sent to chan, but a "non-nil" received package main import ( "fmt" "os/exec" ) func main() { errChan := make(chan error) go func() { var e *exec.Error = nil errChan <- e }() err := <-errChan if err != nil { fmt.Printf("err != nil, but err = %v\n", err) } } The output is weird: err != nil, but err = <nil> Try it here: http://play.golang.org/p/_iyh0m7O1a A: Note: This post is just to have a bit more insight into a potentially confusing problem. Using a channel of type error is the idiomatic way to send errors. Another way around this would be to change the channel signature and explicitly say that is a channel pointer to error instead of a channel of interface errors: package main import ( "fmt" "os/exec" ) func main() { errChan := make(chan *exec.Error) go func() { var e *exec.Error = nil errChan <- e }() err := <-errChan if err != nil { fmt.Printf("err != nil, but err = %v\n", err) } else { fmt.Printf("err == nil\n") } } http://play.golang.org/p/l6Fq8O0wJw A: The problem lies in that the value passed into the channel as a error interface is not nil, but rather a exec.Error pointer which points to nil. The program will behave correctly if you change: go func() { var e *exec.Error = nil if e == nil { errChan <- nil } }() This is the appropriate way to solve the problem because the idiomatic way to report that no error occurred is by passing a nil error interface. However, if you want to change the main instead (maybe because you use a third party package which makes the mistake of returning pointers set to nil), you will have to either do a type assertion to the specific type (*exec.Error) and then check if it is nil, or else use the reflect package. Example using reflect to check for nil: func IsNil(i interface{}) bool { // Check if it is an actual nil-value if i == nil { return true } v := reflect.ValueOf(i) switch v.Kind() { // Only the following kinds can be nil case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: return v.IsNil() } return false } Working example: http://play.golang.org/p/rpG1PVTwwM You can find a discussion about it here: https://groups.google.com/forum/#!topic/golang-nuts/QzVDKv7p0Vs
{ "language": "en", "url": "https://stackoverflow.com/questions/19316963", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Best way to get properties from html and use as global variable in Angular 2+ What is the best way to get properties from html and use as global variable in Angular 2+? index.html ... <script> window.properties = { 'variable1': 'string 1', 'variable2': 'string 2' }; </script> ... A: @Injectable() class MyGlobalService { properties$:Subject = new BehaviorSubject(); constructor() { this.properties.next(window.properties); } } @NgModule({ providers: [MyGlobalService], ... }) class AppModule() class MyComponent { constructor(private myGlobals:MyGlobalService) { myGlobals.properties$.subscribe(val => console.log(val)); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/43502654", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL join on one-to-many relation where none of the many match a given value Say I have two tables User ----- id first_name last_name User_Prefs ----- user_id pref Sample data in User_Prefs might be user_id | pref 2 | SMS_NOTIFICATION 2 | EMAIL_OPT_OUT 2 | PINK_BACKGROUND_ON_FRIDAYS And some users might have no corresponding rows in User_Prefs. I need to query for the first name and last name of any user who does NOT have EMAIL_OPT_OUT as one of their (possibly many, possibly none) User_Pref rows. SELECT DISTINCT u.* from User u LEFT JOIN User_Prefs up ON (u.id=up.user_id) WHERE up.pref<>'EMAIL_OPT_OUT' gets me everyone who has at least one row that isn't "EMAIL_OPT_OUT", which of course is not what I want. I want everyone with no rows that match "EMAIL_OPT_OUT". Is there a way to have the join type and the join conditions filter out the rows I want to leave out here? Or do I need a sub-query? A: I personally think a "where not exists" type of clause might be easier to read, but here's a query with a join that does the same thing. select distinct u.* from User u left join User_Prefs up ON u.id = up.user_id and up.pref = 'EMAIL_OPT_OUT' where up.user_id is null A: Why not have your user preferences stored in the user table as boolean fields? This would simplify your queries significantly. SELECT * FROM User WHERE EMAIL_OPT_OUT = false
{ "language": "en", "url": "https://stackoverflow.com/questions/3294306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Exception on "add_roles" function for discord.py I'm trying to add roles to users by listening for Reaction. Although it will succeed, there will always be errors after execution. I want to ask how to solve this problem? Codes there: @client.event async def on_raw_reaction_add(payload: discord.RawReactionActionEvent): if payload.message_id == 0000: guild: discord.Guild = client.get_guild(payload.guild_id) if payload.emoji.name == "someEmoji": role0: discord.Role = guild.get_role(1111) await payload.member.add_roles(role0) elif payload.emoji.name == "someEmoji": role1: discord.Role = guild.get_role(2222) await payload.member.add_roles(role1) Logs(With pysnooper): 19:50:26.101973 line 54 await member.add_roles(role1) 19:50:26.104641 return 54 await member.add_roles(role1) Return value:.. <Future pending> Starting var:.. payload = <RawReactionActionEvent message_id=1111...d=None> event_type='' member=None> Starting var:.. guild = <Guild id=1111 name='' shard_id=0 chunked=True member_count=0> Starting var:.. member = <Member id=00000 name='member'> Starting var:.. role1 = <Role id=11111 name='role1'> 19:50:26.588117 call 54 await member.add_roles(role1) 19:50:26.590784 exception 54 await member.add_roles(role1) Exception:..... StopIteration [2022-12-20 19:50:26] [ERROR ] discord.client: Ignoring exception in on_raw_reaction_remove Traceback (most recent call last): File "C:\Users\****\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 409, in _run_event await coro(*args, **kwargs) File "main.py", line 54, in on_raw_reaction_remove await member.remove_roles(en_role) File "C:\Users\****\AppData\Local\Programs\Python\Python38\lib\site-packages\pysnooper\tracer.py", line 367, in __exit__ start_time = self.start_times.pop(calling_frame) KeyError: <frame at 0x000001A1014E6DD0, file 'main.py', line 54, code on_raw_reaction_remove>
{ "language": "en", "url": "https://stackoverflow.com/questions/74862938", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Tablelayout with massive data android What is the best way to create a table layout or recyclerview/listview/gridview in android that can pull a lot of data around 1000 rows and around 50 columns each row without to crash ? I want to show it like excel sheet nothing special just show data of course with scrolling both ways. A: TableFixHeaders project on github has an implementation with both Adapter an Recycling of views, plus handles scrolling wery nicely. And is quite easy to modify to suit your needs. This is not so uncommon request, so it has been done numerous times. I am sure you can find other implementations if this one is not right for you. A: I saw a similar question on SO a few months ago, and I was interested to see if I could develop a solution. My concept was to start with a ListView for vertical scrolling and view recycling. Each list item is a HorizontalScrollView to show a table row with many columns. The trick here is to listen to each HorizontalScrollView for swipe events and then scroll every HorizontalScrollView in sync with the view being swiped. I have a proof-of-concept project on Github here: klarson2/android-table-test Downsides: The project was set up for Eclipse, so you can't open it directly with Android Studio. There is still a small bug with event handling that I haven't got around to fixing. Another limitation is that each cell view in the horizontal LinearLayout must be a fixed size so that the columns will line up correctly. However, the example uses a 4MB .csv file with 50 columns and over 10,000 rows for a data source proving that it is possible to display an enormous table in an Android app with responsive two-way scrolling.
{ "language": "en", "url": "https://stackoverflow.com/questions/31620052", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to get a page not redirect to the main I'm absolute beginner at JSP and Spring framework and annotations. I've built a standard CRUD application, but have one issue. Whenever i want add, edit or delete a user, application redirects me to main "user" page, if i'm on a page, with an index more than 1. How can i make it stay still on a page, where i do all actions above? For example, when i want to edit "Tom Hanks"(14, page number 2) It redirects me to the 1st page But i want it to be still on the same page, where i add, edit or delete UserController class is below @Controller public class UserController { private UserService userService; @Autowired public void setUserService(UserService userService) { this.userService = userService; } @RequestMapping(value = "users", method = RequestMethod.GET) public String listUsers(@RequestParam(value="page", required = false) Long page, Model model) { if (null == page) page = 1L; model.addAttribute("user", new User()); model.addAttribute("searcheduser", new User()); model.addAttribute("listUsers", userService.getUsers(page)); model.addAttribute("page", page); return "users"; } @RequestMapping(value = "/users/add", method = RequestMethod.POST) public String addUser(@ModelAttribute("user") User user) { if(user.getId() == 0) userService.addUser(user); else { userService.updateUser(user); } return "redirect:/users"; } @RequestMapping("/remove/{id}") public String removeUser(@PathVariable("id") int id) { userService.removeUser(id); return "redirect:/users"; } @RequestMapping("edit/{id}") public String editUser(@PathVariable("id") int id, @RequestParam(value="page", required = false) Long page, Model model) { if (null == page) page = 1L; model.addAttribute("user", userService.getUser(id)); model.addAttribute("searcheduser", new User()); model.addAttribute("listUsers", userService.getUsers(page)); model.addAttribute("page", page); return "users"; } @RequestMapping("userdata/{id}") public String userData(@PathVariable("id") int id, Model model) { model.addAttribute("user", userService.getUser(id)); return "userdata"; } @RequestMapping(value="searchresults", method = RequestMethod.POST) public String searchResults(@ModelAttribute("searcheduser") User user, Model model) { List<User> searchResult = userService.getUsers(user.getName()); model.addAttribute("listUsers", searchResult); return "searchresults"; } } A: Add the page as a parameter on redirect for remove and edit : @RequestMapping("edit/{id}") public String editUser(@PathVariable("id") int id, @RequestParam(value="page", required = false) Long page, Model model) { if (null == page) page = 1L; model.addAttribute("user", userService.getUser(id)); model.addAttribute("searcheduser", new User()); model.addAttribute("listUsers", userService.getUsers(page)); model.addAttribute("page", page); return "redirect:/users?page="+page; } The same for remove .
{ "language": "en", "url": "https://stackoverflow.com/questions/44864186", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to save a file name in my DB when I download or add a file into my local machine download folder in Laravel. any idea for this thing I want to save a file name into DB when it is downloaded or added into my local system folder.How can I perform this logic. any idea..... thanks for advance A: you could just use the php function glob() to get all filenames from the download directory. then setup a cronjob for every 5m or whatever interval you want where you save the names to your database.
{ "language": "en", "url": "https://stackoverflow.com/questions/47611166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: date format is not working monthpicker I have a month picker in my form in laravel 4.2. While changing the month, the month and year are shown like 05/2015. But i need it to be in the format May, 2015. {{ HTML::style('public/asset/css/smoothness/jquery-ui.css') }} {{ HTML::style('public/asset/css/MonthPicker.css') }} {{ HTML::script('http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js') }} {{ HTML::script('http://code.jquery.com/ui/1.10.2/jquery-ui.js') }} {{ HTML::script('public/asset/js/MonthPicker.min.js') }} {{ HTML::script('public/asset/js/MonthPicker.js') }} Query(document).ready(function() { $("#SearchVal").val(''); var currentYear = (new Date).getFullYear(); var _picker = jQuery('#SearchVal').MonthPicker({ ShowIcon: false }); A: You can do that manually on change event : var monthsLabels = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] var picker = jQuery('#SearchVal').MonthPicker({ ShowIcon: false, OnAfterChooseMonth: function(){ var elts = picker.val().split('/'); picker.val(monthsLabels[parseInt(elts[0])-1]+', '+elts[1]); } }); jsFiddle A: hello bro try to see this will help you it's about Datepicker
{ "language": "en", "url": "https://stackoverflow.com/questions/30343177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Google Apps Script: Server error occurs when using a UiApp and a server handler in new sheets AND there is a library I converted my sheets from the old to the new sheets as the code started creating sheets in the new version which was causing it to fail. After converting, I am now getting another error which I cannot find a solution for. The error seems to be when using UiApp which calls a server handler and there is a library attached to the project. The error occurs even when there is no code in the library. The error occurring is: Server Error: We're sorry, a server error occurred. Please wait a bit and try again. Steps to reproduce (1). Create 2 new sheets, use one as the library and one as the test sheet (2). In the library, add a new version to the project then add the project as a library in the test sheet. There should be no code in the library (doesn't really matter either way). (3). In the test sheet, add the following code: function test() { var ss = SpreadsheetApp.getActiveSpreadsheet(); var app = UiApp.createApplication(); // create a button and handler var buttonHandler = app.createServerHandler("buttonTest"); var button = app.createButton("Button Test"); button.addClickHandler(buttonHandler) app.add(button) ss.show(app); // Display the app } function buttonTest(e) { // nothing here is executed } (4). Run the test code The following error is displayed: Server Error: We're sorry, a server error occurred. Please wait a bit and try again. If the library is removed then it will run as expected A: The UiApp is deprecated. That would be creating the server error. Sometimes the UiApp functions still work (like the chart service) but the output crashes. The googlescript library functionality should still work. https://developers.google.com/apps-script/reference/ui/ui-app?hl=en The html service should be a replacement for the UiApp but unfortunately it does not cover all the same functionality. https://developers.google.com/apps-script/guides/html/
{ "language": "en", "url": "https://stackoverflow.com/questions/23506240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to split/cut till specific path (directory path )of string in perl Input : "/abcd/prod/Cid/1234/Did" or "/abcd/prod/Cid/1234/Did/Pid/234" Output: "/abcd/prod/Cid/1234/" (Only till 4th word, considering '/' is the delimiter) How to slice and get above using perl A: As one-liner : $ perl -F'/' -lane 'print join "/", @{F[0..4]}' <<< "/abcd/prod/Cid/1234/Did" As a script : while (<>) { chomp $_; my @F = split(m[/], $_, 0); print join('/', @F[0..4]), "\n"; }  Output : /abcd/prod/Cid/1234
{ "language": "en", "url": "https://stackoverflow.com/questions/59361600", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Subscripting a string in Javascript I have a data in the object section_data.title and i am trying to use str.sup() where str=section_data.title; and str holds following data: str="Not less than 30 net ft2 (2.8 net m2) per patient in a hospital or nursing home, or not less than 15 net ft2 (1.4 net m2) per resident in a limited care facility, shall be provided within the aggregated area of corridors, patient rooms, treatment rooms, lounge or dining areas, and other similar areas on each side of the horizontal exit. On stories not housing bed or litterborne patients, not less than 6 net ft2 (0.56 net m2) per occupant shall be provided on each side of the horizontal exit for the total number of occupants in adjoining compartments." Now I want to add superscript for the bold words indicated above (e.g ft2). How can I do this using str.sup() or are there any other alternative method to do so in javascript? Or any other tricks? A: String in javascript is not formatted. You can only do that when you output to HTML. So basically you must write it like this var str = "Not less than 30 net ft<sup>2</sup> (2.8 net m<sup>2</sup>)"; document.write(str); You can do a find and replace for all string contain ft2 and m2 turn them into ft<sup>2</sup> and m<sup>2</sup> str.replace(/ft2/g,"ft<sup>2</sup>"); //But it not safe...
{ "language": "en", "url": "https://stackoverflow.com/questions/15916662", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to apply constraint by Stored procedures that ID should start with 'E' and has 2 numerics aftarwards? EID should only be inserted if it starts with 'E' and has 2 numerics aftarwards .... i was trying to write a procedure for the purpose like: create proc emp_checks(@eid varchar(20), @name varchar(20),@age int, @salary int, @city varchar(20)) AS Begin Declare @citycount int= (select count(*) from employee where @city=city) if (@citycount < 2 and @eid like 'E--%') insert into employee values(@eid,@name,@age,@salary,@city) else print 'city exceeded' End here the issue is that -- or spaces would insert non-numerics also here this code also includes few extras *just homework things :) A: Why would you write a stored procedure? MySQL now supports check constraints: alter table employee add constraint chk_employee_eid check (eid regexp '^E[0-9]{2}') Note that this allows anything after the first 3 characters. If you don't want anything, then add $ to the pattern: alter table employee add constraint chk_employee_eid check (eid regexp '^E[0-9]{2}$')
{ "language": "en", "url": "https://stackoverflow.com/questions/62824273", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: TCP messages - Durable and fast solution tips? We use Spring integration for TCP socket communication with the hardware. The client would be sending a sequence number to uniquely identify a message. My requirement is to store these sequence numbers part of the socket message and validate them for non repetitive sequence numbers. I went thru IdempotentReceiver, sounds like what i wanted. But I need a durable and faster mechanism to store it, before unexpected shutdown of service and use the in memory cache for retrieving the latest sequence number. Thank you in advance.! A: You can use PropertiesPersistingMetadataStore for idempotent receiver: The PropertiesPersistingMetadataStore is backed by a properties file and a PropertiesPersister. By default, it only persists the state when the application context is closed normally. It implements Flushable so you can persist the state at will, be invoking flush(). See more in its JavaDocs.
{ "language": "en", "url": "https://stackoverflow.com/questions/47001637", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Contentflow auto resize not working Im using: Contentflow 1.0.2 jquery 1.6.1 I'm trying use Contentflow using reflection and with maximum width/height so it covers all the screen without any scroll bar vertically or horizontally. This example shows exactly what I wanna do, but it uses ImageFlow (another plugin) http://themes.themegoods.com/keres_wp/?page_id=459 At this point my config is like this and everything works fine except that Contentflow doesn't resize when I change the browser size. var cf = new ContentFlow('contentFlow', { reflectionColor: "#000000", circularFlow: false, startItem: 0, fixItemSize: true, scaleFactor:1.5 });
{ "language": "en", "url": "https://stackoverflow.com/questions/21914167", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Numba and KeyboardInterrupt Exception conflict I'm having a problem compiling KeyboardInterrupt exception using Continuum Numba module. Here's my data acquisition code: @jit def lockinmeasurement(x): Measurement=np.empty((0,5)) XMeas=np.empty((0,2)) event_handler = LoggingEventHandler() observer = Observer() observer.schedule(event_handler, path_to_watch, recursive=True) observer.start() try: while x: SQData=pd.read_csv(path_to_watch,sep=',',skiprows=14) Temp=SQData['Temperature (K)'] Field=SQData['Field (Oe)'] XMeas=np.append(XMeas,[[time.clock(),lockin.x]],axis=0) Measurement=np.append(Measurement,[[a,b,c,d,e]]) p1.plot(XMeas,clear=True,label='Lockin X',pen='y') pg.QtGui.QApplication.processEvents() rd=pd.DataFrame(Measurement) rd.to_csv('fileout.csv',sep='\t',index=False) time.sleep(0.2) except KeyboardInterrupt: print('interrupted!') lockinmeasurement(True) The code compiles perfectly fine without '@jit', however when I'm trying to use numba it returns an error: Traceback (most recent call last): File "C:\Anaconda3\lib\site-packages\numba\bytecode.py", line 231, in next info = BYTECODE_TABLE[opcode] KeyError: 121 During handling of the above exception, another exception occurred: lockinmeasurement(True) File "C:\Anaconda3\lib\site-packages\numba\dispatcher.py", line 165, in _compile_for_args return self.compile(sig) File "C:\Anaconda3\lib\site-packages\numba\dispatcher.py", line 303, in compile flags=flags, locals=self.locals) File "C:\Anaconda3\lib\site-packages\numba\compiler.py", line 595, in compile_extra return pipeline.compile_extra(func) File "C:\Anaconda3\lib\site-packages\numba\compiler.py", line 316, in compile_extra raise e File "C:\Anaconda3\lib\site-packages\numba\compiler.py", line 311, in compile_extra bc = self.extract_bytecode(func) File "C:\Anaconda3\lib\site-packages\numba\compiler.py", line 303, in extract_bytecode bc = bytecode.ByteCode(func=self.func) File "C:\Anaconda3\lib\site-packages\numba\bytecode.py", line 333, in __init__ table = utils.SortedMap(ByteCodeIter(code)) File "C:\Anaconda3\lib\site-packages\numba\utils.py", line 109, in __init__ for i, (k, v) in enumerate(sorted(seq)): File "C:\Anaconda3\lib\site-packages\numba\bytecode.py", line 235, in next raise NotImplementedError(ts % tv) NotImplementedError: offset=80 opcode=0x79 opname=SETUP_EXCEPT Is there any way I can overcome this issue ? A: Thanks to Travis' innovation teams' efforts numba is a great and powerful tool for scientific computing. One shall however take a due care to use it where feasible and where jit-compilation can bring some fruit to our hard and fast lives. Numba Documentation states this explicitly, saying: 2.4.1.1. Constructs Numba strives to support as much of the Python language as possible, but some language features are not available inside Numba-compiled functions:- Function definition- Class definition- Exception handling (try .. except, try .. finally)- Context management (the with statement)- Comprehensions (either list, dict, set or generator comprehensions)- Generator delegation (yield from) The raise statement is supported in several forms: raise (to re-raise the current exception) raise SomeException raise SomeException(<arguments>): in nopython mode, constructor arguments must be compile-time constants Similarly, the assert statement is supported with or without an error message.
{ "language": "en", "url": "https://stackoverflow.com/questions/33108075", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Material sidenav causing problem with translate and flex css properties So, currently working with my electron app having a sidenav structure like this: <!-- main container --> <mat-drawer-container> <mat-drawer>parent sidenav</mat-drawer> <mat-drawer-content> parent content <mat-drawer-container> inside child container <mat-drawer>inside child sidenav</mat-drawer> <mat-drawer-content> inside child content <app-route>current problem occurs here</app-route> </mat-drawer-content> </mat-drawer-container> </mat-drawer-content> </mat-drawer-container> So, suppose at first route I'm having Html like this: <div class="box-empty-container"> <div class="box-empty-msg"> <div class="box-empty-logo"><span class="material-icons">info</span></div> <div class="box-empty-title">Nothing to show you here as your specified folders for checking music files are currently empty</div> <div class="box-empty-subtitle">Add new music search directories</div> </div> </div> Also scss: @mixin widthheight100{ width: 100%; height: 100% } .box-empty-container{ position: relative; @include widthheight100() ; .box-empty-msg{ position: absolute ; left: 50% ; top: 45% ; transform: translate(-50%, -50%); text-align: center; .box-empty-logo{ span.material-icons{ font-size: 2.5rem; } } .box-empty-title{ font-family: 'jost-bold'; font-size: 12pt; } .box-empty-subtitle{ font-family: 'jost-regular'; font-size: 10pt; } } I have tried to centralize div.box-empty-msg with both flex and translate method in scss and they are still not at center. When page loads this div is at center but when i open & close the sidenav it's position gets displaced form center. How can I solve this problem ? Edit: Currently changed the scss style to postion: absolute strategy. Link here for similar code in stackblitz. It seems to work fine in stackblitz but in my actual project when screen size is large or medium the div.box-empty-msg is actually shifted some distance away from center. Also I think somehow in my project the sidenav is pushing the div tag away from center. A: @ReneVanDerLende After thoroughly checking my project due to css properties set for mat-drawer-content as { width: 100% ; height: 100% } it interfered with the styles of box-empty-container, hence shifting that slightly towards right.
{ "language": "en", "url": "https://stackoverflow.com/questions/62953331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Variable assigned in dispatch block coming back null I'm trying to make a network call run in a background thread so it doesn't freeze my app while it's waiting. The call happens when I do: nextTime = [myObj getNextTime]; I do an NSLog as soon as I get it, and that one works. However, when I'm outside of the dispatch block, the same NSLog prints out null. myObj *current = ((myObj *)sortedArray[i]); __block NSString *nextTime; dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul); dispatch_async(queue, ^{ nextTime = [myObj getNextTime]; NSLog(@"inside%@",nextTime); dispatch_sync(dispatch_get_main_queue(), ^{ }); }); NSLog(@"outside%@",nextTime); Any ideas why the outer log is printing null? Am I doing something horribly wrong and I just missed it? Thanks! A: That's because you're setting it inside an asynchronous block, and asynchronous blocks return immediately. If you look at the time stamps of the two logs, you'll see that the outer log is actually being posted before both the inner log, and the setting of the variable. From the GCD docs on dispatch_async(): This function is the fundamental mechanism for submitting blocks to a dispatch queue. Calls to this function always return immediately after the block has been submitted and never wait for the block to be invoked. The target queue determines whether the block is invoked serially or concurrently with respect to other blocks submitted to that same queue. Independent serial queues are processed concurrently with respect to each other. A: Your "outside" NSLog statement should actually go in that inner dispatch_async block that is set to run on the main thread, because that block will execute after you've set the value of nextTime. Any code you place below your asynchronous block call will likely execute way before the code inside the block.
{ "language": "en", "url": "https://stackoverflow.com/questions/21763364", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Trying to remove duplicates from large list of objects, keep certain one I have a large list of objects in Python that I'm storing in a text file (for lack of knowledge of how to use any other database for the present). Currently there are 40,000 but I expect the list length eventually may exceed 1,000,000. I'm trying to remove duplicates, where duplicates are defined as different objects having the same value for a text string attribute, but keep the most recent version of that object (defined as having the highest value in another attribute). What I want to make is a function that returns only objects 2 and 3 from the following list, reliably: Object 1: text="hello" ID=1 Object 2: text="hello" ID=2 Object 3: text="something else" ID=3 Doing this manually (looping through the list each time for each object) is too slow already and will get slower with O(l^2), so I need a smarter way to do it. I have seen hashing the objects and using the set function recommended multiple times, but I have two questions about this that I haven't found satisfactory answers to: * *How does hashing improve the efficiency to the degree it does? *How can I do this and retain only the most recent such object? The examples I have seen all use the set function and I'm not sure how that would return only the most recent one. EDIT: I can probably find good answers to question 1 elsewhere, but I am still stuck on question 2. To take another stab at explaining it, hashing the objects above on their text and using the set function will return a set where the objects chosen from duplicates are randomly chosen from each group of duplicates (e.g., above, either a set of (Object 2, Object 3) or (Object 1, Object 3) could be returned; I need (Object 2, Object 3)). A: change to using a database ... import sqlite3 db = sqlite3.connect("my.db") db.execute("CREATE TABLE IF NOT EXISTS my_items (text PRIMARY KEY, id INTEGER);") my_list_of_items = [("test",1),("test",2),("asdasd",3)] db.execute_many("INSERT OR REPLACE INTO my_items (text,id) VALUES (?,?)",my_list_of_items) db.commit() print(db.execute("SELECT * FROM my_items").fetchall()) this may have maginally higher overhead in terms of time ... but you will save in RAM A: Hashing is a well-researched subject in Computer Science. One of the standard uses is for implementing what Python calls a dictionary. (Perl calls the same thing a hash, for some reason. ;-) ) The idea is that for some key, such as a string, you can compute a simple numeric function - the hash value - and use that number as a quick way to look up the associated value stored in the dictionary. Python has the built-in function hash() that returns the standard computation of this value. It also supports the __hash__() function, for objects that wish to compute their own hash value. In a "normal" scenario, one way to determine if you have seen a field value before would be to use the field value as part of a dictionary. For example, you might stored a dictionary that maps the field in question to the entire record, or a list of records that all share the same field value. In your case, your data is too big (according to you), so that would be a bad idea. Instead, you might try something like this: seen_before = {} # Empty dictionary to start with. while ... something : info = read_next_record() # You figure this out. fld = info.fields[some_field] # The value you care about hv = hash(fld) # Compute hash value for field. if hv in seen_before: print("This field value has been seen before") else: seen_before[hv] = True # Never seen ... until NOW! A: Could use a dict with the text as key and the newest object for each key as value. Setting up some demo data: >>> from collections import namedtuple >>> Object = namedtuple('Object', 'text ID') >>> objects = Object('foo', 1), Object('foo', 2), Object('bar', 4), Object('bar', 3) Solution: >>> unique = {} >>> for obj in objects: if obj.text not in unique or obj.ID > unique[obj.text].ID: unique[obj.text] = obj >>> unique.values() [Object(text='foo', ID=2), Object(text='bar', ID=4)]
{ "language": "en", "url": "https://stackoverflow.com/questions/35190221", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to run the backend server/code in re-frame template? Using lein re-frame template I see that there's a -main function that runs a jetty server for the backend code located in clj/. Using emacs I've been able to cider-jack-in-cljs and get the frontend running in the browser, hot reload works and all but I've tried to add routes to the routes function in handler.clj inside the clj/ and haven't been able to figure out how to get that "backend side" of things to work. I found this other question sort of related but in that case the user just wanted to know why the clj/ folder was there, not how to run that code. I haven't been able to find any documentation so far, any help is greatly appreciated. PD: I know that having the backend and frontend in the same project/repo is not recommended (it's mentioned in the other question I linked above) but I just want to get a simple "first app" working and running first and then hopefully get the backend out into another project/repo. A: Assuming you created the project with something like lein new re-frame myapp +handler the code to start the server is on the file src/clj/myapp/server.clj You can open the file and run cider-jack-in-clj, which will ask if you want to launch lein or shadow-cljs. Since it's a CLJ file, choose lein. Once CIDER starts, you can evaluate the -main function (eg. (-main)) to start the server. You can open the URL at http://localhost:3000 and Jetty will serve the resources that are already compiled by shadow-cljs, so you'll see the same output as viewing the other port from CLJS directly. Note that the backend code from the template starts the Jetty server but won't help with reloading the backend. To see how enable hot reloading for the backend, check https://github.com/ring-clojure/ring/wiki/Setup-for-development
{ "language": "en", "url": "https://stackoverflow.com/questions/64671545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Bamboo Failing To Run Task - Null Pointer Exception I have had a set of Bamboo plans running for quite awhile but this morning Bamboo has decided to start throwing an exception when running them. The instance of Bamboo is on Linux but the plans themselves are ran from a remote agent running Windows. Specifically these are plans set to build .net framework mvc applications. The plans fail at different tasks but both with the same error. The error below fails while trying to restore nuget packages but another plan fails while attempting to run a copy command. Running the nuget restore outside of Bamboo runs correctly. I have tried cloning the plan and also reinstalled the remote agent but neither fixed the issue. Error occurred while running Task 'Nuget(8)' of type com.atlassian.bamboo.plugins.scripttask:task.builder.command. error 12-Aug-2020 09:40:17 com.atlassian.bamboo.task.TaskException: Failed to execute task error 12-Aug-2020 09:40:17 at com.atlassian.bamboo.plugins.shell.task.AbstractShellBuildTask.execute(AbstractShellBuildTask.java:65) error 12-Aug-2020 09:40:17 at com.atlassian.bamboo.plugins.shell.task.AbstractShellBuildTask.execute(AbstractShellBuildTask.java:39) error 12-Aug-2020 09:40:17 at com.atlassian.bamboo.task.TaskExecutorImpl.lambda$executeTasks$3(TaskExecutorImpl.java:288) error 12-Aug-2020 09:40:17 at com.atlassian.bamboo.task.TaskExecutorImpl.executeTaskWithPrePostActions(TaskExecutorImpl.java:221) error 12-Aug-2020 09:40:17 at com.atlassian.bamboo.task.TaskExecutorImpl.executeTasks(TaskExecutorImpl.java:288) error 12-Aug-2020 09:40:17 at com.atlassian.bamboo.task.TaskExecutorImpl.execute(TaskExecutorImpl.java:110) error 12-Aug-2020 09:40:17 at com.atlassian.bamboo.build.pipeline.tasks.ExecuteBuildTask.call(ExecuteBuildTask.java:71) error 12-Aug-2020 09:40:17 at com.atlassian.bamboo.v2.build.agent.DefaultBuildAgent.executeBuildPhase(DefaultBuildAgent.java:203) error 12-Aug-2020 09:40:17 at com.atlassian.bamboo.v2.build.agent.DefaultBuildAgent.build(DefaultBuildAgent.java:175) error 12-Aug-2020 09:40:17 at com.atlassian.bamboo.v2.build.agent.BuildAgentControllerImpl.lambda$waitAndPerformBuild$0(BuildAgentControllerImpl.java:122) error 12-Aug-2020 09:40:17 at com.atlassian.bamboo.variable.CustomVariableContextImpl.withVariableSubstitutor(CustomVariableContextImpl.java:185) error 12-Aug-2020 09:40:17 at com.atlassian.bamboo.v2.build.agent.BuildAgentControllerImpl.waitAndPerformBuild(BuildAgentControllerImpl.java:117) error 12-Aug-2020 09:40:17 at com.atlassian.bamboo.v2.build.agent.DefaultBuildAgent$1.run(DefaultBuildAgent.java:126) error 12-Aug-2020 09:40:17 at com.atlassian.bamboo.utils.BambooRunnables$1.run(BambooRunnables.java:48) error 12-Aug-2020 09:40:17 at com.atlassian.bamboo.security.ImpersonationHelper.runWith(ImpersonationHelper.java:26) error 12-Aug-2020 09:40:17 at com.atlassian.bamboo.security.ImpersonationHelper.runWithSystemAuthority(ImpersonationHelper.java:17) error 12-Aug-2020 09:40:17 at com.atlassian.bamboo.security.ImpersonationHelper$1.run(ImpersonationHelper.java:41) error 12-Aug-2020 09:40:17 at java.lang.Thread.run(Thread.java:748) error 12-Aug-2020 09:40:17 Caused by: java.lang.NullPointerException error 12-Aug-2020 09:40:17 at com.atlassian.bamboo.process.ExternalProcessBuilder.lambda$env$0(ExternalProcessBuilder.java:78) error 12-Aug-2020 09:40:17 at com.google.common.base.Predicates$CompositionPredicate.apply(Predicates.java:552) error 12-Aug-2020 09:40:17 at com.google.common.collect.Iterators$7.computeNext(Iterators.java:652) error 12-Aug-2020 09:40:17 at com.google.common.collect.AbstractIterator.tryToComputeNext(AbstractIterator.java:143) error 12-Aug-2020 09:40:17 at com.google.common.collect.AbstractIterator.hasNext(AbstractIterator.java:138) error 12-Aug-2020 09:40:17 at com.google.common.collect.Iterators.size(Iterators.java:191) error 12-Aug-2020 09:40:17 at com.google.common.collect.Collections2$FilteredCollection.size(Collections2.java:211) error 12-Aug-2020 09:40:17 at java.util.AbstractMap.size(AbstractMap.java:85) error 12-Aug-2020 09:40:17 at java.util.HashMap.putMapEntries(HashMap.java:501) error 12-Aug-2020 09:40:17 at java.util.HashMap.putAll(HashMap.java:785) error 12-Aug-2020 09:40:17 at com.atlassian.bamboo.process.ExternalProcessBuilder.env(ExternalProcessBuilder.java:78) error 12-Aug-2020 09:40:17 at com.atlassian.bamboo.process.ProcessServiceImpl.createExternalProcess(ProcessServiceImpl.java:144) error 12-Aug-2020 09:40:17 at com.atlassian.bamboo.process.ProcessServiceImpl.executeExternalProcess(ProcessServiceImpl.java:195) error 12-Aug-2020 09:40:17 at com.atlassian.bamboo.process.ProcessServiceImpl.executeExternalProcess(ProcessServiceImpl.java:210) error 12-Aug-2020 09:40:17 at com.atlassian.bamboo.plugins.shell.task.AbstractShellBuildTask.execute(AbstractShellBuildTask.java:48) error 12-Aug-2020 09:40:17 ... 17 more A: I talked with Atlassian support and they helped me work through the issue. I had setup the remote agent as a windows service which was causing the problems. I removed the service and started the remote agent via the BambooAgent.bat script. Mine was located at %InstallDirectory%/bin/BambooAgent.bat
{ "language": "en", "url": "https://stackoverflow.com/questions/63378142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Asp.net WebApi multipart/form-data with id from route definition I'm sending a multipart/form-data request to an action (file upload), but I'm sending it to an action that has the id in the url as specified by the route: routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}/{action}", defaults: new {action = "Index", id = RouteParameter.Optional } ); Url I'm posting to: /api/Contacts/1/Photo Action: [HttpPost] public HttpResponseMessage Photo(int id) { var task = this.Request.Content.ReadAsStreamAsync(); task.Wait(); Stream requestStream = task.Result; /* ... */ } With the id parameter, I get this error: No 'MediaTypeFormatter' is available to read an object of type 'Int32' with the media type 'multipart/form-data'. Without the id parameter, it works fine. I tried a MediaTypeFormatter in this answer here, but it doesn't seem to get the id from the url and crashes when trying to get it using FirstDispositionNameOrDefault("id"). Is there a way to get the id specified in the route url to bind to the id parameter for the action? A: FirstDispositionNameOrDefault is for reading the values of form controls. You can use the [FromUri] attribute on the parameter: public HttpResponseMessage Photo([FromUri] int id) This tells Web API not to get the parameter from the message body.
{ "language": "en", "url": "https://stackoverflow.com/questions/10052634", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to display data from json with looping javascript? This is my json code structure This is my javascript: $('#kurir').change(function(){ var kurirID = $(this).val(); if(kurirID){ $.ajax({ type:"GET", url:"{{url('checkout/kurir')}}?kurir_id="+kurirID, success:function(res){ if(res){ $("#ongkir").prop('disabled', false); $("#ongkir").empty(); $("#ongkir").append('<option>--- Pilih Kurir ---</option>'); $.each(res,function(key,value){ $("#ongkir").append('<option value="'+key['service']+'">'+this.value['service']+'</option>'); }); }else{ $("#ongkir").empty(); } } }); }else{ $("#ongkir").prop('disabled', true); $("#ongkir").empty(); $("#ongkir").append('<option>--- Pilih Kurir ---</option>'); }}); This is my controller public function getKurirList(Request $request) {$data = RajaOngkir::Cost(['origin'=> 419,'destination'=> 114,'weight'=> 1700,'courier'=> 'jne',])->get(); return response()->json($data); } I want to show all "service" data and price "value". How to iterate this json with a 'each' loop and print the data? Can anyone help me? A: You should iterate over $datas['0']['costs'] foreach ($datas['0']['costs'] as $key =$value){ echo $value['service'] . ' - ' $value['cost'][0]['value']; }
{ "language": "en", "url": "https://stackoverflow.com/questions/48267756", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to use Google Cloud PubSub with Proxy? I'm working with an application that interacts with Google Cloud PubSub. It works fine in normal scenario but I want to enable proxy support so I was going through Publisher.Builder and Subscriber classes and their APIs to see if there are any APIs available to enable proxy support. I managed to find only the setChannelProvider but I'm not sure whether that will work or not. The following code snippet is what I'm thinking of using but that doesn't seem to work. ManagedChannel channel = ManagedChannelBuilder.forAddress(proxyHost, proxyPort).build(); TransportChannelProvider channelProvider = FixedTransportChannelProvider.create(GrpcTransportChannel.create(channel)); publisherBuilder.setChannelProvider(channelProvider); I wasn't able to successfully publish or pull messages to the cloud service. I get the following error: java.util.concurrent.ExecutionException: io.grpc.StatusRuntimeException: DEADLINE_EXCEEDED: deadline exceeded after 9978300322ns So I wanted to know does the PubSub service support proxy through APIs or does it only support the proxy setting i.e. host and port to be provided in the environment path only. A: You can specify the proxyHost/port directly using JVM args https.proxyHost, https.proxyPort mvn clean install -Dhttps.proxyHost=localhost -Dhttps.proxyPort=3128 exec:java then just directly create a client of your choice TopicAdminSettings topicAdminSettings = TopicAdminSettings.newBuilder().build(); TopicAdminClient topicAdminClient = TopicAdminClient.create(topicAdminSettings); FYI- Setting ManagedChannelBuilder.forAddress() here overrides the final target for pubsub (which should be pubsub.googleapis.com 443 (not the proxy) Here is a medium post i put together as well as a gist specificlly for pubsub and pubsub+proxy that requires basic auth headers * * finally, just note, its https.proxyHost even if you're using httpProxy, ref grpc#9561 A: Proxy authentication via HTTP is not supported by Google Pub/Sub, but it can be configured by using GRPC_PROXY_EXP environment variable. I found the same error that you got here (that's why I assume you are using HTTP) and it got fixed by using what I said. A: You need to set JVM args: https.proxyHost, https.proxyPort for proxy authentication an additional configration is needed before any client creation: Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(proxyUsername,proxyPassword).toCharArray()); }
{ "language": "en", "url": "https://stackoverflow.com/questions/50894423", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to loop backwards after finding a certain line in a txt doc? I am working with using excel data to edit parts of large txt files. Some of these edits require deleting certain sections, and other require copying, pasting, and slightly editing these sections. For example, the txt doc takes this basic form: Monitor 1 Monitor 2 Item1 Item2 End Monitor 3 Monitor 4 Monitor 5 Item3 Item4 End Monitor 6 Item4 Item5 End Say I am needing to delete the second block (that is, delete from after the first end to the line before monitor 6). I am able to find the block using lookups for Item3 and Item4. Is there a way to assign this block to a variable? with open(longStr1) as old_file: lines = old_file.readlines() with open(endfile1, "w") as new_file: for line in lines: if "Item3 Item4" in line: #block = from previous End to after next End lines.remove(block) new_file.write(line) So ideally, this would allow me to delete the entire block of text to make the txt file then look like this: Monitor 1 Monitor 2 Item1 Item2 End Monitor 6 Item4 Item5 End How can I define this block using python? A: Iterative approach: search_item = "Item3 Item4" with open('input.txt') as f_in, open('output.txt', 'w') as f_out: block = '' for line in f_in: if block: block += line if line.strip() == 'End': if search_item not in block: f_out.write(block + '\n') block = '' elif line.startswith('Monitor'): block = line output.txt contents: Monitor 1 Monitor 2 Item1 Item2 End Monitor 6 Item4 Item5 End A: You could accumulate the lines to write in a separate string that corresponds to the content of one block. Wait until you reach the end of the block ("end" line) before writing the accumulated lines. If along the way, you find the text pattern that indicates suppression of the block, set a flag that will prevent writing to the file when the end is reached. For example (not tested): with open(longStr1) as old_file: lines = old_file.readlines() lineBlock = "" excluded = False with open(endfile1, "w") as new_file: for line in lines: lineBlock += line if line == "End": if not excluded: new_file.write(lineBlock) lineBlock = "" excluded = False if "Item3 Item4" in line: excluded = True
{ "language": "en", "url": "https://stackoverflow.com/questions/57012777", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to query the print queue on Windows We are developing a critical application and need to have the finest control over the documents printed. To be sure on which documents are printed or not we want to check the printer queue. How can we query the print queue on Windows (status, queue list, errors, ...)? A: EnumPrinters to get the list of printers, EnumJobs to get a list of jobs for that printer. GetJob to get info on a specific job and SetJob to change the settings for that job (pause or cancel it). See more in the Printing and Print Spooler References. .NET has the PrintQueue and PrintServer classes. A: Following URLs may be of interest to you, http://www.codeproject.com/KB/printing/printwatchvbnet.aspx and http://www.codeproject.com/KB/printing/EMFSpoolViewer.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/553051", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Method chaining to communicate between GUI parts in a MVC in Java I am creating a Java Desktop GUI application using the MVC pattern. For the sake of simplicity, I have divided in GUI application into different panels (Scheme of the GUI application) so that each class takes care of something specific. Now, when I am in the Controller part and want to display something in the DRAW PANEL, I have a method chaining. I mean I am calling several methods in a row: view.getRightPanel().getDrawPanel().appendText(model.getResults()); I am wondering whether or not I am making a mistake somewhere. Is it normal to do so, or should I change my code to make it more efficient and elegant? Any information is welcome! Thank you! A: You are not making a mistake if you are doing this in the controller. In the MVC pattern, the controller listens for model changes and updates the view. That is what the controller is supposed to do. Here, view.getRightPanel().getDrawPanel().appendText(model.getResults()); I guess you are changing the text in a draw panel in the view that controller is controlling, which is exactly what the controller is supposed to do. Do be careful not to change update the model directly from the view, or update the view from the model though. That violates MVC. I also suggest you to create multiple controllers to control different panels on the screen. I think that way it will be more manageable.
{ "language": "en", "url": "https://stackoverflow.com/questions/44440434", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I fix: "start-stop-daemon: warning: this system is not able to track process names" when starting springboot as a systemd service? When I start my spring boot app as a systemd service I receive this error: start-stop-daemon: warning: this system is not able to track process names longer than 15 characters, please use --exec instead of --name. Spring boot seems to build the process name from the jar name and the directory the jar is contained in. Is there any way to fix this aside from renaming the jar, and the directory it's contained in, to be shorter than 15 characters? If I try to edit spring boots startup script to use --exec instead of --name then I get another error: 'start-stop-daemon: unable to stat /opt/program/programname_optprogramname (No such file or directory) A: It appears that this issue is fixed in Spring boot 2.0.2. So if you run into this issue upgrading might fix it (not to imply that upgrading is always a simple effort)
{ "language": "en", "url": "https://stackoverflow.com/questions/51217606", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Need help aligning my textfields with my radio buttons how it looks like right now i' m placing all my inputs on the right with float: right; in my css file. But i'm wondering if there is a way to align my radios to the left side of my text fields? so they all align under each other on the left side. A: I would strongly advocate using the more sophisticated, flexible solution even with great browsers support, the flexbox. You could have used align-self to align specify elements along with default alignment to sibling elements. If you did not know about flexbox, It's worth learning right now.
{ "language": "en", "url": "https://stackoverflow.com/questions/60947987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: store time from stopwatch Javascript in MySQL database I am using a javascript to start and stop a timer (stopwatch). What I want is that when the user press the stop button, the data (the time at that moment) will be stored in my MySQL database. Is that possible? And if yes, what do I need to add as code? (I'm just a starter with PHP, if someone can add a small explanation then that would be great so I can learn from it) The following script is my working javascript code: var clsStopwatch = function () { var startAt = 0; var lapTime = 0; var now = function () { return (new Date()).getTime(); }; this.start = function () { startAt = startAt ? startAt : now(); }; this.stop = function () { lapTime = startAt ? lapTime + now() - startAt : lapTime; startAt = 0; }; this.time = function () { return lapTime + (startAt ? now() - startAt : 0); }; }; var x = new clsStopwatch(); var $time; var clocktimer; function pad(num, size) { var s = "0000" + num; return s.substr(s.length - size); } function formatTime(time) { var h = m = s = ms = 0; var newTime = ''; m = Math.floor(time / (60 * 1000)); time = time % (60 * 1000); s = Math.floor(time / 1000); ms = time % 1000; newTime = pad(m, 2) + ':' + pad(s, 2) + ':' + pad(ms, 2); return newTime; } function show() { $time = document.getElementById('time'); update(); } function update() { $time.innerHTML = formatTime(x.time()); } function start() { clocktimer = setInterval("update()", 1); x.start(); } function stop() { x.stop(); clearInterval(clocktimer); } The next is my PHP code that I use to store data in my database, it's on a separate page. define('DB_NAME', 'dbname'); define('DB_USER', 'user'); define('DB_PASSWORD', 'pass'); define('DB_HOST', 'host'); $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); if (!$link) { die('could not connect: ' . mysql_error()); } $db_selected = mysql_select_db(DB_NAME, $link); if (!$db_selected) { die('can not use ' . DB_NAME . ': ' . mysql_error()); } $sql="INSERT INTO game (name, company, email, time) VALUES ('".$_POST['name']."','".$_POST['company']."','".$_POST['email']."','".$_POST['time']."')"; if (!mysql_query($sql)) { die('Error: ' . mysql_error()); } mysql_close(); and my HTML submit form: <body onload="show();"> <form action="highscore.php" method="post"/> name:<br/> <input type="text" name="name"/><br/> company:<br/> <input type="text" name="company"/><br/> email:<br/> <input type="text" name="email"/><br/> Time: <span id="time"></span><br/> <!--<input type="text" name-"time">--> <input type="button" value="start" onclick="start();"> <input type="submit" value="stop" onclick="stop();"> <br/><br/> </form> </body> Maybe a solution could be to post the data in a hidden input field but still i'm struggling to get that one working. A: Try this: function stop() { x.stop(); document.getElementById('counter').value = formatTime(x.time()); clearInterval(clocktimer); } On your form: <input type="hidden" value="" id="counter" name="counter" /> A: Use MySQLi instead of MySQL, because there's some serious security problems with MySQL
{ "language": "en", "url": "https://stackoverflow.com/questions/21912511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to setup static page with css in subdirectory in rails public directory I'm trying to setup jekyll blog in my public/blog directory. For this question let say I just want to have public/blog directory with index.html and css/site.css with css for this page. I'm deploying it using capistrano, so I added public/blog to linked_dirs index.html: <html> <head> <link rel="stylesheet" type="text/css" href="css/site.css"> </head> <body> <h1>Hello World</h1> </body> </html> css/site.css: h1 { color: red; } Now after cap production deploy I can visit domain.com/blog and see Hello World header, but it does not load css file. I get Failed to load resource: the server responded with a status of 404 (Not Found) error. Do you know how can I make it work? A: It was more a nginx question. I added this to my site nginx file: location ^~ /blog/css/ { gzip_static on; expires max; add_header Cache-Control public; }
{ "language": "en", "url": "https://stackoverflow.com/questions/59339355", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can a number be Romanised this way? I know there are a few different ways to Romanise a number, however I'm trying to make up my own and was wondering if this approach is possible. It returns Null for every iteration and I can't seem to see what I am missing here. Any help would be much appreciated! var array; var result = []; function convertToRoman(num) { array = num.toString().split('').reverse(); roman = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC", "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" ]; for (i = 0, j = 0; i < array.length; i++, j += 10) { var location = array[i] + j; result = result.concat(roman[location]); } return result.reverse().join(); } console.log(convertToRoman(123)); A: As array contains strings, you have to parse them back to integers when using them in the arithmetic. This is a possible solution: var roman = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC", "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" ]; function convertToRoman(num) { var result = []; var array = num.toString().split('').reverse(); for (i = 0, j = 0; i < array.length; i++, j += 10) { var location = parseInt(array[i]) + j; result.push(roman[location]); } return result.reverse().join(''); } console.log(convertToRoman(123)); Note that I made some changes regarding variable scope and use of array.push(). I also didn't try the method for multiple inputs. But getting the algorithm correct was not part of your question
{ "language": "en", "url": "https://stackoverflow.com/questions/41780510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Requiring multiple string conditions in WHERE CLAUSE SELECT stu.First_Name, stu.Last_Name, stu.Phone FROM Student stu JOIN Enrollment e ON stu.Student_Id = e.Student_Id JOIN Section sec ON e.Section_Id = sec.Section_Id JOIN Course c ON sec.Course_No = c.Course_No WHERE c.Description = 'Systems Analysis' AND c.Description = 'Project Managment' Hey all, hopefully the last question for today (I'm so sorry). I was wondering if there is a way to check for multiple string conditions (being an AND, not OR). When I use just one my joins work alright, but I can't seem to work past using both. My textbook wants me to solve it with only using the string keywords for the courses. A: Use OR and filter only the rows having the same number of instances to the the number of filter specified in the WHERE clause. SELECT stu.First_Name, stu.Last_Name, stu.Phone FROM Student stu JOIN Enrollment e ON stu.Student_Id = e.Student_Id JOIN Section sec ON e.Section_Id = sec.Section_Id JOIN Course c ON sec.Course_No = c.Course_No WHERE c.Description IN ('Systems Analysis', 'Project Managment') -- two values GROUP BY stu.First_Name, stu.Last_Name, stu.Phone HAVING COUNT(*) = 2 -- rows must have 2 instances
{ "language": "en", "url": "https://stackoverflow.com/questions/49062437", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Controlling x-axis label format for time series plots - R Is there a way force R to print time stamps as %m/%d/%Y on graphs? When I have short (<7 days) of data it prints as days of the week as below? plot(station_171$datetime, station_171$stageheight, pch=ifelse(station_171$outcode ==122,24,21), col="black", bg=ifelse(station_171$outcode ==122,"red","NA") , xlab = "",xlim = c(min(station_101_7$datetime),max(station_101_7$datetime)), ylab = "") legend("topright","171", bty = "n", cex=2) A: You can format the axis using axis.POSIXct as seen below: axis.POSIXct(1,station_171$datetime, format = '%Y-%m-%d %H:%S') One should also make sure to include the xaxt='n' in the plot function to avoid double printing the x-axis labels.
{ "language": "en", "url": "https://stackoverflow.com/questions/39412536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to remove label from dynamically generated check box in PyQt5? So I have a table which has several checkboxes dynamically generated using these lines of codes: chkBoxItem = QTableWidgetItem() chkBoxItem.setTextAlignment(Qt.AlignHCenter) chkBoxItem.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled) chkBoxItem.setCheckState(QtCore.Qt.Unchecked) ui.columnTable.cellChanged.connect(self.checkColumnDataCheckbox) ui.columnTable.setItem(i , 0, chkBoxItem) I have tried resizing it to a small value but it's not working: chkBoxItem.setSizeHint(QSize(10,10)) Seems like it doesn't go beyond a certain minimum width and height. Here's how it looked: Basically, I want to remove this text label so the checkbox can be positioned at the center of the cell A: void QTableWidget::setCellWidget(int row, int column, QWidget *widget) Sets the given widget to be displayed in the cell in the given row and column, passing the ownership of the widget to the table. import sys from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5.QtCore import * class Window(QWidget): def __init__(self, rows, columns): super().__init__() self.table = QTableWidget(rows, columns, self) for row in range(rows): widget = QWidget() checkbox = QCheckBox() checkbox.setCheckState(Qt.Unchecked) layoutH = QHBoxLayout(widget) layoutH.addWidget(checkbox) layoutH.setAlignment(Qt.AlignCenter) layoutH.setContentsMargins(0, 0, 0, 0) self.table.setCellWidget(row, 0, widget) # <---- self.table.setItem(row, 1, QTableWidgetItem(str(row))) self.button = QPushButton("Control selected QCheckBox") self.button.clicked.connect(self.ButtonClicked) layoutV = QVBoxLayout(self) layoutV.addWidget(self.table) layoutV.addWidget(self.button) def ButtonClicked(self): checked_list = [] for i in range(self.table.rowCount()): if self.table.cellWidget(i, 0).findChild(type(QCheckBox())).isChecked(): checked_list.append(self.table.item(i, 1).text()) print(checked_list) if __name__ == '__main__': app = QApplication(sys.argv) window = Window(3, 3) window.resize(350, 300) window.show() sys.exit(app.exec_())
{ "language": "en", "url": "https://stackoverflow.com/questions/56102229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Shortcut to move the cursor to certain characters in Webstorm I've seen several videos where the user is using Webstorm and hits a keyboard shortcut which brings up a small input field that the user can type a letter, number or other character into. Webstorm then presents the user with several choices denoted by "A", "B", "C", etc. which the user can then type the value of to move to the appropriate spot in the file that is currently being edited. I've searched through Webstorm's shortcuts, but I don't see anything to this effect. Does anyone know what this shortcut is? I can try to get a screen shot if my explanation wasn't clear enough. Thanks! A: It is AceJump plugin - the easiest way to get it - go to Settings-Plugins click on Browse Repository and search for AceJump. Once you install it - the hardest thing for me was to force myself to use it after 2 months - I even type documents in webstorm and then copy it to Word. Repository is here https://plugins.jetbrains.com/plugin/7086 Github is here https://github.com/johnlindquist/AceJump Good luck :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/28522153", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a better way to dynamically build an SQL WHERE clause than by using 1=1 at its beginning? I'm building some SQL query in C#. It will differ depending on some conditions stored as variables in the code. string Query="SELECT * FROM Table1 WHERE 1=1 "; if (condition1) Query += "AND Col1=0 "; if (condition2) Query += "AND Col2=1 "; if (condition3) Query += "AND Col3=2 "; It works, but testing 1=1 doesn't seem elegant. If I didn't use it, I would have to remember and check every time if "where" keyword was already added or not to the query. Is there a nicer solution? A: Just append two lines at back. string Query="SELECT * FROM Table1 WHERE 1=1 "; if (condition1) Query+="AND Col1=0 "; if (condition2) Query+="AND Col2=1 "; if (condition3) Query+="AND Col3=2 "; Query.Replace("1=1 AND ", ""); Query.Replace(" WHERE 1=1 ", ""); E.g. SELECT * FROM Table1 WHERE 1=1 AND Col1=0 AND Col2=1 AND Col3=2 will become to SELECT * FROM Table1 WHERE Col1=0 AND Col2=1 AND Col3=2 While SELECT * FROM Table1 WHERE 1=1 will become to SELECT * FROM Table1 ===================================== Thanks for pointing out a flaw of this solution: "This could break the query if, for any reason, one of the conditions contains the text "1=1 AND " or " WHERE 1=1 ". This could be the case if the condition contains a subquery or tries to check if some column contains this text, for example. Maybe this isn't a problem in your case but you should keep it in mind… " In order to get rid of this issue, we need to distinguish the "main" WHERE 1=1 and those from subquery, which is easy: Simply make the "main" WHERE special: I would append a "$" sign string Query="SELECT * FROM Table1 WHERE$ 1=1 "; if (condition1) Query+="AND Col1=0 "; if (condition2) Query+="AND Col2=1 "; if (condition3) Query+="AND Col3=2 "; Then still append two lines: Query.Replace("WHERE$ 1=1 AND ", "WHERE "); Query.Replace(" WHERE$ 1=1 ", ""); A: One solution is to simply not write queries manually by appending strings. You could use an ORM, like Entity Framework, and with LINQ to Entities use the features the language and framework offer you: using (var dbContext = new MyDbContext()) { IQueryable<Table1Item> query = dbContext.Table1; if (condition1) { query = query.Where(c => c.Col1 == 0); } if (condition2) { query = query.Where(c => c.Col2 == 1); } if (condition3) { query = query.Where(c => c.Col3 == 2); } PrintResults(query); } A: Use this: string Query="SELECT * FROM Table1 WHERE "; string QuerySub; if (condition1) QuerySub+="AND Col1=0 "; if (condition2) QuerySub+="AND Col2=1 "; if (condition3) QuerySub+="AND Col3=2 "; if (QuerySub.StartsWith("AND")) QuerySub = QuerySub.TrimStart("AND".ToCharArray()); Query = Query + QuerySub; if (Query.EndsWith("WHERE ")) Query = Query.TrimEnd("WHERE ".ToCharArray()); A: Why not using an existing Query Builder ? Something like Sql Kata. It supports complex where conditions, joins and subqueries. var query = new Query("Users").Where("Score", ">", 100).OrderByDesc("Score").Limit(100); if(onlyActive) { query.Where("Status", "active") } // or you can use the when statement query.When(onlyActive, q => q.Where("Status", "active")) it works with Sql Server, MySql and PostgreSql. A: If this is SQL Server, you can make this code much cleaner. This also assumes a known number of parameters, which may be a poor assumption when I think about the possibilities. In C#, you would use: using (SqlConnection conn = new SqlConnection("connection string")) { conn.Open(); SqlCommand command = new SqlCommand() { CommandText = "dbo.sample_proc", Connection = conn, CommandType = CommandType.StoredProcedure }; if (condition1) command.Parameters.Add(new SqlParameter("Condition1", condition1Value)); if (condition2) command.Parameters.Add(new SqlParameter("Condition2", condition2Value)); if (condition3) command.Parameters.Add(new SqlParameter("Condition3", condition3Value)); IDataReader reader = command.ExecuteReader(); while(reader.Read()) { } conn.Close(); } And then on the SQL side: CREATE PROCEDURE dbo.sample_proc ( --using varchar(50) generically -- "= NULL" makes them all optional parameters @Condition1 varchar(50) = NULL @Condition2 varchar(50) = NULL @Condition3 varchar(50) = NULL ) AS BEGIN /* check that the value of the parameter matches the related column or that the parameter value was not specified. This works as long as you are not querying for a specific column to be null.*/ SELECT * FROM SampleTable WHERE (Col1 = @Condition1 OR @Condition1 IS NULL) AND (Col2 = @Condition2 OR @Condition2 IS NULL) AND (Col3 = @Condition3 OR @Condition3 IS NULL) OPTION (RECOMPILE) --OPTION(RECOMPILE) forces the query plan to remain effectively uncached END A: The quickest literal solution to what you're asking that I can think of is this: string Query="SELECT * FROM Table1"; string Conditions = ""; if (condition1) Conditions+="AND Col1=0 "; if (condition2) Conditions+="AND Col2=1 "; if (condition3) Conditions+="AND Col3=2 "; if (Conditions.Length > 0) Query+=" WHERE " + Conditions.Substring(3); It doesn't seem elegant, sure, to which I would refer you to CodeCaster's recommendation of using an ORM. But if you think about what this is doing here, you're really not worried about 'wasting' 4 characters of memory, and it's really quick for a computer to move a pointer 4 places. If you have the time to learn how to use an ORM, it could really pay off for you. But in regards to this, if you're trying to keep that additional condition from hitting the SQL db, this will do it for you. A: Depending on the condition, it might be possible to use boolean logic in the query. Something like this : string Query="SELECT * FROM Table1 " + "WHERE (condition1 = @test1 AND Col1=0) "+ "AND (condition2 = @test2 AND Col2=1) "+ "AND (condition3 = @test3 AND Col3=2) "; A: I like the fluent interface of stringbuilder, so I made some ExtensionMethods. var query = new StringBuilder() .AppendLine("SELECT * FROM products") .AppendWhereIf(!String.IsNullOrEmpty(name), "name LIKE @name") .AppendWhereIf(category.HasValue, "category = @category") .AppendWhere("Deleted = @deleted") .ToString(); var p_name = GetParameter("@name", name); var p_category = GetParameter("@category", category); var p_deleted = GetParameter("@deleted", false); var result = ExecuteDataTable(query, p_name, p_category, p_deleted); // in a seperate static class for extensionmethods public StringBuilder AppendLineIf(this StringBuilder sb, bool condition, string value) { if(condition) sb.AppendLine(value); return sb; } public StringBuilder AppendWhereIf(this StringBuilder sb, bool condition, string value) { if (condition) sb.AppendLineIf(condition, sb.HasWhere() ? " AND " : " WHERE " + value); return sb; } public StringBuilder AppendWhere(this StringBuilder sb, string value) { sb.AppendWhereIf(true, value); return sb; } public bool HasWhere(this StringBuilder sb) { var seperator = new string [] { Environment.NewLine }; var lines = sb.ToString().Split(seperator, StringSplitOptions.None); return lines.Count > 0 && lines[lines.Count - 1].Contains("where", StringComparison.InvariantCultureIgnoreCase); } // http://stackoverflow.com/a/4217362/98491 public static bool Contains(this string source, string toCheck, StringComparison comp) { return source.IndexOf(toCheck, comp) >= 0; } A: IMHO, I think that your approach is wrong: Query the database by concatenating string is NEVER a good idea (risk of SQL injection and the code can easily be broken if you do some changes elsewhere). You can use an ORM (I use NHibernate) or at least use SqlCommand.Parameters If you absolutely want to use string concatenation, I would use a StringBuilder (it is the right object for string concatenation): var query = new StringBuilder("SELECT * FROM Table1 WHERE"); int qLength = query.Length;//if you don't want to count :D if (Condition1) query.Append(" Col1=0 AND"); if (Condition2) query.Append(" Col2=0 AND"); .... //if no condition remove WHERE or AND from query query.Length -= query.Length == qLength ? 6 : 4; As the last thought, Where 1=1 is really ugly but SQL Server will optimize it anyway. A: The Dapper SqlBuilder is a pretty good option. It's even used in production on StackOverflow. Read Sam's blog entry about it. As far as I know, it's not part of any Nuget package, so you'll need to copy paste its code into your project or download the Dapper source and build the SqlBuilder project. Either way, you'll also need to reference Dapper for the DynamicParameters class. A: A slight bit of overkill in this simple case but I've used code similar to this in the past. Create a function string AddCondition(string clause, string appender, string condition) { if (clause.Length <= 0) { return String.Format("WHERE {0}",condition); } return string.Format("{0} {1} {2}", clause, appender, condition); } Use it like this string query = "SELECT * FROM Table1 {0}"; string whereClause = string.Empty; if (condition 1) whereClause = AddCondition(whereClause, "AND", "Col=1"); if (condition 2) whereClause = AddCondition(whereClause, "AND", "Col2=2"); string finalQuery = String.Format(query, whereClause); This way if no conditions are found you don't even bother loading a where statement in the query and save the sql server a micro-second of processing the junk where clause when it parses the sql statement. A: Save the conditions in a list: List<string> conditions = new List<string>(); if (condition1) conditions.Add("Col1=0"); //... if (conditions.Any()) Query += " WHERE " + string.Join(" AND ", conditions.ToArray()); A: There is another solution, which may also not be elegant, but works and solves the problem: String query = "SELECT * FROM Table1"; List<string> conditions = new List<string>(); // ... fill the conditions string joiner = " WHERE "; foreach (string condition in conditions) { query += joiner + condition; joiner = " AND " } For: * *empty conditions list, the result will be simply SELECT * FROM Table1, *a single condition it will be SELECT * FROM Table1 WHERE cond1 *each following condition will generate additional AND condN A: Just do something like this: using (var command = connection.CreateCommand()) { command.CommandText = "SELECT * FROM Table1"; var conditions = ""; if (condition1) { conditions += "Col1=@val1 AND "; command.AddParameter("val1", 1); } if (condition2) { conditions += "Col2=@val2 AND "; command.AddParameter("val2", 1); } if (condition3) { conditions += "Col3=@val3 AND "; command.AddParameter("val3", 1); } if (conditions != "") command.CommandText += " WHERE " + conditions.Remove(conditions.Length - 5); } It's SQL injection safe and IMHO, it's pretty clean. The Remove() simply removes the last AND; It works both if no conditions have been set, if one have been set or if multiple have been set. A: I see this used all the time in Oracle while building dynamic SQL within stored procedures. I use it in queries while exploring data issues as well just to make switching between different filters of data faster... Just comment out a condition or add it back in easily. I find it's pretty common and easy enough to understand to someone reviewing your code. A: Using string function you can also do it this way: string Query = "select * from Table1"; if (condition1) WhereClause += " Col1 = @param1 AND "; // <---- put conditional operator at the end if (condition2) WhereClause += " Col1 = @param2 OR "; WhereClause = WhereClause.Trim(); if (!string.IsNullOrEmpty(WhereClause)) Query = Query + " WHERE " + WhereClause.Remove(WhereClause.LastIndexOf(" ")); // else // no condition meets the criteria leave the QUERY without a WHERE clause I personally feel easy to to remove the conditional element(s) at the end, since its position is easy to predict. A: I thought of a solution that, well, perhaps is somewhat more readable: string query = String.Format("SELECT * FROM Table1 WHERE " + "Col1 = {0} AND " + "Col2 = {1} AND " + "Col3 = {2}", (!condition1 ? "Col1" : "0"), (!condition2 ? "Col2" : "1"), (!condition3 ? "Col3" : "2")); I'm just not sure whether the SQL interpreter will also optimize away the Col1 = Col1 condition (printed when condition1 is false). A: public static class Ext { public static string addCondition(this string str, bool condition, string statement) { if (!condition) return str; return str + (!str.Contains(" WHERE ") ? " WHERE " : " ") + statement; } public static string cleanCondition(this string str) { if (!str.Contains(" WHERE ")) return str; return str.Replace(" WHERE AND ", " WHERE ").Replace(" WHERE OR ", " WHERE "); } } Realisation with extension methods. static void Main(string[] args) { string Query = "SELECT * FROM Table1"; Query = Query.addCondition(true == false, "AND Column1 = 5") .addCondition(18 > 17, "AND Column2 = 7") .addCondition(42 == 1, "OR Column3 IN (5, 7, 9)") .addCondition(5 % 1 > 1 - 4, "AND Column4 = 67") .addCondition(Object.Equals(5, 5), "OR Column5 >= 0") .cleanCondition(); Console.WriteLine(Query); } A: Here is a more elegant way: private string BuildQuery() { string MethodResult = ""; try { StringBuilder sb = new StringBuilder(); sb.Append("SELECT * FROM Table1"); List<string> Clauses = new List<string>(); Clauses.Add("Col1 = 0"); Clauses.Add("Col2 = 1"); Clauses.Add("Col3 = 2"); bool FirstPass = true; if(Clauses != null && Clauses.Count > 0) { foreach(string Clause in Clauses) { if (FirstPass) { sb.Append(" WHERE "); FirstPass = false; } else { sb.Append(" AND "); } sb.Append(Clause); } } MethodResult = sb.ToString(); } catch //(Exception ex) { //ex.HandleException() } return MethodResult; } A: As has been stated, creating SQL by concatenation is never a good idea. Not just because of SQL injection. Mostly because it's just ugly, difficult to maintain and totally unnecessary. You have to run your program with trace or debug to see what SQL it generates. If you use QueryFirst (disclaimer: which I wrote) the unhappy temptation is removed, and you can get straight in ta doin it in SQL. This page has a comprehensive coverage of TSQL options for dynamically adding search predicates. The following option is handy for situations where you want to leave the choice of combinations of search predicates to your user. select * from table1 where (col1 = @param1 or @param1 is null) and (col2 = @param2 or @param2 is null) and (col3 = @param3 or @param3 is null) OPTION (RECOMPILE) QueryFirst gives you C# null to db NULL, so you just call the Execute() method with nulls when appropriate, and it all just works. <opinion>Why are C# devs so reluctant to do stuff in SQL, even when it's simpler. Mind boggles.</opinion> A: For longer filtering steps StringBuilder is the better approach as many says. on your case I would go with: StringBuilder sql = new StringBuilder(); if (condition1) sql.Append("AND Col1=0 "); if (condition2) sql.Append("AND Col2=1 "); if (condition3) sql.Append("AND Col3=2 "); string Query = "SELECT * FROM Table1 "; if(sql.Length > 0) Query += string.Concat("WHERE ", sql.ToString().Substring(4)); //avoid first 4 chars, which is the 1st "AND " A: Concise, elegant and sweet, as shown in the image below.
{ "language": "en", "url": "https://stackoverflow.com/questions/17321281", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "119" }
Q: How to generate Java PKCS12 store to connect to regular SSL website? we run a standard web API over https with a regular purchased SSL certificate. Our clients just access it via https, the certificate is trusted via default system RootCA. A new client is using a Java communication server that requires the certificate in a PKCS12 keystore. How can we generate the PKS12 keystore from our key/csr/crt/pem files? I did some research, most examples are requiring a private key. Of course I do not want to share our private key with the client. Can a PKCS12 keystore be created without private key, similar to standard RootCA in browsers? Thanks, bluepuma A: YES-ish. Although PFX-now-PKCS12 was designed primarily to store or transfer a privatekey and cert and chain cert(s) as a clump, and most commonly is used for that, it is capable of storing one or more 'lone' cert(s) not matched to any privatekey. And you are correct the client wanting to connect to you should have in their truststore ideally the root cert for your server cert's chain, or alternatively your server cert itself, but decidedly not your privatekey. openssl can actually create such a PKCS12: openssl pkcs12 -export -in certfile.pem [-name $name] -nokeys -out blah.p12 # if you don't specify -name it defaults to 1 (the digit one) which can be mildly confusing # instead of being prompted for the password you can use -passout with several forms # described on the openssl man page, but consider the warning below But the result won't work in Java if they use the standard (Sun/Oracle/OpenJDK) cryptoproviders, which (in 8+) support lone cert(s) in a PKCS12 as 'trustedCert' entries in Java only if the(each) certbag has a special Sun-defined attribute which the Java providers write when they create such a file, but OpenSSL doesn't. Instead use Java's keytool in 8: jre8/bin/keytool -importcert -keystore blah.p12 -storetype pkcs12 -file $certfile [-alias $name] or in 9+ where pkcs12 is now the default: jre9+/bin/keytool -importcert -keystore blah.p12 -file $certfile [-alias $name] If you don't specify the alias it defaults to mykey. In both cases you can add -storepass $pw to avoid being prompted for it, but as a result the password will be visible on your screen, in the command history of your shell or other command processor it is has one, and in most cases to other processes run on your system concurrently, (any of) which may be a security issue or not. You can also add -noprompt to avoid the confirmation prompt. But user207421 is (roughly) correct that using such a truststore can break other SSL/TLS connection(s) made from their system, at least from the same JVM, unless the individual calls specify individual, separate truststores, and if they had coded that they would know how to handle (and ask for) a simpler certificate format, such as PEM.
{ "language": "en", "url": "https://stackoverflow.com/questions/67601037", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: asp.net datasource control parameter outside iframe Hope someone can help me here, i have been searching for a solution for a few days now but havent't found it. I have build a page with 2 iframes, SelectCustomer which opens a page in where a dropdownlist lives with customer names and iframecontent in which i load a page by clicking a link. This page has a sqldatasource with a parameter. I want to refer to the dropdownlist in this parameter to filter the select query but i haven't found a way to refer to the dropdownlist outside the iframe "iframecontent". This is the page with the iframes: <%@ Page Title="" Language="VB" MasterPageFile="~/Dashboard/Sales/Dashboard_Sales.master" AutoEventWireup="false" CodeFile="Index.aspx.vb" Inherits="Dashboard_Sales_Default" %> <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server"> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server"> <!DOCTYPE HTML> <html> <head> </head> <body> <iframe name="SelectCustomer" src="SelectDebiteur.aspx" align="top" frameborder="0" height="50" width="100%" marginheight="0" marginwidth="0" scrolling="auto"> </iframe> <iframe name="iframecontent" height="500" width="100%"> </iframe> </body> </html> </asp:Content> This is the page from the first iframe: <%@ Page Language="VB" AutoEventWireup="false" CodeFile="SelectDebiteur.aspx.vb" Inherits="Dashboard_Sales_SelectDebiteur" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $("#DropDownList1").on("change", function () { // When the DropDownList selected value has been changed, // refresh the other iframed page changing its source // adding the value as its query string. $("#iframecontent", parent.document).attr("src", "Default.aspx?value=" + $(this).val()); return true; }); }); </script> </head> <body> <form id="form1" runat="server"> <div> <asp:SqlDataSource ID="ListDebiteur" runat="server" ConnectionString="<%$ ConnectionStrings:FLOSConnectionString2 %>" SelectCommand="SELECT [aa-270].cddeb, [ba-001].naamorg AS Debiteur FROM [aa-270] INNER JOIN [ba-001] ON [aa-270].cdorg = [ba-001].cdorg ORDER BY Debiteur"></asp:SqlDataSource> <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" DataSourceID="ListDebiteur" DataTextField="Debiteur" DataValueField="cddeb"> </asp:DropDownList> </div> </form> </body> </html> This is the page which get's loaded in the second iframe: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:SqlDataSource ID="ListCustomers" runat="server" ConnectionString="<%$ ConnectionStrings:FLOSConnectionString2 %>" SelectCommand="SELECT [aa-270].cddeb, [ba-001].naamorg AS Debiteur FROM [aa-270] INNER JOIN [ba-001] ON [aa-270].cdorg = [ba-001].cdorg ORDER BY Debiteur"></asp:SqlDataSource> <asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True" DataSourceID="ListCustomers" DataTextField="Debiteur" DataValueField="cddeb"> </asp:DropDownList> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:FLOSConnectionString2 %>" SelectCommand="SELECT [va-211].cdorg, [ba-001].naamorg, RTRIM(YEAR([va-211].[datum-lvoor])) + '-' + CASE WHEN RTRIM(MONTH([va-211].[datum-lvoor])) &lt; 10 THEN '0' + RTRIM(MONTH([va-211].[datum-lvoor])) ELSE RTRIM(MONTH([va-211].[datum-lvoor])) END AS Maand, SUM(CASE WHEN [va-211].cdstatus = 'O' THEN [va-211].aanttelev * ([va-211].prijs / [bb-063].prijsper) WHEN [va-211].cdstatus = 'A' THEN [va-211].aantgelev * ([va-211].prijs / [bb-063].prijsper) END) AS Omzet FROM [ba-001] INNER JOIN [va-211] ON [ba-001].cdorg = [va-211].cddeb LEFT OUTER JOIN [bb-063] ON [va-211].cdprodukt = [bb-063].cdprodukt WHERE ([bb-063].cdprijssrt = 'VERK') AND ([va-211].cdstatus = 'O' OR [va-211].cdstatus = 'A') GROUP BY [ba-001].naamorg, RTRIM(YEAR([va-211].[datum-lvoor])) + '-' + CASE WHEN RTRIM(MONTH([va-211].[datum-lvoor])) &lt; 10 THEN '0' + RTRIM(MONTH([va-211].[datum-lvoor])) ELSE RTRIM(MONTH([va-211].[datum-lvoor])) END, [va-211].cdorg HAVING (SUM(CASE WHEN [va-211].cdstatus = 'O' THEN [va-211].aanttelev * ([va-211].prijs / [bb-063].prijsper) WHEN [va-211].cdstatus = 'A' THEN [va-211].aantgelev * ([va-211].prijs / [bb-063].prijsper) END) &gt; 0) AND ([va-211].cdorg = @param1) ORDER BY Maand, [ba-001].naamorg"> <SelectParameters> <asp:ControlParameter ControlID="DropDownList2" Name="param1" PropertyName="Text" DefaultValue="00000739" /> </SelectParameters> </asp:SqlDataSource> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataSourceID="SqlDataSource1" EnableModelValidation="True" ForeColor="#333333" GridLines="None"> <AlternatingRowStyle BackColor="White" /> <Columns> <asp:BoundField DataField="cdorg" HeaderText="cdorg" SortExpression="cdorg" /> <asp:BoundField DataField="naamorg" HeaderText="naamorg" SortExpression="naamorg" /> <asp:BoundField DataField="Maand" HeaderText="Maand" ReadOnly="True" SortExpression="Maand" /> <asp:BoundField DataField="Omzet" HeaderText="Omzet" ReadOnly="True" SortExpression="Omzet" /> </Columns> <EditRowStyle BackColor="#7C6F57" /> <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" /> <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" /> <RowStyle BackColor="#E3EAEB" /> <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" /> </asp:GridView> </div> </form> </body> </html> And it's code behind page: using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class Dashboard_Sales_Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) DropDownList2.SelectedValue = Request.QueryString["value"]; } } New challenge: <a href="javascript:openPage()" target="iframecontent">Omzet in portefeuille </a> </li> <scriptsrc="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> openPage = $(function () { location.href = "Default.aspx?value=" + $("#DropDownList1").val(); }); </script> A: One of the solutions is to refresh the second iframed page sending the DropDownList selected value as its query string, using jQuery (to make things easier). To demonstrate, I'm basically updating a DropDownList on the second iframed page, but you can easily adapt to your needs: Main page (where the iframes are placed): <iframe id="iframe1" width="500" height="200" src="WebForm1.aspx"></iframe> <iframe id="iframe2" width="500" height="200" src="WebForm2.aspx"></iframe> First iframed page: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $("#ddl1").on("change", function () { // When the DropDownList selected value has been changed, // refresh the other iframed page changing its source // adding the value as its query string. $("#iframe2", parent.document).attr("src", "WebForm2.aspx?value=" + $(this).val()); return true; }); }); </script> <asp:DropDownList ID="ddl1" runat="server" AutoPostBack="true"> <asp:ListItem Text="Option 1" Value="1"></asp:ListItem> <asp:ListItem Text="Option 2" Value="2"></asp:ListItem> </asp:DropDownList> Second iframed page: <asp:DropDownList ID="ddl2" runat="server" AutoPostBack="true"> <asp:ListItem Text="Option 1" Value="1"></asp:ListItem> <asp:ListItem Text="Option 2" Value="2"></asp:ListItem> </asp:DropDownList> protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) ddl2.SelectedValue = Request.QueryString["value"]; } UPDATE Regarding your question posted on the comments, you can find out what's the second page iframe's src (and subsequently change it) this way: $("#iframe2", parent.document).attr("src", $("#iframe2", parent.document).attr("src") + "?value=" + $(this).val()); UPDATE #2 As per your request, you want to load the iframe source dynamically, at the page load. That's how you can achieve this: Main page (where the iframes are placed): <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $("#iframe2").attr("src", "the-page-you-want-to-load-on-this-iframe"); }); </script> <iframe id="iframe1" width="500" height="200" src="WebForm1.aspx"></iframe> <iframe id="iframe2" width="500" height="200"></iframe> First iframed page: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $("#ddl1").on("change", function () { var iframe2BaseSrc = $("#iframe2", parent.document).attr("src"); if (iframe2BaseSrc) { iframe2BaseSrc = iframe2BaseSrc.split("?")[0]; $("#iframe2", parent.document).attr("src", iframe2BaseSrc + "?value=" + $(this).val()); } return true; }); }); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/17728841", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Trouble with Jsfiddle I'm trying to make this Jsfiddle to demonstrate an issue but I can not get it to function properly, can anybody advise? This is the live demo site that I am recreating a Jsfiddle for. Here is my progress on the Jsfiddle. As you can see the thumbnails in my fiddle are not expanding and help would be greatly appreciated. /* var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-7243260-2']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); */ /* default.css */ @import url(//fonts.googleapis.com/css?family=Lato:300,400,700); html { height: 100%; } *, *:after, *:before { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; padding: 0; margin: 0; } /* Clearfix hack by Nicolas Gallagher: http://nicolasgallagher.com/micro-clearfix-hack/ */ .clearfix:before, .clearfix:after { content: " "; display: table; } .clearfix:after { clear: both; } .clearfix { *zoom: 1; } body { font-family: 'Lato', Calibri, Arial, sans-serif; background: #f9f9f9; font-weight: 300; font-size: 15px; color: #333; overflow: scroll; overflow-x: hidden; } a { color: #555; text-decoration: none; } .container { width: 100%; position: relative; } .container > header { width: 90%; max-width: 1240px; margin: 0 auto; position: relative; padding: 0 30px 50px 30px; } .container > header { padding: 60px 30px 50px; text-align: center; } .container > header h1 { font-size: 34px; line-height: 38px; margin: 0 auto; font-weight: 700; color: #333; } .container > header h1 span { display: block; font-size: 20px; font-weight: 300; } .main > p { text-align: center; padding: 50px 20px; } /* Header Style */ .codrops-top { line-height: 24px; font-size: 11px; background: #fff; background: rgba(255, 255, 255, 0.5); text-transform: uppercase; z-index: 9999; position: relative; box-shadow: 1px 0px 2px rgba(0,0,0,0.2); } .codrops-top a { padding: 0px 10px; letter-spacing: 1px; color: #333; display: inline-block; } .codrops-top a:hover { background: rgba(255,255,255,0.8); color: #000; } .codrops-top span.right { float: right; } .codrops-top span.right a { float: left; display: block; } /* Component.css */ .og-grid { list-style: none; padding: 20px 0; margin: 0 auto; text-align: center; width: 100%; } .og-grid li { display: inline-block; margin: 10px 5px 0 5px; vertical-align: top; height: 250px; } .og-grid li > a, .og-grid li > a img { border: none; outline: none; display: block; position: relative; } .og-grid li.og-expanded > a::after { top: auto; border: solid transparent; content: " "; height: 0; width: 0; position: absolute; pointer-events: none; border-bottom-color: #ddd; border-width: 15px; left: 50%; margin: -20px 0 0 -15px; } .og-expander { position: absolute; background: #ddd; top: auto; left: 0; width: 100%; margin-top: 10px; text-align: left; height: 0; overflow: hidden; } .og-expander-inner { padding: 50px 30px; height: 100%; } .og-close { position: absolute; width: 40px; height: 40px; top: 20px; right: 20px; cursor: pointer; } .og-close::before, .og-close::after { content: ''; position: absolute; width: 100%; top: 50%; height: 1px; background: #888; -webkit-transform: rotate(45deg); -moz-transform: rotate(45deg); transform: rotate(45deg); } .og-close::after { -webkit-transform: rotate(-45deg); -moz-transform: rotate(-45deg); transform: rotate(-45deg); } .og-close:hover::before, .og-close:hover::after { background: #333; } .og-fullimg, .og-details { width: 50%; float: left; height: 100%; overflow: hidden; position: relative; } .og-details { padding: 0 40px 0 20px; } .og-fullimg { text-align: center; } .og-fullimg img { display: inline-block; max-height: 100%; max-width: 100%; } .og-details h3 { font-weight: 300; font-size: 52px; padding: 40px 0 10px; margin-bottom: 10px; } .og-details p { font-weight: 400; font-size: 16px; line-height: 22px; color: #999; } .og-details a { font-weight: 700; font-size: 16px; color: #333; text-transform: uppercase; letter-spacing: 2px; padding: 10px 20px; border: 3px solid #333; display: inline-block; margin: 30px 0 0; outline: none; } .og-details a::before { content: '\2192'; display: inline-block; margin-right: 10px; } .og-details a:hover { border-color: #999; color: #999; } .og-loading { width: 20px; height: 20px; border-radius: 50%; background: #ddd; box-shadow: 0 0 1px #ccc, 15px 30px 1px #ccc, -15px 30px 1px #ccc; position: absolute; top: 50%; left: 50%; margin: -25px 0 0 -25px; -webkit-animation: loader 0.5s infinite ease-in-out both; -moz-animation: loader 0.5s infinite ease-in-out both; animation: loader 0.5s infinite ease-in-out both; } @-webkit-keyframes loader { 0% { background: #ddd; } 33% { background: #ccc; box-shadow: 0 0 1px #ccc, 15px 30px 1px #ccc, -15px 30px 1px #ddd; } 66% { background: #ccc; box-shadow: 0 0 1px #ccc, 15px 30px 1px #ddd, -15px 30px 1px #ccc; } } @-moz-keyframes loader { 0% { background: #ddd; } 33% { background: #ccc; box-shadow: 0 0 1px #ccc, 15px 30px 1px #ccc, -15px 30px 1px #ddd; } 66% { background: #ccc; box-shadow: 0 0 1px #ccc, 15px 30px 1px #ddd, -15px 30px 1px #ccc; } } @keyframes loader { 0% { background: #ddd; } 33% { background: #ccc; box-shadow: 0 0 1px #ccc, 15px 30px 1px #ccc, -15px 30px 1px #ddd; } 66% { background: #ccc; box-shadow: 0 0 1px #ccc, 15px 30px 1px #ddd, -15px 30px 1px #ccc; } } @media screen and (max-width: 830px) { .og-expander h3 { font-size: 32px; } .og-expander p { font-size: 13px; } .og-expander a { font-size: 12px; } } @media screen and (max-width: 650px) { .og-fullimg { display: none; } .og-details { float: none; width: 100%; } } <div class="container"> <!--/ Codrops top bar --> <header class="clearfix"> <h1>Thumbnail Grid <span>with Expanding Preview</span></h1> </header> <div class="main"> <ul id="og-grid" class="og-grid"> <li> <a href="#" data-largesrc="https://tympanus.net/Tutorials/ThumbnailGridExpandingPreview/images/thumbs/1.jpg" data-title="Azuki bean" data-description="Swiss chard pumpkin bunya nuts maize plantain aubergine napa cabbage soko coriander sweet pepper water spinach winter purslane shallot tigernut lentil beetroot."> <img src="https://tympanus.net/Tutorials/ThumbnailGridExpandingPreview/images/thumbs/1.jpg" alt="img01"/> </a> </li> <li> <a href="http://cargocollective.com/jaimemartinez/" data-largesrc="https://tympanus.net/Tutorials/ThumbnailGridExpandingPreview/images/thumbs/2.jpg" data-title="Veggies sunt bona vobis" data-description="Komatsuna prairie turnip wattle seed artichoke mustard horseradish taro rutabaga ricebean carrot black-eyed pea turnip greens beetroot yarrow watercress kombu."> <img src="https://tympanus.net/Tutorials/ThumbnailGridExpandingPreview/images/thumbs/2.jpg" alt="img02"/> </a> </li> <li> <a href="http://cargocollective.com/jaimemartinez/" data-largesrc="https://tympanus.net/Tutorials/ThumbnailGridExpandingPreview/images/thumbs/3.jpg" data-title="Dandelion horseradish" data-description="Cabbage bamboo shoot broccoli rabe chickpea chard sea lettuce lettuce ricebean artichoke earthnut pea aubergine okra brussels sprout avocado tomato."> <img src="https://tympanus.net/Tutorials/ThumbnailGridExpandingPreview/images/thumbs/3.jpg" alt="img03"/> </a> </li> <li> <a href="http://cargocollective.com/jaimemartinez/" data-largesrc="https://tympanus.net/Tutorials/ThumbnailGridExpandingPreview/images/thumbs/4.jpg" data-title="Sea lettuce" data-description="Bell pepper eggplant water spinach bell pepper radicchio kale artichoke earthnut pea beet greens carrot celtuce peanut radish mustard jícama tomato bamboo shoot quandong."> <img src="https://tympanus.net/Tutorials/ThumbnailGridExpandingPreview/images/thumbs/4.jpg" alt="img04"/> </a> </li> </ul> <p>Filler text by <a href="http://veggieipsum.com/">Veggie Ipsum</a></p> </div> </div><!-- /container --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script src="js/grid.js"></script> <script> $(function() { Grid.init(); }); </script> <script src="//tympanus.net/codrops/adpacks/demoad.js"></script>
{ "language": "en", "url": "https://stackoverflow.com/questions/50223665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JOIN query to DBF via VBA I apologize if this has been asked but i can't find where i'm going wrong here. I need to query (2) dbf tables AP and VENDOR which contain vendors and payables. I need to get a list of all the payables entered between two specified dates. ap_vendor contains the vendor ID in the AP table and v_vendor contains the vendor ID in the vendor table. I need to use a join to return the vendor name and the amount which are in separate tables. This is my query: SELECT a.ap_invamt, a.ap_invoice, b.v_name FROM AP a JOIN VENDOR b ON a.ap_vendor = b.v_vendor I need to add a WHERE clause as well but i cant even get this part to run. Keep getting error: "Syntax error in FROM clause" A: Unlike other SQL dialects, you cannot use just the word JOIN to specify an inner join in Access (JET) SQL. You have to use both keywords: a INNER JOIN b. Interestingly enough, I just tested it and JET does allow for LEFT JOIN and RIGHT JOIN, without the OUTER keyword. Change your query to read FROM AP a INNER JOIN Vendor b and it should work.
{ "language": "en", "url": "https://stackoverflow.com/questions/49060361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Update Field in ADO Recordset and Re-sort values in Classic ASP Here's the current situation: I have a recordset of products. The price of these products depends upon other information elsewhere on the page. So, as I loop through the recordset for output, I calculate the price using a function, and display it. This all works wonderfully. Now, for the new wrinkle. I need to be able to sort the products by the calculated price before I display them. My attempt was to simply add a new field to the recordset, loop through the recordset once to calculate the price and update that new field, and then resort the recordset on that field before looping again for the display. Needless to say, this does not work. No matter what settings (lockType, cursorType, cursorLocation) I put on this recordset, I am presented with an error stating "Current Recordset does not support updating. This may be a limitation of the provider, or of the selected locktype." Is there any way to make this work as described, or is there another method of accomplishing this result? For reference, here is the code snippet that I am currently working with. set rsProd = server.CreateObject("adodb.recordset") rsProd.cursorType = adOpenKeyset rsProd.lockType = adLockPessimistic rsProd.cursorLocation = adUseServer rsProd.Open sql, Conn1 'loop through the records and calculate prices' Do until rsProd.EOF laPrices = Split(GetParameterProductPrice(rsProd("Product_ID")), "|") 'ERROR OCCURS ON NEXT LINE' rsProd("Sale") = CDbl(laPrices(0)) rsProd("Sale_Special")= CDbl(laPrices(1)) rsProd.MoveNext Loop rsProd.MoveFirst rsProd.Sort = "Sale_Special, Sale, Product_Code" A: One way to accomplish this would be a computed column in your database. The main benefit would be that you wouldn't need to change your page(s). Additionally you could reuse the calculated price in other places in your application - I guess you actually calculate the price again on other parts of the site. A: If this recordset is not huge, one solution is during your loop, store your calculated price into an array. Once you've calculated the pricing, you can sort the array with a sorting function and then print out the results.
{ "language": "en", "url": "https://stackoverflow.com/questions/3056284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Loop to create dummies out of two df R for easier explanation I'm gonna use a smaller example. I have two DF: DF1: T01 T02 T03 T04 T05 1 15 20 48 25 5 2 12 18 35 30 12 3 13 15 50 60 42 DF2: MEDIAN SD T01 13 1.24 T02 18 2.05 T03 45 6.64 T04 30 15.45 T05 12 16.04 What I want to do is create a loop that adds a dummy to DF1 for each variable, that take value 1 if DF1$T01 ≈ (almost equal) to DF2$MEDIAN[1], and 0 if it's not, and then goes to T02, T03, until it breaks. Until now, I haven't been able to create a loop (I'm not really good at creating loops tho) that makes this. I did manage to make the dummy for one of the variables (T01), but in the real DF I have over 40 variables, so doing it by hand it´s not efficient at all. What I have right now is: DF1$dummyt01 <- ifelse(almost.equal(DF1$T01, DF2$MEDIAN[1], tolerance = 2),1,0) outcome expected: DF1: T01 T02 T03 T04 T05 dummyT01 dummyT02 ... dummyT05 1 15 20 48 25 5 1 1 ... 0 2 12 18 35 30 12 1 1 ... 1 3 13 15 50 60 42 1 0 ... 0 Note: Not a native english speaker. Sorry for any mistakes. EDIT: Expected Outcome. A: We may use tidyverse. Loop across the columns of 'DF1', get the column names of that column looped (cur_column()), use that to subset the 'DF2' (as row names) 'MEDIAN' element, do the comparison with almost.equal to return a logical vector, which is coerced to binary with as.integer or +. In the .names add the prefix 'dummy' so as to create as new columns library(dplyr) library(berryFunctions) DF1 <- DF1 %>% mutate(across(everything(), ~ +(almost.equal(., DF2[cur_column(), "MEDIAN"], tolerance = 1)), .names = "dummy{.col}")) -output DF1 T01 T02 T03 T04 T05 dummyT01 dummyT02 dummyT03 dummyT04 dummyT05 1 15 20 48 25 5 0 0 0 0 0 2 12 18 35 30 12 1 1 0 1 1 3 13 15 50 60 42 1 0 0 0 0 Or using a for loop for(i in seq_along(DF1)) DF1[paste0('dummy', names(DF1)[i])] <- +(almost.equal(DF1[[i]], DF2[names(DF1)[i], "MEDIAN"], tolerance = 1)) data DF1 <- structure(list(T01 = c(15L, 12L, 13L), T02 = c(20L, 18L, 15L), T03 = c(48L, 35L, 50L), T04 = c(25L, 30L, 60L), T05 = c(5L, 12L, 42L)), class = "data.frame", row.names = c("1", "2", "3")) DF2 <- structure(list(MEDIAN = c(13L, 18L, 45L, 30L, 12L), SD = c(1.24, 2.05, 6.64, 15.45, 16.04)), class = "data.frame", row.names = c("T01", "T02", "T03", "T04", "T05"))
{ "language": "en", "url": "https://stackoverflow.com/questions/69665173", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Selecting items with join and without foreign key I have query which gets each user's record from blacklist table and relations to them from rules table. It looks like that: $result1 = DB::table('blacklist') ->join('rules', 'blacklist.rule_id', '=', 'rules.id') ->select('blacklist.*', 'rules.clicks', 'rules.minutes') ->groupBy('blacklist.address') ->where('blacklist.user_id', JWTAuth::user()->id) ->get(); However I set field blacklist.rule_id as CAN BE NULL. Above query doesn't get records which have blacklist.rule_id == null(only these with values). I have second query for that purpose: $result2 = DB::table('blacklist') ->select('blacklist.*') ->groupBy('blacklist.address') ->where('blacklist.user_id', JWTAuth::user()->id) ->where('blacklist.rule_id', null) ->get(); But how to do it in one query? A: It is actually an leftJoin instead of join: $result1 = DB::table('blacklist') ->leftJoin('rules', 'blacklist.rule_id', '=', 'rules.id') ->select('blacklist.*', 'rules.clicks', 'rules.minutes') ->groupBy('blacklist.address') ->where('blacklist.user_id', JWTAuth::user()->id) ->get(); A: try this $result2 = DB::table('blacklist') ->select('blacklist.*') ->groupBy('blacklist.address') ->where(function ($result2) { $result2->where('blacklist.user_id', JWTAuth::user()->id) ->orWhereNull('blacklist.user_id'); } ->get();
{ "language": "en", "url": "https://stackoverflow.com/questions/52205772", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Facebook like box plugin not working on navigation I have added the facebook like box plugin code in my web application from https://developers.facebook.com/docs/plugins/like-box-for-pages In my application there is only one html with body tag and I am dynamically adding other html with only div tag as per requirement to that html. I added the following code in one of such divs. <div class="fb-like-box" data-href="http://www.facebook.com/drsailablog" data-width="265px" data-colorscheme="dark" data-show-faces="true" data-header="true" data-stream="false" data-show-border="true"> </div> I am following whatever mentioned in the directives to use the plugin i.e <body> <div id="fb-root"></div> <script> (function(d, s, id){ var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> Now the problem is, its showing the respective like box for the home page while it gets loaded for the first time, but when I move through navigation bar from one menu option to other, I am only able to see the container where I wanted to show like box and no content there. I checked the calls, its not even sending any request to facebook. but if I refresh the page its sending request and I am able to see the content again. What am I doing wrong?? I have tried adding this function within script tag in that div also but still same issue is there i.e loading only on refresh
{ "language": "en", "url": "https://stackoverflow.com/questions/22217014", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Instantiate a class created during runtime I created the demo below that does the following: * *User writes their class in the JTextArea provided. *Clicks on the Instantiate Class JButton to create a java file regarding the class created by the user. *Clicks on the Run JButton in order to actually use the created class (code commented). I don't know if this is the best approach (to creat a java file) to run a class created during runtime. However, in my actual project, I do need these created classes in .java files. I understand that Eclipse does not allow the commented part because at compiling time the compiler has no idea of what myClass is. How can I do this? Code: import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.FileNotFoundException; import java.io.PrintWriter; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JTextArea; public class Main { public static void main(String[] args) { JFrame frame = new JFrame("Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new GridLayout(1,3)); JTextArea editor = new JTextArea(); editor.setPreferredSize(new Dimension(400,400)); editor.setTabSize(4); editor.setText("public class myClass {\n" + "\tpublic int myValue;\n" + "\t\n" + "\tpublic myClass(int value){\n" + "\t\tmyValue = value;\n" + "\t}\n" + "\t\n" + "\tpublic int getValue() {\n" + "\treturn myValue;\n" + "\t}\n" + "}"); JButton instantiate = new JButton("Instantiate class"); JButton run = new JButton("Run"); frame.getContentPane().add(editor); frame.getContentPane().add(instantiate); frame.getContentPane().add(run); frame.pack(); frame.setVisible(true); instantiate.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { PrintWriter out = new PrintWriter("src/myClass.java"); out.println(editor.getText()); out.close(); } catch (FileNotFoundException e1) { e1.printStackTrace(); } } }); run.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //This is what I want to do //myClass myObject = new myClass(4); //System.out.println("My value is: " + myObject.getValue()); } }); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/53354183", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Operator Overloading Insertion What is Problem Here. It is not working as an expected. I want that << (insertion) Work For both cout and cin. #include<iostream> using namespace std; class a { private: string name; int age; unsigned long int salary; public: friend ostream& operator << (ostream& ,a ); friend istream& operator << (istream& ,a ); }; ostream& operator << (ostream& dout,a a1){ cout<<"Name = "<< a1.name<<"Age = "<<a1.age<<"Salary = "<<a1.salary<<end; return dout; } istream& operator << (istream& din,a& a1){ cout<<"Enter Your Name , Age , Salary .....Press Enter To Seperate New Value"<<end; cin>>a1.name>>a1.age>>a1.salary; } main(int argc, char const *argv[]) { a a1; cin<<a1; cout<<a1; return 0; } Error is too long. -> A: I am not sure WHY you want to do this, but it is possible. Just remember that simply because you can do something does not mean that you SHOULD do that thing (see C++ Faq Law of Least Surprise. Aside from violating the law of least surprise, you can do what you are trying to do, your code just has several simple compile errors in it that once fixed will work just fine (see here for working example). Here are the changes to make it compile: friend istream& operator << (istream& ,a& ); // Note the addition of the & // Here the variabe is dout, so change to dout. I also added some spacing ostream& operator << (ostream& dout,a a1){ dout<<"Name = "<< a1.name<<" Age = "<<a1.age<<" Salary = "<<a1.salary<<endl; return dout; } // Here you are using din, so you need to change to din, also you had end instead of endl istream& operator << (istream& din,a& a1){ cout<<"Enter Your Name , Age , Salary .....Press Enter To Seperate New Value"<<endl; din>>a1.name>>a1.age>>a1.salary; return din; } Just so the complete code is also in one easy place for you. Here is your entire program with the changes to make it compile. #include<iostream> using namespace std; class a { private: string name; int age; unsigned long int salary; public: friend ostream& operator << (ostream& ,a ); friend istream& operator << (istream& ,a& ); }; ostream& operator << (ostream& dout,a a1){ dout << "Name = "<< a1.name <<" Age = "<< a1.age <<" Salary = "<< a1.salary << endl; return dout; } istream& operator << (istream& din,a& a1){ cout <<"Enter Your Name , Age , Salary .....Press Enter To Seperate New Value" << endl; din >> a1.name >> a1.age >> a1.salary; return din; } main(int argc, char const *argv[]) { a a1; cin<<a1; cout<<a1; return 0; } Now, if we want to follow the Law of Least surprise, then we would change the istream operator overload to use >> instead of << and move the console text out of the >> operator overload and just present it to the user before reading the values. #include<iostream> using namespace std; class a { private: string name; int age; unsigned long int salary; public: friend ostream& operator << (ostream& ,a ); friend istream& operator >> (istream& ,a& ); }; // Note - Changed variable 'dout' to 'os' for clarity ostream& operator << (ostream& os, a a1){ os << "Name = " << a1.name << " Age = " << a1.age << " Salary = "<< a1.salary << endl; return os; } // Changed variable from 'din' to 'is' for clarity istream& operator >> (istream& is,a& a1){ is >> a1.name >> a1.age >> a1.salary; return is; } main(int argc, char const *argv[]) { a a1; cout << "Enter Your Name , Age , Salary .....Press Enter To Seperate New Value" << endl; cin >> a1; cout << a1; return 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/53781349", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cassandra Count Aggregate over intervals I have a table like CREATE TABLE table ( id text, time_stamp timestamp, value text, PRIMARY KEY (id, time_stamp) ) WITH CLUSTERING ORDER BY (time_stamp DESC) What I want is to obtain the counts in intervals of any arbitrary time unit. Example: { "start": "03-08-2016 00:00:00.000", "end": "03-08-2016 12:00:00.000", "interval": 1, "unit":"HOURS"} This would be the input to return a list of counts in a 12 hour interval, counting every 1 hour. The result I want is like [12, 2, 44, ..., 212]. I know I can do multiple select count(*) from table where time_stamp > '03-08-2016 00:00:00.000' and time_stamp < '03-08-2016 01:00:00.000' allow filtering; select count(*) from table where time_stamp > '03-08-2016 01:00:00.000' and time_stamp < '03-08-2016 02:00:00.000' allow filtering; But that would be multiple queries. Is there any way to do this faster? A: For custom count by intervals, you can create an User Defined Aggregate (UDA). Read my blob posts to avoid the caveats: UDF deep dive: http://www.doanduyhai.com/blog/?p=1876 UDF/UDA best practices & caveats: http://www.doanduyhai.com/blog/?p=2015
{ "language": "en", "url": "https://stackoverflow.com/questions/35874075", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Send post request from visitors network? Possible? I have an post request php code i use to get streaming urls so i can broadcast them to my visitors. Apparently other subscription service i use has stronger security and it requests that stream url be accessed only from the ip you firstly sent request from to get that streaming url. So i need when user opens channel1.php that actually post request is sent from his ip address (instead of my servers) so he can watch stream. Possible? Here is the code <?php $params = array ('password' => 'mypassword', 'username' => 'mysecretusername'); $query = http_build_query ($params); $contextData = array ( 'method' => 'POST', 'header' => "Connection: close\r\n". "Content-Length: ".strlen($query)."\r\n"."User-Agent: okhttp/2.5.0", 'content'=> $query ); $context = stream_context_create (array ( 'http' => $contextData )); $result = file_get_contents ( 'http://api.source.stream/streams/1/sign', // page url false, $context); $json = json_decode($result, true); $pink = $json[url]; echo $json[url]; ?> A: Maybe you would like to try something like this <script> // Sending and receiving data in JSON format using POST mothod // xhr = new XMLHttpRequest(); var url = "http://your.url.com/streams/1/sign"; xhr.open("POST", url, true); xhr.setRequestHeader("Content-type", "application/json"); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { var json = JSON.parse(xhr.responseText); console.log(json.username + ", " + json.password) } } var data = JSON.stringify({"username":"YOURUSERHERE","password":"YOURURLHERE"}); xhr.send(data); </script> But I really do not know how to print out answer in php from their server after you post it. I just know how to send it.
{ "language": "en", "url": "https://stackoverflow.com/questions/41226837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to install boost library using Conan? I'm trying to install boost library using Conan conan install boost/1.79.0@conan/stable but get: boost/1.79.0@conan/stable: Not found in local cache, looking in remotes... boost/1.79.0@conan/stable: Trying with 'conancenter'... ERROR: Unable to find 'boost/1.79.0@conan/stable' in remotes What could be the problem?
{ "language": "en", "url": "https://stackoverflow.com/questions/72716292", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: xcode \377 with an upside down '?' I'm programming with c++ in Xcode and I am trying to print out an array but all that prints is "\377" and an upside down '?' at the end of it. What does this mean? A: You probably generated whatever file you're reading on Windows in UTF-16. You should read and write your files in UTF-8. See \377\376 Appended to file (Windows -> Unix) for more details on this pretty common problem. If you need to read files in UTF-16 in C++, see std::codecvt. That will help you get it over to UTF-8, which is what most of the Mac libraries expect.
{ "language": "en", "url": "https://stackoverflow.com/questions/26978209", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google Maps v2 - onclick listener does not respond after orientation changes I am using Google Maps V2 in my app and when I change orientation to landscape (or basically change th eorientation), the onMapClick method does not respond and does nto respond even after the orientaiton changes again. I know I could avoid this weird bug by setting configChange:orientation|screenSize , but then layouts of my dialogues do not change their layout from layout-portrait to layout-landscape when orientaiton changes. This all is in one activity. Has anyone encountered this issue? What is wrong with the maps? I don´t understand where is the problem, why the listener should be unregistered. I register it in onCreateMethod: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); DisplayMetrics dm = getResources().getDisplayMetrics(); screenWidth = dm.widthPixels; screenHeight = dm.heightPixels; FontUtils.setCustomFont(this, (ViewGroup) getWindow().getDecorView()); RelativeLayout topBar = (RelativeLayout) findViewById(R.id.topBar); LinearLayout placeTextLayout = (LinearLayout)topBar .findViewById(R.id.placeTextLayout); placeTextView = (TextView) placeTextLayout.findViewById(R.id.placeText); sharedPrefs = getSharedPreferences (SkyConstants.PREFS_NAME,Context.MODE_PRIVATE); String place = sharedPrefs.getString (SkyConstants.PREF_LOCATION_ID,SkyConstants.PREF_LOCATION_DEFAULT); dateTextView = (TextView) topBar.findViewById(R.id.dateText); daysTextView = (TextView) topBar.findViewById(R.id.timeText); updateTopBar(); setUpMapIfNeeded(); } private void setUpMapIfNeeded() { if (mMap == null) { mMap = ((SupportMapFragment)getSupportFragmentManager() .findFragmentById(R.id.map)).getMap(); } if (mMap != null) { mMap.getUiSettings().setZoomControlsEnabled(true); mMap.getUiSettings().setZoomGesturesEnabled(true); mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN); mMap.setOnMapClickListener(new OnMapClickListener() { @Override public void onMapClick(LatLng point) { //do something } }); } } A: This is due to the creation of the view for the orientation, If you are in portrait mode, and you change to landscape, it creates again the view, and you need to set the onClickListener again. The same happens if you start the activity in landscape mode, to portrait. A: Setting map to null in onCreate() method helped as I needed to handle orientation changes by the system. so first I set mMap=null then I setup the map.
{ "language": "en", "url": "https://stackoverflow.com/questions/15552315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Remove positions in a vector containing characters that contains a specific letter I have the vector asset.name_vct with the following characters [1] "A3TV" "ABE" "ABG" "ABG.P_0" "ABG.P_1" "ACS" "ACX" "ACX_0" [9] "AENA" "AGS" "ALT" "AMS" "ANA" "ANA_0" "BBVA" "BKIA" [17] "BKIA_0" "BKT" "BME" "BTO_0" "BTO_1" "CABK" "CAR" "CIE" [25] "CIN" "CLNX" "COL" "COL_0" "CRI" "DIA" "EBRO_0" "EBRO_1" [33] "ELE" "ELE_0" "ENC" "ENG" "EVA" "FAD" "FCC" "FER" [41] "GRF" "IAG" "IBE" "IBLA" "IBR" "IDR" "ITX" "JAZ" [49] "LOR" "MAP" "MAP_0" "MAS" "MEL" "MRL" "MTS" "NHH_0" [57] "NHH_1" "NTGY" "OHL" "POP" "PRS_1" "REE" "REE_0" "REP" [65] "SAB" "SAN" "SCYR_0" "SCYR_1" "SGC" "SGRE" "SGRE_0" "TEF" [73] "TEM" "TL5" "TRE" "UNF" "VIS" "VIS_0" "ZEL" I would like to remove all positions that contains "_". A: You can use grepl() to create a boolean condition to filter your vector. Here's a reproducible example: vec <- c("ABC", "DEF", "A_C", "GHI", "JK_") vec[!(grepl("_", vec))] #> [1] "ABC" "DEF" "GHI" Created on 2020-05-15 by the reprex package (v0.3.0)
{ "language": "en", "url": "https://stackoverflow.com/questions/61824559", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can anyone help me figure out how to import this .txt file into my code? I'm working in VS on a repository in Github. I'm importing this stats.csv file into my code but the .readlines() call isn't printing anything. Does anyone know why? Thank you Tried many different import methods #this is our main code import os cmd = 'curl https://raw.githubusercontent.com/ksu-is/NFLQuarterbackstatIdentifier/master/stats.csv -o stats.txt' os.system(cmd) stats = open('stats.txt', 'a+') statheadings = stats.readlines() print(statheadings) print("123123") Should print the stats.csv file lines A: I tried your code, and it worked well without 'a+' option when open the text file. Your code shows nothing because you opened file as a 'wrting' mode. You should give the option as 'r' or 'r+' or just leave it as default. 'r' : open for reading (default) 'a' : open for writing, appending to the end of the file if it exists. '+' : open a disk file for updating (reading and writing) Try: stats = open('stats.txt') # select #stats = open('stats.txt','r') # one of #stats = open('stats.txt','r+') # these statheadings = stats.readlines() print(statheadings) It will work as well, and the result: ['404: Not Found\n'] If you want to check only a value, you can add index also. Print only the last line: print(satheadings[-1]) Result: 404: Not Found A: Rather than attempting to save the file to the disk first, you can just open it directly: import requests response = requests.get('https://raw.githubusercontent.com/ksu-is/NFLQuarterbackstatIdentifier/master/stats.csv') print(response.text) However, the URL that you're trying to access is giving me a 404. Is this because it's in a private repository? If so, you'll want to store it somewhere where it's publicly accessible so your program can reach it (or otherwise set up a more complicated authentication scheme).
{ "language": "en", "url": "https://stackoverflow.com/questions/57155310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding colour to greyscale image Im looking to add colour to a greyscale image; it doesnt have to be an accurate colour representation but adding a colour to a different shade of grey, this is just to identify different areas of interest within an image. E.g. areas of vegetation are likely to be of a similar shade of grey, by adding a colour to this range of values it should be clear which areas are vegetation, which are of water, etc. I have the code for getting colours from an image and storing them as a colour object but this doesnt seem to give a way to modify the values. E.g. if the grey vale is less than 85, colour red, if between 86 and 170 colour green and between 171 and 255 colour blue. I have no idea how this will look but in theory the resulting image should allow a user to identify the different areas. The current code I have for getting pixel value is below. int total_pixels = (h * w); Color[] colors = new Color[total_pixels]; for (int x = 0; x < w; x++) { for (int y = 0; y < h; y++) { colors[i] = new Color(image.getRGB(x, y)); i++; } } for (int i = 0; i < total_pixels; i++) { Color c = colors[i]; int r = c.getRed(); int g = c.getGreen(); int b = c.getBlue(); System.out.println("Red " + r + " | Green " + g + " | Blue " + b); } I appreciate any help at all! Thanks a lot A: You are going to have to choose your own method of converting colours from the greyscale scheme to whatever colour you want. In the example you've given, you could do something like this. public Color newColorFor(int pixel) { Color c = colors[pixel]; int r = c.getRed(); // Since this is grey, the G and B values should be the same if (r < 86) { return new Color(r * 3, 0, 0); // return a red } else if (r < 172) { return new Color(0, (r - 86) * 3, 0); // return a green } else { return new Color(0, 0, (r - 172) * 3); // return a blue } } You may have to play around a bit to get the best algorithm. I suspect that the code above will actually make your image look quite dark and dingy. You'd be better off with lighter colours. For example, you might change every 0 in the code above to 255, which will give you shades of yellow, magenta and cyan. This is going to be a lot of trial and error. A: I recommend you to take a look at Java2D. It has many classes that can make your life much easier. You may end up reinventing the wheel if you ignore it. Here is a short showcase of what you can do: int width = 100; int height = 100; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); image.getRGB(x, y); Graphics2D g2d = (Graphics2D)image.getGraphics(); g2d.setColor(Color.GREEN); g2d.fillRect(x, y, width, height);
{ "language": "en", "url": "https://stackoverflow.com/questions/19966164", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to round up and keep number of digits after decimal point in javascript If .950 display .950 If .954 display .955 If .956 display .960 If the value of the thousandths place is between .001 and .004 then round up to .005 If the thousands place is between .006 and .009 then round to .010 and do not drop the zero. A: Brutally: function formatValue(value) { var tempVal = Math.trunc(value * 1000); var lastValue = (tempVal % 10); if (lastValue > 0 && lastValue <= 5) lastValue = 5; else if (lastValue > 5 && lastValue <= 9) lastValue = 10; else lastValue = 0; return parseFloat((Math.trunc(tempVal / 10) * 10 + lastValue) / 1000).toFixed(3); } formatValue(3.656); // -> "3.660" formatValue(3.659); // -> "3.660" formatValue(3.660); // -> "3.660" formatValue(3.661); // -> "3.665" formatValue(3.664); // -> "3.665" formatValue(3.665); // -> "3.665" Pay attention: function returns a string (.toFixed returns a string).. (but however a fixed decimal length doesn't have any sense in a number) A: Rounding to a certain number of decimals is done by multiplying the value to bring the desired amount of decimals into the integer range, then getting rid of the remaining decimals, then dividing by the same multiplier to make it decimal again. Rounding to a "half-decimal" as you want is accomplished by doubling the multiplier (2X instead of 1X). The + 0.005 is to make it round up as desired, otherwise it would always round down. toFixed() is used to make the string representation of the value have the decimal part padded with zeros as needed. function formatValue(value) { return (Math.floor((value + 0.005) * 200) / 200).toFixed(3); } console.log(formatValue(1.950)); console.log(formatValue(1.954)); console.log(formatValue(1.956)); console.log(formatValue(1.003)); console.log(formatValue(1.007));
{ "language": "en", "url": "https://stackoverflow.com/questions/46753564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: ASP.NET MVC 2 JSONP with MVC Futures I´m using mvc futures 2 with WebApiEnabled for XML and JSON support. But due to cross domain issues with jQuery $.ajax I´m lookin in to JSONP. Is there a simple way to extend futures rest function for JSONP or should I do something else. Do anyone have some hints on this subject ? A: The REST for ASP.NET MVC SDK contains a Word file explaining how you could extend it by adding a custom format: ASP .NET MVC provides capability to return HTML. MVC REST adds out of the box support to return the two most popular formats for programmatic access on the web: XML and JSON. In addition, you can also handle additional formats. This section shows how you can add support for a custom format such as Atom using the provided extensibility. The process involves creating a custom Format Handler, and registering it to handle requests, responses, or both. The steps specific to enabling custom formats are described below: * *Create a custom format handler that may implement either or both of the interfaces IRequestFormatHandler and IResponseFormatHandler. *Register the custom format handler in global.asax in Application_Start In the included MovieApp sample you will find an implementation for AtomFormatHandler which you could use as a base for adding the JSONP functionality. I've also written a JsonpResult which you may take a look at.
{ "language": "en", "url": "https://stackoverflow.com/questions/2776441", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to check type of request (ajax or no) in onsubmit event? In my application forms sometimes is submitted directly, and sometimes by .ajaxForm() from jquery plugin. I want to know how form was submitted. Can I get know about this inside onsubmit event?. $(document).on('submit', 'form', function(e) { if (e.method_to_check_is request_was_ajax) // rest of code here }); After few comment I have to edit question. A: Your event is binded to your submit event, not to an ajax call at this point. However, if you wanted to implement a check to see what this submit is supposed to do, you could: Have this in your markup: <form id="my-id" class="my-forms" method="GET"> <button type="submit"></button> </form> And this in your js: $('#my-id').on('submit', function(e) { e.preventDefault(); var method = this.method; if (method === 'GET') { console.log(method); // do your ajax.get } if (method === 'POST') { console.log(method); // do your ajax.post } }); Of course, this example is contrived as this.method on $('#my-id') would always be 'GET'. However, you could instead change your selector to $('.my-forms') to intercept this event among all elements with the .my-forms class. A: According to your description it is not going to be an ajax request because you are using on('submit', function(){}); which is invoked when you submit html form and it would be an html request to server. If you still want to check type of if the request is GET or POST, you can check form's method attribute. $(document).on('submit', 'form', function(e) { e.preventDefault(); var method = this.method; if(method=='GET') //do something if(method=='POST') //do something });
{ "language": "en", "url": "https://stackoverflow.com/questions/35509160", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: create a variable with multiple product id retrived and insert through ajax in different table Insert multiple product_id into database with ajax. After successful checkout with more than one product. How can i insert it into different table (purchase). $.ajax({ type: "POST", url: "pages/ajax/insert.php", data: {product_id:product_id}, dataType: "JSON", success: function(data) { }, error: function(err) { alert(err); } }); }; this line of code works perfectly for one product but how can i use to send multiple product id. A: Perhaps the simplest is send a string parameter that is a delimited list of product IDs, you split this on the server and handle each ID as necessary. So the update might be: data: {product_ids: "1,2,10,99,500"}
{ "language": "en", "url": "https://stackoverflow.com/questions/48210888", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I fix the problem with Gmail? Gmail marked email with passed SPF, DKIM and DMARC as spam Gmail moves messages to spam folder. PTR records for ipv4 and ipv6 are available. I have the headers: SPF: PASS с IP-адресом 2a05:480:0:992f:0:0:0:2. DKIM: 'PASS', domain drom.com.ua DMARC: 'PASS' Delivered-To: vostoknefteproduct@gmail.com Received: by 2002:a9d:522:0:0:0:0:0 with SMTP id 31csp351612otw; Fri, 5 Apr 2019 05:26:18 -0700 (PDT) X-Google-Smtp-Source: APXvYqzWa1UxYEepV1tor3akYHi1DLXojOZnr61fkANdKlbOkDM880aGrAB9RzQdjipusdfEcAVt X-Received: by 2002:a2e:87d2:: with SMTP id v18mr7262855ljj.4.1554467178382; Fri, 05 Apr 2019 05:26:18 -0700 (PDT) ARC-Seal: i=1; a=rsa-sha256; t=1554467178; cv=none; d=google.com; s=arc-20160816; b=TTDI9m3Rt73dRkcImzRRAM5n98TJgwNxCnrbvKNVMAIOdrWk/iG+NU2OrR3/vDr7Gp fQmPmqt5QyEdZpO1G+He8uYckwETdCQFhVACDVcC5FJ8GWnWsys5p9vbFYzlYh89OZR+ gFfJkt+lb5z607n03Sr9zMW9HiJVBGKLr+SFCsG8u/AOmZCF9wZtGwaP69E+7b916njn WZ+Pz9Q/+DyDKaCOQWrdUlTS5GvrfK/c86/5lA0AjoZN90/Rj+uGlbIROqKUXoLbA/z3 G9LM9df3a6/kfAZBkzHB3PqCaiUhEKbSrcpLj1gT1fKHZKWOnkqb9hlcYwMX2OcHbpA8 zTtg== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=content-language:thread-index:mime-version:message-id:date:subject :to:from:dkim-signature; bh=qI0pd1OCLQLqqFvztD8zxwZ0XJBtraToDzc2t4i88s0=; b=uLJIPEtdroC8P6tqoyfOikNhNzEmtmNRGpgoOefyyN/0wdAqExsSoUxZ9UKLL31lST AT7J8/ZOEMuGa/wn1dSUHfwRqiZl7d/rxM+AtT2a1PaSSLulOgz9HQDGw1r81QXKnZMI XzsGpuPmz9e3apEtczYBM0E3zYjm5Z2ITmpnrk9MluAnEuqE370R/24ixS1W2+EEG4mY FXZ6AsImGfZGFr75zc9kLTPgBxa1hxghD0mu6RIACf45b5ljQZQuspj8kRyhw5NX30SA FRwg1TwRjm3N+kmaUiDv4M64Y7s1d/PU7Gr4rb33v8Ia/aEOpeFfKLs2NfKmiiuvqBh7 94vg== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@drom.com.ua header.s=dkim header.b=G8nYIwzB; spf=pass (google.com: domain of shop@drom.com.ua designates 2a05:480:0:992f::2 as permitted sender) smtp.mailfrom=shop@drom.com.ua; dmarc=pass (p=NONE sp=REJECT dis=NONE) header.from=drom.com.ua Return-Path: <shop@drom.com.ua> Received: from drom.com.ua (drom.com.ua. [2a05:480:0:992f::2]) by mx.google.com with ESMTPS id z24si17168655ljj.124.2019.04.05.05.26.18 for <vostoknefteproduct@gmail.com> (version=TLS1_2 cipher=ECDHE-RSA-AES128-GCM-SHA256 bits=128/128); Fri, 05 Apr 2019 05:26:18 -0700 (PDT) Received-SPF: pass (google.com: domain of shop@drom.com.ua designates 2a05:480:0:992f::2 as permitted sender) client-ip=2a05:480:0:992f::2; Authentication-Results: mx.google.com; dkim=pass header.i=@drom.com.ua header.s=dkim header.b=G8nYIwzB; spf=pass (google.com: domain of shop@drom.com.ua designates 2a05:480:0:992f::2 as permitted sender) smtp.mailfrom=shop@drom.com.ua; dmarc=pass (p=NONE sp=REJECT dis=NONE) header.from=drom.com.ua DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=drom.com.ua ; s=dkim; h=Content-Type:MIME-Version:Message-ID:Date:Subject:To:From:Sender: Reply-To:Cc:Content-Transfer-Encoding:Content-ID:Content-Description: Resent-Date:Resent-From:Resent-Sender:Resent-To:Resent-Cc:Resent-Message-ID: In-Reply-To:References:List-Id:List-Help:List-Unsubscribe:List-Subscribe: List-Post:List-Owner:List-Archive; bh=qI0pd1OCLQLqqFvztD8zxwZ0XJBtraToDzc2t4i88s0=; b=G8nYIwzBB+jpn8qK83ZCo7vu+m AM/RFrxq/PP8dITX1PNXqINAjHPSu2rBVsdE5QTMPDoaHYPbOeC9wFHFMfYspdy/JyQAh4A8hmSNz HgtnwRBVR14Nht8DAqeql7CCrOom0KNS0SQ95dTnOy42/5bFommziwUghHGgzyzjUav4=; Received: from [176.98.31.190] (helo=DESKTOPV2831BB) by drom.com.ua with esmtpsa (TLSv1.2:ECDHE-RSA-AES256-GCM-SHA384:256) (Exim 4.91) (envelope-from <shop@drom.com.ua>) id 1hCNvF-0000Rn-J9 for vostoknefteproduct@gmail.com; Fri, 05 Apr 2019 15:26:17 +0300 From: "DROM - служба обработки заказов" <shop@drom.com.ua> To: <vostoknefteproduct@gmail.com> Subject: Test title Date: Fri, 5 Apr 2019 15:26:17 +0300 Message-ID: <005901d4ebaa$c4b3ea80$4e1bbf80$@drom.com.ua> MIME-Version: 1.0 Content-Type: multipart/alternative; boundary="----=_NextPart_000_005A_01D4EBC3.EA0197B0" X-Mailer: Microsoft Outlook 16.0 Thread-Index: AdTrqr/vXGG/i/4HRdu0LENUGEwBuw== Content-Language: ru X-Scanned-By: ClamAV 0.101.1; Fri, 05 Apr 2019 15:26:17 +0300 Where can be the problem? Thanks A: Unfortunately this seems to be business as usual with gmail. Their spam filter seems entirely arbitrary and uncontrollable by recipients - for example adding addresses to your address book, marking messages as "not spam", or repeatedly moving messages from spam to your inbox does not help, and nor does following their guidelines, which include implementing measures such as SPF, DKIM and DMARC, just as you've done. On my own gmail account, I often find messages sent to myself end up in spam! Their postmaster tools are also broken - this is supposed to provide a feedback mechanism that allows server admins to see why IPs or domains are being blocked or spam filtered, however, it doesn't work properly, and it's very common to see domains & IPs marked as "bad" despite having zero spam reports. There is also no support available for postmaster tools, so you can't even report such problems. It might be worth trying anyway just see what they think of you. In short, you are entirely at google's mercy - even if you're doing everything that they ask, your messages may still get spam filtered, and you have no recourse.
{ "language": "en", "url": "https://stackoverflow.com/questions/55535533", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }