text
stringlengths
15
59.8k
meta
dict
Q: Entity Framework doesn't delete children, instead sets references to null I have the following situation: First the only relevant table/class (all auto generated from DB (MySQL)): The relevant part of the edmx file: <Association Name="navigationitem_ibfk_1"> <End Role="navigationitem" Type="Model.Store.navigationitem" Multiplicity="0..1"> <OnDelete Action="Cascade" /> </End> <End Role="navigationitem1" Type="Model.Store.navigationitem" Multiplicity="*" /> <ReferentialConstraint> <Principal Role="navigationitem"> <PropertyRef Name="id" /> </Principal> <Dependent Role="navigationitem1"> <PropertyRef Name="navigationitemid" /> </Dependent> </ReferentialConstraint> </Association> I think there aren't many more words needed: It's a navigation table, each navigationitem can have children (but it's not a must). Now when I try to remove a top level item which has a child: context.Remove(topLevelNode); context.SaveChanges(); It deletes the top level node in the DB, but at the child nodes it just sets the navigationitemid to null (and yes - I have defined on delete cascade in the DB, when I delete it directly there it works). So what I think it's going on is, that when I delete the parent node, the framework sets all navigationitemid of all children to NULL, then when the navigation should be saved to the DB it won't cascade the delete because the navigationitemid of the children are NULL. What can I do? Thank you. A: The obvious thing one would like to do is define cascade deletes on the association in the context. But trying it I found out that either sql server does not support it or EF needs help: * *Defining cascade delete on the foreign key constraint (using code-first) throws a sql server exception: Introducing FOREIGN KEY constraint 'xxx' on table 'yyy' may cause cycles or multiple cascade paths. (See here.) *Cascade delete in EF model: now when deleting a parent the child records are not deleted. Even worse: the FK fields are not nullified and the foreign key constraint violation will throw an exception. The remedy is to load the child collection before deleting the parent. Especially when deleting a tree of navigationitems this is not a very attractive option, but I'm afraid it's all you've got at the moment.
{ "language": "en", "url": "https://stackoverflow.com/questions/12859481", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to test angular2 app who implements jquery library I have an angular2 components who encapsulate some jquery library (timelineJS3). All works well, but i need write tests. Specifically i want listen click events. To do this i used Renderer2. But it's doesn't work properly with karma. See my code in plunkr https://embed.plnkr.co/7ROP9O2CgQolVeO5ItCb/ describe('- EventArray - ', () => { let events = cosmological.events; it('test click in next (idk how to fire jquery event)', async(() => { var i = 0; component.clicked.subscribe((ev: any) => { expect(ev.unique_id).toEqual(cosmological.events[i++].unique_id); }); //init component.events = events; component.ngAfterViewInit(); // trigger the click spyOn(component.clicked, 'emit'); let button = fixture.nativeElement.querySelector('.tl-slidenav-next .tl-slidenav-content-container'); button.dispatchEvent(new Event('click')); fixture.detectChanges(); fixture.whenStable().then(() => { expect(component.clicked.emit).toHaveBeenCalled(); }) })); }); this piece of code doesn't fire event in karma. Idk why. let button = fixture.nativeElement.querySelector('.tl-slidenav-next .tl-slidenav-content-container'); button.dispatchEvent(new Event('click')); A: First of all you should use debugElement of your fixture which will give you some useful methods for testing. One is triggerEventHandler which will help you with your issue (and just to mention: query would be another method that you will probably want to use often since it's way more powerful than querySelector and will return again a debugElement). let button: DebugElement = fixture.debugElement.query(By.css('.tl-slidenav-next .tl-slidenav-content-container')); button.triggerEventHandler('click', null); // where null is the event being passed if it's used in the listener Hope it helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/45574314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python script waiting for some program being launched and then starting another program. (Windows) I would like to write a python script that will finally be converted to .exe (with pyinstaller lets say) and added to windows startup applications list. This program (once launched) should 'monitor' user and wait until user will start a specified program (say program1.exe) and then my python program should launch another specified program (program2.exe). I know that there is something like subprocess to launch another program from python script but I was not able to make it work so far ;/ And as it comes to this part where I need to monitor if user does start specified program I have no idea haw to bite on this. I don't expect a complete solution (although it would be very nice to find such ;p) but any guides or clues would be very helpfull. A: For the monitoring whether or not the user has launched the program, I would use psutil: https://pypi.python.org/pypi/psutil and for launching another program from a python script, I would use subprocess. To launch something with subprocess you can do something like this: PATH_TO_MY_EXTERNAL_PROGRAM = r"C:\ProgramFiles\MyProgram\MyProgramLauncher.exe" subprocess.call([PATH_TO_MY_EXTERNAL_PROGRAM]) If it is as simple as calling an exe though, you could just use: PATH_TO_MY_EXTERNAL_PROGRAM = r"C:\ProgramFiles\MyProgram\MyProgramLauncher.exe" os.system(PATH_TO_MY_EXTERNAL_PROGRAM) Hope this helps. -Alex
{ "language": "en", "url": "https://stackoverflow.com/questions/35337398", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to Save Shared Preference Value in ClearData Application?[Android] In clear Data Android, Shared Preference is clear. I don't want it clear. A: If you clear the app data, shared preferences will also be cleared, you have to store in your database or cloud. A: there is a trick for that, it is not a normal way but works: <application android:label="MyApp" android:icon="@drawable/icon" android:manageSpaceActivity=".ActivityOfMyChoice"> by adding this line to your manifest instead of "Clear Data" button for "Manage Space" which launches ActivityOfMyChoice will be shown, it calls your activity and the Activity and you can finish your activity there like this: public class ActivityOfMyChoice extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); finish(); } } for me, this method worked! let me know about the result for more info, if you want to save your data even after "clear data" you might use the database to save your data and save your database in a file out of your application place in the device.
{ "language": "en", "url": "https://stackoverflow.com/questions/44786874", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Django image doesn't show up in template I bought bootstrap theme and tried to apply it on my django project. I almost done with it(css, js) except image files. This is what it looks like : Left one is my django project's view, right one is downloaded-source itself. As you can see here, css, js work well but only image doesn't show up. setting.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'collect_static') STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'collect_media') My project tree : ├── chacha_dabang │   ├── __init__.py │   ├── __pycache__ │   │   ├── __init__.cpython-35.pyc │   │   ├── settings.cpython-35.pyc │   │   ├── urls.cpython-35.pyc │   │   └── wsgi.cpython-35.pyc │   ├── settings.py │   ├── urls.py │   └── wsgi.py ├── db.sqlite3 ├── intro │   ├── __init__.py │   ├── __pycache__ │   │   ├── __init__.cpython-35.pyc │   │   ├── admin.cpython-35.pyc │   │   ├── urls.cpython-35.pyc │   │   └── views.cpython-35.pyc │   ├── admin.py │   ├── apps.py │   ├── migrations │   │   ├── __init__.py │   │   └── __pycache__ │   │   └── __init__.cpython-35.pyc │   ├── templates │   │   └── intro │   │   └── index.html │   ├── tests.py │   ├── urls.py │   └── views.py ├── manage.py ├── static │   ├── css │   │   ├── animate.min.css │   │   ├── blue.css │   │   ├── bootstrap.min.css │   │   ├── gray.css │   │   ├── green.css │   │   ├── main.css │   │   ├── navy.css │   │   ├── orange.css │   │   ├── owl.carousel.css │   │   ├── owl.transitions.css │   │   ├── pink.css │   │   ├── purple.css │   │   └── red.css │   ├── fonts │   │   ├── fontello │   │   │   ├── fontello-.eot │   │   │   ├── fontello-circle.eot │   │   │   ├── fontello-circle.svg │   │   │   ├── fontello-circle.ttf │   │   │   ├── fontello-circle.woff │   │   │   ├── fontello-social-.eot │   │   │   ├── fontello-social.eot │   │   │   ├── fontello-social.svg │   │   │   ├── fontello-social.ttf │   │   │   ├── fontello-social.woff │   │   │   ├── fontello.eot │   │   │   ├── fontello.svg │   │   │   ├── fontello.ttf │   │   │   └── fontello.woff │   │   └── fontello.css │   ├── images │   │   ├── art │   │   │   ├── client01.jpg │   │   │   ├── client02.jpg │   │   │   ├── client03.jpg │   │   │   ├── client04.jpg │   │   │   ├── client05.jpg │   │   │   ├── client06.jpg │   │   │   ├── client07.jpg │   │   │   ├── client08.jpg │   │   │   ├── client09.jpg │   │   │   ├── client10.jpg │   │   │   ├── client11.jpg │   │   │   ├── client12.jpg │   │   │   ├── human01.jpg │   │   │   ├── human02.jpg │   │   │   ├── human03.jpg │   │   │   ├── human04.jpg │   │   │   ├── human05.jpg │   │   │   ├── human06.jpg │   │   │   ├── humans01.jpg │   │   │   ├── image-background01.jpg │   │   │   ├── image-background02.jpg │   │   │   ├── image-background03.jpg │   │   │   ├── image-background04.jpg │   │   │   ├── office01.jpg │   │   │   ├── office02.jpg │   │   │   ├── office03.jpg │   │   │   ├── pattern-background01.jpg │   │   │   ├── pattern-background02.png │   │   │   ├── pattern-background03.png │   │   │   ├── photograph01-lg.jpg │   │   │   ├── photograph02.jpg │   │   │   ├── photograph03.jpg │   │   │   ├── photograph04-lg.jpg │   │   │   ├── product01.jpg │   │   │   ├── product02.jpg │   │   │   ├── product03.jpg │   │   │   ├── product04.jpg │   │   │   ├── product05.jpg │   │   │   ├── product06.jpg │   │   │   ├── screen-container.png │   │   │   ├── service01.jpg │   │   │   ├── slider01.jpg │   │   │   ├── slider02.jpg │   │   │   ├── slider03.jpg │   │   │   ├── slider04.jpg │   │   │   ├── slider05.jpg │   │   │   ├── slider06.jpg │   │   │   ├── work01-lg.jpg │   │   │   ├── work01.jpg │   │   │   ├── work02-lg.jpg │   │   │   ├── work02.jpg │   │   │   ├── work03.jpg │   │   │   ├── work04.jpg │   │   │   ├── work05.jpg │   │   │   ├── work05a.jpg │   │   │   ├── work06-lg.jpg │   │   │   ├── work06.jpg │   │   │   ├── work07.jpg │   │   │   ├── work08-lg.jpg │   │   │   ├── work08.jpg │   │   │   ├── work08a-lg.jpg │   │   │   ├── work08a.jpg │   │   │   ├── work08b-lg.jpg │   │   │   ├── work08b.jpg │   │   │   ├── work08c-lg.jpg │   │   │   ├── work08c.jpg │   │   │   ├── work08d-lg.jpg │   │   │   ├── work08d.jpg │   │   │   ├── work08e.jpg │   │   │   ├── work08f-lg.jpg │   │   │   ├── work08f.jpg │   │   │   ├── work08g-lg.jpg │   │   │   ├── work09-lg.jpg │   │   │   ├── work09.jpg │   │   │   ├── work10.jpg │   │   │   ├── work11.jpg │   │   │   ├── work12.jpg │   │   │   ├── work13.jpg │   │   │   ├── work14-lg.jpg │   │   │   ├── work15-lg.jpg │   │   │   ├── work15.jpg │   │   │   ├── work16-lg.jpg │   │   │   ├── work16.jpg │   │   │   ├── work17.jpg │   │   │   ├── work18.jpg │   │   │   ├── work19.jpg │   │   │   ├── work20.jpg │   │   │   ├── work21.jpg │   │   │   ├── work22.jpg │   │   │   ├── work23.jpg │   │   │   ├── work24.jpg │   │   │   └── work25.jpg │   │   ├── favicon.ico │   │   ├── grabbing.png │   │   ├── logo-white.svg │   │   └── logo.svg │   ├── js │   │   ├── bootstrap-hover-dropdown.min.js │   │   ├── bootstrap.min.js │   │   ├── google.maps.api.v3.js │   │   ├── html5shiv.js │   │   ├── jquery.easing.1.3.min.js │   │   ├── jquery.easytabs.min.js │   │   ├── jquery.form.js │   │   ├── jquery.isotope.min.js │   │   ├── jquery.min.js │   │   ├── jquery.validate.min.js │   │   ├── owl.carousel.min.js │   │   ├── respond.min.js │   │   ├── scripts.js │   │   ├── skrollr.min.js │   │   ├── skrollr.stylesheets.min.js │   │   ├── viewport-units-buggyfill.js │   │   ├── waypoints-sticky.min.js │   │   └── waypoints.min.js │   └── switchstylesheet │   └── switchstylesheet.js ├── templates │   └── base.html └── views ├── __init__.py ├── __pycache__ │   ├── __init__.cpython-35.pyc │   └── home.cpython-35.pyc └── home.py This is one of empty image html element showing up in Chrome development tool: And corresponding template source code : <div class="col-sm-6 inner-right-xs text-right"> <figure><img src="{% static 'images/art/product01.jpg' %}" alt=""></figure> </div> (There is {% load staticfiles %} on the top of template) This is urls.py: from django.conf.urls import url, include from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from views.home import Home # import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', Home.as_view(), name='home'), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) This is log when runserver : python manage.py runserver: (chacha_dabang) Chois@Chois-MacPro chacha_dabang $python manage.py runserver Performing system checks... System check identified no issues (0 silenced). You have unapplied migrations; your app may not work properly until they are applied. Run 'python manage.py migrate' to apply them. August 02, 2016 - 10:47:40 Django version 1.9.8, using settings 'chacha_dabang.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [02/Aug/2016 10:47:44] "GET / HTTP/1.1" 200 48896 [02/Aug/2016 10:47:44] "GET /static/css/bootstrap.min.css HTTP/1.1" 304 0 [02/Aug/2016 10:47:44] "GET /static/css/main.css HTTP/1.1" 304 0 [02/Aug/2016 10:47:44] "GET /static/css/owl.carousel.css HTTP/1.1" 304 0 [02/Aug/2016 10:47:44] "GET /static/css/green.css HTTP/1.1" 304 0 [02/Aug/2016 10:47:44] "GET /static/css/animate.min.css HTTP/1.1" 304 0 [02/Aug/2016 10:47:44] "GET /static/css/owl.transitions.css HTTP/1.1" 304 0 [02/Aug/2016 10:47:44] "GET /static/fonts/fontello.css HTTP/1.1" 304 0 [02/Aug/2016 10:47:44] "GET /static/images/logo.svg HTTP/1.1" 304 0 [02/Aug/2016 10:47:44] "GET /static/images/art/product01.jpg HTTP/1.1" 304 0 [02/Aug/2016 10:47:44] "GET /static/images/art/product02.jpg HTTP/1.1" 304 0 [02/Aug/2016 10:47:44] "GET /static/images/art/product03.jpg HTTP/1.1" 304 0 [02/Aug/2016 10:47:44] "GET /static/images/art/slider01.jpg HTTP/1.1" 304 0 [02/Aug/2016 10:47:44] "GET /static/images/art/work01.jpg HTTP/1.1" 304 0 [02/Aug/2016 10:47:44] "GET /static/images/art/work02.jpg HTTP/1.1" 304 0 [02/Aug/2016 10:47:45] "GET /static/images/art/work03.jpg HTTP/1.1" 304 0 [02/Aug/2016 10:47:45] "GET /static/images/art/work04.jpg HTTP/1.1" 304 0 [02/Aug/2016 10:47:45] "GET /static/images/art/work05.jpg HTTP/1.1" 304 0 [02/Aug/2016 10:47:45] "GET /static/images/art/work06.jpg HTTP/1.1" 304 0 [02/Aug/2016 10:47:45] "GET /static/images/art/work07.jpg HTTP/1.1" 304 0 [02/Aug/2016 10:47:45] "GET /static/images/art/product04.jpg HTTP/1.1" 304 0 [02/Aug/2016 10:47:45] "GET /static/images/art/product05.jpg HTTP/1.1" 304 0 [02/Aug/2016 10:47:45] "GET /static/images/art/product06.jpg HTTP/1.1" 304 0 [02/Aug/2016 10:47:45] "GET /static/images/art/slider02.jpg HTTP/1.1" 304 0 [02/Aug/2016 10:47:45] "GET /static/images/logo-white.svg HTTP/1.1" 304 0 [02/Aug/2016 10:47:45] "GET /static/images/art/slider03.jpg HTTP/1.1" 304 0 [02/Aug/2016 10:47:45] "GET /static/images/art/slider04.jpg HTTP/1.1" 304 0 [02/Aug/2016 10:47:45] "GET /static/images/art/slider05.jpg HTTP/1.1" 304 0 [02/Aug/2016 10:47:45] "GET /static/images/art/image-background04.jpg HTTP/1.1" 304 0 [02/Aug/2016 10:47:45] "GET /static/css/blue.css HTTP/1.1" 304 0 [02/Aug/2016 10:47:45] "GET /static/css/red.css HTTP/1.1" 304 0 [02/Aug/2016 10:47:45] "GET /static/css/pink.css HTTP/1.1" 304 0 [02/Aug/2016 10:47:45] "GET /static/css/purple.css HTTP/1.1" 304 0 [02/Aug/2016 10:47:45] "GET /static/css/orange.css HTTP/1.1" 304 0 [02/Aug/2016 10:47:45] "GET /static/css/navy.css HTTP/1.1" 304 0 [02/Aug/2016 10:47:45] "GET /static/css/gray.css HTTP/1.1" 304 0 [02/Aug/2016 10:47:45] "GET /assets/fonts/fontello/fontello.woff HTTP/1.1" 200 48896 [02/Aug/2016 10:47:45] "GET /assets/fonts/fontello/fontello-social.woff HTTP/1.1" 200 48896 [02/Aug/2016 10:47:45] "GET /assets/fonts/fontello/fontello.ttf HTTP/1.1" 200 48896 [02/Aug/2016 10:47:45] "GET /assets/fonts/fontello/fontello-social.ttf HTTP/1.1" 200 48896
{ "language": "en", "url": "https://stackoverflow.com/questions/38710625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: why so many errors are occuring in building the addon? I am unable to resolve these errors and also can't understand their cause.Can anybody help?I have also refreshed dependencies, it is occuring after that too. I uninstall and then installed g1ant from manage nutmeg package still I am facing this error. A: First we need to uninstall G1ANT robot from manage nutmeg package present under Project as it is old version and then go to browse menu and Search G1ANT there and install it and then try to build your addon. Hope it works! A: You might have to try 2 3 times . I had to re-install g1ant language package 2 times to stop receiving those errors. Also you can check reference to verify that whether g1ant language is un-installed and then re-install it.
{ "language": "en", "url": "https://stackoverflow.com/questions/62661238", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Stop TableView cell UIImage resizing in iOS I have a standard (i.e. not a custom) TableView cell with text and images, the problem is my images are different sizes and I want to put them in as something like UIViewContentModeScaleAspectFill. I simply want the UIImage to be 54x54 and not resizes all the time - I just want them square! There are lots of ideas out there but none of them work, the closest I came worked BUT the image was on top of the text (it added another image as a subview). I am not keen on using a custom cell as I use edit mode to drag stuff about and I have not figured that out yet with custom cells. EDIT I latest I have tried; UIImage *tempImage = [UIImage imageWithData:data]; CGSize size = CGSizeMake(54, 54); UIGraphicsBeginImageContext(size); [tempImage drawInRect:CGRectMake(0, 0, size.width, size.height)]; UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); cell.imageView.image = scaledImage; I have this in the cellForRow which I hoped would do it; cell.imageView.contentMode = UIViewContentModeScaleAspectFill; This only works on custom cells; - (void)layoutSubviews { [super layoutSubviews]; self.imageView.frame = CGRectMake(0,0,54,54); } This works well but it covers the text; UIImageView *imgView=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 54, 54)]; imgView.backgroundColor=[UIColor clearColor]; [imgView.layer setCornerRadius:8.0f]; [imgView.layer setMasksToBounds:YES]; [imgView setImage:[UIImage imageWithData: imageData]]; [cell.contentView addSubview:imgView]; This shows the exact problem I am having; Stackoverflow problem ANOTHER EDIT okay this worked, thanks; [cell setIndentationWidth:54]; [cell setIndentationLevel:1]; UIImageView *imgView=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 54, 54)]; imgView.backgroundColor=[UIColor clearColor]; [imgView.layer setMasksToBounds:YES]; [imgView setImage:myImages[indexPath.row]]; [cell.contentView addSubview:imgView]; A: I recommend you to subclass UITableViewCell and create your own custom cell :D but, anyway... try by adding this UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; UIImageView *imgView = nil; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier]; imgView=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 54, 54)]; imgView.backgroundColor=[UIColor clearColor]; imgView.contentMode = UIViewContentModeScaleAspectFill; imgView.tag = 123; [cell.contentView insertSubview:imgView atIndex:0]; [cell setIndentationWidth:54]; [cell setIndentationLevel:1]; } else { imgView = (UIImageView*)[cell.contentView viewWithTag:123]; } imgView.image = [UIImage imageNamed:@"myImage"];
{ "language": "en", "url": "https://stackoverflow.com/questions/18728224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I send datas from web page to serial port of visitor's computer? Possible Duplicate: How can I send data from a web page to a serial port? Is sending data from PHP web page to one of the serial ports of visitor's computer possible or not? If it is yes, how? If it is not, basicly, I want to write a client for a web backend that retrieves the data from the web and then writes the retrieved data to a serial port. Can you help about that? A: Not over the internet, as that would be very dangerous, the user would have to have special software. Otherwise web programs could (very) easily be used for malicious purposes.
{ "language": "en", "url": "https://stackoverflow.com/questions/14148981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to trigger a DataStage job once a SQL server job has completed? Currently there is a job in SQL server that is scheduled to runs several times a day. The SQL Job builds a file for the DataStage job that is scheduled shortly after the SQL server job, problem being that if the SQL job hasn't finished building the file, the DataStage job fails. Is there a trigger/query that can be added on SQL server to trigger DataStage job? A: Multiple solutions are possible: * *Start the DataStage job from command line (via dsjob) and schedule this job in the same scheduler (as the SQL server job) after that job (or schedule both in another common scheduler) *Use a wait for file stage in the DataStage Sequence. This could be configured to wait some time for the file. *Trigger the execution from a database trigger - I have done it for Db2 but it should be possible for you as well - maybe you have to write some code for that...
{ "language": "en", "url": "https://stackoverflow.com/questions/53535842", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Issue with JQuery Image Bubbles in IE I am trying to implement Jquery Image Bubbles as shown here: http://www.dynamicdrive.com/dynamicindex4/imagebubbles.htm However Im receiving a JavaScript error in my Fiddle: http://jsfiddle.net/NinjaSk8ter/hbMzV/ It was determined that loading the JavaScript file from the dynamicdrive Demo Page into the Fiddle would not function. Copying the JavaScript directly did function. A: I was receiving an error that the imgbubbles method does not exist. This means the resource wasn't being loaded into the fiddle. The solution was simple. Rather than trying to load the file into your page from the dynamicdrive domain, copy it to your project folder and load it from there. In your fiddle, I pulled the actual source for the plugin into the JavaScript panel, which resolved the issue of the missing method. Demo: http://jsfiddle.net/hbMzV/13/ (Tested in IE 7 to 10) A: JSLint says to throw in some semi-colons, like so: jQuery(document).ready(function($){ $('ul#orbs').imgbubbles({factor:3.15, speed:1500}); }); Looks like it works even without them though.
{ "language": "en", "url": "https://stackoverflow.com/questions/10113117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pixel-wise like assignment In Matlab Is there any good way to assignment some masked pixels with the same color except for-loop? %% pick a color cl = uisetcolor; %1-by-3 vector im = ones(3, 3, 3) / 2; % gray image mask = rand(3, 3); mask_idx = mask > 0.5; % create a mask %% Something like this im(mask_idx, :) = cl'; % assignment the pixels to color `cl` A: You could do it like this making use of repmat(): %% pick a color cl = uisetcolor; %1-by-3 vector im = ones(3, 3, 3)/2; % gray image mask = rand(3, 3); mask_idx = mask > 0.5; % create a mask cl_rep = repmat(cl,[sum(mask_idx(:)) 1]); im(repmat(mask_idx,[1 1 3])) = cl_rep(:); What I have done is to repeat the mask three times to get all three layers of the image. To be able to match this with the colour-vector cl it also has to be repeated. The number of times it is repeated is the same as the amount of pixels that are to be changed, sum(mask_idx(:)).
{ "language": "en", "url": "https://stackoverflow.com/questions/17586429", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Filtering out the outdated items from table my application is built using ruby on rails, backed by mysql DB It has 2 tables(models) - product(id, name, created_at, updated_at, etc.) and product_details(id, product_type, product_id, expires_on, created_at, updated_at, etc.) (connected by product ID column). I need to select only those active records OR product_ids from product model/table which satisfy either of the following criteria - the product details for that particular product are out-dated/expired(expires_on column is present in product_details table) or there is no entry for that product in product_details table at all(valid scenario in my use case) Please note that product_id is a foreign key which references product(id) Any help is greatly appreciated. Thanks in advance! :) A: Assuming that: class Product < ApplicationRecord has_one :product_detail end and class ProductDetail < ApplicationRecord belongs_to :product end You can use simple single-line query to fetch expired products or products without details: Product.select { |p| p.product_detail.nil? || p.product_detail.expires_on <= Date.today }
{ "language": "en", "url": "https://stackoverflow.com/questions/51064894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Assign name to other rows upon group condition I have a dataset which is of following nature. I would like to replace the names in "MAKE" column if the column contains "PQR" per unique country. country MAKE 1 USA PQR 2 USA ABC 3 UK PQR 4 UK DEF 5 JPN DEF 6 JPN LMN Desired Output: country MAKE 1 USA PQR 2 USA PQR 3 UK PQR 4 UK PQR 5 JPN OTHERS 5 JPN OTHERS A: One option is conditional aggregation with analytic functions: SELECT country, CASE WHEN SUM(CASE WHEN MAKE = 'PQR' THEN 1 ELSE 0 END) OVER (PARTITION BY country) > 0 THEN 'PQR' ELSE 'OTHERS' END AS MAKE FROM yourTable ORDER BY country; Demo
{ "language": "en", "url": "https://stackoverflow.com/questions/52984161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: QtWebView VS D3.js So, I have this school project I'm doing and I needed a visualization tool for the results of some of the processing being done by the software I'm developing. Since I'm using Qt for the software, I thought of using D3.js on top of a QtWebView widget. I'm currently testing with the Qt "Fancy browser" example a simple example of D3.js. I know that when I add Javascript in the index.html file, it works on the Fancy browser. For some reason, the Javascript used in the D3 script doesn't. The thing is, I'm fairly new to both Qt and D3.js, and as such I don't know if I'm missing something regarding the setup to make it possible, or if it's just incorrect code. Some doubts I had regarding this situation: - does QtWebView even support SVG elements in the HTML file? - I noticed that jQuery.js had to be added to the Fancy browser projects' resources in order for it to be evaluated by the application. As far as I could tell, this was done to enable the manipulation of the page's content using jQuery. Could it be that I have to do something similar with D3? If so, how? - It's very likely that nothing shows up because the instructions I'm giving to D3 aren't actually producing anything in the HTML file, how can I address that? I tried searching for information online about what I'm trying to achieve, but there aren't that many sources around. I found some stuff online regarding QtWebkit and Javascript, but unfortunately it's not helping me that much. One final note: in the machine I'm working on I can't access the web because it does not have outside access for everything. Furthermore, I can't even install a Webkit browser (like Chrome or something) for DOM inspection purposes, so it's not getting any simpler. :S Any help would be much appreciated, thank you all! A: So, by investigating about this question I got the following conclusions: * *QtWebView DOES support SVG elements in the HTML. I figure that this is true at least since Qt V4.7, since it is the one I'm presently using; *Still don't know why d3.min.js works and the "regular" d3.js doesn't; *D3.js doesn't have to be added to Qt's resources, calling it in the HTML file is enough. Hope this helps anyone finding the topic.
{ "language": "en", "url": "https://stackoverflow.com/questions/16079674", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to create "upload image " to registration form? I'm creating a website on wordpress. I wanted to add "upload image" part and after people registered, I'll check the image and if it's true image, I'll accept the registration. Like spotify. Spotify wants student certificate to be sure and if it’s right, after that, they allow to use spotify on student price. I know there are plugins but they aren't free. So, how can I do that for free? I searched for code or method but couldn't fide any source. A: Replace existing function function um_get_avatar_uri( $image, $attrs ) { $uri = false; $uri_common = false; $find = false; $ext = '.' . pathinfo( $image, PATHINFO_EXTENSION ); $custom_profile_photo = get_user_meta(um_user( 'ID' ), 'profile_photo', 'true'); if ( is_multisite() ) { //multisite fix for old customers $multisite_fix_dir = UM()->uploader()->get_upload_base_dir(); $multisite_fix_url = UM()->uploader()->get_upload_base_url(); $multisite_fix_dir = str_replace( DIRECTORY_SEPARATOR . 'sites' . DIRECTORY_SEPARATOR . get_current_blog_id() . DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, $multisite_fix_dir ); $multisite_fix_url = str_replace( '/sites/' . get_current_blog_id() . '/', '/', $multisite_fix_url ); if ( $attrs == 'original' && file_exists( $multisite_fix_dir . um_user( 'ID' ) . DIRECTORY_SEPARATOR . "profile_photo{$ext}" ) ) { $uri_common = $multisite_fix_url . um_user( 'ID' ) . "/profile_photo{$ext}"; } elseif ( file_exists( $multisite_fix_dir . um_user( 'ID' ) . DIRECTORY_SEPARATOR . "profile_photo-{$attrs}x{$attrs}{$ext}" ) ) { $uri_common = $multisite_fix_url . um_user( 'ID' ) . "/profile_photo-{$attrs}x{$attrs}{$ext}"; } elseif ( file_exists( $multisite_fix_dir . um_user( 'ID' ) . DIRECTORY_SEPARATOR . "profile_photo-{$attrs}{$ext}" ) ) { $uri_common = $multisite_fix_url . um_user( 'ID' ) . "/profile_photo-{$attrs}{$ext}"; } else { $sizes = UM()->options()->get( 'photo_thumb_sizes' ); if ( is_array( $sizes ) ) { $find = um_closest_num( $sizes, $attrs ); } if ( file_exists( $multisite_fix_dir . um_user( 'ID' ) . DIRECTORY_SEPARATOR . "profile_photo-{$find}x{$find}{$ext}" ) ) { $uri_common = $multisite_fix_url . um_user( 'ID' ) . "/profile_photo-{$find}x{$find}{$ext}"; } elseif ( file_exists( $multisite_fix_dir . um_user( 'ID' ) . DIRECTORY_SEPARATOR . "profile_photo-{$find}{$ext}" ) ) { $uri_common = $multisite_fix_url . um_user( 'ID' ) . "/profile_photo-{$find}{$ext}"; } elseif ( file_exists( $multisite_fix_dir . um_user( 'ID' ) . DIRECTORY_SEPARATOR . "profile_photo{$ext}" ) ) { $uri_common = $multisite_fix_url . um_user( 'ID' ) . "/profile_photo{$ext}"; } } } if ( $attrs == 'original' && file_exists( UM()->uploader()->get_upload_base_dir() . um_user( 'ID' ) . DIRECTORY_SEPARATOR . "profile_photo{$ext}" ) ) { $uri = UM()->uploader()->get_upload_base_dir() . um_user( 'ID' ) . "/profile_photo{$ext}"; } elseif ( file_exists( UM()->uploader()->get_upload_base_dir() . um_user( 'ID' ) . DIRECTORY_SEPARATOR . $custom_profile_photo ) ) { $uri = UM()->uploader()->get_upload_base_url() . um_user( 'ID' ) . DIRECTORY_SEPARATOR . $custom_profile_photo; } elseif ( file_exists( UM()->uploader()->get_upload_base_dir() . um_user( 'ID' ) . DIRECTORY_SEPARATOR . "profile_photo-{$attrs}x{$attrs}{$ext}" ) ) { $uri = UM()->uploader()->get_upload_base_url() . um_user( 'ID' ) . "/profile_photo-{$attrs}x{$attrs}{$ext}"; } elseif ( file_exists( UM()->uploader()->get_upload_base_dir() . um_user( 'ID' ) . DIRECTORY_SEPARATOR . "profile_photo-{$attrs}{$ext}" ) ) { $uri = UM()->uploader()->get_upload_base_url() . um_user( 'ID' ) . "/profile_photo-{$attrs}{$ext}"; } else { $sizes = UM()->options()->get( 'photo_thumb_sizes' ); if ( is_array( $sizes ) ) { $find = um_closest_num( $sizes, $attrs ); } if ( file_exists( UM()->uploader()->get_upload_base_dir() . um_user( 'ID' ) . DIRECTORY_SEPARATOR . "profile_photo-{$find}x{$find}{$ext}" ) ) { $uri = UM()->uploader()->get_upload_base_url() . um_user( 'ID' ) . "/profile_photo-{$find}x{$find}{$ext}"; } elseif ( file_exists( UM()->uploader()->get_upload_base_dir() . um_user( 'ID' ) . DIRECTORY_SEPARATOR . "profile_photo-{$find}{$ext}" ) ) { $uri = UM()->uploader()->get_upload_base_url() . um_user( 'ID' ) . "/profile_photo-{$find}{$ext}"; } elseif ( file_exists( UM()->uploader()->get_upload_base_dir() . um_user( 'ID' ) . DIRECTORY_SEPARATOR . "profile_photo{$ext}" ) ) { $uri = UM()->uploader()->get_upload_base_url() . um_user( 'ID' ) . "/profile_photo{$ext}"; } } if ( ! empty( $uri_common ) && empty( $uri ) ) { $uri = $uri_common; } $cache_time = apply_filters( 'um_filter_avatar_cache_time', current_time( 'timestamp' ), um_user( 'ID' ) ); if ( ! empty( $cache_time ) ) { $uri .= "?{$cache_time}"; } return $uri; }
{ "language": "en", "url": "https://stackoverflow.com/questions/65982576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP - Regex : I need help to build regex according these rules I need help building a regular expression for preg_match according these rules: * *first and last char- letter/digit only. *empty space not allowed *char can be only - letter/digit/'-'/'_'/'.' Legal examples: * *b.t612_rt *rut-be *rut7565 Not legal example: * *.btr78; btr78- (first/last allowed chars) *start end; star t end; (any empty space) *tr$be; tr*rt; tr/tr ... (not allowed chars) Edit: I remove 4 rule with neigbor chars '_'\'-'\'.' please help me. Thanks A: Try this regular expression: ^[A-Za-z0-9]+([-_.][A-Za-z0-9]+)*$ This matches any sequence that starts with at least one letter or digit (^[A-Za-z0-9]+) that may be followed by zero or more sequences of one of -, _, or . ([-_.]) that must be followed by at least one letter or digit ([A-Za-z0-9]+). A: Try this: ^[\p{L}\p{N}][\p{L}\p{N}_.-]*[\p{L}\p{N}]$ In PHP: if (preg_match( '%^ # start of string [\p{L}\p{N}] # letter or digit [\p{L}\p{N}_.-]* # any number of letters/digits/-_. [\p{L}\p{N}] # letter or digit $ # end of the string. %xu', $subject)) { # Successful match } else { # Match attempt failed } Minimum string length: Two characters. A: Well, for each of your rules: * *First and last letter/digit: ^[a-z0-9] and [a-z0-9]$ *empty space not allowed (nothing is needed, since we're doing a positive match and don't allow any whitespace anywhere): *Only letters/digits/-/_/. [a-z0-9_.-]* *No neighboring symbols: (?!.*[_.-][_.-]) So, all together: /^[a-z0-9](?!.*[_.-][_.-])[a-z0-9_.-]*[a-z0-9]$/i But with all regexes, there are multiple solutions, so try it out... Edit: for your edit: /^[a-z0-9][a-z0-9_.-]*[a-z0-9]$/i You just remove the section for the rule you want to change/remote. it's that easy... A: This seems to work fine for provided examples: $patt = '/^[a-zA-Z0-9]+([-._][a-zA-Z0-9]+)*$/';
{ "language": "en", "url": "https://stackoverflow.com/questions/4875659", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: json_encode will not encode more than 6670 rows Someone else had this issue back in '07, but it was not answered: in PHP, json_encode($someArray) silently fails (returns null) if the array has more than 6,670 rows. Does someone have a workaround. Limiting the size of the array to 6600, for example produces the expected result. I can do some do multiple json calls with partial arrays and concatenate results, but that involves some funky string manipulation to get them to stitch together properly, and I would like to avoid that. A: You could always just first slice the array into 2 parts (assuming it's not bigger then 2 times those rows). After that encode it, and add them together again. In case that isn't a solution, you need to increase your memory limit. Here is an example, test it here. On @GeertvanDijk suggestion, I made this a flexible function, in order to increase functionality! <?php $bigarray = array(1,2,3,4,5,6,7,8,9); function json_encode_big($bigarray,$split_over = 6670){ $parts = ceil((count($bigarray) / $split_over)); $start = 0; $end = $split_over; $jsoneconded = []; for($part = 0; $part < $parts; $part++){ $half1 = array_slice($bigarray,$start,$end); $name = "json".$part; $$name = ltrim(rtrim(json_encode($half1),"]"),"["); $jsoneconded[] = $$name; $start += $split_over; } return "[".implode($jsoneconded,",")."]"; } print_r(json_encode_big($bigarray)); ?> I have now test this with more rows then 6,670. You can test it online here as well. Now, I have to mention that I tested the normal json_encode() with a million rows, no problem. Yet, I still hope this solves your problem... In case that you run out of memory, you can set the memory_limit to a higher value. I would advice against this, instead I would retrieve the data in parts, and procces those in parts. As I don't know how you retrieve this data, I can't give an example how to regulate that. Here is how you change the memory in case you need to (sometimes it is the only option, and still "good"). ini_set("memory_limit","256M"); In this case, it is the dubbel from the default, you can see that it is 128M in this documentation A: Possibly depends on your PHP version and the memory allowed for use by PHP (and possibly the actual size of all the data in the array, too). What you could do if all else fails, is this: Write a function that checks the size of a given array, then split off a smaller part that will encode, then keep doing this until all parts are encoded, then join them again. If this is the route you end up taking, post a comment on this answer, and perhaps I can help you out with it. (This is based on the answer by Nytrix) EDIT, example below: function encodeArray($array, $threshold = 6670) { $json = array(); while (count($array) > 0) { $partial_array = array_slice($array, 0, $threshold); $json[] = ltrim(rtrim(json_encode($partial_array), "]"), "["); $array = array_slice($array, $threshold); } $json = '[' . implode(',', $json) . ']'; return $json; }
{ "language": "en", "url": "https://stackoverflow.com/questions/41817056", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Trigger event only on specific div when mouse is over I have six list items and I want to animate the single item only on mouse over. This is my snippet: <li> <div class="overview top_out">Eye</div> <div class="link bottom_out">link</div> <div class="image"></div> </li> <li> <div class="overview top_out">Eye</div> <div class="link bottom_out">link</div> <div class="image"></div> </li> // other same list items What I trying to do is to remove the "top_out" class when mouse in over the list item. I tried this: $("ul li").hover(function(){ $(".overview").toggleClass("top_out"); }); but what I obtained is that all divs react together. How can I do this? Here an example of what to obtain (section Portfolio): Esample site I want the same icon animation effect Thanks A: try: $('ul li').on('mouseenter mouseleave', function() { $(this).find('.overview').toggleClass('top_out'); }); A: You have to use the hovered over li as the context: $("ul li").hover(function(){ $(".overview", this).toggleClass("top_out"); }); Rather than .hover(function() ... you may want to use: .on('mouseenter mouseleave', function() ... $("ul li").on('mouseenter mouseleave', function(){ $(".overview", this).toggleClass("top_out"); }); .top_out { background-color: black; color: white; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <ul> <li> <div class="overview top_out">Eye</div> <div class="link bottom_out">link</div> <div class="image"></div> </li> <li> <div class="overview top_out">Eye</div> <div class="link bottom_out">link</div> <div class="image"></div> </li> </ul> A: It seems like you need to toggle the class based on the context of the element you are hovering over. Use the jQuery selector $(".overview", this) to select .overview elements within the li element that is currently being moused over. I also change the hover event to mouseover/mouseout. $("ul li").on('mouseover mouseout', function () { $(".overview", this).toggleClass("top_out"); }); Which is essentially equivalent to $("ul li").on('mouseover mouseout', function () { $(this).find(".overview").toggleClass("top_out"); });
{ "language": "en", "url": "https://stackoverflow.com/questions/28972823", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Silex security configuration I'm struggling with silex security: I have the following: $app->register(new Silex\Provider\SecurityServiceProvider()); and later on : $app['security.firewalls'] = array( 'admin' => array( 'pattern' => '^/admin', 'http' => true, 'users' => array( // raw password is foo 'admin' => array('ROLE_ADMIN', '5FZ2Z8QIkA7UTZ4BYkoC+GsReLf569mSKDsfods6LYQ8t+a8EW9oaircfMpmaLbPBh4FOBiiFyLfuZmTSUwzZg=='), ), ), ); but when i hit path "localhost/admin" Im getting: Found error: No route found for "GET /admin" cant understand the docs on page of silex rly.. Should I register security filters with controllers? Idefined as follows function in controller: public function admin(){ return 'Hello'; } and route for this is: $app->get('/admin', 'app.vendor_controller:admin'); now Im getting: Hello as soon as i hit path /admin , without authentication form. So there is no authentication proccess included... EDIT~~~~~~~~~~~~~~~~~~~~~ OK, so now after hitting url/admin I'm getting authentication banner with fields to put, as user and password, I'm typing admin , foo but there is no effect on this. `A username and password are being requested by http://localhost:8080. The site says: “Secured”` the code looks as follows: $app['security.firewalls'] = array( 'admin' => array( 'pattern' => '/admin', 'http' => true, 'users' => array( 'admin' => array('ROLE_ADMIN', 'foo') ))); $app['security.access_rules'] = array( array('/admin', 'ROLE_ADMIN'), ); $app->register(new Silex\Provider\SecurityServiceProvider(), array( 'security.firewalls' => array( 'pattern' => '/admin', 'http' => true, 'users' => array( // raw password is foo 'admin' => array('ROLE_ADMIN', 'foo'), )))); A: You configured a firewall that match every /admin* urls, but that don't mean that every URL requires authentication. You can be an anonymous user, and that would be fine. If you want tell silex that "the user need the ROLE_ADMIN to be allowed here", you need to add $app['security.access_rules'] = array( array('^/admin', 'ROLE_ADMIN'), );
{ "language": "en", "url": "https://stackoverflow.com/questions/40651436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Excel Macro - hide comment after edit I have this for entering a comment on a excel worksheet when user insert C or P, and I need to hide the comment after edit. Private Sub Worksheet_Change(ByVal Target As Range) Dim KeyCells As Range Set KeyCells = Range("A1:S1000") If Not Application.Intersect(KeyCells, Range(Target.Address)) _ Is Nothing Then Select Case Range(Target.Address) Case "C": minhaCelula = Target.Address Range(minhaCelula).AddComment ("") Range(minhaCelula).Comment.Visible = True Case "P": minhaCelula = Target.Address Range(minhaCelula).AddComment ("") Range(minhaCelula).Comment.Visible = True End Select End If End Sub A: Some problems with that code: * *Select Case Range(Target.Address) doesn't make sense - it takes the Target range, takes its address and creates a range from that address, which points to the original Target range, and finally VB takes the default property of that range, because its not being used in an object reference context. So the whole thing should be replaced with Target.Value. *Later same thing happens to minhaCelula. *Code under "C" and "P" is the same and should be placed under the same Case branch. *Colons are not used in VB's Select Case. *AddComment should be called without parentheses. Even better, you should benefit from the fact AddComment returns the reference to the added comment, so you can directly use that (in which case you must keep the parentheses). So that should be rewriteen as: Private Sub Worksheet_Change(ByVal Target As Range) If Not Application.Intersect(Me.Range("A1:S1000"), Target) Is Nothing Then Select Case Target.Value Case "C", "P" Target.AddComment("").Visible = True End Select End If End Sub As for the question, when you use Comment.Visible, Excel stops managing the comment's visibility. To leave the management on Excel side, make the comment's shape visible instead: Private Sub Worksheet_Change(ByVal Target As Range) If Not Application.Intersect(Me.Range("A1:S1000"), Target) Is Nothing Then Select Case Target.Value Case "C", "P" With Target.AddComment("").Shape .Visible = msoTrue .Select End With End Select End If End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/14221932", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Display one piece of a multidimensional array while entering another from a form? I need to be able to enter a String value, and have it input the id to that row on a table. I'm trying to get something like a select tag in HTML to work in Ruby. However I need it to programmatically change when new rows are added to the table I'm pulling the values from. The table itself looks something like this: Locations id location_cd | 1 | SLC| | 2 | LAS| etc. I used the Location class to pass these values from this table into an array. Here is the Location class. class Location < ActiveRecord::Base def self.select_options self.all.sorted.collect{ |q| [q.id, q.location_cd]} end end Doing this gives me this multidimensional array when I call the select_options method. [[1, "SLC"], [2, "LAS"]] Here's what I have in the controller. def edit @pallet = Pallet.find(params[:id]) @locations = Location.all end def update @pallet = Pallet.find(params[:id]) if @pallet.update_attributes(pallet_params) flash[:notice] = "Pallet Updated Successfully." redirect_to(:action => 'show', :id => @pallet.id) else @pallet_count = Pallet.count render('edit') end end Pallet is the main class I'm pulling from, and I need to enter the location.id into the pallets table. Here's what I have in edit. <%= link_to("<< Back to List", {:action => 'index'}, :class => 'back-link') %> <div class="pallets edit"> <h2>Update Pallet</h2> <%= form_for(:pallet, :url => {:action => 'update', :id => @pallet.id}) do |f| %> <%= render(:partial => "form", :locals => {:f => f}) %> <div class="form-buttons"> <%= submit_tag("Update Pallet") %> </div> <% end %> </div> This will redirect it to the form, and here's what I have in my form. This is where the problem I'm running into is. <table summary="Pallets from fields"> <tr> <th><%= f.label(:destination) %></th> </tr> <tr> <td><%= f.select(:destination, Location.select_options) %></td> </tr> </table> Doing this will give me a list of the ids like this. 1 2 However I want a list of the location_cds like this. SLC LAS But I need it to be to the point where I can enter SLC, and in the database it would enter 1 instead. To put this into the perspective of the multidimensional array I need to be able to enter the second value of [[1, "SLC"]] on the user side, and the first value(1) should be entered into the table. A: I did a lot of digging and I was able to find something that worked. There is a helper that comes with rails called options_for_select(). What this does is it will take something like this <%= select_tag(:destination, '<option value="1">SLC</option>...') %> And it will auto-generate the options using a multidimensional array Since I already had a multidimensional array by using the select_options method, I was able to use them both in conjunction with each other like so: <td><%= select_tag(:destination, options_for_select(Location.select_options)) %></td> This pulls up exactly what I needed, and appends the correct value to the database when selected. Another method is without the options_for_select helper, but it would need to have a parameter for which row is selected available. @pallet = Pallet.find(2) <td><%= select(:pallet, :destination, Location.select_options) %></td> The advantage of this one is that it automatically defaults to what was already there. This makes it easier for when you update something that isn't the location.
{ "language": "en", "url": "https://stackoverflow.com/questions/31928179", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding API key auth to existing API If we have a .NET API currently validating users through B2C flows on azure where the API validates the token from the FE with B2C. How could we implement functionality for daemons to consume the API as well if there is no user interaction to get a key from b2c? I believe this is called client credentials flow, but I know this does not exist on b2c? Any ideas on how we could achieve this? A: This workaround may work for your case. "Although the OAuth 2.0 client credentials grant flow is not currently directly supported by the Azure AD B2C authentication service, you can set up client credential flow using Azure AD and the Microsoft identity platform /token endpoint for an application in your Azure AD B2C tenant. An Azure AD B2C tenant shares some functionality with Azure AD enterprise tenants. To set up client credential flow, see Azure Active Directory v2.0 and the OAuth 2.0 client credentials flow. A successful authentication results in the receipt of a token formatted so that it can be used by Azure AD as described in Azure AD token reference".
{ "language": "en", "url": "https://stackoverflow.com/questions/71203390", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: dojo datagrid event attach issue I am working with IBM Content Navigator 2.0.3, that uses DOJO 1.8 for the GUI development. I am new in dojo, and I have to enhance one of the forms: add an event handler to the dataGrid so when the row of the grid is selected one of the buttons become enabled. dataGrid described in HTML as follows: <div class="selectedGridContainer" data-dojo-attach-point="_selectedDataGridContainer"> <div class="selectedGrid" data-dojo-attach-point="_selectedDataGrid" ></div> </div> And the JS file that controls the form behavior mentioned this _selectedDataGrid only once, in the postCreate function: postCreate: function() { this.inherited(arguments); this.textDir = has("text-direction"); this.hoverHelpList = []; domClass.add(this._selectedDataGridContainer, "hasSorting"); this._renderSelectedGrid(); _renderSelectedGrid() is being executed, which contains the only mention: _renderSelectedGrid: function() { ....... this._selectedDataGrid.appendChild(this._selectedGrid.domNode); I've tried to add an data-dojo-attach-event onRowClick: enableRemoveUsersButton in the HTML and a enableRemoveUsersButton: function(evt){ this.removeUsersButton.set('disabled', true); }, in js file. Didn't help. Then I tried: dojo.connect(myGrid, "onRowclick", function update() { this.removeUsersButton.set('disabled', true); }); but I couldn't acquire myGrid object using: `var myGrid = dojo.byId("_selectedDataGrid");` Can anyone tell me how to acquire the grid object and/or add an event handler to this grid, that fires when the row of the grid is selected? Thank you! A: You won't be able to get the grid object by dojo.byId("_selectedDataGrid"). It is better to keep the myGrid object at class level (widget level) and connect using dojo.hitch. dojo.connect(this.myGrid, 'onRowClick', dojo.hitch(this, function(){ //access myGrid using this.myGrid and do the handling })); A: From what you have share, I can see that the node "_selectedDataGrid" is just a Div tag. and your dataGrid widget may be "this._selectedGrid" so you should be add the event on that widget not the container node. Also there is dijit.byId to get the instance of dijits/widgets. and dojo.byId is used to search of dom nodes. Hope this was helpful.
{ "language": "en", "url": "https://stackoverflow.com/questions/37181933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android remove window background when it's not shown? I was watching Romain Guy's video(23:27) about how to make android's UI fast and efficient and I discovered that the window background is always redrawn, even if it can't be seen. However, as it's an old video, I'd like to know if this problem has been addressed or not? Is it a good practice to always set a nobackground theme to activities that don't need it?
{ "language": "en", "url": "https://stackoverflow.com/questions/23429593", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Aggregate series from DataFrame based on specific conditions I have the following data structure: sls srx stx hostname m @timestamp 0 1 21.1 389.2 A dev 2021-03-05 05:00:00.112965476+00:00 1 0 0.0 352.4 A dev 2021-03-05 05:00:00.263778044+00:00 2 0 0.0 351.5 A dev 2021-03-05 05:00:00.463778044+00:00 3 0 0.0 333.6 A dev 2021-03-05 05:00:00.663778044+00:00 4 1 13.8 379.1 A dev 2021-03-05 05:00:00.811431112+00:00 5 1 14.6 369.2 A dev 2021-03-05 05:00:01.011431112+00:00 6 1 15.4 359.3 A dev 2021-03-05 05:00:01.211431112+00:00 7 0 0.0 371.5 A dev 2021-03-05 05:00:01.459895995+00:00 8 1 64.1 353.8 A dev 2021-03-05 05:00:01.608929154+00:00 And I'm trying to compute a dataframe or series that looks like this: start end duration 0 2021-03-05 05:00:00.263778044+00:00 2021-03-05 05:00:00.811431112+00:00 0 days 00:00:00.547653068 1 2021-03-05 05:00:01.459895995+00:00 2021-03-05 05:00:01.608929154+00:00 0 days 00:00:00.149033159 So that I can compute the following things: * *Count of 0 to 1 transitions (including 0, 0, 0, 0, 1 sequences) - e.g. 2 for the above data *Total duration of these 0 to 1 transitions - e.g. 0.696686227 for the above data So the query is looking for the first row where sls is 0, then for the first row that is 1 after that. And it needs to do this for every occurrence of 0 (excluding those that are between a 0 and a 1). My naive impl. using pandas is: # @timestamp is a ISO8601 datetime string df['@timestamp'] = pd.to_datetime(df['@timestamp']) df['status_change'] = df['sls'].ne(df['sls'].shift()) df = df.drop(df.index[0]) start = df.loc[(df['sls'] == 0) & ( df['status_change'] == True)].reset_index() end = df.loc[(df['sls'] == 1) & ( df['status_change'] == True)].reset_index() series = pd.DataFrame() series['start'] = start['@timestamp'] series['end'] = end['@timestamp'] series['duration'] = series['end'] - series['start'] But I feel like there must be an easier way of doing this that would also result in better performance (currently, for 4M documents, it takes about 0:01:06.819145 which is not great). I'm just not sure how else to query the data in the way I described it so that performance is at least 2x better. A: perhaps you're lookig for groupby? df.groupby(by=["sls"]).sum() group by docs: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html
{ "language": "en", "url": "https://stackoverflow.com/questions/66539577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Mongodb: use $sample after $group I have the following data set: {company:"One", employee:"John"}, {company:"One", employee:"Mike"}, {company:"One", employee:"Donald"}, {company:"One", employee:"Mickey"}, {company:"Two", employee:"Johnny"}, {company:"Two", employee:"David"}, Ideally, I want a query that returns all distinct companies, number of employees for each company, random employee for each company {Company: "One" , employee_count=4, randomemployee="Donald"}, {Company: "Two" , employee_count=2, randomemployee="David"}, I do find a way to get company and employee_count using aggregate/group However I don't find a way to add the randomemployee with the same query. My aggregation: function aggr (collection,cb){ collection.aggregate(([{$group:{_id:'$company',total:{$sum:1}}},{$sort:{total:-1}}]),function(err, l1){ cb(null, l1) }) } I began an other Sample function: function onesample (collection,arg,cb){ collection.aggregate(([{ $match: { "company": arg }},{ $sample: { size: 1 }}]),function(err, item){ cb(null, item[0].employee) }) } But i'm loosing myself with callbacks and loop. Any elegant way to do this within one query? Thanks a lot. following your answer, I tried the following code. I have an issue with the callback of async.foreachof, seems it doesn't finish before leaving to next step: any clue? var async = require("async"); var MongoClient = require('mongodb').MongoClient; var assert = require('assert'); var url = 'mongodb://localhost:27017/eyc0'; async.waterfall ([ function(cb) { MongoClient.connect(url, function(err, db) { cb(null,db) }) }, function (db, cb) { db.collection('kodes', function(err, coll) { cb(null,db,coll) }) }, function (db,coll, cb) { var pipeline = [ {"$group": {"_id": "$ouat","total": { "$sum": 1}}}, {"$sort":{"total":-1} }, {"$project":{"_id": 0,"total":1,"company": "$_id"}}]; coll.aggregate(pipeline).toArray(function(err, dlist){ cb(null,db,coll,dlist) }) }, function (db,coll,dlist, cb) { // console.log(dlist) cb(null,db,coll,dlist) }, function (db,coll,dlist, cb) { var dlist2 = [] async.forEachOf( dlist, function(item, key, cb){ var pipeline = [{ "$match": { "ouat": item.company } },{ "$sample": { size: 1 } }]; coll.aggregate(pipeline, function (err, data) { item["randref"] = data[0].code; console.log(item.company) dlist2.push(item) cb() }); } ); cb(null,db,coll,dlist,dlist2); }, function (db,coll,dlist,dlist2, cb) { console.log(dlist2) console.log(dlist) }, ]) A: There's one approach that involves one query, it could be close but not as performant (as it uses $unwind) and won't give you the desired result (only the filtered company): var pipeline = [ { "$group": { "_id": "$company", "total": { "$sum": 1 }, "employees": { "$push": "$employee" } } }, { "$project": { "_id": 0, "company": "$_id", "employee_count": "$total" "randomemployee": "$employees" } }, { "$unwind": "$randomemployee" }, { "$match": { "company": arg } }, { "$sample": { size: 1 } } ]; collection.aggregate(pipeline, function(err, result){ console.log(result); }); However, for a solution that uses callbacks from multiple queries, this can be handled easily with use of async module. To get all distinct companies, number of employees for each company, random employee for each company consider using the async.waterfall() function where the first task returns the aggregation results with all distinct companies and number of employees for each company. The second task uses the results from taks 1 above to iterate over using async.forEachOf(). This allows you to perform an asynchronous task for each item, and when they're all done do something else. With each document from the array, run the aggregation operation that uses the $sample operator to get a random document with the specified company. With each result, create an extra field with the random employee and push that to an array with the final results that you can access at the end of each task. Below shows this approach: var async = require("async"); async.waterfall([ // Load full aggregation results (won't be called before task 1's "task callback" has been called) function(callback) { var pipeline = [ { "$group": { "_id": "$company", "total": { "$sum": 1 } } }, { "$project": { "_id": 0, "company": "$_id", "employee_count": "total" } } ]; collection.aggregate(pipeline, function(err, results){ if (err) return callback(err); callback(results); }); }, // Load random employee for each of the aggregated results in task 1 function(results, callback) { var docs = [] async.forEachOf( results, function(value, key, callback) { var pipeline = [ { "$match": { "company": value.company } }, { "$sample": { size: 1 } } ]; collection.aggregate(pipeline, function (err, data) { if (err) return callback(err); value["randomemployee"] = data[0].employee; docs.push(value); callback(); }); }, function(err) callback(null, docs); } ); }, ], function(err, result) { if (err) return next(err); console.log(JSON.stringify(result, null, 4)); } ); With the the async.series() function, this is useful if you need to execute a set of async functions in a certain order. Consider the following approach if you wish to get the all the distinct companies and their employee count as one result and the other random employee as another: var async = require("async"), locals = {}, company = "One"; async.series([ // Load random company function(callback) { var pipeline = [ { "$match": { "company": company } }, { "$sample": { size: 1 } } ]; collection.aggregate(pipeline, function(err, result){ if (err) return callback(err); locals.randomcompany = result[0]; callback(); }); }, // Load full aggregation results (won't be called before task 1's "task callback" has been called) function(callback) { var pipeline = [ { "$group": { "_id": "$company", "total": { "$sum": 1 } } }, { "$project": { "_id": 0, "company": "$_id", "employee_count": "total" } } ]; collection.aggregate(pipeline, function(err, result){ if (err) return callback(err); locals.aggregation = result; callback(); }); } ], function(err) { //This function gets called after the two tasks have called their "task callbacks" if (err) return next(err); //Here locals will be populated with 'randomcompany' and 'aggregation' console.log(JSON.stringify(locals, null, 4)); } ); A: db.comp.aggregate([ {$group:{_id:'$company',emp:{$addToSet:'$employee'}}}, {$project:{emp:1,employee_count:{'$size':'$emp'}, randomvalue:{'$literal':Math.random()}}}, {$project:{emp:1,employee_count:1, randomposition:{'$floor': {'$multiply':['$randomvalue', '$employee_count']}}}}, {$project:{'Company':'$_id', _id:0, employee_count:1, randomemployee:{'$arrayElemAt':['$emp','$randomposition']}}}, {$sort:{Company:1}} ]) Seems to work! A couple of results: { "employee_count" : 4, "Company" : "One", "randomemployee" : "Mike" } { "employee_count" : 2, "Company" : "Two", "randomemployee" : "Johnny" } { "employee_count" : 4, "Company" : "One", "randomemployee" : "Mickey" } { "employee_count" : 2, "Company" : "Two", "randomemployee" : "David" }
{ "language": "en", "url": "https://stackoverflow.com/questions/35311956", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: can't enable windows authentication in IIS I've disabled anonymous authentication and I've enabled Windows authentication on my website in IIS 7. Now, when I browse to the website (http://webserver), Internet Explorer keeps prompting me for a username/password. Since I'm on the intranet, IE should pass on my credentials automatically... What's more is that if I enter my credentials, they are not even recognized. I'm out of ideas, if anyone could help....
{ "language": "en", "url": "https://stackoverflow.com/questions/10216571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Plone/Paster - What could cause "paster addcontent dexterity_content" to not work? I'm trying to use paster to create a dexterity content type. I did a new standalone installation of Plone 4.3.4 in a target folder that's different from the one I was previously working with so it was buildout-cache would be clean. The OS I am using is Ubuntu 14.04. So in my downloads folder, in the installer's folder I extracted, I type in the terminal: ./install.sh --target=/home/myusername/Plone2 --instance=MyProject standalone That installs correctly. Then I go to MyProject in Plone2. I edit the buildout to change my password, and the run buildout: buildout -c develop.cfg Then I goto the src folder and create a new product with zopeskel: ../bin/zopeskel dexterity project.house Then I edit my buildout and under eggs I add project.house and under develop, src/project.house. Then I run buildout again and it builds out correctly. Then in the project.house folder under sources, I try running paster. ../../bin/paster addcontent dexterity_content Then I end up with an error: Traceback (most recent call last): File "../../bin/paster", line 264, in <module> sys.exit(paste.script.command.run()) File "/home/pjdowney/Plone2/buildout-cache/eggs/PasteScript-1.7.5-py2.7.egg/paste/script/command.py", line 104, in run invoke(command, command_name, options, args[1:]) File "/home/pjdowney/Plone2/buildout-cache/eggs/PasteScript-1.7.5-py2.7.egg/paste/script/command.py", line 143, in invoke exit_code = runner.run(args) File "/home/pjdowney/Plone2/buildout-cache/eggs/PasteScript-1.7.5-py2.7.egg/paste/script/command.py", line 238, in run result = self.command() File "/home/pjdowney/Plone2/buildout-cache/eggs/ZopeSkel-2.21.2-py2.7.egg/zopeskel/localcommands/__init__.py", line 70, in command self._extend_templates(templates, args[0]) File "/home/pjdowney/Plone2/buildout-cache/eggs/ZopeSkel-2.21.2-py2.7.egg/zopeskel/localcommands/__init__.py", line 204, in _extend_templates tmpl = entry.load()(entry.name) File "/home/pjdowney/Plone2/buildout-cache/eggs/setuptools-7.0-py2.7.egg/pkg_resources.py", line 2184, in load ['__name__']) ImportError: No module named dexterity.localcommands.dexterity I did recently install Plone 4.3.6 in another target folder. Unfortunately, I never tried using paster because I was creating dexterity content through the web. Could switching to 4.3.6 have ruined everything? My earlier target folder works still though. A: Throwing ""ImportError: No module named dexterity.localcommands.dexterity" + "plone" into a searchengine leads straight to Plone 4.3.4 - ImportError: No module named dexterity.localcommands.dexterity where S. McMahon states it's a bug reported in https://github.com/plone/Installers-UnifiedInstaller/issues/33 and already fixed for Plone-5-installers, but not for Plone-4. The bug is likely caused of the newest setuptools-version and FWIW, I accidentally found these infos one day in the tweets of "glyph", which look helpful: "Public Service Announcement: make @dstufft’s life easier, and do not use the `python-pip´ package from Debian or Ubuntu. It’s broken." (1) "Instead, install pip and virtualenv with get-pip.py, ideally into your home directory. (Sadly, https://pip2014.com/ is still relevant.)" (2) I will have a closer look at the salvation-promising-script get-pip.py, when running into probs again, but for now, I simply don't upgrade anything :-D (1)https://twitter.com/glyph/status/640980540691234816 (2)https://twitter.com/glyph/status/640980540691234816 A: (copied from my own comment on a similar issue in github) I've had fights like this in the past with zopeskel / paster. Nowadays though I avoid it.... choosing to use: * *mrbob for templating eggs *creating dexterity types through the web see plone training *OR alternatively creating dexterity types directly in code without templating - there's a lot less boilerplate code in dexterity cf archetypes I suspect your issue is because your install of 4.3.6 may have upgraded zopeskel or one of it's dependencies to something with different requirements on localcommands/templates. If you want to continue this fight (and I don't recommend it), then you could try pinning all your zopeskel dependencies to latest versions (though Zopeskel has to be less than 3.0 I believe)
{ "language": "en", "url": "https://stackoverflow.com/questions/32594231", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to create groups of N elements from a PCollection Apache Beam Python I am trying to accomplish something like this: Batch PCollection in Beam/Dataflow The answer in the above link is in Java, whereas the language I'm working with is Python. Thus, I require some help getting a similar construction. Specifically I have this: p = beam.Pipeline (options = pipeline_options) lines = p | 'File reading' >> ReadFromText (known_args.input) After this, I need to create another PCollection but with a List of N rows of "lines" since my use case requires a group of rows. I can not operate line by line. I tried a ParDo Function using variables for count associating with the counter N rows and after groupBy using Map. But these are reset every 1000 records, so it's not the solution I am looking for. I read the example in the link but I do not know how to do something like that in Python. I tried saving the counters in Datastore, however, the speed difference between Dataflow reading and writing with Datastore is quite significant. What is the correct way to do this? I don't know how else to approach it. Regards. A: Assume the grouping order is not important, you can just group inside a DoFn. class Group(beam.DoFn): def __init__(self, n): self._n = n self._buffer = [] def process(self, element): self._buffer.append(element) if len(self._buffer) == self._n: yield list(self._buffer) self._buffer = [] def finish_bundle(self): if len(self._buffer) != 0: yield list(self._buffer) self._buffer = [] lines = p | 'File reading' >> ReadFromText(known_args.input) | 'Group' >> beam.ParDo(Group(known_args.N) ...
{ "language": "en", "url": "https://stackoverflow.com/questions/49495336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Adobe SiteCatalyst:How to export the groups with list of usernames and report suite i am working on Adobe SiteCatalyst. i am able to download the groups with column names Group Name,Description,Users and Report Suites. In above list am getting count of users and report suites.but i need a exact name instead of count how this can be done using Adobe Site Catalyst.. Please help me.. A: I don't know of a built in report that will get you this. If there is a small number of users and you don't need to do it very often then you can do this manually. But it would be a pain. If you think it is worth investing some time into this because you have a lot of users and/or you need to do this report often then you can use the Enterprise API to automate this report. You will need to create a user with the Web Services permission. Then using that username and secret (be careful to use the exact format from the Admin tools->Company Settings->Web Services as there is a "loginCompany:username" format and special Shared Secret) Then you can use the APIs assuming you have some development experience. This is a good starting point. https://developer.omniture.com/en_US/get-started/api-explorer#Permissions.GetGroup and also look at GetGroups. Best of luck C.
{ "language": "en", "url": "https://stackoverflow.com/questions/20612770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Fluent Validation C# Unique Id in collection I have an entity that has a nested collection as a property which I will receive from a front-end application. I just want to make sure that each item in this collection(ICollection ChildClassCollection) has a unique Id within the model I have received. I am using FluentValidation and would like to add this validation using it too for consistency. It's something very simple I couldn`t find an elegant way to solve.. An example: public class ParentClass { public string Name { get; set; } public ICollection<ChildClass> ChildClassCollection { get; set; } } public class ChildClass { public int Id { get; set; } public string Name { get; set; } } A: Use HashSet. https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1?view=netframework-4.7.2 public class ParentClass { public string Name { get; set; } public HashSet<ChildClass> ChildClassCollection { get; set; } } public class ChildClass { public int Id { get; set; } public string Name { get; set; } } A: Here is what I ended up with: PRetty cleand, plus, when it encounters issue, it will exit this.RuleFor(or => or.ChildClassCollection) .Must(this.IsDistinct) .WithMessage("There are more than one entity with the same Id"); public bool IsDistinct(List<UpdateRoleDTO> elements) { var encounteredIds = new HashSet<int>(); foreach (var element in elements) { if (!encounteredIds.Contains(element.Id)) { encounteredIds.Add(element.Id); } else { return false; } } return true; } A: Do you want to use only fluentValidator to achieve this without any relationship? If so, you can custom a validator,then use some logic to confirm whether there is a duplicate value in database,like this: public class ChildClassValidator : AbstractValidator<ChildClass> { private readonly MyDbContext _context; public ChildClassValidator(MyDbContext context) { _context = context; RuleFor(x => x.Id).NotEmpty().WithMessage("ID is required.").Must(IsUnique).WithMessage("parent have more than one ids"); } private bool IsUnique(int id) { var model = _context.ParentClasses.GroupBy(x => x.Id) .Where(g => g.Count() > 1) .Select(y => y.Key) .ToList(); //judge whether parentclass has duplicate id if (model==null) return true; else return false; } } A: I use mine custom helper, based by ansver: Check a property is unique in list in FluentValidation. Because the helper is much more convenient to use than each time to describe the rules. Such a helper can be easily chained with other validators like IsEmpty. Code: public static class FluentValidationHelper { public static IRuleBuilder<T, IEnumerable<TSource>> Unique<T, TSource, TResult>( this IRuleBuilder<T, IEnumerable<TSource>> ruleBuilder, Func<TSource, TResult> selector, string? message = null) { if (selector == null) throw new ArgumentNullException(nameof(selector), "Cannot pass a null selector."); ruleBuilder .Must(x => { var array = x.Select(selector).ToArray(); return array.Count() == array.Distinct().Count(); }) .WithMessage(message ?? "Elements are not unique."); return ruleBuilder; } } Usage: For example we want to choose unique id RuleFor(_ => _.ChildClassCollection!) .Unique(_ => _.Id); Or want choose unique id and name RuleFor(_ => _.ChildClassCollection!) .Unique(_ => new { _.Id, _.Name }); Update I optimization performance using code from answer YoannaKostova public static class FluentValidationHelper { public static bool IsDistinct<TSource, TResult>(this IEnumerable<TSource> elements, Func<TSource, TResult> selector) { var hashSet = new HashSet<TResult>(); foreach (var element in elements.Select(selector)) { if (!hashSet.Contains(element)) hashSet.Add(element); else return false; } return true; } public static IRuleBuilder<T, IEnumerable<TSource>> Unique<T, TSource, TResult>( this IRuleBuilder<T, IEnumerable<TSource>> ruleBuilder, Func<TSource, TResult> selector, string? message = null) { if (selector == null) throw new ArgumentNullException(nameof(selector), "Cannot pass a null selector."); ruleBuilder .Must(x => x.IsDistinct(selector)) .WithMessage(message ?? "Elements are not unique."); return ruleBuilder; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/67113427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Storing information from php script I m working on an html page that contains a form allowing users to enter their informations and upload files. all informations will be inserted in Mysql database. in Javascript, im using XMLHttpRequest to send the files to the server and "upload.php" to rename (to avoid dupplicated names) and move them in the upload directory. For better user experience, this will be done before submitting the whole form. My question is : How can i store the new filenames (defined in upload.php)to use them in the form submission "submit.php"? the reason for this is that in "submit.php", i insert first the user informations in "user" table and then select the "user_id" (auto increment) that will be inserted with filenames in the "files" table. Could php sessions be an approach to do this ? is there another way? Thanks for your help html: <form action="submit.php" method="post" id="submitform"> <div> <--!user info part1--> </div> <div id="filesContainer" class="eltContainer"> <input type="file" id="filesList" multiple> </div> <div> <--!user info part2--> </div> javascript: var fd = new FormData() var xhr = new XMLHttpRequest() for (var i=0,nb = fichiers.length; i<nb; i++) { var fichier = fichiers[i] fd.append(fichier.name,fichier) } xhr.open('POST', 'upload.php', true) upload.php : <?php foreach($_FILES as $file){ $filename = date('Y') . date('m') . date('d') . date('H') . date('i') . basename($_FILES[$file]['name']); move_uploaded_file( $file['tmp_name'],"../upload_dir/" .$filename); } exit; A: I would consider using something like md5 for unique filenames. Nevertheless you can push filenames into some array, and than return those filenames, as a result of post request, and put them back into some input field. To retrieve the response simply add this lines to your code below open xhr.onreadystatechange = function { // If the request completed and status is OK if (req.readyState == 4 && req.status == 200) { // keep in mind that fileNames here are JSON string // as you should call json_encode($arrayOfFilenames) // in your php script (upload.php) var fileNames = xhr.responseText; } } If you'd like consider using a simple library for AJAX requests, like axios. It's promise based HTTP client for the browser, really simple to use and saves you some time and effort cause you don't have to memorize all this stuff you and I have just written. This is one approach, but I think you can use $_SESSION as well, and it's perfectly valid. My guess is you don't have logged in user at this point, so my idea is as follows: * *put filenames into the $_SESSION *use db transactions - as @Marc B suggested - to connect files with user *if there were no errors just remove filenames from $_SESSION, if there was some, just redirect the user back to the form (possibly with some info what went wrong), and this way he doesn't have to reupload files, cause you have filenames still in $_SESSION
{ "language": "en", "url": "https://stackoverflow.com/questions/39858136", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: NSMetadataQuery doesn't send a notification when finished (or doesn't finish) I'm trying to access some files stored in the application's documents directory by using an NSMetadataQuery but the NSMetadataQueryDidFinishGatheringNotification doesn't notify my application. I found this question but the answer was to make the NSMetadataQuery an ivar, which I have already done. Here's the code I am using: self.query = [[NSMetadataQuery alloc] init]; [self.query setSearchScopes:[NSArray arrayWithObject:documentsDirectoryURL]]; NSPredicate *pred = [NSPredicate predicateWithFormat:@"%K ENDSWITH '_task'", NSMetadataItemFSNameKey]; [self.query setPredicate:pred]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(queryDidFinishGathering:) name:NSMetadataQueryDidFinishGatheringNotification object:self.query]; [self.query enableUpdates]; [self.query startQuery]; Thanks for your help! A: This is from the Apple document, "About File Metadata Queries" : iOS allows metadata searches within iCloud to find files corresponding files. It provides only the Objective-C interface to file metadata query, NSMetadataQuery and NSMetadataItem, as well as only supporting the search scope that searches iCloud. Unlike the desktop, the iOS application’s sandbox is not searchable using the metadata classes. In order to search your application’s sandbox, you will need to traverse the files within the sandbox file system recursively using the NSFileManager class. Once matching file or files is found, you can access that file in the manner that you require. You are also able to use the NSMedatataItem class to retrieve metadata for that particular file. So, you have to use NSFileManager instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/10875387", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Pass dynamic content to bootstrap modal 3.2 What i'm trying to do is to pass the data-id value to an external link via JQuery ajax. The modal will show up but the data-id attribute is not sending to the external link. I think something is wrong with my Jquery script. But i can't find it. This is my link: <a href="javascript:;" data-id="1" onclick="showAjaxModal();" class="btn btn-primary btn-single btn-sm">Show Me</a> This is my Jquery ajax script: <script type="text/javascript"> function showAjaxModal() { var uid = $(this).data('id'); jQuery('#modal-7').modal('show', {backdrop: 'static'}); jQuery.ajax({ url: "test-modal.php?id=" + uid, success: function(response) { jQuery('#modal-7 .modal-body').html(response); } }); } </script> This is my code for the modal: <div class="modal fade" id="modal-7"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h4 class="modal-title">Dynamic Content</h4> </div> <div class="modal-body"> Content is loading... </div> <div class="modal-footer"> <button type="button" class="btn btn-white" data-dismiss="modal">Close</button> <button type="button" class="btn btn-info">Save changes</button> </div> </div> </div> </div> Can anyone help me out here? I want to load the content of the page found by test-modal. The code of test-modal.php is simple, see below: <?php $uid = $_GET['id']; echo id: '. $uid; ?> I have tried to make a jsfiddle: http://jsfiddle.net/2dp12ft8/3/ but it's totally not working. I have changed the js code but it will still not work. I see the modal showing up but only the word 'undefined' is showing up and not the content of the external file. A: Dont mix onclick attributes with event handlers, its messy and can cause errors (such as mistaking the scope of this, which i believe is you main issue here). If you are using jquery make use of it: First add a class to the links you want to attach the event to, here i use the class showme: <a href="#;" data-id="1" class="btn btn-primary btn-single btn-sm showme">Show Me</a> Then attach to the click event on those links: <script type="text/javascript"> jQuery(function($){ $('a.showme').click(function(ev){ ev.preventDefault(); var uid = $(this).data('id'); $.get('test-modal.php?id=' + uid, function(html){ $('#modal-7 .modal-body').html(html); $('#modal-7').modal('show', {backdrop: 'static'}); }); }); }); </script> To access the variable in php: $uid = $_GET['id']; //NOT $_GET['uid'] as you mention in a comment A: Try the load method instead. I'm taking a guess here, but it seems like you want to actually load the contents of the page found at test-modal.php. If that's correct, replace your ajax call as follows: function showAjaxModal() { var uid = $(this).data('id'); var url = "test-modal.php?id=" + uid; jQuery('#modal-7').modal('show', {backdrop: 'static'}); jQuery('#modal-7 .modal-body').load(url); } If your test-modal.php page contains more than a fragment (e.g., it has html and body tags), you can target just a portion of the page by passing an id of the containing element for the content that you want to load, such as: jQuery('#modal-7 .modal-body').load(url+' #container'); which would only load the contents of the element with the id container from your test-modal.php page into the modal-body.
{ "language": "en", "url": "https://stackoverflow.com/questions/26517605", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Can't make 2 buttons play 2 different songs on my HTML Firstly, I'm super (SUPER) new to coding in general. I'm doing a college project for a site, and I wanted to make a certain page have 2 buttons that play songs, 2 different versions, one for each button. I copied the code from stack overflow, can't remember where but I'll be forever thankful for that one answer. I'm new to SO too so I hope I put the code here the right way :| <!-- BTN1--> <button id="ASong" onClick="playPause()" > <audio src="mp3/Persona_5_OST-_Beneath_the_Mask_(getmp3.pro).mp3" autoplay loop ></audio> <img src="img/musica2.png" width="100px" align="left" margin-top="40px"> <br/> </button> <script> var aud = document.getElementById("ASong").children[0]; var isPlaying = false; aud.pause(); function playPause() { if (isPlaying) { aud.pause(); } else { aud.play(); } isPlaying = !isPlaying; } </script> <!-- BTN1--> <!-- BTN2--> <button id="ASong2" onClick="playPause()" > <audio src="mp3/Persona_5_OST_-_Beneath_the_Mask_r_(getmp3.pro).mp3" autoplay loop ></audio> <img src="img/musica2.png" width="100px" align="left" margin-top="40px"> <br/> </button> <script> var aud = document.getElementById("ASong2").children[0]; var isPlaying = false; aud.pause(); function playPause() { if (isPlaying) { aud.pause(); } else { aud.play(); } isPlaying = !isPlaying; } </script> <!-- BTN2--> The only thing I really tried was changing the ID name for the second song. What happens is. I choose a button and click it first. That one button, with that specific song is the one that'll play (edit, it's not the first one I click, it's only one of the songs :/ it switched which one it was when I changed the ID name) , even if I try to press the other button afterwards. It's like both of them become the same button, they function the same. What I wanted is that each one of them worked separately. I want to be able to click, start one song, pause it, click on the other button and start the other song, which is not what's happening right now. I hope that makes sense D= A: I'm going to modernize this a bit. Inline event handlers listeners are not the way to go these days. I'' use addEventListener instead. Next, I'm going to use one lot of code to handle the actions. One concept to get used to as you learn to program is DRY: Don't Repeat Yourself. To facilitate the state of your playback I'll use a data attribute on the button /*Get the buttons*/ document.querySelectorAll(".playPause").forEach(function(el) { /*Add a click event listener*/ el.addEventListener("click", function() { /*Get the first audio tag in the clicked button*/ var aud = this.querySelector("audio"); /*Check the data attirbute on the button if playing*/ if (this.dataset.isplaying === "true") { /*Debug line*/ console.log("Pausing " + aud.src) /*Change the status of the data attribute*/ this.dataset.isplaying = "false"; /*Pause the audio element*/ aud.pause(); } else { /*Debug line*/ console.log("Playing " + aud.src) /*Change the status of the data attribute*/ this.dataset.isplaying = "true"; /*PLay the audio element*/ aud.play(); } }) }); <button id="ASong" class="playPause" data-isplaying="false"> <audio src="mp3/Persona_5_OST-_Beneath_the_Mask_(getmp3.pro).mp3" autoplay loop ></audio> <img src="img/musica2.png" width="100px" align="left" margin-top="40px"> </button> <button id="ASong2" class="playPause" data-isplaying="false"> <audio src="mp3/Persona_5_OST_-_Beneath_the_Mask_r_(getmp3.pro).mp3" autoplay loop ></audio> <img src="img/musica2.png" width="100px" align="left" margin-top="40px"> </button>
{ "language": "en", "url": "https://stackoverflow.com/questions/74567529", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript es6 - is it reassigning or a parameter? Can someone please explain what's happening here? I know these are middleware for express, I'm looking at the syntax. I understand the es6 syntax for mustBeLoggedIn but I'm not sure what const forbidden = message => (req, res, next) => { is doing. Is message another parameter that comes before req, res, next? If so, why isn't it in the parenthesis? I originally thought this was just assigning another variable name to the function. So I could call it either forbidden() or message(), no? But looking at how it's being used it looks more like a parameter... Another interesting thing I noticed is that the middleware forbidden is being invoked in the get request and mustBeLoggedIn is only being passed and not invoked. Why? const mustBeLoggedIn = (req, res, next) => { if (!req.user) { return res.status(401).send('You must be logged in') } next() } const forbidden = message => (req, res, next) => { res.status(403).send(message) } module.exports = require('express').Router() .get('/', forbidden('only admins can list users'), (req, res, next) => User.findAll() .then(users => res.json(users)) .catch(next)) .post('/', (req, res, next) => User.create(req.body) .then(user => res.status(201).json(user)) .catch(next)) .get('/:id', mustBeLoggedIn, (req, res, next) => User.findById(req.params.id) .then(user => res.json(user)) .catch(next)) A: I dislike this use of the ES6 syntax as it obscures the meaning of the code only in the interest of brevity. The best code is not always the shortest possible way to write it. Give people tools and they will sometimes use them inappropriately. forbidden() is a function that takes one argument message that returns a middleware handler that uses that one argument. So, it's a way of making a customized middleware handler that has a parameter pre-built-in. When you call forbidden(msg), it returns a middleware handler function which you can then use as middleware. The ES5 way of writing this (ignoring for a moment the difference in this which would be different, but is not used here) would look like this: const forbidden = function(message) { return function(req, res, next) { res.status(403).send(message); } } So, when you call forbidden(someMsg), you get back a function that can be used as middleware. If so, why isn't it in the parenthesis? With the ES6 arrow syntax, a single argument does not have to be in parentheses. Only multiple arguments require parentheses. Another interesting thing I noticed is that the middleware forbidden is being invoked in the get request This is because invoking it returns the actual middleware function so you have to execute to get the return value which is then passed as the middleware. and mustBeLoggedIn is only being passed and not invoked. Why? Because it's already a middleware function, so you just want to pass a reference to it, not invoke it yet. FYI, this route: .get('/', forbidden('only admins can list users'), (req, res, next) => User.findAll() .then(users => res.json(users)) .catch(next)) does not make sense to me based on the code you've shown because forbidden() will return a middleware that will ALWAYS return a 403 response and will not allow the next handler to get called. This would only make sense to me if forbidden() had logic in it to check if the current user is actually an admin or not (which you don't show).
{ "language": "en", "url": "https://stackoverflow.com/questions/42407039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to fetch file type data (image) on JQuery page and send to PHP page for image upload I want to upload an image using jQuery asynchronously with data... but cannot upload it... Only data variables can be fetch there in process page but cannot get the image file using $_FILES...... img_upload.php <form name="frm" id="frm" novalidate enctype="multipart/form-data"> <input type="text" id="txt_name" name="txt_name" /> <input type="file" name="img_upload" id="img_upload"> </form> img_upload.js $(function() { $("#frm_edit input, #frm_edit textarea").jqBootstrapValidation({ preventSubmit: true, submitSuccess: function($form, event) { event.preventDefault(); // prevent default submit behaviour var txt_name = $("input#txt_name").val(); var FileImgData = $('#img_upload').prop('files')[0]; var form_data = new FormData(); form_data.append('file', FileImgData); $.ajax({ url: "./img_upload_p.php", type: "POST", data: { txt_name: txt_name, upload_photo: FileImgData }, cache: false, }) }, }); }); img_upload_p.php $str_name=""; if(isset($_POST["txt_name"])) { $str_name=trim($_POST["txt_name"]); } $str_upload_photo=""; if(isset($_FILES['file_photo'])) { $str_upload_photo = trim($_FILES['file_photo']['name']); } Please suggest me that image variable declared (upload_photo: FileImgData) in JQuery file "img_upload_p.js" is correct or not. Also, the way image file variable is fetched in "img_upload_p.php" is correct or not. if any of them are wrong then how can I assign that image variable in JQuery file and fetch in PHP process page... PHP image upload code is ready and in working condition... but just having issue with above two mentioned points... A: One of the best way to do this is use Dropzone js, this is a best library for uploading files using ajax and it also provides progress bar. You can use your own PHP(or any other server side language) code at server side. I hope it will helpful. A: img_upload.js $(function() { $("#frm_edit input, #frm_edit textarea").jqBootstrapValidation({ preventSubmit: true, submitSuccess: function($form, event) { event.preventDefault(); // prevent default submit behaviour var formData = new FormData(); formData.append("hdn_pkid", $("input#hdn_pkid").val()); // if hidden variable is passed formData.append("txt_name",$("input#txt_name").val()); // if other input types are passed like textbox, textarea, select etc... formData.append('img_upload', $('input[type=file]')[0].files[0]); // if image or other file is passed $.ajax({ url: "./img_upload_p.php", type: "POST", data: formData, contentType: false, processData: false, cache: false, }) }, }); }); img_upload_p.php * *Get all variables' value using POST method and store them in new variables to use and process on this page as usual. *Get file variable like below mentioned code and then upload image using normal PHP function or your own way. if(isset($_FILES['img_upload'])) { $str_ = trim($_FILES['img_upload']['name']); }
{ "language": "en", "url": "https://stackoverflow.com/questions/38264663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I continue to perform aggregation on a single thread that has polling? I create a flow, which polls rows from database by status, validate them and after that aggregate to collection. After processing the entire flow, each line is set to the appropriate status. But when I use aggregator with release strategy TimeoutCountSequenceSizeReleaseStrategy, and elapsed time is so small, release group doesn't happen. And after that the following polling occurs in another thread, but previous message group wasn't handled until amount of messages won't reach the target(threshold) in the strategy. Code of my flow: @Bean public IntegrationFlow testFlow(EntityService entityService, EntityValidator entityValidator, EntityFlowProperties properties, EntityChecker checker) { return IntegrationFlows .from(getMessageSource(entityService::getByStatus, properties.getMaxRowsPerPoll()), e -> e.poller(getPollerSpec(properties))) .split() .transform(entityValidator::validate) .filter(ValidationStatus<Entity>::isValid, filter -> filter.discardFlow(flow -> flow.handle(entityService::handleValidationErrors))) .transform(ValidationStatus<Entity>::getEntity) .aggregate(aggregatorSpec -> aggregatorSpec.releaseStrategy(new TimeoutCountSequenceSizeReleaseStrategy(5, 10000))) .transform(checker::checkOnSomething) .split() .transform(CheckResultAware<Entity>::getEntity) .handle(entityService::saveAndChangeStatus) .get(); I expect to perform aggregation on the same thread as polling, and don't make a new polling until the current flow is over. The way of changing statuses between polling and aggregation isn't suitable. Is there a way to do this? A: Why do you need TimeoutCountSequenceSizeReleaseStrategy; your sequences are finite; just use the default SimpleSequenceSizeReleaseStrategy. However the TimeoutCountSequenceSizeReleaseStrategy should release based on the sequence size anyway. But, it's not really suitable for your use case because you can be left with a partial group in the store.
{ "language": "en", "url": "https://stackoverflow.com/questions/55829708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Handle arrays in laravel I am learning laravel and trying to create a community with laravel. I stuck at some part and need to ask you guys. Right now I am trying to displaying posts to reader. This is what i accomplish so far with this code : public $restful = true; public function get_index($title = '') { //Do we have an arguement? if(empty($title)) {return Redirect::to('dashboard');} $view = View::make('entry'); $query = DB::table('threads')->where('title', '=', $title)->first(); //Do we have this thread? if(!$query) {return Redirect::to('entry/suggest');} //We have? so lets rock it! $view->title = $query->title; //we get the title. $thread_id = $query->id; //getting posts. $posts = DB::table('posts')->where('thread_id', '=', $thread_id)->get(); $view->posts = $posts; return $view; } and the view is : <div id="entrybox"> <h2>{{$title}}</h2> @foreach($posts as $post) <p class="entry"><span class="entrynumber">1</span><span class="entry_text">{{$post->post_entry}}</span></p> <p align="right" class="edate"><span class="entry_user">{post_row.POST_USERNAME}</span> <span class="entry_date">{post_row.DATE}</span></p> @endforeach </div> But the hard part(for me) is integrate posts with poster's username or other user info like e-mail for moderate privileges. However hey are in 'users' table. Lets say $posts variable holds data of 10 posts for a thread *a post has thread_id , poster_userid, post, posted_date. How can i grab username from 'users' table and send it to my view? I am sure i need to use foreach after selecting posts from database I just dont know how to handle arrays in foreach. A: Look up how to set up models and their relationships using Eloquent ORM: http://laravel.com/docs/database/eloquent Specifically http://laravel.com/docs/database/eloquent#relationships You should have three models, Thread, Post and User (change poster_userid to user_id... or you can keep it but I wouldn't suggest it... just keep things simple. You could also use author_id or maybe even poster_id if that floats your boat.. just be sure to change 'user_id' out with what you choose) //application/models/User.php class User extends Eloquent { public function posts() { return $this->has_many('Post', 'user_id'); } } and //application/models/Post.php class Post extends Eloquent { public function author() { return $this->belongs_to('User', 'user_id'); } public function thread() { return $this->belongs_to('Thread', 'thread_id'); } } and //application/models/Thread.php class Thread extends Eloquent { public function posts() { return $this->has_many('Post', 'thread_id'); } } and instead of $query = DB::table('threads')->where('title', '=', $title)->first(); //Do we have this thread? if(!$query) {return Redirect::to('entry/suggest');} //We have? so lets rock it! $view->title = $query->title; //we get the title. $thread_id = $query->id; //getting posts. $posts = DB::table('posts')->where('thread_id', '=', $thread_id)->get(); I would just put $thread = Thread::where('title', '=', $title)->first(); if(!$query) {return Redirect::to('entry/suggest');} $posts = $thread->posts()->get(); //or if you want to eager load the author of the posts: //$posts = $thread->posts()->with('author')->get(); Then in your view you can look up the user's name by the following: $post->author->username; Easy peezy. A: With Eloquent you can do this in multiple ways. First, you can add a method to your post model that retrieves the related data. This approach will create a new query for each post, so it's normally not the best choice. class Post extends Eloquent { public function user() { return $this->has_one('User'); } } Second, you can modify your initial query to join your desired data and avoid creating undo queries. Know as "Eager Loading". // Example from Laravel.com foreach (Book::with('author')->get() as $book) { echo $book->author->name; }
{ "language": "en", "url": "https://stackoverflow.com/questions/14281153", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to revert multiple pull request merges all at once and preserve history I have a case where the Github repo master currently has a series of individual pull requests that have already been merged into master. I want to revert say the last 20 of those pull request merges but do it from the command line and preserve history. A similar question was marked as duplicate revert multiple merges However the answers given as already existing do not really deal with the specific question of what happens when everything you want to revert came from a series of pull requests which are all merges. Using the -m option with git revert is good for one merge at time right? So I think the answer is that there is not a good way (from the command line) to quickly revert a series of individual pull requests that have been merged and preserve history? Please correct me if I am wrong about this. If I have to do one at a time, I might as well just use the Github console and click on revert for each one. A: If you want to have a single (later) revision where you revert the changes from all those merges, you can do it like this: git checkout <id-of-revision> # use the ID of the revision you would like to get your project back to (in terms of content) git reset --soft <the-branch> # the branch where we want to add a revision to revert all of that git commit -m "Reverting" # If you like the results git branch -f <the-branch> # move branch pointer to this new revision git checkout <the-branch> A: Step1 Create a new backup branch first and keep it aside. (backup-branch) Create a new branch from master or dev wherever you want to revert.(working-branch) git revert commitid1 git revert commitid2 git revert commitid3.... is the best option. dont do git reset --hard commitid it will mesh up your indexing. Reverting is the safe option. i have done 180 revert commits. Step2 git log -180 --format=%H --no-merges use this command to print all the commit ids alone. it will ignore the merge commit id. commitid1 commitid2 commitid3 ..... it will print like that. Copy it to sublime ctrl+a -> ctrl +alt + l add git revert --no-commit commitid1 git revert --no-commit commitid2 git revert --no-commit commitid3 Copy all and paste in the command prompt. All your commits will be reverted. now do a git commit. Then do git push. create a merge request to master. Step3 How to verifiy? create a new branch (verify-branch). YOu can verify it by doing a git reset -hard commitidX. This is the commit id to which you need to revert. git status It will give you the number of commits behind the master. git push -f Now compare this branch with your working-branch by creating a pull request between them. you will see no changes means your working branch successfully reverted back to the version you're looking for.
{ "language": "en", "url": "https://stackoverflow.com/questions/60766114", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What is the context for `this` in Node.js when run as a script? From the node REPL: $ node > var x = 50 > console.log(x) 50 > console.log(this.x) 50 > console.log(this === global) true Everything makes sense. However, when I have a script: $ cat test_this.js var x = 50; console.log(x); console.log(this.x); console.log(this === global); $ node test_this.js 50 undefined false Not what I expected. I don't really have a problem with the REPL behaving differently from a script, but where exactly in the Node documentation does it say something like "NOTE: when you run a script, the value of this is not set to global, but rather to ___________." Does anyone know, what this refers to in the global context when run as a script? Googling "nodejs this global context script" takes me to this page which looks very promising, as it describes contexts for running scripts, but it doesn't seem to mention the use of the this expression anywhere. What am I missing? A: In Node.js, as of now, every file you create is called a module. So, when you run the program in a file, this will refer the module.exports. You can check that like this console.log(this === module.exports); // true As a matter of fact, exports is just a reference to module.exports, so the following will also print true console.log(this === exports); // true Possibly related: Why 'this' declared in a file and within a function points to different object
{ "language": "en", "url": "https://stackoverflow.com/questions/28018925", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Twilio : Calculating estimated wait time in multi queue multi server system I have a system that has multiple queues, whenever a user calls if no agent is available it will wait in the queue. The queue has multiple filters which separates the agent based on their skills. I want to calculate the estimated wait time for each user in the queue based on their position as well as skill.
{ "language": "en", "url": "https://stackoverflow.com/questions/74158650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: REACT_APP_VERSION=$npm_package_version not working on build with Webpack I have a React app, initialized with CRA. on my .env file I have the following env variable, to access on my application the version of the package.json file: REACT_APP_VERSION=$npm_package_version When I use nom run build with react-scripts build, the production build takes the env value from the .env file and shows the correct version defined on package.json. But when I use web pack to build the production app, the version value is not injected to the env variable. this is my web pack.config.js file: const webpack = require('webpack') const path = require('path') const HtmlWebpackPlugin = require('html-webpack-plugin') const CopyWebpackPlugin = require('copy-webpack-plugin') require('dotenv').config({ path: './.env.staging.local' }) const srcFolder = 'src' const distFolder = 'dist' module.exports = { // entry point for application entry: { app: path.join(__dirname, srcFolder, 'index.js'), }, mode: 'production', resolve: { extensions: ['.js', '.jsx', '.ts', '.tsx', '.json'], fallback: { fs: false, crypto: require.resolve('crypto-browserify'), stream: require.resolve('stream-browserify'), }, }, // output file settings // path points to web server content folder where the web server will serve // the files from file name is the name of the files, where [name] is the // name of each entry point output: { path: path.join(__dirname, distFolder), filename: '[name].js', publicPath: '.', }, optimization: { splitChunks: { chunks: 'async', minSize: 20000, minRemainingSize: 0, minChunks: 1, maxAsyncRequests: 30, maxInitialRequests: 30, enforceSizeThreshold: 50000, cacheGroups: { defaultVendors: { test: /[\\/]node_modules[\\/]/, priority: -10, reuseExistingChunk: true, }, default: { minChunks: 2, priority: -20, reuseExistingChunk: true, }, }, }, }, module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: { loader: 'babel-loader', }, }, { test: /\.css$/i, use: ['style-loader', 'css-loader'], }, ], }, plugins: [ new HtmlWebpackPlugin({ template: 'public/index.html', filename: 'index.html', }), new CopyWebpackPlugin({ patterns: [ { from: 'public/assets', to: './assets' }, { from: 'public/favicon.ico', to: './favicon.ico' }, { from: 'public/manifest.json', to: './manifest.json' }, { from: 'public/robots.txt', to: './robots.txt' }, ], }), new webpack.DefinePlugin({ 'process.env': JSON.stringify(process.env), }), ], performance: { hints: false, maxEntrypointSize: 512000, maxAssetSize: 512000, }, } Can someone please point out what should I do to have this value injected on the env variable as with react-scripts build
{ "language": "en", "url": "https://stackoverflow.com/questions/71027432", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Css needed to highlight common words in a table I came across this page on slate.com that highlights similar words in a table when you hover over one instance: http://www.slate.com/blogs/lexicon_valley/2013/09/11/top_swear_words_most_popular_curse_words_on_facebook.html Does anyone know how this is done? A: You can do it with jQuery like this: $('table td').mouseover(function() { $('table td').removeClass('highlight') var text = $(this).text(); $('table td').filter(function() { return $(this).text() == text; }).addClass('highlight'); }) Check this jsFiddle A: using jQuery.data Always to know how something works, the first step is to read the source code Check this: EXAMPLE $('.interactive_table .cell_word') .hover(function(){ var word = $(this).data('word'); $(this).parent().parent() .find('.word_'+word) .addClass('highlighted'); },function(){ var word = $(this).data('word'); $(this).parent().parent() .find('.word_'+word) .removeClass('highlighted'); }); $('.interactive_table .cell_rank_number') .hover(function(){ $(this).parent() .find('.cell_word') .addClass('highlighted'); },function(){ $(this).parent() .find('.cell_word') .removeClass('highlighted'); });
{ "language": "en", "url": "https://stackoverflow.com/questions/18764032", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Vue radio button v-if with v-model I am very new to html and vue, and trying to create radio button. I use local JSON file which is being used for creating UI. I loop through JSON object and create radio buttons accordingly. I used "defaultedOptionId" to find which one to be checked as default. Here is my JSON: { "id": 1, "selected": 1, "defaultedOptionId": 2, "selections": [ { "selectionId": 1, "description: "XX" }, ... }, ... I am using Vue component, which basically holds JSON file. In the template, I have code so when 'defaultedOptionId === selectionId', check as default <p v-for="(selection, index) in choice.selections"> <input v-if="choice.defaultOptionId === selection.selectionId" type="radio" :name="'option_' + choice.choiceId" :value="selection.selectionId" checked></input> <input v-else type="radio" :name="'option_' + choice.choiceId" :value="selection.selectionId"></input> {{ index+1 }}. {{ selection.description }} 'choice' is basically JSON object. This works if I change defaultOptionId to something else. HOWEVER, if I want to update JSON object as user selects radio button, I have to add v-model to the input field like this: <p v-for="(selection, index) in choice.selections"> <input v-if="choice.defaultOptionId === selection.selectionId" type="radio" :name="'option_' + choice.choiceId" :value="selection.selectionId" v-model="choice.selectedOptionId" checked></input> <input v-else type="radio" :name="'option_' + choice.choiceId" :value="selection.selectionId" v-model="choice.selectedOptionId"></input> {{ index+1 }}. {{ selection.description }} With this, radio buttons with 'checked' property doesn't work. It checks first option and even if I change 'defaultOptionId', it doesn't care. Basically, I want to load different JSON file with different 'defaultOptionId' which changes default check for radio button WHILE when user selects radio button, it updates JSON file's 'selectedOptionId'. I can make it work separately, but not together. I have to use this design since other templates are following the same design. A: It's difficult to understand what you're trying to do and what the problem is because the question looks like a mess, but I'll try to help anyway. Demo: Here's a working example with your data: https://codepen.io/AlekseiHoffman/pen/XWJmpod?editors=1010 Template: <div id="app"> <div v-for="(selection, index) in choice.selections"> <input type="radio" :id="selection.id" :value="selection.selectionId" v-model="choice.selected" > <label> {{selection.description}} </label> </div> <div> Selected: {{ choice.selected }} </div> </div> Script: choice: { "id": 1, "selected": 2, "selections": [ { "selectionId": 1, "description": "Radio One" }, { "selectionId": 2, "description": "Radio Two" } ] } I simplified the JSON object since the other properties are not needed there to make it work. Let me know if you're still having difficulties with your task.
{ "language": "en", "url": "https://stackoverflow.com/questions/59215904", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Comparison of serializing methods Possible Duplicate: Fastest serializer and deserializer with lowest memory footprint in C#? I'm using BinaryFormatter class to serialize an structure or a class. (after serialization, I'm going to encrypt the serialized file before saving. (And of course decrypt it before deserialization)) But I heard that some other serialization classes are present in .Net Framework. Like XmlSerializer, JavaScriptSerializer, DataContractSerializer and protobuf-net. I want to know, which one is best for me? Less RAM space needed for serialize/deserialize is the most important thing for me. Also speed is important. A: If your aim is to reduce memory demands, then don't serialize then encrypt: instead - serialize directly to an encrypting Stream. The Stream API is designed to be chained (decorator pattern) to perform multiple transformations without excessive buffering. Likewise: deserialize from a decrypting stream; don't decrypt then deserialize. Done this way, data is encrypted/decrypted on-the-fly as needed; in addition to reducing memory, it is also good for security - since this also means the entire data never exists in decrypted form as a single buffer. See CryptoStream on MSDN for a full example. Some additional notes; if you do happen to use protobuf-net, there are ways of reducing any in-memory buffering by using "grouped" encoding; you see: the default for sub-messages (including lists) is "length prefixed" - and the way it usually does this is by buffering the data in memory to calculate the length. However, protobuf also supports a format that uses a start/end marker which never requires knowing the length, so never requires buffering - and so the entire sequence can be written in a single pass direct to output (well, it does still use a buffer internally to improve IO, but it pools the buffer here, for maximum re-use). This is as simple as, for sub-objects: [ProtoMember(11, DatFormat = DataFormat.Grouped)] public Customer Customer {get;set;} // a sub-object (where there is no significance in the 11) A: See http://code.google.com/p/protobuf-net/wiki/Performance for a comparison of performance.
{ "language": "en", "url": "https://stackoverflow.com/questions/8629930", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Looking for jQuery find(..) method that includes the current node The jQuery find(..) traversal method doesn't include the current node - it starts with the children of the current node. What is the best way to call a find operation that includes the current node in its matching algorithm? Looking through the docs nothing immediately jumps out at me. A: Define $.fn.findSelf = function(selector) { var result = this.find(selector); this.each(function() { if ($(this).is(selector)) { result.add($(this)); } }); return result; }; then use $.findSelf(selector); instead of $find(selector); Sadly jQuery does not have this built-in. Really strange for so many years of development. My AJAX handlers weren't applied to some top elements due to how .find() works. A: $('selector').find('otherSelector').add($('selector').filter('otherSelector')) You can store $('selector') in a variable for speedup. You can even write a custom function for this if you need it a lot: $.fn.andFind = function(expr) { return this.find(expr).add(this.filter(expr)); }; $('selector').andFind('otherSelector') A: The accepted answer is very inefficient and filters the set of elements that are already matched. //find descendants that match the selector var $selection = $context.find(selector); //filter the parent/context based on the selector and add it $selection = $selection.add($context.filter(selector); A: You can't do this directly, the closest I can think of is using .andSelf() and calling .filter(), like this: $(selector).find(oSelector).andSelf().filter(oSelector) //or... $(selector).find('*').andSelf().filter(oSelector); Unfortunately .andSelf() doesn't take a selector, which would be handy. A: If you want the chaining to work properly use the snippet below. $.fn.findBack = function(expr) { var r = this.find(expr); if (this.is(expr)) r = r.add(this); return this.pushStack(r); }; After the call of the end function it returns the #foo element. $('#foo') .findBack('.red') .css('color', 'red') .end() .removeAttr('id'); Without defining extra plugins, you are stuck with this. $('#foo') .find('.red') .addBack('.red') .css('color', 'red') .end() .end() .removeAttr('id'); A: In case you are looking for exactly one element, either current element or one inside it, you can use: result = elem.is(selector) ? elem : elem.find(selector); In case you are looking for multiple elements you can use: result = elem.filter(selector).add(elem.find(selector)); The use of andSelf/andBack is pretty rare, not sure why. Perhaps because of the performance issues some guys mentioned before me. (I now noticed that Tgr already gave that second solution) A: I know this is an old question, but there's a more correct way. If order is important, for example when you're matching a selector like :first, I wrote up a little function that will return the exact same result as if find() actually included the current set of elements: $.fn.findAll = function(selector) { var $result = $(); for(var i = 0; i < this.length; i++) { $result = $result.add(this.eq(i).filter(selector)); $result = $result.add(this.eq(i).find(selector)); } return $result.filter(selector); }; It's not going to be efficient by any means, but it's the best I've come up with to maintain proper order. A: I was trying to find a solution which does not repeat itself (i.e. not entering the same selector twice). And this tiny jQuery extention does it: jQuery.fn.findWithSelf = function(...args) { return this.pushStack(this.find(...args).add(this.filter(...args))); }; It combines find() (only descendants) with filter() (only current set) and supports whatever arguments both eat. The pushStack() allows for .end() to work as expected. Use like this: $(element).findWithSelf('.target') A: For jQuery 1.8 and up, you can use .addBack(). It takes a selector so you don't need to filter the result: object.find('selector').addBack('selector') Prior to jQuery 1.8 you were stuck with .andSelf(), (now deprecated and removed) which then needed filtering: object.find('selector').andSelf().filter('selector') A: I think andSelf is what you want: obj.find(selector).andSelf() Note that this will always add back the current node, whether or not it matches the selector. A: If you are strictly looking in the current node(s) the you just simply do $(html).filter('selector') A: Here's the right (but sad) truth: $(selector).parent().find(oSelector).filter($(selector).find('*')) http://jsfiddle.net/SergeJcqmn/MeQb8/2/
{ "language": "en", "url": "https://stackoverflow.com/questions/2828019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "151" }
Q: Kendo Grid plumbing I'm trying to get the Kendo UI grid connected in my MVC3 app, but I'm not getting any data displaying. I think it should be simple, but I'm not seeing it. Here is my code: View: @model List<pests.web.com.Models.Workitem> @{ ViewBag.Title = "Worklist"; ViewBag.CurrentPage = "Worklist"; } <div id="grid"></div> <script type="text/javascript"> $("#grid").kendoGrid({ dataSource: { type: "json", transport: { read: { url: "Home/GetWorklist", dataType: "json", type: "POST", contentType: "application/json; charset=utf-8", data: {} } }, columns: [ { field: "PartNumber", width: 90, title: "Part Number" }, { field: "ProcurementCode", width: 90, title: "Procurement Code" }, { width: 100, field: "Priority" }, { field: "Status" } ] } }); </script> <script type="text/javascript" src="../../Scripts/people.js"></script> <script type="text/javascript" src="../../Scripts/kendo.web.min.js"></script> <script type="text/javascript" src="../../Scripts/console.js"></script> <link href="../../Styles/kendo.common.min.css" rel="stylesheet" /> <link href="../../Styles/kendo.default.min.css" rel="stylesheet" /> Layout page: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>@ViewBag.Title</title> <link href="@Url.Content("~/Styles/Site.css")" rel="stylesheet" type="text/css" /> <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script> </head> <body> @RenderBody() </body> </html> Controller code I'm trying to call from the view: public class HomeController : Controller { [HttpPost] public ActionResult GetWorklist() { List<Workitem> worklist = PestsLogic.GetWorklist(); return View("Home", worklist); } } GetWorklist() is returning a few items. They are simple object with a few properties. Here's it is: public class Workitem { public string PartNumber { get; set; } public string ProcurementCode { get; set; } public int Priority { get; set; } public string Status { get; set; } } Is there anything obvious that I've got hooked up wrong? There are no error messages, just a blank page (with a title, though). Thanks! A: The problem was simply that I needed to move the references to the JS files to before I tried to use the Kendo grid.
{ "language": "en", "url": "https://stackoverflow.com/questions/10248657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Train Stacked Autoencoder Correctly I try to build a Stacked Autoencoder in Keras (tf.keras). By stacked I do not mean deep. All the examples I found for Keras are generating e.g. 3 encoder layers, 3 decoder layers, they train it and they call it a day. However, it seems the correct way to train a Stacked Autoencoder (SAE) is the one described in this paper: Stacked Denoising Autoencoders: Learning Useful Representations in a Deep Network with a Local Denoising Criterion In short, a SAE should be trained layer-wise as shown in the image below. After layer 1 is trained, it's used as input to train layer 2. The reconstruction loss should be compared with the layer 1 and not the input layer. And here is where my trouble begins. How to tell Keras which layers to use the loss function on? Here is what I do. Since the Autoencoder module is not existed anymore in Keras, I build the first autoencoder, and I set its encoder's weights (trainable = False) in the 1st layer of a second autoencoder with 2 layers in total. Then when I train that, it obviously compares the reconstructed layer out_s2 with the input layer in_s, instead of the layer 1 hid1. # autoencoder layer 1 in_s = tf.keras.Input(shape=(input_size,)) noise = tf.keras.layers.Dropout(0.1)(in_s) hid = tf.keras.layers.Dense(nodes[0], activation='relu')(noise) out_s = tf.keras.layers.Dense(input_size, activation='sigmoid')(hid) ae_1 = tf.keras.Model(in_s, out_s, name="ae_1") ae_1.compile(optimizer='nadam', loss='binary_crossentropy', metrics=['acc']) # autoencoder layer 2 hid1 = tf.keras.layers.Dense(nodes[0], activation='relu')(in_s) noise = tf.keras.layers.Dropout(0.1)(hid1) hid2 = tf.keras.layers.Dense(nodes[1], activation='relu')(noise) out_s2 = tf.keras.layers.Dense(nodes[0], activation='sigmoid')(hid2) ae_2 = tf.keras.Model(in_s, out_s2, name="ae_2") ae_2.layers[0].set_weights(ae_1.layers[0].get_weights()) ae_2.layers[0].trainable = False ae_2.compile(optimizer='nadam', loss='binary_crossentropy', metrics=['acc']) The solution should be fairly easy, but I can't see it nor find it online. How do I do that in Keras? A: It seems like the question is outdated by looking at the comments. But I'll still answer this as the use-case mentioned in this question is not just specific to autoencoders and might be helpful for some other cases. So, when you say "train the whole network layer by layer", I would rather interpret it as "train small networks with one single layer in a sequence". Looking at the code posted in this question, it seems that the OP has already built small networks. But both these networks do not consist of one single layer. The second autoencoder here, takes as input the input of first autoencoder. But, it should actually take as input, the output of first autoencoder. So then, you train the first autoencoder and collect it's predicitons after it is trained. Then you train the second autoencoder, which takes as input the output (predictions) of first autoencoder. Now let's focus on this part: "After layer 1 is trained, it's used as input to train layer 2. The reconstruction loss should be compared with the layer 1 and not the input layer." Since the network takes as input the output of layer 1 (autoencoder 1 in OP's case), it will be comparing it's output with this. The task is achieved. But to achieve this, you will need to write the model.fit(...) line which is missing in the code provided in the question. Also, just in case you want the model to calculate loss on input layer, you simply replace the y parameter in model,fit(...) to the input of autoencoder 1. In short, you just need to decouple these autoencoders into tiny networks with one single layer and then train them as you wish. No need to use trainable = False now, or else use it as you wish.
{ "language": "en", "url": "https://stackoverflow.com/questions/52221103", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: Can I inherit my WCF DataContract from a shared interface? I have a WCF service and client in the same solution (different projects). The service class itself inherits from an interface, and that interface is shared between client and server (via a linked file). The client uses a service factory to generate a proxy. This has proved a really nice way to link the two sides without referencing the server-side project from the client. One of the service methods returns an object that includes the DataContract and DataMember attributes, and until recently this class was linked to the client as well, but the server-side logic was excluded from the client using compilation symbols. I decided it would be more sensible to turn this into an interface as well. But now I get the following exception every time the service method is called from the client: The underlying connection was closed: A connection that was expected to be kept alive was closed by the server. Its inner exception is as follows: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. So by way of simplified example, my service essentially shares the following interface with the client: public interface IMyData { [DataMember] int Id {get; set;} [DataMember] string Description {get; set;} } The actual object that the interface works with and will return looks something like this: [DataContract] public class MyData : IMyData { [DataMember] public int Id {get; set;} [DataMember] public string Description {get; set;} } The interface of my service looks something like this: [ServiceContract] public interface IMyService { [OperationContract] IMyData GetData(); } The implementation looks something like this: [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single, InstanceContextMode = InstanceContextMode.Single)] public class MyService : IMyService { [OperationContract] IMyData GetData() { // Get data. } } Hope that all makes a little sense! I'm just wondering if I'm doing this all wrong. I'll just go back to sharing the class and sectioning off the server-side-only code if I have to .. but I'd rather use an interface if I can. Any ideas? A: There is no benefit to putting an interface on a DataContract as they simply represent data and no logic. You typically put those DataContracts inside the same assembly with the ServiceContracts or a separate assembly all together. This will prevent exposing the business logic to your clients.
{ "language": "en", "url": "https://stackoverflow.com/questions/11401640", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: The MailChimp PHP library is missing the required GuzzleHttp library I have installed Guzzle on my Godaddy shared hosting via SSH but my Drupal site is still telling me that: "The MailChimp PHP library is missing the required GuzzleHttp library. Please check the installation notes in README.txt." Any ideas why it would be saying that? it appears to have installed correctly. godaddy@user [~/public_html]$ php composer.phar require guzzlehttp/guzzle:~6.0 ./composer.json has been created Loading composer repositories with package information Updating dependencies (including require-dev) - Installing guzzlehttp/promises (1.2.0) Downloading: 100% - Installing psr/http-message (1.0) Downloading: 100% - Installing guzzlehttp/psr7 (1.3.0) Downloading: 100% - Installing guzzlehttp/guzzle (6.2.0) Downloading: 100% Writing lock file Generating autoload files A: On the library page, if you are using the package https://github.com/thinkshout/mailchimp-api-php/releases which contains everything e.g. v1.0.6-package.zip (and therefore having everything already doesn't require composer to get them), then remove /vendor from .gitignore so that all the files in /vendor - including guzzle are included in your code base so that should you deploy the code from your repo to a production server, all of it will be loaded. CREDIT: https://www.drupal.org/node/2709615#comment-11888769 A: This fixed the issue, Guzzle needed to be installed into the MailChimp libraries folder?! Guzzle Instructions godaddy@user [~/public_html]$ cd sites/all/libraries/mailchimp/ godaddy@user [~/public_html/sites/all/libraries/mailchimp]$ curl -sS https://getcomposer.org/installer | php All settings correct for using Composer Downloading 1.1.1... Composer successfully installed to: /home/mysite/public_html/sites/all/libraries/mailchimp/composer.phar Use it: php composer.phar godaddy@user [~/public_html/sites/all/libraries/mailchimp]$ ./composer.phar install Loading composer repositories with package information Updating dependencies (including require-dev) - Installing sebastian/version (1.0.6) Downloading: 100% - Installing sebastian/global-state (1.1.1) Downloading: 100% - Installing sebastian/recursion-context (1.0.2) Downloading: 100% - Installing sebastian/exporter (1.2.1) Downloading: 100% - Installing sebastian/environment (1.3.7) Downloading: 100% - Installing sebastian/diff (1.4.1) Downloading: 100% - Installing sebastian/comparator (1.2.0) Downloading: 100% - Installing symfony/yaml (v3.0.6) Downloading: 100% - Installing doctrine/instantiator (1.0.5) Downloading: 100% - Installing phpdocumentor/reflection-docblock (2.0.4) Downloading: 100% - Installing phpspec/prophecy (v1.6.0) Downloading: 100% - Installing phpunit/php-text-template (1.2.1) Downloading: 100% - Installing phpunit/phpunit-mock-objects (2.3.8) Downloading: 100% - Installing phpunit/php-timer (1.0.8) Downloading: 100% - Installing phpunit/php-token-stream (1.4.8) Downloading: 100% - Installing phpunit/php-file-iterator (1.4.1) Downloading: 100% - Installing phpunit/php-code-coverage (2.2.4) Downloading: 100% - Installing phpunit/phpunit (4.8.21) Downloading: 100% - Installing guzzlehttp/promises (1.2.0) Loading from cache - Installing psr/http-message (1.0) Loading from cache - Installing guzzlehttp/psr7 (1.3.0) Loading from cache - Installing guzzlehttp/guzzle (6.2.0) Loading from cache sebastian/global-state suggests installing ext-uopz (*) phpdocumentor/reflection-docblock suggests installing dflydev/markdown (~1.0) phpdocumentor/reflection-docblock suggests installing erusev/parsedown (~1.0) phpunit/php-code-coverage suggests installing ext-xdebug (>=2.2.1) phpunit/phpunit suggests installing phpunit/php-invoker (~1.1) Writing lock file Generating autoload files
{ "language": "en", "url": "https://stackoverflow.com/questions/37434724", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Building Postgresql C function with Multidimensional Array as input I am extending the Postgresql functions using the C SPI. The function needs to be able to take in a Postgres N-Dim Array and get the data out of it. I am able to get the data from a 1D array but I get a segfault when trying to access a N-Dim array. My first try to just access an element was simply PG_FUNCTION_INFO_V1(sum_elements); Datum matmul(PG_FUNCTION_ARGS) { ArrayType *anyArray = PG_GETARG_ARRAYTYPE_P(0); int32 **a = (int32 **) ARR_DATA_PTR(anyArray); PG_RETURN_INT64(a[1][1]); } I also tried as if it flattened the matrix into a 1D array but the values that came out were just garbage. Thanks for the help! A: You can try using the deconstruct_array (..) function to extract the values. This function will give you a Datum type pointer. Example of the book: deconstruct_array(input_array, //one-dimensional array INT4OID, //of integers 4,//size of integer in bytes true,//int4 is pass-by value 'i',//alignment type is 'i' &datums, &nulls, &count); // result here "The datums pointer will be set to point to an array filled with actual elements." You can access the values using: DatumGetInt32(datums[i]);
{ "language": "en", "url": "https://stackoverflow.com/questions/43240563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get the timestamps of lyrics in songs? We have built an application in Python for getting the lyrics of a song that the user searches for. We are using the Genius API for this. However, we also want to know the timestamps of each lyric in the song, so that we know when each lyric plays or shows up. Is there an API or library that we could use to get the timestamp of each lyric? Or would we need to manually recognize each lyric in the song using an audio recognition technique? Thank you for all of the help. A: Last time I looked, Genius Lyrics' APIs do not include timestamps unfortunately. There are alternatives out there, such as Musixmatch - although they're not free (and apparently not cheap). I did find Lyrics Plus though. It's an integration for Spotify. Maybe their code on GitHub could help. Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/68424762", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to add generic condition to sp select? I really don't know what to do in this situation, so don't be too harsh. If I have my select: declare @Id uniqueidentifier = 'some parent guid' declare @Type int = 1 -- can be 1, 2 or 3 declare @UserType varchar(max) --can be 0, anything else than 0, or all users at once if(@Type = 1) set @UserType = 'and UserType <> 0' if(@Type = 2) set @UserType = 'and UserType = 0' if(@Type = 3) set @UserType = '' select * from users where parentId = @Id + @UserType What to do in the situation where condition is "generic"? Do i really need to create 3 different Sp? A: You can use AND/OR logic to simulate the If-else condition in where clause. Try something like this select * from users where parentid= @id and ( (@Type = 1 and UserType <> 0) or (@Type = 2 and UserType = 0) or (@Type = 3) ) or you can also use Dynamic sql to do this declare @Id uniqueidentifier = 'some parent guid' declare @Type int = 1 -- can be 1, 2 or 3 Declare @UserType varchar(max) --can be 0, anything else than 0, or all users at once Declare @sql nvarchar(max) if(@Type = 1) set @UserType = ' and UserType <> 0' if(@Type = 2) set @UserType = ' and UserType = 0' if(@Type = 3) set @UserType = '' set @sql = 'select * from users where parentId ='''+ cast(@Id as varchar(25))+''''+ @UserType --Print @sql Exec sp_executesql @sql A: Different select statements would be most efficient since each is a fundamentally different query. If static SQL becomes unwieldly, use dynamic SQL. Below is a parameterized example using techniques from http://www.sommarskog.se/dyn-search.html. declare @sql nvarchar(MAX) = N'select * from users where parentId = @Id'; declare @Id uniqueidentifier = 'some parent guid'; declare @Type int = 1; -- can be 1, 2 or 3 declare @UserType varchar(max); --can be 0, anything else than 0, or all users at once SET @sql = @sql + CASE @Type WHEN 1 THEN N' and UserType <> 0' WHEN 2 THEN N' and UserType = 0' WHEN 3 THEN N'' END; EXEC sp_executesql @sql , N'@Id uniqueidentifier' , @Id = @Id;
{ "language": "en", "url": "https://stackoverflow.com/questions/31771130", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: net::ERR_CONTENT_LENGTH_MISMATCH on angular 2 on docker cloud I am getting a net::ERR_CONTENT_LENGTH_MISMATCH main.bundle.js while running angular 2 on docker cloud ,the same however works on my local docker instance The below is the docker file FROM node RUN mkdir -p /usr/src/app WORKDIR /usr/src/app COPY . /usr/src/app RUN npm install and the docker compose version: '2' services: app: build: . volumes: - ./:/usr/src/app ports: - 4200:4200 - 49153:49153 command: npm start Any clue as to why this is happening will be of much help A: Happened to me after I updated one of the packages in node_modules. Probably integrity/checksum-related issue. The cure was to flush node_modules and run $ npm install again.
{ "language": "en", "url": "https://stackoverflow.com/questions/44351273", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using the deep neural network package "Chainer" to train a simple dataset I'm trying to use the chainer package for a large project I'm working on. I have read through the tutorial on their website which gives an example of applying it to the MNIST dataset, but it doesn't seem to scale easily to other examples, and there's simply not enough documentation otherwise. Their example code is as follows: class MLP(Chain): def __init__(self, n_units, n_out): super(MLP, self).__init__( # the size of the inputs to each layer will be inferred l1=L.Linear(None, n_units), # n_in -> n_units l2=L.Linear(None, n_units), # n_units -> n_units l3=L.Linear(None, n_out), # n_units -> n_out ) def __call__(self, x): h1 = F.relu(self.l1(x)) h2 = F.relu(self.l2(h1)) y = self.l3(h2) return y train, test = datasets.get_mnist() train_iter = iterators.SerialIterator(train, batch_size=5, shuffle=True) test_iter = iterators.SerialIterator(test, batch_size=2, repeat=False, shuffle=False) model = L.Classifier(MLP(100, 10)) # the input size, 784, is inferred optimizer = optimizers.SGD() optimizer.setup(model) updater = training.StandardUpdater(train_iter, optimizer) trainer = training.Trainer(updater, (4, 'epoch'), out='result') trainer.extend(extensions.Evaluator(test_iter, model)) trainer.extend(extensions.LogReport()) trainer.extend(extensions.PrintReport(['epoch', 'main/accuracy', 'validation/main/accuracy'])) trainer.extend(extensions.ProgressBar()) trainer.run() Could someone point me in the direction of how to simple fit a straight line to a few data points in 2D? If I can understand a simple fit such as this I should be able to scale appropriately. Thanks for the help! A: I pasted simple regression modeling here. You can use original train data and test data as tuple. train = (data, label) Here, data.shape = (Number of data, Number of data dimesion) And, label.shape = (Number of data,) Both of their data type should be numpy.float32. import chainer from chainer.functions import * from chainer.links import * from chainer.optimizers import * from chainer import training from chainer.training import extensions from chainer import reporter from chainer import datasets import numpy class MyNet(chainer.Chain): def __init__(self): super(MyNet, self).__init__( l0=Linear(None, 30, nobias=True), l1=Linear(None, 1, nobias=True), ) def __call__(self, x, t): l0 = self.l0(x) f0 = relu(l0) l1 = self.l1(f0) f1 = flatten(l1) self.loss = mean_squared_error(f1, t) reporter.report({'loss': self.loss}, self) return self.loss def get_optimizer(): return Adam() def training_main(): model = MyNet() optimizer = get_optimizer() optimizer.setup(model) train, test = datasets.get_mnist(label_dtype=numpy.float32) train_iter = chainer.iterators.SerialIterator(train, 50) test_iter = chainer.iterators.SerialIterator(test, 50, repeat=False, shuffle=False) updater = training.StandardUpdater(train_iter, optimizer) trainer = training.Trainer(updater, (10, 'epoch')) trainer.extend(extensions.ProgressBar()) trainer.extend(extensions.Evaluator(test_iter, model)) trainer.extend( extensions.PlotReport(['main/loss', 'validation/main/loss'], 'epoch')) trainer.run() if __name__ == '__main__': training_main()
{ "language": "en", "url": "https://stackoverflow.com/questions/41094956", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What's behind Excel Solver Evolutionary? I have an optimization problem on Excel, using Evolutionary algorithm. Works fine, but i'd like to understand how it gets to the solution, ie what is or are the exact method(s) used. Is that available anywhere ? The final purpose being to move this project from Excel to a Java program, because it gets more and more complex. Thank you A: Do the same optimization in LibreOffice Calc. Algorithms done in LibreOffice Calc are available as part of the open-source project.
{ "language": "en", "url": "https://stackoverflow.com/questions/63076123", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Open browser windows without menu bars (JavaScript?) The users in my community want the chat to be opened in a small window without all the control bars. So I think a popup window without scroll bars, location bar, status bar and so on would be the best solution. Right? What is the best way to have such a popup window? JavaScript? Can I do it like this? BETWEEN AND <script type="text/javascript"> <!-- var win = NULL; onerror = stopError; function stopError(){ return true; } function openChat(){ settings = "width=640, height=480, top=20, left=20, scrollbars=no, location=no, directories=no, status=no, menubar=no, toolbar=no, resizable=no, dependent=no"; win = window.open('http://www.example.org/chat.html', 'Chat', settings); win.focus(); } // --> </script> BETWEEN AND <a href="#" onclick="openChat(); return false">Open chat</a> ON CHAT.HTML <form><input type="submit" value="Close chat" onClick="window.close()"></form> A: If you want the new window not to have the menu bars and toolbars, the only way to do it is through JavaScript as with the example you provided yourself. However keep in mind that most browsers, nowadays, ignore what you set for the status bar (always show it) and may be configured to also always show the remaining toolbars. If a browser is configured in such a way there's no escaping it, although the default should be that you'll only get the status bar and perhaps the address bar. A: Your solution is good, but there are alternatives. You can create the window by your own, as some kind of layer. Then you need to implement lots of things but it gives you full control over window Look And Feel. Of course you can always use some scripts like jQuery UI Dialog. A: In short, you can't control everything that the browser displays in a pop-up window. Most browsers keep the URL visible, for example. This page explains most of the details (though it is a couple years old).
{ "language": "en", "url": "https://stackoverflow.com/questions/2081456", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Php laravel 5 fatalexception unexpected end of file I have the following code snippet to end a file in php and laravel. @extends('master') @section('content') <p>Hello World</p> @endsection master.blade.php file is as below <!doctype html> <html lang="em"> <head> <meta charset="UTF-8"> <title>{{ $title }}</title> {{ HTML::style('css/bootstrap.css') }} {{ HTML::script('js/bootstrap.js') }} {{ HTML::script('js/jquery.js') }} </head> <body> <div class="navbar"> <div class="navbar-inner"> {{ HTML::link('/','login',array('class' => 'brand')) }} <ul class="nav pull-right"> @if(Auth::user()) <li>{{ HTML::link('logout', 'Logout') }}</li> @else <li>{{ HTML::link('login','login') }}</li> </ul> </div> </div> <div class="container"> @yield('content') </div> However, I get the following error: FatalErrorException in 4d94a10943d3d038e850b4e898e794a8 line 33: syntax error, unexpected end of file What exactly is the syntax to end the file in laravel,php using the blade template. A: You're missing the @endif directive. Your blade syntax needs to be: @if(Auth::user()) <li>{{ HTML::link('logout', 'Logout') }}</li> @else <li>{{ HTML::link('login','login') }}</li> @endif Without the @endif directive, you'll get the "unexpected end of file" error.
{ "language": "en", "url": "https://stackoverflow.com/questions/31256045", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Memory for a member array in C# I have been programming for a while today and I think I need a break because I can't seem to figure this very simple thing. A help will be greatly appreciated. I have a class (actually Form1) and there a member array int[,]f. Now I don't manage memory for it there and then (maybe I should?). Instead in another method, I call a function say: myFunction(f,.....); this function is like void myFunction(int[,] f, ...some other arguments) { //.... f = new int[NX ,NY]; //.... } As you can see, I separate memory for the array f inside the function. Now my question is; is this memory going to be garbage collected when I leave myFunction? A: First, you have to understand a few very important things: Garbage Collection happens randomly. Secondly, Only those objects that have no variables referring to them are eligible for GC Thirdly, f= new int[NX,NY]; You are making f refer to something else. The original f is still referenced by the Form1.f. But this new int[NX, NY] object is now created and referred to only by the local f in the method. After the method returns, nothing should be referring to the new f (unless you assigned it to somewhere else), so the new f becomes eligible for GC. Note that I said "becomes eligible for GC" instead of "is garbage collected". However, since Form1 is still holding a reference to the original f, the original f will not become eligible for GC before the form does (unless you set it to something else).
{ "language": "en", "url": "https://stackoverflow.com/questions/44917406", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Subtracting dates from 2 different tables with join I am trying to Select all records in the claims data where the “from_date” field is before the “eff_date” for the same “emp_ssn”, same “pt_ssn”, in the "patient data". SELECT * FROM CLAIM left join PATIENT on claim.pt_ssn = Patient.pt_ssn WHERE (CLAIM.emp_ssn = Patient.emp_num AND Patient.pt_ssn=Claim.pt_ssn) AND (CLAIM.FROM_DATE < Patient.eff_date); This is giving me undesired results also with duplicates. I have tried left join, right join, inner join, and no join. I still cannot receive desired result. Any help would be appreciated. A: (CLAIM.emp_ssn = Patient.emp_num AND Patient.pt_ssn=Claim.pt_ssn) The second part of the clause Patient.pt_ssn=Claim.pt_ssn is already mentioned in the ON clause so you don't need to mention it again. Try this : SELECT CLAIM.* FROM CLAIM left join PATIENT on claim.pt_ssn = Patient.pt_ssn WHERE CLAIM.emp_ssn = Patient.emp_num AND CLAIM.FROM_DATE < Patient.eff_date EDIT : I'm not sure what data set you have, but I think a simple group by should resolve your query. I'll try my best to help you out : Table : CLAIM pt_ssn emp_ssn claim_name from_date 1234 1 Claim_1 2015-05-10 2345 2 Claim_2 2015-07-10 3456 3 Claim_3 2015-09-10 4567 4 Claim_4 2015-11-10 5678 5 Claim_5 2015-12-10 5678 5 Claim_5 2015-12-04 6789 6 Claim_6 2015-12-12 Table : PATIENT pt_ssn emp_num eff_date 1234 1 2015-05-12 2345 2 2015-07-08 3456 3 2015-09-15 4567 4 2015-11-07 5678 5 2015-12-09 5678 5 2015-12-12 6789 6 2015-12-02 You can see that I have created duplicate records with the pt_ssn as 5678. Now, if I use the aforementioned query, namely : SELECT CLAIM.* FROM CLAIM left join PATIENT on claim.pt_ssn = Patient.pt_ssn WHERE CLAIM.emp_ssn = Patient.emp_num AND CLAIM.FROM_DATE < Patient.eff_date then the result set I get is : pt_ssn emp_ssn claim_name from_date 1234 1 Claim_1 2015-05-10 3456 3 Claim_3 2015-09-10 5678 5 Claim_5 2015-12-04 5678 5 Claim_5 2015-12-04 /*DUPLICATE ENTRY*/ 5678 5 Claim_5 2015-12-10 SQL Fiddle : http://sqlfiddle.com/#!9/342d0/1 You can see the duplicate entry above. If you want to exclude such duplicate entries, you'll need to use Group By as follows : SELECT CLAIM.pt_ssn, CLAIM.emp_ssn, CLAIM.claim_name, CLAIM.from_date FROM CLAIM left join PATIENT on #claim.pt_ssn = Patient.pt_ssn WHERE CLAIM.emp_ssn = Patient.emp_num AND CLAIM.FROM_DATE < Patient.eff_date GROUP BY CLAIM.from_date, CLAIM.pt_ssn, CLAIM.emp_ssn, CLAIM.claim_name This will give you the result set as follows : pt_ssn emp_ssn claim_name from_date 1234 1 Claim_1 2015-05-10 3456 3 Claim_3 2015-09-10 5678 5 Claim_5 2015-12-04 5678 5 Claim_5 2015-12-10 SQL Fiddle : http://sqlfiddle.com/#!9/342d0/2 Observe that there are two entries for the pt_ssn : 5678. This is because they are for different dates. Hope this helps!!! A: I am guessing there is a patient record even if there is no claim.. so the left join should be the other order. Try this (or even list the fields you want returned): SELECT distinct * FROM PATIENT left join CLAIM on claim.pt_ssn = Patient.pt_ssn and CLAIM.emp_ssn = Patient.emp_num WHERE CLAIM.FROM_DATE < Patient.eff_date;
{ "language": "en", "url": "https://stackoverflow.com/questions/35876640", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to type function calls when using Function.prototype.apply I have the following types: type Options = 'A' | 'B' | 'C' | 'D' type SpecificOptions = 'A' | 'B' type OptionsValueType = { A: () => void, B: string } I use those to build the following class methods: declare class MyClass { myFunction(option: 'A', value: OptionsValueType['A']) myFunction(option: 'B', value: OptionsValueType['B']) myFunction(option: Exclude<Options, SpecificOptions>, value: number) } This works great: And I also have some code that calls myFunction inside a loop, using Function.prototype.apply, it looks something like this: const calls = [ ['A', 1], ['B', 1], ['C', 1], ] for (const call of calls) { a.myFunction.apply(undefined, call) } But the code above does not shows any type error. I cannot use as const on the calls array because it's built dynamically (and even if I could, it does not seems to work either). How to type the code above to make sure the .apply is correctly typed? Or is that currently not possible with Typescript? Above code is available on this Typescript playground A: If calls is built dynamically then no, there is no way to get a compile time error based on its value. You can check the values at runtime and throw an error of your own. Otherwise, JS will pass them in as function arguments regardless of their type. If you wanted to check the types yourself you could do: for (const call of calls) { if (typeof call[0] !== 'string' || typeof call[1] !== 'string') { throw new Error('Both arguments to myFunction must be strings'); } a.myFunction.apply(undefined, call) }
{ "language": "en", "url": "https://stackoverflow.com/questions/55668409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Custom post type – customise single.php in child theme I’ve managed to create my first custom post type (in this case artists) but I want to customise how the single page layout look when click on ‘Read more’ about the artist? So far, I have copied the single.php from the Kalium theme to Kalium child theme, but do not know how to change the code in single.php The page I need help with: https://staging2.africanwomensplaywrightnetwork.org/artist/philisiwe-twijnstra/ <?php /* * Template Name: AWPN Featured Article * Template Post Type: Artists */ /** * Kalium WordPress Theme * * Single post template. * * @author Laborator * @link https://kaliumtheme.com */ if ( ! defined( ‘ABSPATH’ ) ) { exit; // Direct access not allowed. } /** * Theme header. */ get_header(); /** * Show post information if exists. */ if ( have_posts() ) : while ( have_posts() ) : the_post(); /** * kalium_blog_single_before_content * * @hooked kalium_blog_single_post_image_full_width – 10 **/ do_action( ‘kalium_blog_single_before_content’ ); ?> <div <?php kalium_blog_single_container_class(); ?>> <div class=”container”> <div class=”row”> <?php /** * kalium_blog_single_content hook * * @hooked kalium_blog_single_post_image_boxed – 10 * @hooked kalium_blog_single_post_layout – 20 * @hooked kalium_blog_single_post_sidebar – 30 **/ do_action( ‘kalium_blog_single_content’ ); ?> </div> </div> </div> <?php /** * kalium_blog_single_after_content * * @hooked kalium_blog_single_post_comments – 10 **/ do_action( ‘kalium_blog_single_after_content’ ); endwhile; endif; /** * Theme footer. */ get_footer(); A: Make sure you give Template Name: AWPN Featured Article a new unique name. Then go inside an artist's post and select from the right sidebar the new Template you created. Write some content, publish, and check the page in the front-end.
{ "language": "en", "url": "https://stackoverflow.com/questions/73233457", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQLite invalid conversion from ‘char’ to ‘const char*’ [-fpermissive] in CPP Need to update database by new value (Name and Address) provided by the user.The error in query is that: * *error: invalid conversion from ‘char’ to ‘const char*’ [-fpermissive] sqlite3_bind_text(res, 2, *c2) *error: too few arguments to function ‘int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int, void ()(void))’ sqlite3_bind_text(res, 2, *c2) my code is: const char *c1 = updatedName.c_str(); const char *c2 = updatedAdd.c_str(); char *sql = ("UPDATE RECORDS SET NAME = ? AND ADDRESS = ? WHERE ACCOUNT_No = ?"); rc = sqlite3_prepare_v2(db, sql, -1, &res, 0); sqlite3_bind_text(res, 1, *c1); sqlite3_bind_text(res, 2, *c2); sqlite3_bind_int(res, 3, acc); rc = sqlite3_step(res); sqlite3_finalize(res); A: sqlite3_bind_text() wants a pointer to the entire string, not only the first character. (You need to understand how C pointers and strings (character arrays) work.) And the sqlite3_bind_text() documentation tells you to use five parameters: sqlite3_bind_text(res, 1, updatedName.c_str(), -1, SQLITE_TRANSIENT);
{ "language": "en", "url": "https://stackoverflow.com/questions/42891445", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Node js promise in a method I am new to asynch programming and I cannot understand Promises. I am trying to use a reverse geocoding library where lat/long is sent to Google Maps and a json detailing the location is returned. class Geolocator { constructor() { let options = { provider: 'google', httpAdapter: 'https', apiKey: mapsKey, formatter: null }; this._geocoder = NodeGeocoder(options); } getLocationId(lat, lon) { this._geocoder.reverse({lat: lat, lon: lon}) .then(function(res) { return this._parse(null, res); }) .catch(function(err) { return this._parse(err, null); }); } _parse(err, res) { if (err || !res) throw new Error(err); return res; } When I call geolocator.getLocationId I get undefined. I am guessing that the method call exits and returns undefined. What is the best way to encapsulate the promise? A: Like @smarx said, you would return the Promise at getLocationId() and execute then branch: class Geolocator { // ... /* returns a promise with 1 argument */ getLocationId(lat, lon) { return this._geocoder.reverse({ lat, lon }) } } // calling from outside geolocator .getLocationId(lat, lon) .then((res) => { // whatever }) .catch((err) => { // error })
{ "language": "en", "url": "https://stackoverflow.com/questions/38680042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: difference between environment variables and System properties iam using the below link to understand environment variables and system properties. https://docs.oracle.com/javase/tutorial/essential/environment/env.html The link says environment variables are set by OS and passed to applications. When i fetch environment variables using System.getenv() it shows me lot of properties which i never set. So it must be OS (im using macOS) which had set these properties. Some of the properties in System.getenv() are MAVEN_CMD_LINE_ARGS, JAVA_MAIN_CLASS_1420, JAVA_MAIN_CLASS_1430. My question is why would OS would like to set the java specific properties in environment variables? Ideally these should be set by JVM (in System.properties()). P.S.: From whatever i have read on net i understand that environment variables are set by OS and System.properties() are set by JVM Also if someone can point me to a good link on environment variable and System.properties it will be very helpful. Iam very confused between the two. A: Environment variables is an OS concept, and are passed by the program that starts your Java program. That is usually the OS, e.g. double-click in an explorer window or running command in a command prompt, so you get the OS-managed list of environment variables. If another program starts your Java program1, e.g. an IDE (Eclipse, IntelliJ, NetBeans, ...) or a build tool (Maven, Groovy, ...), it can modify the list of environment variables, usually by adding more. E.g. the environment variable named MAVEN_CMD_LINE_ARGS would tend to indicate that you might be running your program with Maven. In a running Java program, the list of environment variables cannot be modified. System properties is a Java concept. The JVM will automatically assign a lot of system properties on startup. You can add/override the values on startup by using the -D command-line argument. In a running Java program, the list of system properties can be modified by the program itself, though that is generally a bad idea. 1) For reference, if a Java program wants to start another Java program, it will generally use a ProcessBuilder to set that up. The environment variables of the new Java process will by default be the same as the current Java program, but can be modified for the new Java program by calling the environment() method of the builder.
{ "language": "en", "url": "https://stackoverflow.com/questions/60925254", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: "stripeErr : Error: You cannot accept payments using this API as it is no longer supported in India I got this error while using stripe, on 23 feb 2022 A: Check your account. You should provide a valid IEC export code to accept any payment. A: As per latest RBI guidelines, Stripe has switched from Charges API to Payment Intent API. Use below API as per data : Stripe::PaymentIntent.create( :customer => customer.id, :amount => params[:amount], :description => 'Rails Stripe transaction', :currency => 'usd', ) It worked for me. Checkout Stripe API documentation here A: you need to change "charges" to "paymentIntents" example: const payment = await stripe.charges.create( //Change here { amount: subTotal * 100, currency: "inr", customer: customer.id, receipt_email: token.email, }, { idempotencyKey: uuidv4(), } );
{ "language": "en", "url": "https://stackoverflow.com/questions/71235137", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Tech-stack for querying and alerting on GB scale (streaming and at rest) datasets Trying to scope out a project that involves data ingestion and analytics, and could use some advice on tooling and software. We have sensors creating records with 2-3 fields, each one producing ~200 records per second (~2kb/second) and will send them off to a remote server once per minute resulting in about ~18 mil records and 200MB of data per day per sensor. Not sure how many sensors we will need but it will likely start off in the single digits. We need to be able to take action (alert) on recent data (not sure the time period guessing less than 1 day), as well as run queries on the past data. We'd like something that scales and is relatively stable . Was thinking about using elastic search (then maybe use x-pack or sentinl for alerting). Thought about Postgres as well. Kafka and Hadoop are definitely overkill. We're on AWS so we have access to tools like kinesis as well. Question is, what would be an appropriate set of software / architecture for the job? A: Have you talked to your AWS Solutions Architect about the use case? They love this kind of thing, they'll be happy to help you figure out the right architecture. It may be a good fit for the AWS IoT services? If you don't go with the managed IoT services, you'll want to push the messages to a scalable queue like Kafka or Kinesis (IMO, if you are processing 18M * 5 sensors = 90M events per day, that's >1000 events per second. Kafka is not overkill here; a lot of other stacks would be under-kill). From Kinesis you then flow the data into a faster stack for analytics / querying, such as HBase, Cassandra, Druid or ElasticSearch, depending on your team's preferences. Some would say that this is time series data so you should use a time series database such as InfluxDB; but again, it's up to you. Just make sure it's a database that performs well (and behaves itself!) when subjected to a steady load of 1000 writes per second. I would not recommend using a RDBMS for that, not even Postgres. The ones mentioned above should all handle it. Also, don't forget to flow your messages from Kinesis to S3 for safe keeping, even if you don't intend to keep the messages forever (just set a lifecycle rule to delete old data from the bucket if that's the case). After all, this is big data and the rule is "everything breaks, all the time". If your analytical stack crashes you probably don't want to lose the data entirely. As for alerting, it depends 1) what stack you choose for the analytical part, and 2) what kinds of triggers you want to use. From your description I'm guessing you'll soon end up wanting to build more advanced triggers, such as machine learning models for anomaly detection, and for that you may want something that doesn't poll the analytical stack but rather consumes events straight out of Kinesis.
{ "language": "en", "url": "https://stackoverflow.com/questions/52612148", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: cosine and sine value of large numbers VHDl I want to implement a CPM modulation in VHDL and my device is Spartan 3A DSP. After the mathematical operation the provided data is the argument for a trigonometric functions and i'm trying to use CORDIC IP CORE in Xilinx 14.7 for this and the problem is that the input data for CORDIC must place between -pi to pi and i don't know how to do this that it could be synthetizable! for now i'm trying to implement the modulation in base band and only the cosine and sine value of the provided data should be send. for example i need the value of "cosine(234.56)" but i don't know how to do it!! i would appreciate if anyone could help me on this.
{ "language": "en", "url": "https://stackoverflow.com/questions/32320671", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mysql2 Error - using COALESCE, Unknown column in where clause In my Rails 4.1 Application, I'm building a query to find records in my collection (orders) by an attribute (name) of a polymorphic relationship (buyer). There are 2 possible tables for that polymorphic, so I'm using 2 LEFT JOINS + COALESCE to merge the attributes. Then attempting use the value from the COALESCE in a where clause. The method in my ActiveRecord model looks like this: class Order ... scope :join_by_buyer_name, -> { select("stock_orders.*", "COALESCE(core_customers.business_name, core_entities.name) AS buyer_name") .joins("LEFT JOIN core_customers ON stock_orders.buyer_id = core_customers.id AND stock_orders.buyer_type='Core::Customer'") .joins("LEFT JOIN core_entities ON stock_orders.buyer_id = core_entities.id AND stock_orders.buyer_type='Core::Entity'") } ... def find_by_buyer_name(term) all.join_by_buyer_name.where("buyer_name LIKE ?", term) end end When the ActiveRecord query is executed it looks like this SELECT stock_orders.*, COALESCE(core_customers.business_name, core_entities.name) AS buyer_name FROM `stock_orders` LEFT JOIN core_customers ON stock_orders.buyer_id = core_customers.id AND stock_orders.buyer_type='Core::Customer' LEFT JOIN core_entities ON stock_orders.buyer_id = core_entities.id AND stock_orders.buyer_type='Core::Entity' WHERE `stock_orders`.`type` IN ('Stock::SalesOrder') AND (buyer_name LIKE "blah") Until recently this worked, However I've started receiving the following error: Mysql2::Error: Unknown column 'buyer_name' in 'where clause': SELECT stock_orders.*, COALESCE etc etc etc It works perfectly for sorting by the COALESCE value - ie collection.order("buyer_name asc") and up until recently the where query worked perfectly too... I'm not sure what has changed and can't see anything in Rails or Mysql documentation. Can you see what's wrong here? Please help! A: You cannot use the ALIAS in WHERE clause that is created from the SELECT clause. Use the computed column instead, AND (COALESCE(core_customers.business_name, core_entities.name) LIKE "blah") if you want to use the ALIAS, you have to wrap it in subquery like the query below, SELECT * FROM ( SELECT stock_orders.*, COALESCE(core_customers.business_name, core_entities.name) AS buyer_name FROM `stock_orders` LEFT JOIN core_customers ON stock_orders.buyer_id = core_customers.id AND stock_orders.buyer_type='Core::Customer' LEFT JOIN core_entities ON stock_orders.buyer_id = core_entities.id AND stock_orders.buyer_type='Core::Entity' ) subquery WHERE `type` IN ('Stock::SalesOrder') AND (buyer_name LIKE "blah")
{ "language": "en", "url": "https://stackoverflow.com/questions/48657041", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can send array as an data using ajax Please see attached jsfiddle link, I need to collect data from multiple forms and combined the data as Single data array send it to server(spring mvc controller) to persist using ajax.post Please let me know best way to do it, will my array be converted to Json by ajax call or I have to do some magic on it. Thanks http://jsfiddle.net/6jzwR/1/ <form id="form1" name="formone" class="myclass"> <input type="text" id="txt11" name="txt11" value="name1" /> <input type="text" id="txt12" name="txt12" value="name2" /> </form> <form id="form1" name="formtwo" class="myclass"> <input type="text" id="txt21" name="txt21" value="name3" /> <input type="text" id="txt22" name="txt22" value="name4" /> </form> <input type="button" id="button" value="Click Me" /> (function ($) { $(document).ready(function () { alert("serialize data :" + $('.myclass').length); var mydata = null; $('#button').on('click', function (e) { $('.myclass').each(function () { alert("serialize data :" + $(this).serialize()); if ((mydata === null) || (mydata === undefined)) { mydata = $(this).serializeArray(); alert("My data is null"); } else { mydata = $.merge(mydata, $(this).serializeArray()); alert("My data final data after merger " + test); } }); }); }); }(jQuery)); A: Try this: var array = $('input[type="text"]').map(function() { return $(this).val(); }).get(); alert(JSON.stringify(array)); Demo. A: You can put all the forms' data in an array and join them with & var formdata = [] $('.myclass').each(function(){ formdata.push($(this).serialize()); }); var data = formdata.join('&'); http://jsfiddle.net/6jzwR/3/
{ "language": "en", "url": "https://stackoverflow.com/questions/21343787", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Angularjs ui sortable - Replace content of dropped item <div ui-sortable="sortableSection" ng-model="mainInputs" class="first"> <div ng-repeat="(i, input) in mainInputs | orderBy: input.type"> <div class="alert alert-success rounded gradient" >{{ input.text }}</div> </div> </div> <div ui-sortable="sortableSection" ng-model="column" class="connected-apps-container" style="min-height: 40px;"> place your elements here </div> var mainInputs = function(){ return [ { type: 'radio', text: 'Radio group', "content_to_drop": { type: 'radio', contents: [{ text: 'radio 1', value: '1' },{ text: 'radio 2', value: '2' },{ text: 'radio 3', value: '3' }] } }, { type: 'checkbox', text: 'Checkbox Input', "content_to_drop": { type: 'checkbox', contents: [{ text: 'checkbox 1', value: '1' },{ text: 'checkbox 2', value: '2' },{ text: 'checkbox 3', value: '3' }] } } ]; }; This is a Drag and drop example. One of the elements being dragged will be inserted inside column array. My problem: Instead of adding the whole object, I just only want the "content_to_drop" object to be added inside the column array. Is there any possibility of doing this? For a better look: https://jsfiddle.net/ssftkp96/ A: You can do the following: var newObj = jQuery.extend({}, ui.item.sortable.model.content_to_drop); // clone $scope.column.push(newObj); Or if you want the drop target to only have a single object you must provide it in the form of an array: var newObj = jQuery.extend({}, ui.item.sortable.model.content_to_drop); $scope.column = [newObj]; var myApp = angular.module('myApp', ['ui.sortable']); myApp.controller('MainCtrl', function($scope) { $scope.mainInputs = []; $scope.column = []; var mainInputs = function() { return [{ type: 'radio', text: 'Radio group', content_to_drop: { type: 'radio', contents: [{ text: 'radio 1', value: '1' }, { text: 'radio 2', value: '2' }, { text: 'radio 3', value: '3' }] } }, { type: 'checkbox', text: 'Checkbox Input', content_to_drop: { type: 'checkbox', contents: [{ text: 'checkbox 1', value: '1' }, { text: 'checkbox 2', value: '2' }, { text: 'checkbox 3', value: '3' }] } }]; }; $scope.mainInputs = mainInputs(); $scope.sortableSection = { connectWith: ".connected-apps-container", update: function(event, ui) { if ( // ensure we are in the first update() callback !ui.item.sortable.received && // check that it's an actual moving between the two lists ui.item.sortable.source[0] !== ui.item.sortable.droptarget[0]) { ui.item.sortable.cancel(); // cancel drag and drop var newObj = jQuery.extend({}, ui.item.sortable.model.content_to_drop); $scope.column.push(newObj); // Or for a single object in the drop target, it must be provided as an Array: //$scope.column = [newObj]; } } }; }); <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> <div ng-app="myApp"> <div ng-controller="MainCtrl"> <div class="col-lg-2 col-md-2 col-sm-3 panel panel-default svd_toolbox"> <div ui-sortable="sortableSection" ng-model="mainInputs" class="first"> <div ng-repeat="(i, input) in mainInputs | orderBy: input.type"> <div class="alert alert-success rounded gradient">{{ input.text }}</div> </div> </div> </div> <div class="co-lg-10 well well-sm"> <div ui-sortable="sortableSection" ng-model="column" class="connected-apps-container" style="min-height: 40px;"> place your elements here </div> </div> <pre>{{ column | json }}</pre> </div> </div> <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/2.5.0/ui-bootstrap-tpls.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-sortable/0.17.0/sortable.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
{ "language": "en", "url": "https://stackoverflow.com/questions/43420807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why am I getting "no such file or directory" for an opencv file that exists when compiling in Ubuntu? I'm trying to use the OpenCV library in C++ (VSCode), so I have the statement #include <opencv4/opencv2/imgproc/imgproc.hpp>. When I try to compile using gcc in Ubuntu, however, I get the following error message: /usr/local/include/opencv4/opencv2/imgproc/imgproc.hpp:48:10: fatal error: opencv2/imgproc.hpp: No such file or directory #include "opencv2/imgproc.hpp" I'm fairly new to C++ and Ubuntu in general so I have no idea why this is happening, as I double checked and the file absolutely exists. In fact, even though it's apparently skipped the imgproc folder in finding the file, imgproc.hpp exists both in opencv2 and in the folder imgproc inside opencv2 anyway. How do I get this to work? A: Did you try using #include "opencv4/opencv2/imgproc/imgproc.hpp" instead?
{ "language": "en", "url": "https://stackoverflow.com/questions/61377467", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Importing an old project in updated Android version While Running or importing a project in newer version of Android Studio got the following error even after successfully built - Could not find com.android.tools.build:aapt2:3.3.0-5013011. Searched in the following locations: - file:/C:/Users/dimi1/AppData/Local/Android/Sdk/extras/m2repository/com/android/tools/build/aapt2/3.3.0-5013011/aapt2-3.3.0-5013011.pom - file:/C:/Users/dimi1/AppData/Local/Android/Sdk/extras/m2repository/com/android/tools/build/aapt2/3.3.0-5013011/aapt2-3.3.0-5013011-windows.jar - file:/C:/Users/dimi1/AppData/Local/Android/Sdk/extras/google/m2repository/com/android/tools/build/aapt2/3.3.0-5013011/aapt2-3.3.0-5013011.pom - file:/C:/Users/dimi1/AppData/Local/Android/Sdk/extras/google/m2repository/com/android/tools/build/aapt2/3.3.0-5013011/aapt2-3.3.0-5013011-windows.jar - file:/C:/Users/dimi1/AppData/Local/Android/Sdk/extras/android/m2repository/com/android/tools/build/aapt2/3.3.0-5013011/aapt2-3.3.0-5013011.pom - file:/C:/Users/dimi1/AppData/Local/Android/Sdk/extras/android/m2repository/com/android/tools/build/aapt2/3.3.0-5013011/aapt2-3.3.0-5013011-windows.jar - https://jcenter.bintray.com/com/android/tools/build/aapt2/3.3.0-5013011/aapt2-3.3.0-5013011.pom - https://jcenter.bintray.com/com/android/tools/build/aapt2/3.3.0-5013011/aapt2-3.3.0-5013011-windows.jar Required by: project :app This is the error message I receive. I downloaded an older project and found solutions to the other error messages. Yet, how can I fix this problem/error message? A: According to the directories, I believe it is a problem with the Android SDK. Try reinstalling Android Studio (but keep the project files), which will also reinstall the Android SDK with it. If that doesn't work, go to https://developer.android.com/studio/#downloads, scroll down to command-line tools only, and download the right version of the Android SDK based on your OS. Go through the install process and hopefully that should fix your issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/54263068", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: modifying styles in child component modifies stack order? I'm trying to use @use-gesture/react's useDrag to ... drag things around. Specifically, some MUI components whose styling gets dynamically updated. I have a component wrapped in a div tied to the bind hook from useDrag: return ( <div {...bindHook}> <MyComponent isDraggable={logic} isShadow={logic} /> // <- Instance 1 </div> ) When you click on the div, I shadow out the original element, and create a new copy of the component in a createPortal portal tied to the document body, such that you can drag it around: const dragObjectPortal = dragState && dragState.pointerStartInfo ? createPortal( <div style={dragObjectStyle}> <div style={dragObjectPositionerStyle} ref={dragBoxRef}> <div style={dragObjectHolderStyle} > <MyComponent isDragged /> // <- Instance 2 </div> </div> </div>, document.body ) : null; Instance 1 renders fine. When I click on it, the state updates, it gets greyed out, the portal is created attached to the body, and Instance 2 renders fine. However, when I drag Instance 2 around, the movement is constrained by the borders of Instance 1. The return from MyComponent is something like: return ( <Card sx={{ position: 'relative', zIndex: 0, py: 2, px: 3, cursor: 'default', touchAction: 'none', ...(!!isDraggable) ? cardSxDraggable : {}, ...(!!isShadow) ? cardSxShadow : {} }} > <Box sx={{ width: 300, height: 300, ...(!!isShadow) ? {bgcolor: 'text.disabled'} : {bgcolor: 'primary.main'} }} > </Box> </Card> ) It took ~ forever for me to figure this out, but if I remove the call to Instance 1, and replace it with inline MUI components from the above return (still dynamically styled), it works fine. So, something about the dynamic styling happening in a component, rather than in the main app's return itself, is ... I don't know ... causing some resetting of the stacking order or something. Inline demo (works as expected) Component demo (motion constrained) But in the actual app I'm writing, I need an arbitrary number of these components. What do I have to do to fix it so that it doesn't ... do whatever it's doing to mess with useDrag?
{ "language": "en", "url": "https://stackoverflow.com/questions/71398798", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does (1 >> 0x80000000) == 1? The number 1, right shifted by anything greater than 0, should be 0, correct? Yet I can type in this very simple program which prints 1. #include <stdio.h> int main() { int b = 0x80000000; int a = 1 >> b; printf("%d\n", a); } Tested with gcc on linux. A: 6.5.7 Bitwise shift operators: If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined. The compiler is at license to do anything, obviously, but the most common behaviors are to optimize the expression (and anything that depends on it) away entirely, or simply let the underlying hardware do whatever it does for out-of-range shifts. Many hardware platforms (including x86 and ARM) mask some number of low-order bits to use as a shift-amount. The actual hardware instruction will give the result you are observing on either of those platforms, because the shift amount is masked to zero. So in your case the compiler might have optimized away the shift, or it might be simply letting the hardware do whatever it does. Inspect the assembly if you want to know which. A: according to the standard, shifting for more than the bits actually existing can result in undefined behavior. So we cannot blame the compiler for that. The motivation probably resides in the "border meaning" of 0x80000000 that sits on the boundary of the maximum positive and negative together (and that is "negative" having the highmost bit set) and on certain check that should be done and that the compiled program doesn't to to avoid to waste time verifying "impossible" things (do you really want the processor to shift bits 3 billion times?). A: It's very probably not attempting to shift by some large number of bits. INT_MAX on your system is probably 2**31-1, or 0x7fffffff (I'm using ** to denote exponentiation). If that's the case, then In the declaration: int b = 0x80000000; (which was missing a semicolon in the question; please copy-and-paste your exact code) the constant 0x80000000 is of type unsigned int, not int. The value is implicitly converted to int. Since the result is outside the bounds of int, the result is implementation-defined (or, in C99, may raise an implementation-defined signal, but I don't know of any implementation that does that). The most common way this is done is to reinterpret the bits of the unsigned value as a 2's-complement signed value. The result in this case is -2**31, or -2147483648. So the behavior isn't undefined because you're shifting by value that equals or exceeds the width of type int, it's undefined because you're shifting by a (very large) negative value. Not that it matters, of course; undefined is undefined. NOTE: The above assumes that int is 32 bits on your system. If int is wider than 32 bits, then most of it doesn't apply (but the behavior is still undefined). If you really wanted to attempt to shift by 0x80000000 bits, you could do it like this: unsigned long b = 0x80000000; unsigned long a = 1 >> b; // *still* undefined unsigned long is guaranteed to be big enough to hold the value 0x80000000, so you avoid part of the problem. Of course, the behavior of the shift is just as undefined as it was in your original code, since 0x80000000 is greater than or equal to the width of unsigned long. (Unless your compiler has a really big unsigned long type, but no real-world compiler does that.) The only way to avoid undefined behavior is not to do what you're trying to do. It's possible, but vanishingly unlikely, that your original code's behavior is not undefined. That can only happen if the implementation-defined conversion of 0x80000000 from unsigned int to int yields a value in the range 0 .. 31. IF int is smaller than 32 bits, the conversion is likely to yield 0. A: well read that maybe can help you expression1 >> expression2 The >> operator masks expression2 to avoid shifting expression1 by too much. That because if the shift amount exceeded the number of bits in the data type of expression1, all the original bits would be shifted away to give a trivial result. Now for ensure that each shift leaves at least one of the original bits, the shift operators use the following formula to calculate the actual shift amount: mask expression2 (using the bitwise AND operator) with one less than the number of bits in expression1. Example var x : byte = 15; // A byte stores 8 bits. // The bits stored in x are 00001111 var y : byte = x >> 10; // Actual shift is 10 & (8-1) = 2 // The bits stored in y are 00000011 // The value of y is 3 print(y); // Prints 3 That "8-1" is because x is 8 bytes so the operacion will be with 7 bits. that void remove last bit of original chain bits
{ "language": "en", "url": "https://stackoverflow.com/questions/7603279", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Check for specific naming convention I have a directory where users are saving their excel files that should adhere to a specific naming convention: XX-TestFile.xlsx where XX is a variable digit and -TestFile.xlsx should always be the same and not change. I'd like to be able to check through a batch job if files in the directory adhere to a specific naming convention. If filename is misspelled, i.e. XX-TetsFiel.xlsx, XX is not a digit like 02 or even XX-testfile.xlsx (all lowercase), then files should move to an Error directory. I am using below to move the files to achieve this. I am testing with 11-testFiel.xlsx and it works just fine. @echo off for /f "delims=" %%a in ('dir /b *.xlsx ^| findstr /v "[0-9][0-9]-TestFile.xlsx"') do move "%%a" "C:\Temp\Archive\Error" However, dir /b *.xlsx | findstr /v "[0-9][0-9]-TestFile.xlsx" allows for 109 possible combinations since XX is a variable with two digits like 02. However, I would now only like to check for specific file names of 20 possible digits like 02-TestFile.xlsx, 05-TestFile.xlsx, 10-TestFile.xlsx, etc. This list is fixed... So for example, if file is named 99-TestFile.xlsx I would still like to move it to an Error archive as it is an undesired file name. Can you suggest a solution for this? A: Put the valid names into a text file (i.e. "ValidNames.txt") and use findstr with the /G option. 02-TestFile.xlsx 05-TestFile.xlsx 10-TestFile.xlsx ... @echo off for /f "delims=" %%a in (' dir /b *.xlsx ^| findstr /vxlg:"ValidNames.txt" ') do move "%%a" "C:\Temp\Archive\Error"
{ "language": "en", "url": "https://stackoverflow.com/questions/55457403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: groupby not behaving as expected The below code is suppose to sum the values of a list of tuples but when two or more tuples contain the same value , the tuple is just outputted once : var data = List((1, "1") , (1, "one")) //> data : List[(Int, java.lang.String)] = List((1,1), (1,one)) data = data.groupBy(_._2).map { case (label, vals) => (vals.map(_._1).sum, label) }.toList.sortBy(_._1).reverse println(data) //> List((1,1)) The output of above is List((1,1)) when I'm expecting List((1,1) , (1,"one")) Does the groupBy function paramaters need to be tweaked to fix this ? A: Actually, it does behave as expected. groupBy returns a map. When you map over a map, you construct a new map, where, of course, each key is unique. Here, you'd have the key 1 twice… You should then call toList before calling map, not after.
{ "language": "en", "url": "https://stackoverflow.com/questions/17189278", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript select specificed data from html tag Is is possible for javascript to work like PHP to find specificed data with keyword ? for example other html from html page <video> <source type="application/x-mpegurl" src="https://xxxx.xxxx/xxx.mp4"></video> other html from html page How can javascript work 2 steps 1st get html page (like php CURL) 2nd find specificed data (in my case is all in src="xx") ("source type="application/x-mpegurl" is keywork for finding) ? Sorry but I'm very bad in javascript. A: You can do this with javascript: document.querySelector('source[type="application/x-mpegurl"]').src
{ "language": "en", "url": "https://stackoverflow.com/questions/53222169", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I add hint text in otp text field and remain nodes focused when code entered in them? I am using the OtpTextField package and trying to add dashes (-) in text field as a hint text but unable to do so. There is a property in decoration which requires hasInputDecoration set to true, by doing so all the other decorations donot apply e.g showFieldAsBox sets to false. How can I achieve dashes in the otp text field. In addition I also want the box's border to be blue as text gets entered into the field and remain blue when all six fields are filled. Kindly help me out in this. OtpTextField( mainAxisAlignment: MainAxisAlignment.spaceBetween, numberOfFields: 6, borderColor: color.primaryLight, filled: true, fillColor: color.primaryLight, borderRadius: BorderRadius.circular(8), showCursor: false, fieldWidth: 40, showFieldAsBox: true, disabledBorderColor: color.accentPrimary, decoration: InputDecoration( hintText: "dfgdfgdf", counterText: '', hintStyle: TextStyle( color: Colors.black, fontSize: sizes!.fontRatio!*17, fontWeight: FontWeight.bold, ) ), //runs when a code is typed in onCodeChanged: (String code) { viewModel().otpTextfield(code); }, //runs when every textfield is filled onSubmit: (String verificationCode){ viewModel().otpTextfield(verificationCode); }, // end onSubmit ),
{ "language": "en", "url": "https://stackoverflow.com/questions/74046609", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Attaching database to SQL Server 2016 using Management Studio 13 When using the right-click option on 'databases' the 'Attach' option is not listed. CODE EXAMPLE WITH ERROR I'm wondering if someone else has seen this before. I also get an error when I run this code instead: CREATE DATABASE testdb ON (FILENAME = 'C:\databasefile.mdf') FOR ATTACH_REBUILD_LOG GO My SQL Server version is select @@version Microsoft SQL Azure (RTM) - 12.0.2000.8 Jul 10 2018 21:38:33 Attach option is missing
{ "language": "en", "url": "https://stackoverflow.com/questions/51333642", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there anyway to set a binding on ALL scroll bars? I need to bind on scroll. Normally I would do this: $(window).bind('scroll', someFunction); The issue is that I have a scroll bar on a specific div, so this doesn't work. I need to do this: $('.divClass').bind('scroll', someFunction); This works fine. I want to do this for ALL my scroll bars though. Is there any good way to do this? A: Use on to bing all your div scrollbar, including the dynamically created div. $(document).on('scroll','.divClass', someFunction); The .divClass must be present on all your container where you want to execute the someFunction function.
{ "language": "en", "url": "https://stackoverflow.com/questions/17597823", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Beds Online API - How to set the destination of the hotel and currency of the results Beds was provided the request example, but i cant set the destination of the hotel in here.. I just want to set manually the destination and set the currency using this request body given by the beds online. $bedsonline_data = '{ "stay": { "checkIn": "2019-01-01", "checkOut": "2019-01-05", "shiftDays": "2" }, "occupancies": [ { "rooms": "1", "adults": "1", "children": "1", "paxes": [ { "type": "AD", "age": 30 }, { "type": "AD", "age": 30 }, { "type": "CH", "age": 8 } ] } ], "hotels": { "hotel": [ 1067,1070,1075,135813,145214,1506,1508,1526,1533,1539,1550,161032,170542,182125,187939,212167,215417,228671,229318,23476 ] } }'; Where do i need to set that here in request body? A: see the API docs ...the response will deliver a currency symbol. and the example on Github explains how to set the destination: $rqData = new \hotelbeds\hotel_api_sdk\helpers\Availability(); $rqData->destination = new Destination("PMI");
{ "language": "en", "url": "https://stackoverflow.com/questions/54228584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Why is there a 'dangling else' scenario here? Do you think that this is a case of dangling else? According to compiler and IIT professor it is. But I have doubt! According to theory, after condition of if is met, it will always process further only ONE statement (or one compound statement i.e. multiple statements enclosed within bracket). Here, after first if is processed and met, the compiler should consider immediate statement that is another if and check for the condition. If condition is not met, then compiler will not display any result as we don't have any associated else with printf function saying condition is not met (i.e. n is not zero). Here, compiler should always associated given else in program with first if clause because all the statement given after first if is not enclosed in brackets. So, why there is a scenario of dangling else here? #include <stdio.h> void main(void) { int n = 0; printf("Enter value of N: "); scanf("%d",&n); if (n > 0) if (n == 0) printf("n is zero\n"); else printf("n is negative\n"); getch(); } A: Per Wikipedia's definition of dangling else, you do have a dangling else statement. C makes your code unambiguous. Your code is interpreted as: if (n > 0) { if (n == 0) { printf("n is zero\n"); } else { printf("n is negative\n"); } } Had you meant the code to be interpreted as: if (n > 0) { if (n == 0) { printf("n is zero\n"); } } else { printf("n is negative\n"); } you would be surprised. FWIW, no matter which interpretation is used, your code is wrong. What you need to have is: if (n > 0) { printf("n is positive\n"); } else { if (n == 0) { printf("n is zero\n"); } else { printf("n is negative\n"); } } or if (n > 0) { printf("n is positive\n"); } else if (n == 0) { printf("n is zero\n"); } else { printf("n is negative\n"); } A: * *if (n == 0) printf("n is zero\n"); else printf("n is negative\n"); is ONE statement and *I strongly recommend not even paying any attention into learning the concept of danglings elses (unless it will show up in tests) but instead learning the concept of ALWAYS using curly brackets, because it helps reading the code and it helps preventing bugs especially when inserting debugging statements. So write: if (n > 0) { if (n == 0) { printf("n is zero\n"); } else { printf("n is negative\n"); } } or if (n > 0) { if (n == 0) { printf("n is zero\n"); } } else { printf("n is negative\n"); } and everything is clear to everyone. BTW: Proper indentation - that might be broken due to copy&paste I admit - will help in reading code and preventing bugs, too. A: +1 to @Bodo Thiesen's suggestion to always use curly braces. I suggest you also use clang-format to automatically format your code. It will it will ident everything correctly and generally make coding wonderful. You can configure clang-format extensively to match your preferred style - this is your code clang-format'd in LLVM's house style. #include <stdio.h> void main(void) { int n = 0; printf("Enter value of N: "); scanf("%d", &n); if (n > 0) if (n == 0) printf("n is zero\n"); else printf("n is negative\n"); getch(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/40825259", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: PHP - PayPal Integration, failed running my custom transaction function after payment accepted I have tried using a tutorial script for PayPal payment in the past and it worked. Now it doesn't. The script is simple, all I need is this one page for processing payment: <?php session_start(); include ('mydbconfig.php'); // payPal settings $paypal_email = '[email protected]'; $return_url = 'https://www.mytestsite.com/paypal-thanks.php'; $cancel_url = 'https://www.mytestsite.com/paypal-cancel.php'; $notify_url = 'https://www.mytestsite.com/paypal-notify.php'; $item_name = $_POST['item_name']; $item_amount = $_POST['item_amount']; //price // check if paypal request or response if (!isset($_POST["txn_id"]) && !isset($_POST["txn_type"])){ // firstly append paypal account to querystring $querystring .= "?business=".urlencode($paypal_email)."&"; // append amount& currency (£) to quersytring so it cannot be edited in html //the item name and amount can be brought in dynamically by querying the $_POST['item_number'] variable. $querystring .= "item_name=".urlencode($item_name)."&"; $querystring .= "amount=".urlencode($item_amount)."&"; //loop for posted values and append to querystring foreach($_POST as $key => $value) { $value = urlencode(stripslashes($value)); $querystring .= "$key=$value&"; } // Append paypal return addresses $querystring .= "return=".urlencode(stripslashes($return_url))."&"; $querystring .= "cancel_return=".urlencode(stripslashes($cancel_url))."&"; $querystring .= "notify_url=".urlencode($notify_url); // Append querystring with custom field //$querystring .= "&custom=".USERID; // Redirect to paypal IPN header('location:https://www.paypal.com/cgi-bin/webscr'.$querystring); exit(); } else { // response from Paypal // read the post from PayPal system and add 'cmd' $req = 'cmd=_notify-validate'; foreach ($_POST as $key => $value) { $value = urlencode(stripslashes($value)); $value = preg_replace('/(.*[^%^0^D])(%0A)(.*)/i','${1}%0D%0A${3}',$value);// IPN fix $req .= "&$key=$value"; } // assign posted variables to local variables $data['item_name'] = $_POST['item_name']; $data['item_number'] = $_POST['item_number']; $data['payment_status'] = $_POST['payment_status']; $data['payment_amount'] = $_POST['mc_gross']; $data['payment_currency'] = $_POST['mc_currency']; $data['txn_id'] = $_POST['txn_id']; $data['receiver_email'] = $_POST['receiver_email']; $data['payer_email'] = $_POST['payer_email']; $data['custom'] = $_POST['custom']; // post back to PayPal system to validate $header = "POST /cgi-bin/webscr HTTP/1.0\r\n"; $header .= "Content-Type: application/x-www-form-urlencoded\r\n"; $header .= "Content-Length: " . strlen($req) . "\r\n\r\n"; $fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30); if (!$fp) { // HTTP ERROR header('location: https://www.mytestsite.com/paypal-error.php?tr='.$data['txn_id'].'&in='.$data['item_name'].'&pe='.$data['payer_email'].'&pa='.$data['payment_amount'].'&ps='.$data['payment_status']); } else { fputs ($fp, $header . $req); while (!feof($fp)) { $res = fgets ($fp, 1024); if (strcmp ($res, "VERIFIED") == 0) { //payment accepted, insert transaction to my database //function to insert transaction here } else if (strcmp ($res, "INVALID") == 0) { //something to do if failed } } fclose ($fp); } } ?> After the process is completed, I checked and the payment is paid successfully, but my function or anything I wrote in //function to insert transaction here won't be executed. In the end I'm forced to do the function on paypal-thanks.php page. Is there something's wrong in the script? Is this script can be used to send more than one item purchasing? My cart is my own custom made and I only want to send Item name, number, and price detail, and total price to PayPal order summary. I checked the other PayPal integration questions here, and most of them direct me to PayPal tutorial, documentation, or integration wizard which're confusing. I use this simple script before because I can't understand PayPal documentation (and the sample code, it didn't even let me know where to start) :( And lastly my ultimate question, is this script is the correct and secure way to do a payment transaction? A: use this $fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30); instead of $fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30); i think it is better to use CURL instead of socket
{ "language": "en", "url": "https://stackoverflow.com/questions/14394380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Erlang C-Node erl_errno symbol not found error I tried to use erl_errno as described in the erlang document: http://erlang.org/doc/man/erl_error.html#. However, I'm getting a symbol not found problem during linking. I'm running on Mac and here's the how the program is linked: g++ -L/usr/local/lib/erlang/lib/erl_interface-3.9.3/lib -o "roserl" ./src/driver.o ./src/erl_bridge.o -lei -lm -lerl_interface I have already linked with libei and liberl_interface. What else is needed? A: It is weird but you will have to do this in your header: #ifndef _REENTRANT #define _REENTRANT /* For some reason __erl_errno is undefined unless _REENTRANT is defined */ #endif #include "erl_interface.h" #include "ei.h" This fixed the problem for me. Now I can use erl_errno.
{ "language": "en", "url": "https://stackoverflow.com/questions/44576090", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ActionScript: How to listen for an event from a different XML I have a popup screen in which the player enters their name and clicks OK. When OK is clicked I want the player's name to be passed to the main XML. How can I do this? Here is the function in the main XML that handles the popup: private function NewHighScore():void{ highScorePopup = PopUpManager.createPopUp(this, Popup, true) as Popup; highScorePopup.SetScore(playerscore); PopUpManager.centerPopUp(highScorePopup); playerName = highScorePopup.getName(); trace(playerName); } And here is the popup XML script: import mx.events.CloseEvent; import mx.managers.PopUpManager; import spark.events.TextOperationEvent; public var playerName:String; public function SetScore (playerScore:int):void{ scoreDisplay.text = "You achieved a new high score of " + playerScore.toString(); } protected function button1_clickHandler(event:MouseEvent):void{ remove(); } private function remove():void{ PopUpManager.removePopUp(this);} protected function titlewindow1_closeHandler(event:CloseEvent):void { remove();} protected function nameBox_changeHandler(event:TextOperationEvent):void {playerName = nameBox.text;} public function getName():String{ return playerName; } A: Waiting for player to enter their name is an asynchronous process, therefore you have to wait for an event dispatched by the popup. Since the popup closes itself (gets removed from stage) once OK button is clicked, you can listen on that popup for Event.REMOVED_FROM_STAGE event, and only then gather the data from the popup. Don't for get to remove the event listener from the popup so that you'll not leak the instance. private function NewHighScore():void{ highScorePopup = PopUpManager.createPopUp(this, Popup, true) as Popup; highScorePopup.SetScore(playerscore); PopUpManager.centerPopUp(highScorePopup); highScorePopup.addEventListener(Event.REMOVED_FROM_STAGE,getPlayerName); } function getPlayerName(event:Event):void { event.target.removeEventListener(Event.REMOVED_FROM_STAGE,getPlayerName); var popup:Popup=event.target as Popup; if (!popup) return; var playerName:String=popup.getName(); // now the name will be populated // do stuff with the name }
{ "language": "en", "url": "https://stackoverflow.com/questions/30894977", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Record video using screenrecord error I am trying to use the adb shell screenrecord functionality on my S4 which is running 4.4. I keep getting this error ERROR: unable to configure codec (err=-2147483648) WARNING: failed at 1080x1920, retrying at 720x1280 Yes the video eventually gets recorded in the lower resolution. How can I record it in the highest resolution possible (even if you can suggest another method)? Thank you
{ "language": "en", "url": "https://stackoverflow.com/questions/28956564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Where to store value for duration of request Preamble I'm developing a card game server in Rails. The application records what a player is expected to do via a tree of instances of the PendingAction model. class Player < ActiveRecord::Base has_many :cards has_many :pending_actions end At any time, the player needs to act on any leaf PendingActions - there may be more than one, for instance: 1. End turn | +- 2. Do thing A | | | + 3. Do thing pre-A | +- 4. Do thing B | + 5. Do thing pre-B The view code presents the player with one or more forms, requesting their choice for each leaf action. For instance, in the above case, forms would be presented to solicit input for actions 3 and 5. When the player makes a choice for, say, action 5, that action is destroyed. However, processing their choice may cause them to need to make another choice before the parent (action 4) can happen. Like so: 1. End turn | +- 2. Do thing A | | | + 3. Do thing pre-A | +- 4. Do thing B | + 6. Do other thing pre-B Action 4 therefore needs to be on-hand, so action 6 can be created as its child. At present, I am simply passing action 4 around as a function argument. However, I've just come across a situation where it would really help to be able to have access to it in a before_save hook on a Card object. Question Where is the best place to store an object, associated with a Player, that I can access from all models related to that Player, which is valid throughout - but not beyond - a single HTTP request? I am running under Heroku, with 1 dyno - so I believe I'm single-threaded. A: It depends on which environment you work, but lets assume that this is single-threaded environment. Next, first thought was to create instance attribute to manually assign and retrieve anything. It is will work fine when Player instance is the same for all places. If not, I suggest to introduce class variable, some sort of cache, that will hold Player#id => <some_obj> reference, and with helper accessors, like Player#some_obj which will query Player for object by self.id. That way you will be ensured that for all Player with the same Id, some_obj will be the same. Also, you will need to deside, when to empty that class-cache. For Rails, i suppose after_filter is good enough.
{ "language": "en", "url": "https://stackoverflow.com/questions/14321649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: The portals keep teleporting me back and forth I have a simple c# script to teleport me between two portals. The problem is that when I place the portals facing down, it keeps teleporting me between them. the script works fine when it is upright. I tried to make a cooldown so that it can't teleport me over and over. I also tried to place the destination above the portal. Here is my code: using UnityEngine; public class portal : MonoBehaviour { public GameObject portal2; public GameObject player; void OnTriggerEnter(Collider other) { if (player.transform.position != portal2.transform.position) { if(other.CompareTag("Player")) { player.transform.position = portal2.transform.position; } } } } A: Comparing the transform positions is not likely to be useful as even a tiny amount of offset in the float (think something as small as 0.0000001 will cause the condition to fail. I would suggest that when a player portals through to another portal, that you place them slightly in front of the portal, in addition to a small cooldown that prevents portal travel. You'll need to translate the players speed (not velocity, speed) to the direction (transform.forward) of the portal they exited as well to keep them moving in the right direction.
{ "language": "en", "url": "https://stackoverflow.com/questions/65444416", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to hold the dynamic text box and its values after form submission fails I am using three dynamic textboxes in a form ,my problem is that when the form validation fails then i have to keep the user in that form ,Now my problem is that i have to hold the values and those textbox also in the form ,how this is possible ?? i am giving a fiddle please suggest what can be done, DEMO FIDDLE Here is the fiddle function GetDynamicTextBox(value) { return '<input class="txt1" name="DynamicTextBox" type="text" value="' + value + '" />&nbsp;<input class="txt2 time" id="myPicker" class="time" type="text" />&nbsp;<input name="phoneNum1" id="phoneNum1" class="time txt3" type="text" /><input type="button" value="Remove" class="remove" />'; } This is the code which is responsible for the creating dynamic textboxes
{ "language": "en", "url": "https://stackoverflow.com/questions/32888038", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: capistrano symlink permission denied I am using cap deploy to deploy to staging. cap deploy:setup created the releases and shared folder. This is the deploy.rb code. set :stages, %w(staging production) set :default_stage, "staging" set :stage_dir, "capistrano" require 'capistrano/ext/multistage' set :application, "application" set :repository, "[email protected]:owner/#{application}.git" set :scm, :git set :local_user, ENV['USER'] || ENV['USERNAME'] || "unknown" set :user, "server_owner" set :deploy_via, :copy set :use_sudo, false set :copy_remote_dir, "/home/#{user}/tmp/capistrano" namespace :deploy do desc "Change Permissions" task :change_permissions, :except => { :no_release => true } do run "find #{current_path}/ -type d -exec chmod 755 {} \\;" run "find #{current_path}/ -type f -exec chmod 644 {} \\;" end desc "Create symlinks for shared items" task :update_shared_symlinks, :except => { :no_release => true} do < ln -s command to create the links> end end before "deploy:finalize_update", "deploy:update_shared_symlinks" And this is the staging code role :app, "ipaddress" set :branch, "staging" set :deploy_to, "/home/#{user}/_#{application}_beta/" When deploying with cap deploy i get the following error ln: creating symbolic link `/home/narayan/_instaprint_beta/releases/20130130102815/': Permission denied Can anyone tell me why this is happening? A: Two things: * *Use chmod straight away instead of a find and exec, like so: chmod 755 #{current_path} *Check if the server_owner user has permission to current_path. If not, then use sudo like so: sudo "chmod 755 #{current_path}"
{ "language": "en", "url": "https://stackoverflow.com/questions/14602270", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Firefox driver for selenium where to download the firefox driver for selenium? I only find this, and herer is not the driver file for download https://code.google.com/p/selenium/wiki/FirefoxDriver NOTE: I already have Selenium Webdriver IDE for Firefox but the script aks me to find firefox driver Can I use firefox in for webdriver in C# or its only capable for java? A: The best approach for C# projects is to install the WebDriver NuGet, because if there are any updates it will be notified. Just install NuGet Manager and search for WebDriver. After that just use the following code: IWebDriver driverOne = new FirefoxDriver(); IWebDriver driverTwo = new InternetExlorerDriver("C:\\PathToMyIeDriverBinaries\"); The FirefoxDriver is included in the NuGet. However, you need to download manually the ChromeDriver from here: https://code.google.com/p/selenium/wiki/ChromeDriver You can find ten mins tutorial with images here: http://automatetheplanet.com/getting-started-webdriver-c-10-minutes/ A: You just need to include/import driver to your project if you want to use firefox unlike for CHROME you need to store the jar file or Exe to a particular location and then then you just need to call it in your project demo program import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class Firefox { public void returnFirefoxBrowser(){ WebDriver driver = new FirefoxDriver(); } } chrome File file = new File( "//Users//Documents//workspace//SELENIUM//chromedriver"); System.setProperty("webdriver.chrome.driver",file.getAbsolutePath()); WebDriver driver_chrome; driver_chrome = new ChromeDriver();
{ "language": "en", "url": "https://stackoverflow.com/questions/31207067", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Problems with updating Xamarin.Android.Support.Annotations 28.0.0 After New Years are over I'm at the office again and started to update the packages of my Xamarin project, that I wrote over the last two months. I got the error: Could not install package 'Xamarin.Android.Support.Annotations 28.0.0'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.6.2', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author. What do I have to do, to handle the error?
{ "language": "en", "url": "https://stackoverflow.com/questions/54003927", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: proving strong induction in coq from scratch I am in the middle of proving the equivalence of weak and strong induction. I have a definition like: Definition strong_induct (nP : nat->Prop) : Prop := nP 0 /\ (forall n : nat, (forall k : nat, k <= n -> nP k) -> nP (S n)) . And I would like to prove the following, and wrote: Lemma n_le_m__Sn_le_Sm : forall n m, n <= m -> S n <= S m . Lemma strong_induct_nP__nP_n__nP_k : forall (nP : nat->Prop)(n : nat), strong_induct nP -> nP n -> (forall k, k < n -> nP k) . Proof. intros nP n [Hl Hr]. induction n as [|n' IHn]. - intros H k H'. inversion H'. - intros H k H'. inversion H'. + destruct n' as [|n''] eqn : En'. * apply Hl. * apply Hr. unfold lt in IHn. assert(H'' : nP (S n'') -> forall k : nat, k <= n'' -> nP k). { intros Hx kx Hxx. apply n_le_m__Sn_le_Sm in Hxx. apply IHn. - apply Hx. - apply Hxx. } However I cannot continue the proof any further. How can I prove the lemma in this situation? A: Changing the place of forall in the main lemma makes it much easier to prove. I wrote it as follow: Lemma strong_induct_is_correct : forall (nP : nat->Prop), strong_induct nP -> (forall n k, k <= n -> nP k). (Also note that in the definition of strong_induct you used <= so it's better to use the same relation in the lemma as I did.) So I could use the following lemma: Lemma leq_implies_le_or_eq: forall m n : nat, m <= S n -> m <= n \/ m = S n. to prove the main lemma like this: Proof. intros nP [Hl Hr] n. induction n as [|n' IHn]. - intros k Hk. inversion Hk. apply Hl. - intros k Hk. apply leq_implies_le_or_eq in Hk. destruct Hk as [Hkle | Hkeq]. + apply IHn. apply Hkle. + rewrite Hkeq. apply Hr in IHn. apply IHn. Qed. This is much a simpler proof and also you can prove a prettier lemma using the lemma above. Lemma strong_induct_is_correct_prettier : forall (nP : nat->Prop), strong_induct nP -> (forall n, nP n). Proof. intros nP H n. apply (strong_induct_is_correct nP H n n). auto. Qed. Note: Usually after using a destruct or induction tactic once, it is not very helpful to use one of them again. So I think using destruct n' after induction n would not bring you any further.
{ "language": "en", "url": "https://stackoverflow.com/questions/59227519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: iOS Example (GLSprite) doesnt show anything i implemented the iOS example (GLSprite) for drawing images but it doesnt show anything. the NSLogs say me, that everything is initialized, so i dont know, why nothing is shown. i want to load a png file and to rotate it. * *context loads *framebuffer creates *setupView finishes *drawView finishes No Errors. Everything seem to work fine except this black screen :) Does anybody knows why? h-file #import <Foundation/Foundation.h> #import <OpenGLES/ES1/gl.h> #import <OpenGLES/ES1/glext.h> @interface CJTEAGLView : UIView { GLint backingWidth; GLint backingHeight; EAGLContext *context; GLuint viewRenderbuffer; GLuint viewFramebuffer; GLuint viewDepthRenderbuffer; GLuint playerTexture; BOOL animating; BOOL displayLinkSupported; NSInteger animationFrameInterval; id displayLink; } @property (nonatomic) BOOL animating; @property (nonatomic) NSInteger animationFrameInterval; - (void)startAnimation; - (void)stopAnimation; - (void)drawView; @end m-file @interface CJTEAGLView() - (void)createFramebuffer; - (void)destroyFramebuffer; - (void)setupView; @end const GLfloat spriteVertices[] = { -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f, }; const GLshort spriteTexcoords[] = { 0, 0, 1, 0, 0, 1, 1, 1, }; @implementation CJTEAGLView @synthesize animating; @synthesize animationFrameInterval; + (Class) layerClass { return [CAEAGLLayer class]; } - (id)initWithCoder:(NSCoder*)coder { if(self = [super initWithCoder:coder]) { CAEAGLLayer *eaglLayer = (CAEAGLLayer *)self.layer; eaglLayer.opaque = YES; eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithBool:FALSE], kEAGLDrawablePropertyRetainedBacking, kEAGLColorFormatRGBA8, kEAGLDrawablePropertyColorFormat, nil]; context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1]; if(!context || ![EAGLContext setCurrentContext:context]) { NSLog(@"Context failed"); [self release]; return nil; } animating = FALSE; displayLinkSupported = TRUE; animationFrameInterval = 1; displayLink = nil; [self createFramebuffer]; [self setupView]; [self drawView]; } return self; } - (void)layoutSubviews { [EAGLContext setCurrentContext:context]; [self destroyFramebuffer]; [self createFramebuffer]; [self drawView]; } - (void)createFramebuffer { glGenFramebuffersOES(1, &viewFramebuffer); glGenRenderbuffersOES(1, &viewRenderbuffer); glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer); glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer); [context renderbufferStorage:GL_RENDERBUFFER_OES fromDrawable:(id<EAGLDrawable>)self.layer]; glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, viewRenderbuffer); glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth); glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight); } - (void)destroyFramebuffer { glDeleteFramebuffers(1, &viewFramebuffer); glDeleteRenderbuffers(1, &viewRenderbuffer); glDeleteRenderbuffers(1, &viewDepthRenderbuffer); } - (NSInteger) animationFrameInterval { return animationFrameInterval; } - (void) setAnimationFrameInterval:(NSInteger)frameInterval { if (frameInterval >= 1) { animationFrameInterval = frameInterval; if (animating) { [self stopAnimation]; [self startAnimation]; } } } - (void) startAnimation { if (!animating) { if (displayLinkSupported) { displayLink = [NSClassFromString(@"CADisplayLink") displayLinkWithTarget:self selector:@selector(drawView)]; [displayLink setFrameInterval:animationFrameInterval]; [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; } animating = TRUE; } } - (void)stopAnimation { if (animating) { if (displayLinkSupported) { [displayLink invalidate]; displayLink = nil; } animating = FALSE; } } - (void)setupView { CGImageRef playerImage; CGContextRef playerContext; GLubyte *playerData; size_t playerWidth; size_t playerHeight; glViewport(0, 0, backingWidth, backingHeight); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrthof(-1.0f, 1.0f, -1.5f, 1.5f, -1.0f, 1.0f); glMatrixMode(GL_MODELVIEW); glClearColor(0, 0, 0, 1); playerImage = [UIImage imageNamed:@"Cruiser.png"].CGImage; playerWidth = CGImageGetWidth(playerImage); playerHeight = CGImageGetHeight(playerImage); if(playerImage) { playerData = (GLubyte *) calloc(playerWidth * playerHeight * 4, sizeof(GLubyte)); playerContext = CGBitmapContextCreate(playerData, playerWidth, playerHeight, 8, playerWidth * 4, CGImageGetColorSpace(playerImage), kCGImageAlphaPremultipliedLast); CGContextDrawImage(playerContext, CGRectMake(0, 0, (CGFloat)playerWidth, (CGFloat)playerHeight), playerImage); CGContextRelease(playerContext); glGenTextures(1, &playerTexture); glBindTexture(GL_TEXTURE_2D, playerTexture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, playerWidth, playerHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, playerData); free(playerData); glEnable(GL_TEXTURE_2D); glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); } } - (void)drawView { [EAGLContext setCurrentContext:context]; glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer); glRotatef(3.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer); [context presentRenderbuffer:GL_RENDERBUFFER_OES]; } @end
{ "language": "en", "url": "https://stackoverflow.com/questions/15689632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I read time in min/hr in a dataframe get sales rate? I have a data frame which has hours in min for example 14:59 where 60:00 (max) is 1 (hr). I tried reading this dataframe using the code below I got an error "Can only use .dt accessor with datetimelike values" df['time sold'].dt.minute My hope was after reading the date below to get the sale rate per min. my data is Name Sales Time Jame 603 14:59 Sam 903 34:00 Lee 756 34:55 Is there a way to get how much each sold be the minute? Name Sales Time Sale Rate Jame 603 14:59 xxxx Sam 903 34:00 yyyy Lee 756 34:55 zzzz Please excuse the xyz just used them as place holders. A: first add the HH to be able to convert it to a pandas timedelta: df['Time'] = '00:'+df['Time'].astype(str) then convert to timedelta df['Time'] = pd.to_timedelta(df['Time']) then make a new column equal to sales per minute df['Sales Rate'] = df['Sales'] / (df['Time'].dt.total_seconds()/60) output: Sales Time Sales Rate Jame 603 00:14:59 40.2447 Sam 903 00:34:00 26.5588 Lee 756 00:34:55 21.6516 A: You could do the following if you have datetime dtype in time column: s = '''Name Sales Time Jame 603 14:59 Sam 903 34:00 Lee 756 34:55''' df = (pd.read_csv(io.StringIO(s), sep='\s+', converters={'Time':lambda x: pd.to_datetime(x, format='%M:%S')}) ) df['rate'] = df['Sales'] / (df['Time'].dt.minute + df['Time'].dt.second.div(60))
{ "language": "en", "url": "https://stackoverflow.com/questions/57641963", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JQuery UI add to accordion Here is the demo for the JQuery UI's accordion widget. I have one on my page, and the way to put items in it (as shown on the demo page) is like so: <div id="accordion"> <h3>Section 1</h3> <div> <p> Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integer ut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sit amet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo ut odio. Curabitur malesuada. Vestibulum a velit eu ante scelerisque vulputate. </p> </div> <h3>Section 2</h3> <div> <p> Sed non urna. Donec et ante. Phasellus eu ligula. Vestibulum sit amet purus. Vivamus hendrerit, dolor at aliquet laoreet, mauris turpis porttitor velit, faucibus interdum tellus libero ac justo. Vivamus non quam. In suscipit faucibus urna. </p> </div> <h3>Section 3</h3> <div> <p> Nam enim risus, molestie et, porta ac, aliquam ac, risus. Quisque lobortis. Phasellus pellentesque purus in massa. Aenean in pede. Phasellus ac libero ac tellus pellentesque semper. Sed ac felis. Sed commodo, magna quis lacinia ornare, quam ante aliquam nisi, eu iaculis leo purus venenatis dui. </p> <ul> <li>List item one</li> <li>List item two</li> <li>List item three</li> </ul> </div> <h3>Section 4</h3> <div> <p> Cras dictum. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Aenean lacinia mauris vel est. </p> <p> Suspendisse eu nisl. Nullam ut libero. Integer dignissim consequat lectus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </p> </div> </div> Notice how for every item, there is the following structure: <h3>Title</h3><div><p>Text</p></div>. I would like to be able to dynamically add to this accordion; however, when I tried to simply add that structure to the accordion it didn't work. I looked into my chrome console, and saw that JQuery adds all sorts of classes and properties to the bare-looking elements of the item. Now, of course the obvious way to solve this is instead of adding <h3>Title</h3> to add <h3 class="ui-accordion-header ui-helper-reset ui-state-default ui-accordion-header-active ui-state-active ui-corner-top ui-accordion-icons" role="tab" id="ui-accordion-lessonlist-header-0" aria-controls="ui-accordion-lessonlist-panel-0" aria-selected="true" tabindex="0"><span class="ui-accordion-header-icon ui-icon ui-icon-triangle-1-s"></span>Title</h3> And likewise for every other element. I know that this should work fine, but it looks ugly and I was wondering if JQuery has provided us with some nice function to do all this stuff for us. If it hasn't, can anyone suggest a less annoying way to do this? EDIT: in response to all the answers suggesting to recreate the accordion: I know that that is probably a better idea than the method shown above, but is it possible to "accordion" only the block of HTML that I need as opposed to the whole accordion, which can get quite big? A: Just recreate the accordion when you add new data to it: $("#accordion").append(html).accordion('destroy').accordion(); A: The only critical HTML is the main structure: <div id="accordion"> <h3>Section 1</h3> <div></div> <h3>Section 2</h3> <div></div> </div> You can put anything you want inside the DIV content panels. WHen you add a a new set of h3 and div, destroy and recreate the accordion: var newPanel='<h3>New section</h3><div>New content</div>'; $('#accordion').append(newPanel).accordion('destroy').accordion( /* options */ );
{ "language": "en", "url": "https://stackoverflow.com/questions/14543068", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Many to many hibernate mapping and intermediate table object How can I define a many to many relationship in hibernate where the intermediate table maps to a object? I.e. Build can have another build as dependency and this dependency can be selected in other builds too. The 'build dependency' object should look something like: BuildDep{ int id; Build parent; Build child; .... } mapping to the intermediate table having columns: id, child_build_id, parent_build_id Thank you A: By definition, many-to-many associations can only be used when the association table does not have any other columns besides the foreign keys to the parent tables. Instead, you should use two ManyToOne/OneToMany associations. Here's a forum topic on this subject (with an example): http://www.coderanch.com/t/218431/ORM/databases/Hibernate-Annotations-many-many-association
{ "language": "en", "url": "https://stackoverflow.com/questions/11941939", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get text of a clicked button? Hi I am very new to java and android studio. I made a set of buttons in a fragment and used a for loop to set the text of each button.... For example: for (int i = 0; i < letterBttns.length; i++) { letterBttns[i].setText(ethereal[i]); } What is the best way to get the text of a clicked button? Is there a short way to do it or the only way to do it is calling an onClick method for each button? Because that seems like the long and easy way. A: public class TestActivity extends AppCompatActivity implements View.OnClickListener { ..... @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); .... for (int i = 0; i < letterBttns.length; i++) { letterBttns[i].setOnClickListener(this); } } @Override public void onClick(View v) { String text = ((Button) v).getText().toString(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/50893485", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }