text
stringlengths
15
59.8k
meta
dict
Q: Swagger-codegen-js not finding not translating the response schema defined on the api endpoint Summary I am using swagger-codegen-js to generate typescript files according to the swagger.json defined by an external api. packages used "swagger-js-codegen": "^1.12.0", Alleged Problem The return type on the method listMovies on the generated TS file is simply Promise<Request.Response> and not Promise<Array<Movie>>, i did expect it to be array of movies as the response clearly state the schema and thought/assumed that would be translated. Given a json along the lines of the following, the "/movies": { "get": { "description": "Lists movies", "operationId": "listMovies", "responses": { "200": { "description": "Movie", "schema": { "type": "array", "items": { "$ref": "#/definitions/Movie" } } }, "default": { "$ref": "#/responses/genericError" } } }, "definitions": { "Movie": { "description": "something", "type": "object", "properties": { "archivedAt": { "description": "When the movie was archived", "type": "string", "format": "nullable-date-time", "x-go-name": "ArchivedAt", "readOnly": true } } } Generated TS Method /** * Lists movies * @method * @name Api#listMovies */ listMovies(parameters: { $queryParameters ? : any, $domain ? : string }): Promise <request.Response> { const domain = parameters.$domain ? parameters.$domain : this.domain; let path = '/movies'; . . . this.request('GET', domain + path, body, headers, queryParameters, form, reject, resolve); }); } The script i use to generate the above ts file is straight from the github sample const generateTSFilesUsingSwaggerJsCodegen = function () { var fs = require('fs'); var CodeGen = require('swagger-js-codegen').CodeGen; var file = 'build/sample.json'; var swagger = JSON.parse(fs.readFileSync(file, 'UTF-8')); var tsSourceCode = CodeGen.getTypescriptCode({ className: 'Api', swagger: swagger, imports: ['../../typings/tsd.d.ts'] }); fs.writeFileSync('src/api/api.ts', tsSourceCode) } Am i missing something on the wire up/options passed or is this the expected generated file given the json file and that i need to write custom script to get what I want? A: It is only possible to edit the codegen to change this. But you can just use the body of the return value <restMethod>(<paramters>).then(respose: <request.Response>) { let responseObject: Array<ListMovies> = response.body as Array<ListMovies>; ... } If you want to adapt the codegen, pull it from git and change the following files: lib/codegen.js: var getViewForSwagger2 = function(opts, type){ var swagger = opts.swagger; var methods = []; var authorizedMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'COPY', 'HEAD', 'OPTIONS', 'LINK', 'UNLIK', 'PURGE', 'LOCK', 'UNLOCK', 'PROPFIND']; var data = { isNode: type === 'node' || type === 'react', isES6: opts.isES6 || type === 'react', description: swagger.info.description, isSecure: swagger.securityDefinitions !== undefined, moduleName: opts.moduleName, className: opts.className, imports: opts.imports, domain: (swagger.schemes && swagger.schemes.length > 0 && swagger.host && swagger.basePath) ? swagger.schemes[0] + '://' + swagger.host + swagger.basePath.replace(/\/+$/g,'') : '', methods: [], definitions: [] }; _.forEach(swagger.definitions, function(definition, name){ data.definitions.push({ name: name, description: definition.description, tsType: ts.convertType(definition, swagger) }); }); the last _.forEach is moved from the bottom of the method to here. var method = { path: path, className: opts.className, methodName: methodName, method: M, isGET: M === 'GET', isPOST: M === 'POST', summary: op.description || op.summary, externalDocs: op.externalDocs, isSecure: swagger.security !== undefined || op.security !== undefined, isSecureToken: secureTypes.indexOf('oauth2') !== -1, isSecureApiKey: secureTypes.indexOf('apiKey') !== -1, isSecureBasic: secureTypes.indexOf('basic') !== -1, parameters: [], responseSchema: {}, headers: [] }; if (op.responses && op.responses["200"]) { method.responseSchema = ts.convertType(op.responses["200"], swagger); } else { method.responseSchema = { "tsType": "any" } } this is starting at line 102. add responseSchema to method and append the if / else templates/typescript-class.mustache (line 68) resolve(response.body); templates/typescript-method.mustache (line 69) }): Promise<{{#responseSchema.isRef}}{{responseSchema.target}}{{/responseSchema.isRef}}{{^responseSchema.isRef}}{{responseSchema.tsType}}{{/responseSchema.isRef}}{{#responseSchema.isArray}}<{{responseSchema.elementType.target}}>{{/responseSchema.isArray}}> { That only works for simple types, Object types and arrays of simple / object types. I did not implement the enum types. A: That seems like the expected behaviour. The TypeScript Mustache template outputs a fixed value: ... }): Promise<request.Response> { ...
{ "language": "en", "url": "https://stackoverflow.com/questions/49204349", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Dynamically resize UICollectionViewCell in non-scrolling UICollectionView I have a small, single row horizontal layout UICollectionView at the top of the screen. It can contain up to a maximum of 6 items. The problem is that I want all 6 items visible without scrolling (this collection view is also going to be used in a Today extension which doesn't allow scrolling). What I want to do is reduce the cell-size and inter-item spacing a little bit to allow all 6 cells to fit. Basically I'm trying to avoid this: I've been playing with this for a while but I'm not sure how to approach it. I created a method that's fired every time an item is added or removed from the collection view, just before [self.collectionview reloadData] is called. -(void)setupCollectionViewLayout{ UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout*)self.buttonBarCollectionView.collectionViewLayout; //Figure out if cells are wider than screen CGFloat screenwidth = self.view.frame.size.width; CGFloat sectionInsetLeft = 10; CGFloat sectionInsetRight = 10; CGFloat minItemSpacing = flowLayout.minimumInteritemSpacing; CGSize itemsize = CGSizeMake(58,58); CGFloat itemsizeWidth = itemsize.width; CGFloat totalWidth = sectionInsetLeft + sectionInsetRight + (itemsizeWidth * _armedRemindersArray.count) + (minItemSpacing * (_armedRemindersArray.count -2)); CGFloat reductionAmount = itemsizeWidth; if (totalWidth > screenwidth) { while (totalWidth > screenwidth) { totalWidth = totalWidth - 1; reductionAmount = reductionAmount - 1; } CGSize newCellSize = CGSizeMake(reductionAmount, reductionAmount); flowLayout.itemSize = newCellSize; } else flowLayout.itemSize = itemsize; } This is the result. Not exactly what I was expecting. Not only did it squash everything to the left and also added a second line, but I also seem to have a cell-reuse issue. Truthfully I would just use static-cells if it was even an option, but unfortunately it seems like it's not possible. What should I be doing? Subclassing UICollectionViewFlowLayout? Won't that basically do the same thing I'm doing here with the built-in flow layout? EDIT: Kujey's answer is definitely closer to what I need. I still have a cell-reuse issue though. A: Xcode provides an object designed for your need. It's called UICollectionViewFlowLayout and all you need to do is subclass it and place your cells the way you want. The function prepareForLayout is call every time the collection view needs to update the layout. The piece of code you need is below : #import "CustomLayout.h" #define MainCell @"MainCell" @interface CustomLayout () @property (nonatomic, strong) NSMutableDictionary *layoutInfo; @end @implementation CustomLayout -(NSMutableDictionary *) layoutInfo { if (!_layoutInfo) { _layoutInfo = [NSMutableDictionary dictionary]; } return _layoutInfo; } -(void) prepareLayout { NSMutableDictionary *cellLayoutInfo = [NSMutableDictionary dictionary]; NSIndexPath *indexPath; CGFloat itemWidth; CGFloat itemSpacing; CGFloat widthWithoutSpacing = [self collectionViewContentSize].width / ([self.collectionView numberOfItemsInSection:0]); if (widthWithoutSpacing > [self collectionViewContentSize].height) { itemWidth = [self collectionViewContentSize].height; itemSpacing = ([self collectionViewContentSize].width - itemWidth*[self.collectionView numberOfItemsInSection:0])/ ([self.collectionView numberOfItemsInSection:0]+1); } else { itemWidth = widthWithoutSpacing; itemSpacing = 0; } CGFloat xPosition = itemSpacing; for (NSInteger section = 0; section < [self.collectionView numberOfSections]; section++) { for (NSInteger index = 0 ; index < [self.collectionView numberOfItemsInSection:section] ; index++) { indexPath = [NSIndexPath indexPathForItem:index inSection:section]; UICollectionViewLayoutAttributes *itemAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath]; CGRect currentFrame=itemAttributes.frame; currentFrame.origin.x = xPosition; currentFrame.size.width = itemWidth; currentFrame.size.height = itemWidth; itemAttributes.frame=currentFrame; cellLayoutInfo[indexPath] = itemAttributes; xPosition += itemWidth + itemSpacing; } } self.layoutInfo[MainCell] = cellLayoutInfo; } - (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds { return YES; } - (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect { NSMutableArray *allAttributes = [NSMutableArray arrayWithCapacity:self.layoutInfo.count]; [self.layoutInfo enumerateKeysAndObjectsUsingBlock:^(NSString *elementIdentifier, NSDictionary *elementsInfo, BOOL *stop) { [elementsInfo enumerateKeysAndObjectsUsingBlock:^(NSIndexPath *indexPath, UICollectionViewLayoutAttributes *attributes, BOOL *innerStop) { if (CGRectIntersectsRect(rect, attributes.frame)) { [allAttributes addObject:attributes]; } }]; }]; return allAttributes; } -(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath { return self.layoutInfo[MainCell][indexPath]; } -(CGSize) collectionViewContentSize { return self.collectionView.frame.size; } @end You can also change the y origin of your cells if you need to center them vertically. A: try with this code. I get the width and use _armedRemindersArray (i guess you use this array for the items). -(void)setupCollectionViewLayout{ UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout*)self.buttonBarCollectionView.collectionViewLayout; //Figure out if cells are wider than screen CGFloat screenwidth = self.view.frame.size.width; CGFloat width = screenwidth - ((sectionInsetLeft + sectionInsetRight) *_armedRemindersArray.count + minItemSpacing * (_armedRemindersArray.count -2)); CGSize itemsize = CGSizeMake(width,width); flowLayout.itemSize = itemsize; } A: I don't know why you're setting the itemsize first, and then reducing it. I think you should do it the other way around: -(void)setupCollectionViewLayout{ UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout*)self.buttonBarCollectionView.collectionViewLayout; CGFloat sectionInsetLeft = 10; CGFloat sectionInsetRight = 10; CGFloat minItemSpacing = flowLayout.minimumInteritemSpacing; // Find the appropriate item width (<= 58) CGFloat screenwidth = self.view.frame.size.width; CGFloat itemsizeWidth = (screenwidth - sectionInsetLeft - sectionInsetRight - (minItemSpacing * (_armedRemindersArray.count -2))) / _armedRemindersArray.count itemsizeWidth = itemsizeWidth > 58 ? 58 : itemsizeWidth; flowLayout.itemSize = CGSizeMake(itemsizeWidth, itemsizeWidth); } Does this work? If not, could you please include more of your code?
{ "language": "en", "url": "https://stackoverflow.com/questions/28131440", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Openshift new-app from image creates service with incorrect ports I am using openshift oc new-app to create a app from a image. However oc new-app is creating the associated openshift service incorrectly with only one tcp port, not the two ports than the application uses. Is there any simple way to force openshift new-app to correctly create the service with the two correct ports when building from a image rather than incorrectly with only one port ? Alternatively is there a command line way to add the extra port to the service created that can be scripted (I know about oc edit) .. (Disclaimer.. I am new to openshift and have lots to learn)
{ "language": "en", "url": "https://stackoverflow.com/questions/72825198", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I get rid of the parentheses in the dataframe column?(Python) I have dataframe like this I want to remove the parentheses in the Movie_Name column. Here is a few example df_Movie["Movie Name"].str.findall(r'\([^()]*\)').sum() ['(500)', '(Eksiteu)', '(Mumbai Diaries)', '(Geukhanjikeob)', '(Erkekler Ne İster?)', '(The Witch)', '(Ji Hun)'] And then ı tried this solution. import re df_Movie["Movie Name"] = df_Movie["Movie Name"].str.replace(r'\([^()]*\)', ' ', regex = True) Here is the output of the solution for one example. df_Movie.iloc[394, :] Movie Name Days of Summer Year 2009 IMDB 7.7 Name: 394, dtype: object In this case, the values ​​between the parentheses are completely lost. I don't want that. I want output like this : (500) Days of Summer --> 500 Days of Summer How can ı solve this ? A: You can remove all parentheses from a dataframe column using df_Movie["Movie Name"] = df_Movie["Movie Name"].str.replace(r'[()]+', '', regex=True) The [()]+ regex pattern matches one or more ( or ) chars. See the regex demo.
{ "language": "en", "url": "https://stackoverflow.com/questions/71011910", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: pyspark - how to handle unicode from hive I am trying read a hive table in pyspark from pyspark.sql import SQLContext from pyspark import HiveContext hivec = HiveContext(sc) sqlc = SQLContext(sc) t = hivec.sql("select * from database.table").collect() data = sqlc.createDataFrame(t) data.registerTempTable("masterTable") sqlc.sql("select * from masterTable").show() I get the below error UnicodeEncodeError: 'ascii' codec can't encode character u'\ufffd' in position 8871: ordinal not in range(128) What I have tried: I figured out the record that was falling over, when I "select * from " in hive for the same record, there is no error reported nor can I see any unicode - t = hivec.sql("select * from database.table").collect() there are no errors reported in t variable itself '>>>t prints out all the rows As soon as t gets converted to DataFrame the issue pops up I tried encoding and decoding, combination between 'utf-8' and 'ascii' mainly as I couldn't tell if the field was a unicode or a ascii visually as hive select nor printing the list was showing anything visible or throwing errors. data.select(*(c.encode("ascii","ignore") if not isinstance(c,unicode) else c for c in data.columns )).show(10) Throws the same error. Any suggestions how to get around this?
{ "language": "en", "url": "https://stackoverflow.com/questions/43751723", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: The removeChild(); is removing two inputs? I just need to remove 1 input I'm new to javascript, and currently, I need an individual delete function. I decided to use variable.removeChild() but it's deleting 2 inputs document.addEventListener('DOMContentLoaded', () => { document.getElementById("delete").addEventListener("click", function deletes(){ var parent = document.getElementById("list"); var child = parent.getElementsByTagName("li")[0]; console.log(child); parent.removeChild(child); //deletes a pair of my li inputs }); }); Here is how my HTML code looks like <body> <h1>LIST</h1> <h2>Items: </h2> <div> <ol id="list"> <li>test</li> </ol> </div> <form id="insert"> <input type="text" id="itemInput" placeholder="Item" name="item"> <input type="submit" id="add" value="Add"> </form> <input type="submit" id="search" value="Search"> //search doesn't do anything yet <input type="submit" id="delete" value="Delete first item"> //Here is where it begins </body> Here is my other function. I also use addEventListener() perhaps is that the problem? This code allows me to add list items dynamically to how the user wishes document.addEventListener('DOMContentLoaded', () => { //calls function once #insert has submit a form/hit the input document.querySelector('#insert').onsubmit = () => { //create variable if(document.querySelectorAll('li').length >= 10){ return false; }; //get the value of the input let name = document.querySelector('#itemInput').value; //stores value in the h3 tag //create element of 'li' const li = document.createElement('li'); //add the contents to the value of 'name' li.innerHTML = name; //now append the element to the #list section document.querySelector('#list').append(li); //gets the length of all the list items (li) and stored it in counter counter = document.querySelectorAll('li').length; //change the h2 tag with the updated list items document.querySelector('h2').innerHTML = `Items: ${counter}`; //prevents the form from submitting (good for debugging!!!) return false; }; }); A: Get the list with document.querySelector('#list') and the first li by adding .querySelectorAll('li')[0], then find inputs inside. document.addEventListener('DOMContentLoaded', () => { document.querySelector('#delete').addEventListener("click", function deletes(){ let li = document.querySelector('#list').querySelectorAll('li')[0]; let inputs = li.querySelectorAll('input'); // Is there any input in li? if(inputs.length > 0) { // Delete only the first one inputs[0].remove(); // If you want to keep other inputs, just disable the button this.disabled = true; } }); }); <ul id="list"> <li> <input type="text" value="input1"> <input type="text" value="input2"> </li> </ul> <button id="delete">Delete</button> querySelector() and querySelectorAll() lets you find items by id, classname, tagname, attributes, etc. Just like jQuery does. Reference: https://developer.mozilla.org/en/docs/Web/API/Document/querySelector
{ "language": "en", "url": "https://stackoverflow.com/questions/62842802", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Select select form options using links and asmselect I have integrated jquery-asmselect and would like to be able to also select the options using other links on the page. To visualize what I'm trying to do, you can view the page here Here is the jquery code I'm using for asmselect: $(document).ready(function() { $("#CategoryID").asmSelect({ addItemTarget: 'bottom', animate: true, highlight: false, sortable: false }).after($("<a href='#' class='select-all'>select all neighborhoods</a>").click(function() { $("#CategoryID").children().attr("selected", "selected").end().change(); return false; })); $("#search_SubCategoryID").asmSelect({ addItemTarget: 'bottom', animate: true, highlight: false, sortable: false }).after($("<a href='#' class='select-all'>select all cuisines</a>").click(function() { $("#search_SubCategoryID").children().attr("selected", "selected").end().change(); return false; })); }); A: First of all, you'll need to identify in wich neighborhood you are clicking. Adding a rel (like in the options) might work: ... <li class="evillage"> <a href="#" rel="asm0option0">East Village/LES</a> </li> ... Then, add this script: $(".search-map a").click(function(event) { event.preventDefault(); var hood = $(this).attr('rel'); var $option = $('option[rel=' + hood + ']'); $option.change(); return false; }); Based on this asmselect example. You just need to get the correspondig option depending on the clicked link, and then call the change(); trigger on it. EDITED: The above code failed big time :P Here's the new version (With a working fiddle): $(".search-map a").click(function() { var $city = $(this).html(); var $rel = $(this).attr('rel'); var disabled = $('#asmSelect0 option[rel=' + $rel + ']:first').attr('disabled'); if (typeof disabled !== 'undefined' && disabled !== false) { return false; } var $option = $('<option></option>').text($city).attr({'selected': true, 'rel': $rel}); $('#asmSelect0').append($option).change(); $('#asmSelect0 option[rel=' + $rel + ']:first').remove(); return false; }); I had to do something I don't really like, but I couldn't find any other way of doing this without conflicting with the plugin. Anyway, it's not that bad. Basically I get the name of the neighborhood, the rel to identify the option, generate a new <option>, change(); it, and delete the old option tag. The plugin didn't like trying to change the tag itself without creating a new one... I had to add the if (...) thing because when adding a neighborhood (disabling it on the select), and clicking again on the same neighborhood, it enabled it on the select (And we don't want that, since it's already selected). With that condition, if we click on a link whose neighborhood is disabled, we'll do nothing and the option will remain the same. Sorry if my explanation sucks, It took me a while to get the problem, I had to build everything up again, and I felt like having a lack of english xD Hope it works!
{ "language": "en", "url": "https://stackoverflow.com/questions/8467850", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: IFilterProvider Injection without a Service Locator My goal: To inject an IFilterProvider in the case where one is provided by DI, but to fallback to the global FilterProviders.Providers.GetFilters() method by default. There are a lot of resources on the Internet (including an "official" Microsoft one) that demonstrate how to inject the IFilterProvider interface into a class. However, all of them use the service locator anti-pattern (per Mark Seeman) to do so. Here is a list of the ones I found: * *http://msdn.microsoft.com/en-us/vs2010trainingcourse_aspnetmvcdependencyinjection_topic4.aspx *http://merbla.blogspot.com/2011/02/ifilterprovider-using-autofac-for-mvc-3.html *http://thecodinghumanist.com/blog/archives/2011/1/27/structuremap-action-filters-and-dependency-injection-in-asp-net-mvc-3 *IFilterProvider and separation of concerns So what's wrong with these methods? They all inject a DI container into the target class instead of the other way around. If you see something in your class like container.Resolve(), then you are not yielding control of the lifetime of objects to the DI container, which is what inversion of control is really about. In addition, the problem with trying to create a fallback to the global FilterProviders.Providers instance is that although it has the same signature as the IFilterProvider interface, it does not actually implement this interface. So how can the global static member be injected as a logical default and still allow the use of DI to override it? A: Create an wrapper class based on IFilterProvider that returns the global FilterProviders.Providers.GetFilters() result, like this: public class FilterProvider : IFilterProvider { #region IFilterProvider Members public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor) { return FilterProviders.Providers.GetFilters(controllerContext, actionDescriptor); } #endregion } Then, adjust the constructor in your classes that require the dependency. public class MyBusinessClass : IMyBusinessClass { public MyBusinessClass( IFilterProvider filterProvider ) { if (filterProvider == null) throw new ArgumentNullException("filterProvider"); this.filterProvider = filterProvider; } protected readonly IFilterProvider filterProvider; public IEnumerable<AuthorizeAttribute> GetAuthorizeAttributes(ControllerContext controllerContext, ActionDescriptor actionDescriptor) { var filters = filterProvider.GetFilters(controllerContext, actionDescriptor); return filters .Where(f => typeof(AuthorizeAttribute).IsAssignableFrom(f.Instance.GetType())) .Select(f => f.Instance as AuthorizeAttribute); } } Next, configure your DI container to use FilterProvider concrete type as the default. container.Configure(x => x .For<IFilterProvider>() .Use<FilterProvider>() ); If you need to override the default and provide your own IFilterProvider, now it is just a matter of creating a new concrete type based on IFilterProvider and swapping what is registered in the DI container. //container.Configure(x => x // .For<IFilterProvider>() // .Use<FilterProvider>() //); container.Configure(x => x .For<IFilterProvider>() .Use<NewFilterProvider>() ); Most importantly, there is no service locator anywhere in this pattern.
{ "language": "en", "url": "https://stackoverflow.com/questions/15048030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to read checkbox value in Angular I am trying to get the value of checkbox - i.e true or false. But this is only returning me Object Object. <mat-cell *matCellDef="let row"> <mat-checkbox [checked]="row.isDisabled" (change)="UpdateValue($event,row)"> </mat-checkbox> </mat-cell> In my TS, I have this: UpdateValue(event:any, myStock: stock) { alert(event); ... } Does anyone know how I can get the value as true or false? A: Simply use: UpdateValue(event:any,myStock: stock) { // ... console.log(event.checked); } Here's a working stackblitz for the same. A: Just use ngModel <mat-cell *matCellDef="let row"> <mat-checkbox [checked]="row.isDisabled" [(ngmModel)]="checkValue" (change)="UpdateValue($event,row)"></mat-checkbox> </mat- cell> UpdateValue(event:any,myStock: stock) { alert(this.checkValue); }
{ "language": "en", "url": "https://stackoverflow.com/questions/57213809", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is it possible to parse a remote file with ajax/javascript prototype I want to solve this puzzle but the file resides on remote server. How can I parse this file because I keep getting this error. XMLHttpRequest cannot load http://www.weebly.com/weebly/publicBackend.php. Origin http://mysite.com is not allowed by Access-Control-Allow-Origin. Refused to get unsafe header "X-JSON" Code Below <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <title>Untitled Document</title> <script type="text/javascript" src="prototype.js"></script> <!-- Puzzle starts here --> <script type='text/javascript'> // Note: there may be some unfinished code here, that needs finishing... // You should probably try to get this function working... function solvePuzzle() { new Ajax.Request('http://www.weebly.com/weebly/publicBackend.php', { parameters:{ pos: 'solvepuzzle' }, onSuccess:handlerSolvePuzzle, onFailure:function() { alert('Transmission error. Please try again.'); } }); } function handlerSolvePuzzle(t) { var responseText = t.responseText; responseText = responseText.replace(/\n/, ""); if (responseText.match(/!!$/)) { alert("Oops: "+responseText); } else { // Still need to decode the response // Once the response is decoded, we can fire off the alert // giving the user further instructions //alert(responseText); //alert('To complete the challenge, '+t.responseText); } } </script> </head> <body> <input type="button" onclick="solvePuzzle()" value="hello"/> </body> </html> A: Chrome and Firefox's developer tools allow you to modify JS on the fly. If you're on Chrome, open up the console by going to the menu View->Developer->JavaScript Console. Copy the js from the page source. Alter it. Then paste altered javascript function(s) into the console. Hit enter. Then start typing 'solvePuzzle();' Hit enter. You'll see the response come back. For Firefox, you'll need to download Firebug plugin. A: You cannot do this from JavaScript due to the same origin policy: https://developer.mozilla.org/en/Same_origin_policy_for_JavaScript. If this weebly site supports some sort of JSON API, you could use JSONP: http://en.wikipedia.org/wiki/JSONP. Other than that, you're probably better off interacting with this site via the server side due to security restrictions on the client side. A: Consider installing a HTTP tunnel on your "mysite.com" so that the browser does not have to access "weebly.com" directly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7800781", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Updated command to start blank project with ionic2 and angular2? Trying to create blank project with ionic2 not ionic1 or ionic3 using the below command in terminal ionic start SqliteDemo blank --type ionic2 Error comes as below: ✔ Creating directory ./SqliteDemo - done! ✖ Looking up starter - failed! [ERROR] Unable to find starter template for blank If this is not a typo, please make sure it is a valid starter template within the starters repo: https://github.com/ionic-team/starters what i have tried ? ionic start SQliteDemo blank --v2 not worked all above commands just create Folder for the given name and nothing is inside. Actually Trying: I need to work with sqlite storage/ with any android native api's, as first attempt i try to do a sample project based on sqlite so that i can add android platform to this project and open with Android-Studio and check whether the .db file is created and working or not using Android-Monitor. If any references for this question will be very much appreciated.
{ "language": "en", "url": "https://stackoverflow.com/questions/49168863", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Java code is running select and update query for every data I am writing a Java code in Spring JPA which can add or update a data when saveData function is called. what I am trying to do is that if data is new it gets added as a new record in the database or else it will be updated. public void saveData(List<StudentTable> studentTableList){ List< StudentTable > data= new ArrayList<>(); for(StudentTable dt: studentTableList){ if(dt.getStudentId() ==null) { data.add(dt); }else{ studentRepository.findById(dt.getStudentId()).map( student->{ student.setFirstName(dt.getFirstName()); student.setLastName(dt.getLastName ()); student.setPhone(dt.getPhone()); student.setAddress(dt.getAddress()); return data.add(student); }); } studentRepository.saveAll(data); data.clear(); } } While this code is working fine I see performance issues as my entries grow. I see that update and select queries are run for each row of the table which is slowing down the performance. I want to know if there is any way to run queries only for those rows which are updated or added on a single post request or to improve the performance? A: What about 2 blocks of code for each case? Student student = studentRepository.findById(dt.getStudentId()); if(student == null){ Student newStudent = new Student(); //add data newStudent.save(); } else { student.setFirstName(dt.getFirstName()); student.setLastName(dt.getLastName ()); student.setPhone(dt.getPhone()); student.setAddress(dt.getAddress()); student.update(); } A: You can follow what @fladdimir mentioned. Or, here is my suggestion[will not provide any code, leaving up to you]: * *filter objects which are old ones[contains id as I can see from your code] and news ones in two separate lists *List all ids *use id <--> object as keyValue in a map *Query all the objects with idList you got using IN clause *Now, set value as you are doing in your 2nd code block from the map, add them in a list *merge this list with new objectList *save them altogether with saveAll(your_merged_list) I am not saying this is the optimized way, but at least you can reduce load on your db.
{ "language": "en", "url": "https://stackoverflow.com/questions/70464256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get a list from WebApi controller using jquery ajax I have this controller that returns correct results when I call it from a browser. public async Task<IHttpActionResult> Get(string Id) { if (Id == null) return BadRequest(); try { var items = await obj.GetItems(Id); return Ok(items.ToList()); } catch (Exception e) { return Content(HttpStatusCode.BadRequest, e.Message); } } In my view, I have this jquery. $.ajax({ type: 'GET', url: url, dataType: 'json', data: { Id: "5AE158", }, success: function (data) { alert('success'); }, error: function (x) { alert("error"); } }); When I trigger the function from the UI, I hit a breakpoint in the Controller and I see that it returns correct results, but in the view control flows to the error handler. I experimented with many combinations of dataType, type and function signatures but I'm not able to get a success return value. Any help is appreciated. A: Thanks to all that responded for the clues that helped me solve this. I looked in the console and saw the error message "No 'Access-Control-Allow-Origin' header is present on the requested resource". What wasn't clear in my question was that the url I was trying to reach was on a different server and I was encountering this problem. Thanks for the help.
{ "language": "en", "url": "https://stackoverflow.com/questions/52122759", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: find out the number of multiples of K among the given N numbers You are given N numbers. Now you have Q queries. For each query you will be given an integer K Input Format The first line consists of number N. Next N line contains N numbers. Next line contains number of queries Q. Next Q lines contains Integer K for each query Output Format Output Q lines the answer for every query. Constraints 1 <= N <= 10^5; 1 <= numbers <= 10^5; 1 <= Q <= 10^5; 1 <= K <= 10^5 Sample Input 4 5 8 10 8 1 2 Sample Output 3 My code, getting one failed test case which uses 78000 inputs: ans = [] def countSieve(arr, n): MAX=max(arr) global ans ans = [0]*(MAX + 1) cnt = [0]*(MAX + 1) for i in range(n): cnt[arr[i]] += 1 for i in range(1, MAX+1): for j in range(i, MAX+1, i): ans[i] += cnt[j] def countMultiples(k): return(ans[k]) n=int(input()) a=[] count=0 for i in range(n): j=int(input()) a.append(j) countSieve(a,n) q=int(input()) k=[] for i in range(q): c=int(input()) k.append(c) i=0 for i in k: print(countMultiples(i)) A: The problem is that you create an array of size MAX(a) with a the list of your n numbers. This is inefficient if MAX(a) = 10^5 for example. You should find another way to check if a number A is multiple of number B, for example A%B == 0 (use of modulo). Try to remove countSieve and changed countMultiples. def countMultiples(query, numbers): count = 0 for i in numbers: if i%query == 0: count += 1 return count n=int(input()) numbers = [] for i in range(n): j=int(input()) numbers.append(j) q=int(input()) queries = [] for i in range(q): c=int(input()) queries.append(c) for i in queries: print(countMultiples(i, numbers)) EDIT : Here is an optimization. First I search for numbers divisors, for each divisor I increment a counter in a dict d, then for a query q I print d[q], which is the exact amount of multiples present in the n numbers. The method to search divisors of a number n : I make a loop until the square root of n, then for each divisor i, I also add r = n//i. I also use a dict divs to store divisors for each number n, in order not to re-calculate them if I already found them. Try this (it succeeded the problem https://hack.codingblocks.com/app/dcb/938) : import math d = {} divs = {} for _ in range(int(input())): num = int(input()) if num in divs: for e in divs[num]: d[e] = d.get(e, 0) + 1 else: div_list = [] for i in range(1, math.floor(math.sqrt(num)) + 1): if not num % i: div_list.append(i) d[i] = d.get(i, 0) + 1 r = num // i if (not num % r and r != i): div_list.append(r) d[r] = d.get(r, 0) + 1 divs[num] = div_list for i in range(int(input())): q = int(input()) print(d.get(q, 0)) A: Alternatively, you could try counting how often each number appears and then checking the counts for each multiple of k up to the largest of the N numbers. import collections n = int(input()) nums = [int(input()) for _ in range(n)] counts = collections.Counter(nums) m = max(nums) q = int(input()) for _ in range(q): k = int(input()) x = sum(counts[i] for i in range(k, m+1, k)) print(x) At first sign, this does not look much different than the other approaches, and I think this even still has O(N*Q) in theory, but for large values of Q this should give quite a boost. Let's say Q = 100,000. For all K > 10 (i.e. all except 10 values for K) you will only have to check at most 10,000 multiples (since m <= 100,000). For all K > 10,000 (i.e. 90% of possible values) you only have to check at most 10 multiples, and for 50% of Ks only K itself! I other words, unless there's an error in my logic, in the worst case of N = Q = 100,000, you only have about 1,1 million check instead of 10,000,000,000. >>> N = Q = 100000 >>> sum(N//k for k in range(1,Q+1)) 1166750 (This assumes that all K are different, but if not, you can cache the results in a dict and then will only need a single check for the duplicates, too.) On closer inspection, this approach is in fact pretty similar to what your sieve does, just a bit more compact and computing the values for each k as needed instead of all at once. I did some timing analysis using random inputs using gen_input(n, q, max_k). First, all the algorithms seem to produce the same results. For small-ish input sizes, there is no dramatic difference in speed (except for naive modulo), and your original sieve is indeed the fastest. For larger inputs (maximal values), yours is still the fastest (even by a larger margin), and the divisors approach is considerably slower. >>> n, q = gen_input(10000, 1000, 1000) >>> modulo(n, q) == mine(n, q) == sieve(n, q) == modulo(n, q) True >>> %timeit modulo(n, q) 1 loop, best of 3: 694 ms per loop >>> %timeit mine(n, q) 10 loops, best of 3: 160 ms per loop >>> %timeit sieve(n, q) 10 loops, best of 3: 112 ms per loop >>> %timeit divisors(n, q) 1 loop, best of 3: 180 ms per loop >>> n, q = gen_input(100000, 100000, 100000) >>> %timeit mine(n, q) 1 loop, best of 3: 313 ms per loop >>> %timeit sieve(n, q) 10 loops, best of 3: 131 ms per loop >>> %timeit divisors(n, q) 1 loop, best of 3: 1.36 s per loop Not sure why you are getting timeouts for yours and mine algorithm while @phoenixo's divisors allegedly works (did not try it, though)...
{ "language": "en", "url": "https://stackoverflow.com/questions/60604190", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Bootstrap 3 is unable to unmark the justified dropdown button group for the inactive options With Bootstrap 3.3.7, I am trying to have a justified navigation dropdown button group, to mark correctly, after selection. I am having the problem of both menu options being marked, in the dropdown button, when one after another options being selected. Are there anyways to have the dropdown menu to mark only the option being selected, while being a justified group dropdown navigation button? Thank you! sample code <div class="row"> <div class="col-md-7"> <div class="btn-group btn-group-justified" role="group"> <a href="#left" class="btn btn-primary" role="button" data-toggle="tab">Left</a> <a href="#middle" class="btn btn-primary" role="button" data-toggle="tab">Middle</a> <div class="btn-group" role="group"> <a href="#" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" role="button"> Dropdown <span class="caret"></span> </a> <ul class="dropdown-menu"> <li><a href="#drop1" role="tab" data-toggle="tab">drop 1</a></li> <li><a href="#drop2" role="tab" data-toggle="tab">drop 2</a></li> </ul> </div> </div> <div class="tab-content"> <div class="tab-pane active" role="tabpanel" id="left">please select 1 of the options in the dropdown</div> <div class="tab-pane" role="tabpanel" id="middle">please try the dropdown on the right</div> <div class="tab-pane" role="tabpanel" id="drop1">please try select drop 2 also, then both are marked under the dropdown</div> <div class="tab-pane" role="tabpanel" id="drop2">please try select drop 1 also, then both are marked under the dropdown</div> </div> </div> A: Instead of using button groups I'd recommend using the Nav component instead styled with the pills modifier class. It's not the same but very close and the Tab panels are built to work with the pills styling. It will solve the problem you have now with the active class remaining on the dropdown options. <div> <ul class="nav nav-pills nav-justified" role="tablist"> <li role="presentation" class="active"><a href="#home" aria-controls="home" role="tab" data-toggle="pill">Home</a></li> <li role="presentation"><a href="#profile" aria-controls="profile" role="tab" data-toggle="pill">Profile</a></li> <li role="presentation" class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false"> Dropdown <span class="caret"></span> </a> <ul class="dropdown-menu"> <li><a href="#messages" aria-controls="messages" role="tab" data-toggle="pill">Messages</a></li> <li><a href="#settings" aria-controls="settings" role="tab" data-toggle="pill">Settings</a></li> </ul> </li> </ul> <!-- Tab panes --> <div class="tab-content"> <div role="tabpanel" class="tab-pane active" id="home">home</div> <div role="tabpanel" class="tab-pane" id="profile">profile</div> <div role="tabpanel" class="tab-pane" id="messages">messages</div> <div role="tabpanel" class="tab-pane" id="settings">settings</div> </div> </div> https://codepen.io/partypete25/pen/Moooaq?editors=1100 A: I tailored @partypete25 answers, to my needs. Thanks again @partypete25! sample code <style> .nav.nav-pills.nav-justified.nav-group > li:not(:first-child):not(:last-child) > .btn { border-radius: 0; margin-bottom: 0; } @media(max-width:768px){ .nav.nav-pills.nav-justified.nav-group > li:first-child:not(:last-child) > .btn { border-bottom-left-radius: 0; border-bottom-right-radius: 0; margin-bottom: 0; } .nav.nav-pills.nav-justified.nav-group > li:last-child:not(:first-child) > .btn { border-top-left-radius: 0; border-top-right-radius: 0; } .nav.nav-pills.nav-justified.nav-group li + li { margin-left: 0; } } @media(min-width:768px){ .nav.nav-pills.nav-justified.nav-group > li:first-child:not(:last-child) > .btn { border-top-right-radius: 0; border-bottom-right-radius: 0; } .nav.nav-pills.nav-justified.nav-group > li:last-child:not(:first-child) > .btn { border-top-left-radius: 0; border-bottom-left-radius: 0; } } </style> <div class="row"> <div class="col-md-12"> <ul class="nav nav-pills nav-justified nav-group"> <li class="active"><a href="#left" class="btn btn-primary" role="tab" data-toggle="tab">Left</a></li> <li><a href="#middle" class="btn btn-primary" role="tab" data-toggle="tab">Middle</a></li> <li class="dropdown"> <a href="#" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" role="button"> Dropdown <span class="caret"></span> </a> <ul class="dropdown-menu"> <li><a href="#drop1" role="tab" data-toggle="tab">drop 1</a></li> <li><a href="#drop2" role="tab" data-toggle="tab">drop 2</a></li> </ul> </li> </ul> <div class="tab-content"> <div class="tab-pane active" role="tabpanel" id="left">please select 1 of the options in the dropdown</div> <div class="tab-pane" role="tabpanel" id="middle">please try the dropdown on the right</div> <div class="tab-pane" role="tabpanel" id="drop1">please try select drop 2 also, then both are marked under the dropdown</div> <div class="tab-pane" role="tabpanel" id="drop2">please try select drop 1 also, then both are marked under the dropdown</div> </div> </div> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/44685652", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Sort array by name with array key I have an array like this, how can I sort by "name" Array ( [0] => Array ( [id] => 1 [name] => status_category_confide ) [1] => Array ( [id] => 2 [name] => status_category_love ) [2] => Array ( [id] => 3 [name] => status_category_household ) [3] => Array ( [id] => 4 [name] => status_category_family ) [4] => Array ( [id] => 5 [name] => status_category_friends ) [5] => Array ( [id] => 6 [name] => status_category_colleague ) [6] => Array ( [id] => 7 [name] => status_category_work ) [7] => Array ( [id] => 8 [name] => status_category_ambition ) ) I've tried using the "sort" function but it doesn't work $get_status_mood=mysqli_query($con, "select id, name from category"); while ($gsm=mysqli_fetch_array($get_status_mood)) { //array_push($status_category, constant($gsm['name'])); $status_category[] = array( "id"=>$gsm['id'], "name"=>$gsm['name'] ); } sort($status_category); for ($i=0; $i<count($status_category); $i++) { echo"<option value='".$status_category[$i]['id']."'>".$status_category[$i]['name']."</option>"; } I want to display the results in the order of the name A: Try the SQL order by option $get_status_mood=mysqli_query($con, "select id, name from category order by name asc"); A: You can sort it using array_column and array_multisort functions. $keys = array_column($array, 'name'); array_multisort($keys, SORT_ASC, $array); A: You can try it with usort this sort an array by values using a user-defined comparison function function cmp($a, $b) { return strcmp($a["name"], $b["name"]); } usort($vc_array, "cmp"); A: $a = array(); $a[] = array('id' => 1, 'name' => 'status_category_confide'); $a[] = array('id' => 2, 'name' => 'status_category_love'); $a[] = array('id' => 3, 'name' => 'status_category_household'); function cmp($x, $y) { if (strcmp($x['name'], $y['name']) == 0) { return 0; } return (strcmp($x['name'], $y['name']) < 0) ? -1 : 1; } usort($a, "cmp"); print_r($a);
{ "language": "en", "url": "https://stackoverflow.com/questions/52639580", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: updating query parameters in SQL Data Source I have following code that updates the value of query parameters of a SQL Data Source after going through some conditions. SqlDataSource sdm = new SqlDataSource("<our connection string>", "SELECT [Message Id] ,[To] ,[From] ,[Reply To] ,[Subject] ,[Message] ,[Date added] FROM [database].[dbo].[User Messages] where ([to]=@sid or [from]=@sid) and ([to]=@qid or [from]=@qid) and [reply to]=@rid"); string user = Session["USERID"].ToString(); string to = Request["to"].ToString(); string from = Request["from"].ToString(); sdm.UpdateParameters["rid"].DefaultValue = Request["replyid"].ToString(); sdm.UpdateParameters["sid"].DefaultValue = user; if (user == to) sdm.UpdateParameters["qid"].DefaultValue=from; else sdm.UpdateParameters["qid"].DefaultValue= to; sdm.Update(); sdm.DataBind(); Repeater1.DataSource = sdm; Repeater1.DataBind(); Its showing NullReferenceException at sdm.UpdateParameters["rid"].DefaultValue = Request["replyid"].ToString(); rid is already set in query string as ?rid=a A: You'll want to use the Request.QueryString collection to get your rid parameter out: sdm.UpdateParameters["rid"].DefaultValue = Request.QueryString["rid"]; Using an indexer with Request will get you values out of the QueryString, Form, Cookies or ServerVariables collections, using Request.QueryString directly makes your intentions that little bit clearer. A: Shouldn't the query string be ?replyid=a instead of ?rid=a?. It seems that Request["replyid"] returns null, and then ToString() throws the exception.
{ "language": "en", "url": "https://stackoverflow.com/questions/14438540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to display Date to Ext Js Column with Json response stackoverflow forum member I need some help from you. I am getting the server response for the startDate in json format as "startDate":1328466599000 I want to display it to my ExtJs column. But I am not able to display it. My column in which i am displaying StartDate is [Ext.Date.format(values.StartDate, "c")] and my TaskModel is Ext.define("TaskModel", { extend : "Gnt.model.Task", // Some custom field definitions fields : [ { name: 'Id', type: 'int', useNull : true, mapping: 'id'}, { name: 'StartDate', type: 'date', mapping: 'startDate'}, { name: 'EndDate', type: 'date', mapping: 'endDate', dateFormat: 'MS'}, { name: 'Priority', defaultValue : 1, mapping: 'priority', dateFormat: 'MS' }, { name: 'Duration', mapping: 'duration'}, { name: 'PercentDone', mapping: 'percentDone'}, { name: 'DurationUnit', mapping: 'durationUnit'}, { name: 'parentId', mapping: 'parentId', type: 'int'}, { name: 'Name', mapping: 'taskName'}, { name: 'index', mapping: 'taskindex'}, { name: 'depth', mapping: 'depth'}, ] }); I am not able to view my startDate I am receiving as response to my Column. Does anyone have any idea as to what is causing this error? If anyone has a solution to this problem please help me. A: Could it be that you have defined the dateformat on the priority column, not startdate column? A: I did a blog post here: http://peterkellner.net/2011/08/24/getting-extjs-4-date-format-to-behave-properly-in-grid-panel-with-asp-net-mvc3/ sorry for digging up something from a while back but I was just searching for the same thing and ran into my blog post first (before this item)
{ "language": "en", "url": "https://stackoverflow.com/questions/8847335", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery two column (one dimensional) array? I have a simple one dimensional array but I want to split the long list into two columns using jQuery. How can I achieve this? var articles = ['article10','article9','article8','article7','article6','article5','article4','article3', 'article2', 'article1']; for ( var articCounter = articles.length; articCounter > 0; articCounter--) { document.write('<a href="../articles/' + articles[articCounter-1] + '.pdf" > ' + articles[articCounter-1] + '</a></br>'); } // end for I don't want to have to create two different arrays for two different float divs.... I've googled this many times but many other methods deal with multidimensional arrays. Thank you very much for the help in advance. EDIT: Right now it's just one long list like so: Article1 Article2 Article3 .... But I would like to achieve this: A: This will split your array into 2 arrays: var articles = ["article1", "article2", "article3", "article4", "article5", "article6", "article7", "article8", "article9", "article10"]; var separatorIndex = articles.length & 0x1 ? (articles.length+1)/2 : articles.length/2; var firstChunk = articles.slice(0,separatorIndex); //["article1", "article2", "article3", "article4", "article5"] var secondChunk = articles.slice(separatorIndex,articles.length); //["article6", "article7", "article8", "article9", "article10"] Then you can use them where and/or how you want. Explanation The 2nd line finds an anchor index (alias -> middle index of division),by which array should be divided into 2 chunks. The array can have odd and even lengths,and those 2 situations must be distinguished. As it is impossible to divide odd-length array into 2 equal parts, it must be divided in such way, that 1st chunk will have 1 element more or less,than 2nd chunk.Here, I have implemented first case,that is, 1st chunk will have 1 element more,than 2nd one. Here are the examples of different situations: total length | 1st (length) | 2st (length) | separatorIndex 10 0-4 (5) 5-9 (5) 5 11 0-5 (6) 6-10 (5) 6 12 0-5 (6) 0-11 (6) 6 In table, number-number syntax shows accordingly start and end indexes in array. The division is done by .slice() function.
{ "language": "en", "url": "https://stackoverflow.com/questions/11378628", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Delete unpersisted record I wonder what's the procedure to delete a non persisted record. I have a domain that has many redirections I start to create a redirection with domain = @modelFor('domain') redirection = @store.createRecord('redirection') domain.get('redirections').pushObject(redirection) is this correct ? And how to delete the redirection object if my user click on cancel button ? I've tried this but that does not work. redirection = @get('model') redirection.rollback() redirection.unloadRecord() I'm using ember and ember-data both in canary version. Thanks. A: You should be able to do redirection = @get('model') @store.deleteRecord(redirection)
{ "language": "en", "url": "https://stackoverflow.com/questions/19438052", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: IPython change input cell syntax highlighting logic for entire session You can use extensions or display helpers in IPython to make whatever syntax highlighting you'd like on output cells. For some special cell magics, like %%javascript you can also see the input cell itself is rendered with that language's natural syntax highlighting. How can you cause every input cell to be displayed with some chosen, non-Python syntax highlighting (regardless of any magics used on a cell, regardless of whether the cell embodies Python code, some other language). In my case I am working with a custom-made cell magic for a proprietary language. The %%javascript syntax highlighting works well for this language, but if I have my own %%proprietarylang magic function, I obviously can't use %%javascript to help me with how the cell is displayed. Is there a setting I can enable when I launch the notebook, or some property of the ipython object itself that can be programmatically set inside of my magic function, which will cause the same display logic to happen as if it was %%javascript. I know that general-purpose on-the-fly syntax highlighting is not supported by the notebook currently. I'm asking specifically about how to make use of pre-existing syntax highlighting effects, such as that of %%javascript. I've seen some documentation referring to IPython.config.cell_magic_highlight but this does not seem to exist anymore. Is there a standard replacement for it? A: To replace IPython.config.cell_magic_highlight, you can use something like import IPython js = "IPython.CodeCell.config_defaults.highlight_modes['magic_fortran'] = {'reg':[/^%%fortran/]};" IPython.core.display.display_javascript(js, raw=True) so cells which begin with %%fortran will be syntax-highlighted like FORTRAN. (However, they will still be evaluated as python if you do only this.) A: For recent IPython version, the selected answer no longer works. The 'config_default' property was renamed options_default (Ipython 6.0.0). The following works: import IPython js = "IPython.CodeCell.options_default.highlight_modes['magic_fortran'] = {'reg':[/^%%fortran/]};" IPython.core.display.display_javascript(js, raw=True)
{ "language": "en", "url": "https://stackoverflow.com/questions/28703626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to output vertical bar format in textfile I am trying to save my contents in the textfile in this format |Name|Description| |QY|Hello| But for now mine is returning me as this output: |2014 1Q 2014 2Q 2014 3Q 2014 4Q| |96,368.3 96,808.3 97,382 99,530.5| Code: def write_to_txt(header,data): with open('test.txt','a+') as f: f.write("|{}|\n".format('\t'.join(str(field) for field in header))) # write header f.write("|{}|\n".format('\t'.join(str(field) for field in data))) # write items Any idea how to change my code so that I would have the ideal output? A: This is happenning because you are joining the fields inside data iterable using \t , use | in the join as well for your requirement. Example - def write_to_txt(header,data): with open('test.txt','a+') as f: f.write("|{}|\n".format('|'.join(str(field) for field in header))) # write header f.write("|{}|\n".format('|'.join(str(field) for field in data)))
{ "language": "en", "url": "https://stackoverflow.com/questions/31379900", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does adding a new element to an array list replace all the previous elements with the new one? I have a method in my class TextPlan, which calls all my rules in another class RSTRule and adds all rules to an array list. For this method I have used import java.lang.reflect.InvocationTargetException andimport java.lang.reflect.Method. But it adds to the array list incorrectly. For example, the result ofadd(RSTRule)` in each call of RST methods are as follows: call 1: RSTRules.add(RSTRule)=R1 call 2: RSTRules.add(RSTRule)=R2,R2 call 3: RSTRules.add(RSTRule)=R3,R3,R3 call 4: RSTRules.add(RSTRule)=R4,R4,R4 That means that every time I add a new element, it removes the previous elements from the array list, but repeats the new element. Here is my code: public class TextPlan extends ArrayList<Object> { RSTRules rstRules=new RSTRules(); public RSTRules produceAllRSTRules(RSTRules rstRules) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { RSTRule rstRule=new RSTRule(); Method[] methods =rstRule.getClass().getMethods(); for (Method method : methods) { if (method.getName().startsWith("generate")) { rstRule=(RSTRule)method.invoke(rstRule); rstRules.add(rstRule) ; } } return rstRules; } } hier one of my methodes in "RSTRule", which i call all of them in "TextPlan" to produce an instance of all Rules; public class RSTRule{ protected String ruleName; protected DiscourseRelation discourseRelation; protected String ruleNucleus; protected String ruleSatellite; protected String condition; int heuristic; public RSTRule generateBothAppearBothCosts_Join(){ this.discourseRelation=DiscourseRelation.Join; this.ruleNucleus="BothProductAppear_Elaboration"; this.ruleSatellite="BothProductCost_Elaboration"; this.ruleName="BothProductAppearAndBothProductCost_Join"; this.condition=null; this.heuristic=9; return this; } } A: You're not adding four new RSTRule instances to the list, you're adding the same RSTRule instance four times and modifying it each time through. Since it's the same instance stored four times, the modifications show up in every position of the list.
{ "language": "en", "url": "https://stackoverflow.com/questions/19087561", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: chosen-select not working bootstrap 3 modal? I cannot fix a chosen-select from a modal which i am following here http://jsfiddle.net/koenpunt/W6dZV/, I cannot apply it to my code, please see this image I have a chosen select on its page, but not on modal, I want to apply it on my modal, this is my code on button: <div class="text-center"> <h1>Bootstrap starter template</h1> <p class="lead">Use this document as a way to quickly start any new project.<br/> All you get is this text and a mostly barebones HTML document.</p> <!-- Button trigger modal --> <a data-toggle="modal" href="#myModal" class="btn btn-primary btn-lg">Launch demo modal</a> </div> anyway, I am still applying the codes on the fiddle to mide. the modal: × Modal title United States United Kingdom Afghanistan Aland Islands Albania Algeria American Samoa Andorra Angola .... Close Save changes and for the script. <script> $('#myModal').on('shown.bs.modal', function () { $('.chosen-select', this).chosen(); }); </script> As you can see, I have chosen select at the background, but i cannot apply it on modal.
{ "language": "en", "url": "https://stackoverflow.com/questions/33090215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Getting an error on my do while loop in the doAgain method Getting an error on my do while loop in my doAgain method. Not sure why. Trying to use another Boolean method to check for mistakes in the user input : import java.util.Scanner; import java.util.Random; public class Lottery { public static void main(String[] args) { do { int digits = getDigits(); System.out.println(createNumber(digits)); } while (doAgain() != false); } public static int getDigits() { Scanner kb = new Scanner(System.in); System.out.println("How many digits do you want the num to be?"); int digits = kb.nextInt(); return digits; } public static String createNumber(int digits) { Random r = new Random(); StringBuilder sb = new StringBuilder(digits); for (int i = 0; i < digits; i++) sb.append((char) ('0' + r.nextInt(10))); return sb.toString(); } public static boolean doAgain() { do { Scanner kb = new Scanner(System.in); String answer; System.out.println("Do you want to do this again? Enter yes to continue or no to quit"); answer = kb.nextLine(); if (answer.equals("yes")) return true; else return false; } while (incorrect(answer) != false); } public static boolean incorrect(String answer) { if (!answer.equals("yes") || !answer.equals("no")) return true; else return false; } } A: You should declare String answer=""; inside doAgain function. Otherwise you will get cannot find symbol error in this line while (incorrect(answer) != false); Modify doAgain function to this public static boolean doAgain() { String answer=""; do { Scanner kb = new Scanner(System.in); // String answer; // remove this System.out.println("Do you want to do this again? Enter yes to continue or no to quit"); answer = kb.nextLine(); if (answer.equals("yes")) { return true; } else { return false; } } while (incorrect(answer) != false); } A: Here a some mistakes you made: * *!answer.equals("yes") || !answer.equals("no") always returns true. *answer in } while (incorrect(answer) != false); is out of scope. You need to declare String answer = ""; before the do-while loop. *The loop never repeats, because of you if else which always returns in the loop. The fixed code can be: public static boolean doAgain() { Scanner kb = new Scanner(System.in); String answer = ""; do { System.out.println("Do you want to do this again? Enter yes to continue or no to quit"); answer = kb.nextLine(); } while (incorrect(answer)); // Better not use double negative if (answer.equals("yes")) return true; else return false; } public static boolean incorrect(String answer) { if (answer.equals("yes") || answer.equals("no")) return false; // answer is correct else return true; // answer is incorrect }
{ "language": "en", "url": "https://stackoverflow.com/questions/47827882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: Validation of IP address in Scala I want to validate the IP address in scala. I have implemented the method but I am seeing some errors. Can anyone look into it and suggest if they have better solution. I am not trying to implement functionally. def validIPAddress(IP: String): String = { var isValidIP = true if(IP.contains(":")) { var numbers= IP.split(":") //create an array if (numbers.length!=8) return "Neither" for (n <- numbers) { if(n.length = 0 or n.length > 4) return "Neither" else { for (m <- n) { if(!m in "0123456789abcdefABCDEF") return "Neither" } } } return "IPv6" } else if(IP.contains(".") { //192.168.1.1 nums = IP.split(".") if(nums.length!=4) isValidIP = false //Array.length else { for (a <- nums) { println(a) try { var intA = a.toInt if(intA <=0 || IntA > 255) { isValid = false } } catch (NumberFormatException e) { case e: Exception => None } } if(isValid == true) { println("Valid IP") } else { println("Invalid IP") } } } return "IPv4" else { return "neither" } } A: You might not intend to implement funcationaly but there is no need for imperative code in your example at all and returns and vars cause some serious issues when it comes to reading the intend of the code. I would rewrite the code to something like this sealed trait IP extends Product with Serializable object IP { final case class V4(a: Int, b: Int, c: Int, d: Int) extends IP final case class V6(a: Int, b: Int, c: Int, d: Int, e: Int, f: Int, g: Int, h: Int) extends IP } val ipV4 = """(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})""".r val ipV6 = """([0-9a-fA-F]+):""".r def validIPAddress(ip: String): Either[String, IP] = { def parseV4(s: String) = { val i = Integer.parseInt(s) if (0 <= i && i <= 255) Right(i) else Left(s"$i is not a valid IPv4 number") } def parseV6(s: String) = Integer.parseInt(s, 16) ip match { case ipV4(a, b, c, d) => for { a1 <- parseV4(a) b1 <- parseV4(b) c1 <- parseV4(c) d1 <- parseV4(d) } yield IP.V4(a1, b1, c1, d1) case ipV6(a, b, c, d, e, f, g, h) => // technically speaking this isn't exhausting all possible IPv6 addresses... // as this regexp would ignore e.g. ::1 or :: Right(IP.V6(parseV6(a), parseV6(b), parseV6(c), parseV6(d), parseV6(e), parseV6(f), parseV6(g), parseV6(h))) case _ => Left(s"$ip is neither V4 nor V6 format") } } to make it easier to follow and debug errors, though as I checked this implementation is NOT really conforming to what IPv6 does, as some tuning around regexp usage would be necessary. As a matter of the fact, I would prefer to avoid rolling my own solution altogether if I couldn't afford some time for writing down like 15-20 test cases. So, unless there is a reason to implement your own validator I would delegate that task to some library which already tested handling corner cases. If you have to, however, do the following things: * *don't use return - in Scala it does something different than what you think it does *don't use vars unless you're optimizing - the way you use them have nothing to do with optimization (isValid is never used, so why override it? and other vars are never modified) *don't use string for everything because that is asking for trouble on its own (e.g. "neither" and "Neither" - should the caller use .equalsIgnoreCase on your code to check results?) *start with tests written basing on specification. While I translated your code it fails valid IPv6 addresses. If I skipped the requirement that Iv6 is fixed size, it would be even shorter to: sealed trait IP extends Product with Serializable object IP { final case class V4(a: Int, b: Int, c: Int, d: Int) extends IP final case class V6(values: List[Int]) extends IP } val ipV4 = """(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})""".r val ipV6 = """([0-9a-fA-F]*)((:[0-9a-fA-F]*){2,})""".r def validIPAddress(ip: String): Either[String, IP] = { def parseV4(s: String) = { val i = Integer.parseInt(s) if (0 <= i && i <= 255) Right(i) else Left(s"$i is not a valid IPv4 number") } def parseV6(s: String) = if (s.isEmpty) 0 else Integer.parseInt(s, 16) ip match { case ipV4(a, b, c, d) => for { a1 <- parseV4(a) b1 <- parseV4(b) c1 <- parseV4(c) d1 <- parseV4(d) } yield IP.V4(a1, b1, c1, d1) case ipV6(head, tail, _) => val segments = head +: tail.substring(1).split(':') Right(IP.V6(segments.map(parseV6).toList)) case _ => Left(s"$ip is neither V4 nor V6 format") } } which handled more correct cases but is still far from ready. So if you can - avoid doing it yourself and use a library.
{ "language": "en", "url": "https://stackoverflow.com/questions/60533540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to upload video file on parse in android? I am trying to upload video file on parse. For uploading the video I am using following code: File inputFile = new File(uri.toString()); FileInputStream fis = new FileInputStream(inputFile); ByteArrayOutputStream bos= new ByteArrayOutputStream(); byte[] buf = new byte[(int)inputFile.length()]; for (int readNum; (readNum=fis.read(buf)) != -1;){ bos.write(buf,0,readNum); } byte[] bytes = bos.toByteArray(); ParseFile file = new ParseFile("testVideo1.mp4", bytes); ParseObject parseObject = new ParseObject("chat1"); parseObject.saveInBackground(); But inputfile the File object not converted to FileInputStream. A: thanks for the this, helped me get started with uploading a video to parse, I figure out your issue, you just didn't put the parse file in your parseobject. basically you never sent the video File inputFile = new File(uri.toString()); FileInputStream fis = new FileInputStream(inputFile); ByteArrayOutputStream bos= new ByteArrayOutputStream(); byte[] buf = new byte[(int)inputFile.length()]; for (int readNum; (readNum=fis.read(buf)) != -1;){ bos.write(buf,0,readNum); } byte[] bytes = bos.toByteArray(); ParseFile file = new ParseFile("testVideo1.mp4", bytes); ParseObject parseObject = new ParseObject("chat1"); //addition parseObject.put("video",file); //it should work with this parseObject.saveInBackground();
{ "language": "en", "url": "https://stackoverflow.com/questions/37543989", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use string keys in (fluent) NHibernate I am working with brownfield database that uses strings as primary keys. Using Fluent NHibernate with Sqlite (in-memory provider for unit testing) and SQL Server 2005. I have the following entity: public class Entity { public virtual DateTime TimeStamp { get; set; } public virtual string Name { get; set; } } With this mapping: public class EntityMap : ClassMap<Entity> { public EntityMap() { Map(_ => _.TimeStamp); Id(_ => _.Name).CustomType("AnsiString"); } } However it does not work saying NHibernate.TypeMismatchException : Provided id of the wrong type. Expected: System.Int32, got System.String How make this work? Also, is there any good documentation about fluent nhibernate available? Thanks in advance. A: If you are using strings as your primary keys you'll probably have to do something like this: public class EntityMap : ClassMap<Entity> { public EntityMap() { Id(x => x.Name).GeneratedBy.Assigned(); Map(x => x.TimeStamp); } } From the nhibernate documentation: 5.1.4.7. Assigned Identifiers If you want the application to assign identifiers (as opposed to having NHibernate generate them), you may use the assigned generator. This special generator will use the identifier value already assigned to the object's identifier property. Be very careful when using this feature to assign keys with business meaning (almost always a terrible design decision). Due to its inherent nature, entities that use this generator cannot be saved via the ISession's SaveOrUpdate() method. Instead you have to explicitly specify to NHibernate if the object should be saved or updated by calling either the Save() or Update() method of the ISession. Also here is a related article. It is a bit dated but still applies to your situation: http://groups.google.com/group/fluent-nhibernate/browse_thread/thread/6c9620b7c5bb7ca8
{ "language": "en", "url": "https://stackoverflow.com/questions/9693943", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Adding custom function to handle additional column/ data while resampleBarFeed in PyAlgoTrade I am resampling custom columns with pyalogtrade. Say I have an extra column called EX other than the default columns (open, close, high, low, etc). This is initialized and passed around in the bar.BasicBar() function as {'extraCol1' : 1.09 }. By default, when the data is resampled, the EX is 0 in the resampled data. How/ where do we change, or override this default behaviour of pyalogtrade. Example: Say if we have three 1-minute OHLCV EX bars as follows (toy example) Cols: [O H L C V EX] 1-min bar#1: [1 1 1 1 1 1] 1-min bar#2: [2 2 2 2 2 2] 1-min bar#3: [3 3 3 3 3 3] While resampling it for 3-minute, we get a bar like this: Cols: [O H L C V EX] 3-min bar#1: [1 3 1 3 3 *0*] Suppose we want custom handling of the EX column, say: resampled EX = 3rd minute - 1st minute = 3 - 2 = 1 (instead of the 0) How does one achieve that?
{ "language": "en", "url": "https://stackoverflow.com/questions/73638496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Hide parent div if :empty Trying to hide a parent div if a sibling is empty when document is ready. Doesn't seem to work for me: $('.pp-post-content-location:empty').parent().hide(); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <span class="pp-post-content-subtitle">Location</span> <div class="pp-post-content-location"></div> </div> A: First of All You Haven't included Document .ready in your Script Here's The Code Try this $(document).ready(function(){ var text=$('.pp-post-content-location').text(); //text Is Jquery Function which gets the content inside a element if(text==""){ $('.pp-post-content-location').parent().hide(); } }); Then Just a Simple If Condition to check That is there any Content In Specified Element If it has not Any content then it will hide the PARENT element
{ "language": "en", "url": "https://stackoverflow.com/questions/45857228", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CSS Selector for last-of-type/last-child but different parents? Would like to access item 6 only through css <div class="div-class"> <li class="li-class">Item 1</li> <li class="li-class">Item 2</li> <li class="li-class">Item 3</li> </div> <div class="div-class"> <li class="li-class">Item 4</li> <li class="li-class">Item 5</li> <li class="li-class">Item 6</li> </div> A: EDIT I think that it is duplicate. Select :last-child with especific class name (with only css) So you need which div you want to point. In this case, this is second div so we specified: div:nth-child(2) And then we just select last li as below: li:last-child So finaly we got: div:nth-child(2) li:last-child{ background-color: red; } EDIT With jQuery: $('li').last().css('background', 'red'); Just to let you know, your html structure is incorrect as you should set li right after ul or ol $('li').last().css('background', 'red'); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </div> <div> <li>Item 4</li> <li>Item 5</li> <li>Item 6</li> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/64226774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jsp failed to embed applet from jar, class-file not found I try to embed an applet into my Applet.jsp via jsp:plugin. When I call the jsp through tomcat, the applet throws a "ClassNotFoundException". So far I figured out, that the jar-file could be found and even downloaded, when I entered the classpath into url. In my tomcat-logs I see, that the test.jar is found, but not the MyClass.class in it. My project-structure: webapp - applets - test.jar - WEB-INF - templates - Applet.jsp - web.xml The jar file only contains MyClass.class. Applet.jsp <jsp:plugin type="applet" /webapp/applets/test.jar" code="MyClass.class" width="300" height="300"></jsp:plugin> Tomcat log "POST /webapp/servlet/applet HTTP/1.1" 200 "GET /webapp/applets/test.jar/MyClass.class HTTP/1.1" 404 I also tried Applet.jsp <jsp:plugin type="applet" archive="/webapp/applets/test.jar" code="MyClass" width="300" height="300"></jsp:plugin> and several variations, but no luck. Tomcat log "POST /webapp/servlet/applet HTTP/1.1" 200 "GET /webapp/applets/test.jar HTTP/1.1" 200 "GET /webapp/servlet/MyClass.class HTTP/1.1" 404 Versions are java 1.7, tomcat 7 Why isn't MyClass.class found in the test.jar? EDIT I figured out, that is has to do with the jsp or so. My html with embeded applet-jar works, the jsp still fails. html <html> <head> <title>Time</title> </head> <body> <object codetype="application/java-vm" width="300" height="300" archive="test.jar" classid="java:MyClass.class"></object> </body> </html> Has anybody some ideas about why jsp won't cooperate? And at least I would love to use jsp:plugin
{ "language": "en", "url": "https://stackoverflow.com/questions/19787817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Socket Program to demonstrate Link layer communication in a network without using ip address As we all know that within a network, communication is by the MAC address and not by the ip address. So I always used to think that whether we can write a socket program in server-client paradigm which are only using MAC address for communication but not ip address i.e. the struct sock_in should be left unfilled, and within a lan they should be able to communicate. A: Raw sockets, as given by the example above (by Carl) can work to give you access for L3 header. However, note that on more up-to-date Windows (XP SP3, Vista and 7) raw sockets are greatly restricted by the socket layer, making it difficult to send arbitrary data of your choosing. You can also use special libraries that allow for a much more raw access to the Ethernet adapter. WinPcap (for Windows) or libpcap (for Linux) will allow you to manipulate the entire packet data, including the Ethernet header, and indeed send any other L2 protocol you wish.
{ "language": "en", "url": "https://stackoverflow.com/questions/7338577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Magento properly reindex everything I have searched for a while, followed this answer even looked at the shell indexer script, and I came with this. Basically, I have $processes = Mage::getSingleton('index/indexer')->getProcessesCollection(); $processes->walk('setMode', array(Mage_Index_Model_Process::MODE_MANUAL)); $processes->walk('save'); // Importing data here... Mage::getModel('catalog/product_image')->clearCache(); // rebuild everything!!! $processes = Mage::getSingleton('index/indexer')->getProcessesCollection(); $processes->walk('reindexEverything'); $processes->walk('setMode', array(Mage_Index_Model_Process::MODE_REAL_TIME)); $processes->walk('save'); But I still get this screen in my backend ...How to "update" the indexes? ** UPDATE ** Problem solved! To properly index everything, just call everything! // rebuild everything!!! $processes = Mage::getSingleton('index/indexer')->getProcessesCollection(); $processes->walk('setMode', array(Mage_Index_Model_Process::MODE_REAL_TIME)); $processes->walk('save'); $processes->walk('reindexAll'); $processes->walk('reindexEverything'); A: If you run indexer.php from cli, using the following parameters, do the alerts become resolved: indexer.php reindex all If so, is executing indexer.php with those params as part of your script an option? Edit: also, in Mage_Index_Model_Process take a look at reindexEverything() method. indexer.php has an example of its usage. A: I just encountered this issue in CE v1.9.0.1. My admin module was getting all processes as a collection and looping through each one calling reindexEverything(). I based the code on the adminhtml process controller which was working fine, but my code wasn't working at all. I finally figured out the issue was that I had previously set the reindex mode to manual (to speed up my product import routine) as follows: $processes = Mage::getSingleton('index/indexer')->getProcessesCollection(); $processes->walk('setMode', array(Mage_Index_Model_Process::MODE_MANUAL)); // run product import $processes = Mage::getSingleton('index/indexer')->getProcessesCollection(); foreach($processes as $p) { if($p->getIndexer()->isVisible()) { $p->reindexEverything(); //echo $p->getIndexer()->getName() . ' reindexed<br>'; } } $processes = Mage::getSingleton('index/indexer')->getProcessesCollection(); $processes->walk('setMode', array(Mage_Index_Model_Process::MODE_REAL_TIME)); SOLUTION: set mode back to MODE_REAL_TIME before reindexing everything: $processes = Mage::getSingleton('index/indexer')->getProcessesCollection(); $processes->walk('setMode', array(Mage_Index_Model_Process::MODE_MANUAL)); // run product import $processes = Mage::getSingleton('index/indexer')->getProcessesCollection(); $processes->walk('setMode', array(Mage_Index_Model_Process::MODE_REAL_TIME)); $processes = Mage::getSingleton('index/indexer')->getProcessesCollection(); foreach($processes as $p) { if($p->getIndexer()->isVisible()) { $p->reindexEverything(); //echo $p->getIndexer()->getName() . ' reindexed<br>'; } } Note: these are snips from a few different methods hence the repeated assignment of $processes etc.. It seemed reindexEverything() wasn't doing anything when the processes index mode was set to MODE_MANUAL. Setting mode back to MODE_REAL_TIME and then calling reindexEverything worked fine. I hope this helps someone as I had a few frustrated hours figuring this one out! Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/10560511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to pre-populate a form from a web app on a different server I have Web Application A on Server A that links to Web Application B on Server B. I'm linking to a form that I want to pre-populate with data from Web Application A. So: Web App A --Links to form and sends data for pre-population--> Web App B Since they're on seperate servers I importunately can't just plop something into Session, so I'm going to have to be a little more creative. I'm considering a few different options and I'm looking for the simplest of those solutions. Any suggestions? Here's a few options I'm considering: * *Pass the form data in the link via query string parameters. This seems simple enough, is the legit to do? Or is it a security concern? I'd be passing about 8 parameters, the most sensitive being e-mail address and address. This would all be over SSL. *Similarly, I could pass the data as POST parameters. *Web App A writes a cookie, Web App B reads the data from the cookie. (This seems like more of a security concern than passing as GET or POST parameters) *I could share an object via JNDI to use for prepopulation. Then I guess I could pass a unique ID on the query string which Web App B could use to pick up the object. This seems like it might be "overkill" and I'm not sure how this would work. *I could store the data in a database against a unique ID, pass the unique ID on the query string, then pick it up in Web App B from that same database. Again, this might be "overkill". Any thoughts? Or is there a better solution that I don't have listed? A: In my opinion the GET params are the simplest way to do it, and I don't think there are important security implications. A: You should assume anything that web app A puts in the redirect can be read/stolen/modified/spoofed before it gets to web app B (unless you are using SSL on both app A and B). If this isn't a problem then putting the params on the redirect URL should do you fine. A secure way would be for app A to generate a unique ID (non guessable and short lived) and to store the info against this ID. The ID is passed with the request to app B. Server B then accesses the data from server A using the ID in a private secure way, for example be calling a web service on server A that is not publically accessible.
{ "language": "en", "url": "https://stackoverflow.com/questions/5978590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to query recursive MongoDB Document [File System of files and folders] I am developing an application that uses MongoDB (typegoose) to store file system-like (recursive) documents composed of files and folders. However, I do not know how to query such a schema. For querying, I am provided the following. * *users _id *the array of folder names in order ex. ['root', 'nestedFolder1', 'nestedFolder2', 'etc...'] *_id of the last folder chosen The schema is as follows import { Types } from "mongoose"; interface File { _id: Types.ObjectId; fileName: string; isDir: false; content: string; title: string; description: string; } interface FileSystem { _id: Types.ObjectId; folderName: string; isDir: true; files: File[] | []; folders: FileSystem[] | []; } interface Project { _id: Types.ObjectId; projectName: string; fileSystem: FileSystem; } interface User { _id: Types.ObjectId; projects: Project[]; } Update: Here's a replit for reference https://replit.com/@alphacoma18/mongodb-recursive-schema#server.ts A: 1- Most trivial query, get all FileSystem Documents: const fileSystems = await FileSystem.find({ // Empty Object means no condition thus give me all your data }); 2- Using the $eq operator to match documents with a certain value const fileSystems = await FileSystem.find({ isDir: true, folderName: { $eq: 'root' } }); 3- Using the $in operator to match a specific field with an array of possible values. const fileSystems = await FileSystem.find({ isDir: true, folderName: { $in: ['root', 'nestedFolder1', 'nestedFolder2'] } }); 4- Using the $and operator to specify multiple conditions const fileSystems = await FileSystem.find({ $and: [ { isDir: true }, { folderName: { $in: ['root', 'nestedFolder1', 'nestedFolder2'] } } ] }); 5- Retrieve all documents that are directories and are not empty. const fileSystems = await FileSystem.find({ isDir: true, $or: [ { files: { $exists: true, $ne: [] } }, { folders: { $exists: true, $ne: [] } } ] }); 6- All directories that have a folder name that starts with the letter 'n' const fileSystems = await FileSystem.find({ isDir: true, folderName: { $regex: '^n' } }); Now the tougher queries: 1- count the total number of documents const count = await FileSystem.aggregate([ { $count: 'total' } ]); 2- count the total number of documents that are directories const count = await FileSystem.aggregate([ { $match: { isDir: true } }, { $count: 'total' } ]); 3- Get 'foldername' and 'filename; of all documents that are files. const fileSystems = await FileSystem.aggregate([ { $match: { isDir: false } }, { $project: { folderName: 1, fileName: 1 } } ]); 4- Retrieve the total number of files (isDir: false) in each directory (isDir: true) const fileCounts = await FileSystem.aggregate([ { $match: { isDir: true } }, { $project: { folderName: 1, fileCount: { $size: { $filter: { input: '$files', as: 'file', cond: { $eq: ['$$file.isDir', false] } } } } } } ]); 5- Recursive structure querying: The FileSystem interface is recursive, because it has both an array of files and an array of folders, which are both of type File[] and FileSystem[]. To query this recursive schema, you can use the $lookup operator in an aggregate pipeline, to make a left join between FileSystem and itself, based on some criteria. //Retrieve All Documents from FileSystem and their child documents const fileSystems = await FileSystem.aggregate([ { $lookup: { from: 'FileSystem', localField: '_id', foreignField: 'parentId', as: 'children' } } ]); //Use the match operator in the pipeline to filter the results: const fileSystems = await FileSystem.aggregate([ { $lookup: { from: 'FileSystem', localField: '_id', foreignField: 'parentId', as: 'children' } }, { $match: { isDir: true } } ]);
{ "language": "en", "url": "https://stackoverflow.com/questions/74887585", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: VS2008 and ClearCase : opening solution requests a checkout for no reason I have a little issue that's causing my automated builds to fall over. When we open a solution recently converted from VS2005 to VS2008 VS through ClearCase requests that we checkout the solution file. If we allow it then it makes no changes anyway and by default ClearCase doesn't like checkins without changes. So we undo the checkout - and from then on VS is happy, it was able to write the .suo file. If we un-read protect the solution file, start up VS2008 it creates the .suo file ok, if we then un-hijack the .sln file (no changes anyway so VS2008 doesn't notice) and fire up VS2008 again it's fine - doesn't ask for a checkout. In my build script I delete all view private files from the view and then do an update with forced un-hijack of controlled files. And then we build the deployment projects (and thus all dependencies), and as the .suo file is being deleted it falls into the checkout .sln file behaviour every time. And on the build server there isn't anybody around to see the dialog asking for a checkout, the build hangs. I could change (aka bodge) the build script to not delete the .suo file, but I would rather not do this. edit: clarification - the .suo file is NOT checked into ClearClase - it is a view private file that is being created by VS2008, however to create this file it wants to check out the .sln file for not real reason. Further Edit: I have found the solution to this - I've disabled the integration as per my follow up post on this thread. A: Okay, I found the solution to the problem and it was quite simple in reality. I disabled the Visual Studio ClearCase integration on the build server. VS is being used as we need to build deployment projects and so we call devenv to do this for us. However we are only using it as a build engine, there is never a need for the build engine to know how to modify the source items as they will all have just come from ClearCase. The only items we allow the build server to modify are the assembly file version number attributes in the AssemblyInfo files, but we do that in the NAnt and not in Visual Studio. So, disable the functionality and problem goes away. Probably not the solution for everybody but on a build server it was the way forward. A: This troubleshooting item, got me to this fix pack which has solved the issue in our development environment. We're still using VS2005, but I would expect that it's the same issue as what was going wrong in VS2008. A: This seems to be normal for VS2008, it checks out the .sln file when opening a solution. I dont like it either. Your problem however is the fact that the .suo file is also checked in. This file should not be placed under source control. It is like the proj.user files. I suspect suo stands for Solution User Options. A: You could: * *update your script in order to hijack the sln file in your snapshot view just after your "cleartool update -force -overwrite". *or, to avoid the sln to be checked-out, you could try and keep the .suo file checked-in, If the above suggestion works, then here is a couple of reason why one would want to keep this file under version control: * *Since the .suo file is disposable (VS2008 just creates a new one if it does not exist), having under source control might been seen as a way to avoid that creation (hence avoiding the ClearCase plugin detecting it and trying to "add to source control" it or checking it out). *Another advantage to having .suo file under version control (but not updated through any further checkout/checkin) is when you are comparing your checked out project with another checked out version of the same project downloaded elsewhere: that file will always be identical, as opposed to systematically different (since if is a binary file, and any new version of a binary file would register itself as different)
{ "language": "en", "url": "https://stackoverflow.com/questions/625812", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: I can't connect to the webserver I have a WordPress instance running locally on my mac with XAMPP. It's working fine but when I want to install something I have to login with my ftp username and password. I've tried to use my username and password which I use to logon to WordPress. Also I used my tried my database credentials. I really have no idea which other logon credentials I should have. A: FTP credentials do not refer to your login details, it refers to credentials for File Transfer Protocol, it is given to you when you purchase a web hosting service or setup one yourself on your machine. An alternative to this would be to download the plugin or theme you want and paste it to your /{website folder}/wp-content/themes or /{website folder}/wp-content/plugins A: Try to * *Right click to htdocs folder, choose Get info *Click the lock icon, type your MacOS account password to unlock below options. *Allow everyone Read & Write permission, the click the cog icon and choose Apply to enclosed items..., this should apply all r+w permission to sub-folders. *Done
{ "language": "en", "url": "https://stackoverflow.com/questions/55818550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trouble connecting to laravel api with jwt while hosting on 000webhost i am trying to host a project on 000webhost free tier and i am stuck on this problem. I have searched everywhere i could and still no solution. The project is a laravel 5.7 api using jwt for authentication and works fine on localhost. i uploaded everything on 000webhost without a problem and set up the database with this. I know it is up and working to a certain degree as i can access the index.php and it shows up.(It is just a page showing 'hello' on it). My problem is when i try to make a call to the '/api/showAuthUser' endpoint using postman I get this error. Argument 3 passed to Lcobucci\JWT\Signer\Hmac::doVerify() must be an instance of Lcobucci\JWT\Signer\Key, null given, called in /storage/ssd1/450/8968450/vendor/lcobucci/jwt/src/Signer/BaseSigner.php on line 42 When i try to make a call to '/api/login' using postman i get this error. Argument 2 passed to Lcobucci\JWT\Signer\Hmac::createHash() must be an instance of Lcobucci\JWT\Signer\Key, null given, called in /storage/ssd1/450/8968450/vendor/lcobucci/jwt/src/Signer/BaseSigner.php on line 34 I am sure I have the database connected correctly and I have the jwt secret in the .env file. I have tried every solution I could find online with no joy. The only one i have not tried was running php artisan jwt:secret as I can not run commands in 000webhost or I just don't know how to do this. Sorry if this is not enough information but I am new to api's and this is my last hope. Thank you. A: You have a jwt.php file in your config folder (config/jwt.php). In there please replace the JWT_SECRET with your generated jwt secret key on your .env file In jwt.php file 'secret' => env('JWT_SECRET', 'PLACE YOUR JWT KEY HERE'), Hope this will solve your problem
{ "language": "en", "url": "https://stackoverflow.com/questions/55174012", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to create a link without .lnk extension? If I have a file named "C\Test\mypic.jpg", can I create a shortcut with path "C\Test2\mypic.jpg"? Windows always seems to add a ".lnk" suffix, which is unwanted in my case. A: Link in this case can mean several things but we can unpack all the possible scenarios: * *A shortcut (.lnk file). These files must have the .lnk extension because the file extension is how Windows decides which handler to invoke when you double-click/execute the file. If you create a shortcut to a jpg file the real name can be link.jpg.lnk but the user will see the name as link.jpg in Explorer because .lnk is a special extension that is hidden. *A symbolic link (symlink). These are links on the filesystem level and can have any extension. mklink "c:\mylink.jpg" "c:\file.jpg" *A hardlink. This is another name for the same file (alias), it does not create a shortcut. mklink /H "c:\anothername.jpg" "c:\file.jpg"
{ "language": "en", "url": "https://stackoverflow.com/questions/70237074", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to convert this Oracle query into HSQL query I am trying to convert this Oracle query into HSQL, but i have difficulties. select a.t_user_id, listagg(et.event_type_name,', ') within group (order by a.t_user_id ) from t_agency a inner join t_agency_event_type aet on a.t_user_id = aet.agency_id inner join t_event_type et on aet.t_event_type_id=et.id group by a.t_user_id; Can anybody help me? Thanks in advance! ADDED: My HSQL query is like this: Query queryEventTypes = em.createQuery("select agency, GROUP_CONCAT(et.eventTypeName SEPARATOR ', ') as eventTypeName " + "from TAgency agency join agency.tAgencyEventTypes eat " + "join eat.tEventType et " + "group by hiredAgency.tUserId, hiredAgency.address, hiredAgency.city, hiredAgency.information, " + "hiredAgency.website"); But it gives me the error: unexpected token: SEPARATOR near line 1, column 46 [select agency, GROUP_CONCAT(et.eventTypeName SEPARATOR ', ') as eventTypeName from bg.fmi.master.thesis.model.TAgency agency join agency.tAgencyEventTypes eat join eat.tEventType et group by hiredAgency.tUserId, hiredAgency.address, hiredAgency.city, hiredAgency.information, hiredAgency.website] A: Try the GROUP_CONCAT function supported by HSQLDB version 2.3.x and later. The HSQLDB syntax is different and documented here. http://hsqldb.org/doc/2.0/guide/dataaccess-chapt.html#dac_aggregate_funcs The example given in the Guide shows how you specify the grouping and ordering of the results; SELECT LASTNAME, GROUP_CONCAT(DISTINCT FIRSTNAME ORDER BY FIRSTNAME DESC SEPARATOR ' * ') FROM Customer GROUP BY LASTNAME
{ "language": "en", "url": "https://stackoverflow.com/questions/23527646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does my then() never get invoked whenever I add a stream to my stream controller? I have a bloc which has a stream controller and in the constructor of the bloc I add the stream to the controller. I wait until the stream is added and then I add a listener to it. But the then() never get's invoked. I'm sure that GeoLocator() code works because I had it in a stateful widget before and that worked like a charm but I decided to move the business logic to a bloc. import 'dart:async'; import 'package:geolocator/geolocator.dart'; class LocationBloc { final Geolocator _geolocator = Geolocator(); final LocationOptions _locationOptions = LocationOptions(accuracy: LocationAccuracy.high, distanceFilter: 10); StreamController<Position> _positionStreamController = StreamController<Position>(); double _speed = 0; double get speed => _speed; LocationBloc() { print('it gets here'); final Stream<Position> positionStream = _geolocator.getPositionStream(_locationOptions); print('and here'); _positionStreamController.addStream(positionStream).then((value) { print('it never gets here'); print(value); _positionStreamController.stream.listen((Position position) { this._speed = position == null ? 0 : position.speed; }); }); } void dispose() { print('dispose location stream'); _positionStreamController.close(); _speed = 0; } } When I dispose of he bloc provider when the widget get's disposed and call the dispose in the bloc it throws the following error Bad state: Cannot add event while adding a stream The stateless widget class DigitalSpeedMeter extends StatelessWidget { static Widget create(BuildContext context) { return Provider( create: (_) => LocationBloc(), child: DigitalSpeedMeter(), dispose: (BuildContext context, LocationBloc bloc) => bloc.dispose(), ); } A: I ended up using this import 'dart:async'; import 'package:geolocator/geolocator.dart'; class LocationBloc { final Geolocator _geolocator = Geolocator(); final LocationOptions _locationOptions = LocationOptions(accuracy: LocationAccuracy.high, distanceFilter: 10); StreamController<double> _streamController = StreamController<double>(); Stream<double> get stream => _streamController.stream; LocationBloc() { _streamController.addStream(_geolocator.getPositionStream(_locationOptions).map((position) => position.speed ?? 0.0)); } void dispose() { _streamController.close(); } } With a stream builder widget.
{ "language": "en", "url": "https://stackoverflow.com/questions/61410594", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ionic2 cloud google login with asp.net web api I am building an ionic2 app and implemented google login flow. Which works fine and i get the token after a success full. How do i use this token to authenticate my project web api Endpoint ( using Oauth for generating the tokens). I am using default asp.net web api project template
{ "language": "en", "url": "https://stackoverflow.com/questions/41492705", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to establish a boost asio tcp socket over http proxy? I am trying to establish a TCP socket over http proxy. My current understand is, * *create tcp socket connecting to http_proxy_ip:http_proxy_port *Via the socket send: CONNECT http://my.server.com:80 HTTP/1.0\r\n\r\n My question is : is there need to wrap each tcp packet with some http header or use it like normal TCP sokcet(which is not over http proxy)? Is there any equivalent for boost::asio TCP connection through http proxy Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/21731166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android app to create .txt file I'm trying to create an app where a user selects a few checkboxes, then when they hit submit it creates a .txt file with a sentence in it for every checkbox selected. I have had one successful build of this, and it created the file properly, but I need it saved to an accessible file location so that it can be attached to an email. I don't really care where it saves to, as long as it is accessible. The following code causes a crash when run in Android Virtual Device and my Galaxy 2. The application is a proof of concept for a later app. Thank you. @Override public void onClick(View v) { String nochartOutput = " "; if (sitting.isChecked()) nochartOutput += "The patient was sitting in a chair. "; if (breathing.isChecked()) nochartOutput += "The patient was breathing. "; if (alert.isChecked()) nochartOutput += "The patient was alert. "; FileOutputStream fOut = null; File sdDir = Environment.getExternalStorageDirectory(); try { fOut = openFileOutput(sdDir + "/AutoWriter/samplefile.txt",MODE_WORLD_READABLE); } catch (FileNotFoundException e) { e.printStackTrace(); } OutputStreamWriter osw = new OutputStreamWriter(fOut); try { osw.write(nochartOutput); osw.flush(); osw.close(); } catch (IOException e) { e.printStackTrace(); } } 03-04 18:39:53.604: W/dalvikvm(10453): threadid=1: thread exiting with uncaught exception (group=0x40c211f8) 03-04 18:39:53.624: E/AndroidRuntime(10453): FATAL EXCEPTION: main 03-04 18:39:53.624: E/AndroidRuntime(10453): java.lang.IllegalArgumentException: File /mnt/sdcard/samplefile.txt contains a path separator 03-04 18:39:53.624: E/AndroidRuntime(10453): at android.app.ContextImpl.makeFilename(ContextImpl.java:1703) 03-04 18:39:53.624: E/AndroidRuntime(10453): at android.app.ContextImpl.openFileOutput(ContextImpl.java:723) 03-04 18:39:53.624: E/AndroidRuntime(10453): at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:165) 03-04 18:39:53.624: E/AndroidRuntime(10453): at com.example.com.dresdor.autowriter.MainActivity$1.onClick(MainActivity.java:48) 03-04 18:39:53.624: E/AndroidRuntime(10453): at android.view.View.performClick(View.java:3620) 03-04 18:39:53.624: E/AndroidRuntime(10453): at android.view.View$PerformClick.run(View.java:14292) 03-04 18:39:53.624: E/AndroidRuntime(10453): at android.os.Handler.handleCallback(Handler.java:605) 03-04 18:39:53.624: E/AndroidRuntime(10453): at android.os.Handler.dispatchMessage(Handler.java:92) 03-04 18:39:53.624: E/AndroidRuntime(10453): at android.os.Looper.loop(Looper.java:137) 03-04 18:39:53.624: E/AndroidRuntime(10453): at android.app.ActivityThread.main(ActivityThread.java:4507) 03-04 18:39:53.624: E/AndroidRuntime(10453): at java.lang.reflect.Method.invokeNative(Native Method) 03-04 18:39:53.624: E/AndroidRuntime(10453): at java.lang.reflect.Method.invoke(Method.java:511) 03-04 18:39:53.624: E/AndroidRuntime(10453): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790) 03-04 18:39:53.624: E/AndroidRuntime(10453): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557) 03-04 18:39:53.624: E/AndroidRuntime(10453): at dalvik.system.NativeStart.main(Native Method) A: Your existing code is a mashup of writing to internal storage and external storage. The line fOut = openFileOutput(sdDir + "/AutoWriter/samplefile.txt",MODE_WORLD_READABLE); attempts to create a file in the app's private data directory, and you can only pass file names to this method, not a deeper path. That's where the crash is coming from, but it's not what you want. You started to create a path to external storage, but never actually used it. To write the file to that location on the external SD card, modify your code like so: FileOutputStream fOut = null; //Since you are creating a subdirectory, you need to make sure it's there first File directory = new File(Environment.getExternalStorageDirectory(), "AutoWriter"); if (!directory.exists()) { directory.mkdirs(); } try { //Create the stream pointing at the file location fOut = new FileOutputStream(new File(directory, "samplefile.txt")); } catch (FileNotFoundException e) { e.printStackTrace(); } OutputStreamWriter osw = new OutputStreamWriter(fOut); //...etc... Using the SD card allows the file to be accessed by anyone. A: openFileOutput() writes file in the internal memory and not sd card. So change fOut = openFileOutput(sdDir + "/AutoWriter/samplefile.txt",MODE_WORLD_READABLE); to fOut = openFileOutput("samplefile.txt", MODE_WORLD_READABLE); Also the file name can not contain path separators. See Android Developers Reference public abstract FileOutputStream openFileOutput (String name, int mode) Open a private file associated with this Context's application package for writing. Creates the file if it doesn't already exist. Parameters name The name of the file to open; can not contain path separators. The file can be then be accessed like this. FileInputStream fis = openFileInput("samplefile.txt"); Note: For files which are huge in size, it's better to save it in sd card. Here is the code snippet. if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { FileOutputStream fos = null; try { File rootPath = new File(Environment.getExternalStorageDirectory(), "AutoWriter"); if (!rootPath.exists()) rootPath.mkdirs(); File file = new File(rootPath, "samplefile.txt"); fos = new FileOutputStream(file); // ... more lines of code to write to the output stream } catch (FileNotFoundException e) { Toast.makeText(this, "Unable to write file on external storage", Toast.LENGTH_LONG).show(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) {} } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/15214777", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to make a rich tooltip with a HTML form in it I have a paragraph of text with a link in it. I want to make a rich tool tip with a title on the top and a field to collect email addresses appear on hovering the link. What approach should I take? I have looked into tool tip libraries but none seem to have form support. Please find the code below The content in which the link is present: <p>Pellentesque habitant <a href="#">Link to show tooltip</a> morbi senectus tristique senectus et netus et malesuada pellentesque habitant senectus fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p> Tool tip content: <div class="tooltip"> <h3>Tooltip title</h3> <p>Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p> <form> <input type="email" placeholder="[email protected]" /> <input type="submit" value="subscribe" /> </form> <span class="branding">This is our branding message</span> </div> Now the effect I want to achieve is when I hover the link in the content the tooltip content should appear in a styled div. How should I do it? A: Check this snippet Updated $("a").bind("mousemove", function(event) { $("div.tooltip").css({ top: event.pageY + 10 + "px", left: event.pageX + 10 + "px" }).show(); }) $('.close').bind('click', function(){ $("div.tooltip").fadeOut(); }); body{ font-family:arial; font-size:12px; } .tooltip { width:350px; position:absolute; display:none; z-index:1000; background-color:#CB5757; color:white; border: 1px solid #AB4141; padding:15px 20px; box-shadow: 0px 3px 2px #8D8D8D; border-radius: 6px; } .close{ right: 15px; position: absolute; background: #fff; color: #555; width: 20px; height: 20px; text-align: center; line-height: 20px; border-radius: 50%; font-size: 10px; cursor:pointer; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="main"> <p>Pellentesque habitant <a href="#">Link to show tooltip</a> morbi senectus tristique senectus et netus et malesuada pellentesque habitant senectus fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. </p> <div class="tooltip"> <span class="close">X</span> <h3>Tooltip title</h3> <p>Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. </p> <form> <input type="email" placeholder="[email protected]" /> <input type="submit" value="subscribe" /> </form> <span class="branding">This is our branding message</span> </div> A: Follow these steps: * *Add the link and the tooltip div inside a new div. *Set tooltip div property to be visibility: hidden; *and on hover set the property of this tooltip to be visible. like: HTML: <div class="link"> <a href="#">Link to show tooltip</a> <div class="tooltip"> ......</div> </div> CSS: .link { position: relative; display: inline-block; border-bottom: 1px dotted black; } .link .tooltip { visibility: hidden; width: 120px; background-color: black; color: #fff; text-align: center; border-radius: 6px; padding: 5px 0; position: absolute; z-index: 1; } .link:hover .tooltip { visibility: invisible; } A: You could try to display yout tooltip element with the tilde selector on link hover: .tooltip { display: none; } a:hover ~ .tooltip{ display: block; } And then place your tooltip after the link element. <p> blabla <a href="#">hover me</a> <span class="tooltip">tooltip content</span> blabla </p> Here a pen where it works
{ "language": "en", "url": "https://stackoverflow.com/questions/39362353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Facebook offline conversions without customer data I need to send offline conversions to facebook (https://developers.facebook.com/docs/marketing-api/offline-conversions) but often I don't know the email or other user data. Is it possible to use data such as the Google Analytics client ID as an identifier? I tried to send in the facebook pixel an additional field extern_id which is set to the analytics client id. I send this identifier to Facebook with the offline API, unfortunately I don't find these conversions in facebook ads...
{ "language": "en", "url": "https://stackoverflow.com/questions/57041350", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Finding minimum sum of graph edge weight? I have been given a undirected weighted graph, witch represents the road with junctions. The task is in every cycle, which begins and ends in a same vertex choose the edge with the lowest weight and calculate the sum of all these edges in graph. Idea is to use Prim algorithm, but there is a chance that some cycles doesn't include edge from MST. How to solve this problem, and how to modify Prim's algorithm?
{ "language": "en", "url": "https://stackoverflow.com/questions/21255039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: conditionally set both fill and color in geom_point ggplot R what is wrong my code that does not change the filling color? cars %>% ggplot() + geom_point(aes(x = speed, y = dist, color= I(ifelse(dist >50, 'red', 'black')), fill= I(ifelse(dist >50, 'pink', 'gray')) ) ) A: You need to have a point shape that allows both fill and colour. library(ggplot2) cars %>% ggplot() + geom_point( aes(x = speed, y = dist, color= I(ifelse(dist >50, 'red', 'black')), fill= I(ifelse(dist >50, 'pink', 'gray')), ), shape = 21, size = 4 # changing size so it's easy to visualise ) To check point shapes that allow both fill and colour use help(points) and refer to the 'pch' values section
{ "language": "en", "url": "https://stackoverflow.com/questions/75488453", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: .Net AES encrypt mismatch after decrypt on Java I have to send the AES encrypted json as content to web server. But after decryption, the content has extra trash symbols appeared at the beggining of the line. My test method creates the object that is serialized and being send: [TestMethod] public void SendModeChangeWorksAsExpected() { var snpashot2Send = new ModeChangedReport { ControlWorkMode = ModeEnumeration.Stopped, //Controls ControlDate = DateTime.Now, IsSent = false, SentTime = null, ReportType = ReportType.ModeChanged, Line = new Line { AgencyId = "a799eb4f-86da-4af1-a221-9ed8b741b5ce" } }; //Создаём шифрованное значение var encryptedString = _agencyReportEncriptingTranslator.ConvertModeChange2CypheredString(snpashot2Send); //Отправляем в Агентство и получаем результат var value = _agencyClient.SendModeChangeReport(encryptedString); } Here are the serialization and encrypt methods: public string ConvertModeChange2CypheredString(ModeChangedReport report) { if (report == null) throw new ArgumentNullException(nameof(report)); //obj to json var json = new ModeChangedReportJson { LineId = report.Line.AgencyId, Mode = CreateModeFromIktToUzbekistan(report.ControlWorkMode), ActionDate = ConvertDateToAgencyString(report.ControlDate) }; //Serialization var retString = _agencyJsonSerializer.SerializeReport2Json(json); //Шифруем сериализованный json var cypheredValue = _encryptionService.EncryptString(retString); return cypheredValue; } Encrypt method: public string EncryptString(string plaintext) { var plainTextBytes = Encoding.UTF8.GetBytes(plaintext); var cypheredTextBytes = Encrypt(plainTextBytes); var converted2Base64Value = Convert.ToBase64String(cypheredTextBytes); return converted2Base64Value; } private byte[] Encrypt(byte[] bytes) { #region Args Validation if (bytes == null || bytes.Length < 1) { throw new ArgumentException("Invalid bytes to encrypt"); } if (_key == null || _key.Length < 1) { throw new InvalidOperationException("Invalid encryption key"); } #endregion byte[] encrypted; try { using (AesManaged aes = new AesManaged()) { aes.Key = _key; aes.IV = _iv; aes.Padding = PaddingMode.PKCS7; aes.Mode = CipherMode.CBC; ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, _iv); using (MemoryStream ms = new MemoryStream()) { ms.Write(aes.IV, 0, aes.IV.Length); using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) { cs.Write(bytes, 0, bytes.Length); } encrypted = ms.ToArray(); } } } catch (Exception e) { Console.WriteLine(e); throw; } return encrypted; } Http client send method: public bool SendModeChangeReport(string cypheredValue) { var token = GetAccessToken(); using (var client = new HttpClient()) { client.DefaultRequestHeaders.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.AuthorizationToken); client.DefaultRequestHeaders.Add("DEVICE_ID", _agencyAppSettings.DeviceId); var content2Post = new StringContent(cypheredValue, Encoding.UTF8, "application/json"); using (var response = client.PostAsync(_agencyAppSettings.SendModeChangedReportUrl, content2Post).Result) { string tokenResponse = null; try { tokenResponse = response.Content.ReadAsStringAsync().Result; response.EnsureSuccessStatusCode(); return true; } catch (Exception ex) { _eventLogManager.LogError("При попытке отправить отчёт о смене режима, произошла ошибка: " + $"Код: {response.StatusCode}. Контент: {tokenResponse}. Ошибка: {ex.Message}."); return false; } } } } After decryption on receiving server, the string grows with extra trash characters at the beginning, like G���h R��EQ�Z {"lineid":"a799eb4f-86da-4af1-a221-9ed8b741b5ce"... The decrypt method of the server (Java): I think that the problem is the padding difference: PKCS7 on my side, and PKCS5 on server. How can I solve this problem with the extra chars appear on server side? A: Those aren't trash characters, they're the Unicode Replacement Character returned when bytes are decoded into text using the wrong character set. The very fact you got readable text means decrypting succeeded. It's decoding the bytes into text that failed. The bug is in the Java code. It's using the String(byte[]) which, according to the docs: Constructs a new String by decoding the specified array of bytes using the platform's default charset. That's obviously not UTF8. The String​(byte[] bytes,Charset charset) or String​(byte[] bytes,String charsetName) constructors should be used instead, passing the correct character set, eg : byte[] decryptedBytes = cipher.doFinal(....); return new String(decryptedBytes, StandardCharsets.UTF_8); The hacky alternative is to change the remote server's default character set to UTF8.
{ "language": "en", "url": "https://stackoverflow.com/questions/73077299", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Break the loop into half, if the loop count is even I want to break the loop into half of the total loop count. If the total loop count is odd, I would like to remove the last array item in order to make the total loop count even and add the deleted item to the second half. Here is the code structure to demonstrate the loop- <?php $faqs = new WP_Query( array ( 'post_type' => 'faq' )); ?> <div class="row"> <div class="col-lg-6"> <!-- The first half of the tootal loop count. --> <?php while ($faqs->have_posts()) : $faqs->the_post(); the_content(); endwhile(); ?> </div> <div class="col-lg-6"> <!-- The second half of the tootal loop count. --> <?php while ($faqs->have_posts()) : $faqs->the_post(); the_content(); endwhile(); ?> </div> </div> I don't know how to control the loop based on my mentioned conditions. That's why I couldn't able to try loop controlling. A: In a single loop. Hopefully, it'll work. Couldn't test so let me if you face any situation. <?php $faqs = new WP_Query([ 'post_type' => 'faq', 'post_status' => 'publish', ]); $half = intval($faqs->post_count / 2); $counter = 0; ?> <div class="row"> <div class="col-lg-6"> <?php while ($faqs->have_posts()) : $faqs->the_post(); ?> <?php if ( $counter === $half ) : ?> </div><div class="col-lg-6"> <?php endif; ?> <?php the_content(); ?> <?php ++$counter; endwhile; ?> </div> </div> A: try it like this <?php $faqs = new WP_Query( array ( 'post_type' => 'faq' )); ?> <div class="row"> <div class="col-lg-6"> <!-- The first half of the total loop count. --> <?php $i=0; while ($faqs->have_posts() && $i < $faqs->post_count / 2) : $faqs->the_post(); $i++ the_content(); endwhile(); ?> </div> <div class="col-lg-6"> <!-- The second half of the tootal loop count. --> <?php while ($faqs->have_posts()) : $faqs->the_post(); the_content(); endwhile(); ?> </div> </div> https://wordpress.stackexchange.com/questions/27116/counting-the-posts-of-a-custom-wordpress-loop-wp-query
{ "language": "en", "url": "https://stackoverflow.com/questions/56136994", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: MySQL and PHP application fails - Error 2002 I've written a php-based site on my local machine and I'm trying to run it using the Apache Web Server in XAMPP and a mySQL database, which is on my local machine, external to XAMPP. When I go to the page where it should be, however, I get the following error: Sorry, a problem occurred. Please try later.SQLSTATE[HY000] [2002] No such file or directory I've seen a lot of people saying this points to php.ini not being able to access mysql.sock, but all of the changes haven't worked for me. I don't have any mysql.sock files, but I do have mysqld.sock files, and I've put the paths to them in php.ini at all the points where it asks for them. I haven't seen anyone talking about mysqld.sock files and whether or not it's an issue, so any help would be valuable. Here's my config.php, if that's valuable: ini_set( "display_errors", true ); date_default_timezone_set( "Europe/London" ); // http://www.php.net/manual/en/timezones.php define( "DB_DSN", "mysql:host=localhost;dbname=dog_site" ); define( "DB_USERNAME", "root" ); define( "DB_PASSWORD", "***" ); define( "CLASS_PATH", "classes" ); define( "TEMPLATE_PATH", "templates" ); define( "HOMEPAGE_NUM_POSTS", 5 ); define( "ADMIN_USERNAME", "admin" ); define( "ADMIN_PASSWORD", "***" ); require( CLASS_PATH . "/User.php" ); require( CLASS_PATH . "/Litter.php" ); require( CLASS_PATH . "/Post.php" ); require( CLASS_PATH . "/PostLikes.php" ); require( CLASS_PATH . "/LitterLikes.php" ); require( CLASS_PATH . "/PostComments.php" ); require( CLASS_PATH . "/LitterPhotos.php" ); require( CLASS_PATH . "/PostPhotos.php" ); function handleException( $exception ) { echo "Sorry, a problem occurred. Please try later."; echo $exception->getMessage(); error_log( $exception->getMessage() ); } set_exception_handler( 'handleException' ); ?>```
{ "language": "en", "url": "https://stackoverflow.com/questions/62571231", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to configure Maven to build two versions of an artifact, each one for a different target JRE I have a maven module that I need to use in the J2ME client and in the EJB server. In the client I need to compile it for target 1.1 and in the server for target 1.6 . I also need to deploy the 1.6 version to a Nexus repository, so the members working on the server project can include this dependency without needing to download the source code. I've read at http://java.dzone.com/articles/maven-profile-best-practices that using profiles is not the best way of doing this, but the author didn't say what's the best way. Here is my pom.xml: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <artifactId>proj-parent</artifactId> <groupId>br.com.comp.proj</groupId> <version>0.0.4-SNAPSHOT</version> </parent> <artifactId>proj-cryptolib</artifactId> <name>proj - Cryto Lib</name> <dependencies> <dependency> <groupId>br.com.comp</groupId> <artifactId>comp-proj-mobile-messages</artifactId> <version>0.0.2-SNAPSHOT</version> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.3</source> <target>1.1</target> <fork>true</fork> </configuration> </plugin> </plugins> </build> </project> A: As Haylem suggests thought you'll need to do it in two steps, one for the compile and one for the jars. For the compiler <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>2.5</version> <executions> <execution> <configuration> <source>1.3</source> <target>1.5</target> <fork>true</fork> <outputDirectory>${project.build.outputDirectory}_jdk5</outputDirectory> </configuration> </execution> <execution> <configuration> <source>1.3</source> <target>1.6</target> <fork>true</fork> <outputDirectory>${project.build.outputDirectory}_jdk6</outputDirectory> </configuration> </execution> </executions> </plugin> And then for the jar plugin <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>2.3.1</version> <executions> <execution> <goals> <goal>jar</goal> </goals> <configuration> <classesDirectory>${project.build.outputDirectory}_jdk5</classesDirectory> <classifier>jdk5</classifier> </configuration> </execution> <execution> <goals> <goal>jar</goal> </goals> <configuration> <classesDirectory>${project.build.outputDirectory}_jdk6</classesDirectory> <classifier>jdk6</classifier> </configuration> </execution> </executions> </plugin> you can then refer to the required jar by adding a <classifier> element to your dependency. e.g. <dependency> <groupId>br.com.comp.proj</groupId> <artifactId>proj-cryptolib</artifactId> <version>0.0.4-SNAPSHOT</version> <classifier>jdk5</classifier> </dependency> A: You can configure this via the Maven compiler plugin. Take a look at the Maven compiler plugin documentation. You could enable this via different profiles for instance. If you only want to have different target versions you could simply use a variable target. Something like this: <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.3</source> <target>${TARGET_VERSION}</target> <fork>true</fork> </configuration> </plugin> A: To complement my comment to wjans' answer, as you requested more details. The following would have the compiler plugin executed twice to produce two different sets of classfiles, identified by what is called a classifier (basically, a marker for Maven to know what you refer to when a single project can produce multiple artifacts). Roughly, something like: <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>2.5</version> <executions> <execution> <configuration> <source>1.3</source> <target>1.5</target> <fork>true</fork> <classifier>jdk5</classifier> </configuration> </execution> <execution> <configuration> <source>1.3</source> <target>1.6</target> <fork>true</fork> <classifier>jdk6</classifier> </configuration> </execution> </executions> </plugin> Note that people sometimes frown on using classifiers, as they on using profiles, as they can possibly mean that your project should be scinded in multiple projects or that you are harming your build's portability.
{ "language": "en", "url": "https://stackoverflow.com/questions/10920142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: A better way to do this htaccess rewrite rule I have this rewrite rule that checks for a country code in the url and fetches content accordingly. Problem is there are 60+ countries. Can this be done in a different way rather than entering codes of all the countries in the rule? RewriteRule ^/?(us|uk|ca)/p([0-9]+)/?$ Note the (us|uk|ca) part? A whole lot more need to go in there. Any better way to do this? A: RewriteRule ^/?([a-z][a-z])/p([0-9]+)/?$ But it doesn't check if the language is a valid one (and I don't know if you expect language codes with more than 2 characters if such a thing exists) EDIT : this regexp is shorter : RewriteRule ^([a-z]{2})/p\d+/?$ The first slash is useless and \d+ means one or more digits, see @TerryE's comment
{ "language": "en", "url": "https://stackoverflow.com/questions/12976230", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: mysql query that has join and counts I need help getting the top 5 results and their counts from columns from two different tables in a mysql database joined together. table1 cols ------- id, country, timestamp table2 cols -------- id, table1_id, reason The results id like to get are the top 5 countries and their number of times found between two timestamps, and the top 5 reasons and their counts for all the rows used to generate the first count. There is a one to many relationship between table1 and table2. This is stumping me and I appreciate any insight you could give me. A: It's not entirely clear what resultset you want to return. This may be of some help to you: SELECT t.country , COUNT(DISTINCT t.id) AS count_table1_rows , COUNT(r.id) AS count_table2_rows , COUNT(*) AS count_total_rows FROM table1 t LEFT JOIN table2 r ON r.table1_id = t.id WHERE t.timestamp >= NOW() - INTERVAL 7 DAY AND t.timestamp < NOW() GROUP BY t.country ORDER BY COUNT(DISTINCT t.id) DESC LIMIT 5 That will return a maximum of 5 rows, one row per country, with counts of rows in table1, counts of rows found in table2, and a count of the total rows returned. The LEFT keyword specifies an "outer" join operation, such that rows from table1 are returned even if there are no matching rows found in table2. To get the count for each "reason", associated with each country, you could do something like this: SELECT t.country , COUNT(DISTINCT t.id) AS count_table1_rows FROM table1 t LEFT JOIN ( SELECT s.country , r.reason , COUNT(*) AS cnt_r FROM table1 s JOIN table2 r ON s.table1_id = t.id WHERE s.timestamp >= NOW() - INTERVAL 7 DAY AND s.timestamp < NOW() GROUP BY s.country , r.reason ) u ON u.country = t.country WHERE t.timestamp >= NOW() - INTERVAL 7 DAY AND t.timestamp < NOW() GROUP BY t.country , u.reason ORDER BY COUNT(DISTINCT t.id) DESC , t.country DESC , u.cnt_r DESC , u.reason DESC This query doesn't "limit" the rows being returned. It would be possible to modify the query to have only a subset of the rows returned, but that can get complex. And before we muck the complexity of adding "top 5 within top 5" type limits, we want to ensure that the rows returned by a query are a superset of the rows we actually want. A: Is this what you want? select t2.reason, count(*) from (select t1.country, count(*) from table1 t1 where timestamp between @STARTTIME and @ENDTIME group by country order by count(*) desc limit 5 ) c5 join table1 t1 on c5.country = t1.country and t1.timestamp between @STARTTIME and @ENDTIME join table2 t2 on t2.table1_id = t1.id group by t2.reason; The c5 subquery gets the five countries. The other two bring back the data for the final aggregation.
{ "language": "en", "url": "https://stackoverflow.com/questions/25675316", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: R: Print list to a text file I have in R a list like this: > print(head(mylist,2)) [[1]] [1] 234984 10354 41175 932711 426928 [[2]] [1] 1693237 13462 Each element of the list has different number of its elements. I would like to print this list to a text file like this: mylist.txt 234984 10354 41175 932711 426928 1693237 13462 I know that I can use sink(), but it prints names of elements [[x]], [y] and I want to avoid it. Also because of different number of elements in each element of the list it is not possible to use write() or write.table(). A: Not tested, but it should work (edited after comments) lapply(mylist, write, "test.txt", append=TRUE, ncolumns=1000) A: Format won't be completely the same, but it does write the data to a text file, and R will be able to reread it using dget when you want to retrieve it again as a list. dput(mylist, "mylist.txt") A: I saw in the comments for Nico's answer that some people were running into issues with saving lists that had lists within them. I also ran into this problem with some of my work and was hoping that someone found a better answer than what I found however no one responded to their issue. So: @ali, @FMKerckhof, and @Kerry the only way that I found to save a nested list is to use sink() like user6585653 suggested (I tried to up vote his answer but could not). It is not the best way to do it since you link the text file which means it can be easily over written or other results may be saved within that file if you do not cancel the sink. See below for the code. sink("mylist.txt") print(mylist) sink() Make sure to have the sink() at the end your code so that you cancel the sink. A: depending on your tastes, an alternative to nico's answer: d<-lapply(mylist, write, file=" ... ", append=T); A: Another way writeLines(unlist(lapply(mylist, paste, collapse=" "))) A: Here's another way using sink: sink(sink_dir_and_file_name); print(yourList); sink() A: Here is another cat(sapply(mylist, toString), file, sep="\n") A: I solve this problem by mixing the solutions above. sink("/Users/my/myTest.dat") writeLines(unlist(lapply(k, paste, collapse=" "))) sink() I think it works well
{ "language": "en", "url": "https://stackoverflow.com/questions/3044794", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "53" }
Q: Clearing a text file in PHP I have a text file that ends up with over 500 lines of text each day. I'm setting up a cron job to manually clear the file at the end of the day but I cannot get it to clear. I've looked online and tried the methods below, but nothing seems to clear the text file... (I ran the file on my server and checked the .txt file using Transmit FTP Client to check the text file and the 500+ lines of text were still there.) $handle = fopen ("emails.txt", "w+"); fclose($handle); file_put_contents('emails.txt', ''); $handle = fopen("emails.txt", "w+"); fwrite($handle , ''); fclose($handle); How can I empty this text file using PHP? A: This works for me: $f = fopen('emails.txt','r'); $content = file('emails.txt'); array_splice($content, 0, 500); file_put_contents('emails.txt', $content); fclose($f); A: It looks like you want to truncate your file. Try with w, instead of w+ http://www.tizag.com/phpT/filetruncate.php You may also want to check your error logs. If the file isn't writeable by the web / apache user then nothing significant will occur. A: If you have this on a cron task, you may want to use sed instead. Sed can remove as many lines as you wish from a file. Unix Sed Command to Delete lines in file sed '1d' file removes the first line in a file, while sed '2,4d' file would remove lines 2 through 4. If you do this via cron, be sure to include the full path to your file, from / (root) forward. A: Assuming that your script have permissions to write to the text file and that the two files are located in the same directory. I guess that you're not running the script from the same directory, so you could try this : $handle = fopen (__DIR__."/emails.txt", "w"); fclose($handle);
{ "language": "en", "url": "https://stackoverflow.com/questions/28857210", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Fastest way to get residuals from linear, poisson, and negative binomial regressions across many responses I have a numeric, a count, and an over-dispersed count large matrices: set.seed(1) numeric.mat <- matrix(rnorm(10000*6000),10000,6000) count.mat <- matrix(rpois(10000*6000,10),10000,6000) dispersed.count.mat <- matrix(rnegbin(10000*6000,10,2),10000,6000) And one corresponding factors data.frame (can be a matrix too): factors.df <- data.frame(f1 = sample(LETTERS[1:3], 10000, replace = T), f2 = sample(LETTERS[4:5], 10000, replace = T)) The number of factors is pretty small (in this case only 2 but won't be more than 5 for real data), and the number of levels in each (they're all categorical) is also small (also up to 5). I'd like to obtain the residuals for fitting a linear, poisson, and negative binomial regression models to each of the columns in each of the matrices, respectively. So for a single column: data.df <- factors.df %>% dplyr::mutate(numeric.y = numeric.mat[,1], count.y = count.mat[,1], dispersed.count.y = dispersed.count.mat[,1]) I'd use: lm(numeric.y ~ f1+f2, data = data.df)$residuals residuals(object = glm(count.y ~ f1+f2, data = data.df, family = "poisson"), type = 'pearson') residuals(object = glm.nb(formula = model.formula, data = regression.df), type = 'pearson') For the three regression models. Is there a faster way of obtaining these residuals other than, for example, using do.call, for each. E.g.: do.call(cbind, lapply(1:ncol(numeric.mat), function(i) lm(numeric.y ~ f1+f2, data = dplyr::mutate(factors.df, numeric.y = numeric.mat[,i]) )$residuals )) A: I'd slightly readjust how the workflow runs and allow it to be easily run in parallel. # Use variables to adjust models, makes it easier to change sizes iter <- 60 iter_samps <- 1000 factors_df <- data.frame(f1 = sample(LETTERS[1:3], iter_samps, replace = T), f2 = sample(LETTERS[4:5], iter_samps, replace = T)) # using a data.frame in a longer format to hold the data, allows easier splitting data_df <- rep(list(factors_df), iter) %>% bind_rows(.id = "id") %>% mutate(numeric_y = rnorm(iter_samps * iter), count_y = rpois(iter_samps * iter, 10), dispersed_count_y = MASS::rnegbin(iter_samps * iter, 10, 2)) # creating function that determines residuals model_residuals <- function(data) { data$lm_resid <- lm(numeric_y ~ f1+f2, data = data)$residuals data$glm_resid <- residuals(object = glm(count_y ~ f1+f2, data = data, family = "poisson"), type = 'pearson') return(data) } # How to run the models not in parallel data_df %>% split(.$id) %>% map(model_residuals) %>% bind_rows() To run the models in parallel you can use multidplyr to do all the annoying work library("multidplyr") test = data_df %>% partition(id) %>% cluster_library("tidyverse") %>% cluster_library("MASS") %>% cluster_assign_value("model_residuals", model_residuals) %>% do(results = model_residuals(.)) %>% collect() %>% .$results %>% bind_rows()
{ "language": "en", "url": "https://stackoverflow.com/questions/47170784", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Excel Pain: Saved With Filters, Opened And file Was Half the Size So something happened twice that has caused me hours of retroactive work. Extremely, extremely annoying, and the bain of my existence. I have an .xls file with about 171K rows. I saved it with filters on, reducing the number of shown rows to about 13K. When I reopened the file the next day the filters were not showing, but rows were 'hidden', because in order to show all the rows I had to 'unhide'. The problem is that when I unhide, the total rows is ~65K aka the last numbered row that was showing when I had filters on. Has this happened to anyone before or know how to recover the full 171K rows? I know for a fact I didn't 'clear' or 'delete' anything before or after saving. A: One piece of advise I have is for you to start reading screen prompts. When saving a large file with over 65536 rows this kind of warning is displayed. Only you can prevent your own errors. A: You can avoid this by making a copy of the original and filtering on that, then you always have the source if you make an error.
{ "language": "en", "url": "https://stackoverflow.com/questions/53565768", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Examples table throwing error in Eclipse when parameterising scenario I am in the process of working through a guide on how to parameterise my test runs with an Examples table however when I write the scenario in Eclipse as the guide states, I get an error against the Examples Table. I tried refreshing my project or attempting to see if I needed to import anything however there Eclipse does not provide any information beyond the error message. "Examples" is set to bold and formatted in the manner of "Scenario Outline:" which suggests Eclipse recognises it for what it is but in spite of this I get an error. Scenario: Home page default login Given User is on landing page When User login to application with username <username> and password <password> Then Home page is displayed And The user is registered Examples: |username | password | |Leonard | zxcv | |Lyra | qwerty | The error shown against the Examples line is simply; missing EOF at 'Examples:' A: The answer is simple, and not "I'm an idiot" although there's an argument for that. The issue I am experiencing is that I use Scenario: as opposed to Scenario Outline: Making that simple change removes the error and allows me to run my test
{ "language": "en", "url": "https://stackoverflow.com/questions/57460806", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: fixed height Slider for any device I am trying to achieve a full screen option for any device. There is a slider along with 04 boxes which & I am trying to show all of them in full screen on any device. I have almost achieved it by using .carousel-inner {min-height:83vh;} .carousel-inner img{max-height:83vh;} but its stretching the image. I need a better solution. .container-fluid { margin:0; Padding:0; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <div id="carousel-example-generic" class="carousel slide" data-ride="carousel"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li> <li data-target="#carousel-example-generic" data-slide-to="1"></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner" role="listbox"> <div class="item active"> <img src="http://logohour.com/images/bg2.jpg" alt="..."> <div class="carousel-caption"> ... </div> </div> <div class="item"> <img src="http://logohour.com/images/bg3.jpg" alt="..."> <div class="carousel-caption"> ... </div> </div> <!-- Controls --> <a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next"> <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> <div class="container-fluid"> <div class="col-xs-3"> <img src="http://placehold.it/150x75/111111" alt="..."> </div> <div class="col-xs-3"> <img src="http://placehold.it/150x75/333333" alt="..."> </div> <div class="col-xs-3"> <img src="http://placehold.it/150x75/666666" alt="..."> </div> <div class="col-xs-3"> <img src="http://placehold.it/150x75/999999" alt="..."> </div> </div> <br><br> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> A: in css only Write This .carousel-inner > .item > img { height:500px; } If I use the provided class so its also effecting width but when I used min-height with your class so its working fine but only on laptop and small screen sizes but also stretching. its not working with large screens A: Plz use it <script> $( document ).ready(function() { function mySlider() { var winH = $(window).height(); var winW = $(window).width(); var fourBoxH = $('#fourBox').height(); var finalSliderH = winH - fourBoxH; $('.carousel-inner').css( {'height' : finalSliderH+'px', 'width' : winW+'px', }); }; window.onload = mySlider(); }); </script> css >> .carousel-inner { } .carousel-inner img { width:100% } on 4 box container add id >> <div class="container-fluid" id="fourBox">
{ "language": "en", "url": "https://stackoverflow.com/questions/43691515", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How secure is field validation in Google Forms? Some people are using this data validation pattern to protect forms: * *A youtube video from Google for Education uses this pattern. *A similar scenario to mine with a similarly proposed solution. Since Google for Education showcases this pattern, I want to believe it is reasonably secure. But I also understand the above solution is client-side validation, based on this answer. Logically, doesn't this imply the validation values and logic can be exposed by scraping/viewing the source? How safe is it to store passwords and unique IDs as a regex in these validation fields? For context, I'm hoping to use Google Forms + GAS for verified, unique form submissions from a set of non-google account emails while reducing quota usage from spam/misuse. A: It's not secure. All client side validations are insecure by design. Pattern validation passwords are visible in the source code. Having said that, a single password for multiple users is also insecure. All it takes is one user compromise to invalidate the whole thing. If you need a fully secure solution, create your own form with HtmlService with oauth authorization and Google identity.
{ "language": "en", "url": "https://stackoverflow.com/questions/61701576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to flatten a multi column dataframe into 2 columns Given the following table: group_a = {'ba':[2.0,9.4,10.8], 'bb':[4.2,7.1,3], 'bc':[8.1,9.5,6.1]} A = pd.DataFrame(group_a, index=['aa','ab','ac']) That looks like this: ba bb bc aa 2.0 4.2 8.1 ab 9.4 7.1 9.5 ac 10.8 3.0 6.1 How can I flatten this table so that it looks like this: Values aa_ba 2.0 aa_bb 4.2 aa_bc 8.1 ab_ba 9.4 ab_bb 7.1 ab_bc 9.5 ac_ba 10.8 ac_bb 3.0 ac_bc 6.1 A: You can use stack and rework the index: B = A.stack() B.index = B.index.map('_'.join) out = B.to_frame('Values') output: Values aa_ba 2.0 aa_bb 4.2 aa_bc 8.1 ab_ba 9.4 ab_bb 7.1 ab_bc 9.5 ac_ba 10.8 ac_bb 3.0 ac_bc 6.1 A: Since you have your indexes set, you can do this most easily with a .stack operation. This results in a pd.Series with a MultiIndex, we can use a "_".join to join each level of the MultiIndex by an underscore and create a flat Index. Lastly, since you wanted a single column DataFrame you can use .to_frame() to convert the Series into a DataFrame out = A.stack() out.index = out.index.map("_".join) out = out.to_frame("values") print(out) values aa_ba 2.0 aa_bb 4.2 aa_bc 8.1 ab_ba 9.4 ab_bb 7.1 ab_bc 9.5 ac_ba 10.8 ac_bb 3.0 ac_bc 6.1 You can also use a method chained approach- just need to use .pipe to access the stacked index: out = ( A.stack() .pipe(lambda s: s.set_axis(s.index.map("_".join))) .to_frame("values") ) print(out) values aa_ba 2.0 aa_bb 4.2 aa_bc 8.1 ab_ba 9.4 ab_bb 7.1 ab_bc 9.5 ac_ba 10.8 ac_bb 3.0 ac_bc 6.1 A: Stack, use list comprehension and fstrings to compute new index . s = A.stack().to_frame('values') s.index=([f'{a}_{b}' for a,b in s.index]) values aa_ba 2.0 aa_bb 4.2 aa_bc 8.1 ab_ba 9.4 ab_bb 7.1 ab_bc 9.5 ac_ba 10.8 ac_bb 3.0 ac_bc 6.1
{ "language": "en", "url": "https://stackoverflow.com/questions/72551878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Listing indices using sqlalchemy Is it possible to list all indices in a db using sqlalchemy? A: yes. from sqlalchemy import create_engine from sqlalchemy.engine import reflection engine = create_engine('...') insp = reflection.Inspector.from_engine(engine) for name in insp.get_table_names(): for index in insp.get_indexes(name): print index
{ "language": "en", "url": "https://stackoverflow.com/questions/5605019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Comparing two tables and returning rows that do not exist based on multiple field comparisons Say I have a Table called #ListTable: Item: Apple Bannana Pea Milk Green And Another Table Food similar to: Date Fruit Vegetable Dairy Color 2/16/17 Apple NULL NULL Green 2/16/17 NULL Pea NULL Green 2/16/17 NULL NULL Milk White If the value in the list exists in the Food Table I want to return the record. So I have something like: DECLARE @Date = '2/16/17', @InclusionFlag = 1 SELECT * FROM Food F INNER JOIN #ListTable LT1 ON F.Fruit = LT1.Item WHERE Date = @Date UNION ALL SELECT * FROM Food F INNER JOIN #ListTable LT2 ON F.Color = LT1.Item WHERE Date = @Date ... Essentially returning a record if the item in the List corresponds to one of the fields I specify. I know there could be "duplicate" records like Apple being "Apple" and "Green" and I want that. However, I also want to be able to toggle the Inclusion Flag to 0 and return items in ListTable that do not have a match with any fields in Food. How would I return that list of securities that do not match? I know there are similar questions but I am having trouble figuring it out for the multiple field comparison case. Thanks A: You can use cross apply() to unpivot your data first, then use a case expression with when exists() in your where clause to return 0 or 1 when it exists and compare that to @InclusionFlag. ;with FoodItem as ( select x.Item from food as f cross apply (values (Fruit),(Vegetable),(Dairy),(Color)) as x (Item) where x.Item is not null and f.Date = @Date ) select lt.Item from ListTable as lt where case when exists ( select 1 from FoodItem fi where lt.Item = fi.Item ) then 1 else 0 end = @InclusionFlag A: If I got it right, Food rows (may be repeating) matching #ListTable SELECT F.* FROM Food F INNER JOIN #ListTable LT1 ON LT1.Item IN (F.Fruit, F.Vegetable, F.Dairy, F.Color) WHERE Date = @Date
{ "language": "en", "url": "https://stackoverflow.com/questions/42302713", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get a currency's display name before Android API 19? Currency.getDisplayName(java.util.Locale) is exactly what I want... except it's only available since Android API 19. That's no good as my minSdkVersion < 19. Does anyone know how to get the locale-specific display name for a currency before API 19? Preferably without having to use a third-party library. This question can alternatively be expressed as: How can you get the equivalent of Currency.getDisplayName(java.util.Locale) before Java 7?
{ "language": "en", "url": "https://stackoverflow.com/questions/40349116", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I set static asset cache-control headers while using PHP on Heroku? Is this worth trying to accomplish or should I move the assets to CloudFront (or some other CDN)? Based on past experience, I'm hesitant to go down the CDN route with this project. I tried using a rake task to minify and concatenate my assets, then upload them to the CloudFront. However, when I deployed the project (now containing the rake task) Heroku decided that my app was now ROR and not PHP and the app was toast.
{ "language": "en", "url": "https://stackoverflow.com/questions/12059488", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: subtract two values in the field I am using python. There are two columns. columns A and B. I want to reduce the value in column A and B when the save button in the press this my code But what happens when I press the save button. value to 0 def _tot_get_deposit(self, cr, uid, ids, name, arg, context=None): res = {} for deposit in self.browse(cr, uid, ids, context=context): sum = 0.0 sum = A - B return sum return res A: i think you need to read more about how functions work. once you return anything, the function will end. you can not itterate over anything and return multiple values within a function. try saving them locally in the function, and then at the end returning a list/dict/tuple with all the results. for instance... i think your code could be written: def _tot_get_deposit(self, cr, uid, ids, name, arg, context=None): res = {} results = [] for deposit in self.browse(cr, uid, ids, context=context): sum = 0.0 sum = A - B results.append( sum ) return (res,results) this will create a list of "sum" which is then added to your dict "res" and then returned. together as a tuple.
{ "language": "en", "url": "https://stackoverflow.com/questions/11824295", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How can multiple web devs use git to work on one page simultaneously? We're looking into using git for a new system we're designing. We currently have a production machine and a dev machine. We use svn to keep production updated with our dev commits. The dev machine has a complete copy of our codebase for each developer (just 2 of us currently). Here's the file structure: html/ dev_timmy/ stuff/ thing1.php thing2.php dev_johnny/ stuff/ thing1.php thing2.php If we were both working on thing1.php, I would make changes to the file in my directory, and he'd make changes to it in his. To test our changes, we simply include our dev directory in the url. http://ourwebsite.com/dev_timmy/stuff/thing1.php http://ourwebsite.com/dev_johnny/stuff/thing1.php I'm sure having copies of code isn't the best solution. But how can we view our own changes on the internet? How can we make dev_timmy-based urls resolve to the version of the page that Timmy is working on? A: There's nothing special about git to help with this kind of thing: Files have to be on disk somewhere so they can be dished out by a web server. This question basically boils down to workflow. If you want to be able to look at the code you're working on independent of the code your coworker is working on the general solution is to have multiple sites (either separate web servers or just different virtual hosts behind a server) setup with different URLs. For example at our company we each have our own dev vm, and our own username.company.com URL that we can use to refer to code hosted on our VM. Generally people have their git repository as the document root (or virtual host root) for their web server. They edit and test on this, committing locally as they go. When we're done with our development we merge to a central repository, and there's a web server in test that we can go to which shows what's currently merged for testing. Once that's been accepted it's merged to master and pushed to production. A: But how can we view our own changes on the internet? First of all you have to upload it to the internet of course. You will need some place to store your code (bitbucket, gthub etc). Those cloud services has a web interface to view your changes and all your history as well. How can we make dev_timmy-based urls resolve to the version of the page that Timmy is working on? Using git you can use branches. Each one of you will have its own branch which will allow you 2 to work on the same code at the same time and update your local code whenever you want. This is what branches are. Another solution might be to use the same project as submodule or using workdir which will allow you to have the same code under different folders
{ "language": "en", "url": "https://stackoverflow.com/questions/34643381", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to sort different data types in java and print them in a table ? (using method overloading) The objective is to input "any data type" using a java method overloading. After the value has been taken, another method will sort the data according to it's data type in different arrays. After the all the data has been entered and stored in arrays, it has to be printed onto a table. Eg: data(23) - this will store integer value to an array data(34.453) - this will store the double value to an array data("hello world") - this will store string value to array Considering that array size in java are predefined, the table should not print the null or 0 values. All the null/0 values should be excluded while printing. A: To solve this problem: * *We can use the method overloading to capture all data *Each method will use a different data type but will have the same name - data() *The number of null values of each array should be found out. *the variable n will determine which is the largest size among all the 3 integers. *n will be the test expression limit when printing the table public class overLoadEg { //array that will store integers static int[] intArray = new int[10]; //array that will store doubles static double[] doubleArray = new double[10]; //array that will store strings static String[] stringArray = new String[10]; static int i = 0, j = 0, k = 0, m, n; public static void main(String[] args) { //input values data(23); data(23.4554); data("Hello"); data("world"); data("help"); data(2355); data(52.56); data("val"); data("kkj"); data(34); data(3); data(2); data(4); data(5); data(6); data(7); data(8); display(); } public static void data(int val){ //add int value to int array intArray[i] = val; System.out.println("Int " + intArray[i] + " added to IntArray"); i++; } public static void data(Double val){ //add double value to double array doubleArray[j] = val; System.out.println("Double " + doubleArray[j] + " added to doubleArray"); j++; } public static void data(String val){ //add string value to stringarray stringArray[k] = val; System.out.println("String " + stringArray[k] + " added to stringArray"); k++; } public static void max(){ //To get the maximum number of values in each array int x, y, z; x = y = z = 0; //counting all the null values in each array and storing in x, y and z for(m=0;m<10;m++){ if(intArray[m] == 0){ ++x; } if(doubleArray[m] == 0){ ++y; } if(stringArray[m] == null){ ++z; } } //subtracting the null/0 count from the array size //this gives the active number of values in each array x = 10 - x; y = 10 - y; z = 10 - z; //comparing all 3 arrays and check which has the max number of values //the max numbe is stored in n if(x > y){ if(x > z){ n = x; } else{ n = z; } } else{ if(y > z){ n = y; } else{ n = z; } } } public static void display(){ //printing the arrays in table //All the null/0 values are excluded System.out.println("\n\nInt\tDouble\t\tString"); max(); for(m = 0; m < n; m++){ System.out.println(intArray[m] + "\t" + doubleArray[m] + "\t\t" + stringArray[m]); } System.out.println("Count : " + m); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/68300375", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: d3 cloud layout - show all tags [background] currently I'm working on a little web project for data visualization and I want to use create a tagcloud or wordcloud with cloud layout of the javascript d3 framework (d3 cloud layout). I've built some examples that almost satisfy my requirements. The only thing that doesn't work is, that some words/tags aren't displayed in my tag cloud. As far as I understand the placing algorithm for the tags, this comes because the algorithm finds no suitable place to position all tags without overlaying other tags. My question: How can I display all available tags and is there a setting in the framework to do this? I'm rather new to javascript so I had quite a hard time to understand the whole cloud layout and the positioning algorithm to find a way to achieve my goal.
{ "language": "en", "url": "https://stackoverflow.com/questions/24489651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: iOS8 GameKit TurnBasedMatch playerID deprecated I am working with GameCenter / GameKit in iOS8 to build a TurnBasedMatch. I am confused as to how to identify whether the current player (ie the one with the app running currently on the iPhone) is the one whose turn it is. The reason I am having this issue is that Apple docs say that GKTurnBasedParticipant.playerID is deprecated in iOS8. I used to do the following: - when GameCenter authenticates: (1) store the current playerID locally (2) load the current Match (3) check if Match.currentParticipant's playerID matches the locally stored playerID and if it is then allow the player to take his turn Now in iOS8 - currentParticipant (which is a GKTurnBasedParticipant) has playerID deprecated. So how do I know whether the currentParticipant is actually the local player? A: You don't need to store the playerID to check identities. Local playerID can be accessed always with: [GKLocalPlayer localPlayer].playerID As to how to use playerID now that it's deprecated, that property was only moved from GKTurnBasedParticipant to GKPlayer. That doesn't affect the code that I pasted before, but it does affect the way you access to match.participants. So, for any given player, the way to access it in iOS8 would be: GKTurnBasedParticipant *p1 = (GKTurnBasedParticipant *)self.match.participants[index]; p1.player.playerID As you can see, you only have to add a .player to your current code.
{ "language": "en", "url": "https://stackoverflow.com/questions/25933071", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: SMPT SSL exception origin I am sending mail using SMTP SSL in my c# code. While sending mail , iam getting the following exception- Server does not support secure connections. When does this error comes? Does this implies problem on sender's side or the receiver's side. SMTP configuration <add key="EmailUserName" value="[email protected]" /> <add key="NameToDisplay" value="Admin" /> <!--Use proper password--> <add key="EmailPassword" value="password" /> <add key="SmtpHostUrl" value="smtp.gmail.com" /> <add key="SmtpPort" value="25" /> SendMail method SmtpClient objSmtpClient = new SmtpClient(); objSmtpClient.Host = ConfigurationManager.AppSettings["SmtpHostUrl"]; objSmtpClient.Port = int.Parse(ConfigurationManager.AppSettings["SmtpPort"]); objSmtpClient.UseDefaultCredentials = false; objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; objSmtpClient.EnableSsl = true; objSmtpClient.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["EmailUserName"], ConfigurationManager.AppSettings["EmailPassword"]); objSmtpClient.Send(objMailMessage); Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/44821373", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MPI remote memory access (RMA) inside C++ threads I'm trying to use an MPI remote memory access (RMA) inside C++ threads. This seems to work fine if the number of writes is small, but fails if I attempt to communicate often. The sources below exhibit the following behavior: (i) if compiled with #define USE_THREADS false the program runs fine, irrespective of the value referred to via MY_BOUND; (ii) if compiled with #define USE_THREADS true the program runs fine if executed with only two processes (mpiexec -n 2 ...), i.e., using only one thread for communication, irrespective of the value referred to via MY_BOUND; (ii) if compiled with #define USE_THREADS true the program runs fine if the value referred to via MY_BOUND is low, e.g., 10 or 100, but the program crashes if the value referred to via MY_BOUND is large, e.g., 100000. The error I obtain in the third case for large values of MY_BOUND is: [...] *** Process received signal *** [...] Signal: Segmentation fault: 11 (11) [...] Signal code: Address not mapped (1) [...] Failing at address: 0x0 [...] *** End of error message *** -------------------------------------------------------------------------- mpiexec noticed that process rank 0 with PID 0 on node ... exited on signal 11 (Segmentation fault: 11). -------------------------------------------------------------------------- Attaching a debugger to the processes reveals the following: thread #4: tid = 0x5fa1e, 0x000000010e500de7 mca_osc_pt2pt.so`ompi_osc_pt2pt_sync_pscw_peer + 87, stop reason = EXC_BAD_ACCESS (code=1, address=0x0) * frame #0: 0x000000010e500de7 mca_osc_pt2pt.so`ompi_osc_pt2pt_sync_pscw_peer + 87 frame #1: 0x000000010e4fd2a2 mca_osc_pt2pt.so`osc_pt2pt_incoming_post + 50 frame #2: 0x000000010e4fabf1 mca_osc_pt2pt.so`ompi_osc_pt2pt_process_receive + 961 frame #3: 0x000000010e4f4957 mca_osc_pt2pt.so`component_progress + 279 frame #4: 0x00000001059f3de4 libopen-pal.20.dylib`opal_progress + 68 frame #5: 0x000000010e4fc9dd mca_osc_pt2pt.so`ompi_osc_pt2pt_complete + 765 frame #6: 0x0000000105649a00 libmpi.20.dylib`MPI_Win_complete + 160 And when compiling OpenMPI with --enable-debug I get: * thread #4: tid = 0x93d0d, 0x0000000111521b1e mca_osc_pt2pt.so`ompi_osc_pt2pt_sync_array_peer(rank=1, peers=0x0000000000000000, nranks=1, peer=0x0000000000000000) + 51 at osc_pt2pt_sync.c:61, stop reason = EXC_BAD_ACCESS (code=1, address=0x0) frame #0: 0x0000000111521b1e mca_osc_pt2pt.so`ompi_osc_pt2pt_sync_array_peer(rank=1, peers=0x0000000000000000, nranks=1, peer=0x0000000000000000) + 51 at osc_pt2pt_sync.c:61 58 int mid = nranks / 2; 59 60 /* base cases */ -> 61 if (0 == nranks || (1 == nranks && peers[0]->rank != rank)) { 62 if (peer) { 63 *peer = NULL; 64 } Probably something simple is wrong in my implementation, but I have a hard time finding it, likely due to my lack in understanding MPI, C++ and threading. Any thoughts, comments or feedback? Thanks and happy new year. My setup is GCC 4.9 with OpenMPI 2.0.1 (compiled with --enable-mpi-thread-multiple). #include <iostream> #include <vector> #include <thread> #include "mpi.h" #define MY_BOUND 100000 #define USE_THREADS true void FinalizeMPI(); void InitMPI(int, char**); void NoThreads(int, int); void ThreadFunction(int ThreadID, int Bound) { std::cout << "test " << ThreadID << std::endl; MPI_Group GroupAll, myGroup, destGroup; MPI_Comm myComm; MPI_Win myWin; MPI_Comm_group(MPI_COMM_WORLD, &GroupAll); int ranks[2]{0, ThreadID+1}; MPI_Group_incl(GroupAll, 2, ranks, &myGroup); MPI_Comm_create_group(MPI_COMM_WORLD, myGroup, 0, &myComm); MPI_Win_create(NULL, 0, 1, MPI_INFO_NULL, myComm, &myWin); int destrank = 1; MPI_Group_incl(myGroup, 1, &destrank, &destGroup); std::cout << "Objects created" << std::endl; std::vector<int> data(5, 1); for(int m=0;m<Bound;++m) { MPI_Win_start(destGroup, 0, myWin); MPI_Put(&data[0], 5, MPI_INT, 1, 0, 5, MPI_INT, myWin); MPI_Win_complete(myWin); } MPI_Group_free(&destGroup); MPI_Win_free(&myWin); MPI_Comm_free(&myComm); MPI_Group_free(&myGroup); MPI_Group_free(&GroupAll); } void WithThreads(int comm_size, int Bound) { std::vector<std::thread*> Threads(comm_size-1, NULL); for(int k=0;k<comm_size-1;++k) { Threads[k] = new std::thread(ThreadFunction, k, Bound); } for(int k=0;k<comm_size-1;++k) { Threads[k]->join(); } std::cout << "done" << std::endl; } int main(int argc, char** argv) { InitMPI(argc, argv); int rank,comm_size; MPI_Comm_rank(MPI_COMM_WORLD,&rank); MPI_Comm_size(MPI_COMM_WORLD,&comm_size); if(comm_size<2) { FinalizeMPI(); return 0; } int Bound = MY_BOUND; if(rank==0) { if(USE_THREADS) { WithThreads(comm_size, Bound); } else { NoThreads(comm_size, Bound); } } else { MPI_Group GroupAll; MPI_Comm_group(MPI_COMM_WORLD, &GroupAll); std::vector<int> tmp(5,0); MPI_Group myGroup, destinationGroup; MPI_Comm myComm; MPI_Win myWin; int ranks[2]{0,rank}; MPI_Group_incl(GroupAll, 2, ranks, &myGroup); MPI_Comm_create_group(MPI_COMM_WORLD, myGroup, 0, &myComm); MPI_Win_create(&tmp[0], 5*sizeof(int), sizeof(int), MPI_INFO_NULL, myComm, &myWin); int destrank = 0; MPI_Group_incl(myGroup, 1, &destrank, &destinationGroup); for(int m=0;m<Bound;++m) { MPI_Win_post(destinationGroup, 0, myWin); MPI_Win_wait(myWin); } std::cout << " Rank " << rank << ":"; for(auto& e : tmp) { std::cout << " " << e; } std::cout << std::endl; MPI_Win_free(&myWin); MPI_Comm_free(&myComm); MPI_Group_free(&myGroup); MPI_Group_free(&GroupAll); } FinalizeMPI(); return 0; } void FinalizeMPI() { int flag; MPI_Finalized(&flag); if(!flag) MPI_Finalize(); } void InitMPI(int argc, char** argv) { int flag; MPI_Initialized(&flag); if(!flag) { int provided_Support; MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided_Support); if(provided_Support!=MPI_THREAD_MULTIPLE) { exit(0); } } } void NoThreads(int comm_size, int Bound) { MPI_Group GroupAll; MPI_Comm_group(MPI_COMM_WORLD, &GroupAll); std::vector<MPI_Group> myGroups(comm_size-1); std::vector<MPI_Comm> myComms(comm_size-1); std::vector<MPI_Win> myWins(comm_size-1); std::vector<MPI_Group> destGroups(comm_size-1); for(int k=1;k<comm_size;++k) { int ranks[2]{0, k}; MPI_Group_incl(GroupAll, 2, ranks, &myGroups[k-1]); MPI_Comm_create_group(MPI_COMM_WORLD, myGroups[k-1], 0, &myComms[k-1]); MPI_Win_create(NULL, 0, 1, MPI_INFO_NULL, myComms[k-1], &myWins[k-1]); int destrank = 1; MPI_Group_incl(myGroups[k-1], 1, &destrank, &destGroups[k-1]); } std::vector<int> data(5, 1); for(int k=0;k<comm_size-1;++k) { for(int m=0;m<Bound;++m) { MPI_Win_start(destGroups[k], 0, myWins[k]); MPI_Put(&data[0], 5, MPI_INT, 1, 0, 5, MPI_INT, myWins[k]); MPI_Win_complete(myWins[k]); } } for(int k=0;k<comm_size-1;++k) { MPI_Win_free(&myWins[k]); MPI_Comm_free(&myComms[k]); MPI_Group_free(&myGroups[k]); } MPI_Group_free(&GroupAll); } UPDATE: During debugging I observed that the peers pointer doesn't seem to be NULL in the calling stack frame. Maybe another thread is updating the variable once the debugged thread crashed? Could that indicate an issue related to locking? * thread #4: tid = 0xa7935, 0x000000010fa67b1e mca_osc_pt2pt.so`ompi_osc_pt2pt_sync_array_peer(rank=1, peers=0x0000000000000000, nranks=1, peer=0x0000000000000000) + 51 at osc_pt2pt_sync.c:61, stop reason = EXC_BAD_ACCESS (code=1, address=0x0) frame #0: 0x000000010fa67b1e mca_osc_pt2pt.so`ompi_osc_pt2pt_sync_array_peer(rank=1, peers=0x0000000000000000, nranks=1, peer=0x0000000000000000) + 51 at osc_pt2pt_sync.c:61 58 int mid = nranks / 2; 59 60 /* base cases */ -> 61 if (0 == nranks || (1 == nranks && peers[0]->rank != rank)) { 62 if (peer) { 63 *peer = NULL; 64 } (lldb) frame select 1 frame #1: 0x000000010fa67c4c mca_osc_pt2pt.so`ompi_osc_pt2pt_sync_pscw_peer(module=0x00007fc0ff006a00, target=1, peer=0x0000000000000000) + 105 at osc_pt2pt_sync.c:92 89 return false; 90 } 91 -> 92 return ompi_osc_pt2pt_sync_array_peer (target, pt2pt_sync->peer_list.peers, pt2pt_sync->num_peers, peer); 93 } (lldb) p (pt2pt_sync->peer_list) (<anonymous union>) $1 = { peers = 0x00007fc0fb534cb0 peer = 0x00007fc0fb534cb0 } (lldb) p pt2pt_sync->peer_list.peers (ompi_osc_pt2pt_peer_t **) $2 = 0x00007fc0fb534cb0
{ "language": "en", "url": "https://stackoverflow.com/questions/41411602", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Differentiate between IE compatibility view If a user is on IE 7 and I read <% = Request.Browser.Version %> I get 7.0 if they have IE 9 and are on compatibility view, I get the same thing. Is there anything in Request.Browser that can differentiate between a real IE7 user and a user that is using IE8 or IE9 but in compatibility mode? A: It would be better to do this on the client side using JavaScript. You can use something like this: http://code.google.com/p/ie6-upgrade-warning/ You can tweak it to whatever you want. If your goal is simply to make sure the user is not in compatibility mode, then you can use either the meta tag or http header version of X-UA-COMPATIBLE: <html> <head> <meta http-equiv="X-UA-Compatible" content="IE=Edge" > </head> <body> <p>Content goes here.</p> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/12271049", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Deleting nodes from a binary search tree I understand the idea when deleting a node that has two subtrees: I "erase" the node's value and replace it with either its predecessor from the left subtree's value or its successor from the right subtree's value, and then delete that node. However, does it matter if I choose the successor from the right subtree or the predecessor from the left subtree? Or is either way valid as long as I still have a binary search tree after performing the deletion? A: Both ways to perform a delete operation are valid if the node has two children. Remember that when you get either the in-order predecessor node or the in-order successor node, you must call the delete operation on that node. A: It doesn't matter which one you choose to replace. In fact you may need both. Look at the following BST. 7 / \ 4 10 / \ / 1 5 8 \ 3 To delete 1, you need to replace 1 with right node 3. And to delete 10, you need to replace 10 with left node 8.
{ "language": "en", "url": "https://stackoverflow.com/questions/22601860", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why is Google App Engine Making --set-default a default parameter? So, in the past, when I've used Google App Engine, I've utilized their wonderful version system to create an integration, staging, and production environment. When we're ready to go live, we set the production environment to be the default, and it starts receiving traffic at the standard AppSpot URL (myapp.appspot.com), if it's not the default you have to manually go to the version itself (dev.myapp.appspot.com) for your testing. This is an awesome system for a pre-prod deployment with a full test. However, I just went to do an App Engine deployment today and got this warning: WARNING: Soon, deployments will set the deployed version to receive all traffic by default. To keep the current behavior (where new deployments do not receive any traffic), use the `--no-promote` flag or run the following command: $ gcloud config set app/promote_by_default false To adopt the new behavior early, use the `--promote` flag or run the following command: $ gcloud config set app/promote_by_default true Either passing one of the new flags or setting one of these properties will silence this message. So, apparently, very soon Google will make it so that for every deploy of any version, they will just automatically promote that to be the default and be accessible at the standard AppSpot URL. My question is, what's the benefit in this? I can't use this for A/B testing (since there's no B in the equation here). I can't use this as a pre-prod test, because it takes over my environment right away. Why would I want any version I push up to be the default? Am I missing something? Was I using versions wrong? I'm just genuinely curious.
{ "language": "en", "url": "https://stackoverflow.com/questions/34623346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ListView shows wrong layout I have a listview and in its adapter according to some situations I inflate layouts. for example consider this: if (state1){ resource = R.layout.layout_1 }else if (state2){ resource = R.layout.layout_2 } if (convertedView == null) { view = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)) .inflate(resource, parent,false); } return view; But sometimes ListView gets confused and it shows same layout for different states. I am sure there nothing wrong in code. But in ListView behavior. Any Suggestion? Thanks A: if (state1){ view = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)) .inflate(R.layout.layout_1, parent,false); }else if (state2){ view = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)) .inflate(R.layout.layout_2, parent,false); } return view; A: Well I found the Solution. The problem is that I check if ConverView parameter is NOT null then the adapter doesn't inflate new view and it uses the last one. If I delete this condition and make the adapter to always inflate a new layout the problem gets solved. Like this: public View getView(int position, View convertedView, ViewGroup parent) { View view; int resource = 0; if (state1){ resource = R.layout.layout_1; }else{ resource = R.layout.layout_2; } //if (convertedView == null) { //I should Delete this condition view = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)) .inflate(R.layout.layout_2, parent,false); //} return view;
{ "language": "en", "url": "https://stackoverflow.com/questions/25580158", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: highlight row when rowdetails is expanded Is there any way to get it highlight the row when rowdetails is expanded in ngx-datatable ? we can get highlight expanded row. but can't able to the clicked row A: findParentNode(parentName, childObj) { let tempNodeObj = childObj.parentNode; while(tempNodeObj.tagName != parentName) { tempNodeObj = tempNodeObj.parentNode; } return tempNodeObj; } this.findParentNode('DATATABLE-BODY-ROW',$event.target); this will help to find you the data table row element this.render.addClass(findParentNode,"row-expanded");
{ "language": "en", "url": "https://stackoverflow.com/questions/47869964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Please help identify the mistake in this clock divider code Clock divider from 50mhz (verilog code). I am trying to burn this on fpga but its not working properly. I am using model sim from mentor graphics. Please help identify my mistake. module clk_div( clk, rst, count); parameter count_width=27; parameter count_max=25000000; output [count_width-1:0] count; reg [count_width-1:0] count; input clk,rst; initial count=0; always@(posedge clk) if (rst) begin count<=0; end else if (count<count_max-1) begin count<=count+1; end else if (count==count_max) begin count <=~count; end else if (count>count_max) begin count<=0; end endmodule A: Three things. First, you need begin and end for your always block. Second, why are you doing count <= ~count when the count hits the max? Shouldn't you just set it back to 0? Third, you can't give the internal count register the same name as the count output. You will need to call one of them something else. Actually, why do you want to output count? If this is a clock divider, you want to output another clock, right? The following should work. module clk_div( clk, rst, outclk); parameter count_width=27; parameter count_max=25000000; reg [count_width-1:0] count; input clk,rst; output outclk; reg intern_clk; assign outclk = intern_clk; initial begin count=0; intern_clk=1'b0; end always @(posedge clk) begin if (rst) count <= 0; else if (count == count_max) begin count <= 0; intern_clk <= !intern_clk; end else count <= count + 1'b1; end endmodule But it seems like you are trying to divide the clock down to 1 Hz. That's quite a lot. I recommend you use a PLL instead of making your own clock divider. Since you mention a 50 MHz clock, I'm guessing you are using an Altera FPGA? If so, open up the MegaWizard plugin manager and create a PLL.
{ "language": "en", "url": "https://stackoverflow.com/questions/21889508", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to loop in powershell where loop value is combination of string and variable $A1= get-content -path "File path a1" $B1= get-content -path "File path b1" $A2= get-content -path "File path a2" $B2= get-content -path "File path B2" $A3= get-content -path "File path a3" $B3= get-content -path "File path B3" #I want to select A.i and B.i in each loop while ($i -le 5) { foreach ($line1 in "What to put here")) { $found = $false foreach ($line2 in "What to put here")) { if ($line1 -eq $line2) { write-host "Do something" } } I want to know what should I use in "what to put here" so that a) first loop select a1 and b1 files b) second loop selects a2 and b2 files and so on Hello, The below code is taking too long for large files to print whats different in each file. Can you suggest some optimization? $i = 1 while ($i -le 7) { $t1 = Get-Content -Path $(($oldpath) +($(Get-Variable "F$i").Value) +($Format)) $t2 = Get-Content -Path $(($NEWpath) +($(Get-Variable "F$i").Value) +($Format)) $list1 = new-object 'system.collections.generic.list[string]' $list2 = new-object 'system.collections.generic.list[string]' $listshared = new-object 'system.collections.generic.list[string]' $found = $false foreach ($line1 in $t1) { $found = $false foreach ($line2 in $t2) if (-not $found) { $list1.add($line1) } } foreach ($line2 in $t2) { $found = $false foreach ($line1 in $t1) if (-not $found) { $list2.add($line2) } } Write-Host "Things only in new txt file:" -foreground "magenta" $list1 Write-Host "Things only in old txt file:" -foreground "magenta" $list2 Remove-Variable "t1" Remove-Variable "t2" $i++ } A: You can use for example: Get-Variable -Name "A$i" |select Value but it seems like a bad practice to use a variable for each file... But you did not specify if you compare paths or files. If files, combine with Get-Content. UPDATE: $i=1 while ($i -le 5) { $file1=Get-Content -Path $($(Get-Variable "A$i").Value) $file2=Get-Content -Path $($(Get-Variable "B$i").Value) foreach ($line1 in $file1) { $found = $false foreach ($line2 in $file2) { if ($line1 -eq $line2) { write-host "Do something" } } } Remove-Variable "file1" Remove-Variable "file2" $i++ } This is the version without Get-Content at every variable
{ "language": "en", "url": "https://stackoverflow.com/questions/26302336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why file_exists() function doesn't work correctly? Here is my code: <?php $filename = $var.'p_folder/'.sub_replace('?','',$page).'/images/default.png'; ?> <img src = "<?php echo $filename; ?>" title= "<?php echo file_exists($filename) ? 'exists' : 'not exist'; ?>" > My code shows the image as well, but file_exists() returns false (I mean "not exist" prints).. Why? Actually that's pretty much odd for me .. because I can see the image on the web, so it means the image exists on the directory, but why file_exists() cannot find it? A: file_exists() needs to use a file path on the hard drive, not a URL. So you should have something more like: $thumb_name = $_SERVER['DOCUMENT_ROOT'] . 'images/abcd.jpg'; if(file_exists($thumb_name)) { //your code } A: check your image path and then sever name & document root
{ "language": "en", "url": "https://stackoverflow.com/questions/40582619", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: No newline before EOF? I was solving one of the exercises from K&R but I'm having a minor problem. The exercise is to print a histogram of the length of words in its input. Here's my code: #include <stdio.h> #define IN 1 #define OUT 0 int main(){ //Histogram of the length of words int c, state, len, i; state = OUT; printf("Histogram\n"); while ((c = getchar()) != EOF){ if (c != ' ' && c != '\n' && c != '\t' && c != '\r'){ state = IN; len++; } else if (state == IN){ for (i = 0; i < len; i++){ putchar('['); putchar(']'); } len = 0; putchar('\n'); state = OUT; } } return 0; } The text file I used was: Hello World! This is a text The output of the program was: Histogram [][][][][] [][][][][][] [][][][] [][] [] As it can be seen, the program terminated before printing out the histogram for the last word 'text'. Is this because the text editor on Windows does not automatically put '\r\n' at the end? If so, how can I fix this problem? Thank you. A: Your loop end when getchar() return EOF so you never go in the else if at the end. Example: #include <stdio.h> #include <stdbool.h> int main(void) { printf("Histogram\n"); size_t len = 0; bool running = true; while (running) { switch (getchar()) { case EOF: running = false; case ' ': case '\n': case '\t': case '\r': if (len != 0) { printf("\n"); len = 0; } break; default: printf("[]"); len++; } } } A: Move the tests around: while (true) { const int c = getchar(); if (c != ' ' && c != '\n' && c != '\t' && c != '\r' && c != EOF) { state = IN; len++; } else if (state == IN) { // ... } if (c == EOF) break; }
{ "language": "en", "url": "https://stackoverflow.com/questions/42428924", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to push an image to a docker registry using the docker Registry API v2 I'm a writing a docker registry API wrapper to pull images from one private registry and push them to another. Based on the documentation first I need to pull the manifest and the layers for an image:tag. Following Puling An Image I've successfully downloaded all the layers for a particular image:tag and the manifest. Following Pushing An Image I've followed the steps: * *POST /v2/<name>/blobs/uploads/ (to get the UUID i.e. Location header) *HEAD /v2/<name>/blobs/<digest> (check to see if it already exists in the registry) *PUT /v2/<name>/blobs/uploads/<uuid>?digest=<digest> (Monolithic Upload ) What's not clear to me are the following: * *Is the UUID unique to each individual layer I push or is that reused for all layers (e.g. Do I need to run a new POST for each layer an get a new UUID before I attempt to upload it?). *The Completed Upload section indicates For an upload to be considered complete, the client must submit a PUT request on the upload endpoint with a digest parameter However, as mentioned I'm using the Monolithic Upload which uses a PUT and would be the same request as what shows in the Completed Upload section. So by doing a monolithic upload am I also completing the upload at the same time? Problem * *When I go through all the steps above I receive the BLOB_UNKNOWN error when uploading a digest, e.g. { "errors:" [{ "code": "BLOB_UNKNOWN", "message": "blob unknown to registry", "detail": { "digest": } }, ... ] } According to the docs this error is produced when pushing a manifest and one of the layers in the manifest are unknown: If one or more layers are unknown to the registry, BLOB_UNKNOWN errors are returned. The detail field of the error response will have a digest field identifying the missing blob. An error is returned for each unknown blob. The response format is as follows: What confuses me about this is * *I'm pushing a digest (aka a layer) not the manifest so why is this error returning? *I would expect the blob to be unknown because I'm pushing a new image into the registry For now I'm going to use the docker client, but I haven't found any wrapper examples on-line to see how this is pulled off. Presumably I'm missing some logic or misunderstanding the docs, but I'm not sure where I'm going wrong? A: Wow, it's nice to know I'm not the only one lost in the void with the V2 API ... I'm implementing a similar library and ran across the same issue. From my understanding of the documentation there are two Monolithic uploads: The single exchange POST variant (mentioned at the bottom of the docs), and the two exchange POST + PUT variant (mentioned at the top of the docs). I wasn't able to get the POST-only method working. In my case, I was using it to upload the image manifest after the layer blobs, and before the registry manifest. While the POST appears successful and returns 202, the debug logging on the registry shows that it's never replicated from the staging location into the data store (as happens after chunked uploads). The subsequent attempt to upload the manifest then fails with 400, and debug logging "blob unknown to registry". I was, however, able to work around this issue by using the POST+PUT method. The key sections in the docs for me were: Though the URI format (/v2//blobs/uploads/) for the Location header is specified, clients should treat it as an opaque url and should never try to assemble it. and A monolithic upload is simply a chunked upload with a single chunk ... Following those two instructions I created a new Location header (and UUID) using POST, appended the digest value, and completed the upload by PUTting the blob to the modified location. Side note: Looking at the registry debug logs, the docker CLI checks the existence of the blobs before starting a new upload (and after completing the uploads too -- assuming as a double check on the status code). Update: Found myself working on this again, and figured I'd update you on what I found ... The registry only supports handling the response body during PATCH and PUT operations; the copyFullPayload helper is not invoked for POST. Additionally, all uploads appear to be treated as monolithic uploads (in the sense that they stream the blob from a single request body) as handling of the Content-Range header does not appear to be implemented. Side Note: I conducted this analysis under the scope of increasing test coverage of the V2 API during an overhaul; here is a working example of the POST+PUT method. In general I've found the official documentation to be out-of-sync with the current implementation with regards to headers and status codes. I have tested this against a local V2 registry and DockerHub, but not against other registries such as DTR, quay, or MCR.
{ "language": "en", "url": "https://stackoverflow.com/questions/54578236", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Getting error when high charts library included in java project, maven throwing errors After including the high charts custom js in library or full highchart js code and ran maven, but it's throwing the following errors: [ERROR] highcharts-custom.src.js [63202:44]: missing name after . operator [ERROR]highcharts-custom.src.js:line 63202:column 44:missing name after . operator [ERROR]highcharts-custom.src.js [67212:27]: syntax error [ERROR]highcharts-custom.src.js:line 67212:column 27:syntax error [ERROR]highcharts-custom.src.js:line 67213:column 35:syntax error [ERROR]highcharts-custom.src.js:line 67214:column 22:syntax error I tried with both Highcharts custom build js and full highchart js code in to the project and getting above Maven build errros from both highchart versions downloaded from high chart website. I am using follwing libaries, Highchart-7.1.2 , jquery-3.3.1, Apache Maven 3.5.2, apache-tomcat-8.5.39, jdk1.8.0_212, jre1.8.0_212, any one please help me out. I tried to include both Highcharts custom build js and full code both getting same above errors. A: I found the solution to my own issue, my project has extra maven plugin called YUI Compressor, it is trying to compress them and causing issue. by adding code to excluded the higchart files in pom.xml and directly added minified files in to project solved the issues.
{ "language": "en", "url": "https://stackoverflow.com/questions/56589075", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Angular application showing blank screen I am very new to angular development. I got this angular app code base from my team and attempting to run it locally. I installed node js, npm amd angular cli. I got lot of issues while trying to execute ng serve. But I finally got ride of those. Now the problem is the app compiles successfully using ng serve. But when I navigate to the url(http://localhost:4200) I am seeing a blank screen. I am supposed to get a login page. To troubleshoot, I hit F12 in chrome and able to see the console error shown below: Please find the software versions below: Any help to enable me see the login page can definitely help A: Angular application's bootstraping starts from main.ts file. Open main.ts file and check which module's name is used in bootStrapModule. Once done please check the parent module for any errors in the import statements.
{ "language": "en", "url": "https://stackoverflow.com/questions/62064490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Make bootstrap modal utilize seperate form/sql table I have a form that alters a sql table called "invoices". I want to popup a bootstrap modal that will alter a sql table called "customers". Right now, the only thing that is saved properly is the customer name... am I missing something? Here is the code I have so far... main page : <!-- Modal Add Customer --> <div class="modal fade" id="addNewCustomer" tabindex="-1" role="dialog" aria-labelledby="addNewCustomerLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel">Add New Customer</h4> </div> <div class="modal-body"> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" id="add_customer_form" method="post" class="form-horizontal myaccount" role="form"> <div class="form-group col-lg-7"> <label for="customer_Name_modal">Customer Name (Last Name, First Name)</label> <input type="text" class="form-control" id="customer_Name_modal" name="customer_Name_modal" placeholder="Last Name, First Name"> <span class="help-block"></span> </div> <div class="form-group col-lg-7"> <label for="customer_Phone_modal">Phone Number (555-555-5555)</label> <input type="text" class="form-control" id="customer_Phone_modal" name="customer_Phone_modal" placeholder="555-555-5555"> <span class="help-block"></span> </div> <div class="form-group col-lg-7"> <label for="customer_Email_modal">Email ([email protected])</label> <input type="text" class="form-control" id="customer_Email_modal" name="customer_Email_modal" placeholder="[email protected]"> <span class="help-block"></span> </div> <div class="form-group col-lg-7"> <label for="customer_Address1_modal">Address Line 1 </label> <input type="text" class="form-control" id="customer_Address1_modal" name="customer_Address1_modal" placeholder=""> <span class="help-block"></span> </div> <div class="form-group col-lg-7"> <label for="customer_Address2_modal">Address Line 2 </label> <input type="text" class="form-control" id="customer_Address2_modal" name="customer_Address2_modal" placeholder=""> <span class="help-block"></span> </div> <input type="hidden" id="current_element_id"> </form> </div> <div class="modal-footer"> <button type="button" id="add_new_customer_btn" class="btn btn-primary" data-loading-text="Saving Customer...">Save changes</button> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> Form Save Code : var save_new_customer = function(){ $('#add_new_customer_btn').button('loading'); data = { customerName : $('#customer_Name_modal').val(), customerPhone : $('#customer_Phone_modal').val(), customerEmail : $('#customer_Email_modal').val(), customerAddress1 : $('#customer_Address1_modal').val(), customerAddress2 : $('#customer_Address2_modal').val(), } $.ajax({ url: "ajax.php", dataType: "json", method: 'post', data: { data : data, type: 'saveNewCustomer' }, success: function(result){ if( (typeof result.success !== "undefined") && result.success ){ $("html, body").animate({ scrollTop: 0 }, "slow"); $('#add_new_customer_btn').button('reset'); $('#addNewCustomer').modal('show'); element_id = $('#current_element_id').val(); $('#customerName_'+element_id).val($('#customer_Name_modal').val()); $('#phone_'+element_id).val( $('#customer_Email_modal').val() ); $('#email_'+element_id).val($('#customer_Phone_modal').val()); $('#addressLine1_'+element_id).val($('#customer_Address1_modal').val()); $('#addressLine2_'+element_id).val($('#customer_Address2_modal').val()); $('#add_customer_form')[0].reset(); $('#add_customer_form').find("div.form-group").removeClass('has-success'); $('#message_h1').show(); message('success', CUSTOMER_ADD_SUCCESS); }else{ message('fail', CUSTOMER_ADD_FAIL); } } }); } Sql Code : if(isset($_POST['type']) && $_POST['type'] == 'saveNewCustomer' ){ $res = array(); $res['success'] = false; if(!isset($_POST['data']) || empty($_POST['data'])){ echo json_encode($res);exit; } $data = $_POST['data']; $customerName = mysqli_real_escape_string( $db->con, trim( $data['customerName'] ) ); $customerPhone = mysqli_real_escape_string( $db->con, trim( $data['phone'] ) ); $customerEmail = mysqli_real_escape_string( $db->con, trim( $data['email'] ) ); $customerAddress1 = mysqli_real_escape_string( $db->con, trim( $data['addressLine1'] ) ); $customerAddress2 = mysqli_real_escape_string( $db->con, trim( $data['addressLine2'] ) ); $uuid = uniqid(); $result['operation'] = 'insert'; $query = "INSERT INTO customers (id, customerName, phone, email, addressLine1, addressLine2, uuid) VALUES (NULL, '$customerName', '$customerPhone', '$customerEmail', '$customerAddress1', '$customerAddress2', '$uuid');"; if(mysqli_query($db->con, $query)){ mysqli_close($db->con); $res['success'] = true; } echo json_encode($res);exit; } A: You're using the wrong key in PHP You're calling these keys: $customerName = mysqli_real_escape_string( $db->con, trim( $data['customerName'] ) ); $customerPhone = mysqli_real_escape_string( $db->con, trim( $data['phone'] ) ); $customerEmail = mysqli_real_escape_string( $db->con, trim( $data['email'] ) ); $customerAddress1 = mysqli_real_escape_string( $db->con, trim( $data['addressLine1'] ) ); $customerAddress2 = mysqli_real_escape_string( $db->con, trim( $data['addressLine2'] ) ); but you should be calling: $customerName = mysqli_real_escape_string( $db->con, trim( $data['customerName'] ) ); $customerPhone = mysqli_real_escape_string( $db->con, trim( $data['customerPhone'] ) ); $customerEmail = mysqli_real_escape_string( $db->con, trim( $data['customerEmail'] ) ); $customerAddress1 = mysqli_real_escape_string( $db->con, trim( $data['customerAddress1'] ) ); $customerAddress2 = mysqli_real_escape_string( $db->con, trim( $data['customerAddress2'] ) ); To fix this just copy and paste (replace) the variable assignment in the SQL code.
{ "language": "en", "url": "https://stackoverflow.com/questions/34816148", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to call async function from sync funcion and get result, while a loop is already running I have a asyncio running loop, and from the coroutine I'm calling a sync function, is there any way we can call and get result from an async function in a sync function tried below code, it is not working want to print output of hel() in i() without changing i() to async function is it possible, if yes how? import asyncio async def hel(): return 4 def i(): loop = asyncio.get_running_loop() x = asyncio.run_coroutine_threadsafe(hel(), loop) ## need to change y = x.result() ## this lines print(y) async def h(): i() asyncio.run(h()) A: This is one of the most commonly asked type of question here. The tools to do this are in the standard library and require only a few lines of setup code. However, the result is not 100% robust and needs to be used with care. This is probably why it's not already a high-level function. The basic problem with running an async function from a sync function is that async functions contain await expressions. Await expressions pause the execution of the current task and allow the event loop to run other tasks. Therefore async functions (coroutines) have special properties that allow them to yield control and resume again where they left off. Sync functions cannot do this. So when your sync function calls an async function and that function encounters an await expression, what is supposed to happen? The sync function has no ability to yield and resume. A simple solution is to run the async function in another thread, with its own event loop. The calling thread blocks until the result is available. The async function behaves like a normal function, returning a value. The downside is that the async function now runs in another thread, which can cause all the well-known problems that come with threaded programming. For many cases this may not be an issue. This can be set up as follows. This is a complete script that can be imported anywhere in an application. The test code that runs in the if __name__ == "__main__" block is almost the same as the code in the original question. The thread is lazily initialized so it doesn't get created until it's used. It's a daemon thread so it will not keep your program from exiting. The solution doesn't care if there is a running event loop in the main thread. import asyncio import threading _loop = asyncio.new_event_loop() _thr = threading.Thread(target=_loop.run_forever, name="Async Runner", daemon=True) # This will block the calling thread until the coroutine is finished. # Any exception that occurs in the coroutine is raised in the caller def run_async(coro): # coro is a couroutine, see example if not _thr.is_alive(): _thr.start() future = asyncio.run_coroutine_threadsafe(coro, _loop) return future.result() if __name__ == "__main__": async def hel(): await asyncio.sleep(0.1) print("Running in thread", threading.current_thread()) return 4 def i(): y = run_async(hel()) print("Answer", y, threading.current_thread()) async def h(): i() asyncio.run(h()) Output: Running in thread <Thread(Async Runner, started daemon 28816)> Answer 4 <_MainThread(MainThread, started 22100)> A: In order to call an async function from a sync method, you need to use asyncio.run, however this should be the single entry point of an async program so asyncio makes sure that you don't do this more than once per program, so you can't do that. That being said, this project https://github.com/erdewit/nest_asyncio patches the asyncio event loop to do that, so after using it you should be able to just call asyncio.run in your sync function.
{ "language": "en", "url": "https://stackoverflow.com/questions/74703727", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a better way of receiving data from a websocket server than ClientWebSocket in a client console application? I am trying my hand with Websockets to get data out from a particular URI. From what I understand is that there are no Web API endpoints, just a single URI with various forms of JSON data coming through from the server side. I was wondering if there is a simpler way of getting data from that endpoint beyond what appears to be raw websocket connections in my console application. The data collected will be logged for processing later. clientWebSocket = new ClientWebSocket(); await clientWebSocket.ConnectAsync(new Uri(serverSetting.KSimNetAPIServerUrl), stoppingToken); while (!stoppingToken.IsCancellationRequested) { var buffer = new ArraySegment<byte>(new byte[2048]); WebSocketReceiveResult result; String json; using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { do { result = await clientWebSocket.ReceiveAsync(buffer, stoppingToken); ms.Write(buffer.Array, buffer.Offset, result.Count); } while (!result.EndOfMessage); if (result.MessageType == WebSocketMessageType.Close) break; ms.Seek(0, System.IO.SeekOrigin.Begin); json = Encoding.UTF8.GetString(ms.ToArray()); _logger.LogInformation("Received: {0}", json); } // TODO: Processing of the JSON data }
{ "language": "en", "url": "https://stackoverflow.com/questions/67692348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JavaFX Right Coordinate of a CustomMenuItem I have a Class that extends the CustomMenuItem. This MenuItems are added to a ContextMenu. Now i need to get the X-Coordinates from the right side of the CustomMenuItem. The Problem is, that I have no idea how I can get the Coordinates. The CustMenuItem has no function for getting the Coordinates like getX() or getY(). So how can I solve this problem? This thing I would like to get: Here we can see a Sample for a Context Menu (red lines). In the Context Menu are a lot of different CustomMenuItems implemented. Now I would like to get the right top corner Coordinate of the CustomMenuItem. Thank you for your very nice help. A: Before dealing with menu items, let's start saying that a ContextMenu is a popup window, so it has Windowproperties. You can ask for (x,y) left, top origin, and for (w,h). But you have to take into account the effects, since by default it includes a dropshadow. And when it does, there's an extra space added of 24x24 pixels to the right and bottom. .context-menu { -fx-effect: dropshadow( gaussian , rgba(0,0,0,0.2) , 12, 0.0 , 0 , 8 ); } Since this default dropshadow has a radius of 12px, and Y-offset to the bottom of 8px, the right and bottom coordinates of the context menu, including the 24x24 area, are given by: X=t.getX()+cm.getWidth()-12-24; Y=t.getY()+cm.getHeight()-(12-8)-24; where t could be a MouseEvent relative to the scene, and values are hardcoded for simplicity. Let's see this over an example. Since you don't say how your custom menu items are implemented, I'll just create a simple Menu Item with graphic and text: private final Label labX = new Label("X: "); private final Label labY = new Label("Y: "); @Override public void start(Stage primaryStage) { final ContextMenu cm = new ContextMenu(); MenuItem cmItem1 = createMenuItem("mNext", "Next Long Option",t->System.out.println("next")); MenuItem cmItem2 = createMenuItem("mBack", "Go Back", t->System.out.println("back")); SeparatorMenuItem sm = new SeparatorMenuItem(); cm.getItems().addAll(cmItem1,cmItem2); VBox root = new VBox(10,labX,labY); Scene scene = new Scene(root, 300, 250); scene.setOnMouseClicked(t->{ if(t.getButton()==MouseButton.SECONDARY || t.isControlDown()){ // t.getX,Y->scene based coordinates cm.show(scene.getWindow(),t.getX()+scene.getWindow().getX()+scene.getX(), t.getY()+scene.getWindow().getY()+scene.getY()); labX.setText("Right X: "+(t.getX()+cm.getWidth()-12-24)); labY.setText("Bottom Y: "+(t.getY()+cm.getHeight()-4-24)); } }); scene.getStylesheets().add(getClass().getResource("root.css").toExternalForm()); primaryStage.setScene(scene); primaryStage.show(); primaryStage.setTitle("Scene: "+scene.getWidth()+"x"+scene.getHeight()); } private MenuItem createMenuItem(String symbol, String text, EventHandler<ActionEvent> t){ MenuItem m=new MenuItem(text); StackPane g=new StackPane(); g.setPrefSize(24, 24); g.setId(symbol); m.setGraphic(g); m.setOnAction(t); return m; } If you remove the effect: .context-menu { -fx-effect: null; } then these coordinates are: X=t.getX()+cm.getWidth(); Y=t.getY()+cm.getHeight(); Now that we have the window, let's go into the items. MenuItem skin is derived from a (private) ContextMenuContent.MenuItemContainer class, which is a Region where the graphic and text are layed out. When the context menu is built, all the items are wrapped in a VBox, and all are equally resized, as you can see if you set the border for the item: .menu-item { -fx-border-color: black; -fx-border-width: 1; } This is how it looks like: So the X coordinates of every item on the custom context menu are the same X from their parent (see above, with or without effect), minus 1 pixel of padding (by default). Note that you could also go via private methods to get dimensions for the items: ContextMenuContent cmc= (ContextMenuContent)cm.getSkin().getNode(); System.out.println("cmc: "+cmc.getItemsContainer().getBoundsInParent()); Though this is not recommended since private API can change in the future. EDIT By request, this is the same code removing lambdas and css. private final Label labX = new Label("X: "); private final Label labY = new Label("Y: "); @Override public void start(Stage primaryStage) { final ContextMenu cm = new ContextMenu(); MenuItem cmItem1 = createMenuItem("mNext", "Next Long Option",action); MenuItem cmItem2 = createMenuItem("mBack", "Go Back", action); SeparatorMenuItem sm = new SeparatorMenuItem(); cm.getItems().addAll(cmItem1,cmItem2); VBox root = new VBox(10,labX,labY); Scene scene = new Scene(root, 300, 250); scene.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent t) { if(t.getButton()==MouseButton.SECONDARY || t.isControlDown()){ // t.getX,Y->scene based coordinates cm.show(scene.getWindow(),t.getX()+scene.getWindow().getX()+scene.getX(), t.getY()+scene.getWindow().getY()+scene.getY()); labX.setText("Right X: "+(t.getX()+cm.getWidth()-12-24)); labY.setText("Bottom Y: "+(t.getY()+cm.getHeight()-4-24)); } } }); primaryStage.setScene(scene); primaryStage.show(); primaryStage.setTitle("Scene: "+scene.getWidth()+"x"+scene.getHeight()); } private MenuItem createMenuItem(String symbol, String text, EventHandler<ActionEvent> t){ MenuItem m=new MenuItem(text); StackPane g=new StackPane(); g.setPrefSize(24, 24); g.setId(symbol); SVGPath svg = new SVGPath(); svg.setContent("M0,5H2L4,8L8,0H10L5,10H3Z"); m.setGraphic(svg); m.setOnAction(t); return m; } private final EventHandler<ActionEvent> action = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { System.out.println("action"); } };
{ "language": "en", "url": "https://stackoverflow.com/questions/26798873", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pygame: why am I receiving the error "video system not initialized" when I used init()? code: from signal import pause import sys import pygame def run_game(): # Initialize game and create a screen object. pygame.init() screen = pygame.display.set_mode((1200, 800)) pygame.display.set_caption("Alien Invasion") # Start the main loop for the game. while True: # Watch for keyboard and mouse events. for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() # Make the most recently drawn screen visible. run_game() pygame.display.flip() I'm still learning python, and the book gave me this code, so I assume it was some kind of update from Python or pygame or both. Also, even when I remove pygame.display.flip(), it still gives the same error
{ "language": "en", "url": "https://stackoverflow.com/questions/71135747", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hover on * haven't good size I'm using bootstrap and I have this code : <ul class="dropdown-menu scrollable-menu-brands" style="width:210px;"> {foreach $arr as $id => $r} <li><a class="dropdown-item" style="font-size:15px;font-family: PT Sans Narrow,PTSansNarrow;" href="#">{$r}</a></li> {/foreach} </ul> I have this css: .scrollable-menu-brands { height: auto; max-height: 320px; overflow-x: hidden; } .scrollable-menu-brands::-webkit-scrollbar { -webkit-appearance: none; } .scrollable-menu-brands::-webkit-scrollbar-thumb { border-radius: 8px; border: 2px solid white; /* should match background, can't be transparent */ background-color: rgba(0, 0, 0, .5); } .scrollable-menu-brands li a { height: 10px; padding-top: 0px; } .dropdown-menu > li > a:hover{ background-color: red; ;} But when hover an element of the list, background color is only for top of my element.. Look this screen: Someone understand please? I don't understand why height of over is small like this... If I increase height, it doesn't work. A: @MathAng, It looks like the height of your A and LI aren't matching the same height, the default height of the LI tag is 26 pixels in height. But at your CSS you're saying that it must be 10 pixels for the A tag. What I prefer is or use: .scrollable-menu-brands li a { padding-top: 0px; } instead of: .scrollable-menu-brands li a { height: 10px; padding-top: 0px; } Or add height: 10px; to your LI tag, like so: .scrollable-menu-brands li { height: 10px; } Hopefully this does the trick for you!
{ "language": "en", "url": "https://stackoverflow.com/questions/63625343", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Filter out friends that have already approved the app from app invite dialog In old Facebook sdk(using FBWebDialogs) I was able to set filters and exclude friends with approved app to be listed for invites. Now(with FBSDKAppInviteDialog) I can't find the way to enable such filters. Is there any way to get old functionality back?
{ "language": "en", "url": "https://stackoverflow.com/questions/29935691", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to change Scene / Camera starting position in AndEngine GLES1.0 I am relatively new to AndEngine and stuck in one problem. I made a really sample demo game, in which the character can move left and right in a game made of Tiled. By default, when the game starts, the scene/camera and character is placed at the left side of the screen. The camera moves from left edge of the screen to right side in Landscape mode. Below is my working code: private BoundCamera mCamera; @Override public Engine onLoadEngine() { this.mCamera = new BoundCamera(-100, -100, CAMERA_WIDTH, CAMERA_HEIGHT){ @Override public void onApplySceneMatrix(GL10 pGL) { GLHelper.setProjectionIdentityMatrix(pGL); GLU.gluOrtho2D(pGL, (int)this.getMinX(), (int)this.getMaxX(), (int)this.getMaxY(), (int)this.getMinY()); } }; final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), mCamera); engineOptions.getTouchOptions().setRunOnUpdateThread(true); engineOptions.setNeedsMusic(true).setNeedsSound(true); // It is necessary in a lot of applications to define the following // wake lock options in order to disable the device's display // from turning off during gameplay due to inactivity engineOptions.setWakeLockOptions(WakeLockOptions.SCREEN_ON); final Engine engine = new Engine(engineOptions); try { if (MultiTouch.isSupported(this)) { engine.setTouchController(new MultiTouchController()); if (MultiTouch.isSupportedDistinct(this)) { } else { Toast.makeText(this, "(MultiTouch detected, but your device might have problems to distinguish between separate fingers.)", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(this, "Sorry your device does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)", Toast.LENGTH_LONG).show(); } } catch (final MultiTouchException e) { Toast.makeText(this, "Sorry your Android Version does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)", Toast.LENGTH_LONG).show(); } return engine; } I tried apply different values in new BoundCamera() constructor. But nothing works. Please guide me to solve this. I want to start the camera and scene from the right edge of the screen in Landscape mode. A: In need to make your camera to chase your player. You can do this by: camera.setChaseEntity(player); Just have a look at AndEngine Examples. It has an example which exactly serves your need. Follow the link below to download the code as well: http://code.google.com/p/andengineexamples/ •TMXTiledMapExample
{ "language": "en", "url": "https://stackoverflow.com/questions/18266681", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Query to find out the duplicate rows among two DataTable? I have an excel sheet with columns: Id,Data I have a table in sql server database: Id,Data I have derived rows of both in two different DataTables, now I want to detect rows which are common in both excel and database table and store the duplicates in another DataTable. Something like this: OleDbCommand command1 = new OleDbCommand("select * from [Sheet1$]",connection); DataTable dt2 = new DataTable(); try { OleDbDataAdapter da2 = new OleDbDataAdapter(command1); da2.Fill(dt2); } catch { } A: try out using linq way like this var matched = from table1 in dt1.AsEnumerable() join table2 in dt2.AsEnumerable() on table1.Field<int>("ID") equals table2.Field<int>("ID") where table1.Field<string>("Data") == table2.Field<string>("Data") select table1; A: If you want to find duplicates, you can try this var result = table1.AsEnumerable().Intersect(table2.AsEnumerable()).Select(x => x); If you want to eliminate duplicates from union, you can try this var result = table1.AsEnumerable().Union(table2.AsEnumerable()).Select(x => x);
{ "language": "en", "url": "https://stackoverflow.com/questions/13062720", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: run a function in another function in N times I have ask this kind of question before, but it seems my previous question is a bit misleading due to my poor English. I'm asking again to make clear. I am really confused about it. Thanks in advance. Suppose I have a function A for generating the state of a cell in a certain rule, and I have another function which generates the state of a cell for N times, and each time the rule is as same as the fist function. And, yeah, don't know how to do it... def 1st_funtion(a_matrixA) #apply some rule on a_matrixA and return a new matrix(next state of the cell) return new_matrix def 2nd_funtion(a_matrixB,repeat_times=n) #how to import the 1st_funtion and run for n times and return the final_matrix? #I know if n=1, just make final_matrix=1st_funtion(a_matrixB) return final_matrix A: def 1st_funtion(a_matrixA) #apply some rule on a_matrixA and return a new matrix(next state of the cell) return new_matrix def 2nd_funtion(a_matrixB,repeat_times) for i in range(repeat_times): a_matrixB = 1st_funtion(a_matrixB) return a_matrixB
{ "language": "en", "url": "https://stackoverflow.com/questions/365384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Making plots of intermediate results from sci.py least_squares In sci.py least_squares, I want to use Levenberg-Marquardt method to compute the minimum of the Rosenbrock function, and I see that it gives me the correct minimum and takes 108 iterations. What I would like to know is whether it is possible to get the intermediate iterations, and plot them. How should I do this? I tried to read the sci.py page, but I didn't really get an anser there
{ "language": "en", "url": "https://stackoverflow.com/questions/74403658", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I am trying to build a simple python program of speech recognition(speech to text) when I try to run this program its throwing an error import speech_recognition as sr r = sr.Recognizer() with sr.Microphone() as source: audio = r.listen(source) try: print("JARVIS : "+r.recognize_google(audio)) except Exception: print("Something went Wrong !!!!!!") error = ALSA lib pulse.c:243:(pulse_connect) PulseAudio: Unable to connect: Connection refused ALSA lib pcm_usb_stream.c:486:(_snd_pcm_usb_stream_open) Invalid type for card ALSA lib pcm_usb_stream.c:486:(_snd_pcm_usb_stream_open) Invalid type for card
{ "language": "en", "url": "https://stackoverflow.com/questions/58968595", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Performance of two meteor apps on one database I've created simple todo app from meteor.com website. Let's call it 'project A'. Then duplicated directory with project. Let's call it 'project B'. I've started project A normally. After that I've started project B on port 3456 and connect to project's A database through env variables. The problem is: * *when I add todo in project B, changes appears immidietly in project A. *When I add todo in project A, in project B changes appears after few seconds. Question is: Why? There are two equally the same projects connected to the same database... A: Because oplog tailing is disabled. When there's no oplog tailing, Meteor uses "poll-and-diff" strategy that execute mongodb queries every 10 seconds and then do a diff to see if some data changed. To solve it, you can activate oplog tailing this way: https://github.com/meteor/meteor/wiki/Oplog-Observe-Driver#oplogobservedriver-in-production
{ "language": "en", "url": "https://stackoverflow.com/questions/32828287", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting video file type formats from UTI's I'm building a video editing application that uses AVFoundation. When the user goes to import their video (via an NSOpenPanel file browser), I only want to allow them to select acceptable video formats that AVFoundation supports. You can retrieve those accepted formats by calling audioVisualTypes() on AVURLAsset. However, these formats include a lot of gibberish / stuff I don't need, ex: "public.mpeg", "dyn.ah62d46dzqm0gw23sqf40k4pts3y1g7pbru00g55ssvw067b4gq81q4peqz1w88brrz2de7a", "public.dv-movie", "public.pls-playlist", "dyn.ah62d46dzqm0gw23sqf40k4pts3y1g7pbru00g55ssvw067b4gq80c6durvy0g2pyrf106p50r3wc62pusb0gnpxrsbw0s7pwru", "public.aac-audio", Does anyone have an idea of how to parse these into a simple array of file extensions? Thanks A: You want to use the function UTTypeCopyPreferredTagWithClass. Try this in a playground import MobileCoreServices import AVFoundation let avTypes = AVURLAsset.audiovisualTypes() let anAVType = avTypes[0] if let ext = UTTypeCopyPreferredTagWithClass(anAVType as CFString,kUTTagClassFilenameExtension)?.takeRetainedValue() { print("The AVType \(anAVType) has extension '\(ext)'") } else { print("Can't find the extension for the AVType '\(anAVType)") } print("\n") let avExtensions = avTypes.map({UTTypeCopyPreferredTagWithClass($0 as CFString,kUTTagClassFilenameExtension)?.takeRetainedValue() as String? ?? ""}) print("All extensions = \(avExtensions)\n") avExtensions = avExtensions.filter { $0.isEmpty == false } print("All extensions filtered = \(avExtensions)\n") print("First extension = '\(avExtensions[0])'") print("Second extension = '\(avExtensions[1])'") print("Third extension = '\(avExtensions[2])'") Result: The AVType AVFileType(_rawValue: public.pls-playlist) has extension 'pls' All extensions = ["pls", "", "aifc", "m4r", "", "", "wav", "", "", "3gp", "3g2", "", "", "", "flac", "avi", "m2a", "", "aa", "", "aac", "mpa", "", "", "", "", "", "m3u", "mov", "aiff", "ttml", "", "m4v", "", "", "amr", "caf", "m4a", "mp4", "mp1", "", "m1a", "mp4", "mp2", "mp3", "itt", "au", "eac3", "", "", "webvtt", "", "", "vtt", "ac3", "m4p", "", "", "mqv"] All extensions filtered = ["pls", "aifc", "m4r", "wav", "3gp", "3g2", "flac", "avi", "m2a", "aa", "aac", "mpa", "m3u", "mov", "aiff", "ttml", "m4v", "amr", "caf", "m4a", "mp4", "mp1", "m1a", "mp4", "mp2", "mp3", "itt", "au", "eac3", "webvtt", "vtt", "ac3", "m4p", "mqv"] First extension = 'pls' Second extension = 'aifc' Third extension = 'm4r'
{ "language": "en", "url": "https://stackoverflow.com/questions/45395033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }