text
stringlengths
15
59.8k
meta
dict
Q: Variable path PowerShell - Win10 I've downloaded "openSSH-Win64", so I can ssh into a Linux server using my PowerShell. It works if I go into the folder and call the ssh.exe. I don't wanna go into the folder every time I need to use SSH. I've tried this tutorial but it doesn't work. When typing ssh on powershell I get this error: ComSpec : The term 'ComSpec' is not recognized as the name of a cmdlet, function, script file, or operable program. QUESTION: How can I create a variable path or something so every time I type ssh into my PowerShell it will automatically call this executable file C:\Users\druml\Downloads\OpenSSH-Win64\OpenSSH-Win64\ssh.exe? UPDATE: I was able to get this working on the Command Line (cmd), not using PowerShell. In my case I really need to use PowerShell. A: I was able to do this by following: https://superuser.com/questions/949560/how-do-i-set-system-environment-variables-in-windows-10 Once you have added the new Variable, make sure to restart PowerShell as @J. Bergmann has mentioned.
{ "language": "en", "url": "https://stackoverflow.com/questions/44898299", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: My app doesnt show as a suggestion in file explorer? My project is a download manager that open a link to download something. I want to add this feature that when I use chrome Bower and click in a link , my application suggest to user to use it for opening the link. I used <category android:name="android.intent.category.DEFAULT"/> but there is no effect. here is my manifest: <application android:allowBackup="true" android:icon="@drawable/gigaget" android:label="@string/app_name"> <activity android:name=".ui.main.MainActivity" android:label="@string/app_name" android:theme="@style/Theme.App.Blue" android:launchMode="singleTask"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <intent-filter> <action android:name="us.shandian.giga.intent.DOWNLOAD"/> <category android:name="android.intent.category.DEFAULT"/> <category android:name="android.intent.category.BROWSABLE"/> <data android:mimeType="application/*" android:host="*" android:scheme="http"/> <data android:mimeType="application/*" android:host="*" android:scheme="https"/> </intent-filter> </activity> <activity android:name=".ui.main.DetailActivity" android:label="@string/app_name" android:theme="@style/Theme.App.Blue"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <activity android:name=".ui.web.BrowserActivity" android:label="@string/browser" android:theme="@style/Theme.App.Blue"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <activity-alias android:name=".ui.web.BrowserActivity-share" android:label="@string/open_with_gigaget" android:targetActivity=".ui.web.BrowserActivity"> <intent-filter> <action android:name="android.intent.action.SEND"/> <category android:name="android.intent.category.DEFAULT"/> <data android:mimeType="text/*"/> </intent-filter> </activity-alias> <activity android:name=".ui.settings.SettingsActivity" android:label="@string/settings" android:theme="@style/Theme.App.Blue"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <activity android:name="com.nononsenseapps.filepicker.FilePickerActivity" android:label="@string/app_name" android:theme="@style/Theme.App.Blue"> </activity> <service android:name=".service.DownloadManagerService"/> </application> with this permissions: <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> why I cant see my application as suggested app for download like the other applications. any help? A: You need to tell android that your app should become part of the chooser In the manifest you have to declare that you have an activity that can handle the relevant content <manifest ... > <application ... > <activity android:name=".MyDownloadActivity" ...> <intent-filter > <action android:name="android.intent.action.VIEW" /> <action android:name="android.intent.action.SEND" /> <action android:name="android.intent.action.SENDTO" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:mimeType="*/*" android:scheme="file" /> </intent-filter> <intent-filter > <!-- mime only SEND(_TO) --> <action android:name="android.intent.action.SEND" /> <action android:name="android.intent.action.SENDTO" /> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <category android:name="android.intent.category.CATEGORY_OPENABLE" /> <data android:mimeType="*/*" /> </intent-filter> </activity> </application>
{ "language": "en", "url": "https://stackoverflow.com/questions/42359952", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Angularjs service: when should we use isArray vs params Can someone explain when should we use isArray vs params in Angular services? Assuming in api the return value is ArrayList<MyCustomeCalss> In my service I have angular.module('MyApp').factory('MyService', ['$resource', 'URLService', function ($resource, URL) { return $resource("",null, { 'geresult': { method: 'POST', url: URL.get('result'), //isArray: true when to use?? //params: {} when to use?? } }); }]); A: Maybe I misunderstood something...but don't get it why vs? isArray is just says you that you'll get an array throughout this resource and an array will be returned instantly for you to be able to iterate over it and then it will be populated by your data, so you can use it as an array after you just call a resource. quote from documentation: It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data. This is a useful trick since usually the resource is assigned to a model which is then rendered by the view. params is just pre-bounded params for your POST request. You can read this article for better understanding
{ "language": "en", "url": "https://stackoverflow.com/questions/21925113", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add video player for desktop (macOS and Windows) to a flutter I need to make a program with a video player that will be supported everywhere. I use the video_player library, but it's only for iOS and Android, and I need and for macOS and Windows. A: There is no support for video player plugin on Windows, MacOS or linux as of now. Hopefully flutter team might add this feature by the end of this year.
{ "language": "en", "url": "https://stackoverflow.com/questions/66673107", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Unit test for EJB3 I would like to setup unit and integration for ejb3 (entity/jpa). I'm using Eclipse, Maven, and Jonas server. It seems that easybeans is what I need for integration test. Where can I find some sample project? Thanks, A: You should use the EJB embedded container: http://www.adam-bien.com/roller/abien/entry/embedding_ejb_3_1_container
{ "language": "en", "url": "https://stackoverflow.com/questions/6753204", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to put a foreign key in knex migration? I'm trying to put a foreign key in knex migration. "age_group_id"(primary key of the "agegroups" table) is the foreign key of the "users" table. So, I have put it like the below picture. (line 22) 20220424203501_create_users.ts When I run the code (npm run deploy:fresh) it shows an error like the below. error But, without line number 22, it is not showing an error. Here is my folder structure. folder structure Can someone help me to fix this issue and what is wrong with the way I wrote the foreign key? A: you should check if your database has data that doesn't fit like an id value that is not present in the foreign table, delete any rows like that and the migration should work, it would help if you let us know what npm run deploy:fresh does, you might be doing something else wrong if the data is not clearing on a clean migration A: You need to use the same data type in both tables when using foreign keys. As an example, if you are using 'uuid' for id in agegroups table, then you must use uuid for users table foreign key (age_group_id)also. But here you used 'text' data type for foreign key. Please check whether both data types are similar or not.
{ "language": "en", "url": "https://stackoverflow.com/questions/72000568", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Check if an Object exists in VBScript I'm maintaining a Classic ASP app written in VB Script by an outside company long, long ago. I have an array of imagefile paths, like so: dim banners, arrKeys, i set banners=CreateObject("Scripting.Dictionary") banners.Add "banner1.jpg", "http://www.somelink.com" banners.Add "banner2.jpg", "http://www.somelink.com" banners.Add "banner3.jpg", "http://www.somelink.com" This will exist ONLY on pages that have banner ads. There is some standard code that iterates through this list in an include file (common to all pages). If Not banners Is Nothing then ' then loop through the Dictionary and make a list of image links End if The problem is that if banners is not instantiated on the page (it's not on all pages), I get a Can't find object error What's the proper way to check if an object exists in VB Script? A: If a variable is declared, but not initialized, its value will be Empty, which you can check for with the IsEmpty() function: Dim banners If IsEmpty(banners) Then Response.Write "Yes" Else Response.Write "No" End If ' Should result in "Yes" being written banners will only be equal to Nothing if you explicitly assign it that value with Set banners = Nothing. You will have problems, though, with this technique if you have Option Explicit turned on (which is the recommendation, but isn't always the case). In that case, if banners hasn't been Dimed and you try to test IsEmpty(banners), you will get a runtime error. If you don't have Option Explicit on, you shouldn't have any problems. edit: I just saw this related question and answer which might help, too. A: @Atømix: Replace If Not banners Is Nothing then and use If IsObject(banners) Then Your other code you can then place into an include file and use it at the top of your pages to avoid unnecessary duplication. @Cheran S: I tested my snippets above with Option Explicit on/off and didn't encounter errors for either version, regardless of whether Dim banners was there or not. :-) A: IsObject could work, but IsEmpty might be a better option - it is specifically intended to check if a variable exists or has been initialised. To summarize: * *IsEmpty(var) will test if a variable exists (without Object Explicit), or is initialised *IsNull(var) will test if a variable has been assigned to Null *var Is Nothing will test if a variable has been Set to Nothing, but will throw an error if you try it on something that isn't an object *IsObject(var) will test if a variable is an object (and will apparently still return False if var is Empty). A: Somewhat related is IsMissing() to test if an optional parameter was passed, in this case an object, like this: Sub FooBar(Optional oDoc As Object) 'if parameter is missing then simulate it If IsMissing(oDoc) Then Dim oDoc as Object: oDoc = something ... A: You need to have at least dim banners on every page. Don't you have a head.asp or something included on every page? A: Neither of IsEmpty, Is Object, IsNull work with the "Option Explicit" Setting, as stealthyninja above has misleadingly answered. The single way i know is to 'hack' the 'Option Explicit' with the 'On Error Resume Next' setting, as Tristan Havelick nicely does it here: Is there any way to check to see if a VBScript function is defined?
{ "language": "en", "url": "https://stackoverflow.com/questions/4100506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: Error while assigning a public propery function CharField($len) { return "VARCHAR($len)"; } class ArticleModel extends Model { public $name = CharField(100); // Error Here } When I assign a public property like this with a returned value from a function, it throws the error: PHP Parse error: syntax error, unexpected '(', expecting ',' or ';' in /var/www/test/db.php What can the reason be? A: You can only initialize properties with constants: http://www.php.net/manual/en/language.oop5.properties.php [Properties] are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated. So indeed, initialize them in your constructor. A: Initialize the value in your constructor A: According to the manual you can only assign a constant value when instantiating a class property.
{ "language": "en", "url": "https://stackoverflow.com/questions/8094195", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Caching a result from EF I have this method for retrieving a result from my context and caching it using MemoryCache. public IEnumerable<CustomerRole> GetCustomerRoles() { string key = String.Format(CC_CACHE_CUSTOMER_ROLE_ALL, "all"); return _cacheManager.Get(key, () => { return from r in _customerRoleRepository.Table select r; } ); } I then use this in my view like @foreach (CustomerRole role in Model) { } The problem I have is that because the actual result isn't executed until the data is accessed (in my view), it's not actually caching the result. How do I force this query to run via my caching function rather than waiting until the data is used? I've not included what _cacheManager.Get() does as I know it's caching whatever I send to it properly but if you think that is the problem, let me know and I will post the relative code. Note: I have tried doing it this way hoping it would force the query to run but still no luck public IEnumerable<CustomerRole> GetCustomerRoles() { string key = String.Format(CC_CACHE_CUSTOMER_ROLE_ALL, "all"); return _cacheManager.Get(key, () => { var roles = from r in _customerRoleRepository.Table select r; return roles.Take(roles.Count()); } ); } A: You need to call a method like ToList() to force linq to get the data. Then just add that list to your cache.
{ "language": "en", "url": "https://stackoverflow.com/questions/21760423", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Autoplay audio not working on any browser I am designing an HTML page and added an audio in the header there using the below code: <audio id="audio_play"> <source src="voice/Story 2_A.m4a" type="audio/ogg" /> </audio> <img class="head-icon" src="img/audio.png" onClick="document.getElementById('audio_play').play(); return false;" /> <img class="head-icon2" src="img/audio2.png" onClick="document.getElementById('audio_play').pause(); return false;" /> But now I want to autoplay the audio on page load. I am using autoplay both on the audio tag and the source tag. But can't help. Even removed the last 2 lines of the code following this, but that too won't help. You can check the page directly from here. As per the code added, it is playing the audio upon clicking on the icon now. I am not sure what I am missing to make it autoplay on page load. A: Audio/Video has been restricted from autoplaying. They can play only with user interaction. Also please keep the format of the audio file as ogg instead of m4a as you have specified the type as audio/ogg. Change from voice/Story 2_A.m4a to voice/something.ogg
{ "language": "en", "url": "https://stackoverflow.com/questions/69871080", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding CheckBoxList of items to MVC 4 View I have the challenge of adding CheckBoxList of items to MVC 4 view. I have several models in the same the MVC 4 view. So I created the View Model below public class ArticlesVM { public article articles { get; set; } public game games { get; set; } public gallery mgallery { get; set; } public team teams { get; set; } public ArticlesVM() { Teams = new List<TeamVM>(); } public List<TeamVM> Teams { get; set; } } to include 4 models as it properties. I then created a view where each of the properties can be used independently as follows: @model TeamBuildingCompetition.ViewModels.ArticlesVM @{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout_new.cshtml"; } <h2>Index</h2> @using (Html.BeginForm("Create", "TBCArticles", FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.AntiForgeryToken() <div class="form-horizontal"> <h4></h4> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <div class="form-group"> @Html.LabelFor(model => model.articles.featuredImage, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-8"> @Html.TextBoxFor(model => model.articles.featuredImage, new { @type = "file" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.games.gameName, "Select a Game", htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-8"> @Html.DropDownList("gameID", (IEnumerable<SelectListItem>)ViewBag.gameList, "Select Game", new { @class = "form-control" }) </div> </div> <div class="form-group"> @Html.HiddenFor(model => model.teams.teamID) @Html.HiddenFor(model => model.teams.teamName) @Html.DisplayFor(model => model.teams.teamName) <div class="col-md-8"> @for(int i = 0; i < Model.Teams.Count; i++){ @Html.HiddenFor(model => model.Teams[i].ID) @Html.CheckBoxFor(model => model.Teams[i].IsSelected) @Html.LabelFor(model => model.Teams[i].IsSelected, Model.Teams[i].TeamName) } </div> </div> <div class="form-group"> @Html.LabelFor(model => model.articles.articleTitle, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-8"> @Html.EditorFor(model => model.articles.articleTitle, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.articles.articleTitle, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.articles.articleContent, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-8"> @Html.EditorFor(model => model.articles.articleContent, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.articles.articleContent, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.mgallery.picturePath, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-8"> @Html.TextBoxFor(model => model.mgallery.picturePath, new { @type = "file", @multiple = "true" }) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-8"> <input type="submit" value="Create" class="btn btn-default" /> </div> </div> </div> } @section Scripts { @Scripts.Render("~/bundles/jqueryval") } Here is my TeamVM model below: public class TeamVM { public int ID { get; set; } [Required(ErrorMessage = "Please Enter Your Team Name")] [Display(Name = "Team Name")] public string TeamName { get; set; } [DisplayName("Team Picture")] [ValidateFile] public HttpPostedFileBase TeamPicture { get; set; } [Required] [Display(Name = "Description")] public string Description { get; set; } [Required(ErrorMessage = "Please Enter Team Content")] [Display(Name = "Content")] [MaxLength(500)] public string Content { get; set; } public bool IsSelected { get; set; } } Added the following to my controller action: [HttpGet] public ActionResult Index(ArticlesVM model) { model = new ArticlesVM (); model = new ArticlesVM(); var teamList = (from p in db.teams select new TeamVM() { ID = p.teamID, TeamName = p.teamName, IsSelected = p.IsSelected }); model.Teams = teamList.ToList(); ViewBag.gameList = new SelectList(db.games, "gameID", "gameName"); return View(model); } And now have a null reference error in this portion of the view: <div class="form-group"> @Html.HiddenFor(model => model.teams.teamID) @Html.DisplayFor(model => model.teams.teamName) <div class="col-md-8"> @for(int i = 0; i < Model.Teams.Count; i++){ @Html.HiddenFor(model => model.Teams[i].ID) @Html.CheckBoxFor(model => model.Teams[i].IsSelected) @Html.LabelFor(model => model.Teams[i].IsSelected, Model.Teams[i].TeamName) } </div> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/33242885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Make Object grow upwards in VBA I was able to make an object grow to the right sucessfully, slowly, just the way I needed, but , how can I make it grow upwards? This is what I was able to do (to make it grow to the right) Private Sub growup() If ActiveSheet.Shapes("image1").Width > 300 Then Exit Sub End If For A = 1 To 200 With ActiveSheet.Shapes("image1") .Width = .Width + 3 DoEvents End With Next A end sub Also, (just in case I need in the future) To the left? A: Use the other available properties of .Height .Top There is also .Left '<==For indent As per @Comintern's point you do need to adjust .Top and .Height together! See full property list of shape object here: https://msdn.microsoft.com/en-us/vba/excel-vba/articles/shape-object-excel
{ "language": "en", "url": "https://stackoverflow.com/questions/51656170", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Swift - How to record video in MP4 format with UIImagePickerController? I am creating a app in which i need to record videos and upload it to a server. Now my project has a android version too. To support android version i have to record the videos in mp4 format. I followed this tutorial to set the UIImagePicker media type to movie format imagePicker.mediaTypes = [kUTTypeMovie as String] The UIImagePickerController is perfect for my requirement and the only thing that i need to change is its saving format to mp4. I tried kUTTypeMPEG4 in mediaTypes but it throws error at the run time with no error description. This is my video Capture function func startCameraFromViewController() { if UIImagePickerController.isSourceTypeAvailable(.Camera) == false { return } viewBlack.hidden = false presentViewController(cameraController, animated: false, completion: nil) cameraController.sourceType = .Camera cameraController.mediaTypes = [kUTTypeMovie as String] //cameraController.mediaTypes = [kUTTypeMPEG4 as String] cameraController.cameraCaptureMode = .Video cameraController.videoQuality = .TypeMedium if(getPurchaseId() as! Int == 0) { if(txtBenchMark.text?.isEmpty == false) { cameraController.videoMaximumDuration = NSTimeInterval(300.0) }else{ cameraController.videoMaximumDuration = NSTimeInterval(60.0) } }else{ cameraController.videoMaximumDuration = NSTimeInterval(600.0) } cameraController.allowsEditing = false } I am using Swift 2.2 and Xcode 8 with Use Legacy swift Language version = Yes Any Alternative Solutions are also appreciated. Thanks in advance. EDIT: I found out that there is no method to directly record videos in mp4 format in swift. only can be converted to required format from apple's quicktime mov format. A: A quick swift 4 update to the previous answers: func encodeVideo(videoUrl: URL, outputUrl: URL? = nil, resultClosure: @escaping (URL?) -> Void ) { var finalOutputUrl: URL? = outputUrl if finalOutputUrl == nil { var url = videoUrl url.deletePathExtension() url.appendPathExtension(".mp4") finalOutputUrl = url } if FileManager.default.fileExists(atPath: finalOutputUrl!.path) { print("Converted file already exists \(finalOutputUrl!.path)") resultClosure(finalOutputUrl) return } let asset = AVURLAsset(url: videoUrl) if let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetPassthrough) { exportSession.outputURL = finalOutputUrl! exportSession.outputFileType = AVFileType.mp4 let start = CMTimeMakeWithSeconds(0.0, 0) let range = CMTimeRangeMake(start, asset.duration) exportSession.timeRange = range exportSession.shouldOptimizeForNetworkUse = true exportSession.exportAsynchronously() { switch exportSession.status { case .failed: print("Export failed: \(exportSession.error != nil ? exportSession.error!.localizedDescription : "No Error Info")") case .cancelled: print("Export canceled") case .completed: resultClosure(finalOutputUrl!) default: break } } } else { resultClosure(nil) } } A: Swift 5.2 Update Solution // Don't forget to import AVKit func encodeVideo(at videoURL: URL, completionHandler: ((URL?, Error?) -> Void)?) { let avAsset = AVURLAsset(url: videoURL, options: nil) let startDate = Date() //Create Export session guard let exportSession = AVAssetExportSession(asset: avAsset, presetName: AVAssetExportPresetPassthrough) else { completionHandler?(nil, nil) return } //Creating temp path to save the converted video let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] as URL let filePath = documentsDirectory.appendingPathComponent("rendered-Video.mp4") //Check if the file already exists then remove the previous file if FileManager.default.fileExists(atPath: filePath.path) { do { try FileManager.default.removeItem(at: filePath) } catch { completionHandler?(nil, error) } } exportSession.outputURL = filePath exportSession.outputFileType = AVFileType.mp4 exportSession.shouldOptimizeForNetworkUse = true let start = CMTimeMakeWithSeconds(0.0, preferredTimescale: 0) let range = CMTimeRangeMake(start: start, duration: avAsset.duration) exportSession.timeRange = range exportSession.exportAsynchronously(completionHandler: {() -> Void in switch exportSession.status { case .failed: print(exportSession.error ?? "NO ERROR") completionHandler?(nil, exportSession.error) case .cancelled: print("Export canceled") completionHandler?(nil, nil) case .completed: //Video conversion finished let endDate = Date() let time = endDate.timeIntervalSince(startDate) print(time) print("Successful!") print(exportSession.outputURL ?? "NO OUTPUT URL") completionHandler?(exportSession.outputURL, nil) default: break } }) } A: Minor refactoring of previous examples: import AVFoundation extension AVURLAsset { func exportVideo(presetName: String = AVAssetExportPresetHighestQuality, outputFileType: AVFileType = .mp4, fileExtension: String = "mp4", then completion: @escaping (URL?) -> Void) { let filename = url.deletingPathExtension().appendingPathExtension(fileExtension).lastPathComponent let outputURL = FileManager.default.temporaryDirectory.appendingPathComponent(filename) if let session = AVAssetExportSession(asset: self, presetName: presetName) { session.outputURL = outputURL session.outputFileType = outputFileType let start = CMTimeMakeWithSeconds(0.0, 0) let range = CMTimeRangeMake(start, duration) session.timeRange = range session.shouldOptimizeForNetworkUse = true session.exportAsynchronously { switch session.status { case .completed: completion(outputURL) case .cancelled: debugPrint("Video export cancelled.") completion(nil) case .failed: let errorMessage = session.error?.localizedDescription ?? "n/a" debugPrint("Video export failed with error: \(errorMessage)") completion(nil) default: break } } } else { completion(nil) } } } Also: AVAssetExportPresetHighestQuality preset works when video is played on Android / Chrome. P.S. Be aware that the completion handler of exportVideo method might not be returned on the main thread. A: I made some modifications to the following 2 answers to make it compatible with Swift 5: https://stackoverflow.com/a/40354948/2470084 https://stackoverflow.com/a/39329155/2470084 import AVFoundation func encodeVideo(videoURL: URL){ let avAsset = AVURLAsset(url: videoURL) let startDate = Date() let exportSession = AVAssetExportSession(asset: avAsset, presetName: AVAssetExportPresetPassthrough) let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] let myDocPath = NSURL(fileURLWithPath: docDir).appendingPathComponent("temp.mp4")?.absoluteString let docDir2 = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] as NSURL let filePath = docDir2.appendingPathComponent("rendered-Video.mp4") deleteFile(filePath!) if FileManager.default.fileExists(atPath: myDocPath!){ do{ try FileManager.default.removeItem(atPath: myDocPath!) }catch let error{ print(error) } } exportSession?.outputURL = filePath exportSession?.outputFileType = AVFileType.mp4 exportSession?.shouldOptimizeForNetworkUse = true let start = CMTimeMakeWithSeconds(0.0, preferredTimescale: 0) let range = CMTimeRange(start: start, duration: avAsset.duration) exportSession?.timeRange = range exportSession!.exportAsynchronously{() -> Void in switch exportSession!.status{ case .failed: print("\(exportSession!.error!)") case .cancelled: print("Export cancelled") case .completed: let endDate = Date() let time = endDate.timeIntervalSince(startDate) print(time) print("Successful") print(exportSession?.outputURL ?? "") default: break } } } func deleteFile(_ filePath:URL) { guard FileManager.default.fileExists(atPath: filePath.path) else{ return } do { try FileManager.default.removeItem(atPath: filePath.path) }catch{ fatalError("Unable to delete file: \(error) : \(#function).") } } A: Here is some code that you can use to convert the recorded video into MP4: func encodeVideo(videoURL: NSURL) { let avAsset = AVURLAsset(URL: videoURL, options: nil) var startDate = NSDate() //Create Export session exportSession = AVAssetExportSession(asset: avAsset, presetName: AVAssetExportPresetPassthrough) // exportSession = AVAssetExportSession(asset: composition, presetName: mp4Quality) //Creating temp path to save the converted video let documentsDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] let myDocumentPath = NSURL(fileURLWithPath: documentsDirectory).URLByAppendingPathComponent("temp.mp4").absoluteString let url = NSURL(fileURLWithPath: myDocumentPath) let documentsDirectory2 = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL let filePath = documentsDirectory2.URLByAppendingPathComponent("rendered-Video.mp4") deleteFile(filePath) //Check if the file already exists then remove the previous file if NSFileManager.defaultManager().fileExistsAtPath(myDocumentPath) { do { try NSFileManager.defaultManager().removeItemAtPath(myDocumentPath) } catch let error { print(error) } } url exportSession!.outputURL = filePath exportSession!.outputFileType = AVFileTypeMPEG4 exportSession!.shouldOptimizeForNetworkUse = true var start = CMTimeMakeWithSeconds(0.0, 0) var range = CMTimeRangeMake(start, avAsset.duration) exportSession.timeRange = range exportSession!.exportAsynchronouslyWithCompletionHandler({() -> Void in switch self.exportSession!.status { case .Failed: print("%@",self.exportSession?.error) case .Cancelled: print("Export canceled") case .Completed: //Video conversion finished var endDate = NSDate() var time = endDate.timeIntervalSinceDate(startDate) print(time) print("Successful!") print(self.exportSession.outputURL) default: break } }) } func deleteFile(filePath:NSURL) { guard NSFileManager.defaultManager().fileExistsAtPath(filePath.path!) else { return } do { try NSFileManager.defaultManager().removeItemAtPath(filePath.path!) }catch{ fatalError("Unable to delete file: \(error) : \(__FUNCTION__).") } } Source: https://stackoverflow.com/a/39329155/4786204 A: Run on iOS11, we will always received the nil value for the AVAssetExportSession. Do we have any solution for this case? if let exportSession = AVAssetExportSession(asset: avAsset, presetName: AVAssetExportPresetPassthrough) { //work on iOS 9 and 10 } else { //always on iOS 11 }
{ "language": "en", "url": "https://stackoverflow.com/questions/40354689", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: Treelike structure stored in a database So I am working on a book tracking app and I need to store data about the books. Using objects I would store a list of author objects which would include series objects. Those would have book objects. What is the best way to translate this into a database? Will be using SQLite. A: You would create your tables based on your Object structure and relationships. It seems what you have is an Authors(table) that has many Series(table). Series have many Books(table). Correct me if I'm wrong, I didn't understand your last sentence that well. If I am correct then you would need foreign keys as follows: an author_id on your series table, and a series_idon your books table to link back to the parent table for queries. Let me know if it helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/10038655", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to map multiple lists to one dictionary? I used this code: dictionary = dict(zip(list1, list2)) in order to map two lists in a dictionary. Where: list1 = ('a','b','c') list2 = ('1','2','3') The dictionary equals to: {'a': 1, 'c': 3, 'b': 2} Is there a way to add a third list: list3 = ('4','5','6') so that the dictionary will equal to: {'a': [1,4], 'c': [3,5], 'b': [2,6]} This third list has to be added so that it follows the existing mapping. The idea is to make this work iteratively in a for loop and several dozens of values to the correctly mapped keyword. Is something like this possible? A: dict((z[0], list(z[1:])) for z in zip(list1, list2, list3)) will work. Or, if you prefer the slightly nicer dictionary comprehension syntax: {z[0]: list(z[1:]) for z in zip(list1, list2, list3)} This scales up to to an arbitrary number of lists easily: list_of_lists = [list1, list2, list3, ...] {z[0]: list(z[1:]) for z in zip(*list_of_lists)} And if you want to convert the type to make sure that the value lists contain all integers: def to_int(iterable): return [int(x) for x in iterable] {z[0]: to_int(z[1:]) for z in zip(*list_of_lists)} Of course, you could do that in one line, but I'd rather not. A: In [12]: list1 = ('a','b','c') In [13]: list2 = ('1','2','3') In [14]: list3 = ('4','5','6') In [15]: zip(list2, list3) Out[15]: [('1', '4'), ('2', '5'), ('3', '6')] In [16]: dict(zip(list1, zip(list2, list3))) Out[16]: {'a': ('1', '4'), 'b': ('2', '5'), 'c': ('3', '6')} In [17]: dict(zip(list1, zip(map(int, list2), map(int, list3)))) Out[17]: {'a': (1, 4), 'b': (2, 5), 'c': (3, 6)} In [18]: dict(zip(list1, map(list, zip(map(int, list2), map(int, list3))))) Out[18]: {'a': [1, 4], 'b': [2, 5], 'c': [3, 6]} For an arbitrary number of lists, you could do this: dict(zip(list1, zip(*(map(int, lst) for lst in (list2, list3, list4, ...))))) Or, to make the values lists rather than tuples, dict(zip(list1, map(list, zip(*(map(int, lst) for lst in (list2, list3, list4, ...))))))
{ "language": "en", "url": "https://stackoverflow.com/questions/15834244", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Python Export Blob From SQL Server I have a table in SQL Server with a varbinary(max) column that contains file blobs. I am exporting these with Python and pyodbc like this: import pyodbc conn = pyodbc.connect('DSN=SQL Server;UID=username;PWD=password') cursor = conn.cursor() with open("output.pdf", "wb") as output_file: cursor.execute("SELECT top 1 filedata from schm.table_name") blob = cursor.fetchone() output_file.write(blob[0]) This works for text files, but all other file types (e.g. pdf, xlsx, etc.) are corrupted. Opening the exported file in notepad shows the same characters as casting the column as varchar in SQL Server. How do I remedy this?
{ "language": "en", "url": "https://stackoverflow.com/questions/56693520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to use findAll with associations in Sequelize I'm having problems to use the findAll() method with associations from Sequelize. I have two models: Posts and Authors (an author has many posts and one post has one author), that I have created with Sequelize-cli and then through the migration command npx sequelize db migrate:all i have created them in mysql. To keep things organized, I have the associations between the models in another migration file (created with npx sequelize init:migrations, after all the models already existent), so my code looks like this: AUTHOR MODEL 'use strict'; module.exports = (sequelize, DataTypes) => { const Author = sequelize.define('Author', { authorName: { type: DataTypes.STRING, validate: { is: ["^[a-z]+$",'i'], } }, biography: { type: DataTypes.TEXT, validate: { notEmpty: true, } } }, {}); Author.associate = function(models) { Author.hasMany(models.Post); }; return Author; }; POST MODEL 'use strict'; module.exports = (sequelize, DataTypes) => { const Post = sequelize.define('Post', { title: { type: DataTypes.STRING, validate: { is: ["^[a-z]+$",'i'], notEmpty: true, }, }, content: { type: DataTypes.TEXT, validate: { notEmpty: true, }, }, likes: { type: DataTypes.INTEGER, defaultValue: 0, validate: { isInt: true, }, }, }, {}); Post.associate = function(models) { // associations can be defined here }; return Post; }; ASSOCIATIONS FILE (MIGRATION) (showing only parts that matter) up: (queryInterface, Sequelize) => { return queryInterface.sequelize.transaction(t => { return Promise.all([ queryInterface.addColumn('Posts','AuthorId', { type: Sequelize.INTEGER, references: { model: 'Authors', key: 'id', }, onUpdate: 'CASCADE', onDelete: 'SET NULL', }, { transaction: t }), queryInterface.addColumn('Posts', 'ImagesId', { type: Sequelize.INTEGER, references: { model: 'Images', key: 'id', }, onUpdate: 'CASCADE', onDelete: 'SET NULL', }, { transaction: t }), queryInterface.addColumn('Posts', 'CategoryId', { type: Sequelize.INTEGER, references: { model: 'Categories', key: 'id', }, onUpdate: 'CASCADE', onDelete: 'SET NULL', }, { transaction: t }), ]); }); This is working fine apparently, since in Mysql-Workbench it shows me the following: But, when I try to use the findAll() like this: const { Post, Author } = require('../models/index'); function(response) { Post.findAll({ attributes: ['id', 'title', 'content', 'likes'], include: { model: Author, } }) .then(result => response.json(result)) .catch(error => response.send(`Error getting data. Error: ${error}`)); It gives me the following error: SequelizeEagerLoadingError: Author is not associated to Post! So, I dont know anymore how to proceed. I've been trying many others approaches, but all of then unsuccessfully. I read already many other questions here in StackOverFlow about how to solve this sort of problem, but those were unsuccessfully too. Thanks in advance. A: You need to define the association for Post also as you are querying upon Post model Post.associate = function(models) { Post.belongsTo((models.Author); }; You need to add an association from both ends, Post -> Author and Author -> Post , this way you will never stuck in this kind of error. A: Summarizing this documentation we have the following: If you have these models: const User = sequelize.define('user', { name: DataTypes.STRING }); const Task = sequelize.define('task', { name: DataTypes.STRING }); And they are associated like this: User.hasMany(Task); Task.belongsTo(User); You can fetch them with its associated elements in these ways: const tasks = await Task.findAll({ include: User }); Output: [{ "name": "A Task", "id": 1, "userId": 1, "user": { "name": "John Doe", "id": 1 } }] And const users = await User.findAll({ include: Task }); Output: [{ "name": "John Doe", "id": 1, "tasks": [{ "name": "A Task", "id": 1, "userId": 1 }] }]
{ "language": "en", "url": "https://stackoverflow.com/questions/57681084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Image gets cutt off when positioning outside of a modal window I have this html file: <div style=" width:400px; height:300px; background-color:#009966;"> </div> I'm opening it as a modal window with colorbox, that has this CSS: #cboxOverlay, #cboxWrapper, #colorbox { position: absolute; top: 0; left: 0; z-index: 9999; overflow: hidden; } #cboxWrapper { max-width: none; } #cboxOverlay { position: fixed; width: 100%; height: 100%} #cboxBottomLeft, #cboxMiddleLeft { clear: left; } #cboxContent { position: relative; } #cboxLoadedContent { overflow: auto; -webkit-overflow-scrolling: touch; } #cboxTitle { margin: 0; } #cboxLoadingGraphic, #cboxLoadingOverlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%} #cboxClose, #cboxNext, #cboxPrevious, #cboxSlideshow { cursor: pointer; } .cboxPhoto { float: left; margin: auto; border: 0; display: block; max-width: none; -ms-interpolation-mode: bicubic; } .cboxIframe { width: 100%; height: 100%; display: block; border: 0; } #cboxContent, #cboxLoadedContent, #colorbox { box-sizing: content-box; -moz-box-sizing: content-box; -webkit-box-sizing: content-box; } #cboxOverlay { background: #000; } #colorbox { outline: 0; } #cboxContent { margin-top: 32px; overflow: visible; } .cboxIframe { background: #fff; } #cboxError { padding: 50px; border: 1px solid #ccc; } #cboxLoadedContent { padding: 1px; } #cboxLoadingGraphic { background: url(../images/loading.gif) no-repeat center center; } #cboxLoadingOverlay { background: #000; } #cboxTitle { position: absolute; top: -22px; left: 0; color: #000; } #cboxCurrent { position: absolute; top: -22px; right: 205px; text-indent: -9999px; } #cboxClose { border: 0; padding: 0; margin: 0; overflow: visible; text-indent: -9999px; width: 20px; height: 20px; position: absolute; top: -30px; left:390px; background: url(../images/controls.png) no-repeat; } #cboxClose:active, #cboxNext:active, #cboxPrevious:active, #cboxSlideshow:active { outline: 0; } #cboxPrevious { background-position: 0 0; right: 44px; } #cboxPrevious:hover { background-position: 0 -25px; } #cboxNext { background-position: -25px 0; right: 22px; } #cboxNext:hover { background-position: -25px -25px; } #cboxClose { background-position: -50px 0; right: 0; } #cboxClose:hover { background-position: -50px -25px; } .cboxSlideshow_off #cboxPrevious, .cboxSlideshow_on #cboxPrevious { right: 66px; } .cboxSlideshow_on #cboxSlideshow { background-position: -75px -25px; right: 44px; } .cboxSlideshow_on #cboxSlideshow:hover { background-position: -100px -25px; } .cboxSlideshow_off #cboxSlideshow { background-position: -100px 0; right: 44px; } .cboxSlideshow_off #cboxSlideshow:hover { background-position: -75px -25px; } I've tried playing with the position of the "X" button, I want it to be outside of the DIV, say 50px to the top and 50px to the right, by modifying #cboxClose, but that image gets cutted off, as you can see in the photo. what's causing this? A: The container #cboxWrapper has overflow: hidden; set (near the top of your included CSS); if you add overflow: visible; to that selector, your moved X button should be visible. I wouldn't recommend changing the original overflow: hidden; declaration, since it involves other selectors, but just adding the the following: #cboxWrapper { overflow: visible; }
{ "language": "en", "url": "https://stackoverflow.com/questions/25949920", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to implement Selenium webdriver for web application developed with React.js components I am working with Selenium automation and the appliction I am testing is based on react.js technology and it has so many dynamic contents. Because of this I never find ID or Name of any element. Always I have to search with Text contains. Also It has table based on react.js and there is not table, tr or td componet i.e xpath of one of cell:"//* [@id='react']/div/div/span/span/span/div/div/div[2]/div[1]/div/div[1]/div/div/div/div[1]/div/div/div[1]". I always found similar xpath for button, select drop down or any element. Does anyone help me with this react.js implementation? It become hard to find dynamic elements and locate this elements. Also, it become imposible to get check box state; When checkbox checked: <span class="MuiButtonBase-root-203 MuiIconButton-root-270 MuiSwitchBase-root-295 MuiSwitchBase-default-297 MuiCheckbox-default-292 MuiSwitchBase-checked-298 MuiCheckbox-checked-293"> <span class="MuiIconButton-label-276"> <svg class="MuiSvgIcon-root-279" focusable="false" viewBox="0 0 24 24" aria-hidden="true"> <input class="MuiSwitchBase-input-296" value="on" type="checkbox"> </span> <span class="MuiTouchRipple-root-205"></span> When checkbox not checked: <span class="MuiButtonBase-root-203 MuiIconButton-root-270 MuiSwitchBase-root-295 MuiSwitchBase-default-297 MuiCheckbox-default-292"> <span class="MuiIconButton-label-276"> <svg class="MuiSvgIcon-root-279" focusable="false" viewBox="0 0 24 24" aria-hidden="true"> <input class="MuiSwitchBase-input-296" value="on" type="checkbox"> </span> <span class="MuiTouchRipple-root-205"></span> Anyone has idea? How to read check box and entire table? I have three check boxes (Text1, Text2 and Text3). Lables Text1 and so are dynamically changed based on previous selection..Now from this I want check the status of check box and do appropriate action <span class="MuiButtonBase-root-461 MuiIconButton-root-528 MuiSwitchBase-root-553 MuiSwitchBase-default-555 MuiCheckbox-default-550"> <span class="MuiIconButton-label-534"> <svg class="MuiSvgIcon-root-537" focusable="false" viewBox="0 0 24 24" aria-hidden="true"> <path d="M19 5v14H5V5h14m0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"/> </svg> <input class="MuiSwitchBase-input-554" value="on" type="checkbox"/> </span> <span class="MuiTouchRipple-root-463"/> </span> <p class="MuiTypography-root-1 MuiTypography-body1-10 MuiFormControlLabel-label-549">Text1</p> <label class="MuiFormControlLabel-root-546 MuiFormControlLabel-hasLabel-548"> <span class="MuiButtonBase-root-461 MuiIconButton-root-528 MuiSwitchBase-root-553 MuiSwitchBase-default-555 MuiCheckbox-default-550"> <span class="MuiIconButton-label-534"> <svg class="MuiSvgIcon-root-537" focusable="false" viewBox="0 0 24 24" aria-hidden="true"> <input class="MuiSwitchBase-input-554" value="on" type="checkbox"/> </span> <span class="MuiTouchRipple-root-463"/> </span> <p class="MuiTypography-root-1 MuiTypography-body1-10 MuiFormControlLabel-label-549">Text2</p> <span class="MuiButtonBase-root-461 MuiIconButton-root-528 MuiSwitchBase-root-553 MuiSwitchBase-default-555 MuiCheckbox-default-550"> <span class="MuiIconButton-label-534"> <svg class="MuiSvgIcon-root-537" focusable="false" viewBox="0 0 24 24" aria-hidden="true"> <input class="MuiSwitchBase-input-554" value="on" type="checkbox"/> </span> <span class="MuiTouchRipple-root-463"/> </span> <p class="MuiTypography-root-1 MuiTypography-body1-10 MuiFormControlLabel-label-549">Text3</p> A: Use Xpath-contains instead of string-contains * *Shorten your xpath by using //tag[contains(@attr, 'string')] for example //spans[contains(@class, 'MuiCheckbox-checked')] Code Solution(Level-by-Level) * *First, select high-level elements *Then, find your second-level elements(i.e. Button)
{ "language": "en", "url": "https://stackoverflow.com/questions/47167380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: OnItemClick of a ListView I want to appear a new activity when I click on a ListItem, this is my whole code: This is the ListViewActivity's code: import java.util.ArrayList; import java.util.HashMap; import java.util.List; import json.JSONParser; import org.apache.http.NameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.ListActivity; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; public class IntervActivity extends ListActivity implements OnItemClickListener { //private static final String TAG_PID = "ID"; private static final String TAG_NAME = "name"; ArrayList<HashMap<String, String>> actList; private ProgressDialog progressMessage; private static String url_act= "http://10.0.2.2/Scripts/liste_interventions.php"; //private static String url_act= "http://192.168.43.95/android_Web_Service/actualite.php"; JSONParser jParser = new JSONParser(); JSONArray act = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.interv_list); actList = new ArrayList<HashMap<String, String>>(); new LoadAllact().execute(); // Get listview ListView lv = getListView(); lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // getting values from selected ListItem String name= ((TextView) view.findViewById(R.id.name)).getText().toString(); // Starting new intent Intent in = new Intent(IntervActivity.this, DetailsActivity.class); // sending pid to next activity in.putExtra(TAG_NAME, name); startActivity(in); } }); } class LoadAllact extends AsyncTask<String,String,String> { @Override protected void onPreExecute() { super.onPreExecute(); progressMessage = new ProgressDialog(IntervActivity.this); progressMessage.setMessage("chargement actualité..."); progressMessage.setIndeterminate(false); progressMessage.setCancelable(false); progressMessage.show(); } protected String doInBackground(String... args) { List<NameValuePair> params = new ArrayList<NameValuePair>(); JSONObject json = jParser.makeHttpRequest(url_act, "GET", params); Log.d("actualite: ", json.toString()); try { int success = json.getInt("success"); if (success == 1) { act = json.getJSONArray("act"); for (int i = 0; i < act.length(); i++) { JSONObject c = act.getJSONObject(i); // String id = c.getString("id"); String name = c.getString("name"); // creating new HashMap HashMap<String, String> map = new HashMap<String, String>(); // adding each child node to HashMap key => value //map.put("Int_id", id); map.put("Int_name", name); actList.add(map); } } } catch (JSONException e) {e.printStackTrace();} return null; } protected void onPostExecute(String file_url) { progressMessage.dismiss(); runOnUiThread(new Runnable() { public void run() { ListAdapter adapter = new SimpleAdapter( IntervActivity.this, actList, R.layout.interv_list_item, new String[] {"Int_name"}, new int[]{ R.id.name }); setListAdapter(adapter); } }); } } @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub } } and this is the code of the DetailsActivity that I want to appear when I click on the any item of the ListView: import java.util.ArrayList; import java.util.HashMap; import java.util.List; import json.JSONParser; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.MenuItem; import android.widget.EditText; import android.widget.TextView; public class DetailsActivity extends Activity { private static final String TAG_NAME = "name"; public String name; private static final String TAG_SUCCESS = "success"; ArrayList<HashMap<String, String>> actList; private ProgressDialog pDialog; private static String url_int_details= "http://10.0.2.2/Scripts/details_intervention.php"; //private static String url_act= "http://192.168.43.95/android_Web_Service/actualite.php"; JSONParser jParser = new JSONParser(); protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.details_activity); Intent i = getIntent(); // getting product id (pid) from intent String name = i.getStringExtra("name"); // Getting complete product details in background thread new GetProductDetails().execute(); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); return super.onOptionsItemSelected(item); } class GetProductDetails extends AsyncTask<String, String, String> { /** * Before starting background thread Show Progress Dialog * */ @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(DetailsActivity.this); pDialog.setMessage("Loading product details. Please wait..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } /** * Getting product details in background thread * */ protected String doInBackground(String... params) { // updating UI from Background Thread runOnUiThread(new Runnable() { public void run() { // Check for success tag int success; try { // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("name", name)); // getting product details by making HTTP request // Note that product details url will use GET request JSONObject json = jParser.makeHttpRequest( url_int_details, "GET", params); // check your log for json response Log.d("Single Product Details", json.toString()); // json success tag success = json.getInt(TAG_SUCCESS); if (success == 1) { // successfully received product details JSONArray productObj = json .getJSONArray("interv"); // JSON Array // get first product object from JSON Array JSONObject product = productObj.getJSONObject(0); TextView tvLibelle = (TextView) findViewById(R.id.textView1); tvLibelle.setText(product.getString("name")); TextView tvDate= (TextView) findViewById(R.id.textView2); tvDate.setText(product.getString("date")); TextView tvEchéance= (TextView) findViewById(R.id.textView3); tvEchéance.setText(product.getString("date_deadline")); TextView tvPriorité= (TextView) findViewById(R.id.textView4); tvPriorité.setText(product.getString("priority")); TextView tvDescription= (TextView) findViewById(R.id.textView5); tvDescription.setText(product.getString("description")); TextView tvEtat= (TextView) findViewById(R.id.textView6); tvEtat.setText(product.getString("state")); }else{ // product with pid not found } } catch (JSONException e) { e.printStackTrace(); } } }); return null; } /** * After completing background task Dismiss the progress dialog * **/ protected void onPostExecute(String file_url) { // dismiss the dialog once got all details pDialog.dismiss(); } } } This is DetailsActivity xml code: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="top" android:background="#99E7E5" tools:context="com.example.mobisav.DetailsActivity" > <TextView android:id="@+id/textView6" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/textView4" android:layout_alignBottom="@+id/textView4" android:layout_alignRight="@+id/textView2" android:hint="@string/Etat" android:textAppearance="?android:attr/textAppearanceSmall" /> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView2" android:layout_below="@+id/textView2" android:layout_marginTop="36dp" android:hint="@string/Echeance" android:textAppearance="?android:attr/textAppearanceSmall" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_toRightOf="@+id/textView5" android:hint="@string/Nom_intervention" /> <TextView android:id="@+id/textView4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignRight="@+id/textView1" android:layout_centerVertical="true" android:hint="@string/Priority" android:textAppearance="?android:attr/textAppearanceSmall" /> <TextView android:id="@+id/textView5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/button1" android:layout_alignLeft="@+id/textView6" android:layout_marginBottom="33dp" android:hint="@string/Description" android:textAppearance="?android:attr/textAppearanceSmall" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/textView1" android:layout_marginTop="28dp" android:hint="@string/Date" android:textAppearance="?android:attr/textAppearanceSmall" /> <Button android:id="@+id/button1" style="?android:attr/buttonStyleSmall" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_marginBottom="14dp" android:layout_toLeftOf="@+id/textView4" android:hint="@string/Appeler" /> </RelativeLayout> and finally this is the php file that match with the data base: <?php // array for JSON response $response = array(); $hostname_localhost ='localhost'; $port_localhost =5432; $database_localhost ='techmobi'; $username_localhost ='openpg'; $password_localhost ='openpgpwd'; $localhost = "host='$hostname_localhost' port='$port_localhost' dbname='$database_localhost' user='$username_localhost' password='$password_localhost'"; // check for post data $connexion =pg_connect($localhost) or die ("Erreur de connexion ".pg_last_error()); if (isset($_GET["name"])) { $name = $_GET["name"]; $query_search = "SELECT id, name, date, priority, state, description, date_deadline FROM crm_helpdesk WHERE name = $name"; $query_exec = pg_query($query_search) or die(pg_error()); if (!empty($query_exec )) { // check for empty result if (pg_num_rows($result) > 0) { $query_exec = pg_fetch_array($query_exec ); $interv = array(); $interv["id"] = $query_exec ["id"]; $interv["name"] = $query_exec ["name"]; $interv["date"] = $query_exec ["date"]; $interv["description"] = $query_exec ["description"]; $interv["priority"] = $query_exec ["priority"]; $interv["state"] = $query_exec ["state"]; $interv["date_deadline"] = $query_exec ["date_deadline"]; // success $response["success"] = 1; // user node $response["interv"] = array(); array_push($response["interv"], $interv); // echoing JSON response echo json_encode($response); } else { // no product found $response["success"] = 0; $response["message"] = "No product found"; // echo no users JSON echo json_encode($response); } } else { // no product found $response["success"] = 0; $response["message"] = "No product found"; // echo no users JSON echo json_encode($response); } } else { // required field is missing $response["success"] = 0; $response["message"] = "Required field(s) is missing"; // echoing JSON response echo json_encode($response); } ?> When I run my app and I click any item of the list, a new activity appears but there is no data from the DB on it. Please help A: well, The problem is your String url_int_details in DetailsActivity just the same as url_act. What can I see in your DetailsActivity is: you use GET method from the "http://10.0.2.2/Scripts/details_intervention.php". And this url is contain a listView as you said but not a detail. So how to solve this problem. You should create new_url_int_details like this: http://10.0.2.2/Scripts/details_intervention.php?id=12 Your url has to contain your item's ID. I made something just like your idea, you can learn more from my project. This is my Detail_Activity: public class FMovieDetailsActivity extends Activity { ArrayList<CinemaItems> cinemaList; String id; TextView tvNameF; TextView tvLengthF; TextView tvIMDbF; TextView tvStartF; TextView tvDescriptionF; TextView tvCatF; TextView tvTrailer; TextView tvLengthTrailer; ListView listView; Button btnTrailer; private Context context; ImageView f_imageTrailer; ImageView f_imageView; private static final String TAG_ID = "id"; private static final String TAG_FUTURE_MOVIE = "future_movie"; private static final String TAG_NAME_F = "movienameF"; private static final String TAG_DESCRIPTION_F = "descriptionF"; private static final String TAG_IMDB_F = "imdbF"; private static final String TAG_LENGTH_F = "lengthF"; private static final String TAG_CAT = "cat_name"; private static final String TAG_IMAGE_F = "m_imageF"; private static final String TAG_SUCCESS_F = "success"; private static final String TAG_START_F = "startdateF"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.moviedetails); cinemaList = new ArrayList<CinemaItems>(); Intent i = getIntent(); id = i.getStringExtra(TAG_ID); new JSONAsyncTask().execute(); tvNameF = (TextView) findViewById(R.id.tvMovieName); tvLengthF = (TextView) findViewById(R.id.tvLength); tvIMDbF = (TextView) findViewById(R.id.tvIMdb); tvStartF = (TextView) findViewById(R.id.tvStartDate); tvDescriptionF = (TextView) findViewById(R.id.tvDescription); tvCatF = (TextView) findViewById(R.id.tvCategory); f_imageView = (ImageView) findViewById(R.id.imageMovieDetail); ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); } class JSONAsyncTask extends AsyncTask<String, String, String> { ProgressDialog dialog; @Override protected void onPreExecute() { super.onPreExecute(); dialog = new ProgressDialog(FMovieDetailsActivity.this); dialog.setMessage("Loading, please wait"); dialog.setTitle("Connecting server"); dialog.show(); dialog.setCancelable(false); } @Override protected String doInBackground(String... urls) { try { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(TAG_ID, id)); Log.i("show parse id", id); String paramString = URLEncodedUtils.format(params, "utf-8"); //this is your problem, You lack of this url String url = ServicesConfig.SERVICES_HOST + ServicesConfig.SERVICES_GET_FUTURE_DETAILS + "?" + paramString; Log.i("show url", url); HttpGet httpget = new HttpGet(url); HttpClient httpClient = new DefaultHttpClient(); HttpResponse respone = httpClient.execute(httpget); HttpEntity entity = respone.getEntity(); return EntityUtils.toString(entity, "UTF-8"); } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String respone) { try { JSONObject jsono = new JSONObject(respone); int success = jsono.optInt(TAG_SUCCESS_F, 0); if (success == 1) { JSONObject jsonObject = jsono.getJSONObject(TAG_FUTURE_MOVIE); tvNameF.setText(jsonObject.optString(TAG_NAME_F)); tvIMDbF.setText("IMDb: " + jsonObject.optString(TAG_IMDB_F)); tvLengthF.setText("Duration: " + jsonObject.optString(TAG_LENGTH_F)); tvStartF.setText("Start: " + jsonObject.optString(TAG_START_F)); tvDescriptionF.setText(jsonObject.optString(TAG_DESCRIPTION_F)); tvCatF.setText(jsonObject.optString(TAG_CAT)); Picasso.with(context).load(ServicesConfig.SERVICES_HOST + jsonObject.optString(TAG_IMAGE_F)).fit() .into(f_imageView); } else { Toast.makeText(getBaseContext(), "Unable to fetch data from server", Toast.LENGTH_SHORT).show(); } } catch (Exception e) { e.printStackTrace(); } dialog.dismiss(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: this.finish(); return true; } return super.onOptionsItemSelected(item); } } This is my php file: <?php $response = array(); require_once __DIR__ . '/db_connect.php'; $db = new DB_CONNECT(); if (isset($_GET["id"])) { $id = $_GET['id']; $result = mysql_query("SELECT m.*, c.cat_name FROM future_movie as m inner join category as c on m.cat_id = c.cat_id WHERE m.id = $id"); $img = "test_cinema/images/product/"; if (!empty($result)) { if (mysql_num_rows($result) > 0) { $result = mysql_fetch_array($result); $movie = array(); $movie["id"] = $result["id"]; $movie["movienameF"] = $result["movienameF"]; $movie["descriptionF"] = $result["descriptionF"]; $movie["imdbF"] = $result["imdbF"]; $movie["lengthF"] = $result["lengthF"]; $movie["startdateF"] = $result["startdateF"]; $movie["cat_name"] = $result["cat_name"]; $movie["m_imageF"] = $img.$result["m_imageF"]; $response["success"] = 1; $response["future_movie"] = $movie; echo json_encode($response); } else { $response["success"] = 0; $response["message"] = "No movie found"; echo json_encode($response); } } else { $response["success"] = 0; $response["message"] = "No movie found"; echo json_encode($response); }} else { $response["success"] = 0; $response["message"] = "Required field(s) is missing"; echo json_encode($response);}?>
{ "language": "en", "url": "https://stackoverflow.com/questions/33663670", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: QXmpp Client confirmation of successful authorization I'm wondering whether or not QXmpp client sends the query that confirms succeeded authorization on it's side, having received response from server about authorization response (?). As far as I am aware, QXmpp (that is XMPP as well) protocol based on TCP, so I suppose it ought to (each sides) confirm that received packet successfully.
{ "language": "en", "url": "https://stackoverflow.com/questions/17668862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Determining if TimeoutHandler has timed out I'm using http.TimeoutHandler to return a timeout to the client. This works fine, the problem is that I'm trying to call some code if the timeout has been triggered. I've looked through the docs and the source code, and I can't find a good way of doing this. The response just goes back to the client and I can't find a way to do any introspection on the context or the ResponseWriter etc. The calling code doesn't have access to the context, so I can't inspect it. The actual struct that the http.ResponseWriter is writing to within http.TimeoutHandler does put the information in that I need (it's the http.timeoutWriter), but I can't access it because the http.ResponseWriter interface doesn't support accessing those variables. I'm not overly experience in Go, but I can't help but think that I'm just going to have to re-implement my own http.TimeoutHandler because I can't see a way to do what I need to. Have I missed something? A: As you can see from the source for TimeoutHandler, it sets the context in the request to a context with timeout. That means, in your handler you can use the context to see if timeout happened: func MyHandler(w http.ResponseWriter,r *http.Request) { ... if r.Context().Err()==context.DeadlineExceeded { // Timeout happened } }
{ "language": "en", "url": "https://stackoverflow.com/questions/68693351", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Simple Cordova app with just Firebase plugin doesn't build or run on Android I made a very simple Cordova project, added the Android platform and the Firebase plugin. I can't get it to build or run. I get errors after errors. Here are the steps: * *cordova create hello com.example.hello Hello *cordova platform add android *cordova plugin add cordova-plugin-firebase Or, just download the code from: https://github.com/abelabbesnabi/cordova.git I have the following environment: * *Cordova 9.0.0 *Android Studio 3.5 Build #AI-191.8026.42.35.5791312, built on August 8, 2019 JRE: 1.8.0_202-release-1483-b03 amd64 JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o *Windows 10 10.0 Any idea please? A: change cordova plugin add cordova-plugin-firebase with cordova plugin add cordova-plugin-firebasex another option is after adding cordova-plugin-firebase add 2 another plugin cordova-android-play-services-gradle-release cordova-android-firebase-gradle-release A: Here are the steps to make it work: * *cordova platform remove android *cordova plugin remove cordova-plugin-firebase *cordova plugin add cordova-plugin-firebase-lib *cordova plugin add cordova-plugin-androidx *cordova plugin add cordova-plugin-androidx-adapter That's it!
{ "language": "en", "url": "https://stackoverflow.com/questions/57858830", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JavaScript: Why doesn't the background change to the user's selection (simple)? I have two radio buttons, one for the colour red and one for the colour blue. The user selects one and the selected colour appears as the background colour. That's what I want, and I've managed to get this to work when it comes to changing an image but for some reason my code doesn't work. When I select red, nothing happens, then I select blue and the page turns red. I must be doing something really stupid wrong. JS: function getColour() { var rad = document.forms["Form2"]["ColourRad"]; var i, x; for (i = 0; i < rad.length; i++) { if (rad[i].checked) { x = rad[i].value } } changeColour(x); } function changeColour(colour) { if (colour == "Blue") { document.body.style.backround = "Blue" } else if (colour == "Red") { document.body.style.background = "Red" } } HTML: <body> <form name="Form2">Do you prefer the colour red or blue? <input type="radio" name="ColourRad" onchange="getColour()" value="Blue" />Red <input type="radio" name="ColourRad" onchange="getColour()" value="Red" />Blue </form> </body> JSfiddle: http://jsfiddle.net/rwowf5j8/29/ A: I have fixed your script on http://jsfiddle.net/rwowf5j8/41/ Fixed and tested -- Issue was in the spelling in document.body.style.backround and there were some other tricks to do that easily so I fixed that.. <script> function getColour(value) { changeColour(value); } function changeColour(colour) { if (colour == "Blue") { document.body.style.background = "blue"; } else if (colour == "Red") { document.body.style.background = "Red"; } } </script> <body> <form name="Form2">Do you prefer the colour red or blue? <input type="radio" name="ColourRad" onchange="getColour('Red')" value="Blue" />Red <input type="radio" name="ColourRad" onchange="getColour('Blue')" value="Red" />Blue </form> </body> A: A Very Simple Method to do this.. Hope this helps you. document.onreadystatechange = function() { if(document.readyState == "complete") { var blue = document.getElementById("blue"); var red = document.getElementById("red") ; blue.onclick = function() { document.body.style.background = "blue"; } red.onclick = function() { document.body.style.background = "red"; } } } <body> <form name="Form2">Do you prefer the colour red or blue? <input id="red" type="radio" name="color" value="Blue" />Red <input id="blue" type="radio" name="" value="Red" />Blue </form> </body> A: Using your function to change the background color: function getColour() { var rad = document.forms["Form2"]["ColourRad"]; var i, x; for (i = 0; i < rad.length; i++) { if (rad[i].checked) { x = rad[i].value } } changeColour(x); } function changeColour(colour) { //if the value of the input is the color, you don't need //to check if the color is blue or red to set it document.body.style.background = colour } <form name="Form2">Do you prefer the colour red or blue? <!--in your code, the Red input is with Blue color --> <input type="radio" name="ColourRad" onchange="getColour()" value="Red" />Red <!--the same with the Blue input, where the Blue is Red --> <input type="radio" name="ColourRad" onchange="getColour()" value="Blue" />Blue </form> Also you can use this instead: <form name="Form2">Do you prefer the colour red or blue? <input type="radio" name="ColourRad" onchange="document.body.style.backgroundColor = this.value" value="red" />Red <input type="radio" name="ColourRad" onchange="document.body.style.backgroundColor=this.value" value="blue" />Blue </form> A: Here's another method. First, I wait for the document to finish loading. Next, I get a list of all elements that have the name 'colorRad' - this allows me to collect a list of all the radio buttons involved in setting the background color. Next, I attach an event listener that simply gets the value of the radio-button when its selected and finally, applies this to the background-color of the document body's inline style. Adding a new colour option is as simple as duplicating one of the radio buttons and changing the text displayed in it's label and by setting it's value - this label also allows you to select a radio button with the text, as opposed to limiting the target area to the size of the radio-button's circle only. Lastly, since the onRadBtnChanged function is attached to each radio-button's object, when the function is called, the this parameter refers to the radio-button object itself. This allows us to get info from the radio-button's value, and avoids having to handle each option specifically, as you have done in your changeColor function. Also, we save the wasted cpu cycles of iterating through the entire list each time, as you do in getColor - only one can be selected at a time - attaching the event-handler to the object itself means that we only need concern ourselves with the particular element that changed. (the change event only fires when the radio-button is selected. It does not fire when the selection of a different one causes one to be deselected - it only fires on selection, or 'checking') Example: <!doctype html> <html> <head> <script> window.addEventListener('load', onDocLoaded, false); function onDocLoaded(evt) { var colRadBtns = document.getElementsByName('colorRad'); var i, n = colRadBtns.length; for (i=0; i<n; i++) { colRadBtns[i].addEventListener('change', onRadBtnChanged, false); } } function onRadBtnChanged(evt) { document.body.style.backgroundColor = this.value; } </script> </head> <body> <label><input name='colorRad' value='red' type='radio'/>Red</label> <label><input name='colorRad' value='blue' type='radio'/>Blue</label> <label><input name='colorRad' value='yellow' type='radio'/>Yellow</label> <label><input name='colorRad' value='green' type='radio'/>Green</label> <label><input name='colorRad' value='orange' type='radio'/>Orange</label> </body> </html> A: The 2 things you needed to do were: * *Switch the values in the input tags because they didn't match up. *In the changeColour() function, you didn't fully spell out background in document.body.style.backround you missed the g. I also switched the script tags from the top to be at the bottom, right before the closing body tag just because I usually do it like that. Fixing those two small issues makes it run perfectly. A: Use this instead: document.body.style.backgroundColor A: basically the style property was wrong, it should be backgroundColor but you can get the same effect much simpler, for example: onchange="document.body.style.backgroundColor=this.value;"
{ "language": "en", "url": "https://stackoverflow.com/questions/29255496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Converting ActivityGroup app to use Fragments/FragmentGroup I have an app that I desperately need to convert from using the old ActivityGroup class to Fragments. I'm not sure how to go about it though. Below is a sample of the code I use now. Could anyone provide some insight into what steps I should take to start switching it over to use Fragments / FragmentManager instead? Main.java public class Main extends TabActivity implements OnTabChangeListener { public static TextView txtViewHeading; public static Button btnBack; public static ImageButton btnShare; public static Main mainActivity; public static Boolean isVisible = false; private GoogleCloudMessaging gcm; private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mainActivity = this; NotificationsManager.handleNotifications(this, NotificationSettings.SenderId, PushHandler.class); registerWithNotificationHubs(); //reference headings text & button for access from child activities txtViewHeading = (TextView) findViewById(R.id.txtViewHeading); btnBack = (Button) findViewById(R.id.btnBack); btnShare = (ImageButton) findViewById(R.id.btnShare); // Update the font for the heading and back button Typeface arialTypeface = Typeface.createFromAsset(getApplicationContext().getAssets(), "fonts/arial.ttf"); Typeface myriadTypeface = Typeface.createFromAsset(getApplicationContext().getAssets(), "fonts/myriad.ttf"); txtViewHeading.setTypeface(myriadTypeface); btnBack.setTypeface(arialTypeface); Resources res = getResources(); TabHost tabsNavigation = getTabHost(); // Set up the views for each tab - custom view used for Badge icon LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); // Set up my tabs...each one looks similar to this View statusTabView = inflater.inflate(R.layout.tab, null); ImageView statusTabIcon = (ImageView) statusTabView.findViewById(R.id.tabIcon); statusTabIcon.setImageResource(R.drawable.tab_first); TextView statusTabText = (TextView) statusTabView.findViewById(R.id.tabText); statusTabText.setText("Status"); statusTabText.setTypeface(arialTypeface); statusTabBadge = (TextView) statusTabView.findViewById(R.id.tabBadge); statusTabBadge.setTypeface(arialTypeface); tabsNavigation.addTab(tabsNavigation.newTabSpec(getResources().getString(R.string.main_tab_status)) .setIndicator(statusTabView) .setContent(new Intent(this, StatusGroupActivity.class) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))); //Set default tab to Status tabsNavigation.setCurrentTab(0); tabsNavigation.setOnTabChangedListener(this); } /* Set txtViewHeading text to selected tab text */ @Override public void onTabChanged(String tabId) { // TODO Auto-generated method stub txtViewHeading.setText(tabId); } /* Set code to execute when onDestroy method is called */ @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); } /* Set code to execute when onPause method is called */ @Override protected void onPause() { super.onPause(); isVisible = false; } /* Set code to execute when onResume method is called */ @Override protected void onResume() { super.onResume(); isVisible = true; } /* Set code to execute when onStop method is called */ @Override protected void onStop() { super.onStop(); isVisible = false; } /** * Check the device to make sure it has the Google Play Services APK. If * it doesn't, display a dialog that allows users to download the APK from * the Google Play Store or enable it in the device's system settings. */ private boolean checkPlayServices() { GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance(); int resultCode = apiAvailability.isGooglePlayServicesAvailable(this); if (resultCode != ConnectionResult.SUCCESS) { if (apiAvailability.isUserResolvableError(resultCode)) { apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST) .show(); } else { ToastNotify("This device is not supported by Google Play Services."); finish(); } return false; } return true; } public void ToastNotify(final String notificationMessage) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(Main.this, notificationMessage, Toast.LENGTH_LONG).show(); } }); } public void registerWithNotificationHubs() { if (checkPlayServices()) { // Start IntentService to register this application with GCM. Intent intent = new Intent(this, RegistrationIntentService.class); startService(intent); } } } TabGroupActivity.java public class TabGroupActivity extends ActivityGroup { private ArrayList<String> mIdList; Button btnBack; ImageButton btnShare; TextView txtViewHeading; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); btnBack = Main.btnBack; btnShare = Main.btnShare; txtViewHeading = Main.txtViewHeading; btnBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); if (mIdList == null) mIdList = new ArrayList<String>(); } /** * This is called when a child activity of this one calls its finish method. * This implementation calls {@link LocalActivityManager#destroyActivity} on the child activity * and starts the previous activity. * If the last child activity just called finish(),this activity (the parent), * calls finish to finish the entire group. */ @Override public void finishFromChild(Activity child) { try { btnShare.setVisibility(View.GONE); LocalActivityManager manager = getLocalActivityManager(); int index = mIdList.size()-1; if (index < 1) { finish(); return; } manager.destroyActivity(mIdList.get(index), true); mIdList.remove(index); index--; String lastId = mIdList.get(index); Intent lastIntent = manager.getActivity(lastId).getIntent(); Window newWindow = manager.startActivity(lastId, lastIntent); setContentView(newWindow.getDecorView()); //Set Heading text to current Id txtViewHeading.setText(getActivityHeading(lastId)); //Set Back button text to previous Id if applicable btnBack.setVisibility(View.VISIBLE); //Back button String backId = ""; if(mIdList.size() > 1) { backId = mIdList.get(mIdList.size()-2); btnBack.setVisibility(View.VISIBLE); btnBack.setText(getActivityHeading(backId)); txtViewHeading.setPadding(10,0,0,0); } else { btnBack.setVisibility(View.GONE); txtViewHeading.setPadding(0,0,0,0); } } catch(Exception e) { e.printStackTrace(); } } /** * Starts an Activity as a child Activity to this. * @param Id Unique identifier of the activity to be started. * @param intent The Intent describing the activity to be started. */ public void startChildActivity(String Id, Intent intent) { try { btnShare.setVisibility(View.GONE); Window window = getLocalActivityManager().startActivity(Id,intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)); if (window != null) { mIdList.add(Id); setContentView(window.getDecorView()); txtViewHeading.setText(getActivityHeading(Id)); //Back button String backId = ""; if(mIdList.size() > 1) { backId = mIdList.get(mIdList.size()-2); btnBack.setVisibility(View.VISIBLE); btnBack.setText(backId); txtViewHeading.setPadding(5,0,0,0); } else { btnBack.setVisibility(View.GONE); txtViewHeading.setPadding(0,0,0,0); } } } catch(Exception e) { e.printStackTrace(); } } /** * The primary purpose is to prevent systems before android.os.Build.VERSION_CODES.ECLAIR * from calling their default KeyEvent.KEYCODE_BACK during onKeyDown. */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { //preventing default return true; } return super.onKeyDown(keyCode, event); } /** * Overrides the default implementation for KeyEvent.KEYCODE_BACK * so that all systems call onBackPressed(). */ @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { onBackPressed(); return true; } return super.onKeyUp(keyCode, event); } /** * If a Child Activity handles KeyEvent.KEYCODE_BACK. * Simply override and add this method. */ @Override public void onBackPressed () { try { btnShare.setVisibility(View.GONE); int length = mIdList.size(); if ( length > 1) { Activity current = getLocalActivityManager().getActivity(mIdList.get(length-1)); current.finish(); } } catch(Exception e) { e.printStackTrace(); } } /** * Get the correct heading text and language based on activity id */ public String getActivityHeading(String id) { // method that returns the TEXT for my main heading TextView based on the activity we're on... } } StatusGroupActivity public class StatusGroupActivity extends TabGroupActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); startChildActivity("Status", new Intent(this,Status.class)); } } ... so basically when my app loads, I get my tabs at the bottom, my header at the top, and the "tab content" in the middle. In my Status activity, I can load another activity from it by using ... Intent intent = new Intent(getParent(), SomeOtherActivity.class) TabGroupActivity parentActivity = (TabGroupActivity)getParent(); parentActivity.startChildActivity("Some Other Activity", intent); ... and it loads the SomeOtherActivity activity into the content area. Hitting back takes me back to the Status screen. Any pointers, examples and assistance with converting this over to use Fragments is so greatly appreciated. I will gladly donate 500 of my rep. points for a full example. main.xml (Main Activity Layout file) <?xml version="1.0" encoding="utf-8"?> <android.support.v4.app.FragmentTabHost xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@android:id/tabhost" android:layout_width="match_parent" android:layout_height="match_parent" android:animateLayoutChanges="true" tools:ignore="ContentDescription,HardcodedText" > <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <ImageView android:id="@+id/imageSuccess" android:layout_width="wrap_content" android:layout_height="40dp" android:adjustViewBounds="true" android:scaleType="matrix" android:src="@drawable/bg_navbar_blank" /> <com.myproject.android.BgButtonStyle android:id="@+id/btnBack" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="5dp" android:layout_marginTop="0dp" android:background="@drawable/back_button" android:text="" android:textColor="@color/White" android:textSize="12sp" android:visibility="visible" android:layout_alignParentLeft="true" android:layout_centerVertical="true" android:padding="5dp"/> <ImageButton android:id="@+id/btnShare" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:layout_marginRight="15dp" android:background="@null" android:src="@drawable/icon_share" android:visibility="visible" android:adjustViewBounds="false" android:scaleType="fitXY"/> <com.myproject.android.AutoResizeTextView android:id="@+id/txtViewHeading" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center_horizontal" android:paddingLeft="5dp" android:text="Status" android:textAppearance="?android:attr/textAppearanceLarge" android:textSize="28sp" android:textStyle="bold" android:paddingRight="5dp" android:layout_toEndOf="@id/btnBack" android:layout_toStartOf="@id/btnShare" android:layout_centerVertical="true" android:lines="1"/> </RelativeLayout> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" > </FrameLayout> <TabWidget android:id="@android:id/tabs" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="-4dp" android:layout_weight="0" android:background="@drawable/bg_tabs"> </TabWidget> </LinearLayout> </android.support.v4.app.FragmentTabHost> In my current TabGroupActivity class, in the finishFromChild and startChildActivity methods, I am able to call setText on the txtViewHeading TextView element in my main activity layout. Which is the current activities "title". If there is more than 1 activity in the group, the back button shows the previous title. How can I duplicate this in the examples below? The main activity layout there is much different than mine. A: Add these dependencies to your project: compile 'com.android.support:appcompat-v7:23.4.0' compile 'com.android.support:design:23.4.0' First change your Main activity must be extended from AppCompatActivity. Than change your main activity's layout like below: <?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/coordinatorlayout" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:context=".Main"> <android.support.design.widget.AppBarLayout android:id="@+id/appbarlayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"> <include layout="@layout/toolbar_default" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_scrollFlags="scroll|enterAlways" /> <android.support.design.widget.TabLayout android:id="@+id/tabs" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" app:tabGravity="fill" app:tabMaxWidth="0dp" app:tabIndicatorHeight="4dp" app:tabMode="fixed" app:tabIndicatorColor="@android:color/white" android:background="@color/AppPrimary"/> </android.support.design.widget.AppBarLayout> <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context=".dashboard.DashboardActivity" tools:showIn="@layout/activity_dashboard"> <android.support.v4.view.ViewPager android:id="@+id/viewpager_main" android:layout_width="match_parent" android:layout_height="match_parent"/> </RelativeLayout> </android.support.design.widget.CoordinatorLayout> And here's a toolbar layout example. You can customize however you want. <?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/toolbar_main" style="@style/Widget.MyApp.Toolbar.Solid" android:layout_width="match_parent" android:layout_height="@dimen/abc_action_bar_default_height_material" android:background="@color/AppPrimary" app:contentInsetEnd="16dp" app:contentInsetStart="16dp" /> Than you need to create fragments which you'll use in your tabs instead of activities which you use for tabs. In this case this'll your Status Activity if i'm not wrong. Define a StatusFragment like below: public class StatusFragment extends Fragment { @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // this is your Status fragment. You can do stuff which you did in Status activity } } Than you need to define a tabs adapter which you'll bind with your tabs and convert your TabHost to Fragment/Fragment manager type. Titles string array contains strings which you'll show in your tabs indicator. Such as "Status, My Assume Tab, My awesome tab 2 public class DashboardTabsAdapter extends FragmentPagerAdapter { private String[] mTitles; public DashboardTabsAdapter(FragmentManager fm, String[] titles) { super(fm); this.mTitles = titles; } @Override public Fragment getItem(int position) { return new StatusFragment(); // You can define some other fragments if you want to do different types of operations in your tabs and switch this position and return that kind of fragment. } @Override public int getCount() { return mTitles.length; } @Override public CharSequence getPageTitle(int position) { return mTitles[position]; } } And finally in your Main activity find your view pager, tabs create a new adapter and bind them. final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); final DashboardTabsAdapter dashboardTabsAdapter = new DashboardTabsAdapter(getSupportFragmentManager(), getResources().getStringArray(R.array.tab_titles)); mViewPagerMain = (ViewPager) findViewById(R.id.viewpager_main); mViewPagerMain.setOffscreenPageLimit(3); mViewPagerMain.setAdapter(dashboardTabsAdapter); tabLayout.setupWithViewPager(mViewPagerMain); Edit: You'll no longer need TabHost and TabActivity any more. Your tab grup activity will be your ViewPager which handles screen changes and lifecycle of fragments inside. If you need to get this activity from fragments you can use getActivity() method and cast it to your activity and use it's public methods. A: First you need to add Design Support Library and AppCompatLibrary into your Project Add this code into your app gradle compile 'com.android.support:appcompat-v7:24.0.0' compile 'com.android.support:design:24.0.0' layout for activity_main.xml (like main.xml in your code) <?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/main_content" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true"> <android.support.design.widget.AppBarLayout android:id="@+id/appbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingTop="@dimen/appbar_padding_top" android:theme="@style/AppTheme.AppBarOverlay"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:layout_scrollFlags="scroll|enterAlways" app:popupTheme="@style/AppTheme.PopupOverlay"> </android.support.v7.widget.Toolbar> <android.support.design.widget.TabLayout android:id="@+id/tabs" android:layout_width="match_parent" android:layout_height="wrap_content" /> </android.support.design.widget.AppBarLayout> <android.support.v4.view.ViewPager android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" /> </android.support.design.widget.CoordinatorLayout> In above layout ViewPager will provides horizontal layout to display tabs. You can display more screens in a single screen using tabs. You can swipe the tabs quickly as you can. Root Fragment <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/root_frame" > View for First Fragment <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:background="#ff0" android:layout_height="match_parent" > <TextView android:id="@+id/tv" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_horizontal" android:text="@string/first_fragment" /> <Button android:id="@+id/btn" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_width="wrap_content" android:text="@string/to_second_fragment"/> </RelativeLayout> View for Second and Individual(s) Fragment. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin"> <TextView android:id="@+id/section_label" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout> Now add a MainActivity(like Main Activity in yours code) under which all this thing will handle. public class MainActivity extends AppCompatActivity { private TabGroupAdapter mTabGroupAdapter; private ViewPager mViewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); ArrayList<Fragment> fragmentList = new ArrayList<Fragment>(); fragmentList.add(new RootFragment()); fragmentList.add(new IndividualFragment1()); fragmentList.add(new IndividualFragment2()); ArrayList<String> name = new ArrayList<String>() { { add("Root Tab"); add("Second Tab"); add("Third Tab"); } }; // Create the adapter that will return a fragment for each of the three // primary sections of the activity. mTabGroupAdapter = new TabGroupAdapter(getSupportFragmentManager(),name, fragmentList,); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.container); mViewPager.setAdapter(mTabGroupAdapter); TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(mViewPager); } } There is one FragmentPagerAdapter defined as mTabGroupAdapter inside MainActivity that will add a different tabs inside a single Layout. First we bind the mTabGroupAdapter to mViewPager. TabLayout will act like a TabHost under which Tab will be added by FragmentPagerAdapter. mViewPager is bind to the Tablayout. Under MainActivity TabLayout will display the name of Tabs. TabGroupAdapter public class TabGroupAdapter extends FragmentPagerAdapter { private ArrayList<Fragment> fragmentList = new ArrayList<Fragment>(); private ArrayList<String> fragment_name; public TabGroupAdapter(FragmentManager fm, ArrayList<String> name, ArrayList<Fragment> list) { super(fm); this.fragmentList = list; this.fragment_name = name; } @Override public Fragment getItem(int position) { return fragmentList.get(position); } @Override public int getCount() { return fragmentList.size(); } @Override public CharSequence getPageTitle(int position) { return fragment_name.get(position); } } In TabGroupAdapter you would pass a List of fragments(or single fragment) and list of fragments name(or single name) as arguments in the Constructor. IndividualFragment(s) will act like a individual Tab instead of Activity. RootFragment will be acting as a container for other fragments( First Fragment and Second Fragment) Root Fragment public class RootFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.root_fragment, container, false); FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.root_frame, new FirstFragment()); fragmentTransaction.commit(); return view; } } First Fragment public class FirstFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.first_fragment, container, false); Button btn = (Button) view.findViewById(R.id.btn); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); //use the "root frame" defined in //"root_fragment.xml" as the reference to replace fragment fragmentTransaction.replace(R.id.root_frame, new SecondFragment()); /* * allow to add the fragment * to the stack and return to it later, by pressing back */ fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); } }); } } Second Fragment public class SecondFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); return rootView; } } Individual(s) Fragment public class IndividualFragment1 extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); return rootView; } } public class IndividualFragment2 extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); return rootView; } } In OnCreateView method you would set a layout of a Tab . You won't have to use the getTabHost() method. Let me know if you persist any problem. Whenever you want to dynamically change or update the Tabs in View Pager just add or remove item from fragmentList and call this method mTabGroupAdapter.notifyDataSetChanged(); inside MainActivity.
{ "language": "en", "url": "https://stackoverflow.com/questions/38081842", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: MSAL for Android fails performing B2C login I'm using 0.2.2 version of Microsoft Authentication Library (MSAL) Preview for Android library to perform Azure AD B2C login in my native Android app. The library opens the browser to start login process. Afterwards I log in successfully and it navigates me back to the app. Inside AuthenticationCallback, I get the following error: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'long java.lang.Long.longValue()' on a null object reference at com.microsoft.identity.common.internal.cache.MicrosoftStsAccountCredentialAdapter.getExpiresOn(MicrosoftStsAccountCredentialAdapter.java:231) at com.microsoft.identity.common.internal.cache.MicrosoftStsAccountCredentialAdapter.createAccessToken(MicrosoftStsAccountCredentialAdapter.java:78) at com.microsoft.identity.common.internal.cache.MicrosoftStsAccountCredentialAdapter.createAccessToken(MicrosoftStsAccountCredentialAdapter.java:45) at com.microsoft.identity.common.internal.cache.MsalOAuth2TokenCache.save(MsalOAuth2TokenCache.java:112) ... When I debug and trace the library code, it seems like the library gets the expires_in field from TokenResponse as null. Is there any idea how it can be happening? And also here is my raw config file for the library: { "client_id" : "XXX", "authorization_user_agent" : "DEFAULT", "redirect_uri" : "msalXXX://auth", "authorities" : [ { "type": "B2C", "authority_url": "https://TTT.b2clogin.com/tfp/TTT.onmicrosoft.com/B2C_1_susi/" } ] } where XXX is client id, and TTT is tenant name. I also enabled logging for the library. Here it's after it gets back from browser: D: [2019-04-09 11:22:44 - {"thread_id":"2","correlation_id":"b843f0f5-d446-480c-9c63-cfcc9ad74e51"}] Completing acquire token... Android 28 D: [2019-04-09 11:22:44 - {"thread_id":"2","correlation_id":"b843f0f5-d446-480c-9c63-cfcc9ad74e51"}] Auth code is successfully returned from webview redirect. Android 28 D: [2019-04-09 11:22:44 - {"thread_id":"360","correlation_id":"270f3416-1332-42e4-8672-c8ae748c0006"}] Network status: connected Android 28 D: [2019-04-09 11:22:44 - {"thread_id":"360","correlation_id":"270f3416-1332-42e4-8672-c8ae748c0006"}] Creating TokenRequest... Android 28 D: [2019-04-09 11:22:44 - {"thread_id":"360","correlation_id":"270f3416-1332-42e4-8672-c8ae748c0006"}] Requesting token... Android 28 D: [2019-04-09 11:22:44 - {"thread_id":"360","correlation_id":"270f3416-1332-42e4-8672-c8ae748c0006"}] Performing token request... Android 28 D: [2019-04-09 11:22:45 - {"thread_id":"360","correlation_id":"270f3416-1332-42e4-8672-c8ae748c0006"}] Getting TokenResult from HttpResponse... Android 28 D: [2019-04-09 11:22:45 - {"thread_id":"360","correlation_id":"270f3416-1332-42e4-8672-c8ae748c0006"}] Init: TokenResult Android 28 D: [2019-04-09 11:22:45 - {"thread_id":"360","correlation_id":"270f3416-1332-42e4-8672-c8ae748c0006"}] Saving tokens... Android 28 D: [2019-04-09 11:22:45 - {"thread_id":"360","correlation_id":"270f3416-1332-42e4-8672-c8ae748c0006"}] Creating Account Android 28 D: [2019-04-09 11:22:45 - {"thread_id":"360","correlation_id":"270f3416-1332-42e4-8672-c8ae748c0006"}] Creating account from TokenResponse... Android 28 D: [2019-04-09 11:22:45 - {"thread_id":"360","correlation_id":"270f3416-1332-42e4-8672-c8ae748c0006"}] Init: MicrosoftAccount Android 28 D: [2019-04-09 11:22:45 - {"thread_id":"360","correlation_id":"270f3416-1332-42e4-8672-c8ae748c0006"}] Using Subject as uniqueId Android 28 D: [2019-04-09 11:22:45 - {"thread_id":"360","correlation_id":"270f3416-1332-42e4-8672-c8ae748c0006"}] The preferred username is not returned from the IdToken. Android 28 D: [2019-04-09 11:22:45 - {"thread_id":"360","correlation_id":"270f3416-1332-42e4-8672-c8ae748c0006"}] realm is not returned from server. Use utid as realm. Android 28 D: [2019-04-09 11:22:45 - {"thread_id":"360","correlation_id":"270f3416-1332-42e4-8672-c8ae748c0006"}] Init: MicrosoftStsAccount Android 28 D: [2019-04-09 11:22:45 - {"thread_id":"360","correlation_id":"270f3416-1332-42e4-8672-c8ae748c0006"}] alternative_account_id: null Android 28 D: [2019-04-09 11:22:45 - {"thread_id":"360","correlation_id":"270f3416-1332-42e4-8672-c8ae748c0006"}] alternative_account_id was null. Android 28 D: [2019-04-09 11:22:45 - {"thread_id":"360","correlation_id":"270f3416-1332-42e4-8672-c8ae748c0006"}] Avatar URL: null Android 28 D: [2019-04-09 11:22:45 - {"thread_id":"360","correlation_id":"270f3416-1332-42e4-8672-c8ae748c0006"}] Avatar URL was null. Android 28 D: [2019-04-09 11:22:45 - {"thread_id":"360","correlation_id":"270f3416-1332-42e4-8672-c8ae748c0006"}] Interactive request failed with Exception Android 28 java.lang.NullPointerException: Attempt to invoke virtual method 'long java.lang.Long.longValue()' on a null object reference at com.microsoft.identity.common.internal.cache.MicrosoftStsAccountCredentialAdapter.getExpiresOn(MicrosoftStsAccountCredentialAdapter.java:231) at com.microsoft.identity.common.internal.cache.MicrosoftStsAccountCredentialAdapter.createAccessToken(MicrosoftStsAccountCredentialAdapter.java:78) at com.microsoft.identity.common.internal.cache.MicrosoftStsAccountCredentialAdapter.createAccessToken(MicrosoftStsAccountCredentialAdapter.java:45) ... A: The browser tab should close automatically when the auth succeeds and Azure AD B2C calls back to the app. It's possible that you might mis-configured the app or their is a bug in the specific browser you're using (we've seen this before on smaller browsers, so the data could help). With respect to Azure AD B2C, I'd highly discourage using WebViews as Google and other identity providers explicitly disable WebView support. I'd recommend you to enable logging and share them with me and file an issue on the library if needed(https://github.com/AzureAD/microsoft-authentication-library-for-android/wiki).
{ "language": "en", "url": "https://stackoverflow.com/questions/55576359", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Remove # from value (jQuery) var current = $(this).attr('href'); alert(current); shows the value with '#' eg '#target' instead of just 'target', what do I modify in the code? Thanks A: var current = $(this).attr('href').slice(1); alert(current); A: I assume you're dealing with a <a> element? this.hash.substring(1); // yes, it's that simple... A: As easy as this, just use replace: var current = $(this).attr('href').replace('#','');
{ "language": "en", "url": "https://stackoverflow.com/questions/3156077", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I deserialize a struct that has a generic type that implements a trait? I have difficulty understanding how to deal with polymorphic objects. I have JSON input which I want to deserialize as a struct which can hold another struct of type A or B. Each one implements the G trait: pub trait Action {} impl Action for SendMessage {} #[derive(Debug, Deserialize, Serialize)] struct SendMessage { msg: String, } impl Action for SendEmail {} struct SendEmail { recipient: String, msg: String, } #[derive(Debug, Deserialize, Serialize)] struct ApiResponse<T: Action> { status: String, data: T, } fn main() { let payload = r#" { "status": "200", "data": { "msg": "toto" } } "#; let test: ApiResponse = serde_json::from_str(payload).unwrap(); // Return Error let test: ApiResponse<SendEmail> = serde_json::from_str(payload).unwrap(); // Is ok let test: ApiResponse<SendMessage> = serde_json::from_str(payload).unwrap(); // Return Error } What is the idiomatic way to store the result in my test variable if I don't know the content of my payload?
{ "language": "en", "url": "https://stackoverflow.com/questions/59816071", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Win2D: Create a round image I'm developing a C#/UWP app and I'm wondering if there is a simple way to create/draw a round image from a square image in Win2D? In XAML I could simply do this: <Ellipse> <Ellipse.Fill> <ImageBrush ImageSource="myImage.jpg" Stretch="Uniform"/> </Ellipse.Fill> </Ellipse> How can I get the same result using Win2D ?
{ "language": "en", "url": "https://stackoverflow.com/questions/41078923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to force a query to get the results with only all the rows selected? Well, it's a very simple question, so I hope you could help me. I've two tables with this structure: -- ----------------------------------------------------- -- Table `mydb`.`product` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `mydb`.`products` ( `id_product` INT NOT NULL , `name` VARCHAR(45) NOT NULL , PRIMARY KEY (`id_product`) ) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `mydb`.`features` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `mydb`.`features` ( `id_feature` INT NOT NULL , `id_product` INT NOT NULL , `description` VARCHAR(45) NOT NULL , PRIMARY KEY (`id_feature`) , INDEX `fk_table2_table1` (`id_product` ASC) , CONSTRAINT `fk_table2_table1` FOREIGN KEY (`id_product` ) REFERENCES `mydb`.`products` (`id_product` ) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB; This query returns all the features of the product 5: select descripcion from features where id_product = 5; which are: expensive strong tall Ok, now I want to get all the names of the table 'products' that have only all these features. I tried something like this: select p.name from products p, features f where p.id_product = f.id_product and f.id_feature in (select id_feature from features where description in (select description from features where id_product = 5); But it also gives me back the products which have less or more features than the three that I'm looking for... I hope I was clear. Thanks in advance. A: I think what you're looking for are those products that have all three of those features that don't have any others. If so, something like this should work: SELECT P.Id_Product, P.Name FROM Products P JOIN Features F ON P.id_product = F.id_product JOIN Features F2 ON P.id_product = F2.id_product WHERE F.id_feature IN (SELECT id_feature FROM Features WHERE id_product = 5) GROUP BY P.Id_Product, P.Name HAVING COUNT(DISTINCT F2.id_Feature) = 3 And here is a condensed Fiddle to demonstrate. A: I think you want to use a join statement- i didn't check my query for exact syntax but you get the idea: SELECT * FROM `mydb`.`products` JOIN mydb.features ON mydb.features.id_product = mydb.products.id_product WHERE `mydb`.`features`.`description` = 'strong' OR `mydb`.`features`.`description` = 'tall' OR `mydb`.`features`.`description` = 'expensive';
{ "language": "en", "url": "https://stackoverflow.com/questions/14844626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use Observable.FromEvent with SignalR Close event SignalR Close event has the following definition: public event Func<Exception, Task> Closed; How can I use this with the Rx method Observable.FromEvent? Observable.FromEvent definition looks to return an Action instead of a Func for all overloads
{ "language": "en", "url": "https://stackoverflow.com/questions/68302120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why doesn't i get input as a string for program below Scanner keyboard = new Scanner(System.in); //prompt the user input for a number int a = keyboard.nextInt(); //prompt the user input for a string String str = keyboard.nextLine(); Get Input for String A: The .nextLine() is getting the '\n' character trailing the integer. Fix this by adding keyboard.nextLine() after the .nextInt(). As follows: Scanner keyboard = new Scanner(System.in); // prompt the user input for a number int a = keyboard.nextInt(); // prompt the user input for a string keyboard.nextLine(); // This captures the '\n' character trailing the integer String str = keyboard.nextLine();
{ "language": "en", "url": "https://stackoverflow.com/questions/33949053", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Show weights in JgraphT I have implemented this Graph: ListenableDirectedWeightedGraph<String, MyWeightedEdge> g = new ListenableDirectedWeightedGraph<String, MyWeightedEdge>(MyWeightedEdge.class); In order to show what the class name says; a simple listenable directed weighted graph. I want to change the label of the edges and instead of the format return "(" + source + " : " + target + ")"; I want it to show the weight of the edge. I realise that all actions on the nodes, e.g. the getEdgesWeight() method, are delegated from the graph and not the edge. How can I show the weight of the edge? Do I have to pass in the Graph to the edge somehow? Any help is appreciated. A: I assume that the class MyWeightedEdge already contains a method such as public void setWeight(double weight) If this is indeed the case, then what you need to do is: Derive your own subclass from ListenableDirectedWeightedGraph (e.g., ListenableDirectedWeightedGraph). I would add both constructor versions, delegating to "super" to ensure compatibility with the original class. Create the graph as in your question, but using the new class ListenableDirectedWeightedGraph g = new CustomListenableDirectedWeightedGraph( MyWeightedEdge.class); Override the method setEdgeWeight as follows: public void setEdgeWeight(E e, double weight) { super.setEdgeWeight(e, weight); ((MyWeightedEdge)e).setWeight(weight); } And, last but not least, override the toString method of the class MyWeightedEdge to return the label you want the edge to have (presumably including the weight, which is now available to it). I hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/134510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Get data from table which only have 2 status in a day I have to select data which only have 2 status in a day. example: | Date | Name | Status | |:--------:|:----:|:------:| | 20200222 | BBB | 1 | | 20200222 | BBB | 2 | | 20200223 | AAA | 1 | | 20200224 | AAA | 2 | | 20200225 | AAA | 1 | | 20200225 | BBB | 1 | | 20200225 | AAA | 2 | I need to get the Name which only have status 1 and 2 in one date. A: This can be a solution SELECT Date, Name FROM SampleData GROUP BY Date, Name HAVING MIN(Status) = 1 AND MAX(Status) = 2 A: Here is my solution: declare @test table (Date varchar(8), Name varchar(3), status int) insert @test values ('20200222','BBB',1), ('20200222','BBB',2), ('20200223','AAA',1), ('20200224','AAA',2), ('20200225','AAA',1), ('20200225','BBB',1), ('20200225','CCC',2), ('20200225','CCC',4), ('20200225','DDD',3), ('20200225','AAA',2) select distinct date, name, status from @test where status in (1,2) Edited: This is NOT the solution. Sherkan's is, I did not understand well your first question.
{ "language": "en", "url": "https://stackoverflow.com/questions/60389743", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: WP get_results query not working? I've to fetch the records on the basis of some text. For this i am using LIKE query in get_results. But when I run this query into SQL it works fine but into the code it does not. I am not able to find out where the mistake is. Kindly suggest me the right way to do this. here is my code. $searchTag = $_REQUEST["s"]; <?php if (have_posts()) : while (have_posts()) : the_post(); $current++; ?> here is the problem occurring (the query gives empty results[may be /it doesnot display any thing] ) <?php $post_id = $wpdb->get_results( "SELECT post_id FROM wp_postmeta WHERE meta_value LIKE '%,".$searchTag.",%'OR meta_value LIKE '%,".$searchTag."' OR meta_value LIKE '".$searchTag.",%' OR meta_value='".$searchTag."' " ); A: Please use global $wpdb; before your query. A: I've replicated your issue, you should be using the prefix object. $post_id = $wpdb->get_results( "SELECT post_id FROM " . $wpdb->prefix . "postmeta WHERE meta_value LIKE '%,".$searchTag.",%'OR meta_value LIKE '%,".$searchTag."' OR meta_value LIKE '".$searchTag.",%' OR meta_value='".$searchTag."' " );
{ "language": "en", "url": "https://stackoverflow.com/questions/27421880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Freshly cloned git repositories displays there are local changes I can't quite get my head around, why a freshly cloned git repository shows that there are changes not stagged for commit. Here is a short example: [dpetrov@macbook-pro ~/work]$ git clone /tmp/git/pollers.git pollers Cloning into 'pollers'... done. [dpetrov@macbook-pro ~/work]$ cd pollers/ [dpetrov@macbook-pro ~/work/pollers (master)]$ git status On branch master Your branch is up-to-date with 'origin/master'. nothing to commit, working tree clean [dpetrov@macbook-pro ~/work/pollers (master)]$ git checkout pollers-1.0 gBranch pollers-1.0 set up to track remote branch pollers-1.0 from origin. Switched to a new branch 'pollers-1.0' i [dpetrov@macbook-pro ~/work/pollers (pollers-1.0)]$ git status On branch pollers-1.0 Your branch is up-to-date with 'origin/pollers-1.0'. Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git checkout -- <file>..." to discard changes in working directory) modified: share/mibs/IANAifType-MIB.mib no changes added to commit (use "git add" and/or "git commit -a") [dpetrov@macbook-pro ~/work/pollers (pollers-1.0)]$ git diff share/mibs/IANAifType-MIB.mib diff --git a/share/mibs/IANAifType-MIB.mib b/share/mibs/IANAifType-MIB.mib old mode 100644 new mode 100755 index 3b4added..14da8028 --- a/share/mibs/IANAifType-MIB.mib +++ b/share/mibs/IANAifType-MIB.mib @@ -1,13 +1,11 @@ --- Extracted from http://www.iana.org/assignments/ianaiftype-mib --- - IANAifType-MIB DEFINITIONS ::= BEGIN +IANAifType-MIB DEFINITIONS ::= BEGIN^M IMPORTS MODULE-IDENTITY, mib-2 FROM SNMPv2-SMI TEXTUAL-CONVENTION FROM SNMPv2-TC; ianaifType MODULE-IDENTITY - LAST-UPDATED "200505270000Z" -- May 27, 2005 + LAST-UPDATED "200411220000Z" -- June 17, 2004^M ORGANIZATION "IANA" CONTACT-INFO " Internet Assigned Numbers Authority Any clues how to debug that and what might be causing it? Thanks so much. A: It was a case sensitivity issue in the file names : two different files, with only difference in casing in their names, were stored in git. When checking the differences, git would receive the "wrong" content for one of the two names.
{ "language": "en", "url": "https://stackoverflow.com/questions/48188433", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: 404 error although route exists in laravel 6 I have routes like this: Route::resource('admin/post', 'Admin\PostsController'); Route for edit post exists but I get 404 error. I list all routes php artisan r:l and it shows me the post.edit but it doesn't show me edit page. in web.php Route::resource('admin/post', 'Admin\PostsController'); in Admin\PostsController public function edit($id) { $post = Post::findOrFail($id); return view('backend.posts.edit', compact('post')); } in index.php <a href="{{route('post.edit', $post->id)}}" class="btn btn-sx btn-primary"> <i class="fa fa-edit"></i> </a> this is the error of edit page
{ "language": "en", "url": "https://stackoverflow.com/questions/60812872", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Timing algorithm: clock() vs time() in C++ For timing an algorithm (approximately in ms), which of these two approaches is better: clock_t start = clock(); algorithm(); clock_t end = clock(); double time = (double) (end-start) / CLOCKS_PER_SEC * 1000.0; Or, time_t start = time(0); algorithm(); time_t end = time(0); double time = difftime(end, start) * 1000.0; Also, from some discussion in the C++ channel at Freenode, I know clock has a very bad resolution, so the timing will be zero for a (relatively) fast algorithm. But, which has better resolution time() or clock()? Or is it the same? A: <chrono> would be a better library if you're using C++11. #include <iostream> #include <chrono> #include <thread> void f() { std::this_thread::sleep_for(std::chrono::seconds(1)); } int main() { auto t1 = std::chrono::high_resolution_clock::now(); f(); auto t2 = std::chrono::high_resolution_clock::now(); std::cout << "f() took " << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count() << " milliseconds\n"; } Example taken from here. A: It depends what you want: time measures the real time while clock measures the processing time taken by the current process. If your process sleeps for any appreciable amount of time, or the system is busy with other processes, the two will be very different. http://en.cppreference.com/w/cpp/chrono/c/clock A: The time_t structure is probably going to be an integer, which means it will have a resolution of second. The first piece of code: It will only count the time that the CPU was doing something, so when you do sleep(), it will not count anything. It can be bypassed by counting the time you sleep(), but it will probably start to drift after a while. The second piece: Only resolution of seconds, not so great if you need sub-second time readings. For time readings with the best resolution you can get, you should do something like this: double getUnixTime(void) { struct timespec tv; if(clock_gettime(CLOCK_REALTIME, &tv) != 0) return 0; return (tv.tv_sec + (tv.tv_nsec / 1000000000.0)); } double start_time = getUnixTime(); double stop_time, difference; doYourStuff(); stop_time = getUnixTime(); difference = stop_time - start_time; On most systems it's resolution will be down to few microseconds, but it can vary with different CPUs, and probably even major kernel versions. A: <chrono> is the best. Visual Studio 2013 provides this feature. Personally, I have tried all the methods mentioned above. I strongly recommend you use the <chrono> library. It can track the wall time and at the same time have a good resolution (much less than a second). A: How about gettimeofday()? When it is called it updates two structs (timeval and timezone), with timing information. Usually, passing a timeval struct is enough and the timezone struct can be set to NULL. The updated timeval struct will have two members tv_sec and tv_usec. tv_sec is the number of seconds since 00:00:00, January 1, 1970 (Unix Epoch) and tv_usec is additional number of microseconds w.r.t. tv_sec. Thus, one can get time expressed in very good resolution. It can be used as follows: #include <time.h> struct timeval start_time; double mtime, seconds, useconds; gettimeofday(&start_time, NULL); //timeval is usually enough int seconds = start_time.tv_sec; //time in seconds int useconds = start_time.tv_usec; //further time in microseconds int desired_time = seconds * 1000000 + useconds; //time in microseconds
{ "language": "en", "url": "https://stackoverflow.com/questions/12231166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "66" }
Q: retrieve data after indexing a mysql table Even after indexing a mysql table,in solr am not able to retrieve data after querying like http://localhost:8983/solr/select/?q=slno:5 My data-config.xml file is: <?xml version="1.0" encoding="UTF-8"?> <dataConfig> <dataSource type="JdbcDataSource" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/lbs" user="user" password="password"/> <document name="lbs"> <entity name="radar_places" query="select * from radar_places" deltaImportQuery="SELECT * FROM radar_places WHERE slno='${dataimporter.delta.slno}'" deltaQuery="SELECT slno FROM radar_places WHERE modified > '${dataimporter.last_index_time}'" > <field column="slno" name="slno" /> <field column="place_id" name="place_id" /> <field column="name" name="name" /> <field column="geo_rss_point" name="geo_rss_point" /> <field column="url" name="url" /> <field column="location_id" name="location_id" /> <field column="time" name="time" /> </entity> </document> </dataConfig> In the browser I had used http://localhost:8983/solr/dataimport?command=full-import Later when I checked status of command http://localhost:8983/solr/dataimport/ I got this <response> − <lst name="responseHeader"> <int name="status">0</int> <int name="QTime">1</int> </lst> − <lst name="initArgs"> − <lst name="defaults"> <str name="config">data-config.xml</str> </lst> </lst> <str name="status">idle</str> <str name="importResponse"/> − <lst name="statusMessages"> <str name="Total Requests made to DataSource">1</str> <str name="Total Rows Fetched">1151</str> <str name="Total Documents Skipped">0</str> <str name="Full Dump Started">2010-02-21 07:53:14</str> − <str name=""> Indexing completed. Added/Updated: 0 documents. Deleted 0 documents. </str> <str name="Committed">2010-02-21 07:53:24</str> <str name="Optimized">2010-02-21 07:53:24</str> <str name="Total Documents Processed">0</str> <str name="Total Documents Failed">1151</str> <str name="Time taken ">0:0:10.56</str> </lst> − <str name="WARNING"> This response format is experimental. It is likely to change in the future. </str> </response> 1)Is this has to do anything with <str name="Total Documents Failed">1151</str> Am not able to figure out whats going wrong. A: Are you sure that the data import configuration matches your Solr document schema?
{ "language": "en", "url": "https://stackoverflow.com/questions/2306510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: how to store xls report in public folder from sidekiq background jobs How to store xls report in public folder from sidekiq background jobs? right now its not saving the report in public folder , in views _report.xls.builder file from that file its getting data from controller and downloading. A: In your background job, make sure that the report is stored in the right folder. You can try something like: report_target = Rails.root.join('public/my_report.xls') report = ... File.open(report_target, 'wb') { |file| file << report.generate }
{ "language": "en", "url": "https://stackoverflow.com/questions/36467479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: pagination for div elements in javascript I'm trying to make pagination for div html elements using javascript. But I'm having some trouble making div elements hide/show on clicking the pagination buttons which i made using bootstrap. Below is my code. HTML code for div elements: <div id="page2" > <p>Lorem ipsum dolor sit amet.</p> </div><!--end div 1--> <div id="page3" > <p>Lorem ipsum dolor sit amet.</p> </div><!--end div 2--> <div id="page4" > <p>Lorem ipsum dolor sit amet.</p> </div><!--end div 3--> <div id="page5" > <p>Lorem ipsum dolor sit amet.</p> </div><!--end div 4--> Pagination code: <div class="container"> <div class="text-center"> <ul class="pagination pagination-lg"> <li><a href="" onclick="showPages('1')">1</a></li> <li><a href="" onclick="showPages('2')">2</a></li> <li><a href="" onclick="showPages('3')">3</a></li> <li><a href="" onclick="showPages('4')">4</a></li> <li><a href="" onclick="showPages('5')">5</a></li> </ul> </div> </div> Javascript: function showPages(id){ var totalNumberOfPages = 5; for(var i=1; i<=totalNumberOfPages; i++){ if (document.getElementById('page'+i)) { document.getElementById('page'+i).style.display='none'; } } if (document.getElementById('page'+id)) { document.getElementById('page'+id).style.display='block'; } }; What is wrong in my code?? A: Please check this JSFiddle I've modified this line: <a href="" onclick="showPages('2')">2</a> to this: <a href="#" onclick="showPages('2')">2</a>
{ "language": "en", "url": "https://stackoverflow.com/questions/45177519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Obtaining HTTP session from a webservice We have a web application built on a Tomcat 6/WebWork/Hibernate/SQL Server stack. One part of the web application is a network map built using the Flare toolkit (the predecessor to Flare was Prefuse). The network map data is retrieved via a webservice call, say getData(). This call is made by the Flare application to retrieve XML data it needs to display. The webservice itself has been developed using Apache CXF. I am trying to figure out how I can obtain the HTTP session within the method designated as a webservice. I need this because I need to maintain server side data across client (Flare application) webservice requests. Do I need to get the HTTP session using the basic servlet APIs (knowing that the CXF servlet is being used)? Or is there API support at the CXF level? The webservice itself runs within Tomcat 6. A: This is actually part of the JAX-WS spec. You can do @Resource WebServiceContext ctx; .... ctx.getMessageContext().get(MessageContext.SERVLET_REQUEST) to get the ServletRequest object from which you can do anything with the session or whatever. Note: by default, JAX-WS clients don't maintain the session cookie. You have to set them to maintain the session: ((BindingProvider)proxy).getRequestContext() .put(BindingProvider.SESSION_MAINTAIN_PROPERTY, "true");
{ "language": "en", "url": "https://stackoverflow.com/questions/1994948", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to add id (primary key) when insert a multi-dimensional php array into a mysql table? I created this mysql table: CREATE TABLE earthquakes ( id INT(20) AUTO_INCREMENT, idserial VARCHAR(30), milliseconds BIGINT, latitude FLOAT, longitude FLOAT, magnitude FLOAT, ipocentro FLOAT, source VARCHAR(4), region SMALLINT, PRIMARY KEY(id), INDEX indice_idserial(idserial), INDEX indice_milliseconds(milliseconds), INDEX indice_lat_lng(latitude,longitude), INDEX indice_magnitude(magnitude), INDEX indice_ipocentro(ipocentro) ); And i want to insert a multi-dimensional php array into a mysql table but i dont'know like to add also id. This is code to add array: //MULTIDIMENSIONAL ARRAY $array_database= array( array("2017-06-30-104",1498858541000,39.3322,-122.9027,2.11,0,"U",36) ); // foreach($array_database as $row) { $idserial_db= mysql_real_escape_string($row[0]); $milliseconds_db = mysql_real_escape_string($row[1]); $latitude_db = mysql_real_escape_string($row[2]); $longitude_db = mysql_real_escape_string($row[3]); $magnitude_db = mysql_real_escape_string($row[4]); $ipocentro_db= mysql_real_escape_string($row[5]); $source_db= mysql_real_escape_string($row[6]); $region_db= mysql_real_escape_string($row[7]); $valori_db[] = "('$idserial_db',$milliseconds_db,$latitude_db,$longitude_db,$magnitude_db,$ipocentro_db,'$source_db',$region_db)"; } $values = implode(',', $valori_db); mysqli_query($connessione,"INSERT INTO earthquakes (idserial,milliseconds,latitude,longitude,magnitude,ipocentro,source,region) VALUES $values"); So how i add ID ? Thanks a lot and sorry for my english EDIT Maybe i should to add ID in this way: mysqli_query($connessione,"INSERT INTO earthquakes (id,idserial,milliseconds,latitude,longitude,magnitude,ipocentro,source,region) VALUES $values"); A: In the declaration: //MULTIDIMENSIONAL ARRAY $array_database= array( array("", "2017-06-30-104",1498858541000,39.3322,-122.9027,2.11,0,"U",36) ); // In the loop: $valori_db[] = " ('','$idserial_db',$milliseconds_db,$latitude_db,$longitude_db,$magnitude_db,$ipocentro_db,'$source_db',$region_db)"; In the query: mysqli_query($connessione,"INSERT INTO earthquakes (id,idserial,milliseconds,latitude,longitude,magnitude,ipocentro,source,region) VALUES $values");
{ "language": "en", "url": "https://stackoverflow.com/questions/44871681", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Binning in python with missing values I have to create bins based on age. There are some missing values (nan) that need to be changed as "N/A and assign to a new category as "Not_Availabe". I filled in the missing values and then transformed the strings to float. Students.loc[:, AGE']=Students.loc[:,AGE'].fillna("N/A") Students.loc[:,AGE'] = Students.loc[:,'AGE'].str.replace('\%', '', regex=True).astype(float) When I do this I get an error message as "could not convert string to float: 'N/A'. Then, I tried to use pd.cut and assign bins and labels, but nothing work. If I just do it an error message is "not supported between instances of 'int' and 'str* Code: Students.loc[:,'AGE']=Students.loc[:,'AGE'].fillna("unknown") Students.loc[:,'AGE'] = Students.loc[:,'AGE'].str.replace('\%', '', regex=True).astype(float) Students.loc[:,'AGE'] = Students.loc[:,'AGE'].cat.add_categories("Not_Available") Students.loc[:,'AGE']=pd.cut(x=Students.loc[:,'AGE'],bins=[0,18,30,50,65,75,100],labels=["Unknown,"18 and under", "19-30", "31-50", "51-65", "66-75","75+"]) The output should be similar as: Not_Availabe: 10 18 and under: 16 19-30: 80 31-50: 15 51-65: 5 66-75: 2 75+: 1 A: Convert the AGE column to float first, to avoid trying to convert string to float: df['AGE'] = df['AGE'].str.replace('%', '', regex=True).astype(float) I would suppose to then replace missing AGE values with -1 instead of 'N/A' to simplify binning. df['AGE'] = df['AGE'].fillna(-1) So, strictly speaking, it would not have been necessary here to do the conversion to float first to avoid the error message. Nevertheless this is still the sensible order of steps. Then, define custom ranges and do the binning: ranges = [-1, 0, 18, 30, 50, 65, 75, np.inf] labels = ['Not_Availabe', '18 and under', '19-30', '31-50', '51-65', '66-75', '75+'] df['AGE_labeled'] = pd.cut(df['AGE'], bins=ranges, labels=labels) # print the result print(df['AGE_labeled'].value_counts()) Note: I created the following dummy data for testing (hope it fits the question, as no sample data was given) import numpy as np import pandas as pd # dummy data length = 1000 data = { 'STUDENT_ID': np.random.randint(1000, 9999, length), 'AGE': np.random.randint(0, 99, length), } df = pd.DataFrame (data) df['AGE'] = df['AGE'].astype(str) # convert AGE value to str (as I assume from your question that this is the case) df.loc[df.sample(frac=0.1).index,'AGE'] = np.nan # randomly set some values to nan
{ "language": "en", "url": "https://stackoverflow.com/questions/73685506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PayPal API GetVerifiedStatus not working So I've been trying to implement PayPal's GetVerifiedStatus API into my website but have been running into the following error: Fatal error: Uncaught Error: Class 'PayPal\Types\AA\GetVerifiedStatusRequest' not found in C:\xampp\htdocs\paypaltest\getversys.php:14 Stack trace: #0 {main} thrown in C:\xampp\htdocs\paypaltest\getversys.php on line 14 What could the problem be? What I was able to figure out was that that particular directory is missing. But I have no idea as to how to get it because I've looked for it without any success. I've been using exactly the same code as given by the PayPal SDK. Here it is: <?php use PayPal\Service\AdaptiveAccountsService; use PayPal\Types\AA\AccountIdentifierType; use PayPal\Types\AA\GetVerifiedStatusRequest; require_once('bootstrap.php'); $getVerifiedStatus = new GetVerifiedStatusRequest(); $accountIdentifier=new AccountIdentifierType(); $accountIdentifier->emailAddress = $_REQUEST['emailAddress']; $getVerifiedStatus->accountIdentifier=$accountIdentifier; $getVerifiedStatus->firstName = $_REQUEST['firstName']; $getVerifiedStatus->lastName = $_REQUEST['lastName']; $getVerifiedStatus->matchCriteria = $_REQUEST['matchCriteria']; $service = new AdaptiveAccountsService(Configuration::getAcctAndConfig()); try { $response = $service->GetVerifiedStatus($getVerifiedStatus); } catch(Exception $ex) { require_once 'Common/Error.php'; exit; } $ack = strtoupper($response->responseEnvelope->ack); if($ack != "SUCCESS"){ echo "<b>Error </b>"; echo "<pre>"; print_r($response); echo "</pre>"; } else { echo "<pre>"; print_r($response); echo "</pre>"; echo "<table>"; echo "<tr><td>Ack :</td><td><div id='Ack'>$ack</div> </td></tr>"; echo "</table>"; } require_once 'Common/Response.php'; A: So I'm answering my own question here because I contacted PayPal tech support and was told that the GetVerifiedStatus API is now deprecated and can't be used. This is the reason for the error.
{ "language": "en", "url": "https://stackoverflow.com/questions/51714023", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP echoing an Array and splitting it up I'm currently getting dates from a web page by using the following foreach($returned_content->find('div.box-inset') as $article) { $item['dates'] = $article->find('div.important-dates', 0)->plaintext; $articles[] = $item; } var_dump($articles); Which will output the following array(2) { [0]=> array(1) { ["dates"]=> string(235) " Important Dates Expires On October 28, 2013 Registered On October 29, 2012 Updated On October 29, 2012 " } [1]=> array(1) { ["dates"]=> NULL } } I would ideally like to get the results to lay out as listed like so * *Important Dates *Expires On October 28, 2013 *Registered On October 29, 2012 *Updated On October 29, 2012 But I am lost with getting the content to echo correctly as echo $articles just produces Array and I have never had such an Array before like this one A: try: echo $articles[0]["dates"]; A: foreach($returned_content->find('div.box-inset') as $article) { $item['dates'] = $article->find('div.important-dates', 0)->plaintext; $articles[] = $item['dates']; } you cannot use echo to output array foreach($articles as $strarticle) { echo $strarticle; }
{ "language": "en", "url": "https://stackoverflow.com/questions/19742206", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Css Popup alert in button, instead input text How do i customize css so the popup alert just like this but instead alert popup focus in a button. i have use this kind of validation on text box <div class="form-group"> <label class="control-label col-sm-3" for="judul_laporan">Judul Laporan </label> <div class="col-sm-5"> <input type="email" class="form-control" id="judul_laporan" > <span style="color: red" id="warnlaporan"></span> </div> </div> <button type="button" id="save_laporan"></button> JQuery $("#save_laporan").click(function(){ var judul_laporan = $('input[name="judul_laporan"]'); if(judul_laporan.val() == ''){ judul_laporan.parent().parent().addClass('has-error'); $('#warnlaporan').text("Judul Laporan Belum Ada"); judul_laporan.focus(); result }else{ judul_laporan.parent().parent().removeClass('has-error'); $('#warnlaporan').text(""); } But i dont know how to make a popup alert likes the image ( and it should be button ) A: You can see the x3schools' documentation. It gives you a sample popup at the top of a div. This code opens a popup: // When the user clicks on <div>, open the popup function myFunction() { var popup = document.getElementById("myPopup"); popup.classList.toggle("show"); } /* Popup container */ .popup { position: relative; display: inline-block; cursor: pointer; } /* The actual popup (appears on top) */ .popup .popuptext { visibility: hidden; width: 160px; background-color: #555; color: #fff; text-align: center; border-radius: 6px; padding: 8px 0; position: absolute; z-index: 1; bottom: 125%; left: 50%; margin-left: -80px; } /* Popup arrow */ .popup .popuptext::after { content: ""; position: absolute; top: 100%; left: 50%; margin-left: -5px; border-width: 5px; border-style: solid; border-color: #555 transparent transparent transparent; } /* Toggle this class when clicking on the popup container (hide and show the popup) */ .popup .show { visibility: visible; -webkit-animation: fadeIn 1s; animation: fadeIn 1s } /* Add animation (fade in the popup) */ @-webkit-keyframes fadeIn { from {opacity: 0;} to {opacity: 1;} } @keyframes fadeIn { from {opacity: 0;} to {opacity:1 ;} } <div class="popup" onclick="myFunction()" style="left: 35px; top: 60px">Click me! <span class="popuptext" id="myPopup">Popup text...</span> </div> You also can use microtip, it is a pretty library witch give you the opportunity to create simply popup. This is the only declaration: <button aria-label="Hey tooltip!" data-microtip-position="top-left" role="tooltip">. However, you have to download a package (just 1kb) with rpm in your server.
{ "language": "en", "url": "https://stackoverflow.com/questions/45769012", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: ASP.NET Razor - How to display data from multiple tables in database Sorry if the question isn't worded well but I am very confused and it is very late but I will do my best to explain. So I am trying to display all of the orders from my database into a table without using the Entity Framework. the problem is when I go to orders/getAllOrders I just get a big error that says "the view" then a bunch of <tr><td>2</td><td>Javier</td><td>1</td><td>Groovestring</td><td>3.950000</td></tr>etc.. with my data in it but I don't know how to display it properly. I know my query is working fine and my data is being retrieved fine but I am stumped on displaying it This what I currently have for my controller. namespace Website.Controllers { public class OrderController : Controller { private static bool CanConnectToDb() { var cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString); try { cnn.Open(); return true; } catch (Exception exception) { return false; } finally { if (cnn.State != ConnectionState.Closed) cnn.Close(); } } public ActionResult getAllOrders() { // Connect to Database var cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString); cnn.Open(); // Create Command SqlCommand cmd = new SqlCommand( @"SELECT CustomerOrderId, FirstName ,ProductId, [Name], Price FROM OrderProduct AS o INNER JOIN CustomerOrder co ON co.id = o.CustomerOrderId INNER JOIN Product p ON p.Id = o.ProductId INNER JOIN Customer c ON c.Id = co.CustomerId ORDER BY ProductId" ); cmd.Connection = cnn; string store = ""; // Read from Database SqlDataReader reader = cmd.ExecuteReader(); var orders = new OrderIndexViewModel(); while (reader.Read()) { orders.CustomerOrderId = reader.GetInt32(0); orders.FirstName = reader.GetString(1); orders.ProductId = reader.GetInt32(2); orders.Name = reader.GetString(3); orders.Price = reader.GetDecimal(4); store += "<tr><td>" + orders.CustomerOrderId + "</td><td>" + orders.FirstName + "</td><td>" + orders.ProductId + "</td><td>" + orders.Name + "</td><td>" + orders.Price + "</td></tr>"; } cnn.Close(); return View(store); } } } EDIT: When I change the return to rerturn View(orders); I get this error The model item passed into the dictionary is of type 'Website.Models.OrderIndexViewModel', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[Website.Models.OrderIndexViewModel]'. This is my Model using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Website.Models { public class OrderIndexViewModel { public int CustomerOrderId { get; set; } public string FirstName { get; set; } public int ProductId { get; set; } public string Name { get; set; } public decimal Price { get; set; } } } And then finally this is my view @model IEnumerable<Website.Models.OrderIndexViewModel> @{ ViewBag.Title = "getAllOrders"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h2>getAllOrders</h2> <p> @Html.ActionLink("Create New", "Create") </p> <table class="table"> <tr> <th> Customer Oder Id </th> <th> First Name </th> <th> ProductId </th> <th> Name </th> <th> Price </th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.CustomerOrderId) </td> <td> @Html.DisplayFor(modelItem => item.FirstName) </td> <td> @Html.DisplayFor(modelItem => item.ProductId) </td> <td> @Html.DisplayFor(modelItem => item.Name) </td> <td> @Html.DisplayFor(modelItem => item.Price) </td> <td> @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) | @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) | @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ }) </td> </tr> } </table> Any help will be thoroughly appreciated A: You sended string to model but you must send collection to model and then show in table A: Your view is expecting IEnumerable<Website.Models.OrderIndexViewModel> as the model but you are passing it a single instance of Website.Models.OrderIndexViewModel. This might be another bug in your code, as this will only ever render the last item from the select statement. So you'll want something like this, which will render a row for each result: var orders = new List<OrderIndexViewModel>(); while (reader.Read()) { var order = new OrderIndexViewModel(); order.CustomerOrderId = reader.GetInt32(0); order.FirstName = reader.GetString(1); order.ProductId = reader.GetInt32(2); order.Name = reader.GetString(3); order.Price = reader.GetDecimal(4); orders.Add(order); } cnn.Close(); return View(orders);
{ "language": "en", "url": "https://stackoverflow.com/questions/51807539", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: couchdb views os_process_error - big documents I have a database that we're filling up with documents, some of which are 10 KB, and some of which that are ~70 MB in size. Any view that tries to load these large documents fails with error: {"error":"os_process_error","reason":"{exit_status,0}"}, even this elementary one: function(doc) { emit(null, "test"); } os_process_error is set to 35000, but calling the view dies in ~15 seconds: time curl -X GET http://localhost:5984/portal_production/_design/all_data_keys/_view/view1 {"error":"os_process_error","reason":"{exit_status,0}"} real 0m15.907s user 0m0.016s sys 0m0.000s From a few other threads, seems like this is related stack size: couchdb issue thread. I've applied this patch to increase the stack size, although I couldn't find a reference to the method's value. So I'm shooting in the dark a bit. Soooo.... the real question is: what is the correct approach for using views on large documents? I'm sure I'm not the first to have this problem. A: You'd hit couchjs stack size limit. If you're using CouchDB 1.4.0+ his size is limited by 64 MiB by default. You may increase it by specifying -S <number-of-bytes> option for JavaScript query server in CouchDB config. For instance, to set stack size to 128 MiB your config value will looks like: [query_servers] javascript = /usr/bin/couchjs -S 134217728 /usr/share/couchdb/server/main.js Note, that /usr/bin/couchjs may be different for you depending on your OS. After adding this changes you need to restart CouchDB. If you'll try to update JavaScript query server config though HTTP API, make sure to kill all couchjs processes from shell to let them apply changes. If your CouchDB version is <1.4 try to upgrade first.
{ "language": "en", "url": "https://stackoverflow.com/questions/21273736", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to pickle an instance of a class which is written inside a function? Suppose I have this snippet inside a module def func(params): class MyClass(object): pass How can I pickle an instance of the class MyClass ? A: You can't, because picklable object's class definitions must reside in an imported module's scope. Just put your class inside module scope and you are good to go. That said, in Python there is very little that can't be achieved with a bit of hacking the insides of the machinery (sys.modules in this case), but I wouldn't recommend that. A: The MyClass definition is local variable for the func function. You cannot directly create an instance of it, but you can map it's functions to a new class, and then to use the new class as it is the original one. Here's an example: def func(params): class MyClass(object): some_param = 100 def __init__(self, *args): print "args:", args def blabla(self): self.x = 123 print self.some_param def getme(self): print self.x func.func_code is the code of the func function, and func.func_code.co_consts[2] contains the bytecode of the MyClass definition: In : func.func_code.co_consts Out: (None, 'MyClass', <code object MyClass at 0x164dcb0, file "<ipython-input-35-f53bebe124be>", line 2>) So we need the bytecode for the MyClass functions: In : eval(func.func_code.co_consts[2]) Out: {'blabla': <function blabla at 0x24689b0>, '__module__': '__main__', 'getme': <function getme at 0x2468938>, 'some_param': 100, '__init__': <function __init__ at 0x219e398>} And finally we create a new class with metaclass, that assigns the MyClass functions to the new class: def map_functions(name, bases, dict): dict.update(eval(func.func_code.co_consts[2])) return type(name, bases, dict) class NewMyClass(object): __metaclass__ = map_functions n = NewMyClass(1, 2, 3, 4, 5) >> args: (1, 2, 3, 4, 5) n.blabla() >> 100 n.getme() >> 123 A: You can work around the pickle requirement that class definitions be importable by including the class definition as a string in the data pickled for the instance and exec()uting it yourself when unpickling by adding a __reduce__() method that passes the class definition to a callable. Here's a trivial example illustrating what I mean: from textwrap import dedent # Scaffolding definition = dedent(''' class MyClass(object): def __init__(self, attribute): self.attribute = attribute def __repr__(self): return '{}({!r})'.format(self.__class__.__name__, self.attribute) def __reduce__(self): return instantiator, (definition, self.attribute) ''') def instantiator(class_def, init_arg): """ Create class and return an instance of it. """ exec(class_def) TheClass = locals()['MyClass'] return TheClass(init_arg) # Sample usage import pickle from io import BytesIO stream = BytesIO() # use a memory-backed file for testing obj = instantiator(definition, 'Foo') # create instance of class from definition print('obj: {}'.format(obj)) pickle.dump(obj, stream) stream.seek(0) # rewind obj2 = pickle.load(stream) print('obj2: {}'.format(obj2)) Output: obj: MyClass('Foo') obj2: MyClass('Foo') Obviously it's inefficient to include the class definition string with every class instance pickled, so that redundancy may make it impractical, depending on the the number of class instances involved. A: This is somewhat tough to do because the way Pickle does with objects from user defined classes by default is to create a new instance of the class - using the object's __class__.__name__ attribute to retrieve its type in the object's original module. Which means: pickling and unpickling only works (by default) for classes that have well defined names in the module they are defined. When one defines a class inside a function, usulay there won't be a module level (i.e. global) variable holding the name of each class that was created inside the function. The behavior for pickle and npickle can be customized through the __getstate__ and __setstate__ methods on the class - check the docs - but even them, doing it right for dynamic class can be tricky , but I managed to create a working implementation of it for another S.O. question - -check my answer here: Pickle a dynamically parameterized sub-class
{ "language": "en", "url": "https://stackoverflow.com/questions/11807004", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Join DataFrames, but keep only columns of one I have a DataFrame df1: | ID | A | --------- | 1 | 4 | | 1 | 4 | | 2 | 1 | | 2 | 3 | | 3 | 2 | and a DataFrame df2: | ID | B | --------- | 1 | 2 | | 2 | 2 | | 3 | 9 | I want to (left) join these, but only want to keep the columns of df2. What is a short and easy solution for this? The resulting DataFrame should look somehow like this: |ID | B | --------- | 1 | 2 | | 1 | 2 | | 2 | 2 | | 2 | 2 | | 3 | 9 | A: You could slice the ID column from df1 as a DataFrame and merge on ID: import pandas as pd df1 = pd.DataFrame({'ID': [1, 1, 2, 2, 3], 'A': [4, 4, 1, 2, 3] }) df2 = pd.DataFrame({'ID': [1, 2, 3], 'B': [2, 2, 9] }) merged = df1[['ID']].merge(df2, how='left') This returns a DataFrame of the form: ID B 0 1 2 1 1 2 2 2 2 3 2 2 4 3 9 A: perform the join and pick up only columns in df2 df2.merge(df1, on='ID')[df2.columns] # output: B ID 0 2 1 1 2 1 2 2 2 3 2 2 4 9 3
{ "language": "en", "url": "https://stackoverflow.com/questions/45061427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to refactor models without breaking WPF views? I've just started learning WPF and like the power of databinding it presents; that is ignoring the complexity and confusion for a noob. My concern is how do you safely refactor your models/viewmodels without breaking the views that use them? Take the following snippet of a view for example: <Grid> <ListView ItemsSource="{Binding Contacts}"> <ListView.View> <GridView> <GridViewColumn Header="First Name" DisplayMemberBinding="{Binding Path=FirstName}"/> <GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding Path=FirstName}"/> <GridViewColumn Header="DOB" DisplayMemberBinding="{Binding Path=DateOfBirth}"/> <GridViewColumn Header="# Pets" DisplayMemberBinding="{Binding Path=NumberOfPets}"/> <GridViewColumn Header="Male" DisplayMemberBinding="{Binding Path=IsMale}"/> </GridView> </ListView.View> </ListView> </Grid> The list is bound to the Contacts property, IList(Of Contact), of the windows DataSource and each of the properties for a Contact is bound to a GridViewColumn. Now if I change the name of the NumberOfPets property in the Contact model to PetCount the view will break. How do I prevent the view breaking? A: Unfortunatly this is a known issue in WPF, the xaml is not taken into account when you refactor the entities behind the bindings. I have been making use of third party refactoring tools such as resharper or coderush to solve the problem, they tend to handle it better than the built in refactor function in visual studio. A: If you really don't want to change the view (for whatever reasons) you could leave the NumberOfPets property in the original ViewModel and set its getter to the PetCount property of the refactored ViewModel, there fore this won't break the View.
{ "language": "en", "url": "https://stackoverflow.com/questions/2872033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Host HTML5 site on Google Cloud Storage I'm trying to host my HTML5 site on Google Cloud Storage. When I load the site locally, all the animations work. When I upload it to Google Cloud Storage and access it, my CSS animations don't work. The CSS files are in css/theme.css in my storage bucket and the HTML file points to it like this: <link rel="stylesheet" href="css/theme.css"> <link rel="stylesheet" href="css/theme-elements.css"> <link rel="stylesheet" href="css/theme-animate.css"> A: Make sure the Content-Type metadata is set properly for your CSS files via the Developer Console. If not, you should manually edit the metadata to set the proper type, which is text/css for CSS files. If the type is neither not specified nor auto-detected at upload time, Google Cloud Storage serves files as binary/octet-stream which may prevent the browser from properly rendering it. Alternatively, you can also specify the MIME type in HTML, e.g., <link rel="stylesheet" href="css/theme.css" type="text/css"> to make sure that the browser handles it appropriately.
{ "language": "en", "url": "https://stackoverflow.com/questions/23630497", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: MVC Binding List of Objects in Object I'm trying to dynamically build a table that needs to be bound to a ViewModel on form submission. First item is the Action the form is submitting to. Then the Parent ViewModel and then the child ViewModel. Below those are two text fields representing the data I need bound. When I submit the form all the other fields from the page are bound to their respective property but the complex object of ProgramViewModels is not. What am I missing? public ActionResult Add(AddEntityViewModel viewModel){ Code that does something } public class AddEntityViewModel { public IList<int> Counties { get; set; } public IList<ProgramViewModel> Programs { get; set; } public IList<int> Regions { get; set; } public string EntityName { get; set; } public bool IsValid() { if (string.IsNullOrEmpty(EntityName)) return false; if (Counties == null || Counties.Count == 0) return false; if (Programs == null || Programs.Count == 0) return false; if (Regions == null || Regions.Count == 0) return false; return true; } } public class ProgramViewModel { public int Id; public string SystemId; } <input type="hidden" id="Programs[0]__Id" name="Programs[0].Id" data-programid="3" value="3"> <input type="text" id="Programs[0]__SystemId" name="Programs[0].SystemId" style="width:100%" maxlength="50"> Update: Changed the fields to properties after adiga's answer. But that too did not fix the issue. public class ProgramViewModel { public int Id { get; set; } public string SystemId { get; set; } } A: Your ProgramViewModel contains fields. Change them to properties. public class ProgramViewModel { public int Id { get; set; } public string SystemId { get; set; } } The DefaultModelBinder uses reflection and binds only the properties and not fields. A: If you have a List of a object, you should be performing a foreach instruction to get all of them: <% foreach(var x in values) { %> <div>hello <%= x.name %></div> <% } %>
{ "language": "en", "url": "https://stackoverflow.com/questions/46672145", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Evaluating worst case RAM effective bandwidth with discontinous memory access I'm trying to evaluate the effective memory "bandwidth" (throughput in bytes of data being treated) from main memory to CPU in a worst case scenario: the RAM cache is made totally inefficient due to long distances in the successive addresses being treated. As far as I understand what matters here is the RAM latency and not its bandwidth (which is the throughput when transferring big continuous blocks of data). The scenario is this (say you work with 64 bits=8 bytes values): * *you read data at an address *make some light weight CPU computation (so that CPU is not the bottleneck) *then you read data at new address quite far-away from the first one *and so on I'd like to have an idea of the throughput (say in bytes). A simple calculation assuming the RAM has typical DDR3 13 ns latency yields a bandwidth of 8 B/ 13 ns = 600 MB/s. But this raises several points: * *is this reasoning (at least schematically) correct? *is the time to get data exactly the RAM latency or do you have to add some time related to cache, CPU or any component in-between? Do you know how much? *what happens when doing this in multiple threads? Would there be 600 MB bandwidth for all threads together of for each of them? A: ... effective memory "bandwidth" ... from main memory to CPU in a worst case scenario: There are two "worst" scenarios: memory accesses which don't use (miss) CPU caches and memory accesses which accesses too far addresses and can't reuse open DRAM rows. the RAM cache The cache is not part of RAM, it is part of CPU, and named CPU cache (top part of memory hierarchy). is made totally inefficient due to long distances in the successive addresses being treated. Modern CPU caches has many builtin hardware prefetchers, which may detect non-random steps between several memory accesses. Many prefretchers will detect any step inside aligned 4 kilobyte (KB) page: if you access address1, then address1 + 256 bytes, then L1 prefetcher will start access of address1 + 256*2, address1 + 256*3 etc. Some prefetchers may try to predict out of 4 KB range. So, using only long distances between accesses may be not enough. (prefetchers may be disabled https://software.intel.com/en-us/articles/disclosure-of-hw-prefetcher-control-on-some-intel-processors) As far as I understand what matters here is the RAM latency and not its bandwidth Yes, there are some modes when RAM accesses are latency limited. The scenario is this (say you work with 64 bits=8 bytes values): You may work with 8 byte values; but you should consider that memory and cache work with bigger units. Modern DRAM memory has bus of 64 bits (8bytes) wide (72 bits for 64+8 in case of ECC), and many transactions may use several bus clock cycles (burst prefetch in DDR4 SDRAM uses 8n - 8 * 64 bits. Many transactions between CPU cache and memory controller are bigger too and sized as full cache line or as half of cache line. Typical cache line is 64 bytes. you read data at an address make some light weight CPU computation (so that CPU is not the bottleneck) then you read data at new address quite far-away from the first one This method is not well suitable for modern out-of-order CPUs. CPU may speculatively reorder machine commands and start execution of next memory access before current memory access is done. Classic tests for cpu cache and memory latency (lat_mem_rd from lmbench http://www.bitmover.com/lmbench/lat_mem_rd.8.html and many others) use memory array filled with some special pseudo-random pattern of pointers; and the test for read latency is like (https://github.com/foss-for-synopsys-dwc-arc-processors/lmbench/blob/master/src/lat_mem_rd.c#L95) char **p = start_pointer; for(i = 0; i < N; i++) { p = (char **)*p; p = (char **)*p; ... // repeated many times to hide loop overhead p = (char **)*p; } So, address of next pointer is stored in the memory; cpu can't predict next address and start next access speculatively, it will wait for read data from caches or from memory. I'd like to have an idea of the throughput (say in bytes). It can be measured in accesses per second; for byte accesses, or word accesses or 8 byte accesses there will be similar number of accesses/s and throughput (bytes/s) will be multiplied for unit used. Sometimes similar value is measured - GUPS - guga-updates per second (data in memory is read, updated and written back) with test of Random Access. This test can use memory of computing cluster of hundreds (or tens of thousands) of PC - check GUP/s column in http://icl.cs.utk.edu/hpcc/hpcc_results.cgi?display=combo A simple calculation assuming the RAM has typical DDR3 13 ns latency yields a bandwidth of 8 B/ 13 ns = 600 MB/s. But this raises several points: RAM has several latencies (timings) - https://en.wikipedia.org/wiki/Memory_timings And 13 ns CAS is only relevant when you access opened Row. For random accesses you will often access closed row and T_RCD latency is added to CAS.
{ "language": "en", "url": "https://stackoverflow.com/questions/50214864", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Spring Integration Dynamic Selector for JMS messages Spring Integration Dynamic Selector for JMS messages I have a requirement to use dynamic selectors to retrieve messages from the queue. For example i need to get messages from the queue at regular intervals that are > then 1 hr old. It seems the message selector is initialized just once . Can it be changed everytime the poller is used? and how? A: With the polled adapter, you can use a Smart Poller to change the selector expression before each poll; call setMessageSelector() on the JmsDestinationPollingSource. You cannot dynamically change the selector on a message-driven adapter; you have to stop the adapter first.
{ "language": "en", "url": "https://stackoverflow.com/questions/47145713", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: EF Core declares two foreign key from different table in a single table I'm using EF core with Fluent api and I got three tables (DomainObject is for the Ids) : public class Category : DomainObject { public string Name { get; set; } public string Type { get; set; } } public class Deadline : DomainObject { public Account Tiers { get; set; } public Category Category { get; set; } public DateTime Created_On { get; set; } } public class Transaction : DomainObject { public Account Payee { get; set; } public Category Category { get; set; } public DateTime DateProcessed { get; set; } } as you can see Transaction and Deadline contains a Category foreign key. modelBuilder .Entity<Deadline>() .HasOne(e => e.Account) .WithMany(e => e.Deadlines) .OnDelete(DeleteBehavior.Cascade); modelBuilder .Entity<Transaction>() .HasOne(e => e.Account) .WithMany(e => e.Transactions) .OnDelete(DeleteBehavior.Cascade); If create a Transaction with a "Food" Category and then I try to create a Deadline with a "Food" Category I got : InnerException = {"SQLite Error 19: 'UNIQUE constraint failed: Category.Id'."} This method create a deadline and update in database : public async Task<ManagementResult> CreateDeadline(User user, Account account, string tiers, string type, double amount, Category category, string notes, DateTime next_Deadline, string frequency, int nbOccurences) { ManagementResult result = ManagementResult.Success; if (amount <= 0) { result = ManagementResult.IncorrectAmount; } if (category == null) { result = ManagementResult.CategoryMissing; } if (frequency == null) { result = ManagementResult.FrequencyMissing; } if (result == ManagementResult.Success) { user.Accounts.Remove(account); Deadline deadline = new Deadline() { Tiers = tiers, Account = account, Type = type, Amount = amount, Category = category, Notes = notes, Next_Deadline = next_Deadline, Frequency = frequency, NbOccurences = nbOccurences, Status = "En cours", Created_On = DateTime.Now }; if (account.Deadlines == null) { account.Deadlines = new List<Deadline>(); } // Updating ICollection inside the user object account.Deadlines.Add(deadline); user.Accounts.Add(account); // Here is where i get the Exception await _deadlineService.Create(deadline); } return result; } Then this is DeadlineDataService method : // Here is the create method who's called public async Task<Deadline> Create(Deadline entity) { return await _nonQueryDataService.Create(entity); } And here's the NonQueryDataService method : public async Task<T> Create(T entity) { using (BookkeepingDbContext context = _contextFactory.CreateDbContext()) { EntityEntry<T> createdResult = await context.Set<T>().AddAsync(entity); await context.SaveChangesAsync(); return createdResult.Entity; } } How can I solve this ?
{ "language": "en", "url": "https://stackoverflow.com/questions/69287341", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Show Errors instead of Internal Server Error When my code have error (even syntax errors) browser show 500 - Internal Server Error, In .env I set the APP_DEBUG to true and APP_LOG_LEVEL is debug How can I enable error messages? UPDATE: I use Laravel 5.3 UPDATE 2: I use Apache and defined VirtualHost to access this app : <VirtualHost *:80> ServerAdmin [email protected] DocumentRoot "/Dev/Web/site/public" ServerName site.local ServerAlias www.site.local ErrorLog "/private/var/log/apache2/site.local-error_log" CustomLog "/private/var/log/apache2/site.local-access_log" common <Directory "/Dev/Web/site/public/"> Require all granted AllowOverride All </Directory> </VirtualHost> UPDATE 3: My /etc/hosts records: # Host Database # # localhost is used to configure the loopback interface # when the system is booting. Do not change this entry. ## 127.0.0.1 localhost gat.local www.gat.local site.local www.site.local shop.local www.shop.local A: Short answer you can't. Why? Simply because 500 - Internal Server Error is exactly what it says Internal Server Error, it has nothing to do with Laravel. Server software (Apache in your case) causes error 500. Most likely permissions problem. (server software can not read / write to certain files etc.) From Laravel documentation: After installing Laravel, you may need to configure some permissions. Directories within the storage and the bootstrap/cache directories should be writable by your web server or Laravel will not run. You have to check Apache logs Default on OSX machine /private/var/log/apache2 You want to see more errors? Follow up this SO thread. Neat trick, make sure to have one entry per project in your hosts file. #127.0.0.1 project1.dev www.project1.dev #127.0.0.1 project2.dev www.project2.dev . . . Why? You can just comment out / delete line, searchable, easier to read. A: @MajAfy You can use barryvdh/laravel-debugbar. This will give you in depth knowledge of every error. What query you are running and lot more. Here is the link https://github.com/barryvdh/laravel-debugbar . Its easy to install due to its well documentation. A: After many tries, I found problem, Everything return to file permissions, I changed the permission of laravel.log in storage/logs to 777 and everything work fine !
{ "language": "en", "url": "https://stackoverflow.com/questions/39932218", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Print image field in advanced pdf/html I want to print an image field which is a signature on employee record.${entity.custbody_signature} But when I print it is showing as '?' in the print. This advanced pdf/html template is on purchase order record. A: I created a free-form-text field on PO to store image file url in it. And then printed that image this way in the advanced pdf : <img src= "${record.imgfieldname}"/> A: Use <@filecabinet nstype="image" src="${entity.custbody_signature}">. You won't need to use "available without login" A: The best way to get the image url from image field in NetSuite is to do something like this <img src= "${record.custbody_signature@Url}"/>
{ "language": "en", "url": "https://stackoverflow.com/questions/59819555", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Use Microsoft.Office.Interop.Word In my project, I need to manipulate a .docx file. I was searching in Google and I found this dll: Microsoft.Office.Interop.Word. In my computer, I have Microsoft Office and it's ok but if I run my project in another computer without Microsoft Office installed (Microsoft.Office.Interop.Word.dll will go with project), will my program run? A: No. Microsoft.Office.Interop.Word (and all other interop) will just work when Office is installed on that machine. It is a requirement to actually create the instance of Word. Interop does start the Word executable and can't stand on its own. It is also discouraged to use Interop on a server. A: I concur with Patrick's answer. If you need to manipulate a docx file on a machine without the Word application installed you can work directly with the file via the Office Open XML file format. This can be done with any tools that can work with Zip packages (a docx file is a zip package of the files that make up the document) and XML. Microsoft provides the Open XML SDK for VB.NET and C# which makes things simpler. There's also an SDK for JavaScript. You'll find more information at OpenXMLDeveloper.org.
{ "language": "en", "url": "https://stackoverflow.com/questions/33943053", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why can't a class with a type parameter used exclusively as an argument type be covariant on it? The most common example I have found to explain why contravariantly-valid type parameters cannot be used covariantly has involved constructing some read-write wrapper of a derived type, casting it to a wrapper of the base type, injecting a different derived type, then later reading that wrapped value; something along the lines of the following: class Base { public int base_property; } class Derived : Base { public int derived_property; } class OtherDerived : Base { public string other_derived_property; } interface Wrapper<out T> { void put(T v); T pull(); } Wrapper<Derived> derived_wrapper = new WrapperImpl<Derived>(); Wrapper<Base> cast_wrapper = (Wrapper<Base>)derived_wrapper; cast_wrapper.put(new OtherDerived()); Derived wrapped = derived_wrapper.pull(); // Surprise! This is an OtherDerived. I can understand why this is invalid. But what if Wrapper didn't have pull, and the property it wraps has a private getter? The problem with the (Wrapper<Base>)derived_wrapper cast seems to disappear, and I can't find a problem to replace it. More specifically, I'm not aware of any way for functionality to be conditional on the eventual concrete type of a generic. Unsurprisingly, asserting the type like the following is no use: class WrapperImpl<T> : Wrapper<T> where T : Base { public void put(T v) { if(typeof(T).Equals(Derived)) { Console.WriteLine(v.derived_property); // Type `T' does not contain a // definition for `derived_property'... } } } This leads me to believe that functionality in these methods can only make use of properties of the type T is constrained to. Even if the wrapped property is an OtherDerived where the original WrapperImpl expected a Derived (before being cast), no method could expect that wrapped property to have derived_property because Base is the most specific T is guaranteed to be. Am I missing something here, or perhaps is this a limitation of the compiler to not be able to concretize T on the fly? (I'm guessing that a class like Wrapper finds few uses, but the rules of variance appear quite broad and sweeping, and I'm curious if there are finer rules in play.) A: The T in WrapperImpl<T> can be constrained on any subtype of Base, not just Base itself. Functionality in put should be able to safely access v.derived_property if T : Base is simply changed to a T : Derived. This is the source of trouble when an OtherDerived is passed to put after the (Wrapper<Base>)derived_wrapper cast, in trying to access the nonexistent derived_property.
{ "language": "en", "url": "https://stackoverflow.com/questions/38043355", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Split a list into smaller equal-sized lists keeping a "middle value"? I am looking for a way to split a python list in the following way. So that if I have an array: A = [0,1,2,3,4] I would be able to get: B = [0,1] C = [1,2] D = [2,3] E = [3,4] A: This is way easier than you think. You can use the same algorithm that itertools uses for their pairwise recipe except itertools.tee isn't needed as your input is a list therefore slicing will work. B, C, D, E = zip(A, A[1:]) Results: >>> print(B, C, D, E, sep='\n') (0, 1) (1, 2) (2, 3) (3, 4) A: You could use a list comprehension to create a list of these lists: pairs = [A[i : i + 2] for i in range(len(A) - 1)] If you then want to unpack them into different variables, you can use tuple unpacking: B, C, D, E = pairs A: A more general solution for sublists of length n with overlap of k: def chunk(lst, n=2, k=1): return [lst[i:i+n] for i in range(0, len(lst)-k, n-k)] >>> A = [0, 1, 2, 3, 4, 5, 6, 7] >>> chunk(A) [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7]] >>> chunk(A, 3) [[0, 1, 2], [2, 3, 4], [4, 5, 6], [6, 7]] >>> chunk(A, 5, 2) [[0, 1, 2, 3, 4], [3, 4, 5, 6, 7]]
{ "language": "en", "url": "https://stackoverflow.com/questions/59414606", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: writing a function of class which will build a string that holds all the information about the class object i want to write a method of class and call it dumpData which will build a string that holds all the information about the object. i tried several codes but all i get is AttributeError: 'list' object has no attribute 'dumpData' this is the code i have written so far: class Car(): def __init__(self, brand, productionYear) self.brand = brand self.productionYear = productionYear def dumpData(self,CarList1): return CarList1 if __name__ =="__main__": carObject = [] for i in range(10): carObjectList = [] brand_list = ['kia', 'Hunday', 'BMW', 'Audi', 'Jeep'] brand = random.choice(brand_list) productionYear = random.randint(1995, 2020) carObject.append(Car(brand, productionYear)) carObjectList.append(carObject) print(carObject.dumpData(carObjectList)) i edited this question because it didn't seem to be clear enough. thank you in advance A: Your error is saying you have a list object, not an instance of your class that you've tried to call your function on. I suggest making your class actually hold the list, and the add function take the info you want You don't need a parameter for the list, at that point. class Car(): def __init__(self, brand, year): self.brand = brand self.year = year def __repr__(self): return self.brand + "," + str(self.year) class CarList(): def __init__(self): self.cars = [] def dump(self): return str(self.cars) def add(self, brand, year): self.cars.append(Car(brand, year)) carList1 = CarList() carList1.add('honda', 2009) print(carList1.dump())
{ "language": "en", "url": "https://stackoverflow.com/questions/63234817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Jest spy on React useRef hook not being used after updating Jest to 24.9 When I used jest 22.4 I had a test like the following it ('should blah', () => { const spy = jest.spyOn(React, 'useRef').mockReturnValueOnce(blahMock); const comp = shallowWithIntl(<Blah />); const compShallow = comp.first().shallow(); expect(spy).toBeCalled() }); This works with jest 22.4, not in jest 24.9. I'm not certain that version is the problem as our team uplifted a few things. I will paste our current and old package json devdependencies area below. Old package.json devdependencies "devDependencies": { "@testing-library/react": "^8.0.1", "axios-mock-adapter": "^1.14.0", "babel-cli": "^6.24.1", "babel-core": "^6.24.1", "babel-jest": "^23.0.0", "babel-plugin-transform-object-assign": "^6.22.0", "babel-plugin-transform-object-rest-spread": "^6.23.0", "babel-plugin-transform-regenerator": "^6.24.1", "babel-preset-env": "^1.6.1", "babel-preset-react": "^6.24.1", "enzyme": "^3.3.0", "enzyme-adapter-react-16": "^1.1.1", "enzyme-react-intl": "^1.4.8", "enzyme-redux": "^0.2.1", "enzyme-to-json": "^3.3.3", "eslint": "^5.0.0", "eslint-config-terra": "^2.5.0", "generic-site-app": "^1.0.0", "html-webpack-plugin": "^3.2.0", "husky": "^0.14.3", "identity-obj-proxy": "^3.0.0", "jest": "^22.4.3", "jest-canvas-mock": "^1.1.0", "jsdoc": "^3.5.4", "jsdom": "11.11.0", "nightwatch": "^0.9.12", "orion-toolkit-js": "^3.12.0", "prettier": "^1.14.2", "prettier-eslint": "^8.8.2", "react": "^16.2.0", "react-dom": "^16.2.0", "react-intl": "^2.3.0", "react-on-rails": "7.0.4", "react-redux": "^5.0.7", "react-router": "^3.0.5", "react-test-renderer": "^16.2.0", "redux": "^3.7.2", "redux-saga": "^0.15.3", "redux-test-utils": "^0.2.2", "regenerator-runtime": "^0.11.1", "rimraf": "^2.6.1", "shelljs": "^0.8.1", "style-loader": "^0.20.3", "stylelint": "^9.2.0", "stylelint-config-sass-guidelines": "^5.0.0", "terra-markdown": "^2.24.0", "terra-slide-panel": "^3.3.0", "terra-toolkit": "^4.26.0", "url-loader": "^1.1.2", "webpack-bundle-analyzer": "^3.0.3", "webpack-merge": "^4.2.1" } New package.json devdependencies "devDependencies": { "@babel/cli": "^7.7.0", "@babel/core": "^7.7.2", "@babel/plugin-proposal-object-rest-spread": "^7.6.2", "@babel/plugin-transform-object-assign": "^7.2.0", "@babel/preset-env": "^7.7.1", "@babel/preset-react": "^7.7.0", "@testing-library/react": "^8.0.1", "axios-mock-adapter": "^1.14.0", "babel-jest": "^24.9.0", "browserslist-config-terra": "^1.3.0", "core-js": "^3.4.1", "enzyme": "^3.3.0", "enzyme-adapter-react-16": "^1.1.1", "enzyme-react-intl": "^1.4.8", "enzyme-redux": "^0.2.1", "enzyme-to-json": "^3.3.3", "eslint": "^5.0.0", "eslint-config-terra": "^2.5.0", "generic-site-app": "^1.0.0", "html-webpack-plugin": "^3.2.0", "husky": "^0.14.3", "identity-obj-proxy": "^3.0.0", "jest": "^24.9.0", "jest-canvas-mock": "^1.1.0", "jsdoc": "^3.5.4", "jsdom": "11.11.0", "prettier": "^1.14.2", "prettier-eslint": "^8.8.2", "raf": "^3.4.1", "react": "^16.2.0", "react-dom": "^16.2.0", "react-intl": "^2.3.0", "react-on-rails": "7.0.4", "react-redux": "^5.0.7", "react-router": "^3.0.5", "react-test-renderer": "^16.2.0", "redux": "^3.7.2", "redux-saga": "^0.15.3", "redux-test-utils": "^0.2.2", "regenerator-runtime": "^0.13.3", "rimraf": "^2.6.1", "shelljs": "^0.8.1", "style-loader": "^0.20.3", "stylelint": "^9.2.0", "stylelint-config-sass-guidelines": "^5.0.0", "terra-aggregate-translations": "^1.4.0", "terra-markdown": "^2.24.0", "terra-slide-panel": "^3.3.0", "terra-toolkit": "^5.13.0", "url-loader": "^1.1.2", "webpack": "^4.41.2", "webpack-bundle-analyzer": "^3.0.3", "webpack-cli": "^3.3.10", "webpack-dev-server": "^3.9.0", "webpack-merge": "^4.2.1" }
{ "language": "en", "url": "https://stackoverflow.com/questions/59159674", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: C++ extern storage class life-span I am a C++ newbie and come from a Java background. I would like to confirm the following: I am reading C++ by dissection by Ira Pohl and the book states that the life-span for a file/extern variable/function is the duration of the program (which makes sense because the variable is not declared in a class). What I want to know; is that also the case for a variable declared in a class? If not, if a variable is declared in a class does that make the variable use the auto storage class? Thanks. A: A member variable in a class has a life-span corresponding to the life-span of the class's instances, unless declared static. struct Foo { int x; static int y; }; This Foo, and therefore its x, has program life-span: static Foo foo; This one is auto: int main() { Foo foo; } This one is dynamically allocated and lives until the Foo is delete'd: int main() { Foo *foo = new Foo; } In each case, the y has program life-span.
{ "language": "en", "url": "https://stackoverflow.com/questions/4603271", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Toggle hide and show I have tried everything to get it to toggle show and hide but every time I add hide in the function, it stops working or I can get hide to work flawlessly while show doesn't work at all. Any help would be appreciated. <div class="ShowHideClicker clear" > <img src="something.gif"></div> <div class="ShowHideList"> <div class="ui-widget" id="SearchBar"> <label for="tags">Search:</label> <input id="tags"> <button class='clear' id="ClearButton"> Clear</button> </div> <div id="Result"></div> </div> $(document).ready(function(){ $('.ShowHideList').hide(); $('.ShowHideClicker').click(function(){ $(this).next().show('drop', {direction: 'left'}, 1000); }); }); A: Here is the simple solution with toggleClass: $('.ShowHideClicker').on('click', function(){ $(this).next().toggleClass('hidden'); }); http://jsfiddle.net/LcYLY/ A: You should be using the .toggle() this way: JSFIDDLE and make sure you have included jQuery and jQuery UI in your header ("drop" is a jQuery UI feature) jQuery: $(document).ready(function(){ $('.ShowHideClicker').click(function(){ $('.ShowHideList').toggle('drop', 1000); }); }); CSS: .ShowHideList { display: none; }
{ "language": "en", "url": "https://stackoverflow.com/questions/24939645", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how can I get pyodbc to perform a "SELECT ... INTO" statement without locking? I'm trying to copy a table in SQL Server, but a simple statement seems to be locking my database when using pyodbc. Here's the code I'm trying: dbCxn = db.connect(cxnString) dbCursor = dbCxn.cursor() query = """\ SELECT TOP(10) * INTO production_data_adjusted FROM production_data """ dbCursor.execute(query) The last statement returns immediately, but both LINQPad and SQL Server Management Studio are locked out of the database afterwards (I try to refresh their table lists). Running sp_who2 shows that LINQPad/SSMS are stuck waiting for my pyodbc process. Other databases on the server seem fine, but all access to this database gets held up. The only way I can get these other applications to resolve their stalls is by closing the pyodbc database connection: dbCxn.close() This exact same SELECT ... INTO statement statement works fine and takes only a second from LINQPad and SSMS. The above code works fine and doesn't lock the database if I remove the INTO line. It even returns results if I add fetchone() or fetchall(). Can anyone tell me what I'm doing wrong here? A: Call the commit function of either the cursor or connection after SELECT ... INTO is executed, for example: ... dbCursor.execute(query) dbCursor.commit() Alternatively, automatic commit of transactions can be specified when the connection is created using autocommit. Note that autocommit is an argument to the connect function, not a connection string attribute, for example: ... dbCxn = db.connect(cxnString, autocommit=True) ...
{ "language": "en", "url": "https://stackoverflow.com/questions/26922078", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: check single value from one table with table with multiple values separated by comma I have two tables in which one contains the correct answers to the questions and the other contains the answers submitted by user. I want to calculate the correct answers the user has entered with the tables which have the correct answers and make a new column, status, which has the status such as 'correct' or 'incorrect'. The problem is the correct answer tables has values separated by comma such as a,b,c and if a user enters the value its being send as single entry . such as a and then a new entry b . and i want to compare the values a and b present in the user answers submitted by user table to the correct answer table with entry a,b,c and also if a user enters a option d instead of b and d is not in a,b,c even if the user entry a is in a,b,c then also the answer should be marked as incorrect . So even if one option selected by user is wrong then the exact correct options in the correct option table then the status should be incorrect . I have made a SQL fiddle of the tables against which I tried this query SELECT qa.question_id,qa.type,qa.answers FROM questions_answer qa, user_test_answers uta where FIND_IN_SET(uta.answers, qa.answers) > 0 and qa.question_id='4' and uta.user_id='2' and qa.question_id=uta.question_id This returned empty results. The result i expect is question_id test_id user_answer type correct_answer status 13 4 a multiple_choice c incorrect 13 4 c multiple_choice c correct 14 4 a multiple_choice a,c correct 15 4 b true_false a incorrect A: You can try using GROUP_CONCAT in MySQL: SELECT uta.question_id, uta.test_id, GROUP_CONCAT(uta.answers ORDER BY uta.answers) AS user_answer, qa.type, qa.answers correct_answer, CASE WHEN GROUP_CONCAT(uta.answers) = qa.answers THEN 'correct' ELSE 'incorrect' END AS status FROM user_test_answers uta LEFT JOIN questions_answer qa ON qa.question_id = uta.question_id GROUP BY uta.user_id, uta.question_id Check I used ORDER BY in GROUP_CONCAT which means that inquestions_answer table, answers must be in alphabetical order. Also, there seems to be an invalid entry in user_test_answers, with question_id 20. HTH EDIT: SELECT uta.question_id, uta.test_id, uta.user_answer, qa.type, qa.answers correct_answer, CASE WHEN uta.user_answer = qa.answers THEN 'correct' ELSE 'incorrect' END AS status FROM questions_answer qa LEFT JOIN ( SELECT user_id, type, test_id, question_id, GROUP_CONCAT(answers ORDER BY answers) AS user_answer, timestamp from user_test_answers GROUP BY user_id, question_id ) uta ON qa.question_id = uta.question_id EDIT 2: SELECT uta.question_id, uta.test_id, uta.user_answer, qa.type, qa.answers correct_answer, CASE WHEN uta.user_answer = qa.answers THEN 'correct' ELSE 'incorrect' END AS status FROM questions_answer qa LEFT JOIN ( SELECT user_id, type, test_id, question_id, GROUP_CONCAT(answers ORDER BY answers) AS user_answer, timestamp from user_test_answers WHERE user_id = 2 AND test_id = 4 -- for user 2 and test 4 GROUP BY user_id, question_id ) uta ON qa.question_id = uta.question_id WHERE test_id = 4 -- try omitting this one in case you get incorrect results IMHO, you need to look at and improve your DB design and schemas.
{ "language": "en", "url": "https://stackoverflow.com/questions/24106027", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Defining recrussive JSON Object notation Whats wrong in below JSON Object definition I am trying to create a new JSON Object like below. So that my idea is to access COMPANYSETUP.HourSetup.initiate(); Not sure the error ? COMPANYSETUP = { initiated : false, companyId : "", initiate : function() { if(!initiated){ // TO DO initiated = true; } }, HourSetup = { initiated : false, hourId : "", initiate : function() { if(!initiated){ // TO DO initiated = true; } } } }; A: Assuming you want a javascript object and not JSON, which disallows functions, HourSetup = Should be changed to: HourSetup : Also, as JonoW points out, your single line comments are including some of your code as the code is formatted in the post. A: There's a "=" that shouldn't be there. Change it to ":" A: JSON is a form of JavaScript deliberately restricted for safety. It cannot include dangerous code elements like function expressions. It should work OK in plain eval()ed JavaScript, but it's not JSON.
{ "language": "en", "url": "https://stackoverflow.com/questions/1399808", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Saving Data as JSON feed from fullcalendar I'm wanting to save the objects that are created to the json-feed file, using $.ajax but nothing is being saved. The object is placed on the calendar but when I check the JSON feed in my .php file, nothing is changed? var calendar = $('#calendar').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: '' }, selectable: true, selectHelper: true, select: function(start, end) { var title = prompt('Event:'); $.ajax({ url: "json-events.php", type: 'POST', data: {"foo": "bar"}, processData: false, contentType: 'application/json' }); if (title) { calendar.fullCalendar('renderEvent', { title: title, start: start, end: end, allday: false }, true // make the event "stick" ); } calendar.fullCalendar('unselect'); }, editable: true, events: "json-events.php", eventDrop: function(event, delta) { alert(event.title + ' was moved ' + delta + ' days\n' + 'would update json-feed here'); }, A: var calendar = $('#calendar').fullCalendar({ editable: true, header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay' }, events: "events.php", selectable: true, selectHelper: true, select: function(start, end, allDay) { var title = prompt('Event Title:'); var url = prompt('Type Event url, if exits:'); if (title) { start = $.fullCalendar.formatDate(start, "yyyy-MM-dd HH:mm:ss"); end = $.fullCalendar.formatDate(end, "yyyy-MM-dd HH:mm:ss"); $.ajax({ url: 'add_events.php', data: 'title='+ title+'&start='+ start +'&end='+ end +'&url='+ url , type: "POST", success: function(json) { alert('Added Successfully'); } }); calendar.fullCalendar('renderEvent', { title: title, start: start, end: end, allDay: allDay }, true // make the event "stick" ); } calendar.fullCalendar('unselect'); }, editable: true, eventDrop: function(event, delta) { start = $.fullCalendar.formatDate(event.start, "yyyy-MM-dd HH:mm:ss"); end = $.fullCalendar.formatDate(event.end, "yyyy-MM-dd HH:mm:ss"); $.ajax({ url: 'update_events.php', data: 'title='+ event.title+'&start='+ start +'&end='+ end +'&id='+ event.id , type: "POST", success: function(json) { alert("Updated Successfully"); } }); }, eventResize: function(event) { start = $.fullCalendar.formatDate(event.start, "yyyy-MM-dd HH:mm:ss"); end = $.fullCalendar.formatDate(event.end, "yyyy-MM-dd HH:mm:ss"); $.ajax({ url: 'update_events.php', data: 'title='+ event.title+'&start='+ start +'&end='+ end +'&id='+ event.id , type: "POST", success: function(json) { alert("Updated Successfully"); } }); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/16723807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Robolectric tests not running (Android) I have successfully installed Robolectric, but my tests are not running at all. There are no errors, but also no results. What did I miss? After running ./gradlew test there are no test reports, but test-classes are generated properly My build.gradle: buildscript { repositories { mavenCentral() maven { url 'https://maven.fabric.io/repo' } } dependencies { ... classpath 'io.fabric.tools:gradle:1.+' classpath 'org.robolectric:robolectric-gradle-plugin:0.11.+' } } allprojects { repositories { mavenCentral() } } apply plugin: 'android-sdk-manager' apply plugin: 'com.android.application' apply plugin: 'io.fabric' apply plugin: 'idea' apply plugin: 'hugo' apply plugin: 'android' apply plugin: 'robolectric' idea { module { downloadJavadoc = true downloadSources = true testOutputDir = file('build/test-classes/debug') } } repositories { mavenCentral() maven { url 'https://repo.commonsware.com.s3.amazonaws.com' } flatDir name: 'localRepository', dirs: 'libs-aar' maven { url 'https://maven.fabric.io/repo' } } dependencies { repositories { mavenCentral() } ... // Espresso androidTestCompile files('lib/espresso-1.1.jar', 'lib/testrunner-1.1.jar', 'lib/testrunner-runtime-1.1.jar') androidTestCompile 'com.google.guava:guava:14.0.1' androidTestCompile 'com.squareup.dagger:dagger:1.1.0' androidTestCompile 'org.hamcrest:hamcrest-integration:1.1' androidTestCompile 'org.hamcrest:hamcrest-core:1.1' androidTestCompile 'org.hamcrest:hamcrest-library:1.1' androidTestCompile('junit:junit:4.11') { exclude module: 'hamcrest-core' } androidTestCompile('org.robolectric:robolectric:2.3') { exclude module: 'classworlds' exclude module: 'commons-logging' exclude module: 'httpclient' exclude module: 'maven-artifact' exclude module: 'maven-artifact-manager' exclude module: 'maven-error-diagnostics' exclude module: 'maven-model' exclude module: 'maven-project' exclude module: 'maven-settings' exclude module: 'plexus-container-default' exclude module: 'plexus-interpolation' exclude module: 'plexus-utils' exclude module: 'wagon-file' exclude module: 'wagon-http-lightweight' exclude module: 'wagon-provider-api' } androidTestCompile 'com.squareup:fest-android:1.0.+' } android { compileSdkVersion 19 buildToolsVersion '19.1.0' useOldManifestMerger true defaultConfig { minSdkVersion 11 targetSdkVersion 19 buildConfigField "String", "GIT_SHA", "\"${gitSha()}\"" testInstrumentationRunner "com.google.android.apps.common.testing.testrunner.GoogleInstrumentationTestRunner" // buildConfigField "String", "BUILD_TIME", buildTime() } ... sourceSets { main { manifest.srcFile 'AndroidManifest.xml' java.srcDirs = ['src/com', 'src/se', 'src/viewpagerindicator' , 'src-gen'] res.srcDirs = ['res'] assets.srcDirs = ['assets'] } ... androidTest { setRoot('src/androidTest') } } packagingOptions { exclude 'META-INF/LICENSE.txt' exclude 'META-INF/NOTICE.txt' exclude 'LICENSE.txt' exclude 'META-INF/LICENSE' exclude 'META-INF/NOTICE' } } ... robolectric { include '**/*Tests.class' exclude '**/espresso/**/*.class' } And my test: @RunWith(RobolectricTestRunner.class) public class StartTest { @Test public void testSomething() throws Exception { //Activity activity = Robolectric.buildActivity(DeckardActivity.class).create().get(); assertTrue(true); } } A: I think the problem is with your file mask. You are including Tests.class, but your class is called StartTest (notice the missing s) so it won't be included.
{ "language": "en", "url": "https://stackoverflow.com/questions/26774993", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Phpmailer how to include it to script? I am using PHPmailer github, I use the "gmail.php" from the examples and it works perfect when I open it in my browser. But when I copy the code and add it to my existing signup script I get an 500 Error. Also when I try to include it I get an 500 Error. How can I add phpmailer to my existing signup script? <?php /** * This example shows settings to use when sending via Google's Gmail servers. */ //SMTP needs accurate times, and the PHP time zone MUST be set //This should be done in your php.ini, but this is how to do it if you don't have access to that date_default_timezone_set('Etc/UTC'); require '../PHPMailerAutoload.php'; //Create a new PHPMailer instance $mail = new PHPMailer; //Tell PHPMailer to use SMTP $mail->isSMTP(); //Enable SMTP debugging // 0 = off (for production use) // 1 = client messages // 2 = client and server messages $mail->SMTPDebug = 2; //Ask for HTML-friendly debug output $mail->Debugoutput = 'html'; //Set the hostname of the mail server $mail->Host = 'xxxxxx'; // use // $mail->Host = gethostbyname('smtp.gmail.com'); // if your network does not support SMTP over IPv6 //Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission $mail->Port = 587; //Set the encryption system to use - ssl (deprecated) or tls $mail->SMTPSecure = 'tls'; //Whether to use SMTP authentication $mail->SMTPAuth = true; //Username to use for SMTP authentication - use full email address for gmail $mail->Username = "xxxxxx"; //Password to use for SMTP authentication $mail->Password = "xxxxxxxxxxxxx"; //Set who the message is to be sent from $mail->setFrom('xxx', 'xxx'); //Set an alternative reply-to address $mail->addReplyTo('xx', 'xx'); //Set who the message is to be sent to $mail->addAddress('Txxx', 'John Doe'); //Set the subject line $mail->Subject = 'Welcome to xx!'; //Read an HTML message body from an external file, convert referenced images to embedded, //convert HTML into a basic plain-text alternative body $mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__)); if (!$mail->send()) { } else { }
{ "language": "en", "url": "https://stackoverflow.com/questions/33976342", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ymacs with Filepicker.io, with ajax to retrieve the content I am using Ymacs with Filepicker.io from here and i am trying to retrieve the content div using ajax. But the problem is I can't include jQuery library too because it is resulting a conflicting and the ajax still not working i also tried this code from jQuery but it doesn't seem that it is effecting anything. I put the no noConflict in two place. Any ideas how to solve this problem? <script type="text/javascript" src="/js/jquery-1.7.2.min.js"> $.noConflict(); window.setInterval(getAjax, 3000); function getAjax() { $.ajax({ type: "POST", url: '/index', data: "some-data" }); } </script> A: Did you forgot a script tag or am I missing jQuery being loaded someplace else? This is working for me: <!DOCTYPE html> <script type="text/javascript" src="/js/jquery-1.7.2.min.js"></script> <script> // $.noConflict(); window.setInterval(getAjax, 3000); // This is getting hoisted function getAjax() { $.ajax({ type: "POST", url: '/index', data: "some-data" }); } </script> https://gist.github.com/3505792
{ "language": "en", "url": "https://stackoverflow.com/questions/11437993", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Different Colors for Different heights in spline chart in highchart I have an spline chart in highchart. its height is zero to one. I want to have all the points above the line y=0.5 have a red background color and points bellow this line have a green bckground. How can I do this in highchart? A: Try like this $(document).ready(function(){ $("#points").each(function(){ if((this).val()>0.5) (this).css("background-color","red"); }); }) Considered that your all points must have the id "points" and their values must be their respective heights(0.1,0.2,....like that) A: "This feature is planned for Highcharts 3.0. We wrote up a temporary hack, which is limited to SVG browsers. That means that it won’t work in IE6, 7 and 8. See http://jsfiddle.net/highcharts/PMyHQ/" - @orstein Hønsi (Admin, Highcharts JS) - Nov 14, 2011 Source: http://highcharts.uservoice.com/forums/55896-general/suggestions/787281-threshold-option-for-colors A: You can very well create a utility method that converts your series.data from [[x,y],...] into [{ x:xVal,y:yVal,color:color,...}...] This function could look something like this function groupDataByValue(data, threshold, aboveColor, belowColor) { var newData = []; $.each(data, function() { var dataPoint = { x: this[0], y: this[1], marker: {} }; var color; if (dataPoint.y > threshold) { color = aboveColor; } else { color = belowColor; } dataPoint.color = color; dataPoint.marker.fillColor = color; newData.push(dataPoint); }); return newData; } Before setting the series.data property pass it to this method and set the result value as the series.data Coloring points based on values @ jsFiddle
{ "language": "en", "url": "https://stackoverflow.com/questions/12348917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it normal that the strange src addr appears when DMA(PLX PEX 8733) runs a while? I am curious about the processing of DMA(PEX 8733) driver transfer, and using kzalloc to get a piece of buff for observing a running DMA descriptor table. It is according to DMA spec, the descriptor format is like: descriptor format When I start my observation, the result is like expected example 1 (The order is dw0, dw1, dw2, dw3.) or expected example 2. expected example 2: DMA Descriptor Entry 0, (80003c66, 3890, 74ea046c, fff4028e) DMA Descriptor Entry 1, (c000042e, 3890, 74ea0048, fff4024e) After a while(about 2 hours), the result shows: unexpected example 1 or unexpected example 2 unexpected example 2: DMA Descriptor Entry 0, (80007c0e, ffff3890, 65da046e, fffc04ee) DMA Descriptor Entry 1, (c000042e, ffff3890, 65da0040, fffc00c0) I am not able to realize the dw1 have 0xffff in source address' high byte. Do I misunderstand or miss something about DMA descriptor? I am not sure the potential issue(Additional messages) which is related to the high src addr, but it appears when DMA runs a while. Additional messages: DMAR: DRHD: handling fault status reg 402 DMAR: DMAR: [DMA Read] Request device [01:00.2] fault addr fffc0000 DMAR: [fault reason 06] PTE Read access is not set
{ "language": "en", "url": "https://stackoverflow.com/questions/52291814", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: iOS best way to store images So, i just want to know what the best way to display image from URL. I have to display few post from the server into my iOS app using UITableView with title and image in it. I had already created the WebServer for my app and fetching is done through TBXML and using Core Data to store the title and description from the server. and i saw some library available to cache the image like https://github.com/path/FastImageCache Now my question is that how can i display image from the URL ? And what is the best method to do it. Thanks A: The best way is to write your own code. Using a library will work but it will be generic and by definition slower than what you can write for your specific use case. You are far, far better off learning the few lines of code it takes to download an image and display it. Learn how to use a NSURLSession. Learn how to consume NSData and turn it into a UIImage. Learn how to use a NSNotification or a block to propagate the loaded image to your user interface. Your code will be stronger and you will become a better developer.
{ "language": "en", "url": "https://stackoverflow.com/questions/24187041", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Companion Objects in Kotlin Interfaces I am trying to make a interface Parcelable, as such I need a interface like this interface AB : Parcelable { companion object { val CREATOR : Parcelable.Creator<AB> } } and my two classes A and B looking like data class A (...): Parcelable{ ... companion object { val CREATOR : Parcelable.Creator<AB> = object : Parcelable.Creator<AB> { override fun newArray(size: Int): Array<AB?> { return arrayOfNulls(size) } override fun createFromParcel(parcel: Parcel): AB { return A(parcel) } } } I am struggling to implement such a interface in kotlin. It seems the interface class does not allow for the CREATOR Perhaps I am taking the wrong approach, I have a parcelable that contains a list of classes that are either A or B so I am doing parcel.readTypedList(this.list, AB.CREATOR) I require that the list be either A or B and that is why I am using an interface. Anyone have any advice or a possible solution? A: By convention classes implementing the Parcelable interface must also have a non-null static field called CREATOR of a type that implements the Parcelable.Creator interface. You need to annotate CREATOR property with @JvmField annotation to expose it as a public static field in containing data class. Also you can take a look at https://github.com/grandstaish/paperparcel — an annotation processor that automatically generates type-safe Parcelable wrappers for Kotlin and Java. A: In Kotlin, an interface can have a companion object but it is not part of the contract that must be implemented by classes that implement the interface. It is just an object associated to the interface that has one singleton instance. So it is a place you can store things, but doesn't mean anything to the implementation class. You can however, have an interface that is implemented by a companion object of a class. Maybe you want something more like this: interface Behavior { fun makeName(): String } data class MyData(val data: String) { companion object: Behavior { // interface used here override fun makeName(): String = "Fred" } } Note that the data class does not implement the interface, but its companion object does. A companion object on an interface would be useful for storing constants or helper functions related to the interface, such as: interface Redirector { fun redirectView(newView: String, redirectCode: Int) companion object { val REDIRECT_WITH_FOCUS = 5 val REDIRECT_SILENT = 1 } } // which then can be accessed as: val code = Redirector.REDIRECT_WITH_FOCUS
{ "language": "en", "url": "https://stackoverflow.com/questions/35327443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "34" }
Q: Why check box checked id is getting empty in this case When i am selected status as approved and click on a check box and click on delete button , i am getting the id as empty could you please let em know how to resolve this issue Jsfiddle My code: $(document).on('click', '#deletebtn', function(event) { var $checked = $('#tablecontent').find(":checkbox:checked"); if (confirm("Are you Sure to Delete") == true) { var ids = []; $.each($checked, function(i, e) { var status = $(e).parent().parent().find('.label-status').text(); var filterstatus = $('#filterstatus').val(); if (!filterstatus) { ids.push($(e).attr("id")); } else { if ($(e).attr("id") != 'selectall' && status == $('#filterstatus').val()) { ids.push($(e).attr("id")) } } }); alert(ids); } }); A: Issue : When you are trying to get the Status of the Row/Record by using Parent method of the jQuery, then it is not actually getting the correct element where you can find the status. Solution : Change the following line of code var status = $(e).parent().parent().find('.label-status').text(); to var status = $(e).closest('.AddreqTableCols').find('.label-status').text(); A: i guess this is what you are trying to do, if its not clear enough what is happening, feel free to ask. $("#selectall").click(function (e) { var $this = $(this); $("#tablecontent [type='checkbox']").prop("checked", $this.is(":checked")); }); $("#deletebtn").click(function (e) { if (!confirm("Are you sure you want to delete?")) return; var $checked = $("#tablecontent [type='checkbox']:checked"); var ids = $.map($checked, function (chk) { return $(chk).attr("id"); }); console.log(ids); alert(ids.join(",")); }); http://jsfiddle.net/cdkLkcdk/48/ COMMENT If i was assigned to write the same thing, i would set the status as a data-status on the checkbox itself to make things easier. A: The problem is that status is always empty. When you select a filterstatus it comes in the new if check and status == $('#filterstatus').val() will always be false since status is empty. Change your code to: var status = $(e).parent().parent().parent().find('.label-status').text(); You forgot an extra .parent(). Note: You can always use console.log() to test if your variables are filled in correctly.
{ "language": "en", "url": "https://stackoverflow.com/questions/29698141", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: android studio duplicate resources I'm getting these duplicate resources errors. [color/colorAccent] C:\Users\haide\Documents\androidProjects\SkyrimGenerator\SkyrimScenarioCharacterGenerator\app\src\main\res\values\strings.xml [color/colorAccent] C:\Users\haide\Documents\androidProjects\SkyrimGenerator\SkyrimScenarioCharacterGenerator\app\src\main\res\values\colors.xml: Error: Duplicate resources [color/colorPrimary] C:\Users\haide\Documents\androidProjects\SkyrimGenerator\SkyrimScenarioCharacterGenerator\app\src\main\res\values\strings.xml [color/colorPrimary] C:\Users\haide\Documents\androidProjects\SkyrimGenerator\SkyrimScenarioCharacterGenerator\app\src\main\res\values\colors.xml: Error: Duplicate resources [color/colorPrimaryDark] C:\Users\haide\Documents\androidProjects\SkyrimGenerator\SkyrimScenarioCharacterGenerator\app\src\main\res\values\strings.xml [color/colorPrimaryDark] C:\Users\haide\Documents\androidProjects\SkyrimGenerator\SkyrimScenarioCharacterGenerator\app\src\main\res\values\colors.xml: Error: Duplicate resources [style/AppTheme] C:\Users\haide\Documents\androidProjects\SkyrimGenerator\SkyrimScenarioCharacterGenerator\app\src\main\res\values\strings.xml [style/AppTheme] C:\Users\haide\Documents\androidProjects\SkyrimGenerator\SkyrimScenarioCharacterGenerator\app\src\main\res\values\styles.xml: Error: Duplicate resources Here is my colors.xml: <?xml version="1.0" encoding="utf-8"?> <resources> <color name="colorPrimary">#3F51B5</color> <color name="colorPrimaryDark">#303F9F</color> <color name="colorAccent">#FF4081</color> </resources> Here is my styles.xml: <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> and strings.xml: <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> This happened after I changed my strings.xml invalidated cache and restarted because it wouldn't update. I tried multiple permutations of having just one apptheme and one color in a single file, but I get compilation errors. Say I delete apptheme from strings.xml and colors from color.xml, I'll get compilation error. If I have any two duplicates it'll give me duplicate error... Does anyone know how to fix the error? A: I had same issue once... I noticed that i had declared the variable colorPrimary in the app level build.gradle file and also in colors.xml. I fixed the error by removing the resource value in the build.gradle file I had this in my app level build.gradle defaultConfig { ... resValue 'color', "colorPrimary", "#2196F3" } And this in my colors.xml <color name="colorPrimary">#C41426</color> I removed one of them problem solved
{ "language": "en", "url": "https://stackoverflow.com/questions/55093973", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to render a component inside render method? I have a react app like this import Modal from 'some-component' class Blog extends React.Component { render () { <Modal title='' content='' onOk='' onClose=''/> <SomeComponent> </SomeComponent> } } I am trying to use a separate function to render the modal, and call that function inside the render method like this ... renderModal = () => {} render() { // call renderModal here <SomeComponent> </SomeComponent> } but it doesn't work A: renderModal = () => { return (........your html....); } render () { {this.renderModal()}; } You can use this code to get what you are asking.. A: render () { return ( <Modal title='' content='' onOk='' onClose=''/> <SomeComponent> </SomeComponent> ) } you should wrap them in a parent element => render () { return ( <> <Modal title='' content='' onOk='' onClose=''/> <SomeComponent> </SomeComponent> </> ) } then you can use renderModal = () => <Modal title='' content='' onOk='' onClose='' /> render () { return ( <> {this.renderModal()} <SomeComponent> </SomeComponent> </> ) }
{ "language": "en", "url": "https://stackoverflow.com/questions/58603651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: OSError: [WinError 6] with undetected chromedriver Exception ignored in: <function Chrome.__del__ at 0x00000241BFF44360> Traceback (most recent call last): File "C:\Users\kevin\AppData\Local\Programs\Python\Python311\Lib\site-packages\undetected_chromedriver\__init__.py", line 769, in __del__ File "C:\Users\kevin\AppData\Local\Programs\Python\Python311\Lib\site-packages\undetected_chromedriver\__init__.py", line 758, in quit OSError: [WinError 6] The handle is invalid The code runs without error through python console and I just wanna know if there is anyway to run the code without running it through the python console. My python version is 3.1.1., Chrome is the lastest version, and undetected chrome driver is also the lastest version. import undetected_chromedriver.v2 as uc driver = uc.Chrome() driver.get('https://nowsecure.nl') This is the code that I found from the undetected chromedriver github.
{ "language": "en", "url": "https://stackoverflow.com/questions/74817978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: AttributeError: 'bool' object has no attribute 'clone' in Peewee with SQLite I am trying to get the following query: ignored = Activity.select().join(StuActIgnore).join(Student).where(Student.id == current_user.id) Activity.select().where(~(Activity.name**"%BBP") & Activity not in ignored) This does not give me any errors, but any of the following: Activity.get(~(Activity.name**"%BBP") & Activity not in ignored) Activity.select().where(~(Activity.name**"%BBP") & Activity not in ignored).join(Course) gives me the following error: AttributeError: 'bool' object has no attribute 'clone' If I try this: Activity.select().join(Course).join(StuCouRel).join(Student).where(~(Activity.name**"%BBP") & Activity not in ignored & Student.id == current_user.id) it will tell me that: TypeError: argument of type 'Expression' is not iterable I find this very confusing, because this: already_selected = Course.select().join(StuCouRel).join(Student).where(Student.id == current_user.id) to_choose = Course.select().where(Course not in already_selected) works perfectly fine, while it is very analogous to what I'm trying to do, it seems. I have absolutely no idea what this might mean and I can't find anything in the documentation. 'bool' object probably stands for boolean, but I cannot see how the result of my query is a boolean. I also don't know what 'clone' means and I also don't know how to resolve this error. A: Python casts whatever __contains__() returns to a boolean. That is why you cannot use "not in" or "in" when constructing peewee queries. You instead use << to signify "IN". You might try: ignored = (Activity .select() .join(StuActIgnore) .join(Student) .where(Student.id == current_user.id)) Activity.select().where(~(Activity.name**"%BBP") & ~(Activity.id << ignored)) See the docs on querying for more info http://peewee.readthedocs.org/en/latest/peewee/querying.html#column-lookups
{ "language": "en", "url": "https://stackoverflow.com/questions/20646814", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: c++ -std=c++11 -stdlib=libc++ with boost.thread gives Segmentation fault: 11 on OSX Tried to run some sample code. But something unexpected occured. I wonder is there any known issus about boost.thread used with libc++ together ? Program compiled with -std=c++11 or no option runs well. But when I compiled with -stdlib=libc++ or -std=c++11 -stdlib=libc++ The output was like: in main in thread bash: line 1: 37501 Segmentation fault: 11 ./a.out Compiler: Apple LLVM version 4.2 (clang-425.0.28) (based on LLVM 3.2svn) Target: x86_64-apple-darwin12.3.0 Thread model: posix OS: Mac OS X 10.8.3 The sample code is quite simple: #include "stdio.h" #include <boost/thread/thread.hpp> class callable { public: void operator()() { printf("in thread\n"); } }; int main() { boost::thread t = boost::thread(callable()); printf("in main\n"); t.join(); return 0; } A: boost.thread is probably linked to libstdc++. libstdc++ and libc++ have incompatible ABI. They shouldn't be used both in one program.
{ "language": "en", "url": "https://stackoverflow.com/questions/16384659", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Correct autolayout width not being returned on iOS 8 I'm trying to get the width of a UIView inside a custom UITableViewCell, in order to make some changes to it's appearance. I'm using autolayout, however, the width of the view returned is that which is defined in the xib file. This is different to its actual width once autolayout has laid out the cell. My code is in layoutSubviews(): override func layoutSubviews() { super.layoutSubviews() print(backgroundView.frame.width) } This works in iOS 9, but not in iOS 8. Calling self.setNeedsLayout() and self.layoutIfNeeded() has no effect. Where can I move the code so that it displays the correct width? Thanks. A: I've had this problem before, and if I recall correctly it had something to do with iOS not knowing the actual size until after the view has been drawn the first time. We were able to get it to update by refreshing after viewDidAppear (like you mentioned it's the appropriate size after refreshing), but that's not exactly the nicest solution. Something else you could try is adding constraint outlets to the cell that you manipulate wherever you do your cell setup. For example, if you needed a UI element to be a certain width in some cases but not others, you could add a width constraint that you change the value of. This lets your other elements resize themselves based on the other constraints in the view. The limitation here is that you need to know the width of one of your elements beforehand.
{ "language": "en", "url": "https://stackoverflow.com/questions/37613098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to exploit default mysql value column? I've a bit problem, I valorize a variable in this way: Dim hash As String = "" If hashes.SelectedValue IsNot Nothing Then hash = hashes.SelectedValue End If my table structure: `resources_guid` char(36) DEFAULT '00000000-0000-0000-0000-000000000000', when I perform the insert with MySqlCommand and the variable is empty, I get "NULL" instead of the default value, I tried also to set only Dim hash As String but the default value isn't exploited. Why? A: Reading between the lines, you're generated an insert command, passing hash as the value to set for your resources_guid column? If you supply any value, even null, that will be used instead of the default. To use the default, you need to not supply that parameter/column to the MySqlCommand object at all.
{ "language": "en", "url": "https://stackoverflow.com/questions/34792331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: add an input field in splashscreen using cordova spalshscreen pulgin is there any way to implement custom make Splash screen in ionic which have multiple logo and an input field on splash screen. i am using Cordova splash screen plugin for the the above implementation A: Create a basic splash screen without a cordova-plugin-splashscreen plugin. In this example the splash screen is removed using afterEnter view event. The idea is simple, show a fixed overlay container over a rest of the content. Add this DIV to your HTML page. Inside that DIV you have logo and input fields. <div id="custom-splashscreen"> <div class="item item-image"> <img src="http://3.bp.blogspot.com/-fGX23IjV0xs/VcRc4TLU_fI/AAAAAAAAAKk/ys3cyQz6fQc/s1600/download.jpg"> </div> <div class="card"> <div class="item item-text-wrap"> <div class="list"> <label class="item item-input"> <input type="text" placeholder="First Name"> </label> <label class="item item-input"> <input type="text" placeholder="Last Name"> </label> <label class="item item-input"> <textarea placeholder="Comments"></textarea> </label> </div> </div> </div> </div> Add this to css/style.css. Customize CSS depending on what you want to achieve. #custom-splashscreen { display: flex; flex-direction: column; justify-content: center; position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 100; background-color: #771313; } #custom-splashscreen .item-image { display: block; margin: 0 auto; width: 50%; height: auto; background-color: #771313; } Add this to your controller if you want that splash screen disappear after a specified number of seconds. Considering that you have input fields I guess you do not want splash screen to disappears. In controller you can put whatever you want. For example, a splash screen will be removed after a user clicks on the button. $scope.$on('$ionicView.afterEnter', function() { setTimeout(function() { document.getElementById("custom-splashscreen").style.display = "none"; }, 3000); }) Splash screen should look like this. As you can see it have logo and input fields. P.S. For the purposes of development add CORS plugin to Chrome and enable it while you work on app.
{ "language": "en", "url": "https://stackoverflow.com/questions/37802829", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can't $subtract a timestamp from a timestamp in mongodb When I run the following query the cant $subtract atimestamp from a timestamp occurred. Is there any alternative way to subtract two timestamp or convert the timestamp to integer and then do the subtract? { "collection": "visits_logs", "aggregate": [ { "$group": { "_id": { "_sid": "$_sid" }, "first1": { "$first": "$_time" }, "last1": { "$last": "$_time" }, "HTTP_REFERER_HOST": { "$first": "$HTTP_REFERER_HOST" } } }, { "$project": { "length": { "$subtract": ["$last1","$first1"] }, "HTTP_REFERER_HOST": 1 } }, { "$group": { "_id": "$HTTP_REFERER_HOST", "length": { "$avg": "$length" } } } ] } The complete error is: Error: Assert: command failed: { "ok" : 0, "errmsg" : "cant $subtract atimestamp from a timestamp", "code" : 16556, "codeName" : "Location16556" } : aggregate failed _getErrorWithCode@src/mongo/shell/utils.js:25:13 doassert@src/mongo/shell/assert.js:16:14 assert.commandWorked@src/mongo/shell/assert.js:370:5 DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1319:5 @(shell):1:1
{ "language": "en", "url": "https://stackoverflow.com/questions/49770267", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to use return_sequences option and TimeDistributed layer in Keras? I have a dialog corpus like below. And I want to implement a LSTM model which predicts a system action. The system action is described as a bit vector. And a user input is calculated as a word-embedding which is also a bit vector. t1: user: "Do you know an apple?", system: "no"(action=2) t2: user: "xxxxxx", system: "yyyy" (action=0) t3: user: "aaaaaa", system: "bbbb" (action=5) So what I want to realize is "many to many (2)" model. When my model receives a user input, it must output a system action. But I cannot understand return_sequences option and TimeDistributed layer after LSTM. To realize "many-to-many (2)", return_sequences==True and adding a TimeDistributed after LSTMs are required? I appreciate if you would give more description of them. return_sequences: Boolean. Whether to return the last output in the output sequence, or the full sequence. TimeDistributed: This wrapper allows to apply a layer to every temporal slice of an input. Updated 2017/03/13 17:40 I think I could understand the return_sequence option. But I am not still sure about TimeDistributed. If I add a TimeDistributed after LSTMs, is the model the same as "my many-to-many(2)" below? So I think Dense layers are applied for each output. A: The LSTM layer and the TimeDistributed wrapper are two different ways to get the "many to many" relationship that you want. * *LSTM will eat the words of your sentence one by one, you can chose via "return_sequence" to outuput something (the state) at each step (after each word processed) or only output something after the last word has been eaten. So with return_sequence=TRUE, the output will be a sequence of the same length, with return_sequence=FALSE, the output will be just one vector. *TimeDistributed. This wrapper allows you to apply one layer (say Dense for example) to every element of your sequence independently. That layer will have exactly the same weights for every element, it's the same that will be applied to each words and it will, of course, return the sequence of words processed independently. As you can see, the difference between the two is that the LSTM "propagates the information through the sequence, it will eat one word, update its state and return it or not. Then it will go on with the next word while still carrying information from the previous ones.... as in the TimeDistributed, the words will be processed in the same way on their own, as if they were in silos and the same layer applies to every one of them. So you dont have to use LSTM and TimeDistributed in a row, you can do whatever you want, just keep in mind what each of them do. I hope it's clearer? EDIT: The time distributed, in your case, applies a dense layer to every element that was output by the LSTM. Let's take an example: You have a sequence of n_words words that are embedded in emb_size dimensions. So your input is a 2D tensor of shape (n_words, emb_size) First you apply an LSTM with output dimension = lstm_output and return_sequence = True. The output will still be a squence so it will be a 2D tensor of shape (n_words, lstm_output). So you have n_words vectors of length lstm_output. Now you apply a TimeDistributed dense layer with say 3 dimensions output as parameter of the Dense. So TimeDistributed(Dense(3)). This will apply Dense(3) n_words times, to every vectors of size lstm_output in your sequence independently... they will all become vectors of length 3. Your output will still be a sequence so a 2D tensor, of shape now (n_words, 3). Is it clearer? :-) A: return_sequences=True parameter: If We want to have a sequence for the output, not just a single vector as we did with normal Neural Networks, so it’s necessary that we set the return_sequences to True. Concretely, let’s say we have an input with shape (num_seq, seq_len, num_feature). If we don’t set return_sequences=True, our output will have the shape (num_seq, num_feature), but if we do, we will obtain the output with shape (num_seq, seq_len, num_feature). TimeDistributed wrapper layer: Since we set return_sequences=True in the LSTM layers, the output is now a three-dimension vector. If we input that into the Dense layer, it will raise an error because the Dense layer only accepts two-dimension input. In order to input a three-dimension vector, we need to use a wrapper layer called TimeDistributed. This layer will help us maintain output’s shape, so that we can achieve a sequence as output in the end.
{ "language": "en", "url": "https://stackoverflow.com/questions/42755820", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "63" }
Q: Error when optimizing C++ code with inline assembly I am trying to learn inline assembly and I implemented Euclid algorithm in assembly! Now when I am trying to run my code with g++ filename -O1 it's compiling and running fine but when I am trying to do the same with clang++-3.6 filename -O1 code is compiling but producing segmentation fault! Also both gcc and clang producing compile time error when I am trying to run my code with -O2 or higher flags! g++ error eculid.cpp: Assembler messages: eculid.cpp:19: Error: symbol `CONTD' is already defined eculid.cpp:19: Error: symbol `DONE' is already defined clang error eculid.cpp:7:5: error: invalid symbol redefinition "movl %1, %%eax;" ^ <inline asm>:1:34: note: instantiated into assembly here movl %eax, %eax;movl %ecx, %ebx;CONTD: cmpl $0, %ebx;je DONE;xor... ^ eculid.cpp:7:5: error: invalid symbol redefinition "movl %1, %%eax;" ^ <inline asm>:1:132: note: instantiated into assembly here ...%edx;idivl %ebx;movl %ebx, %eax;movl %edx, %ebx;jmp CONTD;DONE: movl %ea... ^ 2 errors generated. Here is my code #include <iostream> using namespace std; int gcd(int var1, int var2) { int result = 0; __asm__ __volatile__ ( "movl %1, %%eax;" "movl %2, %%ebx;" "CONTD: cmpl $0, %%ebx;" "je DONE;" "xorl %%edx, %%edx;" "idivl %%ebx;" "movl %%ebx, %%eax;" "movl %%edx, %%ebx;" "jmp CONTD;" "DONE: movl %%eax, %0;" :"=r"(result) :"r"(var1), "r"(var2) ); return result; } int main(void) { int first = 0, second = 0; cin >> first >> second; cout << "GCD is: " << gcd(first, second) << endl; return 0; } You can check my code here (same error produced by my compiler) A: Just to put this in answer form so the question can be closed (please click the check mark next to this answer if it answers your question), at its simplest, you need to change your code like this: __asm__ __volatile__ ( "movl %1, %%eax;" "movl %2, %%ebx;" "CONTD%=: cmpl $0, %%ebx;" "je DONE%=;" "xorl %%edx, %%edx;" "idivl %%ebx;" "movl %%ebx, %%eax;" "movl %%edx, %%ebx;" "jmp CONTD%=;" "DONE%=: movl %%eax, %0;" :"=r"(result) :"r"(var1), "r"(var2) : "eax", "ebx", "edx", "cc" ); Using %= adds a unique number to the identifiers to avoid conflicts. And since the contents of registers and flags are being modified, you need to inform the compiler of that fact by 'clobbering' them. But there are other things you can do that make this a bit faster, and a bit cleaner. For example, instead of doing movl %%eax, %0 at the end, you can just tell gcc that result will be in eax when the block exits: __asm__ __volatile__ ( "movl %1, %%eax;" "movl %2, %%ebx;" "CONTD%=: cmpl $0, %%ebx;" "je DONE%=;" "xorl %%edx, %%edx;" "idivl %%ebx;" "movl %%ebx, %%eax;" "movl %%edx, %%ebx;" "jmp CONTD%=;" "DONE%=:" :"=a"(result) :"r"(var1), "r"(var2) : "ebx", "edx", "cc" ); Likewise, you can tell gcc to put var1 and var2 into eax and ebx for you before calling the block instead of you doing it manually inside the block: __asm__ ( "CONTD%=: cmpl $0, %%ebx;" "je DONE%=;" "xorl %%edx, %%edx;" "idivl %%ebx;" "movl %%ebx, %%eax;" "movl %%edx, %%ebx;" "jmp CONTD%=;" "DONE%=:" :"=a"(result), "+b"(var2) : "a"(var1) : "edx", "cc" ); Also, since you will (presumably) always be using result when calling gcd, volatile is unnecessary. If you won't be using result, then there's no point forcing the calculation to be done anyway. As written, the -S output for this statement will be one very long line, making debugging difficult. That brings us to: __asm__ ( "CONTD%=: \n\t" "cmpl $0, %%ebx \n\t" "je DONE%= \n\t" "xorl %%edx, %%edx \n\t" "idivl %%ebx \n\t" "movl %%ebx, %%eax \n\t" "movl %%edx, %%ebx \n\t" "jmp CONTD%= \n" "DONE%=:" : "=a"(result), "+b"(var2) : "a"(var1) : "edx", "cc" ); And I see no particular reason to force gcc to use ebx. If we let gcc pick its own register (usually gives best performance), that gives us: __asm__ ( "CONTD%=: \n\t" "cmpl $0, %1 \n\t" "je DONE%= \n\t" "xorl %%edx, %%edx \n\t" "idivl %1 \n\t" "movl %1, %%eax \n\t" "movl %%edx, %1 \n\t" "jmp CONTD%= \n" "DONE%=:" : "=a"(result), "+r"(var2) : "a"(var1) : "edx", "cc" ); And lastly, avoiding the extra jump when the loop is complete gives us: __asm__ ( "cmpl $0, %1 \n\t" "je DONE%= \n" "CONTD%=: \n\t" "xorl %%edx, %%edx \n\t" "idivl %1 \n\t" "movl %1, %%eax \n\t" "movl %%edx, %1 \n\t" "cmpl $0, %1 \n\t" "jne CONTD%= \n" "DONE%=:" : "=a"(result), "+r"(var2) : "a"(var1) : "edx", "cc" ); Looking at the -S output from gcc, this gives us: /APP cmpl $0, %ecx je DONE31 CONTD31: xorl %edx, %edx idivl %ecx movl %ecx, %eax movl %edx, %ecx cmpl $0, %ecx jne CONTD31 DONE31: /NO_APP This code uses fewer registers, performs fewer jumps and has fewer asm instructions than the original code. FWIW. For details about %=, clobbers, etc, check out the official gcc docs for inline asm. I suppose I should ask why you feel the need to write this in asm rather than just doing it in c, but I'll just assume you have a good reason.
{ "language": "en", "url": "https://stackoverflow.com/questions/33273986", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can Indy load SSL certificate from cryptografic card or token? My application is written using Delphi 2007 and Indy 10. It uses certificates in .p12 files. I set Indy's CertFile, KeyFile and RootCertFile properties and everything works great. But soon, it will be used for certificates stored on cryptographic cards or tokens. Can Indy load SSL certificate from a cryptographic card or token? If not, how can I improve the application to use a certificate stored on a cryptographic card or token?
{ "language": "en", "url": "https://stackoverflow.com/questions/42157305", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to call an event handler and a state from a parent component to a child component in a recommended way by using reactjs? I'm using react redux in an application. I am trying to send an event handler (with a state) from a parent component to a child component I have developed a separate Alert component for the reusability in different parent components Please see my tried code -- CustomizedAltert.js ------ import React from 'react'; import Button from '@material-ui/core/Button'; import Snackbar from '@material-ui/core/Snackbar'; import MuiAlert from '@material-ui/lab/Alert'; import { makeStyles } from '@material-ui/core/styles'; function Alert(props) { return <MuiAlert elevation={6} variant="filled" {...props} />; } const useStyles = makeStyles((theme) => ({ root: { width: '100%', '& > * + *': { marginTop: theme.spacing(2), }, }, })); export default function CustomizedAltert({props,childCloseHandler}) { const classes = useStyles(); const [open, setOpen] = React.useState(false); const handleClick = () => { setOpen(true); }; const handleClose = (event, reason) => { if (reason === 'clickaway') { return; } setOpen(false); }; return ( <div className={classes.root}> <Snackbar open={props.open} anchorOrigin={{ vertical:'middle', horizontal:'right' }} autoHideDuration={props.duration} onClose={childCloseHandler} > <Alert onClose={childCloseHandler} severity={props.type}> {props.message} </Alert> </Snackbar> </div> ); } ---- ParentComponent.Js---------------------- import CustomizedAlert from './components/CustomizedAlert'; const showAlert = (obj) => { if(obj) { if(obj.name) return <CustomizedAlert open={true} type="error" duration={6000} message={obj.message} childCloseHandler={childOnCloseHandler}></CustomizedAlert > } } -- For Child Component Hander and state childOnCloseHandler = (event, reason) => { if (reason === 'clickaway') { return; } setOpen(false); }; export default function ParentComponent() { return ( <div className={classes.paper}> <showAlert customer ={customerObj} /> </div> ); What should I do in my code? Application built with { "react": "16.13.0", "react-dom": "^16.13.0", "react-redux": "^7.2.0", "redux": "^4.0.4" "@material-ui/core": "^4.9.5" } The problem I face is getting a recommended way to create a refined child component without using useRef and forwardRef: I tried to follow articles and looked up example implementations but could not find the recommended way to solve the the issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/63089020", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cannot convert a pointer to a struct to a int pointer I'm trying to build a memory manager for my operating system. However, when I add a pointer to the next node property of the first heap item, it doesn't work. I suspect it cannot convert a pointer to a heap item to a unsigned int pointer. Constants #define MEMORY_BLOCK_FREE 0 #define MEMORY_BLOCK_USED 1 #define MEMORY_BLOCK_TAIL 2 Memory Block Struct typedef struct { u32* addr; u32 size; u8 state; u32* next_block; } memory_block; Add function u32* add_block(u32 size) { memory_block* cblock = &head; while (1) { if (cblock->state == MEMORY_BLOCK_TAIL) { break; } cblock = (memory_block*)cblock->next_block; } u32* addr = cblock->addr; cblock->size = size; cblock->state = MEMORY_BLOCK_USED; memory_block next; next.state = MEMORY_BLOCK_TAIL; next.addr = (u32*)(addr + size); cblock->next_block = (u32*)&next; } A: memory_block next; It is a wrong code. Try this memory_block *next; next = malloc(sizeof(memory_block));
{ "language": "en", "url": "https://stackoverflow.com/questions/62668437", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get the name of an image file from the root folder. The name of the folder is upload I am trying to get the name of a particular image file that has already been uploaded, not the one being uploaded in the folder to delete the file. I have looked up all over google. Please help me. It is the last increment i have to make before the end of the day. I do have the imageurl as http://localhost/public_html/upload/123.jpeg I have found this as my answer to delete the file but i do not know how to extract the file name unlink($imagePath . $file_name); Thank you A: You can extract a file name from a path using basename like this: basename($imagePath); // output: 123.jpeg or without the extension: basename($imagePath, ".jpeg"); // output: 123 A: <?php $path = "index.php"; //type file path with extension $title = basename($path,".php"); // get only title without extension /remove (,".php") if u want display extension echo $title; ?> A: Try it with two way.. First : base_path unlink(base_url("uploads/".$image_name)); getcwd : Some times absolute path not working. unlink(getcwd()."/uploads/".$image_name);
{ "language": "en", "url": "https://stackoverflow.com/questions/39138190", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java on Linux: maximize a non-Java GUI application From Java code, is there a way to maximize the window of a different GUI application? I have access to Process objects created for these other programs, as well as a semi-reliable way to get their PIDs and a generic String indicating the name of the process binary (e.g. "firefox"). I can also programmatically execute full bash shell statements (including commands connected with pipes), if there's some command-line way of going about it. On MS Windows, I recall seeing somewhere about a Java library that wraps the win32 windowing API, allowing one to pass those Windows-specific signals to applications - would there be something similar to that on a Linux setup? This is for a Red Hat system, if that matters. A: Not in a "standards-based" way, no. The X-Windows system is independent of specific window managers, as such, there is no standard way to "maximize" a window. It ultimately depends on the features of the window manager in use...
{ "language": "en", "url": "https://stackoverflow.com/questions/7115615", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: kubernetes "unable to get metrics" I am trying to autoscale a deployment and a statefulset, by running respectivly these two commands: kubectl autoscale statefulset mysql --cpu-percent=50 --min=1 --max=10 kubectl expose deployment frontend --type=LoadBalancer --name=frontend Sadly, on the minikube dashboard, this error appears under both services: failed to get cpu utilization: unable to get metrics for resource cpu: unable to fetch metrics from resource metrics API: the server could not find the requested resource (get pods.metrics.k8s.io) Searching online I read that it might be a dns error, so I checked but CoreDNS seems to be running fine. Both workloads are nothing special, this is the 'frontend' deployment: apiVersion: apps/v1 kind: Deployment metadata: name: frontend labels: app: frontend spec: replicas: 3 selector: matchLabels: app: frontend template: metadata: labels: app: frontend spec: containers: - name: frontend image: hubuser/repo ports: - containerPort: 3000 Has anyone got any suggestions? A: First of all, could you please verify if the API is working fine? To do so, please run kubectl get --raw /apis/metrics.k8s.io/v1beta1. If you get an error similar to: “Error from server (NotFound):” Please follow these steps: 1.- Remove all the proxy environment variables from the kube-apiserver manifest. 2.- In the kube-controller-manager-amd64, set --horizontal-pod-autoscaler-use-rest-clients=false 3.- The last scenario is that your metric-server add-on is disabled by default. You can verify it by using: $ minikube addons list If it is disabled, you will see something like metrics-server: disabled. You can enable it by using: $minikube addons enable metrics-server When it is done, delete and recreate your HPA. You can use the following thread as a reference.
{ "language": "en", "url": "https://stackoverflow.com/questions/70838207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Formly: How to receive data in JSON? Link: http://thrivingkings.com/read/Formly-The-form-glamorizer-for-jQuery I am making a contact form using Formly and I was wondering how you actually send the message to your server/ to an email address. Their example is: <script> $(document).ready(function() { $('#ContactInfo').formly({'theme':'Dark'}, function(e) { $('.callback').html(e); }); }); </script> and they say: This time, we setup a callback function which will give us the data in URL format. This is not the safest method of transferring user data and should not be used with secure information. Also, you can easily change the callback method to .serializeArray() to receive the data in JSON. How do you you recieve data in JSON? I understand what they are saying by using .serializeArray() but I don't know how to send that data. I don't have much experience with this. Thanks. A: You'd send the data to your server by utalizing jQuery POST like this: var postData = $("#ContactInfo").serializeArray(); $.post('ajax/test.html', postData, function(returnData) { console.log(returnData); }, "json"); From http://api.jquery.com/jQuery.post/ Put the path to your server endpoint, that handles the posted data in replacement of ajax/test.html. I did assume #ContactInfo is your form element. I did use $.serializeArray() to create a sendable JSON of your form content, as you can see here http://api.jquery.com/serializeArray/
{ "language": "en", "url": "https://stackoverflow.com/questions/15843055", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Product bundles UI in Model Driven App, Sales Insights Are Product Bundles supported in this new iteration of UI -- Model Driven App? Here is a modern product picker. It does not distinct between type of product, is not aware it's a bundle: Here is modern read-only sub-grid view. It does not even display contents of a Bundle:
{ "language": "en", "url": "https://stackoverflow.com/questions/73820884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the most efficient way to store and recall one object from either of two unique keys in Java? I am working on creating a very performance-focused event-driven system. In this program, I have one object that needs to be linked to two different unique keys. The object contains parameters of what to do when one of two different events is triggered. public class MonthConfiguration implements Comparable<MonthConfiguration>, Serializable { final String monthID; public final String displayID; private final Double dte; public boolean enabled; ... public MonthConfiguration(String monthID, String displayID, boolean enabled, double dte) { this.monthID = monthID; this.displayID = displayID; this.enabled = enabled; this.dte = dte; } ... @Override public int compareTo(MonthConfiguration o) { return this.dte.compareTo(o.dte); } } I currently need to quickly recall one of these objects in two different call backs that are triggered with unique keys HashMap<String, MonthConfiguration> monthMap = new HashMap<>() @Override public void onEventOne(String key1) { MonthConfiguration mon1 = monthMap.get(key1) ... } @Override public void onEventTwo(String key2) { MonthConfiguration mon2= monthMap.get(key2) ... } In the above example key1 != key2, however mon1 and mon2 are the same. Currently I am using the code MonthConfiguration mon = new MonthConfiguration (monthID, displayID,enabled, dte); monthMap.put(key1, mon); monthMap.put(key2, mon); Is there a better way to do this? The number of MonthConfiguration objects is rather large and I am worried about the efficiency of this and possible memory leaks as objects are deleted/added to the map.
{ "language": "en", "url": "https://stackoverflow.com/questions/49430734", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SSL: 400 no required certificate was sent The code and inputs I'm trying to establish SSL connection and I'm getting 400 No required SSL certificate was sent response from the server. I'm doing this in a standard way like it's described for example here; I run Java 8. The sample of my code would be: OkHttpClient client = new OkHttpClient(); KeyStore keyStoreClient = getClientKeyStore(); KeyStore keyStoreServer = getServerKeyStore(); String algorithm = ALGO_DEFAULT;//this is defined as "PKIX" KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm); keyManagerFactory.init(keyStoreClient, PASSWORD_SERVER.toCharArray()); SSLContext sslContext = SSLContext.getInstance("TLS"); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(algorithm); trustManagerFactory.init(keyStoreServer); sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom()); client.setSslSocketFactory(sslContext.getSocketFactory()); client.setConnectTimeout(32, TimeUnit.SECONDS); // connect timeout client.setReadTimeout(32, TimeUnit.SECONDS); // socket timeout return client; And here is the code that I use to send GET-request: public String get(String url) throws IOException { String callUrl = URL_LIVE.concat(url); Request request = new Request.Builder() .url(callUrl) .build(); Response response = this.client.newCall(request).execute(); return response.body().string(); } I enabled: System.setProperty("javax.net.debug", "ssl"); So to see debug messages - but there's no errors/warnings/alerts there, the only thing is in the very end: main, called close() main, called closeInternal(true) main, SEND TLSv1.2 ALERT: warning, description = close_notify main, WRITE: TLSv1.2 Alert, length = 26 main, called closeSocket(true) Which is the only thing I can treat as "abnormal" stuff (but I doubt it is). I tried: * *Different protocols disabling/enabling. For instance, forcing TLSv1 / TLSv1.1 for the socket with no success. To try that I wrapped my ssl factory into another factory which disables/enables certain protocols. *Disabling SSLv2Hello - but it doesn't change the picture. *Install Oracle policies because before there were notices about some skipped algorithms and this installation "solved" that but the overall result is still same. *Setting System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true"); - lame, but also didn't change a thing apart from message in the log Allow unsafe renegotiation: true (was "false" obviously) *Using KeyManagerFactory.getDefaultAlgorithm() as algorithm for KeyManagerFactory.getInstance() call. That raises exception Get Key failed: Given final block not properly padded and as far as I got the idea, it's because of wrong algorithm used (read this). My default algorithm is: SunX509 *Adding the certificate directly to my machine with keytool -importcert -file /path/to/certificate -keystore keystore.jks -alias "Alias" and then using this in my program via System.setProperty("javax.net.ssl.trustStore","/path/to/keystore.jks"); with setting password: System.setProperty("javax.net.ssl.trustStorePassword","mypassword"); (I set password in keytool after which confirmed trusted certificate with yes); see this and this posts. No errors were raised with this - but issue persisted. *Adding the certificate to the global keystore (the one located in JAVA_PATH/jre/lib/security/cacerts) with: keytool -import -trustcacerts -keystore cacerts -storepass changeit -noprompt -alias Alias -file /path/to/certificate (see this); looks like import operation was successful but it didn't change the picture There's also notice in debug: ssl: KeyMgr: choosing key: 1 (verified: OK) - not sure if it's relevant as I'm not SSL expert. Unfortunately I can not see the server-side logs so I can't observe the full picture. Question What can be the reason for this 400 error and how can I progress further (debug/try something else) ? Any tips would be much appreciated. A: Your server is asking for a client-side certificate. You need to install a certificate (signed by a trusted authority) on your client machine, and let your program know about it. Typically, your server has a certificate (with the key purpose set to "TLS server authentication") signed by either your organization's IT security or some globally trusted CA. You should get a certificate for "TLS client authentication" from the same source. If you capture the TLS handshake in Wireshark, you'll see the ServerHello message followed by a "Client Certificate Request", to which you reply with a "Client Certificate" message with length 0. Your server chooses to reject this.
{ "language": "en", "url": "https://stackoverflow.com/questions/36284543", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Get FDQN from url and link it to grafana dashboards data link I have a grafana dashboard and I want to extract the url and use it in grafana data links .is there a variable I can use in order to get the url. Example: I want to extract this https://bingoke.com and use it in datalinks I want to replace localhost with https://bingoke.com which comes from the url using some variable . not hard coding it. A: Don't use absolute URL e.g. https://bingoke.com/?queueId=..., but relative URL instead e.g. /?queueId=..., so browser will use current protocol/domain automatically.
{ "language": "en", "url": "https://stackoverflow.com/questions/72628242", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }