_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d2001
train
Have you actually tried if this aligns your variables correctly? When you compile, the executable always has a header whose size may not be a multiple of 16. Also, alignment_purge may not really get the variables following it out of alignment, because the compiler may add padding. Finally, the headers don't introduce variables, so if you put your variables above or below headers, that doesn't change anything. You can take a look at this question to see how to request aligned memory. As a side note, normally you wouldn't want to include source files into another file. See this question on this subject. A: Putting variable declarations at the top of a file is not required to enforce any specific alignment. You may just be getting lucky here, or it may be an idiosyncrasy of your compiler. If you're using gcc, you can use the aligned attribute to request the correct alignment - other compilers probably have equivalent extensions or #PRAGMAs. eg. your variable declarations with gcc's extension would look like: float v1[16] __attribute__ ((aligned (16))); float v2[16] __attribute__ ((aligned (16))); If you need it to be entirely portable, I think your only solution is to dynamically allocate a large block of memory, and then manage the alignment of allocated blocks within it yourself. Note that the alignment only needs to be enforced where the variables are actually stored, in the .cpp file. You can just forward declare them in a header, and that will let you refer to them in your other files. #includeing the .cpp file is not only unnecessary, it will cause a link error as every file has its own copy of the variables with the same names. OP is using Digital Mars (if you'd mentioned this right away, I would have looked it up). Searching for digital mars alignment, the first hit is the pragma documentation. I looked at align first, and it referred me to pack. Using this, your code would look like: #pragma pack(push, 16) float v1[16]; float v2[16]; // ... any other aligned variables defined here #pragma pack(pop) However, pack affects the alignment of members inside structures - it's not clear what it does for global variables. I think, to be certain, you need to write an aligned allocator: start by searching _aligned allocation C++` for example, and post a dedicated question if you can't figure it out.
unknown
d2002
train
Solved this by doing: refocusEditor({ editor }: { editor: Editor }) { const block = Editor.above(editor, { match: (n) => Editor.isBlock(editor, n), }); const path = block ? block[1] : []; ReactEditor.focus(editor); // @ts-ignore Transforms.setSelection(editor, path); }
unknown
d2003
train
Selenium does not support sending keys to the browser address bar, unfortunately. Someone suggested a solution with win32com.client library here Haven't tried it myself as I haven't been faced with this situation. The idea is you may need to consider workarounds, as this is outside the scope of Selenium.
unknown
d2004
train
You're sending an IList into your view. This will display a single item. public ActionResult Index() { var info = _repository.GetLocation("Oberhausen").First(); return View(info); } If you really want a list (e.g., you're going to display a table or some such), keep your action as is and change your view to: @model IList<LocateIt.ModelsLocationInfo> A: I don't understand what the parentheses are doing in the model declaration. The syntax for @model should be: @model Your.Namespace.ClassName The in your code you use Model, not model.
unknown
d2005
train
No -- if you go to your GitHub accounts page, you can add as many SSH public keys as you want.
unknown
d2006
train
Try mYourDbHelper.getWritableDatabase().execSQL("CREATE TABLE ....") from where you need to create another table
unknown
d2007
train
I fixed my code and now it works like a charm, My complete code: - (id)initAddressBook { self = [super init]; if (self) { self.addressBook = ABAddressBookCreateWithOptions(NULL, NULL); ABAddressBookRegisterExternalChangeCallback(self.addressBook, addressBookChangeHandler, NULL); } return self; } - (void)duplicateUserContactsFromAddressBook:(ABAddressBookRef)myAddressBook { NSLog(@"duplicateUserContacts"); if (myAddressBook != NULL && kWeHaveAccessToContacts) { // Get all user contacts CFArrayRef allContactsRef = [self getAllContactsInAddressBook:myAddressBook]; // Delete old group if exists [self deleteGroupWithName:kGroupNameMobileControl fromAddressBook:myAddressBook]; // Create Mobile Control 'white list' group self.groupCallBlockRef = [self createGroupWithName:kGroupNameMobileControl fromAddressBook:myAddressBook]; // Copy contacts to new group for (int i = 0; i < ABAddressBookGetPersonCount(myAddressBook); i++) { ABRecordRef personFromContacts = CFArrayGetValueAtIndex(allContactsRef, i); [self addPerson:personFromContacts toGroup:self.groupCallBlockRef fromAddressBook:myAddressBook]; } } } - (void)deleteGroupWithName:(NSString*)groupName fromAddressBook:(ABAddressBookRef)myAddressBook { if (myAddressBook != NULL && kWeHaveAccessToContacts) { CFArrayRef allGroups = ABAddressBookCopyArrayOfAllGroups(myAddressBook); if (allGroups != NULL) { for (int i = 0; i < CFArrayGetCount(allGroups); i++) { ABRecordRef group = CFArrayGetValueAtIndex(allGroups, i); CFStringRef name = ABRecordCopyCompositeName(group); NSString *currentGroupName = (__bridge NSString*)name; if ([currentGroupName isEqualToString:groupName]) { [self deleteGroup:group fromAddressBook:myAddressBook]; } } } } } - (ABRecordRef)getGroupReference:(ABAddressBookRef)myAddressBook { NSLog(@"getGroupReference"); if (myAddressBook != NULL && kWeHaveAccessToContacts) { CFArrayRef allGroups = ABAddressBookCopyArrayOfAllGroups(myAddressBook); if (allGroups != NULL) { for (int i = 0; i < CFArrayGetCount(allGroups); i++) { ABRecordRef group = CFArrayGetValueAtIndex(allGroups, i); CFStringRef name = ABRecordCopyCompositeName(group); NSString *groupName = (__bridge NSString*)name; NSLog(@"groupName: %@", groupName); if ([groupName isEqualToString:kGroupNameMobileControl]) { self.groupCallBlockRef = group; break; } else { continue; } } } } return self.groupCallBlockRef != NULL ? self.groupCallBlockRef : NULL; } - (CFArrayRef)getAllContactsInAddressBook:(ABAddressBookRef)myAddressBook { NSLog(@"getAllContacts"); if (myAddressBook != NULL && kWeHaveAccessToContacts) { CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(myAddressBook); self.arrayOfAllContacts = people; } else { self.arrayOfAllContacts = NULL; } NSLog(@"Total number of contacts: %li", CFArrayGetCount(self.arrayOfAllContacts)); return self.arrayOfAllContacts; } - (void)deleteContact:(ABRecordRef)person inAddressBook:(ABAddressBookRef)myAddressBook { if (myAddressBook != NULL && kWeHaveAccessToContacts) { CFErrorRef error = NULL; ABAddressBookRemoveRecord(myAddressBook, person, &error); ABAddressBookSave(myAddressBook, &error); CFRelease(error); CFRelease(person); } } - (void)blockPerson:(ABRecordRef)person inAddressBook:(ABAddressBookRef)myAddressBook { BOOL hasContact = [self checkIfContactExists:person inAddressBook:myAddressBook]; if (hasContact) { NSLog(@"Contact exists, delete him."); [self deleteContact:person inAddressBook:myAddressBook]; } else { NSLog(@"Contact not exists."); } } - (BOOL)checkIfContactExists:(ABRecordRef)person inAddressBook:(ABAddressBookRef)myAddressBook { __block BOOL answer = NO; if (myAddressBook != NULL && kWeHaveAccessToContacts) { CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(myAddressBook); for(int i=0; i<ABAddressBookGetPersonCount(myAddressBook); i++) { ABRecordRef personToCompare = CFArrayGetValueAtIndex(people, i); if (ABRecordGetRecordID(personToCompare) == ABRecordGetRecordID(person)) { answer = YES; CFRelease(people); CFRelease(personToCompare); CFRelease(person); break; } } } return answer; } - (ABRecordRef)createGroupWithName:(NSString*)groupName fromAddressBook:(ABAddressBookRef)myAddressBook { NSLog(@"createGroup"); ABRecordRef newGroup = ABGroupCreate(); if (myAddressBook != NULL && kWeHaveAccessToContacts) { ABRecordSetValue(newGroup, kABGroupNameProperty, (__bridge CFStringRef)groupName, NULL); ABAddressBookAddRecord(myAddressBook, newGroup, NULL); ABAddressBookSave(myAddressBook, NULL); self.groupCallBlockRef = newGroup; } return newGroup; } - (void)addPerson:(ABRecordRef)person toGroup:(ABRecordRef)group fromAddressBook:(ABAddressBookRef)myAddressBook { NSLog(@"addContactToGroup"); ABGroupAddMember(group, person, NULL); ABAddressBookSave(myAddressBook, NULL); } static void addressBookChangeHandler(ABAddressBookRef addressBook, CFDictionaryRef info, void *context) { if (context) { [(__bridge CallBlockManager*)context handleAddressBookChange:addressBook withInfo:info]; } } - (void)handleAddressBookChange:(ABAddressBookRef)myAddressBook withInfo:(CFDictionaryRef)info { // }
unknown
d2008
train
The selected event should fire automatically on click. Consider the following code block. Here I pass in a set of handlers to decide things like what url to use, what label to attach the auto complete behavior to etc. Ultimately making an ajax request to populate the auto complete list. ActivateInputFieldSearch: function (callBack, fieldID, urlHandler, labelHandler, valueHandler) { $("#" + fieldID).autocomplete({ source: function (request, response) { var requestUrl; if (_.isFunction(urlHandler)) { requestUrl = urlHandler(request); } else { requestUrl = urlHandler; } $.ajax({ url: requestUrl, dataType: "json", data: { maxRows: 10, searchParameter: request.term }, success: function (data) { response($.map(data, function (item) { var dataJson = $.parseJSON(item); return { label: labelHandler(dataJson), value: valueHandler(dataJson), data: dataJson }; })); } }); }, minLength: 0, select: function (event, ui) { if (callBack) { callBack(ui.item); } }, open: function () { $(this).removeClass("ui-corner-all").addClass("ui-corner-top"); }, close: function () { $(this).removeClass("ui-corner-top").addClass("ui-corner-all"); }, focus: function (event, ui) { $("#" + fieldID).val(ui.item.value); } }); } A: I had a similar problem. I was attempting to use an autocomplete on 3 text boxes. If the user started typing in any of the three text boxes, an ajax call would fire and would return all the distinct combinations of those boxes in the database based on what was typed in them. The important part of what I'm trying to say is that I had the "mouse click no autocompleting" problem. I had a function firing on select to set the values for all of the text boxes. It was something like this: function showAutocompleteDropDown( a_options ){ console.log('options: ' + a_options); if ( a_options == "" ){ // nothing to do return; }// if // find out which text box the user is typing in and put the drop down of choices underneath it try{ // run jquery autocomplete with results from ajax call $(document.activeElement).autocomplete({ source: eval(a_options), select: function(event, ui){ console.log( 'event: ' + event.type ); console.log( ' running select ' ); // set the value of the currently focused text box to the correct value if (event.type == "autocompleteselect"){ console.log( "logged correctly: " + ui.item.value ); ui.item.value = fillRequestedByInformation( ); } else{ console.log( "INCORRECT" ); } }// select }); } catch(e){ alert( e ); }// try / catch }// showAutocompleteDropDown() function fillRequestedByInformation( ){ // split the values apart in the name attribute of the selected option and put the values in the appropriate areas var requestedByValues = $(document.activeElement).val().split(" || "); var retVal = $(document.activeElement).val(); $(document.activeElement).val(""); var currentlyFocusedID = $(document.activeElement).attr("id"); console.log( 'requestedByValues: ' + requestedByValues ); console.log( 'requestedByValues.length: ' + requestedByValues.length ); for (index = 0; index < requestedByValues.length; index++ ){ console.log( "requestedByValues[" + index + "]: " + requestedByValues[index] ); switch ( index ){ case 0: if ( currentlyFocusedID == "RequestedBy" ){ retVal = requestedByValues[index]; } $('#RequestedBy').val(requestedByValues[index]); break; case 1: if ( currentlyFocusedID == "RequestedByEmail" ){ retVal = requestedByValues[index]; } $('#RequestedByEmail').val(requestedByValues[index]); break; case 2: if ( currentlyFocusedID == "RequestedByPhone" ){ retVal = requestedByValues[index]; } $('#RequestedByPhone').val(requestedByValues[index]); break; default: break; } } }// fillRequestedByInformation() and then I changed it to the following: function showAutocompleteDropDown( a_options ){ console.log('options: ' + a_options); if ( a_options == "" ){ // nothing to do return; }// if // find out which text box the user is typing in and put the drop down of choices underneath it try{ // run jQuery autocomplete with results from ajax call $(document.activeElement).autocomplete({ source: eval(a_options), select: function(event, ui){ console.log( 'event: ' + event.type ); console.log( ' running select ' ); // set the value of the currently focused text box to the correct value if (event.type == "autocompleteselect"){ console.log( "logged correctly: " + ui.item.value ); ui.item.value = fillRequestedByInformation( ui.item.value ); } else{ console.log( "INCORRECT" ); } }// select }); } catch(e){ alert( e ); }// try / catch }// showAutocompleteDropDown() function fillRequestedByInformation( a_requestedByValues ){ // split the values apart in the name attribute of the selected option and put the values in the appropriate areas var requestedByValues = a_requestedByValues.split(" || "); var retVal = $(document.activeElement).val(); $(document.activeElement).val(""); var currentlyFocusedID = $(document.activeElement).attr("id"); console.log( 'requestedByValues: ' + requestedByValues ); console.log( 'requestedByValues.length: ' + requestedByValues.length ); for (index = 0; index < requestedByValues.length; index++ ){ console.log( "requestedByValues[" + index + "]: " + requestedByValues[index] ); switch ( index ){ case 0: if ( currentlyFocusedID == "RequestedBy" ){ retVal = requestedByValues[index]; } $('#RequestedBy').val(requestedByValues[index]); break; case 1: if ( currentlyFocusedID == "RequestedByEmail" ){ retVal = requestedByValues[index]; } $('#RequestedByEmail').val(requestedByValues[index]); break; case 2: if ( currentlyFocusedID == "RequestedByPhone" ){ retVal = requestedByValues[index]; } $('#RequestedByPhone').val(requestedByValues[index]); break; default: break; } } }// fillRequestedByInformation() The debugging is still in there for now, but the change was in the select event in the autocomplete by adding a parameter to the function fillRequestedByInformation() and the first line of said function. It returns to and overwrites ui.item.value to get the correct value for that box instead of the selected value. Example of a selected autocomplete value: "John Doe || [email protected] || 1-222-123-1234" Also, used eval( a_options ) so that the autocomplete could utilize a_options. before I used eval, it would not even recognize I had values in the source. a_options is the result. A: i think you need the select event $( ".selector" ).autocomplete({ select: function(event, ui) { ... } }); http://jqueryui.com/demos/autocomplete/#event-select
unknown
d2009
train
The jQuery Hoverable Plugin: unifies touch and mouse events over different platforms like desktops and mobile devices with touchscreens That might be a good alternative for your app. A: You want to create a second implementation that works with the click event. May be something like this: $(selector syntax).click(function () { AnimationEffect(this); }); $(selector syntax).mouseenter(function () { AnimationEffect(this); }); function AnimationEffect(TheDiv) { //your animation goes here, TheDiv is the jquery object //you can access it like this: $(TheDiv). } A: Have the user click on the watch, then click again to get rid of the info. This can be accomplished using the .toggle() method: http://api.jquery.com/toggle-event/
unknown
d2010
train
Change Run Configuration to x86 to Debug or Release
unknown
d2011
train
You could do the following to get rid of enum. Replace enum with a class. public abstract class Platform {} Add Device class which answers if it's compatible with a Platform. public abstract class Device { public abstract bool IsCompatibleWith(Platform platform); } Make CaptureDevice a subclass of Device. public abstract class CaptureDevice : Device { public Platform Platform; public override bool IsCompatibleWith(Platform platform) { // I'm using type comparison for the sake of simplicity, // but you can implement different business rules in here. return this.Platform.GetType() == platform.GetType(); } public bool IsCompatibleWith(SensorDevice sd) { // We are compatible if sensor is compatible with my platform. return sd.IsCompatibleWith(this.Platform); } } Make SensorDevice a subclass of Device. public abstract class SensorDevice : Device { public IEnumerable<Platform> Platforms; public override bool IsCompatibleWith(Platform platform) { // I'm using type comparison again. return this.Platforms.Any(p => p.GetType() == platform.GetType()); } public bool IsCompatibleWith(CaptureDevice cd) { // We are compatible if capture is compatible with one of my platforms. return this.Platforms.Any(p => cd.IsCompatibleWith(p)); } } Basically, that's all you need to do. To illustrate how it works, I've added the code below. // Platforms public class StandardPlatform : Platform { } public class DeluxPlatform : Platform { } public class JumboPlatform : Platform { } // Capture device(s) public class CD1 : CaptureDevice { public CD1() { Platform = new StandardPlatform(); } } // Sensor device(s) public class SD1 : SensorDevice { public SD1() { Platforms = new List<Platform> { new StandardPlatform(), new DeluxPlatform() }; } } public class SD2 : SensorDevice { public SD2() { Platforms = new List<Platform> {new JumboPlatform()}; } } // Somewhere in the code... var cd1 = new CD1(); var sd1 = new SD1(); Console.WriteLine(cd1.IsCompatibleWith(sd1)); // True Console.WriteLine(sd1.IsCompatibleWith(cd1)); // True var sd2 = new SD2(); Console.WriteLine(sd2.IsCompatibleWith(cd1)); // False Console.WriteLine(cd1.IsCompatibleWith(sd2)); // False A: EDIT: If you want to get rid off the enum, why shouldn't use a config file ? You configure your platforms like this: <Platforms> <Platform name="Standard"> <Device>Namespace.of.your.Device.CaptureDevice</Device> <Device>Namespace.of.another.Device.AnotherDevice</Device> </Platform> <Platform name="Deluxe"> <Device>Namespace.of.your.Device.CaptureDevice</Device> </Platform> </Platforms> Other syntax: <Platforms> <Platform> <Name>Standard</Name> <Devices> <Device>Namespace.of.your.Device.CaptureDevice</Device> <Device>Namespace.of.another.Device.AnotherDevice</Device> <Devices> </Platform> </Platforms> Then, you have the same base structure, you could do something like this: abstract class ADevice<T> where T : ADevice<T> { public ADevice<T>(T device , string filename) { // Parsing of the file // Plus, setting the Platforms Property } // Or (but you should keep the first constructor to see the filename dependency) public ADevice<T>(T device) { // Parsing of the file } public IEnumerable<Platform> Platforms { get; private set; } public bool IsCompatibleWith(T device) { return this.Platforms.Contains(device.Platform); // <- this is type-checking! } } Then: abstract class CaptureDevice : ADevice<CaptureDevice> { public CaptureDevice(CaptureDevice device, string filename) : base(device, filename) { } // Or (But still same comment) public CaptureDevice(CaptureDevice device) : base(device, defaultFilename) { } } Same for SensorDevice And instead of the Enum, you can create a simple class for the moment as: public class Platform { public Platform(string name) { Name = name; } public string Name { get; } }
unknown
d2012
train
In your manifest file, you have given permisssion for potrait and landscape, So you have avoid that, instead of that do it in your activity.
unknown
d2013
train
I said in a comment, it's probably easier to simply color cells to look like buttons and have the users click on a cell to send the emails - then you can simply use the offset for the particular row, but if you insist on using command buttons, it's quite simple. Take your current code and put it in a new subroutine that accepts a range parameter. Then, add your buttons, and link each one to its own code with a different range. Option Explicit Private Sub CommandButton3_Click() SendEmail Range("A3") End Sub Private Sub CommandButton4_Click() SendEmail Range("A4") End Sub Private Sub CommandButton5_Click() SendEmail Range("A5") End Sub `... Sub SendEmail(TheRange as Range) On Error GoTo ErrHandler ' SET Outlook APPLICATION OBJECT. Dim objOutlook As Object Set objOutlook = CreateObject("Outlook.Application") ' CREATE EMAIL OBJECT. Dim objEmail As Object Set objEmail = objOutlook.CreateItem(olMailItem) With objEmail .to = "[email address].com" .Subject = TheRange 'Change this line .Body = "[Message]" .Send ' SEND THE MESSAGE. End With ' CLEAR. Set objEmail = Nothing: Set objOutlook = Nothing ErrHandler: End Sub If you prefer instead to use the SelectionChanged event, you can do it like this. Then, you can just update [C4:C8] if you want to add any more "buttons" Private Sub Worksheet_SelectionChange(ByVal Target As Range) If Target.CountLarge > 1 Then Exit Sub If Not Intersect(Target, [C4:C8]) Is Nothing Then SendEmail Range("A" & Target.Row) 'Optionally select the subject we sent so we can re-click 'You can choose any other cell not in our event range Range("A" & Target.Row).Select End If End Sub
unknown
d2014
train
I'll assume that you subclassed BaseView to create your admin view and that you are using Flask-login. Then override the is_accessible method in your view class, to check the current user's quality: from flask.ext.admin.base import BaseView from flask.ext.login import current_user class MyView(BaseView): def is_accessible(self): return current_user.testlevel == 'admin' Hope this helps!
unknown
d2015
train
If i understand correctly, you want to get something similar to from native android project: public class MyApp extends android.app.Application { private static MyApp instance; public MyApp() { instance = this; } public static Context getContext() { return instance; } } Is that the context you need? If yes, then no - you cant get and access it directly. But, you can write a plugin, that will pass required parameters from and to it that will manipulate the context in the native code.
unknown
d2016
train
As far as I know, you can't do that in typescript. Typescript has the concept of declaration merging, which is what allows us to extend types other people wrote, and you can merge interface and namespaces, but not classes. Look here. If the @types/cropperjs would have been written using interfaces, you could have extended that interface using your own declaration. Here is an ugly hack you can do for now: import * as Cropper from 'cropperjs'; interface MyCropper extends Cropper { scale(scaleX: number, scaleY?: number): void; } function CreateCropper(dom: HTMLImageElement, options: Cropper.CropperOptions): MyCropper { return new Cropper(dom, options) as MyCropper; } casting is always ugly, but at least you hide it in one place, I think it's reasonable... A: Just wanted to add another possible "solution". I say "solution" because it's in my opinion quite ugly but then again it's a workaround. After seeing and reading (see Aviad Hadad's answer) that class merging is not possible and read about typescripts node module resolution Basically if you import an non-relative path like import * as Cropper from 'cropperjs typescript will look for the appropriate files in a folder named node_modules and it starts in the directory in which the file with the import statement resides. It then traverses up (example taken from the typescript documentation) * */root/src/node_modules/moduleB.ts */root/node_modules/moduleB.ts */node_modules/moduleB.ts (I assume that's the global node_modules directory) Since typescript will also look for d.ts files I copied the whole index.d.ts from the @types/cropperjs package, renamed it to cropperjs.d.ts and put it in a folder named /root/src/node_modules. (and added the missing method) if you trace the resolution with tsc --traceResolution you'll see that typescript will take the d.ts file from the custom node_modules directory. The advantage with this solution is that you don't have to touch your code. As soon as @types/cropperjs has updated the missing method you can just delete your custom node_modules directory and everything will still work. Disadvantage is you have to copy and paste code around.
unknown
d2017
train
Sometimes we've had to add DoEvents when sending messages like this in our VB app hosted on Citrix. See if this works for you: Private Declare Auto Function SendMessage Lib "user32.dll" (ByVal hWnd As IntPtr, ByVal msg As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr Private Sub DropDownCalendar(ctl As DateTimePicker) Const WM_LBUTTONDOWN = &H201 Const WM_LBUTTONUP = &H202 If ctl Is Nothing Then Exit Sub End If ctl.Select() Dim lParam = (ctl.Width - 10) + (CInt(ctl.Height / 2) * &H10000) 'click down, and show the calendar SendMessage(ctl.Handle, WM_LBUTTONDOWN, CType(1, IntPtr), CType(lParam, IntPtr)) Application.DoEvents() 'Click-up, and activate the calendar (without this the calendar is shown, but is not active, and doesn't work as expected) SendMessage(ctl.Handle, WM_LBUTTONUP, CType(1, IntPtr), CType(lParam, IntPtr)) End Sub Private Sub dteDate_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles dteDate.KeyDown Try If e.KeyCode = Keys.Delete Then CType(sender, DateTimePicker).CustomFormat = " " e.Handled = True ElseIf e.KeyCode <> Keys.Tab And e.KeyCode <> Keys.ShiftKey Then DropDownCalendar(CType(sender, DateTimePicker)) End If Catch ex As Exception MsgBox(ex.Message) End Try End Sub
unknown
d2018
train
This thread helped me: View controller responds to app delegate notifications in iOS 12 but not in iOS 13 Objective C: if (@available(iOS 13.0, *)) { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillResignActive:) name:UISceneWillDeactivateNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidBecomeActive:) name:UISceneDidActivateNotification object:nil]; } else { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil]; [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(appDidBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil]; } A: Application and scene lifecycle is not the same thing! In my opinion, disabling calls of application state change methods (as well as sending application state change notifications on change the state of each scene) is a mistake, even though there was an understandable intention to force programmers to adapt to the new scenes lifecycle. Here is a scene delegate template restoring the expected calls of application state change methods of the application delegate: @available(iOS 13.0, *) class SceneDelegate: UIResponder, UIWindowSceneDelegate { func sceneWillResignActive(_ scene: UIScene) { if !UIApplication.shared.connectedScenes.contains(where: { $0.activationState == .foregroundActive && $0 != scene }) { UIApplication.shared.delegate?.applicationWillResignActive?(.shared) } } func sceneDidEnterBackground(_ scene: UIScene) { if !UIApplication.shared.connectedScenes.contains(where: { $0.activationState == .foregroundActive || $0.activationState == .foregroundInactive }) { UIApplication.shared.delegate?.applicationDidEnterBackground?(.shared) } } func sceneWillEnterForeground(_ scene: UIScene) { if !UIApplication.shared.connectedScenes.contains(where: { $0.activationState == .foregroundActive || $0.activationState == .foregroundInactive }) { UIApplication.shared.delegate?.applicationWillEnterForeground?(.shared) } } func sceneDidBecomeActive(_ scene: UIScene) { if !UIApplication.shared.connectedScenes.contains(where: { $0.activationState == .foregroundActive && $0 != scene }) { UIApplication.shared.delegate?.applicationDidBecomeActive?(.shared) } } } SceneDelegate.swift A: iOS 13 has a new way of sending app lifecycle events. Instead of coming through the UIApplicationDelegate they come through the UIWindowSceneDelegate which is a UISceneDelegate sub-protocol. UISceneDelegate has the important delegate methods. This change is to support multiple windows in iOS 13. There's more information in WWDC 2019 session 212 "Introducing Multiple Windows on iPad". The technical information starts at around 14:30 and is presented by a man with very sparkly high-tops. The shorter session 258 Architecting Your App for Multiple Windows also has a great introduction to what's changed. Here's how it works: If you have an "Application Scene Manifest" in your Info.plist and your app delegate has a configurationForConnectingSceneSession method, the UIApplication won't send background and foreground lifecycle messages to your app delegate. That means the code in these methods won't run: * *applicationDidBecomeActive *applicationWillResignActive *applicationDidEnterBackground *applicationWillEnterForeground The app delegate will still receive the willFinishLaunchingWithOptions: and didFinishLaunchingWithOptions: method calls so any code in those methods will work as before. If you want the old behaviour back you need to * *Delete the "Application Scene Manifest" entry from the app's Info.plist *Comment or delete the application:configurationForConnectingSceneSession:options: method (or the Swift application(_:configurationForConnecting:options:)function) *Add the window property back to your app delegate (@property (strong, nonatomic) UIWindow *window;) Alternatively, open the SceneDelegate file that Xcode made and use the new lifecycle methods in there: - (void)sceneDidBecomeActive:(UIScene *)scene { } - (void)sceneWillResignActive:(UIScene *)scene { } ... etc It's possible to use the new UIScene lifecycle stuff without adopting multiple window support by setting "Enable Multiple Windows" ("UIApplicationSupportsMultipleScenes") to "NO" in the Info.plist (this is the default for new projects). This way you can start adopting the new API in smaller steps. You can see that the scene delegate method names are a close match for the app delegate ones. One confusing thing is that the app delegate methods aren't deprecated so you won't get a warning if you have both app delegate and scene delegate methods in place but only one will be called. Other things that UISceneDelegate takes over are user activities (continueUserActivity: etc), state restoration (stateRestorationActivityForScene: etc), status bar questions and opening URLs. (I'm not sure if these replace the app delegate methods). It also has analogous notifications for the lifecycle events (like UISceneWillDeactivateNotification). From the WWDC Session, some images for you: The function equivalents for Swift: The class responsibilities:
unknown
d2019
train
If I understand your question correctly, this is what you wanted to achieve? Assuming your code works properly just that the if statement is wrong/incorrect. <div class="row-fullsize archive-header"> <?php $category_header_src = woocommerce_get_header_image_url(); ?> <?php if( $category_header_src ) : ?> <div class="small-12 large-6 columns"> <?php echo '<div class="woocommerce_category_header_image"><img src="' . $category_header_src . '" /></div>'; ?> </div> <?php endif; ?> <div class="small-12 large-6 columns"> <div class="hd-woocom-description"> <div class="hd-woo-content"> <h1><?php echo get_term_meta( get_queried_object_id(), 'wh_meta_title', true); ?></h1> <p><?php echo get_term_meta( get_queried_object_id(), 'wh_meta_desc', true); ?></p> </div> </div> </div> </div> Thanks everybody for assisting me with this. I ended up coding it a different way. It's not clean but it works until I can figure out a cleaner way to do it. Appreciate all the help. <?php $category_header_src = woocommerce_get_header_image_url(); if( $category_header_src != "" ) { echo '<div class="row-fullsize archive-header">'; echo '<div class="small-12 large-6 columns">'; echo '<div class="woocommerce_category_header_image"><img src="'.$category_header_src.'" /></div>'; echo '</div>'; echo '<div class="small-12 large-6 columns">'; echo '<div class="hd-woocom-description">'; echo '<div class="hd-woo-content">'; echo '<h1>',esc_attr ( get_term_meta( get_queried_object_id(), 'wh_meta_title', true )),'</h1>'; echo '<p>', esc_attr( get_term_meta( get_queried_object_id(), 'wh_meta_desc', true )),'</p>'; echo '<p><?php echo $productCatMetaDesc = get_term_meta( get_queried_object_id(), wh_meta_desc, true); ?></p>'; echo '</div></div></div></div>'; } ?>
unknown
d2020
train
simply use Object.values() with Array.reudce() to merge objects and then get the values: var arr = [{ item: { id: 1, name: "Abc" }, amount: 1 }, { item: { id: 1, name: "Abc" }, amount: 2 }, { item: { id: 2, name: "Abc" }, amount: 2 },{ item: { id: 1, name: "Abc" }, amount: 2 }]; var result = Object.values(arr.reduce((a,curr)=>{ if(!a[curr.item.id]) a[curr.item.id] = Object.assign({},curr); // Object.assign() is used so that the original element(object) is not mutated. else a[curr.item.id].amount += curr.amount; return a; },{})); console.log(result); A: used map to catch em all :D var arr = [{ item: { id: 1, name: "Abc" }, amount: 1 }, { item: { id: 1, name: "Abc" }, amount: 2 }, { item: { id: 2, name: "Abc" }, amount: 2 },{ item: { id: 1, name: "Abc" }, amount: 2 }]; var res = {}; arr.map((e) => { if(!res[e.item.id]) res[e.item.id] = Object.assign({},e); // clone, credits to: @amrender singh else res[e.item.id].amount += e.amount; }); console.log(Object.values(res));
unknown
d2021
train
.npmrc First, you need to configure your access in a local .npmrc file. You can put this file in your source root folder. always-auth = true # First, set a different registry URL for your scope @myscope:registry=https://company.jfrog.io/artifactory/api/npm/my-npm-registry/ # Then, for this scope, you need to set the token //company.jfrog.io/artifactory/api/npm/my-npm-registry/:_auth = {{your token - see below}} Token You need to get the NPM Token from Artifactory (note it isn't your API Key. * *Get your Artifactory API Key from your Artifactory profile: https://company.jfrog.io/ui/admin/artifactory/user_profile *Run the next command on your Linux terminal: curl -u {{ ARTIFACTORY_USERNAME }}:{{ ARTIFACTORY_API_KEY }} https://company.jfrog.io/artifactory/api/npm/auth/ * *Powershell: $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f {{ ARTIFACTORY_USERNAME }},{{ ARTIFACTORY_API_KEY }}))) Invoke-RestMethod -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} https://company.jfrog.io/artifactory/api/npm/auth/ *You should receive this: _auth = {{ YOUR_NPM_TOKEN }} always-auth = true *So now you can take this Token and put it in the .npmrc file above. Github Actions How to do all this in Github Actions? * *First, save your Jfrog username and API Key in Github Secrets: JFROG_USER & JFROG_PAT. *And you can add the next step to your workflow, after checkout and before yarn/npm install: - name: npm token run: | echo "@myscope:registry=https://company.jfrog.io/artifactory/api/npm/my-npm-registry/" > .npmrc echo "//company.jfrog.io/artifactory/api/npm/my-npm-registry/:$(curl -u ${{ secrets.JFROG_USER }}:${{ secrets.JFROG_PAT }} https://company.jfrog.io/artifactory/api/npm/auth/)" >> .npmrc
unknown
d2022
train
Does this work? def get_layer(request): #this url will return png image url='https://example.com/geoserver/layer/wms?.......' r = requests.get(url) return HttpResponse(r.content, content_type="image/png")
unknown
d2023
train
I don't have enough reputation to comment on your very helpful post, but wanted to add that the public schema by default gives full access to the PUBLIC role (implicit role that all users belong to). So you would first need to revoke this access. This can be done in pgAdmin in the Security tab of the schema properties dialog, or with the SQL command REVOKE CREATE ON SCHEMA public FROM PUBLIC; See also: * *Issue creating read-only user in PostgreSQL that results in user with greater permission with public schema *PostgreSQL - Who or what is the "PUBLIC" role?
unknown
d2024
train
The script will timeout. You need to set it so that it won't timeout using set_time_limit. A: I wouldn't do this I would either use a cron (that is a link) job if it is a regular task or an at (that is a link) job if the job is added at the run time of your script. cron allows you to run a recurring job every day at 1pm for example whereas at allows you to schedule a job to run once for now +1day for example. I have written a PHP 5.3 wrapper for the at queue if you choose to go down that route. It is available on GitHub https://github.com/treffynnon/PHP-at-Job-Queue-Wrapper A: The main problem with using PHP this way is, in my experience, not web server timeouts (there are ways to handle that with difficulty varying on the server and the platform) but memory leaks. Straightforward PHP code tends to leak a lot of memory; most of the scripts I wrote were able to do hundreds of times as many work after I did some analysis and placed some unsets. And I was never able to prevent all the leaks this way. I'm also told there are memory leaks in the standard library, which, if true, makes it impossible to write daemons that would run for a long time in loops. A: There is also time_sleep_until(). Maybe more useful to wake up on a specific time... A: If you access the script through a web browser, it will be terminated after 30 seconds. If you start the PHP script on the command line, this could work. A: It would work, but your "startup time" will be subject to drift. Let's say your job takes 10 seconds to run, then sleeps 86400, runs another 10, sleeps 86400, etc.. You start it exactly at midnight on day 1. On Day 2 it'll run at 12:00:10am, on day 3 it's 12:00:20am, etc... You can do some fancy math internally to figure out how long the run took, and subtract that from the next sleep call, but at the point, why not use cron? With cron the script will exit after each run, cleaning up memory and resources used. With your sleep method, you'll have to be VERY careful that you're not leaking resources somewhere, or things will eventually grind to a halt. A: I had a similar problem before and found a php cron parsing class that will allow you to execute php similar to running crons. You can tie it to a commonly accessed script on your site if you don't have access to run crons directly. I actually use this script as part of a larger cron job script: * *a cron job runs every hour *an xml file for each sub-cron with a cron-like time component(i.e.- * */2 * * * php /home..) *the sub-cron script that will run if the current time meets the criteria of the sub-cron time component *a user interface is setup so that I don't have to manually add/remove sub-crons from the main cron The cronParser class is here. A: Many correct answers, but: Using sleep() means your script keeps running, and keeps using memory. Raising the default timeout of 30s will work, but again, this is bad idea. I suggest you use crontasks. A: This is why legitimate cron jobs were invented. Just use crontab. Using a PHP script to do it will be EXTRAORDINARILY unreliable, buggy, and poorly timed. Hope this is insightful.
unknown
d2025
train
Have you imported #import "TabContainerView.h" in controller 2 .h file.
unknown
d2026
train
Which will typically have better running time, multiple if blocks or a single if/else block? This is largely irrelevant as the semantics are different. Now, if the goal is comparing the case of if (a) { .. } else if (b) { .. } else { .. } with if (a) { return } if (b) { return } return where no statements follow the conditional then they are the same and the compiler (in the case of a language like C) can optimize them equivalently. A: Always go for if else if... when you know only one of the condition is to be executed, Writing multiple if's will make the compiler to check for each and every condition even when the first condition is met which will have a performance overhead, multiple if's can be used when u want to check and perform multiple operations based on certain condition A: The if/else approach is faster, because it will skip evaluating the following conditions after one test succeeds. However, the two forms are only equivalent if the conditions are mutually exclusive. If you just mindlessly convert one form into the other, you will introduce bugs. Make sure that you get the logic right.
unknown
d2027
train
Okay. I don't know if you managed to solve your problem but there seems to be a couple things wrong with your code. First in this code block in the beginning: Private int currentX =getWidth()/2; private int currentY =getHeight()/2; private boolean condition = false; private boolean position = false; Random rand = new Random(); int randomX=rand.nextInt(180) + 20; int randomY =rand.nextInt(250) + 20; ^I am sure this does not compile, you can't have function calls when declaring header variables. Second if((condition==false)&&(position==false)) { currentY -= 5 ; } if((condition==false)&&(position==true)) { currentY += 5 ; } if((condition==true)&&(position==false)) { currentX -= 5 ; } if((condition==true)&&(position==true)) { currentX += 5 ; } } }, 50, 50); } Your block coding style is horrible and hard to read. http://en.wikipedia.org/wiki/Programming_style#Indentation has a good guide on mastering this, read it! This applies to your switch/case statements too! Lastly your question: private void food(){ Random rand = new Random(); int randomX=rand.nextInt(150) + 20; int randomY=rand.nextInt(250) + 20; } ^ Just generates random numbers, but doesn't do anything with them. I am guessing you meant: private void food(){ Random rand = new Random(); randomX=rand.nextInt(150) + 20; randomY=rand.nextInt(250) + 20; } which sets the classes global randomX and randomY to new values. This doesn't help though since you don't actually call the Food() function anywhere in this class! And considering it is "Private" and can only be used by this class that must be an error. tl;dr You need to study programming some more, but it is a good effort. I will help you more in the comments if you like. If my answer helped, please accept it. Fenix
unknown
d2028
train
You can do like this: <?php foreach($dbInfo as $image): ?> <ul class="thumbnails"> <li class="span3"> <div class="thumbnail"> <img src="<?php echo $image['full_path']; ?>"/> <h3><?php echo $image['image_name']; ?></h3> <p><?php echo $image['image_type']; ?></p> <p><?php echo $image['image_size']; ?></p> <p><?php echo $image['image_dimensions']; ?></p> </div> </li> <?php endforeach; ?>
unknown
d2029
train
No, since you have people_idpeople as FK in Registration table; you need to provide that information as well else you will see the error you are facing currently. Your data should look like (Example) Email,Full Name,Country,Date Registered,idpeople [email protected],Carley Bahringer,Papua New Guinea,1987-10-03 22:09:54, 1
unknown
d2030
train
Yes, With olly open and debugging a certain program, go to View tab>Memory or Alt+M then, find the memory address (first you have to choose the memory part of the program like .data or .bss) and then click on the address (or addresses selecting multiple with Shift) with the right mouse button and hover to Breakpoint then you'll be able to choose the to break the program when it writes or reads the address A good thing to do is first find the address on cheatEngine then use the breakpoint on ollydbg.
unknown
d2031
train
controlList2 = Nothing There's your failure. You're specifically setting the list to null, then trying to use it. A: You are setting it to Nothing which is null controlList2 = Nothing
unknown
d2032
train
Best practice , use inline style on all elements. It's not just outlook, gmail has similar issues ( security reasons ) A: It is always a good practice when making a mailer always use inline style. All Outlook versions and others like gmail, yahoo, hotmail have a good support for inline style.
unknown
d2033
train
The phonegap-googlemaps-plugin is not subjected by <access origin="*" />, because the Google Maps SDK for iOS connects to the internet directly. Typically the bundle identifier and the API key are mismatch. Google Maps iOS SDK Integration not loading maps Is there any error message in Xcode?
unknown
d2034
train
There is a way to modify the cursor, but it comes with a catch. The feature is only available in the Sublime Text "4" alpha builds, which you can only run if you're a registered user and willing to run alpha-level software, which means occasional random crashes and features not working right as the bugs get ironed out. You're also committing to upgrading to each new build as it's released and reporting issues back to the dev team. If you're interested, start at the Sublime Discord server here. The new builds are posted in #announcements. You say you're a relatively new user, so I would not recommend running the alpha builds at this time, especially if it's just for this one feature.
unknown
d2035
train
Yes you can call other asynctask from the onpost method.
unknown
d2036
train
because of scope definition, you are just adding elements to the parameter List<String> list in public void addElement(String string, List<String> list) { list.add(string); } A: It's working fine if you just un-comment the while loop: Output: new element1 new element2 new element3 new element4 new element5 new element6 new element7 new element8 new element9 new element10 Code: package collectionwaliclass; import java.util.ArrayList; import java.util.List; public class ArraylistWaliClass { public static List<String> list= new ArrayList<>() ; public static void main(String[] args) { // TODO Auto-generated method stub //list= ; ArraylistWaliClass arraylistWaliClass= new ArraylistWaliClass(); //adding the element to the existing list int counter=0; while(counter++<10) { arraylistWaliClass.addElement("new element"+counter, list); } //traversing the list in the arryaList list.forEach((x)-> { System.out.println(x); }); //deleting the list from the arraylist } public void addElement(String string, List<String> list) { list.add(string); } }
unknown
d2037
train
Just use: ViewContext.Controller.GetType().Name This will give you the whole Controller's Name A: Create base class for all controllers and put here name attribute: public abstract class MyBaseController : Controller { public abstract string Name { get; } } In view @{ var controller = ViewContext.Controller as MyBaseController; if (controller != null) { @controller.Name } } Controller example public class SampleController: MyBaseController { public override string Name { get { return "Sample"; } } A: You are still in the context of your CategoryController even though you're loading a PartialView from your Views/News folder. A: I have put this in my partial view: @HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString() in the same kind of situation you describe, and it shows the controller described in the URL (Category for you, Product for me), instead of the actual location of the partial view. So use this alert instead: alert('@HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString()'); A: Other way to get current Controller name in View @ViewContext.Controller.ValueProvider.GetValue("controller").RawValue A: I do it like this: @ViewContext.RouteData.Values["controller"] A: You can use any of the below code to get the controller name @HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString(); If you are using MVC 3 you can use @ViewContext.Controller.ValueProvider.GetValue("controller").RawValue A: For anyone looking for this nowadays (latest versions) of ASP.NET Core MVC, you can use: @Context.Request.RouteValues["controller"].ToString()
unknown
d2038
train
So Slack has Open APIs for interacting with the Slack App. Here Since you want to monitor the conversations so Events APIs and Conversations APIs would help you to notify as well as capture the conversations. conversations.history will help you to fetch the messages within public or private channels. Since you want to intervene in the conversation then I suggest using chatbot, which will provide a suitable way to intervene and respond to some particular events. Bot Users A: Dialogflow has an sample on how to do this: https://github.com/dialogflow/agent-human-handoff-nodejs You'll have to build you own front end for the human to override the response and call the Dialogflow query API to integrate: Slack <--> Front end w/human override <--> Dialogflow's query API <--> Dialogflow Agent A: Yes, it's possible. Just login to DialogFlow with your Google credentials, then on the left sidebar you can see the Integrations Tab. Click on it. You will find a bunch of different integrations for line, telegram, Twilio, kik, Viber, Skype and a lot more. Click on Slack. It will ask you for some details for connecting with endpoints such as client ID, token, client secret. You can get it from the Slack API. You can also check the Slack API integration link here. After everything is properly set up, click the "Test in Slack" button in the DialogFlow Slack integration.
unknown
d2039
train
I would say this is not good practice. As you pointed out, this would confuse the roles of Assertions and Exceptions. The topic is somewhat common, this link has a lot of nice ideas. By combining exceptions and assertions, you end up with a conundrum... is the class an exception helper, or is it an assertion helper? Since assertions are compiled out of the Release build, would your assertion class even work in Release mode? It would be non-conventional to expect an Assertion class to work in release mode. So, would your Assertion class throw the exceptions in Release mode? There lies the confusion. By convention, I would say the exception should not be thrown when using an Assert Class (in Release mode) because it is understood that assertions are not part of a Release build. The code above should not make 'Exception Handling' easier nor harder, it should be the same since the exception handling depends on what is catching the exception in the stack. I think you are really asking if it makes throwing Exceptions easier or harder. I think it could make dealing with your exceptions easier. I also think it is probably unnecessary. What is most important is that you are consistent with this... if you are going to use an ExceptionHelper class, then embrace it and be consistent... otherwise it is all done for naught. Debug.Assert: * *Use liberally *Use whenever there is a chance that an assumption could be wrong *Used to help other programmers, not necessarily the end user *Should never affect the flow of the program *Not compiled in Release builds *Always yells 'BLOODY MURDER' when something unexpected happens, this is a good thing *many other reasons, I'm not aiming for a complete list Exceptions: * *Can be caused for any reason, it is not always known why *Always in debug or release builds *Pertains to how the application flows *Some exception handlers may silently swallow an exception and you would never know it *many other reasons, I'm not aiming for a complete list A: To be honest, I'm not sure a custom Assert class would help clarify anything, and I'm not sure you should be worried about two lines need to check and throw an exception vs one line. Your current way of checking parameters is the way we do things as well. In fact, a majority of public methods around our code look something like this: public void PerformStringOperation(string str1, string str2) { if(string.IsNullOrEmpty(string1)) throw new ArgumentNullException(...); if(string.IsNullOrEmpty(string2)) throw new ArgumentNullException(...); // perform string operation(s) here } We have never found it too encumbering, and I'm sure it is the exact solution used by many teams.
unknown
d2040
train
You have a misplaced $ anchor in your regex. Use this rule: <IfModule mod_rewrite.c> Options -MultiViews RewriteEngine on RewriteRule ^page/([a-z0-9:-]+)\.html$ page.php?partid=$1 [L,QSA,NC] </IfModule>
unknown
d2041
train
A quick answer to your question will be that the thenApply line doesn't compile because the result from the line above (map(CompletableFuture::supplyAsync)) returns Stream<CompletableFuture<Cake>> and not CompletableFuture<Cake>. You'll need to do something like map(cakeFuture -> cakeFuture.thenApply(new FrostCakes())). But I think there's a more important point that needs to be made. If your examples are meant for educational purposes, I'd recommend investing another day or two in preparation, and more specifically in reading about the fundamentals of stream operations and CompletableFuture. This way you'll feel much more confident when you get to present your material, but more importantly, you won't be presenting less than perfect code examples that can potentially harm your colleagues/students notion about how can streams and CompletableFutures (and even decorators) be used. I'll point out some of the things that I think need to be redone in your examples. * *Manually setting the parallelism level of the common ForkJoinPool is not always a good idea. By default, it uses the number of processors, as returned by Runtime.availableProcessors() which is a pretty good default. You need to have a pretty good reason to change it to something more than that, because in most cases you'll just be introducing unnecessary overhead from scheduling and maintenance of redundant threads. And to change it to the number of tasks you're planning to fire is almost always a bad idea (explanation omitted). *Your stream examples perform a couple of stream operations, then terminate with a collection, and then a stream operation is performed on the collected list. They can be rewritten without the collection to list, by directly applying the forEach on the stream returned by the last mapping, and arguably this will be a better demonstration of the fluent programming model using Java 8 streams. *Your examples also don't perform their operations in parallel. You can fix that easily by adding .parallel() after IntStream.range(), but unless you remove the redundant collection to list from above, you won't be able to see that you've done something in parallel just by printing the list contents with forEach. *Your classes implementing the java.util.function interfaces are not very idiomatic. I would argue that they should be replaced with the corresponding lambda expressions even though in your case this could result in a mouthful lambda in lambda, unless your second example is slightly rewritten. *CompletableFuture.thenAccept returns a CompletableFuture<Void>, so in this stage of your stream processing you lose the references to the created, frosted and decorated cakes. This can be OK if you don't care about them, or if you log something about them in the decoration logic, but your example can easily mislead people that the finally collected list of CompletableFutures can be used to reach to the cakes (after all, who doesn't want to have his cake and eat it too). So your first example can look something like IntStream.range(0, NUM_OF_CAKES) .parallel() .mapToObj(Cake::new) .map(Frosted::new) .map(Decorated::new) .forEach(System.out::println); Notice how the cake IDs are not ordered because of the parallel execution.
unknown
d2042
train
What you need to do is start and end the keyframes at a translateX of 0%, add in extra keyframes to handle the actual animation. In the following example, I've added an extra keyframe point at 50% that goes to a translateX offset of 25%. This results in a 'smooth' transition, but does cause the bubbles to stop briefly once returning to their original position. You may want to consider adding extra points in the keyframe animation, each with their own unique translateX offsets :) $(document).ready(function() { var bubbles = $('.bubble') function animate_bubbles() { bubbles.each(function(index) { $(this).css('animation-delay', `${index * 0.3}s`) $(this).addClass('bubble-active') }) } animate_bubbles() }); html, body { height: 100%; } #page-wrapper { box-sizing: border-box; padding: 10%; background: black; height: 100%; display: flex; flex-direction: row; justify-content: space-around; align-items: center; flex-wrap: wrap; } .bubble { background: skyblue; border-radius: 50%; width: 5%; margin-right: 5%; } .bubble:before { content: ''; display: block; padding-top: 100%; } .bubble-active { animation: bubble-animation 3s infinite linear; } @keyframes bubble-animation { 0% { transform: rotate(0deg) translateX(0%) rotate(0deg); } 50% { transform: rotate(360deg) translateX(25%) rotate(-360deg); } 100% { transform: rotate(360deg) translateX(0%) rotate(-360deg); } } <!doctype html> <html lang='en'> <head> <meta charset='utf-8' /> <meta name='viewport' content='width=device-width, initial-scale=1.0'> <link href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.css" rel="stylesheet" /> <link rel='stylesheet' href='test.css'> </head> <body> <div id='page-wrapper'> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> </div> <script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script> <script src='test.js'></script> </body> </html> Hope this helps! :) A: They are moving to the right like that because the start of the animation immediately tells the bubbles to translateX(25%). If you load the page with the transform already applied, it works like you'd want. See the updated snippet below with just one extra line of CSS. $(document).ready(function() { var bubbles = $('.bubble') function animate_bubbles() { bubbles.each(function(index) { $(this).css( 'animation-delay', `${index * 0.3}s` ) $(this).addClass('bubble-active') }) } animate_bubbles() }); html, body { height: 100%; } #page-wrapper { box-sizing: border-box; padding: 10%; background: black; height: 100%; display: flex; flex-direction: row; justify-content: space-around; align-items: center; flex-wrap: wrap; } .bubble { background: skyblue; border-radius: 50%; width: 5%; margin-right: 5%; transform: rotate(0deg) translateX(25%) rotate(0deg); } .bubble:before { content: ''; display: block; padding-top: 100%; } .bubble-active { animation: bubble-animation 3s infinite linear; } @keyframes bubble-animation { from { transform: rotate(0deg) translateX(25%) rotate(0deg); } to { transform: rotate(360deg) translateX(25%) rotate(-360deg); } } <!doctype html> <html lang='en'> <head> <meta charset='utf-8' /> <meta name='viewport' content='width=device-width, initial-scale=1.0'> <link href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.css" rel="stylesheet"/> <link rel='stylesheet' href='test.css'> </head> <body> <div id='page-wrapper'> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> <div class='bubble'></div> </div> <script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script> <script src='test.js'></script> </body> </html>
unknown
d2043
train
Try this in your activity: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (!isAccessGranted()) { Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS); startActivity(intent); } } private boolean isAccessGranted() { try { PackageManager packageManager = getPackageManager(); ApplicationInfo applicationInfo = packageManager.getApplicationInfo(getPackageName(), 0); AppOpsManager appOpsManager = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE); int mode = appOpsManager.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, applicationInfo.uid, applicationInfo.packageName); return (mode == AppOpsManager.MODE_ALLOWED); } catch (PackageManager.NameNotFoundException e) { return false; } } A: try this code i hope help you if (Build.VERSION.SDK_INT >= 21) { UsageStatsManager mUsageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE); long time = System.currentTimeMillis(); List stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 10, time); if (stats == null || stats.isEmpty()) { Intent intent = new Intent(); intent.setAction(Settings.ACTION_USAGE_ACCESS_SETTINGS); context.startActivity(intent); } } A: Add this permission in your manifest uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" and continue with this answer https://stackoverflow.com/a/39278489/16126283
unknown
d2044
train
Do yourself and your sanity a favor and learn how to use GPLex and GPPG. They are the closest thing that C# has to Lex and Yacc (or Flex and Bison, if you prefer) which are the proper tools for this job. Regular expressions are great tools for performing robust string matching, but when you want to match structures of strings that's when you need a "grammar". This is what a parser is for. GPLex takes a bunch of regular expressions and generates a super-fast lexer. GPPG takes the grammar you write and generates a super-fast parser. Trust me, learn how to use these tools ... or any other tools like them. You'll be glad you did. A: Here is a complete rework of the regex in C#. Assumptions : (tell me if one of them is false or all are false) * *An INI file section can only have key/value pair lines in its body *In an non INI file section, function calls can't have any parameters Regex flags : RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled | RegexOptions.Singleline Input test: const string dataFileScr = @" Start 0 { Next = 1 Author = rk Date = 2011-03-10 /* Description = simple */ } PZ 11 { IA_return() } GDC 7 { Message = 6 Message = 7 Message = 8 Message = 8 RepeatCount = 2 ErrorMessage = 10 ErrorMessage = 11 onKey[5] = 6 onKey[6] = 4 onKey[9] = 11 } [Section1] key1 = value1 key2 = value2 [Section2] key1 = value1 key2 = value2 "; Reworked regex: const string patternFileScr = @" (?<Section> (?# Start of a non ini file section) (?<SectionName>[\w ]+)\s* (?# Capture section name) { (?# Match but don't capture beginning of section) (?<SectionBody> (?# Capture section body. Section body can be empty) (?<SectionLine>\s* (?# Capture zero or more line(s) in the section body) (?: (?# A line can be either a key/value pair, a comment or a function call) (?<KeyValuePair>(?<Key>[\w\[\]]+)\s*=\s*(?<Value>[\w-]*)) (?# Capture key/value pair. Key and value are sub-captured separately) | (?<Comment>/\*.+?\*/) (?# Capture comment) | (?<FunctionCall>[\w]+\(\)) (?# Capture function call. A function can't have parameters though) )\s* (?# Match but don't capture white characters) )* (?# Zero or more line(s), previously mentionned in comments) ) } (?# Match but don't capture beginning of section) ) | (?<Section> (?# Start of an ini file section) \[(?<SectionName>[\w ]+)\] (?# Capture section name) (?<SectionBody> (?# Capture section body. Section body can be empty) (?<SectionLine> (?# Capture zero or more line(s) in the section body. Only key/value pair allowed.) \s*(?<KeyValuePair>(?<Key>[\w\[\]]+)\s*=\s*(?<Value>[\w-]+))\s* (?# Capture key/value pair. Key and value are sub-captured separately) )* (?# Zero or more line(s), previously mentionned in comments) ) ) "; Discussion The regex is build to match either non INI file sections (1) or INI file section (2). (1) Non-INI file sections These sections are composed by a section name followed by a body enclosed by { and }. The section name con contain either letters, digits or spaces. The section body is composed by zero or more lines. A line can be either a key/value pair (key = value), a comment (/* Here is a comment */) or a function call with no parameters (my_function()). (2) INI file sections These sections are composed by a section name enclosed by [ and ] followed by zero or more key/value pairs. Each pair is on one line. A: # 2. not work for .ini file like Won't work because as stated by your regular expression, an { is required after [Section]. Your regex will match if you have something like this : [Section] { key = value } A: Here is a sample in Perl. Perl doesen't have named capture arrays. Probably because of backtracking. Maybe you can pick something out of the regex though. This assumes there is no nesting of {} bracktes. Edit Never content to leave well enough alone, a revised version is below. use strict; use warnings; my $str = ' Start 0 { Next = 1 Author = rk Date = 2011-03-10 /* Description = simple */ } asdfasdf PZ 11 { IA_return() } [ section 5 ] this = that [ section 6 ] this_ = _that{hello() hhh = bbb} TOC{} GDC 7 { Message = 6 Message = 7 Message = 8 Message = 8 RepeatCount = 2 ErrorMessage = 10 ErrorMessage = 11 onKey[5] = 6 onKey[6] = 4 onKey[9] = 11 } '; use re 'eval'; my $rx = qr/ \s* ( \[ [^\S\n]* )? # Grp 1 optional ini section delimeter '[' (?<Section> \w+ (?:[^\S\n]+ \w+)* ) # Grp 2 'Section' (?(1) [^\S\n]* \] |) # Condition, if we matched '[' then look for ']' \s* (?<Body> # Grp 3 'Body' (for display only) (?(1)| \{ ) # Condition, if we're not a ini section then look for '{' (?{ print "Section: '$+{Section}'\n" }) # SECTION debug print, remove in production (?: # _grp_ \s* # whitespace (?: # _grp_ \/\* .*? \*\/ # some comments | # OR .. # Grp 4 'Key' (tested with print, Perl doesen't have named capture arrays) (?<Key> \w[\w\[\]]* (?:[^\S\n]+ [\w\[\]]+)* ) [^\S\n]* = [^\S\n]* # = (?<Value> [^\n]* ) # Grp 5 'Value' (tested with print) (?{ print " k\/v: '$+{Key}' = '$+{Value}'\n" }) # KEY,VALUE debug print, remove in production | # OR .. (?(1)| [^{}\n]* ) # any chars except newline and [{}] on the condition we're not a ini section ) # _grpend_ \s* # whitespace )* # _grpend_ do 0 or more times (?(1)| \} ) # Condition, if we're not a ini section then look for '}' ) /x; while ($str =~ /$rx/xsg) { print "\n"; print "Body:\n'$+{Body}'\n"; print "=========================================\n"; } __END__ Output Section: 'Start 0' k/v: 'Next' = '1' k/v: 'Author' = 'rk' k/v: 'Date' = '2011-03-10' Body: '{ Next = 1 Author = rk Date = 2011-03-10 /* Description = simple */ }' ========================================= Section: 'PZ 11' Body: '{ IA_return() }' ========================================= Section: 'section 5' k/v: 'this' = 'that' Body: 'this = that ' ========================================= Section: 'section 6' k/v: 'this_' = '_that{hello() hhh = bbb}' Body: 'this_ = _that{hello() hhh = bbb} ' ========================================= Section: 'TOC' Body: '{}' ========================================= Section: 'GDC 7' k/v: 'Message' = '6' k/v: 'Message' = '7' k/v: 'Message' = '8' k/v: 'Message' = '8' k/v: 'RepeatCount' = '2' k/v: 'ErrorMessage' = '10' k/v: 'ErrorMessage' = '11' k/v: 'onKey[5]' = '6' k/v: 'onKey[6]' = '4' k/v: 'onKey[9]' = '11' Body: '{ Message = 6 Message = 7 Message = 8 Message = 8 RepeatCount = 2 ErrorMessage = 10 ErrorMessage = 11 onKey[5] = 6 onKey[6] = 4 onKey[9] = 11 }' =========================================
unknown
d2045
train
It's possible, but there are a lot of variables that need to be taken into consideration, so it's really hard to help without you doing an attempt first. This will only show you where to start, you need to figure out the rest: add_action( 'gform_after_submission', 'post_to_third_party', 10, 2 ); function post_to_third_party( $entry, $form ) { global $woocommerce; // use this to find out $entry output var_dump($entry); // Make sure to add hidden field somewhere in the form with product id and define it here, If you have some other way of defining products in the form you need to make sure product id is returned in the variable below somehow $product_id = rgar( $entry, '12' ); $address = array( 'first_name' => rgar( $entry, '5' ), 'last_name' => rgar( $entry, '2' ), 'company' => rgar( $entry, '3' ), 'email' => rgar( $entry, '4' ), 'phone' => rgar( $entry, '5' ), 'address_1' => rgar( $entry, '6' ), 'address_2' => rgar( $entry, '7' ), 'city' => rgar( $entry, '8' ), 'state' => rgar( $entry, '9' ), 'postcode' => rgar( $entry, '10' ), 'country' => rgar( $entry, '11' ), ); $prices = array( 'totals' => array( 'subtotal' => 0, 'total' => 0, ) ); $order = wc_create_order(); $order->add_product( wc_get_product($product_id), 1, $prices); $order->set_address( $address, 'billing' ); $order->calculate_totals(); $order->update_status("processing", 'Sample Order', TRUE); }
unknown
d2046
train
a typical parameter list for such a function would be: (defun preceders (item vector &key (start 0) (end (length vector)) (test #'eql)) ... ) As you can see it has START and END parameters. TEST is the default comparision function. Use (funcall test item (aref vector i)). Often there is also a KEY parameter... LENGTH is called repeatedly for every recursive call of PRECEDERS. I would do the non-recursive version and move two indexes over the vector: one for the first item and one for the next item. Whenever the next item is EQL to the item you are looking for, then push the first item on to a result list (if it is not member there). For the recursive version, I would write a second function that gets called by PRECEDERS, which takes two index variables starting with 0 and 1, and use that. I would not call POSITION. Usually this function is a local function via LABELS inside PRECEDERS, but to make it a bit easier to write, the helper function can be outside, too. (defun preceders (item vector &key (start 0) (end (length vector)) (test #'eql)) (preceders-aux item vector start end test start (1+ start) nil)) (defun preceders-aux (item vector start end test pos0 pos1 result) (if (>= pos1 end) result ... )) Does that help? Here is the iterative version using LOOP: (defun preceders (item vector &key (start 0) (end (length vector)) (test #'eql)) (let ((result nil)) (loop for i from (1+ start) below end when (funcall test item (aref vector i)) do (pushnew (aref vector (1- i)) result)) (nreverse result))) A: Since you already have a solution that's working, I'll amplifiy Rainer Joswig's solution, mainly to make related stylistic comments. (defun preceders (obj seq &key (start 0) (end (length seq)) (test #'eql)) (%preceders obj seq nil start end test)) The main reason to have separate helper function (which I call %PRECEDERS, a common convention for indicating that a function is "private") is to eliminate the optional argument for the result. Using optional arguments that way in general is fine, but optional and keyword arguments play horribly together, and having both in a single function is a extremely efficient way to create all sorts of hard to debug errors. It's a matter of taste whether to make the helper function global (using DEFUN) or local (using LABELS). I prefer making it global since it means less indentation and easier interactive debugging. YMMV. A possible implementation of the helper function is: (defun %preceders (obj seq result start end test) (let ((pos (position obj seq :start start :end end :test test))) ;; Use a local binding for POS, to make it clear that you want the ;; same thing every time, and to cache the result of a potentially ;; expensive operation. (cond ((null pos) (delete-duplicates (nreverse result) :test test)) ((zerop pos) (%preceders obj seq result (1+ pos) end test)) ;; I like ZEROP better than (= 0 ...). YMMV. (t (%preceders obj seq (cons (elt seq (1- pos)) result) ;; The other little bit of work to make things ;; tail-recursive. (1+ pos) end test))))) Also, after all that, I think I should point out that I also agree with Rainer's advice to do this with an explicit loop instead of recursion, provided that doing it recursively isn't part of the exercise. EDIT: I switched to the more common "%" convention for the helper function. Usually whatever convention you use just augments the fact that you only explicitly export the functions that make up your public interface, but some standard functions and macros use a trailing "*" to indicate variant functionality. I changed things to delete duplicated preceders using the standard DELETE-DUPLICATES function. This has the potential to be much (i.e., exponentially) faster than repeated uses of ADJOIN or PUSHNEW, since it can use a hashed set representation internally, at least for common test functions like EQ, EQL and EQUAL. A: A slightly modofied variant of Rainer's loop version: (defun preceders (item vector &key (start 0) (end (length vector)) (test #'eql)) (delete-duplicates (loop for index from (1+ start) below end for element = (aref vector index) and previous-element = (aref vector (1- index)) then element when (funcall test item element) collect previous-element))) This makes more use of the loop directives, and among other things only accesses each element in the vector once (we keep the previous element in the previous-element variable). A: Answer for your first UPDATE. first question: see this (if (foo) (bar (+ 1 baz)) (bar baz)) That's the same as: (bar (if (foo) (+ 1 baz) baz)) or: (let ((newbaz (if (foo) (+ 1 baz) baz))) (bar newbaz)) Second: Why not start with I = 1 ? See also the iterative version in my other answer... A: The iterative version proposed by Rainer is very nice, it's compact and more efficient since you traverse the sequence only one time; in contrast to the recursive version which calls position at every iteration and thus traverse the sub-sequence every time. (Edit: I'm sorry, I was completely wrong about this last sentence, see Rainer's comment) If a recursive version is needed, another approach is to advance the start until it meets the end, collecting the result along its way. (defun precede (obj vec &key (start 0) (end (length vec)) (test #'eql)) (if (or (null vec) (< end 2)) nil (%precede-recur obj vec start end test '()))) (defun %precede-recur (obj vec start end test result) (let ((next (1+ start))) (if (= next end) (nreverse result) (let ((newresult (if (funcall test obj (aref vec next)) (adjoin (aref vec start) result) result))) (%precede-recur obj vec next end test newresult))))) Of course this is just another way of expressing the loop version. test: [49]> (precede #\a "abracadabra") (#\r #\c #\d) [50]> (precede #\a "this is a long sentence that contains more characters") (#\Space #\h #\t #\r) [51]> (precede #\s "this is a long sentence that contains more characters") (#\i #\Space #\n #\r) Also, I'm interested Robert, did your teacher say why he doesn't like using adjoin or pushnew in a recursive algorithm?
unknown
d2047
train
Use set function with sorted: if sorted(set(y)) == sorted(y): pass Set remove duplicates from given list so its easy to check if your list has duplicates. Sorted its optional but if you give user option to input numbers in other order this will be helpful then. set() sorted() Simpler solution if you don't need sorted use: len(y) != len(set(y)) Its faster because u dont need use sort on both lists. Its return True of False. Check for duplicates in a flat list A: You can check the length of the set of the list and compare with its regular length: l = [1, 3, 32, 4] if len(set(l)) == len(l): pass
unknown
d2048
train
Log in via phpMyAdmin with a MySQL account that has sufficient privileges (like root). If you don't have such account, ask this MySQL server's manager about it.
unknown
d2049
train
The result of the most common encryption algorithms (i.e. AES and RSA) are seemingly random binary values. It means that there is a 50% chance that a single bit is either 0 or 1. This is true for all bits of the ciphertext. 8 bits usually make up a byte. Binary data cannot be represented as text by default, but you can still open the ciphertext in a text editor which might handle it as ASCII and see that some bytes are not printed. Others might be printed and there might even be characters in there that classify as whitespace. A: Your link doesn't match your question. Your link references specifically magnetic stripe data. Magnetic stripes can encode any 7-bit ASCII, which includes whitespace (and explicitly does, for example, for the cardholder's name). The encrypted format does not, because it is hex-encoded, so each character will be '0'-'F'. But the byte 0x20 (SPACE) can certainly exist in encrypted data. It probably won't, since the kind of data that's encrypted on magnetic stripes typically does not include spaces, but it certainly can. But all of this is pointing to a fundamental problem. If you care about whitespace, you are mishandling the data. You need to follow the spec closely when decoding a magnetic stripe, and if you're worrying about whitespace, you're on the wrong road. The link you gave includes some of the ISO standards involved. What precise encoding is performed depends on which track you're reading, and thus which standard applies.
unknown
d2050
train
I configured exactly the versions you mentioned (gridgain-hadoop-os-6.6.2.zip + hadoop-2.2.0) -- the "wordcount" sample works fine. [UPD after question's author log analysis:] Raju, thanks for the detailed logs. The cause of the problem are incorrectly set env variables export HADOOP_MAPRED_HOME=${HADOOP_HOME} export HADOOP_COMMON_HOME=${HADOOP_HOME} export HADOOP_HDFS_HOME=${HADOOP_HOME} You explicitly set all these variables to ${HADOOP_HOME} value, what is wrong. This causes GG to compose incorrect hadoop classpath, as seen from the below GG Node log: +++ HADOOP_PREFIX=/usr/local/hadoop-2.2.0 +++ [[ -z /usr/local/hadoop-2.2.0 ]] +++ '[' -z /usr/local/hadoop-2.2.0 ']' +++ HADOOP_COMMON_HOME=/usr/local/hadoop-2.2.0 +++ HADOOP_HDFS_HOME=/usr/local/hadoop-2.2.0 +++ HADOOP_MAPRED_HOME=/usr/local/hadoop-2.2.0 +++ GRIDGAIN_HADOOP_CLASSPATH='/usr/local/hadoop-2.2.0/lib/*:/usr/local/hadoop-2.2.0/lib/*:/usr/local/hadoop-2.2.0/lib/*' So, to fix the issue please don't set unnecessary env variables. JAVA_HOME and HADOOP_HOME is quite enough, nothing else is needed. A: many thnaks to Ivan, thanks for your help and support, the solution you gave was good to get me out of the problem. The issue was not to set other hadoop related environment variables. this is enough to set. JAVA_HOME , HADOOP_HOME and GRIDGAIN_HOME
unknown
d2051
train
The code for show less should probably (depending on your requirement) be a lot simpler. $scope.hasLessItemsToShow = function() { return pagesShown > 1; }; So, as long as you are showing more than one page of data, you can "go back", or show less.
unknown
d2052
train
My guess is that the proxy declaration is missing the protocol. An URI has to be specified (according to the doc), that contains the protocol (scheme). So this could work: 'proxy' => 'tcp://89.122.180.178:46565'. It might be necessary to remove 'protocol_version' since this may not be required for tcp. Does that work for you? (or have you already solved it? ... ;-)
unknown
d2053
train
In C, you must know the length of the array: there is no language level ".length" to tell you. However, Strings are null-terminated, so standard functions like strlen() can be used. EXAMPLE: #include <stdio.h> #include <string.h> #define MAX_ELEMENTS 10 int main (int argc, char *argv[]) int my_array[MAX_ELEMENTS]; char my_string = "abc"; int i; for (int i=0; i < MAX_ELEMENTS; i++) my_array[i] = i*2; for (int i=0; i < MAX_ELEMENTS); i++) printf ("my_array[%d]=%d\n", i, my_array[i]); for (int i=0; i < strlen(my_string); i++) printf ("my_string[%d]=%c\n", i, my_string[i]); return 0; } A: You can just access the element directly: int SIZE_OF_STRING = 5; char string[SIZE_OF_STRING+1]; string[0] = 'h'; string[1] = 'e'; string[2] = 'l'; string[3] = 'l'; string[4] = 'o'; string[5] = '\0'; int sizeOfstring = strlen(string); for(int i = 0; i < sizeOfstring; i++){ if( str[i] == 'X'){ return 1; } } You can also explicitly use strcmp if you want to compare 2 char arrays. A: for(int i = 0; str[i]; i++){ if (str[i] == 'X') return 1; } A: Java strings hold at their beginning a 4 byte int value that indicates its size. Method length() just reads that value. In C however, string literals are ended with a null termination character \0. So strlen() in C iterates through single chars in string literal until it meets a \0. That's how it gets string's length. If you would like to use a method on string which returns you string's length, you can go with C++ and use a std::string class. It has a size() method for example. Here's a C code for snippet you provide. #include<string.h> /* ... */ size_t len = strlen(str); for(size_t i = 0; i < len; i++){ if (str[i] == 'X') return 1; }
unknown
d2054
train
Declare private LocationManager locationManager; then locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new GeoUpdateHandler()); next create a class GeoUpdateHandler which implements LocationListener and has the function public void onLocationChanged(Location location) { int lat = (int) (location.getLatitude() * 1E6); int lon = (int) (location.getLongitude() * 1E6); String tim = String.format("%d", location.getTime());} A: Here is a simple example of retrieving the location of a user, using the Network Provider // Acquire a reference to the system Location Manager myLocManager = (LocationManager)getSystemService( Context.LOCATION_SERVICE ); // Define a listener that responds to location updates locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { // Return a string representation of the latitude & longitude. Pass it to the textview and update the text String tempLat = ""+location.getLatitude(); String tempLon = ""+location.getLongitude(); tempLat = refineStrg( tempLat ); tempLon = refineStrg( tempLon ); // Store/set lat and long values storeLat_storeLong( tempLat, tempLon ); } @Override public void onProviderDisabled(String arg0) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } }; // The two lines below request location updates from the network location provider myLocManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 0, 0,locationListener ); Remember to include the proper permissions in the manifest file for accessing user location (consult the website I posted in my comment) Finally to retrieve the current time you could use the Calendar or Date class, like so: Calendar cal = Calendar.getInstance(); cal.getTime(); Look here for info on how to use the Date class over the Calendar.
unknown
d2055
train
Spec: For statements: The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next. If a map entry that has not yet been reached is removed during iteration, the corresponding iteration value will not be produced. If a map entry is created during iteration, that entry may be produced during the iteration or may be skipped. The choice may vary for each entry created and from one iteration to the next. If the map is nil, the number of iterations is 0. The spec states that if you add entries to the map you are ranging over, the elements you add may or may not be visited by the loop, and moreover, which is visited is not even deterministic (may change when doing it again). A: You are modifying map you are iterating over. This is the cause.
unknown
d2056
train
You can do it in the Activity file for activity_layout.xml in the following way: View view = findViewById(R.id.left_grid); ImageView image = view.findViewById(R.id.thumbImage); image.setBackgroundResource(R.id.image)); //or whatever you wish to set TextView text = view.findViewById(R.id.issueName); text.setText("Whatever text you want to set); In this way, you can access all the Views in the included layout.
unknown
d2057
train
Try orderBy() with join() like: $memberships = \DB::table("memberships") ->where("company_id", $companyId) ->where(function ($query) { $query->where('end_date', '>=', Carbon::now()->toDateString()) ->orWhereNull('end_date'); }) ->join("customers", "memberships.customer_id", "customers.id") ->select("customers.*", "memberships.*") ->orderBy("customers.lastname", "asc") ->get(); dd($memberships); Let me know if you are still having the issue. Note, code not tested! so you may need to verify by yourself once.
unknown
d2058
train
The problem is I did not use proper version of TensorFlow. I finally got an answer by following this page, which tells me to install apple version Tensorflow and use conda environment, it solves the problem.
unknown
d2059
train
pyc files are stored in the python marshal format. http://daeken.com/python-marshal-format it seems that the only issue is with encoded integers which are automatically downgraded to 32 bit integers when you read the pyc on a 32 bit machine. However the pyc format doesn't include 64bit addresses/offset inside it so the same pyc should run on both 64bit and 32bit interpreters.
unknown
d2060
train
you try to remove 'x' which is a declared as char, x is equal to 120 The .Remove only takes 2 parameters of type int the start and (optional) count to remove from the string. If you pass a char, it will be converted to the integer representation. Meaning if you pass 'x' -> 120 is greater than the string's .Length and that's why it will throw this error! A: Remove takes an int parameter for the index within the string to start removing characters, see msdn. The remove call must automatically convert the char to its ASCII integer index and try to remove the character at that index from the string, it is not trying to remove the character itself. If you just want to remove any cases where x occurs in the string do: "testx".Replace("x",string.Empty); If you want to remove the first index of x in the string do: var value = "testx1x2"; var newValue = value.Remove(value.IndexOf('x'), 1); A: Implicit conversion lets you compile this code since char can be converted to int and no explicit conversion is required. This will also compile and the answer will be 600 (120*5) - char c = 'x'; int i = c; int j = 5; int answer = i * j; From MSDN, implicit conversion is summarized as below - As other's have stated you could use Replace or Remove with valid inputs. A: There is no overload of Remove that takes a char, so the character is implicitly converted to an int and the Remove method tries to use it as an index into the string, which is way outside the string. That's why you get that runtime error instead of a compile time error saying that the parameter type is wrong. To use Remove to remove part of a string, you first need to find where in the string that part is. Example: var x = "tesx"; var x = x.Remove(x.IndexOf('x'), 1); This will remove the first occurance of 'x' in the string. If there could be more than one occurance, and you want to remove all, using Replace is more efficient: var x = "tesx".Replace("x", String.Empty); A: Since you are passing a char in the function and this value is getting converted to int at runtime hence you are getting the runtime error because the value of char at runtime is more than the length of the string.You may try like this:- var x = "tesx"; var s = x.Remove(x.IndexOf('x'), 1); or var s = x.Replace("x",string.Empty); .Remove takes the int as parameter. Remove takes two parameters. The first one is what position in your string you want to start at. (The count starts at zero.) The second parameter is how many characters you want to delete, starting from the position you specified. On a side note: From MSDN: This method(.Remove) does not modify the value of the current instance. Instead, it returns a new string in which the number of characters specified by the count parameter have been removed. The characters are removed at the position specified by startIndex. A: You can use extension methods to create your own methods for already existing classes. Consider following example: using System; using MyExtensions; namespace ConsoleApplication { class Program { static void Main(string[] args) { const string str1 = "tesx"; var x = str1.RemoveByChar('x'); Console.WriteLine(x); Console.ReadKey(); } } } namespace MyExtensions { public static class StringExtensions { public static string RemoveByChar(this String str, char c) { return str.Remove(str.IndexOf(c), 1); } } }
unknown
d2061
train
Ruby on Rails does not depend on Javascript and therefore you don't need to know Javascript to learn Ruby and Rails. To answer one of your questions the link_to method doesn't refer to which action you are trying to call but to the HTTP method such as "POST", "GET", "PUT", "DELETE". You should use :action to tell which action in the controller (methods) to go to. There are a few places that can get you started with Ruby and Rails. * *Code School - Code school has a few free courses and one of them happens to be a very good one on Ruby on Rails *Code Academy - Code academy is more structured than code school and still provides many courses on different web development technologies *Railscasts - Railscasts is a great site with some free videos of rails tutorials Maybe some people can elaborate on more sources. Also, Github has many open source projects that you can take a look at and have a feel on how people use Ruby and Rails. A: In order to change the the page layout to show a "mini" form in response to a user clicking a particular element, you're going to either need to render a new view, or modify the current document via JavaScript. Here's a simplified version of what this view code might look like if you opted to reveal a form via JavaScript: ERB: # rendering each available article... <% @articles.each do |article| %> <p> <b>Name:</b> <%= article.name %> </p> <p> <b>Available:</b> <%= article.stocks %> </p> <% button_tag(:type => 'button', :class => 'buy-btn', data-article-id="article.id") do %> <strong>Buy Me!</strong> <% end %> # for each article, create a mini form with which # the user can buy n of said article... <div class="field hidden-item" id="form-#{article.id}" > <%= form_for(OrderItem.new do |f| %> <b>How many?</b> <br /> <%= f.number_field_tag :amount%> <%= f.submit %> <% end %> </div> <% end %> CSS: .field { display: none; //hides the div from all browsers by default } JavaScript to help tie everything together: $(document).ready(function() { //... other js code // bind all elements with the css class 'buy-btn' to // a click event... $(".buy-btn").bind('click', function() { var id = $(this).data('article-id'); $("#form-" + id).slideDown(); // shows the selected element with a nice slide down effect }); //... other js code }); So in the ERB we supply each article with a mini-form waiting to be populated and submitted. The form is hidden by default in our CSS, to be made visible when the user clicks the "Buy Me!" button for the article in question. This approach can also be adjusted a bit to allow the user to order however many different articles they desire by moving the the form declarations around a bit, and with appropriate handling in the OrderItemsController.create action. Another thing to keep in mind is that clicking the submit button on a form will cause the page to redirect by default. That's probably how you'll want to leave it while just getting started, but when you start to become comfortable, check out how to use :remote => true on submit tags to allow submitting forms in the background via AJAX. If you REALLY want to do it without any JavaScript at all, you're going to either have to do some very advanced work with CSS or will have to rig a link that passes a parameter to your view that instructs it to show a particular form. Here's what that might look like: # rendering each available article, as before... <% @articles.each do |article| %> <p> <b>Name:</b> <%= article.name %> </p> <p> <b>Available:</b> <%= article.stocks %> </p> # ... but now set up a link that passes a param to the controller... <%= link_to( 'Buy Me!', "/articles?article=#{article.id}" ) %> # which we then use to render a form on the page if the id in the # 'article' param matches the id of the article we are currently # rendering... <% if params[:article] && params[:article] == article.id %> <%= form_for(OrderItem.new do |f| %> <b>How many?</b> <br /> <%= f.number_field_tag :amount%> <%= f.submit %> <% end %> </div> <% end %> This may not be exact, but I hope it points you in the right direction!
unknown
d2062
train
It might be a false-positive. I would need to see more of your code and the input that was provided to it that triggered the warning from ZAP. Taking any security-related action on the client side can never be trusted because client-side validation can be circumvented with minimal know-how. You're left with performing sanitization on the server-side where the functions/subs doing the sanitization cannot be augmented.
unknown
d2063
train
According to Docs, there is table(DB instance class) which tells which settings can be changed, you can change your instance class for your aurora, as a note An outage occurs during this change. For redis according to docs, you can scale down node type of your redis cluster (version 3.2 or newer). During scale down ElastiCache dynamically resizes your cluster while remaining online and serving requests. In both the cases your data will be preserved.
unknown
d2064
train
You redefine the property with the call to defineProperty. You should give it a getter: Object.defineProperty(this, 'index', { get() { return index; }, set() { throw new AssertionError("can't set attribute"); } }); Any given property name can only be used once; a property has to either be a plain property or a property with getter/setter functions.
unknown
d2065
train
Why not use Regex? I think this will catch the letters in caps "[A-Z]{1,}/?[A-Z]{1,}[0-9]?" This is better. I got a list of all such symbols. Here's my result. ['BFLY', 'CBOE', 'BPVIX', 'CBOE/CME', 'FX', 'BPVIX1', 'CBOE/CME', 'FX', 'BPVIX2', 'CBOE/CME', 'FX'] Here's the code import re reg_obj = re.compile(r'[A-Z]{1,}/?[A-Z]{1,}[0-9]?') sym = reg_obj.findall(a)enter code here print(sym)
unknown
d2066
train
Probably just need to reference a named function or two instead of the anon ones. function showStuff(typeToShow) { $('.popular' + typeToShow + 'Additional').show(); $('#showmore-' + typeToShow + .showless').show(); $('#showmore-' + typeToShow + .showmore').hide(); $('#showmore-' + typeToShow).removeClass('sd-dark28').addClass('sd-dark28down'); return false; } function hideStuff(typeToHide) { $('.popular' + typeToHide + 'Additional').hide(); $('#showmore-' + typeToHide + .showless').hide(); $('#showmore-' + typeToHide + .showmore').show(); $('#showmore-' + typeToHide ).addClass('sd-dark28').removeClass('sd-dark28down'); } NOTE: a) You could probably make these methods a bit slicker, but you get the idea! NOTE: b) You'd need to rename '#showmore-town' to '#showmore-towns' (with an S) if you want to use the substitution suggested. Then in your toggle you could reference these functions: $('#showmore-towns').toggle(showStuff(towns), hideStuff(towns)); $('#showmore-cities').toggle(showStuff(cities), hideStuff(cities)); A: I mean...if it's always going to start with #showmore-...we can work it down $('[id^=showmore-]').toggle( function() { var id = $(this).prop('id'); id = id.split('-')[1]; var upperID = id.charAt(0).toUpperCase() + id.slice(1); $('.popular'+upperID+'Additional').show(); $('#showmore-'+id+' .showless').show(); $('#showmore-'+id+'.showmore').hide(); $('#showmore-'+id).removeClass('sd-dark28').addClass('sd-dark28down'); return false; }, function() { var id = $(this).prop('id'); id = id.split('-')[1]; var upperID = id.charAt(0).toUpperCase() + id.slice(1); $('.popular'+upperID+'Additional').hide(); $('#showmore-'+id+' .showless').hide(); $('#showmore-'+id+' .showmore').show(); $('#showmore-'+id).addClass('sd-dark28').removeClass('sd-dark28down'); }); A: you could do: (function() { $('#showmore-towns').toggle( function() { showmorelessOn('#showmore-town'); }, function() { showmorelessOff('#showmore-town'); } ); $('#showmore-cities').toggle( function() { showmorelessOn('#showmore-town'); }, function() { showmorelessOff('#showmore-town'); } ); var showmorelessOn = function(context) { $('.popularCitiesAdditional').show(); $('.showless', context).show(); $('.showmore', context).hide(); $(context).removeClass('sd-dark28').addClass('sd-dark28down'); return false; }; var showmorelessOff = function(context) { $('.popularCitiesAdditional').hide(); $('.showless', context).hide(); $('.showmore', context).show(); $(context).addClass('sd-dark28').removeClass('sd-dark28down'); }; })(); though I agree, could perhaps be better served on codereview.stackexchange.com A: I would do this almost entirely in the CSS. Only use .toggleClass() and determine what is shown and what is hidden in the CSS. A: (function() { $('#showmore-towns').toggle( function() { showmorelessOn.call($('#showmore-town')); }, function() { showmorelessOff.call($('#showmore-town')); } ); $('#showmore-cities').toggle( function() { showmorelessOn.call($('#showmore-town')); }, function() { showmorelessOff.call($('#showmore-town')); } ); var showmorelessOn = function() { $('.popularCitiesAdditional').show(); $('.showless', this).show(); $('.showmore', this).hide(); $(this).removeClass('sd-dark28').addClass('sd-dark28down'); return false; }; var showmorelessOff = function() { $('.popularCitiesAdditional').hide(); $('.showless', this).hide(); $('.showmore', this).show(); $(this).addClass('sd-dark28').removeClass('sd-dark28down'); }; })(); (function() { $('#showmore-towns').toggle( function() { showmoreless(); } ); $('#showmore-cities').toggle( function() { showmoreless(); } ); var showmoreless = function() { if(this.hasClass('sd-dark28'){ $('.popularCitiesAdditional').show(); $('.showless', this).show(); $('.showmore', this).hide(); $(this).removeClass('sd-dark28').addClass('sd-dark28down'); } else { $('.popularCitiesAdditional').hide(); $('.showless', this).hide(); $('.showmore', this).show(); $(this).addClass('sd-dark28').removeClass('sd-dark28down'); } }.bind($('#showmore-town')); })();
unknown
d2067
train
OK, then use this: SET TERM ^ ; create or alter procedure GETTREENODES returns ( ID integer, TREE_REF integer, PARENT_REF integer, ATTRIBUTE_REF integer, DATA_REF integer) as declare variable DATAREFEXISTS varchar(4096); begin DATAREFEXISTS = ','; for Select id, tree_ref, parent_ref, attribute_ref, data_ref from attribute_instances into :id, :tree_ref, :parent_ref, :attribute_ref, :data_ref do begin IF (position(',' || data_ref || ',', DATAREFEXISTS) =0) THEN begin suspend; DATAREFEXISTS = DATAREFEXISTS || data_ref || ',' ; end end end^ SET TERM ; ^ /* Following GRANT statetements are generated automatically */ GRANT SELECT ON ATTRIBUTE_INSTANCES TO PROCEDURE GETTREENODES; /* Existing privileges on this procedure */ GRANT EXECUTE ON PROCEDURE GETTREENODES TO SYSDBA; Call it like this: Select * from gettreenodes order by tree_ref, parent_ref
unknown
d2068
train
What's cutting-off the title are the margins on the left and right. They are set to be large enough to not allow overlapping of the title and any buttons in the header. You can try some CSS like this: .ui-dialog .ui-header h1 { margin-left : 30px; margin-right : 0px; } This may un-center the title but I haven't used the jQM-SimpleDialog plugin so I'm not sure what it adds to the mix. Here is a demonstration of the above code: http://jsfiddle.net/Y75dE/ A: This can be done through CSS. Assign a Class to the div/dialog. Ex: <div class="mydialog"/> Put the below css snippet code in the css file and include this in header. Add a class to the CSS file. .mydialog { margin-left : 20px; margin-right : 1px; } This should help you, customize the left,right as per your requirement.
unknown
d2069
train
I made the following steps to reduce the memory pressure: * *used separate class for my custom EventArgs (before: in view controller) *no anonymous function for button in UINavigationBar *no anonymous funciton for UIActionSheet *rewrote EventHandler in that way that I subscribe to them in viewWillAppear and unsubscribe in viewWillDisappear (most of the time) *added Target for UIGestureRecognizer in viewWillAppear and removed it in viewWillDisappear *removed cycle between view controller and datasource through using a WeakReference I made some checks and it now seems to work. For testing if a view controller is deallocated or not use this: protected override void Dispose (bool disposing) { Console.WriteLine (String.Format ("{0} controller disposed - {1}", this.GetType (), this.GetHashCode ())); base.Dispose (disposing); } Through this and commenting the things out I were able to detect the reference cycles. I hope I fixed all problems. The main problems were the EventHandler. For solving my issue the following questions belong to it: * *Clicked handler not executed for UIButton in UIBarButtonItem *How to break reference cycle between view controller and data source *Through presenting new view controller viewWillDisappear on parent is triggered where I unsubscribe from the events *RemoveTarget from UITapGestureRecognizer *Add/remove EventHandler for UIBarButtonItem The following links were helpful in resolving the memory issue: * *Memory and Performance Best Practices *Is this a bug in MonoTouch GC? *Memory Management Pitfalls in Xamarin iOS - Introduction + Part 1 + Part 2 *Weak Event Pattern in MonoTouch *iOS Memory Managment by Rodrigo Kumpera (Xamarin) *My App Crashed, Now What? – Part 1 + Part 2 *signal
unknown
d2070
train
Like @hfontanez I think your problem is in this code: if(hasMoreCommands() == true){ do { str = input.nextLine().trim(); // Strip out any comments if (str.contains("//")) { str = (str.substring(0, str.indexOf("//"))).trim(); } } while (str.startsWith("//") || str.isEmpty() || hasMoreCommands()); command = str; } However, my solution is to change the while clause to while (str.isEmpty() && hasMoreCommands()); I'm assuming that "advance" ought to return the next non-comment / blank line. If the string from the previous pass is empty (after stripping any comment) it will go round the loop again provided that wasn't the last line. But, if that was the last line or str still has something in it, then it will exit the loop. Comments should have been stripped so don't need tested for in the while. I think if you just test for hasNextLine within the loop then it will never exit the loop if the last line was comment / blank. A: My guess is that your problem is here: if(hasMoreCommands() == true){ do { str = input.nextLine().trim(); // Strip out any comments if (str.contains("//")) { str = (str.substring(0, str.indexOf("//"))).trim(); } } while (str.startsWith("//") || str.isEmpty() || hasMoreCommands()); command = str; } The exception you encountered (NoSuchElementException) typically occurs when someone tries to iterate though something (String tokens, a map, etc) without checking first if there are any more elements to get. The first time the code above is executed, it checks to see if it has more commands, THEN it gets in a loop. The first time it should work fine, however, if the test done by the while() succeeds, the next iteration will blow up when it tries to do input.nextLine(). You have to check is there is a next line to be got before calling this method. Surround this line with an if(input.hasNextLine()) and I think you should be fine.
unknown
d2071
train
Just use the sigmoid layer as the final layer. There's no need for any cross entropy when you have a single output, so just let the loss function work on the sigmoid output which is limited to the output range you want.
unknown
d2072
train
You can use a delegate to fire an event in parent page after note is added to the database. // Declared in Custom Control. // CustomerCreatedEventArgs is custom event args. public delegate void EventHandler(object sender, CustomerCreatedEventArgs e); public event EventHandler CustomerCreated; After note is added, fire parent page event. // Raises an event to the parent page and passing recently created object. if (CustomerCreated != null) { CustomerCreatedEventArgs args = new CustomerCreatedEventArgs(objCustomerMaster.CustomerCode, objCustomerMaster.CustomerAddress1, objCustomerMaster.CustomerAddress2); CustomerCreated(this, args); } In parent page, implement required event to re-fill grdiview. protected void CustomerCreated(object sender, CustomerCreatedEventArgs e) { try { BindGridView(); } catch (Exception ex) { throw ex; } } In your case, you can not use any custom event args, and use EventArgs class itself.
unknown
d2073
train
Since you are reducing the data frame, use groupBy.agg instead of window function; Here you compare the phone_number column with yes string ($"phone_number" === "yes") and convert the result to integer which turns true into 1 and false into 0 and then we count 1s by suming up the column: some_df.groupBy("user_id").agg( sum(($"phone_number" === "yes").cast("integer")).as("my_col") ).show +-------+------+ |user_id|my_col| +-------+------+ | B| 2| | A| 0| +-------+------+
unknown
d2074
train
Try this: patchdate=` psql -t -q -c "select patch_date from version_history where version ='1.1.1'"`
unknown
d2075
train
This appears to be occurring because you have nested blocks. That is, each code-block ( .code-block ) is nested within the previous one, so each image is slightly more padded than the one before. See the attached image. Nested Squarespace Code Blocks - Dev. Tools Screenshot I'm not sure how this problem was created. Did you copy and paste code containing sqs-block code-block sqs-block-code elements? It appears that you did, at least at first glance. To fix this, you're going to need to remove all of the Squarespace-specific divs that wrap each of your flip-container divs. Within the code block, all you should have is a series of flip-container divs, one after another. Like this: <div class="flip-container" ontouchstart="this.classList.toggle('focus');">etc</div> <div class="flip-container" ontouchstart="this.classList.toggle('focus');">etc</div> <div class="flip-container" ontouchstart="this.classList.toggle('focus');">etc</div> <div class="flip-container" ontouchstart="this.classList.toggle('focus');">etc</div>
unknown
d2076
train
I think you should put a timer and then do the console due to the async nature of JavaScript. var socket = io('http://test.domain.net:1234', {reconnection: false}); setTimeout(function(){ console.log("Connected:" + socket.connected); }, 3000); `
unknown
d2077
train
It's definitely a strange one. There seems to be a 3px border on your header which might be causing the issue. However if you increase the offset of your waypoints from 50 to 53 seems to fix the problem. var sections = $("section"); var navigation_links = $("nav a"); sections.waypoint({ handler: function (event, direction) { var active_section; active_section = $(this); if (direction === "down") active_section = active_section.prev(); var active_link = $('nav a[href="#' + active_section.attr("id") + '"]'); navigation_links.removeClass("selected"); active_link.addClass("selected"); }, offset: 53 })
unknown
d2078
train
I solved my own problem. Paypal does not canonicalize their webhook validation requests. When you receive the POST from Paypal, do NOT parse the request body before you go to send it back to them in the verification call. If your webhook_event is any different (even if the fields are in a different order), the event will be considered invalid and you will receive back a FAILURE. You must read the raw POST body and post that exact data back to Paypal in your webhook_event. Example: if you receive {"a":1,"b":2} and you post back {..., "webhook_event":{"b":2,"a":1}, ...} (notice the difference in order of the json fields from what we recieved and what we posted back) you will recieve a FAILURE. Your post needs to be {..., "webhook_event":{"a":1,"b":2}, ...} A: For those who are struggling with this, I'd like to give you my solution which includes the accepted answer. Before you start, make sure to store the raw_body in your conn, as described in Verifying the webhook - the client side @verification_url "https://api-m.sandbox.paypal.com/v1/notifications/verify-webhook-signature" @auth_token_url "https://api-m.sandbox.paypal.com/v1/oauth2/token" defp get_auth_token do headers = [ Accept: "application/json", "Accept-Language": "en_US" ] client_id = Application.get_env(:my_app, :paypal)[:client_id] client_secret = Application.get_env(:my_app, :paypal)[:client_secret] options = [ hackney: [basic_auth: {client_id, client_secret}] ] body = "grant_type=client_credentials" case HTTPoison.post(@auth_token_url, body, headers, options) do {:ok, %HTTPoison.Response{status_code: 200, body: body}} -> %{"access_token" => access_token} = Jason.decode!(body) {:ok, access_token} error -> Logger.error(inspect(error)) {:error, :no_access_token} end end defp verify_event(conn, auth_token, raw_body) do headers = [ "Content-Type": "application/json", Authorization: "Bearer #{auth_token}" ] body = %{ transmission_id: get_header(conn, "paypal-transmission-id"), transmission_time: get_header(conn, "paypal-transmission-time"), cert_url: get_header(conn, "paypal-cert-url"), auth_algo: get_header(conn, "paypal-auth-algo"), transmission_sig: get_header(conn, "paypal-transmission-sig"), webhook_id: Application.get_env(:papervault, :paypal)[:webhook_id], webhook_event: "raw_body" } |> Jason.encode!() |> String.replace("\"raw_body\"", raw_body) with {:ok, %{status_code: 200, body: encoded_body}} <- HTTPoison.post(@verification_url, body, headers), {:ok, %{"verification_status" => "SUCCESS"}} <- Jason.decode(encoded_body) do :ok else error -> Logger.error(inspect(error)) {:error, :not_verified} end end defp get_header(conn, key) do conn |> get_req_header(key) |> List.first() end
unknown
d2079
train
Your "onclick" attributes should look like this: <span class="button-prev" role="button" onclick="reloadweek(event);" data-semana=<?php echo $weekprev; ?>>&laquo; Previous Week</span> and then your function needs an "event" parameter: function reloadweek(event){ There's no point in javascript: in "onclick" handler values. You'd really be better off using jQuery to set up your event handlers: jQuery(document).on(".button-prev, .button-next", "click", function(event) { var uploading = jQuery('div#uploading').html('<p><img width="60px" src="<?php echo get_template_directory_uri();?>/images/loading.gif"/></p>'); jQuery('#calendar').load("<?php echo get_template_directory_uri();?>/ajaxloader.php #calendar", { 'week': $(this).data("semana") }, function() { today(); }); }); The value of this in the handler will be bound (by jQuery) to the element that was clicked on. Then you really don't need event at all, though jQuery will make sure it's passed through.
unknown
d2080
train
You can use try using HandlerInterceptorAdapter instead Check: https://www.logicbig.com/how-to/code-snippets/jcode-spring-mvc-deferredresultprocessinginterceptor.html
unknown
d2081
train
This is done to provide two names for the same event. "ViewDissapearing" is how the event was previously wrongly named, and all existing code that subscribes to the "ViewDissapearing" event is instead rerouted to subscribe to the new correctly spelt "ViewDisappearing" event instead. The add { ... } block is executed when someone calls ViewDissapearing += ..., which does nothing more than ViewDisappearing += that same .... Similarly for the remove { ... } block and -=. A: This is to allow other code to attach to this event. This is the same idea as the Get / Set Property of a variable. For Events it is Add / Remove. As with Properties of variables, you can use the Variable directly, or you can use an Property. You usually use the Properrty if you want to add some custom code when adding a event. A: This is explicitly stating what is normally autogenerated by the compiler for an event in a class.
unknown
d2082
train
You can use DependencyService. The DependencyService class is a service locator that enables Xamarin.Forms applications to invoke native platform functionality from shared code. 1º Create a public interface (for organization sake, maybe under Mobile > Services > IGetSSID) public interface IGetSSID { string GetSSID(); } 2º Create the Android Implementation [assembly: Dependency(typeof(GetSSIDAndroid))] namespace yournamespace { public class GetSSIDAndroid : IGetSSID { public string GetSSID() { WifiManager wifiManager = (WifiManager)(Android.App.Application.Context.GetSystemService(Context.WifiService)); if (wifiManager != null && !string.IsNullOrEmpty(wifiManager.ConnectionInfo.SSID)) { return wifiManager.ConnectionInfo.SSID; } else { return "WiFiManager is NULL"; } } } } 3º Then in your forms you get the SSID like this: var ssid = DependencyService.Get<IGetSSID>().GetSSID(); Note: Don't forget to add this permission on your Android Manifest <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> A: Get SSID and BSSID API31 Xamarin C# Example Required permissions: CHANGE_NETWORK_STATE, ACCESS_FINE_LOCATION If API<31 TransportInfo will return Null using Android.Content; using Android.Net; using Android.Net.Wifi; protected override void OnStart() { base.OnStart(); NetworkRequest request = new NetworkRequest.Builder().AddTransportType(transportType: TransportType.Wifi).Build(); ConnectivityManager connectivityManager = Android.App.Application.Context.GetSystemService(Context.ConnectivityService) as ConnectivityManager; NetworkCallbackFlags flagIncludeLocationInfo = NetworkCallbackFlags.IncludeLocationInfo; NetworkCallback networkCallback = new NetworkCallback((int)flagIncludeLocationInfo); connectivityManager.RequestNetwork(request, networkCallback); } private class NetworkCallback : ConnectivityManager.NetworkCallback { public NetworkCallback(int flags) : base(flags) { } public override void OnCapabilitiesChanged(Network network, NetworkCapabilities networkCapabilities) { base.OnCapabilitiesChanged(network, networkCapabilities); WifiInfo wifiInfo = (WifiInfo)networkCapabilities.TransportInfo; if (wifiInfo != null) { string ssid = wifiInfo.SSID.Trim(new char[] {'"', '\"' }); string bssid = wifiInfo.BSSID; } } } Click Android API reference.ConnectivityManager.NetworkCallback(int)!
unknown
d2083
train
I missed to add post routing in routes.php Route::post('search', 'SearchController@index'); Post routing did the job for me. Cheers!
unknown
d2084
train
You can just use empty() - as seen in the documentation, it will return false if the variable has no value. An example on that same page: <?php $var = 0; // Evaluates to true because $var is empty if (empty($var)) { echo '$var is either 0, empty, or not set at all'; } // Evaluates as true because $var is set if (isset($var)) { echo '$var is set even though it is empty'; } ?> You can use isset if you just want to know if it is not NULL. Otherwise it seems empty() is just fine to use alone. A: Here are the outputs of isset() and empty() for the 4 possibilities: undeclared, null, false and true. $a=null; $b=false; $c=true; var_dump(array(isset($z1),isset($a),isset($b),isset($c)),true); //$z1 previously undeclared var_dump(array(empty($z2),empty($a),empty($b),empty($c)),true); //$z2 previously undeclared //array(4) { [0]=> bool(false) [1]=> bool(false) [2]=> bool(true) [3]=> bool(true) } //array(4) { [0]=> bool(true) [1]=> bool(true) [2]=> bool(true) [3]=> bool(false) } You'll notice that all the 'isset' results are opposite of the 'empty' results except for case $b=false. All the values (except null which isn't a value but a non-value) that evaluate to false will return true when tested for by isset and false when tested by 'empty'. So use isset() when you're concerned about the existence of a variable. And use empty when you're testing for true or false. If the actual type of emptiness matters, use is_null and ===0, ===false, ===''. A: It depends what you are looking for, if you are just looking to see if it is empty just use empty as it checks whether it is set as well, if you want to know whether something is set or not use isset. Empty checks if the variable is set and if it is it checks it for null, "", 0, etc Isset just checks if is it set, it could be anything not null With empty, the following things are considered empty: * *"" (an empty string) *0 (0 as an integer) *0.0 (0 as a float) *"0" (0 as a string) *NULL *FALSE *array() (an empty array) *var $var; (a variable declared, but without a value in a class) From http://php.net/manual/en/function.empty.php As mentioned in the comments the lack of warning is also important with empty() PHP Manual says empty() is the opposite of (boolean) var, except that no warning is generated when the variable is not set. Regarding isset PHP Manual says isset() will return FALSE if testing a variable that has been set to NULL Your code would be fine as: <?php $var = '23'; if (!empty($var)){ echo 'not empty'; }else{ echo 'is not set or empty'; } ?> For example: $var = ""; if(empty($var)) // true because "" is considered empty {...} if(isset($var)) //true because var is set {...} if(empty($otherVar)) //true because $otherVar is null {...} if(isset($otherVar)) //false because $otherVar is not set {...} A: In your particular case: if ($var). You need to use isset if you don't know whether the variable exists or not. Since you declared it on the very first line though, you know it exists, hence you don't need to, nay, should not use isset. The same goes for empty, only that empty also combines a check for the truthiness of the value. empty is equivalent to !isset($var) || !$var and !empty is equivalent to isset($var) && $var, or isset($var) && $var == true. If you only want to test a variable that should exist for truthiness, if ($var) is perfectly adequate and to the point. A: Empty returns true if the var is not set. But isset returns true even if the var is not empty. A: $var = 'abcdef'; if(isset($var)) { if (strlen($var) > 0); { //do something, string length greater than zero } else { //do something else, string length 0 or less } } This is a simple example. Hope it helps. edit: added isset in the event a variable isn't defined like above, it would cause an error, checking to see if its first set at the least will help remove some headache down the road.
unknown
d2085
train
Try this: $('#size_list').html('<form id="dropdown_menu"><select id="dropdown_options"></select></form>'); $('#dropdown_options').html('<option>Choose size</option>'); You can't use a hammer as a wrench... Or use document.getElementById('size_list').innerHTML or use $('#size_list').html() Don't forget to put a # before an id selector in jQuery and a . before a class selector otherwise jQuery tries to find a <size_list> tag which won't exist in the DOM tree. A: First of all, while it may be convenient to add select options using the direct insert html methods, it rarely works universally. The bulletproof way to add options to a select is to build them up one at a time in a loop, assigning their value and label the old-fashioned way. var form = new Element('form', {id: 'dropdown_menu' }); var picker = new Element('select', {id: 'dropdown_options', size: 1 }); $('size_list').insert(form); form.insert(picker); picker.options[picker.options.length] = new Option('Choose size', ''); // want to add a list of elements in a loop? $w('Foo Bar Baz').each(function(val){ picker.options[picker.options.length] = new Option(val, val); }); IE has never dealt with modifications of the select element gracefully at all, this goes back to IE 5 when I first started trying to do this sort of thing.
unknown
d2086
train
I am gonna answer some of your questions * *there is no binding that would limit access to LAN network though you can use windows authentication to allow users from your network to use the service *the nettcpbinding is only a tcp connection and you can host it on IIS pof course check this link for more information hosting nettcp on IIS *you can have one base address for multiple endpoints , example: https://localhost:8080/calculator.svc net.tccp://localhost:8080/calculator.svc
unknown
d2087
train
Solved Batch file now reads javac TestShipment.java Shipment.java ShipmentHW1.java cd .. java shipment.TestShipment pause and it works like a charm. Anyone have any ideas why I had to call the package.class instead of just compiling it regularly? A: Try doing javac TestShipment.java java TestShipment pause A: Without seeing the contents of TestShipment.java, I'll assume you have some dependency on the Shipment and ShipmentHW1 classes. As such, when you execute a program that uses the TestShipment class, you need to have the .class files for each of the three (and any other dependencies). So you will have to compile Shipment.java and ShipmentHW1.java as well before running your java command. If they are in the same package, you're good, if not, you will have to specify an appropriate value for the -cp option. When running java with a class name, you need to specify the fully qualified class name. A: If your .java files are declared to be in the 'shipping' package, then you probably need to be running java from the parent directory of 'shipping', e.g. cd <path>/shipping javac TestShipment.java cd .. java shipping/TestShipment
unknown
d2088
train
Just want to add to Kaj's answer, from API level 17, you can call View.generateViewId() then use the View.setId(int) method. In case you need it for targets lower than level 17, here is its internal implementation in View.java you can use directly in your project: private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); /** * Generate a value suitable for use in {@link #setId(int)}. * This value will not collide with ID values generated at build time by aapt for R.id. * * @return a generated ID value */ public static int generateViewId() { for (;;) { final int result = sNextGeneratedId.get(); // aapt-generated IDs have the high byte nonzero; clamp to the range under that. int newValue = result + 1; if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. if (sNextGeneratedId.compareAndSet(result, newValue)) { return result; } } } ID number larger than 0x00FFFFFF is reserved for static views defined in the /res xml files. (Most likely 0x7f****** from the R.java in my projects.) From the code, somehow Android doesn't want you to use 0 as a view's id, and it needs to be flipped before 0x01000000 to avoid the conflits with static resource IDs. A: Just an addition to the answer of @phantomlimb, while View.generateViewId() require API Level >= 17, this tool is compatibe with all API. according to current API Level, it decide weather using system API or not. so you can use ViewIdGenerator.generateViewId() and View.generateViewId() in the same time and don't worry about getting same id import java.util.concurrent.atomic.AtomicInteger; import android.annotation.SuppressLint; import android.os.Build; import android.view.View; /** * {@link View#generateViewId()}要求API Level >= 17,而本工具类可兼容所有API Level * <p> * 自动判断当前API Level,并优先调用{@link View#generateViewId()},即使本工具类与{@link View#generateViewId()} * 混用,也能保证生成的Id唯一 * <p> * ============= * <p> * while {@link View#generateViewId()} require API Level >= 17, this tool is compatibe with all API. * <p> * according to current API Level, it decide weather using system API or not.<br> * so you can use {@link ViewIdGenerator#generateViewId()} and {@link View#generateViewId()} in the * same time and don't worry about getting same id * * @author [email protected] */ public class ViewIdGenerator { private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); @SuppressLint("NewApi") public static int generateViewId() { if (Build.VERSION.SDK_INT < 17) { for (;;) { final int result = sNextGeneratedId.get(); // aapt-generated IDs have the high byte nonzero; clamp to the range under that. int newValue = result + 1; if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. if (sNextGeneratedId.compareAndSet(result, newValue)) { return result; } } } else { return View.generateViewId(); } } } A: Regarding the fallback solution for API<17, I see that suggested solutions start generating IDs starting from 0 or 1. The View class has another instance of generator, and also starts counting from number one, which will result in both your and View's generator generating the same IDs, and you will end up having different Views with same IDs in your View hierarchy. Unfortunately there is no a good solution for this but it's a hack that should be well documented: public class AndroidUtils { /** * Unique view id generator, like the one used in {@link View} class for view id generation. * Since we can't access the generator within the {@link View} class before API 17, we create * the same generator here. This creates a problem of two generator instances not knowing about * each other, and we need to take care that one does not generate the id already generated by other one. * * We know that all integers higher than 16 777 215 are reserved for aapt-generated identifiers * (source: {@link View#generateViewId()}, so we make sure to never generate a value that big. * We also know that generator within the {@link View} class starts at 1. * We set our generator to start counting at 15 000 000. This gives us enough space * (15 000 000 - 16 777 215), while making sure that generated IDs are unique, unless View generates * more than 15M IDs, which should never happen. */ private static final AtomicInteger viewIdGenerator = new AtomicInteger(15000000); /** * Generate a value suitable for use in {@link View#setId(int)}. * This value will not collide with ID values generated at build time by aapt for R.id. * * @return a generated ID value */ public static int generateViewId() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) { return generateUniqueViewId(); } else { return View.generateViewId(); } } private static int generateUniqueViewId() { while (true) { final int result = viewIdGenerator.get(); // aapt-generated IDs have the high byte nonzero; clamp to the range under that. int newValue = result + 1; if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. if (viewIdGenerator.compareAndSet(result, newValue)) { return result; } } } } A: Since support library 27.1.0 there's generateViewId() in ViewCompat ViewCompat.generateViewId() A: Create a singleton class, that has an atomic Integer. Bump the integer, and return the value when you need a view id. The id will be unique during the execution of your process, but wil reset when your process is restarted. public class ViewId { private static ViewId INSTANCE = new ViewId(); private AtomicInteger seq; private ViewId() { seq = new AtomicInteger(0); } public int getUniqueId() { return seq.incrementAndGet(); } public static ViewId getInstance() { return INSTANCE; } } Note that the id might not be unique, if there already are views that have ids in the view 'graph'. You could try to start with a number that is Integer.MAX_VALUE, and decrease it instead of going from 1 -> MAX_VALUE
unknown
d2089
train
You can try this. In FragmentA you put this code private static NameOfTheFragment instance = null; public static NameOfTheFragment getInstance() { return instance; } Then create a function to return what you want, like a List View public ListView getList(){ return list; } Then in FragmentB you do this in onCreateView ListView list = NameOfTheFragment.getInstance().getList(); Then you show list in fragment B
unknown
d2090
train
Have you tried this? Write in your manifest file this permittion. . . <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> A: I got my drawing get saved. The changes i need to made in code is to create a bitmap along-with the canvas by command mCanvas = new Canvas( mBitmap );, which turn my canvas background as the image background.. Previously i had only started to painting the canvas which has black color background by default.
unknown
d2091
train
You can set the user-selected values in the localStorage localStorage.setItem('sort', 'desc'); and then when the user returns back to the current page fetch the values from localStorage on the component mount lifecycle method let sort = localStorage.getItem('sort'); and pass it to the grid Component.
unknown
d2092
train
Release Location is by default set to <ISProjectDataFolder> which is same location as the .ism or Installshield project file however you may change it to where setup.exe or installer project output is supposed to produced. In one installshield project you can set only one Release Location so, it is not clear how and where you set location for others? Do you have multiple installshield projects if yes, then you should name each projects outout file a different name so they do not overwrite existing files. See this screenshot
unknown
d2093
train
Full disclosure, I'm a developer for JanusGraph on Compose. * *It's as safe as any other OSS software project with a large amount of backers. Everyone could jump on some new toy tomorrow, but I doubt it. Companies are putting money into it and the development community is very active. *There is a CQL backend for Janus that's compatible with the Thrift data model. Migration to CQL should be simple and pretty painless when 0.2.0 is released. *I know there are already people using Titan for production applications. With JanusGraph being forked from Titan, I think it's pretty reasonable to start in with JanusGraph from everything I've seen. As far as a roadmap, I'd check out the JanusGraph mailing list (dev/users) and see what's going on and what's being talked about. A: Disclosure: I am one of the co-founders of the JanusGraph project; I am also seeking out and adding production users to our GitHub repo and website, so I may be slightly biased. :) Regarding your questions: * *Is it safe to use? The project is young, but it is built on a foundation of Titan, a very popular graph database that's been around since 2012 and has already been running in production. We have contributors from a number of well-known companies, and several companies are building their business-critical applications directly on JanusGraph, e.g., * *GRAKN.AI is building their knowledge graph on JanusGraph *IBM's Compose.io has built a managed JanusGraph service *Uber is already running JanusGraph in production (having previously run Titan) *several other companies run JanusGraph as a core part of their production environment We are also starting to identify companies who will provide consulting services around JanusGraph in case someone needs production-level support for their own self-managed deployments. So as you can see, there is significant interest in and support for this project. *Cassandra upgrade @pantalohnes answered this question; I won't repeat it here. *Production readiness As I linked above (GitHub repo and website), we already have production users of JanusGraph which you can find there. Those are just the companies that are publicly willing to lend their name/logo to the project; I'm sure there are more. Also, Titan has been running in many production environments for several years; JanusGraph is a more up-to-date version of Titan, despite the low version number. I am also speaking with other companies who are planning to migrate to JanusGraph soon; look for announcements via the @JanusGraph Twitter handle to learn about more production deployments.
unknown
d2094
train
You are using a com.documents4j.LocalConverter object to perform the conversion. According to the documentation: A LocalConverter can only be run if: * *The JVM is run on a MS Windows platform that ships with the Microsoft Scripting Host for VBS (this is true for all contemporary versions of MS Windows. *MS Word is installed in version 2007 or higher. PDF conversion is only supported when the PDF plugin is installed. The plugin is included into MS Word from Word 2010 and higher. *etcetera Obviously, neither of these prerequisites can be met on a Linux machine. Your options would appear to be: * *Use RemoteConverter to get a remote Windows machine to do the conversion. *Look for alternative RTF to PDF converter that will run on Linux.
unknown
d2095
train
Use a context bound of Fractional: case class Vector3[@specialized(Float, Double) T : Fractional](x: T, y: T, z: T) { ... then within the body of the class, get an instance of the arithmetic operators: val fractOps = implicitly[Fractional[T]] lastly import its members into the scope of the class: import fractOps._ Thereafter you can write ordinary infix operations on values of type T used within the class. Sadly, you will have to use fractOps.div(a, b) instead of a / b for division.
unknown
d2096
train
Use an application which allows you more flexible archiving from the command line, such as 7-Zip. Alternately, if you insist on scripting your own solution, use Get-ChildItem, filter out the undesireables, and then iterate over the results and build the archive manually using System.IO.Compression.ZipFileExtensions. That seems potentially pretty error prone to me, however.
unknown
d2097
train
You need to iterate through the ModelState collection checking the ModelState.Errors collection count for each property is greater than 0. To get the collection of modelstate items in error, something like ModelState["Property"].Where(ms => ms.Errors.Count > 0) Kindness, Dan
unknown
d2098
train
You need to set the "dn_lookup_attribute" to distinguishedName (DN) instead of the userPrincipalName / sAMAccountName so that it will use this user's DN for member checking in the in_group. As shown below: {dn_lookup_attribute, "distinguishedName"}, {user_dn_pattern, "CN=${username},OU=Users,DC=sample,DC=companyname,DC=com"}, Instead of: {dn_lookup_attribute, "userPrincipalName"}, {user_dn_pattern, "${username}@as.companyname.com"}, Microsoft Active Directory and OpenLDAP are different LDAP service flavors and have different user list attribute for groups. The Microsoft Active Directory Group for the users list is called "member" while the OpenLDAP group is called "uniqueMember". Overall config file: [ { rabbit, [ { auth_backends, [rabbit_auth_backend_ldap, rabbit_auth_backend_internal] } ] }, { rabbitmq_auth_backend_ldap, [ {servers, ["sample.companyname.com","192.168.63.123"]}, {dn_lookup_attribute, "distinguishedName"}, {dn_lookup_base, "DC=AS,DC=companyname,DC=com"}, {user_dn_pattern, "CN=${username},OU=Users,DC=sample,DC=companyname,DC=com"}, {use_ssl, false}, {port, 636}, {log, true}, { tag_queries, [ {administrator,{in_group,"CN=Rabbit User Group,OU=City Name, OU=Groups, OU=IT Group,DC=sample,DC=companyname,DC=com","member"}}, {management, {constant, true}} ] } ]%% rabbitmq_auth_backend_ldap, } ].
unknown
d2099
train
Your java code needs to be placed in src/main/java directory instead of src/main/kotlin. Kotlin compiler doesn't compile Java files in Kotlin source roots, Java compiler doesn't compile Java files in Kotlin source roots, therefore .class files are not created by any of the compilers and you get this error. The solution is to move *.java files into src/main/java directory. Create this directory manually if it doesn't exist.
unknown
d2100
train
Alex from Branch.io here: this should be working in WhatsApp, and I can confirm it does as expected with a test app on my end. I suspect WhatsApp doesn't like something about the image you're providing — could be the dimensions are wrong or unspecified. You could try our $og_image_height and $og_image_width params and take a look Facebook's open graph debug tool for any other errors. A: It worked for me, I just added $og_type, $og_image_width, $og_image_height and now it's working fine, I hope this can help you image implementation here
unknown