id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23534800
Couldn't locate or instantiate custom event: "com.mopub.mobileads.VungleInterstitial". D/MoPub: Loading custom event interstitial adapter. D/MoPub: Attempting to invoke custom event: "com.mopub.mobileads.VungleInterstitial" D/MoPub: Couldn't locate or instantiate custom event: "com.mopub.mobileads.VungleInterstitial". V/MoPub: MoPubErrorCode: Unable to find Native Network or Custom Event adapter. D/MoPub: Loading failover url: Gradle File apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "23.0.1" defaultConfig { applicationId "com.example.mopubads" minSdkVersion 14 targetSdkVersion 23 versionCode 11 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile('com.mopub:mopub-sdk:4.9.0@aar') { transitive = true } compile 'com.google.firebase:firebase-ads:10.0.1' compile 'com.facebook.android:audience-network-sdk:4.15.0' compile 'com.mopub.volley:mopub-volley:1.1.0' compile files('libs/dagger-2.7.jar') compile files('libs/javax.inject-1.jar') compile files('libs/vungle-publisher-adaptive-id-4.0.3.jar') } apply plugin: 'com.google.gms.google-services' proguard -keep public class com.google.ads.** { public *; } -keep class com.facebook.ads.** { *; } -keepclassmembers class com.mopub.** { public *; } -keep public class com.mopub.** -keep class com.mopub.mobileads.** {*;} -dontwarn com.vungle.** -keep class com.vungle.** { *; } -keep class javax.inject.*
doc_23534801
But a FirebaseApplication is like a static dictionary object and the values can only be obtained by specifying the 'key' by get() method. How can I update the FirebaseApplication all the time? If each value of the firebase object is a dictionary with date/time as keys, how can I retrieve the newest values? from firebase import firebase url = "https://dw-1d-cc5-grp08.firebaseio.com/" # this is a test url token = "yurddml214RsOPi9Ua0OhuDgeuzxm2Q7v7V6T6ZZ" #this is a test token firebase = firebase.FirebaseApplication(url,token) output_data = firebase.get('/humidity') print(output_data) A: In addition to accessing data by key, you can order and filter data by one of its child properties. For example: https://yourdb.firebaseio.com/users.json?orderBy="name"&equalTo="Yannis" This URL will give you all users whose name property is equal to "Rahul". See the Firebase documentation on ordering and filtering for more examples. A: You can use Firebase functions to get it done.
doc_23534802
// File "my_exception.h" #include <exception> #include <string> namespace proj { namespace exception { struct Exception : public std::exception { explicit Exception(const std::string& msg) noexcept : msg_(msg) { } inline const char* what() const noexcept override { return msg_.c_str(); } private: std::string msg_; }; } } Then I defined a derived exception class called BadParameterAccess in another namespace, splitting the declaration and the implementation in a .h and a .cpp files, respectively: // File parameter_exception.h #include "exception.h" namespace proj { namespace parameter { struct BadParameterAccess final : public exception::Exception { BadParameterAccess() noexcept; }; } } // File parameter_exception.cpp #include "parameter_exception.h" namespace proj { namespace parameter { BadParameterAccess::BadParameterAccess() noexcept : exception::Exception("[BadParameterAccess] parameter not set yet."){ } } } I tried to compile this code using several compilers. With clang 6.0 I get the following error: parameter_exception.cpp:7:18: error: initializer 'Exception' does not name a non-static data member or base class; did you mean the base class 'Exception'? : exception::Exception("[BadParameterAccess] parameter not set yet."){ } ^~~~~~~~~ Exception ./parameter_exception.h:11:35: note: base class 'exception::Exception' specified here struct BadParameterAccess final : public exception::Exception ^~~~~~~~~~~~~~~~~~~~~~~~~~~ g++ 7 gives an equivalent error, and Visual Studio 2017 gives the following: parameter_exception.cpp(8): error C2039: 'Exception': is not a member of 'std::exception' The code compiles perfectly when either: * *in the file parameter_exception.cpp I specify the full path for the base class initializer (proj::exception::Exception), or *in the file parameter_exception.cpp I remove the namespaces from the base class initializer (Exception), or *in the file my_exception.h I remove the inheritance from std::exception, or *I rename my namespace exception in some other way. As far as I have understood from the different errors I got, the compiler expects to find a member called Exception inside the class std::exception rather than inside the namespace exception, but I don't understand why this happens. Moreover, I would have expected the compiler to give me an error when I inherit from exception::Exception in the header file parameter_exception.h first, but it does not. Can someone explain me the reason? Thank you in advance. A: as @molbdnilo suggests there is a problem of name lookup. the problem is whith the name "exception" beeing used for namespace exception and the standard::exception struct. I removed code and comments from the code you posted. namespace standard { struct exception{ explicit exception() noexcept { } }; } namespace exception { struct A: public standard::exception { explicit A() noexcept { } }; } namespace parameter { struct BadParameterAccess final : public exception::A { //BadParameterAccess() noexcept : exception::A() { }; // KO BadParameterAccess() noexcept : ::exception::A() { }; // OK }; } namespace standard1 { struct exception1{ explicit exception1() noexcept { } }; } namespace exception2 { struct A: public standard1::exception1 { explicit A() noexcept { } }; } namespace parameter1 { struct BadParameterAccess1 final : public exception2::A { BadParameterAccess1() noexcept : exception2::A() { }; // OK //BadParameterAccess1() noexcept : ::exception2::A() { }; // OK }; }
doc_23534803
Once the data was imported, I clicked in New > Python 3 and wrote Used pandas' fast CSV parser, pandas.read_csv(), and once I ran line 4, I could see the memory usage increase to 88% of the capable using CleanMem Mini Monitor and got results in less than 1 minute. Then, to build the bar chart df1=df[[0]] df2=df[[1]] df3=df[[2]] mlab.barchart(df1,df2,df3) Unfortunately, I got this MemoryError --------------------------------------------------------------------------- MemoryError Traceback (most recent call last) <ipython-input-6-9736b00b5abc> in <module> 2 df2=df[[1]] 3 df3=df[[2]] ----> 4 mlab.barchart(df1,df2,df3) c:\infovis\virtualenvs\dev\lib\site-packages\mayavi\tools\helper_functions.py in the_function(*args, **kwargs) 35 36 def the_function(*args, **kwargs): ---> 37 return pipeline(*args, **kwargs) 38 39 if hasattr(pipeline, 'doc'): c:\infovis\virtualenvs\dev\lib\site-packages\mayavi\tools\helper_functions.py in __call__(self, *args, **kwargs) 80 scene.disable_render = True 81 # Then call the real logic ---> 82 output = self.__call_internal__(*args, **kwargs) 83 # And re-enable the rendering, if needed. 84 if scene is not None: c:\infovis\virtualenvs\dev\lib\site-packages\mayavi\tools\helper_functions.py in __call_internal__(self, *args, **kwargs) 1093 """ Override the call to be able to scale automatically the axis. 1094 """ -> 1095 g = Pipeline.__call_internal__(self, *args, **kwargs) 1096 gs = g.glyph.glyph_source 1097 # Use a cube source for glyphs. c:\infovis\virtualenvs\dev\lib\site-packages\mayavi\tools\helper_functions.py in __call_internal__(self, *args, **kwargs) 90 the last object created by the pipeline.""" 91 self.store_kwargs(kwargs) ---> 92 self.source = self._source_function(*args, **kwargs) 93 # Copy the pipeline so as not to modify it for the next call 94 self.pipeline = self._pipeline[:] c:\infovis\virtualenvs\dev\lib\site-packages\mayavi\tools\sources.py in vertical_vectors_source(*args, **kwargs) 1356 1357 data_source = MVerticalGlyphSource() -> 1358 data_source.reset(x=x, y=y, z=z, scalars=s) 1359 1360 name = kwargs.pop('name', 'VerticalVectorsSource') c:\infovis\virtualenvs\dev\lib\site-packages\mayavi\tools\sources.py in reset(self, **traits) 306 traits['u'] = traits['v'] = np.ones_like(s), 307 traits['w'] = s --> 308 super(MVerticalGlyphSource, self).reset(**traits) 309 310 def _scalars_changed(self, s): c:\infovis\virtualenvs\dev\lib\site-packages\mayavi\tools\sources.py in reset(self, **traits) 172 173 else: --> 174 points = np.c_[x.ravel(), y.ravel(), z.ravel()].ravel() 175 points.shape = (-1, 3) 176 self.trait_set(points=points, trait_change_notify=False) c:\infovis\virtualenvs\dev\lib\site-packages\numpy\lib\index_tricks.py in __getitem__(self, key) 404 objs[k] = objs[k].astype(final_dtype) 405 --> 406 res = self.concatenate(tuple(objs), axis=axis) 407 408 if matrix: <__array_function__ internals> in concatenate(*args, **kwargs) MemoryError: Unable to allocate array with shape (153543233, 3) and data type int64 And the result was this A: Due to constantly being out-of-memory I had to come up with a way to reduce the amount of data. Inspired in Trifacta, I've decided to go with sampling (create a sample from the CSV file). The following are some of the possible samples I could product For simplification reasons, decided to go with random samples. Using Git Bash on Windows 10 I just ran a similar command (the number of rows might not be the same as the one used) as shuf -n 10000 BIGFILE.csv > SAMPLEFILE.csv Then the procedure to create the visualization was exactly the same except the name of the file and the result was the following
doc_23534804
That is, b is two d array, and I am trying to implement around printing values and the adress, but why is *(b+1) giving the same thing as b+1? I thought *(b+1) would give the value of the first element of the second row. and if I change printf("%p\n", *(b+1)) to printf("%d\n", *(b+1)), it just gives a garbage value. Why is it working like this? I appriciate any feedback! thank you int main() { int b[3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; printf("b:\n"); print_2d_array(3, 4, b); printf("\n"); printf("%p\n", b); printf("%p\n", *(b+1)); printf("%p\n", b+1); return 0; } Output is like this, b: 0 1 2 3 4 5 6 7 8 9 10 11 0x7ffeecee6730 0x7ffeecee6740 0x7ffeecee6740 A: The question you have asked essentially boils down to a question about the nature of an array and the address of an array, which is a fairly well covered topic (see this for example). However, you likely confused yourself with the pointer arithmetic, so this answer tries to clarify some of that. In C, when array object is used in an expression, its value and type becomes the same as the pointer to its first element. In your case, you have: int b[3][4] = { /* ... */ }; /* ... */ printf("%p\n", *(b+1)); printf("%p\n", b+1); If we consider the last print statement,b in the expression b + 1 becomes the same as &b[0] + 1, and this would be the same as &b[1]. When we consider the print statement before the last one, we note that *(b+1) is defined to be the value b[1]. However, the result of that expression is an array of 4 int. That array now takes on the value and type of its first element, which would be &b[1][0]. Since you need to be able to find the address of the first element of an array from the array itself, the address of an array, &b[1], has the same pointer value as the address of its first element &b[1][0]. However, &b[1] and &b[1][0] have different types. The former is a pointer to an array, while the later is a pointer to an int. For additional information, I encourage you to read the linked question at the top of this answer for more about arrays and the address of arrays. A: *why is (b+1) giving the same thing as b+1? The output address is numerically same but their type is different. The type of *(b+1) is int [4] whereas the type of b+1 is int (*)[4]. *(b+1), when used in an expression, will convert to address of first element of second row1): *(b + 1) -> b[1] -> ((b[1]) + (0)) -> &(*((b[1]) + (0))) -> &b[1][0] and b+1 will give address of second row. Address of an array and address of first element of that array are numerically same but their type are different. *I thought (b+1) would give the value of the first element of the second row. *(b+1) will give the second element of 2D array b which is nothing but a 1D array of 4 integers. To access the first element of second row using *(b+1), you can do: (*(b+1))[0] To access the second element of second row using *(b+1), you can do: (*(b+1))[1] third element .... (*(b+1))[2] and so on ..... Note that *(b+1) is equivalent to b[1]1). So, (*(b+1))[0] is equivalent to b[1][0] (*(b+1))[1] is equivalent to b[1][1] .. and so on Hope this clarifies your doubt. 1 ) From C Standards#6.5.2.1 The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2)))..
doc_23534805
From the link above, i've been able to connect my c# app with google sheets. For this to work, it is required an internet conection (an exception is thrown if not). Since "Backup and Sync from Google" app for windows is installed in my computer, the offline edit mode is available for the spreadsheets synced by the app. Does anyone know some way to take advantage of the offline mode feature in c#? So if there's no internet available i can still update my sheet? Thanks in advance A: Offline editing is a feature with in the application. You would have to code your own application to store the data and send it to Google using the API once you are online again.
doc_23534806
var I: Integer; begin I:= StrToInt('0xAA'); ShowMessage(IntToStr(I)); // shows 170 = $AA end; is OK in Delphi 2009. BTW the feature helped me to extract hexadecimal constants from C header file. I wonder is it OK to use the feature or the feature is about to be "fixed" in future versions? A: Recall that the Delphi RTL is used by C++ Builder, too. The documentation doesn't go into detail about exactly what it means when it says StrToIntaccepts "decimal or hexadecimal notation." You can safely expect StrToInt to continue to accept C-style numbers. Val accepts the same input, as does Read (because they all end up calling System._ValLong). A: It's a feature, and you can rely on it. One of the philosophical changes that occurred in the evolution of Turbo Pascal into Delphi was the acknowledgment that Delphi lives in a C-dominated world and there was more to be gained by gracefully accepting or tolerating C-isms than ignoring them and forcing the Delphi developer to sort it out. Interop with C++ Builder as mentioned by Rob was a factor, but so was the fact that Delphi was designed first for Windows, and Windows has a lot of C language artifacts in the Windows API. I think the term "impedance mismatch" may apply here - it was simple enough to remove the impedance mismatch between Delphi hex handling and "Rest of World", so we did.
doc_23534807
SharedPreferences doesn't seem to support arrays or arraylists. What's the best approach here? A: You can use a table in a SQLiteDatabase to store the search history, and use the standard SQL API to access it. Or you can use a file in XML, JSON, YAML, CSV, plain text, or whatever you like to persist the history. The advantage is simplicity and (maybe) performance. The disadvantage is that you'll have to serialize and deserialize yourself (a possible variation is to serialized a Java object directly) A: SharedPreferences support boolean int, float, long and String. BUT ArrayList are Serializable, so if you also declare you object Serializable, you can encode them into a ByteBuffer with an ObjectOutputStream, then convert this byteBuffer into a String, and finally store it into a SharedPreferences, or better to a binary file (as bytebuffer). In your case, where you just have to save String, it is easer run through every element of the array and save them as "arrayName"+index, and finally save the size of the array.
doc_23534808
or Is it possible to writing custom dealloc method for NSObject Class so that we can call any method before deallocating that object? As garbage collector is not available for iPhone, I wants to create small framework which handles memory leak at runtime & create a log files for leaks (I known that there is instrument that identify the leaks but still for R&D and don't want to implement Garbage Collector algo). We are trying to maintain a list of allocated object. for example: A *a=[[A alloc]init]; NSString * veribaleAddress=[NSString stringWithFormat:@"%p",&a]; NSString *allocatedMemoryAddress=[NSString stringWithFormat:@"%p",a]; // Global dictionary for maintaining a list of object NSMutableDictionary *objects; [objects setValue: allocatedMemoryAddress forKey: veribaleAddress]; but when any object get deallocate then I want to 1st look, whether address of that object is present in dictionary or not. If address present then remove it from dictionary. Please guide me, whether it's possible or not. Thanks A: Here’s an example gist showing how to swizzle the dealloc method, if that’s what you are after. Main part of the code: void swizzle(Class c, SEL orig, SEL patch) { Method origMethod = class_getInstanceMethod(c, orig); Method patchMethod = class_getInstanceMethod(c, patch); BOOL added = class_addMethod(c, orig, method_getImplementation(patchMethod), method_getTypeEncoding(patchMethod)); if (added) { class_replaceMethod(c, patch, method_getImplementation(origMethod), method_getTypeEncoding(origMethod)); return; } method_exchangeImplementations(origMethod, patchMethod); } id swizzledDealloc(id self, SEL _cmd) { // …whatever… return self; } const SEL deallocSel = @selector(dealloc); // If using ARC, try: // const SEL deallocSel = NSSelectorFromString(@"dealloc"); const SEL swizzledSel = @selector(swizzledDealloc); class_addMethod(c, swizzledSel, (IMP) swizzledDealloc, "@@:"); swizzle(c, deallocSel, swizzledSel); As Bavarious says, this is dark magic and I wouldn’t use it in production, ever. A: You might be able to use objc_setAssociatedObject to track the lifespan of the object. Something like this: Header: // SGBObjectTracker.h typedef void (^SGBObjectTrackerCallback)(id trackedObject); @interface SGBObjectTracker : NSObject @property (nonatomic, assign) id trackedObject; @property (nonatomic, copy) SGBObjectTrackerCallback callback; +(void) trackObject:(id)object withCallback:(SGBObjectTrackerCallback)callback; @end Implementation: // SGBObjectTracker.m #import "SGBObjectTracker.h" #import <objc/runtime.h> @implementation @synthesize trackedObject, callback; -(void) dealloc { callback(trackedObject); [super dealloc]; } +(void) trackObject:(id)object withCallback:(SGBObjectTrackerCallback)callback { SGBObjectTracker *tracker = [[self alloc] init]; tracker.callback = callback; tracker.trackedObject = object; objc_setAssociatedObject(object, _cmd, tracker, OBJC_ASSOCIATION_RETAIN); [tracker release]; } @end This takes advantage of the fact that associated objects are released when the objects they are associated with are dealloced. It won't work with NSZombies enabled, and it may break if you're using ARC or something else which messes about with retain counts. I wouldn't count on being able to use the object in question during the callback, but its address should still be OK and that's what you seem to need.
doc_23534809
When I use a $q or $resource to realize a ajax request Here is the response when there is some data: [{"number":"132412341234","type":"5","createTime":1388369479626,"updateTime":1388369479626,"kind":"devices#get","id":"52c0d6470cf2393bb3df6371"}] Here is the response with no-data response: [{"request":"persons/529c6a970cf2ce4b156d0f3e/devices","status":404,"error":"can't find persons records"}] However,when I go back to my controller to get these data with promise: var devices=DeviceResource.query({personId:1234}); response devices became: [$promise: Object, $resolved: false] 0: f $$hashKey: "00M" error: "can't find persons records" request:"persons/529c6a970cf2ce4b156d0f3e/devices" status: 404 __proto__: f $promise: Object $resolved: true length: 1 __proto__: Array[0] the array[0]'s proto is "f" what is the "f" mean? Where can I get these document? It seems in angular $q document just some promise content. Can anybody help me? Thx a lot... A: I would assume you're using a minified version. Try using the production version instead to get a better trace, e.g.: <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js"></script>
doc_23534810
Please provide code examples of how I can acquire this data. My current capture code is below: var htmlCode = string.empty; using (WebClient client = new WebClient()) // WebClient class inherits IDisposable { // Get the file content without saving it htmlCode = client.DownloadString("https://www.wedj.com/dj-photo-video.nsf/firstdance.html"); } Using the above code, you receive the source code as seen here: The data shown in image 1, as seen from the browser inspector is hidden inside of <div class="entry row"> A: There are few ways to implement what you need (considering a C# console application). Maybe the easiest one is to use tools that interact with an instance of a browser, i.e. Selenium (used for unit tests). So: * *Install Selenium.WebDriver nuget package *Install a browser where your application will run (let's suppose chrome) *Download the browser driver (chromedriver) *Write something like: IWebDriver driver = null; try { ChromeOptions options = new ChromeOptions(); options.AddArguments("--incognito"); driver = new ChromeDriver(options); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5); driver.Url = "https://www.wedj.com/dj-photo-video.nsf/firstdance.html"; var musicTable = driver.FindElement(By.Id("musicTable")); // interact with driver to get data from the page. } finally { if (driver != null) driver.Dispose(); } Otherwise, you need to investigate a little bit more how the webpage works. As far as I can see, the page loads a javascript, https://www.wedj.com/dj-photo-video.nsf/musiclist.js, that it is responsible to load the list of music from server. This js script basically load data from following url: https://www.wedj.com/gbmusic.nsf/musicList?open&wedj=1&list=category_firstdance&count=100 (you can open it also in a browser). Excluding "(" and ")", the result is a json you can parse (maybe using newtonsoft.json package): { "more": "yes", "title": "<h1>Most Requested Wedding First Dance Songs<\/h...", "event": "<table class='musicTable g6-table-all g6-small' id='musicTable' borde..." } The event property contains the data you need (you can use HtmlAgilityPack nuget package to parse it). Pro Selenium: * *easy to interact with *the behavior is the same of what you see by the browser Cons Selenium: * *you need chrome or another browser installed *the browser is running when you interact with it *the browser download the full page (images, html, js, css...) Pro manual: * *you load only what you need *no dependencies to external programs (i.e. browsers) Cons manual: * *you need to understand how html/js works *you need to manually parse the json/html In this specific case, I prefer the second options. A: Read about Selenium Automation tool for C#, but it'll open every web page that you want to scrap and then e.g return source code or perform some actions on that webpage. Generally this tool is not (afaik) for web crawlers, but can be good at the beginning, especially if your dotnet core app is sitting on some virtual machine / docker. But care, it may be risky to open not-safe pages via browser. A: You might watn to try pupeteer sharp. It allows you to get the current HTML state. using (var page = await browser.NewPageAsync()) { await page.GoToAsync("http://www.spapage.com"); var result = await page.GetContentAsync(); } https://github.com/kblok/puppeteer-sharp
doc_23534811
<ui:include src="/WEB-INF/jsp/header.jsp" /> but my header.jsp have variables and I need a controller to initialise theses variables, is there a way to call a controller and include the controller method jsp in an other jsp ? For exemple; <%@tag description="Overall Page template" pageEncoding="UTF-8"%> <%@attribute name="header" fragment="true"%> <%@attribute name="footer" fragment="true"%> <html> <body> <div id="pageheader"> //include my header controller <ui:include src="/WEB-INF/jsp/header.jsp" /> </div> <div id="body"> <jsp:doBody /> </div> <div id="pagefooter"> //include my footer controller </div> </body> </html> header.jsp Header ${test} my header method public String header(Map<String, Object> model){ model.put("test", "test"); return "header"; } But the controller is not used and ${test} is empty A: I think, if you call an MVC controller from an MVC view, your application will brake common MVC principles. Your code will be hard to debug, hard to test and hard to understand by others. It, probably, would be a better idea to prepare model attributes for all parts of your view (the main part of the page, header and footer) in one controller. The model that you pass to a JSP view is available in included custom JSP tags and JSPs. You can use a @ModelAttribute annotated method to supply attributes to a few controller methods at once. You could use JSP tags instead of JSP pages to define your header and footer (at least that's how I do it in my application). A: First of all, your JSP should not "call" directly to any controller. Secondly, I see you're using Spring framework, and in Spring, from any controller to JSP, there is only 1 model object being passed to the JSP. Therefore if in the header you need to initialise another model, you have to call the URL to the controller instead of calling the header.jsp. A: The ther answers already explained that the model should be populated by an controller. ... If you need the same model variables in all pages, for example in the header or footer, the a common way is to enrich the model in a single HandlerInterceptor, instead of every controller method.
doc_23534812
Before [ {id: 0, name: 'Bob', age: 27}, {id: 1, name: 'Frank', age: 32}, {id: 2, name: 'Joe', age: 38} ] It can change: After [ {id: 0, name: 'Bob', age: 27}, {id: 1, name: 'Frank', age: 33}, {id: 2, name: 'Joe', age: 38} ] Notice Frank just turned 33. I have an app where I am trying to watch the people array and when any of the values changes then log the change: <style> input { display: block; } </style> <div id="app"> <input type="text" v-for="(person, index) in people" v-model="people[index].age" /> </div> <script> new Vue({ el: '#app', data: { people: [ {id: 0, name: 'Bob', age: 27}, {id: 1, name: 'Frank', age: 32}, {id: 2, name: 'Joe', age: 38} ] }, watch: { people: { handler: function (val, oldVal) { // Return the object that changed var changed = val.filter( function( p, idx ) { return Object.keys(p).some( function( prop ) { return p[prop] !== oldVal[idx][prop]; }) }) // Log it console.log(changed) }, deep: true } } }) </script> I based this on the question that I asked yesterday about array comparisons and selected the quickest working answer. So, at this point I expect to see a result of: { id: 1, name: 'Frank', age: 33 } But all I get back in the console is (bearing in mind i had it in a component): [Vue warn]: Error in watcher "people" (found in anonymous component - use the "name" option for better debugging messages.) And in the codepen that I made, the result is an empty array and not the changed object that changed which would be what I expected. If anyone could suggest why this is happening or where I have gone wrong here then it would be greatly appreciated, many thanks! A: It is well defined behaviour. You cannot get the old value for a mutated object. That's because both the newVal and oldVal refer to the same object. Vue will not keep an old copy of an object that you mutated. Had you replaced the object with another one, Vue would have provided you with correct references. Read the Note section in the docs. (vm.$watch) More on this here and here. A: I have changed the implementation of it to get your problem solved, I made an object to track the old changes and compare it with that. You can use it to solve your issue. Here I created a method, in which the old value will be stored in a separate variable and, which then will be used in a watch. new Vue({ methods: { setValue: function() { this.$data.oldPeople = _.cloneDeep(this.$data.people); }, }, mounted() { this.setValue(); }, el: '#app', data: { people: [ {id: 0, name: 'Bob', age: 27}, {id: 1, name: 'Frank', age: 32}, {id: 2, name: 'Joe', age: 38} ], oldPeople: [] }, watch: { people: { handler: function (after, before) { // Return the object that changed var vm = this; let changed = after.filter( function( p, idx ) { return Object.keys(p).some( function( prop ) { return p[prop] !== vm.$data.oldPeople[idx][prop]; }) }) // Log it vm.setValue(); console.log(changed) }, deep: true, } } }) See the updated codepen A: if we have Object or Array of object and we want to watch them in Vuejs or NUXTJS need to use deep: true in watch watch: { 'Object.key': { handler (val) { console.log(val) }, deep: true } } watch: { array: { handler (val) { console.log(val) }, deep: true } } A: Your comparison function between old value and new value is having some issue. It is better not to complicate things so much, as it will increase your debugging effort later. You should keep it simple. The best way is to create a person-component and watch every person separately inside its own component, as shown below: <person-component :person="person" v-for="person in people"></person-component> Please find below a working example for watching inside person component. If you want to handle it on parent side, you may use $emit to send an event upwards, containing the id of modified person. Vue.component('person-component', { props: ["person"], template: ` <div class="person"> {{person.name}} <input type='text' v-model='person.age'/> </div>`, watch: { person: { handler: function(newValue) { console.log("Person with ID:" + newValue.id + " modified") console.log("New age: " + newValue.age) }, deep: true } } }); new Vue({ el: '#app', data: { people: [ {id: 0, name: 'Bob', age: 27}, {id: 1, name: 'Frank', age: 32}, {id: 2, name: 'Joe', age: 38} ] } }); <script src="https://unpkg.com/vue@2.1.5/dist/vue.js"></script> <body> <div id="app"> <p>List of people:</p> <person-component :person="person" v-for="person in people"></person-component> </div> </body> A: The component solution and deep-clone solution have their advantages, but also have issues: * *Sometimes you want to track changes in abstract data - it doesn't always make sense to build components around that data. *Deep-cloning your entire data structure every time you make a change can be very expensive. I think there's a better way. If you want to watch all items in a list and know which item in the list changed, you can set up custom watchers on every item separately, like so: var vm = new Vue({ data: { list: [ {name: 'obj1 to watch'}, {name: 'obj2 to watch'}, ], }, methods: { handleChange (newVal) { // Handle changes here! console.log(newVal); }, }, created () { this.list.forEach((val) => { this.$watch(() => val, this.handleChange, {deep: true}); }); }, }); With this structure, handleChange() will receive the specific list item that changed - from there you can do any handling you like. I have also documented a more complex scenario here, in case you are adding/removing items to your list (rather than only manipulating the items already there). A: This is what I use to deep watch an object. My requirement was watching the child fields of the object. new Vue({ el: "#myElement", data:{ entity: { properties: [] } }, watch:{ 'entity.properties': { handler: function (after, before) { // Changes detected. }, deep: true } } }); A: Instead of "watch" I solved the problem with "computed"! I have not tested this code but i think it should work. Please tell me in the comments if not. <script> new Vue({ el: '#app', data: { people: [ {id: 0, name: 'Bob', age: 27}, {id: 1, name: 'Frank', age: 32}, {id: 2, name: 'Joe', age: 38} ], oldVal: {}, peopleComputed: computed({ get(){ this.$data.oldVal = { ...people }; return people; }, set(val){ // Return the object that changed var changed = val.filter( function( p, idx ) { return Object.keys(p).some( function( prop ) { return p[prop] !== this.$data.oldVal[idx][prop]; }) }) // Log it console.log(changed) this.$data.people = val; } }), } }) </script>
doc_23534813
A: After taking a look at the ECMAScript 2015 Language Specification I could confirm the expected behaviour, as long as toString is not overwritten: ToString will be evaluated with ToPrimitive which in turn evaluates OrdinaryToPrimitive for the Array with the hint set to string which then finally calles the Arrays toString. A: It might be safe 99% of the time but since it is JavaScript you should also expect monkey patching. Even if you run in a safe environment, I would still opt for clarity: const arr = ['abc', 'xyz']; const str = `test=${arr.join(',')}`; Why? * *The intent is clearer (IMHO) *People who don't know the inner workings of JavaScript can still understand that code What's up with the 1%? People can and will monkey patch JavaScript. Can you afford a risk there? Array.prototype.toString = () => ''; const arr = ['abc', 'xyz']; const str = 'test=' + arr; console.log(str);
doc_23534814
FireBug is getting the JSON response correctly but it is still not showing up in fullCalendar. I'm out of ideas. The FireBug response: [{"id":1,"title":"TESTTITLE","info":"INFOINFOINFO","start":"2012-08-20T12:00:00","end":"2012-08-20T12:00:00","user":1}] JSON.aspx public partial class JSON : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // Get events from db and add to list. DataClassesDataContext db = new DataClassesDataContext(); List<calevent> eventList = db.calevents.ToList(); // Select events and return datetime as sortable XML Schema style. var events = from ev in eventList select new { id = ev.event_id, title = ev.title, info = ev.description, start = ev.event_start.ToString("s"), end = ev.event_end.ToString("s"), user = ev.user_id }; // Serialize to JSON string. JavaScriptSerializer jss = new JavaScriptSerializer(); String json = jss.Serialize(events); Response.Write(json); Response.End(); } } Site.master <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" /> <link href='fullcalendar/fullcalendar.css' rel='stylesheet' type='text/css' /> <script src='jquery/jquery-1.7.1.min.js' type='text/javascript'></script> <script src='fullcalendar/fullcalendar.js' type='text/javascript' ></script> <script type="text/javascript"> $(document).ready(function () { $('#fullcal').fullCalendar({ eventClick: function() { alert('a day has been clicked!'); }, events: 'JSON.aspx' }) }); </script> I've been scanning related questions for days but none of them seems to fix mine... A: Try this , you have to have a webmethod in aspx file that fullcalendar can call asynchronously $(document).ready(function () { $('#fullcal').fullCalendar({ eventClick: function() { alert('a day has been clicked!'); }, events: function (start, end, callback) { $.ajax({ type: "POST", //WebMethods will not allow GET url: "json.aspx/GetEvents", //url of a webmethod - example below data: "{'userID':'" + $('#<%= hidUserID.ClientID %>').val() + "'}", //this is what I use to pass who's calendar it is //completely take out 'data:' line if you don't want to pass to webmethod - Important to also change webmethod to not accept any parameters contentType: "application/json; charset=utf-8", dataType: "json", success: function (doc) { var events = []; //javascript event object created here var obj = $.parseJSON(doc.d); //.net returns json wrapped in "d" $(obj.event).each(function () { //yours is obj.calevent events.push({ title: $(this).attr('title'), //your calevent object has identical parameters 'title', 'start', ect, so this will work start: $(this).attr('start'), // will be parsed into DateTime object end: $(this).attr('end'), id: $(this).attr('id') }); }); callback(events); } }); } }) then this would be in json.aspx [WebMethod(EnableSession = true)] public static string GetEvents(string userID) { DataClassesDataContext db = new DataClassesDataContext(); List<calevent> eventList = db.calevents.ToList(); // Select events and return datetime as sortable XML Schema style. var events = from ev in eventList select new { id = ev.event_id, title = ev.title, info = ev.description, start = ev.event_start.ToString("s"), end = ev.event_end.ToString("s"), user = ev.user_id }; // Serialize to JSON string. JavaScriptSerializer jss = new JavaScriptSerializer(); String json = jss.Serialize(events); return json; }
doc_23534815
public class GetLocation extends Activity implements LocationListener { LocationManager lm; TextView tv; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_get_mission); // Acquire a reference to the system Location Manager tv= (TextView)findViewById(R.id.locationOutput); lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 1, this); } public void onLocationChanged(Location arg0) { String lat = String.valueOf(arg0.getLatitude()); String lon = String.valueOf(arg0.getLongitude()); Log.e("GPS", "location changed: lat="+lat+", lon="+lon); tv.setText("lat="+lat+", lon="+lon); } public void onProviderDisabled(String arg0) { Log.e("GPS", "provider disabled " + arg0); } public void onProviderEnabled(String arg0) { Log.e("GPS", "provider enabled " + arg0); } public void onStatusChanged(String arg0, int arg1, Bundle arg2) { Log.e("GPS", "status changed to " + arg0 + " [" + arg1 + "]"); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_get_mission, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: NavUtils.navigateUpFromSameTask(this); return true; } return super.onOptionsItemSelected(item); } } However I want to get the location from Network not GPS. So I change: lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 1, this); to lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this); Then I get nothing. Is this down to an error in the code, or is it that the location doesn't change as frequently as it does with GPS therefore onLocationChange is never called? If I want to see the location at this time without a change should I use .getLastKnownLocation if so where can I call this so that it will update when the app starts? A: The cause could be that you have to move much more than in GPS mode. Try to move for some kilometers, and look if you still don't get an location update. Try to set minTime to 6000 ms, meters i would set 10 or much more. Check if you have to enable Network service. A: Did you use LocationManager.isProviderEnabled() to see if the Network provider is enabled/disabled. network_enabled=locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); and if it is disabled: startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);
doc_23534816
import numpy as np import matplotlib.pyplot as plt y1 = np.random.randn(100) y2 = np.random.randn(100)+2 y3 = 2*np.random.randn(100)+2 y4 = np.random.randn(100) y = np.append(np.append(np.append(y1,y2),y3),y4) fig = plt.figure() ax = fig.add_subplot(111) ax.plot(y) def exp_smoothing(y, alpha): s=np.zeros(len(y)) s[0] = y[0] for i in range(1,len(y)): s[i] = alpha*y[i]+(1-alpha)*s[i-1] return np.array(s) ax.plot(exp_smoothing(y,.05), c='r') plt.show() This gives the following output: The red line gives a good idea about the change in mean that's occurring, but not about the change in variance. I would like to vary the line's thickness, so that thicker parts indicate sections of the original trend with high variance, and thinner parts indicate sections of the original trend with low variance. The only way I can think of this is by plotting not one line, but many smaller lines, with the width of each set using set_lw (see documentation). Is there a better way to go about this?
doc_23534817
while (pq.size() > 1) { // Extract shortest two ropes from pq int first = pq.top(); pq.pop(); int second = pq.top(); pq.pop(); // Connect the ropes: update result and // insert the new rope to pq res += first + second; pq.push(first + second); } It is known that inserting into priority queue for n elements is O(nlogn) operation. But lets say priority queue is implemented as an array. Won't it become O(N*N) operation. Or what will be the complexity for the above code for n elements. A: A well-implemented priority queue will insert elements in O (log n) amortised steps per insertion. A well-implemented priority queue is quite likely to use an array, with the array elements arranged according to the heapsort algorithm.
doc_23534818
I was hoping someone may be able to help me think of this differently, or realize what I'm missing. Google hasn't been much help. My guess is that it's because I'm trying to send a click event to a game window (openGL), vs. a normal window. Here is another example of what I'm trying to send: CGEventRef CGEvent; NSEvent *customEvent; NSPoint location; location.x = 746; location.y = 509; customEvent = [NSEvent mouseEventWithType: NSLeftMouseDown location: location modifierFlags: NSLeftMouseDownMask timestamp: time(NULL) windowNumber: windowID context: NULL eventNumber: 0 clickCount: 1 pressure: 0]; CGEvent = [customEvent CGEvent]; CGEventPostToPSN(&psn, CGEvent); Interestingly enough, I can move the mouse fine (CGDisplayMoveCursorToPoint(kCGDirectMainDisplay, clickPt);), I just can't send any clicks :/ Any help would be greatly appreciated. Edit: Here is what is strange, once I move the mouse using CGDisplayMoveCursorToPoint, I actually have to physically move my mouse up or down a hair before I can even click, which is odd. The game doesn't accept any input unless I move it up/down (and the pointer then changes). Thanks! A: Well what you are try to build is "bot" or "robot" which basically sends commands in an orderly fashion to a game. Basically it will play for you as you are afk. This is great for games that force you to play to harvest minerals, commodities or whatever gives you money to advance in the game. Which is really kind of boring. I have successfully done this for a popular game, although i cannot mention the game as it breaks the user agreements which all these type of games have against "bots". So beware of what you are doing, as it may break your user agreement for many MMPG. But i post this successfully here because, the Mac has less bots available, none that i have been able to research, vs the PC which i have found many. So to level the playing field.. here is the code. I recommend to compile it as command line, and execute the macro in AppleScript (were the logic will reside on how to mimic the games click mouses, movements and send keys, basically your AI. 1.- First you need to run class that will get your psn "process serial number" which all games have. Basically what Thread it is running at. You can find out the name of the process in the utility in the Mac called "Activity Monitor". This can also be done easily in AppleScript. Once you have the name, this class will locate and give you back its psn. #import <Cocoa/Cocoa.h> #include <Carbon/Carbon.h> #include <stdio.h> @interface gamePSN : NSObject { ProcessSerialNumber gamePSN; ProcessInfoRec gameProcessInfo; pid_t gameUnixPID; } - (ProcessSerialNumber) gamePSN; - (ProcessInfoRec) gameProcessInfo; - (pid_t) gameUnixPID; - (void) getPSN; @end @implementation gameSN - (ProcessSerialNumber) gamePSN { return gamePSN; } - (ProcessInfoRec) gameProcessInfo { return gameProcessInfo; } - (pid_t) gameUnixPID; { return gameUnixPID; } - (void) getPSN { auto OSErr osErr = noErr; auto OSErr otherErr = noErr; auto ProcessSerialNumber process; auto ProcessInfoRec procInfo; auto Str255 procName; auto FSSpec appFSSpec; auto char cstrProcName[34]; auto char one ='G'; // FIRST CHARCTER OF GAME PROCESS NAME THESE NEED TO BE CHANGED AS I PUT IN FAKES auto char two ='A'; // SECOND CHARACTER OF GAME PROCESS NAME THESE NEED TO BE CHANGED AS I PUT IN FAKES auto char three = 'M'; // THIRD CHARACTER OF GAME PROCESS NAME THESE NEED TO BE CHANGED AS I PUT IN FAKES auto unsigned int size; process.highLongOfPSN = kNoProcess; process.lowLongOfPSN = kNoProcess; procInfo.processInfoLength = sizeof(ProcessInfoRec); procInfo.processName = procName; procInfo.processAppSpec = &appFSSpec; while (procNotFound != (osErr = GetNextProcess(&process))) { if (noErr == (osErr = GetProcessInformation(&process, &procInfo))) { size = (unsigned int) procName[0]; memcpy(cstrProcName, procName + 1, size); cstrProcName[size] = '\0'; // NEEDS TO MATCH THE SIGNATURE OF THE GAME..FIRST THREE LETTERS // IF YOU CANT FIND IT WITH THE ACTIVITY MONITOR UTILITY OF APPLE MAC OS // THEN RUN THIS SAME CLASS WITH AN NSLOG AND IT WILL LIST ALL YOUR RUNNING PROCESSES. if ( (((char *) &procInfo.processSignature)[0]==one) && (((char *) &procInfo.processSignature)[1]==two) && (((char *) &procInfo.processSignature)[2]==three) && (((char *) &procInfo.processSignature)[3]==two)) { gamePSN = process; otherErr = GetProcessInformation(&gamePSN, &gameProcessInfo); otherErr = GetProcessPID(&process, &gameUnixPID); } } } } Once you have this process number it is easy to send key events as well as mouse events. Here is the mouse event clicks to send. // mouseClicks.h // ClickDep // Created by AnonymousPlayer on 9/9/11. #import <Foundation/Foundation.h> @interface mouseClicks : NSObject - (void) PostMouseEvent:(CGMouseButton) button eventType:(CGEventType) type fromPoint:(const CGPoint) point; - (void) LeftClick:(const CGPoint) point; - (void) RightClick:(const CGPoint) point; - (void) doubleLeftClick:(const CGPoint) point; - (void) doubleRightClick:(const CGPoint) point; @end / // mouseClicks.m // ClickDep // Created by AnonymousPlayer on 9/9/11.v #import "mouseClicks.h" @implementation mouseClicks - (id)init { self = [super init]; if (self) { // Initialization code here if you need any. } return self; } - (void) PostMouseEvent:(CGMouseButton) button eventType:(CGEventType) type fromPoint:(const CGPoint) point; { CGEventRef theEvent = CGEventCreateMouseEvent(NULL, type, point, button); CGEventSetType(theEvent, type); CGEventPost(kCGHIDEventTap, theEvent); CFRelease(theEvent); } - (void) LeftClick:(const CGPoint) point; { [self PostMouseEvent:kCGMouseButtonLeft eventType:kCGEventMouseMoved fromPoint:point]; NSLog(@"Click!"); [self PostMouseEvent:kCGMouseButtonLeft eventType:kCGEventLeftMouseDown fromPoint:point]; sleep(2); [self PostMouseEvent:kCGMouseButtonLeft eventType:kCGEventLeftMouseUp fromPoint:point]; } - (void) RightClick:(const CGPoint) point; { [self PostMouseEvent:kCGMouseButtonRight eventType:kCGEventMouseMoved fromPoint:point]; NSLog(@"Click Right"); [self PostMouseEvent:kCGMouseButtonRight eventType: kCGEventRightMouseDown fromPoint:point]; sleep(2); [self PostMouseEvent:kCGMouseButtonRight eventType: kCGEventRightMouseUp fromPoint:point]; } - (void) doubleLeftClick:(const CGPoint) point; { [self PostMouseEvent:kCGMouseButtonRight eventType:kCGEventMouseMoved fromPoint:point]; CGEventRef theEvent = CGEventCreateMouseEvent(NULL, kCGEventLeftMouseDown, point, kCGMouseButtonLeft); CGEventPost(kCGHIDEventTap, theEvent); sleep(2); CGEventSetType(theEvent, kCGEventLeftMouseUp); CGEventPost(kCGHIDEventTap, theEvent); CGEventSetIntegerValueField(theEvent, kCGMouseEventClickState, 2); CGEventSetType(theEvent, kCGEventLeftMouseDown); CGEventPost(kCGHIDEventTap, theEvent); sleep(2); CGEventSetType(theEvent, kCGEventLeftMouseUp); CGEventPost(kCGHIDEventTap, theEvent); CFRelease(theEvent); } - (void) doubleRightClick:(const CGPoint) point; { [self PostMouseEvent:kCGMouseButtonRight eventType:kCGEventMouseMoved fromPoint:point]; CGEventRef theEvent = CGEventCreateMouseEvent(NULL, kCGEventLeftMouseDown, point, kCGMouseButtonRight); CGEventPost(kCGHIDEventTap, theEvent); sleep(2); CGEventSetType(theEvent, kCGEventRightMouseUp); CGEventPost(kCGHIDEventTap, theEvent); CGEventSetIntegerValueField(theEvent, kCGMouseEventClickState, 2); CGEventSetType(theEvent, kCGEventRightMouseDown); CGEventPost(kCGHIDEventTap, theEvent); sleep(2); CGEventSetType(theEvent, kCGEventRightMouseUp); CGEventPost(kCGHIDEventTap, theEvent); CFRelease(theEvent); } @end You may need to play with the sleep which is the time interval between pushing the mouse button and releasing it. I have found that using 1 second sometimes it does not do it. Putting 2 seconds make it work all the time. So your main would to the following. int main(int argc, char *argv[]) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSUserDefaults *args = [NSUserDefaults standardUserDefaults]; // Grabs command line arguments -x, -y, -clicks, -button // and 1 for the click count and interval, 0 for button ie left. int x = [args integerForKey:@"x"]; int y = [args integerForKey:@"y"]; int clicks = [args integerForKey:@"clicks"]; int button = [args integerForKey:@"button"]; //int interval= [args integerForKey:@"interval"]; int resultcode; // PUT DEFAULT VALUES HERE WHEN SENT WITH EMPTY VALUES /*if (x==0) { x= 1728+66; y= 89+80; clicks=2; button=0; } */ // The data structure CGPoint represents a point in a two-dimensional // coordinate system. Here, X and Y distance from upper left, in pixels. CGPoint pt; pt.x = x; pt.y = y; // Check CGEventPostToPSN Posts a Quartz event into the event stream for a specific application. // only added the front lines plus changed null in Create Events to kCGHIDEventTap gamePSN *gameData = [[gamePSN alloc] init]; [gameData getPSN]; ProcessSerialNumber psn = [gameData gamePSN]; resultcode = SetFrontProcess(&psn); mouseClicks *mouseEvent =[[mouseClicks alloc] init]; if (button == 0) { if (clicks==1) { [mouseEvent LeftClick:pt]; } else { [mouseEvent doubleLeftClick:pt]; } } if (button == 1) { if (clicks==1) { [mouseEvent RightClick:pt]; } else { [mouseEvent doubleRightClick:pt]; } } [gameData release]; [mouseEvent release]; [pool drain]; return 0; } Hope this is helpful.... remember you can execute this in the terminal or in AppleScript by sending the following command. do shell script "/...Path to Compiled Program.../ClickDep" & " -x " & someX & " -y " & someY & " -clicks 1 -button 1" HAPPY GAMING!!!!
doc_23534819
I will be using PHP code to insert this data into MYSQL database. I will not be able to store these text files in memory! Therefor I have to process each data-file line by line. To do this I am using stream_get_line(). * *Some of the data contained will be updates, some will be inserts. Question Would it be faster to use Insert / Select / Update statements, or create a CSV file and import it that way? Create a file thats a bulk operation and then execute it from sql? I need to basically insert data with a primary key that doesnt exist, and update fields on data if the primary key does exist. But I will be doing this in LARGE Quantities. Performance is always and issue. Update The table has 22,000 Columns, and only say 10-20 of them do not contain 0. A: I would load all of the data to a temporary table and let mysql do the heavy lifting. * *create the temporary table by doing create table temp_table as select * from live_table where 1=0; *Read the file and create a data product that is compatible for loading with load data infile. *Load the data into the temporary table and add an index for your primary key *Next Isolate you updates by doing a inner query between the live table and the temporary table. walk through and do your updates. *remove all of your updates from the temporary (again using an inner join between it and the live table). *process all of the inserts with a simple insert into live_table as select * from temp_table. *drop the temporary table, go home and have a frosty beverage. This may be over simplified for your use case but with a little tweaking it should work a treat.
doc_23534820
HANDLE hToken; if(OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY, &hToken)) { DWORD dwSize = 0; if(!GetTokenInformation(hToken, TokenPrivileges, NULL, dwSize, &dwSize) && ::GetLastError() == ERROR_INSUFFICIENT_BUFFER) { BYTE* pb = new (std::nothrow) BYTE[dwSize]; if(pb) { TOKEN_PRIVILEGES* pTPs = (TOKEN_PRIVILEGES*)pb; DWORD dwSize2; if(GetTokenInformation(hToken, TokenPrivileges, pTPs, dwSize, &dwSize2) && dwSize2 <= dwSize) { for(UINT i = 0; i < pTPs->PrivilegeCount; i++) { //Analyze privilege attributes to understand if it's enabled or disabled? DWORD dwPrivAttr = pTPs->Privileges[i].Attributes; //... } } delete[] pb; } } CloseHandle(hToken); } So let's see the structure of TOKEN_PRIVILEGES and LUID_AND_ATTRIBUTES in particular: #define SE_PRIVILEGE_ENABLED_BY_DEFAULT (0x00000001L) #define SE_PRIVILEGE_ENABLED (0x00000002L) #define SE_PRIVILEGE_REMOVED (0X00000004L) #define SE_PRIVILEGE_USED_FOR_ACCESS (0x80000000L) It looks like it is defined as a bitmask, but that brings up the following questions of interpreting these flags: * *What is the difference between ENABLED and ENABLED_BY_DEFAULT? *What is SE_PRIVILEGE_USED_FOR_ACCESS and how can it be used? *What if both SE_PRIVILEGE_ENABLED and SE_PRIVILEGE_REMOVED are set? Or, reset? *I just ran a simple test and for my process the SeShutdownPrivilege privilege had those attributes set as 0. So what is that supposed to mean? I'm more confused over this structure, but I'll keep it at just these points for now. Thank you! A: To take your questions in order: * *ENABLED_BY_DEFAULT means the privilege is one of those that is enabled when the process starts. If you have ENABLED but not ENABLED_BY_DEFAULT then the process has enabled the privilege explicitly. If you have ENABLED_BY_DEFAULT but not ENABLED then the process has disabled the privilege explicitly. *According to the documentation, SE_PRIVILEGE_USED_FOR_ACCESS is set whenever the privilege is actually used. You might use this for troubleshooting, e.g., to detect that you are setting privileges that you are not actually using, or to determine experimentally which privileges a particular system call needs. (I've never checked whether this actually behaves as documented, though I have no reason to think otherwise.) *If both SE_PRIVILEGE_ENABLED and SE_PRIVILEGE_REMOVED are set, you've found a bug in Windows. :-) If neither SE_PRIVILEGE_ENABLED nor SE_PRIVILEGE_REMOVED are set, then the privilege is present in the token, and has not been removed, but is not currently enabled. You can enable it (or remove it) with AdjustTokenPrivileges(). *If the attribute is zero, then the privilege is present in the token but is not currently enabled, has not been removed, was not enabled by default, and has never been used by the process. A: What some of us may need to be told explicitly is that privileges have THREE possible states, not just two. As I began researching this stuff, I thought that a process would either have, or not have a privilege. But it turns out that even if the process has a privilege, it can be in a disabled state. In other words, disabled != doesn't have it. The rest follows logically. If a privilege is not present in the process' access token, the process does not have that privilege. And vice versa, if the process does not have a privilege, the privilege will not be present in the token. If the process has the privilege, the process can enable or disable it at will, right? Why is this useful? All right, I can guess that this allows you to call library functions without fully knowing what they do, and have them fail if they do more than you thought... Odd though.
doc_23534821
I know the regularization loss in pytorch usually defined through the defination of the optimizer (weight_decay): torch.optim.SGD(params, lr=<required parameter>, momentum=0, dampening=0, weight_decay=1e-5, nesterov=False) how can I get the regularization loss value so that I can print it? A: According to this answer, the regularization loss is never computed explicitly. So, what you need to do is calculate the loss on your own using the parameters. Something like l2_loss = 0 for param in net.parameters() : l2_loss += 0.5 * torch.sum(param ** 2)
doc_23534822
<form class="form-horizontal" ng-submit="onSubmit()" method="POST" id='products'enctype="multipart/form-data" novalidate="novalidate"> <input type="hidden" name="_token" value="IPcUrZpuTnJQE22gFYCuD9bWMz5q90eCVvrlmtY4"> <div class="form-group" ng-class=""> <label class="col-md-2 control-label ">Product Name</label> <div class="col-md-10"> <input class="form-control" name="prod_name" size ="" ng-model='myMoudle.prod_name' maxlength="" type="text" required="required" value=""> </div> </div> <div class="form-group" ng-class=""> <label class="col-md-2 control-label ">Picture</label> <div class="col-md-10"> <input class="form-control " name="prod_pic" ng-model='myMoudle.prod_pic' type="file" file-input="files" value=""> </div> </div> <div class="form-group" ng-class=""> <label class="col-md-2 control-label ">Price</label> <div class="col-md-10"> <input class="form-control " name="prod_price" ng-model='myMoudle.prod_price' type="number" value=""> </div> </div> <button type="submit" class="btn btn-info btn-sm pull-left"><i class="fa fa-plus"></i></button> </form> My js code: app = angular.module('myMoudle', []); app.controller('myController', function ($scope, $http) { $scope.names = []; $scope.onSubmit = function () { var fd = new FormData(); $http({ method: 'POST', url: 'CreateProducts', headers: { "Content-Type": undefined }, data: fd }) .success(function (response) { $scope.names = response; }) .error(function (response) { console.log(response); }); } }); and my php controller function looks like this: public function postCreateProducts(Request $request) { print_R($_FILES) ; echo $request->input('prod_name'); $posts = Input::all(); print_R($posts) ; } all that is shown is Array(), Array(). And not what I send in the form.
doc_23534823
<form id="form" action="#" > <h1>Data Package source information</h1> <fieldset> <h2>Specify the details of the new Data Package</h2> <div class="row"> <div class="col-lg-8" id="importFileData"> <div class="form-group"> <label>Customer *</label> <select class="form-control required" id="selectCustomer" data-bind="options: customers, optionsText: 'Name', optionsValue: 'Id'"></select> </div> <div class="form-group"> <label>System type *</label> <select class="form-control required" id="selectSystem" data-bind="options: systems, optionsText: 'Name', optionsValue: 'TypeId'"></select> </div> <div class="form-group"> <label>Select the instrument where the data package comes from *</label> <select class="form-control required" id="selectInstrument" data-bind="options: instruments, optionsText: 'SerialNumber', optionsValue: 'SerialNumber'"></select> </div> <div class="form-group"> <label class="font-noraml">Select the date of import (by default today)</label> <div class="input-group date"> <span class="input-group-addon"><i class="fa fa-calendar"></i></span><input id="importDate" type="text" class="form-control" value="@DateTime.Now.ToString("d")"> </div> </div> </div> <div class="col-lg-4"> <div class="text-center"> <div style="margin-top: 20px"> <i class="fa fa-sign-in" style="font-size: 180px; color: #e5e5e5"></i> </div> </div> </div> </div> </fieldset> </form> And here the Javascript: $("#form") .steps({ bodyTag: "fieldset", onStepChanging: function (event, currentIndex, newIndex) { var form = $(this); // Always allow going backward even if the current step contains invalid fields! if (currentIndex > newIndex) { return true; } form.validate(); // Start validation; Prevent going forward if false return form.valid(); }, onStepChanged: function (event, currentIndex, priorIndex) { }, onFinishing: function (event, currentIndex) { var form = $(this); form.validate(); // Start validation; Prevent form submission if false return form.valid(); }, onFinished: function (event, currentIndex) { var form = $(this); // Submit form input form.submit(); } }) .validate({ errorPlacement: function (error, element) { element.before(error); } }); $("#selectCustomer") .select2({ placeholder: "Select a customer", allowClear: true }) .on("change", function (e) { var selectedCustomerId = $("#selectCustomer").val(); $.ajax({ url: self.getValidUrl() + "/api/DataPackageManagementApi/Systems/" + selectedCustomerId, async: true, type: "GET", success: function (results) { self.importDataPackageViewModel.systems.removeAll(); self.importDataPackageViewModel.systems.push(""); $.each(results, function (key, item) { self.importDataPackageViewModel.systems.push(item); }); $("#selectSystem").prop("disabled", false); }, error: function (jqXhr, textStatus, errorThrown) { console.log(JSON.stringify(jqXhr)); console.log("AJAX error: " + textStatus + " : " + errorThrown); } }); }); $("#selectSystem") .select2({ placeholder: "Select a system", allowClear: true, disabled: true }) .on("change", function (e) { var selectedCustomerId = $("#selectCustomer").val(); var selectedSystemId = $("#selectSystem").val(); $.ajax({ url: self.getValidUrl() + "/api/DataPackageManagementApi/Instruments/" +selectedCustomerId +"/" +selectedSystemId, async: true, type: "GET", success: function (results) { self.importDataPackageViewModel.instruments.removeAll(); self.importDataPackageViewModel.instruments.push(""); $.each(results, function (key, item) { self.importDataPackageViewModel.instruments.push(item); }); $("#selectInstrument").prop("disabled", false); }, error: function (jqXhr, textStatus, errorThrown) { console.log(JSON.stringify(jqXhr)); console.log("AJAX error: " + textStatus + " : " + errorThrown); } }); }); $("#selectInstrument") .select2({ placeholder: "Select a Instrument", allowClear: true, disabled: true }); My problem are two: * *The validation of the form only validates the first select2 input control, never the second nor the third. *The style of the select2 validation error does not match with the rest of the validation controls. Does anyone know what am I doing wrong? I've searched both jquery.validation and select2 documentation and examples and to me it looks like I'm doing it correctly, but obviously there is a mistake somewhere. Many thanks in advance! Regards, Javier A: You can validate something like this: $('#form-add-comment').validate({ onkeyup: false, rules: { Comment: "required" }, messages: { Comment: "Please enter Comment" }, errorClass: "has-error", validClass: "success", highlight: function (element, errorClass, validClass) { var elem = $(element); if (elem.hasClass("select2-offscreen")) { elem.parent().addClass('Select2Error'); } else { elem.parent().addClass(errorClass); } }, unhighlight: function (element, errorClass, validClass) { var elem = $(element); if (elem.parent().hasClass(errorClass)) elem.siblings('.error-container').remove(); if (elem.hasClass("select2-offscreen")) { $("#" + elem.attr("id")).on("change", function () { $(this).parent.removeClass("Select2Error"); }); elem.parent().removeClass('Select2Error'); elem.siblings('.error-container').remove(); } else { elem.parent().removeClass(errorClass); } }, errorPlacement: function (error, element) { var container = $('<div />'); container.addClass('error-container'); $("#" + element[0].id).addClass('disp-error'); error.insertBefore(element); error.wrap(container); error.insertBefore(error); }, });
doc_23534824
package example.portlet; @Component( immediate = true, property = { "com.liferay.portlet.display-category=category.sample", "com.liferay.portlet.instanceable=true", "javax.portlet.display-name=Example Portlet", "javax.portlet.init-param.template-path=/", "javax.portlet.init-param.view-template=/view.jsp", "javax.portlet.resource-bundle=content.Language", "javax.portlet.security-role-ref=power-user,user" }, service = Portlet.class ) public class ExamplePortlet extends MVCPortlet { @Override public void serveResource(ResourceRequest request, ResourceResponse response) throws IOException, PortletException { ... } } I would like to call this portlet using A.io.request from existing JavaScript which is outside of portlet module. How can I do that? What url should I provide? A: A portlet has a URL depending on the page its on and potentially then on the instance, as it could be added to the page multiple times. Thus one cannot really know "the" URL. If this is rightfully portlet code, you should encapsulate its call or at least the URL resolution in the portlet. Otherwise it might need to be in a servlet or even both (e.g. in a library called by the servlet and a portlet). A: As Olaf pointed out, you don't get an URL to a portlet. You can get URL to a portlet instance that is placed on some page in some site in some server instance. If you simply want something that serves JSON (regardless of the page/site/instance), you don't have to write a portlet for it. You can just write restful service that Liferay will happily serve for you. An example can be found here.
doc_23534825
This is the error : ValidationError: Account validation failed: email: Path `email` is required. at new ValidationError (/api/node_modules/mongoose/lib/error/validation.js:31:11) at model.Document.invalidate (/api/node_modules/mongoose/lib/document.js:2413:32) at p.doValidate.skipSchemaValidators (/api/node_modules/mongoose/lib/document.js:2262:17) at /api/node_modules/mongoose/lib/schematype.js:1058:9 at processTicksAndRejections (internal/process/task_queues.js:79:11) And this is my code : /*******************FACEBOOK AUTH*************************/ passport.use( new FacebookStrategy({ // options for facebook strategy clientID: XXXXXXXXXXXXXXXXXX, clientSecret: "XXXXXXXXXXXXXXXXXXXXX", callbackURL: "http://localhost:3001/auth/facebook/callback", profileFields : ['id', 'displayName', 'email'] }, (accessToken, refreshToken, profile, done) => { // passport callback function console.log('passport callback function fired:'); console.log(profile); if(profile!==null){ var id = profile.id; var email = profile.email; console.log(id); console.log(email); var strfullname = profile.displayName; var fullname = strfullname.split(/(\s+)/); var nom = fullname[2]; var prenom = fullname[0]; console.log("nom "+ nom); console.log("prenom "+ prenom); Account.findOne({'email' : email},function (err, account){ if(err){ console.log(err); done(err); } if(account){//exist if(err){ console.log(err); done(err); } else {//get account console.log('currentAccount'); //check if enable = true if(account.enable===true){ //send token try{ jwt.sign({ account },config.secretKey, (err,token)=>{ if(err){ done(err) } else{ done(null,token); } }); } catch(e){ done(err); } }else{ done("This account is disabled, please contact support for more information",null); } } } else{//new account if(err) { console.log(err); done(err); } const account = new Account({ email : email, nom : nom, acceptCGU : true, prenom : prenom, facebook : { id : id, email : email, name : strfullname } }); //save data account.save((err => { if(err){ console.log(err); done(err); } else{ console.log('newaccount'); //send email var smtpTransport = nodemailer.createTransport({ service : 'gmail', auth : { user : "xxxxx.xxxxx@gmail.com", pass : "xxxxxxxxx" } }); var mailOptions = { to : email, from : "xxxxx.xxxxx@gmail.com", subject : "Bienvenue chez XXXXX !", text : "Bienvenue chez xxxxxx ! \n \n Votre compte : "+email+" a bien été créé. \n \n Nos dernières offres exclusives n'attendent plus que vous sur notre site xxxxx.\n A bientôt ! \n \n L'équipe XXXX" } smtpTransport.sendMail(mailOptions,function(err){ if(err){ res.status(400); resultats = { "success": false, "message": 'Error : '+ err, "result": '' } res.json(resultats); } else{ //send token try{ jwt.sign({ account },config.secretKey, (err,token)=>{ if(err){ done(err) } else{ done(null,token); } }); } catch(e){ done(err); } } }); } })); } }); } }) ); Routes: /*******************FACEBOOK AUTH ROUTES********************* */ // auth with faceboook router.get('/auth/facebook', passport.authenticate('facebook')); // callback route for facebook to redirect to // hand control to passport to use code to grab profile info router.get('/auth/facebook/callback*', passport.authenticate('facebook'), (req, res) => { if(req.user){ res.cookie('token', req.user); return res.redirect("http://localhost:3000"); } else{ console.log('error'); return res.redirect("http://localhost:3000"); } }); A: I've resolved that by changing this line: var email = profile.email; to var email = profile._json.email;
doc_23534826
Imagine your celery worker tasks and your beat scheduler all work fine. Using default construction methods you will be stuck with 2 logfiles defined by, e.g. : celery worker ..... -f ./logs/celeryworker.log celery beat ..... -f ./logs/celerybeat.log These will just grow indefinitely. How can I introduce a rotating log? A: The default celery logging.FileHandler is a WatchedFileHandler. We want to use a TimedRotatingFileHandler from logging.handlers. So we use the celery signal after_setup_logger in our tasks file to accomplish the following : from celery.signals import after_setup_logger @after_setup_logger.connect def replace_handler(**kwargs_): logger = kwargs_['logger'] if 'logger' in kwargs_ else None if logger and logger.handlers: handler_celery = logger.handlers[-1] handler = TimedRotatingFileHandler(handler_celery.baseFilename, 'midnight', 1) handler.setFormatter(handler_celery.formatter) logger.handlers[-1] = handler Now this resets both the worker and beat logger. I have tested this using 2 minute intervals in the TimedRotatingFileHandler constructor, so I assume it works for overnight rotation. EDIT1: 25/09/2019 Thanks to Tomáš Linhart - I shall look into logrotate. I was up coding tonight, so I checked that the log indeed rotates overnight. I also updated the code slightly to be a bit safer. I have quite a simple setup : concurrency=1 where I need a FIFO queue of tasks to be processed sequentially, so maybe this simple solution masks potential problems pointed out by Tomáš. EDIT2: 25/09/2019 I have spent time looking into this. There are still several problems : WatchedFileHandler is linux only and can still suffer from race conditions, while logrotate itself can also suffer from race conditions. https://docs.python.org/3/howto/logging-cookbook.html#logging-to-a-single-file-from-multiple-processes explains multi-process logging and https://docs.python.org/3/howto/logging-cookbook.html explains how to use a QueueListener rather than creating your own multiprocessing.Process. Putting this all together I have created a multi-process class wrapper for the TimedRotatingFileHandler : import logging from logging.handlers import QueueHandler, QueueListener, TimedRotatingFileHandler from multiprocessing import Queue as MQueue import multiprocessing.queues from celery.signals import after_setup_logger from atexit import register class QueuedTimedRotatingFileHandler: instance = None def __init__(self, filename_, formatter_): self.queue = MQueue(-1) handler = TimedRotatingFileHandler(filename_, 'midnight', 1) handler.setFormatter(formatter_) self.listener = QueueListener(self.queue, handler) self.listener.start() register(self.stop) def stop(self): self.listener.stop() @after_setup_logger.connect def replace_handler(**kwargs_): logger = kwargs_['logger'] if 'logger' in kwargs_ else None if logger and logger.handlers: handler_celery = logger.handlers[-1] if QueuedTimedRotatingFileHandler.instance is None: QueuedTimedRotatingFileHandler.instance = \ QueuedTimedRotatingFileHandler( handler_celery.baseFilename, handler_celery.formatter ) handler = QueueHandler(QueuedTimedRotatingFileHandler.instance.queue) logger.handlers[-1] = handler This now feels like the safest and most elegant cross-platform solution. Any comments welcome. EDIT3: 26/09/2019 Last change I think, have altered the code above. Needed to construct the wrapper like a singleton because celery worker can parse file multiple times. EDIT4: 02/10/2019 One last change. Stopping the listener needs to be registered with atexit to be triggered correctly.
doc_23534827
The problem is if I encrypt those fields then I am not able to manipulate them like aggregating the results or searching etc. Any pointers would be appreciated.
doc_23534828
A: You can create a jar base on you Jython http://wiki.python.org/jython/JythonFaq/DistributingJythonScripts
doc_23534829
list_box = Gtk.ListBox() list_box.insert(Gtk.Label('foo'), -1) list_box.insert(Gtk.Label('bar'), -1) list_box.insert(Gtk.Label('qux'), -1) # ListBoxRow is added automatically window = Gtk.Window() window.add(list_box) window.show_all() When I call show_all(), the first row of the list is being selected automatically what I don't want to happen. How to prevent auto-selecting it? I tried changing the order of the functions call window.show_all() window.add(list_box) which broke the layout and the size of the window doesn't fit to the list. A: I was running into this issue as well, I used the following code to do it: listbox = Gtk.ListBox(margin=0) listbox.set_selection_mode(Gtk.SelectionMode.NONE) I can still click on each row and do a callback with the following, as well: listbox.connect("row-activated", self.callback) A: The ListBox has a property selection-mode, which you can set to Gtk.SELECTION_NONE. In this case none of the rows will be selected (and cannot be selected later). I don't know if that is what you want. You can also call the method unselect_all, which will unselect all rows. For this to work, the ListBox must be in SELECT_MULTIPLE or SELECT_SINGLE mode. This example seems to work completely as expected (i.e. no selection at the start, and if a line is selected, the button can unselect it). If in your installation it doesn't work, I would try to update your packages: from gi.repository import Gtk class MainWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self) self.connect("delete-event", self.on_delete) self.listbox = Gtk.ListBox() self.listbox.insert(Gtk.Label('foo'), -1) self.listbox.insert(Gtk.Label('bar'), -1) self.listbox.insert(Gtk.Label('qux'), -1) # ListBoxRow is added automatically button = Gtk.Button("Clear selection") button.connect("clicked", self.on_button_clicked) vbox = Gtk.VBox() vbox.pack_start(button, False, True, 0) vbox.pack_start(self.listbox, False, True, 0) self.add(vbox) self.show_all() Gtk.main() def on_button_clicked(self, btn): self.listbox.unselect_all() def on_delete(self, win, event): Gtk.main_quit() def main(): w = MainWindow() return 0 if __name__ == '__main__': main() A note about gtk3 themes: Some themes do not show selected rows at all. Particularly dark themes such as eg. FlatStudioDark, but also some light themes. A: Add a dummy label to the top of your list_box and hide it: dummyLabel = Gtk.Label('nothing') # workaround for focus of title entry list_box.insert(dummyLabel, -1) list_box.insert(Gtk.Label('foo'), -1) list_box.insert(Gtk.Label('bar'), -1) list_box.insert(Gtk.Label('qux'), -1) # ListBoxRow is added automatically window = Gtk.Window() window.add(list_box) window.show_all() dummyLabel.hide() Gtk.main() The result: result
doc_23534830
Tab bar A: To style the editor's area described the question above, use the property displayed below. "editorGroupHeader.tabsBackground": "#00FF00" It seems some people are confused how to get the property to activly change the color of the area that the property is responsible for, so I added 2 examples of how to correctly use V.S. Code Color-Token theme-properties below. There are two examples, because there are two ways to use it. The first is shown here. 1.  Using the Property in a Theme Below shows how to use the property that colors the area described by the author of the question. The author asked specificly for the background, but I included all three properties that are responsible for coloring the area. This example demonstrates using a theme to color the V.S. Code Editor. // Using the property in a VSCode Theme: // FILE (Linux): // $HOME/.vscode/extensions/${theme}/themes/${theme}.json // FILE (Windows 10) // C:\Users\${uid}\.vscode\extensions\${theme}\themes\${theme}.json { "$schema": "vscode://schemas/color-theme", "id": "developers-dojo", "type": "dark", "colors": { "editorGroupHeader.tabsBackground": "#021331", "editorGroupHeader.tabsBorder": "#00FF4040", "editorGroupHeader.border": "#000000D0", } } 2. Using the Property in a settings.json File The easiest way to use the property editorGroupHeader.tabsBackground to color the V.S. Code Editor is to simply type the property into your setting.json file, or your work-space's ./.vscode/settings.json file. Just remember that this is a property that belongs to a group of color tokens defined in a location separate from where the settings properties are defined, so if you just add it to your settings.json file, your going to find that the property doesn't work that way. You need to use the special configuration JSON-Property, workbench.colorCustomizations to wrap the color-properties you want to use. If you add the snippet below to a settings.json file, you will change the color of the Tab's Group area. // Use in either your user's "settings.json" file // Or in your work-space's "./.vscode/settings.json" file { "workbench.colorCustomizations": { "editorGroupHeader.tabsBackground": "#0000FF", "editorGroupHeader.tabsBorder": "#0F6C8C", "editorGroupHeader.border": "#FF5010", } }
doc_23534831
My select box. {{ Form::select('destination', array(), null, array('class' => 'large', 'id'=>'destination')) }} My text box. {{ Form::text('depart', null, array('class'=>'date', 'id'=>'date')) }}. And my javascript code. <script type="text/javascript"> $(document).ready(function($){ $('#destination').change(function(){ var origin = $(this).find(':selected').text(); $.get("{{ URL::route('getDate')}}", {origin: origin}, function(data) { var model = $('#date'); model.empty(); $.each(data, function(index, element) { model.append("<input type = "text"value='"+ element +"'/>"); }); }); }); }); This is my controller code public function getDate() { if (Request::ajax()) { $result = []; $first = Input::get('origin'); $tables= Timetable::join('route', 'tbl_rte_id', '=', 'id') ->where('rte_origin', $first) ->orderBy('rte_destination', 'asc') ->get(array('id', 'tbl_start')); foreach ($tables as $table) { $result[$table->id] = $table->tbl_start; } return Response::json($result); } } When I change My javascript code and textbox to selectbox as following it worked. {{ Form::select('ja', array(), null, array('class' => 'large', 'id'=>'ja')) }} <script type="text/javascript"> $(document).ready(function($){ $('#destination').change(function(){ var origin = $(this).find(':selected').text(); $.get("{{ URL::route('getDate')}}", {origin: origin}, function(data) { var model = $('#ja'); model.empty(); $.each(data, function(index, element) { model.append("<option value='"+ element +"'>" + element + "</option>"); }); }); }); }); Problem is on following row model.append("<input type = "text"value='"+ element +"'/>"); How to solve it. A: You're not escaping quotes in: model.append("<input type = "text"value='"+ element +"'/>"); Either use: model.append('<input type="text" value="' + element + '"/>'); or... model.append("<input type=\"text\" value=\"" + element + "\"/>"); If you use an editor with syntax highlighting this should be obvious.
doc_23534832
A: GCM (Google Cloud Messageing) It's not a perfect solution to do work, When a third party server send to request to Google server for push-notification to mobile. After that a Google server is responsible for send push-notification to mobile. Mostly time Google server sent notification immediately. Sometimes it's delay just because of network traffic. Suppose Google server sent notification to device now developer responsibility to handle the request and show the notification on notification. Failure Case (Device side): 1) No Network - If Google server sent notification to your device 2) Slow Network 3) Wrong way to handling message As per your above explanation, you are getting message sometimes that means your code is well! If you performing some task after getting notification---Please choose other solution because you cann't believe on GCM. A: That mainly depends on internet speed. Also at times google server cant process the request. If you received the notification once that proves it will work A: Check your code or server-side code. (also more important network service or google background service) in my case, my GCM service success rate is 65% (google statistics) but I remove 'collapseKey'(in the online sample code) then success rate up to 85% important is GCM isn't 100% success services. (this is google say..) finally, this link will help you http://developer.android.com/guide/google/gcm/gcm.html
doc_23534833
public String everyNth(String str, int n) { String result=""; for(int i=0; i<str.length(); i+=n){ result += " " + str.charAt(i); } return result; } A: What you could do is use a StringBuilder that will be initialized with your input String, then use setCharAt(int index, char ch) to modify a given char, this way you avoid building a new String at each iteration as you currently do with the operator += on String. Something like: public String everyNth(String str, int n) { if (n < 1) { throw new IllegalArgumentException("n must be greater than 0"); } StringBuilder result = new StringBuilder(str); // This will replace every nth character with '-' for (int i = n - 1; i < str.length(); i += n) { result.setCharAt(i, '-'); } return result.toString(); } NB: Starts from n - 1 unless you want to replace the first character too if so starts from 0. If you want to simply remove the characters, you should use the method append(CharSequence s, int start, int end) to build the content of your target String, as next: public String everyNth(String str, int n) { if (n < 1) { throw new IllegalArgumentException("n must be greater than 0"); } StringBuilder result = new StringBuilder(); // The index of the previous match int previous = 0; for (int i = n-1; i < str.length(); i += n) { // Add substring from previous match to the current result.append(str, previous, i); // Set the new value of previous previous = i + 1; } // Add the remaining sub string result.append(str, previous, str.length()); return result.toString(); } A: First of all, you can't replace in a Java String. They're immutable. So you're going to have to make a new String with the right properties. There are a number of ways to do this, one of which involves iterating over the original String and copying characters unless the current index is a multiple of n. You could also convert the String to an Array and loop over every nth element of the array and change those. A: You can use the modulus operator (%) to achieve what you are trying to like so: public String everyNth(String str, int n){ StringBuilder sb = new StringBuilder(); for(int i=0,n=str.length;i<n;i++){ if(i%n==0){ sb.append("-"); else{ sb.append(str.charAt(i); } } return sb.toString(); } A: If you want to use modulus, it could go like this: public static String everyNth(String str, int n, char append) { StringBuilder sb = new StringBuilder(); for (int i = 1; i < str.length(); i++) { if (i % n == 0) { sb.append(append); } else { sb.append(str.charAt(i-1)); } } return sb.toString(); }
doc_23534834
I have some large data files that I can parse out to generate a list of coordinate that are mostly sequential 5 6 7 8 15 16 17 25 26 27 What I want is a list of the gaps 1-4 9-14 18-24 I don’t know perl, SQL or anything fancy but thought I might be able to do something that would subtract one number from the next. I could then at least grep the output where the difference was not 1 or -1 and work with that to get the gaps. A: With awk : awk '$1!=p+1{print p+1"-"$1-1}{p=$1}' file.txt explanations * *$1 is the first column from current input line *p is the previous value of the last line *so ($1!=p+1) is a condition : if $1 is different than previous value +1, then : *this part is executed : {print p+1 "-" $1-1} : print previous value +1, the - character and fist columns + 1 *{p=$1} is executed for each lines : p is assigned to the current 1st column A: interesting question. sputnick's awk one-liner is nice. I cannot write a simpler one than his. I just add another way using diff: seq $(tail -1 file)|diff - file|grep -Po '.*(?=d)' the output with your example would be: 1,4 9,14 18,24 I knew that there is comma in it, instead of -. you could replace the grep with sed to get -, grep cannot change the input text... but the idea is same. hope it helps. A: A Ruby Answer Perhaps someone else can give you the Bash or Awk solution you asked for. However, I think any shell-based answer is likely to be extremely localized for your data set, and not very extendable. Solving the problem in Ruby is fairly simple, and provides you with flexible formatting and more options for manipulating the data set in other ways down the road. YMMV. #!/usr/bin/env ruby # You could read from a file if you prefer, # but this is your provided corpus. nums = [5, 6, 7, 8, 15, 16, 17, 25, 26, 27] # Find gaps between zero and first digit. nums.unshift 0 # Create array of arrays containing missing digits. missing_nums = nums.each_cons(2).map do |array| (array.first.succ...array.last).to_a unless array.first.succ == array.last end.compact # => [[1, 2, 3, 4], [9, 10, 11, 12, 13, 14], [18, 19, 20, 21, 22, 23, 24]] # Format the results any way you want. puts missing_nums.map { |ary| "#{ary.first}-#{ary.last}" } Given your current corpus, this yields the following on standard output: 1-4 9-14 18-24 A: Just remember the previous number and verify that the current one is the previous plus one: #! /bin/bash previous=0 while read n ; do if (( n != previous + 1 )) ; then echo $(( previous + 1 ))-$(( n - 1 )) fi previous=$n done You might need to add some checking to prevent lines like 28-28 for single number gaps. A: Perl solution similar to awk solution from StardustOne: perl -ane 'if ($F[0] != $p+1) {printf "%d-%d\n",$p+1,$F[0]-1}; $p=$F[0]' file.txt These command-line options are used: * *-n loop around every line of the input file, do not automatically print every line *-a autosplit mode – split input lines into the @F array. Defaults to splitting on whitespace. Fields are indexed starting with 0. *-e execute the perl code A: Given input file, use the numinterval util and paste its output beside file, then munge it with tr, xargs, sed and printf: gaps() { paste <(echo; numinterval "$1" | tr 1 '-' | tr -d '[02-9]') "$1" | tr -d '[:blank:]' | xargs echo | sed 's/ -/-/g;s/-[^ ]*-/-/g' | xargs printf "%s\n" ; } Output of gaps file: 5-8 15-17 25-27 How it works. The output of paste <(echo; numinterval file) file looks like: 5 1 6 1 7 1 8 7 15 1 16 1 17 8 25 1 26 1 27 From there we mainly replace things in column #1, and tweak the spacing. The 1s are replaced with -s, and the higher numbers are blanked. Remove some blanks with tr. Replace runs of hyphens like "5-6-7-8" with a single hyphen "5-8", and that's the output. A: This one list the ones who breaks the sequence from a list. Idea taken from @choroba but done with a for. #! /bin/bash previous=0 n=$( cat listaNums.txt ) for number in $n do numListed=$(($number - 1)) if [ $numListed != $previous ] && [ $number != 2147483647 ]; then echo $numListed fi previous=$number done
doc_23534835
public class animation : MonoBehaviour { public RawImage image; public Text text; private Rect rect; // Use this for initialization void Start () { Application.targetFrameRate = 60; rect = image.uvRect; } // Update is called once per frame void FixedUpdate () { rect.y += (Time.fixedDeltaTime*0.1f); text.text = (Time.fixedDeltaTime * 0.1f).ToString() + " : " + Time.fixedDeltaTime + " : "+image.uvRect.y; image.uvRect = rect; } } In Unity's editor animation is smooth, but on devices (iOS or Android) it's not. There are no other scripts in the scene so CPU is not loaded so much to make animation not smooth. So why it's so and how to fix it? A: It's because you using FixedUpdate(). Try to use Update() instead. FixedUpdate should be used to physics operations. You should also chande Time.fixedDeltaTime to Time.deltaTime. FixedUpdate depends on physic steps that you can setup in editor. But Update is based on FPS so your animation will be smoother than in FixedUpdate.
doc_23534836
Feature: Checkout In order to buy products As a customer I need to be able to checkout items in the cart Background: Given step 1 And step 2 @Ready Scenario: Deliver now When step 3 Then step 4 @NoneReady Scenario: Deliver later When step a Then step b And step c @AddressNotCovered Scenario: Address Not Covered When step i Then step ii If I run behat on a single tag, it works just fine: $ behat --tags=Ready Feature: Checkout In order to buy products As a customer I need to be able to checkout items in the cart @Ready Scenario: Deliver now # tests/features/Checkout/CheckOut.feature:9 step 1 And step 2 .. 1 scenario (1 passed) 7 steps (7 passed) 0m3.85s (36.62Mb) But if I run it on multiple tags, it hangs at the end of the first tag: behat --tags=Ready,AddressNotCovered Feature: Checkout In order to buy products As a customer I need to be able to checkout items in the cart @Ready Scenario: Deliver now # tests/features/Checkout/CheckOut.feature:9 Given step .. .. And .. // hangs here What am I doing wrong? Environment Laravel 5.4 Behat 3.1.0 PHP 7.1.23 PHPUnit 5.7.27 from my composer.json "require": { "php": ">=5.5.9", "laravel/framework": "5.4.*", .. "behat/behat": "3.1.0", "laracasts/behat-laravel-extension": "^1.1", }, "require-dev": { "phpunit/phpunit": "~5.7", "phpspec/phpspec": "~2.1", "johnkary/phpunit-speedtrap": "^1.0", }, Behat.yml default: extensions: Laracasts\Behat: env_path: .env.testing autoload: - ./tests/features/bootstrap suites: Checkout: paths: [./tests/features/Checkout] contexts: [CheckoutFeatureContext] Update I tried to create sample gherkin to illustrate the problem above. I ran into the same problem when trying to auto append snippets. Appending snippets worked with a single scenario, but failed on multiple scenarios: working example: single scenario # tests/features/Example/Example.feature Feature: Example In order to show dev team how to use behat/gherkin using background As a developer I need to be able write gherkin using a background and multiple scenarios And all scenarios should run Background: Givens setup condition 1 And setup condition 2 Scenario: scenario one When I perform first sample trigger point Then result one must happen And result two must happen When I run the following command behat tests/features/Example/Example.feature --append-snippets adding snippets worked just fine Feature: Example In order to show dev team how to use behat/gherkin using background As a developer I need to be able write gherkin using a background and multiple scenarios And all scenarios should run Background: # tests/features/Example/Example.feature:9 Givens setup condition 1 And setup condition 2 Scenario: scenario one # tests/features/Example/Example.feature:13 When I perform first sample trigger point Then result one must happen And result two must happen 1 scenario (1 undefined) 4 steps (4 undefined) 0m0.48s (24.63Mb) u tests/features/bootstrap/FeatureContext.php - `setup condition 2` definition added u tests/features/bootstrap/FeatureContext.php - `I perform first sample trigger point` definition added u tests/features/bootstrap/FeatureContext.php - `result one must happen` definition added u tests/features/bootstrap/FeatureContext.php - `result two must happen` definition added failing example: multiple scenarios when we have multiple scenarios # tests/features/Example/Example.feature Feature: Example In order to show dev team how to use behat/gherkin using background As a developer I need to be able write gherkin using a background and multiple scenarios And all scenarios should run Background: Givens setup condition 1 And setup condition 2 Scenario: scenario one When I perform first sample trigger point Then result one must happen And result two must happen Scenario: scenario two When I perform second sample trigger point Then result a must happen And result b must happen running the same --append-snippets command chokes: Feature: Example In order to show dev team how to use behat/gherkin using background As a developer I need to be able write gherkin using a background and multiple scenarios And all scenarios should run Background: # tests/features/Example/Example.feature:9 Givens setup condition 1 And setup condition 2 Scenario: scenario one # tests/features/Example/Example.feature:13 When I perform first sample trigger point Then result one must happen And result two must happen ^C // had to abort here A: It turns out the examples above were too simplistic. After doing some research (especially helpful was this post) I realized that this "stalling" is due to tearing down the database after each test. So this is what fixed it: First I replaced DatabaseTransactions with DatabaseMigrations in my FeatureContext class: class FeatureContext extends TestCase implements Context, SnippetAcceptingContext { use DatabaseMigrations, .. Given the above, I removed the manual migration comand from my bitbucket pipeline script - php artisan --env=testing config:cache which makes sense since with the new code, the database will always be refreshed and migrated before each test. Then I added the setUp() call to the behat hooks: /** @BeforeScenario */ public function before(BeforeScenarioScope $scope) { parent::setUp(); } And that's it. The best part about this solution is that it completely aligned my local testing environment with that of bitbucket pipelines, so that the results were always the same. Further explanation: from our wiki In general, it's a good idea to start each test fresh without left overs from the previous test (esp when it comes to databases). In the words of laravel: It is often useful to reset your database after each test so that data from a previous test does not interfere with subsequent tests. For that we use migrations. That being said, since we're actually using Behat, we need this migration to happen before and after each scenario life cycle. We do that using Behat's hooks. We do that here: /** @BeforeScenario */ public function before(BeforeScenarioScope $scope) { parent::setUp(); } parent::setUP() tells the Laravel framework to do the necessary work before and after each scenario: protected function setUp() { if (! $this->app) { $this->refreshApplication(); } $this->setUpTraits(); <---- here .. This in turn calls setup traits: protected function setUpTraits() { $uses = array_flip(class_uses_recursive(static::class)); if (isset($uses[DatabaseMigrations::class])) { $this->runDatabaseMigrations(); } .. which calls this public function runDatabaseMigrations() { $this->artisan('migrate:fresh'); $this->app[Kernel::class]->setArtisan(null); $this->beforeApplicationDestroyed(function () { $this->artisan('migrate:rollback'); RefreshDatabaseState::$migrated = false; }); } Notice that Laravel will also rollback the changes once the application is destroyed. It's very important to understand this in order to prevent Behat stalling when there are multiple scenarios and a given before them. Also keep in mind that when we use Gherkin like so: Feature: Checkout In order to buy products As a customer I need to be able to checkout items in the cart Background: Given step 1 And step 2 @Ready Scenario: Deliver now When step 3 Then step 4 @NoneReady Scenario: Deliver later When step a Then step b And step c Then each scenario starts with the background steps, not in the scenario steps itself Example: Feature: Checkout In order to buy products As a customer I need to be able to checkout items in the cart Background: Given step 1 <-- every scenario starts here, so we call setup before this step And step 2 @Ready Scenario: Deliver now When step 3 <-- not here Then step 4 @NoneReady Scenario: Deliver later When step a Then step b And step c A: The following steps work for me on Arch Linux and PHP 7.3: composer global require laravel/installer laravel new behat-laravel cd behat-laravel composer require behat/behat behat/mink behat/mink-extension laracasts/behat-laravel-extension --dev touch behat.yml # edit behat.yml # edit features/bootstrap/FeatureContext.php vendor/bin/behat --init # Add steps and tag them vendor/bin/behat vendor/bin/behat --tags Ready,NoneReady # behat.yml default: extensions: Laracasts\Behat: # env_path: .env.behat Behat\MinkExtension: default_session: laravel laravel: ~ <?php // features/bootstrap/FeatureContext.php use Behat\Behat\Hook\Scope\AfterStepScope; use Behat\Behat\Tester\Exception\PendingException; use Behat\Behat\Context\Context; use Behat\Behat\Context\SnippetAcceptingContext; use Behat\Gherkin\Node\PyStringNode; use Behat\Gherkin\Node\TableNode; #This will be needed if you require "behat/mink-selenium2-driver" #use Behat\Mink\Driver\Selenium2Driver; use Behat\MinkExtension\Context\MinkContext; /** * Defines application features from the specific context. */ class FeatureContext extends MinkContext implements Context, SnippetAcceptingContext { /** * Initializes context. * * Every scenario gets its own context instance. * You can also pass arbitrary arguments to the * context constructor through behat.yml. */ public function __construct() { } /** * @When stepready :arg1 */ public function stepready($arg1) { return true; } /** * @When steplater :arg1 */ public function steplater($arg1) { return true; } } # feature/customer.feature Feature: Checkout In order to buy products As a customer I need to be able to checkout items in the cart @Ready Scenario: Deliver now When stepready 1 Then stepready 2 @NoneReady Scenario: Deliver later When steplater 1 Then steplater 2 frosch ➜ behat-laravel vendor/bin/behat --tags Ready,NoneReady Feature: Checkout In order to buy products As a customer I need to be able to checkout items in the cart @Ready Scenario: Deliver now # features/customer.feature:7 When stepready 1 # FeatureContext::stepready() Then stepready 2 # FeatureContext::stepready() @NoneReady Scenario: Deliver later # features/customer.feature:12 When steplater 1 # FeatureContext::steplater() Then steplater 2 # FeatureContext::steplater() 2 Szenarien (2 bestanden) 4 Schritte (4 bestanden) 0m0.02s (18.47Mb)
doc_23534837
FYI, I know there are many methods for including rich object models in Angular. I don't want to go the route of using Restangular at the moment for example. I want to keep this extremely simple at the moment, and hopefully increase my understanding of angular modules. Thanks!! ---------- teacher.js ----------- (function() { var teacherConstructor = function() { var teacher = { student: [] }; return teacher; }; var module = angular.module("MyApp.models"); module.value("teacber", teacberConstructor); }()); ---------- student.js (function() { var studentConstructor = function(theTeacher) { var student = { myTeacher: theTeacher }; return student; }; var module = angular.module("MyApp.models"); module.value("student", studentConstructor); }()); A: A possible solution - use factory: (function() { var module = angular.module("MyApp.models"); module.factory("teacher", ["student", function(Student) { var teacherConstructor = function() { ... var student = new Student(this); ... }; return teacherConstructor; }]); })(); Anyway the definition of the teacher "class" must be done inside Angular's definition function, for it to be able to reference the student. This however introduces an unecessary closure. I would suggest dropping the outer function, in favor of Angular's native way: angular.module("MyApp.models").factory("Teacher", ["student", function(Student) { var Teacher = function() { ... var student = new Student(this); ... }; return Teacher; }]); As a sidenote, it is customary for "classes" to start with capital. i.e. Student, Teacher. And the constructor may as well have the name of the class, thus teacherConstructor → Teacher in the code above.
doc_23534838
@RunWith(Arquillian.class) public class EjbTest { @Inject private RepAlertManager ejb; @Deployment public static Archive<?> createDeployment() { return ShrinkWrap.create(JavaArchive.class, "foo.jar") .addClasses(RepAlertManagerImpl.class) .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"); } @Test public void testEjb() throws IOException, SQLException { try { List<Long> result = ejb.doSomething("ENTRATE"); for(Long temp:result){ System.out.println(temp); } } catch (Exception e) { e.printStackTrace(); } } } I run it from Eclipse as JUnit Test, but debug goes out deployment method after nothing happens
doc_23534839
"a acrobat jumped over an bridge" and I want to change this to "an acrobat jumped over a bridge". Right now, I'm using lyrics = re.sub(r" a (a|e|i|o|u|y){1}([a-z]+|[A-Z]+)", r" an (a|e|i|o|u|y){1}([a-z]+|[A-Z]+)", lyrics) and the resulting string doesn't replace in the way I'd hope it would, as expected. How else can I do this? To clarify, I want to be able to generalize this for every case, not just the example I used above. A: According to English grammar, an comes before a word that starts with a vowel. For that you can use this: >>> import re >>> re.sub(r'\ba\b(?=\s+[aeiouAEIOU])', 'an', "a acrobat jumped over a bridge") 'an acrobat jumped over a bridge' >>> re.sub(r'\ba\b(?=\s+[aeiouAEIOU])', 'an', "a elephant") 'an elephant' >>> Notice, a before acorbat has been changed to an, whereas a before bridge has not been changed. Also the a before elephant has been changed to an, hence the above regex is generalized and works for all words. Here we are using: '\ba\b(?=\s+[aeiouAEIOU])' \ba\b tries to match a literal a with word boundary on either sides (?=\s+[aeioudAEIOU]) ensures positive lookahead of vowel space and vowel char To replace all a with an you can use this: >>> re.sub(r'\ba\b', 'an', "a bridge") 'an bridge'
doc_23534840
let constraints = { audio: { mandatory: { chromeMediaSource: 'desktop', chromeMediaSourceId: sourceId } }, video: { mandatory: { chromeMediaSource: 'desktop', chromeMediaSourceId: sourceId } } } let stream = await navigator.mediaDevices.getUserMedia(constraints) And we would like to only capture audio from the application that is being streamed. Is it possible to do this? Maybe some third party solutions?
doc_23534841
How can I do this using RxJava2? A: there is 2 solutions 1. * *Listen for events at the application level *Track the time interval between these events *Do your calculation if lastInputTime = idleTime 2. * *use TextWatcher with afterTextChanged *use postDelayed handler *Do your calculation
doc_23534842
1) use AWS snowball to move on-premise to s3 (region1)and then use Redshift's SQL COPY cmd to copy data from s3 to redshift. 2) use AWS Datapipeline(note there is no AWS Datapipeline in region1 yet. so I will setup a Datapipeline in region2 which is closest to region1) to move on-premise data to s3 (region1) and another AWS DataPipeline (region2) to copy data from s3 (region1) to redshift (region1) using the AWS provided template (this template uses RedshiftCopyActivity to copy data from s3 to redshift)? which of above solution is faster? or is there other solution? Besides, will RedshiftCopyActivity faster than running redshift's COPY cmd directly? Note it is one time movement so I do not need AWS datapipeline's schedule function. Here is AWS Datapipeline's link: AWS Data Pipeline. It said: AWS Data Pipeline is a web service that helps you reliably process and move data between different AWS compute and storage services, as well as on-premises data sources.... A: It comes down to network bandwidth versus the quantity of data. The data needs to move from the current on-premises location to Amazon S3. This can either be done via: * *Network copy *AWS Snowball You can use an online network calculator to calculate how long it would take to copy via your network connection. Then, compare that to using AWS Snowball to copy the data. Pick whichever one is cheaper/easier/faster. Once the data is in Amazon S3, use the Amazon Redshift COPY command to load it. If data is being continually added, you'll need to find a way to send continuous updates to Redshift. This might be easier via network copy. There is no benefit in using Data Pipeline.
doc_23534843
public Form1() { InitializeComponent(); WebClient webClient = new WebClient(); try { if (!webClient.DownloadString("https://pastebin.com/raw/SUVh3TP1").Contains("dasda")) { MessageBox.Show("Working!"); } } catch { } } A: The webClient is successfully downloading that URL and reading the string that's there ("dasda"). Because you have a ! at the start of your if condition, when the .Contains() evaluates to true, the expression in the if evaluates to false and the MessageBox.Show() is skipped.
doc_23534844
The following is written: So, what is the correct time complexity? Thank you! A: In this context, constant time refers to the number of elements in the map, not anything about those elements. If you have a string of size n, and insert it into a map of size m, O(n) insertion is constant in m.
doc_23534845
=IF(MONTH(A15)<7,"FY "&YEAR(A15)-1&"/"&RIGHT(YEAR(A15),2),"FY "&YEAR(A15)&"/"&RIGHT(YEAR(A15)+1,2)) I am trying to set this formula by vba using the following code. ActiveCell.formulaR1C1 = "=IF(MONTH(A15)<7,"FY "&YEAR(A15)-1&"/"&RIGHT(YEAR(A15),2),"FY "&YEAR(A15)&"/"&RIGHT(YEAR(A15)+1,2))" The VBA compiler displays a compile error: Expected: end of statement. This appears to have a problem with the exclamation marks. Does anyone now how to include a text constant in a cell formula set by vba code? A: You need to use double quotes within the string like so: ActiveCell.formulaR1C1 = "=IF(MONTH(A15)<7,""FY ""&YEAR(A15)-1&""/""&RIGHT(YEAR(A15),2),""FY ""&YEAR(A15)&""/""&RIGHT(YEAR(A15)+1,2))" A: You only use FormulaR1C1 if you pass a reference in R1C1 format, but you're using A1 format. You can also shorten that formula if you wish: ActiveCell.Formula = "=""FY ""&YEAR(A15)-(MONTH(A15)<7)&""/""&RIGHT(YEAR(A15)+(MONTH(A15)>=7),2)"
doc_23534846
for user in userList: counter = 0 for channel in channelList: async for message in channel.history(limit=None, after=yesterday): if message.author == user: counter += 1 if counter == messageQuery: listUserCompleted.append(message.author.display_name) return Thank you in advance! A: If you want to break out of just the inner for loop and move on to the next user, then you want to use a break statement, like this: for user in userList: counter = 0 for channel in channelList: async for message in channel.history(limit=None, after=yesterday): if message.author == user: counter += 1 if counter == messageQuery: listUserCompleted.append(message.author.display_name) break That will break out of the innermost loop that you're in, which is the for channel.... A: Return returns the entire function and stops the Function block from executing. Use the keyword continue instead to get to the next iteration of the loop.
doc_23534847
tzdata-java : Depends: tzdata (= 2013i-0wheezy1) but 2014a-0wheezy1 is to be installed What can I do to work around this issue? For reproduction: I tried to install openjdk with this command: apt-get install opendjk-6-jre. Then I tried apt-get install openjdk-6-jre-headless and apt-get install tzdata-java to trace down the dependency that's broken. uname -a gives me 2.6.32-042stab084.17 #1 SMP Fri Dec 27 17:10:20 MSK 2013 x86_64 GNU/Linux A: I've worked around this by grabbing the two packages needed: http://ftp.uk.debian.org/debian/pool/main/t/tzdata/tzdata_2013i-0wheezy1_all.deb and http://ftp.uk.debian.org/debian/pool/main/t/tzdata/tzdata-java_2013i-0wheezy1_all.deb Then installing them with dpkg -i *deb which fixes the deps so I can then re-run my apt-get install openjdk-6-jre-headless and it'll complete. This has allowed me to install Jetty, which had tzdata-java as a nested dependency. Hope it works for you. Edit: just seen ckonig's post, perfect! Thanks for sharing that. A: https://www.debian.org/releases/wheezy/errata Should have read that much earlier. Only had to install the proposed updates. If you use APT to update your packages, you can install the proposed updates by adding the following line to /etc/apt/sources.list: # proposed additions for a 7 point release deb http://ftp.us.debian.org/debian wheezy-proposed-updates main contrib non-free
doc_23534848
Just have this set as of: const StyledSelect = styled(Select)` border: 1px solid red; The rendered HTML is: <div class="clearfix"> <div class="Search_search__fYl81 sc-bdVaJa xpdcY"> <div class="Select dropdown-arrow Select--single is-clearable is-searchable"> <div class="Select-control"> <span class="Select-multi-value-wrapper" id="react-select-2--value"> <div class="Select-placeholder">Search</div> <div class="Select-input"><input role="combobox" aria-expanded="false" aria-owns="" aria-haspopup="false" aria-activedescendant="react-select-2--value" class="Select-input" value=""></div> </span> <span class="Select-arrow-zone"><i class="fa fa-search" aria-hidden="true" style="color: rgb(153, 153, 153);"></i></span> </div> </div> </div> </div> border: 10px solid red;
doc_23534849
In my code, I am attempting to something akin to their sample OAuth (found here), I have placed the code into a controller: class OauthController extends Controller { public function reqToken() { $oauthHandler = new OauthHandler(env('EVERNOTE_SANDBOX', 'true')); $callback = 'http://localhost/auth'; //temp $oauthData = $oauthHandler->authorize(env('EVERNOTE_KEY', ''), env('EVERNOTE_SECRET', ''), $callback); } } According to the Evernote Cloud SDK, the following line of code is called under authorize(): header($authorizationUrl); I have debugged my way to seeing that this line of code does, get called, and yet my page does not get rerouted to the $authorizationUrl, which is: "Location: https://sandbox.evernote.com/OAuth.action?oauth_token=token" I end up staying on the blank laravel page. If it helps, here is my route: Route::get('/auth', 'OauthController@reqToken'); I've tried looking in the docs for info on the header function, but couldn't see anything that indicates why It's messing up for me. Any ideas? A: After the header() function is called, you should kill the request with die; or exit; and not output anything on the page. after your ->authorize() call try adding that in. The other thing it could be is that headers have already been sent, so this isn't "actually" being sent to the browser. Usually what it is that the header doesn't fully send and Laravel continues doing stuff after your method is called that could corrupt this header or override it and cause an issue. so calling exit; or die; right after the header is set, you skip all of the extraneous overhead that Laravel offers by default. A: try laravel redirect function. redirect() you can pass in a full url
doc_23534850
I am working on an N-Tier app that relies a lot on serialization, objects interact with the database mainly in a serialized fashion, objects and collections are inserted, updated and read as XML from within stored procedures. For some of the smaller data classes I am simply using ExecuteNonQuery, Reader, etc to interact with the data, as its easier, but I have encountered a problem. Data is inserted into the database using ExecuteNonQuery, using Parameters - some of the data inserted are properties that are Enums (stored in the DB as ints) that have the FlagAttribute attached. On a Enum such as: <Flags()> _ Public Enum Fruit As Integer <Description("None"), XmlEnum("0")> None = 0 <Description("Apple"), XmlEnum("1")> Apple = 1 <Description("Banana"), XmlEnum("2")> Banana = 2 <Description("Orange"), XmlEnum("4")> Orange = 4 End Enum The value read back might be an Integer value of 1, 3, 7, etc, and inserted into the database not using serialization, when it is read back however as part of a larger group of classes using the ExecuteXmlReader (filling a XmlReader object) and then needing to be deserialized, it can not be, as 7 for example, causes 'Instance validation error: '7' is not a valid value for Fruit', as it is expecting it to be serialized in the format of: <fruitOptions>1 2 4<fruitOptions> All in all it is a little confusing, and I could probably work around it by storing it in the database in the 1, 2, 4 format, but sadly not in the int type that it currently is in. Does anyone have any ideas on this? A: You're going to have to ask your DBA or the author of the stored procedure you're using. It appears they've specified that this field is not an enum, but rather a list.
doc_23534851
I have download my app from google play store and I still can't buy any of my In App purchase within the application. I have the following error : "The publisher cannot purchase the item". All my In App purchase are also valid and active. I'm using the same google account than in my google play developer console. I have read on google that it's normal that developer can't buy it's own items in testing mode (alpha or beta) but here i'm using the official version and I still can't do it !! (It's my first android application) What did I do wrong ? Thanks, A: if you have the same account configured on the device (the one which you are using for developer console) make sure it is removed. Google Play will allow switching between all google accounts added on device. Also, before removing try switching directly in google play first to an account that is not your developer account and then do the purchase. If that doesn't work you'll probably need to remove the developer account for the device if you want to make a purchase fro your own app.
doc_23534852
async function a () { const b = JSON.parse('{"a":"x"}'); console.log(b) } If I hover over the "b" on the second line, I see that its type is inferred as any. However, there is no error. Am I misunderstanding what noImplicitAny is supposed to do or is this a bug? A: The --noImplicitAny compiler option produces warnings only in places where type inference fails, and it falls back or defaults to any. For example, you get an implicit-any error when a function parameter cannot be contextually typed: const f = (arg) => arg + 1; // error! // ------> ~~~ implicit any You also get such an error if an auto-typed variable (see microsoft/TypeScript#11263) cannot be inferred by the compiler via control flow, such as if the variable is referenced in separate function scope: let w; // error! // >~ implicit any w = 2; function foo() { w } // implicit any These are situations where the compiler says "I don't know what's going on here so I'll give it an any type". On the other hand, if you call a function whose return type is any, you will get a value of type any. This might be an "implicit" any in the sense that the caller of the function does not need to write out the return type, but it isn't due to a failure of type inference. On the contrary, when a variable you assign that to is inferred as any, it's a success of type inference (just like x being a number in const x = 1 + 2 indicates successful inference). So there's no implicit-any error in these situations. And since the TypeScript library typings for JSON.parse() looks like interface JSON { parse(text: string, reviver?: (this: any, k: string, v: any) => any): any; } then const b = JSON.parse('{"a":"x"}'); successfully infers any for the type of b and there is no compiler warning. Playground link to code
doc_23534853
A: As Yan notes in his answer, you could use the standard BSD-style networking APIs like socket(), connect(), etc. However, if you want to stay in Objective C and Foundation, then you're looking for NSInputStream and NSOutputStream, which are the stream classes for Cocoa. You should not, however, look at NSSocketPort as that's specifically for use with Distributed Objects. Apple's "Introduction to Stream Programming Guide for Cocoa" is here: http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/Streams/Streams.html You should start with that document and then check out the class references which have pointers to sample code projects which use NSStream and its subclasses. A: If you don’t mind using third-party code, AsyncSocket is a popular library that wraps CFSocket and CFStream, providing an Objective-C API for communication via TCP and UDP (AsyncUdpSocket).
doc_23534854
This works perfectly. However, when I add a link with role="button", like <a type="button" href="https://twitter.com/" class="btn-floating"><i class="fab fa-twitter"></i></a> on the same page it results that the Font Awesome icons are not added and the tooltips also do not show anymore on link hover. When I remove the link with role="button" the other links render as expected again. After inspecting the page I was presented with the following error: Uncaught TypeError: $(...).attr(...) is undefined More specifically, the following line in the script was highlighted: return $(this).attr("href").match(/\.(pdf|doc|docx|ppt|pptx|xls|xlxs|epub|odt|odp|ods|txt|rtf)$/i); However, when I add the relevant code in the code snippet, everything works just fine (until now)! I have reached a dead end. Who can shine his or her light on this problem? Kind regards, /** Icons JavaScript **/ /** Add new-window and download classes automatically to links **/ $('a[target=_blank]').addClass('new-window'); $("a").filter(function () { return $(this).attr("href").match(/\.(pdf|doc|docx|ppt|pptx|xls|xlxs|epub|odt|odp|ods|txt|rtf)$/i); }).addClass('download'); /** Links JavaScript **/ /* Check for links in document */ var links = document.querySelectorAll("a"); /* Create index for download links unique id*/ var downloadIndex = 0; /* Create index for new window links unique id*/ var newWindowIndex = 0; /* Check links on page */ for (var linkIndex = 0; linkIndex < links.length; linkIndex++) { /* Creating a span to wrap the screen-reader text */ var srTxtWrapper = document.createElement("span"); /* Add class .sr-only to screen-reader span */ srTxtWrapper.classList.add("sr-only"); if (links[linkIndex].classList.contains("download")) { /* Add download attribute */ links[linkIndex].setAttribute("download", ""); /* Add unique id to download link */ links[linkIndex].setAttribute("id", "download-file-" + downloadIndex); /* Add title attribute saying download file */ links[linkIndex].setAttribute("title", "download bestand"); /* Add data-toggle tooltip data attribute */ links[linkIndex].setAttribute("data-toggle", "tooltip"); /* Creating the screen-reader text */ var srTxt = document.createTextNode("(deze link downloadt een bestand)"); /* Adding the screen-reader text to the span*/ srTxtWrapper.appendChild(srTxt); links[linkIndex].appendChild(srTxtWrapper); /* Increase downloadIndex by one for next download link */ downloadIndex++; } else if (links[linkIndex].classList.contains("new-window")) { /* Add target _blank attribute for link to open in new window */ links[linkIndex].setAttribute("target", "_blank"); /* Add unique id to new window link */ links[linkIndex].setAttribute("id", "new-window" + newWindowIndex); /* Add title attribute saying link opens in new window */ links[linkIndex].setAttribute("title", "open in nieuw venster/tab"); /* Add data-toggle tooltip data attribute */ links[linkIndex].setAttribute("data-toggle", "tooltip"); /* Creating the screen-reader text */ var srTxt = document.createTextNode("(deze link opent in een nieuw venster/tab)"); /* Adding the screen-reader text to the span*/ srTxtWrapper.appendChild(srTxt); links[linkIndex].appendChild(srTxtWrapper); /* Increase newWindowIndex by one for next newWindow link */ newWindowIndex++; } } /* Font Awesome icons for new-window and download classes links (not in button links) */ a.new-window:not(.button)::after, a.download:not(.button)::after { -webkit-font-smoothing: antialiased; display: inline-block; font-style: normal; font-variant: normal; text-rendering: auto; line-height: 1; font-family: "Font Awesome 6 Free"; font-weight: 900; margin-left: 0.35rem } a.new-window:not(.button)::after { content: "\f08e" } a.download:not(.button)::after { content: "\f019" } /* button floating */ .btn-floating { position: relative; z-index: 1; display: inline-block; padding: 0; margin: 10px; overflow: hidden; vertical-align: middle; cursor: pointer; border-radius: 50%; -webkit-box-shadow: 0 5px 11px 0 rgba(0, 0, 0, 0.18), 0 4px 15px 0 rgba(0, 0, 0, 0.15); box-shadow: 0 5px 11px 0 rgba(0, 0, 0, 0.18), 0 4px 15px 0 rgba(0, 0, 0, 0.15); -webkit-transition: all .2s ease-in-out; transition: all .2s ease-in-out; width: 47px; height: 47px } .btn-floating i { font-size: 1.25rem; line-height: 47px } .btn-floating i { display: inline-block; width: inherit; color: #fff; text-align: center } .btn-floating:hover { -webkit-box-shadow: 0 8px 17px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); box-shadow: 0 8px 17px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19) } .btn-floating:before { <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/js/bootstrap.min.js"></script> <link href=" https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" rel="stylesheet" /> <link href="https://cdn.usebootstrap.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" /> <p>Link that opens a webpage in new window/tab: <a href="https://www.d2l.com/" target="_blank" class="new-window" rel="noreferrer noopener">D2L Homepage</a></p> <hr> <p>Link that opens as PDF download: <a href="https://www.d2l.com/wp-content/uploads/2022/03/Video-transcript.pdf" download target="_blank" class="download" rel="noreferrer noopener">Transcript of Inclusive Learning with D2L Brightspace (PDF)</a></p> <hr> <a type="button" href="https://twitter.com/" class="btn-floating"><i class="fab fa-twitter" style="color: blue"></i></a> A: I eventually found a solution: https://stackoverflow.com/a/50626843/19299088 I replaced ".attr()" with ".prop()" it fixed the issue. Everything works as expected and I don't get the error "TypeError: $(…).attr(…)" anymore.
doc_23534855
Is this possible? How can I do this? A: If you specifiy that the validationMethod is only for certain events you can control it. E.g. @ValidationMethod(on={"useradminsubmit"}) public void checkWhatever(ValidationErrors errors) { .... } If your handleEvent method is not included then the validation will not fire.
doc_23534856
Until now I got two problems that I can't solve. First of all, how to get inputs from JCheckBox and JRadioButton? And I get these user inputs in console, but how to get it to show just below the registration form in panel? import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Login implements ActionListener { private static JTextField nameText; private static JTextField emailText; private static JPasswordField passwordText; private static JPasswordField confirmPasswordText; public void loginForm() { JPanel panel = new JPanel(); JFrame frame = new JFrame(); frame.setSize(600, 400); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(panel); frame.setTitle("Registration Form"); panel.setLayout(null); JLabel headingLabel = new JLabel("REGISTRATION FORM"); headingLabel.setBounds(285, 25, 160, 25); panel.add(headingLabel); JLabel nameLabel = new JLabel("Name"); nameLabel.setBounds(150, 70, 80, 25); panel.add(nameLabel); nameText = new JTextField(20); nameText.setBounds(270, 70, 165, 25); panel.add(nameText); JRadioButton maleButton = new JRadioButton("Male"); maleButton.setBounds(270, 100, 60, 25); panel.add(maleButton); JRadioButton femaleButton = new JRadioButton("Female"); femaleButton.setBounds(370, 100, 100, 25); panel.add(femaleButton); JLabel emailLabel = new JLabel("E-mail"); emailLabel.setBounds(150, 130, 80, 25); panel.add(emailLabel); emailText = new JTextField(20); emailText.setBounds(270, 130, 165, 25); panel.add(emailText); JLabel passwordLabel = new JLabel("Password"); passwordLabel.setBounds(150, 160, 80, 25); panel.add(passwordLabel); passwordText = new JPasswordField(); passwordText.setBounds(270, 160, 165, 25); panel.add(passwordText); JLabel confirmPasswordLabel = new JLabel("Confirm password"); confirmPasswordLabel.setBounds(150, 190, 120, 25); panel.add(confirmPasswordLabel); confirmPasswordText = new JPasswordField(); confirmPasswordText.setBounds(270, 190, 165, 25); panel.add(confirmPasswordText); JCheckBox c1 = new JCheckBox("I agree to websites rules!"); c1.setBounds(260, 220, 200, 25); panel.add(c1); JButton button = new JButton("Submit"); button.setBounds(300, 260, 100, 25); button.addActionListener(new Login()); panel.add(button); JLabel success = new JLabel(); success.setBounds(260, 290, 300, 25); panel.add(success); frame.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { String name = nameText.getText(); // String male = maleButton.getText(); // String female = femaleButton.getText(); String email = emailText.getText(); String password = passwordText.getText(); String confirmPassword = confirmPasswordText.getText(); // String c1 = String.valueOf(JCheckBox.getDefaultLocale()); System.out.println(name + ", " + email + ", " + password + ", " + confirmPassword); } } A: Below code is a rewrite of your GUI application. import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; public class Login { private JCheckBox c1; private JPasswordField confirmPasswordText; private JPasswordField passwordText; private JRadioButton femaleButton; private JRadioButton maleButton; private JTextArea textArea; private JTextField emailText; private JTextField nameText; private void createAndDisplayGui() { JFrame frame = new JFrame("Registration"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(createHeading(), BorderLayout.PAGE_START); frame.add(createForm(), BorderLayout.CENTER); frame.add(createButtonsPanel(), BorderLayout.PAGE_END); frame.pack(); frame.setLocationByPlatform(true); frame.setVisible(true); } private JButton createButton(String text, int mnemonic, ActionListener listener) { JButton button = new JButton(text); button.setMnemonic(mnemonic); button.addActionListener(listener); return button; } private JPanel createButtonsPanel() { JPanel buttonsPanel = new JPanel(); buttonsPanel.add(createButton("Submit", KeyEvent.VK_S, this::submit)); return buttonsPanel; } private JPanel createForm() { JPanel form = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.anchor = GridBagConstraints.LINE_START; gbc.gridx = 0; gbc.gridy = 0; gbc.insets.bottom = 5; gbc.insets.left = 10; gbc.insets.right = 10; gbc.insets.top = 0; JLabel nameLabel = new JLabel("Name"); form.add(nameLabel, gbc); gbc.gridx = 1; nameText = new JTextField(16); form.add(nameText, gbc); gbc.gridy = 1; form.add(createRadioButtons(), gbc); gbc.gridx = 0; gbc.gridy = 2; JLabel eMailLabel = new JLabel("E-mail"); form.add(eMailLabel, gbc); gbc.gridx = 1; emailText = new JTextField(16); form.add(emailText, gbc); gbc.gridx = 0; gbc.gridy = 3; JLabel passwordLabel = new JLabel("Password"); form.add(passwordLabel, gbc); gbc.gridx = 1; passwordText = new JPasswordField(16); form.add(passwordText, gbc); gbc.gridx = 0; gbc.gridy = 4; JLabel confirmLabel = new JLabel("Confirm password"); form.add(confirmLabel, gbc); gbc.gridx = 1; confirmPasswordText = new JPasswordField(16); form.add(confirmPasswordText, gbc); gbc.gridx = 1; gbc.gridy = 5; c1 = new JCheckBox("I agree to websites rules!"); form.add(c1, gbc); gbc.gridx = 1; gbc.gridy = 6; textArea = new JTextArea(2, 30); textArea.setEditable(false); textArea.setFocusable(false); JScrollPane scrollPane = new JScrollPane(textArea); form.add(scrollPane, gbc); return form; } private JPanel createHeading() { JPanel heading = new JPanel(); JLabel label = new JLabel("REGISTRATION FORM"); label.setFont(label.getFont().deriveFont(Font.BOLD, 14.0f)); heading.add(label); return heading; } private JPanel createRadioButtons() { JPanel radioButtons = new JPanel(); ButtonGroup group = new ButtonGroup(); maleButton = new JRadioButton("Male"); maleButton.setSelected(true); radioButtons.add(maleButton); group.add(maleButton); femaleButton = new JRadioButton("Female"); radioButtons.add(femaleButton); group.add(femaleButton); return radioButtons; } private void submit(ActionEvent event) { textArea.setText(""); String name = nameText.getText(); textArea.append(name); String gender; if (maleButton.isSelected()) { gender = "male"; } else { gender = "female"; } textArea.append(", " + gender); String email = emailText.getText(); textArea.append(", " + email); String password = new String(passwordText.getPassword()); textArea.append(", " + password); String confirmPassword = new String(confirmPasswordText.getPassword()); textArea.append(", " + confirmPassword); textArea.append(", " + c1.isSelected()); } public static void main(String[] args) { EventQueue.invokeLater(() -> new Login().createAndDisplayGui()); } } * *Usually you use a layout manager rather than setting it to null. Refer to Laying Out Components Within a Container *You need to group JRadioButtons in a ButtonGroup to ensure that only one can be selected. Refer to How to Use Buttons, Check Boxes, and Radio Buttons *Method getText is deprecated for JPasswordField. Refer to How to Use Password Fields. *I chose to display the user inputs in a JTextArea in a JScrollPane but there are other options. Refer to Using Text Components and How to Use Scroll Panes. *Since Java 8, the ActionListener interface can be implemented via a method reference.
doc_23534857
class User{ public $first; public $last; public $email; public $guid; public $website; public $bio; public $picture; public $gender; ... } and a constructor that takes values from factory functions and puts them in the class, like so: public function __construct($guid, $first , $last,$email, $bio, $picture, $gender) { $this->guid = $guid; $this->first = $first; $this->last = $last; $this->email = $email; ... } Is there a simple method that will auto-assign all these variables? Or can I loop through them all using a for with PHP's parameter functions? A: This should be simpler in such case: class User{ public function __construct($params) {//params is array('first' => 'hello', 'last' => 'hi', 'email'=>'hellohi@hi.com') foreach ($params as $key => $value) { $this->$key = $value; } } } You can then access properties as: $params = array('first' => 'hello', 'last' => 'hi', 'email'=>'hellohi@hi.com'); $user = new User($params); echo $user->first; A: <?php class User { public $first; public $last; public $email; public $guid; public $website; public $bio; public $picture; public $gender; public function __construct($params) { // Same params array from previous answer. foreach ($params as $key => $value) { $this->$key = $value; } } } ?> A: Using func_get_args as suggested by Simon Germain and using the list function you get : <?php class Test{ var $x, $y, $z; function __construct($x, $y, $z){ list($this->x, $this->y, $this->z) = func_get_args(); } } I don't believe it can be done in a shorter way.
doc_23534858
<!-- Leptonica --> <dependency> <groupId>net.sourceforge.lept4j</groupId> <artifactId>lept4j</artifactId> <version>1.9.0</version> </dependency> <!-- OpenCV --> <dependency> <groupId>org.openpnp</groupId> <artifactId>opencv</artifactId> <version>3.2.0-1</version> </dependency> I'd like to use OpenCV and Leptonica functions together. In order to do this, I need to be able to convert Mat to Pix and Pix to Mat. This is what I have for now: public static Pix matToGrayscalePix(Mat mat) { if (mat == null) { throw new IllegalArgumentException("Recycled matrix"); } final byte[] bytes = new byte[(int) mat.total()]; mat.get(0, 0, bytes); ByteBuffer buff = ByteBuffer.wrap(bytes); return Leptonica1.pixReadMem(buff, new NativeSize(buff.capacity())); } public static Mat pixToGrayscaleMat(Pix pix) { if (pix == null) { throw new IllegalArgumentException("Recycled matrix"); } PointerByReference pdata = new PointerByReference(); NativeSizeByReference psize = new NativeSizeByReference(); int format = net.sourceforge.lept4j.ILeptonica.IFF_TIFF; Leptonica1.pixWriteMem(pdata, psize, pix, format); byte[] b = pdata.getValue().getByteArray(0, psize.getValue().intValue()); return new MatOfByte(b).reshape(0, pix.h); } But these functions doesn't work right now. What am I doing wrong ? A: Try the following: public static Pix convertMatToPix(Mat mat) { MatOfByte bytes = new MatOfByte(); Imgcodecs.imencode(".tif", mat, bytes); ByteBuffer buff = ByteBuffer.wrap(bytes.toArray()); return Leptonica1.pixReadMem(buff, new NativeSize(buff.capacity())); } public static Mat convertPixToMat(Pix pix) { PointerByReference pdata = new PointerByReference(); NativeSizeByReference psize = new NativeSizeByReference(); Leptonica1.pixWriteMem(pdata, psize, pix, ILeptonica.IFF_TIFF); byte[] b = pdata.getValue().getByteArray(0, psize.getValue().intValue()); Leptonica1.lept_free(pdata.getValue()); return Imgcodecs.imdecode(new MatOfByte(b), Imgcodecs.CV_LOAD_IMAGE_UNCHANGED); }
doc_23534859
here the html : <input type="checkbox" id="krs_id_kelas" name="krs_id_kelas[]" value="0ec81bdf-1fc6-447d-ab65-bc67a857d99c"> <input type="checkbox" id="krs_id_kelas" name="krs_id_kelas[]" value="173867c3-5721-4aa2-9344-f5ad9fd05537"> Script $(document).ready(function () { $('#form_krs_kolektif').submit(function (event) { var formData = { 'krs_id_prodi': $('#krs_id_prodi').val(), //this part is fine 'periode': $('#periode_krs option:selected').val(), //this part is fine 'krs_id_regis_mhs': $('#krs_id_regis_mhs').val(), //this part is fine 'id_kelas[]': $('#krs_id_kelas:checked').serialize() // only this part has a problem }; $.ajax({ type: 'POST', url: '<?=base_url()?>akademik/proses_krs_kolektif/', data: formData, dataType: 'json', encode: true }) event.preventDefault(); }); }); When I print_r the POST result from php part, the response from console is like this Array ( [0] => krs_id_kelas%5B%5D=0ec81bdf-1fc6-447d-ab65-bc67a857d99c&krs_id_kelas%5B%5D=173867c3-5721-4aa2-9344-f5ad9fd05537 ) What I want is array like this, how can I fix it ? Array ( [0] => 0ec81bdf-1fc6-447d-ab65-bc67a857d99c [1] => 173867c3-5721-4aa2-9344-f5ad9fd05537 ) A: HTML should be, instead of ID you must use class: <input type="checkbox" class="krs_id_kelas" name="krs_id_kelas[]" value="0ec81bdf-1fc6-447d-ab65-bc67a857d99c"> <input type="checkbox" class="krs_id_kelas" name="krs_id_kelas[]" value="173867c3-5721-4aa2-9344-f5ad9fd05537"> try this script: $(document).ready(function () { $('#form_krs_kolektif').submit(function (event) { var chekedValue = []; $('.krs_id_kelas:checked').each(function(){ chekedValue .push($(this).val()); }) var formData = { 'krs_id_prodi': $('#krs_id_prodi').val(), //this part is fine 'periode': $('#periode_krs option:selected').val(), //this part is fine 'krs_id_regis_mhs': $('#krs_id_regis_mhs').val(), //this part is fine 'id_kelas': chekedValue // only this part has a problem }; $.ajax({ type: 'POST', url: '<?=base_url()?>akademik/proses_krs_kolektif/', data: formData, dataType: 'json', encode: true }) event.preventDefault(); }); }); and print $_POST you will get the desired result. A: try this One change from var formData = { 'krs_id_prodi': $('#krs_id_prodi').val(), //this part is fine 'periode': $('#periode_krs option:selected').val(), //this part is fine 'krs_id_regis_mhs': $('#krs_id_regis_mhs').val(), //this part is fine 'id_kelas[]': $('#krs_id_kelas:checked').serialize() // only this part has a problem }; to var formData = $('#form_krs_kolektif').serialize();
doc_23534860
computed: { searchedSlots: function() { return this.items.filter(function(item) { return ( (item.shortcode.toLowerCase().match(this.searchTerms.toLowerCase())) || (item.slots.toLowerCase().match(this.searchTerms.toLowerCase())) ) }.bind(this)); } } Also the search v-model input isn't displaying in the Summary Here is the form at JSFiddle Here is an example of what the form may look like after it has been filled in <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0, shrink-to-fit=no' name='viewport' /> <style> input, select, button { float:left; display:block; clear:both; min-width:200px; margin-bottom: 1rem; } .maxfee, .summary, p.summaryresult { float:left; display:block; clear:both } </style> <!-- Vue.js CDN --> <script src="https://unpkg.com/vue"></script> </head> <body> <form name="myform" id="deliveryservice"> <!--<pre>{{ items.shortcode }}</pre>--> <!-- Load in dayslots from external JSON file --> <input name="dayslot" v-for="item in searchedSlots" v-model.lazy="dayslotv" type="text" placeholder="Enter Day and Delivery Slot" required> <select v-model="search"> <option v-for="item in items" v-bind:value="item.slot"> {{ item.shortcode }} {{ item.slot }} </option> </select> <select v-model="servicev" required> <option selected disabled hidden>Please Select</option> <option value="standard">Standard</option> <option value="installation">Installation</option> </select> <!-- Customer adds the max amount they wish to pay --> <div class="maxfee"> <input name="price" v-model.number="pricev" type="currency" placeholder="Max price you will pay" required> </div> <!-- We then display a summary of the options they chose, before they submit --> <div class="summary"><p>Summary:</p></div> <p class="summaryresult" style="font-weight:bold;">I would like {{ search.shortcode }} on {{ servicev }} service and pay no more than £{{ pricev }}</p> <button type="submit">Submit</button> </form> <script> const app = new Vue({ el: '#deliveryservice', data: { items: [], search: '', dayslotv: '', servicev: '', pricev: '' }, created: function() { fetch('https://s3.eu-west-2.amazonaws.com/dayslots10/dayslots.json') .then(resp => resp.json()) .then(items => { this.items = items }) }, }); </script> </body> </html> A: I fixed some errors. Filter will be done in few minutes. new Vue({ el: '#deliveryservice', data: { items: [], query: '', slot: '', service: 'standard', price: '0', src: 'https://s3.eu-west-2.amazonaws.com/dayslots10/dayslots.json' }, methods: { setSlot (evt) { this.slot = evt.target.value } }, async created () { this.items = await (await fetch(this.src)).json() this.slot = this.items[0].slot } }) input, select, button { float: left; display: block; clear: both; min-width: 200px; margin-bottom: 1rem; } .maxfee, .summary, p.summaryresult { float: left; display: block; clear: both } <form name="myform" id="deliveryservice"> <input v-model="query" type="text" placeholder="Enter Day and Delivery Slot" required > <select value="slot" @change="setSlot"> <option v-for="({shortcode, slot}, idx) in items" :value="slot" :selected="idx === 0" >{{ shortcode }} - {{ slot }}</option> </select> <select v-model="service" required> <option value="standard">Standard</option> <option value="installation">Installation</option> </select> <div class="maxfee"> <input v-model.number="price" type="number" min="0" placeholder="Max price you will pay" required > </div> <div class="summary"> <p>Summary:</p> </div> <p class="summaryresult" style="font-weight:bold;"> I would like {{ slot }} on {{ service }} service and pay no more than £{{ price }} </p> <button type="submit">Submit</button> </form> <script src="https://unpkg.com/vue"></script>
doc_23534861
But while deleting the existing record in the kendo grid actually it's deleting and adding the hidden field but again that it's showing in the grid when i am clicking to add new record. It should not show in grid but it's should have in dataSource. Please anyone help me to achieve this.Thanks. Here the JsFiddle Link.. [http://jsfiddle.net/bagya1985/wftu0vzn/7/][1] A: add filter to dataSource: var savingsDataSource = new kendo.data.DataSource({ data: savings, filter: { field: "operationContext", operator: "neq", value: "IsDelete" }, ... });
doc_23534862
doc_23534863
A: Are you really interested in a click event or have you just been using the click event where you're really looking for the change event: The change event is sent to an element when its value changes. This event is limited to <input> elements, <textarea> boxes and <select> elements. A: 2 possible reasons. Reason 1: click hold and scroll is the same as click and drag Reason 2: It's on click... not on release you have to be clicking down on the element first.
doc_23534864
import zipfile, os, pathlib, time from os.path import basename now = time.strftime('%H%M%S') source3 = 'F:\oneMoreTry' # create a ZipFile object with zipfile.ZipFile(now + '.zip', 'w') as zipObj: # Iterate over all the files in directory for folderName, subfolders, filenames in os.walk(source3): for filename in filenames: # create complete filepath of file in directory filePath = os.path.join(folderName, filename) # Add file to zip zipObj.write(filePath, basename(filePath))
doc_23534865
* *Pivot all unique rows in col1 to columns in the df *Assign the corresponding values in col2 to rows pivot does not work because there are duplicate values. pivot_table does not work because aggfunc returns only means, etc, whereas I need all rows pivoted. I did not have success with melt or unstack. Original df: col1 col2 attr1 2 attr2 6 attr3 3 ... ... attr1 9 attr2 2 attr3 5 Desired output: attr1 attr2 attr3 2 6 3 9 2 5 A: Use set_index, groupby with cumcount and unstack: df.set_index([df.groupby('col1').cumcount(),'col1'])['col2'].unstack() Output: col1 attr1 attr2 attr3 0 2 6 3 1 9 2 5
doc_23534866
However, in this file, there should also be "arbitrary blocks of XML", which have no meaning for my application, and I need to write them through to the output file without modification. I would like to be able to test parts of the input file which are relevant for my application against my XSD, but not require my customer to write an XSD for the "arbitrary blocks of XML" which are only relevant for his application and not for mine. How can I specify this in the XSD file? So far I've done the following: * *Define a namespace for those tags which are relevant for my application *Create an XSD file which defines those tags within that namespace (i.e. which are relevant for my application) *In my XSD file, use <xs:any> to state that at a certain point in my file, any tags supplied by the user may be present *I have, for testing, chosen a tag for the "arbitrary block of XML", defined an XSD (no namespace) for that tag, and inserted it into the XML file, like <test xmlns="" xsi:noNamespaceSchemaLocation="x"/> and that works fine. However, as soon as I don't put the schema location reference in the <test> tag the XSD validator complains it doesn't recognize the <test> tag as it's not in my main XSD, despite the fact that it's validating against the <xs:any> tag in the schema. Is there any way to say to the XSD validator "this particular tag does not require any XSD to be present for any of its contents"? A: Adrian, you're absolutely on a right track with usage of <xs:any> element. However you need to add last piece to the puzzle - define how content inside this element has to be validated. By default validating parser will expect schema defined for this element and will fail validation if it's not available (or content is not valid according to this schema). In order to change behavior you need to specify attribute <xs:any processContents="skip">. Another option (maybe more preferable) is to specify processContents="lax" which means that parser will look for schema definition and if it's found it will use to validate the fragment but if it's not then it will ignore it. More about this attribute you could find in specification. Also there is quite helpful article on creating extensible schemas.
doc_23534867
I do really know, it is not recommend... NSString *path=[[NSString alloc] initWithFormat:@"/su"]; NSMutableDictionary *param=[[NSMutableDictionary alloc] init]; [param setValue:@"facebook" forKey:@"wd"]; MKNetworkEngine *engine=[[MKNetworkEngine alloc] initWithHostName:@"suggestion.baidu.com" customHeaderFields:nil]; MKNetworkOperation *op=[engine operationWithPath:path params:param httpMethod:@"get" ssl:NO]; [op addCompletionHandler:^(MKNetworkOperation *completedOperation) { } errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) { NSLog(@"error"); }]; [engine enqueueOperation:op]; A: I had a similar issue. The second key overwrites the first. When I deleted the Allow Arbitrary Loads in Web Content option it started working. Obviously the Allow Arbitrary should be left on YES You're probably using iOS > 10.0 or macOS > 10.12. Version-specific ATS behavior: In a current operating system, the presence of a fine-grained transport security key (NSAllowsArbitraryLoadsForMedia, NSAllowsArbitraryLoadsInWebContent, or NSAllowsLocalNetworking) overrides the value of the NSAllowsArbitraryLoads key to NO. This allows you to set NSAllowsArbitraryLoads to YES if needed for your app in older operating systems, without disabling ATS generally in current operating systems. https://developer.apple.com A: After I set the exception domain,It works! But It means the Allow Arbitrary Loads doesn't works?
doc_23534868
Though i got many jsp pages calling same servlet I cannot specify a specific jsp location in request.sendRedirect() method of servlet. So how do I do it??
doc_23534869
this is how my controller and view code looks @model MvcApplication1.Controllers.Employee <div class="editor-label"> @Html.LabelFor(model => model.Id) </div> <div class="editor-field"> @Html.EditorFor(model => model.Id) </div> Controller public ActionResult Index() { Employee emp = new Employee(); emp.Id = 101; return View(emp); } Model public class Employee { public int Id { get; set; } } where i made the mistake for which numeric up/down is getting render for my id property. what to change in code so textbox should appear for id property. i do not want to change id property's data type. thanks A: You can continue using EditorFor, just change @Html.EditorFor(model => model.Id) to @Html.EditorFor(model => model.Id, "Text"). The "Text" means you want to use the text template instead of the default template for that type. A: The EditorFor() method uses the TemplatesHelpers class to determine which EditorTemplate to use for rendering the html (for example, taking into account any custom EditorTemplates for the type, a [UiHint] or [DataType] attribute if one exists and the type itself. In the case of int, the inbuilt default template generates <input type="number" name="Id" .... /> which will render the browsers HTML5 implementation of a number up-down input if supported. If you do not want this, then use @Html.TextBoxFor(m => m.Id) which will render type="text"
doc_23534870
A: Here is an example of using cookies with a stopwatch: https://jsfiddle.net/tmonster/00eobuxy/ function setCookie(cname, cvalue, exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000)); var expires = "expires=" + d.toGMTString(); document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; } function getCookie(cname) { var name = cname + "="; var decodedCookie = decodeURIComponent(document.cookie); var ca = decodedCookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; } Number.prototype.pad = function() { return ("0" + String(this)).substr(-2); } var startTime = new Date(); var isRunning = false; function tick() { if (!isRunning) return; var t = new Date(new Date() - startTime); document.getElementById("stopwatch").innerHTML = t.getUTCHours().pad() + ":" + t.getMinutes().pad() + ":" + t.getSeconds().pad(); setTimeout(tick, 1000); } function CheckIfClockedIn() { var ct = getCookie("ClockInTime"); if (ct.length == 0) return; isRunning = true; startTime = new Date(ct); tick(); document.getElementById("punchInOut").innerHTML = "Clock out"; } function PunchInOut() { if (!isRunning) { isRunning = true; startTime = new Date(); tick(); setCookie("ClockInTime", startTime, 1); document.getElementById("punchInOut").innerHTML = "Clock out"; } else { isRunning = false; setCookie("ClockInTime", "", 0); document.getElementById("stopwatch").innerHTML = "Not clocked in"; document.getElementById("punchInOut").innerHTML = "Clock in"; } } A: If you store the start time (as in the actual time of day value the moment the stopwatch was started) in a cookie, then any time you open the page from that browser, you can read the start time from the cookie, get the current time, calculate the elapsed time and show the elapsed time. You can then count up the time from there. It will appear that the timer was running the whole time. A nice feature of doing it this way is that you don't have to store anything when the tab is closed (which is sometimes problematic). Instead, you just store the cookie when the stopwatch is started.
doc_23534871
example mathew - 25 john - 26 joe - 25 stewart - 27 kelly - 24 brandon -23 magy - 22 .......etc. Thanks Mathew A: You can make use of the MySQL's between and limit clause for this: $range = 5; // you'll be selecting around this range. $min = $rank - $range; $max = $rank + $range; $limit = 10; // max number of results you want. $query = "select * from table where rank between $min and $max limit $limit"; A: SELECT data FROM table WHERE rank>=25 LIMIT 0,10 A: you can use BETWEEN: SELECT * FROM `table` WHERE `rank` BETWEEN $input-5 AND $input+5 LIMIT 10 of course make sure you're input is validated/sanitized or use prepared statements. the code above is pseudocode to explain how you'd do it language agnostic (apart from the sql part ;))
doc_23534872
from Tkinter import * from PIL import ImageTk, Image import os root = Tk() img = ImageTk.PhotoImage(Image.open("9.jpg")) panel = Label(root, image = img) panel.pack(side = "bottom", fill = "both", expand = "yes") root.mainloop() Pycharm IDE gives me these error "cannot import name _imagingtk" 2) errors which IDE pycharm is giving can anyone help me.
doc_23534873
It starts at StartPage, where the user clicks on the select values button and this opens up PageOne. At this page the user should type the desired values and click the select values button (I´m sorry, I couldn't find a way to save all the values at one, if you know how to do this too, please let me know). After the user saves the values, he goes back to StartPage and clicks the Calculate button. If all values are OK, it shows the result variable. import tkinter as tk from tkinter import ttk, END import math LARGE_FONT =("Verdana", 12) def calculate(): global value_a global value_b global value_c value_list = [value_a, value_b, value_c] if "" in value_list: return False else: delta = (int(value_b.get())**2) - 4*int(value_a.get())*int(value_c.get()) if delta >= 0: delta_root = math.sqrt(delta) bhask_pos = int(-value_b.get()) + (delta_root)/2*int(value_a.get()) bhask_neg = int(-value_b.get()) - (delta_root)/2*int(value_a.get()) global result result = "The equation", int(value_a.get()), "x² +", int(value_b.get()), "x +", int(value_c.get()), "has the results ", int(bhask_pos), "and ", int(bhask_neg) else: pass return True class App(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self,*args, **kwargs) #self.geometry("720x360") container = tk.Frame(self) container.pack(side="top", fill="both", expand=True) container.grid_columnconfigure(0, weight=1) container.grid_rowconfigure(0, weight=1) self.frames = {} for F in (StartPage, PageOne): frame = F(container, self) self.frames[F] = frame frame.grid(row=0, column=0, sticky="nsew") self.show_frame(StartPage) def show_frame(self, cont): frame = self.frames[cont] frame.tkraise() class StartPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) button = ttk.Button(self, text="Insert values", command=lambda: controller.show_frame(PageOne)) button.pack(side="top", padx=10, pady=20, expand=False) canvas = tk.Canvas(self, width=400, height=200, bg="#C0C0C0", bd="10") canvas.pack(side="bottom", padx=10, pady=20, expand=False) if calculate() == False: canvas.create_text(30, 30, text="Error. Check if you selected all values") elif calculate() == True: canvas.create_text(30, 30, text=result) else: pass calculation_button = ttk.Button(self, text="Calculate", command=calculate) calculation_button.pack() class PageOne(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) def get_entry_data_a(): global value_1 value_1 = int(value_a.get()) entry_a.delete(0, END) print(value_1)#just for debugging def get_entry_data_b(): global value_2 value_2 = int(value_b.get()) entry_b.delete(0, END) print(value_2) def get_entry_data_c(): global value_3 value_3 = int(value_c.get()) entry_c.delete(0, END) print(value_3) def event_data_a(event): value_1 = int(value_a.get()) entry_a.delete(0, END) print(value_1) def event_data_b(event): value_2 = int(value_b.get()) entry_b.delete(0, END) print(value_2) def event_data_c(event): value_3 = int(value_c.get()) entry_c.delete(0, END) print(value_3) text_a = tk.Label(self, text="value from a:", padx=10, pady=10) text_a.grid(row=1, column=1) text_b = tk.Label(self, text="value from b:", padx=10, pady=10) text_b.grid(row=2, column=1) text_c = tk.Label(self, text="value from c", padx=10, pady=10) text_c.grid(row=3, column=1) value_a = tk.IntVar() entry_a = tk.Entry(self, textvariable=value_a) entry_a.grid(row=1, column=2) entry_a.delete(0, END) button_a = ttk.Button(self, text="Save value", command=get_entry_data_a) button_a.grid(row=1, column=3, padx=10, pady=10) value_b = tk.IntVar() entry_b = tk.Entry(self, textvariable=value_b) entry_b.grid(row=2, column=2) entry_b.delete(0, END) button_b = ttk.Button(self, text="Save value", command=get_entry_data_b) button_b.grid(row=2, column=3, padx=10, pady=10) value_c = tk.IntVar() entry_c = tk.Entry(self, textvariable=value_c) entry_c.grid(row=3, column=2) entry_c.delete(0, END) button_c = ttk.Button(self, text="Save value", command=get_entry_data_c) button_c.grid(row=3, column=3,padx=10, pady=10) entry_a.bind("<Return>", event_data_a) entry_b.bind("<Return>", event_data_b) entry_c.bind("<Return>", event_data_c) back_button = ttk.Button(self, text="Return to Start Page", command=lambda:controller.show_frame(StartPage)) back_button.grid(row=5, column=2, padx=20, pady=20) app = App() app.mainloop() The results should appear in the canvas, as well as a message error if the user does not select a value. My actual problem is that the canvas object is created in StartPage, so I need to define the function before the StartPage class (because I need the boolean result returned from the function calculate() to create the text in the canvas), but the actual values that the user chooses comes only at the end of the code. How is it possible to use those values? Where should I define the function calculate() in this case? This is the error message: line 10, in calculate value_list = [value_a, value_b, value_c] NameError: name 'value_a' is not defined A: To get the globals working properly, just make sure to give them initial values before their first used. The easiest way to do this is to assign them default values at the module level. For example: value_a = "" value_b = "" value_c = "" def calculate(): global value_a global value_b global value_c # ... That should get your code working. But while Python supports globals, they're almost never the right choice. Look at the logic of your application and think of ways to use local scope more. One possibility is to set value_a, value_b, and value_c as instance variable in your App class, since it's accessible as controller in both frames. For example: def calculate(value_a, value_b, value_c): value_list = [value_a, value_b, value_c] # ... class App(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self,*args, **kwargs) self.value_a = "" self.value_b = "" self.value_c = "" # ... class StartPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) # ... if calculate(controller.value_a, controller.value_b, controller.value_c): # ... class PageOne(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) def get_entry_data_a(): value_1 = int(controller.value_a.get()) entry_a.delete(0, END) print(value_1)#just for debugging # ... controller.value_a = tk.IntVar()
doc_23534874
I also have customs posts types with the slug of 'labs', Ex: example.com/labs/post-name1. My objective is to make the existing page an archive page for labs posts, basically making example.com/labs/ to example.com/research/labs/ I have tried changing the custom post slug to "research/labs" instead of just "labs" using a rewrite on the custom post created. register_post_type( 'labs', array( 'labels' => array( 'name' => __( 'labs','lstheme' ), 'singular_name' => __( 'labs' ) ), 'public' => true, 'has_archive' => true, 'rewrite' => array( 'slug' => 'research/labs', 'with_front' => FALSE ), 'supports' => array( 'title', 'editor', 'thumbnail', 'comments','author' ), ) Changing the slug makes the WordPress posts Archive page URL as I want it to (example.com/research/labs/), but the page that was working before the change becomes a blank page. Probably a very beginner question, but I couldn't find a solution for that…
doc_23534875
<createTable tableName="ADDRESS"> <column name="id" type="bigint(20)" autoIncrement="true"> <constraints primaryKey="true" nullable="false" /> ... //columns </column> </createTable> <createTable tableName="PERSON"> <column name="id" type="bigint(20)" autoIncrement="true"> <constraints primaryKey="true" nullable="false" /> ... //columns </column> </createTable> <addForeignKeyConstraint constraintName="fk_constraint_worker_phone_number" referencedTableName="CONTACT_NUMBER" baseColumnNames="ContactNumbers" baseTableName="WORKER" referencedColumnNames="id" /> I want 3rd table (like hibernate generate in @OneToMany mapping). How to do this with liquibase-springboot? A: If the relation is truly a OnToMany, you don't need a 3rd table. Simply, add PrimaryKeyJoinColumn. If the address can be reused for many persons, it's a ManyToMany relation. You can use @ManytoMany and add information about you joined table un @jointable A: Well, in case of liquibase we have to create the 3rd table manually and have to apply the necessary constraints. Create the table which manages the mapping : <createTable tableName="PERSON_ADDRESS"> <column name="PERSON_ID" type="BIGINT"> <constraints primaryKey="true" nullable="false" /> </column> <column name="ADDRESS_ID" type="BIGINT"> <constraints primaryKey="true" nullable="false" /> </column> </createTable> Apply the constraints: 1) Ensure that Persons id is unique in the mapping table 2) A foreign key relationship between ADDRESS's id and PERSON_ADDRESS's PERSON_ID 3) A foreign key relationship between PERSON's id and PERSON_ADDRESS's ADDRESS_ID <addUniqueConstraint columnNames="PERSON_ID" tableName="PERSON_ADDRESS" constraintName="UK_PHONE_NUMBERS_ID" /> <addForeignKeyConstraint constraintName="FK_ADDRESS_PERSON_ADDRESS" referencedTableName="ADDRESS" baseColumnNames="ADDRESS_ID" baseTableName="PERSON_ADDRESS" referencedColumnNames="id" /> <addForeignKeyConstraint constraintName="FK_PERSON_PERSON_ADDRESS" referencedTableName="PERSON" baseColumnNames="PERSON_ID" baseTableName="PERSON_ADDRESS" referencedColumnNames="id" />
doc_23534876
@Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); LayoutInflater inflater = getActivity().getLayoutInflater(); builder.setView(inflater.inflate(R.layout.buddy_challenge, null)); this.title = (TextView)getActivity().findViewById(R.id.challenge_title); this.challenge = (Button)getActivity().findViewById(R.id.challenge_button); this.at = (AutoCompleteTextView)getActivity().findViewById(R.id.chall_ex); ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("action", "getAllEx")); new ServerCallEx().execute(params); return builder.create(); } The custom layout inflates properly but if I try changing the TextView or try attach an Adapter to the AutoCompleteTextView I get a null pointer exception and can't figure out why (don't know why the getActivity.findViewByID() is not working). Help! A: Try something like: LayoutInflater inflater = getActivity().getLayoutInflater(); View view = inflater.inflate(R.layout.buddy_challenge, null); builder.setView(view); this.title = (TextView)view.findViewById(R.id.challenge_title); Regards. A: Resolved this with : @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.buddy_challenge, container, false); this.title = (TextView)view.findViewById(R.id.challenge_title); this.at = (AutoCompleteTextView)view.findViewById(R.id.chall_ex); this.at.setThreshold(1); return view; } and calling this to remove the title: challDialog.setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_Holo_Light_Dialog); A: Because you haven't created it yet. You called create and return the View at the end of the method, but you're trying to do findViewById before that.
doc_23534877
Here's some dummy data to show what I'm trying to do dat <- data.frame(species = rep (c("Oak", "Elm", "Ash"), each = 3), result = c(10, 7, 4, 13, 9, 2, 8, 5, 1), treatment = rep(c('Ctrl', 'Type_1', 'Type_2'))) species result treatment 1 Oak 10 Ctrl 2 Oak 7 Type_1 3 Oak 4 Type_2 4 Elm 13 Ctrl 5 Elm 9 Type_1 6 Elm 2 Type_2 7 Ash 8 Ctrl 8 Ash 5 Type_1 9 Ash 1 Type_2 What I'd like to do is subtract the Type_1 and Type_2 treatment results for each species by the respective control and generate a new data.frame containing the results. It should look like this. species result treatment_diff 1 Oak 3 Type_1 2 Oak 6 Type_2 3 Elm 4 Type_1 4 Elm 11 Type_2 5 Ash 3 Type_1 6 Ash 7 Type_2 Happy to take a dplyr, tidyr, datatable or any other solution Thanks very much A: An option could be using group_by and use the first value for each group to extract with and filter the rows with result 0 like this: dat <- data.frame(species = rep (c("Oak", "Elm", "Ash"), each = 3), result = c(10, 7, 4, 13, 9, 2, 8, 5, 1), treatment = rep(c('Ctrl', 'Type_1', 'Type_2'))) library(dplyr) dat %>% group_by(species) %>% mutate(result = first(result) - result) %>% filter(result != 0) #> # A tibble: 6 × 3 #> # Groups: species [3] #> species result treatment #> <chr> <dbl> <chr> #> 1 Oak 3 Type_1 #> 2 Oak 6 Type_2 #> 3 Elm 4 Type_1 #> 4 Elm 11 Type_2 #> 5 Ash 3 Type_1 #> 6 Ash 7 Type_2 Created on 2022-07-29 by the reprex package (v2.0.1)
doc_23534878
IntPtr desktop = GetDC(IntPtr.Zero); using (Graphics g1 = Graphics.FromHdc(desktop)) { Pen blackPen = new Pen(Color.Orange, 10); Point pleftTop = new Point(2, 1); Point pleftBottom = new Point(2, 765); g1.DrawLine(blackPen, pleftTop, pleftBottom); Point pTopLeft = new Point(1, 3); Point pTopRight = new Point(1356, 3); g1.DrawLine(blackPen, pTopLeft, pTopRight); Point pRight1 = new Point(1356, 1356); Point pRight2 = new Point(1358, 1); g1.DrawLine(blackPen, pRight1, pRight2); Point pBottom1 = new Point(1, 765); Point pBottom2 = new Point(1356, 765); g1.DrawLine(blackPen, pBottom1, pBottom2); string text = string.Empty; int screenHeight = Screen.GetWorkingArea(this).Height; int screenWidth = Screen.GetWorkingArea(this).Width; text = "Recording your screen & audio"; int centerWidth = ((screenWidth / 3)); int opacity = 255; g1.PixelOffsetMode = PixelOffsetMode.HighQuality; g1.DrawString(text, new Font("Arial", 15), new SolidBrush(Color.FromArgb(opacity, Color.WhiteSmoke)), centerWidth, 0); A: The Graphics.Draw... functions replace the pixels. There is no way to undo that unless you either * *store the pixels that are being changed so you can reverse the drawing or *draw the pixels on a copy of the desktop so you can revert to the actual desktop or *overlay the desktop with a transparent surface and draw on that and remove the surface when it is no longer needed. A: Instead of storing all the pixels you could also just broadcast a message informing the desktop and all its child windows (i.e. everything) to repaint. This is probably much better than my earlier suggestion, as you can paint whatever you like all over the desktop. const int RDW_INVALIDATE = 0x0001; const int RDW_ALLCHILDREN = 0x0080; const int RDW_UPDATENOW = 0x0100; [DllImport("User32.dll")] static extern bool RedrawWindow(IntPtr hwnd, IntPtr rcUpdate, IntPtr regionUpdate, int flags); ... // Redraw the desktop and its children RedrawWindow(IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, RDW_INVALIDATE | RDW_ALLCHILDREN | RDW_UPDATENOW); A: One other option available to you is to use ControlPaint.DrawReversibleFrame. It's quirkier and you can't draw text, but implementing this method is quick. You don't even need a handle to the desktop. Basically it draws a rectangle with an XOR operation so that if you call it a second time in the same location then the rectangle is erased. Note that if any of the rectangle's pixels are modified between the first call and the second call then you'll get artifacts which will persist until the underlying window repaints itself. A: bool change = false; private void timer1_Tick(object sender, EventArgs e) { try { if (change) { InvalidateRect(IntPtr.Zero, IntPtr.Zero, true); change = false; } else { PaintLineToScreen(); change = true; } } catch (System.Exception caught) { MessageBox.Show(caught.Message); } }
doc_23534879
"This is a valid URL but it doesn't look like JIRA". I am trying to connect to my company installation of JIRA studio which is http://[company].jira.com and I know this URL is correct as I have several projects using it successfully. Is there some setting I should enable in JIRA studio for this to work? A: I had a similar issue and fixed it by setting our JIRA studio Title to "Atlassian JIRA". You can change it by going to admin->general->account->account name->(change) The plugin looks for one (or both) of those words, I forget which. You might also have to enable "Accept Remote API Calls" in admin->issues->global settings->general configuration->options Hope that works for you.
doc_23534880
pdf_file = self.request.POST['file'].file pdf_reader = pypdf.PdfFileReader(pdf_file) This gives me error: Traceback (most recent call last): .... File "/myrepo/myproj/main.py", line 154, in post pdf_text = pypdf.PdfFileReader(pdf_file) File "lib/PyPDF2/pdf.py", line 649, in __init__ self.read(stream) File "lib/PyPDF2/pdf.py", line 1100, in read raise utils.PdfReadError, "EOF marker not found" PdfReadError: EOF marker not found It gives this error for any file, even for those that can successfully be read from file on the disk via open(filename, 'r') am i missing something? thanks in advance! A: the solution is to use get_uploads from blobstore_handlers.BlobstoreUploadHandler: from google.appengine.ext.webapp import blobstore_handlers from cStringIO import StringIO import PyPDF2 class UploadHandler(blobstore_handlers.BlobstoreUploadHandler): def post(self): upload_files = self.get_uploads('file') blob_info = upload_files[0] blob_reader = blobstore.BlobReader(blob_info) blob_content = StringIO(blob_reader.read()) pdf_info = PyPDF2.PdfFileReader(blob_content)
doc_23534881
code exactly same as that of the tutorial (in youtube) said but code is being executed in the tutorial but I got stuck with this error. I tried to use seaborn library jointplot function. Type error occurs when the I load the dataframe in the jointplot fucntion. Jupyter shows the message for the type error: Cannot interpret '<attribute 'dtype' of 'numpy.generic' objects>' as a data type import seaborn as sns df = sns.load_dataset('tips') sns.jointplot(x='tip', y='total_bill', data=df, kind='hex')
doc_23534882
The Array is like this : var data = [ [ ['timestamp1', 'value1'], ['timestamp2 ', 'value2'] ], [ ['timestamp1', 'value1'], ['timestamp2 ', 'value2'] ], [ ['timestamp1', 'value1'], ['timestamp2 ', 'value2'] ] ]; And what I'd like as a result is something like this : t1 v1 t1 v1 t1 v1 t2 v2 t2 v2 t2 v2 I've done some research and tried an example : var csvContent = ''; var dataString; data. (function (infoArray) { dataString = infoArray.join(';'); csvContent += dataString + "\n"; }); But it doesn't seem to work with this kind of multiple-dimensional array. Does anyone have a clue of a working solution ? Thanks a lot in advance. A: That's doable of course. What makes it a little more difficult in your case is that it's a three-dimensional array. Well basically you just need two for-loops and compose a string out of the elements. var data = [ [ ['timestamp1', 'value1'], ['timestamp2', 'value2'] ], [ ['timestamp1', 'value1'], ['timestamp2', 'value2'] ], [ ['timestamp1', 'value1'], ['timestamp2', 'value2'] ] ]; var csvContent = ""; for (var a = 0; a < data[0].length; a++) { if (a != 0) { csvContent += "\n"; } for (var b = 0; b < data.length; b++) { csvContent += data[b][a][0] + "," + data[b][a][1] + ","; } } console.log(csvContent);
doc_23534883
So the tables are; shops int id //shopId & primaryKey varchar(50) shopName ... //other details left out. ShopProductTypes int id //Category id int ShopId //Foreign Key to shop table varchar(50) CategoryName ... This is all straighforwards, and works through sql viewer etc a treat. I have imported the database model, and unbchecked the Pluralize / Singularize box. my context is; public ReportingContext(string connectionString) : base(connectionString) { Database.SetInitializer<ReportingContext>(null); } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); } public DbSet<AutoComp_Reporting.DAL.Shop> Shops{get; set;} public DbSet<AutoComp_Reporting.DAL.ShopProductTypes> ShopCategories { get; set; } } but when I run; var foo = (from s in context.Shops where (s.Id == id).select s).toList(); I can see all the shops, but if I try to look at the categories in QuickWatch, I get the follwoing exception {"An error occurred while executing the command definition. See the inner exception for details."} System.Data.EntityException {System.Data.EntityCommandExecutionException} Unwinding that eventually reveals; Message "Invalid column name 'Shops_Id'.\r\nInvalid column name 'Shops_Id'.\r\nInvalid column name 'Shops_Id'." I may well be doing something wrong as I am new to entity framework, but I cannot fix this error. I have got MultipleActiveResultSets=True in my database connection string. So how do I track down the cause of this error, and / or fix it? I am guessing that the actual inner exception is down to the way that the framework is interpreting the properties, so may be a red herring.. A: Changing the name of the Foreign Key in the table, and applying the ForeignKey attribute seems to have worked. However I am sure that this is not the correct solution, else it means that the framework only works out of the box if you have a database that has been built to a specific naming convention. Bearing in mind this is a legacy application, how do I fix this issue once and for all?
doc_23534884
I'm not sure exactly how to phrase this question, so this is the example of what I'm trying to achieve: public interface IEverythingVM : IA, IB { MyTypeA {get;} MyTypeB {get;} MyTypeC {get;} MyTypeD {get;} MyTypeE {get;} MyTypeF {get;} } public class EverythingVM : IEverythingVM { // Populate everything from MyTypeA to MyTypeF } public interface IA { MyTypeA {get;} MyTypeB {get;} MyTypeC {get;} } public interface IB { MyTypeD {get;} MyTypeE {get;} MyTypeF {get;} } Realisation: I was under the impression that I could do something like the following, but having written it out, it's planely apparent why it won't work - I'm trying to take something big, debigulate it and then rebigulate it, which is a concept so ridiculous it makes me want to laugh out loud and chortle. { IA varIA = new EverythingVM(param1, param2); IB varIB = new EverythingVM(param1, param2); var cm = new ComparisonManager(varIA, varIB); } public class ComparisonManager { public ComparisonManager(IEverythingVM varEIA, IEverythingVM varEIB) { // be able to acces MyTypeA, MyTypeB & MyTypeC from varEIA // be able to acces MyTypeD, MyTypeE & MyTypeF from varEIB } } Question: Ultimately what I'm trying to achieve is that in some cases I want MyTypeA, MyTypeB & MyTypeC available in ComparisonManager, and in other cases I want MyTypeD, MyTypeE & MyTypeF available in ComparisonManager. Is there any way for me to achieve this given the current structure? A: Why don't you do like this: public class ComparisonManager { public ComparisonManager(IA varEIA, IB varEIB) {} } ? A: it turns out the solution was to: public class ComparisonManager<T> { private readonly T _diskServiceVm; private readonly T _panelServiceVm; public ComparisonManager(T diskServiceVm, T panelServiceVm) { _diskServiceVm = diskServiceVm; _panelServiceVm = panelServiceVm; } } Implementation: if (/* circumstance A */) { IA varIA = new A(varA, varB); IA varIB = new B(varA, varB); // this knows how to deal with MyTypeA, MyTypeB & MyTypeC var comparisonManager = new ComparisonManager<IA>(varIA , varIB); } else { IB varIA = new A(varA, varB); IB varIB = new B(varA, varB); // this knows how to deal with MyTypeD, MyTypeE & MyTypeF var comparisonManager = new ComparisonManager<IB>(varIA , varIB); }
doc_23534885
and this is the result in emulator and this the setting of emulator A: The keyboard will not pop up if you are emulating a device with a hardware keyboard. Goto AVD, select your AVD name and click edit. Edit Android Virtual Device dialog will appear. You can verify this A: Looks like you are emulating a device which has a hardware keyboard. You can still use your system keyboard to type data into the EditText on the Emulator for testing purposes. But if you really want to show the keyboard when you click the EditText, you would need to emulate a device which supports only a soft keyboard. Or otherwise, go to AVD Manager in Eclipse and select your the virtual device that you created. Edit AVD and remove hardware keyboard from the properties of the AVD. That way your emulator would be configured only to support a soft keyboard. A: Just Check it once in AVD Configuration (Goto ->Windows->AVD manager-->Select AVD-->Edit )whether that Hardware Keyboard is checked or not.if it's not checked that it woudn't come. A: Here, you have enabled the option for hardware keyboard, you can only see the keyboard if you enabled soft keyboard for you AVD, you can use you physical keyboard for interaction or edit your AVD
doc_23534886
my controller: public String editAccount(@RequestParam("id") String id, Model model) { model.addAttribute("account", accountService.getAccount(id)); model.addAttribute("allRoles", roleService.getRoles()); return EDIT_ACCOUNT; } my jsp: <form:form action="" modelAttribute="account"> <form:checkboxes items="${allRoles}" path="roles" itemLabel="name" itemValue="id" delimiter="<br/>"/> </form> the generated html: <span><input id="roles1" name="roles" type="checkbox" value="1"/><label for="roles1">User</label></span><span><br/><input id="roles2" name="roles" type="checkbox" value="2"/><label for="roles2">Admin</label></span><span><br/><input id="roles3" name="roles" type="checkbox" value="3"/><label for="roles3">SuperAdmin</label></span<input type="hidden" name="_roles" value="on"/> I used a second for each loop (not shown) to make sure that the model object contained the roles. It does, yet none of the checkboxes are checked and when I submit the roles object is always empty. Can someone please tell me what I'm missing? Thanks EDIT Sorry just realized it might be helpful to see the account and role objects: public class Account { private String username, firstName, lastName, email; private List<Role> roles; @NotNull @Size(min = 1, max = 50) public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @NotNull @Size(min = 1, max = 50) public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } @NotNull @Size(min = 1, max = 50) public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @NotNull @Size(min = 6, max = 50) public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public List<Role> getRoles() { return roles; } public void setRoles(List<Role> roles) { this.roles = roles; } public String toString() { return ReflectionToStringBuilder.toString(this); } } public class Role { private int id; private String name; public Role() {} public Role(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } @NotNull @Size(min = 1, max = 50) public String getName() { return name; } public void setName(String name) { this.name = name; } } EDIT #2 Controller Post Method @RequestMapping(value = "edit", method = RequestMethod.POST) public String updateAccount(@RequestParam("id") String id, @ModelAttribute("account") @Valid AccountEditForm form, BindingResult result) { System.out.println("FORM VALUES AFTER: " + form); return (result.hasErrors() ? EDIT_ACCOUNT : ACCOUNT_REDIRECT); } AccountEditForm is the form backing object. When I do a GET I grab an Account object and pass the values into an AccountEditForm before displaying the screen. I will attach the AccountEditForm just for clarity. It is very similiar to the account object. I just happened to seperate my form objects from my model objects. public class AccountEditForm { private String username, firstName, lastName, email; private List<Role> roles = new ArrayList<Role>(); @NotNull @Size(min = 1, max = 50) public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @NotNull @Size(min = 1, max = 50) public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } @NotNull @Size(min = 1, max = 50) public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @NotNull @Size(min = 6, max = 50) public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public List<Role> getRoles() { return roles; } public void setRoles(List<Role> roles) { this.roles = roles; } public String toString() { return ReflectionToStringBuilder.toString(this); } } EDIT #3 Role Property Editor public class RolePropertyEditor extends PropertyEditorSupport { private Map<Integer, Role> roleMap = new HashMap<Integer, Role>(); public RolePropertyEditor(List<Role> roleList) { for (Role r : roleList) roleMap.put(r.getId(), r); } public void setAsText(String incomingId) { Role role = roleMap.get(incomingId); System.out.println("PROPERTY EDITOR ROLE " + role); setValue(role); } public String getAsText() { System.out.println("PROPERTY EDITOR ID " + ((Role)getValue()).getId()); return String.valueOf(((Role)getValue()).getId()); } } Defined in my controller like: @InitBinder public void initBinder(WebDataBinder binder) { binder.setAllowedFields(new String[] { "username", "password", "confirmPassword", "firstName", "lastName", "email", "acceptTerms", "currentPassword" }); binder.registerCustomEditor(Role.class, new RolePropertyEditor(roleService.getRoles())); } EDIT #4 NEW ProeprtyEditor public class SecurityRolePropertyEditor extends PropertyEditorSupport { private RoleService roleService; public SecurityRolePropertyEditor(RoleService roleService) { this.roleService = roleService; } public void setAsText(final String name) { Role role = roleService.getRoleByName(name); setValue(role); } } A: Add an equals method to your Roles entity. see this answer (Spring MVC Pre Populate Checkboxes): of a similar question for more details. A: It seems you are missing implementation equals and hashCode method on your entities.
doc_23534887
I know it will be because my query is fairly poor, can anyone advise me? The idea is * *connect to database with photo links *get the default user picture as $profile_main *join the words "photo_" with the default picture number and call it $answer (ex: column 'photo_1' in database) *now check the database again and get the results for $answer and output all information from that database column. $result = mysqli_query($con,"SELECT * FROM tbl_photos"); while($row = mysqli_fetch_array($result)) { $profile_main = $row['default']; $answer = "photo_" . $profile_main; $result2 = mysqli_query($con,"SELECT $answer FROM tbl_photos"); while($row = mysqli_fetch_array($result2)) { echo "<img src=\"" . $row[0] . "\">"; } } A: mysql_fetch_row returns numerical indexes instead of column names (so ['default'] just won't work)... This is how I would do it if I'm understanding you correctly: $result = mysqli_query($con,"SELECT * FROM tbl_photos"); while($row = mysqli_fetch_assoc($result)) { $answer = $row['photo_'.$row['default']]; echo "<img src=\"" . $answer . "\">"; } Anyway, this is assuming default and photo_x are in the same row. A: If you want only one result for a photo then you can use LIMIT like this SELECT $answer FROM tbl_photos LIMIT 1 A: First, both loops you set same $row variable. Use 2 different variable names so that the results don't get mixed up. Second issue is that you have you have 2 loops , so it will show all results each time. You need to break in the second loop. Like this: $result = mysqli_query($con,"SELECT * FROM tbl_photos"); while($row = mysqli_fetch_array($result)) { $profile_main = $row['default']; $answer = "photo_" . $profile_main; $result2 = mysqli_query($con,"SELECT $answer FROM tbl_photos"); while($row2 = mysqli_fetch_array($result2)) { echo "<img src=\"" . $row2[0] . "\">"; break; } } Or by using only one query, it would be much more efficient: $result = mysqli_query($con,"SELECT * FROM tbl_photos"); while($row = mysqli_fetch_array($result)) { $profile_main = $row['default']; $answer = "photo_" . $profile_main; echo "<img src=\"" . $row[$answer] . "\">"; } A: You only require 1 query. TRY $result = mysqli_query($con,"SELECT * FROM tbl_photos"); while($row = mysqli_fetch_array($result)) { $photo = "photo_" .($row['default']; echo "<img src=\"" . $photo . "\">"; }
doc_23534888
There is a directory within the website that needs to be ignored by both WebDeploy and MSBuild because it breaks the site. I was able to configure the deployment configuration file (.pubxml) to make WebDeploy ignore directory: <PropertyGroup> ... <ExcludeFoldersFromDeployment>node_modules</ExcludeFoldersFromDeployment> </PropertyGroup> I was also able to get the site to compile by making the directory hidden in the file system. However, I am unable to get MSBuild to ignore the directory when called from WebDeploy. How do I ignore the directory anytime the site is compiled? Update The compiler logs this in the Output Window when it fails: C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v12.0\Web\Microsoft.WebSite.Publishing.targets(172,5): Error MSB4018: The "CollectFilesinFolder" task failed unexpectedly. A: You want to apply a skip rule so that the directory is ignored by the synchronisation process completely. Add this to your .pubxml file: <ItemGroup> <MsDeploySkipRules Include="SkipNodeModules"> <AbsolutePath>node_modules</AbsolutePath> </MsDeploySkipRules> </ItemGroup> If you run into problems with it not working, you may be seeing this problem. If so, just add: <PropertyGroup> <UseMsDeployExe>true</UseMsDeployExe> </PropertyGroup>
doc_23534889
onclick="document.getElementById('field1').value = Math.round((parseFloat(document.getElementById('field2').value,2)*100))/100 + Math.round((parseFloat(document.getElementById('field3').value,2)*100))/100;" Most numbers round ok to 2 decimal points which is what I need. However, with an example like onclick="document.getElementById('field1').value = Math.round((parseFloat(document.getElementById('21.29').value,2)*100))/100 + Math.round((parseFloat(document.getElementById('54.70').value,2)*100))/100;" Field 1 is returning 75.99000000000001 How can I trim to 75.99 consistently? A: How about this: parseFloat(document.getElementById('21.29').toFixed(2)); The toFixed method should take care of the rounding nicely for you. A: Use the method toFixed(2) to fix it at 2 decimal places: (Math.round((parseFloat(document.getElementById('21.29').value,2)*100))/100 + Math.round((parseFloat(document.getElementById('54.70').value,2)*100))/100).toFixed(2); A: var num = 5 / 6; var display = num.toFixed(2) num outputs: 0.8333333333333334 display outputs: "0.83" A: I had a similar issue - where I do not wanted to round the value but trim upto 2 decimals I got the perfect solution for by writing this function and using where ever needed to trim upto 2 decimals function upto2Decimal(num) { if (num > 0) return Math.floor(num * 100) / 100; else return Math.ceil(num * 100) / 100; } if you call upto2Decimal(2.3699) or upto2Decimal(-2.3699) // returns 2.36 or -2.36 check this solution using your JS console of the browser A: You can use : function myFunction() { var num = "-54.987656"; var roundedValue = roundMethod(num,5); document.getElementById("demo").innerHTML = roundedValue; } function roundMethod(numberVal, roundLimit) // This method will not add any additional 0, if decimal places are less than the round limit { var isDecimal = numberVal.indexOf(".") != -1; if(isDecimal) { if(numberVal.split(".")[1].length > roundLimit) { return parseFloat(numberVal).toFixed(roundLimit).toString(); }else { return numberVal; } }else { return numberVal; } } <html> <body> <p>Click the button to display the fixed number.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> </body> </html>
doc_23534890
i am getting response as --> {"detail":"Authentication credentials were not provided."} I tried with requests python library. Also i am getting the error "target machine actively refused as given below" I tried httplib2 , If any one know Kindly help on this..... :-( import httplib2 http = httplib2.Http() resp = http.request("http://www.something.com", "HEAD")[0] Traceback (most recent call last): File "", line 1, in resp = http.request("http://www.something.com", "HEAD")[0] File "C:\Users\vijayakumar.v\Downloads\python-rest-client-0.2.tar\python-rest-client\python-rest-client\httplib2__init__.py", line 1050, in request (response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey) File "C:\Users\vijayakumar.v\Downloads\python-rest-client-0.2.tar\python-rest-client\python-rest-client\httplib2__init__.py", line 854, in _request (response, content) = self._conn_request(conn, request_uri, method, body, headers) File "C:\Users\vijayakumar.v\Downloads\python-rest-client-0.2.tar\python-rest-client\python-rest-client\httplib2__init__.py", line 823, in _conn_request conn.request(method, request_uri, body, headers) File "C:\Python27\lib\httplib.py", line 1057, in request self._send_request(method, url, body, headers) File "C:\Python27\lib\httplib.py", line 1097, in _send_request self.endheaders(body) File "C:\Python27\lib\httplib.py", line 1053, in endheaders self._send_output(message_body) File "C:\Python27\lib\httplib.py", line 897, in _send_output self.send(msg) File "C:\Python27\lib\httplib.py", line 859, in send self.connect() File "C:\Users\vijayakumar.v\Downloads\python-rest-client-0.2.tar\python-rest-client\python-rest-client\httplib2__init__.py", line 715, in connect raise socket.error, msg error: [Errno 10061] No connection could be made because the target machine actively refused it http = httplib2.Http() resp = http.request("http://www.something.com", "GET")[0] Traceback (most recent call last): File "", line 1, in resp = http.request("http://www.something.com", "GET")[0] File "C:\Users\vijayakumar.v\Downloads\python-rest-client-0.2.tar\python-rest-client\python-rest-client\httplib2__init__.py", line 1050, in request (response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey) File "C:\Users\vijayakumar.v\Downloads\python-rest-client-0.2.tar\python-rest-client\python-rest-client\httplib2__init__.py", line 854, in _request (response, content) = self._conn_request(conn, request_uri, method, body, headers) File "C:\Users\vijayakumar.v\Downloads\python-rest-client-0.2.tar\python-rest-client\python-rest-client\httplib2__init__.py", line 823, in _conn_request conn.request(method, request_uri, body, headers) File "C:\Python27\lib\httplib.py", line 1057, in request self._send_request(method, url, body, headers) File "C:\Python27\lib\httplib.py", line 1097, in _send_request self.endheaders(body) File "C:\Python27\lib\httplib.py", line 1053, in endheaders self._send_output(message_body) File "C:\Python27\lib\httplib.py", line 897, in _send_output self.send(msg) File "C:\Python27\lib\httplib.py", line 859, in send self.connect() File "C:\Users\vijayakumar.v\Downloads\python-rest-client-0.2.tar\python-rest-client\python-rest-client\httplib2__init__.py", line 715, in connect raise socket.error, msg error: [Errno 10061] No connection could be made because the target machine actively refused it
doc_23534891
To work with this process, we requested and got an application created in AAD via AAD Team. After creation of AAD app, the AAD team also gave us application name, application id and object id ; Now, the MS Teams' admin team is asking for process/documentation to link chatbot to be created in app studio to AAD app. Can someone share these instructions or point to any existing ones ? (I couldn't find any in my searches). A: The short answer is that this needs to go into the "botId" section in the Teams app manifest (see here for refence: https://learn.microsoft.com/en-us/microsoftteams/platform/resources/schema/manifest-schema). Longer answers: * *You might not be editing a manifest directly - you are doing it in App Studio, so just go to the Bot section and that's where you capture the Bot ID *It sounds like there is a missing piece in what you are trying to do. You need: a. an Azure Application (got) b. a Teams app where you can capture the Azure App ID as bot id (got) c. a 'Bot' registration in Azure (it's a kind of Azure resource) - have you got this already? If not, someone with Azure access will need to create it. There is a section in the wizard to use an existing Azure Application - you'd need to select that and enter the Azure application id. Here's more info on doing the bot registration: https://learn.microsoft.com/en-us/azure/bot-service/abs-quickstart?view=azure-bot-service-4.0&tabs=userassigned. For the screenshot in section 6, I recommend choosing "Multi-tenant" as the app type (then you can skip the 'Bot identity information' section later), and for 'Creation Type' is where you want to link to the already-created Azure Application. Also note the "pricing tier" - by default it's on "standard", but you can change to the "free" tier to see if that's sufficient for you - your bot needs to be handling a lot of message to need to move up to the paid tier. A: What I did end up doing was: * *Create an app registration in azure with a secret. The secret becomes bot password in teams. *Create a bot using https://dev.botframework.com/bots. Since my app/bot is single tenant, I needed to be able to create a bot without azure service which requires subscription. I enabled Teams for this bot, besides web chat which is enabled by default. *Create an app using app studio, referencing the azure app and bot from botframework.
doc_23534892
What is the significance of the leading underscore in cookie names? Is it simply a convention, or is there a technical reason? A: At the time this question was asked, there wasn't a specific technical reason. However, since about 2015 there has been support in browsers for two specific "cookie prefixes": __Secure- prefix: Cookies with names starting with __Secure- (dash is part of the prefix) must be set with the secure flag from a secure page (HTTPS). __Host- prefix: Cookies with names starting with __Host- must be set with the secure flag, must be from a secure page (HTTPS), must not have a domain specified (and therefore, are not sent to subdomains), and the path must be /. These solve some historical security problems with cookies. By default it is possible for subdomains to set cookies on parent domains, which violates some expectations around the Same-Origin Policy. And it's possible for http:// URLs to set and overwrite cookies that were originally set via an https:// URL. By using these cookie prefixes you can opt out of those problems and into a more secure cookie paradigm.
doc_23534893
void Show(vector<int> myvec) { vector<int>::iterator it; cout << "Vector contains:"; for( it = myvec.begin(); it < myvec.end(); it++) { cout << " " << *it; } cout << endl; } while this one gives me an error message at compile time: template <class T> void Show2(vector<T> myvec) { vector<T>::iterator it; cout << "Vector contains:"; for( it = myvec.begin(); it < myvec.end(); it++) { cout << " " << *it; } cout << endl; } The error is: $ g++ hello.cpp hello.cpp: In function ‘void Show2(std::vector<T, std::allocator<_Tp1> >)’: hello.cpp:19: error: expected ‘;’ before ‘it’ hello.cpp:21: error: ‘it’ was not declared in this scope It seems a very simple mistake, but I couldn't find it. A: You need to say typename vector<T>::iterator it. On another note, you're passing vectors by value. That means the entire vector gets copied in the function call. void Show(vector<T> const &myvec) and using const_iterator would be wiser. A: Some compilers have problems detecting what is a member name and what is a type name, when inside templates. Try writing something like this in the first line of your template function body. typename vector<T>::iterator it; A: You need this: typename vector<T>::iterator it; This tells the compiler that vector<T>::iterator should be treated as a type, something it can't assume since iterator is dependent on what T is. A: Maybe it works using typename vector<T>::iterator it; Your compiler cannot know that there is an inner class iterator. A: In the first instance the parameter, although it uses a template, is not a template, it is a fully defined class (vector<int>) In the latter instance the parameter is a template on type T and thus requires typename
doc_23534894
My questions are: * *What is the purpose of jaspersoft custom-build of iText? Patches? *Is it safe to use regular iText library, version 2.1.7 found in maven central repo? A: Since the iText license changed from MPL/LGPL Jasper Report couldn't upgrade. So according to the LGPL they supplied a jar file with their changes. You may ask what changes are: * *they added a pom.xml (not relevant in your case) *they did a minor change to the ant.properties for their own version numbering (not relevant in your case) *patched the PdfGraphics2D.java file (fixed a transparency bug) The change is about the currentFillGState, Lines 1089, 1490, 1616-1628. What this means for you is difficult to tell but you have the following possibilities: * *exchange the patched.jar with the default and run (extensive) tests *add the patched.jar to your repository *add the public jasper report repo to your repo (http://jasperreports.sourceforge.net/maven2) *and as others pointed out ask jr folks for further details, e.g. here would be a start: http://community.jaspersoft.com/jasperreports-library/issues/2594-0
doc_23534895
I can spawn an application and can work with output but I can't send arrow down key: import pexpect import time import sys, os os.environ['LINES'] = "25" os.environ['COLUMNS'] = "80" child=pexpect.spawn("my_ncurses_app", maxread=4000, encoding="utf-8") child.logfile=sys.stdout child.setwinsize(25,80) KEY_DOWN = '\033[B' #close button appears on screen, After that I want to press down key twice and enter child.expect("Close") #ncurses_app sees KEY_DOWN as 3 different keys \033, [, B child.send(KEY_DOWN) child.send(KEY_DOWN) child.sendline() #ncurses_app sees enter as Int(10) It works perfect for other CLI applications, but not for my. Debugging shows what instead of 1 arrow down symbol application sees 3 different keys. How I can send KEY_DOWN as one symbol? Possibly I should use smth other instead of pexpect, smth with low-level interaction with processes?
doc_23534896
But in case if i want to send an mail when any exception occurs its not working. namespace App\Exceptions; use App\Mail\Exception\ExceptionMail; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; use Throwable; class Handler extends ExceptionHandler { /** * A list of the exception types that are not reported. * * @var array */ protected $dontReport = [ // ]; /** * A list of the inputs that are never flashed for validation exceptions. * * @var array */ protected $dontFlash = [ 'current_password', 'password', 'password_confirmation', ]; /** * Register the exception handling callbacks for the application. * * @return void */ public function register() { $this->reportable(function (Throwable $e) { Mail::to('some@gmail.com')->send(new ExceptionMail()); }); } }
doc_23534897
every question can have many answers. And answers have status id which is a number. So: I have: class Question < ActiveRecord::Base has_many :answers, :order =>'status_cat_id' Now, answers are related to users, and I want the order of answers to be first by status_is and then by user name. So, when I'll call: @question.answers I will get the answers ordered first by status and then by the user name. Is it possible to achieve that through the model? A: The answer is: has_many :answers, :include => :user, :order =>'status_cat_id, users.name'
doc_23534898
https://exdev.server.propctrl.com/v5.4/Basic/AgencyIntegration.svc?wsdl I am able to create my soap client, and when I try to call a function it returns saying access denied: Message: Access is denied. Based on documentation, there is no verification/auth method that I first need to call, but it seems I have to use a type called Credentials. struct Credentials { string Password; string Username; } I then tried created a Credentials object: class Credentials { public function __construct($username, $password) { $this->username = $username; $this->password = $password; } } And assigned new values to it and used it in my SoapHeaders: $credentials = new Credentials($username, $password); $header = new SoapHeader('http://localhost','Credentials',$credentials,false); $client->__setSoapHeaders($header); When I then use a function I still get the same error: echo "<pre>"; try { $response = $client->__soapCall("EchoAuthenticated", array("EchoAuthenticated" => "asdfasdf")); var_dump($response); } //catch exception catch(Exception $e) { echo 'Message: ' .$e->getMessage(); } Message: Access is denied. I guess my question is that I don't know where/how to pass through the credentials in order for the API to authorise my request. Any ideas/suggestions? update1: A: The authentication method should be explained in some documentation, anyway there are Soap services that use HTTP Header for authentication, for example $soapClient->setHttpHeaders([ 'clientId' => $username, 'clientSecret' => $password ]); But please consider that keys ( in my example clientId and clientSecret ) depend by the service implementation. Do you have a service documentation?
doc_23534899
A: So, in short, is redirecting allowed after the request has already been forwarded, or will it result in an IllegalStateException? No, it's absolutely fine. The response itself has no knowledge of the forwarding - it occurs purely within the internals of the server. Forwarding is simply a mechanism for internal transfer of control from one server component to another. In contrast, you generally cannot forward after redirecting, since redirecting "commits" the response, and there's no undoing that. A: You will only get an IllegalStateException when the reponse is committed. So if the forwarded resource commits the response before redirecting, then you will get IllegalStateException. The response is committed when the response headers are already been sent. This can happen when you write a byte to the response body and flush it. A redirect requires an uncommitted response because a redirect needs to be done by setting a Location header with a blank body. In a decent MVC approach, the JSP is part of the response, so whenever you send a redirect from inside a JSP by either a scriptlet or a JSTL <c:redirect>, then you will risk IllegalStateException. But if you don't do that anywhere, there's nothing to worry about.