texts
sequence | tags
sequence |
---|---|
[
"How to run clickHandlers on buttons moved from main view component to header bar",
"I've used JRab's example here http://supportforums.blackberry.com/t5/Tablet-OS-SDK-for-Adobe-AIR/App-specific-system-menu/td-p/693... to add a header menu to my app. What I'm having trouble with is executing my functions from the header mennu. For example, my firstView is appHome.mxml. It instantiates a Canvas object that has an erase(). There is a button in appHope.mxml that executes the erase() on the Canvas instance. I'm trying move the Erase button out of my appHome.mxml and into my headerMenu.mxml but don't know how to execute the erase() on the Canvas instance. The first thing I thought to try was click=\"{appHome.myCanvas.erase()}\" but obviously that didn't work. \n\nI asked a similar question yesterday here: Flex executing a function on another view and I accepted the answer before I tried it. The problem is that the headermenu.mxml is not a child of appHome.mxml. They are both children of the main app.mxml. Secondly, the object that has the erase() is in a separate .as class I instantiate in appHome.mxml.\n\nI hope I described my question well enough. Thanks n advance to anyone that can help."
] | [
"apache-flex",
"function",
"click"
] |
[
"React Native onClick is not firing",
"Working on React Native application for Android using NativeBase, I'm stuck with a problem. Despite using arrow function, the onClick()-event in my Button component is not firing, and I can't figure out why. \n\nHere is the code:\n\nimport React from 'react';\nimport {View, Text} from 'react-native';\nimport {withNavigation} from 'react-navigation';\nimport {Button, Header, Icon, Item, Input} from 'native-base';\n\nlet text = '';\n\nclass SearchBar extends React.Component {\n onButtonClick = () => {\n text = 'yes';\n };\n\n render() {\n return (\n <View>\n <Header searchBar rounded>\n <Item>\n <Icon name=\"ios-search\" />\n <Input placeholder=\"Search\" />\n </Item>\n </Header>\n <Button onClick={() => this.onButtonClick()}>\n <Text>Search</Text>\n </Button>\n <Text>Is the button clicked? {text}</Text>\n </View>\n );\n }\n}\n\nexport default withNavigation(SearchBar);\n\n\nCan you help me? In all other components I implemented the event functionalities exactly like in the example above, and these are working. What is the problem with the above one?\n\nI also tried the Button from React-Native instead of NativeBase - same problem."
] | [
"react-native",
"native-base"
] |
[
"Load json data list in Django models",
"I'm tring to convert this json list to django models. but I'm confused. How can I solve this question:\nJson\n[\n {\n "rank": 1,\n "employer": "Walmart",\n "employeesCount": 2300000,\n "medianSalary": 19177\n },\n {\n "rank": 2,\n "employer": "Amazon",\n "employeesCount": 566000,\n "medianSalary": 38466\n }\n]\n\n\nclass Persons(models.Model):\n rank = models.PositiveIntegerField()\n employer = models.CharField(max_length=100)\n employeesCount = models.PositiveIntegerField()\n medianSalary = models.PositiveIntegerField()\n\n verbose_name = 'Person'\n verbose_name_plural = 'Person'"
] | [
"json",
"django"
] |
[
"how to put the current date in bootstrap datetimepicker",
"Currently I have two input boxes one with the current date shown to the user and second one with datetimepicker to select the date and time. I want to combine the functionality of both into a single one where user is presented with the current date and has the opportunity to select date/time from the picker. The problem is that when I try to add the datetimepicker functionality the current date disappears.\n\nBelow is the code for the two input boxes and my early attempt to combine the two.\n\nStart Date: <input type=\"text\" class=\"date-time-input\" name=\"sdate\" id=\"sdatefield1\"/><br/>\n<script type=\"text/javascript\"> \n // window.addEventListener(\"load\", function() {\n var now = new Date();\n var utcString = now.toISOString().substring(0,19);\n var year = now.getFullYear();\n var month = now.getMonth() + 1;\n var day = now.getDate() - 1;\n var hour = now.getHours();\n var minute = now.getMinutes();\n var second = now.getSeconds();\n var localDatetime = \n (day < 10 ? \"0\" + day.toString() : day) + \"-\" +\n (month < 10 ? \"0\" + month.toString() : month) + \"-\" +\n year + \" \" +\n //(day < 10 ? \"0\" + day.toString() : day) + \"T\" +\n (hour < 10 ? \"0\" + hour.toString() : hour) + \":\" +\n (minute < 10 ? \"0\" + minute.toString() : minute) +\n utcString.substring(16,19);\n var datetimeField = document.getElementById(\"sdatefield\");\n datetimeField.value = localDatetime;\n//});\n</script>\n\n<div class=\"container\">\n <div class=\"row\">\n <div class='col-sm-6'>\n <div class=\"form-group\">\n <div class='input-group date' id='datetimepicker1'>\n <input type='text' class=\"form-control\" />\n <span class=\"input-group-addon\">\n <span class=\"glyphicon glyphicon-calendar\"></span>\n </span>\n </div>\n </div>\n </div>\n <script type=\"text/javascript\">\n $(function () {\n $('#datetimepicker1').datetimepicker({\n sideBySide: true,\n format: 'DD-MM-YYYY HH:mm:ss', \n });\n });\n </script>\n </div>\n</div>\n\n\nand combined:\n\n<div class=\"container\">\n <div class=\"row\">\n <div class='col-sm-6'>\n <div class=\"form-group\">\n <div class='input-group date' id='sdatefield'>\n <input type='text' class=\"form-control\" />\n <span class=\"input-group-addon\">\n <span class=\"glyphicon glyphicon-calendar\"></span>\n </span>\n </div>\n </div>\n </div>\n <script type=\"text/javascript\">\n $(function () {\n $('#sdatefield').datetimepicker({\n sideBySide: true,\n format: 'DD-MM-YYYY HH:mm:ss', \n });\n });\n </script>\n </div>\n</div>\n\n<script type=\"text/javascript\"> \n // window.addEventListener(\"load\", function() {\n var now = new Date();\n var utcString = now.toISOString().substring(0,19);\n var year = now.getFullYear();\n var month = now.getMonth() + 1;\n var day = now.getDate() - 1;\n var hour = now.getHours();\n var minute = now.getMinutes();\n var second = now.getSeconds();\n var localDatetime = \n (day < 10 ? \"0\" + day.toString() : day) + \"-\" +\n (month < 10 ? \"0\" + month.toString() : month) + \"-\" +\n year + \" \" +\n //(day < 10 ? \"0\" + day.toString() : day) + \"T\" +\n (hour < 10 ? \"0\" + hour.toString() : hour) + \":\" +\n (minute < 10 ? \"0\" + minute.toString() : minute) +\n utcString.substring(16,19);\n var datetimeField = document.getElementById(\"sdatefield\");\n datetimeField.value = localDatetime;\n//});\n</script>\n\n\nThanks for help"
] | [
"javascript",
"html",
"bootstrap-datetimepicker"
] |
[
"Python 3 POST request to handle form data",
"I can't figure out how to correctly set up a POST request with the following data:\n\nGeneral\nRequest URL: https://myurl.com/install/index.cgi\nRequest Method: POST\n\nRequest Headers\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3\nAccept-Encoding: gzip, deflate, br\nAccept-Language: en-US,en\nCache-Control: max-age=0\nConnection: keep-alive\nContent-Length: 48\nContent-Type: application/x-www-form-urlencoded\nHost: myurl.com\nOrigin: https://myurl.com\nReferer: https://myurl.com/install/\nUpgrade-Insecure-Requests: 1\nUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)\n\nForm Data\npage: install\nstate: STATUS\n\n\nI can do the following:\n\nimport requests\n\nheaders = {\"Accept\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\",\n \"Accept-Encoding\":\"gzip,deflate,br\",\n \"Accept-Language\":\"en-US,en;q=0.8\",\n \"Cache-Control\":\"max-age=0\",\n \"Connection\":\"keep-alive\",\n \"Content-Length\":\"48\",\n \"Content-Type\":\"application/x-www-form-urlencoded\",\n \"Host\":\"myurl.com\",\n \"Origin\":\"https://myurl.com\",\n \"Referer\":\"https://myurl.com/install/?s=ROM\",\n \"User-Agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36\"}\n\nf = requests.put(path, headers=headers)\n\n\nBut how do I handle the form data? Under the form data there is a page: install and a state: STATUS.\n\nHow do I include this on my POST request?"
] | [
"python",
"python-3.x",
"python-requests"
] |
[
"\"The tenant for tenant guid ... does not exist\" when using client credentials flow (daemon) to access Microsoft Graph API",
"I want to access Microsoft Graph periodically from a console application in order to copy messages from an Outlook mailbox to a database. \nIn order to authenticate programmatically, I had to use the Microsoft Graph's \"Client Credentials Flow\".\n\nThese are the steps I had to take:\n\n\nRegister an App in the Azure portal and create a Client Secret for it.\nAdd all the permissions I need and grant them access:\n\n\nHave an Admin confirm those permissions by accessing it for the first time. This is done using the following URL: \n\nhttps://login.microsoftonline.com/{tenant}/v2.0/adminconsent\n?client_id={app id}\n&state=1234\n&redirect_uri=https://login.microsoftonline.com/common/oauth2/nativeclient\n&scope=https://graph.microsoft.com/.default\n\n\nI received the following response:\n\nadmin_consent: True\ntenant: ca566779-1e7b-48e8-b52b-68**********\nstate: 12345\nscope**: scope: https://graph.microsoft.com/User.Read https://graph.microsoft.com/.default\n\n\n(The scope might explain the problem described later here: Why do I only get User.Read when I've configured 13 different permissions??)\n\n\nGet an access token (with success!):\n\n\nTry to read users (with success):\n\n\nTry to read my own emails (without success):\n\n\nTry to read somebody else's emails (the user was invited to access the app as a guest, but still, no success):\n\n\n\n\nI don't understand why I can't read Messages but I can read Users. It seems the permissions were completely ignored (I confirmed that I don't need any permission to read the users).\n\nUPDATE\n\nThis is my tenant name:\n\n\n\nThese are the users added to the tenant:\n\n\n\nImportant: I don't own an office 365 subscription in my Azure AD. All these emails belong to a different AD.\n\nThe previous question "The tenant for tenant guid does not exist" even though user is listed on users endpoint? is similar to mine but I believe this is not a duplicate as my problem is slightly different and the proposed solution uses OAuth1 (I am using OAuth2)."
] | [
"microsoft-graph-api",
"microsoft-graph-mail"
] |
[
"NFC tag redirect to download app from Play Store",
"I developed a NFC app in android. How do i do if i want,once the user scan the tag,the tag redirect the user to playstore to download my app if the user haven't install my app. If user already installed my app it should open the app instead redirect to play store. Any advice or link is highly appreciated. Thanks"
] | [
"android",
"nfc",
"ndef"
] |
[
"How do I check that each value is being pushed to the second array",
"I have an array of 6 values, of which want 4 unique random values.\nCurrently, I retrieve 4 random values from the list, but not unique.\nWhen I try and check the value already exists it doesn't seem to work correctly.\nIs my logic what is wrong? If so could someone point me in the right direction?\n\r\n\r\nconst Teams = [\"Tetra\", \"Tiny Tetra\", \"Tetra terriers\", \"OneSeasonWonders\", \"Yurtie Ahern\", \"Liverpool\"];\n\nfor (let i = 0; i < 4; i++) {\n let pickedTeam = [];\n let randomTeam = Math.floor(Math.random() * Teams.length);\n pickedFromArray = Teams[randomTeam];\n //console.log(pickedFromArray);\n if (pickedTeam.includes(pickedFromArray, 0)) {\n randomTeam = Math.floor(Math.random() * Teams.length);\n } else {\n pickedTeam.push(pickedFromArray);\n }\n console.log(\"Slot \" + i + \" - \" + pickedTeam);\n}"
] | [
"javascript",
"arrays"
] |
[
"ASP.NET MVC a better way to post model ID?",
"I have a ViewModel I am binding to a view:\n\nProductViewModel model = Mapper.Map<Product, ProductViewModel>(product);\nreturn View(model);\n\n\nThe view (and viewmodel) is used to edit a Product so ProductViewModel has an ID property that corresponds to the ID in the database.\n\nAnd to Post the ID back to the Controller I am doing this in my form on the view:\n\[email protected](x => x.Id)\n\n\nEven though this works - I was wondering whether there was a better way to Post the ID back to the Controller? Route Values maybe? or is this a fairly standard pattern/approach?"
] | [
"asp.net",
"asp.net-mvc",
"post"
] |
[
"Entity inheritance in android room",
"I have a parent class Queue which has following fields:\n\n\nName\nType\nStatus\n\n\nBased on the type, I have decomposed Queue into further subclasses, each of which has its own extra fields. For example:\n\nProductionQueue extends Queue { startDate, endDate }\nShippingQueue extends Queue { shippingDate, shippingAgent }\n...\n\n\nI have created Queue as a base class in android studio and extending my subclasses from it but the code fails to compile and complains about missing fields (subclass fields). Here is an example:\n\n@Entity(tableName = \"queue\")\npublic class Queue {\n int id;\n String name;\n int type;\n int status;\n}\n\n@Entity\npublic class ProductionQueue extends Queue {\n String startDate;\n String endDate\n}\n\n@Dao\npublic interface ProductionQueueDao extends BaseDao<ProductionQueue> {\n @Query(\"SELECT * FROM queue WHERE id = :queueID\")\n LiveData<List<ProductionQueue>> findByID(Long queueID);\n}\n\n\n\nOn compilation I receive: error: The columns returned by the query does not have the fields [startDate, endDate] in com.example.room.ProductionQueue even though they are annotated as non-null or primitive. Columns returned by the query: [id,name,type,status].\n\n[id,name,type,status] are coming from parent class while [startDate, endDate] are subclass fields.\n\nOn various occasions in my application, I would only list the queue names, type, and status and I would prefer to keep queue data in a single table for quick querying.\n\nI can create sub tables for individual subclasses and use relations but if Room allows inheritance all of this can be easily avoided. Does room support such inheritance if yes how can I make it work?\n\nThanks."
] | [
"android",
"android-room"
] |
[
"How to create a chunk in 3D world?",
"i am working on voxel based game engine, in which i need to have chunks. I have tried to read a Chunk class from minecraft, but i cant understand it. \nBy chunk i mean: 16x16x256 array of blocks\n\nSo my question is: How chunk works and how does it store data?"
] | [
"java",
"minecraft",
"voxel"
] |
[
"iCloud Enable/Disable using toggle from application side",
"I want to make enable/disable sync my core data with iCloud. Is it good way to do?\nCan you share logic what should i have to do?\nHere i am trying to remove and reinsert persistence store again when switch enable/disable.\n\nThanks,"
] | [
"iphone",
"core-data",
"icloud"
] |
[
"Automatic sync realm with server",
"Im using realm with some api and i want to reach the behavior when i delete object at server it should be automatically deleted on the app.\nWith CoreData there is a RestKit framework that do the trick, does realm have something similar. I ve tried ObjectMapper and Alamofire with no success."
] | [
"ios",
"swift",
"restkit",
"realm"
] |
[
"unable to store array's multiple values in one single insert query in mysql database",
"Edited:\nIn my application I want to store two array value in a two column with a single query. I am stuck here.Last two column value insert is my problem.I tried many ways but it's does not work exactly what i want. \n\nin database that question id is same only other two things r different. My array values goes to the last column of database. I am unable to do that.\n\nfrom here data goes\n\n<form method=\"post\" action=\"questionmadddb.php\">\n<input name='questionid' value='<?php echo $questionid?> \n<?php\nif(isset($_POST['num'])){\n $num=$_POST['num'];\n for ($i=1; $i <=$num ; $i++) { \n echo \"<tr>\n <td><label>OPTION \" . $i . \"</label></td>\n <td><input class='form-control' name='txtfllname[]'></td>\n <td><input class='form-control' name='txtflrname[]'></td>\n </tr>\";\n }\n}\n?>\n<td colspan=6><button class=\"btn btn-success btn-lg btn-block\" type=\"submit\" >ADD QUESTION</button></td>\n\n\n\n\nhere is query\n\n<?php\n\nif(isset($_POST[\"txtfllname\"]) && is_array($_POST[\"txtfllname\"])){ \n$capture_field_vals =\"\";\nforeach($_POST[\"txtfllname\"] as $key => $text_field){\n $a=(\"INSERT INTO qflinfo (questionid,qfllid,qfllname,qflrid,qflrname,status) VALUES ('$questionid','$i','$text_field',0)\");\n $i++;\n //echo $a;\n mysqli_query($conn,$a) or die(mysqli_error($conn));\n}\n\n}?>\n\n\nhow to get last two column data and insert?please help me...How can I do that?"
] | [
"php",
"mysql",
"html"
] |
[
"Connect to remote Postgres server via SQLAlchemy",
"I am trying to send some commands to a remote Postgres server using SQLAlchemy but each time I receive an error.\n\nPlease note that I can connect to the remote Postgres using SSH username and password to login to the server. For that I have used my local terminal, PuTTY and WinSCP so the problem appears to be in the Python code I have written\n\n # create postgres engine to connect to the database\n engine = create_engine('postgres://server_username:server_password@server_name:port/database')\n\n with engine.connect() as conn:\n ex = conn.execute(\"SELECT version();\")\n conn.close() # not needed but keep just in case\n print(ex)\n\n\nRunning the code above yields the following error:\n\nsqlalchemy.exc.OperationalError: (psycopg2.OperationalError) SSL SYSCALL error: Connection reset by peer (0x00002746/10054)\nexpected authentication request from server, but received S\n\n\nI have also tried adding the SSL verification parameter as follows\n\ncreate_engine('postgres://server_username:server_password@server_name:port/database?sslmode=verify-full')\n\n\nwhich returned the error \n\nsqlalchemy.exc.OperationalError: (psycopg2.OperationalError) root certificate file \"C:\\Users\\aris.pavlides\\AppData\\Roaming/postgresql/root.crt\" does not exist\nEither provide the file or change sslmode to disable server certificate verification.\n\n\nat which point I had nothing to lose so I disabled certificate verification altogether \n\ncreate_engine('postgres://server_username:server_password@server_name:port/database?sslmode=disable')\n\n\nwhich returned the initial error message.\n\nDo you have any ideas on how I can modify the code to make it work?"
] | [
"python",
"postgresql",
"sqlalchemy"
] |
[
"How to read complete IP frames from TCP socket in Python?",
"I need to read a complete (raw) IP frame from a TCP stream socket using Python. Essentially I want an unmodified frame just as if it came off the physical line, including all the header information.\n\nI have been looking into raw sockets in Python but I have ran into some issues. I don't need to form my own packets, I simply need to read and forward them verbatim.\n\nSo, how can I read an entire IP frame (incl. header) from an existing TCP socket (in Python)?\n\nPreferably I'd like to use only standard libraries. Also, I am on a Linux host.\n\nThanks!"
] | [
"python",
"linux",
"sockets",
"raw-sockets"
] |
[
"Subscribing to HttpInterceptor errors, angular 5",
"The application I am working on previously had a HTTP interceptor which had been manually written - it looked a bit like this:\n\n@Injectable()\nexport class HttpInterceptorService extends Http {\n\n onError: EventEmitter<Response> = new EventEmitter();\n\n constructor(backend: XHRBackend, defaultOptions: RequestOptions) {\n super(backend, defaultOptions);\n }\n\n request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {\n return super.request(url, options).catch((error: Response) => {\n this.onError.emit(error);\n // other stuff\n return Observable.throw(error);\n });\n }\n}\n\n\nThe onError EventEmitter is important, as a service called notifications.service.ts used that to subscribe to it and update the UI if an error occurred.\n\nI have been working on upgrading this application to Angular 5, which has involved removing all the HttpModule code and replacing it with HttpClient. I also had to update the HttpInterceptorService, so it now looks like this:\n\n@Injectable()\nexport class HttpInterceptorService implements HttpInterceptor {\n\n onError: EventEmitter<HttpErrorResponse> = new EventEmitter();\n\n public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {\n return next.handle(request)\n .catch((error: HttpErrorResponse) => {\n this.onError.emit(error);\n return Observable.throw(error);\n });\n }\n}\n\n\nThe Interceptor and HttpClientModule are implemented in the app.module.ts in the standard way (according to the docs). This works well, and the interceptor is used when the application runs and HTTP requests are made. However, to make it work, I had to remove the notification service, as when I try to run it with that service injected into a few components, a console error simply says: No provider for HttpInterceptorService!. I have tried adding a provider for the HttpInterceptorService to the relevant module files, but it hasn't worked. \n\nSo my question is, what is the standard way of subscribing to the errors caught in the HttpInterceptor and consuming them in another service?"
] | [
"javascript",
"angular",
"typescript"
] |
[
"Modify an AccuRev transaction comment",
"In AccuRev, is there a way to change the comment I provided for a transaction?"
] | [
"accurev"
] |
[
"Segfault when joining paths",
"I wrote this function to join two paths in C;\n\nvoid *xmalloc(size_t size)\n{\n void *p = malloc(size);\n if (p == NULL) {\n perror(\"malloc\");\n exit(EXIT_FAILURE);\n }\n return p;\n}\n\nchar *joinpath(char *head, char *tail)\n{\n size_t headlen = strlen(head);\n size_t taillen = strlen(tail);\n char *tmp1, *tmp2;\n\n char *fullpath = xmalloc(sizeof(char) * (headlen + taillen + 2));\n tmp1 = head;\n tmp2 = fullpath;\n while (tmp1 != NULL)\n *tmp2++ = *tmp1++;\n *tmp2++ = '/';\n tmp1 = tail;\n while (tmp1 != NULL);\n *tmp2++ = *tmp1++;\n return fullpath;\n}\n\n\nBut I am getting segfault on first while loop, at *tmp2++ = *tmp1++;. Any ideas?"
] | [
"c",
"string",
"segmentation-fault",
"concatenation"
] |
[
"Laravel one to many relationship trouble",
"have 15 one to many tables in DB and everything works fine, but now when i tried to add one more table i got this error. I tried 5-6 solutions from google but i cant resolve problem. artikal_naruzba table work fine. My all tables are empty!\n\nError\n\n[Illuminate\\Database\\QueryException]\n\n SQLSTATE[HY000]: General error: 1215 Cannot add`enter code here` foreign key constraint (SQL: alter table `Narudzbe` add constraint narudzbe_kupac_id_foreign foreign key (`kupac_id`) references `kupci` (`id`))\n\n [PDOException]\n SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint\n\n\nTable Narudzba\n\npublic function up()\n {\n Schema::create('Narudzbe', function(Blueprint $table)\n {\n $table->increments('id');\n $table->integer('kupac_id')->unsigned();\n $table->foreign('kupac_id')->unsigned()->references('id')->on('kupci');\n $table->integer('BrojNarudzbe');\n $table->boolean('Status')->default(1);\n $table->boolean('Otkazano')->default(0);\n $table->timestamps();\n });\n\n\n\n Schema::create('artikal_naruzba', function(Blueprint $table){\n $table->increments('id');\n $table->integer('artikal_id')->unsigned()->index();\n $table->foreign('artikal_id')->references('id')->on('artikli')->onDelete('cascade');\n\n $table->integer('narudzba_id')->unsigned()->index();\n $table->foreign('narudzba_id')->references('id')->on('Narudzbe')->onDelete('cascade');\n\n $table->timestamps();\n });\n\n }\n\n\nTable Kupac\n\npublic function up()\n {\n Schema::create('kupci', function(Blueprint $table)\n {\n $table->increments('id');\n $table->string('ime');\n $table->string('prezime');\n $table->string('email')->unique();\n $table->string('lozinka', 60);\n $table->string('telefon', 30);\n $table->timestamps();\n });\n }\n\n\nNaruzba model\n\nclass Narudzba extends Model {\n\n protected $table = 'Narudzbe';\n\n public function kupac(){\n return $this->belongsTo('App\\Kupac');\n }\n\n public function artikli(){\n\n return $this->belongsToMany('App\\Artikal');\n }\n}\n\n\nKupac Model\n\nclass Kupac extends Model {\n\n protected $table = 'kupci';\n\n public function narudzba(){\n return $this->hasMany('App\\Narudzba');\n }\n\n}"
] | [
"laravel",
"laravel-5"
] |
[
"How to generate new aspx page dynamically?",
"I couldn't find an answer for my question anywhere.\n\nI'm building a website shop in webforms aspx, i created a page which insert new product to my database.\n\nhow can i do, that once i created a product, it will automatically create a new page for that product (with design that i will pre-define for all new products)?\n\n(same idea for example in facebook, once a new user register, the system automatically create a new page for that user wall/timeline)"
] | [
"asp.net",
"webforms",
"auto-generate"
] |
[
"Is sequence unpacking atomic?",
"Is sequence unpacking atomic? e.g.:\n\n(a, b) = (c, d)\n\n\nI'm under the impression it is not.\n\nEdit: I meant atomicity in the context of multi-threading, i.e. whether the entire statement is indivisible, as atoms used to be."
] | [
"python",
"variable-assignment",
"atomic"
] |
[
"Display SSRS Report in WPF",
"I am trying to get a report from SQL Server Reporting Services to appear on a WPF application. The server has SQL Server 2014.\n\nI added a ReportViewer to my XAML as I had seen in examples:\n\n<Window x:Class=\"WPFReport.MainWindow\"\n ...\n xmlns:rv=\"clr-namespace:Microsoft.Reporting.WinForms;assembly=Microsoft.ReportViewer.WinForms\"\n Title=\"MainWindow\" Height=\"500\" Width=\"850\">\n\n ...\n\n <WindowsFormsHost>\n <rv:ReportViewer x:Name=\"_reportViewer\" />\n </WindowsFormsHost>\n\n ...\n\n</Window>\n\n\nThe code I see everywhere to connect the ReportViewer to a report is like this:\n\npublic MainWindow()\n{\n InitializeComponent();\n\n _reportViewer.Load += ReportViewer_Load;\n}\n\nprivate void ReportViewer_Load(object sender, EventArgs e)\n{\n if(!_isReportViewerLoaded)\n {\n _reportViewer.ProcessingMode = ProcessingMode.Remote;\n _reportViewer.ServerReport.ReportServerUrl = \n new Uri(\"http://{MyReportServer}/ReportServer/\");\n _reportViewer.ServerReport.ReportPath = \"/Reports/{MyReportName}.rdl\";\n\n _reportViewer.RefreshReport();\n\n _isReportViewerLoaded = true;\n }\n}\n\n\nThe report I am trying to access, however, appears to be accessed in a different way.\n\nI can access it in a browser by going through a ReportViewer.aspx file:\n\nhttp://{MyReportServer}/ReportServer/Pages/ReportViewer.aspx?%2f{MyReportName}\n\n\nIs there a way to access my report in a ReportViewer?"
] | [
"c#",
"wpf",
"reporting-services"
] |
[
"Implement SQL Server 2016 Snapshot Isolation in C#/ADO.NET for SELECT queries",
"In order to prevent long read operations from blocking short, frequent write operations in my existing mixed OLTP/reporting web application backed by SQL Server 2016, I want to use Snapshot Isolation on a few long-running queries. The queries have already been well indexed and just take a long time to run due to large amounts of data, and while I may use RCSI later, I would like to start by using the less invasive Snapshot Isolation.\n\nMy question is: how do I enable Snapshot Isolation on my SELECT queries in C#? It seems I would have to wrap my select queries in a transaction, which just feels totally wrong.\n\n List<Cat> cats = new List<Cat>();\n TransactionOptions transactionOption = new TransactionOptions\n {\n IsolationLevel = IsolationLevel.Snapshot\n };\n using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Required, transactionOption))\n {\n using (SqlConnection sqlConnection = new SqlConnection(databaseConnectionString))\n {\n using (SqlCommand sqlCommand = sqlConnection.CreateCommand())\n {\n sqlCommand.CommandText = \"proc_Select_A_Billion_Cats\";\n sqlCommand.CommandType = CommandType.StoredProcedure;\n\n sqlConnection.Open();\n\n using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())\n {\n while (sqlDataReader.Read())\n {\n // SOME CODE HERE can read the Cat object in from data reader\n\n // Add this cat to the collection\n cats.Add(cat);\n }\n }\n }\n }\n }\n\n\n\nFrom http://www.levibotelho.com/development/plugging-isolation-leaks-in-sql-server/ I can see that in SQL Server 2014 and later the isolation level will be reset when the connection is returned to the pool, so that's good.\n\nBut can it be right to wrap a stored proc that does only SELECT in an ADO.NET transaction? Is there not some better way than this to implement Snapshot Isolation in C#?"
] | [
"c#",
"sql-server",
"ado.net",
"transactionscope",
"isolation-level"
] |
[
"OpenOffice Automation delphi",
"We want to automate OpenOffice, When i search on internet couldnot find a end-to-end help for that and delphi examples are too less. Our intention is to insert document variables and replace the document variable with there values and copying paragraphs etc.\n\nCan any one help me to find an end-to-end help or a pas file like word2000.pas where i can find all the word routines.\n\nThanks,\nBasil"
] | [
"delphi",
"automation",
"wrapper",
"openoffice.org"
] |
[
"How to override/replace GWT class in Maven project?",
"I want to make some changes in AbstractCellTable class (change visibility of some fields and methods to protected or public etc). I've cloned AbstractCellTable.java file, made changes in it and put it into my Eclipse project 'commons' (with same package name com.google.gwt...).\n\nSome other GWT projects use commons project. They are in the same Eclipse workspace and use source dependency from commons. I can compile them and use replaced AbstractCellTable class using standard GWT Eclipse plugin.\n\nThe problem appears when I want to change my projects to Maven ones. There is no problem with installation of commons project (mvn clean install). Changed source file of AbstractCellTable.java appears in generated jar file. But when I'm compiling dependant projects I get compile errors. I don't have stacktrace now, but the reason of this problem lies in using by GWT compiler original version of AbstractCellTable class. Errors show that commons.jar has compile errors (sic!) even if was installed properly earlier.\n\nI've already tried to change ordering of dependencies in pom.xml, but it doesn't work. I'm thinking about installing own version of gwt-user.jar in my repo, but it won't be easy, as GWT project don't rely on Maven.\n\nIs there any better solution to replace original GWT classes?"
] | [
"java",
"maven",
"gwt",
"maven-3"
] |
[
"Problems to encode PHP data with json_encode and use it in js file",
"Okay, I read a bunch of questions on StackOverflow but didn't seem to solve my problem.\n\nI have a php file like this one:\n\n <?php\n require \"config.php\";\n try {\n $conn = new PDO(\"mysql:host=\" . DB_SERVER . \";dbname=\" . DB_NAME, DB_USERNAME, DB_PASSWORD);\n }\n catch(PDOException $e) {\n die(\"Database connection could not be established.\");\n }\n $conn->exec(\"SET NAMES UTF8\");\n $sql = \"SELECT result.year, SUM(result.grade) AS year_total_points\n FROM (\n SELECT *\n FROM students AS s\n INNER JOIN points AS p\n ON s.fn = p.student_fn\n ) result\n GROUP BY result.year\n ORDER BY year_total_points DESC\";\n $query = $conn->query($sql);\n if($query->rowCount() > 0) {\n $data = array (\n \"years\" => [],\n \"years_total_points\" => [],\n );\n while ($row = $query->fetch(PDO::FETCH_ASSOC)) {\n $data['years'][] = $row['year'];\n $data['years_total_points'][] = $row['year_total_points'];\n }\n echo json_encode($data);\n }\n else {\n echo mysql_error();\n }\n\n $conn = null;\n ?>\n\n\nLong story short I make a query to the database and get a table with column year and column year_total_points. I want to store the data in an associative array so I can pass it to the js file. Because I later in the js file need an array of all years as strings and an array of all points also as strings, I decided to store them in an associative array. But I think that json_encode doesn't encode it as it should because executing the following code:\n\n function success(data){\n var barChartData = {\n labels : data[\"years\"],\n datasets : [\n {\n fillColor : \"rgba(151,187,205,0.5)\",\n strokeColor : \"rgba(151,187,205,0.8)\",\n highlightFill : \"rgba(151,187,205,0.75)\",\n highlightStroke : \"rgba(151,187,205,1)\",\n data : data[\"years_total_points\"]\n }\n ]\n }\n var ctx = document.getElementById(\"myChart\").getContext(\"2d\");\n window.myBar = new Chart(ctx).Bar(barChartData, {\n responsive : true\n });\n }\n\n function error(){\n alert('Error!');\n }\n\n window.onload = function(){\n $.ajax({url: \"http://localhost/year_comparison.php\"}).done(success).error(error);\n }\n\n\nit says that data[\"years\"] is undefined and I would expect it to be something like [\"2011\", \"2012\", \"2013\"]. Everything with the query is ok because when I added alert(data); I got a result {\"years\":[\"2011\"],\"years_total_points\":[\"85.98\"]}. But alert(data[\"years\"]) says undefined. Any help to solve this issue would be greatly appreciated."
] | [
"javascript",
"php",
"arrays",
"json",
"chart.js"
] |
[
"How to pass arguments to the function without binding in React-Native",
"So, i've readed that doing something like this\n\n<SomeButton onPress={() => { this.someFunction(args)}} />\n\nis bad because it is creating a new instance of function for each render cycle.\n\nBut how do i pass args in React-Native then?"
] | [
"javascript",
"reactjs",
"react-native"
] |
[
"hierarchical clustering on correlations in Python scipy/numpy?",
"How can I run hierarchical clustering on a correlation matrix in scipy/numpy? I have a matrix of 100 rows by 9 columns, and I'd like to hierarchically cluster by correlations of each entry across the 9 conditions. I'd like to use 1-pearson correlation as the distances for clustering. Assuming I have a numpy array X that contains the 100 x 9 matrix, how can I do this?\n\nI tried using hcluster, based on this example:\n\nY=pdist(X, 'seuclidean')\nZ=linkage(Y, 'single')\ndendrogram(Z, color_threshold=0)\n\n\nHowever, pdist is not what I want, since that's a euclidean distance. Any ideas?\n\nthanks."
] | [
"python",
"numpy",
"cluster-analysis",
"machine-learning",
"scipy"
] |
[
"Missing publisher name in windows Dialog during installation",
"I have created installer executable using Install4j IDE. When I am taking the executable and running the executable on some other system. I am getting a warning dialog. On which Publisher name is missing.\n\nPlease refer the attached image.\n\n\n\nI have already set the publisher name in application info tab under general setting in install4j IDE.\n\nHow can I get publisher name on windows dialog?"
] | [
"windows",
"windows-7",
"windows-7-x64",
"install4j"
] |
[
"Xamarin Android Project failed to create",
"When I am creating a DroidBlankAppApplication, Visual Studio just says 'Creating project 'App1'... project creation failed.' There is no details in the Output window. No errors in the error window. And I can't find anywhere to see what the exact issue is."
] | [
"android",
"xamarin",
"visual-studio-2017"
] |
[
"Python. Libtcodpy. Linux (Lubuntu) Attribute Error",
"I've had to fight to get this library to run. I can import it and the samples_cpp works fine. But when I run my roguelike, I get this error:\n\n> python main.py\nTraceback (most recent call last):\n File \"main.py\", line 3, in <module>\n import libtcodpy as libtcod\n File \"/home/slumking/Documents/Python/scripts/hm_game-master/libtcodpy.py\", line 479, in <module>\n _lib.TCOD_console_has_mouse_focus.restype = c_bool\n File \"/usr/lib/python2.7/ctypes/__init__.py\", line 378, in __getattr__\n func = self.__getitem__(name)\n File \"/usr/lib/python2.7/ctypes/__init__.py\", line 383, in __getitem__\n func = self._FuncPtr((name_or_ordinal, self))\nAttributeError: ./libtcod.so: undefined symbol: TCOD_console_has_mouse_focus"
] | [
"python",
"libtcod"
] |
[
"Python CSV Module read and write simultaneously",
"I have two .csv files I am looking up data in one (file a) and matching it to the other (file b) once I find the appropriate row in b I want to write to a specific cell in the appropriate row. Additionally I need to iterate over this so I will likely be writing to each row in file b potentially several times. \n\ncan I write to a csv file and then read it over and over again?\n\ndef match(name, group, cnum):\n for data in masterfile_list:\n if (name in data[0]):\n if (group in data[4]):\n if (cnum == \"112\"):\n data[7] = cnum\n elif (cnum == \"111\"):\n data[8] = cnum\n elif (cnum == \"110\"):\n data[9] = cnum\n elif (cnum == \"109\"):\n data[10] = cnum\n elif (cnum == \"108\"):\n data[11] = cnum\n elif (cnum == \"107\"):\n data[12] = cnum\n elif (cnum == \"106\"):\n data[13] = cnum\n elif (cnum == \"105\"):\n data[14] = cnum\n elif (cnum == \"104\"):\n data[15] = cnum\n elif (cnum == \"103\"):\n data[16] = cnum\n elif (cnum == \"102\"):\n data[17] = cnum\n elif (cnum == \"101\"):\n data[18] = cnum \n\n\nI would ideally write/replace the line that matches."
] | [
"python",
"csv"
] |
[
"Instantiate generic type from variable",
"I would like to instantiate a new object where the type and generic type are defined as variables. The final result could look like the newListOfObjects created manually here:\n\nvar newListOfObjects = new List<TabViewModel>();\n\n\nWhere TabViewModel is the following object:\n\npublic class TabViewModel\n{\n public string Title { get; set; }\n public int TabOrder { get; set; }\n}\n\n\nThe problem comes when trying to instantiate the new object using only variables. We have one generic type variable, genericType, which is an interface and one list of type arguments, listOfTypeArgs. In the example above the generic type would be IList and the arguments would be TabViewModel. It would then look like following (note, some code is psudo for easier understanding):\n\nType genericType = IList'1;\nType[] listOfTypeArgs = TabViewModel;\nvar newObject = Activator.CreateInstance(genericType.MakeGenericType(listOfTypeArgs));\n\n\nIt is then obvious that I get the error 'System.MissingMethodException' with the note that I can not instantiate a variable from an interface. \n\nHow can I convert the interface to its represenative so that I can\ninstantiate the new object?\n\nNOTE: I can not change Type genericType = IList'1; nor\n Type[] listOfTypeArgs = TabViewModel;"
] | [
"c#",
"variables",
"object",
"generics",
"instantiation"
] |
[
"Do spaces matter when using .text in VBA?",
"I have two loops going through rows and columns in excel with a large if or statement checking if there's a certain string in one of the columns. However, even though I've added Option Compare Text to get rid of case sensitivity, sometimes my code will skip over columns even if they have the specified text in them. \n\nRight now, my statement looks like this:\n\n If worksheet.Cells(j, i).Text=\"text\" or worksheet.Cells(j, i).Text = \"other text\"...\n\n\nI figured it could be that spaces are causing the problem, but after testing, it seems arbitrary. Is there something wrong with my If statement, or is there possibly something else in the excel sheets it's not working on that I haven't covered? (Like text being italicized or bold). \n\nFor the record, I'm not using like or instr because some of the columns may contain pieces of the string but may not be what I'm looking for."
] | [
"vba",
"excel"
] |
[
"Need help vectorizing code or optimizing",
"I am trying to do a double integral by first interpolating the data to make a surface. I am using numba to try and speed this process up, but it's just taking too long. \n\nHere is my code, with the images needed to run the code located at here and here."
] | [
"python",
"optimization",
"numba"
] |
[
"Google Places API AutoComplete error Android",
"I followed google tutorial here to implement an autocomplete searching in Android. once I constructed the app and run it I get this error \n\n returned from sslSelect() with result 0, error code 2\n returned from sslSelect() with result 1, error code 2\n\n\nany clue ?\n\nThanks in advance"
] | [
"android",
"google-places-api"
] |
[
"Probability of predicted image in a segmentation with model keras",
"so we are building a segmentation (keras model). Gray-scale image with a black and white mask.\nThe mask can be totally black, we manually classify it then as positive else as negative.\nAfter the model.predict we look at the result.\nIf the image contains a white pixel we manually classify it as negative, if it's totally black it's positive. So we get a numpy array like [1,1,1,0,.....]\nI was wondering if it's possible to get a probability on each pixel or image that the model predicted.\nTo be able to use the ROC curve (sklearn.metrics.roc_curve)\nI tried first to put in the Y_train (manually classification) and prediction (also manually classification) in the ROC curve but it keeps giving 0.5\nAny thoughts?"
] | [
"keras",
"image-segmentation",
"roc"
] |
[
"How can I combine two similiar javascript functions?",
"Is there a way to combine the following two instructions into more efficient code?\n\n $('.sandwiches').mouseleave(function () {\n $('.sandwiches').hide();\n});\n$('.food').mouseleave(function () {\n $('.sandwiches').hide();\n});"
] | [
"javascript",
"performance"
] |
[
"Using different major versions of the same assembly in the same project",
"I have the following:\n\nProject A uses System.Web.Mvc version 5.2.3.0\nProject A references Project B which uses System.Web.Mvc version 4.0\n\n\nAt compile time, version 4 of System.Web.Mvc is written to Project A's bin directory. And as you would expect, I get could not load System.Web.Mvc or one of its dependencies... error.\n\nThere is a nearly identical question, but in this case the major versions of the DLLs are different, so a binding redirect will not work (the error literally says that Comparing the assembly name resulted in the mismatch: Major Version).\n\nUpgrading one of the projects is out of the question for the time being.\n\nSo what can I do?"
] | [
"c#",
".net",
"asp.net-mvc"
] |
[
"Makefile Support for Multiple Architectures/Configurations",
"What's the easiest way to give a makefile support for multiple architectures and configurations? For example, a release configuration might use more optimization than a debug configuration. Should the changing options be defined as variables in the makefile, and users be relied on to update them as needed?\n\n# Change to -O2 for release.\nCOMPILER_OPTIONS := -arch x86_64 -O0\n\n\nOr should this sort of thing be handled in rules?\n\n*_Release.a:\n # Recipe for building a release library, i.e., with optimization.\n # Unsure how to integrate this with different architectures.\n\n\nOr perhaps a combination of the two?"
] | [
"makefile",
"build-automation"
] |
[
"Play Sound Using HTML 5 on Web Application",
"I'm building a web application to support RPG games, like Dungeons & Dragons. It's \nlike a AJAX chat room with dice rollers, avatars, shared information, character sheets and \nso on...\n\nOne of my desired features is to let the game master to play music to all game members.\n\nHow can I implement that?\n\nI'm building the application with Asp.NET, using C# 3.5.\n\nIn the client side I'm using jQuery (latest version).\n\nI intend to avoid Flash and Silverlight (even if the music resource will be available to \nsome browsers only).\n\nI tryed to use ogg format, but I don't know how to make it work with my own audio \nfiles. Do I need to implement a stream or something?\n\nThe application already is online. If someone want to see it, let me know. But \nit's only available in portuguese (Brazil).\n\nAny tip will be apreciated."
] | [
"audio",
"html"
] |
[
"Try codesnippet until condition is True",
"this is probably a nobraner, but I can't figure it out. \nI've got this function which converts wav files to mp3. I call this from my button_click handle. The thing is, when the conversion is started, the rest of the code in the button_click handler continue, while the conversion is happening in a different thread. \n\nNow, I need the rest of the code in the button_click handle so continue to try until a boolean is true, so that I know that the conversion is done before the rest of the code continues. \n\nI've tried using Do While but it didn't seem to do the trick. Perhaps it's just me though.."
] | [
"c#",
"vb.net"
] |
[
"how to use \"st_distance\" in hibernate hql and mysql 5.6.2?",
"I want to sort the distance using hibernate but the \"st_distance\" not work. the log : \n\n\n ----- org.hibernate.QueryException: No data type for node: org.hibernate.hql.internal.ast.tree.MethodNode -[METHOD_CALL] MethodNode: '(' +-[METHOD_NAME] IdentNode: 'st_distance' {originalText=st_distance} -[EXPR_LIST] SqlNode: 'exprList' +-[METHOD_CALL] MethodNode: '(' | +-[METHOD_NAME] IdentNode: 'POINT' {originalText=POINT} | -[EXPR_LIST] SqlNode: 'exprList' | +-[DOT] DotNode: 'facilitato0_.c_longitude' {propertyName=longitude,dereferenceType=PRIMITIVE,getPropertyPath=longitude,path={synthetic-alias}.longitude,tableAlias=facilitato0_,className=com.kingox.ins.dao.entity.Facilitator,classAlias=null} | | +-[IDENT] IdentNode: '{synthetic-alias}' {originalText={synthetic-alias}} | | -[IDENT] IdentNode: 'longitude' {originalText=longitude} | -[DOT] DotNode: 'facilitato0_.c_latitude' {propertyName=latitude,dereferenceType=PRIMITIVE,getPropertyPath=latitude,path={synthetic-alias}.latitude,tableAlias=facilitato0_,className=com.kingox.ins.dao.entity.Facilitator,classAlias=null} | +-[IDENT] IdentNode: '{synthetic-alias}' {originalText={synthetic-alias}} | -[IDENT] IdentNode: 'latitude' {originalText=latitude} -[METHOD_CALL] MethodNode: '(' +-[METHOD_NAME] IdentNode: 'POINT' {originalText=POINT} -[EXPR_LIST] SqlNode: 'exprList' +-[PARAM] ParameterNode: '?' {ordinal=0, expectedType=null} -[PARAM] ParameterNode: '?' {ordinal=1, expectedType=null} [select id, name, st_distance(POINT (longitude, latitude),POINT(?,?)) as tmpDistance"
] | [
"java",
"hibernate",
"hql"
] |
[
"Copy a column from one table to another in oracle",
"I try to copy the column [codigomall] of the table 'sectores' to the column [malla] of the table 'grm'.\nWhat I've tried so far is the following: \n\nupdate grm\nset grm.malla = (select c.codigomall from grm a, sectores c, table(sdo_join('grm', 'geometry','sectores','geometry', 'mask=inside')) j where j.rowid1 = a.rowid and j.rowid2 = c.rowid)\nwhere exists (select c.codigomall from grm a, sectores c, table(sdo_join('grm', 'geometry','sectores','geometry', 'mask=inside')) j where j.rowid1 = a.rowid and j.rowid2 = c.rowid)\n\n\nOracle gives that the process is correct, but it doesn't copy any value in grm.malla.\n\nI tried to replace c.codigmall with j.codigmall, but Oracle gave me an error:\n\nupdate grm\nset malla = (select j.codigomall from grm a, sectores c, table(sdo_join('grm', 'geometry','sectores','geometry', 'mask=inside')) j where j.rowid1 = a.rowid and j.rowid2 = c.rowid)\nwhere exists (select j.codigomall from grm a, sectores c, table(sdo_join('grm', 'geometry','sectores','geometry', 'mask=inside')) j where j.rowid1 = a.rowid and j.rowid2 = c.rowid)\n\n\nDo you know where I am failing? I have a feeling that the j.codigomall is a mistake\n\nContext: There are two spatial layers, I want to inherit one column to another by spatial overlay"
] | [
"oracle",
"oracle-spatial"
] |
[
"Different results with MACS2 when Peakcalling with .bed or .bam",
"I got the following problem: \nI use MACS2 (2.1.0.20140616) with the following short commandline:\n\nmacs2 callpeak -t file.bam -f bam -g 650000000 -n Test -B --nomodel -q 0.01\n\n\nIt seems to work as I want, but when I convert the .bamfile into .bed via \n\nbedtools bamtobed -i file.bam > file.bed\n\n\nand use MACS2 on this, I get a lot more peaks. As far as I understand, the .bed-file should contain the same information as the .bam-file, so that's kinda odd. \n\nAny suggestions what's the problem?\n\nThanks!"
] | [
"bioinformatics",
"bam",
"bed",
"bedtools"
] |
[
"How to search datetime value in JSONB using ransack",
"This is a sample code that searches key value inside jsonb_column for name\n\nransacker :name do |parent| \n Arel::Nodes::InfixOperation.new('->>', parent.table[:jsonb_column_here], \n Arel::Nodes.build_quoted('name'))\nend\n\n\nBEFORE we're not using JSONB column and this works for searching using datetime values.\n\n Ransack.configure do |config|\n config.add_predicate 'between_begin_and_end',\n arel_predicate: 'between_begin_and_end',\n formatter: proc { |v| v.to_date },\n validator: proc { |v| v.present? },\n type: :string\nend\n\nmodule Arel\n module Predications\n def between_begin_and_end date\n gteq(date.to_date.beginning_of_day).and(lt(date.end_of_day))\n end\n end\nend\n\n\n**Example data:**\n\njsonb_column {\n \"data_created_at\"=>2020-03-23 05:10:46 UTC,\n ....\n ....\n}\n\n\nHOW to incorporate my previous method now with JSONB column."
] | [
"ruby-on-rails",
"ruby",
"postgresql",
"jsonb",
"ransack"
] |
[
"Notice: Undefined index: filetoUpload",
"Okay, so I am trying to build a system where an admin can upload files for people of other departments working in a company. So I was working on the php file upload script but i keep getting this Error\n\n\n Notice: Undefined index: filetoUpload\n\n\nHere's my code.\n\nIndex.html\n\n<form class=\"form-group\" method=\"POST\" action=\"upload.php\">\n <select class=\"form-control col-sm-6\" name=\"department\">\n <option>Department</option>\n <option>HR</option>\n <option>Engineering</option>\n <option>Finance</option>\n <option>HR Forms</option>\n <option>IT</option>\n <option>Learning Center Other</option>\n <option>Learning Center Technical</option>\n <option>Marketing</option>\n <option>Operations</option>\n <option>Processe<s/option>\n <option>Other</option>\n </select><br>\n <input type=\"file\" name=\"fileToUpload\" value=\"Choose File\" id=\"fileToUpload\" class=\"btn btn-info\"><br>\n <input type=\"submit\" name=\"btn\" class=\"btn btn-primary\" value=\"Upload\" style=\"margin-top: 10px;\">\n </form>\n\n\nupload.php\n\n<?php\n\n$department = $_POST['department'];\n$file = $_FILES['fileToUpload']['name'];\necho $department . $file;\n\n\n?>"
] | [
"php",
"file-upload"
] |
[
"How to NOT pre-load images in expand script?",
"I have a question that's bugging me quite a bit, been working on it a while with every road leading to dissapoints, and no suitable alternatives I've found.\n\nHow do I have the following NOT pre-load images?\n\nvar oStyle = document.createElement('style');\noStyle.setAttribute('type','text/css');\nvar css = 'a.hovex-imageview { -moz-outline: 1px dotted red; }';\ncss += 'a.hovex-imageview img.hovex-imageview { display: none;position: fixed;left: 15%;right: 85%;top:15%;bottom:85%;max-width: 100%;margin: 0;border: none; }';\ncss += 'a.hovex-imageview:hover img.hovex-imageview { display:block;max-width:80%;max-height:80%; }';\noStyle.innerHTML = css;\ndocument.getElementsByTagName('head')[0].appendChild(oStyle);\n\nvar aElm = document.getElementsByTagName('a');\nfor (i=0; i<aElm.length; i++) {\n if (aElm[i].href.match(/\\.(jpg|jpeg|gif|png)$/)) {\n var oImg = document.createElement('img');\n oImg.setAttribute('src',aElm[i].href);\n oImg.setAttribute('class','hovex-imageview');\n aElm[i].appendChild(oImg);\n aElm[i].setAttribute('class','hovex-imageview'); \n }\n} \n\n\nBasically, it is perfect in almost every way for my purpose, though the one drawback is it often finds itself on pages with >1000 large images, so having it only load the full image on mouseover of the link/thumb would save people some crashed browsers, I've had people complain about that.\n\nI can see why this could be difficult to do, as it works by creating every image on load and hiding them, then showing them on hover, with it said if I'd found/managed to write an acceptable alternative I'd of used it: this seems to be what I've got.\n\nGreat thanks to any helpful wizards in advance~"
] | [
"javascript",
"jquery",
"hover",
"thumbnails"
] |
[
"VB - show msgbox once a time(r)",
"I have the following code :\n\nSub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick\n Dim mesaj As New Integer\n\n My.Computer.Network.DownloadFile(\"http://rotutorial.net/anunt.txt\", \"c:\\classmate\\msg1.txt\", \"\", \"\", False, 60000, True)\n Dim readtext As New System.IO.StreamReader(\"c:\\classmate\\msg1.txt\")\n Dim text As String\n text = readtext.ReadToEnd\n readtext.Close()\n Dim parti(10) As String\n parti = text.Split(\"_\")\n\n Dim writetext1 As New System.IO.StreamReader(\"c:\\classmate\\msg.txt\")\n Dim text1 As String\n Dim parti1(10) As String\n text1 = writetext1.ReadToEnd\n parti1 = text1.Split(\"_\")\n\n writetext1.Close()\n Dim unic As New Integer\n unic = Val(parti(0))\n Dim unic1 As New Integer\n unic1 = Val(parti1(0))\n\n If unic <> unic1 Then\n If unic <> unic1 Then\n mesaj = MsgBox(parti(3), vbYesNo, \"Mesaj\")\n End If\n Dim writetext2 As New System.IO.StreamWriter(\"c:\\classmate\\msg.txt\")\n Dim text2 As String\n text2 = text & \"/\" & text1\n writetext2.Write(text2)\n writetext2.Close()\n\n Timer1.Enabled = False\n Timer1.Enabled = True\n End If\n Timer1.Enabled = False\n Timer1.Enabled = True\n\n\n\n\n\n\n End Sub\n\n\nThe timer interval is set to 5000(5 seconds), but every time when the timer is ticking the msgbox appears on screen but the in the file msg.txt is writting once. So, The timer check if that unic is different from unic1, and if is different shows up a msg box, and it's writting the new line in msg.txt, but on next timer tick, even if the unic and unic1 are equals the msgbox shows up anyway, but it's more interesting because it doesn't write again in file, only shows up the msgbox. I don't understand this.\n\nSorry for my bad english, i'm from Romania.\n\nThank you!"
] | [
"vb.net",
"visual-studio-2010",
"visual-studio",
"timer"
] |
[
"Advice on persistant data type to use",
"Newbie question - I would like some advice on the best persistant data type to use.\n\nRequirements: \n\n\nData to be stored : Simple text and pictures\nApp Type: Information app featuring drill down tables and detailed view screens with several images on screen.\nData Updates: Yes, the app will be updated on a regular basis with new text and images, (updates preferable downloaded in the background, whilst the app is running and this data will be stored)\n\n\nCan anybody offer me some advise as to the best persistant data type to use to.\nThanks in advance."
] | [
"ios",
"xcode",
"persistence"
] |
[
"File.ReadAllLines() quickly followed by File.WriteAllLines() causes exception due to lock",
"In my program I have a chunk of code that does\n\nvar lines = File.ReadAllLines(myFileName);\n\nif (lines[0] != null)\n{\n //does a few things\n File.WriteAllLines(myFileName, lines);\n}\n\n\nWhile this worked fine at first, recently it has given me an exception due to the file being used by another process ~90% of the time. This already made no sense to me since File.ReadAllLines() is supposed to close the file after reading. I added System.Threading.Thread.Sleep(3000) right before the File.WriteAllLines(), which increased my success rate to ~50%. Is sleeping the thread and crossing my fingers really my only option? I can not find any sources where people have had similar issues with File.ReadAllLines().\n\nAny suggestions, explanation, or practical fixes would help. I can't help but feel like I'm missing something.\n\nEDIT: edited my if statement with the actual code, incase it matters\n\nEDIT: I am reading and writing the file to a network share, not my local machine.\n\nEDIT: It does not appear to be any kind of hung version of my app holding on to the file, and from what I can tell by using the FileUtil class in this question, it is my app that has a lock on the file."
] | [
"c#"
] |
[
"Count elements across users in df after grouping by, in Spark Scala",
"I have this df:\n|User |country|\n| Ron | italy| \n| Tom | japan|\n| Lin | spain|\n| Tom | china|\n| Tom | china|\n| Lin | japan|\n| Tom | china|\n| Lin | japan|\n\nI want to count for each user the total amount of his countries.\nfor example, for the df above I'll get:\n[Ron -> [italy ->1], Tom -> [Japan -> 1, china -> 3], Lin -> [Spain -> 1, Japan ->2]]\n\nI started with\nval groupedbyDf = df.groupBy("User")\n\nBut I don't know how to continue.. agg() ?"
] | [
"scala",
"dataframe",
"apache-spark",
"group-by",
"aggregate"
] |
[
"Chart.js align line graph to the left",
"i am wondering why my chart isn't aligned to the left and how i can do this? This is my code:\n\nvar data = {\n labels: [\"ID\"]\n , datasets: [\n {\n label: \"Sensor 1\"\n , data: [{\n x: 0\n , y: 2\n }, {\n x: 12\n , y: 5\n }]\n , backgroundColor: [\n 'rgba(255, 99, 132, 0.2)'\n , ]\n , borderColor: [\n 'rgba(255,99,132,1)'\n ]\n , borderWidth: 1\n }\n ]\n};\nvar options = {\n title: {\n display: true\n , text: 'Custom Chart Title'\n }\n , scales: {\n yAxes: [{\n ticks: {\n beginAtZero: true\n }\n }]\n , xAxes: [{\n type: \"linear\"\n , position: \"bottom\"\n }]\n }\n};\nvar myLineChart = Chart.Line(ctx, {\n data: data\n , options: options\n});\n\n\nThe line starts right in the center of the graph but i don't know how i can align it to the left (on the x-Axis). This is how it looks like:\n\nhttps://picload.org/image/raoipwci/chartjs.png\n\nAs you can see, another problem is, that the y-axis doesn't match up with the dataset i entered.\n\nEdit: Okay, i finally got it working. I added the correct code."
] | [
"javascript",
"html",
"css",
"chart.js"
] |
[
"convert nested dictionaries to list of list",
"I’ve a nested dictionary that looks like this:\n\n{\n \"g\": {\n \"o\": {}\n },\n \"h\": {\n \"p\": {}\n },\n \"e\": {\n \"v\": {},\n \"m\": {\n \"s\": {}\n }\n },\n \"f\": {\n \"n\": {}\n },\n \"a\": {\n \"i\": {}\n },\n \"d\": {\n \"u\": {},\n \"l\": {\n \"r\": {}\n }\n },\n \"b\": {\n \"j\": {}\n },\n \"c\": {\n \"t\": {},\n \"k\": {\n \"q\": {\n \"z\": {}\n }\n }\n }\n}\n\n\nIs there a fast way of convert it to a list of lists to get the following output:\n\n [g, o]\n [h, p]\n [e, v]\n [e, m, s]\n [f, n]\n [a, i]\n [d, u]\n [d, l, r]\n [b, j]\n [c, t]\n [c, k, q, z]\n\n\nwe stop when we encounter an empty dictionary. for example, we start with \"g\", it has child \"o\" which in turn has no children, the list thus consists of \"g\" and \"o\". \n\nanother example: starting with \"e\", children are \"v\" and \"m\" and \"m\" has \"s\". Thus we have two lists: one with \"e\" and \"v\" and another with \"e\", \"v\" and \"m\".\n\nI tried creating a recursive function but unfortunately, it didnt turn out well."
] | [
"python",
"list",
"dictionary"
] |
[
"Iterating through nested JSON in Ruby",
"first time posting here.\nHaving trouble getting into a JSON, and I could use some active.\n\nThe data that I need is at this level:\n\nrestaurant[\"menu\"][0][\"children\"][0][\"name\"]\n\nrestaurant[\"menu\"][0][\"children\"][0][\"id\"]\n\n\nI want an array of \"id\"s based on \"name\"s.\n\nThis is the method that I'm working with:\n\ndef find_burgers(rest)\n\n array = []\n\n rest[\"menu\"].each do |section| \n section[\"children\"].each do |innersection| \n innersection[\"name\"].downcase.split.include?(\"burger\")\n array.push(innersection[\"id\"]) \n end\n end \n return array\nend\n\n\nAs you can imagine, I'm getting back an array of every \"id\", not just the \"id\"s for burgers. I've tried many combinations of .map and .keep_if.\n\nThanks for reading.\n\nEDIT: This is one menu item:\n\n{\n \"children\" => [\n [ 0] {\n \"availability\" => [\n [0] 0\n ],\n \"children\" => [\n [0] {\n \"children\" => [\n [0] {\n \"availability\" => [\n [0] 0\n ],\n \"descrip\" => \"\",\n \"id\" => \"50559491\",\n \"is_orderable\" => \"1\",\n \"name\" => \"Single\",\n \"price\" => \"0.00\"\n },\n [1] {\n \"availability\" => [\n [0] 0\n ],\n \"descrip\" => \"\",\n \"id\" => \"50559492\",\n \"is_orderable\" => \"1\",\n \"name\" => \"Double\",\n \"price\" => \"2.25\"\n }\n ],\n \"descrip\" => \"What Size Would You Like?\",\n \"free_child_select\" => \"0\",\n \"id\" => \"50559490\",\n \"is_orderable\" => \"0\",\n \"max_child_select\" => \"1\",\n \"max_free_child_select\" => \"0\",\n \"min_child_select\" => \"1\",\n \"name\" => \"Milk Burger Size\"\n },\n [1] {\n \"children\" => [\n [0] {\n \"availability\" => [\n [0] 0\n ],\n \"descrip\" => \"\",\n \"id\" => \"50559494\",\n \"is_orderable\" => \"1\",\n \"name\" => \"Bacon\",\n \"price\" => \"2.00\"\n }\n ],\n \"descrip\" => \"Add\",\n \"free_child_select\" => \"0\",\n \"id\" => \"50559493\",\n \"is_orderable\" => \"0\",\n \"max_child_select\" => \"1\",\n \"max_free_child_select\" => \"0\",\n \"min_child_select\" => \"0\",\n \"name\" => \"Burgr Ad Bacon Optn\"\n }\n ],\n \"descrip\" => \"American cheese, lettuce, tomato and Milk Sauce\",\n \"id\" => \"50559489\",\n \"is_orderable\" => \"1\",\n \"name\" => \"Milk Burger\",\n \"price\" => \"4.25\"\n },"
] | [
"ruby-on-rails",
"ruby",
"json"
] |
[
"Conditional value in helper method in ruby",
"I would like to set a parameter in this helper method, but I'm not sure if is possible to use a ternary operator or something to set a value with some condition.\n\n<%= number_field_tag 'somearray[][somefield]', nil, {min: 0.000, step: 0.001, class: \"form-control\", :'aria-label' => \"Quantity\" ,onchange: \"change_total(this)\",value: 'VALUE SHOULD BE HERE'} %>\n\n\nThe condition is something like this:\n\nif params['somearray'].nil? != true\n return params['somearray'].first[\"quantity\"]\nelse\n return nil\nend"
] | [
"ruby-on-rails",
"ruby"
] |
[
"active record where method and not",
"I can't seem to find the answer to this anywhere. I know I can do:\n\nItem.where(:color => 'red')\n\n\nto get all red items, but how do I get all items whose color is not red?"
] | [
"ruby-on-rails",
"ruby",
"activerecord"
] |
[
"Ruby Rails - NoMethodError , drop-down list",
"I am trying to follow this tutorial. It has written in previous version of Rails and I am using Rails 4. There was a drop-down list the selection does not appear, I am getting following error: \n\nNoMethodError in Book#show\nShowing C:/Ruby193/mylibrary/app/views/book/show.html where line #3 raised:\n\nundefined method `name' for nil:NilClass\nExtracted source (around line #3):\n\n 1 <h1><%= @book.title %></h1>\n 2 <p><strong>Price: </strong> $<%= @book.price %><br />\n 3 <strong>Subject: </strong> <%= @subject.name %><br />\n 4 </p>\n 5 <p><%= @book.description %></p>\n 6 <hr />\n\nRails.root: C:/Ruby193/mylibrary\n\n\nHere is the show.html \n\n <h1><%= @book.title %></h1>\n <p><strong>Price: </strong> $<%= @book.price %><br />\n <strong>Subject: </strong> <%= @book.subject.name %><br />\n </p>\n <p><%= @book.description %></p>\n <hr />\n <%= link_to 'Back', {:action => 'list'} %>\n\n\nHere is migrate/258412_subjects.rb\n\nclass Subjects < ActiveRecord::Migration\n def self.up\n create_table :subjects do |t|\n t.column :name, :string\n end\n Subject.create :name => \"Physics\"\n Subject.create :name => \"Mathematics\"\n Subject.create :name => \"Chemistry\"\n Subject.create :name => \"Psychology\"\n Subject.create :name => \"Geography\"\n end\n\n def self.down\n drop_table :subjects\n end\nend\n\n\nHere is migrate/05465_books.rb\n\nclass Books < ActiveRecord::Migration\n def self.up\n create_table :books do |t|\n t.column :title, :string, :limit => 32, :null => false\n t.column :price, :float\n t.column :subject_id, :integer\n t.column :description, :text\n end\n end\n\n def self.down\n drop_table :books\n end\nend\n\n\nHere is models/book.rb\n\nclass Book < ActiveRecord::Base\n belongs_to :subject\n validates_presence_of :title\n validates_numericality_of :price, :message=>\"Error Message\"\nend\n\n\nHere is my controller class book_controller.rb\n\nclass BookController < ApplicationController\n\n def list\n @books = Book.all\n end\n def show\n @book = Book.find(params[:id])\n end\n def new\n @book = Book.new\n @subjects = Subject.all\n end\n def create\n @book = Book.new(book_params)\n if @book.save!\n redirect_to :action => 'list'\n else\n @subjects = Subject.all\n render :action => 'new'\n end\n end\n def edit\n @book = Book.find(params[:id])\n @subjects = Subject.all\n end\n def update\n @book = Book.find(params[:id])\n if @book.update_attributes(book_params)\n redirect_to :action => 'show', :id => @book\n else\n @subjects = Subject.all\n render :action => 'edit'\n end\n end\n def delete\n Book.find(params[:id]).destroy\n redirect_to :action => 'list'\n end\n\n private\n\n def book_params\n params.permit(:title, :price, :description)\n end\n\nend\n\n\nWhat should I do?, Thank you in advance"
] | [
"ruby-on-rails",
"ruby-on-rails-4"
] |
[
"Using Streamwriter Append not working",
"Hey All my code is set up like this..\n\nMethod()\nusing (StreamWriter writer = new StreamWriter(@\"file\"))\n {\n writer.WriteLine(\"Service Start {0}\", DateTime.Now, true);\n }\n\nMethod () \nusing (StreamWriter writer = new StreamWriter(@\"filet\"))\n {\n writer.WriteLine(\"Service Stopped {0}\", DateTime.Now, true);\n }\n\n\nMy text file isn't getting appended, instead it is getting replaced. I thought setting true was suppose to append the files but it hasn't.\nThis is a c# windows service App"
] | [
"append",
"streamwriter"
] |
[
"MYSQL search multiple records in the same table with the same first part of primary key",
"I have two tables:\nSALE(SALE_CODE,SALE_DATE) and\nSALE_ITEM(SALE_CODE,ITEM_CODE,QUANTITY,PRICE)\nwith SALE_CODE and SALE_CODE,ITEM_CODE as primary keys respectively. \n\nI want to find out the sale with the biggest income. \n\nI can only figure out how to do it if each sale contains only one item\n\nSELECT SALE_CODE,PRICE*QUANTITY \nFROM SALE_ITEM\nWHERE PRICE*QUANTITY =(SELECT MAX(PRICE*QUANTITY) \nFROM SALE_ITEM);\n\n\nBut if there are multiple records on the SALE_ITEM table with the same SALE_CODE but with different ITEM_CODE, I don't know what to do"
] | [
"mysql",
"sql"
] |
[
"Merge cloud yaml AWS cloud formation template",
"I have multiple files that contains my cloud formation template.yaml file. For example\n\nbase.yaml\n\nAWSTemplateFormatVersion: 2010-09-09\nTransform: AWS::Serverless-2016-10-31\n\nConditions:\n conFunctionInVPC: !And\n - !Not [!Equals [!Join [\"\", !Ref parFunctionSubnets], \"\"]]\n - !Not [!Equals [!Join [\"\", !Ref parFunctionSecurityGroups], \"\"]]\n conFunctionNotInVPC: !Not [!Condition conFunctionInVPC]\n conAwsXRaySdkLayer: !Not [!Equals [!Ref parAwsXRaySdkLayerArn, \"\"]]\n\n\napplication.yaml\n\nDescription: >\n test\n A short description of the function purpose\n\n\nI want to produce the final yaml file. I tried a simple merging function\n\nwith open('base.yaml') as f:\n base = yaml.load(f)\nwith open('application.yaml') as f:\n application = yaml.load(fp)\ntemplate = merge(base, template) # my own function not important here\nyaml.dump(template, open('template.yaml', 'w'))\n\n\nHowever I get the error:\n\n\n yaml.constructor.ConstructorError: could not determine a constructor for the tag '!And'\n\n\nHow can I tell yaml to just keep the node as simple it is? And be able to output it again when dumping it?\n\nI tried with\n\nyaml.add_multi_constructor('!', lambda loader, suffix, node: node)\n\n\nbut then when I dump the file, I get the SequenceNode object in my yaml for each !ref\n\nfor example:\n\nconFunctionInVPC: !!python/object:yaml.nodes.SequenceNode\n end_mark: !!python/object:yaml.error.Mark\n buffer: null\n column: 2\n index: 721\n line: 24\n name: template/template.yaml\n pointer: null\n flow_style: false\n start_mark: !!python/object:yaml.error.Mark\n buffer: null\n column: 20\n index: 581\n line: 21\n name: template/template.yaml\n pointer: null\n tag: '!And'\n value:"
] | [
"python",
"yaml",
"amazon-cloudformation"
] |
[
"How to get all namespaces of xml document for correct XPath evaluating?",
"I try to evaluate simple xpath \n\n\"//pr:Name\"\n\n\nfor this xml\n\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<pr:Products xmlns:pr=\"http://www.example.com/\">\n <pr:Name>Coffee</pr:Name>\n</pr:Products>\n\n\nbut I get xml file in run-time i.e. I can't fill XmlNamespaceManager using method AddNamespace() (this why evaluating failed). I tried to do this trick\n\n XDocument xdoc;\n XmlReader reader;\n using (var stream = new FileStream(\"test.xml\", FileMode.Open))\n {\n reader = new XmlTextReader(stream);\n xdoc = XDocument.Load(reader);\n }\n var nsManager = new XmlNamespaceManager(reader.NameTable);\n var xpath = \"//pr:Name\";\n var xvalue = xdoc.XPathEvaluate(xpath, nsManager);\n\n\nbut it does not help me.\nDo you have any idea how to resolve namespaces for XPath or evaluate XPath in other way?\nThank you!"
] | [
"c#",
".net",
"xml",
"xpath",
"xdoc"
] |
[
"Fails to get the location on Android mobile",
"Actually my problem is sometimes i can get the location and sometimes i can't get the location on Android real device. I used following code for getting the location,\n\nLocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);\nCriteria criteria = new Criteria();\ncriteria.setAccuracy(Criteria.ACCURACY_FINE);\ncriteria.setAltitudeRequired(false);\ncriteria.setBearingRequired(false);\ncriteria.setPowerRequirement(Criteria.POWER_LOW);\nString provider = locationManager.getBestProvider(criteria, true);\nLocation location = locationManager.getLastKnownLocation(provider);\n\n\nI need to get the location when my application starts up. I don't know why sometimes it fails. How to resolve this issue?"
] | [
"android",
"mobile",
"locationmanager",
"android-location"
] |
[
"How to get a correlation coefficient table of a data set",
"My sample data is below;\n\nIt has 40 rows and 26 columns including headers\n\nConstituency: 01 | HP Deprivation Score | Total Population 2011| 5?year Population Change| Age Dependency Rate| Proportion of Lone Parents | |\nCarlow-Kilkenny -1.70 145,659 8.9 34.1 19.0\nCavan-Monaghan -3.90 120,483 11.9 35.2 17.5\nClare -0.40 111,336 5.5 34.7 17.5\nCork East 0.50 114,365 14.2 34.7 18.6\nCork North-Central -0.40 117,131 3.2 30.6 26.1\nCork North-West 2.10 86,593 9.7 34.2 15.8\nCork South-Central 4.90 117,991 5.6 31.2 20.0\nCork South-West 2.00 82,952 7.8 36.0 15.4\nDonegal -6.30 152,358 9.7 36.3 23.0\n\n\nI try to get a correlation coefficient table/matrix for each column and want to keep the constituency names. Here is the code I've tried based on other answers;\n\nlibrary(corrplot)\nelection2016[is.na(election2016)] = 0\n\ndf <- data.frame(matrix(unlist(election2016), nrow=39, byrow=T),stringsAsFactors=FALSE)\nM <- cor(df)\ncorrplot(M, method=\"circle\")\n\n\nThe table I got is not accurate as it contains different numbers in the data frame. \n\nCan anyone help?"
] | [
"r",
"list",
"dataframe",
"correlation",
"r-corrplot"
] |
[
"ActiveModel::MassAssignmentSecurity::Error with nested attributes",
"Hi im trying to create a relation one-to-many in my rails app.\n\nFist i create my models\n\nclass Produto < ActiveRecord::Base\n attr_accessible :compra, :descricao, :estoque, :venda\n\n has_many :precos\n accepts_nested_attributes_for :precos\nend\n\nclass Preco < ActiveRecord::Base\n attr_accessible :compra_decimal, :produto_id, :venda_decimal\n\n belongs_to :produto\nend\n\n\nThen i created my controller\n\nclass ProdutosController < ApplicationController\n def new\n @produto = Produto.new\n @produto.precos.build\n end\n\n def create\n @produto = Produto.new(params[:produto])\n\n if @produto.save?\n redirect_to produtos_path\n end\n end\nend\n\n\nAfter this i created my .html.erb pages:\n\n_form\n\n<%= form_for @produto do |f| %>\n <p>\n <%= f.label :descricao %><br/>\n <%= f.text_field :descricao %>\n </p>\n <p>\n <%= f.label :compra %><br/>\n <%= f.text_field :compra %>\n </p>\n <p>\n <%= f.label :venda %><br/>\n <%= f.text_field :venda %>\n </p>\n <p>\n <%= f.label :estoque %><br/>\n <%= f.text_field :estoque %>\n </p>\n<%= f.fields_for :precos do |builder| %>\n <%= render \"precos\", :f => builder %>\n<% end %>\n <p><%= f.submit %></p>\n<% end %>\n\n\n_precos\n\n<p>\n <%= f.label :venda_decimal %><br/>\n <%= f.text_field :venda_decimal %>\n</p>\n<p>\n <%= f.label :compra_decimal %><br/>\n <%= f.text_field :compra_decimal %>\n</p>\n\n\nnew\n\n<%= render \"form\" %>\n\n\nthen, when i submit the form this error appears:\n\nActiveModel::MassAssignmentSecurity::Error in ProdutosController#create\n\nCan't mass-assign protected attributes: precos_attributes\n\n\ndoes anyone have any idea about it?"
] | [
"ruby-on-rails",
"ruby",
"ruby-on-rails-3.2"
] |
[
"Use Dagger generated test code in Android",
"I'm trying to use Dagger2 in my android project as explained in hitherejoe/Android-Boilerplate. While I am setting up the project I got following error on build time.\n\nError:(30, 26) error: cannot find symbol variable DaggerTestComponent\n\n\nAfter digging into the documentation and generated code I figured out that code is not generating in debug (/app/build/generated/source/apt/debug/) folder but in test/debug(/app/build/generated/source/apt/test/debug) folder. \nSo in my test source folder can not import the generated DaggerTestComponent.\n\nAny clue how to include test/debug folder to the source?\nMy dependancies are as follows\n\ntestCompile 'com.neenbedankt.gradle.plugins:android-apt:1.8'\ncompile \"com.google.dagger:dagger:$DAGGER_VERSION\"\napt \"com.google.dagger:dagger-compiler:$DAGGER_VERSION\"\nprovided 'javax.annotation:jsr250-api:1.0'\ncompile 'javax.inject:javax.inject:1'\ntestApt \"com.google.dagger:dagger-compiler:$DAGGER_VERSION\"\n\n\nThanks in advance."
] | [
"android",
"android-testing",
"dagger-2"
] |
[
"Access variable from a static function in php",
"Here is a program from php. I am not able to print the value of the protected variable from a static function. What is wrong with this program?\n\nclass SomeClass\n{\n protected $_someMember;\n\n public function __construct()\n {\n $this->_someMember = 1;\n self::getSomethingStatic();\n }\n\n public static function getSomethingStatic()\n { \n echo $_someMember * 5; \n }\n}\n$obj = new SomeClass();"
] | [
"php"
] |
[
"binary Converter using Get Set",
"Am making a Binary converter in a windows form using Get and Set method\n\nCode to carry out the conversion\n\nclass SubnetConvert\n{\nprivate int numconvert;\nprivate string OctetToBinary;\n\npublic int OctetConvert\n{\nget \n{\n return numconvert;\n}\n set\n {\n List<int> Subnet = new List<int>(new int[] { 128, 64, 32, 16, 8, 4, 2, 1 });\n foreach (int num in Subnet)\n {\n if (num <= numconvert)\n {\n numconvert -= num;\n OctetToBinary += \"1\";\n }\n else\n {\n OctetToBinary += \"0\";\n }\n }\n }\n}\npublic string SendBinary\n{\n set\n {\n OctetToBinary = value;\n }\n get\n {\n return OctetToBinary;\n }\n}\n\n\nCode applied to the Convert button\n\n private void btnSubnetting_Click(object sender, EventArgs e)\n {\n SubnetConvert SubnetOctet = new SubnetConvert();\n lblOctet1.Text = \"\";\n int Octet1 = int.Parse(txtOctet1.Text);\n SubnetOctet.OctetConvert = Octet1;\n lblOctet1.Text = SubnetOctet.SendBinary;\n }\n\n\nAt the moment the only value returned is either 8 0s or 8 1s"
] | [
"c#"
] |
[
"Repeater button on click -VB.NET",
"I have created a repeater control(databinded) with few text boxes and button in a panel.Now when i click the Edit button inside the repeater control,i want to show save button and enable textboxes (which are disabled on page load).For this how can i access the Edit button and write vb.net code for this purpose.\n\nEdit button will allow the textboxes to enable and when save button is clicked the values to be saved to database.\nThanks"
] | [
"asp.net",
"vb.net"
] |
[
"Splitting a list of lists into multiple lists by length of sub list",
"I have a sorted list that looks like:\n\ntokens = [[46565], [44460], [73, 2062], [1616, 338], [9424, 24899], [1820, 11268], [43533, 5356], [9930, 1053], [260, 259, 1151], [83, 31840, 292, 3826]]\n\n\nand I want to split it into distinct lists by the length of sublist like so:\n\na = [[46565], [44460]]\nb = [[73, 2062], [1616, 338], [9424, 24899], [1820, 11268], [43533, 5356], [9930, 1053]]\nc = [[260, 259, 1151]]\nd = [[83, 31840, 292, 3826]]\n\n\nI'm having some trouble trying to do this without just looping over the entire original list and checking the length of each sublist.\n\nI thought perhaps I could do something with:\n\nlengths = list(map(len,tokens))\n\nfor k, v in zip(lengths, tokens):\n <SOME CODE HERE>\n\n\nany ideas?"
] | [
"python",
"list",
"sorting",
"sublist"
] |
[
"Uncaught TypeError: p5 is not a constructor",
"I have some troubles to start my p5js, since I'm getting this error:\nUncaught TypeError: p5 is not a constructor\nimport * as p5 from 'p5';\nexport default {\n init() {\n //a P5 moire pattern.\n let s = (sk) => {\n let layers = [];\n\n // sk.translate(window.innerWidth/2,window.innerHeight/2);\n sk.setup = () =>{\n let gfx = sk.createGraphics(window.innerWidth, window.innerHeight);\n let gfx2;\n\n sk.createCanvas(window.innerWidth, window.innerHeight);\n sk.angleMode(sk.DEGREES);\n sk.imageMode(sk.CENTER);\n sk.translate(window.innerWidth/2, window.innerHeight/2);\n sk.background(40);\n gfx.stroke(200);\n gfx.strokeWeight(3);\n gfx.line(0, 0, window.innerWidth, 0);\n for(let i=0; i<1000; i++){\n gfx.point(Math.random() *window.innerWidth, Math.random() *window.innerHeight);\n }\n\n gfx2 = {...gfx};\n sk.image(gfx,0,0);\n sk.rotate(1);\n sk.image(gfx2,0,0);\n }\n\n }\n const P5 = new p5(s, document.getElementById('grid'));\n }\n}\n\nI my destination index.js the object gets just initialized as myObject.init(), index.html has a div#grid in it.\nI can't see the issue. Any help would be appreciated."
] | [
"javascript",
"p5.js"
] |
[
"Titan 1.0.0 FIXED configuration \"set-vertex-id\" - can be overriden?",
"I'm trying to override the graph.set-vertex-id configuration in Titan 1.0.0 \n\nBy loading the configuration from an xml file:\n\n cache.db-cache-time = 180000\n cache.db-cache-size = 0.25\n graph.set-vertex-id=true\n storage.batch-loading=true\n....\n\n\nI'm getting the error :\n\n Local setting graph.set-vertex-id=true (Type: FIXED) is overridden by globally managed value (false). Use the ManagementSystem interface instead of the local configuration to control this setting.\n\n\nI also tried \n\n BaseConfiguration configuration = new BaseConfiguration();\n configuration.setProperty(\"storage.hostname\", \"any_hostname\");\n configuration.setProperty(\"storage.backend\", \"thrift\");\n configuration.setProperty(\"graph.set-vertex-id\", Boolean.TRUE);\n\ntitanGraph = TitanFactory.open(configuration);\n\n\nBut by checking the config with TitanManagement \n\n titanGraph.openManagement().get(\"graph.set-vertex-id\");\n\n\nI can see that it's still 'false'.\n\nHas anyone tried to assign custom vertices ids in this version of Titan? Before the upgrade we used Titan 0.4.2 and it worked just fine.\n\nThe documentation (http://s3.thinkaurelius.com/docs/titan/1.0.0/configuration.html ) says that\n\nGLOBAL: These options are always read from the cluster configuration and cannot be overwritten on an instance basis.\nFIXED: Like GLOBAL, but the value cannot be changed once the Titan cluster is initialized.\nWhen the first Titan instance in a cluster is started, the global configuration options are initialized from the provided local configuration file. Subsequently changing global configuration options is done through Titan’s management API. \nTo access the management API, call g.getManagementSystem() on an open Titan instance handle g. For example, to change the default caching behavior on a Titan cluster:\n\n mgmt = graph.openManagement()\n mgmt.get('cache.db-cache')\n // Prints the current config setting\n mgmt.set('cache.db-cache', true)\n // Changes option\n mgmt.get('cache.db-cache')\n // Prints 'true'\n mgmt.commit()\n // Changes take effect\n\n\nFirstly, there is no getManagementSystem() on a graph in Titan 1.0.0. Secondly, overriding the \"graph.set-vertex-id\" config like that will throw another error, because at this point the graph is already initialised:\n\n Cannot change the fixed configuration option: root.graph.set-vertex-id\n\n\nThank you !"
] | [
"configuration",
"titan",
"vertex"
] |
[
"Three.js + OrbitControls - Uncaught TypeError: Cannot read property 'render' of undefined",
"I am writing a class for rotating cube, but every time i rotate it or zoom, i get an error \"Cannot read property 'render' of undefined\". What am i doing wrong? I guess something is wrong with the scopes. Here is my class:\n\nmyclass = function() {\n this.camera = null;\n this.scene = null;\n this.renderer = null;\n this.product = null;\n\n this.init = function (container) {\n this.scene = new THREE.Scene();\n this.camera = createCamera();\n this.product = createProduct();\n this.scene.add(this.product);\n this.createRenderer();\n this.setControls();\n container.appendChild(this.renderer.domElement);\n this.animate();\n\n };\n\n function createCamera() {\n var camera = new THREE.PerspectiveCamera(20, 300 / 400, 1, 10000);\n camera.position.z = 1800;\n return camera;\n }\n\n function createProduct() {\n var geometry = new THREE.BoxGeometry(300, 200, 200);\n var materials = ...;\n\n var product = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));\n return product;\n }\n this.createRenderer = function () {\n this.renderer = new THREE.WebGLRenderer({antialias: true});\n this.renderer.setClearColor(0xffffff);\n this.renderer.setSize(this.sceneWidth, this.sceneHeight);\n };\n\n this.setControls = function () {\n this.controls = new THREE.OrbitControls(this.camera, this.renderer.domElement);\n this.controls.addEventListener('change', this.render);\n };\n\n this.animate = function () {\n requestAnimationFrame(this.animate.bind(this));\n this.render();\n };\n\n this.render = function () {\n this.renderer.render(this.scene, this.camera);\n };\n };\n\n\nTnanks."
] | [
"javascript",
"three.js"
] |
[
"DOMDocument::loadHTML() - with external Javascript",
"I am getting data from Instagram's oEmbed. I am receiving this API response:\n{\n "version": "1.0",\n "author_name": "diegoquinteiro",\n "provider_name": "Instagram",\n "provider_url": "https://www.instagram.com/",\n "type": "rich",\n "width": 658,\n "html": "<blockquote class=\\"instagram-media\\" data-instgrm-ca...",\n "thumbnail_width": 640,\n "thumbnail_height": 640\n}\n\nFor the html key, I wanted to load it using DOMDocument::loadHTML(), so this is my code:\n$dom = new \\DOMDocument('1.0', 'UTF-8');\n$dom->loadHTML($data['html']);\n\nThe problem with this is that it doesn't fully render the page, because the html value has a <script async src="//platform.instagram.com/en_US/embeds.js"></script> but it doesn't execute that script.\nIs there a way to fully render the page, like execute the javascript at the bottom, then I'll start to parse the HTML. I'm doing a DOMXPath to parse those HTMLs.\nBy the way this is the whole value of the html key from Instagram's API response:"
] | [
"php",
"laravel",
"dom",
"instagram-api"
] |
[
"How to fix \"slurmd.service: Can't open PID file\" error in slurm",
"Though SLURM works fine for job submitting, running, and queueing, I got a minor error below.\n\nsudo systemctl status slurmd\n\nJun 12 10:20:40 noki-System-Product-Name systemd[1]: slurmd.service: Can't open PID file /var/run/slurm-llnl/slurmd.pid (yet?) after start: No such file or directory\n\nsudo systemctl status slurmctld\n\nJun 12 10:20:40 noki-System-Product-Name systemd[1]: slurmd.service: Can't open PID file /var/run/slurm-llnl/slurmd.pid (yet?) after start: No such file or directory\n\nI followed the installation of a guide from\n\nfile:///home/noki/Downloads/Webinar_2_Slurm_II--Ubuntu16.04_and_18.04.pdf\n\nThis problem may come from the ownership of slurm.conf file?\n\nHere are my slurm.conf and ownership for slur*.pid\n\n# slurm.conf file generated by configurator easy.html.\n# Put this file on all nodes of your cluster.\n# See the slurm.conf man page for more information.\n#\nControlMachine=noki-System-Product-Name\n#ControlAddr=\n# \n#MailProg=/bin/mail \nMpiDefault=none\n#MpiParams=ports=#-# \nProctrackType=proctrack/pgid\nReturnToService=1\nSlurmctldPidFile=/var/run/slurm-llnl/slurmctld.pid\n#SlurmctldPort=6817 \nSlurmdPidFile=/var/run/slurm-llnl/slurmd.pid\n#SlurmdPort=6818 \nSlurmdSpoolDir=/var/spool/slurmd\nSlurmUser=noki\n#SlurmdUser=root\nStateSaveLocation=/var/spool/slurm-llnl\nSwitchType=switch/none\nTaskPlugin=task/none\n# \n# \n# TIMERS \n#KillWait=30 \n#MinJobAge=300 \n#SlurmctldTimeout=120 \n#SlurmdTimeout=300 \n# \n# \n# SCHEDULING \nFastSchedule=1\nSchedulerType=sched/backfill\nSelectType=select/linear\n#SelectTypeParameters=\n# \n# \n# LOGGING AND ACCOUNTING \nAccountingStorageType=accounting_storage/none\nClusterName=linux\n#JobAcctGatherFrequency=30 \nJobAcctGatherType=jobacct_gather/none\n#SlurmctldDebug=3 \nSlurmctldLogFile=/var/log/slurm-llnl/SlurmctldLogFile\n#SlurmdDebug=3 \nSlurmdLogFile=/var/log/slurm-llnl/SlurmdLogFile\n# \n# \n# COMPUTE NODES \nNodeName=noki-System-Product-Name CPUs=4 RealMemory=6963 Sockets=1 CoresPerSocket=4 ThreadsPerCore=1 State=UNKNOWN \nPartitionName=debug Nodes=noki-System-Product-Name Default=YES MaxTime=INFINITE State=UP\n\n\ntotal 8\n-rw-r--r-- 1 noki root 6 Jun 12 10:20 slurmctld.pid\n-rw-r--r-- 1 root root 6 Jun 12 10:20 slurmd.pid"
] | [
"pid",
"status",
"slurm",
"systemctl"
] |
[
"Why should Ninject dlls be in the Web/bin folder? Can't I just put them in the GAC?",
"My company has got a deployment policy (I skip the details) such that any 3rd party software should be installed in the GAC, whilst our libraries are in Web/bin folder. But this approach doesn't work with Ninject and MVC 3/4. Let's follow an example:\n\nThis is my dependencies binding code:\n\npublic class RequestorDependenciesRegistration : NinjectModule\n{\n public override void Load()\n {\n Bind<IMyDearDependency>().To<MyDearImplementation>();\n }\n}\n\n\nAnd this is my MVC controller:\n\npublic MyController(IMyDearDependency something) {\n this.something = something; // 'something' is set only if Ninject dlls are in Web/bin... X-(\n}\n\n\nIf Ninject dlls are in the GAC, it loads the module correctly, but when instantiating the MVC Controller the dependency is not injected (in some cases is null, in some cases MVC returns an error \"No parameterless constructor etc etc\"). If I manually copy Ninject*.dll in the Web/bin folder, than everything works fine, even without restarting IIS! Can't really understand why...\n\nEven more surprisingly (for me), if I do something super-dirty like storing a reference to the Ninject Kernel instance in a public static property and use it as a ServiceLocator, it works! (Something dirty like this, in the MVC controller):\n\npublic MyController(IMyDearDependency something) { // 'something' is always null if Ninject is only in the GAC...\n var controller = Kernel.Get<MyController>()\n this.something = controller.something; // ... but this 'controller.something' is set, even if Ninject is only in the GAC!!! 8-O\n}\n\n\nCan anyone suggest me the reason why? And possibly a solution? :-) Many thanks!!"
] | [
"asp.net-mvc",
"dll",
"ninject",
"gac",
"ninject.web.mvc"
] |
[
"TripleDES encrypting and decrypting gives strange results",
"I have a working implementation of TripleDESCng (tested against some test vectors), but the following happens:\n\nWhen I encrypt plain text This is a sample message (24 bytes, thus for this it would be 3 blocks) (hex for it is 5468697320697320612073616D706C65206D657373616765) with an example key, I get E81F113DD7C5D965E082F3D42EC1E2CA39BCDBCCBC0A2BD9. However, when I decrypt this with the same example key, I get 5468697320697320612073616D706C650000000000000000, which, when converted back to ASCII, is: \n\nThis is a sample.\n\nAny reason other than my code why this would behave this way? To encrypt and decrypt, I use 24 byte keys (ECB mode).\n\nEDIT:\n\nusing (var tripleDES = new TripleDESCryptoServiceProvider())\n{\n byte[] data = ASCIIEncoding.ASCII.GetBytes(\"This is a sample message\");\n Console.WriteLine(BitConverter.ToString(data));\n tripleDES.IV = new byte[tripleDES.BlockSize / 8];\n var encryptor = tripleDES.CreateEncryptor();\n byte[] result = new byte[data.Length];\n encryptor.TransformBlock(data, 0, data.Length, result, 0);\n var decryptor = tripleDES.CreateDecryptor();\n byte[] result2 = new byte[result.Length];\n decryptor.TransformBlock(result, 0, result.Length, result2, 0);\n Console.WriteLine(BitConverter.ToString(result2));\n}\nConsole.ReadLine();"
] | [
"c#",
".net",
"cryptography"
] |
[
"How to ensure PyCharm runs AND compiles using Java 8?",
"When I run my code I get "Unsupported class file major version 59", which suggests java 15 bytecode.\nWhen I run "java -version" on my terminal I get Java version 1.8.0_271-b09\nSo I believe the issue is that PyCharm is compiling the application in Java 15 and then trying to run it in Java 8. What is more confusing is I don't even have Java 15 installed in my machine.\nSo the question is how do I ensure it compiles at Java 8 to begin with?\nI've tried using the "Choose Runtime" plugin, but everytime I select JDK 1.8 it shuts down and throws an error saying "must be Java 11 or later"\nI'm pretty exhausted by this issue and really could use help on this- thanks."
] | [
"java",
"java-8",
"compiler-errors",
"pycharm",
"runtime-error"
] |
[
"How would you use Hashicorp's Nomad 'template stanza' to generate an nginx config file through the Nomad job file?",
"With the assumption that Consul and Nomad has been configured to run on a pool of resource. How would you rendered a template file for the sole purpose of generating e.g. an Nginx 'default.conf' file. \n\nUsing the template stanza configuration below, as an example; Nomad fails to generate a default.conf 'file'; instead a default.conf 'directory' is created. \n\ntemplate {\n source = \"/path/to/tmp.ctmpl\"\n destination = \"folder/default.conf\"\n change_mode = \"restart\"\n change_signal = \"SIGINT\"\n}\n\n\nI'm either missing a trick, or have misunderstood the functionalities of the 'template stanza'. \n\nOne of the issue with the template generating a directory rather than a file is, you cannot mount a directory to a config file path. So running a task that uses the Nomad docker driver with the exemplar 'docker' volume config results in an error. \n\nvolumes = [\"/path/to/job/folder/default.conf:/etc/nginx/conf.d/default.conf\" ]\n\n\nOr is it impossible to have the template stanza generate a config file?\n\n*P.s. Using Nomad build 0.5.5**"
] | [
"nginx",
"docker",
"consul",
"consul-template",
"nomad"
] |
[
"Accessing variable within Struct Pointer produces Segmentation fault at run time - C",
"I've been working on this problem for quite some time now, can't seem to find an answer anywhere. The problem is fairly simple, I was given a sample program and asked to fix the error (This is a homework problem for University). \n\nHere is the program in C:\n\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct \n{\n int a;\n char *b;\n} Cell;\nvoid AllocateCell(Cell * q) \n{\n\n q =(Cell*) malloc (sizeof(Cell));\n q->b = (char*)malloc(sizeof(char));\n\n}\nint main (void) \n{\n\n Cell * c;\n AllocateCell(c);\n c->a = 1; // Produces Seg Fault\n\n free(c);\n return 0;\n}\n\n\nThe Segmentation fault is produced by the line:\n\nc->a = 1;\n\n\nClearly the seg fault comes from some part of the memory allocation, but I'm not quite sure from where."
] | [
"c",
"pointers",
"struct",
"dynamic-memory-allocation"
] |
[
"jquery.jqGrid.min.js:14 Uncaught TypeError: Cannot read property '0' of undefined",
"In my application in jqgrid form i want to upload file as well as post data simultaneously.Where i am using jquery version as as jquery-3.1.1.js and jqgrid version as 5.2.0 .\nAs i have read on intenet its not possible to upload file&post data in jqgrid simultaneously.So after submitting data other than file ,you can upload file through ajaxFileUploadmethod.As I am using latest version of jquery,its not possible to upload file through this function.So my question is :-1)what is above error & how to remove it2)how to upload file in jqgrid without ajaxfile uploadThanks in advance"
] | [
"jquery",
"jqgrid"
] |
[
"Netty Byte Array Decoder",
"I have problem using Netty 4.0 for handle data GPS, i don't have any problem if less than 10 Device, but problem occured if more than that,\n\nPacket data send by gps is begin with 0x78 0x78 and ended with 0XD and 0XA, so i have implements channdle handle like below:\n\n private void init(int port) {\n ServerBootstrap bootstrap = new ServerBootstrap();\n bootstrap.group(bossGroup, workerGroup);\n bootstrap.channel(NioServerSocketChannel.class);\n bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {\n @Override\n protected void initChannel(SocketChannel ch) throws Exception {\n // Decoders\n byte delimiter[] = {0x0d,0x0A};\n ch.pipeline().addLast(\"frameDecoder\",new DelimiterBasedFrameDecoder(1024, Unpooled.wrappedBuffer(delimiter)));\n ch.pipeline().addLast(new ProtocolDecoder());\n }\n });\n listServer.add(new ServerTracker(bootstrap, port, \"XDevice\"));\n}\n\n\nProblem:\nwhen first time device connect, i can read header 0x78 0x78, but next messages not always begin with 0x78 0x78\nWhat the problem with my code?"
] | [
"java",
"netty"
] |
[
"Java MySQL missing driver?",
"I'm trying to make my program read/write in a database. I found this sample code to connect which compiles without problems:\n\n\"http://webhelp.ucs.ed.ac.uk/services/mysql/example2-java.php\"\n\nbut Im having issues running it. Whenever I execute I get \n\nFailed to load mysql driver\njava.lang.ClassNotFoundException: com.mysql.jdbc.Driver\n\n\nDo I need to download the driver manually and supply it through classpath or is it already given in java?\n\nEDIT Alright, so I downloaded the driver but how can I run it with classpath to use the driver? I got this as my batch command but it gives me an error:\n\njava -classpath driver/mysql.jar MySQL\n\n\nand the error is\n\nError: Could not find or load main class MySQL\n\n\nWhile without the classpath it finds the MySQL class :S\n\nEDIT FIGURED IT OUT :D\n\njava -cp .;./driver/mysql.jar MySQL"
] | [
"java",
"mysql",
"driver"
] |
[
"!== Comparison Operator Should Be True but Isn't",
"function nonUniqueElements(data) {\r\n var duplicates = [];\r\n var compArr = data;\r\n\r\n for (var i = 0; i < data.length; i++) {\r\n for (var j = 0; j < compArr.length; j++) {\r\n console.log('Comparing ' + data[i] + ' to ' + compArr[j]);\r\n if (data[i] === compArr[j]) {\r\n console.log('Found match first pass');\r\n console.log(data.indexOf(i), compArr.indexOf(j));\r\n if (data.indexOf(i) !== compArr.indexOf(j)) {\r\n console.log('Also passes second pass')\r\n console.log('Pushing ' + data[i] + ' to new array')\r\n duplicates.push(data[i]);\r\n console.log(duplicates);\r\n }\r\n }\r\n }\r\n console.log('End of run through');\r\n }\r\n\r\n return (duplicates);\r\n}\r\n\r\nconsole.log(nonUniqueElements([5, 5, 5, 5]));\r\n\r\n\r\n\n\nI'm trying to return all non-unique values in an array. I've duplicated the array and am running a nested loop to compare the copy against the original.\n\nWhen it finds a match (in this case every time), there's a second check to ensure that only values at a different index are pushed to a new array.\n\nI've put some console.log()s to help me step through the program. Even when console.log(data.indexOf(i), compArr.indexOf(j)) is printing different values, the block of code in the if (data.indexOf(i) !== compArr.indexOf(j)) statement isn't running.\n\nAny ideas?"
] | [
"javascript",
"arrays",
"if-statement",
"comparison"
] |
[
"JavaScript function from PHP",
"I have a JavaScript function, pop_item. I have to call this from PHP, so my PHP code is the following:\n\necho '<a href=\"javascript:pop_item('.$_code.',1)\">Link </a>';\n\n\nIt provides no error, but pop_item is not functioning,\n\nThe HTML output for the above is:\n\n<a href=\"javascript:pop_item('ABC',1)\">Link </a>"
] | [
"php",
"javascript"
] |
[
"Frustrating but quite common taking SNAPSHOT problem!",
"Taking photos using system provided component(MediaStore.ACTION_IMAGE_CAPTURE) is quit common.\n\nAs Ive experimented, with a certain rate the android system will kill the snapshot calling Activity to prevent memory related exception, and the calling activity will be created again where returned. Thus I have to save the states of the calling Activity via onSaveInstanceState, and retrieve them via onRestoreInstanceState. (If Im not correct and there is further info, please point it out)\n\nHowever, I also found out that, when the killing occurs, all my information stored in the RAM were ERASED, RESETED, for example those Singleton class type objects, or static classes and their fields!\n\nThis mechanism is so frustrating, how to handle such situation??"
] | [
"android",
"android-activity",
"snapshot"
] |
[
"How to add several documents using capped collection via mongodb Java driver 3.4+?",
"I want to add several document using capped collection and writing like:\n\n// this code insert only first document using capped collection \nMongoDatabase database = mongoClient.getDatabase(\"db\");\n database.createCollection(\"capped_collection\",\n new CreateCollectionOptions().capped(true).sizeInBytes(536870912).maxDocuments(5000));\n\n MongoCollection<Document> collection = database.getCollection(\"capped_collection\");\n\n Document found = database.getCollection(\"capped_collection\").find(new Document(\"title\", title)\n .append(\"url\", url)\n .append(\"img\", img)\n .append(\"price\", price)).first();\n\n if (found == null) {\n\n collection.insertOne(new Document(\"title\", title)\n .append(\"url\", url)\n .append(\"img\", img)\n .append(\"price\", price));\n\n mongoClient.close();\n }\n\n\nIn this case capped collection gives me to insert only first document and that's all (I want several not one). If I create normal collection I can insert several docs. Why it happens?\n\nMongoDatabase database = mongoClient.getDatabase(\"db\");\n MongoCollection<Document> collection = database.getCollection(\"normal_collection\");\n\n Document found = database.getCollection(\"normal_collection\").find(new Document(\"title\", title)\n .append(\"url\", url)\n .append(\"img\", img)\n .append(\"price\", price)).first();\n\n if (found == null) {\n collection.insertOne(new Document(\"title\", title)\n .append(\"url\", url)\n .append(\"img\", img)\n .append(\"price\", price));\n\n mongoClient.close();\n }\n\n\nIn this way I can insert several documents using normal collection.\n\nAs I understand properly, there is no difference in the code between inserting documents into a capped collection and a normal collection, but in fact I have different results.\n\nUpdated:\nJust tried manually to add docs in capped collection via powershell\n\nIn powershell manually could be like:\n\n\nDocuments looks like (as test):\n\n\nCorrect me, please, if I'm wrong. Thanks for help."
] | [
"java",
"mongodb"
] |
[
"Can Embedded Ruby Be Used Outside of Rails?",
"Can embedded ruby (erb) be used outside of rails in regular webpages to dynamically update content (almost as a replacement for PHP)?"
] | [
"ruby",
"erb"
] |
[
"Apache2 Forward proxy with DNS lookup failure for port 443 (SSL) only",
"I had to use a forward proxy to limit the access to limited site. I'd tried this before on Apache 1 and all is okay. \n\nRecently, I setup a RHEL6 Linux box and try to use Apache 2 to do the same thing. However, it always reports the following for any SSL site.\n\nFor example, it can resolve the IP to access to ibank.standardchartered.com.hk but not for ibank.standardchartered.com.hk:443\n\nSeems it does something DNS lookup in the local proxy server but not in the main proxy.\nBut when I manually add the ibank.standardchartered.com.hk to local server host table, it works.\n\n - - [25/Apr/2012:17:44:00 +0800] \"GET http://www.standardchartered.com.hk/_images/zh/menu1_sub.gif HTTP/1.1\" 304 -\n - - [25/Apr/2012:17:44:00 +0800] \"GET http://www.standardchartered.com.hk/_images/zh/menu2_sub.gif HTTP/1.1\" 304 -\n - - [25/Apr/2012:17:44:00 +0800] \"GET http://www.standardchartered.com.hk/_images/zh/menu5_sub.gif HTTP/1.1\" 304 -\n - - [25/Apr/2012:17:44:00 +0800] \"GET http://www.standardchartered.com.hk/_images/zh/menu6_sub.gif HTTP/1.1\" 304 -\n - - [25/Apr/2012:17:44:00 +0800] \"GET http://www.standardchartered.com.hk/_images/zh/menu7_sub.gif HTTP/1.1\" 304 -\n - - [25/Apr/2012:17:44:00 +0800] \"GET http://www.standardchartered.com.hk/_images/zh/menu8_sub.gif HTTP/1.1\" 304 -\n\nV2.12\n[Wed Apr 25 16:52:34 2012] [error] [client ] proxy: DNS lookup failure for: ibank.standardchartered.com.hk returned by ibank.standardchartered.com.hk:443\n[Wed Apr 25 16:53:29 2012] [error] [client ] proxy: DNS lookup failure for: www.google.com returned by www.google.com:443\n[Wed Apr 25 17:47:04 2012] [error] [client ] proxy: DNS lookup failure for: ibank.standardchartered.com.hk returned by ibank.standardchartered.com.hk:443\n[Wed Apr 25 17:47:04 2012] [error] [client ] proxy: DNS lookup failure for: ibank.standardchartered.com.hk returned by ibank.standardchartered.com.hk:443\n\nv2.4\n[Wed Apr 25 16:36:53.387721 2012] [proxy:error] [pid 8024:tid 140494533285632] [client ] AH00898: DNS lookup failure for: ibank.standardchartered.com.hk returned by ibank.standardchartered.com.hk:443\n[Wed Apr 25 16:36:53.387932 2012] [proxy:error] [pid 8024:tid 140494533285632] [client ] AH00898: DNS lookup failure for: ibank.standardchartered.com.hk returned by ibank.standardchartered.com.hk:443\n\n\nHere is my configuration:\n\n# LoadModule foo_module modules/mod_foo.so\nLoadModule headers_module modules/mod_headers.so\nLoadModule proxy_module modules/mod_proxy.so\nLoadModule proxy_connect_module modules/mod_proxy_connect.so\nLoadModule proxy_ftp_module modules/mod_proxy_ftp.so\nLoadModule proxy_http_module modules/mod_proxy_http.so\nLoadModule proxy_ajp_module modules/mod_proxy_ajp.so\nLoadModule proxy_balancer_module modules/mod_proxy_balancer.so\n....\n\nProxyRequests On\nProxyVia On\n\nProxyRemote * http://proxy.main.com:8080\n\n<Proxy *>\nOrder deny,allow\nDeny from none\nAllow from all\n</Proxy>\n\n\nIt is impossible to put all the internet ssl entry into host table.\nDoes anyone can solve this?\n\nThanks\n\nUpdate on 26-Apr: Finally, I found no solution and change to use Squid."
] | [
"ssl",
"apache2",
"mod-proxy"
] |
[
"How to create nested lists in Pyspark using collect_list over a window?",
"I have a Spark DF I aggregated using collect_list and PartitionBy to pull lists of values associated with a grouped set of columns. As a result, for the grouped columns, I now have a new column containing a list of the elements associated with group. However, I would like this list to be further broken down so it contains nested lists. It's also important that the order of these columns is sorted by Date. See below:\ndata = [\n ["ABC", 1, 3, "2020-04-01", "product_one"],\n ["ABC", 1, 3, "2020-04-01", "product_two"],\n ["ABC", 1, 3, "2020-04-12", "product_one"],\n ["ABC", 1, 3, "2020-04-12", "product_two"],\n]\n\ndf = pd.DataFrame(data, columns=["ID", "Ref_No", "Number", "Date", "Product"])\nsdf = spark.createDataFrame(df)\n\nw = Window.partitionBy("ID", "Ref_No", "Number").orderBy("Date")\n\ngrouped_sdf = (\n sdf.withColumn(\n "Products",\n spark_fns.collect_list("Product").over(w),\n )\n .withColumn(\n "Dates",\n spark_fns.collect_set("Date").over(w),\n )\n .groupby("ID", "Ref_No", "Number")\n .agg(\n spark_fns.max("Products").alias("Products"),\n spark_fns.max("Dates").alias("Dates"),\n )\n)\n\nID Ref_No Number Products Dates\nABC 1 3 [product_one, [2020-04-01,\n product_two, 2020-04-12]\n product_one, \n product_two] \n\nI would like the lists in the column Products to actually contain lists as well, associated with each timing. So the desired output is:\nSo we know that the first list (within the list) is associated with the first date, and then second list within the list is associated with the second.\nID Ref_No Number Products Dates\nABC 1 3 [[product_one, [2020-04-01,\n product_two], 2020-04-12]\n [product_one, \n product_two]]"
] | [
"python",
"list",
"apache-spark",
"pyspark",
"apache-spark-sql"
] |
[
"What's the recommended way to import `unittest` or `unittest2` depending on python version",
"I have this little test.py script I needs to get it running on our CI. In our local machines, most people use python 2.7, so import unittest works. But in the CI, the environment is python 2.6, which means import unittest2.\n\nCurrently, I'm invoking the script via \n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(message)s')\n import xmlrunner\n unittest2.main(testRunner=xmlrunner.XMLTestRunner(output='xml-reports'))"
] | [
"python",
"python-unittest"
] |
[
"How to display Google Photos album in the mobile browser?",
"I'm developing client-side React app. The application should display gallery of photos from Google Photos. I'm using Firebase to store a short url to album (f.e. https://photos.app.goo.gl/[ALBUM_ID] and an album's title. Then I request the url and extract images by regex. On dekstop version everything works. When I run it on mobile I can't get any photos. If I enter directly the url to album in the mobile browser, Google Photos app is opening. If on mobile device I switch to \"Desktop version\" it works fine.\nIs there any way to override this behaviour?\n\nI tried to set content width to 1024. It doesn't help.\n\n<meta name=\"viewport\" content=\"width=1024\" />\n\n\nclass Album extends Component {\n state = {\n images: null,\n fullscreen: false,\n currentIndex: 0,\n loading: false\n }\n\nasync componentDidMount() {\n await this.setImages();\n }\n\n async setImages() {\n if (!this.currentAlbumId || this.currentAlbumId !== this.props.match.params.id) {\n this.currentAlbumId = this.props.match.params.id;\n\n if (!this.state.loading) {\n this.setState({ loading: true });\n }\n\n const album = await this.getAlbum(this.props.match.params.id);\n const links = this.extractPhotos(album);\n\n if (links && links.length > 0) {\n this.setState({\n images: links.map((url) => ({\n src: `${url}=w1024`,\n width: 16,\n height: 9\n })),\n })\n }\n this.setState({ loading: false });\n }\n }\n\n async getAlbum(id) {\n // https://google-photos-album-demo.glitch.me/{id}\n const response = await Axios.get(`${'https://cors-anywhere.herokuapp.com/'}https://photos.app.goo.gl/${id}`);\n return response.data;\n }\n\n extractPhotos(content) {\n const regex = /\\[\"(https:\\/\\/lh3\\.googleusercontent\\.com\\/[a-zA-Z0-9\\-_]*)\"/g;\n\n const links = new Set()\n let match\n while (match = regex.exec(content)) {\n links.add(match[1])\n }\n return Array.from(links)\n }"
] | [
"javascript",
"reactjs",
"mobile-browser",
"google-photos"
] |
[
"Is it necessary to split data into three; train, val and test?",
"Here the difference between test, train and validation set is described. In most documentation on training neural networks, I find that these three sets are used, however they are often predefined. \n\nI have a relatively small data set (906 3D images in total, the distribution is balanced). I'm using sklearn.model_selection.train_test_split function to split the data in train and test set and using X_test and y_test as validation data in my model. \n\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2, random_state=1)\n...\nhistory = AD_model.fit(\n X_train, \n y_train, \n batch_size=batch_size,\n epochs=100,\n verbose=1,\n validation_data=(X_test, y_test))\n\n\nAfter training, I evaluate the model on the test set:\n\ntest_loss, test_acc = AD_model.evaluate(X_test, y_test, verbose=2)\n\n\nI've seen other people also approach it this way, but since the model has already seen this data, I'm not sure what the consequences are of this approach. Can someone tell me what the consequences are of using the same set for validation and testing? And since I already have a small data set (with overfitting as a result), is it necessary to split the data in 3 sets?"
] | [
"python",
"tensorflow",
"keras",
"scikit-learn",
"conv-neural-network"
] |
[
"Most common/liked syntax for in-code documentation (comments)?",
"I've been coding PHP with Notepad++ for years now, but today I downloaded Eclipse IDE. One of its features is auto-completing certain \"syntax-patterns\", such as comments. I've seen a lot of different ways to implement comments and documentation into php-files, so now I started wondering, should I follow the syntax Eclipse suggests.\n\nHere's a snap of what I mean:\n\n\nWhat do you think?\n\nMartti Laine"
] | [
"php",
"eclipse",
"syntax",
"comments"
] |
[
"Deciphering a Confusing Function Prototype",
"I have the following function prototype:\n\nchar *(*scan)(char *, char *, char *, char *, int , int);\n\n\nscanleft() is a function and has the type of static char *.\n\nWhen I try to compile, I found that there is a pointer type mismatch between scan and scanleft.\n\nif ((subtype & 1) ^ zero) scan = scanleft; else scan = scanright;\n\n\nWhat does the prototype of scan() mean?"
] | [
"c"
] |
[
"Action.Submit on Adaptive Cards not working with Input.Text Python SDK",
"I am trying the adaptive cards with the Bot Builder v4 Python SDK. I am trying to gather feedback from the user using the Input.text field and then the Action.submit \n\n{\n\"$schema\": \"http://adaptivecards.io/schemas/adaptive-card.json\",\n\"type\": \"AdaptiveCard\",\n\"version\": \"1.0\",\n\"body\": [ \n],\n\"actions\": [{\n \"type\": \"Action.ShowCard\",\n \"title\": \"Want to provide feedback\",\n \"card\": {\n \"type\": \"AdaptiveCard\",\n \"actions\": [\n {\n \"type\": \"Action.Submit\",\n \"data\": \"Yes, it was helpful\",\n \"title\": \"Yes\"\n },\n {\n \"type\": \"Action.Submit\",\n \"data\": \"No, it wasn't helpful\",\n \"title\": \"No\"\n },\n {\n \"type\": \"Action.Submit\",\n \"data\": \"Start Over\",\n \"title\": \"Start Over\"\n },\n {\n \"type\": \"Action.Submit\",\n \"data\": \"Exit\",\n \"title\": \"Exit\"\n },{\n \"type\": \"Action.ShowCard\",\n \"title\": \"Comment\",\n \"card\": {\n \"type\": \"AdaptiveCard\",\n \"body\": [\n {\n \"type\": \"Input.Text\",\n \"id\": \"comment\",\n \"isMultiline\": true,\n \"placeholder\": \"Enter your comment\"\n }\n ],\n \"actions\": [\n {\n \"type\": \"Action.Submit\",\n \"title\": \"OK\"\n }\n ]\n }\n }\n ]\n }\n }\n]}\n\n\nThis is working well on the visualizer. When I write some comments and and click on OK, this works on the visualizer but does not work in practice. It raises a 502 error.\n\nSee below screenshot\n\n\nI'm using the Bot Build v4 SDK for Python and testing this on Web Chat. It seems there is no issue on the Adaptive Card side of this, I suppose this has something to do with the Python SDK. Any pointers as to where the error might be ?"
] | [
"botframework",
"azure-bot-service"
] |
[
"Codeigniter automatic redirect to a friendly url not working",
"I need to redirect the url http://domainname/foldername/functionname/dynamicstring to http://domainname/foldername/dynamicstring . \n\nI have added this in my route\n\n\r\n\r\n$route['([a-zA-z_]+)'] = 'controllername/functionname/$1';\r\n\r\n\r\n\n\nand i am able to access this url http://domainname/foldername/dynamicstring only when i type it in url. \nOtherwise on clicking buttons, the site is redirecting to http://domainname/foldername/functionname/dynamicstring which now shows 404 not found.\n\nView page code\n\n\r\n\r\n<a href=\"<?php echo base_url('functionname');?>/<?php echo $dynamicstring ;?>\"></a>\r\n\r\n\r\n\n\nController\n\n\r\n\r\npublic function functionname($dynamicstring)\r\n {\r\n $data['fun1'] = $this->Modelname->fun1($dynamicstring);\r\n $data['fun2'] = $this->Modelname->fun2($dynamicstring);\r\n $this->load->view('folder/viewpage',$data);\r\n }\r\n\r\n\r\n\n\nCan someone help me with this?"
] | [
".htaccess",
"codeigniter",
"url",
"dynamic",
"routes"
] |
[
"TypeError: FormListView() missing 1 required positional argument: 'request'",
"I am newbie in django and i have a problem.\nWhen starting the server, the following error occurs:\nFile "/home/user/Portfolio/web_project/web_page/urls.py", line 5, in <module>\n path('', FormListView(), name = 'home'),\nTypeError: FormListView() missing 1 required positional argument: 'request'\n\nI understand that I am not writing the requests correctly, but now I do not understand what exactly the problem is.\nurls.py:\nfrom django.urls import path\nfrom .views import FormListView\n\nurlpatterns = [\n path('', FormListView(), name = 'home'),\n path('success/', Success(), name = 'success')\n]\n\nviews.py:\nfrom django.core.mail import send_mail, BadHeaderError\nfrom django.shortcuts import render, redirect\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom .models import Form\nfrom django.views.generic import TemplateView\n\ndef FormListView(request):\n if request.method == 'GET':\n form = FormListView()\n else:\n form = FormListView(request.POST)\n if form.is_valid():\n name = form.cleaned_data['name']\n surname = form.cleaned_data['surname']\n email = form.cleaned_data['email']\n try:\n send_mail(name, surname, email, ['[email protected]'])\n except BadHeaderError:\n return HttpResponse('Invalid')\n return redirect('success')\n return render(request, "index.html", {'form': form})\n\ndef Success(request):\n return HttpResponse('Success!')"
] | [
"python",
"python-3.x",
"django",
"django-views"
] |
[
"Why do i get a \"404 not found\" error on IE(not Chrome) in node.js express? and how to solve?",
"I'm making web server with node.js and express module.\n\nSo, I installed node.js, express and express-generator.\n\nAnd I completed a prototype web server for my project yesterday.\n\nBut, when I tested my prototype, I have a strong question.\n\nIn Chrome, I could connect for URL like '127.0.0.1:3000'\n\nor '172.30.5.164:3000'(this is my intranet ip address).\n\nBut!!\n\nIn Explorer, I could't connect!! \n\nSo, I tried to find the way.\n\nI solved the 127.0.0.1:3000 problem.\n\nJust I changed Explorer configuration for intranet and I could connect \n\nlike this way 'http://localhost:3000'\n\nHowever,\n\nI didn't find the way how to connect use URL like http://172.30.5.164:3000\n\nI don't use socket.io module, just use basic express-generator template like GET/POST way.\n\nI need how to connect on IE strongly because my project is related to OLE Automation, So I have to use ActiveXObject.\n\nAnyone who give me the hint?\n\nI'm not good at english writing, so i got to worry about that you understand my problem.\n\nThanks in advance."
] | [
"javascript",
"node.js",
"google-chrome",
"internet-explorer",
"express"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.