texts
sequence | tags
sequence |
---|---|
[
"Using Extensions: Weighing The Pros vs Cons",
"Recently I asked a question about how to clean up what I considered ugly code. One recommendation was to create an Extension Method that would perform the desired function and return back what I wanted. My first thought was 'Great! How cool are Extensions...' but after a little more thinking I am starting to have second thoughts about using Extensions...\n\nMy main concern is that it seems like Extensions are a custom 'shortcut' that can make it hard for other developers to follow. I understand using an Extension can help make the code syntax easier to read, but what about following the voice behind the curtain? \n\nTake for example my previous questions code snippet:\n\nif (entry.Properties[\"something\"].Value != null)\n attribs.something = entry.Properties[\"something\"].Value.ToString();\n\n\nNow replace it with an Extension:\n\npublic static class ObjectExtensions\n{\n public static string NullSafeToString(this object obj)\n {\n return obj != null ? obj.ToString() : String.Empty;\n }\n}\n\n\nand call using the syntax:\n\nattribs.something = entry.Properties[\"something\"].Value.NullSafeToString();\n\n\nDefinetely a handy way to go, but is it really worth the overhead of another class object? And what happens if someone wants to reuse my code snippet but doesn't understand Extension? I could have just as easily used the syntax with the same result:\n\nattribs.something = (entry.Properties[\"something\"].Value ?? string.Empty).ToString()\n\n\nSo I did a little digging and found a couple of articles that talked about the pros/cons of using Extensions. For those inclined have a look at the following links:\n\nMSDN: Extension Methods\n\nExtension Methods Best Practice\n\nExtension Methods\n\nI can't really decide which is the better way to go. Custom Extensions that do what I want them to do or more displayed code to accomplish the same task? I would be really interested in learning what 'real' developers think about this topic..."
] | [
"c#",
"extension-methods"
] |
[
"Handling timers for many users in Nodejs",
"I'm building a web app in Node/Express such that users can set a timer so that a certain task gets executed or repeated. My question is how can I set timer for many users with an event triggered after deadline. I don't want to handle this on the client side beacuse users can close the browser. A good example of this is services such as pingdom.com that allow you to set timer and send a ping every X minutes to your server. How can this be acheived?\nI hope I don't get many negatives for asking this and I'm also not asking you guys to write me the code. I simply want to know a robust strategy to solve this problem. \nHere is what I thought about:\n\n\nSave the endtime in db and using a cron job check every second to see if the time is up (This is not really good in my opinion since the query and all calculations might take more than 1 second)\nSomehow assign a variable to setInterval and store them in a global list"
] | [
"javascript",
"node.js",
"timer",
"cron"
] |
[
"django, how to trigger Ajax error function()",
"The scenario is adding an item to a cart and also choosing a fabric with it. Two errors I want to show with an alert pop up:\n\na) when either when no color is selected / e.g. general error\n\nb) Only 1 item with the same fabric allowed per cart\n\n\nPutting out the (a) general error message works.\nBut I'm unsure how to trigger the error alert of my ajax from the if statement in my view from django.\nMy Ajax form:\nvar productForm = $(".form-product-ajax")\n productForm.submit(function(event){\n event.preventDefault();\n var thisForm = $(this)\n var actionEndpoint = thisForm.attr("data-endpoint");\n var httpMethod = thisForm.attr("method");\n var formData = thisForm.serialize();\n\n $.ajax({\n url: actionEndpoint,\n method: httpMethod,\n data: formData,\n success: function(data){\n var submitSpan = thisForm.find(".submit-span")\n if (data.added){\n $.alert({\n title: "Success",\n content: "Product added",\n theme: "modern",\n })\n submitSpan.html("<button type='submit' class='btn btn-success'>Add to cart</button>")\n } \n },\n error: function(errorData){\n $.alert({\n title: "Oops!",\n content: data.message,\n theme: "modern"\n })\n }\n })\n })\n\nDjango carts.view simplified\ndef cart_update(request): \n added = False\n error_messages = "Please check your selections."\n\n if str(product_obj.type).lower() == "fabric":\n cart_obj, new_obj = Cart.objects.new_or_get(request)\n fabric_obj = str(Fabric.objects.filter(name__contains=fabric_select).first())\n for item in cart_obj.choices.all():\n if fabric_obj == item.fabric_note: \n error_messages = "You've reached the maximum order amount for this fabric." \n # how to trigger ajax error: function() here to give it the new error_message \n\n else: \n added = True\n cart_obj.choices.add(choices_obj)\n\n if request.is_ajax():\n json_data = {\n "added": added,\n "message": error_messages,\n }\n return JsonResponse(json_data)\n\nAlso is using the error_message for ajax's data.message fine to use? Or is there an easier way having two different error alerts coming up with ajax?"
] | [
"json",
"django",
"ajax"
] |
[
"Pandas - Select rows from a dataframe based on list in a column",
"This thread Select rows from a DataFrame based on values in a column in pandas shows how you can select rows if the column contains a scalar. How can I do so if my column contains a list of varied length?\n\nTo make it simple, assume the values in the list are similar.\n\n label\n0 [1]\n1 [1]\n2 [1]\n3 [1]\n4 [1]\n5 [1]\n6 [1]\n7 [1]\n8 [1]\n9 [1]\n10 [1]\n11 [1]\n12 [1]\n13 [1]\n14 [1]\n15 [1]\n16 [0,0,0]\n17 [1]\n18 [1]\n19 [1]\n20 [1]\n21 [1]\n22 [1]\n23 [1]\n24 [1]\n25 [1]\n26 [1]\n27 [1, 1]\n28 [1, 1]\n29 [0, 0]\n\n\nI tried the following which does not work. What I tried was to check if the last element of the list is equivalent to a scalar.\n\ndf_pos = df[df[\"label\"][-1] == 1]\n\n\nUsing tolist()[-1] returns me only the last row.\n\ndf_pos = df[df[\"label\"].tolist()[-1] == 1]"
] | [
"python",
"pandas"
] |
[
"Why does the Num typeclass have an abs method?",
"I’m thinking about standard libraries (or preludes) for functional languages.\n\nIf I have Ord instance for n, then it is trivial to implement abs:\n\nabs n = if n > 0 then n else (-n)\n\n\nIn the case of vector spaces, the absolute value (length) of a vector is very important. But the type doesn’t match because the absolute value of a vector is not a vector: it is a real number.\n\nWhat was the design rationale behind having abs (or signum) as part of the Num typeclass?"
] | [
"haskell",
"typeclass"
] |
[
"tile file names different between tiles generated with Mobac and loaded from Internet?",
"I want to use offline tiles in an Android app using OSMDROID to avoid downloading via Internet. According to several examples here I started to use Mobac for creating tiles of a certain area in OSM MapQuest format. I also folllowed the instruction to generate jpg-format instead of png. The zip-file was generated too succesfully, but the tiles are not displayed in my app. I also checked the folder structure and I also modified the path \"MapQuest\" to \"MapquestOSM\", but all experiments were not successful. \n\nThe tilesource in my code is set to MAPQUESTOSM and all works fine, when I load the tiles from the Internet, but when I try to read it from my phone-directoy, nothing is displayed. \n\nWhat I have seen is that on my phone the downloaded tiles have the file name \".jpg.tile\", but Mobac generates \".jpg. I extracted the zip file and when I change the file name also to .jpg.tile, then the changed tiles becomes displayed (only the changed ones!). I have not found any issue related to this file name difference!\n\nIn my code I use from examples the setTileSource (works for Internet loading):\n\nmv = (MapView) findViewById(R.id.mapView);\nmv.setUseDataConnection(false);\nmv.setTileSource(TileSourceFactory.MAPQUESTOSM);\n\n\non my Samsung J5 the tiles are loaded from Internet into directory /osmdroid/tiles///.jpg.tile \n\nHas there been a change in the file names or what could be wrong. Nobody seemed to have this problem in the past?"
] | [
"android",
"openstreetmap",
"osmdroid"
] |
[
"What is this \"/\\,$/\"?",
"Tried to search for /\\,$/ online, but coudnt find anything. \nI have:\n\ncoords = coords.replace(/\\,$/, \"\");\n\n\nIm guessing it returns coords string index number. What I have to search online for this, so I can learn more?"
] | [
"javascript"
] |
[
"Ignite server node not able to reconnect",
"I have 2 server nodes working together in the same cluster as accepted\n Topology snapshot [ver=2, servers=2, clients=0, CPUs=8, heap=7.1GB]\n\nIf the connection (LAN) lost and return after a while the nodes wouldn't reconnect\n Topology snapshot [ver=3, servers=1, clients=0, CPUs=8, heap=3.6GB]\n\nHow can server nodes reconnect after the connection lost?\n\nsetting reconnect count will work ?"
] | [
"ignite"
] |
[
"Using `WITH` or `MATCH` clause while extracting paths",
"Before I explain the problem I am facing, I think it would be better if I explain the structure of my graph database a bit. Following are the Nodes, Relationships and Properties in my neo4j graph database:\n\nNodes:\n\n\nUser\nEmail\nPhone\nBook\nBlogPost\n\n\nRelationships:\n\n\nHAS (used as : user -[:HAS]-> (e:Email|Phone))\nREAD (used as : user - [:READ] -> (b:Book|BlogPost))\nWROTE (used as: user - [:WROTE] -> (b:Book|BlogPost))\n\n\nProperties:\n\n\nuid (associated with nodes User, Book, BlogPost, Email, Phone)\nname (associated with node User)\ntitle (associated with nodes Book, BlogPost)\nemail (associated with node Email)\nphone (associeated with node Phone)\n\n\nBefore I actually put up my question I would like to state that I am pretty new to the neo4j technology so I do understand that solution to my problem might be basic.\n\nWhat I am trying to achieve ?\n\nI want to get all the shortest paths between two users and then for each node between those two users in a path I would like to get:\n\n\nThe email address and/or phone number if the node is a User node.\nTitle of the node if it's a Book or a BlogPost node.\n\n\nWhere am I stuck ?\n\nI can get the paths using the following cypher query:\n\nmatch (u1: User {uid: '0001'}),\n(u2: User{uid: '0002'}),\npaths = allShortestPaths((u1)-[*..4]-(u2))\nreturn paths\n\n\nAfter getting the paths I can get the properties of the nodes, relationships in the path using the extract, nodes, relationships functions if I ammend the above query as follows:\n\nmatch (u1: User {uid: '0001'}),\n(u2: User{uid: '0002'}),\npaths= allShortestPaths((u1)-[*..4]-(u2))\nwith extract(n in nodes(paths) | [n.name]) as nds,\nextract(r in relationships(paths)| [type(r)]) as rels\nreturn nds,rels\n\n\nThe problem\n\nBut what I really want to get is the email and phone properties off Email and Phone nodes that are connected to any nodes within a given path.\n\nI have gone through the official documentation and a lot of blog posts but could not find any solution or a similar problem for that matter.\n\nHow can I achieve the above mentioned ?\n\nPS: I would like to achieve this in a single query\n\nThanks"
] | [
"neo4j",
"cypher"
] |
[
"how to visible layout in android",
"am working on android application in which there is two activity that is main activity and mode activity. my first activity is main activity have some invisible icon, \n and second activity is mode activity .when i click on button in my second activity i cam back my first activity i want that invisible icon should visible. \n\nenter code here\n\n pro.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n autobtn.setImageResource(R.drawable.auyto);\n pro.setImageResource(R.drawable.proactiv);\n Intent it = new Intent(ModeActivity.this, Mainactivity.class);\n startActivity(it);\n }\n });"
] | [
"android",
"android-fragments",
"sharedpreferences",
"visibility"
] |
[
"Jquery automatically form submit, but returns nothing",
"I'm using Keith Jquery Countdown 1.5.8 for doing the countdown and the ticking time is working perfectly for every user. i have 2 forms in a single php file (let's say multiform.php) but the form submits nothing when the countdown reaches zero.\n\nHere is my jquery code :\n\n<script type=\"text/javascript\">\n$(function () {\n $('#defaultCountdown').countdown({until: <?php echo($usertime); ?>,\n onExpiry: function() {\n $('#quizform').submit();\n }\n });\n});\n</script>\n\n\nand some of my multiform.php codes are :\n\n<?php\n if($choice==1) {\n?>\n...\n<form action=\"submit.php\" method=\"post\" name=\"quizform\" id=\"quizform\">\n...\n...\n<input type=\"submit\" name=\"save_1\" value=\"Save\" />\n</form>\n\n<?php\n } else {\n?>\n...\n<form action=\"submit.php\" method=\"post\" name=\"quizform\" id=\"quizform\">\n...\n...\n<input type=\"submit\" name=\"save_2\" value=\"Save\" />\n</form>\n\n\nand submit.php consists of :\n\nif(isset($_POST['save_1'])) {\n ...do part 1\n}\nelse {\n ...do part 2\n}\n\n\nThe form submits nothing, none of those text input values submitted to \"submit.php\". It returns blank.\nAm i doing wrong ?"
] | [
"php",
"jquery"
] |
[
"SSRS hide textbox based on number of rows in report",
"I am limiting my report to 10,000 rows in the query (TOP 10000) because if they don't specify parameters (default is all selected) it takes forever to run and to be honest isn't useful. \n\nI created a textbox in the body of the report at the bottom below my tablix. The report has no groupings or totals or anything. I set the Hidden property to be:\n\n=IIf(CountRows(\"MainQuery\")>=1000,False,True)\n\n\nThe text is something like \"More than 9999 results were returned. Report truncated.\"\n\nI get an out of scope error. When I put CountRows(\"MainQuery\") as the value of the text box, it give me the value fine. Why doesn't it like my expression?"
] | [
"reporting-services",
"ssrs-2012"
] |
[
"How to draw text with a shadow like Windows XP does on Desktop icons?",
"Windows XP draws icon text with a nice shadow, which helps to read the text on various backgrounds. The font color is white and the shadow is black (if desktop background is white) or there is no shadow at all (if desktop background is black).\n\nSo there are two sub-tasks:\n\n\nHow the shadow gets drawn? It is not a simple x,y offset of the text; the shadow looks more like a blur to me.\nHow to make shadow to behave the way it becomes more visible on white backgrounds and less visible on dark?\n\n\nI need a solution for GDI (not GDI+)."
] | [
"windows-xp",
"gdi",
"shadow",
"drawtext"
] |
[
"Filtering ListFragment Through SearchView",
"enter image description hereI’m having trouble with making the listfragment searchable with Search Widget after filtering it through searchView.setOnQueryTextListener new SearchView.OnQueryTextListener.\n\nThe code:::\n\n @Override\n public void onActivityCreated(Bundle savedInstanceState) {\n super.onActivityCreated(savedInstanceState);\n\n setHasOptionsMenu(true);\n\n adapter = new ArrayAdapter<String>(\n getActivity(), android.R.layout.simple_list_item_activated_1,\n hymns.HYMN_HEAD);\n\n setListAdapter(adapter);\n\n View detailsFrame = getActivity().findViewById(R.id.details);\n\n mDuelPane = detailsFrame!= null && detailsFrame.getVisibility() == View.VISIBLE;\n\n\n if(savedInstanceState != null){\n\n mCurCheckPosition = savedInstanceState.getInt(\"curChoice\", 0);\n }\n\n if(mDuelPane){\n getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);\n showDetails(mCurCheckPosition);\n }\n\n };\n\n searchView.setOnQueryTextListener new SearchView.OnQueryTextListener(){ \n\n @Override\n public boolean onQueryTextSubmit(String query) { \n return true;\n } \n\n @Override\n public boolean onQueryTextChange(String newText) {\n adapter.getFilter().filter(query); return true;\n }\n }\n\n\nThe filter works but when the searched items are clicked, it will not return the index true position in the details activity. For instance, if an item is in 77th position in the original listview, and you try to search through by filtering, and after filtering, the said 77th item is now the number 1 position of the filters, when clicked, instead of returning the 77th position of the details activity, it returns the number one details of the original listview.\nI hope you can help me with this as I’m a baby programmer. Thanks Sir\n\nenter image description here\n\nenter image description here"
] | [
"android",
"android-studio"
] |
[
"Can not setStatusBarOrientaion in IOS6",
"Orientation status not change when I use UINavigationController.\nthis is my code:\n\nAppDelegate.h file\n\n#import <UIKit/UIKit.h>\n@class MainViewController;\n@interface AppDelegate : UIResponder<UIApplicationDelegate>\n@property (strong, nonatomic) UIWindow *window;\n@property (strong, nonatomic) MainViewController *mainViewController;\n@end\n\n\nAppDelegate.m file\n\n...\n\n-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDistionary* launchOptions\n{\nself.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds]];\nself.mainViewController = [[MainViewController alloc]initWithNibName:@\"MainViewController\" bundle:nil];\nUINavigateionController *navigationController = [[UINavigationController alloc]initWithRootViewController:self.mainViewController];\nself.window.rootViewController = navigationController;\n[self.window makeKeyAndVisible];\nreturn YES;\n}\n....\n\n\nMainViewController.m\n\n...\n-(NSUInteger)supportedInterfaceOrientations{\n return UIInterfaceOrientationMaskLandscapeLeft;\n}\n-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{\n return UIInterfaceOrientationMaskLandscapeLeft;\n}\n-(BOOL)shouldAutorotate{\n return YES;\n}\n-(void) viewDidAppear:(BOOL)animated {\n\n [UIApplication sharedApplication].statusBarOrientation = UIInterfaceOrientationLandscapeLeft;\n [self.navigationController setNavigationBarHidden:YES];\n}\n..."
] | [
"ios6"
] |
[
"Creating a script that checks to see if each word in a file",
"I am pretty new to Bash and scripting in general and could use some help. Each word in the first file is separated by \\n while the second file could contain anything. If the string in the first file is not found in the second file, I want to output it. Pretty much \"check if these words are in these words and tell me the ones that are not\"\n\nFile1.txt contains something like:\n\ndog\ncat\nfish\nrat\n\n\nfile2.txt contains something like:\n\ndog\nbear\ncatfish\n\n\nmagic ->rat\n\nI know I want to use grep (or do I?) and the command would be (to my best understanding):\n\n$foo.sh file1.txt file2.txt\n\n\nNow for the script...\n\nI have no idea...\n\ngrep -iv $1 $2"
] | [
"bash",
"shell",
"awk"
] |
[
"Retrofit Interceptor not adding query param to URL",
"I'm trying to add apikey in the URL using custom interceptor but it's not adding the params in the URL so response body is null.\n\nCustomInterceptor\n\nclass CustomInterceptor : Interceptor {\n\n override fun intercept(chain: Interceptor.Chain): Response {\n\n val url = chain.request().url().newBuilder()\n .addQueryParameter(\"apiKey\", API_KEY)\n .build()\n\n val request = chain.request().newBuilder()\n .url(url)\n .build()\n\n return chain.proceed(request)\n }\n}\n\n\nClient\n\nclass Client {\n\n companion object {\n\n const val API_KEY = \"123123\"\n private const val apiUrl = \"https://www.omdbapi.com/\"\n\n fun <T> create(service: Class<T>): T {\n val client = OkHttpClient.Builder()\n .addInterceptor(CustomInterceptor())\n .build()\n\n return Retrofit.Builder()\n .baseUrl(apiUrl)\n .addConverterFactory(GsonConverterFactory.create())\n .client(client)\n .build()\n .create(service)\n }\n }\n}\n\n\nIMovie\n\ninterface IMovie {\n\n @GET(\"/\")\n fun searchMovie(@Query(\"s\") query: String): Call<SearchResult>\n}\n\n\nAfter sending the request the response body is null and this is the\n\nActual URL:- https://www.omdbapi.com/?s=Man\n\nExpected URL:- https://www.omdbapi.com/?s=Man&apikey=123123"
] | [
"android",
"kotlin",
"retrofit"
] |
[
"id value needs a default value according to error 1364?",
"I want to create two tables. practice has a AUTO_INCREMENT attachment and is a PRIMARY KEY. continued has the id entity continued_id which exists as a FOREIGN KEY that references practice(user_id). Mysql executes the code below fine until line 19, where I receive the 1364 error, stating that continued_id has no default value.\n\nI am confused. I thought that user_id, which auto_increments, and it being the PK, would have a defining value of 1,2,3... I thought that continued_id is equivalent to user_id, and therefore its default value is 1? Perhaps I am misunderstanding how PK's and FK's actually work in sql?\n\nError:\n\n20:03:02 INSERT INTO continued(hobby) VALUES(\"Tennis\") Error Code: 1364. Field 'continued_id' doesn't have a default value 0.000 sec\n\n\n\nCREATE TABLE practice(\n user_id INT AUTO_INCREMENT PRIMARY KEY NOT NULL,\n user_name VARCHAR(60) NOT NULL,\n user_real_name VARCHAR(60) NOT NULL\n);\nCREATE TABLE continued(\n continued_id INT NOT NULL,\n FOREIGN KEY(continued_id)REFERENCES practice(user_id),\n hobby VARCHAR(25) NOT NULL\n);\nINSERT INTO practice(user_name,user_real_name)\nVALUES(\"KittenKing\",\"Henry\");\nINSERT INTO practice(user_name,user_real_name)\nVALUES(\"DogDictator\",\"Mary\");\nINSERT INTO practice(user_name,user_real_name)\nVALUES(\"HamsterHam\",\"Denver\");\n\nINSERT INTO continued(hobby)\nVALUES(\"Tennis\");\nINSERT INTO continued(hobby)\nVALUES(\"Hockey\");\nINSERT INTO continued(hobby)\nVALUES(\"Spear Hunting\");\n\nSELECT * FROM practice,continued;"
] | [
"mysql",
"sql",
"foreign-keys",
"primary-key",
"mysql-error-1364"
] |
[
"How to post bulk data to elastic search?",
"I am trying to do bulk insert to elastic search. Below is the code\n\nimport re\nfname = 'meta_info.csv'\ndf = pd.read_csv(fname)\ndf = df.iloc[5:9,:]\ndf.reset_index(inplace = True)\ndf.rename(columns ={\"index\":\"temp\", \"investment_name\":\"names\"}, inplace = True)\ndf['create'] = df[\"temp\"].apply(lambda x: json.dumps({\"create\":{\"_id\":x}}))\ndf[\"names1\"] = df[\"names\"].apply(lambda x: json.dumps({\"names\":x}))\ndf['final'] = df['create']+r\"@\"+ df['names1']\n\ns = df['final'].str.cat(sep = r\"@\")\ns = s+\"@\"\ns1 = re.sub(r\"@\", r'\\n', s)\n\nurl = 'http://localhost:9200/my_index/_bulk'\nresponse = requests.post(url, headers=headers1, data= s1)\nprint(response.content)\n\n\ns1 - Fed into request:\n\n{\"create\": {\"_id\": 5}}\n{\"names\": \"Birla Sun Life Fixed Maturity Plan - Annual Series 3-Growth\"}\n{\"create\": {\"_id\": 6}}\n{\"names\": \"Birla Sun Life Fixed Maturity Plan - Annual Series 1-Dividend\"}\n{\"create\": {\"_id\": 7}}\n{\"names\": \"Birla Sun Life Fixed Maturity Plan - Annual Series 1-Growth\"}\n{\"create\": {\"_id\": 8}}\n{\"names\": \"Birla Sun Life Fixed Maturity Plan - Quarterly Series II-Dividend\"}\n\n\nThis is the solution. It works. Looks crazy but it works."
] | [
"python",
"elasticsearch"
] |
[
"Mass create methods for an object",
"I know that a new method for an object can be declare like so:\nvar MyObject = function() {return new MyObject.prototype};\nMyObject.prototype.exists = function() {alert("The object exists.")};\n\nHow can I create many methods as a bunch for MyObject instead of one by one?\nI have tried:\nMyObject.prototype = {\n exists: function() {alert("The object exists.")},\n isBorn: function() {alert("The object is born.")},\n isDead: function() {alert("The object has left our world.")}\n}\n\nCalling MyObject.exists() returns: Uncaught TypeError: MyObject.exists is not a function\n\nWhat I am trying to do:\nI am trying to do something like jQuery does.\njQuery is defined like so:\njQuery = function(selector, context) {included)\n return new jQuery.fn.init(selector, context);\n}\n\nWe don't say var j = new jQuery; when we call it like jQuery("#foo").\nThen the files says:\njQuery.fn = jQuery.prototype = {\n jquery: version,\n constructor: jQuery,\n length: 0,\n\n toArray: function() {\n return slice.call( this );\n }\n ...\n}\n\nIsn't toArray() a method of the jQuery object? Why doesn't it show the same error when I call it."
] | [
"javascript",
"object",
"prototype"
] |
[
"@font-face kit Preloader",
"I am using Font Squirrel\nto generate a custom Icon font file for my site. Is there a way to preload the font before rendering the page in Internet Explorer 9 as well as other browsers.\n\nAny help would be appreciated."
] | [
"javascript",
"html",
"fonts",
"font-face",
"webfonts"
] |
[
"CSS button - transparent arrow on both sides",
"I am trying to create the button below by using the pseudo-elements before and after. I do not want to manipulate the HTML DOM. I'm searching for a solution with pure CSS.\n\n\n\nHow is it possible to make the currently white border-color of these triangles transparent?\n\n//EDIT: The marked topic does not answer my question because I need a different angle than just rotating a square. It is also not transparent. I don't want to manipulate the DOM.\n\n//SOLVED: This is the result after using Kate Millers solution:\n\n\n\n//EDIT2: There is another problem with the solution I use now:\n\n\n\nIs there a way to fix the border-width of the triangles (left and right)?\nHere you can see how the size changes to 14.4 and 26.4px, 26.4px:"
] | [
"css",
"less",
"css-shapes"
] |
[
"Stopping youtube video once it reaches a point",
"It looks like the YouTube API does not have a way to stop a video playing once it reaches a certain point. It has a way to start it at a certain point, but not to stop it at a certain point. I'm wondering if there's a workaround for this? or maybe I glanced over it without noticing."
] | [
"youtube",
"gdata-api",
"youtube-api",
"gdata"
] |
[
"superclass storing a subclass",
"I know a Superclass can store an instance of a Subclass,\n\nfor example:\n\npublic class Subclass\n{\n private int color;\n\n public Subclass()\n {\n color = \"red\";\n }\n}\n\nSuperclass v = new Subclass();\n\n\na Superclass does not know about the methods, variables, etc in the subclass,\nyet casting it, gives you access to these.\n\nHow does that work?\n\nexample:\n\nVechicle v = new Car();\nCar c = (Car) v;\nConsoel.WriteLine(c.color);\n\n\nOutput:\nred"
] | [
"c#",
"inheritance"
] |
[
"How to write a Tcl script which will create a list of models and subcircuit names",
"I got stuck in a Tcl script which will create a list of models and subcircuit names contained within a Spice .lib file: The name of the .lib file should be given on the command line\n. the file looks like the following:\n.model Q2N2222 NPN(Is=14.34f Xti=3 Eg=1.11 Vaf=74.03 Bf=255.9 Ne=1.307\n+ Ise=14.34f Ikf=.2847 Xtb=1.5 Br=6.092 Nc=2 Isc=0 Ikr=0 Rc=1\n+ Cjc=7.306p Mjc=.3416 Vjc=.75 Fc=.5 Cje=22.01p Mje=.377 Vje=.75\n+ Tr=46.91n Tf=411.1p Itf=.6 Vtf=1.7 Xtf=3 Rb=10)\n* National pid=19 case=TO18\n* 88-09-07 bam creation\n*$\n\n.model Q2N3904 NPN(Is=6.734f Xti=3 Eg=1.11 Vaf=74.03 Bf=416.4 Ne=1.259\n+ Ise=6.734f Ikf=66.78m Xtb=1.5 Br=.7371 Nc=2 Isc=0 Ikr=0 Rc=1\n+ Cjc=3.638p Mjc=.3085 Vjc=.75 Fc=.5 Cje=4.493p Mje=.2593 Vje=.75\n+ Tr=239.5n Tf=301.2p Itf=.4 Vtf=4 Xtf=2 Rb=10)\n* National pid=23 case=TO92\n* 88-09-08 bam creation\n*$\n\n.model Q2N3906 PNP(Is=1.41f Xti=3 Eg=1.11 Vaf=18.7 Bf=180.7 Ne=1.5 Ise=0\n+ Ikf=80m Xtb=1.5 Br=4.977 Nc=2 Isc=0 Ikr=0 Rc=2.5 Cjc=9.728p\n+ Mjc=.5776 Vjc=.75 Fc=.5 Cje=8.063p Mje=.3677 Vje=.75 Tr=33.42n\n+ Tf=179.3p Itf=.4 Vtf=4 Xtf=6 Rb=10)\n* National pid=66 case=TO92\n* 88-09-09 bam creation\n*$\n\nAnd here is the code i develop but confused how to proceed next:\nproc find_lib_parts {ece476} {\n\n set value [string first ".lib" $ece476]\n#open the file \n\n if {$value = -1} {\n#set filename $ece476\n if {[catch {set fid [ open $ece476 "r"]} error_message]} {\n puts $error_message\n exit\n }\n\n#read a line\n\nset infos [split [read $fid] "\\n"]\n#close $fid\n\nset data [string trim $infos "\\n"]\n\n#get an empty list\nset res {}\nappend res "MODEL FOUND:\\n"\n\nforeach line $data {\n\n# match every line that has more than three columns\n# match every line where the first element is "model"\n# or match every line where the first element is "MODEL"\n\n if{[llength $line] > 3 && [lindex $line 0] eq {model}} {\n lappend res [lindex $line 0] \\n\n }\n \n if{[llength $line] > 3 && [lindex $line 0] eq {MODEL}} {\n lappend res [lindex $line 0] \\n\n }\n }\n}\nclose $fid\n}"
] | [
"tcl"
] |
[
"Can it be possible to use trigger in java controller spring",
"Is there a way to run AFTER EACH ROW trigger in java (spring 2.5 controller). I am using sql developer. I want trigger in java code controller.\nThanks in advance,"
] | [
"spring-mvc",
"triggers"
] |
[
"is there a way through which WebView can open pdf by clicking on a link which is inside the loaded webpage URL?",
"[enter image description here][1]I want to open a pdf in WebView, not by directly passing the pdf URL. This means there is a URL that opens in WebView and when that page opens in WebView it contains a link that opens pdf.\nHow can I open that pdf in WebView?\nFor example:\nThis is the screenshot of webpage loaded in WebView (Open the below image).\n[1]: https://i.stack.imgur.com/Z71pr.png\nIn side this image their is a option of view in Action row. So How to open that pdf which is coming from a URL loaded in WebView?\nThanks"
] | [
"android",
"webview",
"android-webview"
] |
[
".net core 2.0 JWT token",
"I have a web Api built with .net core 2.0 and a mobile app built with xamarin. To login the mobile app make a call to the web api by passing (username and password). If the credentials are valid web Api provide back a JWT token. The mobile app has a feature that keep the user logged in even when you close the app, like (facebook, Instagram etc...). \n\nThe question are these:\n\n\nHow to keep the JWT token valid until the user is logged-In in the\napp without ask him/her again the login credentials to give him/her\nanother valid JWT token?\nHow to make the JWT token invalid after the user decide to logout\nfrom the app?"
] | [
"c#",
".net-core",
"jwt",
".net-core-2.0",
"jwt-auth"
] |
[
"File not found error in java, file is in my project folder?",
"The file is in my project, and named correctly, I am quite new to JAVA. Any hints would be appreciated, TIA.\n\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.util.Scanner;\npublic class ExceptionsAndCarryOn {\n\n public static void main(String[] args) throws FileNotFoundException {\n // TODO Auto-generated method stub\n\n Scanner UserInput = new Scanner(new File(\"Numbers.txt\"));\n System.out.println(\"Please enter the numbers: \");\n\n int [] numbers = new int [5];\n int i = 0;\n while(UserInput.hasNextInt()){\n numbers[i++] = UserInput.nextInt();\n }\n\n int sum = 0;\n for ( i = 0; i < numbers.length; i++)\n sum += numbers[i];\n System.out.println(sum);\n\n UserInput.close();\n\n }\n\n}"
] | [
"java",
"file-not-found"
] |
[
"Maven on Windows Subsystem For Linux",
"I'm trying to run maven on Windows Subsystem for Linux, and getting \"cannot allocate memory\" errors. However, free -m shows that I have plenty of memory available, and the same build on Cygwin succeeds.\n\nAnyone have any tips for dealing with this? I'd prefer to change my settings.xml over my pom.xml's, but I'm open to almost anything."
] | [
"maven",
"windows-subsystem-for-linux"
] |
[
"comparing multi dimension arrays",
"I have 2 images and each is partial of a complete image, and the 2 combined could create the complete image.\n\nHowever there is overlap on the 2 images, and I am trying to create a program that will find where the top row of image2 meets whichever row of pixels in image 1.\nI created a for loop to gather each row of pixels per image in an array.\n\nthis is my code:\n\nint row = 0;\n for (int i = 0; i < imageArray1.length; i++) {\n\n for (int j = 0; j < imageArray1[i].length; j++) {\n if (imageArray1[i][j] == (imageArray2[0][0])) {\n row = imageArray1[i][j];\n }\n }\n\n }\n\n\nthe problem is I am pretty sure I am only gathering a with the individual pixel that is top left of the second image, rather than the whole row.\nAny ideas how to get around this?\nnew to java"
] | [
"java",
"arrays",
"javafx",
"compare"
] |
[
"Placing multiple divs in an array in JavaScript",
"So I have a lot of divs in my markup look similar to:\n\n<div class=\"container\">\n <div class=\"wrapper\">\n <h3>Title</h3>\n <p>Some text</p>\n </div>\n</div>\n\n\nThe markup is look very messy and i'm fairly new to JS but wondering, if I could place all these divs into an array, then a for loop to iterate over them, then print them. But still have enough control over each div that I can change the background colour on them?\n\nMy JS so far:\n\n var div = {\n divInfo: [\n {\n title: \"title\",\n description: \"Lorem ipsum dolor sit amet, consectetur adipiscing\"\n }\n ]\n };\n\n\nI've only shown one div at moment, as i'm still struggling with the for loop.\n\nAny help/suggestions?\nThanks!"
] | [
"javascript",
"jquery",
"html"
] |
[
"Get Geolocation for image captured using AVFoundation's AVCaptureStillImageOutput",
"I used AVFoundation to capture an image in a UIView and add comments to it. Now, I need to get the geolocation of the captured image. My current code snippet is as shown below. The metadata does not have the geolocation. Maybe I will have to use CLLocation? Please guide me ASAP.\n\n[stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error)\n {\n CFDictionaryRef metadataDict = CMCopyDictionaryOfAttachments(NULL, imageSampleBuffer, kCMAttachmentMode_ShouldPropagate);\n NSMutableDictionary *metadata = [[NSMutableDictionary alloc] initWithDictionary:(__bridge NSDictionary*)metadataDict];\n CFRelease(metadataDict);\n NSLog(@\"%@\",metadata);\n CFDictionaryRef exifAttachments = CMGetAttachment( imageSampleBuffer, kCGImagePropertyExifDictionary, NULL);\n if (exifAttachments)\n {\n // Do something with the attachments.\n }\n else\n NSLog(@\"no attachments\");\n\n NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];\n [captureSession stopRunning];\n [imageData writeToFile:path atomically:YES];\n }];"
] | [
"ios",
"geolocation",
"avfoundation"
] |
[
"what are the guidelines when writing cucumber stories?",
"What are the guidelines that need to be followed while writing cucumber stories.\n\nWhen to use @Given @when @Then @and tags?"
] | [
"java",
"cucumber"
] |
[
"Using Python, recursively create symbolic links for all .jpg files created within the last 24 hours",
"I store my photo library organized by year and event, for example:\n/mnt/mediapool/images1/2020/Day at the beach/IMG1.JPG\n/mnt/mediapool/images1/2020/Day at the beach/IMG2.JPG\n/mnt/mediapool/images1/2021/Sunset/IMG15.JPG\n\nUsing Python3, how can I recurse through all my images and create symbolic links inside another directory that list all images created within the last 24 hours (and 7-days, 30-days, etc..)?\nFor example:\n/mnt/mediapool/sorted/last-24h/IMG1.JPG (symbolic link to /mnt/mediapool/images1/2020...)\n/mnt/mediapool/sorted/last-24h/IMG2.JPG (symbolic link to /mnt/mediapool/images1/2020...)\n/mnt/mediapool/sorted/last-24h/IMG3.JPG (symbolic link to /mnt/mediapool/images1/2020...)\n/mnt/mediapool/sorted/last-7d/IMG1.JPG (symbolic link to /mnt/mediapool/images1/2020...)"
] | [
"python",
"python-3.x",
"shell",
"operating-system"
] |
[
"How to return json dictionary in django ajax update",
"i am asking this question multiple times since i have not received any applicable help. \n\nmy problem is that i dont know how to return query result to template as an ajax response. \n\ni did this: \n\nif request.path == \"/sort/\":\n sortid = request.POST.get('sortid')\n locs = Location.objects.order_by(sortid)\n if request.is_ajax():\n return HttpResponse(locs,mimetype=\"application/json\")\n\n\nthen my ajax done function does this: \n\n}).done(function(data){\n$('.sortierennach').html(data);\n});\n\n\nwhat now happens is that it just replaces the content of .sortierennach, it is not rendering django dic so that i can do this: \n\n{% for loc in locs %}\n {{loc.name}}\n{% endfor %}\n\n\ncan someone please help me... thanks a lot"
] | [
"javascript",
"python",
"ajax",
"django",
"json"
] |
[
"Change cursor type when the mouse gets over some selected text using HTML/Javascript",
"I need to change cursor type when the mouse gets over a selected text.\n\nHere you can find an explanatory image : \n\nImage to explain the type of cursor I want http://img190.imageshack.us/img190/1786/72162829.png\n\nIn this example the user has to drag some text to the textarea. Since the traditional pointer is not intuitive I would like to use the \"move\" pointer (cursor:pointer). I made this image with photoshop. Does anyone know how to make it for real in HTML / CSS / JAVASCRIPT ?"
] | [
"javascript",
"html",
"css",
"cursor",
"textrange"
] |
[
"IE11 css filter brightness",
"Internet Explorer does not respect the css property filter: brightness(100);. Following this tutorial I have also tried using ms-filter: brightness(1); but that did not work either. Is there a work-around?\n\nNot sure if this makes a difference, but I am applying the filter onto a background image svg.\n\nhttps://codepen.io/anon/pen/Ovoxqg (Works in Chrome, breaks in IE11. You should see a gray heart and white heart.)\n\n<div class=\"icon\"></div>\n<br><br><br>\n<div class=\"icon brightness\"></div>\n\nbody {\n background-color: aqua;\n}\n\n.icon {\n width: 25px;\n height: 25px;\n background-image: url(data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%3E%3Cpath%20fill%3D%22%23657786%22%20d%3D%22M12%2021.638h-.014C9.403%2021.59%201.95%2014.856%201.95%208.478c0-3.064%202.525-5.754%205.403-5.754%202.29%200%203.83%201.58%204.646%202.73.813-1.148%202.353-2.73%204.644-2.73%202.88%200%205.404%202.69%205.404%205.755%200%206.375-7.454%2013.11-10.037%2013.156H12zM7.354%204.225c-2.08%200-3.903%201.988-3.903%204.255%200%205.74%207.035%2011.596%208.55%2011.658%201.52-.062%208.55-5.917%208.55-11.658%200-2.267-1.822-4.255-3.902-4.255-2.528%200-3.94%202.936-3.952%202.965-.23.562-1.156.562-1.387%200-.015-.03-1.426-2.965-3.955-2.965z%22%2F%3E%3C%2Fsvg%3E);\n}\n\n.brightness {\n filter: brightness(100);\n -ms-filter: brightness(1);\n}"
] | [
"css",
"internet-explorer-11"
] |
[
"How to get the process running in the task manager using Install Shield",
"I am very new to Installsheild and it is programming. We have an application which run using MMC.exe. during uninstallation we need to check whther the app is running if yes then need to close the app. if user runs the app there is process mmc.exe running in the task manager.\nhow can i check whthere MMC.exe is running in the task manager\n\nThanks in Advance"
] | [
"installshield",
"uninstallation"
] |
[
"Exclude certain fields for the users who are superusers",
"I'm trying to make a custom User Model and have parameters like Date of Birth, current level and other such parameters. When I run python manage.py createsuperuser, it gives an error saying these values cannot be null. I don't want these parameters for the superuser account. WHat do I do?\n\nI tried adding the following line to the class that inherits from the UserAdmin class\nexclude = ('date_of_birth', 'currentLevel', 'totalStars', 'badges')\n\nThis is the model fields\n\nclass Learner(AbstractBaseUser):\n first_name = models.CharField(max_length=100)\n last_name = models.CharField(max_length=100)\n email = models.EmailField(max_length=255, unique=True)\n date_of_birth = models.DateField(auto_now=False, auto_now_add=False)\n\n currentLevel = models.ForeignKey(SubLevelConcepts, related_name='currentLevel', on_delete=models.CASCADE)\n totalStars = models.IntegerField(default=0)\n badges = models.IntegerField(default=0)\n\n active = models.BooleanField(default=True)\n staff = models.BooleanField(default=False)\n superuser = models.BooleanField(default=False)\n\n objects = LearnerManager()\n\n\nThis is the admin class\n\nclass LearnerAdmin(UserAdmin):\n\n add_form = LearnerCreationForm\n form = LearnerChangeForm\n\n model = Learner\n\n exclude = ('date_of_birth', 'currentLevel', 'totalStars', 'badges')\n\n list_display = (\n 'first_name',\n 'last_name',\n 'email',\n 'staff',\n 'active'\n )\n list_filter = (\n 'email',\n 'active'\n )\n fieldsets = (\n (None, {'fields': ('email', 'password',)}),\n ('Permissions', {'fields': ('staff', 'active')}),\n )\n\n add_fieldsets = (\n (None, {\n 'classes': ('wide',),\n 'fields': ('email', 'first_name', 'last_name','password1', 'passsword2', 'staff', 'active')}\n )\n )\n\n search_fields = ('email',)\n ordering = ('id',)\n filter_horizontal = ()\n\n\nThis is the final error when i run python manage.py createsuperuser\n\ndjango.db.utils.IntegrityError: (1048, \"Column 'currentLevel_id' cannot be null\")\n\n\nI want the superuser to just take email and password and finish the job. I'll add the first_name and last_name later"
] | [
"python",
"python-3.x",
"django-2.2"
] |
[
"How to add buttons in an array and loop through them?",
"Got a bunch of letter buttons in code below:\n\nCode:\n\n<?php\n $a = range(\"A\",\"Z\");\n?>\n\n<table id=\"answerSection\">\n <tr>\n\n<?php\n $i = 1;\n foreach($a as $key => $val){\n if($i%7 == 1) echo\"<tr><td>\";\n echo\"<input type=\\\"button\\\" onclick=\\\"btnclick(this);\\\" value=\\\"$val\\\" id=\\\"answer\".$val.\"\\\" name=\\\"answer\".$val.\"Name\\\" class=\\\"answerBtns answers answerBtnsOff\\\">\"; \n if($i%7 == 0) echo\"</td></tr>\";\n $i++;\n }\n?>\n </tr>\n</table>\n\n\nNow the code below is able to turn on an answer button:\n\nCode:\n\nfunction addwindow(btn) { \n$('#answer'+btn).addClass(\"answerBtnsOn\");\n}\n\n\nBut the only problem is that the code above is only able to turn on a single answer button on only. For example if the \"Answer\" is B, then it will look for button \"#answerB\" and turn on that button which is button B. or if the \"Answer\" is E, then it will look for button \"#answerE\" and turn on that button which is button E.\n\nThe problem is that if there are multiple answers. If the \"Answer\" is B E, then it does not turn on buttons B and E. This is because it is trying to find button \"#answerBE\" which is incorrect, it should be looking for button \"#answerB\" and button \"#answerE\" and turn them both on. \n\nAnother example is if \"Answer\" is A D F, it doesn't turn on buttons A D and F because it is trying to find button \"#answerADF\" which is incorrect, it should be looking for button \"#answerA\", button \"#answerD\", and button \"#answerF\" and turn them all on. \n\nSo my question is that how can I turn on multiple buttons if there are multiple Answers? Do I need to put all the buttons in an array and loop through them so that it is able to go through all the buttons and turn on those buttons which should be turn on?\n\nUPDATE:\n\nBelow is the \"Add\" button which calls on the addwindow() function and above the add button is the \"Answer\" column where it displays rows of Answers\n\n echo '<td class=\"noofanswerstd\">'.htmlspecialchars($searchNoofAnswers[$key]).'</td>';\n echo \"<td class='addtd'><button type='button' class='add' onclick=\\\"parent.addwindow('$searchAnswer[$key]');\\\">Add</button></td></tr>\";"
] | [
"javascript",
"jquery"
] |
[
"DATEDIFF function on SQL server returns a null value when I use variables",
"I am trying to get the total of minutes between a start time and end time. This data is found on the same table, same column and I have set a variable to return the values I need. \n\nSo far, that is working fine. Now, the problem comes when I use DATEDIFF with the variables as it returns NULL: \n\nDECLARE @hol datetime\n\nSET @hol = (\n SELECT fecha_Registro \n FROM Registro \n WHERE id_Registro = 4 \n AND id_Tipo_Registro = 2\n); \n\nSELECT @hol as varText \n\nDECLARE @bye DATETIME \n\nSET @hol = (\n SELECT fecha_Registro \n FROM Registro \n WHERE id_Registro = 3 \n AND id_Tipo_Registro = 1\n); \n\nSELECT @hol as varText2 \n\nSELECT DATEDIFF(MI, @bye, @hol) as total_minutos \n\n\nAs you can see the variables have the correct values on them, so, I am not understanding why does it comes back null. When I do it with the actual dates, it works fine."
] | [
"sql",
"sql-server",
"datediff"
] |
[
"Time as a determining value",
"I have a section of code that is being used to determine if a certain event should happen. The code looks like this.\n\n If (Date.Now.Ticks Mod 100) < 4 Then\n Return True\n Else\n Return False\n End If\n\n\nThe idea here is that this event should happen 4 time out of 100, or 4%. However, in production, the actually percentages range from 10% to 60%. The application is being hosted on two load balanced Win2k3 servers. \n\nAny suggestion would be helpful.\n\nKeith"
] | [
".net",
"vb.net",
"iis"
] |
[
"Valid Javascript snippet not working on codepen or jsfiddle?",
"I have a button that when clicked it changes the color of text to red.\n\nSome basic JS below:\n\nfunction colorChange() {\n document.getElementById('text').style.color = \"red\";\n}\n\n\nand HTML:\n\n<p id=\"text\">some text</p>\n<button type=\"button\" onclick=\"colorChange()\">red</button>\n\n\nDoes not work on either JSfiddle or Codepen. However - when I make an identical local HTML file it works as expected. \n\nWhat would be a/the reason as to why this vanilla Javascript doesn't work in Codepen/JSfiddle? There are no libraries (jQuery, React etc) involved. My first immediate thought was in JSFiddle, there is a property that you can set in settings for the load type. I set this to onLoad and still did not work. Codepen doesn't look like it offers control over this. \n\nJSFiddle:\nhttps://jsfiddle.net/mo5pro4a/1/\n\nCodepen: \nhttps://codepen.io/anon/pen/YVYZXj\n\nUPDATE: Codepen actually looks to be OK - the issue is primarily now with jsfiddle."
] | [
"javascript",
"html",
"jsfiddle",
"codepen"
] |
[
"Reducer getting fewer records than expected",
"We have a scenario of generating unique key for every single row in a file. we have a timestamp column but the are multiple rows available for a same timestamp in few scenarios.\n\nWe decided unique values to be timestamp appended with their respective count as mentioned in the below program.\n\nMapper will just emit the timestamp as key and the entire row as its value, and in reducer the key is generated.\n\nProblem is Map outputs about 236 rows, of which only 230 records are fed as an input for reducer which outputs the same 230 records.\n\npublic class UniqueKeyGenerator extends Configured implements Tool {\n\n private static final String SEPERATOR = \"\\t\";\n private static final int TIME_INDEX = 10;\n private static final String COUNT_FORMAT_DIGITS = \"%010d\";\n\n public static class Map extends Mapper<LongWritable, Text, Text, Text> {\n\n @Override\n protected void map(LongWritable key, Text row, Context context)\n throws IOException, InterruptedException {\n String input = row.toString();\n String[] vals = input.split(SEPERATOR);\n if (vals != null && vals.length >= TIME_INDEX) {\n context.write(new Text(vals[TIME_INDEX - 1]), row);\n }\n }\n }\n\n public static class Reduce extends Reducer<Text, Text, NullWritable, Text> {\n\n @Override\n protected void reduce(Text eventTimeKey,\n Iterable<Text> timeGroupedRows, Context context)\n throws IOException, InterruptedException {\n int cnt = 1;\n final String eventTime = eventTimeKey.toString();\n for (Text val : timeGroupedRows) {\n final String res = SEPERATOR.concat(getDate(\n Long.valueOf(eventTime)).concat(\n String.format(COUNT_FORMAT_DIGITS, cnt)));\n val.append(res.getBytes(), 0, res.length());\n cnt++;\n context.write(NullWritable.get(), val);\n }\n }\n }\n\n public static String getDate(long time) {\n SimpleDateFormat utcSdf = new SimpleDateFormat(\"yyyyMMddhhmmss\");\n utcSdf.setTimeZone(TimeZone.getTimeZone(\"America/Los_Angeles\"));\n return utcSdf.format(new Date(time));\n }\n\n public int run(String[] args) throws Exception {\n conf(args);\n return 0;\n }\n\n public static void main(String[] args) throws Exception {\n conf(args);\n }\n\n private static void conf(String[] args) throws IOException,\n InterruptedException, ClassNotFoundException {\n Configuration conf = new Configuration();\n Job job = new Job(conf, \"uniquekeygen\");\n job.setJarByClass(UniqueKeyGenerator.class);\n\n job.setOutputKeyClass(Text.class);\n job.setOutputValueClass(Text.class);\n\n job.setMapperClass(Map.class);\n job.setReducerClass(Reduce.class);\n\n job.setInputFormatClass(TextInputFormat.class);\n job.setOutputFormatClass(TextOutputFormat.class);\n // job.setNumReduceTasks(400);\n\n FileInputFormat.addInputPath(job, new Path(args[0]));\n FileOutputFormat.setOutputPath(job, new Path(args[1]));\n\n job.waitForCompletion(true);\n }\n\n}\n\n\nIt is consistent for higher no of lines and the difference is as huge as 208969 records for an input of 20855982 lines. what might be the reason for reduced inputs to reducer?"
] | [
"java",
"hadoop",
"mapreduce",
"hdfs"
] |
[
"\"Bad file number\" error for a very long command line",
"I have a particularly large java command to execute (lot's of parameters, long classpath, etc) - and when I run it like that (as I normally do in my Windows via git bash app, which tries to emulate linux bash):\n\njava <classpath here> <params>\n\n\nit returns me the weird message:\nsh.exe\": /c/Windows/system32/java: Bad file number\n\nBUT, whenever I decrease the command length (by removing any part of it - classpath, params) to about 32k symbols - it runs ok. \n\nIs there any length limit in Windows/bash/java to a single executed command ?"
] | [
"windows",
"bash"
] |
[
"Amazon Web Services - Length of HostIds returned",
"I'm making a platform that requires allocating hosts programatically. The API returns a HostId, that's a string. (Source: boto3 docs). If anyone has experience dealing with AWS, could you tell me if this string has a constant length? And if it does, how long is it?\nThis is from the perspective of designing a database - specifically for setting a maximum length to the field. I don't want to assign the host ids superfluous space."
] | [
"amazon-web-services",
"amazon-ec2"
] |
[
"How to add two arrays together in C++?",
"I need to add two arrays together. Why does the following how work?\n\n#include <iostream>\nusing namespace std;\nint main ()\n { \n int sumvals[3];\n int nums[3];\n\n sumvals [0] = 1;\n sumvals [1] = 2;\n sumvals [2] = 3;\n\n\n for (i=0; i <= 3; i++)\n {\n sumvals[i] = sumvals[i] + numbs [i];\n cout << \"the sum of the array elements is: \" << sumvals << endl;\n\n }"
] | [
"c++"
] |
[
"Store Highcharts in Javascript Function - How to?",
"I am trying to store the entire Highcharts/Highstocks script into a function for js to make things a bit more compact and easier to replicate.\n\n$(function() {\n// Create the chart\n window.chart = new Highcharts.StockChart({\n chart : {\n renderTo : 'container'\n },\n\n rangeSelector : {\n selected : 1\n },\n\n title : {\n text : 'AAPL Stock Price'\n },\n\n series : [{\n name : 'AAPL',\n data : [[1,2],[4,5]],\n tooltip: {\n valueDecimals: 2\n }\n }]\n });\n});\n\n\nThis is basically whats in the file highchartsfunc.js that I call for the function. Any idea?"
] | [
"javascript",
"function",
"highcharts",
"highstock"
] |
[
"Initialising Board Game Grid Java",
"basically I'm struggling to create a grid for a board game I'm creating. Basically I've got 2 types of pieces, Warriors and Grass currently(grass is stationary). The warrior class has subclasses of warrior, ie) ninja etc.\nEach piece on the board has a unique char value, which will be displayed in the output of the board as shown.\nHere are my classes:\n\npackage me.sample;\n\nimport java.awt.*;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class Grid {\n\n private static char[][] boardArray;\n private int mRow;\n private int mCol;\n private int mIterations;\n\n\n public Grid_23722002(int row, int col, ArrayList<Warrior_23722002> warList, ArrayList<Grass> grassList, char[][] array) {\n\n\n \n\n\n }\n\n\n public static void displayGrid(Grid_23722002 grid) {\n\n for (int i = 0; i < grid.getRow(); i++) {\n\n for (int j = 0; j < grid.getCol(); j++) {\n\n System.out.println(boardArray[i][j]);\n\n }\n\n\n }\n\n\n }\n\n public int getRow() {\n\n return mRow;\n\n }\n\n public int getCol() {\n\n return mCol;\n }\n\n}\n\n\n\n\npackage me.sample;\n\npublic class Piece {\n\n private int mRow;\n private int mCol;\n\n\n public Piece(){\n\n\n }\n\n public int getRow(){\n\n return this.mRow;\n\n }\n\n public int getCol(){\n\n return this.mCol;\n\n }\n \n\n public void setRow(int row){\n\n this.mRow = row;\n\n }\n\n public void setCol(int col){\n\n this.mCol = col;\n\n }\n\n\n}\n\n\n\n\n\npackage me.sample;\n\npublic class NinjaWarrior extends Warrior implements WarriorInterface, PieceInterface{\n\n private String mType = "Ninja";\n private final char CHAR = 'N';\n\n\n public NinjaWarrior() {\n\n }\n\n public String getType(){\n\n return mType;\n\n }\n\n public void performSpecialAbility() {\n }\n\n public void specialAbilityCompleted() {\n }\n\n @Override\n public char getChar() {\n return CHAR;\n }\n\n @Override\n public String getPieceType() {\n return null;\n }\n}\n\n\n\n\n\npackage me.sample;\n\npublic class Grass extends Piece implements PieceInterface {\n\n private final char CHAR = 'g';\n\n public Grass() {\n\n\n\n\n }\n\n\n @Override\n public char getChar() {\n return CHAR;\n }\n\n @Override\n public String getPieceType() {\n return null;\n }\n}\n\n\n\nI've currently got two ArrayLists defined with the appropriate objects in the main class, one for the warriors and one for grass. Below is an example of me initialising the different Lists. THis is just a code snippet, the full code incorporates all the different types of warrior.\nelse if (list.get(i).contains("Ninja")) {\n\n NinjaWarrior n = new NinjaWarrior();\n final String[] attributes = list.get(i).split(" ");\n setWarriorAttributes(n, attributes);\n warriorList.add(n);\n\n }\n\n else if (list.get(i).contains("Grass") && !(list.get(i).length() > 8)){\n\n int counter = 1;\n\n while(!(list.get(i+counter).isEmpty())){ \n\n final String[] attributes = list.get(i+counter).split(" ");\n Grass g = new Grass();\n g.setRow(Integer.parseInt(attributes[0]));\n g.setCol(Integer.parseInt(attributes[1]));\n\n grassList.add(w);\n counter++;\n\n }\n\n }\n\n\nThe question then becomes, how can I initialise the grid as to get it into a form as follows, so I can print it if need be?\nExampleBoard"
] | [
"java",
"arrays",
"multidimensional-array"
] |
[
"Find and fill in a field in a browser window",
"I need to open a URL from R, then find and fill in a specific field in it with some values calculated in R. Is there any way of doing that?\n\nP.S. I do not need to retrieve anything back from the browser, I just need to fill one field and leave the browser window open.\n\nP.P.S. I have heard about RSelenium but it looks like it only works in a remote browser."
] | [
"r",
"url",
"browser"
] |
[
"shell_exec empty response for nslookup query",
"I am using Ubuntu and xampp, I am trying to execute the command nslookup gmail.com via. PHP, but I am getting an empty response. The same thing worked while I tried on a windows machine as well as in a Linux server running CentOS.\n\nFYI nslookup gmail gives proper response when I run the command directly on my terminal, the problem is only when I try to do it via. php.\n\nI even tried doing a which nslookup and then \n$nslookup = shell_exec(\"/usr/bin/nslookup $server\"); with no help, but the same blank response.\n\nAlthough Note that the command whoami when executed from PHP(which I have commented in the following code) does give a proper response of daemon\n\nI am very new to Ubuntu, so a little help would be great.\n\n<?php\n$email = $_GET['email'];\n$server = explode(\"@\", $email)[1];\necho $server;\n\n$nslookup = shell_exec(\"nslookup $server\");\n// $nslookup = shell_exec(\"whoami\");\nprint_r($nslookup);\n?>"
] | [
"php",
"linux",
"ubuntu",
"networking",
"shell-exec"
] |
[
"Visual Studio 2019 professiona - libman fires \"library could not be resolved\" for every library",
"I'trying to add client side library in visual studio using libman but i got "The xxx could not be resolved by the "ppp" provider"\nintellisense in search bar works fine and find library as i start typing but i can't go over with installation\ni try:\n\[email protected]\[email protected]\[email protected]\[email protected]\[email protected]\n\nwith all provider: cdnjs, jsdelivr, unpkg\nadding file manually in libman.json trigger the same error"
] | [
"javascript",
"visual-studio-2019",
"libman"
] |
[
"How can I use SPARQL to find instances where two properties do not share any of the same objects?",
"In my company's taxonomy, all concepts have a value for skos:prefLabel, and most have a bunch of values for a custom property -- let's call it ex:keyword -- whose values have the datatype rdf:langString. I want to find concepts where the value of skos:prefLabel does NOT exactly match ANY value of ex:keyword, when case and language are ignored.\nIt is fairly straightforward to write a query for concepts where the values DO match, like this:\nSELECT *\nWHERE {\n ?concept skos:prefLabel ?label ;\n ex:keyword ?kw\n FILTER (lcase(str(?label)) = lcase(str(?kw)))\n}\n\nWhere I'm getting tripped up is in trying to negate this.\nUsing != in the FILTER would just return a bunch of cases where ?label and ?kw don't match, which is not what I'm after.\nWhat I would like is to be able to use a FILTER NOT EXISTS, but that's invalid with an expression like (?a = ?b); it only works with something like {?a ?b ?c}.\nI suspect that there is a proper way to express FILTER NOT EXISTS (?a = ?b) in SPARQL, but I don't know what it is. Can someone help?"
] | [
"sparql",
"rdf"
] |
[
"How to center a frame with Tkinter?",
"I searched a lot about how to center a frame with Tkinter and Python 3.8.\nI wrote a code where 4 buttons are in a frame but I don't know how to center the frame in the window. I tried several methods like grid_propagate(0), grid(sticky=""), pack(expand=True), ...\nBut nothing works then.\nI am sharing my most recent code there. I hope you can help me.\nwindow = Tk()\nframe = Frame(window)\nbutton1 = Button(frame, text="Button 1")\nbutton2 = Button(frame, text="Button 2")\nbutton3 = Button(frame, text="Button 3")\nbutton4 = Button(frame, text="Button 4")\n\nbutton1.grid(row=0, column=0)\nbutton2.grid(row=0, column=1)\nbutton3.grid(row=1, column=0)\nbutton4.grid(row=1, column=1)\nframe.grid_propagate(0)\nframe.grid(row=0, column=0, rowspan=2, columnspan=2)\n\nwindow.mainloop()"
] | [
"python",
"python-3.x",
"tkinter",
"centering"
] |
[
"vimscript for Ultisnips+Deoplete compatibility",
"I'm wondering how to write a function that overloads <TAB>.\n\nFirst it would do a check to see if there is a snippet that needs to be completed, and if there is a snippet, then expand it.\n\nOtherwise, I would like the function to do a check to see if there is a space before the cursor (or we are on new line) before Tab is pressed. If so, then it should do regular <tab>. \nOtherwise, I'd like for it to call\n\ndeoplete#manual_complete()\n\n\nUnless there is already a menu open, in which case, I should be able to tab through it.\n\nHere was my attempt (Which fails completely) and some settings for reference:\n\nlet g:ulti_expand_or_jump_res = 0 \"default value, just set once\n\nfunction! Ulti_ExpandOrJump_and_getRes()\n call UltiSnips#ExpandSnippetOrJump()\n return g:ulti_expand_or_jump_res\nendfunction\n\ninoremap <silent><expr> <tab>\n \\ (Ulti_ExpandOrJump_and_getRes() > 0) ? \"\\<C-y>\"\n \\ : pumvisible() ? \"\\<C-n>\" :\n \\ <SID>check_back_space() ? \"\\<TAB>\" :\n \\ deoplete#manual_complete()\n\nfunction! s:check_back_space() abort \"{{{\n let col = col('.') - 1\n return !col || getline('.')[col - 1] =~ '\\s'\nendfunction \"}}}\n\n\nOddly enough, when I press tab, the bottom right of vim reads that I have typed \"^I\", which is very strange behavior.\n\nThe reason I do not have the ultisnips expand trigger as \"tab\" is that it disables the use of tab for deoplete (for whatever reason.)"
] | [
"vim",
"neovim"
] |
[
"How to set android:drawable to left and top?",
"I just wanted to set icon to the top and left corner of my TextView.\nThis is my code and the output respectively:\n\n<TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"@string/Content\"\n android:drawableLeft=\"@drawable/icon\" />\n\n\nOutput:\n\n\n\nbut I want to set my icon to the top and left like this one :"
] | [
"android",
"drawable"
] |
[
"Extracting src attribute",
"What I want to do:\nThis HTML code:\n<img class="poster lazyload lazyloaded"\n data-src="https://image.tmdb.org/t/p/w94_and_h141_bestv2/3qlQM9KP1cyvNfPChA9rASASdHr.jpg"\n data-srcset="https://image.tmdb.org/t/p/w94_and_h141_bestv2/3qlQM9KP1cyvNfPChA9rASASdHr.jpg 1x, https://image.tmdb.org/t/p/w188_and_h282_bestv2/3qlQM9KP1cyvNfPChA9rASASdHr.jpg 2x"\n alt="Hitman"\n src="https://image.tmdb.org/t/p/w94_and_h141_bestv2/3qlQM9KP1cyvNfPChA9rASASdHr.jpg"\n srcset="https://image.tmdb.org/t/p/w94_and_h141_bestv2/3qlQM9KP1cyvNfPChA9rASASdHr.jpg 1x, https://image.tmdb.org/t/p/w188_and_h282_bestv2/3qlQM9KP1cyvNfPChA9rASASdHr.jpg 2x"\n data-loaded="true">\n\nI want to extract the "data-src" or "src" (or every attribute contain the URL to the image) attribute value.\nWhat I Tried:\nPosters = soup.find("img")["src"]\nprint(Posters)\n\nBut this obviously returns all the values from every img tag, so every link is not related to the posters.\nOutput:\nhttps://www.themoviedb.org/assets/2/v4/logos/v2/blue_short-8e7b30f73a4020692ccca9c88bafe5dcb6f8a62a4c6bc55cd9ba82bb2cd95f6c.SVG\nhttps://www.themoviedb.org/assets/2/v4/logos/v2/blue_short-8e7b30f73a4020692ccca9c88bafe5dcb6f8a62a4c6bc55cd9ba82bb2cd95f6c.SVG\n\nWith posters I mean (check this URL: https://www.themoviedb.org/search?&query=Hitman) the posters of films.\nSummary\nI want to extract the value inside an attribute, inside the class ".lazyloaded"\nI hope is everything clear. Thanks.\n\nEdit:\nExplaination, where was the problem?\nFor everyone reading, Laurent's answer is the solution, the problem was the parsed HTML.\nAs we can see on my browser the class that contain the attribute that i was trying to scrape was inside the class "poster lazyload lazyloaded":\n\nbut if we print the website.content:\n <img class="poster lazyload" \n data-src="https://image.tmdb.org/t/p/w94_and_h141_bestv2/lrDpwvha8VX05vIFxeSZTiPJGYl.jpg" \n data-srcset="https://image.tmdb.org/t/p/w94_and_h141_bestv2/lrDpwvha8VX05vIFxeSZTiPJGYl.jpg 1x, https://image.tmdb.org/t/p/w188_and_h282_bestv2/lrDpwvha8VX05vIFxeSZTiPJGYl.jpg 2x"\n alt="The Hitman&#x27;s Bodyguard Collection">\n\nit's very very different."
] | [
"python",
"web-scraping"
] |
[
"calling and changing a file using sed command within a function",
"Hi I have wrapped a sed command (which works out it's own) within a shell function. \n\n#!/bin/bash\n\nsnp2fasta() { \nsed -i \"s/^\\(.\\{'$2'\\}\\)./\\1'$3'/\" $1; \n}\n\n\nand call it with\n\n$ ./snp2fasta input.txt 45 A\n\n\nno changes are made to input.txt\n\nHowever if I simply do\n\n$ sed -i 's/^\\(.\\{45\\}\\)./\\1A/' input.txt\n\n\nthen this works and the file is changed by changing the 45th character to an A.\n\nHowever when wrapping into a shell script (to handle command line variables) the shell script snp2fasta.sh runs fine, but no changes are made to the file.\n\nwhy is this?"
] | [
"bash",
"shell",
"sed"
] |
[
"macOS - Terminal - find and remove folder in the Users directory older than X days",
"I work for a school and I'd like to send out a script to delete user folders older than X days on lab computers.\n\nI've come up with:\n\nfind /Users/* -prune -mtime 30 | grep -v /Users/admin | grep -v /Users/Shared\n\n\nThat returns the directories other than those 2 directories that are older than 30 days, which is great, but I'm not quite sure how to now delete those folders.\n\nThanks."
] | [
"macos",
"terminal"
] |
[
"How do I transform my Scala XML object (of class Elem) to HTML using XSLT?",
"I have a small piece of code that, given the paths of my XML and XSLT files, outputs an HTML file in the provided path. It goes like this:\n\n try {\n val tFactory: TransformerFactory = TransformerFactory.newInstance\n val transformer: Transformer = tFactory.newTransformer(new StreamSource(\"<PATH TO XSL>\"))\n transformer.transform(new StreamSource(\"<PATH TO XML>\"), new StreamResult(new FileOutputStream(\"PATH TO HTML\")))\n } catch {\n case e: Exception => e.printStackTrace\n }\n\n\nNow, instead of an XML file as an input, I want to input a Scala Elem object. How do I make that possible?"
] | [
"html",
"xml",
"scala",
"xslt"
] |
[
"Cloud functions returns null, when called directly from the app",
"I am trying to use Firebase cloud functions from my app to post emails and names of users into cloud firestore collection with randomly generated IDs. Everything works well, but I want to get a response from a function to my app and I can't really manage to do that. Here's my code from my app where I call the cloud function:\n\nonPress ({commit, dispatch}, payload) {\n var addUserInformation = firebase.functions().httpsCallable('addUserInformation');\n addUserInformation(payload)\n .then(function(result) {\n console.log(result)\n }).catch(function(error) {\n var code = error.code;\n var message = error.message;\n var details = error.details;\n console.log(code);\n console.log(message);\n console.log(details);\n });\n },\n\n\nAnd here's the code of a cloud function: \n\n const functions = require('firebase-functions')\nconst admin = require('firebase-admin');\n\nadmin.initializeApp(functions.config().firebase);\n\n// // Create and Deploy Your First Cloud Functions\n// // https://firebase.google.com/docs/functions/write-firebase-functions\n//\n\n\nexports.addUserInformation = functions.https.onCall((data) => {\n admin.firestore().collection('Backend').where('email', '==', data[1]).get()\n .then(function(querySnapshot) {\n if (querySnapshot.size > 0) {\n console.log('Email already exists')\n } else {\n admin.firestore().collection('Backend').add({\n name: data[0],\n email: data[1]\n })\n console.log('New document has been written')\n }\n return {result: 'Something here'};\n })\n .catch(function(error) {\n console.error(\"Error adding document: \", error);\n })\n});\n\n\nThe console shows that result is null"
] | [
"javascript",
"firebase",
"google-cloud-functions"
] |
[
"Free image RGB and BGR",
"I'm using FreeImage to load a jpeg and a tiff.\nThe jpeg is 24-bit (8 bpp). The tiff is 48-bit (16 bpp).\n\nProblem is, FreeImage loads the jpeg as BGR, and the tiff as RGB.\n\nHow can I distinguish between the 2 so I can render it to the screen properly?"
] | [
"jpeg",
"tiff",
"freeimage"
] |
[
"How to read dictionary data from a file in python?",
"I have the following file dic.txt:\n\n{'a':0, 'b':0, 'c':0, 'd':0}\n\n\nI want to read its contents and use as a dictionary. After entering new data values I need to write them into that file. Basically I need a script to work with the dictionary, update its values and save them for later use.\n\nI have a working script, but can't figure out how to actually read the contents of the dic.txt into a variable in the script. Cause when I try this:\n\nfile = '/home/me/dic.txt'\ndic_list = open(file, 'r')\nmydic = dic_list\ndic_list.close()\n\n\nWhat I get as mydic is a str. And I can't manipulate its values. So here is the question. How do I create a dictionary from a dic.txt?"
] | [
"python"
] |
[
"Nested Directives in OpenACC",
"I'm trying to use nested feature of OpenACC to active dynamic parallelism of my gpu card. I've Tesla 40c and my OpenACC compiler is PGI version 15.7.\n\nMy code is so simple. When I try to compile following code compiler returns me these messages \n\nPGCC-S-0155-Illegal context for pragma: acc parallel loop (test.cpp: 158)\nPGCC/x86 Linux 15.7-0: compilation completed with severe errors\n\n\nMy code structure:\n\n#pragma acc parallel loop\nfor( i = 0; i < N; i++ )\n{\n // << computation >>\n\n int ss = A[tid].start;\n int ee = A[tid].end;\n\n #pragma acc parallel loop\n for(j = ss; j< ( ee + ss); j++)\n {\n // << computation >>\n }\n\n\nI've also tried to change my code to use routine directives. But I couldn't compile again\n\n#pragma acc routine workers\nfoo(...)\n{\n\n #pragma acc parallel loop\n for(j = ss; j< ( ee + ss); j++)\n {\n // << computation >>\n }\n}\n\n#pragma acc parallel loop\nfor( i = 0; i < N; i++ )\n{\n // << computation >>\n\n int ss = A[tid].start;\n int ee = A[tid].end;\n\n foo(...);\n\n}\n\n\nI've tried of course only with routine (seq,worker,gang) without inner parallel loop directive. It has been compiler but dynamic parallelism hasn't been activated.\n\n 37, Generating acc routine worker\n Generating Tesla code\n 42, #pragma acc loop vector, worker /* threadIdx.x threadIdx.y */\n Loop is parallelizable\n\n\nHow am I supposed to use dynamic parallelism in OpenACC?"
] | [
"cuda",
"gpu",
"nvidia",
"openacc",
"dynamic-parallelism"
] |
[
"Struts2 / jQuery: resume link href redirect after e.preventDefault();",
"On my Struts2 application, I have some buttons that will delete items from a table. So far, so good. Now, I'm trying to use jQuery to present the users with an alert to confirm if they really want to delete the chosen item. To do this, what I have in mind is what I think it is the most obvious approach:\n\n\n \n User clicks on the \"delete\" button;\n Show alert to the user (it contains two links: one to cancel the delete action and another one to confirm it);\n \n \n \n 2.1. If the user presses \"cancel\", the alert simply goes away;\n \n 2.2. If the user presses \"confirm\", the item is deleted, and then the alert goes away;\n \n\n\nWhat I've got so far:\n\nJSP:\n\n<table>\n <tr>\n [...]\n <td><a href=\"<s:url action=\"deleteexperiment\"><s:param name=\"id\"><s:property value=\"exp_id\"/></s:param></s:url>\" class=\"delete ink-button all-100\">delete</a></td>\n [...]\n </tr>\n</table>\n\n<div id=\"confirm-delete\" class=\"ink-alert basic\" role=\"alert\" style=\"display: none\">\n <p class=\"quarter-bottom-padding\"><b>Confirm delete:</b> Do you really want to delete this experiment?</p>\n <button id=\"no\" class=\"ink-button all-20 red\">Cancel</button>\n <button id=\"yes\" class=\"ink-button all-20 green\">Confirm</button>\n</div>\n\n<script type=\"text/javascript\">\n $(document).ready(function()\n {\n $('.delete').click(function(e)\n {\n e.preventDefault();\n $('#confirm-delete').show();\n\n $('#yes').click(function(event)\n {\n // resume e.preventDefault(), i.e., continue redirecting to the original href on the table above\n $('#confirm-delete').hide();\n });\n\n $('#no').click(function(event)\n {\n $('#confirm-delete').hide();\n });\n });\n });\n</script>\n\n\nI've tried like 20 different approaches (in what concerns trying to restore the original behaviour to the link - the commented line) with no luck. Please note that the href atrribute contains Struts tags, so something like window.location.href = \"<s:url action=\"deleteexperiment\"><s:param name=\"id\"><s:property value=\"exp_id\"/></s:param></s:url>\"; won't work, because jQuery won't \"know\" what is the ID, I guess (it will redirect to http://localhost:8080/AppName/deleteexperiment.action?id= , so the ID is empty). Unless it would be possible to pass the ID to jQuery when calling the click() function, of course. Is that possible? Which other options are left for me? Thanks."
] | [
"jquery",
"jsp",
"struts2",
"preventdefault"
] |
[
"Using output stream overloading operator for pointers",
"I have a coursework to submit and I almost finished it all. But I'm stuck in\na bit where I have to read a class instance to a file using output stream operator. the output stream operator takes instance as an argument but I need\nto use it for a pointer to an instance. any help please?\n\nMy output stream operator implementation is:\n\nostream& operator<<(ostream& out, sequence &s)\n{\n out<<s.number_of_samples;//<<s.samples;\n s.samples=new float [s.number_of_samples];\n for(int i=0; i<s.number_of_samples; i++) out<<s.samples[i];\n return(out);\n}\n\n\nThe bit where it reads the instance to a file is:\n\nofstream output_filtered_samples_file(\"output.txt\");\nsequence* filtered_sequence = test_FIR.apply_filter(test_sequence);\noutput_filtered_samples_file<<filtered_sequence;\n\n\nFull code is http://ideone.com/V0Xavo"
] | [
"c++",
"instance",
"overloading"
] |
[
"Cutting images while zoom",
"I have a problem with zooming large image. When i zooming image to much and I move my image (pannable function) I loose a piece of image (like cut). Where is mistake in my code?\n\nprivate void zoom(ImageView imagePannable) {\n imagePannable.setOnScroll(\n new EventHandler<ScrollEvent>() {\n @Override\n public void handle(ScrollEvent event) {\n double zoomFactor = 1.20;\n double deltaY = event.getDeltaY();\n\n if (deltaY < 0) {\n zoomFactor = 0.80;\n }\n else\n zoomFactor = 1.20;\n\n imagePannable.setFitHeight(imagePannable.getFitHeight() * zoomFactor);\n imagePannable.setFitWidth(imagePannable.getFitWidth() * zoomFactor);\n\n event.consume();\n }\n });\n}\n\n\n\n\ndouble propX = viewportBounds.getWidth() / image.getWidth();\ndouble propY = viewportBounds.getHeight() / image.getHeight();\n\nimageView.setFitWidth(imageView.getImage().getWidth() * propX);\nimageView.setFitHeight(imageView.getImage().getHeight() * propY);\n\n\nscrollPane.setContent(imageView);\n\nscrollPane.setPannable(true);\n// center the scroll contents.\nscrollPane.setHvalue(0.5);\nscrollPane.setVvalue(0.5);\n\nzoom(imageView);"
] | [
"javafx",
"zooming",
"scrollpane"
] |
[
"Javascript executing twice after clicking the back button instantclick.io",
"I am using the instantclick.io js library, to make my webpage snappier, however when i go back a page, using the back button, every js event that i use (jquery) gets executed twice. I do utilize the 'data-no-instant' attr in my script tag and I do use InstantClick.on('change', function() {\n});\n\nExample jquery event that gets executed twice:\n\n$('.nav .menu-toggle').click(function() {\n\n ...\n\n});"
] | [
"javascript",
"jquery",
"instantclick.io"
] |
[
"Retrieve string from Javascript in Visual Basic",
"Ok so I'm working on a visual basic program that allows me to control pandora \nthrough hotkeys instead of having to access the site directly and press the buttons ect.\n\nTo my question, Is there a way I can access the javascript variables on the site to get\nsong name and, elapsed time ect? (I'm fairly new to visual basic)"
] | [
"vb.net",
"pandora"
] |
[
"MarkLogic Get all Nested Field name of Json document using javascript",
"I need a recursive function in javascript, which can return me all fieldname (Key Name) of my json document store in MarkLogic. JSON document is very dynamic and have multiple hierarchical elements. So need a function which can traverse through JSON and fetch all fieldname (Keys Name).\n\nOne option I thought was to get entire document into MaP object and run Map function to get all keys. But not sure whether MarkLogic allows to capture entire json doucment into Map and one can read fields names. \n\nThanks in Advance\n\nGot the function to iterate through JSON document to pull Key Name \n\nSample JSON \n\nvar object = {\n aProperty: {\n aSetting1: 1,\n aSetting2: 2,\n aSetting3: 3,\n aSetting4: 4,\n aSetting5: 5\n },\n bProperty: {\n bSetting1: {\n bPropertySubSetting : true\n },\n bSetting2: \"bString\"\n },\n cProperty: {\n cSetting: \"cString\"\n }\n}\n\n\nSolution available at StackOverflow\n\nRecursively looping through an object to build a property list \n\n*\n\nfunction iterate(obj, stack) {\n for (var property in obj) {\n if (obj.hasOwnProperty(property)) {\n if (typeof obj[property] == \"object\") {\n iterate(obj[property], stack + '.' + property);\n } else {\n console.log(property + \" \" + obj[property]);\n $('#output').append($(\"<div/>\").text(stack + '.' + property))\n }\n }\n }\n }\niterate(object, '')*"
] | [
"javascript",
"marklogic"
] |
[
"Firefox 57 loads http request twice",
"TL;DR This appears to be a browser problem that is fixed in newer (58+) versions.\n\n\n\nI'm working on a Node.js/express-based web server and I'm running into a problem where my browser (Firefox 57.0.1 on Mac OS) loads a page twice. I've been googling for tons and tons of other answers and blog posts, but haven't found a solution yet.\n\nObviously, apart from the double network traffic, this is a problem in an application that performs database work under the hood.\n\nReproducing the problem\n\nHere's a simple script to replicate the issue:\n\n#!/usr/bin/env node\n\nconst express = require('express');\n\nconst app = express();\napp.disable('etag');\n\napp.listen(3000, () => console.log('\\n\\n\\n\\n\\nListening on port 3000!'));\n\napp.all('/', function (req, res, next) {\n rn=Math.random();\n console.log('\\n'+req.method+' '+req.url);\n console.log('rn='+rn);\n res.send('rn='+rn);\n next();\n});\n\n\nFor every request to /, the server generates a random number and returns it to the client. That way, I can see (using console.log()) how many requests are being made and which ones are being rendered in the browser.\n\nWhen I request http://localhost:3000/, I get the following output in my console:\n\nGET /\nrn=0.3196834037080407\n\nGET /\nrn=0.8270968825090677\n\n\nFull HTTP headers\n\nUsing Firefox' developer tools, I can see that two identical requests are being made. First request:\n\nAccept: text/html,application/xhtml+xm…plication/xml;q=0.9,*/*;q=0.8\nAccept-Encoding: gzip, deflate\nAccept-Language: en-US,sv-SE;q=0.5\nCache-Control: max-age=0\nConnection: keep-alive\nDNT: 1\nHost: localhost:3000\nUpgrade-Insecure-Requests: 1\nUser-Agent: Mozilla/5.0 (Macintosh; Intel …) Gecko/20100101 Firefox/57.0\n\n\nFirst response:\n\nConnection: keep-alive\nContent-Length: 21\nContent-Type: text/html; charset=utf-8\nDate: Mon, 18 Dec 2017 05:44:51 GMT\nX-Powered-By: Express\n\n\nSecond request:\n\nAccept: text/html,application/xhtml+xm…plication/xml;q=0.9,*/*;q=0.8\nAccept-Encoding: gzip, deflate\nAccept-Language: en-US,sv-SE;q=0.5\nCache-Control: no-cache\nConnection: keep-alive\nDNT: 1\nHost: localhost:3000\nPragma: no-cache\nUpgrade-Insecure-Requests: 1\nUser-Agent: Mozilla/5.0 (Macintosh; Intel …) Gecko/20100101 Firefox/57.0\n\n\nThe only difference between the first and the second requests are the Cache-Control and Pragma headers.\n\nSecond response:\n\nConnection: keep-alive\nContent-Length: 21\nContent-Type: text/html; charset=utf-8\nDate: Mon, 18 Dec 2017 05:44:51 GMT\nX-Powered-By: Express\n\n\nI can actually see Firefox render the first number and then immediately replace it with the second, as if it actually clicks the \"Reload\" button.\n\nIn the developer tools, on the \"Stack trace\" tab seems to confirm this. Here's the first request:\n\nloadURI/< chrome://global/content/browser-child.js:354:14\n_wrapURIChangeCall chrome://global/content/browser-child.js:308:7\nloadURI chrome://global/content/browser-child.js:353:5\nreceiveMessage chrome://global/content/browser-child.js:288:9\n\n\n.. and the second request:\n\nreload chrome://global/content/browser-child.js:366:5\nreceiveMessage chrome://global/content/browser-child.js:297:9\n\n\nOther things I've checked\n\n\nI've disabled Adblock Plus for localhost. There are no other add-ons installed in the browser.\nNo other browser I've tried exhibits the same behaviour: Safari on MacOS, Chrome 63 on Windows, Edge, Internet Explorer 11.\nThere's no cross-origin stuff going on here, it's a simple one-page request.\nNo javascript involed.\nNo images, scripts or iframes with empty hrefs.\nBoth responses are HTTP/200, both requests are GET (i.e. no HEAD thing happening).\n\n\nAny pointers would be greatly appreciated."
] | [
"node.js",
"express",
"firefox"
] |
[
"Generate table relationship diagram from existing schema (For Sqlite Databse)",
"I have a sqlite database schema... Is there any tool available that would produce a diagram showing existing tables and their relationships?"
] | [
"sqlite"
] |
[
"How to use variables in a selector",
"With .class & I can add rules adds a parent-class to the path, but it always put that parent in the front of all parents.\n\nIs there someway to add a parent in the middle somewhere.\n\nI tried using a variable for it like this:\nExample less:\n\n@color: \"\";\n.a {\n .b @color {\n .d {\n .e {\n font-size: 2em;\n color: black;\n @color: \".yellow\";\n color: yellow;\n @color: \".red\";\n color: red;\n @color: \"\";\n }\n .f {\n font-size: 1.2em;\n }\n }\n }\n}\n\n\nExpected output:\n\n.a .b .d .e {\n font-size: 2em;\n color: black;\n}\n.a .b .yellow .d .e {\n color: yellow;\n}\n.a .b .red .d .e {\n color: red;\n}\n.a .b .d .f {\n font-size: 1.2em;\n}\n\n\nBut that didn't work.\n\nSo how do I write something that generates that output in a good way.\nI'd like to have the color variation close to the default color.\nAnd I'd like to not have unnecessary duplicated code = not reseting the font-size to the same value for each color."
] | [
"less"
] |
[
"Can touches be cancelled from a UIViewController?",
"Q: Is there a built in method to summarily cancel touch events in a UIView/UIViewController\n\nBackground: I am implementing a help system in my app that will have a message box on screen, and a colored overlay over the base UI. As the user taps the message box, it will disappear, a portion of the main UI will be revealed, and a new message box describing it will show up.\n\nThe important bit is having the revealed portion of the UI be useable while still not letting the rest work or not work as needed.\n\nI was about to make a bunch of views to act as a mask, but it would be way easier if I could dictate where touches should go based on location.\n\nI have started looking at overriding\n\n override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {\n\n}\n\n\nbut as far as I have been able to find, theres no simple method to call like in a gestureRecognizer to cancel (or set a cancelled state)."
] | [
"ios",
"swift",
"uiviewcontroller"
] |
[
"Pycharm console output not fully display as stored in variable",
"New to Pycharm here. I am trying to get the full output from my code but somehow it is shorten or converted in the console. Below are my code:\n\nimport subprocess\nimport os\n\nwdir='D:\\Microvirt\\MEmu'\nos.chdir(wdir)\nprocess = subprocess.Popen(\"adb shell screencap -p\", shell=True, \nstdout=subprocess.PIPE)\nscreenshot = process.stdout.read()\nprint(screenshot)\n\n\nPycharm Console Image:\n\n\nWhy is it differrent in the console output and the content stored in the variable ? How can I made it to display the same as in the variable on the right hand side ? Thank you for taking time to read."
] | [
"pycharm"
] |
[
"Select from index structure",
"Helo,\nSometimes I need to check only unique values on indexed column(s).\nIs there any fast way to check this directly from index (clustered)?\n\nI have table with several timestamps, each timestamp is in few milions rows, so even if I use index, query below takes quite long (5-8 minutes) with Index Scan.\n\nselect distinct TimeStamp from table\n\n\nWhen I execute several times (for all values) query like this\n\nSelect top 1 TimeStamp from table where TimeStamp='2018-06-01 09:43:09.440'\n\n\nit works instantly.\n\nGroup by didn't change anything\n\nSelect UpdateDate\nfrom [z_Arch_Exp_Czesciowy]\ngroup by UpdateDate\n\n\ntakes 6 minutes with index scan"
] | [
"sql-server",
"indexing"
] |
[
"Inheriting the same method from multiple interfaces",
"That we know multiple (interface) inheritance is allow in c# but, I want to know is it possible that two interface \nExample :\n\n interface calc1\n{\n int addsub(int a, int b);\n}\ninterface calc2\n{\n int addsub(int x, int y);\n}\n\n\nwith same method name with same type and with same type of parameter\n\nwill get inherit in above class ?\n\nclass Calculation : calc1, calc2\n{\n public int result1;\n public int addsub(int a, int b)\n {\n return result1 = a + b;\n }\n public int result2;\n public int addsub(int x, int y)\n {\n return result2= a - b;\n }\n}\n\n\nif yes then which interface method will get called.\n\nThanks in advance."
] | [
"c#",
"inheritance"
] |
[
"Generate \"JSON schema documentation\" automatically",
"So, I'm using alot of JSON while developing PHP applications. And a function returns json strings or whatever it's really hard to know what they contain, and it's time consuming to keep documenting up to date especially if it changes alot.\n\nWould it be a good idea to implement something like this:\n\nInstead of using return $x I would implement a function called _return which would something like:\n\nfunction _return($obj)\n{\n var_dump(debug_backtrace());\n return $obj;\n}\n\n\nIt would do more than that, it would look up in the stacktrace what the name of the function is and then I could make this code save the $obj type to an appropriate file, and they could be used to create automatically updated documentation!\n\nWould this be an okay idea? Maybe to time consuming to execute debug_backtrace() at each return?\n\nI would use it like:\n\nclass T\n{\n public function __constructor()\n {\n }\n\n public function first()\n {\n return $this->second();\n }\n\n public function second()\n {\n $array = array('david' => 'value', 'test' => 'oj');\n return _return($array);\n }\n\n}\n\nfunction _return($obj)\n{\n var_dump(debug_backtrace());\n return $obj;\n}\n\n$t = new T();\n$t->first();"
] | [
"php",
"documentation",
"automation"
] |
[
"Validation two length options",
"I'm validating the model field number.\n\nI try to achieve that only numbers that are 8 or 6 characters long are allowed.\n\nBut with this code i get a error:\n\nCode:\n\nvalidates :number, length: { is: [6,8] } \n\n\nError:\n\nArgumentError (:is must be a nonnegative Integer or Infinity):\n app/models/patient.rb:6:in `<class:Patient>'\n app/models/patient.rb:1:in `<top (required)>'\n app/controllers/patients_controller.rb:38:in `create'\n\n\nHow should i change my code? Thanks"
] | [
"ruby-on-rails",
"ruby-on-rails-3",
"validation",
"ruby-on-rails-4"
] |
[
"Listiview Scrolling Down-Up Changes row's color",
"I'm using a listview with adapter inside for changing backcolor in every row according value Active.\nAlso i'm using holder in my adapter but every time i'm scrolling down and up my listview, all colors are been changed.\n\nHere is my Class:\n\nclass FactClass\n{\n [PrimaryKey, AutoIncrement, Column(\"_Id\")]\n\n public int id { get; set; } // AutoIncrement and set primarykey \n\n public string Name { get; set; }\n public string Phone { get; set; }\n\n public string Comments { get; set; }\n\n public int Active { get; set; }//According this Values ListView is changing Color\n\n public string Location { get; set; }\n\n public bool IsChecked { get; set; }\n\n}\n\n\nHere is my Adapter:\n\npublic override View GetView(int position, View convertView, ViewGroup parent)\n {\n DataViewHolder holder = null;\n if (convertView == null)\n {\n convertView = LayoutInflater.From(mContext).Inflate(Resource.Layout.FactAdapter, null, false);\n holder = new DataViewHolder();\n\n holder.txtid = convertView.FindViewById<TextView>(Resource.Id.idtxt);\n holder.txtName = convertView.FindViewById<TextView>(Resource.Id.Nametxt);\n holder.txtPhone = convertView.FindViewById<TextView>(Resource.Id.Phonetxt);\n holder.txtActive = convertView.FindViewById<TextView>(Resource.Id.Activetxt);\n\n convertView.Tag = holder;\n\n }\n else\n {\n\n holder = convertView.Tag as DataViewHolder;\n\n }\n\n holder.txtid.Text = Convert.ToString(mitems[position].id);\n holder.txtName.Text = mitems[position].Name;\n holder.txtPhone.Text = mitems[position].Phone;\n\n\n holder.txtActive.Text = Convert.ToString(mitems[position].Active);\n\n if (holder.txtActive.Text == \"1\")\n {\n holder.txtName.SetBackgroundColor(Color.LightGreen);\n holder.txtPhone.SetBackgroundColor(Color.LightGreen);\n }\n if (holder.txtActive.Text == \"2\")\n {\n holder.txtName.SetBackgroundColor(Color.Orange);\n holder.txtPhone.SetBackgroundColor(Color.Orange);\n }\n return convertView;\n\n }\n\n public class DataViewHolder : Java.Lang.Object\n {\n public TextView txtid { get; set; }\n public TextView txtName { get; set; }\n public TextView txtPhone { get; set; }\n public TextView txtActive { get; set; }\n\n\n }\n\n\nThe TextView txtActive is responsible for which color will take my row.\nExample if txtActive =1 row is green, txtActive =2 row is orange\n\nImage Before scrolling listview\n\nImage after Scolling Down and up again my listview\n\nAnother row has automatically changed his color."
] | [
"java",
"c#",
"xamarin"
] |
[
"What is the best way to store data from Firebase to SQLite or offline in flutter?",
"In my app when user is offline, I want data to store in local db and then sync data with firebase."
] | [
"firebase",
"flutter",
"firebase-realtime-database",
"dart",
"google-cloud-firestore"
] |
[
"Testing for bugs on Apple devices that you do not own",
"I'm starting to send out a beta version of my app for users to test. One came back and told me that the app crashes on her iPod Touch (2nd Gen). How do I debug for this considering I don't own one. All I have is the iPhone 4, yet there 9 other devices (each generation of iPhone, iPod Touch and iPad) that I would like my app to run on. Any advice?\n\nEDIT 1\n\nThere is no iPod Touch hardware option in the simulator. Should I just assume that it is treated as an iPhone?"
] | [
"iphone",
"unit-testing",
"debugging",
"ipad",
"ipod-touch"
] |
[
"Magento get $product->getFinalPrice();",
"I am having issue in magento..\nOn my product Page when I try \n\n$product->getFinalPrice();\n\n\nit shows discounted Price correctly ($812)..\n\nbut when order is placed, Instead of this price, I get some other wrong price(411) ( I haven;t figured out what Price is that because I haven't set that price anywhere while adding this prodcut)\n\nso my question is, \n\nHow can I send Correct Price ($product->getFinalPrice();) on Cart page..\n\nOn cart page, price is shown with \n$item->getPrice() which comes from qouted items \n\nanyway I can access $product->getFinalPrice(); and replace $item->getPrice(). with $product->getFinalPrice(); on cart page ???\n\ncan anybody guide me why prices are shown so wrong??"
] | [
"magento",
"methods",
"cart"
] |
[
"how to search a text in solr using REST Api?",
"I have a query in Elastic Search shown below\n\nsample code\n\nHow can I perform the same using Solr?"
] | [
"solr"
] |
[
"What is the difference in accessing an external string from a resource using a different method?",
"In my current application, I am implementing localization. I came across various ways to access the string (external string). Some methods are:\n\n\nAccessing directly using R.string.hello\nUsing getResourse().getString(R.string.hello)\ngetString.\nThe Eclipse tool to externalize resources, which creates a message.property file and access the string from a snippet.\n\n\nThe main confusion is between 1 and 2. If I use \"1\" that is accessing directly, can I get resources based on locale?"
] | [
"android",
"string",
"localization"
] |
[
"OutOfMemeryError from take photo android in some devices",
"I have a problem when I take a photo with the camera in some devices and versions of Android. For example, in my Xperia U v4.0.3 my code works good but in another xperia U v2.3.3 it doesn't work...\n\nI read a lot of about this error but I couldn't fix it... \n\nMy code to take a photo and show it:\n\npublic void callCamera(){\nIntent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);\nFile photo = new File(Environment.getExternalStorageDirectory(), \"Pic.jpg\");\nintent.putExtra(MediaStore.EXTRA_OUTPUT,\nUri.fromFile(photo));\nimageUri = Uri.fromFile(photo);\nstartActivityForResult(intent, SELECT_CAMERA);\n}\n\npublic void onActivityResult(int requestCode, int resultCode, Intent data) {\n if (requestCode == SELECT_CAMERA) {\n\n\n Uri selectedImage = imageUri;\n getContentResolver().notifyChange(selectedImage, null);\n\n ContentResolver cr = getContentResolver();\n\n try {\n\n imageSelected = android.provider.MediaStore.Images.Media\n .getBitmap(cr, selectedImage);\n // I tried to read the image created for the camera in the Sd\n //But I've got the same error... \n //imageSelected = Utils.readImageSD(this, selectedImage.getPath());\n\n imageSelected = Utils.rotateImage(Utils.scaleBitmap(imageSelected, 160, 160));\n ivImageLoad.setImageBitmap(imageSelected);\n\n } catch (Exception e) {\n Utils.showToast(getApplicationContext(), R.string.errorLoad);\n Log.e(\"Camera\", e.toString());\n }\n\n }\n\n}\n\n\nI hope somebody can help me... I don't know what can I do.... \n\nThanks in advance.\n\nRegards."
] | [
"android",
"camera",
"out-of-memory"
] |
[
"How to keep image's tintColor for an UIButton?",
"I created a custom class CircularButton in which I can set a custom image, backgroundColor, tintColor for the image and inset to the edge of the button.\n\nIt's working fine, except for the tintColor. I want to be able to set the tintColor, but if I don't provide one, it should keep the original tintColor of my image (rendered as template image).\n\nopen class CircularButton: UIButton {\n\n public init(width: CGFloat, backgroundColor: UIColor? = nil, tintColor: UIColor? = nil, image: UIImage? = nil, contentMode: ContentMode? = nil, insets: UIEdgeInsets? = nil) {\n super.init(frame: .zero)\n\n self.backgroundColor = backgroundColor ?? .clear\n self.tintColor = tintColor ?? // issue is here\n self.imageEdgeInsets = insets ?? .zero\n self.imageView?.contentMode = contentMode ?? .scaleAspectFit\n\n setImage(image?.withRenderingMode(.alwaysTemplate), for: .normal)\n\n if width != 0 {\n widthAnchor.constraint(equalToConstant: width).isActive = true\n }\n\n heightAnchor.constraint(equalTo: widthAnchor).isActive = true\n clipsToBounds = true\n }\n\n override open func layoutSubviews() {\n super.layoutSubviews()\n\n layer.cornerRadius = frame.width / 2\n }\n\n public required init?(coder aDecoder: NSCoder) {\n fatalError()\n }\n}\n\n\nHere is how I initialize it :\n\nlet likeButton = CircularButton(width: 45, backgroundColor: #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.5), tintColor: .white, image: UIImage(named: \"heart\"), insets: .init(top: 5, left: 5, bottom: 5, right: 5))\n\n\nThis is working, except that if I don't want to provide a tintColor, it takes the default blue tintColor for the button and render my image in blue.\n\nHere is what I have tried in my custom class:\n\n...\n\nself.tintColor = tintColor ?? imageView?.tintColor"
] | [
"ios",
"swift",
"tintcolor"
] |
[
"Writing assert messages to log file",
"I have written a c++ application to be run on an embedded device running onboard Linux OS. For debug purposes I have inserted std::cout statements in my application. \n\nI run the application using the below command to store all my log messages into a file\n\n./TestApplication > /var/log/test_log\n\n\nAs expected all the log messages are stored in test_log. But when the application faces an assertion, the assert message is not stored in the log file. \n\nMy application depends on a lot of third party packages which each have their own custom assert function. Hence writing my own custom assert function for the application as a whole will be too difficult as I need to cater for the third party custom asserts also.\n\nIs there a simple way to dump all my log and assert messages into a log file?"
] | [
"c++",
"linux",
"embedded",
"assert"
] |
[
"Running a while loop and retrieving row names from dataset on R",
"What I'm trying to do right now is to get, from the mtcars dataset on R, the car names that are that have an hp column value of less than 200. The thing is that I want the car names and I don't want to go back and rematch all the numbers with the corresponding car names. How might I go about doing that? Here's what I have so far:\n\n> carvector<-mtcars[\"hp\"]\n> while (i<=32)\n+ i<-i+1\nif (mtcars[i,1]<200)\np<-mtcars[i,1]\n\n\nIts not quite working and I guess I'm closer to storing the values than the names of the cars. How can I make sure the names are not lost? How do I dispose of the values I don't want?"
] | [
"r",
"while-loop",
"statistics"
] |
[
"Update elements within Nested Xml",
"I have Xml which looks like this:\n\n<DataMapper xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n <SqlTable />\n <Level_01s>\n <DataParameter>\n <SqlTable>MY-Table-Name</SqlTable>\n <Children>\n <DataParameter>\n <SqlTable>MY-Table-Name</SqlTable>\n <Children>\n <DataParameter>\n <SqlTable>MY-Table-Name</SqlTable>\n <Children>\n <DataParameter>\n <SqlTable>[All]</SqlTable>\n <Children />\n </DataParameter>\n <DataParameter>\n <SqlTable>MY-Table-Name</SqlTable>\n <Children>\n <DataParameter>\n <SqlTable>[All]</SqlTable>\n <Children />\n </DataParameter>\n </Children>\n </DataParameter>\n </Children>\n </DataParameter>\n </Children>\n </DataParameter>\n </Children>\n </DataParameter>\n </Level_01s>\n</ DataMapper>\n\n\nWhat I'd like to do is update all instances of the element. The issue that I have is that the DataParameters may go n-levels deep.\n\nHow can I recursivly ensure I update all of these?\n\nI am using this code to update Root-level elements:\n\nXDocument xdoc = XDocument.Parse(myxmlstring);\nvar element = xdoc.Elements(\"SqlTable\").Single();\nelement.Value = \"foo\"; \nxdoc.Save(\"file.xml\");\n\n\nvia Best way to change the value of an element in C#"
] | [
"c#",
".net",
"xml",
"linq-to-xml"
] |
[
"Spring MVC Hibernate - Save object with multiple checkboxes",
"I'm trying to understand how can I save an employee with multiple tasks. But I don't know even how to start.\n\n\n\n// Employee class\n@Entity\npublic class Employee {\n\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private int id;\n private int idNumber;\n private String firstName;\n private String lastName;\n\n @ManyToOne\n @JoinColumn(name = \"task_id\")\n private Set<Task> tasks = new HashSet<Task>();\n\n}\n\n// Task class\n@Entity\npublic class Task {\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private int id;\n private String name;\n}\n\n// Dao\n@Override\npublic void saveEmployee(Employee employee) {\n sessionFactory.getCurrentSession().save(employee);\n} \n\n// Controller\n@RequestMapping(value = \"/save\", method = RequestMethod.POST)\npublic @ResponseBody void saveEmployee(@RequestBody Employee employee){\n employeeRepository.saveEmployee(employee)\n}\n\n\nI'll really appreciate if you refer documentation or code of any related example."
] | [
"java",
"spring",
"hibernate"
] |
[
"Keep JFrame on top of others",
"I am in a situation where I create a frame FrameB from my main frame FrameA. When the user is working on FrameB I would like it to be on top of FrameA even when the user accidentally clicks on FrameA."
] | [
"java",
"swing",
"jframe"
] |
[
"Trying to create a program that adds outliers of a data set to a new list (So I can identify how many outliers are in a dataset)",
"I am attempting to create a program that generates a data set based on numbers you give it and then plots a histogram based on the data set. I need to see the exact number of outliers in the data set, I am trying to do this by creating a 'clean' list with all of the non-outliers and and then leaving the original data set array with only outliers. However, when I try to do this both arrays stay exactly the same. Not isolating outliers at all. (It's like there are no outliers in the data)\n(All I need to achieve with this program is seeing the bin_count_1, bin_count_2 and the amount of outliers in the data set)\nCode:\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport csv\n\ndata_seed = 1700\ndata_mean = 175\ndata_size = 1123\ndata_bin_num = 41\n\ndata_std = 7\n\nnp.random.seed(data_seed)\ndata_set = np.random.normal(data_mean, data_std, size = data_size)\n\ndata_bin_count, data_value, patches = plt.hist(data_set, facecolor='blue', bins = 41)\n\nplt.xlabel('Data')\nplt.ylabel('Count')\nplt.axis([np.amin(data_set), np.amax(data_set), 0, 1.05*np.amax(data_bin_count)])\nplt.grid(True)\nplt.show()\n\nbin_count_1 = data_bin_count[data_bin_num // 4]\nbin_count_2 = data_bin_count[data_bin_num // 2]\nprint(bin_count_1, bin_count_2)\n \ndef Outlier(a, IQR, Q1, Q3):\n \n if a < Q1 - 1.5 * IQR or a > Q3 + 1.5 * IQR:\n \n outlier = True\n else:\n outlier = False\n \n return(outlier)\n\ndata_clean = []\noutlier_set = []\n\nQ1 = np.percentile(data_set, 25) \nQ3 = np.percentile(data_set, 75)\nIQR = max(data_set) - min(data_set) \nIQRround = round(IQR, 2) \n\nprint("Q1 = {:,.2f}".format(Q1)) \nprint("Q3 = {:,.2f}".format(Q3))\nprint(f"IQR = {IQRround}") \n\nn= len(data_set)\n\nfor i in range(n): \n \n outlier = Outlier(data_set[i], IQR, Q1, Q3)\n\n if outlier == False : \n data_clean.append(data_set[i])\n else:\n print("value removed (outlier) = {:,.2f}".format(data_set[i])) \n \ndata_clean = np.asarray(data_clean) \n\nn = len(data_clean) \nprint("n = {:.0f}".format(n)) \n\nprint("data_clean = {}".format(data_clean))\nprint(f"data_set = {data_set}") \n\ndata_outlier_count = len(data_set)\nprint(data_outlier_count)\n\nOutlier detection function:\ndef Outlier(a, IQR, Q1, Q3):\n \n if a < Q1 - 1.5 * IQR or a > Q3 + 1.5 * IQR:\n \n outlier = True\n else:\n outlier = False\n \n return(outlier)\n\nError:\nProgram is not detecting outliers from a data set (All I need to know is the bin_count_1, bin_count_2 and the amount of outliers in the data.\nThings I have already tried:\nRemoving the outliers to a completely separate list.\nSubtracting 'data_set' and 'data_clean' it = 0\nIt is like the detection function isn't working at all, the program doesn't know what an outlier is and I'm not sure why."
] | [
"python",
"numpy",
"matplotlib",
"dataset",
"outliers"
] |
[
"JSON unmarshalling to POJO and inserting",
"I would like to unmarshal a json string to a pojo class. \nI am reading it from an existing url: \nhttps://builds.apache.org/job/Accumulo-1.5/api/json\n\nI am using apache camel to unmarshal the url\n\n@Component\npublic class RouteBuilder extends SpringRouteBuilder {\n\nprivate Logger logger = LoggerFactory.getLogger(RouteBuilder.class);\n@Override\npublic void configure() throws Exception {\n\n logger.info(\"Configuring route\");\n\n //Properties die hij niet vindt in de klasse negeren\n ObjectMapper objectMapper = new ObjectMapper();\n objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);\n\n\n DataFormat reportFormat = new JacksonDataFormat(objectMapper, HealthReport.class);\n\n from(\"timer://foo?fixedRate=true&delay=0&period=2000&repeatCount=1\")\n .routeId(\"accumoloToJsonRoute\")\n .setHeader(Exchange.HTTP_METHOD, constant(\"GET\"))\n .to(\"https://builds.apache.org:443/job/Accumulo-1.5/api/json\")\n .convertBodyTo(String.class)\n .unmarshal(reportFormat) //instance van Build\n .log(LoggingLevel.DEBUG, \"be.kdg.teamf\", \"Project: ${body}\")\n .to(\"hibernate:be.kdg.teamf.model.HealthReport\");\n\n\n}\n\n}\n\n\nSo far so good. I would like to only insert the 'healthReport' node using hibernate annotations.\n\n@XmlRootElement(name = \"healthReport\")\n@JsonRootName(value = \"healthReport\")\n@Entity(name = \"healthreport\")\npublic class HealthReport implements Serializable {\n@Id\n@GeneratedValue(strategy = GenerationType.IDENTITY)\nprivate int Id;\n\n@Column\n@JsonProperty(\"description\")\nprivate String description;\n\n@Column\n@JsonProperty(\"iconUrl\")\nprivate String iconUrl;\n\n@Column\n@JsonProperty(\"score\")\nprivate int score;\n\npublic HealthReport() {\n}\n\npublic HealthReport(int score, String iconUrl, String description) {\n this.score = score;\n this.iconUrl = iconUrl;\n this.description = description;\n}\n\npublic String getDescription() {\n return description;\n}\n\npublic String getIconUrl() {\n return iconUrl;\n}\n\npublic int getId() {\n return Id;\n}\n\npublic int getScore() {\n return score;\n}\n\npublic void setDescription(String description) {\n this.description = description;\n}\n\npublic void setIconUrl(String iconUrl) {\n this.iconUrl = iconUrl;\n}\n\npublic void setId(int id) {\n Id = id;\n}\n\npublic void setScore(int score) {\n this.score = score;\n}\n}\n\n\nThis is where the problem is. It does not recognize the annotations \nand only null values are inserted in my database \n\n@XmlRootElement(name = \"healthReport\")\n@JsonRootName(value = \"healthReport\")\n\n\nDoes anybody know how to fix this?\n\nThanks"
] | [
"json",
"hibernate",
"annotations",
"apache-camel"
] |
[
"Personalize ReactJS Pagination Style in Ant.Design - Is there any way?",
"I'm developing a website based on ReactJS. Among different libraries, I've chosen Ant-Design (antd) due to its pretty elements. However, I do actually need to change some element styles. In Pagination component, I've chosen Simple mode which is shown in below image:\n\n\n\nThe code for this component is:\n\n<Pagination simple defaultCurrent={2} total={50} />\n\n\nIs there any way to change the format of this component? Something like \"2 from 5\" instead of \"2 / 5\"? I know it has nothing to do with CSS!"
] | [
"javascript",
"reactjs",
"web",
"antd"
] |
[
"How to pass data from MainActivity to Recyclerview adapter in KOTLIN ANDROID STUDIO",
"I tried accessing shared preferences inside view holder but I want to access it throughout the whole activity which I couldn’t so then I tried to pass the values from MainActivity through intent.putextras() but I don’t know how to receive it inside the recycler view adapter"
] | [
"android-studio",
"kotlin",
"android-recyclerview"
] |
[
"Ajax events in jQuery - firing an event on form submission using Rails",
"I have a page with multiple forms on it. These forms are using a data attribute data-remote=\"true\n so that the Rails jquery-ui-rails.js automatically adds events to submit these forms via javascript.\n\nWhen a user submits any of these forms I would like to add a class so I can style it as needed. As Rails is automatically adding the ajax handlers to submit the form I can't just add this class at the point the handlers are added - I need to manually add code for this myself (I think).\n\nThe following code was my first attempt - this attaches okay, but as ajaxStart is a global event it triggers it simultaneously for every form on the page.\n\n$('form').ajaxStart(function(e) {\n console.log(\"element is \" + ($(e).attr('id')));\n return $(e).addClass('submitting');\n})\n\n\nI have also tried beforeSend as according to http://docs.jquery.com/Ajax_Events this is a local event and seems to be the only relevant one: \n\n$('form').beforeSend(function(e) {\n console.log(\"element is \" + ($(e).attr('id')));\n return $(e).addClass('submitting');\n})\n\n\nHowever, this raises the error:\n\nUncaught TypeError: Object [object Object] has no method 'beforeSend' \n\n\nHow can I attach this event to all of the forms on my page so that it fires once per ajax submission, and only for the current form that is being submitted?"
] | [
"jquery",
"ruby-on-rails",
"ajax"
] |
[
"Transferring data between layers of an application",
"If I have a C# application with a 5 layer architecture, much like what is presented here http://msdn.microsoft.com/en-us/library/ee658109.aspx, and I take the strict interaction approach of allowing a layer to only interact with the layer below, I am running into trouble when getting data in my Data layer and passing that data back up to my Business layer.\n\nFor example, if I have a business object called MyObject that is defined in my Business layer, but information needed to construct an object of type MyObject is retrieved from the database in the Data layer, my Business layer needs a reference to my Data layer in order to interact with the database. But, my Data layer then also needs a reference to the Business layer, since that is where the MyObject definition lives and the Data layer needs to construct an object of that type from the database results and give that data back to the Business layer. Now we have a circular dependency between the Business layer and the Data layer.\n\nI am wondering what the proper approach is to solve this problem.\n\nI have thought about using DTO objects defined in my Data layer to pass information back to the Business layer. This would work since the Business layer is able to interact with the Data layer, but not vice versa. It just seems like this might be an awful lot of duplicate code to basically mimic the business object definitions in the Data layer.\n\nI also thought about creating interfaces for all of my business objects and putting those interfaces into a separate project that both the Business layer and Data layer can interact with. That way, I can pass instances of the interface and the only common reference between the Business layer and Data layer is the project where the interfaces are defined. I don't see many implementations of this either.\n\nI am wondering what others have done to solve this problem."
] | [
"c#"
] |
[
"Waiting for Network Connection To Complete before proceeding with Func?",
"I have a resume function that reestablishes a network connection before it gathers updated parameters for the app.\n\nIssue is that it seems to be trying to get some parameters before the network link has been reestablished.\n\nIs there a way i can pause until the connection is made?\n\nThe getParameters func is on a background thread using:\n\ndispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^(void) { //code }\n\n\nThe initConnection is primary thread\n\nHere is the func:\n\n- (void)screenUnlocked {\n [self initConnection];\n\n CDCChannelCollectionView *scrollView;\n\n if ([self channelView]) {\n scrollView = [[self channelView] scrollView];\n for (CDCChannelStrip* strip in [scrollView visibleCells]) {\n [self getParameters:[NSNumber numberWithInteger:strip.channelNumber]];\n }\n }\n}\n\n\nedit:\n\nSomething like this?\n\n- (void)initConnection: completion:(void (^)(void))completionBlock {\n if (![self isDemo]) {\n [self setTcpControl:[[CDCControl alloc] initWithAddress:[self IPAddress] usingProtocol:TCP]];\n [[self tcpControl] setDelegate:self];\n [self setUdpControl:[[CDCControl alloc] initWithAddress:[self IPAddress] usingProtocol:UDP]];\n [[self udpControl] setDelegate:self];\n\n if (successful) {\n completionBlock();\n }\n }\n}"
] | [
"ios",
"objective-c",
"networking"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.