texts
list | tags
list |
---|---|
[
"Display icons in Django admin for each item",
"I want to add a specified icon for each model on admin index page. I added an attribute named \"picture\" on each model then I modified /contrib/admin/sites.py to pass that picture name to template and checked and use it on index.html template of admin to get the result.\nI wonder to know if there is a better way\n\nclass Product(models.Model):\n abbr = models.CharField(max_length=20,unique=True)\n title = models.CharField(max_length=200,unique=True)\n owner = models.ForeignKey(UserProxy)\n des = models.TextField(blank=True,null=True)\n picture = 'product.png' \n def __unicode__(self):\n return self.abbr\n class Meta:\n none"
]
| [
"python",
"django",
"django-templates",
"django-admin"
]
|
[
"How to get all the keys of json in java using Gson or org.json library?",
"For example from the following json, id, items, fromNumber should be retrieved.\nThe json can be having n number of nesting.\n\n{\n\"items\": [{\n \"id\": 633706061003,\n \"fromNumber\": \"16572307534\",\n\n \"contact\": {\n \"id\": 499354453003,\n \"homePhone\": \"16572307534\"\n },\n\n \"records\": [{\n \"id\": 353389055003,\n \"result\": \"LA\",\n \"recordings\": [{\n \"id\": 16427622003,\n }]\n }]\n}],\n\"limit\": 100,\n\"offset\": 0,\n\"totalCount\": 5949\n\n\n}\n\nI have implemented the below code, but in this code I have to tell the level of nesting\n\nString prefix = \"\";\n\n /*\n * Root Array\n */\n JsonArray rootArray = new JsonParser().parse(json).getAsJsonArray();\n\n for (int i = 0; i < rootArray.size(); i++) {\n\n /*\n * Single object in root array while iterations. for id, properties, tags etc.\n */\n JsonObject rootArrayObject = rootArray.get(i).getAsJsonObject();\n\n Set<Map.Entry<String, JsonElement>> rootArrayObjectEntrySet = rootArrayObject.entrySet();\n\n /*\n * Getting the keys and values of RootArray Single Object\n */\n for (Map.Entry<String, JsonElement> entryChild : rootArrayObjectEntrySet) {\n\n prefix = entryChild.getKey();\n\n /*\n * Getting each object, key or array as an element\n */\n JsonElement rootArrayObjElement = rootArrayObject.get(entryChild.getKey());\n\n\n if(rootArrayObjElement.isJsonArray()){\n\n /*\n * Getting array's object in single object of root array. Example: tags\n */\n JsonArray rootArrayObjArray = rootArrayObjElement.getAsJsonArray();\n\n for (int j = 0; j < rootArrayObjArray.size(); j++) {\n\n\n }\n\n\n }else if(rootArrayObjElement.isJsonObject()){\n\n /*\n * Single object in root array \n */\n JsonObject rootArrayObjObj = rootArrayObjElement.getAsJsonObject();\n\n Set<Map.Entry<String, JsonElement>> rootArrayObjObjEntrySet = rootArrayObjObj.entrySet();\n\n for (Map.Entry<String, JsonElement> rootArrayObjObjChild : rootArrayObjObjEntrySet) {\n\n\n\n\n /*\n * Getting each object, key or array as an element\n */\n JsonElement rootArrayObjObjElement = rootArrayObjObj.get(rootArrayObjObjChild.getKey());\n\n if(rootArrayObjObjElement.isJsonPrimitive()){\n\n\n\n\n }else if(rootArrayObjObjElement.isJsonArray()){\n\n JsonArray rootArrayObjArray = rootArrayObjObjElement.getAsJsonArray();\n\n for (int j = 0; j < rootArrayObjArray.size(); j++) {\n\n\n\n }\n }\n\n }\n\n\n }else if(rootArrayObjElement.isJsonPrimitive()){\n\n\n\n\n }\n\n\n }\n\n\n\n\n\n }"
]
| [
"java",
"json"
]
|
[
"Redux-form not formatting post data and [object Object] issue",
"I have two problems that are a result of each other. I populate two fields with initialValue data, I can then push another field to the array. The issue came about when I tried to amend the initialValue structure from:\n\n initialValues: {\n rockSingers: [ \"Axl Rose\", \"Brian Johnson\"]\n }\n\n\nto:\n\n initialValues: {\n rockSingers: [{ singer: \"Axl Rose\" }, { singer: \"Brian Johnson\" }]\n }\n\n\nThe first problem is that the field now returns [object Object]. Upon submitting the form the correct json format is displayed until I come on to my 2nd issue... when adding a new value that does not format the same as the initialValue data - e.g.\n\n{\n \"rockSingers\": [\n {\n \"singer\": \"Axl Rose\"\n },\n {\n \"singer\": \"Brian Johnson\"\n },\n \"Tom Rudge\"\n ]\n}\n\n\nHere is the codesandbox - https://codesandbox.io/s/8kzw0pw408"
]
| [
"javascript",
"reactjs",
"react-redux",
"redux-form"
]
|
[
"instagram web api net::ERR_BLOCKED_BY_RESPONSE",
"I have created a simple photo gallery by a hashtag\nUsing instagram-web-api and electron\nMain process:\nconst Instagram = require('instagram-web-api')\nconst client = new Instagram({})\nipc.on('get-photos', (event, hashtagFromClient) => {\ncreatePhotoArray()\n\nasync function createPhotoArray() {\n let photoArray = []\n\n let p = await client.getPhotosByHashtag({ hashtag: hashtagFromClient })\n\n for (let i = 0; i < p.hashtag.edge_hashtag_to_media.edges.length; i++) {\n photoArray.push([p.hashtag.edge_hashtag_to_media.edges[i].node.thumbnail_src, p.hashtag.edge_hashtag_to_media.edges[i].node.edge_liked_by.count])\n }\n\n event.sender.send('gallery-created', photoArray)\n}\n})\n\nRender process:\nipc.send('get-photos', game.userData.hashtag)\n\nipc.on('gallery-created', function (event, photoArr) {\n photoArray = photoArr\n maxNumIMG = photoArray.length\n for (let i = 0; i < photoArray.length; i++) {\n myTimeout = setTimeout(function () { createNewPhoto(photoArray[i][0]) }, gapTime * i)\n }\n})\n\nBut I see the floating error:\nnet::ERR_BLOCKED_BY_RESPONSE\n\nHow can I fix it?"
]
| [
"api",
"npm",
"electron",
"instagram",
"response"
]
|
[
"How to test a sprites rotation in cocos2d",
"I want to stop an action once my sprite gets to a certain rotation. For example:\n\nCCAction *rotateUp = [CCRotateTo actionWithDuration:0.3 angle:-35];\n[player runAction:rotateUp];\n\nif (player.rotation == -35) {\n [player stopAction:rotateUp];\n [player runAction:[CCRotateTo actionWithDuration:0.5 angle:65]];\n}\n\n\nOnce the player gets to the max rotation I want it to run a different action. But this isn't working. What can I do instead?"
]
| [
"ios",
"cocos2d-iphone",
"cocos2d-iphone-2.x"
]
|
[
"SQL Azure V12 BACPAC import error: \"The internal target platform type SqlAzureV12DatabaseSchemaProvider does not support schema file version '3.5'.\"",
"Today, Jan. 20, 2017, I created a BACPAC file from a SQL Azure V12 database, and when I went to import it to a local SQL Server 2014 instance using SQL Server Management Studio 2014, I got this error:\n\n\n The internal target platform type SqlAzureV12DatabaseSchemaProvider\n does not support schema file version '3.5'. (File: [filepath])\n (Microsoft.Data.Tools.Schema.Sql)\n\n\nNote that I found several similar questions to this here on StackOverflow, but none with the exact same error message or same solution. I tried installing the Microsoft® SQL Server® Data-Tier Application Framework (17.0 RC 1), but that didn't help. (If there's a newer version, I couldn't find it.)"
]
| [
"sql-server",
"azure-sql-database",
"ssms-2014",
"bacpac"
]
|
[
"error \"Finder got an error: The operation can’t be completed because there is already an item with that name.\" number -48",
"At work, I want to backup some Mac files to a Windows share and have created an AppleScript. It mounts the destination then creates a folder if it doesn't already exist. It then copies the contents of a local folder to this new folder on the destination. It then unmounts the destination\n\nmount volume \"smb://service.backup:<password>@server.domain.com/computer-backup\"\nset dest to result as alias\ntell application \"Finder\"\n if not (exists POSIX file \"/Volumes/server.domain.com/computer-backup/Web\") then make new folder with properties {name:\"Web\"} at \"computer-backup\"\n duplicate items of folder \"Macintosh HD:Library:Server:Web\" to POSIX file \"/Volumes/computer-backup/Web\" with replacing\n eject dest\nend tell\n\n\nThe mount is fine. But if the folder \"Web\" exists on the destination then it errors - despite the \"if not (exists\" statement. I have a very similar script at home (with different usernames, passwords and server addresses) which works fine. I am pretty sure I have had this working at work as well (hence the use of POSIX) but not anymore.\n\nI chose this route as a more granular alternative to TimeMachine and to show my boss I could write AppleScript :>)\n\nAny help gratefully received.\n\nAll the best\n\nJohn"
]
| [
"applescript",
"backup"
]
|
[
"Performing JTextField validation on button click throws NullPointerException",
"I would like to validate few text fields on button click.\n\nThe main concept is to let user input few numbers in few text fields and when he clicks a button to run some method to validate inputs.\n\n\nCheck if there are only numbers in textfields.\nCheck if there is duplicate numbers in textfields.\nCheck if all 6 fields contain some value.\nCheck if numbers are in range 1-100\n\n\nI would like to run validation on button click\n\nprivate void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { \n\n} \n\n\nThese are textfields I would like to validate:\n\nprivate javax.swing.JTextField jTextField1;\nprivate javax.swing.JTextField jTextField2;\nprivate javax.swing.JTextField jTextField3;\nprivate javax.swing.JTextField jTextField4;\nprivate javax.swing.JTextField jTextField5;\nprivate javax.swing.JTextField jTextField6; \n\n\nI have found some piece of code online but I can't seem to get it working.\nHere is the code:\n\nJTextField[] fields;\n\nvoid validation() { //call when appropriate(ie ActionListener of JButton) \n System.out.println( \"Called validation!\");\n int[] nums = new int[fields.length];\n Set<Integer> set = new HashSet<>();\n System.out.println( \"Called validation!\" + nums);\n\n for (int i = 0; i < fields.length; i++) { \n try {\n nums[i] = Integer.parseInt(fields[i].getText());\n } catch (NumberFormatException ex) {\n //not a valid number tell user of error\n JOptionPane.showMessageDialog(null,\"Not a valid format\");\n return;\n }\n\n if (nums[i] < 1 || nums[i] > 48) {\n //out of number range tell user of error\n JOptionPane.showMessageDialog(null,\"Range error\");\n return;\n }\n\n if (!set.add(nums[i])) {\n //duplicate element tell user of error\n JOptionPane.showMessageDialog(null,\"Duplicate\");\n return;\n }\n }\n\n JOptionPane.showMessageDialog(null,\"A, OK\");\n}\n\n\nHow can i make this method to work on buton click.\nWhen i run this method netbeans shows error:\n\nException in thread \"AWT-EventQueue-0\" java.lang.NullPointerException..."
]
| [
"java",
"swing",
"validation",
"jtextfield",
"user-input"
]
|
[
"Comparing two BOOL values",
"In my instance method, would like to compare a BOOL parameter with the content of a static variable, for instance:\n\n- (NSArray*)myMethod:(NSString*)someString actualValuesOnly:(BOOL)actualValuesOnly {\nstatic NSString *prevSsomeString;\nstatic BOOL prevActualValuesOnly;\nstatic NSArray *prevResults\n\nif ([someString isEqualToString:prevSomeString] && \n ([actualValuesOnly isEqual: prevActualValuesOnly]) \n // HOW TO COMPARE THESE TWO BOOLEANS CORRECTLY?? \n { return prevResults; }// parameters have not changed, return previous results \nelse { } // do calculations and store parameters and results for future comparisons)\n\n\nWhat would be the correct way to do this?"
]
| [
"objective-c",
"ios",
"comparison",
"boolean"
]
|
[
"How to add a property to a PNG file",
"I have a PNG file to which i want to add the properties\n\n\nPixels per unit, X axis\nPixels per unit, Y axis\nUnit specifier: meters\n\n\nThese properties are explained in the PNG specification: http://www.w3.org/TR/PNG-Chunks.html\n\nI have programmatically read the properties of the png to check if the properties exists, so that i can set the value for this properties, but i could not see this properties in the png file.\n(Refer pixel-per-unit.JPG)\n\nHow can we add properties to the png file?\n\nregards"
]
| [
"c#",
".net"
]
|
[
"Making bigger and revert button to original size Javascript",
"I have a project to make 2 buttons that containing value before and after test score.\n\nThe student is 50 and every student have 2 buttons that containing their previous and present test score in some subject.\nthe button is placed in 2 columns Before and After, sorted by highest score and resize them depending on their score.\nSo we don't know how to identify which was the pair of those buttons.\n\nSo I decide to make if that \"id\" of pairing button is same \neg: id=\"Score1\" and id=\"Score1_a\"\n\nProgress now, I make the pairing button in \"Before\" and \"After\" Columns change their color to Red if we hover mouse on one of them.\n\nBut it's still not enough.. \nSo I use script to make the buttons bigger when we hover on it, but I don't know how to Revert it back to original size. \nCan you guys help me?\n\nThis is my script: \n\n <script>\n function mouseover(obj) {\n var id2=obj.id+\"_a\";\ndocument.getElementById(obj.id).style.background = \"magenta\";\ndocument.getElementById(obj.id).style.width = \"100px\";\ndocument.getElementById(obj.id).style.height = \"100px\";\ndocument.getElementById(id2).style.background = \"magenta\";\n }\n function mouseout(obj) {\n var id2=obj.id+\"_a\";\ndocument.getElementById(obj.id).style.background = \"deepskyblue\";\ndocument.getElementById(id2).style.background = \"deepskyblue\";\ndocument.getElementById(obj.id).style.offsetwidth;\ndocument.getElementById(obj.id).style.offsetheight;\n }\n</script>\n\n <button id=\"score1\" style='width:70px; height:70px;'>70</button>\n <button id=\"score1_a\" style='width:65px; height:65px;'>65</button>\n <button id=\"score2\" style='width:25px; height:25px;'>25</button>\n <button id=\"score2_a\" style='width:50px; height:50px;'>50</button> \n\n\nThanks."
]
| [
"javascript",
"php"
]
|
[
"How to merge all associations of objects in a collection in Ruby on Rails?",
"In my Ruby on Rails application, I have a \"Parent\" model and each Parent is associated with a number of children. I would like to select a number of Parent and have a set of all children based on some criteria. Let's say we have\n\nParent.where([some condition])\n\n\nHow can I get a collection which is the union of the children of each Parent in the collection in one line? I would like to do something like the following, but inline.\n\nParent.where([some condition]).each do |p|\n children += p.children\nend"
]
| [
"ruby-on-rails",
"ruby"
]
|
[
"ES6 Class multiple inheritance through mixins",
"I'm trying to understand ES6 multiple inheritance using mixins. \n\nI was following this article (simple mixins). But when I run the code, my output is:\n\n\nmain\nUncaught ReferenceError: this is not defined,\nand the error is pointing to console.log('main') again\n\n\nI’m running it on the latest version of Chrome. Here is my code: \n\n\n\nconst RaceDayService = superclass => class extends superclass { \n constructor(){\n console.log('service');\n }\n}\n\nconst RaceDayDB = superclass => class extends superclass { \n constructor(){\n console.log('db');\n }\n}\n\nclass RaceDayUI {\n constructor(){\n console.log('ui');\n }\n}\n\nclass RaceDay extends RaceDayDB(RaceDayService(RaceDayUI)){\n constructor(options){\n console.log('main');\n }\n}\n\nconst raceDay = new RaceDay();\n\n\nAny ideas on what I’m doing incorrectly?\n\nThanks!"
]
| [
"javascript",
"inheritance",
"ecmascript-6",
"multiple-inheritance",
"mixins"
]
|
[
"How to add additional validation to Model field?",
"I have a second thing:\n\n<td>\n @Html.LabelFor(m => m.Number, titleHtmlAttrs)\n</td>\n<td>\n <span class=\"element-value2\">\n @Html.EditorFor(m => m.Number)\n @Html.ValidationTooltipFor(m => m.Number)\n </span>\n</td>\n\n\nAnd this is how this field looks like in model:\n\n[Display(Name = \"Special Number\")]\n[StringLength(20)]\npublic string Number { get; set; }\n\n\nWhich means that if I wanted to change this field, i can have any value from empty to 20.\nIt's ok, but now I need an additional validation.\nIn model I have some fields:\n\npublic DateTime? TimeOf { get; set; }\npublic bool HasType { get; set; }\n\n\nNew validation should work ONLY if TimeOf is not null and HasType is true. New validation should prevent empty values in Number. Basically, change (from empty to 20) to (from 1 to 20).\n\nHow could I correctly accomplish this?\n\nP.S Sorry about my bad English."
]
| [
"c#",
"asp.net-mvc",
"validation"
]
|
[
"Puppeteer how to click a button when id, name not available",
"This may be a simple one, but I am not getting how to click a button in Puppeteer if id, name of button not available.\n\nConsider below html code.\n\n<button data-bb-handler=\"success\" type=\"button\" class=\"btn btn-success\">Answer</button>\n\n\nHow I can click the Answer button in Puppeteer .\n\nI tried below code, it does not work.\n\npage.click('#Answer');\npage.click('button[data-bb-handler=\"success\"]');\n\n\nPlease let me know how I can click the button in such cases."
]
| [
"google-chrome-devtools",
"puppeteer"
]
|
[
"How to send mail dynamic parameter email in content using Laravel?",
"$url_str = $request->account_name . \".hello.com/\";\n\n $objDemo = new \\stdClass();\n $objDemo->firstname = $request->first_name;\n $objDemo->account_name = $request->account_name;\n $objDemo->title = 'Registration Information';\n $objDemo->username = $request->username;\n $objDemo->password = $password;\n $objDemo->url = URL('/');\n\n $objTmp = new \\stdClass();\n $objTmp->firstname = $request->first_name;\n $objTmp->account_name = $request->account_name;\n $objTmp->title = 'Booking Registration Information';\n $objTmp->username = $request->username;\n $objTmp->password = $password;\n $objTmp->url = $url_str;\n\n Mail::to($request->email)->send(new BookingRegistration($objTmp));\n Mail::to($request->email)->send(new AccountRegistration($objDemo));\n\n\nI have create send mail in Laravel. on objDemo working well. but for ObjTmp not working maybe the parameter $url_str have any \".\" value make it not working ."
]
| [
"laravel-5",
"sendmail"
]
|
[
"How to convert datatable record into custom Class?",
"I have data table with following record\n\nColumns -> A B C D E \nRows-> 1 2 3 X Y\n 1 2 3 P Q\n\n\nI would like this datatable to convert into my custom List as following\n\nMyClass\n{\nint A\nint B\nint C\nList<ChildClass>\n}\n\nChildClass\n{\nString D\nString E\n}\n\n\nI am using following code to make it but i stuck in between for childclass. Please help?\n\nIList<MyClass> items = dt.AsEnumerable().Select(row => \n new MyClass\n {\n A= row.Field<int>(\"A\"),\n B= row.Field<int>(\"B\"),\n C= row.Field<int>(\"C\"),\n }).ToList();"
]
| [
"c#",
".net",
"linq",
"list"
]
|
[
"How to query all the points inside a geomtry object of wkt format",
"i have a table named slope it contains the following columns X, Y, Z and geometry. the aforementioned values represents the x,y,z coordinates\nof a geometry. i have also an object named fieldGeometry which is in WKT format.\nmy question is how can i query the all the points in terms of X, Y that are inside the object fieldGeometry.\nas shown in the code below, it is my attempts but not successful.\nplease let me know how to query all the points inside a geometry object in wkt format\ncode:\ndef executeWithFetchallForST_Intersects(self, cursor, fieldAsPolygonsGeometry, gridPointsAsGeometry):\n #"SELECT ST_Intersects("+ fieldAsPolygonsGeometry + "," + gridPointsAsGeometry + ")"\n cursor.execute("SELECT ST_Intersects("+ fieldAsPolygonsGeometry + "," + gridPointsAsGeometry + ") FROM " + config['PostgreDB']['table_name'])\n return cursor.fetchall()"
]
| [
"python",
"postgresql",
"postgis"
]
|
[
"Building JSON object using JQuery",
"I am trying to create a JSON array using JQuery (from an existing JSON object $yAxis) as per the below lines of code. \n\nabc.yAxis = [ \n $.each($yAxis, function(i, obj){\n var $metric= obj.title.text;\n var $oppositeAxis=obj.title.opposite;\n { title: {\n style: {\n font: 'xyz',\n color: 'black'\n },\n text:'$metric'.substring(0,30),\n }, \n opposite: $oppositeAxis\n }, \n}); \n];\n\n\nFireBug always says the below error: \n\n[SyntaxError: invalid label\n[at]\ncolor: 'black']\n\n\nMy existing JSON object ($yAxis) is:\n\n{\n\"yaxis\": \"[{'title':{'text':'A'},'opposite':false},{'title':{'text':'B'},'opposite':true}, {'title':{'text':'C'},'opposite':false}]\"\n}\n\n\nI will be sending this new JSON as input to highCharts."
]
| [
"jquery",
"ajax",
"json",
"jsonp"
]
|
[
"Dependencies between PHPUnit tests",
"I'm writing a PHPUnit test case for an API (so not exactly a unit test) and I'm thinking about having a test that all other tests will depend on.\n\nThe tests in the test case make API requests. Most of these requests require a user. The test in question will create that user that the other tests will use.\n\nWould that be a horrible idea?"
]
| [
"php",
"phpunit"
]
|
[
"Path to executable added to PATH and executable runs using cmd but not from a python IDE",
"I have an .exe under %COPASIDIR%\\bin and this path has been added to the PATH variable. When I open cmd and type the name of the exe (CopasiSE) I get the expected behaviour, shown in the screen shot below:\n\n\nAdditionally, when I start ipython or python from the command prompt and run os.system('CopasiSE') I also the expected behaviour. However, when using an IDE (spyder and pycharm) the I get:\n\nimport os\nos.system('CopasiSE')\nOut[9]: 1\n'CopasiSE' is not recognized as an internal or external command,\noperable program or batch file.\n\n\nDoes anybody have any idea why this is happening? \n\nEdit\n\nBased on comments I tried using subprocess.call with the shell=True switch and got the following:\n\n\n\nEdit2\nAfter seeing @Arne's comment I compared the path that I get from os.system('echo %PATH%') command from the IDE (path_ide) to what I get directly from the shell (path_cmd) and the specific path pointing to the directory containing my exe is in both outputs."
]
| [
"python",
"windows",
"environment-variables",
"pycharm",
"spyder"
]
|
[
"Using embedded MongoDb in Spring Boot application along with MongoTemplate fails",
"I have Spring Boot application:\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication()\npublic class App {\n\n public static void main(String[] args) {\n SpringApplication.run(App.class, args);\n }\n\n}\n\n\nbuild.gradle contains:\n\n\n testCompile group: \"de.flapdoodle.embed\", name:\n \"de.flapdoodle.embed.mongo\", version: \"2.0.0\"\n\n\nand\n\n\n compile(\"org.springframework.boot:spring-boot-starter-data-mongodb\")\n\n\nThere's controller which uses MongoTemplate\n\n@RestController\n@RequestMapping(Constants.MAILBOX_BASE_PATH)\npublic class MController {\n\n private static final Logger log = LoggerFactory.getLogger(MailboxController.class);\n\n private MongoTemplate mongoTemplate;\n\n @Autowired\n public MController(MongoTemplate mongoTemplate) {\n this.mongoTemplate = mongoTemplate;\n }\n}\n\n\nAnd test\n\n@RunWith(SpringRunner.class)\n@SpringBootTest()\n@AutoConfigureMockMvc\npublic class MontrollerTests { \n\n @Autowired\n private MockMvc mvc;\n\n private MongoTemplate _mongoTemplate;\n...\n}\n\n\nMy intention is to use embedded MongoDB for the above test.\nWhen i run it the following error is popped:\n\n\n 2017-03-05 17:14:51.993 ERROR 27857 --- [ main]\n o.s.boot.SpringApplication : Application startup failed\n \n org.springframework.beans.factory.UnsatisfiedDependencyException:\n Error creating bean with name 'mController' defined...\n\n\nand at the of the stacktrace there's \n\n\n java.lang.IllegalStateException: Invalid mongo configuration, either\n uri or host/port/credentials must be specified\n\n\nMy application properties:\n\nserver.port=8090\nspring.data.mongodb.uri=mongodb://localhost:27017/test\nspring.data.mongodb.port=27017\n\n\nHow to solve this issue?\nThanks in advance."
]
| [
"java",
"mongodb",
"spring-boot",
"spring-data-mongodb"
]
|
[
"Displaying a material table in Angular",
"I'm pretty new to Angular and I'm trying to create a table to better display my data. I'm getting the data from a JSON provided by my server.\n\nContent of data.component.html:\n\n<div class=\"container\">\n <h1>Search history</h1>\n <table *ngIf=\"searches\">\n <li *ngFor=\"let search of searches\">\n <p class=\"searchParams\">{{search.searchParams}}</p>\n <p class=\"searchDate\">{{search.searchDate | date: \"yyyy-MM-dd hh:mm\"}}</p>\n </li>\n </table>\n</div>\n\n\nContent of data.component.ts:\n\n@Component({\n selector: 'app-data',\n templateUrl: './data.component.html',\n styleUrls: ['./data.component.scss']\n})\nexport class DataComponent implements OnInit {\n searches: Object;\n constructor(private _http: HttpService) {\n }\n\n ngOnInit() {\n this._http.getSearches().subscribe(data => {\n this.searches = data;\n console.log(this.searches);\n });\n }\n}\n\n\nWhat I get is something that looks like a bullet list:\n\n\n\nI'm trying to take this as example but I don't understand how to implement it. What is my datasource here? What HTML should I write to get such a nice looking table?"
]
| [
"html",
"angular",
"angular-material"
]
|
[
"fabricjs apply filter on base64 datasource on mobile",
"I'm uploading a picture via an input type=\"file\" and I get a picture in base64: \n\n<input type=\"file\" accept=\"image/*\" />\n\n\nI apply a filter on it in fabricjs like this:\n\n var filter = new fabric.Image.filters.Grayscale();\nimage.filters.push(filter);\nimage.applyFilters();\ncanvas.renderAll();\n\n\nBut if the canvas with the applied filter is rendered, the picture disappear. If I remove the filter afterwards, the picture shows again.\n\nI use fabricjs in v.2.0.0-rc.3"
]
| [
"javascript",
"fabricjs",
"fabricjs2"
]
|
[
"TypeError using MoviePy",
"I'm working on a python script that takes a picture and a music file and create a video file using MoviePy library. Unfortunatly, I'm facing a problem I'm not able to resolve. When I try to define the AudioFile I get this error :\n\nTypeError: 'float' object cannot be interpreted as an integer\n\n\nHere's my code:\n\nfrom moviepy.editor import *\n\nclip = VideoFileClip(\"my_picture.jpg\")\nclip = clip.set_audio(AudioFileClip(\"music.mp3\"))\nclip = clip.set_duration(8)\nclip.write_videofile(\"movie.mp4\",fps=15)\n\n\nI'm fairly new to Python so if someone could help me sort this problem it would be great :)\n\nHere's the full error:\n\n File \"movietest.py\", line 5, in <module>\n clip = clip.set_audio(AudioFileClip(\"music.mp3\"))\n File \"C:\\Users\\Julien_Dev\\AppData\\Local\\Programs\\Python\\Python35-32\\lib\\site-packages\\moviepy-0.2.2.11-py3.5.egg\\moviepy\\audio\\io\\AudioFileClip.py\", line 63, in __init__\n buffersize=buffersize)\n File \"C:\\Users\\Julien_Dev\\AppData\\Local\\Programs\\Python\\Python35-32\\lib\\site-packages\\moviepy-0.2.2.11-py3.5.egg\\moviepy\\audio\\io\\readers.py\", line 70, in __init__\n self.buffer_around(1)\n File \"C:\\Users\\Julien_Dev\\AppData\\Local\\Programs\\Python\\Python35-32\\lib\\site-packages\\moviepy-0.2.2.11-py3.5.egg\\moviepy\\audio\\io\\readers.py\", line 234, in buffer_around\n self.buffer = self.read_chunk(self.buffersize)\n File \"C:\\Users\\Julien_Dev\\AppData\\Local\\Programs\\Python\\Python35-32\\lib\\site-packages\\moviepy-0.2.2.11-py3.5.egg\\moviepy\\audio\\io\\readers.py\", line 123, in read_chunk\n self.nchannels))\nTypeError: 'float' object cannot be interpreted as an integer"
]
| [
"python"
]
|
[
"ArrayAdapter BluetoothChat",
"I need a bluetooth transmission in my App. Therefor I used parts of the BluetoothChat Project of the android SDK. I can already connect to other devices and send data. Now i have go get the data on the other device. If I am right, the data is stored in the mConversationArrayAdapter which is an object of the ArrayAdapter. \nBut how do i get the Data out of the Arraydapter? What Methods do I have to use?"
]
| [
"android",
"android-arrayadapter"
]
|
[
"Wordpress Form Manager - Email issues",
"When a form was submitted, user didn't receive the email notification.\n\nwhat's the problem should be?\n\nhttp://wordpress.org/extend/plugins/wordpress-form-manager/\n\nCan any one please help me?\nThanks in Advance."
]
| [
"wordpress",
"phpmailer"
]
|
[
"How to preview an uploaded image as the background image of a div?",
"I want to preview an uploaded image file in a div. I have done a bit of research and I have found this piece of code from this post, it is the code to preview an uploaded image file, but in an <img> tag:\n\n<script type=\"text/javascript\">\n function readURL(input) {\n if (input.files && input.files[0]) {\n var reader = new FileReader();\n\n reader.onload = function (e) {\n $('#blah').attr('src', e.target.result);\n }\n\n reader.readAsDataURL(input.files[0]);\n }\n }\n</script>\n\n\nThe associated HTML:\n\n<body>\n <form id=\"form1\" runat=\"server\">\n <input type='file' onchange=\"readURL(this);\" />\n <img id=\"blah\" src=\"#\" alt=\"your image\" />\n </form>\n</body>\n\n\nVery cool. However, what I want is to display the uploaded image as the background image of a div, an example of which would be like this:\n\n<div class=\"image\" style=\"background-image:url('');\"></div>\n\nI know that, logically, I would have to replace\n\n$('#blah').attr('src', e.target.result);\n\nwith something like\n\n$('div.image').attr('style', e.target.result);.\n\nBut how to make the path of the image go into the value of the 'background-image' property?\n\nAnd yes, do I need to link to the JQuery library for this?\n\nThank you."
]
| [
"javascript",
"jquery",
"image",
"upload"
]
|
[
"Jena's TDB dataset got TDBTransactionException when try to commit an transaction",
"This is what I wrote:\n\npublic static void main(String[] args) {\n Dataset dataset = TDBFactory.createDataset(\"/tmp/someThings\");\n dataset.begin(ReadWrite.WRITE);\n Model model = dataset.getDefaultModel();\n model.setNsPrefix(\"kg\", \"http://sankuai.com/kg\");\n Resource resource = model.createResource(\"http://sankuai.com/kg/jena\");\n resource.addProperty(model.createProperty(\"kg\", \"language\"), \"SPARQL\");\n dataset.commit();\n System.out.println(model);\n}\n\n\nBut instead give me some output, It shows an error:\n\nException in thread \"main\" org.apache.jena.tdb.transaction.TDBTransactionException: Not in a transaction\n\n\nhas there something I done was wrong?"
]
| [
"graph",
"sparql",
"rdf",
"jena"
]
|
[
"Why does Convert.ToDouble change my Value by factor 1000?",
"I am reading some x and y coordinates from an XML file.\n\nThe coordinates look like this 3.47, -1.54, .. and so on.\n\nWhen I assign the value to a double variable by\n\ndouble x, y;\nx = Convert.ToDouble(reader[\"X\"]); // X Value: 3.47\n\n\nThe Value becomes 3470.00\n\nWhy is this the case?"
]
| [
"c#",
"double",
"type-conversion"
]
|
[
"check to see if then load external scripts if they arent present",
"I have 3 external files that have to be loaded for my adverts to display\n\n http://www.manx.net/Scripts/jquery-1.6.1.min.js?v=12.01.2012\n http://www.manx.net/Scripts/jquery-migrate-1.2.1.min.js?v=12.01.2012\n https://code.createjs.com/createjs-2015.11.26.min.js\n\n\nProblem is, if i have 2 of our adverts running at the same time on the adserver they conflict as they are both trying to pull the external files in at the same time. (i have to include these files in my advert each time as the adserver randomly picks the adverts to display).\n\nIs there a way that i can scan to see if the files are already loaded on the page, if they are do nothing and run the rest of the file. If they arent loaded then load and run the rest of the file that follows.\n\nCheers"
]
| [
"javascript"
]
|
[
"How to fix message: \"SQLSTATE[42000]: Syntax error or access violation: 1203 error",
"My website runs fine on localhost but when deploying it to shared hosting. I get this error: \n\n\n SQLSTATE[42000]: Syntax error or access violation: 1203\n User id11846490_otisljoe already has more than 'max_user_connections'\n active connections (SQL: select count(*) as aggregate from invoices\n where title = Invoice and invoices.deleted_at is null)\n\n\nI figured out and, googled why it occurred but I can found the solution."
]
| [
"laravel",
"vue.js"
]
|
[
"having problems with installing composer",
"I'm having problems installing composer. The error being displayed is:\n\n\n Connection Error [ERR_CONNECTION]: Unable to connect to getcomposer.org\n Proxy http####://10.50.7.154:3128### [from Internet Settings] failed with errors:\n Failed to open stream: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.\n \n Request to https://getcomposer.org/installer failed with errors:\n Failed to open stream: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond."
]
| [
"composer-php"
]
|
[
"How to show alert choosing subcategory when parent dropdown not selected?",
"I am new in coding and learning from the internet how to code.\nI have two dropdowns. 1st one is Parent Dropdown and 2nd is Sub-Category Dropdown.\n\n\n\nI want to show an alert message when Parent dropdown not selected and user directly click on sub-category dropdown. The message will show, \"You must select the parent category\".\n\n\n\nFor this purpose I have tried value= onclick confirm ('You must select the parent category') on select this is whant I want but the problem is that whenever I click on sub-category this alert always come. I have tried onchange as well but this also not work for me. \n\nI also tried to count index length.val but this also not working.\n\nI also tried below script but that also not work for me.\n\n <script>\n var dropdown = document.getElementById(\"child\");\n dropdown.onchange = function(event){\n if(dropdown.value==\"\"){\n alert(\"Your message\")\n }\n }\n </script>\n\n\nPlease have a look at what I am doing with my code.\n\n //This is what I code \n <script>\n function get_child_options(){\n var parentID = jQuery('#parent').val(); \n jQuery.ajax({ //Inside jQuery we create ajax object\n url:'/halfdrink/adminseller/parsers/child_categories.php',\n type:'POST',\n data: {parentID : parentID }, \n success: function(data){\n jQuery('#child').html(data); },\n error: function(){alert(\"Something went wront with the child options.\")},\n\n });\n }\n\n // This also the main code line where I call get_child_options\n jQuery('select[name=\"parent\"]').change(get_child_options); \n </script>\n\n\nI am definitely doing something wrong but don't know what I am doing wrong.\n Your suggestions are welcome."
]
| [
"javascript",
"jquery"
]
|
[
"MSIL store a value of structure to return",
"I am using RemotingLite library (see at github) and have an issue with Proxy class factory.\nIn few words the issue is when generating code for return an ValueType objects like user defined structures.\n\nHere a part of original code:\n\n...\nmIL.Emit(OpCodes.Ldloc, resultLB.LocalIndex); //load the result array\nmIL.Emit(OpCodes.Ldc_I4, 0); //load the index of the return value. Alway 0\nmIL.Emit(OpCodes.Ldelem_Ref); //load the value in the index of the array\n\nif (returnType.IsValueType)\n{\n mIL.Emit(OpCodes.Unbox, returnType); //unbox it\n mIL.Emit(ldindOpCodeTypeMap[returnType]);\n}\nelse\n mIL.Emit(OpCodes.Castclass, returnType);\n}\n mIL.Emit(OpCodes.Ret);\n\n\nldindOpCodeTypeMap is a dictionary with opcodes like OpCodes.Ldind_U2 etc. So it works only for standard MSIL types like Int16, Int32 etc. But what I need to do if I need to push to stack then return a custom ValueType value (for example - Guid - size is 16 bytes)?\n\nFor example:\n\n...\nmIL.Emit(OpCodes.Unbox, returnType); //unbox it\nOpCode opcode;\nif (ldindOpCodeTypeMap.TryGetValue(returnType, out opcode))\n{\n mIL.Emit(ldindOpCodeTypeMap[returnType]);\n}\nelse\n{\n // here I getting the size of custom type\n var size = System.Runtime.InteropServices.Marshal.SizeOf(returnType);\n // what next?\n}\n...\n\n\nHere I have get a size of custom ValueType value. So how Load a value of custom ValueType onto the evaluation stack indirectly like Ldind_x opcodes do that?\nThanks!"
]
| [
"c#",
".net",
"cil",
"il"
]
|
[
"How to repaint - prapare JWindow graphics before setting it to visible?",
"To avoid any flickers after JWindow is set to visible I've done it this way - but still I see for a few milliseconds some JLabel (tree: JWindow -> JPanel -> JLabel) old text, then text changes to new value (it must be done before JWindow is set to visible):\n\npublic SomeExtendedJWindow extends SomeJWindow {\n\n @Override\n public void setVisible(boolean visible) {\n if (visible) {\n class doGraphics extends SwingWorker<Void, Object> {\n\n @Override\n public Void doInBackground() {\n validate();\n pack();\n return null;\n }\n\n @Override\n protected void done() {\n SomeJWindow.super.setVisible(true);\n }\n }\n (new doGraphics()).execute();\n } \n }\n}\n\n\nMaybe I should validate or do something with JLabels also?"
]
| [
"java",
"swing",
"graphics",
"swingworker"
]
|
[
"Indexing on only part of a field in MongoDB",
"Is there a way to create an index on only part of a field in MongoDB, for example on the first 10 characters? I couldn't find it documented (or asked about on here).\n\nThe MySQL equivalent would be CREATE INDEX part_of_name ON customer (name(10));.\n\nReason: I have a collection with a single field that varies in length from a few characters up to over 1000 characters, average 50 characters. As there are a hundred million or so documents it's going to be hard to fit the full index in memory (testing with 8% of the data the index is already 400MB, according to stats). Indexing just the first part of the field would reduce the index size by about 75%. In most cases the search term is quite short, it's not a full-text search.\n\nA work-around would be to add a second field of 10 (lowercased) characters for each item, index that, then add logic to filter the results if the search term is over ten characters (and that extra field is probably needed anyway for case-insensitive searches, unless anybody has a better way). Seems like an ugly way to do it though.\n\n[added later]\n\nI tried adding the second field, containing the first 12 characters from the main field, lowercased. It wasn't a big success. \n\nPreviously, the average object size was 50 bytes, but I forgot that includes the _id and other overheads, so my main field length (there was only one) averaged nearer to 30 bytes than 50. Then, the second field index contains the _id and other overheads. \n\nNet result (for my 8% sample) is the index on the main field is 415MB and on the 12 byte field is 330MB - only a 20% saving in space, not worthwhile. I could duplicate the entire field (to work around the case insensitive search problem) but realistically it looks like I should reconsider whether MongoDB is the right tool for the job (or just buy more memory and use twice as much disk space).\n\n[added even later]\n\nThis is a typical document, with the source field, and the short lowercased field:\n\n{ \"_id\" : ObjectId(\"505d0e89f56588f20f000041\"), \"q\" : \"Continental Airlines\", \"f\" : \"continental \" }\n\n\nIndexes:\n\ndb.test.ensureIndex({q:1});\n\ndb.test.ensureIndex({f:1});\n\n\nThe 'f\" index, working on a shorter field, is 80% of the size of the \"q\" index. I didn't mean to imply I included the _id in the index, just that it needs to use that somewhere to show where the index will point to, so it's an overhead that probably helps explain why a shorter key makes so little difference.\n\nAccess to the index will be essentially random, no part of it is more likely to be accessed than any other. Total index size for the full file will likely be 5GB, so it's not extreme for that one index. Adding some other fields for other search cases, and their associated indexes, and copies of data for lower case, does start to add up, and make paging and swapping more likely (it's an 8GB server) which I why I started looking into a more concise index."
]
| [
"mongodb",
"indexing"
]
|
[
"How to convert System.IO.Stream into a Texture in Unity for Android?",
"I'm building a client-side Android app in Unity, and when it downloads a jpg from an AWS S3 server, the result comes back as a System.IO.Stream.\n\nHowever my limited knowledge of Mono and .Net means that I'm struggling to figure out how to turn this System.IO.Stream blob of data into a Texture in Unity, that I can then set on a quad in my scene.\n\nI've seen promising examples of code online like: var img = Bitmap.FromStream(stream);\nyet System.Drawing.Bitmap is not supported in Unity for Android as far as I can tell - does anyone have any suggestions? \n\nThanks in advance!\n\n(The exact example code I'm using to download from AWS S3 is the GetObject() function that can be found here http://docs.aws.amazon.com/mobile/sdkforunity/developerguide/s3.html, but in their example they use a System.IO.StreamReader which only works with reading in text not byte data for images)"
]
| [
"c#",
"android",
"unity3d",
"amazon-s3",
"mono"
]
|
[
"True depth values using OpenGL readPixels",
"I'd like to retrieve the depth buffer from my camera view for a 3D filtering application. Currently, I'm using glReadPixels to get the depth component. Instead of the [0,1] values, I need the true values for the depth buffer, or true distance to the camera in world coordinates.\n\nI tried to transform the depth values by the GL_DEPTH_BIAS and GL_DEPTH_SCALE, but that didn't work. \n\nglReadPixels(0, 0, width_, height_, GL_DEPTH_COMPONENT, GL_FLOAT, depth_buffer);\nglGetDoublev(GL_DEPTH_BIAS, &depth_bias); // Returns 0.0\nglGetDoublev(GL_DEPTH_SCALE, &depth_scale); // Returns 1.0\n\n\nI realize this is similar to Getting the true z value from the depth buffer, but I'd like to get the depth values into main memory, not in a shader."
]
| [
"opengl",
"depth-buffer"
]
|
[
"Laravel convert input name array to dot notation",
"How do I convert an input name array to dot notation, similar to the way the validator handles keys? I'd like it to work for non-arrays as well.\n\nFor example, say I have:\n\n$input_name_1 = 'city';\n$input_name_2 = 'locations[address][distance]';\n\n\nHow would I convert that to:\n\n$input_dot_1 = 'city';\n$input_dot_2 = 'locations.address.distance';"
]
| [
"php",
"laravel"
]
|
[
"Issue with SQL Azure regarding clustered index and delete constraints",
"I have the following SQL script that seems to work on local SQL 2008 R2 instance but fails on Azure SQL.\n\nI have scoured the web but have not found any solution yet.\n\nAny suggestions?\n\nI would like to avoid Identity columns.\n\nCREATE TABLE dbo.[Category]\n(\n CategoryId NVARCHAR(36),\n CONSTRAINT PK_Category_CategoryId PRIMARY KEY CLUSTERED(CategoryId)\n)\nGO\nCREATE TABLE dbo.[File]\n(\n FileId NVARCHAR(36),\n CONSTRAINT PK_File_FileId PRIMARY KEY CLUSTERED(FileId)\n)\nGO\nCREATE TABLE dbo.[FileCategory]\n(\n FileId NVARCHAR(36),\n CategoryId NVARCHAR(36)\n CONSTRAINT FK_FileCategory_FileId FOREIGN KEY (FileId) REFERENCES [File](FileId) ON DELETE CASCADE,\n CONSTRAINT FK_FileCategory_CategoryId FOREIGN KEY (CategoryId) REFERENCES [Category](CategoryId) ON DELETE CASCADE,\n)\nGO\nINSERT INTO [Category] VALUES('ABC')\nINSERT INTO [Category] VALUES('DEF')\nINSERT INTO [Category] VALUES('GHI')\nGO\n\n\nThe above runs fine however it fails on the following statement with the error shown below:\n\nDELETE FROM [Category] WHERE [CategoryId] = 'ABC'\n\n\n\n Msg 40054, Level 16, State 1, Line 3 Tables without a clustered index\n are not supported in this version of SQL Server. Please create a\n clustered index and try again."
]
| [
"sql-server",
"azure",
"azure-sql-database"
]
|
[
"Convert Latitude, Longitude and Altitude to point in a flat 3D space",
"I have a camera and I want to identify specific points in the world with it. I want it to be the more precise as it can be. I tried to convert to (x, y, z) using the answer in this: Lat Long to X Y Z position in JS .. not working. But the thing is, I don't know how to affect the camera angles (yaw, pitch, roll) with the curvature of the earth, so it gets kind of weird. So I was thinking of converting it to a flat 3D representation and convert altitude, latitude, and altitude without the curvature of the earth to (x, y, z) so that I can see all the points in front.\n\nIs this a good idea? If not, how can I affect the angles of the camera depending on the position in the world so that I always have the right perspective from the camera?"
]
| [
"python",
"opencv",
"camera-calibration"
]
|
[
"Using git difftool to view differences in entire directory",
"I'm having trouble trying to use git difftool (in this case, opendiff for mac) to visualise the differences made in the latest git commit. I don't want to launch opendiff for each pair of files that has changed, I just want to launch one instance of opendiff which compares the entire directory, so I've followed the advice from this answer which is to use --dir-diff. I ended up using this command:\n\ngit difftool HEAD^ HEAD --dir-diff\n\n\nThe problem is that when I launch this command, the opendiff says that there are 0 differences (even though using normal diff will show differences in multiple files). What's going on? How do I use difftool correctly?"
]
| [
"git",
"diff",
"difftool",
"opendiff"
]
|
[
"Writing a parallel loop",
"I am trying to run a parallel loop on a simple example.\nWhat am I doing wrong?\n\nfrom joblib import Parallel, delayed \nimport multiprocessing\n\ndef processInput(i): \n return i * i\n\nif __name__ == '__main__':\n\n # what are your inputs, and what operation do you want to \n # perform on each input. For example...\n inputs = range(1000000) \n\n num_cores = multiprocessing.cpu_count()\n\n results = Parallel(n_jobs=4)(delayed(processInput)(i) for i in inputs) \n\n print(results)\n\n\nThe problem with the code is that when executed under Windows environments in Python 3, it opens num_cores instances of python to execute the parallel jobs but only one is active. This should not be the case since the activity of the processor should be 100% instead of 14% (under i7 - 8 logic cores).\n\nWhy are the extra instances not doing anything?"
]
| [
"python",
"windows",
"parallel-processing",
"joblib"
]
|
[
"How do I handle an int** in Ada?",
"I'm trying to call SDL_LoadWAV using a pre-made binding to the C library from which it comes. SDL_LoadWAV is just a wrapper for SDL_LoadWAV_RW:\n\nfunction SDL_LoadWAV\n (file : C.char_array;\n spec : access SDL_AudioSpec;\n audio_buf : System.Address;\n audio_len : access Uint32) return access SDL_AudioSpec\nis\nbegin\n return SDL_LoadWAV_RW\n (SDL_RWFromFile (file, C.To_C (\"rb\")),\n 1,\n spec,\n audio_buf,\n audio_len);\nend SDL_LoadWAV;\n\n\nHere is the prototype of the function in C:\n\nSDL_AudioSpec* SDL_LoadWAV_RW(SDL_RWops* src,\n int freesrc,\n SDL_AudioSpec* spec,\n Uint8** audio_buf,\n Uint32* audio_len)\n\n\n(See here for more information)\n\nNow as you can see, it passes a Uint8 (unsigned 8-bit integer) array by reference, in the form of a Uint8**. This is causing me a great bit of vexation. Here is the appropriate binding:\n\nfunction SDL_LoadWAV_RW\n (src : access SDL_RWops;\n freesrc : C.int;\n spec : access SDL_AudioSpec;\n audio_buf : System.Address;\n audio_len : access Uint32) return access SDL_AudioSpec;\npragma Import (C, SDL_LoadWAV_RW, \"SDL_LoadWAV_RW\");\n\n\nAs you can see, the binding maps the Uint8** to a System.Address. I've tried a couple of tricks to get that data where I want it to go, but nothing seems to work. Right now, my code looks like this (it has a few custom types and exceptions in it):\n\ntype Music is new Resource with\nrecord\n --Id : Integer; (Inherited from Resource)\n --Filename : Unbounded_String; (Inherited from Resource)\n --Archive_Name : Unbounded_String; (Inherited from Resource)\n --Zzl_Size : Integer; (Inherited from Resource)\n Audio : access SDL_AudioSpec_Access;\n Length : aliased Uint32;\n Buffer : System.Address;\n Position : Integer := 1;\nend record;\n\noverriding procedure Load(Mus : in out Music) is\n Double_Pointer : System.Address;\nbegin\n Log(\"Loading music \" & To_Ada(Get_Audio_Filepath(Mus)));\n Audio_Load_Lock.Seize;\n if null = SDL_LoadWAV(Get_Audio_Filepath(Mus), Mus.Audio.all, Double_Pointer, Mus.Length'access) then\n raise Audio_Load_Failed with To_String(Mus.Filename) & \"&Stack=\" & Get_Call_Stack;\n end if;\n Log(\"Music length =\" & Integer'Image(Integer(Mus.Length)));\n declare\n type Sample_Array is array(1..Mus.Length) of Uint8;\n Single_Pointer : System.Address;\n for Single_Pointer'address use Double_Pointer;\n pragma Import(Ada, Single_Pointer);\n Source : Sample_Array;\n for Source'address use Single_Pointer;\n pragma Import(Ada, Source); \n Dest : Sample_Array;\n for Dest'address use Mus.Buffer;\n pragma Import(Ada, Dest);\n begin\n Dest := Source;\n end;\n Audio_Load_Lock.Release;\nend Load;\n\n\nBut, like more or less everything else I've tried, I get a PROGRAM_ERROR/EXCEPTION_ACCESS_VIOLATION when the Load function is executed.\n\nCan anyone figure out how I need to handle this System.Address? Thanks!"
]
| [
"c",
"pass-by-reference",
"ada",
"memory-address",
"ffi"
]
|
[
"\"comma\" and urlencoding PHP",
"On my site, a user can enter text in a field called \"Description\". I can get whatever text was entered by performing a query and returning this as $description. I eventually want to use this information to build a URL. I am running into issues if the user enters a \",\" in part of the text. As an example, let's say the user entered \"test description, test description\". \n\n$description will return as: \"test%20description,%20test%20description\"\n\nRunning urlencode($description) results in: \"test+description%2C+test+description\"\n\nThis is okay for the \"test+description\" part, but not the %2C. Ultimately what I am asking is, how can I instead return: \"test+description,+test+description\""
]
| [
"php",
"url",
"urlencode"
]
|
[
"Hibernate @CreationTimestamp @UpdateTimestamp for Calendar",
"In my entity I have fields:\n\n@UpdateTimestamp\n@Column\nprivate java.util.Calendar modifiedDate;\n@CreationTimestamp\n@Column\nprivate java.util.Calendar createdDate;\n\n\nThese fields are changed by hibernate. I see result saved to DB. In DB saved data without time, how I could explain to hibernate that calendar should be saved with current dateTime?\n\n\n\nP.S.\nI saw workarounds like method annotations @PreUpdate @PrePersist i do not think i need ones."
]
| [
"java",
"hibernate",
"jpa",
"orm"
]
|
[
"How to get CREATE TABLE Permission for windows authentication users in SQL Server express 2005",
"I recently installed SQL Server 2005 Management Studio Express. When I login to the Database server machinename\\SQLEXPRESS using Windows Authentication.\n\nI am unable to create tables or create databases. How do I grant the permissions for the users logged in as Windows Authentication to be able to create tables / databases?"
]
| [
"sql-server",
"windows-authentication",
"sql-server-2005-express"
]
|
[
"Godot: color only a certain digit within a row",
"with this\nvar ggg = ""\nif enteredDigitsCount == 4:\n ggg = ggg.insert(2, "_")\n text = text.insert(1, ggg)\n\nI can have that _ inserted between the 1st and the 2nd digit when I enter the 4th one in my Label (e. g. 1_234).\nNow, as there is a property font_color under Custom Colors in the Label's Inspector, I wonder if I could color a certain digit in a different color than the others when the condition is met. So for example, with entering the fourth digit, I'd like the first one to change color.\nIs it possible to somehow "replace" that _ with font_color to achieve this?"
]
| [
"text",
"insert",
"label"
]
|
[
"Global (system-wide) hotkey with Powershell",
"i have a winform waitng in the back and would like to make it appear with a global (system wide) hotkey. (see bogus \"new-hotkey\"-cmdlet below)\nI searched the web intensively but only found C# solutions, which i could not translate into powershell (v3).\n\n[void][System.Reflection.Assembly]::LoadWithPartialName(\"System.Windows.Forms\")\n\n$form1 = New-Object 'System.Windows.Forms.Form'\n$form1.ClientSize = '300, 250'\n$form1.windowstate = \"minimized\"\n\n# -- bogus code --\n$hk = new-hotkey -scope Global -keys \"Ctrl,Shift,Z\" -action ({$form1.windowstate = \"normal\" })\n# ----------------\n\n$form1.ShowDialog() \n\n\nthanks, Rob"
]
| [
"winforms",
"powershell",
"hotkeys",
"global-hotkey"
]
|
[
"Project must list all files or use an 'include' pattern",
"I see this warning thrown in VSCode:\n\n\n\nThis is the line that throws the ts warning:\n\nimport packageJson from \"../package.json\";\n\n\nWeirdly, building and linting the project works fine:\n\n$ tsc --project .\n✨ Done in 1.16s.\n\n\n$ tslint --config ../../tslint.json --project .\n✨ Done in 1.59s.\n\n\nIs this a warning caused by the VSCode parser, or is there something wrong in my tsconfig.json file?\n\n// tsconfig.json\n{\n \"exclude\": [\n \"node_modules\"\n ],\n \"extends\": \"../../tsconfig.json\",\n \"files\": [\n \"package.json\"\n ],\n \"include\": [\n \"src/**/*\"\n ],\n \"compilerOptions\": {\n /* Basic Options */\n \"outDir\": \"dist\",\n /* Module Resolution Options */\n \"baseUrl\": \".\",\n }\n}"
]
| [
"typescript",
"tslint"
]
|
[
"How to copy items from Documents directory to .app directory in iPhone App?",
"I have created a script that saves some files in the Documents directory of my app. Now I need to copy these files into my \"application.app\" bundle...\n\nHow I can do this? Thanks to everyone that can help me."
]
| [
"iphone",
"ios",
"directory"
]
|
[
"Transform (or copy) an object to a subclass instance in Objective-C",
"I want to transform an instance of an object into an instance of a subclass of that object class, so that I can use the additional methods and properties of that subclass, in Objective-C.\n\nHow can I do this in a way that does not require me to hardcode the properties of that object class in a copy method?"
]
| [
"ios",
"objective-c",
"macos",
"objective-c-runtime"
]
|
[
"Add custom content element layouts in TYPO3",
"In TYPO3 I want to add several custom content element layouts to the existing ones of the default content type \"Header\". The custom layouts should make it possible, to make a header that is originally an H1 header look like H2 or H3, for instance.\n\nSo I added this Typoscript code, that is supposed to add the additional options to the interface in the backend:\n\nTCEFORM {\n tt_content {\n layout {\n altLabels {\n 0 = abc\n 1 = def\n 2 = geh\n 3 = Layout H1\n 4 = Layout H2\n 5 = Layout H3\n }\n removeItems = 6,7,8,9,10\n } \n }\n}\n\n\nAs well as this, that should add the CSS classes:\n\ntt_content.stdWrap.innerWrap.cObject = CASE\ntt_content.stdWrap.innerWrap.cObject {\n key.field = layout\n\n 3 = TEXT\n 3.value = like-h1\n\n 4 = TEXT\n 4.value = like-h2\n\n 5 = TEXT\n 5.value = like-h3\n}\n\n\nHowever, of my 3 additional layouts, only one is added to the interface in the backend:\n\n\nNo matter what I try, I can't get the other two layouts to be added to the dropdown list in the backend. What could be a reason for this?"
]
| [
"typo3",
"content-management-system",
"typoscript"
]
|
[
"D3: How to dynamically refresh a graph by changing the data file source?",
"How do I update the data on demand by changing the file d3 accesses? With a click, for example, it would read data from a new data file and add more nodes to the graph like AJAX. \n\nI use d3.tsv to read in data.tsv, one of many files of the same format. \n\nI made a simple graph to illustrate my question. Thanks in advance.\n\n<script src=\"http://d3js.org/d3.v3.min.js\"></script>\n<script>\n var width = 400,\n height = 200;\n\n var x = d3.scale.linear().range([0, width]),\n y = d3.scale.linear().range([height, 0]);\n\n var svg = d3.select(\"body\")\n .append(\"svg\")\n .attr(\"width\", width)\n .attr(\"height\", height);\n\n d3.tsv(\"data.tsv\", function(error, data) { \n if (error) console.warn(error);\n x.domain(d3.extent(data, function(q) {return q.xCoord;}));\n y.domain(d3.extent(data, function(q) {return q.yCoord;}));\n\n svg.selectAll(\".dot\")\n .data(data)\n .enter().append(\"circle\")\n .attr(\"r\", 10)\n .attr(\"cx\", function(d) { return x(d.xCoord); })\n .attr(\"cy\", function(d) { return y(d.yCoord); })\n }); \n</script>\n<a href=\"#\">update the graph</a>"
]
| [
"ajax",
"d3.js",
"graph"
]
|
[
"Sandbox shell programs on time",
"I'm writing a grading robot for a Python programming class, and the students' submissions may loop infinitely. I want to sandbox a shell call to their program so that it can't run longer than a specific amount of time. I'd like to run, say, \n\nrestrict --msec=100 --default=-1 python -c \"while True: pass\"\n\n\nand have it return -1 if the program runs longer than 100ms, and otherwise return the value of the executed expression (in this case, the output of the python program)\n\nDoes Python support this internally? I'm also writing the grading robot in Perl, so I could use some Perl module wrapped around the call to the shell script."
]
| [
"python",
"shell",
"sandbox"
]
|
[
"Android : two TextView, Two fonts , only one applied",
"Pretty weird problem,\nAnd I don't find anything to explain why it is happening.\nI have two very classic textViews, and I want to apply two different fonts to each textViews. \n'Title' in regular, 'Description' in light. \nThe problem is that it takes only the first one and applies it to both of them.\nExplanation : If I put medium or light to the first, both of the textviews will have the same font, whatever font I put for the second one.\nHere is my xml : \n\n<TextView\n android:id=\"@+id/title\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_gravity=\"center_vertical\"\n android:fontFamily=\"sans-serif-medium\"\n android:textColor=\"@color/black\"\n android:textSize=\"14sp\" />\n\n <TextView\n android:id=\"@+id/description\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_gravity=\"center_vertical\"\n android:textColor=\"@color/black\"\n android:textSize=\"12sp\"\n android:fontFamily=\"sans-serif-light\"\n android:visibility=\"gone\" />\n\n\nResult being both of them in medium. (edit : the visibility of the 2nd textView is changed programaticly in the code)\n\nAnd I tried to do it programaticly :\n\nfinal TextView tv_title = (TextView) v.findViewById(R.id.title);\n if (tv_title != null) {\n tv_title.setTypeface(Typeface.create(\"sans-serif-medium\", Typeface.NORMAL));\n }\nfinal TextView tv_subTitleription = (TextView) v.findViewById(R.id.description);\n if (tv_subTitleription != null) {\n tv_subTitleription.setTypeface(Typeface.create(\"sans-serif-light\", Typeface.NORMAL));\n }\n\n\nI am seriously amazed by this weird attitude. Does anyone has any idea why it is not applying differents fonts to each?\n\nThank you :)"
]
| [
"android"
]
|
[
"Assembly's definition does not match",
"Error 2 Could not load file or assembly\n 'CrystalDecisions.Enterprise.Framework, Version=10.2.3600.0,\n Culture=neutral, PublicKeyToken=692fbea5521e1304' or one of its\n dependencies. The located assembly's manifest definition does not\n match the assembly reference. (Exception from HRESULT: 0x80131040)\n\n\nCan anyone tell how to correct this error?\nI tried to delete the files from the bin folder and I even tried downloading a new dll file and added reference to it. Still it didnt work out."
]
| [
"c#",
"asp.net",
".net-assembly"
]
|
[
"tkinter won't update entry box with function",
"Lately I've bean learning how to use the tkinter module in Python 3 to create a GUI. Unfortunately I've become stuck on an issue where my Entry widgets won't update. To understand the problem I wrote a short test case that populates an Entry widget with the string 'hello'.\n\nclass SettingsWindow():\n\n def __init__(self):\n self.root = tk.Tk()\n\n main_frame = ttk.Frame(self.root, padding=(15, 15, 15, 15))\n main_frame.grid()\n\n start_time = tk.StringVar()\n start_time_ent = ttk.Entry(main_frame, textvariable=start_time, width=5)\n start_time.set('hello')\n start_time_ent.grid()\n\n main_frame.mainloop()\n\nif __name__ == '__main__': \n app = SettingsWindow()\n\n\nThe issue arises when I attempt to organize my work in terms of methods:\n\nclass SettingsWindow():\n\n def __init__(self):\n self.root = tk.Tk()\n\n main_frame = ttk.Frame(self.root, padding=(15, 15, 15, 15))\n main_frame.grid()\n\n self.general_settings(main_frame, parent_column=1, parent_row=2)\n\n main_frame.mainloop()\n\n def general_settings(self, parent_frame, parent_column=0, parent_row=0):\n start_time = tk.StringVar()\n start_time_ent = ttk.Entry(parent_frame, textvariable=start_time, width=5)\n start_time.set('hello')\n start_time_ent.grid()\n\nif __name__ == '__main__': \n app = SettingsWindow()\n\n\nWhen I run the second version of the code, the window loads with an empty Entry widget. My only guess on why this happens is start_time.set('hello') is stuck in some queue and I'm missing a command when compiling the window. Any suggestions?"
]
| [
"python",
"python-3.x",
"user-interface",
"tkinter"
]
|
[
"Youtube player for xamarin forms",
"Hi I am trying to create a youtubeview inherited from webview with the support of youtube-api (https://github.com/nishanil/YouTubePlayeriOS/blob/master/Classes/YouTubePlayer.cs.) But the IOS UIWebview in this class returns a string after executing javascript, where as xamarin forms webview don't. Could someone help me achive this so that a single control work in all patforms.\n\nThere's no good youtube player outside for xamarin forms, there are different examples individually. Please help me."
]
| [
"youtube-api",
"custom-controls",
"xamarin.forms"
]
|
[
"I can't test a Google App using OpenID single sign-on on the AppEngine devserver, locally",
"I'm starting to develop an application using App Engine (Python) that will be integrated in the Google Apps platform and will be sold in the Marketplace. I've implemented the Single Sign-On openID authentication and it works fine when deployed, but doesn't work locally at all.\n\nHow can i do that locally? user.federated_identity() apparently does not work on the localhost.\n\n--edit--\nPrecisely, what i need to do is to be able to run this tutorial on App Engine's devserver."
]
| [
"python",
"google-app-engine",
"google-apps",
"google-openid"
]
|
[
"Large matrixes in Java",
"I have a big matrix (around 100x20.000.000) integer elements. I am storing this as an ArrayList of Lists. Unfortunately Java does not like that and I get an OutOfMemoryError. \n\nIs there a good way to store a big matrix in Java? \n\nI am used to pythons \"import library to do this for you\". Is there a suitable library for this in java? \n\nThis post is not a solution of my problem, because in that post the user tried to store strings. The solution was to map the strings to integers and thus save some space. I can not do that. I just have a big matrix of ints."
]
| [
"java",
"python",
"matrix",
"out-of-memory"
]
|
[
"How to access custom claim in aspnet core application authorized using Identity Server",
"I'm following Identity Server quickstart template, and trying to setup the following\n\n\nIdentity server aspnet core app\nMvc client, that authenticates to is4 and also calls webapi client which is a protected api resource.\n\n\nThe ApplicationUser has an extra column which I add into claims from ProfileService like this:\n\n public async Task GetProfileDataAsync(ProfileDataRequestContext context)\n {\n var sub = context.Subject.GetSubjectId();\n var user = await _userManager.FindByIdAsync(sub);\n if (user == null)\n return;\n\n var principal = await _claimsFactory.CreateAsync(user);\n if (principal == null)\n return;\n\n var claims = principal.Claims.ToList();\n\n claims.Add(new Claim(type: \"clientidentifier\", user.ClientId ?? string.Empty));\n\n // ... add roles and so on\n\n context.IssuedClaims = claims;\n }\n\n\nAnd finally here's the configuration in Mvc Client app ConfigureServices method:\n\n JwtSecurityTokenHandler.DefaultMapInboundClaims = false;\n\n services.AddAuthentication(options =>\n {\n options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;\n options.DefaultScheme = \"Cookies\";\n options.DefaultChallengeScheme = \"oidc\";\n }).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)\n .AddOpenIdConnect(\"oidc\", options =>\n {\n options.Authority = \"http://localhost:5000\";\n options.RequireHttpsMetadata = false;\n\n options.ClientId = \"mvc\";\n options.ClientSecret = \"mvc-secret\";\n options.ResponseType = \"code\";\n\n options.SaveTokens = true;\n\n options.Scope.Add(\"openid\");\n options.Scope.Add(\"profile\");\n options.Scope.Add(\"offline_access\");\n\n options.Scope.Add(\"api1\");\n\n options.GetClaimsFromUserInfoEndpoint = true;\n\n options.ClaimActions.MapUniqueJsonKey(\"clientidentifier\", \"clientidentifier\");\n });\n\n\nWith GetClaimsFromUserInfoEndpoint set to true I can access the custom claim in User.Identity, but this results in 2 calls for ProfileService.\n\nIf I remove or set to false then this claim is still part of access_token, but not part of id_token, and then I can't access this specific claim from context User.\n\nIs there a better way I can access this claim from User principal without resulting in 2 calls (as it's now)? or perhaps reading access_token from context and updating user claims once the token is retrieved?\n\nthanks :)"
]
| [
"c#",
"asp.net-core",
"identityserver4"
]
|
[
"Query Tuning and rewrite - SQL Server",
"Could you help to optimize the below query to perform better? Can I reduce the cost?\n\nSELECT this_.id AS id1_20_0_, \n this_.version AS version2_20_0_, \n this_.domain AS domain4_20_0_, \n this_.createdate AS createda5_20_0_, \n this_.lastmodifydate AS lastmodi6_20_0_, \n this_.ownerid AS ownerid7_20_0_, \n this_.timeperiod AS timeperi8_20_0_, \n this_.type AS type9_20_0_, \n this_.capturesource AS capture10_20_0_, \n this_.value AS value11_20_0_, \n this_.siteid AS siteid12_20_0_, \n this_.lastmodifyuserid AS lastmod13_20_0_, \n this_.classid AS classId3_20_0_ \nFROM dbo.pcwdepconstraints this_ \nWHERE this_.classid = 65 \n AND this_.ownerid = 200000000001 \n AND ( this_.capturesource IS NULL \n OR this_.capturesource IN ( 1073741826, 1073741827, 0, 1, 2 ) ) \n\n\n\n\nI have recreated the ix2_pcwdepcons by below columns, but still there is no change in the execution plan and its cost.\n\n( this_.id , \n this_.version , \n this_.domain ,\n this_.createdate ,\n this_.lastmodifydate,\n\n this_.timeperiod ,\n this_.type , \n this_.value , \n this_.siteid \n this_.lastmodifyuserid )"
]
| [
"sql-tuning",
"database-tuning",
"query-tuning"
]
|
[
"Pointers to NSManagedObject after object delete / context save?",
"Can someone please explain what happens to the pointers to the NSManagedObjects after the object is deleted and the context is saved? How should I set them up so that they get set to nil automatically?"
]
| [
"ios",
"objective-c",
"core-data"
]
|
[
"Successor constraints fail when pickup and delivery is enabled",
"I want to solve a VRP with pickups and deliveries. In addition I have some successor constraints that specify that a stop must follow another stop. For example:\n\n\nstop 1 is the pickup for stop 2\nstop 3 must be serviced immediately after stop 2\n\n\nThe pickup-dropoff constraints work as described in the examples. To implement the successor constraint I made three attempts:\n\n\ncpsolver.Add(routing_model.NextVar(2) == 3)\ncpsolver.Add(cpsolver.MemberCt(routing_model.NextVar(2), [3]))\nrouting_model.NextVar(2).SetValue(3)\n\n\nAll attempts result in assignment == None if routing_model.AddPickupAndDelivery(1, 2) is added and there are at least two vehicles.\nAll attempts find a solution if routing_model.AddPickupAndDelivery(1, 2) is not added.\n\nn_stops = 4\nn_vehicles = 2\nix_depot = 0\n\nindex_manager = pywrapcp.RoutingIndexManager(n_stops, n_vehicles, ix_depot)\nrouting_model = pywrapcp.RoutingModel(index_manager)\ncpsolver = routing_model.solver()\n\nrouting_model.AddPickupAndDelivery(1, 2)\ncpsolver.Add(routing_model.NextVar(1) == 2)\ncpsolver.Add(routing_model.NextVar(2) == 3)\n\nassignment = routing_model.Solve()\nprint(assignment)\n\n>>> None\n\n\nWhat is going on here? How to best implement successor constraints?"
]
| [
"or-tools"
]
|
[
"How do i make my Pods in Kubernetes Cluster (GKE) to use the Node's IP Address to communicate to the VMs outside the cluster",
"I have created a Kubernetes Cluster on Google Cloud using GKE service.\n\nThe GCP Environment has a VPC which is connected to the on-premises network using a VPN. The GKE Cluster is created in a subnet, say subnet1, in the same VPC. The VMs in the subnet1 are able to communicate to an on-premises endpoint on its internal(private) ip address. The complete subnet's ip address range(10.189.10.128/26) is whitelisted in the on-premises firewall.\n\nThe GKE Pods use the ip addresses out of the secondary ip address assigned to them(10.189.32.0/21). I did exec in one of the pods and tried to hit the on-premise network but was not able to get a response. When i checked the network logs, i found that the source ip was Pod's IP(10.189.37.18) which was used to communicate with the on-premises endpoint(10.204.180.164). Where as I want that the Pod should use the Node's IP Address to communicate to the on-premises endpoint.\n\nThere is a deployment done for the Pods and the deployment is exposed as a ClusterIP Service. This Service is attached to a GKE Ingress."
]
| [
"networking",
"google-cloud-platform",
"google-kubernetes-engine",
"firewall",
"vpn"
]
|
[
"Are 'gmailified' inboxes accessible via the gmail API?",
"Google just released Gmailify yesterday:\n\nhttp://gmailblog.blogspot.com/2016/02/gmailify-best-of-gmail-without-gmail.html\n\nIf one Gmailifies a third-party email address, can data from that email address then be accessed via the Gmail API?\n\nIf not, is this coming? And/or if so, are there any quirks we should be aware of?"
]
| [
"gmail-api"
]
|
[
"Where to look for image caching",
"I am trying to update a web site. There are new images which are uploaded to it. The web server is Apache. The web pages are written in PHP.\n\nBut I noticed that the new images are not being loaded when the site's URL is accessed from my Windows 10 computer (and also from my Android phone). Instead, the old images are accessed, but not always. Even if I rename the images on the web server the old ones are loaded. \n\nEven if I create a new web page which accesses one of the new jpgs, the old ones are loaded. (Like, say, mywebpage.php and mywebpage-x.php).\n\nSo mywebpage-x.php should try to load image5001.jpg but instead loads image500.jpg from mywebpage.php.\n\nWhere would I look for what I'm doing wrong?"
]
| [
"apache",
"browser-cache"
]
|
[
"Using 'If' functions in a 'For' loop over Pandas DataFrames?",
"So I have this Pandas DataFrame.\nDataFrame\nI am trying to figure out how to write this in python.\nFor each row I want to say, "if the 'Bid_Size' is a different value that the 'Bid_Size' in the previous row, highlight this cell.\nFor instance in my provided data set, row #3/column-'Bid_Size' would be highlighted because it is a different value than the 'Bid_Size' in the previous row.\nI am guessing it would go something like\nimport pandas as pd\nfile = pd.read_csv('DataBase.csv', header=None, names=['Book_ID','Asset','Best_Bid','Bid_Size','Best_Ask', 'Ask_Size']) \n\ndf = pd.DataFrame(file)\n\ndef highlight_yellow(df):\n for rows in df:\n if df['Best_Bid'] != -['Best_Bid']:\n return['highlight:yellow']\n\ndf.style.apply(highlight_yellow)\n\nThank you, I just can not figure this one out."
]
| [
"python",
"pandas"
]
|
[
"How should I indent ternary conditional operator in python so that it complies with PEP8?",
"PEP8 doesn't say anything about ternary operators, if I am not mistaken.\nSo what do you suggest, how should I write long lines with ternary conditional operators?\n\nsome_variable = some_very_long_value \\\n if very_long_condition_holds \\\n else very_long_condition_doesnt_hold\n\n\nor\n\nsome_variable = some_very_long_value \\\n if very_long_condition_holds \\\n else very_long_condition_doesnt_hold\n\n\nWhich one do you prefer the most?"
]
| [
"python",
"formatting",
"pep8",
"ternary"
]
|
[
"Convert mean intensity values from a 24bit image to 8bit 0-255 scale",
"I have feature measurements from a color camera that is taking black and white images saved as 24bit files and processed using proprietary zeiss software. The mean intensities are in the thousands but I am trying to recreate this process using sci-kit image whose auto-thresholding Otsu reports 0-255 grayscale intensity since I converted using 'image_as_ubyte'. Is there a conversion I can use for the 24bit mean intensities that I can map to scale between 0-255?"
]
| [
"python",
"image-processing",
"scikit-image"
]
|
[
"Destroy DataTable and recreate using newly fetched data",
"I need to reinitialize jQuery DataTable with newly fetched data. I have read several posts with similar problem and the solution involves destroying the existing dataTable before re-initializing. The table renders well initially but when trying to render it again with change in the number of columns I get the error: Uncaught TypeError: Cannot read property 'style' of undefined. I understand that this error occurs when the HTML column count and the column definition for DataTables do not match. This implies that the initial table was not successfully destroyed. Here is the code:\n\nvar dataSet1 = [{\n \"country\": \"Benin\",\n \"year\": 1996, \n \"water\": 70.0\n },{\n \"country\": \"Vietnam\",\n \"year\": 1996, \n \"water\": 95.1\n }];\n\n var dataSet2 = [{\n \"country\": \"Benin\",\n \"year\": 2000, \n \"water\": 75.8, \n \"electricity\": 58.5 //additional column from the database\n },{\n \"country\": \"Vietnam\",\n \"year\": 2000, \n \"water\": 96.8, \n \"electricity\": 63.2 \n }];\n\n $('#example_dt').DataTable({\n data: dataSet1,\n columns: [\n { data: \"country\" },\n { data: \"year\" },\n { data: \"water\" }],\n 'searching': false\n });\n\n $('#update_data_btn').click (function(){\n //$(\"#example_dt\").DataTable().fnDestroy();\n $('#example_dt').DataTable({\n destroy: true,\n //retrieve: true\n data: dataSet2, \n columns: [\n { data: \"country\" },\n { data: \"year\" },\n { data: \"water\" }, \n { data: \"electricity\" }],\n // \"bDestroy\": true,\n 'searching': false\n } );\n }); \n});\n\n\nI have tried various suggestion below from similar posts but but can't seem to get this resolved. The same error still comes up.\n\n[1] Adding destroy: true\n[2] Adding $(\"#example_dt\").DataTable().fnDestroy();\n[3] Adding retrieve: true \n[4] Adding \"bDestroy\": true\n[5] Using $('#example_dt').empty(); //this empties and new table not created\n\n\nHere is the fiddle"
]
| [
"jquery",
"datatables"
]
|
[
"Wrong value default ENUM Mysql type",
"as i see every where even in here :\n\n\n From the MySQL manual:\n \n If an ENUM column is declared to permit NULL, the NULL value is a\n legal value for the column, and the default value is NULL. If an ENUM\n column is declared NOT NULL, its default value is the first element of\n the list of permitted values.\n\n\nBut in my database is not like this !!!! Why ?\n\nthis is one of field structure :\n\n`dead` enum('0','1') NOT NULL DEFAULT '0';\n\n\nbut why all data in the dead field is null ???\n\nand if i chose that type to enter a value this will be list :\n\n ()Empty\n (0)\n (1)\n\n\nWhy always null is there ?\n\nand another thing is when i use query like this :\n\n UPDATE TABLE SET dead = 0 -> result : dead = null\n UPDATE TABLE SET dead = 1 -> result : dead = 0\n UPDATE TABLE SET dead = 2 -> result : dead = 1\n\n\nBest Regards."
]
| [
"php",
"mysql",
"database",
"enums"
]
|
[
"PrepareForSegue without functional",
"I have a TableView with 8 sections. All section has 4 Row's. For each row there are a detail view controller.\n\nI have now added a SearchBar in table view. The search works and the result is displayed to me in the search display controller.\n\nBut I can no longer go to the Details View. It is always shown me the same DetailsView.\n\nWhat I have done wrong in the method \"PrepareForSegue\" and \"didSelectRowAtIndexPath\"?\n\nMethode \"prepareForSegue\":\n\n-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender\n{\n\nif ([segue.identifier isEqualToString:@\"BrasilienSegue\"]) {\n BrasilienViewController *BVC = segue.destinationViewController;\n\n NSIndexPath *indexPath = nil;\n\n if ([self.searchDisplayController isActive]) {\n indexPath = [self.searchDisplayController.searchResultsTableView indexPathForSelectedRow];\n BVC.BrasilienLaenderLabel = [self.searchCountriesArray objectAtIndex:indexPath.row];\n\n } else {\n indexPath = [self.tableView indexPathForSelectedRow];\n BVC.BrasilienLaenderLabel = [self.listeDerNationen objectAtIndex:indexPath.row];\n }\n}\n\nif ([segue.identifier isEqualToString:@\"KroatienSegue\"]) {\n KroatienViewController *KVC = segue.destinationViewController;\n\n NSIndexPath *indexPath = nil;\n\n if ([self.searchDisplayController isActive]) {\n indexPath = [self.searchDisplayController.searchResultsTableView indexPathForSelectedRow];\n KVC.kroatienLaenderLabel = [self.searchCountriesArray objectAtIndex:indexPath.row];\n\n } else {\n indexPath = [self.tableView indexPathForSelectedRow];\n KVC.kroatienLaenderLabel = [self.listeDerNationen objectAtIndex:indexPath.row];\n }\n}\n\n\nMethode \"didSelectRowAtIndexPath\":\n\n- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath\n{\n[self tableView: self.tableView accessoryButtonTappedForRowWithIndexPath: indexPath];\n[self.tableView deselectRowAtIndexPath:indexPath animated:YES];\n\nif (tableView == self.searchDisplayController.searchResultsTableView) {\n [self performSegueWithIdentifier: @\"BrasilienSegue\" sender: self];\n}\n\nif (tableView == self.searchDisplayController.searchResultsTableView) {\n [self performSegueWithIdentifier: @\"KroatienSegue\" sender: self];\n}\n\n}"
]
| [
"objective-c",
"ios7"
]
|
[
"Flask and selenium-hub are not communicating when dockerised",
"I am having issues with getting data back from a docker-selenium container, via a Flask application (also dockerized).\n\nWhen I have the Flask application running in one container, I get the following error on http://localhost:5000, which goes to the selenium driver using a Remote driver that is running on http://localhost:4444/wd/hub\n\nThe error that is generated is:\nurllib.error.URLError: <urlopen error [Errno 99] Cannot assign requested address>\n\nI have created a github repo with my code to test, see here.\n\nMy docker-compose file below seems ok:\n\nversion: '3.5'\nservices:\n web:\n volumes:\n - ./app:/app\n ports:\n - \"5000:80\"\n environment:\n - FLASK_APP=main.py\n - FLASK_DEBUG=1\n - 'RUN=flask run --host=0.0.0.0 --port=80'\n command: flask run --host=0.0.0.0 --port=80\n # Infinite loop, to keep it alive, for debugging\n # command: bash -c \"while true; do echo 'sleeping...' && sleep 10; done\"\n\n selenium-hub:\n image: selenium/hub:3.141\n container_name: selenium-hub\n ports:\n - 4444:4444\n\n chrome:\n shm_size: 2g\n volumes:\n - /dev/shm:/dev/shm\n image: selenium/node-chrome:3.141\n# image: selenium/standalone-chrome:3.141.59-copernicium\n depends_on:\n - selenium-hub\n environment:\n - HUB_HOST=selenium-hub\n - HUB_PORT=4444\n\n\nWhat is strange is that when I run the Flask application in Pycharm, and the selenium grid is up in docker, I am able to get the data back through http://localhost:5000. The issue is only happening when the Flask app is running inside docker.\n\nThanks for the help in advance, let me know if you require further information.\n\n\n\nEdit\n\nSo I amended my docker-compose.yml file to include a network (updated the code in github. As I've had the Flask app code running in debug and in a volume, any update to the code results in a refresh of the debugger.\n\nI ran docker network inspect on the created network, and found the local docker IP address of selenium-hub. I updated the app/utils.py code, in get_driver() to use the IP address in command_executor rather than localhost. Saving, and re-running from my browser results in a successful return of data.\n\nBut I don't understand why http://localhost:4444/wd/hub would not work, the docker containers should see each other in the network as localhost, right?"
]
| [
"python",
"selenium",
"docker",
"flask"
]
|
[
"Estimating Posterior in Python?",
"I'm new to Bayesian stats and I'm trying to estimate the posterior of a poisson (likelihood) and gamma distribution (prior) in Python. The parameter I'm trying to estimate is the lambda variable in the poisson distribution. I think the posterior will take the form of a gamma distribution (conjugate prior?) but I don't want to leverage that. The only thing I'm given is the data (named \"my_data\"). Here's my code:\n\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport scipy.stats \n\nx=np.linspace(1,len(my_data),len(my_data))\nlambda_estimate=np.mean(my_data)\n\nprior= scipy.stats.gamma.pdf(x,alpha,beta) #the parameters dont matter for now\n\nlikelihood_temp = lambda yi, a: scipy.stats.poisson.pmf(yi, a)\nlikelihood = lambda y, a: np.log(np.prod([likelihood_temp(data, a) for data in my_data]))\n\nposterior=likelihood(my_data,lambda_estimate) * prior\n\n\nWhen I try to plot the posterior I get an empty plot. I plotted the prior and it looks fine, so I think the issue is the likelihood. I took the log because the data is fairly large and I didn't want things to get unstable. Can anyone point out the issues in my code? Any help would be appreciated."
]
| [
"python",
"statistics",
"probability",
"bayesian",
"poisson"
]
|
[
"Implementing iterator design pattern",
"I have a class Example witch private field Hashmap<Integer, CustomObject>. My goal is to access all instances of CustomObject in this class using the Iterable interface. First, I declare Example to implement Iterable<CustomObject>. Then I call iterator() method. However, I don't know if I should specify hasNext() etc, what to put in main code? Here is what I have so far:\npublic class Example implements Iterable<Songs>{\n private HashMap <Integer, CustomObject>;\n\n @Override\n public Iterator<CustomObject> iterator() {\n for (CustomObject customObject: this){\n System.out.println(customObject);\n }\n\n public static void main(String[] args) {\n Example.iterator();\n }"
]
| [
"java",
"design-patterns",
"iterator",
"iterable"
]
|
[
"Best way to find strings between two points",
"I know this is fairly basic, however I was wondering what the best way to find a string between two referenced points.\n\nFor example:\n\nfinding the string between 2 commas: \n\nHello, This is the string I want, blabla\n\n\nMy initial thought would be to create a list and have it do something like this:\n\nstringtext= []\ncommacount = 0\nword=\"\"\nfor i in \"Hello, This is the string I want, blabla\":\n if i == \",\" and commacount != 1:\n commacount = 1\n elif i == \",\" and commacount == 1:\n commacount = 0\n if commacount == 1:\n stringtext.append(i)\n\nprint stringtext\nfor e in stringtext:\n word += str(e)\n\nprint word\n\n\nHowever I was wondering if there was an easier way, or perhaps a way that is just simply different. Thankyou!"
]
| [
"python",
"string"
]
|
[
"Reachability class and hostnames that require https or vpn (ios)",
"I have implemented the Reachability class successfully. However, in my app I'd like to notify the user when a connection to our server only can't be made (but the regular internet is working). \n\nReachability is reporting that the iPhone successfully can reach a hostname, when I thought it might return an error b/c I was not on an authenticated network: \n\nThe hostname I use is 'foreverfreebank.com'. Again, Reachability's hostname check reports success.\n\nHowever, \n\n--to access this site via the web, one needs to use https in the browser, i.e. 'https://foreverfreebank.com'\n\nDoes Reachability account for this case? Or does the protocol part ('https') not count for anything? \n\nI am confused b/c if you type in in the Firefox browser 'http://foreverfreebank.com', (leaving out the 's'), you get an error. That is, http:// should NOT be reachable. \n\nSimilarly, I have another site that requires VPN access to get to the site: http://checksforever.com. When I try the hostname: 'checksforever.com', Reachability reports success even though I am not on VPN. \n\nIs this expected behavior? Thanks"
]
| [
"ios",
"networking",
"connection",
"reachability"
]
|
[
"Display file contents",
"I am trying to display a full textfile in a batch file, but when I do it like this, it opens notepad.\n\n@echo off\ncall YourText.txt\npause >nul\nexit\n\n\nI also tried\n\n@echo off\nmore < YourText.txt\npause >nul\nexit\n\n\nBoth with double quotes, and without. However, it doesn't work. Then, when I did it without @echo off it works, but it will display each line as:\n\nC:\\Documents and Settings\\Gebruiker\\Mijn documenten\\others\\Bureaublad YourTextline 1\nC:\\Documents and Settings\\Gebruiker\\Mijn documenten\\others\\Bureaublad YourTextline 2\n\n\nI already tried the set /f command without any luck.\nDoes anybody know how to import a full text file through a batch file?"
]
| [
"command-line",
"batch-file"
]
|
[
"How to \"streamify\" functions in NodeJS?",
"Say I have a function that returns something:\n\nfunction f(thing){\n //do stuff\n return result;\n}\n\n\nIf there are instances where I want to use this function as the transform() function in the transform stream, I can \"streamify\" it by using a function similar to util.promisify():\n\nfunction streamify(func){\n return function(chunk, encoding, callback){\n this.push(func(chunk));\n callback();\n }\n}\n\n\nBut say I have a class, which contains an object representing a resource, and I want to use a method of that class in a stream. For example:\n\nclass c {\n constructor(args){\n this.resource = new SomeResource(args.something);\n }\n classMethod(thing){\n //do stuff\n this.resource.func();\n //do more stuff\n return result;\n }\n}\n\n\nIf I simply pass the function to the stream constructor, or even use my streamify() above, when the function is called this is referencing the stream, not the class, so the function generates an error since this.resource doesn't exist in that context. I could do something like this:\n\nsomeStream.resource = myClass.resrouce;\n\n\nBut I was always under the impression that directly modifying the prototypes like that was frowned upon.\n\nI'm looking to see if there's a way to accomplish this without having to extend the Stream classes and implement an entirely new class. That just seems like overkill just to be able to use 1 function from either a 3rd-party library or my own in the context of a transform stream."
]
| [
"node.js",
"stream"
]
|
[
"WHERE parameter equals ANY column (Entity attribute) value",
"I need to write a generic NamedQuery; such as, find me all the objects where any of the attributes matches the given parameter.\n\nselect mo from MyObject mo where mo.ANYAttribute = someParameter \n\nI could not figure out the expression for \"where mo.ANYAttribute\". The sort of wildcard such as \" + or * or ANY or .)... Something that will save me from writing query where I have to write manually to check for each attribute such as:\n\nwhere mo.attribute1= :someParameteror or mo.attribute2 = :someParameter\n\nI am using JPA 2.0.\n\nIs it possible this way or I have to change my approach?\n\nMany Thanks,\nNav"
]
| [
"jpa",
"jpa-2.0",
"jpql"
]
|
[
"invalid host header Heroku node.js react app",
"My heroku app is a react app. I am running into an issue of invalid host header.\n\nThe first thing i tried to do was make a .env.development folder but I may have set it up wrong. If anyone has any suggestions please let me know. \n\nThe repo is on github at https://github.com/syne612/projectIcarusWebsite if anyone has any suggestions please let me know."
]
| [
"javascript",
"node.js",
"reactjs",
"heroku"
]
|
[
"SQL XML .node .query() returns empty string instead of NULL if table node exist",
"Why does .query() return empty string instead of NULL if the table doesn't exist? I am new to querying xml in SQL so I am just playing around and this was unexpected.\n\nHere is an example of the problem.\n\ndeclare @xml xml\n\nset @xml = N'<xdoc><Header><OrderID>1234</OrderID><Detail><ProductID>12345</ProductID><Amount>12.50</Amount></Detail></Header></xdoc>'\n\nSELECT \n Tbl.Col.value('OrderID[1]', 'varchar(10)') as OrderID, \n Tbl.Col.query('Detail') as Detail\nFROM @xml.nodes('//Header') Tbl(Col)\n\nset @xml = N'<xdoc><Header><OrderID>1234</OrderID></Header></xdoc>'\n\nSELECT \n Tbl.Col.value('OrderID[1]', 'varchar(10)') as OrderID, \n Tbl.Col.query('Detail') as Detail\nFROM @xml.nodes('//Header') Tbl(Col)\n\n\nThe first select statement returns as expected. The Detail field is the xml of the table detail within the header.\n\nHowever, on the second select statement this header record did not have a detail table so I expected the field to be null instead of empty string.\n\nOutput"
]
| [
"sql",
"sql-server",
"xml",
"xml-parsing"
]
|
[
"How to set a border to a triangle",
"I've tried to set a black solid 1px border for triangle: jsFiddle. I write the follwoing markup:\n\n<div>\n</div>\n\n\nand styles\n\ndiv{\n position: absolute;\n left:0px; \n top:0px;\n width: 0;\n height: 0; \n border-left: 5px solid transparent; \n border-right: 5px solid transparent; \n border-bottom: 10px solid red;\n}\n\n\nBut I don't understand how to set the border for the triangle in this case."
]
| [
"html",
"css"
]
|
[
"How to call functions from a vararg-parameter?",
"Is it possible to call functions which are contained in a vararg-parameter?\n\ndef perform(functions:() => Unit*) = ?"
]
| [
"scala"
]
|
[
"mysql recursive query not showing all possible results",
"I am trying to follow Train Routes example as in the link below\nhttps://www.percona.com/blog/2020/02/13/introduction-to-mysql-8-0-recursive-common-table-expression-part-2/\nMy table is as below\nSchema (MySQL v8.0)\nCREATE TABLE `routesy` (\n `id` int(1) DEFAULT NULL,\n `stationA` varchar(6) DEFAULT NULL,\n `stationB` varchar(6) DEFAULT NULL,\n `dist` int(3) DEFAULT NULL\n) ENGINE=InnoDB DEFAULT CHARSET=utf8;\n\n\nINSERT INTO `routesy` (`id`, `stationA`, `stationB`, `dist`) VALUES\n(1, 'DO0182', 'DO0064', 10),\n(2, 'DO0064', 'DO0147', 70),\n(3, 'DO0064', 'DO0049', 80),\n(4, 'DO0064', 'DO0139', 90),\n(5, 'DO0206', 'DO0147', 140),\n(6, 'DO0072', 'DO0139', 150),\n(7, 'DO0008', 'DO0049', 260),\n(8, 'DO0208', 'DO0008', 280);\n\n\nQuery #1\nWITH RECURSIVE paths (cur_path, cur_dest, tot_distance) AS ( \n SELECT CAST(stationA AS CHAR(100)), CAST(stationA AS CHAR(100)), 0 \n FROM routesy\n WHERE stationA='DO0182'\n UNION \n SELECT CONCAT(paths.cur_path, ' -> ', routesy.stationB), routesy.stationB, paths.tot_distance+routesy.dist \n FROM paths, routesy \n WHERE paths.cur_dest = routesy.stationA \n AND NOT FIND_IN_SET(routesy.stationB, REPLACE(paths.cur_path,' -> ',',') ) ) \n SELECT cur_path,cur_dest,tot_distance FROM paths;\n\n\n\n\n\ncur_path\ncur_dest\ntot_distance\n\n\n\n\nDO0182\nDO0182\n0\n\n\nDO0182 -> DO0064\nDO0064\n10\n\n\nDO0182 -> DO0064 -> DO0147\nDO0147\n80\n\n\nDO0182 -> DO0064 -> DO0049\nDO0049\n90\n\n\nDO0182 -> DO0064 -> DO0139\nDO0139\n100\n\n\n\n\nView on DB Fiddle\nI was hoping to see results below as well as these are valid paths. Why does the recursion stop at 3 levels?\nDO0182 -> DO0064 -> DO0147 -> DO0206\nDO0182 -> DO0064 -> DO0139 -> DO0072\nDO0182 -> DO0064 -> DO0049 -> DO0008 -> DO0208"
]
| [
"mysql",
"recursive-query"
]
|
[
"Python: suggestions to improve a chunk-by-chunk code to read several millions of points",
"I wrote a code to read *.las file in Python. *las file are special ascii file where each line is x,y,z value of points.\n\nMy function read N. number of points and check if they are inside a polygon with points_inside_poly.\n\nI have the following questions:\n\n\nWhen I arrive at the end of the file I get this message: LASException: LASError in \"LASReader_GetPointAt\": point subscript out of range because the number of points is under the chunk dimension. I cannot figure how to resolve this problem.\na = [file_out.write(c[m]) for m in xrange(len(c))] I use a = in order to avoid video print. Is it correct?\nIn c = [chunk[l] for l in index] I create a new list c because I am not sure that replacing a new chunk is the smart solution (ex: chunk = [chunk[l] for l in index]). \nIn a statement if else...else I use pass. Is this the right choice?\n\n\nReally thank for help. It's important to improve listen suggestions from expertise!!!!\n\nimport shapefile\nimport numpy\nimport numpy as np\nfrom numpy import nonzero\nfrom liblas import file as lasfile\nfrom shapely.geometry import Polygon\nfrom matplotlib.nxutils import points_inside_poly \n\n\n# open shapefile (polygon)\nsf = shapefile.Reader(poly)\nshapes = sf.shapes()\n# extract vertices\nverts = np.array(shapes[0].points,float)\n\n# open las file\nf = lasfile.File(inFile,None,'r') # open LAS\n# read \"header\"\nh = f.header\n\n# create a file where store the points\nfile_out = lasfile.File(outFile,mode='w',header= h)\n\n\nchunkSize = 100000\nfor i in xrange(0,len(f), chunkSize):\n chunk = f[i:i+chunkSize]\n\n x,y = [],[]\n\n # extraxt x and y value for each points\n for p in xrange(len(chunk)):\n x.append(chunk[p].x)\n y.append(chunk[p].y)\n\n # zip all points \n points = np.array(zip(x,y))\n # create an index where are present the points inside the polygon\n index = nonzero(points_inside_poly(points, verts))[0]\n\n # if index is not empty do this otherwise \"pass\"\n if len(index) != 0:\n c = [chunk[l] for l in index] #Is It correct to create a new list or i can replace chunck?\n # save points\n a = [file_out.write(c[m]) for m in xrange(len(c))] #use a = in order to avoid video print. Is it correct?\n else:\n pass #Is It correct to use pass?\n\nf.close()\nfile_out.close()\n\n\ncode proposed by @Roland Smith and changed by Gianni\n\nf = lasfile.File(inFile,None,'r') # open LAS\nh = f.header\n# change the software id to libLAS\nh.software_id = \"Gianni\"\nfile_out = lasfile.File(outFile,mode='w',header= h)\nf.close()\nsf = shapefile.Reader(poly) #open shpfile\nshapes = sf.shapes()\nfor i in xrange(len(shapes)):\n verts = np.array(shapes[i].points,float)\n inside_points = [p for p in lasfile.File(inFile,None,'r') if pnpoly(p.x, p.y, verts)]\n for p in inside_points:\n file_out.write(p)\nf.close()\nfile_out.close()\n\n\ni used these solution:\n1) reading f = lasfile.File(inFile,None,'r') and after the read head because i need in the *.las output file\n2) close the file \n3) i used inside_points = [p for p in lasfile.File(inFile,None,'r') if pnpoly(p.x, p.y, verts)] instead of \n\nwith lasfile.File(inFile, None, 'r') as f:\n... inside_points = [p for p in f if pnpoly(p.x, p.y, verts)]\n... \n\n\nbecause i always get this error message\n\nTraceback (most recent call last):\nFile \"\", line 1, in \nAttributeError: _exit_"
]
| [
"python",
"performance",
"coding-style",
"matplotlib",
"chunked-encoding"
]
|
[
"Customizing client texts in Unblu",
"I am using Unblu co-browsing tool and would like to customize some client texts.\n\nUnblu FAQ says: \"The message is displayed only on the client side. The texts are easily configurable by properties.\", but does not mention how.\n\nUnblu Text properties Doc describes how to customize some texts, but I cannot find the ones I would like to alter:\n\n\n\"How can I help you?\"\n\"Talk to one of our agents via live chat.\"\n\"Establish co-browsing connection\"\n\"Have one of our agents join you via co-browsing\"\n\n\nI have Unblu 4.2.23."
]
| [
"tomcat"
]
|
[
"How can we show our user LinkedIn recommendations on our website?",
"We want to extract or get the our website user's recommendations on LinkedIn and show it on our website?\n\nI searched and find to use these fields:\n\n(id,first-name,last name,recommendations-received)\n\n\nBut can someone describe to me more how to use it like currently we are getting data in form of response from LinkedIn getting:\n\n$response = $OBJ_linkedin->profile('~:(id,first-name,last-name,picture-urls::(original),email-address,public-profile-url,summary,phone-numbers,im-accounts,twitter-accounts,primary-twitter-account,headline)');\n\n\nShould I add to new fields of recommendations to these response field or do something else?"
]
| [
"cakephp-1.3",
"linkedin-jsapi"
]
|
[
"What is the need of abstract classes ? Why access a derived classes method through its base class ? in C++",
"I am a beginner in C++ object oriented programming. I was studying \"Abstract Classes\" where the example code is:\n\n#include <iostream>\nusing namespace std;\n\nclass Enemy {\n public:\n virtual void attack() = 0;\n};\n\nclass Ninja: public Enemy {\n public:\n void attack() {\n cout << \"Ninja!\"<<endl;\n }\n};\n\nclass Monster: public Enemy {\n public:\n void attack() {\n cout << \"Monster!\"<<endl;\n }\n};\n\n\nint main()\n{\n Ninja n;\n Monster m;\n Enemy *e1 = &n;\n Enemy *e2 = &m;\n\n e1->attack();\n e2->attack();\n\n return 0;\n}\n\n\nWhat I want to understand is why can't I just use the objects of derived classes to access directly the derived class members with \".\" operator (It works, but it is not advised why?).\n\nLike this:\n\nint main()\n{\n Ninja n;\n Monster m;\n Enemy *e1 = &n;\n Enemy *e2 = &m;\n\n //e1->attack();\n //e2->attack();\n n.attack();\n m.attack();\n\n return 0;\n}\n\n\nI know there will be situations where we need to go through the base class to access the members of derived classes (I think this is the normally used by all the programmers), but I have no idea on real world implementation of that kind of cases (Why can't we go direct, why is through pointers of base class?).\n\nI would be very glad if someone can clarify my doubt."
]
| [
"c++",
"inheritance",
"polymorphism"
]
|
[
"\"Allow Local Notification\" Alert is not coming second time in iOS 8 iphone App",
"In order to use local notifications in the app , we need to get the user permission using 'registerUserNotificationSettings' method which will ask for an alert \"Allow Local notifications\". For my application, First time it is showing the alert. But if we delete the app from the device and build it again it is not asking agin. I am using iOS 8 version."
]
| [
"ios",
"iphone",
"notifications"
]
|
[
"How to select all articles from one category and sub-category In MySQL 5",
"Three tables save articles information:\n\ncategories table: \n\nid, lft, rgt, title\n\n\nlft: left value\n\nrgt: right value\n\nlft and rgt value is Nested Set, example:\n\n root \n (0,15)\n / \\\n / \\\n cat1 cat2\n (1,6) (7, 14) \n /| / | \\\n / | / | \\\n / | / | \\\n cat3 cat4 cat5 cat6 cat7\n(2,3) (4,5) (8,9)(10,11)(12,13)\n\n\narticle table: \n\nid, title\n\n\narticle_category_map table: \n\narticle_id, category_id\n\n\nHow to select all articles from one category and sub-category in MySQL?\n\nI expect: \n\n1、When click cat2, display all articles of cat2 and cat5 and cat6 and cat7.\n\n2、When click cat5 , only display all articles of cat5.\n\n3、Wher click root, display all articles of all categories (include cat1, cat2, cat3,cat4, cat5, cat6, cat7...)."
]
| [
"php",
"mysql",
"sql"
]
|
[
"Error compiling secp256k1-php, What is going on?",
"Im trying to run make command to install the secp256k1 php bindings..\nbut I get a compilation error.\nI seriously have no idea why.\nhttps://github.com/Bit-Wasp/secp256k1-php\nstatic void secp256k1_ctx_dtor(zend_resource *rsrc TSRMLS_DC)\n ^\n/Users/admin/Desktop/Code/mxd-blockchain/core/classes/secp256k1-php-0.2/secp256k1/secp256k1.c:620:31: note: to match this '('\nstatic void secp256k1_ctx_dtor(zend_resource *rsrc TSRMLS_DC)\n ^\n/Users/admin/Desktop/Code/mxd-blockchain/core/classes/secp256k1-php-0.2/secp256k1/secp256k1.c:628:55: error: expected ')'\nstatic void secp256k1_pubkey_dtor(zend_resource *rsrc TSRMLS_DC)\n ^\n/Users/admin/Desktop/Code/mxd-blockchain/core/classes/secp256k1-php-0.2/secp256k1/secp256k1.c:628:34: note: to match this '('\nstatic void secp256k1_pubkey_dtor(zend_resource *rsrc TSRMLS_DC)\n ^\n/Users/admin/Desktop/Code/mxd-blockchain/core/classes/secp256k1-php-0.2/secp256k1/secp256k1.c:636:53: error: expected ')'\nstatic void secp256k1_sig_dtor(zend_resource * rsrc TSRMLS_DC)\n ^\n/Users/admin/Desktop/Code/mxd-blockchain/core/classes/secp256k1-php-0.2/secp256k1/secp256k1.c:636:31: note: to match this '('\nstatic void secp256k1_sig_dtor(zend_resource * rsrc TSRMLS_DC)\n ^\n/Users/admin/Desktop/Code/mxd-blockchain/core/classes/secp256k1-php-0.2/secp256k1/secp256k1.c:644:63: error: expected ')'\nstatic void secp256k1_scratch_space_dtor(zend_resource * rsrc TSRMLS_DC)\n ^"
]
| [
"php",
"github",
"makefile",
"secp256k1"
]
|
[
"\"Error: you attempted to set the key `latitude` with the value `37.785834` on an object that is meant to be immutable and has been frozen.\"",
"I'm using the navigator.geolocation API in React Native to set the user coordinates as part of the component state, which the MapView is supposed to use as the region prop, and running getCurrentPosition() throws an error.\n\nI'm not sure how to fix this. The error says this is an immutability issue, although I made sure I used let and const where they're supposed to be.\n\nThis is my initial state:\n\nthis.state = {\n data: {\n name: \"Nie powinieneś tego widzieć.\",\n address: \"Wyślij zrzut ekranu tego widoku do nas na stronie dokosciola.pl w zakładce Kontakt.\",\n url: \"https://dokosciola.pl\",\n coords: {\n latitude: undefined,\n longitude: undefined,\n latitudeDelta: 0.00922 * 1.5,\n longitudeDelta: 0.00421 * 1.5\n },\n hours: [\"8:00\", \"10:00\", \"12:00\"]\n }\n};\n\n\nThis is how I use the geolocating API:\n\nlocateUser = () => {\n navigator.geolocation.getCurrentPosition(\n position => {\n let state = this.state;\n state.data.coords.latitude = position.coords.latitude;\n state.data.coords.longitude = position.coords.longitude;\n this.setState(state);\n console.log(this.state);\n },\n error => Alert.alert(\"Ups!\", `Wystąpił wewnętrzny błąd:\\n${error}`),\n { enableHighAccuracy: true, timeout: 30000, maximumAge: 5000 }\n );\n};\n\n\nI run the locateUser() function before mounting the app, so:\n\ncomponentWillMount() {\n this.locateUser();\n}\n\n\nThis is how I use the MapView component from react-native-maps:\n\n<View style={{ flex: 1 }}>\n <MapView\n style={{ flex: 1 }}\n initialRegion={this.state.data.coords}\n region={this.state.data.coords}\n mapType={\"mutedStandard\"}\n >\n {data.map(element => {\n return (\n <ChurchMarker\n coords={element.coords}\n key={element.id}\n onPress={() => this.update(element)}\n />\n );\n })}\n </MapView>\n</View>\n\n\nChurchMarker is a precooked Marker, also from react-native-maps, and data - a simple array of objects, mocking a potential API response:\n\n[\n {\n id: string,\n name: string,\n address: string,\n url: string,\n coords: {\n latitude: number,\n longitude: number\n },\n hours: string[]\n },\n ...\n]\n\n\nI expect the MapView to focus on the user coordinates as the app mounts, but the error I specified in locateUser() executes, with the following message:\n\nError: you attempted to set the key `latitude` with the value `37.375834` on an object that is meant to be immutable and has been frozen.\n\n\nAfter that there's also a warning:\n\nWarning: Failed prop type: The prop `region.latitude` is marked as required in `MapView`, but its value is `undefined`.\n\n\nand the same for the longtitude. This means the state didn't update.\nAny fixes to this? What am I implementing wrong?"
]
| [
"reactjs",
"react-native",
"geolocation",
"state",
"immutability"
]
|
[
"How to replace the value in a list with their ordinal number?",
"I have a list:\n\na = [[6, 8, 12, 15], [2, 5, 13], [1], [5], [6, 15]]\n\n\nAnd I want to replace all of the value in the inner lists to their ordinal values like:\n\nb = [[0, 0, 0, 0], [1, 1, 1], [2], [3], [4, 4]]\n\n\nI tried this:\n\nfor jj in a:\n for uu in range(0, len(jj)):\n for k,q in enumerate(a):\n jj[uu] == k\n\n\nIt didn't output the list I wanted. How can I accomplish this?"
]
| [
"python",
"python-3.x",
"for-loop",
"replace"
]
|
[
"Running FFMPEG from Shell Script /bin/sh",
"I am trying to setup a Shell Script to work within an automator watch folder...\n\nEverything works with the exception of the Run Shell Scrip portion...\n\nEssentially when a file shows up in the watch folder, it runs the shell scrip which calls FFMPEG and then will move the file to an archive folder for safe keeping. However right now automator is telling me everything worked but now file is being created.\n\nI have the Shell set to /bin/sh and Pass input set to as arguments\n\nHere is my script:\n\nfor f in \"$@\"\ndo\nname=$(basename \"$f\")\ndir=$(dirname \"$f\")\nffmpeg -i \"$f\" -b 250k -strict experimental -deinterlace -vcodec h264 -acodec aac \"$dir/mp4/${name%.*}.mp4\"\necho \"$dir/mp4/${name%.*}.mp4\"\ndone\n\n\nit does echo the correct filename, but does not actually run ffmpeg\n\nI have tried adding -exec before it like I have seen in some scripts but still nothing..."
]
| [
"shell",
"ffmpeg",
"sh"
]
|
[
"Tokenising words in a dictionary Python",
"So I have json file where I import data into python.\n\nI have an agentId field and an agentText field in JSON\n\nSample json:\n\n{\n\"messages\": \n[\n {\"agentId\": \"1\", \"agentText\": \"I Love Python\"},\n {\"agentId\": \"2\", \"agentText\": \"but cant seem to get my head around it\"},\n {\"agentId\": \"3\", \"agentText\": \"what are the alternatives?\"}\n]\n}\n\n\nI'm trying to create a dictionary/key pair value with agentIds and the AgentText fields by doing the following:\n\nWhen I do this, the key value pairs work fine:\n\nimport json\n\nwith open('20190626-101200-text-messages2.json', 'r') as f:\n data = json.load(f)\n\nfor message in data['messages']:\n agentIdandText = {message['agentId']: [message['agentText']]}\n print(agentIdandText)\n\n\nand the output I get this:\n\n{'1': ['I love python']}\n{'2': [\"but cant seem to get my head around it\"]}\n{'3': ['what are the alternatives?']}\n\n\nbut as soon as I try to tokenise the words(below), I start hitting errors\n\nfrom nltk.tokenize import TweetTokenizer\nvarToken = TweetTokenizer()\n\nimport json\n\nwith open('20190626-101200-text-messages2.json', 'r') as f:\n data = json.load(f)\n\nfor message in data['messages']:\n agentIdandText = {message['agentId']: varToken.tokenize([message['agentText']])}\n print(agentIdandText)\n\n\nPartial error message (edited in from comments):\n\nreturn ENT_RE.sub(_convert_entity, _str_to_unicode(text, encoding)) \nTypeError: expected string or bytes-like object\n\n\nSo what I'm expecting is this:\n\n{\n'1': ['I', 'love', 'python'],\n'2': ['but', 'cant', 'seem', 'to', 'get', 'my', 'head', 'around', 'it'],\n'3': ['what', 'are', 'the', 'alternatives?']\n}\n\n\nHow can I achieve this?"
]
| [
"python",
"json",
"dictionary"
]
|
[
"Function field return type in Dart",
"In the following class I want to type the onPress method as a function which returns void. Is there a way to do that?\n\nclass Human {\n var onPress;\n\n Human({\n this.onPress,\n });\n}"
]
| [
"dart",
"flutter"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.