text
stringlengths
0
13M
Title: Check if array is not empty Tags: php;arrays Question: ********Update********** ```var_dump: string(0)``` "" I am trying to check if part of an array is not empty then display code but the code get's displayed anyway. I have tried ```!is_null !empty```. I am not really sure which should be correct or should I go with: ```if (sizeof($book['Booking']['comments'])&gt;0)``` Code: ```<?php if (!empty($book['Booking']['comments'])) {?&gt; <table width="100%" border="0"&gt; <tbody&gt; <tr&gt; <td style="font-family:'Lucida Grande', sans-serif;font-size:12px;font-weight:normal;color:#666666;"&gt; <?=$book['Booking']['comments']?&gt; </td&gt; </tr&gt; </tbody&gt; </table&gt; <? } ?&gt; ``` Array: ```Array ( [Booking] =&gt; Array ( [id] =&gt; 109 [user_id] =&gt; 1 [corporate_account_id] =&gt; 0 [id_ref] =&gt; RES000109 [price] =&gt; 178.00 [arrival] =&gt; 2011-10-18 00:00:00 [departure] =&gt; 2011-10-19 00:00:00 [rate_title] =&gt; [adult_guests] =&gt; 4 [child_guests] =&gt; 0 [company] =&gt; gravitate [titlename] =&gt; [firstname] =&gt; John [surname] =&gt; Doe [address1] =&gt; 123 Fake St [address2] =&gt; [city] =&gt; New York [state] =&gt; NY [postcode] =&gt; 12345 [country] =&gt; US [phone] =&gt; 1111111111 [mobile] =&gt; [fax] =&gt; [email] =&gt; [email protected] [comments] =&gt; [created] =&gt; 2011-10-18 13:40:47 [updated] =&gt; 2011-10-18 13:40:47 [status] =&gt; 1 [cancelled] =&gt; 0 [request_src] =&gt; website [request_token] =&gt; 0 [token] =&gt; ayzrGnx [survey_sent] =&gt; 0000-00-00 00:00:00 [survey_returned] =&gt; 0000-00-00 00:00:00 [send_sms] =&gt; 0 [payment_time] =&gt; 0000-00-00 00:00:00 [fullname] =&gt; John Doe ) ``` Comment: What's the type of `comments` supposed to be? `empty` should work fine in all cases except when you have a string composed entirely of whitespace. Comment: What `var_dump($book['Booking']['comments'])` gives? Comment: possible duplicate of [How to tell if a PHP array is empty?](http://stackoverflow.com/questions/2216052/how-to-tell-if-a-php-array-is-empty) Here is the accepted answer: I suspect it may contain ```(bool) FALSE```, which is not true for ```is_null()```. Try simply: ```if ($book['Booking']['comments']) { ``` This should also work for anything that evaluates to ```FALSE```, like an empty string. Comment for this answer: `which is not true for empty()` - who said you that? Comment for this answer: `if (!$book['Booking']['comments']) {` will do the opposite. Comment for this answer: Whoa! Two months took you to correct one statement ;) What about other one? Comment for this answer: @Col.Shrapnel somebody +1ed me for it randomly, to be honest I haven't re-visited this page since I wrote this, and I have admit this is *not* the best answer here... but it might as well be correct in it's inadequacy... Here is another answer: ```!empty($var)```, ```count($var) &gt; 0```, ```!$var```, all of these will work in most situations. empty() has the "advantage" of not throwing a notice when the given variable / array key doesn't exist, but if you don't have to worry about that a boolean check (```!$var```) should suffice (see here which types convert to FALSE). It also happens to be the shortest in code. Here is another answer: Empty array: ```$array = array();``` ```reset($array)``` returns ```FALSE```. Populated array: ```$array = array('foo', 'bar');``` ```reset($array)``` returns first element (```'foo'```). Here is another answer: I think you can try to use this following logic, and try to make it a little bit simpler. ```<?php // Only change this // and leave everything else as is $book_comment = $book['Booking']['comments']; $book_comment = trim($book_comment); // The reason I use empty trim, is to take // away any space. // In the output, use the original $book['Booking']['comments'] if(!empty($book_comment)):?&gt; <table width="100%" border="0"&gt; <tbody&gt; <tr&gt; <td style="font-family:'Lucida Grande', sans-serif;font-size:12px;font-weight:normal;color:#666666;"&gt; <?=$book['Booking']['comments']?&gt; </td&gt; </tr&gt; </tbody&gt; </table&gt; <?php endif;?&gt; ``` I have not tested this, as I can't right now, but hopefully that should somewhat help you. Here is another answer: If you want to ascertain whether the variable you are testing is actually explicitly an not empty array, you could use something like this: ```if ($book['Booking']['comments'] !== array()) { //your logic goes here .................... } ``` This logic is more faster from others solution. Also it will maintain coding standard. Here is another answer: that is not an array for sure. do ```var_dump($book["Booking"]["comments"])``` to check the data type accordingly Comment for this answer: I would like to display the code if it is not empty would I use ===? Thanks Comment for this answer: then you should just do - if($book["Booking"]["comments"] == "") Here is another answer: ```if (count($book['Booking']['comments']) &gt; 0) { ... }``` Here is another answer: You may want to ```trim()``` that property to remove any whitespace before testing if it is ```empty()```. Edit: I'm assuming it is a string. It doesn't look like an empty array. Here is another answer: I don't think that ```$book['Booking']['comments']``` is even an array in this case. So you could just use ```strlen``` http://php.net/manual/en/function.strlen.php ```<?php if (strlen($book['Booking']['comments'])) {?&gt;``` Here is another answer: your question is too localized. There is some typo in your code or something like that. There is absolutely no difference what to use in your case, ```if (!empty($var))``` or ```if ($var)```. So, ```if ($book['Booking']['comments']) {``` worked, there was no problem with your ```if (!empty($book['Booking']['comments']))``` too. So, there was no poin in the [email protected]. All these answers trying to answer this not-a-real-question are nonsense. the only issue can be a space symbol mentioned by jotorres1, but you have already said there are none.
Title: Refreshing display for newly added labels with ArcObjects from Python? Tags: python;arcgis-10.1;arcobjects;labeling Question: I've added a shapefile to an MXD and Edited the symbolization of it with ArcObjects. Now I'm trying to edit the labeling with ArcObjects. I've successfully been able to edit the default class in the IAnnotateLayerPropertiesCollection2 object. I've also successfully added two more label classes to that collection object. The default class that I edited is displaying correctly, but the extra two Label Classes aren't displaying after the script is run. When I manually open the properties of the layer and open the properties for each label class that I added and choose OK or Apply, then they show up. So I know that they are being added properly, but how do I get them to display through the script? I've tried MxDoc.UpdateContets(), MxDoc.ActiveView.Refresh(), arcpy.RefreshActiveView() and none of them work for this. I'm using Python to handle the ArcObjects, but if you know how to do it in VB or C#, I can interpolate it. ```def ApplyLabels_arcobjects(layersource, pFLayer, pStyleGallery, carto): # If there are no labels in the custom symbology object if not layersource.symbology.labels: return # Get Annotation Properties Collection geofeaturelayer = Snippets.CType(pFLayer, carto.IGeoFeatureLayer) pAnnoPropColl = geofeaturelayer.AnnotationProperties pAnnoPropColl2 = Snippets.CType(pAnnoPropColl, carto.IAnnotateLayerPropertiesCollection2) # Loop through each label in the custom symbology object i = 0 for labelsource in layersource.symbology.labels: print("This is label number {0}".format(i+1)) # TODO Remove, for debugging # Get the premade Label Style from the style file pStyleGallery.LoadStyle(labelsource.style_filename, labelsource.label_classname) gallerystyle = getLabelSymbol(labelsource, pStyleGallery, carto) pLabelStyle = Snippets.CType(gallerystyle, carto.ILabelStyle2) # If I can get a Annotation Property that is already there, great: if i <= pAnnoPropColl2.Count - 1: print("Editing the one already there") # TODO Remove, for debugging pAnnoLayerProp = pAnnoPropColl2.QueryItem(i)[0] # Class Name pAnnoLayerProp.Class = labelsource.name # Sql string for Where expression pAnnoLayerProp.WhereClause = labelsource.sql_string # Set Sympol and Placement Properties pLabelEngineProp = Snippets.CType(pAnnoLayerProp, carto.ILabelEngineLayerProperties2) pLabelEngineProp.Symbol = pLabelStyle.Symbol pLabelEngineProp.OverposterLayerProperties = pLabelStyle.OverposterLayerProperties # If I have to add an Annotation Property to the Collection, then: else: print("Adding new Label Engine")# TODO Remove, for debugging # New Label Engine pLabelEngineProp = Snippets.NewObj(carto.MaplexLabelEngineLayerProperties, carto.ILabelEngineLayerProperties2) # Apply Symbol pLabelEngineProp.Symbol = pLabelStyle.Symbol # Apply Placement Properties pLabelEngineProp.OverposterLayerProperties = pLabelStyle.OverposterLayerProperties # Cast pAnnoLayerProp = Snippets.CType(pLabelEngineProp, carto.IAnnotateLayerProperties) # Class Name pAnnoLayerProp.Class = labelsource.name # Sql string for Where expression pAnnoLayerProp.WhereClause = labelsource.sql_string # Display Annotation pAnnoLayerProp.DisplayAnnotation = True # Add it to the collection pAnnoPropColl2.Add(pAnnoLayerProp) # Turn on Annotation for the Map Layer geofeaturelayer.DisplayAnnotation = True i += 1 ``` Here is another answer: I've not done much with labelling with ArcObjects so this may not be relevant or you have tried it already? Have you tried setting IAnnotateLayerProperties.DisplayAnnotation Property? Comment for this answer: Yes I have. I'll add my code too. Comment for this answer: I'm not familiar with Python but what I've done with ArcObject_C# is something like this:Write a class which implements IExtension interface,in this class use a varible for IActiveView and assign it properly.Then cast it to IActiveViewEvents_Event interface.Now you can overload the AfterDraw event or ItemAddes,ItemDeleted.In that overloaded event you can write your code to refresh map view. Comment for this answer: You should make this an answer. I can't test it anymore but it sounds like it might work. Here is another answer: Try this ELSE statement: ```else: print("Adding new Label Engine")# TODO Remove, for debugging # New Label Engine pLabelEngineProp = Snippets.NewObj(carto.MaplexLabelEngineLayerProperties, carto.ILabelEngineLayerProperties2) # Apply Symbol pLabelEngineProp.Symbol = pLabelStyle.Symbol # Apply Placement Properties pLabelEngineProp.OverposterLayerProperties = pLabelStyle.OverposterLayerProperties # Cast pAnnoLayerProp = Snippets.CType(pLabelEngineProp, carto.IAnnotateLayerProperties) # Class Name pAnnoLayerProp.Class = labelsource.name # Sql string for Where expression pAnnoLayerProp.WhereClause = labelsource.sql_string ((ILabelEngineLayerProperties2)pAnnoLayerProp).Expression = labelExpression; ((ILabelEngineLayerProperties2)pAnnoLayerProp).Symbol = pLabelStyle.Symbol; ((ILabelEngineLayerProperties2)pAnnoLayerProp).OverposterLayerProperties = pLabelStyle.OverposterLayerProperties; # Display Annotation pAnnoLayerProp.DisplayAnnotation = True # Clear existing labelling classes pAnnoPropColl2.Clear() # Add it to the collection pAnnoPropColl2.Add(pAnnoLayerProp) # Turn on Annotation for the Map Layer geofeaturelayer.DisplayAnnotation = True ``` Here is another answer: AnnotationProperties is a get/put property meaning a reference is not handed out. You need to set the collection back into the FeatureLayer after modifying it.
Title: Accessing model instances associated with a forms.ModelMultipleChoiceField from the templates Tags: django;django-models;django-forms;django-templates Question: I'd like to create a form that would allow a visitor to pick one or several instances of a Model which roughly looks like this: ```class Package(models.Model): name = models.CharField(max_length=255) image = models.ImageField(upload_to="foo") ``` I have for that created a Form that looks like this: ```class PackageSelectionForm(forms.Form): packages = forms.ModelMultipleChoiceField(queryset=Package.objects.all(), widget=forms.CheckboxSelectMultiple()) ``` Now, I'd like to display the image associated with each Package instance in the HTML form in their respective label tags (or near), but I can't manage to find a way to access the instances from the form fields. Do you see how I can? thanks Comment: Thanks, I will check it out! Comment: I wanted to do something similar, so I ended up creating a custom form field that lets you assign multiple fields from your model as html data attributes. You can check it out and pip install it if you think it will fit your needs: https://github.com/denvaar/django-fancy-feast/blob/master/docs/DataModelChoiceField.rst
Title: sapply with multiple arguments in r Tags: r Question: I want to compute a weighted mean over factors with the code below ```factor <- factor(cut(var1, quantile(var1, seq(0,1,0.1)))) var2_split = split(vat2, factor) weight_split = split(weight, factor) sapply(var2_split, weighted.mean, weight_split) ``` I get the following error ```Error in FUN(X[[1L]], ...) : 'x' and 'w' must have the same length ``` How do I format my vector and weights for sapply? As an example suppose I have a matrix m with 3 columns x,y,z where x is a set of target values, y is a set of weights, and z is a set of values over which I want to bucket weighted.mean(x,y). Specifically I want weighted.mean(x,y) bucketed by quartiles of z. ```# Code that doesn't work x <- c(1,2,3,4,5,6) y <- c(6,3,4,2,3,4) z <- c(1,1,2,3,3,4) m <- as.matrix(c(x,y,z),nrow=6,ncol=3)) # bucket z by quartile. z.factor <- cut(z, quantile(z, seq(0,1,0.25)), include.lowest=TRUE) x.split = split(x, z.factor) y.split = split(y, z.factor) # want to bucket weighted.mean(x,y) on quartiles of z sapply(x.split, weighted.mean, y.split) ``` Comment: Does mapply work for the example above ? Comment: Sorry, above is an attempt at what I want to do. I have two problems : (1) grouping by quartiles and (2) applying weighted.mean on each group. Comment: You can only sapply over one vector/list at a time. If you want to simultaneously iterate allong var2_split and weight_split, try `mapply` or `Map` instead. It would be easier to give a more specific answer if you provide a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with your question. Comment: Your example above isn't [reproducible](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). Provide some sample input data (ie `var1`, `vat2`, `weight`, etc) so it's possible to run and test on data that looks like your actual input. Here is the accepted answer: With your specific sample, try ```#first, note the include.lowest=TRUE to get all values z.factor <- factor(cut(z, quantile(z, seq(0,1,0.25)), include.lowest=TRUE)) #same x.split = split(x, z.factor) y.split = split(y, z.factor) # here we use mapply mapply(weighted.mean, x.split, y.split) ``` this gives ```[1,1.25] (1.25,2.5] (2.5,3] (3,4] 1.333333 3.000000 4.600000 6.000000 ``` which seems correct given your sample input.
Title: Linker error when using gSOAP with 2 different wsdl files Tags: c++;gsoap Question: I am writing a C++ web service client using gSOAP on linux using 2 separate wsdl files in the same application. I have managed to get things working with just one wsdl file, and after reading documentation, went through the process of using wsdl2h on both files: ``` wsdl2h -o header.h wsdlfile1.wsdl wsdlfile2.wsdl ``` This worked fine and so I then did ``` soapcpp2 -i -I/usr/share/gsoap/import/ header.h ``` I then did all the usual namespace modifications in the typemap.dat as instructed. I now find that I have two .cpp and .h files of the type soapService1Proxy.cpp/h and soapService2Proxy.cpp/h. This is not quite what I expected, but regardless, I included both headers in my main function and created instances of each Proxy class and used in exactly the same way as I did for with just one wsdl file. I then compile with ``` g++ -DWITH_OPENSSL main.cpp soapC.cpp soapService1Proxy.cpp soapService2Proxy.cpp -lgsoapssl++ -lssl ``` which returns the error ``` /tmp/ccHNDAM4.o:(.data+0x0): multiple definition of `namespaces' /tmp/ccLJIHwV.o:(.data+0x0): first defined here collect2: ld returned 1 exit status ``` I know that the 'namepaces' refers to the array in the .nsmap files (which in this case are identical for each wsdl). I have included only one of these as the compiler complains of multiple definition if I include both. I really would appreciate it if anyone could tell me what I am doing wrong here as I have tried to follow the guidelines and gSOAP docs as faithfully as possible but simply cannot resolve this problem. Here is the accepted answer: I've never used SOAP but I had a quick look at this user guide. The last paragraph in section 7.1.4 says that the ```-n``` and ```-p``` options to ```soapcpp2``` help to resolve link conflicts. The link there to section 19.35 provides more information. It appears you have to run ```wsdl2h``` on each file separately using the ```-q``` option to provide a C++ namespace for each one. When you then run ```soapcpp2``` it will automatically apply ```-p``` and all you have to do is supply ```-n``` to have the ```namespaces``` array prefixed with your C++ namespace name followed by an underscore. I haven't tried any of this but hopefully that will be enough to get you going again.
Title: TableView: How to proceed after catching 'NSInternalInconsistencyException'? Tags: ios;objective-c;uitableview Question: I have an application with a ```UITableView```. The application communicates with a server. Problem is the following: Client 1 deletes a cell of the TableView. The data update is transmitted to the server which sends a data update to Client 2. In the same moment Client 2 deletes a cell from the TableView. Due to the receiving update an ```NSInternalInconsistencyException``` is thrown because the number of cells before and after are not as expected (difference is 2 not 1). The app crashes in ```[tableView endUpdates]; ``` Of course I can catch the exception with ```- (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { @try{ // Send data update to the server [sender sendDataToServer:data]; // Update tableview [tableView beginUpdates]; [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationFade]; [tableView endUpdates]; } @catch (NSException * e) { // Hide red delete-cell-button tableView.editing = NO; // Jump to previous ViewController [self.navigationController popViewControllerAnimated:YES]; } } } ``` But after the successful catch I get an ``` EXC_BAD_ACCESS exception in [_UITableViewUpdateSupport dealloc]. ``` What can I do to prevent the app from crashing? What do I have to do in the catch-block to "clean" the situation? Reloading the tableview doesn't take any effect. EDIT: numberOfRows-method looks like this: ```- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [dataSourceArray count]; } ``` Comment: `deleteRowsAtIndexPath` updates the view but not the model. You have to delete the object also from the data source array. Then you can remove the expection block. It will never occur again. And remove also `begin/endUpdates`. It has no effect in this case. Comment: @Farley write your `numberOfRowsInSection` method Comment: You don't *"clean"* it - you have to ***prevent it*** from occurring! Write your code in a way that makes these kind of exceptions impossible to happen. Comment: Sounds like some thread synchronisation is required. Look at `@synchronized(lock) { ... }`. Comment: are you deleting this object from your array? Comment: @vadian: Yes, i delete object also from data source array. Crashes anyway. Here is the accepted answer: @synchronized(lock) solved my problem. I just had to make sure that only one thread is able to manipulate the data source array at the same time. Now everything works fine, no more 'NSInternalInconsistencyException'. Thx to trojanfoe and luk2302.
Title: How to use GradientBoostingClassifier init Parameters in sklearn Tags: python;scikit-learn Question: I want to use one sklearn.ensemble.GradientBoostingClassifier to init another sklearn.ensemble.GradientBoostingClassifier, but it raises error "IndexError: too many indices for array". It seams that it's an error in sklearn and also I've found pull request in sklearn on GitHub and sklearn on GitHub. If someone try to do this and have positive experience please let me know. System info: MacOS X 10.11.5 (15F34) python -V : Python 2.7.11 181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16 Anaconda custom (x86_64) sklearn.__version__ : '0.17.1' Above is a sample code that shows this error. ```from sklearn.datasets import load_iris from sklearn import ensemble from sklearn.cross_validation import train_test_split iris = load_iris() X, y = iris.data, iris.target X, y = X[y < 2], y[y < 2] # make it binary X_train, X_test, y_train, y_test = train_test_split(X, y) # Fit GBT init with RF clf = ensemble.GradientBoostingClassifier() clf.fit(X_train, y_train) clf2 = ensemble.GradientBoostingClassifier(init=clf) clf2.fit(X_train, y_train) acc = clf2.score(X_test, y_test) print("Accuracy: {:.4f}".format(acc2)) ``` Comment: https://stackoverflow.com/questions/17454139/gradientboostingclassifier-with-a-baseestimator-in-scikit-learn
Title: Programatically load a UserControl from another project Tags: asp.net Question: I like to build a components collection project so that I can use those components later on other projects. For example I created a UserControl called MyDataGrid.ascx So suppose the projects layout are something like this: ``` --> IPGostarProject - Under namespace of IPGostar - contains components and lot's of user controls --> SampleProject - here I want to use MyDataGrid.ascx UserControl from IPGostar namespace. ``` But as you know LoadControl function only takes virtual directory as it's parameter. So you can't load anything outside the SampleProject directory! So how can I do that? Here is another answer: As long as you're dealing with partial classes there's no great way to do this outside of file system trickery. A better way is to implement shared UserControls as WebControls. If you have extensive markup, it's probably not well suited to be a shared control, anyway... e.g. will you also share the style sheet? Separate out the majority of the markup which is not part of the core functionality of your control, and implement just the core as a WebControl, generating any markup and controls in code. The actual project that implements it should be responsible for layout, formatting, etc. Use events to provide hooks to the client (e.g. for a data grid, events for CreateRow, CreateCell, and so on) Here is another answer: One way would be for the post-build event (or whatever build script you are using) of SampleProject project to copy the actual user controls into a subfolder of SampleProject so they are [email protected].
Title: How to change muitl divs the display which have some special id? Tags: javascript;jquery Question: I has some div as follows ```<div id="span1"&gt;</div&gt; <div id="span3"&gt;</div&gt; <div id="span5"&gt;</div&gt; <div id="span7"&gt;</div&gt; ..... ``` There is "span" in the id, How to show or hide them by jquery ? Here is the accepted answer: This should do the trick, if I understand the question correctly. ```$('[id*="span"]').hide(); ``` That said, a much BETTER approach would be to put a class on all the elements you want to manipulate with the same code then use the class to hide the elements as a group. ```<div id="span1" class"span"&gt;</div&gt; <div id="span3" class"span"&gt;</div&gt; <div id="span5" class"span"&gt;</div&gt; <div id="span7" class"span"&gt;</div&gt; $('div.span').hide(); ``` This is much cleaner. Comment for this answer: Thanks! one more question , `function category_select(id){ hide/show some div} `, How to pass id param to string '[id*="/param/"]' ? Comment for this answer: http://stackoverflow.com/questions/10672033/how-to-pass-js-code-to-string-gracefully it's here Comment for this answer: +1 for using the `*=`, but wouldn't `^=` do the same? assuming they all start in `span` Comment for this answer: @Joseph - I was playing it safe. The OP said that span was "in" the ID so I wasn't sure we could count on it being a prefix. Comment for this answer: @why I think you should post a separate question for that. The format of this site works better that way. In any case. Go with the second option it is a much better approach anyway. Here is another answer: you can put the selectors of the ones to hide in an array and join then with a comma: ```var tohide = [ "#span1", "#span3", "#span5", "#span7" ]; $(tohide.join(',')).hide(); ``` or, add a common class to each: ```<div class="tohide" id="span1"&gt;</div&gt; <div class="tohide" id="span3"&gt;</div&gt; <div class="tohide" id="span5"&gt;</div&gt; <div class="tohide" id="span7"&gt;</div&gt; $('.tohide').hide(); ``` Comment for this answer: Actually, you don't even need `.join(',')`, `toString()` is enough. But clever solution! Comment for this answer: +1 - Very clever solution. Thinking outside the box today are you?
Title: Coinbase API returning "product not found" for valid product ID Tags: javascript;node.js;rest;post;coinbase-api Question: I'm using the sandbox API at the moment, and I can query the products, including individually, but if I try and place a buy order, the response I get is ```{ message: 'Product not found' }```. Here's my code: ```async function cb_request( method, path, headers = {}, body = ''){ var apiKey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx', apiSecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx', apiPass = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx'; //get unix time in seconds var timestamp = Math.floor(Date.now() / 1000); // set the request message var message = timestamp + method + path + body; //create a hexedecimal encoded SHA256 signature of the message var key = Buffer.from(apiSecret, 'base64'); var signature = crypto.createHmac('sha256', key).update(message).digest('base64'); //create the request options object var baseUrl = 'https://api-public.sandbox.pro.coinbase.com'; headers = Object.assign({},headers,{ 'CB-ACCESS-SIGN': signature, 'CB-ACCESS-TIMESTAMP': timestamp, 'CB-ACCESS-KEY': apiKey, 'CB-ACCESS-PASSPHRASE': apiPass, 'USER-AGENT': 'request' }); // Logging the headers here to ensure they're sent properly console.log(headers); var options = { baseUrl: baseUrl, url: path, method: method, headers: headers }; return new Promise((resolve,reject)=&gt;{ request( options, function(err, response, body){ if (err) reject(err); resolve(JSON.parse(response.body)); }); }); } async function main() { // This queries a product by id (successfully) try { console.log( await cb_request('GET','/products/BTC-USD') ); } catch(e) { console.log(e); } // Trying to place a buy order here (using the same id as above) returns { message: 'Product not found' } var buyParams = { 'type': 'market', 'side': 'buy', 'funds': '100', 'product_id': 'BTC-USD' }; try { var buy = await cb_request('POST','/orders',buyParams); console.log(buy); } catch(e) { console.log(e); } } main(); ``` I've tried sending the params in the body, which responds with ```invalid signature```, even when stringified. I've also tried using the params shown in the API docs, but that responds with ```product not found``` too. Any ideas? TIA Comment: Could be a weird permission error. Do you have "trade" permission? Comment: Also if you make a GET call on the /products endpoint to you get the product ID for BTC-USD? Comment: Is this applying to any order types or specifically market orders? Here is the accepted answer: As j-petty mentioned you need to send data as request body for POST operation as described in the API documentation so this is why you get &quot;product not found&quot;. Here is working code based on what your shared: ``` var crypto = require('crypto'); var request = require('request'); async function cb_request( method, path, headers = {}, body = ''){ var apiKey = 'xxxxxx', apiSecret = 'xxxxxxx', apiPass = 'xxxxxxx'; //get unix time in seconds var timestamp = Math.floor(Date.now() / 1000); // set the request message var message = timestamp + method + path + body; console.log('######## message=' + message); //create a hexedecimal encoded SHA256 signature of the message var key = Buffer.from(apiSecret, 'base64'); var signature = crypto.createHmac('sha256', key).update(message).digest('base64'); //create the request options object var baseUrl = 'https://api-public.sandbox.pro.coinbase.com'; headers = Object.assign({},headers,{ 'content-type': 'application/json; charset=UTF-8', 'CB-ACCESS-SIGN': signature, 'CB-ACCESS-TIMESTAMP': timestamp, 'CB-ACCESS-KEY': apiKey, 'CB-ACCESS-PASSPHRASE': apiPass, 'USER-AGENT': 'request' }); // Logging the headers here to ensure they're sent properly console.log(headers); var options = { 'baseUrl': baseUrl, 'url': path, 'method': method, 'headers': headers, 'body': body }; return new Promise((resolve,reject)=&gt;{ request( options, function(err, response, body){ console.log(response.statusCode + &quot; &quot; + response.statusMessage); if (err) reject(err); resolve(JSON.parse(response.body)); }); }); } async function main() { // This queries a product by id (successfully) try { console.log('try to call product-------&gt;'); console.log( await cb_request('GET','/products/BTC-USD') ); console.log('product-------------------&gt;done'); } catch(e) { console.log(e); } var buyParams = JSON.stringify({ 'type': 'market', 'side': 'buy', 'funds': '10', 'product_id': 'BTC-USD' }); try { console.log('try to call orders-------&gt;'); var buy = await cb_request('POST','/orders', {}, buyParams); console.log(buy); console.log('orders-----------------------&gt;done'); } catch(e) { console.log(e); } } main(); ``` Here is another answer: It's worth mentioning that the sandbox API has different results than the production API. Consider the following CURLs. Sandbox API: ```❯ curl --request GET \ --url https://api-public.sandbox.exchange.coinbase.com/products/ETH-USD \ --header 'Accept: application/json' {&quot;message&quot;:&quot;NotFound&quot;}% ``` Production API: ```❯ curl --request GET \ --url https://api.exchange.coinbase.com/products/ETH-USD \ --header 'Accept: application/json' {&quot;id&quot;:&quot;ETH-USD&quot;,&quot;base_currency&quot;:&quot;ETH&quot;,&quot;quote_currency&quot;:&quot;USD&quot;,&quot;base_min_size&quot;:&quot;0.00029&quot;,&quot;base_max_size&quot;:&quot;2800&quot;,&quot;quote_increment&quot;:&quot;0.01&quot;,&quot;base_increment&quot;:&quot;0.00000001&quot;,&quot;display_name&quot;:&quot;ETH/USD&quot;,&quot;min_market_funds&quot;:&quot;1&quot;,&quot;max_market_funds&quot;:&quot;4000000&quot;,&quot;margin_enabled&quot;:false,&quot;fx_stablecoin&quot;:false,&quot;max_slippage_percentage&quot;:&quot;0.02000000&quot;,&quot;post_only&quot;:false,&quot;limit_only&quot;:false,&quot;cancel_only&quot;:false,&quot;trading_disabled&quot;:false,&quot;status&quot;:&quot;online&quot;,&quot;status_message&quot;:&quot;&quot;,&quot;auction_mode&quot;:false}% ``` You'll notice that the paths are identical but you get different results so keep that in mind. For testing purposes BTC-USD can be used. Here is another answer: You need to send a POST request to the ```/orders``` endpoint and include the body in the request payload. There are some example answers in this question. ```var options = { baseUrl: baseUrl, url: path, method: method, headers: headers json: true, body: body } request.post(options, function(err, response, body){ if (err) reject(err); resolve(JSON.parse(response.body)); }); ``` Comment for this answer: Thanks for your answer. I've tried sending it in the body and parsing it beforehand etc. but I'm getting an `invalid signature` response. Comment for this answer: Have you tried using `JSON.stringify()` on the body object when generating the signature as shown in the [documentation](https://docs.pro.coinbase.com/?javascript#signing-a-message)? Reason being if this is the operation they're using when validating the payload matches your signature, you'll need to do the same thing. The difference between a ' and a " for example will result in an incorrect signature.
Title: Difference between Firebase instance and DatabaseReference Tags: android;firebase;firebase-realtime-database Question: I'm using firebase as back end for my application. First I was using Firebase instance to save object to firbase database which worked perfectly fine but I had to change the implementation to get key from object saved for my further implementation. but after changing implementation it discard some of properties when saving. Following are the codes and screenshots of both implementations. Implementation 1. ``` Firebase ref = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_new_advertisement); ref = new Firebase("https://xxxxxxxxxxxx.firebaseio.com/"); } addAdvertisement.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Mobile mobile = new Mobile(lclManu, lclMdl); MobileAdd mobileAdd = new MobileAdd(); mobileAdd.setMobile(mobile); mobileAdd.setPrice(lclPrice); mobileAdd.setdescription(lclDes); mobileAdd.setDate(date); User publishere = new User(); Log.d("UUID", mAuth.getCurrentUser().getUid()); publishere.setUUID(mAuth.getCurrentUser().getUid()); ref.child("Advertisements").push().setValue(mobileAdd); } ``` Implementation 2. ``` DatabaseReference ref = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_new_advertisement); ref = FirebaseDatabase.getInstance().getReference(); addAdvertisement.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Mobile mobile = new Mobile(lclManu, lclMdl); MobileAdd mobileAdd = new MobileAdd(); mobileAdd.setMobile(mobile); mobileAdd.setPrice(lclPrice); mobileAdd.setdescription(lclDes); mobileAdd.setDate(date); User publishere = new User(); mobileAdd.setPublisher(publishere); DatabaseReference dbRef = ref.child("Advertisements").push(); dbRef.setValue(mobileAdd); } } }); ``` Following is the screenshot with the implementation's result. Highlighted properties are missing in second implementation. Why when I save with ```DatabaseReference``` I'm missing these properties and with ```Firebase``` reference I can save obejects without any issues? Is there a special scenarios we should use these two methods? Why should we choose one method over another. How can I overcome this issue in the second implementation? Update. ```public class MobileAdd extends Add { private Offer offers; private Mobile mobile; private User publisher; private List<String&gt; imagepaths; public MobileAdd() { } public MobileAdd(String description, double price, Date date) { super(description, price, date); } public MobileAdd(String description, double price, Date date,Offer offers, Mobile mobile, User publisher) { super(description, price, date); this.offers = offers; this.mobile = mobile; this.publisher = publisher; } public Offer getOffers() { return offers; } public void setOffers(Offer offers) { this.offers = offers; } public Mobile getMobile() { return mobile; } public void setMobile(Mobile mobile) { this.mobile = mobile; } public User getPublisher() { return publisher; } public void setPublisher(User publisher) { this.publisher = publisher; } public List<String&gt; getImagepaths() { return imagepaths; } public void setImagepaths(List<String&gt; imagepaths) { this.imagepaths = imagepaths; } } ``` Class Add. ```public class Add { private String key; private String description; private double price; private Date date; protected Add() { } public Add(String description, double price, Date date) { this.description = description; this.price = price; this.date = date; } public String getdescription() { return description; } public void setdescription(String description) { this.description = description; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } } ``` Class Mobile ``` public class Mobile{ private String manufacturer; private String model; public Mobile() { } public Mobile(String manufacturer, String model) { this.manufacturer = manufacturer; this.model = model; } protected Mobile(Parcel in) { manufacturer = in.readString(); model = in.readString(); } public String getManufacturer() { return manufacturer; } public void setManufacturer(String manufacturer) { this.manufacturer = manufacturer; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } } ``` Comment: Post the code for your `MobileAdd` and `Mobile` classes. _Implementation1_ uses the Firebase Legacy SDK, which uses Jackson to serialize/deserialize POJOs. _Implementation2_ uses the new SDK, which does not use Jackson. The supported annotations and accepted POJO forms are different between the two SDKs. Comment: @qbix added classes Here is the accepted answer: As I mentioned in my comment, Implementation1 uses the Firebase Legacy SDK, which uses Jackson to serialize/deserialize POJOs. Implementation2 uses the new SDK, which does not use Jackson. The supported annotations and accepted POJO forms are different between the two SDKs. The ```description``` field is not written by Implementation2 because of a capitalization error. The getter/setter methods should be ```getDescription()``` and ```setDescription()``` with capital 'D'. Also, ```Date``` is not a simple POJO and will not be serialized by the new SDK. One option is to use Date.getTime() and store the date as a long.
Title: How to set the message ID and time stamp for incoming messages Tags: android;sms Question: I am developing an app that receive sms and I want to know how to set message ID and timestamp for incoming messages. Here is another answer: Are you sure that you want to 'set' the message ID and timestamp, do you mean that you want to read them as they are received by the phone? I doubt that you will be able to set these values manually Comment for this answer: actually i want to keep track of massages that i have already read ,so i waz thinking of massage id and time stamp Here is another answer: I'm guessing you're using an SmsMessage object. This object does not allow you to set any ID or timestamp, but you can retrieve the timestamp with getTimeStampMillis(), and there doesn't seem be any ID's in this class. If you want to be able to have and manipulate these values you probably need to write your own Sms-class. Comment for this answer: @MkhululiKhustaricoBuzwa You don't need to set any values for that. Just retrieve. Or am I misunderstanding something? getStatusOnIcc() can give you read/unread status. If you need to have a list of read messages, then maybe create a list of these objects/some id you've made Comment for this answer: actualy i want to keep track of massages that have being already read thats why i was thinikng of massage id and time stamp
Title: Problems encapsulating Dialog components in Tapestry 5.3 Tags: java;jquery;tapestry Question: I'm trying to build a Tapestry component called CrudEntityField, based on ```TextField``` (core), ```DialogLink``` (tapestry5-jquery) and ```Dialog``` (tapestry5-jquery) components, along with ```Zone``` for AJAX updates. My use case is quite simple: ``` CrudEntityField will render as a TextField. If you know the entity id, you can enter it there directly. If you don't know the id, you can click on the ```DialogLink``` button (SELECT), which pops up a Dialog window. The Dialog lists all available entities in table format, and lets us filter by some criteria. Once the user selects the entity, the text field is automatically refreshed with the related id (e.g '6'). Also, a related name/description is printed for clarity (e.g. '[Gipuzkoa]'). Snapshots: CrudEntityField, Pop-up Dialog ``` Ideally, all this logic can be encapsulated in a single Tapestry component. But here come the issues: The dialog (```<div t:type="jquery/dialog" t:clientId="dialogIdXXX"&gt;```, see below) includes a search form, and is itself embedded within another form (CRUD form). As nested forms are not allowed, I could try to un-nest it. However, this approach will fail, as I get a runtime exception when the inner form is rendering, before I have the opportunity to move it. ```@AfterRender public void afterRender(MarkupWriter writer) { Element body = writer.getDocument().find("html/body"); writer.getDocument().getElementById("dialogIdXXX").moveToBottom(body); } ``` I tried other approaches, such as ```@HeartbeatDeferred```, ```RenderCommand```, etc. but I found no way to render the dialog out of the Form. Component template: ```<t:content&gt; <!-- A) Entity Field --&gt; <t:zone t:id="entityZone" id="zoneIdXXX"&gt; <div class="inputElement"&gt; <t:label for="textField"/&gt; <input t:id="textField"/&gt; [<t:body/&gt;] <t:jquery.dialoglink t:dialog="dialogIdXXX" class="dialogLink"&gt;SELECT</t:jquery.dialoglink&gt; </div&gt; </t:zone&gt; <!-- B) Entity Dialog --&gt; <div t:type="jquery/dialog" t:clientId="dialogIdXXX" params="params" &gt; <table t:id="xa2grid" t:entity="inherit:entity" t:add="actions"&gt; <p:actionsCell&gt; <a t:type="EventLink" t:event="SELECT" t:zone="zoneIdXXX" t:context="entity.id" href="#"&gt;SELECT</a&gt; </p:actionsCell&gt; </table&gt; </div&gt; </t:content&gt; ``` Ok, so I can split the component in two pieces: ```EntityField``` (form input field) and ```EntityDialog``` (placed out of the Form, in the page template). Not ellegant, though, since this approach breaks the abstraction. But this approach won't work either. The zone event is now triggered by the ```EntityDialog``` component, and must be handled by itself or one of its containers. But the zone is defined in ```EntityField```, which is now a sibling! (I can paste more code if not clear). Here is the accepted answer: As you've seen, you can't render a form inside a form so you will need to delay the rendering of the dialog until after the form has rendered. So, instead of rendering the dialog inside your component, use an environmental bean. The environmental will store the config for all dialogs on the page http://tapestry.apache.org/environmental-services.html Include a block at the end of every page which looks up the config from the environment and renders all of the Dialogs. Hopefully you are using a layout so this will be in one place. eg: Layout.java ```@Inject Environment environment; @Property private DialogConfigs dialogConfigs; @Property private DialogConfig dialogConfig; void beforeRender() { dialogConfigs = new DialogConfigsImpl(); environment.push(DialogConfigs.class, dialogConfigs); } void afterRender() { environment.pop(DialogConfigs.class); } ``` Layout.tml ```<html&gt; <body&gt; <t:body/&gt; <t:loop source="dialogConfigs.values" value="dialogConfig"&gt; <div t:type="jquery/dialog" foo="dialogConfig.foo" bar="dialogConfig.bar"&gt; </t:loop&gt; </body&gt; </html&gt; ``` CrudEntityField.java ```@Environmental private DialogConfigs dialogConfigs; @Parameter private String foo; @Parameter private String bar; void beforeRender() { dialogConfigs.add(new DialogConfig(foo, bar)); } ```
Title: Keep first occurrence in duplicated values in dictionary Tags: python;python-3.x;dictionary;iteritems Question: Having duplicated values in dictionary such as the following: ```dict_numbers={'one':['one', 'first','uno', 'une'], 'zero':['zero','nothing','cero'], 'first':['one', 'first','uno', 'une'], 'dos':['two','second','dos', 'segundo','deux'], 'three':['three','tres','third','tercero'], 'second':['two','second','dos','segundo','deux'], 'forth':['four','forth', 'cuatro','cuarto'], 'two': ['two','second','dos', 'segundo','deux'], 'segundo':['two','second','dos', 'segundo','deux']} ``` I'd like to get the first occurrences of keys that have duplicated values. Notice, that the dictionary does not have duplicated keys, but duplicated values. In this example, I would get a list keeping the first occurrence of duplicated values: ```list_numbers_no_duplicates=['one','zero','dos','three','forth'] ``` ```first``` key is removed because ```one``` has already the same values. ```second``` key is removed because ```dos``` has already the same values. ```two``` key is removed because ```dos``` has already the same values. How to keep track of the several duplicates in the values of keys? Thanks in advance Comment: `dos` is the first key with the value `['two','second','dos', 'segundo','deux']`, `two` and `segundo` keys are also in the dictionary, but they have the same value `['two','second','dos', 'segundo','deux']`, they appear after `dos`, so they are not part of the final_list. Comment: can you explain `'dos'` and `'forth'` in the expected output? Here is the accepted answer: Hopefully I understood correctly your goal. The following uses ```chain``` from the ever-so-useful itertools package. ``` &gt;&gt;&gt; {key: vals for i, (key, vals) in enumerate(dict_numbers.items()) if key not in chain(*list(dict_numbers.values())[:i])} {'one': ['one', 'first', 'uno', 'une'], 'zero': ['zero', 'nothing', 'cero'], 'dos': ['two', 'second', 'dos', 'segundo', 'deux'], 'three': ['three', 'tres', 'third', 'tercero'], 'forth': ['four', 'forth', 'cuatro', 'cuarto']} ``` Essentially, this works by recreating the original dictionary for entries where there are no occurrence where the key is found in any of the preceding lists (hence the enumerate and slicing shenanigans).
Title: maxBy((Map.Entry<K, V>) -> R): Map.Entry<K, V>?' is deprecated. Use maxByOrNull instead Tags: android;kotlin Question: I'm trying to use maxBy in kotlin but I get a deprecated warning to replace it with maxByOrNull. ```val max = response.maxBy { it.value.size } ``` ``` maxBy((Map.Entry<K, V&gt;) -&gt; R): Map.Entry<K, V&gt;?' is deprecated. Use maxByOrNull instead. ``` The autofix in android studio does it like below ```val max = maxByOrNull({ it.value.size }) ``` But this doesn't compile with error ``` Unresolved reference: maxByOrNull ``` What is the proper implementation as ```response.maxByOrNull { it.value.size }``` also doesn't work Comment: You need to call it on ``response``, same as your original ``maxBy`` version. If it's still not working (highlighted in red) put the text cursor on it, hit alt+enter and pick the import option Comment: try this https://stackoverflow.com/questions/31712046/kotlin-unresolved-reference-in-intellij
Title: Overwriting menu css with javascript in C# Tags: c#;javascript;asp.net;css Question: I'm using C# to create a website for motorists to pay their parking fee with their smartphone. I'm having some issues with my menu however. I want the menu to be white with black text and the current page needs to be blue with white text, but when I try to do so with css I'm getting something completely different: the current page menu item is still white with black text and behind it you see a little bit of blue. Does someone know how I can resolve this one? My menu items are in the master page: ```<div id="menu"&gt; <ul&gt; <li id="accountmenu"&gt;<a href="PersoonlijkeGegevens.aspx"&gt;Mijn account</a&gt;</li&gt; <li id="parkeermenu"&gt;<a href="Parkeer.aspx"&gt;Parkeer</a&gt;</li&gt; <li id="saldomenu"&gt;<a href="SaldoGegevens.aspx"&gt;Mijn saldo</a&gt;</li&gt; </ul&gt; </div&gt; ``` I add the current page class with JavaScript in each page: ```<script type="text/javascript"&gt; $(document).ready(function () { $("#saldomenu").addClass("currentpage"); }); </script&gt; ``` And finally I set the css in a css file of the master page ```#menu ul li a:link, a:visited { background:#fff; display:inline-block; padding:5px 10px 6px; color:#000; font-size:16px; text-decoration:none; -moz-border-radius:6px; -webkit-border-radius:6px; -moz-box-shadow:0 1px 3px rgba(0,0,0,0.6); -webkit-box-shadow:0 1px 3px rgba(0,0,0,0.6); border-bottom:1px solid rgba(0,0,0,0.25); position:relative; cursor:pointer; } .currentpage { background:#172c7d; color:#fff; } ``` I really don't know what I'm doing wrong here and I've been searching for 2 weeks now for the correct answer. Can please someone help me out on this one. Comment: Try using **http://docs.jquery.com/Plugins/livequery** Here is the accepted answer: You need to make the currentpage class more specific. Your currentpage class was only affecting the li element and not the link. ```#menu ul li.currentpage a:link, #menu ul li.currentpage a:visited { background:#172c7d; color:#fff; } ```
Title: Android - AddContentView defined in XML Tags: java;android Question: AdMob documentation to integrate it on Android instructs to create the following XML, if we want to create the view via XML: ```<?xml version="1.0" encoding="utf-8"?&gt; <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:ads="http://schemas.android.com/apk/res-auto" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"&gt; <com.google.android.gms.ads.AdView android:id="@+id/adView" android:layout_width="wrap_content" android:layout_height="wrap_content" ads:adUnitId="MY_AD_UNIT_ID" ads:adSize="BANNER"/&gt; </LinearLayout&gt; ``` And set it as content view to Activity: ```public class BannerExample extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Look up the AdView as a resource and load a request. AdView adView = (AdView) this.findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder().build(); adView.loadAd(adRequest); } } ``` But in my case (I use cocos2d-x 3) I have already a subclass of Activity and I just need to add that view to my existing content, not set content view as it is done in the code above. How I can addContentView the view that is defined in XML? Comment: could you please add code for your existing content view(xml file) and where you need to add this content in the existing content? Add some more explanation. Here is another answer: When you call. ```setContentView(R.layout.main); ``` in onCreate it automatically inflates the view for you so you can start assigning your views from the xml to your own variables like such: ```AdView adView = (AdView) findViewById(R.id.adView); ``` Make sure that the xml layout you defined at the top is the same that is being passed in setContentView(). In this case R.layout.main should contain a View with id adView of AdView type. In other words, R.layout.main should be: ```<?xml version="1.0" encoding="utf-8"?&gt; <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:ads="http://schemas.android.com/apk/res-auto" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"&gt; <com.google.android.gms.ads.AdView android:id="@+id/adView" android:layout_width="wrap_content" android:layout_height="wrap_content" ads:adUnitId="MY_AD_UNIT_ID" ads:adSize="BANNER"/&gt; </LinearLayout&gt; ``` If what you want however, is inflate and use main layout and add the AdView, you must inflate the view yourself and add it to some element in main layout. Like such: ```RelativeLayout item = (RelativeLayout)findViewById(R.id.item); View child = getLayoutInflater().inflate(R.layout.child, null); item.addView(child); ``` References: How to inflate one view with a layout Comment for this answer: am I right that `setContentView` adds the View to the Activity to be seen when activity starts? Comment for this answer: It adds the view if you are explicitly telling the activity to inflate the corresponding layout. Here is another answer: You can simply add ```<com.google.android.gms.ads.AdView android:id="@+id/adView" android:layout_width="wrap_content" android:layout_height="wrap_content" ads:adUnitId="MY_AD_UNIT_ID" ads:adSize="BANNER"/&gt; ``` to your existing XML layout file.
Title: 3by3 matrix multiplication Tags: c++;class;matrix;multiplication Question: I have a 3by3 matrix class that isn't working properly. When I multiply using a third instance to store the answer and multiply two others instances it works properly. But when I try to do *= it gives me weird numbers. Here's the regular * and *= functions: ``` threeby3matrix operator*(threeby3matrix&amp; multiplier) { threeby3matrix m1; m1[0] = matrix[0] * multiplier[0] + matrix[1] * multiplier[3] + matrix[2] * multiplier[6]; m1[1] = matrix[3] * multiplier[1] + matrix[4] * multiplier[4] + matrix[5] * multiplier[7]; m1[2] = matrix[6] * multiplier[2] + matrix[7] * multiplier[5] + matrix[8] * multiplier[8]; m1[3] = matrix[0] * multiplier[0] + matrix[1] * multiplier[3] + matrix[2] * multiplier[6]; m1[4] = matrix[3] * multiplier[1] + matrix[4] * multiplier[4] + matrix[5] * multiplier[7]; m1[5] = matrix[6] * multiplier[2] + matrix[7] * multiplier[5] + matrix[8] * multiplier[8]; m1[6] = matrix[0] * multiplier[0] + matrix[1] * multiplier[3] + matrix[2] * multiplier[6]; m1[7] = matrix[3] * multiplier[1] + matrix[4] * multiplier[4] + matrix[5] * multiplier[7]; m1[8] = matrix[6] * multiplier[2] + matrix[7] * multiplier[5] + matrix[8] * multiplier[8]; return m1; } threeby3matrix&amp; operator*=(threeby3matrix&amp; multiplier) { matrix[0] = matrix[0] * multiplier[0] + matrix[1] * multiplier[3] + matrix[2] * multiplier[6]; matrix[1] = matrix[3] * multiplier[1] + matrix[4] * multiplier[4] + matrix[5] * multiplier[7]; matrix[2] = matrix[6] * multiplier[2] + matrix[7] * multiplier[5] + matrix[8] * multiplier[8]; matrix[3] = matrix[0] * multiplier[0] + matrix[1] * multiplier[3] + matrix[2] * multiplier[6]; matrix[4] = matrix[3] * multiplier[1] + matrix[4] * multiplier[4] + matrix[5] * multiplier[7]; matrix[5] = matrix[6] * multiplier[2] + matrix[7] * multiplier[5] + matrix[8] * multiplier[8]; matrix[6] = matrix[0] * multiplier[0] + matrix[1] * multiplier[3] + matrix[2] * multiplier[6]; matrix[7] = matrix[3] * multiplier[1] + matrix[4] * multiplier[4] + matrix[5] * multiplier[7]; matrix[8] = matrix[6] * multiplier[2] + matrix[7] * multiplier[5] + matrix[8] * multiplier[8]; return *this; } ``` For some reason I get [18][18][18][108][228][18][108][708][1638] when they all should be 18. I tried messing around with brackets, but nothing seems to work. Comment: @SamVarshavchik - I guess they want to get the typing up to scratch Comment: Did you yet learn anything about "for" loops, yet? Comment: also I forgot to mention, I used a single dimensional dynamic array to store the 2 dimensional array Here is another answer: you are modifying matrix as you use it for calculation. try something like this: ```threeby3matrix&amp; operator*=(threeby3matrix&amp; multiplier) { st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16swap(*this, operator*(multiplier)); return *this; } ``` Comment for this answer: oh wow, seems like a stupid mistake now that I see it, thanks. And we learned loops, it just didn't seem very practical since it would take multiple loops and variables, so I just typed it out
Title: ASP.NET web api returning only first object in each object in a array Tags: c#;asp.net-mvc;entity-framework;asp.net-core;asp.net-web-api Question: startup.cs ``` services.AddMvc().AddJsonOptions(options =&gt; { options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1); ``` below is the sample response json returned by web api application when deployed to production. In localhost Iam getting data for "lastHourData","lastHourBeforeData" but not in production. ``` [{ "currentData": { "id": "213123123esdwq23d", "payload": [ { "key": "sdfsdf", "value": "T" } ] }, "lastHourData": null, "lastHourBeforeData": null }, { "currentData": { "id": "sdfdsf", "payload": [ { "key": "gf", "value": "T" } ] }, "lastHourData": null, "lastHourBeforeData": null }] ``` below is the method, CurrentData,LastHourData and LastHourBeforeData each has 250 properities. ``` public async Task<ComepletePanel&gt; GetCompletePanelData(string id) { var queryRequest = RequstBuilder(id); var result = await queryRequest; var currentResult = result.Items.Select(Map2).FirstOrDefault(); var queryRequest2 = getlastHourDataForMasterPanelBuilder(id); var result2 = await queryRequest2; var currentResult2 = result2.Items.Select(Map2).FirstOrDefault(); var queryRequest3 = getlastBeforHourDataForMasterPanelBuilder(id); var result3 = await queryRequest3; var currentResult3 = result3.Items.Select(Map2).FirstOrDefault(); var completData = new ComepletePanel { CurrentData = currentResult, LastHourData = currentResult2, LastHourBeforeData = currentResult3 }; return completData; } ``` below is the controller method ``` public async Task<IEnumerable<ComepletePanel&gt;&gt; GetCustBoilersByCustId2(int id) { try { var recordData= await _context.table.ToListAsync(); List<ComepletePanel&gt; resultData= new List<ComepletePanel&gt;(); foreach (var b in recordData) { var CurrentResponse = await _getItem.GetCompletePanelData(b.id); resultData.Add(CurrentResponse); } return resultData; } catch (Exception ex) { _logger.LogError($"Failed to get all customers {ex}"); return null; } } ``` Comment: it's the same table. just adding different datetime conditions for both of them. in localhost it's working and in the production it's not. same database and same table used for both the environments Comment: If you are getting the first part of the data and not the rest and it is working in localhost then it has to do with some sort of server settings/cutoffs. I will reduce the size of the data and/or console write/If 'null' to see if anything reaches your method. Comment: Do you have data for LastHourData and LastHourBeforeData in PROD? Here is another answer: You might need to serialize your object. Please see this for your reference: https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to Comment for this answer: Is this correct JsonSerializer.Serialize(completData); ? JsonSerializer doesn't have extension menthod called Serialize Comment for this answer: Seems like you've configured the serialization options but you still need to call the serializer to serialize your object like this return JsonSerializer.Serialize(completData); Comment for this answer: Do you have these in your using statement? using System.Text.Json; using System.Text.Json.Serialization; Comment for this answer: Ok I hope that helps. Here is another answer: I think you should refactor your code to look more presentable and appealing to you like this. It might solve your problem. Instead of you writing methods like ```getLastHourDataForMasterPanelBuilder(string id)``` and ```getlastHourDataForMasterPanelBuilder(string id)```, first those names look too long and then just summarize your algorithm in one method such that you just pass a time or a logic data or time argument to it then it gets the data based on time you want. ```public async Task<IEnumerable<CompletePanel&gt;&gt; GetCompleteData(string id params string[] args) { List<QueryRequest&gt; requests = new List<QueryRequest&gt;(); foreach (string argument in args) { var queryRequest = RequestBuilder(id); var result = await queryRequest; var knownResult = result.Items.Select(Map2).FirstOrDefault(); requests.Add(knownResult); } return requests; } ``` Then in your controller instead of performing a loop you just pass the id and time argument or logical argument as string to the method.
Title: Deployment of Symfony 3.2 project to Strato Tags: php;mysql;symfony Question: I developed a Symfony project (version 3.2) with some data in a database (mysql). Development was done by using the local machine and XAMPP. Everything is ok so far. Now comes the tricky part: deployment. I read all documentation. There are two options: Upload the relevant source, migrate database and configure project by running composer scripts in prod on the server configure via composer in prod environment, upload, migrate database. (The only difference is where you run the scripts.) The problem: with Strato both options are not working: For option 1: I am not able to run the scripts on the server, I get a class not found exception even with "set SYMFONY_ENV=prod" (export command does not exist) before "php composer.phar install --no-dev --optimize-autoloader". Error: ``` PHP Fatal error: Class 'Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle' not found ``` For option 2: Stratos rdbms.strato.de database server is not accessible from other machines. Error: ``` The test of the connection fails. The scripts are not finishing. ``` I already searched here but I was not able to find anything. Does anyone know a solution? Comment: That is right, I regret it already. But more important is finding some workaround. Comment: If think you answered yourself this question. Running a symfony website on a shared hosting a NOT a good idea. Here is another answer: Are you sure you cannot execute ```export``` command? Is that some shared hosting limitation or...? If you really cannot use that command, it seems to me that one workaround could be to remove bundles that do not belong to production environment from ```AppKernel.php``` (in your app on Strato) That part of code looks like this: ```// AppKernel.php if (in_array($this-&gt;getEnvironment(), ['dev'], true)) { $bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle(); $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle(); $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle(); $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle(); } ``` Also, you will need to remove everything from ```config_dev.yml``` except: ```imports: - { resource: config.yml } ``` More about composer and symfony environment differences you can read here: How does composer know symfony environment Also, year ago I wrote a post about deploying Symfony on shared hosting, maybe it could help you some time in future :)) http://matkodjipalo.com/index.php/2016/05/19/installing-symfony-on-hostgator-shared-hosting/ Comment for this answer: Thanks for your comment! I tried everything I could. I decided to switch to a Strato V Server and now it is working.
Title: CommonCsv : IllegalArgException when during record.get when particular file is used Tags: java;apache-commons Question: I have the following: StateCountryDataLoader.java ```private Map<String, String&gt; getStateCountryMap() throws IOException { final Map<String, String&gt; stateCountryMap = new HashMap<&gt;(); try (final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(getFile (filePath)), StandardCharsets.UTF_8)); final CSVParser parser = new CSVParser(reader, CSVFormat.TDF.withHeader("STT_CDE", "CTRY_CDE") .withSkipHeaderRecord())) { for(CSVRecord r : parser) { stateCountryMap.put(r.get("STT_CDE"), getValueOrDefault(r.get("CTRY_CDE")));//get or default is an isNotBlank check. if true, return empty string, otherwise return the value provided to it } } return stateCountryMap; } private File getFile(String path) throws IOException { return new ClassPathResource(path).getFile(); } ``` And this works fine when the file used is the following: STT.txt ```STT_CDE CTRY_CDE AA USA AB CAN AE USA AK USA AL USA AP USA AR USA AZ USA BC CAN CA USA CO USA CT USA DC USA DE USA FL USA FR GA USA GU USA HI USA IA USA ID USA IL USA IN USA KS USA KY USA LA USA MA USA MB CAN MD USA ME USA MI USA MN USA MO USA MS USA MT USA NB CAN NC USA ND USA NE USA NH USA NJ USA NL CAN NM USA NS CAN NT CAN NU CAN NV USA NY USA OH USA OK USA ON CAN OR USA PA USA PE CAN PR USA QC CAN RI USA SC USA SD USA SK CAN TN USA TX USA UT USA VA USA VI USA VT USA WA USA WI USA WV USA WY USA YT CAN ``` I have no issues when this is the case; the record.get methods function as expeted, even for the line that includes a blank CTRY_CDE value. But when i use the following file: sample.txt ```STT_CDE CTRY_CDE AA USA AB CAN FR ``` I get the following: ```Caused by: java.lang.IllegalArgumentException: Index for header 'CTRY_CDE' is 1 but CSVRecord only has 1 values! at org.apache.commons.csv.CSVRecord.get(CSVRecord.java:108) at com.lmig.ci.fnol.bo.assign.dataload.StateValidValueLoad.getStateCountryMap(StateValidValueLoad.java:83) etc... ``` Worth nothing, that should I remove the FR line, then everything runs as expected, and when i open the file in Intellij after the test has ran, the tab after FR has disappeared, so im not sure if its an issue with how im reading in the file or not, but I don't see what the issue is, given the same line is present in the full file, and any unit tests or calls to this method don't throw the same exception. I'm quite new to CommonCsv so I'm not sure if whats occurring is due to inexperience(maybe there is a setting that I've failed to check that would avoid this issue), or if something else is at play here regarding how the file is read in, but I can't get to the bottom of this Comment: Do the file that fails to parse ends with a linefeed? If it doesn't, I'd try adding one, maybe the parser would handle running into a `\n` better than in an EOF when it expects a value. Comment: Glad to see that fixed it ! Comment: @Aaron unsure, will check this out. If it adds anything, I've noticed in the full file the tab is preserved but every time i move rows in the smaller sample, the tab is removed Comment: @Aaron, so yeah, Intellij making life difficult. I didn't realise that on save it would strip out trailing whitespace and tabs, changing this setting fixed the issue
Title: Calling sqlite3_close for a static sqlite3* handle Tags: objective-c;sqlite Question: I want to provide access an sqlite database in Objective C. I don't want the caller to bother about the DB itself and so I intend to do something like this in my DataStore.m: ```#import "DataStore.h" #import <sqlite3.h&gt; static sqlite3 *database = nil; @implementation DataStore + (void) initialize { if(self != [DataStore class]) return; ... ... sqlite3_open(databasePath, &amp;database); } + (NSArray *) readWith:foo:bar { ... } + (bool) writeWith:foo:bar { .. } ``` Now the problem with the whole thing is: I will never get to call sqlite3_close throughout the entire application. It certainly does not look elegant. How could I improve this? One way would be to open and close my database on each access, and get rid of the static DB handle. How costly would it be? PS: I don't have a strong OO background and so if my idea is bad, I don't mind changing it altogether. Here is the accepted answer: You can use a "destructor" to automatically close the database on quit ```__attribute__((destructor)) static void close_db (void) { sqlite3_close(database); } ```
Title: How to use Deck Panel of Ui Services Tags: google-apps-script Question: After reading the GAS documentation related to Deck Panel of the Ui Services, I understand that once an element is added to a Deck panel, it becomes invisible, and if the element is removed from this, it will be visible again. I wrote some testing code, but I can't get to make a panel visible when I remove it from the Deck Panel. Any insights? Here is the code: ```function doGet() { var app = UiApp.createApplication(); var globalPan = app.createAbsolutePanel(); app.add(globalPan); var deckPanel = app.createDeckPanel().setId('deck').setSize(300, 300).setTitle('DeckPanel').setAnimationEnabled(true); globalPan.add(deckPanel); globalPan.add(app.createHorizontalPanel().add(app.createLabel('Element to add to DeckPanel')).setId('visiblePan')); var hidden = app.createHidden('hEl', 'visible').setId('hEl').setName('hEl'); app.add(hidden); app.add(app.createButton('Add to DeckPanel').setId('button').addClickHandler(app.createServerHandler('handlerFunction').addCallbackElement(hidden))); return app; } function handlerFunction(eventInfo) { var app = UiApp.getActiveApplication(); var parameter = eventInfo.parameter; var state = parameter.hEl; if (state == 'visible'){ app.getElementById('deck').add(app.getElementById('visiblePan')); app.getElementById("button").setText("Remove from DeckPanel"); app.getElementById('hEl').setValue('hidden'); }; else{ app.getElementById('deck').remove(0); app.getElementById("button").setText("Add to DeckPanel"); app.getElementById('hEl').setValue('visible'); }; return app; } ```
Title: How do I fix this branching / story making on python? Tags: python;input Question: ```sceneDict = {} sceneDict["Beggining"] = { "Branching" : False "SceneText" : "Walking towards the enterance to the hollowed out tree you \ notice some large skulls on the sides of the dirt path along with other \ large sized bones which don't look like anything you've ever seen before.", "NextScene" : "Enterance" } sceneDict["Enterance" = { "Branching": True, "SceneText" : "You come up to the cave enterance and upon inspecting it you notice some \ liquid dripping from the roof of the enterance, you catch a small amount in your hand.. It's \ red and has the consistency of blood. All of a sudden a thundering roar is heard behind you and a massive \ troll has appeared!", "Choices" : [ {"ChoiceNumber" : "1. ", "ChoiceText" : "Run into the cave to escape the troll", "NextScene" : "Cave"}, {"ChoiceNumber" : "2. ", "ChoiceText" : "Attempt to escape between the trolls legs", "NextScene" : "Chase"}, {"ChoiceNumber" : "3. ", "ChoiceText" : "Pull out your sword in an attempt to combat the troll" "NextScene" : "Combat"} ] } sceneDict["Combat"] = { "Branching": False, "SceneText" : "As you reach back to grab your sword from your back the troll puts its arm out to the \ side and in one sweeping motion smashes you into a tree, unfortunately ending your life.", "NextScene" : "Afterlife" } sceneDict["Afterlife"] = { "Branching": True, "SceneText" : "You feel sunlight on your face and as you open your eyes there is two pathways infront of you \ as well as a sign over top of both'that's strange, I should probably be dead' however, above the arrow signs \ there is a sign that reads 'You messed up, it happens but try again' the paths both lead to the two other choices\ you had before you took the worst of the three choices.", "Choices" : [ {"ChoiceNumber" : "1. ", "ChoiceText" : "Run into the cave to escape the troll", "NextScene" : "Cave"}, {"ChoiceNumber" : "2. ", "ChoiceText" : "Attempt to escape between the trolls legs", "NextScene" : "Chase"} ] } sceneDict["Chase"] = { "Branching": False, "SceneText" : "You slide on your knees between the trolls legs as it's enormous fists come crashing down behind \ you, you get back up and start running down the hill towards your village hearing its thunderous steps close \ behind. The people of your town hear the ruckus and go towards the gate to see you being chased and they all \ start cheering you to keep going!", "NextScene" : "Decisions" } sceneDict["Decisions"] = { "Branching": True, "SceneText" : "You are about 100 meters out from your village but you remember that there is a river to the \ right of the gate you could most likely lead the troll over there and have it crash through the bridge \ into the water, or you could chance the guards speed of closing the gate to block the troll.", "Choices" : [ {"ChoiceNumber" : "1. ", "ChoiceText" : "Continue towards the village", "NextScene" : "Village"}, {"ChoiceNumber" : "2. ", "ChoiceText" : "Run towards the water", "NextScene" : "Bridge"} ] } sceneDict["Village"] = { "Branching": False, "SceneText" : "You run towards the village as fast as you possibly can the troll clearling gaining on you \ you call out for the guards to start closing the gate as you are running, the gate begins to close as you \ close in on it, you quickly slide through the last remaining opening as the gate slams shut followed by a loud \ 'BANG!' as the troll smashes his head into the gate. The village cheers as you made it back alive!", } sceneDict["Bridge"] = { "Branching": False, "SceneText" : "As the villagers are cheering they start questioning what are you doing?! You change your path \ and go for the bridge. You start running over the wooden bridge as it is creeking and after a few seconds \ really shaking. Suddenly you hear a snap as the bottom gives out and you grab onto the side of the bridge. \ The bridge falls away at your feet only leaving the sides to hold onto as you hear a loud splash and see \ the troll floating away into the distance.", } sceneDict["Cave"] = { "Branching": True, "SceneText" : "You run forward into the cave, and slip on some of the blood into the depths of it. Behind you \ the troll is coming, however you hear the sound of splashing further into the cave.", "Choices" : [ {"ChoiceNumber" : "1. ", "ChoiceText" : "Run deeper into the cave towards the splashing", "NextScene" : "Jump"}, {"ChoiceNumber" : "2. ", "ChoiceText" : "Stand your ground to the troll", "NextScene" : "Learn"} ] } sceneDict["Jump"] = { "Branching": False, "SceneText" : "You run towards the end of a cliff which has a small waterfall going over the edge of it \ you hear the troll gaining on you, but the drop is managable, you take a step back and leap for glory! You \ land with a splash and the troll sits at the top roaring in anger at your escape, you made it.. now to find \ your way home..", } sceneDict["Learn"] = { "Branching": False, "SceneText" : "You reach back to grab your sword from your back but in one swift movement the troll smashes you \ into the ground turning you into mince meat, very unfortunate.. You hear a shimmering sound and you appear back \ in on the path towards the cave again as if a God has given you a second chance or something.", "NextScene" : "Enterance" } currentScene = "Beggining" while currentScene != "": sceneData = sceneDict[currentScene] print(sceneData["SceneText"]) print() if sceneData["Branching']: for choice in sceneData["Choices"]: print(choice["ChoiceNumber"] + choice["ChoiceText"]) print() answer = input("&gt; ") print() answer = int(answer) - 1 if answer <= len(sceneData["Choices"]) currentScene = sceneData["Choices"][answer]["NextScene"] else: currentScene = sceneData ["NextScene"] window.exitonclick() ``` I have this code, and it should work it looks flawless, however I am getting a syntax error every time I run it but it does not point me to the error? Where is the error and how do I fix it if you could help that'd be great thanks! Here is another answer: In your while loop, you have used the incorrect closing quote in your if statement: ```if sceneData["Branching'] ``` You should use either: ```if sceneData["Branching"] ``` or: ```if sceneData['Branching'] ``` Also, in order to have text on multiple lines you should do the following: ```sceneDict["Beggining"] = { "Branching" : False "SceneText" : "Walking towards the enterance to the hollowed out tree you \n" "notice some large skulls on the sides of the dirt path along with other \n" "large sized bones which don't look like anything you've ever seen before.", "NextScene" : "Enterance" } ``` Comment for this answer: Hey, thanks for responding I fixed that and also noticed earlier I had `sceneDict["Enterance" = {` so I fixed that to `sceneDict["Enterance"] = {` but after fixing those two things I still receive a syntax error and it doesn't point to it. Comment for this answer: So I indented everything that you showed above, and did the adjustments to the splitting of lines.. but I still get syntax errors without them being pointed to by Python, so I really have no idea as to where the code is faulted. Comment for this answer: Added the commas in the right places for the choices and dictionaries, aswell as the colon after choices but now I am getting a syntax error near the top in the first set on choices on the 3rd one { bracet Comment for this answer: Make sure that your key value pairs in your dictionaries are all separated by commas and the last thing I can see is you are missing a colon after the following if statement: if answer <= len(sceneData["Choices"])
Title: Google Sheets: VLOOKUP formula for a multi line cells range Tags: google-sheets;formulas;google-sheets-query;google-sheets-arrayformula;vlookup Question: I have here a sample project, where columns ```A``` to ```C``` are in ```FORM RESPONSES``` TAB/SHEET and columns ```D``` and ```E``` are in ```RECORDS``` TAB/SHEET. In the ```RECORDS``` I have a list of names, in alphabetical order, and a column for BATCHES(```E9```). What I wish to have as an output is to AUTOMATICALLY bring/distribute the batches from ```RESPONSES!B4:B``` to the respective attendees in ```RECORD``` TAB (```E10:E```). NOTE: The names are already available in the Google Form(Checkbox type), so the list of names in ```RECORD``` TAB are just the same as in the Google Form. But the problem is, there are responses in ```C4:C``` that has multiple names in a single cell, and I don't know what to do anymore. hehe. I have already tried the ```INDEX``` and ```MATCH``` formulas based on how I understood it as a total beginner in Google Sheet, but it only works on the first name. I hope that someone could help me achieve the output that I wanted to achieve. Thank you so much and may God bless everyone! Here's the screenshot of my sample project: Comment: Welcome. Please remember that as per [site guidelines](https://webapps.stackexchange.com/help/someone-answers) when an answer addresses your question, you should [accept](https://webapps.stackexchange.com/help/accepted-answer) it and even [upvote](https://webapps.stackexchange.com/help/why-vote) it so others can benefit as well. Comment: Hi! Thank you for guiding me, I have accepted your answer, and now I am trying to figure out how to upvote it. Your answer really helped me a lot. Thank you so much! Comment: *"I am trying to figure out how to upvote it"*. Just press the up-arrow once. Although the message will say you don't have enough reputation, it will show in the future when you do. Here is the accepted answer: Please try the following ```=INDEX(IFERROR(VLOOKUP(D8:D, QUERY(SPLIT(FLATTEN({Respos!B3:B&amp;&quot;@&quot;&amp;SPLIT(Respos!C3:C,CHAR(10))}),&quot;@&quot;), &quot;select Col2, Col1 where Col2 <&gt;'' &quot;),2,0))) ``` (please -as always- adjust formula according to your ranges and locale) Additional info (following OP's comment) ```@``` is just a symbol we use as the identifier for the ```SPLIT``` function. It could be anything like ♞ or , NOT present in our text. ```Col1``` and ```Col2``` are the column numbers in our query. Be careful because they are case sensitive. That means ```col``` OR ```COL``` will NOT work. Functions used: ```INDEX``` ```IFERROR``` ```QUERY``` ```VLOOKUP``` ```SPLIT``` ```FLATTEN``` ```CHAR``` Comment for this answer: Wow! This is amazing! It worked 100%. Thank you soooo much! May I ask, what are the two "@" and "col1" and "col2" for? and the "2" before the "0"?
Title: Wierd Behavior Appending to list inside function Tags: python;list;append Question: ```def test(list2): list2.append(1) print len(list2) print len(LIST1) LIST1 = [1] while len(LIST1) < 9: test(LIST1) ``` Please explain why 'LIST1' is increasing in size if I'm appending to 'list2', isn't variables inside functions local? And above all, how can I circumvent this? The same happens if I make a new variable: ```def test(arg_list): list2 = arg_list list2.append(1) print len(list2) print len(LIST1) LIST1 = [1] while len(LIST1) < 9: test(LIST1) ``` Comment: In your first example, `my_list` is not defined, and neither `list1` nor `list2` are modified, and `LIST2` is not defined. Comment: Sorry, bad formatting. Fixed. Here is the accepted answer: No, parameters passed to a function are by reference, and in the second example the local variable is yet another reference to the same list. Parameter passing and variable assignment do not create copies of the list, only references to the same object. In other words: anything you do to an object being referenced inside the function (say, a list) will be reflected on the object itself once the function exits - the function parameter and the object "outside" the function are one and the same. How can you circumvent this? well, if it fits your usage scenario you can simply copy the list before passing it as a parameter, like this: ```test(LIST1[:]) ``` The above will create a new, different list (it's a shallow copy, though ... for performing a deep copy use ```copy.deepcopy```), which you can safely modify inside the function, as the list "outside" the function will remain unchanged. Comment for this answer: Thanks. Spot on. Btw what's the difference between shallow copy and deepcopy? Comment for this answer: So if I modify a element in a shallow copy of a list, it alter the element in original list? Comment for this answer: @iCodez Got it, I added that to my answer. Thanks! Comment for this answer: @f.rodrigues In a shallow copy, the list is new but the elements are the same. In a deep copy, the list is new and its elements are also copied, recursively. Comment for this answer: @f.rodrigues if it's a mutable object (say, another list or a map), yes indeed!. An immutable object (say, a string or a number) can't be modified in-place, so it's not a problem
Title: Wagtail streamfield block: injecting jQuery into the Wagtail Admin Tags: javascript;jquery;django;wagtail Question: I'm creating a block for Wagtail streamfields which shows real-time code syntax highlighting using the Prism JS library. It is partially working; when I have a language selected and code in place on an existing page, the code shows up, highlighted as expected: However, when I try to create a new Wagtail page with a new Code Block, I get a JavaScript error: It seems like the library is being delayed on loading when there isn't content there for it to highlight. I've tried both ```$(document).ready``` and ```$(window).load```, but this is a different situation since the template containing the Prism library is loaded dynamically when you click the "Code Snippet" button. Here's the ext of the error I'm getting: ```VM730:2 Uncaught ReferenceError: Prism is not defined at prism_repaint (eval at globalEval (jquery-2.2.1.js:338), <anonymous&gt;:2:5) at populate_target_code (eval at globalEval (jquery-2.2.1.js:338), <anonymous&gt;:9:5) at HTMLDocument.eval (eval at globalEval (jquery-2.2.1.js:338), <anonymous&gt;:2:29) at fire (jquery-2.2.1.js:3182) at Object.add [as done] (jquery-2.2.1.js:3241) at jQuery.fn.init.jQuery.fn.ready (jquery-2.2.1.js:3491) at eval (eval at globalEval (jquery-2.2.1.js:338), <anonymous&gt;:1:13) at eval (<anonymous&gt;) at Function.globalEval (jquery-2.2.1.js:338) at domManip (jquery-2.2.1.js:5285) ``` Here's the Django Wagtail code I'm using for the Wagtail block: ```class CodeBlock(StructBlock): """ Code Highlighting Block """ WCB_LANGUAGES = get_language_choices() language = ChoiceBlock(choices=WCB_LANGUAGES) code = TextBlock() class Meta: icon = 'code' template = 'wagtailcodeblock/code_block.html' form_template = 'wagtailcodeblock/code_block_form.html' ``` ...and the code for the form template for the Wagtail admin: ```<script&gt; function prism_repaint(target_class) { Prism.highlightElement($(target_class)[0]); } function populate_target_code(label) { target_class = '#target-element-' + label; code_text = $('#' + label).val(); $(target_class).text(code_text); prism_repaint(target_class); } </script&gt; {% with prism_version="1.6.0" %} {% block extra_css %} <link href="https://cdnjs.cloudflare.com/ajax/libs/prism/{{ prism_version }}/themes/prism.min.css" rel="stylesheet" /&gt; {% endblock extra_css %} {% block extra_js %} <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/{{ prism_version }}/prism.min.js"&gt;</script&gt; {% endblock extra_js %} <div class="{{ classname }}"&gt; {% if help_text %} <div class="object-help help"&gt;{{ help_text }}</div&gt; {% endif %} <ul class="fields"&gt; {% for child in children.values %} <li{% if child.block.required %} class="required"{% endif %}&gt; {% if child.block.label %} <label{% if child.id_for_label %} for="{{ child.id_for_label }}"{% endif %}&gt;{{ child.block.label }}:</label&gt; {% endif %} {{ child.render_form }} </li&gt; {% if child.block.label == "Language" %} {# As we loop through, load each language dialect #} {% for language_choice, language_name in child.block.field.choices %} {% if language_choice|length %} <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/{{ prism_version }}/components/prism-{{ language_choice }}.min.js"&gt;</script&gt; {% endif %} {% endfor %} <script&gt; $(document).ready(function() { // Set initial language class on load target_class = '#target-element-{{ child.id_for_label }}'.replace('language', 'code'); {% if child.id_for_label|length %} $(target_class).addClass('language-' + $('#{{ child.id_for_label }}').val()); {% endif %} // Change language being highlighted when dropdown is changed $('#{{ child.id_for_label }}').bind('input propertychange', function() { language_class = 'language-' + $('#{{ child.id_for_label }}').val(); $(target_class).removeClass().addClass(language_class); prism_repaint(target_class); }); }); </script&gt; {% endif %} {% if child.block.label == "Code" %} <script&gt; $(document).ready(function() { populate_target_code('{{ child.id_for_label }}'); $('#{{ child.id_for_label }}').bind('input propertychange', function() { populate_target_code('{{ child.id_for_label }}'); }); }); </script&gt; <li&gt; <pre&gt;<code id="target-element-{{ child.id_for_label }}"&gt;</code&gt;</pre&gt; </li&gt; {% endif %} {% endfor %} </ul&gt; </div&gt; {% endwith %} ``` I've verified that the CSS and JS are properly being injected into the code using the ```extra_css``` and ```extra_js``` template blocks. I've also attempted using the ".getScript" function, but haven't had any luck. I'm by no means a JavaScript expert, so any help would be appreciated. The entire source for the project can be found on GitHub, in case that helps: https://github.com/FlipperPA/wagtailcodeblock Any help tracking fixing this would be appreciated! Thanks for your time. Here is the accepted answer: StreamField blocks borrow Django's form media API to associate JS/CSS files with blocks - this is the recommended way to import JS/CSS libraries. Your code would become: ```from django import forms class CodeBlock(StructBlock): """ Code Highlighting Block """ # ... @property def media(self): prism_version = "1.6.0" return forms.Media( js=["https://cdnjs.cloudflare.com/ajax/libs/prism/%s/prism.min.js" % prism_version], css={'all': ["https://cdnjs.cloudflare.com/ajax/libs/prism/%s/themes/prism.min.css" % prism_version]} ) ``` Defining the JS/CSS in this way means that the imports will appear on any edit page that could potentially include your block, rather than just being inserted when your block is added.
Title: How to extract everything after 1st series of numbers PL/SQL Tags: sql;regex;oracle;regexp-substr Question: I want to extract everything after the 1st series of numbers. For example, the outcome of 95a6 should be 95 and a6. And the outcome of 9B2 should be 9 and B2 Comment: The value is in 1 field, for example 263C2. The outcome I want is are 2 values in 2 fields, which would be 263 in one field and C2 in the other field. Comment: Huh? Are you returning one value or two values? How are you getting "95"? Here is the accepted answer: You can use ```REGEXP_SUBSTR``` for this: ```SELECT str , REGEXP_SUBSTR(str, '\d+') AS substr1 , REGEXP_SUBSTR(str, '[A-Za-z].*') AS substr2 FROM ( SELECT '95a6' AS str FROM DUAL UNION SELECT '9 B2' FROM DUAL ) tests ``` Here ```\d+``` matches a sequence of digits and ```[A-Za-z].*``` matches a letter and everything after it. Demo on db<>fiddle Comment for this answer: And how can I remove all white spaces, if there is any? Comment for this answer: If I use trim it removes the white spaces but when I use REGEXP_SUBSTR to divide the column into 2 columns it still has white spaces. For example: the original input, which is 1 field, 95 a6 ----> output is '95' and ' a6'. So still with whitespace Comment for this answer: You could simply `TRIM` the string before matching. Be advised that this is a very simple regex designed only to handle the examples you provided. Comment for this answer: @bhr... my bad... TRIM ***after*** REGEXP_SUBSTR i.e. `TRIM(REGEXP_SUBSTR(...))`. Having said that, I recently added another example in my answer. Or change the second regexp from `\D.*` to `[a-zA-Z].*`. Lots of possible workarounds. Comment for this answer: Can you explain please the difference between \d and \D ? and why you added `.` ?
Title: SQL Virtual Table Tags: sql;ms-access;ms-access-2003 Question: I have my database set up as such: Each product I have has it's own table where it records the quantity sold/transaction # (so column 1 is "transactionID", column 2 is "quantity") ex) p-backScratcher (where p- is indicative of "product") There are also tables for each year which hold records of each transaction that went through. Each of these tables holds the following columns: "transactionID", "date", "time", "pt_CA", "pt_DB", "pt_VC", "pt_MC", "pt_CH", "pt_AM" ex) sales-2008, sales-2009, etc. etc. I'd like to be able to reference a single table that holds all the records for each year without having to change the sql for the table to include a new year. So for example, I'd want to query all transactions for "p-backScratcher", I don't want to have to type out ```SELECT sales-2008.date, sales-2009.date FROM sales-2008, sales-2009 WHERE sales-2008.transactionID = p-backScratcher.transactionID OR sales-2009.transactionID = p-backScratcher.transactionID ``` ...but rather: ```SELECT sales.date FROM sales WHERE sales.transactionID = p-backScratcher.transactionID ``` Comment: This design seems to rather difficult to work with. Is there a reason for choosing this design over others which might be easier to work with? Comment: My first thought was to include everything in one table; where anything past the "pt_AM" column would be a product's quantity. Basically anytime I'd do something like that, I'd eventually run out of columns (in the long run). Having a table for each product assures me that a) I won't have any tables with excess null entries and b) lookup times would be shorter by separating sales by year; considering reports are typically generated either monthly or for a given year (though due to the concerns posted, I'll probably just consolidate all transaction info to a single table) Here is the accepted answer: ``` I'd like to be able to reference a single table that holds all the records for each year without having to change the sql for the table to include a new year. ``` This is why you should not be using one table per product and one table per year. What you need is one "Product" table and one "Transaction" table. Comment for this answer: Exactly. This is a bad design. Here is another answer: What you're looking for is called a "View" which pretty much is a stored statement that is a list of properly formatted results. You can query it directly like it is a table. Here is another answer: In SQL, as Kyle's answer states, you can create a View, which is a kind of Virtual table, but I would strongly recommend that you get a book, or google, Relational database design, before you commit yourself to a database structure.
Title: Availability of DBDB-V data Tags: data-request Question: DBDB-V is a digital bathymetric database (variable resolution) format. I'm particularly looking for test data in this format (to test FalconView amongst other tools). I've found the OAML data at https://esme.bu.edu/download/index.shtml (which I have tried to load, but haven't yet managed to get to display in FalconView yet), but I'd really like to find something of a little higher resolution. It doesn't matter where, and it doesn't really matter how good the data is, just as long as it matches the standard.
Title: Null Pointer Exception Traced to Line 90 of CommentPostgres.java, SQL works correctly in DBeaver, Test does not Tags: amazon-rds;java-11;dbeaver;postgresql-12 Question: All code for entire project is available here The database is PostgreSQL 12.7 The backend is Java 11.0.12 I am building my TDD tests with JUnit 5.8.1 Here is ```CommentDaoTest.java``` None of it is working, but I am specifically working on ```getAllNotNull``` Line one of the method gets an exception response that leads to a NullPointerException on line 90 of ```CommentPostgres.java``` ```package com.revature.data; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import java.util.Set; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import com.revature.beans.Comment; import com.revature.data.postgres.CommentPostgres; public class CommentDaoTest { private CommentDAO cd = new CommentPostgres(); @BeforeEach public void setup() { cd = new CommentPostgres(); } @Test public void getByIdNotNull() { Comment actual = cd.getById(1); assertNotEquals(null, actual); } @Test public void getByIdValidComment() { String expected = &quot;Polarised methodical access&quot;; Comment one = cd.getById(1); String actual = one.getCommentText(); assertEquals(expected, actual); } @Test public void getAllNotNull() { Set<Comment&gt; actual = cd.getAll(); assertNotEquals(null, actual); } } ``` Here is the relevant part of ```CommentPostgres.java```... ``` @Override public Set<Comment&gt; getAll() { Set<Comment&gt; comments = new HashSet<&gt;(); try (Connection conn = connUtil.getConnection()) { String sql = &quot;select * from comment&quot;; Statement stmt = conn.createStatement(); ResultSet resultSet = stmt.executeQuery(sql); while (resultSet.next()) { Comment comment = new Comment(); comment.setCommentId(resultSet.getInt(&quot;comment_id&quot;)); comment.setCommentText(resultSet.getString(&quot;comment_text&quot;)); **Line 90** comment.getApprover().setEmpId(resultSet.getInt(&quot;approver_id&quot;)); comment.getRequest().setReqId(resultSet.getInt(&quot;req_id&quot;)); comment.setSentAt(resultSet.getTimestamp(&quot;sent_at&quot;).toLocalDateTime()); System.out.println(comment); comments.add(comment); } } catch (SQLException e) { e.printStackTrace(); } return comments; } ``` Here is the relevant SQL ```create table if not exists employee ( emp_id serial unique primary key, first_name varchar(40), last_name varchar(40), username varchar(30), passwd varchar(25), role_id integer not null references user_role, funds real, supervisor_id integer, dept_id integer ); create table if not exists reimbursement ( req_id serial unique primary key, emp_id integer references employee, event_date date, event_time time, location varchar(50), description varchar(75), cost real, grading_format_id integer references grading_format, event_type_id integer references event_type, status_id integer references status, submitted_at time ); create table if not exists comment ( comment_id serial unique primary key, req_id integer references reimbursement, approver_id integer references employee, comment_text varchar(100), sent_at time ); INSERT INTO comment (req_id, approver_id, comment_text, sent_at) VALUES (1, 43, 'Polarised methodical access', '8:56:03'), (2, 34, 'Decentralized 3rd generation encryption', '16:26:13'), (3, 1, 'Open-architected asymmetric firmware', '3:52:08'), (4, 34, 'Upgradable content-based synergy', '8:01:03'), (6, 49, 'Progressive foreground frame', '7:35:55'), (7, 43, 'Persevering didactic definition', '16:55:07'), (8, 43, 'Proactive responsive success', '2:21:47'), (9, 17, 'Devolved content-based task-force', '22:04:18'), (10, 43, 'Self-enabling client-server orchestration', '9:03:46'), (13, 49, 'Pre-emptive stable encoding', '12:47:36'), (14, 11, 'Streamlined asymmetric initiative', '17:45:58'), (15, 43, 'Open-architected web-enabled leverage', '2:19:17'), (17, 43, 'Innovative transitional alliance', '12:43:29'), (19, 1, 'Organized didactic protocol', '3:54:43'), (20, 17, 'Switchable 5th generation solution', '20:54:12'); ``` The scripts holding the rest of it are on github in the link at the top. When I do a ```SELECT * FROM comment; ``` in DBeaver I get all of the comments with ```approver_id's``` however when I run ```getAllNotNull``` I get a NullPointer pointing at the ```approver_id```. I put a Sys.out trying to catch to comment a few lines below 90, but it doesn't hit so the NullPointer is happening on the first time through. Here is the stacktrace. ```java.lang.NullPointerException at com.revature.data.postgres.CommentPostgres.getAll(CommentPostgres.java:90) at com.revature.data.CommentDaoTest.getAllNotNull(CommentDaoTest.java:42) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:725) at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60) at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131) at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149) at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140) at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84) at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115) at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105) at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106) at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64) at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45) at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37) at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104) at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:214) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:210) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:66) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) at java.util.ArrayList.forEach(ArrayList.java:1259) at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) at java.util.ArrayList.forEach(ArrayList.java:1259) at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35) at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57) at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52) at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114) at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:95) at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:91) at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:60) at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:98) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:40) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:529) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:756) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:452) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210) ``` Please let me know if you want more files or code snippets added. Thank you for your help. Comment: Have you checked the value returned by `comment.getApprover()`? My suspicion is that this call returns `null`. --- It would also be beneficial if you [edit] the post and provide a command to reproduce the test error. Comment: I put the `System.out.println(comment)` into the `getAll` method in `CommentPostgres.java`. It didn't reach that line. I'm not sure how else to check it. Comment: Paste the exception stackstrace as well. Here is the accepted answer: This line creates a new, empty ```Comment``` object: ```Comment comment = new Comment(); ``` After that line, you never call ```comment.setApprover()```, so the approver property inside the ```comment``` object is ```null```. This doesn't have anything to do with missing data in the database, it is a problem with the way you are initializing your Java objects. Look at what you are doing here: ```comment.getApprover().setEmpId(resultSet.getInt(&quot;approver_id&quot;)); ``` You're saying &quot;take the new comment object I just created, get the approver object from it, and then set the ID of that approver&quot;. Instead your code needs to look something like this: ```Approver approver = getApproverByEmpId(resultSet.getInt(&quot;approver_id&quot;)); comment.setApprover(approver); ``` Where ```getApproverByEmpId(Integer empId)``` is a new method you need to create that queries the ```employee``` table, and returns an ```Employee``` object.
Title: Does an RST packet get sent to the application regardless of its sequence number? Tags: c++;sockets;winapi;tcp;network-programming Question: When an application is receiving data from a socket, it will receive the data in the correct order in which it was sent. TCP will know how to re-order the data based on the sequence number included in each packet's header. But what about an ```RST``` packet, for example: if the other side sent some data and then sent an ```RST``` packet (by ungracefully closing the connection), and the ```RST``` packet was received before the data, what will happen in this case? Will TCP wait for the data to be received and then give the application the data followed by the ```RST``` packet, or will TCP give the application the ```RST``` packet immediately before receiving the data? Here is another answer: It doesn't make any difference. Receipt of the RST will cause the entire contents of the socket receive buffer to be thrown away in either case.
Title: Need help to hover different background images in wordpress HTML code Tags: javascript;html;jquery;css;wordpress Question: I want exactly like this website: https://www.petzl.com/INT/en I have displayed background video, 3 texts, by hovering on them the images are changing + links to access them. But by hovering the text, petzl.com website have activated different images on hover, sometimes different images are appearing on hover. Can I achieve the different images by css or need to have js or anything? Also need to have span/div elements to appear in one line. My website link: beta.edgerope.com Please find code below: Below is the code, I have added as HTML shortcode in the page and in the background video is displayed ```<style&gt; .image{ height: 800px; width: 100%; display: grid; place-content:center; justify-content:middle; color: white; font-size:30px; background-color: #; background-position: center; background-size: cover; } .training{ display:inline-block; padding-top: 50px; padding-right: 1500px; padding-bottom: 50px; padding-left: 1px; } .image&gt;div { display: inline-block; width: 100px; } .image&gt;div img { position: absolute; left: 0; top: 0; width: 100%; height: 100%; object-fit: cover; opacity: 0; z-index: 0; display: inline-block; } .image&gt;div span { position: relative; z-index: 1; cursor: pointer; display: inline-block; } .image&gt;div span:hover+img { opacity: 1; display: inline-block; } .div{ dipslay } </style&gt; <div class="image"&gt; <div class="services"&gt; <span class="services" onclick="window.location=''"&gt;Services</span&gt; <img src="https://www.petzl.com/sfc/servlet.shepherd/version/download/0686800000D6sSCAAZ"&gt; </div&gt; <div class="Training"&gt; <span class="training" onclick="window.location='beta.edgerope.com/courses'"&gt;Training</span&gt; <img src="https://beta.edgerope.com/wp-content/uploads/2022/08/1-1-1536x864.jpg"&gt; </div&gt; <div class="shop"&gt; <span class="shop" onclick="window.location='beta.edgerope.com/shop'"&gt;Shop</span&gt; <img src="https://www.petzl.com/sfc/servlet.shepherd/version/download/0686800000D6sSCAAZ"&gt; </div&gt; </div&gt;``` : Here is another answer: There are many ways to acomplish this, and you should be able to do this with pure css and html. I've made an example that uses css pseudo elements in order to display the correct image when hovering the sections/links. Also changed up to use a tags instead of using ```onclick=&quot;window.location&quot;``` as you did. Here you can change/set the default image in the #hero selector ```<style&gt; /* Styling for the default hero */ #hero { height: 800px; width: 100%; display: flex; color: black; background-color: #000; } /* Wrapper for all the sections */ .hero-sections { width: 100%; height: 100%; position: relative; /* Allows to change the z-index, and */ z-index: 1; display: flex; flex-direction: row; justify-content: center; align-items: center; gap: 2rem; } /* Container for the image */ .hero-imag181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16after { content: &quot;&quot;; position: absolute; left: 0; top: 0; width: 100%; height: 100%; z-index: -1; /* Allows the image to appear behind the text */ pointer-events: none; /* Prevent image to show when hovering the 181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16ter element*/ background-image: var( --bg-url ); /* Uses the images set by the html (css variable) */ opacity: 0; /* Hides the image when it's not active */ transition: opacity 0.5s; /* Adds a fade transition to the opacity*/ } /* Styles when the the user hovers or has focus on the buttons/links */ .hero-image:is(:hover, :focus-within)181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16ter { opacity: 1; /* Change the opacity when the text is active/in hover */ } /* Styles the buttons/links */ .hero-cta { color: white; text-decoration: none; font-size: 2rem; } </style&gt; <div id=&quot;hero&quot;&gt; <div class=&quot;hero-sections&quot;&gt; <div class=&quot;services hero-image&quot; style=&quot; --bg-url: url(https://www.petzl.com/sfc/servlet.shepherd/version/download/0686800000D6sSCAAZ); &quot; &gt; <a class=&quot;hero-cta&quot; href=&quot;#&quot;&gt;Services</a&gt; </div&gt; <div class=&quot;training hero-image&quot; style=&quot; --bg-url: url(https://beta.edgerope.com/wp-content/uploads/2022/08/1-1-1536x864.jpg); &quot; &gt; <a class=&quot;hero-cta&quot; href=&quot;beta.edgerope.com/courses&quot;&gt;Training</a&gt; </div&gt; <div class=&quot;shop hero-image&quot; style=&quot; --bg-url: url(https://www.petzl.com/sfc/servlet.shepherd/version/download/0686800000D6sSCAAZ); &quot; &gt; <a class=&quot;hero-cta&quot; href=&quot;beta.edgerope.com/shop&quot;&gt;Shop</a&gt; </div&gt; </div&gt; </div&gt; ``` If you would like to go more advanced here I would recommend implementing some javascript handling ```mouseenter``` and ```mouseleave```. As you said you used Wordpress you could also use the .hover() from jQuery.
Title: Download byte array sent by web api as pdf on client Tags: jquery;asp.net-mvc-4;asp.net-web-api;download Question: I am exporting crystal report to a pdf document and there is a button in UI that downloads that pdf in "Downloads" folder. To achieve this I have a method in web api that gets executed on button click and that method returns HttpResponseMessage whose contents are the byte array (the pdf resides on blob and I download that file to a byte array). From UI, using window.open method of javascript I am directly opening the URL of the web api method which when executed downloads the file in downloads folder. This works fine. But now I have added [Authorize] attribute to the web api controller and hence when javascript window opens with the method URL, user is prompted for a user name and password value. I am trying to post an ajax request to the server which returns me byte array on client. After the ajax request is executed, I have written the code below: ```data = "data:application/octet-stream;base64," + data; document.location = data; ``` The file does get downloaded but it gets downloaded as a "download" file for which I have to use "Open with.." option to view the file. How can I download it as a pdf document ? Here is another answer: If you are trying to serve a file with WebApi, you can do this: ``` HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK); Stream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true); response.Content = new StreamContent(fileStream); response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); response.Content.Headers.ContentDisposition.FileName = "myfilename.pdf"; return response; ``` You don't need to manually dispose the stream, the framework calls HttpResponseMessage.Dispose, which calls StreamContent.Dispose, which calls FileStream.Dispose. Comment for this answer: I had written similar code before and it works perfectly fine. But I have now decorated my web api controller with [Authorize] attribute. That is why I am sending byte[] from server to client. You can read the question again. I want to download that byte[] as pdf on client.
Title: How angular interceptors works? Tags: javascript;angularjs Question: I was learning angular interceptors today. I did some samples to to better understand the concept. Here is small sample. ```var app = angular.module("myApp", []); app.factory("timestampMaker", [ function() { var timestampMaker = { request: function(config) { console.log(config); config.requestTimestamp = new Date().getTime(); return config; }, response: function(response) { response.config.responseTimestamp = new Date().getTime(); return response; } }; return timestampMaker; } ]); app.config(['$httpProvider', function($httpProvider) { $httpProvider.interceptors.push('timestampMaker'); } ]); app.run(function($http) { $http.get('https://api.github.com/users/naorye/repos').then(function(response) { console.log(response); var time = response.config.responseTimestamp - response.config.requestTimestamp; console.log("The request took" + (time / 1000) + "seconds") }); });``` ```<html ng-app="myApp"&gt; <head&gt; <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"&gt;</script&gt; </head&gt; </html&gt;``` When I am doing ```console.log(config)``` inside request function, here is the output on the console. I am not getting how ```responseTimestamp``` appear in the config object of request where as its defined inside response function Here is another answer: Note I used the source code for 1.2.x which is the one added in the question. ```$httpProvider``` is a provider that gives you ```$http``` service. As a provider, in config time exposes a public array - there you just add all strings from services names you wanted to be injected in your response/requests. That is what you do here ```app.config(['$httpProvider', function($httpProvider) { $httpProvider.interceptors.push('timestampMaker'); } ]); ``` and it can be only done in config time because per docs providers can be configured before the application starts You can see the exposed array in the source code in line 159 ```var responseInterceptorFactories = this.responseInterceptors = []; ``` When you request the ```$http``` service, injecting it into your service/controller, ```$get``` function is executed. In that function, your array of interceptors is iterated, as you can see in source code in line 179 ``` var reversedInterceptors = []; forEach(responseInterceptorFactories, function(interceptorFactory, index) { var responseFn = isString(interceptorFactory) ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory); /** * Response interceptors go before "around" interceptors (no real reason, just * had to pick one.) But they are already reversed, so we can't use unshift, hence * the splice. */ reversedInterceptors.splice(index, 0, { response: function(response) { return responseFn($q.when(response)); }, responseError: function(response) { return responseFn($q.reject(response)); } }); }); ``` Per convention, they reverse the order. You can see that using the string, they get a reference to the function using ```$injector.get``` or ```$injector.invoke```, and using ```$q.when()``` we can introduce them to the promises chain, even if they are synchronous code - See this Can I use $q.all in AngularJS with a function that does not return a .promise? if you are not sure what I meant about ```$q.when()``` So far we have an array with functions, which are all promise-like (thanks to ```$q.when()```). When you request data through ```$http``` like this ```$http.get('https://api.github.com/users/naorye/repos').then(function(response) { console.log(response); var time = response.config.responseTimestamp - response.config.requestTimestamp; console.log("The request took" + (time / 1000) + "seconds") }); ``` even though you have the ```.get()```, is just a shortcut for all the same functionality which is here In the code the relevant part is this one: First, a chain array is created with two values: an inner function which is not important for our purpose (but it returns a promise - this is important), and undefined value. Our array with interceptors is iterated, and request interceptors are added at the beginning (before the request) and response at the end. Like this ``` function serverRequest { // some code }; var chain = [serverRequest, undefined]; var promise = $q.when(config); // apply interceptors forEach(reversedInterceptors, function(interceptor) { if (interceptor.request || interceptor.requestError) { chain.unshift(interceptor.request, interceptor.requestError); } if (interceptor.response || interceptor.responseError) { chain.push(interceptor.response, interceptor.responseError); } }); ``` then, having the chain complete (remember our array of interceptors was full of promises), the code iterates it, adding all of them using ```.then()```, causing all of them to be executed in a chain, following promises chaining (you can google that) ``` while(chain.length) { var thenFn = chain.shift(); var rejectFn = chain.shift(); promise = promise.then(thenFn, rejectFn); } ``` Finally, the callback you add in ```success``` and ```error``` is added at the very end of the chain and the promise is returned ``` promise.success = function(fn) { promise.then(function(response) { fn(response.data, response.status, response.headers, config); }); return promise; }; promise.error = function(fn) { promise.then(null, function(response) { fn(response.data, response.status, response.headers, config); }); return promise; }; return promise; ``` The only part I am not sure about is the use of ```undefined``` in the chain array Summary You add the name for your services, ```$HttpProvider``` uses ```$invoke``` service to get them and adds them in the promise chain using ```$q.when()```, returning a promise. At the end of that, your callbacks for a specific ```$http``` request is added.
Title: When installing SSAS, should you install the version that corresponds to the version of SQL Server installed, or go with the newest version of SSAS? Tags: sql-server;ssas;sql-server-2014 Question: I am currently running SQL Server 2014 and need to install SSAS. Is it best to match the version of SSAS to the version of SQL Server installed or is it recommended that the newest version of SSAS be installed? I figure the SQL Server environment is set up one of two ways: 1) You should usually match versions of SQL Server and SSAS for compatibility reasons (they were in theory designed for each other). 2) You should usually install the newest version of SSAS because this is the current version that the SQL Server team is focusing their most time on and thus has more bug fixes, security fixes, features, etc. than older versions. Thanks! Here is the accepted answer: Great question, and in this case the answer is 2: You should install the newest version of SSAS because this is the current version that the SQL Server team is focusing their most time on and thus has more bug fixes, security fixes, features, etc. than older versions ..unless you have a version installed prior or equal to SQL 2008. In your case of SQL 2014, install the latest version. There is no need to install the version that was released at the same time as your version of SQL Server. See The Installing SQL Server Analysis Services Page for more information. The SSAS and SSMS teams work independantly of each other as is the case with many teams within Microsoft. Here is another answer: Just install the latest man, go with the flow, and accept one the answers. People take time to answer your question. Here is another answer: In order to offer a recommendation I need to know whether you value stability or features more? Since SSAS is a separate instance from SQL Server it does not need to be the exact same version as SQL Server. Check out this article from Microsoft on SSAS version compatibility. Based on this article I would recommend you install either SSAS 2014 or SSAS 2016. At the end of the day, the safest thing to do is install the same version of SSAS. So if you value stability and don't want to deal with unforeseen problems down the road, I would recommend 2014. If you want a specific feature in 2016, or just like installing the latest and greatest, then you could install 2016. Note that I have never installed different versions of SSAS and SQL Server. Comment for this answer: I didn't mean that an older version has fewer bugs than a later version. I meant that trying to connect 2 pieces of software that are the same version will be less likely to create issues. The original question is about whether it is safer to match the version of SQL Server and SSAS. I believe it is. Comment for this answer: lower vesion doesn't mean "safer and more stable". SQL 2014 still has many unsolved bugs that are solved in SQL 2016. So it's case by case. Comment for this answer: SQL Server engine acts as data source for SSAS, so the match between versions is not needed to get safer option. The choice mostly depends on features in both SQL engine and SSAS. Your link to MS site is about compatibility for SSAS projects and features, it's not about compatibilities between SQL Server and SSAS. Here is another answer: You can install different versions of SSAS and the SQL Server Data Engine on the same host, yes. Should you? That completely depends on your needs. If it's a requirement that you have SSAS 2016, because it has a feature that 2014 does not, but requirement to use 2014, because 2016 breaks something else, or isn't supported, then you can do that. There weren't a huge amount of breaking changes in SQL Server 2016 though: Breaking changes in SQL Server 2016; so I'm surprised you want to go to route. If you have SSAS 2016 and SQL Server Data Engine 2014, that's 2 sets of licences; you'll need one set for 2014 and one for 2016. If, however, you're using just one version (let's say 2016), then that's one set of licences; as your licences gives you access to all the tools that comes with that version of SQL Server (so you also get SSIS, and SSRS). That doesn't seem cost effective. I realise that this is a question in an answer but I have to ask; Why do you want 2 different versions installed?
Title: Discord.js Emoji Collector Tags: javascript;discord;discord.js Question: i have litle problem when i using collector i tried test with logging actions. Then where is problem when i remove/delete reaction from message its doesnt react i must add reaction first time and that removing/deleting reaction detect works after setting first time reaction but previously reaction doesnt works. ```const collector = msg.createReactionCollector({ dispose: true }); collector.on('collect', (reaction, user) =&gt; { console.log(&quot;Collect&quot;); }); collector.on('remove', (reaction, user) =&gt; { console.log(&quot;remove&quot;); }); ``` Comment: Are you saying it's not detecting the message's reactions being removed, if it wasn't added after the collector was created? Here is another answer: I find way how fix this ```msg.createReactionCollector({ dispose: true }); client.on('messageReactionAdd', (reaction, user) =&gt; { console.log(&quot;ReactionAdded&quot;); }); client.on('messageReactionRemove', (reaction, user) =&gt; { console.log(&quot;ReactionAdded&quot;); }); ``` Here is another answer: If I understood your question correctly, what's happening here is that the message in which the reactions are being added/removed is not cached by the bot on boot, and it is only cached after the first reaction gets added or removed from it, this is why the second action is detected but the first one isn't. One away to solve this would be to cache the message on startup by fetching it using ```<TextChannel&gt;.messages.fetch(<MESSAGE_ID&gt;)```.
Title: ASP.NET MVC 5: Query fails to return data using IdentityDbContext in UnitOfWork Pattern Tags: asp.net-mvc;entity-framework;ef-code-first Question: I am trying to extend the UnitOfWork pattern that I used for a number of MVC 4 applications to MVC 5 whilst also using the new IdentityDbContext and things are not working out. The problem is its very hard to debug as no errors are being generated. First, some code. I have a context definition that looks as follows. I have added my own DbSets to the out of the box IdentityDbContext as it makes sense to keep everything in one place. ```public class ApplicationDbContext : IdentityDbContext<ApplicationUser&gt; { public DbSet<PALSOfficer&gt; PALSOfficers { get; set; } public DbSet<Client&gt; Clients { get; set; } public DbSet<GP&gt; GPs { get; set; } public DbSet<Surgery&gt; Surgeries { get; set; } public DbSet<Disability&gt; Disabilities { get; set; } public DbSet<Area&gt; Areas { get; set; } public DbSet<PALSReferral&gt; PALSReferrals { get; set; } public DbSet<Appointment&gt; Appointments { get; set; } public ApplicationDbContext() : base("DefaultConnection") { } } ``` I then have a UnitOfWork class that looks as follows: ```public class UnitOfWork : IDisposable { private bool _disposed = false; private ApplicationDbContext _context = new ApplicationDbContext(); public UserManager<ApplicationUser&gt; _userManager { get; set; } private PalsOfficerRepository _palsOfficerRepository; private UserRepository _userRepository; private GenericRepository<Area&gt; _areaRepository; public UserRepository UserRepository { get { if (this._userRepository == null) { this._userRepository = new UserRepository(_context); } return _userRepository; } } public PalsOfficerRepository PalsOfficerRepository { get { if (this._palsOfficerRepository == null) { this._palsOfficerRepository = new PalsOfficerRepository(_context); } return _palsOfficerRepository; } } public GenericRepository<Area&gt; AreaRepository { get { if (this._areaRepository == null) { this._areaRepository = new GenericRepository<Area&gt;(_context); } return _areaRepository; } } public UserManager<ApplicationUser&gt; UserManager { get { if (this._userManager == null) { this._userManager = new UserManager<ApplicationUser&gt;(new UserStore<ApplicationUser&gt;(_context)); } return _userManager; } } public void Save() { try { _context.SaveChanges(); } catch (DbEntityValidationException dbEx) { foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); } } throw; } } protected virtual void Dispose(bool disposing) { if (disposing) { if (this._userManager != null) { this._userManager.Dispose(); } _userManager.Dispose(); } this._disposed = true; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } ``` So far so good. I am using code first to generate my database with automatic migrations. My problem is that if I try to query the database, odd things happen. Take this method for instance. ```var results = new SearchResults<PALSOfficer&gt;(); var officers = from o in Context.PALSOfficers select o; if (!string.IsNullOrEmpty(keyword)) { officers = (from o in officers where o.FirstName.Contains(keyword) || o.LastName.Contains(keyword) select o); } officers = officers.OrderBy(p =&gt; p.LastName); results.Total = officers.Count(); int offset = page * display; results.ResultList = results.Total &gt; offset ? officers.Skip(offset).Take(display) : officers; //results.ResultList = Context.PALSOfficers; return results; ``` This returns nothing even though the database contains data. Weirdly, the count will work. If I put a breakpoint in and mouseover the results I get the message that 'children could not be evaluated' If I simply return ```Context.PALSOfficers``` I get the rows back. Any type of manipulation of that data though (sorting etc) seems to break the query entirely. Here is the definition of PALSOfficer ```public class ApplicationUser : IdentityUser { public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } public DateTime Added { get; set; } public DateTime Updated { get; set; } } public class PALSOfficer : ApplicationUser { public string InternalReference { get; set; } public virtual ICollection<Area&gt; Areas { get; set; } } ``` Comment: Ok, so I bypassed the whole UnitOfWork class and instead tried by just creating a new context and querying and it still doesnt work. Also, I am noticing that the first time the query runs it can take upward of 20 seconds for the database to come back. Comment: Your question is really hard to answer as is: try writing a Short, Self Contained, Correct (Compilable), Example -- http://sscce.org/
Title: Change the pop-up text for "favorite question" tooltip Tags: feature-request;bookmarks;tooltips Question: Please do not duplicate this for one of the similar bug report or discussion questions, which only ask "why" it is like this or state "it should not be" like this. I am proposing an actual idea to change it (feature-request). (TL;DR; further below for those who know the issue) The current message when hovering the tooltip: ``` This is a favorite question (click again to undo) ``` The message is one of the states regardless Currently, whether the question is a favorite or not, it states exactly the same message (as above). This could be fine if the message was different, but the current message is one of the actual states of the tooltip. So if it is a favorite then the message is fine as it states "this is a favorite", but if it's not a favorite then the message is telling me it is the opposite potential state to what it actually is. This really is confusing, and while it's not exactly an admin control area button, I just think it's illogical enough to warrant a change. Someone's telling porkies It is not a favorite question, I do not have any favorite [email protected]. This is even confirmed to me in my profile: ``` You have no favorite questions ``` The is confusing, because my profile states that I have no favorites but when on a question I'm told by a tooltip pop-up message that I do have a favorite. In fact, if I were to believe the tooltip message, every single question on every Stack site would be a favorite... ``` "I'm not upset that you lied to me, I'm upset that from now on I can't believe you." - Friedrich Nietzsche ``` Undo that which has not been done I cannot "(click again to undo)" because I never did it in the first place. ``` undo To reverse the doing of; cause to be as if never done: ``` I cannot reverse the doing of something I have not done. I cannot cause to be as if never done because it has already not has been never done (I didn't do it yet). TL;DR; A Simple Change So, I am proposing to simply change the static text to something more logical, such as . ``` Click to toggle favorite on or off ``` It's still not perfect given the amazingly worded functionality the site otherwise offers, but at least it's generic and not one of the possible states. Also the visual state confirms it a bit, as when a question "is favorite" the star is gold, and when "not favorite" it's grey and offy looking (I know this is in play with the current message, but it still has an incorrect message). (Although.. the HTML anchor's CSS class does currently change based on state -"not favorite" is ```class="star-off"```, and "is favorite" is ```class="star-off star-on"```, so something in the scripts already knows the state change, how hard would it be to... no, no, simple request James..). Please implement this and I won't mention that "favourite" is also misspelled... Here is another answer: The question I asked about this gave me the answer that it is telling you: ``` The tooltip is telling you in what situation to click the star (&quot;This is a favorite question&quot;). It is also telling you that this can be undone (&quot;(click again to undo)&quot;). ``` Now, that makes sense - but it is not consistent with other buttons on SE. The 'accept answer' button says (emphasis mine): ``` Click to accept this answer because it solved your problem or was the most helpful in finding your solution (click again to undo) when unclicked Click to undo acceptance of this answer; you accepted this answer [DATE] when clicked ``` That's the simplest solution to this (and to make it more consistent with the site) is, add 'Click to' to the message and change the message again when it has been clicked. ie (in bold and italics is the change, the 'optionally' is optional ;): ``` Click to make Tthis is a favorite question (click again to undo) when unclicked Click to remove this from your favorites (optionally); you added this as a favorite on [DATE] when clicked; ``` It should, as you said, be easy to implement this - because you already know when the state changes - so you can just change the message depending on what class the button has! Another option is to follow the voting symbols which simply say: ``` This question shows research effort; it is useful and clear when unclicked This question shows research effort; it is useful and clear (click again to undo)when clicked ``` So, just make it: ``` Make Tthis is a favorite question when unclicked Make Tthis is a favorite question (click again to undo) when unclicked ```
Title: Using svjour3 and spbasic, is it possible to move the year to the end of a reference? Tags: bibliographies;bibtex;journal-publishing Question: I am writing a paper for submission to a springer journal that specifies the use of documentclass svjour3. The only bibliographystyle in the springer template for Harvard referencing is spbasic. The author guidelines example of how a reference should look in the bibliography list is: ``` Hamburger, C.: Quasimonotonicity, regularity and duality for nonlinear systems of partial differential equations. Ann. Mat. Pura Appl. 169, 321–354 (1995) ``` However, spbasic currently puts the year directly after the author name, for example: ``` Goodhart C.A., Sunirand P., Tsomocos D.P. (2005) A risk assessment model for banks. Annals of Finance 1(2):197–224 ``` Is there any way to force spbasic to adopt the different style, or can someone recommend a bibliographystyle which is compatible with the svjour3 documentclass that will achieve the correct format? Comment: Ask the Springer folks about this. Perhaps you should use another bibliographystyle.
Title: Where to put file transformation (webconfigs) on pipeline? Tags: c#;asp.net;jenkins;devops Question: My company has the credentials and strings from webconfigs on source code. We use Jenkins to build and another tool to deploy. Should I use Jenkins to store my data from config and use data transformation? Or my deployment tool? Where these data are stored? I am reading Microsoft documentation, but it only explains for Azure Devops.
Title: Markup for linked Schema.org articleSection(s) Tags: html;schema.org;microdata Question: I'm trying to mark up article sections (```articleSection```) on my blog listing page. Each article section also has a link to go to that section. Which of these syntaxes, if any, is correct as they produce different results in the Google Structured Data Testing Tool: ```<a href="#"&gt;<span itemprop='articleSection'&gt;section name 1</span&gt;</a&gt; ``` Testing Tool result: ```articleSection: section name 1``` ```<span itemprop='articleSection'&gt;<a href="#"&gt;section name 2</a&gt;</span&gt; ``` Testing Tool result: ```articleSection: section name 2``` ```<a href="#" itemprop='articleSection'&gt;section name 3</a&gt; ``` Testing Tool result: ```articleSection: http://www.example.com/pagelocation/#``` Perhaps this matters, perhaps it doesn't. Does having a link inside the ```articleSection``` property help? ```articleSection``` looks for 'text' not URL. GoldStarBonus: Is there any way/advantage to associate a link to the articleSection name? If not, that's fine for now. Here is the accepted answer: The ```articleSection``` property expects Text as value. In Microdata, you can give a text value by not using an element that would specify an URL (like ```a```, ```area```, ```link```, ```video``` etc.) or a datetime (```time```). So don’t use ```a```. ```span``` is fine, unless there is a more appropriate element defined in HTML5. As far as Microdata and Schema.org are concerned, there is no difference between these: ```<a href="#"&gt;<span itemprop="articleSection"&gt;…</span&gt;</a&gt;``` ```<span itemprop="articleSection"&gt;<a href="#"&gt;…</a&gt;</span&gt;``` As Schema.org does not define a type for an article section (e.g., ```ArticleSection```), you can’t specify any additional data about such a section. Comment for this answer: Thank you very much. I feel much clearer on this now.
Title: input and graphicx - look for images where file is located Tags: graphics;input;directory Question: I have a LaTeX document split in multiple text files, inside various folders, as follows: ```\section{Foo} \subsection{Foo1} \input{foo/1} \subsection{Foo2} \input{foo/2} \section{Bar} \subsection{Bar1} \input{bar/1} ``` And so on. Suppose that, inside the ```Foo2``` subsection, I must insert an image. How can I tell```LaTeX``` to look for the image inside the directory the currently open file is (i.e. ```foo```) so that inside the file ```2``` I can just write: ```\includegraphics{baz} ``` and I can place all images for a determined section inside their folders, among that section's input text files? Comment: I have multiple graphics file inside each directory, named differently. My actual file names are a little explicative, not just numbers like used in this example. Something around `theory/plasma` `theory/probes` and so on. Comment: Better than my original question, is there a declaration like `\graphicspath` which functions both for images and text files? This way, I could set it at the beginning of each section, and input subsections and images with just their names, without having to repeat the relative path for every one of them. Comment: Are there multiple image files called `baz` spread across these directories? Would you be willing to rename `foo/1` to be `foo/foo_1`? Comment: I think if you use the TEXINPUTS environment variable you will be fine as long as there are no duplicate `tex` filenames. Similarly, you can set `\graphicspath` once if there are no duplicate image filenames. Here is another answer: There are a number of ways of tackling this depending on how your directories are laid out. If you directory tree looks like ```-foo -foo1.tex -foo2.tex -baz.pdf -baz.eps -bar -bar1.tex -qux.pdf ``` where the files in the ```foo``` and ```bar``` directories have unique names, then you can specify the ```TEXINPUT``` environment variable to include the sub-directories. The details of how to set ```TEXINPUTS``` depend on your distribution (e.g., TeXLive or MikTeX) and OS (e.g., Windows or Linux). In my opinion, this is the ideal setup since you are telling ```tex``` where to look for files. In this case your "main" file would look like ```\section{Foo} \subsection{Foo1} \input{foo1} \subsection{Foo2} \input{foo2} \section{Bar} \subsection{Bar1} \input{bar1} ``` You could also use ```\graphicspath``` in this situation to set the directories to look for images in. In this case, the main file would look like ```\graphicspath{{foo}{bar}} \section{Foo} \subsection{Foo1} \input{foo/foo1} \subsection{Foo2} \input{foo/foo2} \section{Bar} \subsection{Bar1} \input{bar/bar1} ``` If you directory tree looks like ```-foo -1.tex -2.tex -baz.pdf -baz.eps -bar -1.tex -qux.pdf -baz.pdf -baz.eps ``` where the files in the ```foo``` and ```bar``` directories do not have unique names, then you cannot specify the ```TEXINPUT``` environment variable since it will not know which file you mean. You can still use ```\graphicspath```, but you have to set it before each ```\input``` ```\graphicspath{{foo}} \section{Foo} \subsection{Foo1} \input{foo/1} \subsection{Foo2} \input{foo/2} \graphicspath{{bar}} \section{Bar} \subsection{Bar1} \input{bar/1} ``` You could also use the ```import``` package. ```\section{Foo} \subsection{Foo1} \import{foo/}{1} \subsection{Foo2} \import{foo/}{2} \graphicspath{{bar}} \section{Bar} \subsection{Bar1} \import{bar/}{1} ``` Things get a little tricky with the ```import``` package if your directories are nested. Here is another answer: You can use ```\graphicspath{{foo}}\input{foo/1} .. \graphicspath{{bar}}\input{bar/1} ``` Comment for this answer: Isn't there a way to tell `LaTeX` that graphics should be picked inside the directory I'm in? I mean, it's obviously gonna look for images inside the directory the main `.tex` file is (or, actually, the folder I'm compiling in, I suppose). Instead, I want it to look for them inside the directory the input file is. I'm writing inside it, I want it to take its own directory for `\includegraphics` Comment for this answer: @JeffreyLebowski `\input` is designed to work like cutting and pasting the file contents in to that point tex really does not expose the current location of the file. there are packages that offer wrappers that offer slightly different interface but they will basically be doing exactly the above
Title: how to get android default font list programmatically? Tags: android;android-fonts Question: I am trying to create app which provide text formatting (like font style , font size , font color). So I want default fonts provided by android as a list to be shown in drop-down. Selecting font from drop-down will change the Text dynamically. Can anyone help , how can I achieve this either via XML or programmatically ? See the image how it must look like Comment: For ordinary widgets, there are only three options: serif, sans-serif, and monospace. Fonts are not part of the Android SDK. Comment: That's your job. Package some in your app. Or, download some from the Internet. Pay attention to the font licensing terms, of course. Comment: @Pallavi its making a one comman class for the set different type of font and in activity to set after bind text view. Comment: @Pallavi yes this for the different different font type. Comment: @Pallavi how many font size you want ?? Comment: Ok. So how I can get more fonts? Comment: @HardikParmar I need to put .ttf files in asset folder, Correct? Comment: @HardikParmar , but how many .ttf files I will download? And also it will increase the size of the package. So is there any better way. Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/111517/discussion-between-pallavi-and-hardik-parmar). Here is another answer: There are only three system wide fonts in Android SDK. ``` normal serif monospace ``` More info : click here Comment for this answer: need to add your app itself Comment for this answer: Ok. So how I can get more fonts? Here is another answer: font list is saved in ```Typeface``` class as a static field ```Map<Stirng, Typeface&gt; sSystemFontMap```. you just need to get this field. See my answer here.
Title: How to group these base on same address? Tags: python;django Question: ```{'street_number': '3', 'street_name': 'Raycraft', 'street_type': 'Dr', 'municipality': 'Amherstview', 'postal_code': 'K7N1Z1', 'type_of_reports': 'Valuation'}, {'street_number': '3', 'street_name': 'Raycraft', 'street_type': 'Dr', 'municipality': 'Amherstview', 'postal_code': 'K7N1Z1', 'type_of_reports': 'Inspection'} ``` Group these values by address ? for example output should be like: ```{'street_number': '3', 'street_name': 'Raycraft', 'street_type': 'Dr', 'municipality': 'Amherstview', 'postal_code': 'K7N1Z1', 'type_of_reports': ['Valuation',Inspection]} ``` Comment: it is a queryset for django. i need to convert it like in another format. Comment: type of reports are coming together Comment: I dont understand the question. Also, is this a dictionary? json? xlm? Comment: I dont understand the difference between the set and expected output. Here is another answer: I assume each of those keys is a field name in a model somewhere. If you want to do this directly in the template you might be able to use regroup In your model add a property that is a string of all the info you want to group on: ```@cached_property def id_str(self): return f'{self.street_number} {self.street_name}, {self...}'#add all fields you wish to group by ``` Then in your view add a queryset of the model to the context and in the template regroup on this property (assume the context object is called queryset): ```{% regroup queryset by id_str as regrouped_queryset %} <ul&gt; {% for address in regrouped_queryset %} <li&gt;{{ address.grouper }}</li&gt; <ul&gt; {% for each in address.list %} <li&gt;{{ each.type_of_reports }}</li&gt; {% endfor %} </ul&gt; </li&gt; {% endfor %} </ul&gt; ``` Comment for this answer: i tried your but it is not giving as output seems. Comment for this answer: What was the output?
Title: How to specify the port that the client side of socket in PHP? Tags: php;sockets Question: I want to bind a specified port to the CLIENT side of socket in PHP. Can I do this? How to do this? Using socket_bind()? but I dont know what should be set for the address I have googled the solution about this question but no example/solution can be found. Thanks for helping. Comment: @lanzz He doesn't want to listen. He said 'client socket'. 267-633-4682 therefore doesn't apply either. Here is the accepted answer: Look here: http://php.net/manual/en/function.socket-bind.php ```socket_bind ( resource $socket , string $address [, int $port = 0 ] ) ``` So something like: ```socket_bind($socket, 'localhost', 5555); ``` Of course, I don't know what the address of the host is, it might not be localhost. Comment for this answer: I have read the php manual. socket_bind is usually for SERVER side. For CLIENT side, is the address the IP of client? I just want to make sure what should the address is. Comment for this answer: I am a beginner in socket programming. Maybe I have some concept about socket not clear. As described as this picture http://pic.pimg.tw/kezeodsnx/4a83b89243c39.png The server side bind to a ip and port so that it can send and receive data to and from client respectively. The ip of server is likely be fixed because all its client needs to connect only one server(in normal cases). But for client, if I want to specify a port in client side, I guess I should use socket_bind(), which requires 2 parameters ip and port. What is the address of ip in the this socket_bind()?Is the ip address of client? Comment for this answer: But if I have hundreds of clients, then I needs to know the ip of hundreds of clients(I know this can done by some php functions). I am not sure what I thought is true or not so I just come here to understand more about the socket_bind() for client side (I will send the php client code to the clients so the code should be finished before sending the code and should not need to be changed for each clients) Comment for this answer: It can (and should) be used by both SERVER and CLIENT side. How do you create the socket, what is the thing you call "server". How do you want to communicate with that socket. Elaborate if you need better answer. Comment for this answer: On both the server and client you should bind the socket to same ip/port. If the server and client are on the same machine - it would be "267-633-4682", if it's different, you maybe should bind it to the public ip of the server. This is called TCP socket, there are also UNIX sockets. Sockets allow duplex communication between two processes - if you need multiple clients bound to the same socket, you actually need a socket server that will handle every new connection separately. Here is another answer: You can do it if you create the stream yourself with ```stream_context_create``` You will need to use bindto: ``` Used to specify the IP address (either IPv4 or IPv6) and/or the port number that PHP will use to access the network. The syntax is ip:port. Setting the IP or the port to 0 will let the system choose the IP and/or port. ``` So: ```$ctx = stream_context_create(array('socket'=&gt; array('bindto' =&gt; "0:1234"))); ``` Then use the context as you see fit. Comment for this answer: Can I use this with socket created by php socket functions i.e. socket_create()? Comment for this answer: Not socket_create, but functions such as `stream_socket_*` or `fopen`
Title: MongoDb projection on array of objects, Get matched object only Tags: arrays;mongodb;mongodb-query Question: I have mongo document like this ```{ "_id": "5b14679e592baa493e0bc208", "productCode": "ABC", "corridors": [ { "countryNameEn": "Sweden", "countryNameFr": "Suède", "countryCode": "SE", "currencyNameEn": "Swedish Krona", "currencyNameFr": "Couronne suédoise", "currencyCode": "SEK", "corridorLimit": "abc" }, { "countryNameEn": "USA", "countryNameFr": "Suède", "countryCode": "US", "currencyNameEn": "USA", "currencyNameFr": "Couronne suédoise", "currencyCode": "USD", "corridorLimit": "abc" } ] }, { "_id": "5b14679e592baa493e0bc208", "productCode": "XYZ", "corridors": [ { "countryNameEn": "Sweden", "countryNameFr": "Suède", "countryCode": "SE", "currencyNameEn": "Swedish Krona", "currencyNameFr": "Couronne suédoise", "currencyCode": "SEK", "corridorLimit": "abc" }, { "countryNameEn": "USA", "countryNameFr": "Suède", "countryCode": "US", "currencyNameEn": "USA", "currencyNameFr": "Couronne suédoise", "currencyCode": "USD", "corridorLimit": "abc" } ] } ``` I want to find document whose ```productCode``` is ```ABC``` and ```currencyCode``` is ```USD``` in corridors array. How can I return only the matching object from ```corridors``` array like only only object that has ```USD``` ```currencyCode``` should come in result and not all array. I tried running this query ```{ productCode: 'ABC', corridors: { $elemMatch: { currencyCode: "USD"}}}```. But it gives me the whole array and not the only matched element. Comment: refer to this documentation. use $elemmatch in projection https://docs.mongodb.com/manual/reference/operator/projection/elemMatch/ Comment: use it in projection Comment: I am already using $elemmatch Here is another answer: I don't think you can use $elemMatch in $project. Check this Try the following query: ```db.collection.aggregate([ { $match : {"productCode" : "ABC"} }, { $unwind : "$corridors" }, { $match : { "corridors.currencyCode" : "USD"} }, { $group : { _id : "$productCode", corridors : {$addToSet : "$corridors"} } }]); ``` Outputs: ```{ "_id" : "ABC", "corridors" : [ { "countryNameEn" : "USA", "countryNameFr" : "Suède", "countryCode" : "US", "currencyNameEn" : "USA", "currencyNameFr" : "Couronne suédoise", "currencyCode" : "USD", "corridorLimit" : "abc" } ] } ``` In the result you'll have ```_id``` instead of ```productCode```. If you still want ```productCode```, you can just include ```$project``` in the end. Hope this helps! Comment for this answer: You "think" wrong then. The [`$elemMatch`](https://docs.mongodb.com/manual/reference/operator/projection/elemMatch/) operator has two forms, being one for query and the other ( linked one ) for projection. The question has been long answered though and it's preferable to use `$filter` for "multiple matches" than `$unwind` anyway, for a whole host of reasons. But a standard `$elemMatch` or [positional `$` operator](https://docs.mongodb.com/manual/reference/operator/projection/positional/) is all that is needed for a "single" matching result.
Title: What is the fastest way to see battery level in Windows 8 Surface tablet via touch? Tags: windows-8;battery;tablet;microsoft-surface;windows-rt Question: What is the fastest way to use touch to see battery level on a Windows 8 Surface tablet? Currently it seems that I have to go to the lock screen to see battery level, but that is quite a bit of effort to get to and return from. Is there a better way? Here is the accepted answer: Swipe in from the right to access the Charms. It will be in the bottom left next to the time. Comment for this answer: That is fantastic! Quick swipe to see battery, signal strength, and time. Quick swipe again to make it go away. Comment for this answer: Only problem is it doesn't seem to tell you if it's charging and its percentage as a number, even if you try to tap it.
Title: PropertySourcesPlaceholderConfigurer With Specific Value Parser Tags: java;spring;configuration;properties-file Question: I understand that the ```${...}```-notation works as long as it contains references to other properties. However, I want to extend that parsing algorithm. Here's the properties-file: ```connection.http.connectTimeout=15000 #connection.http.readTimeout=${connection.http.connectTimeout} connection.http.readTimeout=%{30*1000} ``` The second line would still work and set ```readTimeout``` to 15000, but I want to make line 3 work. I have to say that I don't care what prefix and postfix I use, the above example uses ```%{...}```, but whatever makes it work is fine with me. ```${...}``` might be the better choice as all the required parsing exists already, but then my new algorithm has to kick in before the usual Spring-stuff. Here's what I have so far: ```@Configuration public class BaseAppConfig { @Bean public static PropertySourcesPlaceholderConfigurer properties(Environment environment) throws IOException { String env = getEnvProperty(environment); PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer(); configurer.setLocations(getPropertiesFiles(env)); configurer.setIgnoreResourceNotFound(true); return configurer; } ``` I tried a fancier ```PropertySourcesPlaceholderConfigurer```, but ```convertPropertyValue()``` is never called: ``` PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer() { @Override protected String convertPropertyValue(String originalValue) { System.out.println("Parse " + originalValue); return super.convertPropertyValue(originalValue); } }; ``` I tried to look into how Spring does its job and it seems that it works with ```PropertyResolver```s. However, I don't see how I could weave one into that. So how would I solve this? Here is the accepted answer: Actually it's quite easy once I knew that Spring's ```RandomValuePropertySource``` was working exactly the way I intended. Within minutes I was able to code a fancy duration configuration like ```connection.connectTimeout=${duration:15s} ``` The missing link then is: ``` @Bean public static PropertySourcesPlaceholderConfigurer properties(Environment environment) throws IOException { AbstractEnvironment standardEnvironment = ((AbstractEnvironment) environment); MutablePropertySources propertySources = standardEnvironment.getPropertySources(); propertySources.addLast(new DurationValuePropertySource()); } ```
Title: Nhibernate mapping clarification wrt Map using entities Tags: nhibernate;nhibernate-mapping Question: When using a mapping such as: ```<class name="Product"&gt; <id name="Id"&gt; <generator class="guid" /&gt; </id&gt; <property name="Name"/&gt; <map name="UserAddedFields" table="UserAddedFields" &gt; <key column="parent_id"/&gt; <index-many-to-many column="UserAddedFieldId" class="UserAddedField"/&gt; <element column="fieldValue"/&gt; </map&gt; </class&gt; ``` And I wanted to add a new UserAddedField to an existing Product I need to first save the UserAddedField or I will get a TransientObjectException. The exception seems to imply I could set a cascade action that would make it autosave but nothing I've tried seems to work. Is this not possible? /////////////////////////////////////////////// After the suggestion below I've changed the mapping to the following but I'm getting a StaleStateException: Batch update returned unexpected row count from update; actual row count: 0; expected: 1 ``` <class name="Product"&gt; <id name="Id"&gt; <generator class="guid" /&gt; </id&gt; <property name="Name"/&gt; <bag name="UserAddedFields" lazy="true" inverse="true" batch-size="25" cascade="all-delete-orphan"&gt; <key column="parentId" /&gt; <one-to-many class="UserAddedFieldSetting" /&gt; </bag&gt; </class&gt; <class name="UserAddedField" &gt; <id name="Id"&gt; <generator class="guid" /&gt; </id&gt; <property name="Name" /&gt; <property name="IsGlobal" type="bool"/&gt; </class&gt; <class name="UserAddedFieldSetting" &gt; <id name="Id"&gt; <generator class="guid" /&gt; </id&gt; <property name="FieldValue" /&gt; <many-to-one class="Product" name="Product" /&gt; <many-to-one class="UserAddedField" name="UserAddedField" cascade="all"/&gt; </class&gt; ``` Here is the accepted answer: As you've already experienced, cascading is not supported on the ```index``` element/mapping. While elements like Map or ManyToOne do support ```cascade```, the ```index-many-to-many``` is just another index, which nature is not intended to be cascade supporting. My suggestion would be: do not use the map. Introduce brand new object instead, represented by table ```UserAddedFields```. If we'd extend it with a surrogated primary key, we can have an object like: ```public class UserAddedFieldSetting { public virtual int Id { get; protected set; } public virtual Product Product { get; set; } public virtual UserAddedField UserAddedField { get; set; } public virtual decimal FieldValue { get; set; } ``` which can be mapped as a ```<bag&gt;```, i.e: ```IList<UserAddedFieldSetting&gt;```. Not only it will support cascading on the ```many-to-one``` mapping of the ```UserAddedField```, but also the querying will be much more simple and straightforward ```<bag name="UserAddedFields" lazy="true" inverse="true" batch-size="25" cascade="all-delete-orphan"&gt; <key column="parent_id" /&gt; <one-to-many class="UserAddedFieldSetting" /&gt; </bag&gt; ``` EXTEND: So, now, we have a mapping (see updated part in the question), which is working as needed - well almost. The issue is, that NHibernate is executing the ```SaveOrUpdate()``` on our ```many-to-one``` relation. The problem here is, how to decide, that ```SaveOrUpdate``` should INSERT or UPDATE? And NHibernate decided to UPDATE by the way... but the row count returned was 0. Because there was in fact no row to update. We need to insert. The key to the answer is in the mapping of the "unsaved value", the value representing the new == "to be inserted" state. So let's extend the mapping: ```<class name="UserAddedField" &gt; <id name="Id" unsaved-value="00000000-0000-0000-0000-000000000000"&gt; <generator class="guid" /&gt; </id&gt; ... ``` And be sure, that every new C# instance of the ```UserAddedField``` has the ```Id = Guid.Empty; ``` Now, NHibernate, when the SaveOrUpdate is called, will know, that ```Guid.Empty``` means do INSERT... Comment for this answer: I've extended the answer, with description what is happening. We only need to learn NHibernate how to correctly decide if the `UserAddeField` is existing *(should be updated due to `cascade`)* or INSERTED Comment for this answer: Thanks for your help, this is exactly what I want, but I still cant seem to get it to work. I've included the mapping I'm using in the original message. Any help on what I'm doing wrong would be greatly appreciated. Comment for this answer: Excellent. Thanks, you nailed it. In my case however, setting unsaved-value was not needed. It was actually UserAddedFieldSetting that was causing the Update/Insert confusion. The mistake was in my test set up, When I created the new UserAddedFieldSetting object I foolishly assigned it an Id.
Title: C++ Is making objects depend on others a good design? Tags: c++;oop Question: I have a basic design that consists of three classes : A Data class, A Holder class wich holds and manages multiple Data objects, and a Wrapper returned by the Holder wich contains a reference to a Data object. The problem is that Wrapper must not outlive Holder, or it will contain a dangling reference, as Holder is responsible for deleting the Data objects. But as Wrapper is intended to have a very short lifetime (get it in a function, make some computation on its data, and let it go out of scope), this should not be a problem, but i'm not sure this is a good design. Here are some solutions i thought about: -Rely on the user reading the documentation, technically the same thing happens with STL iterators -Using shared_ptr to make sure the data lasts long enought, but it feels like overkill -Make Wrapper verify its Holder still exists each time you use it -Any idea? (I hope everyone can understand this, as english is not my native language) Edit : If you want to have a less theoric approach, this all comes from a little algorithm i'm trying to write to solve Sudokus, the Holder is the grid, the Data is the content of each box (either a result or a temporary supposition), and the Wrapper is a Box class wich contains a reference to the Data, plus additional information like row and column. I did not originally said it because i want to know what to do in a more general situation. Comment: Probably the first *and* third option. At least, provide a means to check if the wrapper is "valid". As for the shared_ptr, it isn't so much that it is overkill, but it changes the semantics. The holder no longer is the owner of the objects, and no longer controls their lifetime. So it depends on whether this matches your use-case or not. Comment: "feels like overkill" why is that? Here is the accepted answer: Only ever returning a ```Wrapper``` by value will help ensure the caller doesn't hold onto it beyond the calling scope. In conjunction with a comment or documentation that "Wrappers are only valid for the lifetime of the Holder that created them" should be enough. Either that or you decide that ownership of a ```Data``` is transferred to the ```Wrapper``` when the ```Wrapper``` is created, and the ```Data``` is destroyed along with the ```Wrapper``` - but what if you want a to destroy a ```Wrapper``` without deleting the ```Data```? You'd need a method to optionally relinquish ownership of the ```Data``` back to the ```Holder```. Whichever you choose, you need to decide what owns (ie: is responsible for the lifetime of) ```Data``` and when - once you've done that you can, if you want, use smart pointers to help with that management - but they won't make the design decision for you, and you can't simply say "oh I'll use smart pointers instead of thinking about it". Remember, if you can't manage heap memory without smart pointers - you've got no business managing heap memory with them either! Comment for this answer: In my design i decided that `Holder` would be the class that manages `Data` lifetime, as it makes no sense to make `Wrapper` responsible for this : compare with `st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16vector` and its iterator : `vector` is the `Holder` and iterator is the `Wrapper`. By the way, i'd prefer not to use smart pointers because they force me to use heap memory whereas i could do everything on stack in my situation. But, as i am not making a STL container, would it be recommended to use the same design strategy? ("If you do that it's UB") Comment for this answer: One of the first tidbits in the book Effective c++ is "Always favour the stack", so yes anywhere you can avoid heap allocation, do so. I'd also say that generally if you want to pass an 'alias' to an object on the stack then use a reference *not* a pointer. This means that it's impossible (almost!) to inadvertently try to delete the object. Here is another answer: To elaborate on what you have already listed as options, As you suggested, ```shared_ptr<Data&gt;``` is a good option. Unless performance is an issue, you should use it. Never hold a pointer to ```Data``` in ```Wrapper```. Store a handle that can be used to get a pointer to the appropriate ```Data``` object. Before ```Data``` is accessed through ```Wrapper```, get a pointer the ```Data``` object. If the pointer is not valid, throw an ```exception```. If the pointer is valid, proceed along the happy path.
Title: Why does scrolling a UIWebView *feel* so much different than scrolling any other UIScrollView? Tags: ios;cocoa-touch;uiwebview;uiscrollview Question: I'm building an app that loads in a small amount of simple HTML (locally) into a single full-screen UIWebView. I'm noticing that scrolling this web view feels significantly different than scrolling any other UIScrollView. This does not appear to be a performance or a responsiveness issue, per se... It's just a matter of how the momentum plays out as you drag and flick the web view up and down. It just doesn't feel very "native" (for lack of a better word). It's like scrolling through molasses or pudding... kinda "sticky" and not as "slick" as you would like it to feel. Does anyone know what causes this? Is there any way to fix it, or at the very least make scrolling a UIWebView feel more "native"? Comment: @JackLawrence - The HTML is actually user-generated, pulled from the server periodically, and stored in core data. I could theoretically implement the view with native controls, but it's not as flexible as displaying the user-generated data directly. Comment: What sort of HTML are you displaying? Maybe there's a way to accomplish everything using native controls. Here is the accepted answer: I have the same perception. It must have to do with the webView's scrollView deceleration rate. Just ran this test, and 1) it confirms our suspicion and 2) suggests a fix. I added a scrollView and a webView to my UI then logged the following: ```NSLog(@"my scroll view's decel rate is %f", self.scrollView.decelerationRate); NSLog(@"my web view's decel rate is %f", self.webView.scrollView.decelerationRate); NSLog(@"normal is %f, fast is %f", UIScrollViewDecelerationRateNormal, UIScrollViewDecelerationRateFast); ``` The output confirms the guess about webView being more frictional: ```my scroll view's decel rate is 0.998000 my web view's decel rate is 0.989324 normal is 0.998000, fast is 0.990000 ``` And suggests a fix: ```self.webView.scrollView.decelerationRate = UIScrollViewDecelerationRateNormal; ``` Comment for this answer: @BrentRoyal-Gordon I just stumbled upon this question and i'm wondering: if `normal` scroll deceleration rate is `0.998000` and `fast` is `0.990000` which is lower than `normal`, then shouldn't the `webview` value of `0.989324` which is even lower than `fast` make the scroll even speedier instead of slower? That is, web views being more expensive to render, i would have expected a value larger than `0.998000` for the deceleration rate, not lower. Am i missing something? Comment for this answer: This is fantastic! I hope it works for my project. Thank you. Comment for this answer: It's worth noting that this is done because web views are much more expensive to render than most other views. Making the scrolling "stiffer" helps hide this by ensuring there's less new area to draw when the user scrolls. That's not to say you shouldn't change this if you know a particular web view can handle it, but keep in mind that it *is* being done for a reason and you should make sure it's not a problem for your use case. Comment for this answer: Silky smooth. Just perfect. Thanks! Comment for this answer: Deceleration is an ambiguous term. It makes better sense if you think of it as the magnitude of negative acceleration. Probably applied as v' = v(1-r).
Title: Ubuntu Mate - Not enough space in /boot to update Tags: ubuntu-mate Question: I am running Ubuntu MATE on a Raspberry Pi. It is a pretty fresh install from Ubuntu MATE. I tried to run ```sudo do-release-upgrade``` but received the following message: ``` Not enough free disk space The upgrade has aborted. The upgrade needs a total of 49.5 M free space on disk '/boot'. Please free at least an additional 5,390 k of disk space on '/boot'. You can remove old kernels using 'sudo apt autoremove' and you could also set COMPRESS=xz in /etc/initramfs-tools/initramfs.conf to reduce the size of your initramfs. ``` I tried the suggestions noted in warning to not avail. I referenced this question, but none of it appeared to work either. Running ```dpkg -l | grep linux-image``` returns nothing. Looking at the output of ```df -h```, I understand the problem (there is only 43M available on boot), but what I am less certain of is what I can do to make room. There do not appear to any old kernels, and ```autoremove``` did not work. What else can I do to clean ```/boot``` and make room. Thanks. EDIT: Sorry, I meant to actually show the output of ```df -h```: ``` pi@kb-pi:/boot/grub$ df -h Filesystem Size Used Avail Use% Mounted on /dev/root 15G 4.0G 11G 28% / devtmpfs 459M 0 459M 0% /dev tmpfs 463M 452K 463M 1% /dev/shm tmpfs 463M 13M 451M 3% /run tmpfs 5.0M 4.0K 5.0M 1% /run/lock tmpfs 463M 0 463M 0% /sys/fs/cgroup /dev/mmcblk0p1 63M 21M 43M 34% /boot tmpfs 93M 32K 93M 1% /run/user/1000 ``` Comment: That is a *really* small boot partition, I'd never make one less than 512MB to be honest, any chance you can power down the pi, load up the card in a GUI environment on your computer, resize the partitions around, then try and redo the updates? Because a 64MB boot partition is probably enough for one kernel at most and likely not enough for an update... Here is another answer: You can dynamically increase the size of your boot partition: How to dynamically increase a Linux partition Hope this helps :)
Title: How to properly subclass an existing row Tags: ios;swift;eureka-forms Question: I'm needing help in correctly subclassing an existing row so I can change the UI only, not the function. The type of row I'd like to subclass is TextRow. Again, I only want to change the UI and not the functionality. Eurek mentions here a way to do it but I can't seem to figure out the correct way to do it. I'd like to form rows look like this. The steps according to Eureka: Subclassing cells using the same row Sometimes we want to change the UI look of one of our rows but without changing the row type and all the logic associated to one row. There is currently one way to do this if you are using cells that are instantiated from nib files. Currently, none of Eureka's core rows are instantiated from nib files but some of the custom rows in EurekaCommunity are, in particular the PostalAddressRow which was moved there. What you have to do is: Create a nib file containing the cell you want to create. Then set the class of the cell to be the existing cell you want to modify (if you want to change something more apart from pure UI then you should subclass that cell). Make sure the module of that class is correctly set Connect the outlets to your class Tell your row to use the new nib file. This is done by setting the cellProvider variable to use this nib. You should do this in the initialiser, either in each concrete instantiation or using the defaultRowInitializer. For example: <<< PostalAddressRow() { $0.cellProvider = CellProvider(nibName: "CustomNib", bundle: Bundle.main) } You could also create a new row for this. In that case try to inherit from the same superclass as the row you want to change to inherit its logic. There are some things to consider when you do this: If you want to see an example have a look at the PostalAddressRow or the CreditCardRow which have use a custom nib file in their examples. If you get an error saying ```Unknown class <YOUR_CLASS_NAME&gt; in Interface Builder file```, it might be that you have to instantiate that new type somewhere in your code to load it in the runtime. Calling let t = YourClass.self helped in my case. Basically what I need help with is setting up the correct xib/nib and class to use within the form. Thank you. Comment: What code have you tried so far? Comment: @Carpsen90 I have followed a tutorial to build my own custom classes but it was a lot of work for only wanting to change my UI. I don't want to sublcass Cell and Row and design my own custom cells, I want to subclass an existing TextRow and just change the UI if that makes sense.
Title: Finding carrot seeds in Minecraft PE Tags: minecraft-bedrock-edition Question: I have done some research and know that you can breed pigs with carrots. How do you get carrot seeds to plant carrots? Here is the accepted answer: You need to keep on killing zombies, until you get one from them. Then, plant the carrot in hoed/tiled ground (grass) and wait until it shows orange at the bottom. Finally, harvest it and it should drop 1-3 carrots. Once finished, just repeat steps 2-3 for more carrots Comment for this answer: Useful answer... +1 Here is another answer: In order to get carrots, you must kill a zombie. After you have killed the zombie, you simply till the ground and plant the carrot in the tilled ground. Comment for this answer: I will add a picture if I have some time. Here is another answer: The carrots themselves are the seeds. You can just plant the carrots you have, then they will grow and "duplicate". Source and more information Comment for this answer: Same goes for potatoes, by the way. Comment for this answer: Pat answer... -1 Here is another answer: Unlike Wheat, planting carrots requires that you have carrots already, which is kind of a catch-22 if you have none to start with. Carrots were added to PE in 0.8. (December 2013) as a rare drop from Zombies. Once you have a single carrot, planting it and then harvesting it when fully grown will drop 1-4 carrots, so from that point onward you're likely to get them faster from farming.
Title: Selenium C# - Clicking on hidden checkbox and disabled anchor Tags: c#;selenium;testing;automation Question: The HTML I'm testing has a hidden checkbox (with display set to none) with id "ed_passengers_terms". Followed by a span that has 2 icons inside it. Based on whether or not the checkbox is checked, the icon changes and an anchor is enabled. HTML for checkbox: ```<div class="field checkboxes divider-half color-focus"&gt; <input type="checkbox" id="ed_passengers_terms" name="ed_passengers[terms]" required="required" class="form-control hide" value="1" /&gt; <label for="ed_passengers_terms" class="[ short-label is-adjusted ] label-stack"&gt; <span class="fa-stack"&gt; <i class="icon-checkbox fa-stack-1x sc-grey-2"&gt;</i&gt; <i class="icon-tick text--h6 fa-stack-2x sc-yellow"&gt;</i&gt; </span&gt; </label&gt; <span class="regular text--h6 sc-dark-grey"&gt;I accept SuperCoucou's <a target="_blank" href="/terms"&gt;Terms &amp; Conditions</a&gt;</span&gt; </div&gt; ``` HTML for anchor: ```<a href="#" onclick="$('.ed-book-form').submit();return false;" class="disabled btn btn-action btn-block text-uppercase text--h7 semibold view-details divider-half"&gt;next</a&gt; ``` JavaScript that enables anchor: ```if ($('#ed_passengers_terms').size() &amp;&amp; $('#ed_passengers_terms').is(':checked')) { $('.btn-action').removeClass('disabled'); } $('body').on('change', '#ed_passengers_terms', function() { if ($(this).is(":checked")) { $('.btn-action').removeClass('disabled'); } else { $('.btn-action').addClass('disabled'); } }); ``` I'm trying to create a test that enters some data on that page, then checks the checkbox to be able to click the hyperlink and proceed. I've tried using Click() on the span, the icon, and the div. It didn't work. I've tried: ```((IJavaScriptExecutor)driver).ExecuteScript("$('#ed_passengers_terms').checked = True;"); ``` As a workaround, I thought I might use JavaScriptExecutor to enable the anchor and it does enable it but I can't seem to be able to click it anyway using: ```driver.FindElement(By.CssSelector(".btn.btn-action.btn-block")).Click(); ``` Or using: ```driver.FindElement(By.XPath("//a[contains(.,'Next')]")).Click(); ``` I need a way to be able to do the following: 1 - Preferably click the checkbox, but if that's not possible, I can enable the anchor using JavaScript so it's a non-issue. 2 - Click the anchor so the onClick action gets executed and then it redirects to the correct page. P.S. I do not have access to change the HTML or the JavaScript, it's not my script, I'm only testing it Comment: To clarify, class hide added to the input field with id = "ed_passengers_terms" has display: none; Comment: Exact steps: 1 - Enter some data (no issues there) 2 - Check checkbox with ID ed_passengers_terms - this enables 3 - Click on Comment: I don't see any element within the shared HTML with _with display set to none_. How is the `` tag related to the shared HTML? Can you update the question with the exact _Manual Steps_ you are trying to _Automate_? Here is another answer: This is the solution I found: ```// this removes the hide class from the input which had display set to none ((IJavaScriptExecutor)driver).ExecuteScript("$('#ed_passengers_terms').removeClass('hide');"); // This clicked the checkbox using driver.FindElement(By.Id("id").Click(); didn't work ((IJavaScriptExecutor)driver).ExecuteScript("document.getElementById('ed_passengers_terms').click();"); // This clicked the anchor, using driver.FindElement.Click() didn't work with class or xpath or cssSelector ((IJavaScriptExecutor)driver).ExecuteScript("document.querySelector('.btn.btn-action.btn-block.divider-half').click();"); ``` I am pretty new Selenium (3rd day) but it seems like javascriptexecutor is a bit more reliable from what I've seen so far
Title: How to time out a session state variable in Yii? Tags: php;session;yii Question: I create a state variable in user identity class and and use in one of actions in controller. Before using I want to check if state variable exists. i.e In userIdentity class: ```Yii181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16pp()-&gt;user-&gt;setState('pictures', array());//Want this variable to die after 5 mins ``` In my controller action: ```if(isset(Yii181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16pp()-&gt;user-&gt;pictures)) { //do what I want if state variable picture is set } ``` Is there any way to set timeout for session state variables? I know we can provide session timeouts in config file but that will logout user which is not I want. I just want to unset/destroy state variable 'pictures' after 5 minutues. Any way to do that in Yii? Here is another answer: As I know there is no such built-in mechanism in Yii, so on success login: ```Yii181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16pp()-&gt;user-&gt;setState('pictures', array()); Yii181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16pp()-&gt;user-&gt;setState('logged_time', microtime(true)); ``` before each request ```if (Yii181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16pp()-&gt;user-&gt;hasState('logged_time') &amp;&amp; (microtime(true) - Yii181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16pp()-&gt;user-&gt;logged_time &gt; 300)) { Yii181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16pp()-&gt;user-&gt;setState('pictures', null); // unset pictures state Yii181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16pp()-&gt;user-&gt;setState('logged_time', null); // unset logged_time if necessary } ```
Title: Script not working with changing proj structure Tags: linux;bash;shell;go;sh Question: I have the following file ```make.sh``` which is working on the following project: ```myapp utils run.go auth.go server.go make.sh ``` When I run this script it creates the expected tar and everything is working! ```#!/bin/sh go get ./... rm -r /tmp/myapp rm /tmp/myapp.tar.gz mkdir /tmp/myapp go build -o /tmp/myapp/myapp_mac env GOOS=windows GOARH=amd64 go build -o /tmp/myapp/myapp_win64.exe env GOOS=linux GOARCH=amd64 go build -o /tmp/myapp/myapp cp -R ./resources /tmp/myapp/ cd /tmp tar -czf myapp.tar.gz myapp ``` Now I needed to change the project structure to the following: ```myapp make.sh src utils run.go auth.go server server.go ``` Now when I run the ‘make.sh’ it I got an error: ```can't load package: package myapp: no Go files in /Users/i023333/go/src/myapp ``` Any idea how to adapt it? I try to put the ```make.sh``` inside the ```server folder``` as is and it create the tar but its not valid…any idea what should I change the script here to adopt to the new project structure? EDIT1 Before the structure which is generated is like following ```tmp myapp myapp myapp_mac myapp_win64.exe myapp.tar.gz ``` After trying the script in the answer of ```Charles Duffy``` I got the following ```tmp myapp myapp myapp_mac myapp_win64.exe ``` The tar file is missing, any idea ? Comment: @Flimzy - can you show how please ? Comment: @Flimzy - Its not related to the code at all it just packaging , the code doesn't change it exactly the same , just the project structure changed Comment: @Flimzy - this is the reason that I've tried to move the script to the `server ` folder and it working but I suspect it doesnt watch the `utils` folder and the go files there .... Comment: @CharlesDuffy - Do you mean just remove the word `env`? Comment: btw, the `env` is completely needless. `GOOS=windows GOARH=amd64 go build -o /tmp/myapp/myapp_win64.exe` would do exactly the same thing (setting GOOS and GOARCH environment variables only for the duration of the individual command). Comment: And btw, storing files with hardcoded names in `/tmp` is an actively dangerous practice -- someone else who creates a `/tmp/myapp` symlink or directory of symlinks can force your code to overwrite files that you have permission to but they don't. Comment: Yes, I mean exactly that. Won't fix anything, but it removes one tiny bit of unnecessary inefficiency. Comment: BTW, where is `resources`? It isn't shown in either your old or new directory listings, and it's relevant to the script. Comment: Sorry, the problem, as made plain by the error message, is that there is no go source in your project directory `myapp` now. You can't compile nothing. Try compiling `myapp/util` instead. Here is the accepted answer: To change your script, add the line: ```cd src/server || exit ``` ...before any action which needs to care about the source. Thus: ```#!/bin/sh cd src/server || exit # <--- ADD THIS LINE go get ./... || exit rm -rf /tmp/myapp # aside: using hardcoded names in /tmp is a Really Bad Idea. rm -f /tmp/myapp.tar.gz mkdir -p /tmp/myapp go build -o /tmp/myapp/myapp_mac || exit GOOS=windows GOARH=amd64 go build -o /tmp/myapp/myapp_win64.exe || exit GOOS=linux GOARCH=amd64 go build -o /tmp/myapp/myapp || exit cp -R ./resources /tmp/myapp/ || exit cd /tmp || exit tar -czf /tmp/myapp.tar.gz myapp ``` That said, I would suggest instead writing this as: ```#!/bin/bash basedir=$(cd -- "${BASH_SOURCE%/*}" &amp;&amp; pwd) || exit rm -rf -- "$basedir/build" || exit mkdir -p -- "$basedir/"{build,dist} || exit build() (cd src/server &amp;&amp; GOOS=$1 GOARCH=$2 exec go build -o "$basedir/build/$3") build darwin amd64 myapp_mac || exit build linux amd64 myapp || exit build windows amd64 myapp_win64 || exit if [[ -d "$basedir/resources" ]]; then cp -PR -- "$basedir/resources/." "$basedir/build/resources" || exit fi tar -czf "$basedir/dist/myapp.tar.gz" -C "$basedir/build" . ``` Note: We're operating relative to the script's location, so it works even if run from a different directory (you can run ```./myapp/build```, and it'll set ```builddir``` to the path to ```./myapp```). We're not using ```/tmp``` (if we wanted to do so safely, then we'd have something like ```builddir=$(mktemp -t -d myapp-build.XXXXXX)```, and then ```rm -rf "$builddir"``` at the end). We're using a ```#!/bin/bash``` shebang, which permits extensions such as ```[[ ]]``` and ```$BASH_SOURCE```, instead of ```#!/bin/sh```. Repeated operations are encapsulated in a function. We always die on errors we don't expect (which includes failing to copy ```resources``` if ```resources``` doesn't exist), but don't die on errors we do expect (such as filing to copy ```resources``` because it doesn't exist). The exit status of the script is always the exit status of the last command, so there's no need for explicit error handling there. Comment for this answer: where should I do it and how should it solve the issue of the diffrent structure ? Comment for this answer: HI Thanks , I've tried it and I got the following error `:rm: /tmp/myapp: No such file or directory rm: /tmp/myapp.tar.gz: No such file or directory can't load package: package myapp/src: no Go files in /Users/i023223/go/src/myapp/src` Comment for this answer: Now it dont create the `tar` file in the tmp folder, any idea what could be wrong ? what I did is copy the `make.sh` to 'make1' file to the same place `root project` and execute it exactly your code ... Comment for this answer: the first to errors 'rm' is not critical I guess but the `no Go files...` is more imported how to overcome it ....? Comment for this answer: Thanks 1+ , It now much better it create the folder myapp and there I can find 3 files as before but now the problem is that there is no `tar` file , its not generated , any idea why ? Comment for this answer: Thanks Now its working ! I remove the exit from the cp ..., I can give the bounty in 1 hour and i'll do that :) . just last question . from a best practise point of view how would you write it ? without hardcoded name etc.Thanks a lot sir! Comment for this answer: Thanks Charles, it will be great if you add in the answer the "best practise" script , I want to learn from your example. thank you! Comment for this answer: Thanks, I've test it exaclty as you write and when I put the new `make.sh` in the root folder it create `build` folder under the root folder but it's empty and I got in the terminal following error `tar: Failed to open './dist/myapp.tar.gz' ` any idea how to solve it ? Comment for this answer: I remove the exit from the `cp` line and now it generate the tar in build folder on the root project (also change the `tar -czf "$basedir/build/appcontroller.tar.gz"` to `build` instead `dist`) and the tar was created in size of 200kb instead 10 mb , i've no other idea , maybe you ? Comment for this answer: Thanks a lot it's working :) last question , to make it work i've created the "dist" folder , if I dont do it it will not work. why? Comment for this answer: The difference in the structure is that there's now a `src` directory, and that your code is moved into it. If you do this *before* running `go build`, then the build is now done in the directory with your source. Comment for this answer: Ahh -- I misread the structure. That's... frankly, a bad choice of structures for Go; you should have one subdirectory, and thus one `main`, per utility. Comment for this answer: That said, since the one thing you're compiling is the server, the first line needs to be `cd src/server || exit`, since that's the one piece you're actually compiling. Comment for this answer: If I had to guess, I'd guess that the `cp` of `resources` is failing so it aborts at that step. But I can't fix it since **you haven't answered my question** about where the `resources` directory is in the new structure. (If there is none, remove that whole line). Also, if that *is* the problem, there would be an error; including that error would make it much easier to diagnose. Comment for this answer: so, the usual thing is to have a `build/` directory under the top of your source directory, at the same level as `src/`; to put build products there, and have a `dist/` directory where you put distributable archives (like the tarball) that are produced by a build. If for some reason you don't want to do that, the best-practice way to create temporary directories is with `mktemp`, to get a new and unique one each time (and clean it up when you're done). Comment for this answer: @RaynD, ...added. Comment for this answer: `dist` was intentional. By convention, `build` is where immediate build products go, `dist` is where distributables go. You should be able to `rm -rf build` without deleting your tarballs. (Also, if you modify your script to get your version number, as by retriving it from `git`, then you can create `dist/myapp-${version}.tar.gz` and keep a library of built binaries from different versions). Comment for this answer: As for the immediate issue, that's on account of `BASH_SOURCE` being relative rather than absolute; easily fixed (albeit inefficiently, on account of being on MacOS and not having GNU tools). Comment for this answer: Also, the `|| exit` on the cp line is likewise intentional. You should fix whatever's causing `cp` to fail, not paper over the issue by ignoring the failure. Comment for this answer: Oops -- that's a bug; added `dist` to the `mkdir`. Here is another answer: Your script executes ```go build``` without specifying the packages it needs to compile. By default the ```go``` tool will look for Go source files in the current directory. There are no, since you have moved them elsewhere. Try adding the list of packages at the end of the ```go build``` command. And note, that package names should include the full path relative to the ```GOPATH``` directory. See the documentation here. Comment for this answer: Thanks but i've tried to move the `make.sh` to the `server` folder but it didint works ...not sure how it refer to the 'utils' folder in this case ..., can you please provide example of what your suggestion ? Comment for this answer: Thanks a lot, I did it already (otherwise I get complication error ) and it doesnt work , same issue.....any other idea? Comment for this answer: Btw I not expert in bash scripts , I understand most of it ( didnt created by me...) but not sure about 3 things: 1. `go get ./...` what does the ` ./...` path doing 2. `go build -o` what this exactly do 3. the env `env GOOS` why its needed at all ? Thanks a lot!!! Comment for this answer: @H4xorPL - Thanks! Comment for this answer: In `server.go` try to change to `import "myapp/src/utils"` Here is another answer: this should do it I believe ```#!/bin/sh cd src/server go get ./... rm -rf /tmp/myapp rm -f /tmp/myapp.tar.gz mkdir -p /tmp/myapp go build -o /tmp/myapp/myapp_mac env GOOS=windows GOARH=amd64 go build -o /tmp/myapp/myapp_win64.exe env GOOS=linux GOARCH=amd64 go build -o /tmp/myapp/myapp cd ../.. cp -R ./resources /tmp/myapp/ cd /tmp tar -czf myapp.tar.gz myapp/ ```
Title: JavaFX Exception in Application start method (java.lang.IllegalStateException: Location is not set.) Tags: java;javafx;runtime-error Question: I tried moving my fxml file around but I can't seem to get the right path to my file. Also does my controller have to be in the same package as my fmxl file. I read online I should put my fxml file into the resources folder and that's what I did but it's still not working. My controller is in the UI folder should I move that to the resource folder? ```public class Main extends Application{ public Main() { } private static ArgumentParser argumentParser; private static Stage primaryStage; private static ArgumentResponder argumentResponder; private static UncaughtExceptionLogger uncaughtExceptionLogger; private static Settings settings; /** * The main method, for starting the application. * * <p&gt;See {@link Argument} for the supported arguments.</p&gt; * * @param args arguments given when starting KouChat. */ public static void main(String[] args){ argumentParser = new ArgumentParser(args); argumentResponder = new ArgumentResponder(argumentParser); if (!argumentResponder.respond()) { return; } new LogInitializer(argumentParser.hasArgument(Argument.DEBUG)); // Initialize as early as possible to catch all exceptions uncaughtExceptionLogger = new UncaughtExceptionLogger(); settings = loadSettings(argumentParser); launch(args); } private static Settings loadSettings(final ArgumentParser argumentParser) { final Settings settings = new Settings(); final ArgumentSettingsLoader argumentSettingsLoader = new ArgumentSettingsLoader(); argumentSettingsLoader.loadSettings(argumentParser, settings); final PropertyFileSettingsLoader propertyFileSettingsLoader = new PropertyFileSettingsLoader(); propertyFileSettingsLoader.loadSettings(settings); return settings; } @Override public void start(Stage primaryStageObj) throws Exception{ primaryStage = primaryStageObj; System.out.println(getClass().getResource("Chat.fxml")); FXMLLoader loader = new FXMLLoader(getClass().getResource("Chat.fxml")); ChatController pls = new ChatController(argumentParser, settings, uncaughtExceptionLogger); loader.setController(pls); pls.setStage(primaryStage); Parent root = loader.load(); primaryStage.setTitle("Flake"); primaryStage.setScene(new Scene(root, 959,583 )); primaryStage.setResizable(false); primaryStage.show(); primaryStage.setResizable(false); primaryStage.setOnCloseRequest(e -&gt; Platform.exit()); } } ``` This is my project path to help see where I am going wrong The error message I am receiving when running my code. ```Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389) at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767) Caused by: java.lang.RuntimeException: Exception in Application start method at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917) at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$154(LauncherImpl.java:182) at java.lang.Thread.run(Thread.java:748) Caused by: java.lang.IllegalStateException: Location is not set. at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2434) at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2409) at net.usikkert.kouchat.Main.start(Main.java:71) at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$161(LauncherImpl.java:863) at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$174(PlatformImpl.java:326) at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295) at java.security.AccessController.doPrivileged(Native Method) at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294) at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95) at com.sun.glass.ui.win.WinApplication._runLoop(Native Method) at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177) ... 1 more Exception running application net.usikkert.kouchat.Main ``` Comment: @James_D I added the leading / but I still get the same error. How do i check if my resources folder is configured properly. Comment: When i do this: `System.out.println(getClass().getResource("/Chat.fxml"));` I still get null Comment: @James_D i am still new to this what exactly is the build folder and how do i get to this. Are you talking about my target folder? Because if so I don't see my fxml files in there just my regular classes and interfaces Comment: @James_D Yes i see the other contents of my resources folder. Mabye its because im converting from swing to javafx? Comment: @James_D I'm using intellij, can i just move my fxml to my main folder and try to run it from there? I dont know how to configure which files are deployed by the resources folder Comment: Okay Thank you so much for your help! Comment: @FruitCode are you using maven? This error often occurs when you are using maven and even if you put the `.fxml` file right next to the Main class or wherever you load it, it doesn't find it. If this is the case I think I know how to solve it. If you are not using maven then it should work relative simply. Probably you should play with the path, like adding a "/" or "." or carefully spelling the file's name. In IntelliJ if you are holding Ctrl and mouseover the "Chat.fxml" it should be highlighted and "clickable" if it is not, then there is a problem. Comment: Assuming your `resources` folder is configured as expected (i.e. that the contents go to the root of the classpath), your `Chat.fxml` file will be in the classpath root. `getClass().getResource()` searches relative to the current class, so it will look in the `net.usikkert.kouchat` package. To search in the root of the classpath, use `getClass().getResource("/Chat.fxml")` (with a leading `/`). Comment: Check the build folder and see if `Chat.fxml` is there, and if so, which folder it is in. Comment: Target folder sounds right. (The folder names depend on the IDE/build tool.) The folder that has the hierarchy where the class files end up. Are the other contents of the resources folder deployed there? Comment: So clearly somewhere you must have configured which files (or types of files) are deployed from the resources folder. I'd right-click on it and look for a configuration/properties option. This just looks IDE specific. Comment: I don't know: I don't use IntelliJ. But it seems that if you have a separate resources folder for resources that are not compiled, that would be the natural place to put an FXML file.
Title: Notify when any app launched irrespective of launcher app we are using Tags: android;android-intent;android-activity;android-framework Question: How can i notify or know when any android app get launched? If i want to know the app launch state i can know if i put log in package/apps/launcher/...../Launcher.java, but control do not come here if we are using another launcher app. I searched a lot but i did not find solution. They are saying we can not get app launch events in android. Please tell me the process in framework when any app launched or resumed or destroyed. I have seen some solution like reading Log, but that is restricted from jellybean and that is not at all my intention Apps like app lock are doing this work even in Jellybean,kitkat and higher Any help would be appreciated.
Title: Timers not creating a delay Tags: actionscript-3;actionscript;air Question: I'm creating a program in Adobe Animate; one of functions is sending OSC messages to a DMX lighting program to change the lighting in the room. The standard changes are working as expected, but I'm having trouble with the "fades". I need to send a series of OSC messages in succession. What I have now is Adobe Animate creating series of timers through an independent function. What I feel I need is a delay feature, but I know this isn't possible in AS3. ```function fadeFixtureData(fixture:int, rgbStart:Array, rgbEnd:Array, intervals:int):void { if (rgbStart.length != rgbEnd.length) { return void; } var rgbCalculated:Array = new Array(); for (var i = 0; i <= intervals; i++) { for (var j = 0; j < rgbStart.length; j++) { rgbCalculated[j] = ((((rgbEnd[j] - rgbStart[j])/intervals) * (i)) + rgbStart[j]); } delayedFunctionCall((i * 33), function(e:Event) {sendFixtureData(fixture,rgbCalculated);}); trace(i * 33); trace(rgbCalculated); } } function delayedFunctionCall(delay:int, func:Function) { var timer:Timer = new Timer(delay, 1); timer.addEventListener(TimerEvent.TIMER, func); timer.start(); } ``` The program seems to be tracing everything correctly, but the result is that all the messages are being sent at the same time. Only the last message is relayed to the lighting program. Comment: You cannot create an anonymous dynamic function that you plan to be dependent on the for loop counter. This is not Javascript to allow such things, sorry. Here is another answer: There are two ways I would suggest. Both methods should let you interrupt any fade with a new one. So halfway through a fade out, you might change your mind and want to fade on again (if this was for example, based on human interaction). To achieve that, in these examples you just fire ```fadeTo(yourValue)``` again, as needed. The EnterFrame approach: ```public class Main extends Sprite { private var targetValue:Number; private var currentValue:Number = 0; private var increment:Number; private static const MAX_VALUE:int = 255; private static const FADE_TIME:Number = 5; // Seconds for a full fade from 0% to 100%. public function Main() { increment = MAX_VALUE / (stage.frameRate * FADE_TIME); // Dynamically calculate based on app framerate. addEventListener(Event.ENTER_FRAME, enterFrameHandler); // Initiate a fade. fadeTo(1); } /** * Initiates fade. * @param percentage A value between 0 and 1. 0 being off, 1 being full on, 0.5 as an example, being 50% brightness. */ private function fadeTo(percentage:Number):void { if (percentage &gt; 1) percentage = 1; if (percentage < 0) percentage = 0; targetValue = MAX_VALUE * percentage; } private function enterFrameHandler(e:Event):void { if (currentValue == targetValue) return; // No updates required. if (currentValue < targetValue) { currentValue+= increment; if (currentValue &gt; targetValue) currentValue = targetValue; } else { currentValue-= increment; if (currentValue < targetValue) currentValue = targetValue; } doRGBThing(currentValue); } private function doRGBThing(currentValue:Number):void { trace(int(currentValue)); // Replace this with your OSC related code. } } ``` The Tween approach (like GreenSock's TweenLite): ```public class MainTween extends Sprite { private var currentValueObj:Object = {currentValue: 0}; private static const MAX_VALUE:int = 255; private static const FADE_TIME:Number = 5; // Seconds for a full fade from 0% to 100%. public function MainTween() { // Initiate a fade. fadeTo(1); } /** * Initiates fade. * @param percentage A value between 0 and 1. 0 being off, 1 being full on, 0.5 as an example, being 50% brightness. */ private function fadeTo(percentage:Number):void { if (percentage &gt; 1) percentage = 1; if (percentage < 0) percentage = 0; TweenLite.killTweensOf(currentValueObj); TweenLite.to(currentValueObj as Object, FADE_TIME, {currentValue: MAX_VALUE * percentage, onUpdate: doRGBThing}); } private function doRGBThing():void { trace(currentValueObj.currentValue); } } ``` Here is another answer: You can use ```setTimeOut``` instead. ```var myTm = setTimeOut(delay, 1000); // in milliseconds function delay(): void { // your delayed code } ```
Title: Why doesn't C++ have a pointer to member function type? Tags: c++;function;pointers;member Question: I could be totally wrong here, but as I understand it, C++ doesn't really have a native "pointer to member function" type. I know you can do tricks with Boost and mem_fun etc. But why did the designers of C++ decide not to have a 64-bit pointer containing a pointer to the function and a pointer to the object, for example? What I mean specifically is a pointer to a member function of a particular object of unknown type. I.E. something you can use for a callback. This would be a type which contains two values. The first value being a pointer to the function, and the second value being a pointer to the specific instance of the object. What I do not mean is a pointer to a general member function of a class. E.G. ```int (Fr181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16*)(char,float) ``` It would have been so useful and made my life easier. Hugo Comment: um i _did_ read the question fully Comment: I think what you are looking for might be in these librairies... Fast Delegates [http://www.codeproject.com/KB/cpp/FastDelegate.aspx](http://www.codeproject.com/KB/cpp/FastDelegate.aspx) Boost.Function [http://www.boost.org/doc/libs/1_37_0/doc/html/function.html](http://www.boost.org/doc/libs/1_37_0/doc/html/function.html) And here is a very complete explanation of function pointer related questions [http://www.parashift.com/c++-faq-lite/pointers-to-members.html](http://www.parashift.com/c++-faq-lite/pointers-to-members.html) Comment: No. If you read the question fully, you'd see that I'm talking about a function pointer which contains *both* a pointer to the function *and* as pointer to the object. Something which I can use as a *callback*. Comment: c++ does have pointer to member function. check the below link. http://www.parashift.com/c++-faq-lite/pointers-to-members.html Comment: Note that C++11 does effectively have such a pointer: `st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16function`, obtained from `st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16bind`. Here is the accepted answer: @RocketMagnet - This is in response to your other question, the one which was labeled a duplicate. I'm answering that question, not this one. In general, C++ pointer to member functions can't portably be cast across the class hierarchy. That said you can often get away with it. For instance: ```#include <iostream&gt; using st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16cout; class A { public: int x; }; class B { public: int y; }; class C : public B, public A { public: void foo(){ cout << "a.x == " << x << "\n";}}; int main() { typedef void (181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16*pmf_t)(); C c; c.x = 42; c.y = -1; pmf_t mf = static_cast<pmf_t&gt;(&amp;181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16foo); (c.*mf)(); } ``` Compile this code, and the compiler rightly complains: ```$ cl /EHsc /Zi /nologo pmf.cpp pmf.cpp pmf.cpp(15) : warning C4407: cast between different pointer to member representations, compiler may generate incorrect code $ ``` So to answer "why doesn't C++ have a pointer-to-member-function-on-void-class?" is that this imaginary base-class-of-everything has no members, so there's no value you could safely assign to it! "void (181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16)()" and "void (voi181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16)()" are mutually incompatible types. Now, I bet you're thinking "wait, i've cast member-function-pointers just fine before!" Yes, you may have, using reinterpret_cast and single inheritance. This is in the same category of other reinterpret casts: ```#include <iostream&gt; using st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16cout; class A { public: int x; }; class B { public: int y; }; class C : public B, public A { public: void foo(){ cout << "a.x == " << x << "\n";}}; class D { public: int z; }; int main() { C c; c.x = 42; c.y = -1; // this will print -1 D&amp; d = reinterpret_cast<D&amp;&gt;(c); cout << "d.z == " << d.z << "\n"; } ``` So if ```void (voi181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16*)()``` did exist, but there is nothing you could safely/portably assign to it. Traditionally, you use functions of signature ```void (*)(void*)``` anywhere you'd thing of using ```void (voi181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16*)()```, because while member-function-pointers don't cast well up and down the inheritance heirarchy, void pointers do cast well. Instead: ```#include <iostream&gt; using st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16cout; class A { public: int x; }; class B { public: int y; }; class C : public B, public A { public: void foo(){ cout << "a.x == " << x << "\n";}}; void do_foo(void* ptrToC){ C* c = static_cast<C*&gt;(ptrToC); c-&gt;foo(); } int main() { typedef void (*pf_t)(void*); C c; c.x = 42; c.y = -1; pf_t f = do_foo; f(&amp;c); } ``` So to your question. Why doesn't C++ support this sort of casting. Pointer-to-member-function types already have to deal with virtual vs non-virtual base classes, and virtual vs non-virtual member functions, all in the same type, inflating them to 4*sizeof(void*) on some platforms. I think because it would further complicate the implementation of pointer-to-member-function, and raw function pointers already solve this problem so well. Like others have commented, C++ gives library writers enough tools to get this done, and then 'normal' programmers like you and me should use those libraries instead of sweating these details. EDIT: marked community wiki. Please only edit to include relevant references to the C++ standard, and add in italic. (esp. add references to standard where my understanding was wrong! ^_^ ) Comment for this answer: Rocket - you can still overload it. Consider [[ class C { public: virtual void foo(); }; ]]. Classes derived from C can use 'do_foo' as their function pointer value still. [[ D d; something( do_foo, static_cast(&d) ); ]] Comment for this answer: Pointers to members need to be big, exactly _because_ they are unbound. As soon as you bind it to an object, you have the objects vtable(s). Comment for this answer: Thanks. This reply makes the most sense. As I see it, the one problem preventing it is the need for other classes to be able to overload that callback function. Perhaps if overloading callbacks was disallowed it would be possible... Here is another answer: I think that the answer is that the designers of C++ choose not to have in language the things that could be just as easily implemented in a library. Your own description of what you want gives a perfectly reasonable way to implement it. I know it sounds funny, but C++ is a minimalistic language. They did leave to libraries all they could leave to them. Here is another answer: As others pointed out, C++ does have a member function pointer type. The term you were looking for is "bound function". The reason C++ doesn't provide syntax sugar for function binding is because of its philosophy of only providing the most basic tools, with which you can then build all you want. This helps keep the language "small" (or at least, less mind bogglingly huge). Similarly, C++ doesn't have a lock{} primitive like C#'s but it has RAII which is used by boost's scoped_lock. There is of course the school of thought that says you should add syntax sugar for everything that might be of use. For better or worse, C++ does not belong to that school. Here is another answer: It does. For example, ```int (Fr181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16*)(char,float) ``` is a pointer to a member function of a class ```Fred``` that returns an ```int``` and takes a ```char``` and a ```float```. Comment for this answer: @ZachHirsch This is a member function *pointer* type. Is there a member function type? (By the way there is function and function pointer type.) Comment for this answer: I guess he meant a pointer to a member function of ANY class (possibly a member of NO class) as long as the parameters other than the implicit "this" pointer have the same types. Comment for this answer: That's only a pointer to the function, isn't it? So it's not what Hugo means. He means something like delegate types in .NET. Here is another answer: C++ is already a big language, and adding this would have made it bigger. What you really want is even worse than just a bound member function, it's something closer to boost181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16unction. You want to store both a ```void(*)()``` and a pair for callbacks. After all, the reason is that you want the give the caller a complete callback, and the callee should not care about the exact details. The size would likely be ```sizeof(void*)+sizeof(void(*)())```. Pointers to member functions can be bigger, but that is because they are unbound. They need to deal with the possibility that youre' taking the address of a virtual function, for instance. However, a built-in bound-pointer-to-member-function type would not suffer from this overhead. It can resolve the exact function to be called at the moment of binding. This is not possible with a UDT. boost181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16unction cannot discard the overhead of a PTMF when it binds the object pointer. You need to know understand structure of a PTMF, vtable, etcetera - all non-standard stuff. However, we might get there now with C++1x. Once it's in st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16, it's fair game for compiler vendors. The standard library implementation itself is not portable (see e.g. type_info). You'd still want to have some nice syntax, I guess, even if a compiler vendor implements this in the library. I'd like ```st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16function<void(*)()&gt; foo = &amp;myX &amp;&amp; X181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16r```. (It doesn't clash with existing syntax, as X181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16r is not an expression - only &amp;X181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16r is) Here is another answer: The issue is surely not the basics of having an object pointer and a function pointer in one easy-to-use package, because you could do this using a pointer and a thunk. (Such thunks are already used by VC++ on x86 to support pointers to virtual member functions, so that these pointers only take up 4 bytes.) You might end up with a lot of thunks, it's true, but people already rely on the linker to eliminate duplicate template instantiations -- I do, anyway -- and there's only so many vtable and this offsets you'll end up with in practice. The overhead would probably not be significant for any reasonably-sized program, and if you don't use this stuff then it won't cost you anything. (Architectures that traditionally use a TOC would store the TOC pointer in the function pointer part, rather than in the thunk, just as they would have to do already.) (This new type of object would not be exactly substitutable for a normal pointer to function, of course, because the size would be different. They would, however, be written the same at the call point.) The problem that I see is that of the calling convention: supporting pointers to functions this way might be tricky in the general case, because the generated code would have to prepare the arguments (this included) the same way without regard to the actual type of thing, function or member function, to which the pointer points. This is probably not a big deal on x86, at least not with thiscall, because you could just load ECX regardless and accept that if the calling function doesn't need it then it will be bogus. (And I think VC++ assumes ECX is bogus in this case anyway.) But on architectures that pass arguments for named parameters in registers to functions, you may end up with a fair amount of shuffling in the thunk, and if stack arguments are pushed left-to-right then you're basically stuffed. And this can't be fixed up statically, because in the limit there's no cross-translation-unit information. [Edit: MSalters, in a comment to rocketmagnet's post above, points out that if both object AND function are known, then the this offset and so on can be determined immediately. This totally didn't occur to me! But, with this in mind, I suppose there need only be stored the exact object pointer, maybe offset, and the exact function pointer. This makes thunks totally unnecessary -- I think -- but I'm pretty sure that the issues of pointing to member functions and non-member functions alike would remain.] Comment for this answer: Yes, if you restrict your delegates to always refer to bound member functions, it's no problem. Strikes me it would be better to be able to support both member functions and non-member functions, though. Mind you, perhaps this is just over-generalization. I don't have a specific use case in mind. Comment for this answer: Thanks for your helpful answer. Re: last 2 paras, assuming the arguments are always the same, this shouldn't be a problem. E.G. the type of the pointer would be declared to be a member function pointer taking int and returning int. Any object with a int foo(int) member function could pass that ptr. Here is another answer: The TR1 has st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16tr181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16function, and it will be added to C++0x. So in a sense it does have it. One of the design philosophies of C++ is: you don't pay for what you don't use. The problem with C# style delagates is they are heavy and require language support, that everyone would pay for whether they used them or not. That is why the library implementation is preferred. The reason delegates are heavy is that a method pointer is often larger than a normal pointer. This happens whenever the method is virtual. The method pointer will call a different function depending on what base class uses it. That requires at least two pointers, the vtable and the offset. There is other weirdness involved with the method is from a class involved in multiple inheritance. All that said, I am not a compiler writer. It may have been possible to make a new type for bound method pointers that would subvert the virtual-ness of method referenced (after all we know what the base class is if the method is bound).
Title: "Skip Intro" link over HTML5 video not working on iPad Tags: ipad;html;html5-video Question: I am using the "Javascript Fake Click" script to autoplay an introductory HTML5 video on an iPad, which then directs to a landing page. I have a simple "skip intro" link on top of the video element in a higher z-index. This link works in other browsers, but not on the iPad (iOS 3.2.2). I think it may have to do with the click event on a video on the iPad defaulting to pause/play the video. Any ideas on how to get around this? Here is the accepted answer: This may be the same problem I had. The video tag will capture all the events when the controls attribute is added to the video tag.. Try removing the controls attribute... Here is another answer: I made something like that. I used this function: ``` function videoEnd() { $('#mainVideo').fadeOut('slow'); window.location = "/home.aspx"; } ``` Works fine on the iPAD. Here is another answer: As far as I know, the javascript hack doesn't work on iOS 4 and above. Apple forces all videos on iOS to start only from user input, so "autoplay" doesn't work either. If you remove the "controls" attribute, the video won't even start playing. What you're trying to accomplish isn't acctually possible (considering all the iOS versions...)
Title: Wordpress on Chrome for iOS 9 can't display responsive tables for mobile, td always has display: table-cell Tags: ios;css;wordpress Question: On Chrome for iOS 9 (iPhone 5) I can't display responsive tables for mobile, it always sets display style attribute for td as { display: table-cell }. I want every td to be on separate line, to behave as a row - it already works fine like this on all browsers on desktop, even Chrome - when I stretch it so it is small on the monitor. It looks fine on chrome developer tools in all mobile modes. It looks fine on saucelabs mobile phone simulator too. When I save this page (cache it), and try to see it on Chrome for iOS on iPhone, it displays properly - each td on its own line (looks as a separate row). I suspect it's the wordpress that does some tinkering, since cached version displays fine. I am banging my head for hours and hours on this with no success. Things I tried to fix it (all tries have failed) so it displays responsively (style for td has display: block;) on my iPhone: 1. Added at the beginning of file, 2. Added display: block; clear: both; inline at the html-element-tag-level, 3. I clear cache and add javascript for alerting the css("display") and it still outputs the table-cell, 4. Add the id-s for each of the td-s and add 'display: block' to these specific td-s through external CSS, 5. Add piece of javascript that will change all td's 'display' to be 'block' ($("td").css("display","block"); ) whenever a select field is changed - works on cached version but not on my live version, 6. I can do the same thing from 5. (see above) to change display to none, but not to block! If I remember what else I tried, I will update the question. Here is the accepted answer: This seems to be resolved on iOS9 new version. I can no longer replicate it on Firefox for iOS 9.2.1 nor Chrome for iOS 9.2.1. Comment for this answer: I can still replicate it on iOS 7 though.
Title: Elimnar un evento programado en android Tags: java;android Question: Buenas tardes, estoy programando un ```spinner``` que sale con una bandera que tengo. si el usuario hace un gesto o un click en la pantalla saco un ```progressDialog```. Mi cuestión es como anulo el segundo click para que no me haga el evento al cual le di click ya trate con el ```getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE); ``` pero con esto ya no me serviría el segundo click que muestra el ```progressdialiog```. Estoy tratando de saber como eliminar la pila de eventos que están programados en caso tal que se active la segunda acción. Para capturar el evento estoy utilizando un ```dispatchTouchEvent``` muchas gracias Comment: podrias ser un poco mas detallado?, no se entiende que quieres lograr Comment: Podria ser esto? http://stackoverflow.com/questions/5195321/remove-an-onclick-listener Comment: Podrías detallar un poco tu pregunta, al dar clic al spinner se abre un dialogo y donde deseas ya no puedas realizar clic? Here is the accepted answer: No entiendo demasiado la pregunta, pero si la idea es activar o desactivar la funcionalidad del boton puedes realizar una instancia del spinner con java mediante un casting a spinner del metodo findviesbyid y entroducirle la id de R.id."el nombre del componente" por parametro. Entonces, el objeto spinner posee el metodo addOnClickListener para agregar eventos, el cual recibe una interfaz por parametro, la cual si es null, no provocara que no haga nada. Si necesitas que no haga nada solo cuando ya se ha pulsado puedes añadirle y elminarle el evento on click con el oyente de foco. Suerte!
Title: .NET Memory Consumption Question Tags: .net;memory-management Question: Does either of these methods use more memory than the other or put a larger load on GC? Option #1 ```LargeObject GetObject() { return new LargeObject(); } ``` Option #2 ```LargeObject GetObject() { LargeObject result = new LargeObject(); return result; } ``` Here is the accepted answer: The compiler will generate IL that's equivalent to version 2 of your code, a virtual stack location is needed to store the object reference. The JIT optimizer will generate machine code that's equivalent to version 1 of your code, the reference is stored in a CPU register. In other words, it doesn't matter. You get the exact same machine [email protected]. Here is another answer: You could look at the IL generated (using reflector) and see if it [email protected]. Depending on the compilation optimization settings, #2 might store an extra value on the stack (for the ```result``` value), but that will only be an extra 4 or 8 bytes (if it's a class, which it should be!), and will not affect the [email protected]. Comment for this answer: Yes, but if the IL is the same, then the code will do exactly the same thing. Comment for this answer: The IL isn't the compiled code though. It's only an intermediary step. Here is another answer: The heap memory usage of both methods is equal. There is tiny overhead in creation of the local variable in the second case but it shouldn't bother you. Variable will be stored on the stack and won't cause any additional pressure for GC. Also this additional variable might be optimized by the compiler or JIT (so it maybe not present in the code actually being executed by CLR). Comment for this answer: It's unlikely that there will be any difference in the generated code in release mode. The JIT compiler will almost certainly remove the unnecessary temporary variable.
Title: Google Places JS: Exact Match Tags: javascript;google-places-api Question: i'm using google places to find nearby places by type, for example: ```placeService.nearbySearch({ location: { lat: lat, lng: lng }, radius: radius, type: 'hospital' }); ``` This query return also private clinics that i don't want to include in my results. I tried using the parameter "name" with "hospital" but no luck. How can i limit the query to search only for hospitals (strict meaning) Response example (the first one is the clinic): ```[ { "geometry": { "location": { "lat": lat, "lng": lng } }, "icon": "https://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png", "id": "b5999bf0dd4430fb9727d646124786d65d9b3598", "name": "Private Clinic", "opening_hours": { "open_now": true, "weekday_text": [] }, "place_id": "ChIJddQneTymMRMRv2A_Sl2z6Pk", "reference": "CmRSAAAAL92d4D0kBQ6OBL-S7sNok47bUoJrW0fBRpfvfOwQMH6lLY7qYFT6TsCfOonjjM8Ga5McGz10-sxpVNOO_a3llvkUE98ny_xaVPKs46hyQuld_GwqWQQ5FcGc6XMj1_eOEhCQn0JPeNTi8cQHLjnxe3xSGhQAI18uipgHZyx-myoOjCRYMMEfmw", "scope": "GOOGLE", "types": [ "hospital", "doctor", "health", "point_of_interest", "establishment" ], "vicinity": "Address", "html_attributions": [] }, { "geometry": { "location": { "lat": lat, "lng": lng } }, "icon": "https://maps.gstatic.com/mapfiles/place_api/icons/doctor-71.png", "id": "ff2075175d3d83fff78113c06029e8ead3b4b1a5", "name": "Hospital", "opening_hours": { "open_now": true, "weekday_text": [] }, "place_id": "ChIJHU7OI-ClMRMR4n9sWIPONLw", "rating": 3.7, "reference": "CmRSAAAA5J6mz42nH9AZX8hkst-Yh8XTLkb6jD54yWoUYTEnL0t47aWnJKTdop4qmRz2pO71OrtVmx_4mRxVQnezzy-uqx--82qKrTHQ0O2rK0BzbItwiHx8aUEp--EqLfEGQDYoEhA4jyOlEAwD2GJjkP21UbzhGhT1Te6iOF0nbcgWgMeZpIfEd1SC0Q", "scope": "GOOGLE", "types": [ "hospital", "point_of_interest", "establishment" ], "vicinity": "Address", "html_attributions": [] } ] ``` Comment: You need to filter the results yourself. Post a comprehensive sample of the results if you want help filtering them. Comment: How does the term "privacy" apply to publicly available address entries for public institutions/companies? Besides, you wanted a way to filter by name, maybe taking out the names wasn't the best idea. ;) Comment: Anyway, what you want to look into is the `Array#filter` method. Try things like *"filter the result array for items with `"Hospital"` in their name"*. Or *"filter the result array for items that do not have `"doctor"` as one of their categories"*. Maybe the latter is more resilient than the former. It all comes down to how consistent Google's place data is. Comment: It's impossible to help you since you don't show your current code. However, your question is no so much *"How can I do $thing with Google Maps?"* anyway. It's *"How do I filter down a list of objects in Javascript?"* and that question has been answered countless times on this site and elsewhere, have a look around. Comment: Yeah, there seems to be no way to make Google pre-filter the results you want. You must refine the results yourself. Comment: @Tomalak i've posted the example. The first one is the clinic that i don't want to include, the second one is a good match. I removed the name, address and location for privacy. Comment: @Tomalak you're right but the filter by name is just a try that i've done.. i'm open to every suggestions. Comment: @Tomalak uhm ok, i agree about the last one (i'm already applying a filter on the property "types", checking that the first position is "hospital" but i don't know if there is a more "robust" way to do it) Comment: @Tomalak my question is about google places and how to query in a more accurate way. But it seems that there is no way to do it so i have to filter the response and "this" is about javascript, not my question :). Anyway, thanks for your time.
Title: Retrieve two data ID using only one condition Tags: mysql;sql;asp.net;vb.net;for-loop Question: I have this program that 'should' retrieve two data ID using only one condition. This is my code. Thanks. ```Dim coys As String() = {"COY = 'A' AND COY = 'B'", "COY = 'C' AND COY = 'D'", "COY = 'E' AND COY = 'F'", "COY = 'G' AND COY = 'H'"} Dim sec As String() = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", _ "U", "V", "W", "X", "Y", "Z", "A2", "B2", "C2", "D2", "E2", "F2", "G2", "H2", "I2", "J2", "K2", "L2", _ "M2", "N2", "O2", "P2", "Q2", "R2", "S2", "T2", "U2", "V2", "W2", "X2", "Y2", "Z2"} For x As Integer = 0 To coys.Length - 1 cn.Open() Dim cmd As String = "SELECT a1, a2 a3, COY FROM AA WHERE " &amp; coys(x) &amp; " AND a5 = '" &amp; class2.SelectedValue &amp; "' ORDER BY COY, a2" Dim adp As SqlDataAdapter = New SqlDataAdapter(cmd, cn) adp.Fill(dt) GridView2.DataSource = dt GridView2.DataBind() cn.Close() Dim cnt As Integer = dt.Rows.Count For i As Integer = 0 To numsec2.SelectedValue - 1 Dim vHeader As String = sec(i) If Not dt.Columns.Contains(vHeader) Then Dim f As New Data.DataColumn(vHeader, GetType(System.String)) dt.Columns.Add(f) f.AllowDBNull = True End If Next Next ``` If I use OR in the coys() array it shows all of the data without acknowledging the second condition, and if I use AND in the coys() array it does not work. Here is the accepted answer: Use the ```OR``` condition and put it in ```()```, in this way it will honor the second condition: ```Dim coys As String() = {"(COY = 'A' OR COY = 'B')", "(COY = 'C' OR COY = 'D')", "(COY = 'E' OR COY = 'F')", "(COY = 'G' OR COY = 'H')"} ```
Title: Issues with objects passing through each other in Unity Tags: unity3d Question: I was creating a simulation that involved a rotating bucket drum that is supposed to go through rough soil. To simulate this, I made a project in Unity and imported that CAD design of the drum and added in a bunch of spheres for the dirt. Then, I added a mesh collider to the drum, sphere colliders to the dirt, and rigidbodies to everything. I also turned on the continuous dynamic collision detection on both the dirt and the drum, and made sure to turn of isTrigger and isKinematic in both. But whenever I run the sim, the same issue pops up: the spheres just go directly through the drum and nothing I can do will fix it. I've tried looking at other threads but all of those solutions don't work. Can I get some help? Thanks. Image of the drum before colliding with the spheres Image of the drum in the middle of the spheres with nothing disturbed Image of the components on the rotating drum Image of the components on the spheres (All of them have the same setup) Code: ```using System.Collections; using System.Collections.Generic; using UnityEngine; public class RotateScript : MonoBehaviour { public float thrust = 0.1f; public float torque = 0.5f; public Rigidbody rb; void Start() { rb = GetComponent<Rigidbody&gt;(); rb.AddForce(0, 0, -thrust, ForceMode.Impulse); } private void FixedUpdate() { float turn = Input.GetAxis("Horizontal"); rb.AddTorque(transform.up * torque * turn); if(Input.GetKeyDown(KeyCode.W)) { rb.AddForce(0, 0, (thrust * 2), ForceMode.Impulse); } if(Input.GetKeyDown(KeyCode.S)) { rb.AddForce(0, 0, (-thrust * 2), ForceMode.Impulse); } } } ``` Comment: Perhaps try making the mesh collider convex. Mesh colliders can't interact with anything if they aren't convex Comment: What are the settings for the rigidbodies on the dirt? From the image it looks like they're all floating in midair which suggests to me that you may have frozen their position. Comment: Just found a [link](https://docs.unity3d.com/ScriptReference/Rigidbody-collisionDetectionMode.html) that states: "Continuous Collision Detection is only supported for Rigidbodies with Sphere-, Capusle- or BoxColliders." This means that your dirt spheres can't detect the mesh collider on the rotating bucket drum. Try switching the collision detection mode to discrete for all the objects. Comment: Just to narrow things down, try changing the bucket drum's collider to a box collider and see if they can interact then. If they can interact then the problem is likely with the mesh collider, if they still can't interact then the problem is likely a problem with the rigidbody. I can't see anything wrong with your code but just to be sure, you should also try using the scene window to manually move the drum into the dirt and see if they interact. Could you also show some pictures of the components on both the drum and the dirt gameobjects so I can see the setup? Comment: Have you tried a combination of these suggestions? I.e. Make the mesh collider convex and make sure that the rigidbodies for everything are set to discrete collision detection? I can see in the images that the drum's rigidbody is still set to continuous collision detection. I don't know if you changed it back to that because you put a box collider on or not but it is something that does NEED to be set to discrete for the mesh collider. If none of this is working, then you might just have to use compound colliders(lots of smaller colliders that will roughly be the same shape as the drum) Comment: Thanks for the quick response! I tried doing that but it didn't seem to work. Any other ideas? Comment: The rigidbodies don't use gravity and are not kinematic, and their mass is 1. Their collision detection is set to continuous. Comment: No, that didn't seem to work. The exact same behavior happened as last time, maybe there's another factor that's screwing everything up? Comment: When I changed the collider from the mesh to a standard box, it interacted with the dirt. If I move the drum into the dirt in the scene view, nothing happens. I also updated the images in the original post to include the components on the gameobjects.
Title: I refreshed the cache in my opencart website and now the website is not loading? Tags: php;icons;opencart;opencart-3 Question: After making Some changes in the code and refreshing using Modification i am enable to load my Website Comment: you need to provide more details. what is the error? Comment: Fatal error: Call to undefined method Action181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16xecute() /home/public_html/system/engine/event.php on line 62
Title: function pointer from one class to member function of any class Tags: c++;c++11 Question: I'm having difficulties defining a function pointer that can point to any member function (not just member functions for the specified class). For instance, C++ forces me to specify the class that a function pointer to a member function would point to: ```typedef void (Foo181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16*MyFunctionPointerTypeName)(int); ``` but what if the class member function that this function pointer is going to point to isn't in ```Foo```? How then would I write this, or what alternative approach could I use? Update: For anyone looking for a quick answer on how to accomplish this with a C++11 ```st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16function``` (as tutorials on the subject seem to assume alot of the reader): Definition (from within ```Foo```): ```st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16function<void(int)&gt; _fun; ``` Binding (from any class): ```objFoo-&gt;_fun = st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16bind(&amp;SomeOtherClass181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16memberFunction, this, st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16placeholders181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16_1); ``` Calling it (from within ```Foo```) ```if(_fun != nullptr) _fun(42); ``` If your function has no parameters, you can remove ```st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16placeholders181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16_1```. And if your function has two parameters you'll need to also add ```st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16placeholders181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16_2``` as a parameter to ```st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16bind```. Similarly for three parameters, four parameters, etc. Comment: In what circumstances do you want to use this? Here is the accepted answer: You cannot write a member pointer that could point to a member of any class. Remember: one of the arguments of a member pointer is the class instance itself. And pointers are typed, so the type of its arguments is very much a part of the pointer's type. You can use ```st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16function``` however, which can store all sorts of callables. How you would actually call it (ie: what parameters you give it) depends on your needs, as you haven't explained what you're trying to do. Comment for this answer: `one of the arguments of a member pointer is the class instance itself`. Technically incorrect. Instead its the `this` pointer or pointer to the object in question. Comment for this answer: Having read [Member Function Pointers and the Fastest Possible C++ Delegates](http://www.codeproject.com/Articles/7150/Member-Function-Pointers-and-the-Fastest-Possible) just now, I agree. It isn't possible to do this with a function pointer. I've got a working solution with st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16function (since I'm using C++11), but I wish a function pointer would have worked (for sake of simplicity). Here is another answer: Use inheritance: ```#include <iostream&gt; struct Foo {}; struct Bar : public Foo { int F0() { return 0; } }; struct Baz : public Foo { int F1() { return 1; } }; int main(int argc, char **argv) { int (Bar181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16*pF0)() = &amp;Bar181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16; int (Baz181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16*pF1)() = &amp;Baz181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16; int (Foo181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16*pointer1)() = static_cast<int (Foo181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16*)()&gt;(pF0); int (Foo181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16*pointer2)() = static_cast<int (Foo181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16*)()&gt;(pF1); Bar r; Baz z; // Pointer to Foo member function calling Bar member function st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16cout << (r.*pointer1)() << '\n'; // Pointer to Foo member function calling Baz member function st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16cout << (z.*pointer2)() << '\n'; return 0; } ``` Output: ```0 1 ``` Hope it helps.
Title: Do amiibo cards require an amiibo reader/writer? Tags: animal-crossing-new-leaf Question: I have an old 3DS XL, and I recently downloaded the new AC:NL update. I understand that the amiibo cards can now do some neat things, but I don't want to buy a $20 peripheral for 1 game. Can I just use a camera to scan the cards with the camera or do I need the reader/writer? Comment: It's worth mentioning that the Amiibo reader/writer is usable with all amiibo, not just the cards for Animal Crossing New Leaf. You could use it for SSB4 or Fire Emblem Fates (assuming you have the appropriate amiibo), as well. Comment: @Vemonus I know that the reader/writer can be used with other games, but I don't have any other use for amiibo besides this game. Nonetheless, I appreciate the answer, and you deserve top answer by far. Comment: ah I see. Well, unfortunately you'll need the NFC adapter. Maybe you'll find another game you like in the future that you can use it for, though! Comment: @Vemonus Hey, you never know. What's your friend code? (if you want to play Sm4sh or Animal Crossing sometime) Mines 0361-6682-4264 Comment: Oh, I never even thought of sharing that. I'll go put it on my profile, give me a second. Here is the accepted answer: Amiibo Cards work the same was as regular Amiibo figurines, in that they require a special reader/writer. Meaning, if you don't have the new Nintendo 3DS that comes with this reader/writer built-in, you will need to buy the NFC adapter that you've mentioned. For reference, see this tutorial on how to use the Animal Crossing Amiibo cards. Namely, this step: ``` Follow the instructions and when prompted, place the Animal Crossing amiibo card of the animal you want to visit on the NFC area of the touch screen (New Nintendo 3DS system) or on the NFC Reader/Writer. ``` These are the only two ways to access the Amiibo Card, or an Amiibo, with a Nintendo 3DS for that matter. It's worth noting that this isn't the only game that you would be able to use the NFC for. Two enjoyable games that you could use the NFC with applicable Amiibo for are Super Smash Bros. for the 3DS and Fire Emblem Fates. Comment for this answer: The cards work exactly the same as the actual figurines. They work with an NFC chip. So even if someone tried to do a camera reader, they wouldn't be able to read the NFC chip with a simple camera. Comment for this answer: @Karlyr thanks, I'll add that to the answer for completion
Title: How can I fix Laravel Mix without Laravel UI in Laravel 8? Tags: laravel;npm;laravel-mix;laravel-fortify Question: I get the following error when I use Laravel Mix, that is when I run ```npm run dev```. ``` ERROR in /menu/js/bootstrap.min Module not found: Error: Can't resolve 'C:\Users\AsemaN\Desktop\AryaBMS\resources\menu\bootstrap.min.css' in 'C:\Users\AsemaN\Desktop\AryaBMS' ERROR in /menu/js/bootstrap.min Module not found: Error: Can't resolve 'C:\Users\AsemaN\Desktop\AryaBMS\resources\menu\bootstrap.min.js' in 'C:\Users\AsemaN\Desktop\AryaBMS' webpack compiled with 2 errors Notifications are disabled Reason: DisabledForUser Please make sure that the app id is set correctly. Command Line: C:\Users\AsemaN\Desktop\AryaBMS\node_modules\node-notifier\vendor\snoreToast\snoretoast-x64.exe -appID &quot;Laravel Mix&quot; -pipeName \.\pipe\notifierPipe- b68a9c48-faee-4b5b-abf8-3030e5663f34 -p C:\Users\AsemaN\Desktop\AryaBMS\node_modules\laravel-mix\icons\laravel.png -m &quot;Error: Error: Can't resolve 'C:\Users\AsemaN \Desktop\AryaBMS\resources\menu\bootstrap.min.css' in 'C:\Users\AsemaN\Desktop\AryaBMS'&quot; -t &quot;Laravel Mix&quot; npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! [email protected] development: ```mix``` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the [email protected] development script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\AsemaN\AppData\Roaming\npm-cache_logs\2021-12-15T08_17_23_702Z-debug.log npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! [email protected] dev: ```npm run development``` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the [email protected] dev script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\AsemaN\AppData\Roaming\npm-cache_logs\2021-12-15T08_17_24_017Z-debug.log ``` Let me say that I do not use Laravel UI but I use Laravel Fortify weboack.mix.js ```mix.js('resources/menu/bootstrap.min.js', 'public/menu/js') .postCss('resources/menu/bootstrap.min.css', 'public/menu/css') ``` Comment: "C:\Users\AsemaN \Desktop\AryaBMS\resources\menu\bootstrap.min.css" looks like there's a space there that shouldn't be there.
Title: color java JSlider based on tick value Tags: java;swing;colors;jslider Question: I want to have a JSlider with three kind of colors each one occupying a range of values(eg. 1 to 10 is green, 10 to 20 is yellow, 20 to 30 is red), how can this be implemented? Comment: Do you want the background to have three stripes of color? Or do you want it to be colored one of the three colors based on the selected value? Comment: @Russell Zahniser: I want the background to have three stripes of color, how can I make GradientPaint to do that to the background JPanel Here is the accepted answer: Edit: Oops, for some reason I thought there was a ```paintBackground()``` method in JComponent. I guess you'd instead have to do ```setOpaque(false)``` (so that ```super``` doesn't paint the background) and then override ```paintComponent()``` like this: ```protected void paintComponent(Graphics g) { int w = getWidth(); int h = getHeight(); int x1 = w / 3; int x2 = w * 2 / 3; g.setColor(Color.GREEN); g.fillRect(0, 0, x1, h) g.setColor(Color.YELLOW); g.fillRect(x1, 0, x2 - x1, h) g.setColor(Color.RED); g.fillRect(x2, 0, w - x2, h) super.paintComponent(); } ```
Title: How do I handle auto incrementing primary keys during migration Tags: ruby-on-rails;dbmigrate Question: ```create table foo (id auto increment primary key, name varchar(255)) ``` I wrote a simple rails migration script which creates a new record on ```self.up``` and drops it on ```self.drop``` with ```delete(:id =&gt; 1)```. If I perform db:migrate it creates a new entry with id=1 and if I rollback it gets removed. The problem occurs if I migrate / drop again as the record gets created with primary key id=2 and my drop script fails on a rollback. It is very important that the primary key is the same every time as I have other dependencies based on that. What should be the right way to handle this. Here is another answer: I think the right way to handle it is dropping the table instead of deleting records. As you create the table in your self.up method you can perform a drop on it. ``` def down drop_table :system_settings end ``` Here is another answer: The thing that does this is ```AUTO_INCREMENT``` option in MySQL. I dont think ```ActiveRecord``` allows you to turn it off. However you could turn it off by removing ```AUTO_INCREMENT``` value for the id field in MySQL (you will have to execute a MySQL query for this.) On second thought, you are maintaining some Orphan records in your database. I dont believe this would be the right thing to do. Try deleting these things from the Rails console with models properly setup to delete dependent records when the mother record gets deleted and then use some rake scripts or something to add the data again and set up required associations. Here is another answer: You should not use migrations for adding seed data, use the ```db/seed.rb``` file instead. This will reinstall your seed data when you do ```rake db:reset```, this will also reset your id counters so the data will have predictable ids. Data added through migrations will not be reloaded when doing a ```rake db:reset```! Comment for this answer: Yes, db:reset will drop and recreate the database containing just the seed data. So it's not the way to go in a production environment where you have data you want to keep in your database. Comment for this answer: Will this drop and re-create the seed data, this might fail since there will be other records which have a foreign key dependency on the seed data.
Title: JavaScript is working and doesn't at the same time Tags: javascript;html;css Question: I have the following task, I need to make a 2x2 table and each tile of that table has a button that should open the hidden div that contains the iframe. If an iframe is opened, the grid-template-columns and grid-template-rows are changed. From 30vw 30vw for columns, and 20vh 20vh for rows, to 95vw for columns, and optionally for rows. Variationally - if, for example, I opened the first frame, but at the same time I already had the third one open, then my grid-template-rows will be 110vh 20vh 110vh 20vh, and if I open only the first, then 110vh 20vh 20vh 20vh, respectively. Before I tried to do variable height of lines, everything worked for me, the width and height of the first container decreased and increased, the iframe appeared, but as soon as I wrote the code for variability, everything broke at once: the iframe does not appear, the width increases but does not decrease, the height increases only for 1 element ... The logic of my js is as follows: Check if that element is hidden, for which the button that called the method is responsible, if yes, then we look at which iframs have already been shown, and depending on this we set the line height and set ```display: block;```. If this element is shown, then we do the same thing, but set display: none; Here is a piece of html code: ```<div id=&quot;projects-grid&quot;&gt; <div class=&quot;project-tile&quot;&gt; <a href=&quot;&quot;&gt; <button class=&quot;a-btn&quot;&gt; <h2&gt;Go to Tribute page</h2&gt; </button&gt; </a&gt; <button class=&quot;show-btn&quot; onclick=&quot;firstBtnClick()&quot;&gt; <p id=&quot;first-show-p&quot;&gt;Click to open site</p&gt; </button&gt; <div id=&quot;first-hidden&quot;&gt; <img src=&quot;https://i.postimg.cc/V6Dh8R60/Tribute-Page-Preview.png&quot; alt=&quot;&quot;&gt; <!-- <iframe src=&quot;https://codepen.io/YouAreMe12/full/bGRdxZg&quot; frameborder=&quot;0&quot;&gt;</iframe&gt; --&gt; </div&gt; </div&gt; <div class=&quot;project-tile&quot;&gt; <a href=&quot;&quot;&gt; <button class=&quot;a-btn&quot;&gt; <h2&gt;Survey form</h2&gt; </button&gt; </a&gt; <button class=&quot;show-btn&quot; onclick=&quot;secondBtnClick()&quot;&gt; <p class=&quot;show-para&quot;&gt;Click to open site</p&gt; </button&gt; <div id=&quot;second-hidden&quot;&gt; <img src=&quot;https://i.postimg.cc/V6Dh8R60/Tribute-Page-Preview.png&quot; alt=&quot;&quot;&gt; </div&gt; </div&gt; <div class=&quot;project-tile&quot;&gt; <a href=&quot;&quot;&gt; <button class=&quot;a-btn&quot;&gt; <h2&gt;Product landing page</h2&gt; </button&gt; </a&gt; <button class=&quot;show-btn&quot; onclick=&quot;thirdBtnClick()&quot;&gt; <p class=&quot;show-para&quot;&gt;Click to open site</p&gt; </button&gt; <div id=&quot;third-hidden&quot;&gt; <img src=&quot;https://i.postimg.cc/V6Dh8R60/Tribute-Page-Preview.png&quot; alt=&quot;&quot;&gt; </div&gt; </div&gt; <div class=&quot;project-tile&quot;&gt; <a href=&quot;&quot;&gt; <button class=&quot;a-btn&quot;&gt; <h2&gt;Technical documentation page</h2&gt; </button&gt; </a&gt; <button class=&quot;show-btn&quot; onclick=&quot;forthBtnClick()&quot;&gt; <p class=&quot;show-para&quot;&gt;Click to open site</p&gt; </button&gt; <div id=&quot;forth-hidden&quot;&gt; <img src=&quot;https://i.postimg.cc/V6Dh8R60/Tribute-Page-Preview.png&quot; alt=&quot;&quot;&gt; </div&gt; </div&gt; </div&gt; ``` Css: ``` #projects-grid { display: grid; grid-template-columns: 30vw 30vw; grid-template-rows: 20vh 20vh; grid-gap: 9rem; margin: 0 auto; margin-bottom: 6rem; } .project-tile { background: var(--main-gray); box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5); border-radius: 4px; margin: 6px; padding: 10px; display: flex; flex-direction: column; align-items: center; justify-items: center; border: 1px solid cyan; } #first-hidden { pad: var(--main-cyan); display: none; } #second-hidden { display: none; } #third-hidden { display: none; } #forth-hidden { display: none; } iframe { border-radius: 5px; width: 87vw; height: 89vh; border-bottom: 7px solid var(--main-white); } ``` and JS with responsive height: ``` function firstBtnClick() { //start if (document.getElementById(&quot;first-hidden&quot;).style.display == &quot;none&quot;) { //second is shown if (document.getElementById(&quot;second-hidden&quot;).style.display != &quot;none&quot;) { //second and third if (document.getElementById(&quot;third-hidden&quot;).style.display != &quot;none&quot;) { //and also forth if (document.getElementById(&quot;forth-hidden&quot;).style.display != &quot;none&quot;) { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;110vh 110vh 110vh 110vh&quot;; } document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;110vh 110vh 110vh 20vh&quot;; //second and forth } else if (document.getElementById(&quot;forth-hidden&quot;).style.display != &quot;none&quot;) { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;110vh 110vh 20vh 110vh&quot;; } document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;110vh 110vh 20vh 20vh&quot;; //second is hidden third is shown } else if (document.getElementById(&quot;third-hidden&quot;).style.display != &quot;none&quot;) { //third and forth if (!document.getElementById(&quot;forth-hidden&quot;).style.display != &quot;none&quot;) { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;110vh 20vh 110vh 110vh&quot;; } document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;110vh 20vh 110vh 20vh&quot;; //only forth } else if (document.getElementById(&quot;forth-hidden&quot;).style.display != &quot;none&quot;) { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;110vh 20vh 20vh 110vh&quot;; } document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;110vh 20vh 20vh 20vh&quot;; document.getElementById(&quot;first-show-p&quot;).textContent = &quot;Click to hide site&quot;; document.getElementById(&quot;first-hidden&quot;).style.display = &quot;block&quot;; } else { //column check if (document.getElementById(&quot;second-hidden&quot;).style.display != &quot;none&quot; || document.getElementById(&quot;third-hidden&quot;).style.display != &quot;none&quot; || document.getElementById(&quot;forth-hidden&quot;).style.display != &quot;none&quot;) { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateColumns = &quot;95vw&quot;; }else{ document.getElementById(&quot;projects-grid&quot;).style.gridTemplateColumns = &quot;30vw 30vw&quot;; } //second if (document.getElementById(&quot;second-hidden&quot;).style.display != &quot;none&quot;) { //second and third if (document.getElementById(&quot;third-hidden&quot;).style.display != &quot;none&quot;) { //also forth if (document.getElementById(&quot;forth-hidden&quot;).style.display != &quot;none&quot;) { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;20vh 110vh 110vh 110vh&quot;; } document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;20vh 110vh 110vh 20vh&quot;; //second and forth } else if (document.getElementById(&quot;forth-hidden&quot;).style.display != &quot;none&quot;) { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;20vh 110vh 20vh 110vh&quot;; } //only second document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;20vh 110vh 20vh 20vh&quot;; //third } else if (document.getElementById(&quot;third-hidden&quot;).style.display != &quot;none&quot;) { //third and forth if (document.getElementById(&quot;forth-hidden&quot;).style.display != &quot;none&quot;) { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;20vh 20vh 110vh 110vh&quot;; } //only third document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;20vh 20vh 110vh 20vh&quot;; //forth } else if (document.getElementById(&quot;forth-hidden&quot;).style.display != &quot;none&quot;) { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;20vh 20vh 20vh 110vh&quot;; } document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;20vh 20vh&quot;; document.getElementById(&quot;first-show-p&quot;).textContent = &quot;Click to open site&quot;; document.getElementById(&quot;second-hidden&quot;).style.display = &quot;none&quot;; } } function secondBtnClick() { //start if (document.getElementById(&quot;second-hidden&quot;).style.display == &quot;none&quot;) { //first is shown if (document.getElementById(&quot;first-hidden&quot;).style.display != &quot;none&quot;) { //first and third if (document.getElementById(&quot;third-hidden&quot;).style.display != &quot;none&quot;) { //and also forth if (document.getElementById(&quot;forth-hidden&quot;).style.display != &quot;none&quot;) { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;110vh 110vh 110vh 110vh&quot;; } document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;110vh 110vh 110vh 20vh&quot;; //first and forth } else if (document.getElementById(&quot;forth-hidden&quot;).style.display != &quot;none&quot;) { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;110vh 110vh 20vh 110vh&quot;; } document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;110vh 110vh 20vh 20vh&quot;; //first is hidden third is shown } else if (document.getElementById(&quot;third-hidden&quot;).style.display != &quot;none&quot;) { //third and forth if (!document.getElementById(&quot;forth-hidden&quot;).style.display != &quot;none&quot;) { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;20vh 110vh 110vh 110vh&quot;; } document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;20vh 110vh 110vh 20vh&quot;; //only forth } else if (document.getElementById(&quot;forth-hidden&quot;).style.display != &quot;none&quot;) { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;20vh 110vh 20vh 110vh&quot;; } document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;20vh 110vh 20vh 20vh&quot;; document.getElementById(&quot;second-show-p&quot;).textContent = &quot;Click to hide site&quot;; document.getElementById(&quot;second-hidden&quot;).style.display = &quot;block&quot;; } else { //column check if (document.getElementById(&quot;first-hidden&quot;).style.display != &quot;none&quot; || document.getElementById(&quot;third-hidden&quot;).style.display != &quot;none&quot; || document.getElementById(&quot;forth-hidden&quot;).style.display != &quot;none&quot;) { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateColumns = &quot;95vw&quot;; }else{ document.getElementById(&quot;projects-grid&quot;).style.gridTemplateColumns = &quot;30vw 30vw&quot;; } //first if (document.getElementById(&quot;first-hidden&quot;).style.display != &quot;none&quot;) { //first and third if (document.getElementById(&quot;third-hidden&quot;).style.display != &quot;none&quot;) { //also forth if (document.getElementById(&quot;forth-hidden&quot;).style.display != &quot;none&quot;) { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;110vh 20vh 110vh 110vh&quot;; } document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;110vh 20vh 110vh 20vh&quot;; //first and forth } else if (document.getElementById(&quot;forth-hidden&quot;).style.display != &quot;none&quot;) { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;110vh 20vh 20vh 110vh&quot;; } //only first document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;110vh 20vh 20vh 20vh&quot;; //third } else if (document.getElementById(&quot;third-hidden&quot;).style.display != &quot;none&quot;) { //third and forth if (document.getElementById(&quot;forth-hidden&quot;).style.display != &quot;none&quot;) { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;20vh 20vh 110vh 110vh&quot;; } //only third document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;20vh 20vh 110vh 20vh&quot;; //forth } else if (document.getElementById(&quot;forth-hidden&quot;).style.display != &quot;none&quot;) { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;20vh 20vh 20vh 110vh&quot;; } document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;20vh 20vh&quot;; document.getElementById(&quot;second-show-p&quot;).textContent = &quot;Click to open site&quot;; document.getElementById(&quot;second-hidden&quot;).style.display = &quot;none&quot;; } } function thirdBtnClick() { //start if (document.getElementById(&quot;third-hidden&quot;).style.display == &quot;none&quot;) { //first is shown if (document.getElementById(&quot;first-hidden&quot;).style.display != &quot;none&quot;) { //first and second if (document.getElementById(&quot;second-hidden&quot;).style.display != &quot;none&quot;) { //and also forth if (document.getElementById(&quot;forth-hidden&quot;).style.display != &quot;none&quot;) { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;110vh 110vh 110vh 110vh&quot;; } document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;110vh 110vh 110vh 20vh&quot;; //first and forth } else if (document.getElementById(&quot;forth-hidden&quot;).style.display != &quot;none&quot;) { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;110vh 20vh 110vh 110vh&quot;; } document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;110vh 20vh 110vh 20vh&quot;; //first is hidden second is shown } else if (document.getElementById(&quot;second-hidden&quot;).style.display != &quot;none&quot;) { //second and forth if (!document.getElementById(&quot;forth-hidden&quot;).style.display != &quot;none&quot;) { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;20vh 110vh 110vh 110vh&quot;; } document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;20vh 110vh 110vh 20vh&quot;; //only forth } else if (document.getElementById(&quot;forth-hidden&quot;).style.display != &quot;none&quot;) { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;20vh 20vh 110vh 110vh&quot;; } document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;20vh 20vh 110vh 20vh&quot;; document.getElementById(&quot;third-show-p&quot;).textContent = &quot;Click to hide site&quot;; document.getElementById(&quot;third-hidden&quot;).style.display = &quot;block&quot;; } else { //column check if (document.getElementById(&quot;first-hidden&quot;).style.display != &quot;none&quot; || document.getElementById(&quot;second-hidden&quot;).style.display != &quot;none&quot; || document.getElementById(&quot;forth-hidden&quot;).style.display != &quot;none&quot;) { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateColumns = &quot;95vw&quot;; }else{ document.getElementById(&quot;projects-grid&quot;).style.gridTemplateColumns = &quot;30vw 30vw&quot;; } //first if (document.getElementById(&quot;first-hidden&quot;).style.display != &quot;none&quot;) { //first and second if (document.getElementById(&quot;second-hidden&quot;).style.display != &quot;none&quot;) { //also forth if (document.getElementById(&quot;forth-hidden&quot;).style.display != &quot;none&quot;) { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;110vh 110vh 20vh 110vh&quot;; } document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;110vh 110vh 20vh 20vh&quot;; //first and forth } else if (document.getElementById(&quot;forth-hidden&quot;).style.display != &quot;none&quot;) { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;110vh 20vh 20vh 110vh&quot;; } //only first document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;110vh 20vh 20vh 20vh&quot;; //second } else if (document.getElementById(&quot;second-hidden&quot;).style.display != &quot;none&quot;) { //second and forth if (document.getElementById(&quot;forth-hidden&quot;).style.display != &quot;none&quot;) { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;20vh 110vh 20vh 110vh&quot;; } //only second document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;20vh 110vh 20vh 20vh&quot;; //forth } else if (document.getElementById(&quot;forth-hidden&quot;).style.display != &quot;none&quot;) { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;20vh 20vh 20vh 110vh&quot;; } document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;20vh 20vh&quot;; document.getElementById(&quot;third-show-p&quot;).textContent = &quot;Click to open site&quot;; document.getElementById(&quot;third-hidden&quot;).style.display = &quot;none&quot;; } } function forthBtnClick() { //start if (document.getElementById(&quot;forth-hidden&quot;).style.display == &quot;none&quot;) { //first is shown if (document.getElementById(&quot;first-hidden&quot;).style.display != &quot;none&quot;) { //first and second if (document.getElementById(&quot;second-hidden&quot;).style.display != &quot;none&quot;) { //and also third if (document.getElementById(&quot;third-hidden&quot;).style.display != &quot;none&quot;) { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;110vh 110vh 110vh 110vh&quot;; } document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;110vh 110vh 20vh 110vh&quot;; //first and third } else if (document.getElementById(&quot;third-hidden&quot;).style.display != &quot;none&quot;) { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;110vh 20vh 110vh 110vh&quot;; } document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;110vh 20vh 20vh 110vh&quot;; //first is hidden second is shown } else if (document.getElementById(&quot;second-hidden&quot;).style.display != &quot;none&quot;) { //second and third if (!document.getElementById(&quot;third-hidden&quot;).style.display != &quot;none&quot;) { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;20vh 110vh 110vh 110vh&quot;; } document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;20vh 110vh 20vh 110vh&quot;; //only third } else if (document.getElementById(&quot;third-hidden&quot;).style.display != &quot;none&quot;) { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;20vh 20vh 110vh 110vh&quot;; } document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;20vh 20vh 20vh 110vh&quot;; document.getElementById(&quot;forth-show-p&quot;).textContent = &quot;Click to hide site&quot;; document.getElementById(&quot;forth-hidden&quot;).style.display = &quot;block&quot;; } else { //column check if (document.getElementById(&quot;first-hidden&quot;).style.display != &quot;none&quot; || document.getElementById(&quot;second-hidden&quot;).style.display != &quot;none&quot; || document.getElementById(&quot;third-hidden&quot;).style.display != &quot;none&quot;) { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateColumns = &quot;95vw&quot;; }else{ document.getElementById(&quot;projects-grid&quot;).style.gridTemplateColumns = &quot;30vw 30vw&quot;; } //first if (document.getElementById(&quot;first-hidden&quot;).style.display != &quot;none&quot;) { //first and second if (document.getElementById(&quot;second-hidden&quot;).style.display != &quot;none&quot;) { //also third if (document.getElementById(&quot;third-hidden&quot;).style.display != &quot;none&quot;) { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;110vh 110vh 110vh 20vh&quot;; } document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;110vh 110vh 20vh 20vh&quot;; //first and third } else if (document.getElementById(&quot;third-hidden&quot;).style.display != &quot;none&quot;) { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;110vh 20vh 110vh 20vh&quot;; } //only first document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;110vh 20vh 20vh 20vh&quot;; //second } else if (document.getElementById(&quot;second-hidden&quot;).style.display != &quot;none&quot;) { //second and third if (document.getElementById(&quot;third-hidden&quot;).style.display != &quot;none&quot;) { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;20vh 110vh 110vh 20vh&quot;; } //only second document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;20vh 110vh 20vh 20vh&quot;; //third } else if (document.getElementById(&quot;third-hidden&quot;).style.display != &quot;none&quot;) { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;20vh 20vh 110vh 20vh&quot;; } document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;20vh 20vh&quot;; document.getElementById(&quot;forth-show-p&quot;).textContent = &quot;Click to open site&quot;; document.getElementById(&quot;forth-hidden&quot;).style.display = &quot;none&quot;; } } ``` And without: ```function btnClick(){ if (document.getElementById(&quot;first-hidden&quot;).style.display == &quot;none&quot;) { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateColumns = &quot;95vw&quot;; document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;110vh 20vh 20vh 20vh&quot;; document.getElementById(&quot;first-hidden&quot;).style.display = &quot;block&quot;; }else { document.getElementById(&quot;projects-grid&quot;).style.gridTemplateColumns = &quot;30vw 30vw&quot;; document.getElementById(&quot;projects-grid&quot;).style.gridTemplateRows = &quot;20vh 20vh&quot;; document.getElementById(&quot;first-hidden&quot;).style.display = &quot;none&quot;; } ```
Title: iOS 6: UUIDString on iPhone 3GS Tags: objective-c;ios;ios6;uuid;iphone-3gs Question: I've been working on ```ASIdentifierManager``` framework to get the new ```UUIDString```, the identifier should replace in iOS 6 the UDID, and can be stopped or not by the user for Settings. Everything is ok on simulators and iPhone 4S, but on iPhone 3GS (it's iOS 6 updated!) I'm getting as UUIDString the following: 00000000-0000-0000-0000-000000000000 This is how I'm getting it: ```if ([ASIdentifierManager sharedManager]) NSLog(@"%@", [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString]); ``` Does anyone know why? Have you encountered this problem? Thanks Here is another answer: According to this article http://techcrunch.com/2012/09/27/source-apples-udid-replacement-for-advertisers-in-ios-6-is-broken/ there are serious problems with the new advertising identifier in iOS 6. It is claimed that on devices that were updated to iOS 6 via Wi-Fi, the advertising identifier contains only zeros. According to that article, the problem does not occur on devices that were updated via iTunes. Even if that does not solve your problem, it might help to explain it.
Title: Building a 32-bit float out of its 4 composite bytes Tags: c++;floating-point;endianness;portability;single-precision Question: I'm trying to build a 32-bit float out of its 4 composite bytes. Is there a better (or more portable) way to do this than with the following method? ```#include <iostream&gt; typedef unsigned char uchar; float bytesToFloat(uchar b0, uchar b1, uchar b2, uchar b3) { float output; *((uchar*)(&amp;output) + 3) = b0; *((uchar*)(&amp;output) + 2) = b1; *((uchar*)(&amp;output) + 1) = b2; *((uchar*)(&amp;output) + 0) = b3; return output; } int main() { st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16cout << bytesToFloat(0x3e, 0xaa, 0xaa, 0xab) << st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16endl; // 1.0 / 3.0 st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16cout << bytesToFloat(0x7f, 0x7f, 0xff, 0xff) << st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16endl; // 3.4028234 × 10^38 (max single precision) return 0; } ``` Comment: Considering that this was my first question on Stack Overflow, I'm thrilled at the various responses. I thank everyone for their input. Here is the accepted answer: You could use a ```memcpy``` (Result) ```float f; uchar b[] = {b3, b2, b1, b0}; memcpy(&amp;f, &amp;b, sizeof(f)); return f; ``` or a union* (Result) ```union { float f; uchar b[4]; } u; u.b[3] = b0; u.b[2] = b1; u.b[1] = b2; u.b[0] = b3; return u.f; ``` But this is no more portable than your code, since there is no guarantee that the platform is little-endian or the ```float``` is using IEEE binary32 or even ```sizeof(float) == 4```. (Note*: As explained by @James, it is technically not allowed in the standard (C++ §[class.union]/1) to access the union member ```u.f```.) Comment for this answer: To solve the `sizeof(float)` problem you may just declare the `b` member as `uchar b[sizeof(float)];`. Comment for this answer: @Matteo: Right, but then the input needs to be modified as well. Here is another answer: You can use ```st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16copy```: ```float bytesToFloat(uchar b0, uchar b1, uchar b2, uchar b3) { uchar byte_array[] = { b3, b2, b1, b0 }; float result; st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16copy(reinterpret_cast<const char*&gt;(&amp;byte_array[0]), reinterpret_cast<const char*&gt;(&amp;byte_array[4]), reinterpret_cast<char*&gt;(&amp;result)); return result; } ``` This avoids the union hack, which isn't technically allowed by the language. It also avoids the commonly used ```reinterpret_cast<float*&gt;(byte_array)```, which violates the strict aliasing rules (it is permitted to reinterpret any object as an array of ```char```, so the ```reinterpret_cast```s in this solution do not violate the strict aliasing rules). It still relies on ```float``` being four bytes in width and relies on your four bytes being a valid floating point number in your implementation's floating point format, but you either have to make those assumptions or you have to write special handling code to do the conversion. Comment for this answer: @JoshD: No; it still relies on `sizeof(float) == 4` and doesn't take endianness into consideration. It just avoids `reinterpret_cast(some_uchar_array)` and the union hack. Comment for this answer: @MSalters: But `memcpy` doesn't reinterpret a byte array as a float; it reinterprets a float as a byte array. Comment for this answer: I'm fairly certain that `reinterpret_cast(byte_array)` must be allowed if the byte_array (1) is aligned properly and (2) actually contains a float. I think so because otherwise it would be impossible to `memcpy` a `float` to another `float` (since `memcpy` writes to a byte array), and yet a `float` is the archetypical POD type. Comment for this answer: It's indeed not `memcpy` itself; that obviously works only on byte arrays. It's the guarantee that you can use the output byte array as a float. Here is another answer: I typically use this in C -- no ```memcpy``` or ```union``` required. It may break aliasing rules in C++, I don't know. ```float bytesToFloat(uint8_t *bytes, bool big_endian) { float f; uint8_t *f_ptr = (uint8_t *) &amp;f; if (big_endian) { f_ptr[3] = bytes[0]; f_ptr[2] = bytes[1]; f_ptr[1] = bytes[2]; f_ptr[0] = bytes[3]; } else { f_ptr[3] = bytes[3]; f_ptr[2] = bytes[2]; f_ptr[1] = bytes[1]; f_ptr[0] = bytes[0]; } return f; } ``` If you have a whole array of bytes that need to be re-interpreted as floats, you can call the following procedure for each consecutive sequence of 4 bytes in the array if necessary, to switch the byte order (e.g. if you are running on a little endian machine, but the bytes are in big endian order). Then you can simply cast the ```uint8_t *``` array pointer to ```float *```, and access the memory as an array of floats. ```void switchEndianness(uint8_t *bytes) { uint8_t b0 = bytes[0]; uint8_t b1 = bytes[1]; uint8_t b2 = bytes[2]; uint8_t b3 = bytes[3]; bytes[0] = b3; bytes[1] = b2; bytes[2] = b1; bytes[3] = b0; } ``` Here is another answer: If you want a portable way to do this, you'll have to write a bit of code to detect the endianess of the system. ```float bytesToFloatA(uchar b0, uchar b1, uchar b2, uchar b3) { float output; *((uchar*)(&amp;output) + 3) = b0; *((uchar*)(&amp;output) + 2) = b1; *((uchar*)(&amp;output) + 1) = b2; *((uchar*)(&amp;output) + 0) = b3; return output; } float bytesToFloatB(uchar b0, uchar b1, uchar b2, uchar b3) { float output; *((uchar*)(&amp;output) + 3) = b3; *((uchar*)(&amp;output) + 2) = b2; *((uchar*)(&amp;output) + 1) = b1; *((uchar*)(&amp;output) + 0) = b0; return output; } float (*correctFunction)(uchar b0, uchar b1, uchar b2, uchar b3) = bytesToFloatA; if ((*correctFunction)(0x3e, 0xaa, 0xaa, 0xab) != 1.f/3.f) // horrifying, I know { correctFunction = bytesToFloatB; } ``` Comment for this answer: That won't be equal in any endians because `1./3.` is a `double`, not a `float`. You should use something like `1.0f/3`. Here is another answer: There's no way to do this portable, since different platforms can use: different byte ordering (big endian vs. little endian) different representations for floating point values (see http://en.wikipedia.org/wiki/IEEE_754-1985 for an example) different sizes for floating point values I also wonder where you get these 4 bytes from? If I assume that you get them from another system, and you can guarantee that both systems use exactly the same method to store floating-point values in memory, you can use the union trick. Otherwise, your code is almost guaranteed to be non-portable. Here is another answer: The following functions pack/unpack bytes representing a single precision floating point value to/from a buffer in network byte order. Only the pack method needs to take endianness into account since the unpack method explicitly constructs the 32-bit value from the individual bytes by bit shifting them the appropriate amount and then OR-ing them together. These functions are only valid for C/C++ implementations that store a float in 32-bits. This is true for IEEE 754-1985 floating point implementations. ```// unpack method for retrieving data in network byte, // big endian, order (MSB first) // increments index i by the number of bytes unpacked // usage: // int i = 0; // float x = unpackFloat(&amp;buffer[i], &amp;i); // float y = unpackFloat(&amp;buffer[i], &amp;i); // float z = unpackFloat(&amp;buffer[i], &amp;i); float unpackFloat(const void *buf, int *i) { const unsigned char *b = (const unsigned char *)buf; uint32_t temp = 0; *i += 4; temp = ((b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3]); return *((float *) &amp;temp); } // pack method for storing data in network, // big endian, byte order (MSB first) // returns number of bytes packed // usage: // float x, y, z; // int i = 0; // i += packFloat(&amp;buffer[i], x); // i += packFloat(&amp;buffer[i], y); // i += packFloat(&amp;buffer[i], z); int packFloat(void *buf, float x) { unsigned char *b = (unsigned char *)buf; unsigned char *p = (unsigned char *) &amp;x; #if defined (_M_IX86) || (defined (CPU_FAMILY) &amp;&amp; (CPU_FAMILY == I80X86)) b[0] = p[3]; b[1] = p[2]; b[2] = p[1]; b[3] = p[0]; #else b[0] = p[0]; b[1] = p[1]; b[2] = p[2]; b[3] = p[3]; #endif return 4; } ``` Comment for this answer: I'm pretty sure this is undefined behaviour in C++ due to strict aliasing rules. Comment for this answer: I think there is a mistake in the code line: return *((float *) temp); It should be: return *((float *) &temp); Comment for this answer: ironically, I was looking for a way to cleanly read a float from a binary file, and I ended up being lazy and doing the pointer hack in unpackFloat() above. I googled to find a better way and end up finding someone who did the exact same thing.
Title: com.predic8.soamodel.TypeRefAccessException while creating SOAP request template for WSDL Tags: java;soap;wsdl;soa;membrane-soa Question: I have a requirement where i need to create soap xml request template for a particular operation in WSDL. I am using membrane soa-modeljars to achieve this. http://www.membrane-soa.org/soa-model-doc/1.4/java-api/create-soap-request-template.htm It works perfectly fine for simple WSDL which does not references any xsd in it. But it starts failing as soon as i try to load WSDL which has xsd referenced in it. Below is the error message which I am receiving. ```Exception in thread &quot;main&quot; com.predic8.soamodel.TypeRefAccessException: Could not find the referenced type 'PozSupplierIntDFF' in namespace 'http://xmlns.oracle.com/apps/flex/prc/poz/suppliers/supplierServiceV2/supplierContact/'. at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at org.codehaus.groovy.reflection.CachedConstructor.invoke(CachedConstructor.java:83) at org.codehaus.groovy.reflection.CachedConstructor.doConstructorInvoke(CachedConstructor.java:77) at org.codehaus.groovy.runtime.callsite.ConstructorSite$ConstructorSiteNoUnwrap.callConstructor(ConstructorSite.java:84) at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallConstructor(CallSiteArray.java:60) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:235) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:263) at com.predic8.schema.Schema.findType(Schema.groovy:240) at com.predic8.schema.Schema$findType$2.callCurrent(Unknown Source) at com.predic8.schema.Schema.getType(Schema.groovy:218) at com.predic8.schema.Schema$getType$1.call(Unknown Source) at com.predic8.wstool.creator.RequestTemplateCreator.createElement(RequestTemplateCreator.groovy:71) at com.predic8.wstool.creator.RequestTemplateCreator$createElement.call(Unknown Source) at com.predic8.schema.Element.create(Element.groovy:97) at com.predic8.schema.Element$create.call(Unknown Source) at com.predic8.schema.creator.AbstractSchemaCreator$_createSequence_closure1.doCall(AbstractSchemaCreator.groovy:61) at sun.reflect.GeneratedMethodAccessor173.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93) at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325) at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:294) at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1022) at groovy.lang.Closure.call(Closure.java:414) at groovy.lang.Closure.call(Closure.java:430) at org.codehaus.groovy.runtime.DefaultGroovyMethods.each(DefaultGroovyMethods.java:2040) at org.codehaus.groovy.runtime.DefaultGroovyMethods.each(DefaultGroovyMethods.java:2025) at org.codehaus.groovy.runtime.DefaultGroovyMethods.each(DefaultGroovyMethods.java:2066) at org.codehaus.groovy.runtime.dgm$163.invoke(Unknown Source) at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoMetaMethodSiteNoUnwrapNoCoerce.invoke(PojoMetaMethodSite.java:274) at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite.call(PojoMetaMethodSite.java:56) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125) at com.predic8.schema.creator.AbstractSchemaCreator.createSequence(AbstractSchemaCreator.groovy:60) at com.predic8.schema.creator.AbstractSchemaCreator$createSequence.call(Unknown Source) at com.predic8.schema.Sequence.create(Sequence.groovy:30) at com.predic8.schema.Sequence$create.call(Unknown Source) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callSafe(AbstractCallSite.java:94) at com.predic8.wstool.creator.RequestTemplateCreator$_createComplexType_closure2.doCall(RequestTemplateCreator.groovy:103) at com.predic8.wstool.creator.RequestTemplateCreator$_createComplexType_closure2.doCall(RequestTemplateCreator.groovy) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93) at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325) at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:294) at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1022) at groovy.lang.Closure.call(Closure.java:414) at groovy.lang.Closure.call(Closure.java:408) at groovy.util.BuilderSupport.doInvokeMethod(BuilderSupport.java:147) at groovy.util.BuilderSupport.invokeMethod(BuilderSupport.java:67) at org.codehaus.groovy.runtime.InvokerHelper.invokePogoMethod(InvokerHelper.java:931) at org.codehaus.groovy.runtime.InvokerHelper.invokeMethod(InvokerHelper.java:908) at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodN(ScriptBytecodeAdapter.java:168) at com.predic8.wstool.creator.RequestTemplateCreator.createComplexType(RequestTemplateCreator.groovy:102) at com.predic8.wstool.creator.RequestTemplateCreator$createComplexType$0.call(Unknown Source) at com.predic8.schema.ComplexType.create(ComplexType.groovy:94) at com.predic8.schema.ComplexType$create.call(Unknown Source) at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133) at com.predic8.wstool.creator.RequestTemplateCreator.createElement(RequestTemplateCreator.groovy:73) at com.predic8.wstool.creator.RequestTemplateCreator$createElement.call(Unknown Source) at com.predic8.schema.Element.create(Element.groovy:97) at com.predic8.schema.Element$create.call(Unknown Source) at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133) at com.predic8.schema.creator.AbstractSchemaCreator$_createSequence_closure1.doCall(AbstractSchemaCreator.groovy:61) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93) at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325) at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:294) at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1022) at groovy.lang.Closure.call(Closure.java:414) at groovy.lang.Closure.call(Closure.java:430) at org.codehaus.groovy.runtime.DefaultGroovyMethods.each(DefaultGroovyMethods.java:2040) at org.codehaus.groovy.runtime.DefaultGroovyMethods.each(DefaultGroovyMethods.java:2025) at org.codehaus.groovy.runtime.DefaultGroovyMethods.each(DefaultGroovyMethods.java:2066) at org.codehaus.groovy.runtime.dgm$163.invoke(Unknown Source) at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoMetaMethodSiteNoUnwrapNoCoerce.invoke(PojoMetaMethodSite.java:274) at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite.call(PojoMetaMethodSite.java:56) at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125) at com.predic8.schema.creator.AbstractSchemaCreator.createSequence(AbstractSchemaCreator.groovy:60) at com.predic8.schema.creator.AbstractSchemaCreator$createSequence.call(Unknown Source) at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133) at com.predic8.schema.Sequence.create(Sequence.groovy:30) at com.predic8.schema.Sequence$create.call(Unknown Source) at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callSafe(AbstractCallSite.java:94) at com.predic8.wstool.creator.RequestTemplateCreator$_createComplexType_closure2.doCall(RequestTemplateCreator.groovy:103) at com.predic8.wstool.creator.RequestTemplateCreator$_createComplexType_closure2.doCall(RequestTemplateCreator.groovy) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93) at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325) at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:294) at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1022) at groovy.lang.Closure.call(Closure.java:414) at groovy.lang.Closure.call(Closure.java:408) at groovy.util.BuilderSupport.doInvokeMethod(BuilderSupport.java:147) at groovy.util.BuilderSupport.invokeMethod(BuilderSupport.java:67) at org.codehaus.groovy.runtime.InvokerHelper.invokePogoMethod(InvokerHelper.java:931) at org.codehaus.groovy.runtime.InvokerHelper.invokeMethod(InvokerHelper.java:908) at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodN(ScriptBytecodeAdapter.java:168) at com.predic8.wstool.creator.RequestTemplateCreator.createComplexType(RequestTemplateCreator.groovy:102) at com.predic8.wstool.creator.RequestTemplateCreator$createComplexType$0.call(Unknown Source) at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133) at com.predic8.schema.ComplexType.create(ComplexType.groovy:94) at com.predic8.schema.ComplexType$create.call(Unknown Source) at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133) at com.predic8.wstool.creator.RequestTemplateCreator.createElement(RequestTemplateCreator.groovy:67) at com.predic8.wstool.creator.RequestTemplateCreator$createElement.call(Unknown Source) at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133) at com.predic8.schema.Element.create(Element.groovy:97) at com.predic8.schema.Element$create.call(Unknown Source) at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133) at com.predic8.wstool.creator.SOARequestCreator$_buildBody_closure3.doCall(SOARequestCreator.groovy:98) at com.predic8.wstool.creator.SOARequestCreator$_buildBody_closure3.doCall(SOARequestCreator.groovy) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93) at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325) at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:294) at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1022) at groovy.lang.Closure.call(Closure.java:414) at groovy.lang.Closure.call(Closure.java:408) at groovy.util.BuilderSupport.doInvokeMethod(BuilderSupport.java:147) at groovy.util.BuilderSupport.invokeMethod(BuilderSupport.java:67) at org.codehaus.groovy.runtime.InvokerHelper.invokePogoMethod(InvokerHelper.java:931) at org.codehaus.groovy.runtime.InvokerHelper.invokeMethod(InvokerHelper.java:908) at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodN(ScriptBytecodeAdapter.java:168) at com.predic8.wstool.creator.SOARequestCreator.buildBody(SOARequestCreator.groovy:83) at com.predic8.wstool.creator.SOARequestCreator.this$3$buildBody(SOARequestCreator.groovy) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93) at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325) at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:384) at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1022) at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.callCurrent(PogoMetaClassSite.java:69) at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:52) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:154) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:166) at com.predic8.wstool.creator.SOARequestCreator$_createRequest_closure2.doCall(SOARequestCreator.groovy:78) at com.predic8.wstool.creator.SOARequestCreator$_createRequest_closure2.doCall(SOARequestCreator.groovy) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93) at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325) at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:294) at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1022) at groovy.lang.Closure.call(Closure.java:414) at groovy.lang.Closure.call(Closure.java:408) at groovy.util.BuilderSupport.doInvokeMethod(BuilderSupport.java:147) at groovy.util.BuilderSupport.invokeMethod(BuilderSupport.java:67) at org.codehaus.groovy.runtime.InvokerHelper.invokePogoMethod(InvokerHelper.java:931) at org.codehaus.groovy.runtime.InvokerHelper.invokeMethod(InvokerHelper.java:908) at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodN(ScriptBytecodeAdapter.java:168) at com.predic8.wstool.creator.SOARequestCreator.createRequest(SOARequestCreator.groovy:74) at testdhananjay.testclass.main(testclass.java:61) ``` Here is another answer: i had a similiar problem. I called this method. ``` ComplexType complexType = schema.getComplexType(e.getType().getLocalPart()); ``` I had the problem that there is no complex Type available. If you have a XSD File you will get two schemas. ```final List<Schema&gt; schemas = definitions.getSchemas(); // Deliver you two schemas ``` If you go through the schemas you will see that your complexType will be in an other schema. ``` for (final Schema schema : schemas) { System.out.println(&quot;Complextypes Numer: &quot; + schema.getComplexTypes().size()); for (final ComplexType c : schema.getComplexTypes()) { System.out.println(&quot;Complextypes: &quot; + c.getName()); } } ``` You need the correct schema to get access to this type. I hope that will help you and others.
Title: Understanding Hadoop through matrix multiplication using R Tags: r;hadoop;matrix Question: This is just an attempt to understand Hadoop, R and the best practice for doing certain things that really leverages the best of both Hadoop and R. If the goal is to multiply two matrices A*B when these two matrices are stored in Hadoop then traditional methods of multiplying two matrices A &amp; B in R is against the logic of big data. The reason we are having this discussion in the first place is because r chokes on big data and it is impossible to multiple two large matrices in R ? If I am correct so far, matrix multiplication should be performed using shell scripts/ unix scripts, is this correct ? we just use R to display the results of this operation (matrix multiplication) that occurred behind the scene via shell script, am I correct ? Interested to know your thoughts on this topic. Comment: Check out [mining massive dataset](http://infolab.stanford.edu/~ullman/mmds/book.pdf), maybe page 30. Comment: Do you think you can answer your own question so it will be helpful for the coming readers or you want me to do it? Comment: @B.Mr.W. that pdf is exactly what the doctor prescribed :) awesome.
Title: sed remove digits at end of the line Tags: regex;linux;sed Question: I need to find out how to delete up to 10 digits that are at the end of the line in my text file using sed. For example if I have this: ```ajsdlfkjasldf1234567890 asdlkjfalskdjf123456 adsf;lkjasldfkjas123 ``` it should become: ```ajsdlfkjasldf asdlkjfalskdjf adsf;lkjasldfkjas ``` can anyone help? I have this, but its not working: ```sed 's/[0-9]{10}$//g' ``` Comment: I think that would only work if you have exactly ten numbers. Comment: yep, can you improve it to make it work? I've been trying but I cant :s Here is the accepted answer: Have you tried this: ``` sed 's/[0-9]+$//' ``` Your command would only match and delete exactly 10 digits at the end of line and only, if you enabled extended regular expressions (-E or -r, depending on your version of sed). You should try ``` sed -r 's/[0-9]{1,10}$//' ``` Here is another answer: A quick look here suggests you should try this: ```$ sed 's/[0-9]\{0,10\}$//g' ``` { } should be escaped, unless you switch to extended regex syntax: ```$ sed -r 's/[0-9]{0,10}$//g' ``` Here is another answer: The following should work: ```sed 's/[0-9]\{1,10\}$//' file ``` Regex syntax in ```sed``` requires backslashes before the brackets to use them for repetition, unless you use an extended regex option.
Title: Stop DataContractSerializer putting in namespace? Tags: datacontractserializer;datacontract Question: I want to serialize datacontract classes into XMl, but without the Namespaces. I've added: ```[DataContract(Namespace="")] ``` but I still get: ```<Person xmlns:i="http://www.w3.org/2001/XMLSchema-instance"&gt; <Title&gt;Mr</Title&gt; ... </Person&gt; ``` Is there any way to stop this happening as I just want the clean xml to pass into a legacy component.
Title: Can Amaterasu's speed increase? Tags: naruto Question: In the battle against Raikage, Sasuke cast Amaterasu and Raikage avoided it pretty easily because he's fast. In the battle against Kaguya, Sasuke cast Amaterasu and it hit her. Question Was it because: - Sasuke Amaterasu speed had increased as he grew stronger so Kaguya couldn't dodge? - Kaguya could dodge it but she simply took it because she knew it was a chakra that she could absorb? Are there any information about this? Note: Kaguya is faster than Raikage, right? Here is another answer: Speed is just a vague concept while using Amaterasu. The real answer to this is accuracy. While fighting Sasuke, Itachi missed the Amaterasu several times. Not because Sasuke was running at the speed of light, but because of his blurry vision, which could not target Sasuke properly. It could be that Sasuke missed casting it on the Raikage because he wasn't as proficient with it as he was while fighting Kaguya. His visual prowess was also enhanced and his vision was clearer because of the Eternal Mangekyou Sharingan while fighting Kaguya. So, the speed of the jutsu could increase (time taken to cast the jutsu, not reach the object) after unlocking the Eternal Mangekyou Sharingan. Comment for this answer: if you look at when sasuke aimed for raikage, he didn't miss the target. His aim was spot on. raikage was just way faster. The speed of amaterasu can't be increased because it doesn't take any time to cast the jutsu. As long as you can see the user and you activate the justsu then it immidiately starts burning. Plus the only difference between eternal mangekyou and normal mangekyou is that the eternal mangekyous light never runs out. The anime never talks about added abilities that come with the eternal mangekyou. Its just that its a more everlasting version of the mangekyou sharingan Comment for this answer: That's my point.Eternal Mangekyou means clearer vision-which increases the accuracy of the jutsu.Obito,Itachi,Madara have themselves stated many times that with the Eternal Mangekyou,they have better chakra control. Comment for this answer: Obito never stated that cause he never obtained eternal to begin with. and also can you show (cite me a source). Like a manga pic or Anime episode where that was said Comment for this answer: This is just a vague statement like the question you asked,Anime Scientist where Kakashi "compliments" Naruto Comment for this answer: Also,if Obito never obtained the EMS,why didn't the anime show him losing his vision?He had so many eyes to begin with,he used many of them for Izanagi(Vs Konan) and he used Kamui endlessly without any difficulty. Comment for this answer: In Order to get an EMS Obito would have needed the mangekyou of a sibling, and Obitos family was never elaborated on in Naruto so I'm guessing his situation was similar to Narutos. Also, I doubt he could get Eternal Mangekyou Sharingan with just one Mangekyou, I think thats because the Sharingan is a pair Dojutsu Comment for this answer: That's not true.To awaken the Mangekyou,I agree someone close to the person,like a family member is required.But to obtain the EMS,you just need a spare pair of Sharingan. Comment for this answer: If he did not awaken EMS,can you explain why his vision never blurred? Comment for this answer: I guess its cause Obito already had senjuu blood or something, Cause if it were just possible to obtain EMS from a normal Mangekyou then why didn't danzou make shisuis eye an ems with the amount of sharingans that he had? Comment for this answer: even Itachi stated while he was fighting Sasuke that he needed the mangekyou of a blood relative. You know Itachi was very smart right? why do you think he would prefer to be partially blind if he could have just easily attained the mangekyou of any of the people he killed, watch episode 134 to 139, the explanation is somewhere there Comment for this answer: if Obito had Senju blood,he would have Rinnegan in both his eyes(Senju+Uchiha=Rinnegan).Itachi did not obtain EMS because he just did not want to.There is a question on that topic here as well. Comment for this answer: obito had senjuu blood actually, the mere fact that he had zetsu's skin implanted into the right half of his body is proof that he had senjuu blood because white zetsu was cultivated from hashiramas cells. Also one needs ems to evolve to rinnegan, a mere sharingan or mangekyou can't evolve to rinnegan without the ems, check my answer: https://anime.stackexchange.com/questions/48995/would-naruto-awaken-rinnegan-if-he-take-sharingan-from-sasuke/48997#48997 Comment for this answer: Assuming you are correct about having just Uchiha and senju bloodline to create the Rinnengan, then can you explain why Danzou sharingans did NOT all evolve to rinnengan. If that theory was 100% the truth then all the sharingans on Danzous hand and shisuis eyes would have all evolved to rinnengan when he got hasirama's cells implanted into him right? Comment for this answer: Danzo was never an Uchiha to begin with.He had no Uchiha blood.So he couldn't unlock his Rinnegan.Also,White Zetsu was NOT CULTURED with Hashirama cells.It was the remnants of the people from the previous Infinite Tsukoyomi.Here's some evidence:https://youtu.be/8tXFWSzWcmU Comment for this answer: http://naruto.wikia.com/wiki/Zetsu white zetsu is one of the remnants of Kaguyas infinite tsukinomi, after madara summoned the gedo statue, black zetsu took out white zetsu and another one, tobi. Also, the eye of an uchiha contains their DNa, and white zetsu has hashimramas cells, Senju dna and chakra Here is another answer: Short Answer: Kaguya Otsutsuki was very powerful but her speed was just slightly above average. During her battle with Sasuke and Naruto, all she mainly did was hop from dimension to dimension, use a bunch of Kekkai Moras and absorb their attacks with her Rinnengan. Note that she is NOT faster than Raikage Ai when he uses the Lightning release chakra Mode to enhance his speed and reaction time. The only reason why Raikage could dodge it is cause he combined 2 Jutsus simultenously in order to detect and flicker away from the flames. Kaguya on the other hand, was not fast enough to dodge the flames. However, she was skilled enough to quickly absorb them before they did enough damage on her. So to answer your question, the speed of Amaterasu was never increased, She just was not fast enough to dodge the flames like Raikage did. Super Long explanation: The Amaterasu is a very fast jutsu in terms of how long it takes before it is cast. Unlike other jutsu, all it requires is that you see the person you want to hit and then Black Flames are ignited at the focal point of the target! This means that as long as the user can see you, the Amaterasu is most likely going to hit. In order to dodge an &quot;accurately-aimed&quot; Amaterasu, I believe the persons speed must be pretty close to that of light because the focal point of vision is directly what your eyes see from the refraction of light. (Its a completely different scenario if the user is partially blind and can't aim well.) In the case of Raikage, he used 2 jutsu's simultaneously in order to dodge sasukes Amaterasu. The first one is the lightning release chakra mode. During his battle with Sasuke, Raikage was wraped in lightning during the entire fight and once sasuke started to use the mangekyou Sharingan, Raikage instinctively started using way more chakra for the Lightning Release Chakra Mode in order to increase his already heightened speed and reaction time. With enhanced speed and reaction time, Raikage was able to immediately react to sasuke's amaterasu, he then used the ShunShin no jutsu ( Lightning release Body Flicker technique ). Since he combined the 2 jutsus perfectly, he was able to instantly react to and swiftly move away from the flames (all within a matter of seconds, simply mindblowing lol). Moreover, Kaguya could not pull such a feat.
Title: New software can't be installed because there is a problem with the software currently installed--trying to install Loggerpro for Ubuntu Tags: apt;software-installation;dpkg;dependencies Question: When I try to install loggerpro, this is the message I get. I looked on the forum and tried the following commands: ```sudo apt-get install --reinstall deconf ``` and then it says: ```unable to access package deconf``` then I tried ```sudo apt-get install --reinstall debconf ``` and then i got ```Reading package lists... Done Building dependency tree Reading state information... Done You might want to run 'apt-get -f install' to correct these: The following packages have unmet dependencies: linux-image-extra-3.16.0-60-generic : Depends: linux-image-3.16.0-60-generic but it is not going to be installed linux-image-extra-3.16.0-62-generic : Depends: linux-image-3.16.0-62-generic but it is not going to be installed linux-image-generic-lts-utopic : Depends: linux-image-3.16.0-62-generic but it is not going to be installed E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution). then I try apt-get install: XXXXX:~$ apt-get -f install E: Could not open lock file /var/lib/dpkg/lock - open (13: Permission denied) E: Unable to lock the administration directory (/var/lib/dpkg/), are you root? ``` What do I do now? I'm not a computer person, so if you can explain what I should do next in the simplest terms possible I would really appreciate it! OKay, I tried what john Orion suggested and this is what i got: ```Reading package lists... Done Building dependency tree Reading state information... Done Correcting dependencies... Done The following packages were automatically installed and are no longer required: account-plugin-windows-live libupstart1 linux-headers-3.16.0-30 linux-headers-3.16.0-30-generic linux-image-3.16.0-30-generic linux-image-extra-3.16.0-30-generic Use 'apt-get autoremove' to remove them. The following extra packages will be installed: linux-image-3.16.0-60-generic linux-image-3.16.0-62-generic Suggested packages: fdutils linux-lts-utopic-tools linux-headers-3.16.0-60-generic The following NEW packages will be installed: linux-image-3.16.0-60-generic linux-image-3.16.0-62-generic 0 upgraded, 2 newly installed, 0 to remove and 195 not upgraded. 5 not fully installed or removed. Need to get 0 B/31.0 MB of archives. After this operation, 69.2 MB of additional disk space will be used. Do you want to continue? [Y/n] Y (Reading database ... 356758 files and directories currently installed.) Preparing to unpack .../linux-image-3.16.0-62-generic_3.16.0-62.82~14.04.1_i386.deb ... Done. Unpacking linux-image-3.16.0-62-generic (3.16.0-62.82~14.04.1) ... dpkg: error processing archive /var/cache/apt/archives/linux-image-3.16.0-62-generic_3.16.0-62.82~14.04.1_i386.deb (--unpack): cannot copy extracted data for './boot/vmlinuz-3.16.0-62-generic' to '/boot/vmlinuz-3.16.0-62-generic.dpkg-new': failed to write (No space left on device) No apport report written because the error message indicates a disk full error dpkg-deb: error: subprocess paste was killed by signal (Broken pipe) Examining /etc/kernel/postrm.d . run-parts: executing /etc/kernel/postrm.d/initramfs-tools 3.16.0-62-generic /boot/vmlinuz-3.16.0-62-generic run-parts: executing /etc/kernel/postrm.d/zz-update-grub 3.16.0-62-generic /boot/vmlinuz-3.16.0-62-generic Preparing to unpack .../linux-image-3.16.0-60-generic_3.16.0-60.80~14.04.1_i386.deb ... Done. Unpacking linux-image-3.16.0-60-generic (3.16.0-60.80~14.04.1) ... dpkg: error processing archive /var/cache/apt/archives/linux-image-3.16.0-60-generic_3.16.0-60.80~14.04.1_i386.deb (--unpack): cannot copy extracted data for './boot/vmlinuz-3.16.0-60-generic' to '/boot/vmlinuz-3.16.0-60-generic.dpkg-new': failed to write (No space left on device) No apport report written because the error message indicates a disk full error dpkg-deb: error: subprocess paste was killed by signal (Broken pipe) Examining /etc/kernel/postrm.d . run-parts: executing /etc/kernel/postrm.d/initramfs-tools 3.16.0-60-generic /boot/vmlinuz-3.16.0-60-generic run-parts: executing /etc/kernel/postrm.d/zz-update-grub 3.16.0-60-generic /boot/vmlinuz-3.16.0-60-generic E: Sub-process /usr/bin/dpkg returned an error code (1) ``` I still can't install new software, and get the same error message, and the dependency not satisfiable: vstdrivers. Any other ideas????? Comment: `utopic`? I believe that you are a bit out-dated... Comment: @JohnOrion You might want to convert that to an answer, it will most likely solve his problem. Comment: Hi, I tried what John Orion suggested and this is what I got:4 Comment: You need to be using root permissions when you use apt-get .. try `sudo apt-get -f install` when it asks for a password ..use your users login password but be aware it doesn't show any indication that a password is being typed.. just type it in and press enter Here is another answer: From the errors such as ```failed to write (No space left on device)```, it looks like the Ubuntu partition on your hard drive is full. Perhaps you could delete some files or transfer them to another drive or partition, and then re-visit this issue. You could also run ```sudo apt-get clean``` to free up some space. Update: Since the errors are related to kernel installation, it's likely that you need to free up space in you ```/boot``` directory, which may be in a different partition than the rest of your system. Please see the answer to this question for instructions on how to do that: Can&#39;t upgrade due to low disk space on /boot Comment for this answer: Yes, `sudo apt-get clean` . If that doesn't help, then you need to free up space in other ways. Comment for this answer: If there are no errors, then it worked. However, I think the problem is actually with your `/boot` partition; please see the edit I just made to my answer. Comment for this answer: Hi I just tried that and nothing happens. just to be clear it's sudo apt-get clean written just like that? Comment for this answer: I've also deleted several films, music, etc, and I still get this message. Comment for this answer: what should happend after I type in sudo apt-get clean ? all that happens is I'm immediately brought back to my XXX@XXX:~$ It's almost as though it isn't processing the command? Comment for this answer: Hi; thanks for all the help! I've tried to get rid of old kernels using the commands reccommended in the 'can't upgrade due to low disk space on /boot' and still get: E: Sub-process /usr/bin/dpkg returned an error code (1) Also, I realized (thru reading through some comments) that maybe I have low disk space because i'm using 14.04, encrypted. Is there a way to increase the disc space without unencrypting my computer? thanks so much for the help, but i still can't download loggerpro!!!
Title: Force decimals in html inputs with InputMask html (jqueryl or js)? Tags: javascript;jquery;html;regex Question: I want to force my html input the following display: 14 mantissa maximun(from 1 to 14) and the Effective Three decimal point, if the user does not specify the value of the points after they take the default 000 Example: Enter 5 show 5.000 enter 5.2 Show 5.200 enter 22222 show 22222.000 display. please help Comment: how if the value 12-14 digit? became "123456789123.000"(became 15 digit long)? Comment: Please show some effort. What have you tried? Comment: @najeh22 I'm not even questioning that you have made an effort. I'm just asking you to show us your failed attempts, so we have something to improve on. Comment: belive I made a lot of effort from yesterdays that I could get this solution to my problem because it is more complex than that , but a solution like this can be enough, I look everywhere but I did not find an answer . Comment: in my data base table i have price numeric(16,3) Comment: I tried first jquery inputmasque with the plugin digital bash , the problem is whith the optionanal value , i can't add decimal 000 if I put only digital value, after that i passed to regex and i start creating my own expression but it doesn't work: like this var ex=/[0-9]{1-14}(\.[0-9]{3} |(\.000)$/; Comment: I tried this but I still have problemes with it ,checkDec(el){ var ex=/^[0-9]{1,3}\.[0-9]{2}$/; if(ex.test(el.value)==false){ el.value = el.value.substring(0,el.value.length - 1); } } ,I use onkeyup in html. Here is another answer: Use ```.indexOf``` to check for the ```.``` character. Make sure it's there and check the length of the ```substring``` that goes after its index. If it's less then 3, add some zeros. HTML ```<input type="text" id="input" maxlength="14" value="" /&gt; ``` JavaScript ```/* Select the desired input, and add an onChange event listener */ document.querySelector('#input').onchange = function () { /* if the user didn't add a dot, we add one with 3 zeros */ if (this.value.indexOf('.') == -1) this.value += '.000'; /* Otherwise, we check how many numbers there are after the dot and make sure there's at least 3*/ if (this.value.substring(this.value.indexOf('.') + 1).length < 3) while (this.value.substring(this.value.indexOf('.') + 1).length < 3) this.value += '0'; }; ``` Live Demo Comment for this answer: @najeh22 There are no regular expressions in my answer, so I don't know what your problem is. Also: [**How to accept an answer**](http://meta.stackexchange.com/a/971-791-2149). Comment for this answer: What do you mean by "force the display of the real part" ? I don't see that part in your original question. Comment for this answer: thank you, it 's fine, but i still have probleme with regular expression Comment for this answer: your answer answers part of the question, but because of the other party which is not yet solved, my problem is not solved. I need a regex expression to force the display of the real part, I tested the input mask with your solution, but it gives no good result. Comment for this answer: I want to force my html input the following display: 14 digital maximun(from 1 to 14) and Three decimal point.from 0.000 to 99999999999999.999 Comment for this answer: 14 numbers maximum before the point. Comment for this answer: I find the solution http://jsfiddle.net/vandalo/fhYAs/ Here is another answer: check if the number match ```(\d{1,14})(\.\d{1,3}){0,1}``` split by .(dot) char check the length of the second array result add .000 if null or ajust if have 1 or 2 length by add 2 or 1 zero Comment for this answer: [see this](http://jsfiddle.net/4BcF5/). i think that will be clear enough for you to get what you need. and i said `split(".")` not `substring()` Comment for this answer: I tried this but I still have problemes with it ,checkDec(el){ var ex=/^[0-9]{1,3}\.[0-9]{2}$/; if(ex.test(el.value)==false){ el.value = el.value.substring(0,el.value.length - 1); } } ,I use onkeyup in html.
Title: How to fit a compose-arctangent function? Tags: python;numpy;curve-fitting;data-fitting;atan Question: I'm trying to fit a double broken profile function which consists of the arctangent function. My code doesn't seem to be working: ```XX=np.linspace(7.5,9.5,16) YY=np.asarray([7,7,7,7.1,7.3,7.5,8.4,9,9.3,9.6,10.3,10.2,10.4,10.5,10.5,10.5]) def func_arc(x,a1,a2,a3,b1,b2,b3,H1,H2): beta=0.001 w1=np.zeros(len(x)) w2=np.zeros(len(x)) for i in np.arange(0,len(x)): w1[i]=(((math.pi/2)+atan((x[i]-H1)/beta))/math.pi) w2[i]=(((math.pi/2)+atan((x[i]-H2)/beta))/math.pi) y=(a1*x[i]+b1)*(1-w1[i])+(a2*x[i]+b2)*w1[i]*(1-w2[i])+(a3*x+b3)*w2[i] return(y) ``` Where the ```a``` and ```b``` terms are slope and zero-point values of the linear regressions. The ```w``` terms are used to switch the domain. I take into account the following restrictions for continuity (H1 y H2) and restrict parameters: ```mask=(XX<=8.2) mask2=(XX&gt;8.2) &amp; (XX<9) mask3=(XX&gt;=9) l1=np.polyfit(XX[mask], YY[mask], 1) l2=np.polyfit(XX[mask2], YY[mask2], 1) l3=np.polyfit(XX[mask3], YY[mask3], 1) H1=(l2[1]-l1[1])/(l1[0]-l2[0]) H2=(l3[1]-l2[1])/(l2[0]-l3[0]) p0=[l1[0],l2[0],l3[0],l1[1],l2[1],l3[1],H1,H2] popt_arc1, pcov_arc1 =curve_fit(func_arc, XX, YY,p0) ``` I obtain a single line instead of a broken profile (S-shape). What I obtain: Comment: First I'd like to say that you are probably completely over-fitting your data. It does not look like data with two domains of linear bnehavior. It is more like an `arctan` itself. So what is the motivation here? Can you provide some insight? Comment: Hi. While technically speaking SO is not to give advice on your model-function, I think you made it by far too complicated. If you can state more precisely what you actually need, I am sure that this part can be improved as well. Comment: Thank you @mikuszefski; actually, I am working with a big database and I intended to exemplify the general behavior with only a dozen, trying to reproduce two plateaus, and I used this mathematical expression to reproduce a scientific paper. Here is another answer: Here is my version. Due to the fact that the linear functions should connect continuously, the parameters are actually less. The offsets ```b2``` and ```b3```, hence, are not fitted, but are a result of reacquiring the linear function to meet at the transitions. Moreover, one might argue that the data does not justify a slope in the beginning or end. This could be justified / checked via the reduced chi-square or other statistical methods. ```import matplotlib.pyplot as plt import numpy as np from scipy.optimize import curve_fit XX=np.linspace( 7.5, 9.5, 16 ) YY=np.asarray( [ 7, 7, 7, 7.1, 7.3, 7.5, 8.4, 9, 9.3, 9.6, 10.3, 10.2, 10.4, 10.5, 10.5, 10.5 ]) yy0 = np.median( YY ) xx0 = np.median( XX ) h0 = 0.8 * min( XX ) + 0.2 * max( XX ) h1 = 0.8 * max( XX ) + 0.2 * min( XX ) def transition( x, x0, s ): return ( 0.5 * np.pi + np.arctan( ( x - x0 ) * s ) ) / np.pi def box( x, x0, x1, s ): return transition( x, x0, s ) * transition( -x, -x1, s ) def my_piecewise( x, a1, a2, a3, b1, x0, x1 ): S = 100 b2 = ( a1 - a2 ) * x0 + b1 ### due to continuity b3 = ( a2 - a3 ) * x1 + b2 ### due to continuity out = transition( -x , -x0, S ) * ( a1 * x + b1 ) out += box( x , x0, x1 , S ) * ( a2 * x + b2 ) out += transition( x , x1, S ) * ( a3 * x + b3 ) return out def parameter_reduced( x, a2, b1, x0, x1 ): return my_piecewise(x, 0, a2, 0, b1, x0, x1 ) def alternative( x, x0, a, s, p, y0 ): out = np.arctan( np.abs( ( s * ( x - x0 ) ) )**p )**( 1.0 / p ) out *= a * (x - x0 ) / np.abs( x - x0 ) out += y0 return out xl=np.linspace( 7.2, 10, 150 ) sol, _ = curve_fit( my_piecewise, XX, YY, p0=[ 0, 1, 0, min( YY ), h0, h1 ] ) fl = np.fromiter( ( my_piecewise(x, *sol ) for x in xl ), np.float ) rcp = np.fromiter( ( y - my_piecewise(x, *sol ) for x,y in zip( XX, YY ) ), np.float ) rcp = sum( rcp**2 ) solr, _ = curve_fit( parameter_reduced, XX, YY, p0=[ 1, min(YY), h0, h1 ] ) rl = np.fromiter( ( parameter_reduced( x, *solr ) for x in xl ), np.float ) rcpr = np.fromiter( ( y - parameter_reduced(x, *solr ) for x, y in zip( XX, YY ) ), np.float ) rcpr = sum( rcpr**2 ) guessa = [ xx0, max(YY)-min(YY), 1, 1, yy0 ] sola, _ = curve_fit( alternative, XX, YY, p0=guessa) al = np.fromiter( ( alternative( x, *sola ) for x in xl ), np.float ) rca = np.fromiter( ( y - alternative(x, *sola ) for x, y in zip( XX, YY ) ), np.float ) rca = sum( rca**2 ) print rcp, rcp / ( len(XX) - 6 ) print rcpr, rcpr / ( len(XX) - 4 ) print rca, rca / ( len(XX) - 5 ) fig = plt.figure( figsize=( 12, 8 ) ) ax = fig.add_subplot( 1, 1, 1 ) ax.plot( XX, YY , ls='', marker='o') ax.plot( xl, fl ) ax.plot( xl, rl ) ax.plot( xl, al ) plt.show() ``` Results look okey for me.
Title: Writing language converter in ANTLR Tags: antlr;rewrite Question: I'm writing a converter between some dialects of the same programming language. I've found a grammar on the net - it's complex and handles all the cases. Now I'm trying to write the appropriate actions. Most of the input is just going to be rewritten to output. What I need to do is parse function calls, do my magic (rename function, reorder arguments, etc) and write it. I'm using AST as output. When I come across a function call, I build a custom object structure (from classes defined in my target language), call the appropriate function and I have a string that represents the transformed function that I want to get. The problem is, what I'm supposed to do with that string? I'd like to replace the .text attribute of the enclosing rule, but setText() is only available on lexer rules and the rule's .text attribute is read-only. How to solve this problem? ```program : statement_list { output = $statement_list.text; } ; //... statement : expression_statement // ... ; expression_statement : function_call // ... ; function_call : ID '(' { /* build the object, assign name */ Function function = new Function(); //... } ( arg1 = expression { /* add first parameter */ } ( ',' arg2 = expression { /* add the rest of parameters */ } )* )? ')' { /* convert the function call */ string converted = Tools.Convert(function); // $setText(converted); // doesn't work // $functionCall.text = converted; // doesn't work } ; ``` Here is the accepted answer: The easiest way is to create a rewriter. Set grammar to rewrite, use templates and create a template in-place. Then use TokenRewriteStream and it's ToString() method. ```grammar Test; options { language = CSharp2; output = template; rewrite = true; } program : statement_list ; //... statement : expression_statement // ... ; expression_statement : function_call // ... ; function_call : ID '(' { /* build the object, assign name */ Function function = new Function(); //... } ( arg1 = expression { /* add first parameter */ } ( ',' arg2 = expression { /* add the rest of parameters */ } )* )? ')' -&gt; { new StringTemplate(Tools.Convert(function)) } ; ``` And the driver: ``` string input = "...."; var stream = new ANTLRStringStream(input); var lexer = new TestLexer(stream); // need to use TokenRewriteStream var tokenStream = new TokenRewriteStream(lexer); var parser = new TestParser(tokenStream); parser.program(); // original text Console.WriteLine(tokenStream.ToOriginalString()); // rewritten text Console.WriteLine(tokenStream.ToString()); ``` Here is another answer: Once you have an AST, you'll need to write a tree walker that emits your program as the transformed source. You might even have an intermediate tree walker doing tree transformations depending upon the complexity of your changes. That said, going through an AST step, may not be the best approach. You might want to take a look at "Language Design Patterns" by Terrence Parr (Pragmatic Programmers). Chapter 11 addresses your type of program. He mentions a tool, ANTLRMorph, that might be better suited for your problem. Comment for this answer: The ANTLRMorph project is at http://www.antlr.org/wiki/display/Morph/Home;jsessionid=1EE0150D66C1B50451B202AD44D74134 The goal is to able prople to write translators with concrete syntax rewrite rules, in the spirit of ASF-SDF. By the way, ASF-SDF (http://www.meta-environment.org/) should really be considered for writing such translators.
Title: how to remove the lines in captcha Tags: ocr;captcha Question: I have a simple captcha,I want to recognize the picture. the picture is like: I want to use the tesseract. http://code.google.com/p/tesseract-ocr/ but the tesseract only can use on the clear picture. so I should preprocess the pic. the preprocess code is: ```im = Image.open('test.png') # text = image_to_string(im) enhancer = ImageEnhance.Contrast(im) im = enhancer.enhance(4) img = img.convert("RGBA") width,height = im.size # pixdata = img.load() for y in xrange(img.size[1]): for x in xrange(img.size[0]): if im.getpixel((x,y)) != (0,0,0): im.putpixel((x,y),(255,255,255) ) for y in xrange(img.size[1]): for x in xrange(img.size[0]): if y<2 or y&gt;(img.size[1]-3): continue if im.getpixel((x, y))[0]==255 and im.getpixel((x, y+2))[0]==0 and im.getpixel((x, y-1))[0]==0: im.putpixel((x, y),(0,0,0)) # else: # continue list(im.getdata()) im.show() ``` after the process,the pic is like: so I failed. can anyone give me some tips? I know how to remove the line if the line is a pixel width,but the line here is not consistent.
Title: wxComboBox adding hover effect Tags: c++;wxwidgets Question: Here is my code in C++ when initialize a frame in wxwidgets: ```wxPanel *panel = new wxPanel(this, wxID_ANY); combo_list = new wxComboBox(panel,ID_COMBOBOX); combo_list-&gt;Append("Guitar"); combo_list-&gt;Append("Violin"); Connect(ID_COMBOBOX, wxEVT_COMMAND_COMBOBOX_SELECTED, wxCommandEventHandler(ComboBox181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16OnSelect)); ``` However, there is no default hover effect, which is background color changing when you move mouse on a specific selection. And I find for an hour on google but still cannot find it. Can anybody told me how to make the hover effect? I just want to implement two drop down lists. The content in the first one has been determined before the running the program. In the order one the content will only be determined after I choose a directory.
Title: How can I get the alert box to show total from dropdown selections? Tags: javascript;jquery Question: I've made an error in this script and the alert box doesn't calculate the total, can anyone help please? The alert box just shows 0 but I need it to total the value of the 2 dropdown selections ```<head&gt; <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"&gt;</script&gt; <title&gt;Sandbox</title&gt; <meta http-equiv="Content-type" content="text/html; charset=utf-8" /&gt; <style type="text/css" media="screen"&gt; body { background-color: #fff; font: 16px Helvetica, Arial; color: #fff; } </style&gt; </head&gt; <body&gt; <select id="t_dermal_name"&gt; <option value="t_default_dermal"&gt;-- Choose --</option&gt; <option value="1" rel="30"&gt;Between Eyebrows</option&gt; <option value="7" rel="30"&gt;Individual Line Softening</option&gt; <option value="2" rel="30"&gt;Lip Contouring</option&gt; </select&gt; <select id="t_wrinkle_name"&gt; <option value="t_default_wrinkle"&gt;-- Choose --</option&gt; <option value="1" rel="30"&gt;Between Eyebrows</option&gt; <option value="7" rel="30"&gt;Individual Line Softening</option&gt; <option value="2" rel="30"&gt;Lip Contouring</option&gt; </select&gt; <br /&gt; <button id="btn1"&gt;click</button&gt; <script&gt; $(document).ready ( function () { $("#btn1").click ( function () { var resultVal = 0.0; var objRegExp = '\s+'; $(".test").each ( function() { resultVal += parseFloat ( $(this).val().replace(/\s /g,'').replace(',','.')); }); alert ( resultVal ); }); }); </script&gt; <script src="/js/render/edit.js"&gt;</script&gt; <script&gt;var _gaq=[['_setAccount','UA-1656750-13'],['_trackPageview']];(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.src='//www.google-analytics.com/ga.js';s.parentNode.insertBefore(g,s)})(document,'script')</script&gt;</body&gt; </html&gt; ``` Here is another answer: ```$(".test").each``` Don't know if this is your only problem but... You don't have any elements with the class ```test``` so your code does nothing as the selector grabs nothing, so you stay with ```0```. Maybe you meant: ```$("select").each (function() { ... // Will select all the select elements. ``` You can also simplify the code with: ```$("#btn1").click (function () { var resultVal = 0; $("select").each(function() { resultVal += parseFloat($(this).val()); }); alert (resultVal); }); ``` Comment for this answer: just spotted this, got there before me! Here is another answer: ```$("#btn1").click ( function () { var total = 0; $('select[id*="_name"]').each(function(){ total += parseFloat($(this).val()); }); alert(total); }); ```
Title: Archive without root folder in .zip [node-archiver] Tags: javascript;node.js;archive;node-archiver Question: I'm using node-archiver to archive folder "export" with photos inside. Everything works ok but inside archive I got folder 'offers' and photos are in this folder. I would like to have like a "flat" .zip, so when I'll unpack my .zip it unpack photos without that 'offers' folder. My code: ``` const folderPath = '/export/.'; const output = fs.createWriteStream('test/offers.zip'); const archive = archiver('zip'); archive.pipe(output); archive.directory(folderPath, false); archive.finalize(); ``` What I'm getting after unpacking: What I would like to get: How can I achieve this? Regards, Gemmi Comment: Hi @Seblor, thx. I already tried that and with `*` node-archiver won't zipping my files. Comment: Thank you for replay @Shilly It doesn't work in any provided examples :/ Comment: Have you tried `archive.directory( 'export/' , false);` or `archive.glob( 'export/*.*' );` ? Comment: I think that's because `/export/.` is the same as `/export` so it targets the folder, not the files inside. Try changing the path to `/export/*` Comment: Oh right, I forgot it should be `.glob` not `.directory`, my bad. Good catch Shilly Here is another answer: All you need is set prefix via options property. Like this ```archive.directory(folderPath, false, { prefix: 'your destination folder' }); ``` Regards, Lukas
Title: Change parameter to a boolean value in python Tags: python;function;boolean Question: I was trying to create a back button in pygame using python but my parameter(condition) is not being set to false, how do I do this? Here is my code: ```def back(condition): #condition - any boolean variable in my script mouse = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() if 5 + 125 &gt; mouse[0] &gt; 5 and 5 + 125 &gt; mouse[1] &gt; 5: gameDisplay.blit(backBtn, (5, 5)) if click[0] == 1: if condition: condition = False else: gameDisplay.blit(backBtn_hover, (5, 5)) ``` If you have any sort of answer please answer. Thank you! :D Comment: I wanted condition to be a parameter that takes in a boolean variable and only set condition to false when the back button is clicked Comment: When the back button is pressed, the condition should be set to false. This is the kind of functionality I want but it the condition is not automaticly being set to false by itself. If its impossible to set the condition to false, I will have to create an individual button for every menu in my game. Comment: I didn't understand. Do you want to set `condition` to be by default `False` ? Comment: So what is the problem, what's not working in your example? It sounds very simple. Comment: use a class with an instance member `condition` (`self.condition`). Give it a better name. Comment: function parameters are passed by value for simple types like bool and numbers and by *const* reference for strings (non mutable object) Here is another answer: Since ```condition``` is of an immutable type, any change to it is only visible inside the function. You will need to return it and assign it back when calling the function. ```def back(condition): #condition - any boolean variable in my script mouse = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() if 5 + 125 &gt; mouse[0] &gt; 5 and 5 + 125 &gt; mouse[1] &gt; 5: gameDisplay.blit(backBtn, (5, 5)) if click[0] == 1: if condition: condition = False else: gameDisplay.blit(backBtn_hover, (5, 5)) return condition ... condition = back(condition) ``` It is usually not advisable to make it a global variable so I'm not going to suggest that. Here is another answer: Your answer likely is due to scoping of your variables, three examples provided below that hopefully will lead you to a solution: Situation 1 ```condition = True def back(condition): condition = False print(f&quot;{condition=}&quot;) def main(): local_condition = back(condition) global_condition = condition print(f&quot;{local_condition=}\n{global_condition=}&quot;) if __name__ == '__main__': main() ``` Results: ```condition=False local_condition=None global_condition=True ``` Situation 2 with added return in back funciton ```condition = True def back(condition): condition = False print(f&quot;{condition=}&quot;) return condition def main(): local_condition = back(condition) global_condition = condition print(f&quot;{local_condition=}\n{global_condition=}&quot;) if __name__ == '__main__': main() ``` Results 2: ```condition=False local_condition=False global_condition=True ``` Situation 3 redefining global ```condition = True def back(condition): condition = False print(f&quot;{condition=}&quot;) return condition def main(): global condition condition = back(condition) global_condition = condition print(f&quot;{condition=}\n{global_condition=}&quot;) if __name__ == '__main__': main() ``` Results 3: ```condition=False condition=False global_condition=False ``` Here is another answer: Do you expect this to happen? ```condition = True back(condition) print(condition) # False ``` That's not how Python works. You can't change variables passed to functions. Something like that would work. ```container = { 'condition': True } back(container) print(container['condition']) # False ``` Because in this case you don't change the variable, but its content. But anyway it's bad code. Normally you would do something like that: ```condition = True condition = back(condition) print(condition) # False ``` Of course you need to add a return statement to your function.
Title: How to create duplicate Dates in Python Tags: python-3.x;pandas;dataframe;date Question: I have a data frame named df and it has a column DATES, I want to fill it with 1million dates(doesn't need to be unique) in day.month.year format. Ex: 01.01.2020 Here is another answer: Replace ```dt.now()``` with whatever date you want: ```df[&quot;DATES&quot;] = np.repeat(dt.now().strftime(&quot;%m.%d.%Y&quot;),1000000) ``` Here is another answer: you can use ```date_range``` method in pandas.Also you can shuffle it and assign to column. ```period = 1000000 df[&quot;DATES&quot;] = pd.date_range(end='1.1.2020', periods=period ) ``` Comment for this answer: @noah i think your suggestions are correct.I will change the answer.Thank you Comment for this answer: This requires the df to be 1,000,000 rows already which I'm not sure is the case in the question (easy for them to change periods to 1,000,000 though). It also needs an `end='1.1.2018'` since dealing with such a large number of dates (or else goes beyond max date value). Comment for this answer: `date_range` is definitely a "better" approach than my `np.repeat()` though!
Title: Prewitt filter in Matlab Tags: matlab;gradient Question: I am trying to take a gradient of an image using the Prewitt filter. Can you tell me if this approach is correct? I = imread('image.jpg') Gx = [-1 0 1; -1 0 1; -1 0 1]; Gy = [1 1 1; 0 0 0; 1 1 1]; D = conv2(conv2(I, Gx), Gy) imshow(D) Is that correct? Is there a cleaner way to do it (no need to call conv2 twice)? Is conv2(I, Gx) the same as conv2(Gx, I)? (i.e. commutative?) Thanks. Here is another answer: Judging by my wikipedia-ing it looks like what you should do is: ```I = imread('image.jpg') Gx = [-1 0 1; -1 0 1; -1 0 1]; Gy = [1 1 1; 0 0 0; -1 -1 -1]; A = sqrt( conv2(I,Gx).^2 + conv2(I,Gy).^2 ); imshow(A); ``` Link to Wikipedia Article
Title: In mobile showing background good, but in bluestacks showing white background Tags: java;android;background;bluestacks Question: I have problem, i setted bakground image, it showing good in mobile, but in bluestacks emulator it shows white background.... Why? What is the problem? Can somebody help me to fix this problem? The problem with: android:background="@drawable/map_new_9" activity_main.xml ```<?xml version="1.0" encoding="utf-8"?&gt; <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" tools:ignore="ContentDescription" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:id="@+id/base"&gt; ... ... <androidx.constraintlayout.widget.ConstraintLayout android:id="@+id/base1" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"&gt; <ImageView android:id="@+id/base2" android:layout_width="match_parent" android:layout_height="1920dp" android:background="@drawable/map_new_9" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /&gt; </androidx.constraintlayout.widget.ConstraintLayout&gt; </ScrollView&gt; </androidx.constraintlayout.widget.ConstraintLayout&gt; ``` Comment: Probably a BlueStacks issue. Try the android emulator in Android Studio. Comment: My computer is sh*t and i can't run Android Studio's emulator, so i test on my phone... :( But thanks for the answer
Title: Plot embedded meshes with python Tags: python;matplotlib Question: I have data, where each point is an element of a 4 dimensional array. More precisely, it is a coarse mesh in each element of which I have a smaller mesh. Say the coarse mash is 2x2 and in each of the mesh elements I have another smaller mesh which is 3x3. The question is how to plot that with python. What I do is to find the global position of each of the fine mesh elements and plot it with scatter plot. This works, but I was thinking whether it could be done more efficiently, without the necessity to compute the global indexes. To illustrate my point consider the following minimal example ```import matplotlib.pyplot as plt import numpy as np def from4to2d(i1,j1,i2,j2,nx,ny): return (i1*nx + i2, j1*ny + j2) nx=ny=3 # 3x3 fine mesh x=[] y=[] z=[] for i1 in range(0,2): for j1 in range(0,2): for i2 in range(0,3): for j2 in range(0,3): a,b = from4to2d(i1,j1,i2,j2,nx,ny) x+=[a] y+=[b] z+=[a*b] plt.scatter(x, y, c=z ,s=200, marker='s',cmap=mpl.cm.spectral,linewidths=0) plt.savefig('fig.png',dpi=200,bbox_inches='tight') ``` The question is, if I could do the same without having to find the global positions via ```from4to2d(i1,j1,i2,j2,nx,ny)```. Comment: you'll need to add a self-contained example that demonstrates how you're generating this data structure and what you've already tried in terms of visualizing it. Comment: so what exactly do you want? A plot with dots? polygons? help us out here and include some more details and examples of what you're trying to do? Comment: @PaulH I included a minimal example.
Title: Formatting subequations where one of them is a piece-wise function Tags: horizontal-alignment;subequations Question: I have the following LaTeX code: ```\begin{subequations} \begin{align} F_h(t) = F(\Delta y) = \left\{ \begin{array}{lr} K_h (\Delta y)^{P_h} \; \text{if} \; \Delta y &gt; 0\\ 0 \; \; \hspace{1.23cm}\; \text{if} \; \Delta y \leq 0 \end{array} \right. \label{eqn: hammer1}\\ F_h(t) = -m_h \label{eqn: hammer2} \end{align} \end{subequations} ``` when I compile it, the 2nd equation is aligned to the right-most margin of equation 1. How do I set it such that the 2nd equation is aligned to the left-most margin of the first equation? Here is the accepted answer: You forgot to place the alignment character inside your ```align``` construction. Also, consider using ```cases``` for the conditional constructions: ```\documentclass{article} \usepackage{mathtools}% http://ctan.org/pkg/mathtools \begin{document} \begin{subequations} \begin{align} F_h(t) &amp;= F(\Delta y) = {\begin{cases} K_h (\Delta y)^{P_h} &amp; \text{if $\Delta y &gt; 0$} \\ 0 &amp; \text{if $\Delta y \leq 0$} \end{cases}} \label{eqn: hammer1} \\ F_h(t) &amp;= -m_h \label{eqn: hammer2} \end{align} \end{subequations} \end{document} ```
Title: "numberedList" feature in CKEditor 5 in Reactjs doesn't work Tags: reactjs;ckeditor;ckeditor5 Question: I read many questions and their answers about CKEditor 5 but I've not resolved my problem yet. Here my react component that I used for CKEditor: ```import React from 'react'; import CKEditor from '@ckeditor/ckeditor5-react'; import ClassicEditor from '@ckeditor/ckeditor5-build-classic'; ClassicEditor.defaultConfig = { toolbar: [ "heading", "|", "bold", "fontFamily", "italic", "link", "bulletedList", "numberedList", "blockQuote", "insertTable", "undo", "redo" ], // This value must be kept in sync with the language defined in webpack.config.js. language: 'fa' }; const BusinessDescription = ({ onChange, defaultValue }) =&gt; { return <div className="Business-editor "&gt; <CKEditor editor={ ClassicEditor } data={defaultValue || ''} onBlur={ ( event, editor ) =&gt; { onChange(editor.getData()); }} /&gt; </div&gt;; }; export default BusinessDescription; ``` My problem is: When a user selects "numberedList" icon it doesn't work, also when selects "bulletedList" icon, but when selects "blockQuote" then "bulletedList", the features for block quote and bulleted list work well. The weierd situation will happened when a user selects "blockQuote" then "numberedList". in this situation the features for block quote and bulleted list work again and under no circumstances "numberedList" doesn't work. Here is another answer: Add this css. ```.ck.ck-content ul, .ck.ck-content ul li { list-style-type: inherit; } .ck.ck-content ul { /* Default user agent stylesheet, you can change it to your needs. */ padding-left: 40px; } .ck.ck-content ol, .ck.ck-content ol li { list-style-type: decimal; } .ck.ck-content ol { /* Default user agent stylesheet, you can change it to your needs. */ padding-left: 40px; } ``` The styles must have been overrided. github-comment
Title: The powershell commandlet New-AzureRmWebAppSlot randomly gives a "'Location' cannot be null" error Tags: azure-devops;azure-web-app-service;azure-pipelines;azure-powershell;azure-rm Question: We have a PowerShell script that for each deployment creates a slot on each of the Azure web app that is involved in the deployment. This morning this suddenly started to fail for many of our deployments, but not all even it the same code was being run and deployed. The line that started to fail: ```$deploySlot = New-AzureRmWebAppSlot -ResourceGroupName "$ResourceGroupName" -Name "$($webapp.serviceApp)" -Slot "$slotName" ``` I added ```Resolve-AzureRmError -Last``` in a try catch around the command and got the following: ```2018-10-17T06:35:06.0228046Z 2018-10-17T06:35:06.0228769Z 2018-10-17T06:35:06.0230563Z HistoryId: 1 2018-10-17T06:35:06.0230703Z 2018-10-17T06:35:06.0231161Z 2018-10-17T06:35:06.0234999Z Message : 'Location' cannot be null. 2018-10-17T06:35:06.0235402Z StackTrace : at Microsoft.Azure.Management.WebSites.Models.Resource.Validate() 2018-10-17T06:35:06.0235646Z at Microsoft.Azure.Management.WebSites.Models.Site.Validate() 2018-10-17T06:35:06.0268780Z at Microsoft.Azure.Management.WebSites.WebAppsOperations.<BeginCreateOrUpdateSlotWithHttpMessagesAs 2018-10-17T06:35:06.0269062Z ync&gt;d__326.MoveNext() 2018-10-17T06:35:06.0269217Z --- End of stack trace from previous location where exception was thrown --- 2018-10-17T06:35:06.0269503Z at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 2018-10-17T06:35:06.0269658Z at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 2018-10-17T06:35:06.0301248Z at Microsoft.Azure.Management.WebSites.WebAppsOperations.<CreateOrUpdateSlotWithHttpMessagesAsync&gt;d 2018-10-17T06:35:06.0302594Z __137.MoveNext() 2018-10-17T06:35:06.0304593Z --- End of stack trace from previous location where exception was thrown --- 2018-10-17T06:35:06.0306400Z at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 2018-10-17T06:35:06.0306724Z at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 2018-10-17T06:35:06.0312293Z at Microsoft.Azure.Management.WebSites.WebAppsOperationsExtensions.<CreateOrUpdateSlotAsync&gt;d__265. 2018-10-17T06:35:06.0314813Z MoveNext() 2018-10-17T06:35:06.0314990Z --- End of stack trace from previous location where exception was thrown --- 2018-10-17T06:35:06.0315157Z at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 2018-10-17T06:35:06.0315321Z at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 2018-10-17T06:35:06.0315562Z at Microsoft.Azure.Commands.WebApps.Utilities.WebsitesClient.CreateWebApp(String 2018-10-17T06:35:06.0315722Z resourceGroupName, String webAppName, String slotName, String location, String serverFarmId, 2018-10-17T06:35:06.0315886Z CloningInfo cloningInfo, String aseName, String aseResourceGroupName) 2018-10-17T06:35:06.0316053Z at 2018-10-17T06:35:06.0316261Z Microsoft.Azure.Commands.WebApps.Cmdlets.DeploymentSlots.NewAzureWebAppSlotCmdlet.ExecuteCmdlet() 2018-10-17T06:35:06.0316608Z at Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet.ProcessRecord() 2018-10-17T06:35:06.0316902Z Exception : Microsoft.Rest.ValidationException 2018-10-17T06:35:06.0317067Z InvocationInfo : {New-AzureRmWebAppSlot} 2018-10-17T06:35:06.0323731Z Line : $deploySlot = New-AzureRmWebAppSlot -ResourceGroupName "$ResourceGroupName" -Name 2018-10-17T06:35:06.0324841Z "$($webapp.serviceApp)" -Slot "$slotName" 2018-10-17T06:35:06.0325059Z 2018-10-17T06:35:06.0325200Z Position : At D:\a\r1\a\Cloud apps\AzureDeploy\Publish-WebApps.ps1:313 char:31 2018-10-17T06:35:06.0326182Z + ... eploySlot = New-AzureRmWebAppSlot -ResourceGroupName "$ResourceGroupN ... 2018-10-17T06:35:06.0326820Z + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 2018-10-17T06:35:06.0326981Z HistoryId : 1 2018-10-17T06:35:06.0327103Z ``` The command is executed on a VSTS Azure PowerShell task. I added a retry inside the try catch and it seems to always work for the retry. Is something timing out? Comment: Did you crossed slot limit ? Comment: No. Running the same command inside the `catch section` works fine as a workaround, so pretty sure that is not the case
Title: MPI deadlock (Message Passing Interface) Tags: mpi Question: I'm beginner in MPI coding, I tried to pass message using simple two dimensional array, dividing process in two process elements...but code get stucks in message passing...the code is as follows...I'd edited as sending and receiving order ```#include<stdio.h&gt; #include<mpi.h&gt; double a[15][15]; int main(int argc, char **argv) { int process_id,nprocess; int i,j; int Nxl=5,Nx=10,Ny=10; MPI_Status status; MPI_Datatype line; MPI_Init(&amp;argc,&amp;argv); MPI_Comm_size(MPI_COMM_WORLD,&amp;nprocess); MPI_Comm_rank(MPI_COMM_WORLD,&amp;process_id); //Nxl=((Nx-2)/nprocess)+2; //printf("NXL=%d\n",Nxl); // printf("process_id=%d\n",process_id); if(process_id==0) { for(i=1;i<=5;i++) { for(j=1;j<=Ny;j++) { a[i][j]=3*2*i; MPI_Send(&amp;a[Nxl-1][j],1,MPI_DOUBLE,0,1,MPI_COMM_WORLD); } } for(i=1;i<=5;i++) { for(j=1;j<=Ny;j++) { printf("matrices=%f\n",a[i][j]); MPI_Recv(&amp;a[1][j],1,MPI_DOUBLE,1,1,MPI_COMM_WORLD,&amp;status); printf("PROCESS_ID=%d\n",process_id); } } } if(process_id==1) { for(i=6;i<=10;i++) { for(j=1;j<Ny;j++) { a[i][j]=4*2; MPI_Send(&amp;a[2][j],1,MPI_DOUBLE,1,2,MPI_COMM_WORLD); } } for(i=6;i<=10;i++) { for(j=1;j<Ny;j++) { MPI_Recv(&amp;a[Nxl][j],1,MPI_DOUBLE,0,1,MPI_COMM_WORLD,&amp;status); printf("PROCESS_ID=%d\n",process_id); } } } MPI_Finalize(); } ``` Comment: `MPI_Sendrecv` is your best friend in that case. Here is the accepted answer: (I'm going to write this answer as if you have more than two process to be more general for posterity, but you can reinterpret it to mean just two.) Hristo and John are right. The problem is that all of your processes are sending a message before anyone receives it. This means that the sends may never return. Somehow you need to make sure that the receives are also available. You can do this in one of two ways: Convert blocking calls to non-blocking If you convert your blocking (```MPI_SEND```/```MPI_RECV```) calls to non-blocking calls and add an ```MPI_WAITALL``` at the end of your code, that would allow all of the processes to simultaneously send and receive the messages. Then after the waitall, you can do whatever you want to do with the data that you've received. Convert ```MPI_SEND```/```MPI_RECV``` to ```MPI_SENDRECV``` This option has essentially the same result in that you will do the sends and receives simultaneously, but you still need to be careful to ensure that everyone is entering exchanges with the same processes. For instance, if you had everyone trying to do a communication in a ring, you'd need to make sure that they all send to the right and receive from the left (or vice versa) rather than do both the send and receive to the right (which would still be a deadlock). Here is another answer: You are making both participants in the conversation speak, then listen. You need to make it so one speaks and the other listens, followed by the opposite. Comment for this answer: Are you able to get even a trivial MPI program working? One that just sends once in one process and receives in the other? Comment for this answer: Even after editing and make the send and receive independently, dint help