texts
sequence
tags
sequence
[ "ASP.NET Handler for managing images/files", "I need to do the following:\n\n\nShow Image on a page\nShow a link to a document (PDF, DOC etc) that opens up the document\nUpload a image\n\n\nI have the functionality in the backend that has the following signatures:\n\npublic byte[] GetFile(string fileName) //For both documents and images\n\npublic void AddFile(string fileName, byte[] data) //For both documents and images\n\n\nMy question is, can I write a handler that can get images/documents and upload images/documents so that I can use it in my client by doing a:\n\n<asp:Image runat=\"server\" ImageUrl=\"~/Image.ashx?FileName=myFileName\" />\n\n\nThe handler in turn would call the GetFile and AddFile methods.\n\nThis may work for showing images. What about showing documents and uploading images/documents?\n\nAlso, what about the security associated with the handler? Can a malicious user use it?" ]
[ "c#", "asp.net", ".net" ]
[ "How to you remove unwanted server info on response", "I have what I think is just a really simple question but I cant seem to find the answer on google or i'm just using the wrong terms.\n\nI'm using PHP Mailer to send emails, there's no problem with that.\n\nMy problem is on the response headers I am receiving other information. Some smtp client -> server info. That's fine and all, helps me see status of smtp but now i can't read the ajax response from the page.\n\nIs there a way to remove the client -> server info or a way to just read the returned value of the ajax page?\n\n2016-02-27 15:42:06 SERVER -> CLIENT: 220 smtp.gmail.com ESMTP e1sm26974173pas.1 - gsmtp\n2016-02-27 15:42:06 CLIENT -> SERVER: EHLO localhost\n2016-02-27 15:42:07 SERVER -> CLIENT: 250-smtp.gmail.com at your service, [121.54.58.240]\n 250-SIZE 35882577\n 250-8BITMIME\n 250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH\n 250-ENHANCEDSTATUSCODES\n 250-PIPELINING\n 250-CHUNKING\n 250 SMTPUTF8\n2016-02-27 15:42:07 CLIENT -> SERVER: AUTH LOGIN\n2016-02-27 15:42:07 SERVER -> CLIENT: 334 VXNlcm5hbWU6\n2016-02-27 15:42:07 CLIENT -> SERVER: aUhlbHAuc3d1QGdtYWlsLmNvbQ==\n2016-02-27 15:42:07 SERVER -> CLIENT: 334 UGFzc3dvcmQ6\n2016-02-27 15:42:07 CLIENT -> SERVER: aWhlbHAxMjM0\n2016-02-27 15:42:08 SERVER -> CLIENT: 235 2.7.0 Accepted\n2016-02-27 15:42:08 CLIENT -> SERVER: \n2016-02-27 15:42:08 SERVER -> CLIENT: 250 2.1.0 OK e1sm26974173pas.1 - gsmtp\n2016-02-27 15:42:08 CLIENT -> SERVER: \n2016-02-27 15:42:08 SERVER -> CLIENT: 250 2.1.5 OK e1sm26974173pas.1 - gsmtp\n2016-02-27 15:42:08 CLIENT -> SERVER: DATA\n2016-02-27 15:42:09 SERVER -> CLIENT: 354 Go ahead e1sm26974173pas.1 - gsmtp\n2016-02-27 15:42:09 CLIENT -> SERVER: Date: Sat, 27 Feb 2016 16:42:06 +0100\n2016-02-27 15:42:09 CLIENT -> SERVER:\n2016-02-27 15:42:09 CLIENT -> SERVER: \n2016-02-27 15:42:09 CLIENT -> SERVER: \n2016-02-27 15:42:09 CLIENT -> SERVER: Subject: Reset password complete\n2016-02-27 15:42:09 CLIENT -> SERVER: Message-ID: <fcad829908390aaf1cf72f28886ac1d5@localhost>\n2016-02-27 15:42:09 CLIENT -> SERVER: X-Mailer: PHPMailer 5.2.13 (https://github.com/PHPMailer/PHPMailer)\n2016-02-27 15:42:09 CLIENT -> SERVER: MIME-Version: 1.0\n2016-02-27 15:42:09 CLIENT -> SERVER: Content-Type: multipart/alternative;\n2016-02-27 15:42:09 CLIENT -> SERVER: boundary=\"b1_fcad829908390aaf1cf72f28886ac1d5\"\n2016-02-27 15:42:09 CLIENT -> SERVER: Content-Transfer-Encoding: 8bit\n2016-02-27 15:42:09 CLIENT -> SERVER:\n2016-02-27 15:42:09 CLIENT -> SERVER: This is a multi-part message in MIME format.\n2016-02-27 15:42:09 CLIENT -> SERVER:\n2016-02-27 15:42:09 CLIENT -> SERVER: --b1_fcad829908390aaf1cf72f28886ac1d5\n2016-02-27 15:42:09 CLIENT -> SERVER: Content-Type: text/plain; charset=us-ascii\n2016-02-27 15:42:09 CLIENT -> SERVER:\n2016-02-27 15:42:09 CLIENT -> SERVER: \n2016-02-27 15:42:09 CLIENT -> SERVER:\n2016-02-27 15:42:09 CLIENT -> SERVER:\n2016-02-27 15:42:09 CLIENT -> SERVER: --b1_fcad829908390aaf1cf72f28886ac1d5\n2016-02-27 15:42:09 CLIENT -> SERVER: Content-Type: text/html; charset=us-ascii\n2016-02-27 15:42:09 CLIENT -> SERVER:\n2016-02-27 15:42:09 CLIENT -> SERVER: \n2016-02-27 15:42:09 CLIENT -> SERVER:\n2016-02-27 15:42:09 CLIENT -> SERVER:\n2016-02-27 15:42:09 CLIENT -> SERVER:\n2016-02-27 15:42:09 CLIENT -> SERVER: --b1_fcad829908390aaf1cf72f28886ac1d5--\n2016-02-27 15:42:09 CLIENT -> SERVER:\n2016-02-27 15:42:09 CLIENT -> SERVER: .\n2016-02-27 15:42:09 SERVER -> CLIENT: 250 2.0.0 OK 1456587732 e1sm26974173pas.1 - gsmtp\n2016-02-27 15:42:09 CLIENT -> SERVER: QUIT\n2016-02-27 15:42:10 SERVER -> CLIENT: 221 2.0.0 closing connection e1sm26974173pas.1 - gsmtp\n1\n\n\nI basically just need that \"1\" at the end as confirmation of ajax call.\n\nPlease help. Thank you" ]
[ "ajax", "phpmailer" ]
[ "My java script cropper stops working once i implement to save the images in an S3 (django)", "I'm creating a website to upload images and crop said images, and everything is working until I implement that the images be saved in an S3.\nThis is how it looks like with the s3 impelented\nAnd this is how it should look, and how it looks when i comment out the S3 part in the settings\nThis is what I have in settings:\nDEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'\nAWS_ACCESS_KEY_ID = 'AKIAZ5FSUY7STUQSZKVO'\nAWS_SECRET_ACCESS_KEY = '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'\nAWS_STORAGE_BUCKET_NAME = 'djangos3-2'\nAWS_S3_OBJECT_PARAMETERS = {\n 'CacheControl': 'max-age=86400',\n}\nAWS_QUERYSTRING_AUTH = 'False'\nS3_USE_SIGV4 = True\nAWS_S3_SIGNATURE_VERSION = 's3v4'\n\nThe image model:\nclass ImageModel(models.Model):\n created_on = models.DateTimeField(null=True)\n created_by = models.ForeignKey(User, related_name='images', editable=False, on_delete=models.PROTECT)\n image = models.ImageField(upload_to='storage')\n\nAnd the template\n{% extends "base.html" %}\n\n{% block Title %} - SW1+ Data Entry - Crop Upload{% endblock Title %}\n\n{% load static %}\n\n{% block headScript %}\n<link rel="stylesheet" type="text/css" href="{% static 'node_modules/cropperjs/dist/cropper.css' %}" />\n<script type="text/javascript" src="{% static 'node_modules/cropperjs/dist/cropper.js' %}"></script>\n\n<style>\n .image{\n display: block;\n max-width: 100%;\n }\n\n</style>\n{% endblock headScript %}\n\n{% block body %}\n<a href="{% url 'sw2manager:data_entry' %}" class="btn btn-primary">Back</a>\n <div>\n <img id="image" src="{{image.image.url}}" style="width: 450px;height: 350px;">\n </div>\n<------ Code not shone for briefness -------> \n<script type="text/javascript ">\n var image = document.getElementById('image');\n\n image.addEventListener('cropend', function (e) {\n crop();\n });\n\n var cropper = new Cropper(image, {});\n\n var formData;\n\n function crop(){\n\n cropper.getCroppedCanvas().toBlob(function (blob) {\n\n var urlCreator = window.URL || window.webkitURL;\n var imageUrl = urlCreator.createObjectURL(blob);\n document.querySelector("#imaget").src = imageUrl;\n\n formData = new FormData();\n\n formData.append('image', blob, "blob.png");\n\n formData.append('csrfmiddlewaretoken', '{{ csrf_token }}');\n\n });\n\n }\n\n $("#crop").on("click", crop);\n\n function save(){\n\n $.ajax("{% url 'sw2manager:imageajaxupload' image.page.pk %}", {\n method: "POST",\n data: formData,\n processData: false,\n contentType: false,\n success: function () {\n window.location.reload();\n console.log('Upload success');\n alert("Upload success!!!");\n\n },\n error: function () {\n console.log('Upload error');\n alert("Upload error...");\n }\n });\n\n }\n\n $("#save").on("click", save);\n\n\nI'm very very new to js and the cropper itself was built with someone else's help so maybe Im missing something obvious, so if anyone can lend any help I would be very grateful." ]
[ "javascript", "html", "django", "amazon-s3" ]
[ "How to get JdbcClientTokenServices to store tokens in datasource?", "Here is my code, I need to setMandatory to 'false' because the resource provider does not return the 'state' parameter as the Oauth2 specification recommends.\n\n @Bean\n @Scope(value = \"session\", proxyMode = ScopedProxyMode.INTERFACES)\n public OAuth2RestOperations restTemplate() {\n OAuth2RestTemplate template = new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(accessTokenRequest));\n AuthorizationCodeAccessTokenProvider authorizationCodeAccessTokenProvider = new AuthorizationCodeAccessTokenProvider();\n authorizationCodeAccessTokenProvider.setStateMandatory(false);\n AccessTokenProviderChain provider = new AccessTokenProviderChain(Arrays.asList(authorizationCodeAccessTokenProvider));\n provider.setClientTokenServices(clientTokenServices());\n template.setAccessTokenProvider(provider);\n return template;\n }\n\n\nHere is the code from the github example that works with H2:\n\n @Bean\n @Scope(value = \"session\", proxyMode = ScopedProxyMode.INTERFACES)\n public OAuth2RestOperations restTemplate() {\n OAuth2RestTemplate template = new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(accessTokenRequest));\n AccessTokenProviderChain provider = new AccessTokenProviderChain(Arrays.asList(new AuthorizationCodeAccessTokenProvider()));\n provider.setClientTokenServices(clientTokenServices());\n return template;\n }\n\n\n\nI changed the LONGVARBINARY to BLOB for all cases in schema.sql, in order to get the scripts to work with MySQL. I can verify that my database is created.\ntemplate.setAccessTokenProvider(provider); without this line, I still get the CSRF problems because the resource provider isn't returning the \"state\" param.\nI am using an AuthorizationCodeResourceDetails just like the example as well. I also setup my accessTokenRequest and clientTokenServices identical to the example.\n\n\nAfter the user authorizes the client and is redirected back, the code is exchanged for a token and things are working. I can see that my client does have an access token. I expect to see that access token stored in the database as well. I am creating the database schema on startup and the datasource appears to be setup properly. I don't get any errors during runtime that point to configuration issues either. Everything else is working as expected, I just don't get any data in any of the tables where I expect to see information about the access and refresh tokens sent back from the resource server." ]
[ "spring-security-oauth2" ]
[ "ansible-playbook --extra-vars not accepting multiple params within bash script using $@", "I am wanting to run ansible-playbook from a bash script, where some parameters passed to the script will passed to Ansible in the form of --extra-vars.\n\nEXTRA_VARS=\"--extra-vars '${@:2}'\"\nansible-playbook \\\n-i hosts_$1 \\\n$EXTRA_VARS \\\nplaybook.yml\n\n\nI've put the command over multiple lines because in my script there are several long options passed to ansible and I want to improve readability. If the user does not supply any variables beyond $1, then I just want to execute the playbook.\n\nHowever, when I run something like:\n\n./myscript inventory VAR1=KEY1 VAR2=KEY2\n\n\nI get an error:\n\nERROR! the playbook: VAR2=KEY2' could not be found.\n\n\nAm I not quoting EXTRA-VARS correctly when I set it? Or is bash doing something funny when it expands the variable?" ]
[ "bash" ]
[ "Access the new ember router in the console", "Is there an equivalent function to grab the currentPath in the console with the new router in ember? \n\nBefore, I was able to do this:\n\nApp.router.get(\"currentPath\")\n\n\nHowever, it seems with the new router, you can't access the router in the same fashion. In fact App.router simply returns undefined.\n\nAny help here would be greatly appreciated.\n\nedit: \n\nOn a related note, because I can no longer access App.router and its properties, I can't figure out how to manually trigger state changes. For example, \n\nApp.router.transitionTo(\"some.state\")\n\n\nis no longer viable. What is everyone doing instead of this now?" ]
[ "ember.js" ]
[ "Nicescroll jquery scrollend function not working. Getting as undefined. Using beat version jquery only", "$(document).ready(function() {\n // var nice = $(\"html\").niceScroll(); // The document page (body)\n var scroll_var = $(\".panel\").niceScroll({ \n cursorborder:\"\",\n cursorcolor:\"#00F\",\n boxzoom:true\n });\n\n scroll_var.scrollend(function(){\n\n });\n\n});\n\n\nGetting scrollend is undefined." ]
[ "jquery", "nicescroll" ]
[ "How do I convert mysql query to django model's ORM?", "This is my mysql query.\n\nSELECT DeviceUID, Max(LogTime) , count(DeviceUID), Mode\n FROM P2PLog.ConnectResult_Table group by DeviceUID;\n\n\nHow do I convert this code to ORM?\n\nI try to this orm. I need to select Max(LogTime) as column. How do I do? \n\n>>> ct = ConnectresultTable.objects\n>>> aaa = ct.values('deviceuid', 'mode').annotate(items=Count('deviceuid'))\n>>> print aaa.query\nSELECT `ConnectResult_Table`.`DeviceUID`, `ConnectResult_Table`.`Mode`, COUNT(`C\nonnectResult_Table`.`DeviceUID`) AS `items` FROM `ConnectResult_Table` GROUP BY\n`ConnectResult_Table`.`DeviceUID`, `ConnectResult_Table`.`Mode` ORDER BY NULL" ]
[ "python", "mysql", "django", "python-2.7", "orm" ]
[ "SKBitmap.Decode is returning NULL for some image files", "Can somebody help here.\nI am using SkiaSharp 1.68.3 version in .Net Core 3.1 framework.\nMy requirement is to read the image file (raw file having >3 MB of size with various types like bmp, jpeg, jpg, tiff, png, gift etc) and need to resize with white background color etc and upload into blob storage.\nThe problem is when I use SKBitmap.Decode( ) method by passing the stream object of the image file, I am getting NULL occasionally. Here is the code, I am using and I don't understand where am I doing any mistake.\n try\n {\n if (stream == null)\n {\n return (null, ImageErrorType.ImageFormatError, "Invalid Stream");\n }\n stream.Seek(0, SeekOrigin.Begin); \n var data = new BinaryReader(stream).ReadBytes((int)stream.Length);\n var imgInfo = SKBitmap.DecodeBounds(data); \n if (imgInfo.IsEmpty)\n {\n return (null, ImageErrorType.ImageFormatError, "Invalid Stream");\n }\n var bmp = SKBitmap.Decode(data, imgInfo);\n return (bmp, ImageErrorType.NoError, string.Empty);\n }\n catch (Exception ex)\n {\n return (null, ImageErrorType.UnknownError, ex.Message);\n }\n finally\n {\n stream?.Seek(0, SeekOrigin.Begin);\n }\n\n\nHere are the two images which is working and not working.\nNot Working Image\nWorking Image" ]
[ "decode", "skiasharp" ]
[ "How to install tensorflow-gpu on ubuntu with amd radeon r4/r5 graphics card", "Here is the output from tensorflow import:\n\nFile \"/home/shashi/libs/anaconda3/lib/python3.5/imp.py\", line 343, in load_dynamic return _load(spec) \nImportError: libcuda.so.1: cannot open shared object file: No such file or directory." ]
[ "tensorflow", "ubuntu-16.04", "amd" ]
[ "Finding the neighbors of all map coordinates", "I need help optimizing my code. Here is the dastardly function in question.\n\ndef FindAllNeighborCoords(cardinal_neighbor_array, principle_neighbor_array, width, height):\n\n # Loop through every coordinate on the map.\n for x in xrange(width):\n for y in xrange(height):\n\n # These if checks make sure the coordinate is in the map.\n if x - 1 >= 0:\n cardinal_neighbor_array[x, y].add((x - 1, y))\n principle_neighbor_array[x, y].add((x - 1, y))\n\n if y - 1 >= 0:\n cardinal_neighbor_array[x, y].add((x, y - 1))\n principle_neighbor_array[x, y].add((x, y - 1))\n\n if y + 1 < height:\n cardinal_neighbor_array[x, y].add((x, y + 1))\n principle_neighbor_array[x, y].add((x, y + 1))\n\n if x + 1 < width:\n cardinal_neighbor_array[x, y].add((x + 1, y))\n principle_neighbor_array[x, y].add((x + 1, y))\n\n if x - 1 >= 0 and y - 1 >= 0:\n principle_neighbor_array[x, y].add((x - 1, y - 1))\n\n if x - 1 >= 0 and y + 1 < height:\n principle_neighbor_array[x, y].add((x - 1, y + 1))\n\n if x + 1 < width and y - 1 >= 0:\n principle_neighbor_array[x, y].add((x + 1, y - 1))\n\n if x + 1 < width and y + 1 < height:\n principle_neighbor_array[x, y].add((x + 1, y + 1))\n\nprint cardinal_neighbor_array[20, 20]\nset([20, 21), (21, 20), (19, 20), (20, 19)])\n\n\nThis function loops through everyone coordinate on the map, finds that neighbors surrounding neighbor coordinates and saves them to a set. It searches for two neighbor types - cardinal and principal. Or, 4 and 8. Each set is placed in a 2D array. I can then grab the neighbors of a coordinate by doing something like cardinal_array[0, 0] which will return a set of coordinates. I hope that makes sense! I use neighbors a TON in my project so it's faster to find and store them all once rather than repeatedly look them up. Enormous parts of my engine use these neighbor sets so I'd rather speed up how it currently works than making any major changes. The sets are comprised of tuples containing the (x, y) coordinates of each neighbor. The tuple thing can be changed if you have a better solution. This function is called once during map generation and its the slowest by far." ]
[ "python", "performance", "numpy", "set" ]
[ "image overwritten if I set a margin", "Using this html code:\n\n<div class=\"container-fluid\" >\n <div class=\"row\">\n <div class=\"col-md-3\" >\n <table id=\"Table\" width=\"100%\">\n <tr>\n <td align=\"left\" valign=\"middle\" >\n <img src=\"MyImage\" width=\"220\" height=\"200\">\n </td>\n </tr>\n\n\n\n <tr>\n <td width=\"251\" height=\"400\" align=\"left\" valign=\"top\" >\n\n <p style=\"margin-top: 20px; margin-bottom: 0px;\">\n <img src=\"MyImage2\" width=\"220\" height=\"200\">\n </p> \n </td>\n </tr>\n </table> \n </div>\n\n <div class=\"col-md-9 \" >\n\n <form id=\"form1\" class=\"form-horizontal\" runat=\"server\" >\n <div \" align=\"left\" >\n Some other HTML stuff\n </div>\n </form>\n </div>\n\n </div>\n </div>\n\n\nIt works fine, however, I need to add a left margin of 50px before MyImage2.\nSo I update my code this way.\n\n<div class=\"container-fluid\" >\n <div class=\"row\">\n <div class=\"col-md-3\" >\n <table id=\"Table\" width=\"100%\">\n <tr>\n <td align=\"left\" valign=\"middle\" >\n <img src=\"MyImage\" width=\"220\" height=\"200\">\n </td>\n </tr>\n\n\n\n <tr>\n <td width=\"251\" height=\"400\" align=\"left\" valign=\"top\" style=\"margin-left: 50px;\">\n<!-----------------50 px margin added------------->\n <p style=\"margin-top: 20px; margin-bottom: 0px;margin-left: 50px;\">\n <img src=\"MyImage2\" width=\"220\" height=\"200\">\n </p> \n </td>\n </tr>\n </table> \n </div>\n\n <div class=\"col-md-9 \" >\n\n <form id=\"form1\" class=\"form-horizontal\" runat=\"server\" >\n <div \" align=\"left\" >\n Some other HTML stuff\n </div>\n </form>\n </div>\n\n </div>\n </div>\n\n\nWith this code I have a responsivity issue.\nIf I reduce the window size, the \"other HTML stuff\" displayed on the right frame overwrites the image2 of 50 pixels.\n\nHow can I have the right frame not to overwrite the right part of my image2?\n\nI tried to increase the width of the td and / or table tage, it did not work for me. So hopefully someone can help me there.\n\nEDIT:\nyou can check the issue on this link:\nhttp://www.bootply.com/t1hF1cHuD2\nreduce the window to have right frame to overwrite the left frame (which is what I want not to happen)" ]
[ "html", "css" ]
[ "Action delegate created during for loop not respecting the \"for variable\" value when used as parameter in the delegated method", "Noob here, apologies if I'm not using terminology correctly...\nEach code block below starts with a list of letters { "a", "c" } and creates an action delegate to later insert "b" prior to "c".\nI find that when I use the "for variable", i, for the index parameter of List.Insert(), the value passed is not respected when I call the action delegate later on. But if I capture i in a new int and pass that when creating the action delegate, then the value is respected. Further, if I inspect the variables i and index on the iteration where the action delegate is created, they both hold the same value: 1.\nI would expect that both code blocks would return "abc", but obviously they don't.\nWhy is the behavior is different between the two sets of code?\nThis code outputs "acb":\n public void Test()\n {\n List<string> letters = new List<string>() { "a", "c" };\n List<Action> actions = new List<Action>();\n for (int i = 0; i < letters.Count; i++)\n {\n string letter = letters[i];\n if (letter == "c")\n {\n actions.Add(new Action(() => letters.Insert(i, "b")));\n }\n }\n\n for (int i = actions.Count - 1; i > -1; i--)\n actions[i]();\n\n foreach (var letter in letters)\n Debug.Write(letter);\n }\n\nThis code outputs "abc":\n public void Test()\n {\n List<string> letters = new List<string>() { "a", "c" };\n List<Action> actions = new List<Action>();\n for (int i = 0; i < letters.Count; i++)\n {\n string letter = letters[i];\n if (letter == "c")\n {\n int index = i; // Using "index" instead of i when creating the action\n actions.Add(new Action(() => letters.Insert(index, "b")));\n }\n }\n\n for (int i = actions.Count - 1; i > -1; i--)\n actions[i]();\n\n foreach (var letter in letters)\n Debug.Write(letter);\n }" ]
[ "c#", "loops", "delegates" ]
[ "Upload Download from mysql php", "I've made use of a script which is available online. The File upload.php allows the user to upload a file and then store the selected file in the MySQL database. \n Later the download.php script displays the links for all the files stored in the database. When the user clicks the link, the file should be downloaded. I've enclosed the script below.\n But the problem is, I am not using any upload.php nor download .php.\n I have tried this in wordpress using \"php code for post (Only shortcode placed ion the page)\" at one shot.\n\n<?php \nif(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)\n\n{\n\n$fileName = $_FILES['userfile']['name'];\n\n$tmpName = $_FILES['userfile']['tmp_name'];\n\n$fileSize = $_FILES['userfile']['size'];\n\n$fileType = $_FILES['userfile']['type'];\n\n$fileType = (get_magic_quotes_gpc() == 0 ? mysql_real_escape_string(\n$_FILES['userfile']['type']) :\nmysql_real_escape_string(stripslashes($_FILES['userfile'])));\n\n$fp = fopen($tmpName, 'r');\n\n$content = fread($fp, filesize($tmpName));\n\n$content = addslashes($content);\n\nfclose($fp);\n\nif(!get_magic_quotes_gpc())\n\n{\n\n$fileName = addslashes($fileName);\n\n}\n\nmysql_connect(\"localhost\",\"*****\",\"***\");\n\nmysql_select_db(\"****\");\n\n$query = \"INSERT INTO wp3_cte (FileupName, size, type, content ) \".\n\n\"VALUES ('$fileName', '$fileSize', '$fileType', '$content')\";\n\nmysql_query($query) or die('Error, query failed');\n\necho \"File $fileName uploaded\";\n\n}\n\n?>\n<form method=\"post\" enctype=\"multipart/form-data\">\n<table width=\"350\" border=\"0\" cellspacing=\"1\" cellpadding=\"1\">\n<tbody>\n<tr>\n<td width=\"246\">\n<input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"2000000\" />\n\n<input id=\"userfile\" type=\"file\" name=\"userfile\" /></td>\n<td width=\"80\"><input id=\"upload\" type=\"submit\" name=\"upload\" value=\" Upload \" /></td>\n</tr>\n</tbody>\n</table>\n</form>\n<html>\n<head>\n <title>Download File From MySQL Database</title>\n <meta http-equiv=\"Content-Type\" content=\"text/html; \n charset=iso-8859-1\">\n</head>\n<body>\n\n\n<?php\nmysql_connect(\"localhost\",\"**********\",\"**********\");\nmysql_select_db(\"**********\");\n$query = \"SELECT id, FileupName FROM wp3_cte\";\n$result = mysql_query($query) or die('Error, query failed');\nif (mysql_num_rows($result) == 0) {\necho \"Database is empty <br>\";\n } else {\n while (list($id, $name) = mysql_fetch_array($result)) {\n ?>\n<a href=\"download.php?id=<?php echo urlencode($id); ?>\"\n ><?php echo urlencode($name); ?></a> <br>\n <?php\n}\n}\nmysql_close();\n?>\n</body>\n</html>\n<?php\nif (isset($_GET['id'])) {\nmysql_connect(\"localhost\",\"**********\",\"**********\");\nmysql_select_db(\"**********\");\n$id = $_GET['id'];\n$query = \"SELECT FileupName, type, size, content\"FROM wp3_cte WHERE id = '$id'\";\n $result = mysql_query($query) or die('Error, query failed');\n list($name, $type, $size, $content) = mysql_fetch_array($result);\nheader(\"Content-length: $size\");\nheader(\"Content-type: $type\");\nheader(\"Content-Disposition: attachment; filename=$name\");\nob_clean();\nflush();\necho $content;\nmysql_close();\nexit;\n }\n ?> \n\n\n The problem i am facing is in this peace of code:`download.php`.\n\n Uploaded file is showing properly if i click on download file blank page appears.\n\n Id is displayed in Url\n\n The uploaded file is saving in some folder named upload in ftp server i tried a lot but i was out with no result.\n can any one help me Thanks in advance!!!!" ]
[ "php", "mysql", "wordpress" ]
[ "Container Managed Transaction with JDO/DataNucleus", "Goodmorning all,\n\nI'm currently playing with Datanucleus/JDO. One thing that I like is the Type safe query system, and I want to use Datanucleus in future projects (I come from Hibernate background).\nI want to let the container (JBOSS 5) manage the transaction and I've defined a data source following the instructions from a datanucleus user (datanucleus forum thread), the only problem is that i cannot understand how to get a JDOPersistenceManager, all i get from a jndi lookup is the PersistenceManager, if I try a cast to JDOPersistenceManager i will get ClassCastException.\nI need the JDOPersistenceManager to get a typesafe query...\nMy configuration is the same as the one explained in the thread..\n\nDoes someone encountered the same problem before?\nAnd I wander also IF this thing would be possible at all...\n\nThank you for the replies!" ]
[ "jndi", "jdo", "datanucleus" ]
[ "Reference variables outside of function, in other classes", "I've written a program that essentially allows the user to make a profile, then later sign back in (after the code has been closed) and continue with their data saved to a text file. \n\nclass SignIn(tk.Frame):\ndef __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.configure(background=\"#FFC2B5\")\n\n #Exit\n tk.Button(self, text=\"EXIT\", command=EXIT, bg=\"#FFA795\") .grid(column=0, row=0, sticky=\"nesw\", pady=10, padx=10)\n\n #InputDetails\n input_details = tk.Label(self, text=\"Please input your first and last name to access your profile\")\n input_details.grid(column=0, row=1)\n\n #FIRSTNAME\n first_name_label = tk.Label(self, text=\"First Name:\")\n first_name_label.grid(column=0, row=2)\n\n first_name_entry = tk.Entry(self)\n first_name_entry.grid(column=1, row=2)\n\n #LASTNAME\n last_name_label = tk.Label(self, text=\"Last Name:\")\n last_name_label.grid(column=0, row=3)\n\n last_name_entry= tk.Entry(self)\n last_name_entry.grid(column=1, row=3)\n\n def SignInConfirm():\n for file in os.listdir(\"/Users/140032/Desktop/SDD Major Project/\"):\n filename = os.fsdecode(file)\n if filename.endswith(\".txt\"):\n completeName = os.path.join(\"/Users/140032/Desktop/SDD Major Project/\", file)\n with open(completeName,'r') as inf:\n dict_from_file = ast.literal_eval(inf.read())\n if dict_from_file['First_Name'] == first_name_entry.get() and dict_from_file['Last_Name'] == last_name_entry.get():\n print(\"Credentials Accepted. Welcome to 'The Mega Pop Quiz' \" + dict_from_file[\"First_Name\"] + \"!\")\n global PermFile\n PermFile = str(file)\n print(PermFile)\n else:\n continue\n continue\n else:\n continue\n\n controller.show_frame(\"SubjectsPage\")\n\n #CONFIRM\n confirm_button = tk.Button(self, text=\"SUBMIT\", command=SignInConfirm )\n confirm_button.grid(column=2, row=4)\n\n\nI'm having trouble with using the text file the user signs into in other parts of the code. Essentially, it iterates through every file, and when it finds a file that matches the input, it goes on with the program. PermFile is the file that the user signs into, and I can't find a way to reference the file later on outside of the function (in seperate classes). If I can get the name of the file the user logs into as a variable that can be used in other classes, I should be good to continue with the rest of the program." ]
[ "python-3.x", "oop" ]
[ "Base class don't have default constructor when derived class constructor initialization lists", "I just read Constructors and initialization of derived classes\nAnd I met a question. Code as followed.\nThe problem is when I comment the father default constructor. There will be a error.\nBut the default constructor shouldn't be create automatically by compiler?\nThank you for answer my question.\n\n#include <iostream>\nusing namespace std;\nclass Father{\npublic:\n int food;\n Father(){} // father default constructor \n Father(int f):food(f){\n }\n};\nclass Child: public Father{\npublic:\n int beverage;\n Child(int b):beverage(b){\n }\n}; \nint main(int argc, const char * argv[])\n{\n Child c(10);\n return 0;\n}" ]
[ "c++", "constructor", "derived-class", "initializer-list" ]
[ "Why does a button and a keypress with same function work different?", "I want to achieve the same result in a keypress event for \"enter\" for something that already works for me on a button and somehow the keypress always duplicates the information based on the number of times \"enter\" was already pressed.\nThe first time it shows the information correctly and the 2nd time doubled, the 3rd time 3 times, etc...\n\n$(document).on('keypress', '.dataa', function (event) {\n if (event.which === 13) {\n event.preventDefault();\n save_data();\n }\n});\n\n\nand this is the function that works correctly if used on a button:\n\nfunction save_data() {\n var final='';\n var datas='';\n var spans=$(\"body\").find('#'+pruebaa).attr(\"data\");\n $(\".dataa\").each(function() { \n if(!!$(this).val()){\n datas+=$(this).val()+\"-\";\n }\n });\n final=spans+datas;\n $(\".tabla\").remove();\n dlg.remove();\n $(\"body\").find('#'+pruebaa).attr(\"data\",final);\n}\n\n\nThe problem seems to be data's part since its the part that is doubled the 2nd time, tripled the 3rd, etc..." ]
[ "jquery", "jquery-ui", "keypress" ]
[ "Can you interact with the app in test using absolute positioning in Detox?", "I am trying to test a react native app on android which uses a native library which does oauth-based authentication using a webview. Detox does not support webviews (yet) so I was wondering if I could tap on the keyboard using coordinates in order to get through the auth (bad I know, but gets me unstuck for now)." ]
[ "detox" ]
[ "nodejs+moongose sort inner array by element timestamp", "I have the follwing schema: \n\n var VisionsystemSchema = new mongoose.Schema({\n linenumber: {\n type: String,\n index: true,\n unique: true\n },\n name: String,\n rois: [\n {\n name: String,\n history: [Date, Number]\n }\n ]\n});\n\n\nfor each element in rois array i have an array of history values with a [date,number] tuple. how can i order the history array by its Date first element?" ]
[ "node.js", "mongodb", "sorting", "mongoose" ]
[ "Resolving NodeJS CSS subpackages?", "I'm creating a CSS library and I'd like to support subpackages the same way RxJS does. For example with RxJS we can import the entire kitchen sink like this (Taken from https://www.npmjs.com/package/rxjs):\n\nvar Rx = require('rxjs/Rx'); \nRx.Observable.of(1,2,3); // etc\n\n\nOr individual operators like this:\n\nvar Observable = require('rxjs/Observable').Observable;\n// patch Observable with appropriate methods\nrequire('rxjs/add/observable/of');\nrequire('rxjs/add/operator/map');\n\n\nMy initial observation is that this may be as simple as just packaging the modules in subfolders of the root module. For example RxJS node_modules install folder has the subfolder rxjs/add/observable which contains all the observable extensions like zip.js, throw.js..., etc.\n\nSo following this pattern postcss-import could be extended to resolve imports in submodule folders the same way. For example:\n\n\n@import @superflycss/utilities-layout/margins\n\n\nWould import node_modules/superflycss/utilities-layout/margins.css and if that does not exist it would look for node_modules/superflycss/utilities-layout/margins/index.css, and if that does not it exist it would thrown an error.\n\n\n@import @superflycss/utilities-layout/margins/\n\n\nWould import node_modules/superflycss/utilities-layout/margins/index.css only.\n\nThe modules I'm producing have have the kitchen sink packaged in the directory target/main/css/index.css. This exposes all the css utilities or components (Depending on what type of module it is).\n\nThe problem is, as with RxJS, this can be a very heavy file (For instance contain imports to all Google Fonts). \n\nSo I'm hoping that by following the RxJS approach the entire thing becomes more flexible and standardized by following the same rules that NodeJS require.resolv() algorithm uses. Thoughts?" ]
[ "javascript", "css", "node.js", "postcss", "postcss-import" ]
[ "Sidekiq + Rails 6.0.0 in API mode : WARN -- : attack prevented by Rack::Protection::AuthenticityToken", "I'm currently trying to setup a standalone rails 6.0.0 API fresh install (rails new xxx --api) + sidekiq (that includes Rack::Protection)\n\nAfter setting-up Rack::Cors, i get the following 403 error on any non-GET request : \n\n\n WARN -- : attack prevented by Rack::Protection::AuthenticityToken\n\n\nTo my understanding this is related to CSRF tokens, which don't make sense for a json API.\n\nHere is a copy of the request I'm doing :\n\n\n curl 'http://127.0.0.1:5100/searches' -H 'Accept: application/json,\n text/plain, /' -H 'Referer: http://localhost:8080/' -H 'Origin:\n http://localhost:8080' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel\n Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko)\n Chrome/76.0.3809.132 Safari/537.36' -H 'Sec-Fetch-Mode: cors' -H\n 'Content-Type: application/x-www-form-urlencoded' --data '{query:\n 'test'}' --compressed\n\n\nThe 2 possible solutions that I cannot solve : \n\n\ndisable rack-protection\nget a token in a controller (ActionController::API) to pass to the requests" ]
[ "ruby-on-rails", "sidekiq", "rack", "ruby-on-rails-6" ]
[ "JQuery: Start object as hidden in a way that allows .fadeIn() to work", "I have an object that I want to start as hidden. I have tried to use each one of these styles one at a time. I have them in a class, not as inline styles.\n\ndisplay:none;\n\n\nand\n\nopacity:0;filter:alpha(opacity=0);\n\n\nNow, these both worked obviously, the objects load hidden. The issue is that when I use these, the JQuery .fadeIn() function doesn't work. In fact, when I set the opacity to .5 (50), the fade in only fades in to .5 (50).\n\nSo what can I default the object to that will allow the .fadeIn() function to work?\n\nThanks!" ]
[ "jquery", "hide", "fadein" ]
[ "loop through data instead of indexing in R", "I am trying to convert my data into a html document using Rmarkdown, and I am currently relying on conversion to vectors and indexing to solve my problem.\nAlthough my sample data has 4 observations, my actual datasets has over 30 records, so indexing seems cumbersome and unnatural.\nIs there a better way to pull out each of these elements in sequence? Any suggestions would be great.\n --\ntitle: "Rmarkdown report"\noutput: html_document\n---\n \n \n```{r echo = FALSE}\nmydata <- data.frame(First = c("John", "Hui", "Jared"), Second = c("Smith", "Chang", "Jzu"), Sport = c("Football","Soccer","Ballet"), Age = c("12", "13", "12"), submission = c("Microbes may be the friends of future colonists living off the land on the moon, Mars or elsewhere in the solar system and aiming to establish self-sufficient homes. Space colonists, like people on Earth, will need what are known as rare earth elements, which are critical to modern technologies. These 17 elements, with daunting names like yttrium, lanthanum, neodymium and gadolinium, are sparsely distributed in the Earths crust. Without the rare earths, we wouldn’t have certain lasers, metallic alloys and powerful magnets that are used in cellphones and electric cars. But mining them on Earth today is an arduous process. It requires crushing tons of ore and then extracting smidgens of these metals using chemicals that leave behind rivers of toxic waste water.",\n\n"Experiments conducted aboard the International Space Station show that a potentially cleaner, more efficient method could work on other worlds: let bacteria do the messy work of separating rare earth elements from rock. The idea is the biology is essentially catalyzing a reaction that would occur very slowly without the biology, said Charles S. Cockell, a professor of astrobiology at the University of Edinburgh.\nOn Earth, such biomining techniques are already used to produce 10 to 20 percent of the world’s copper and also at some gold mines; scientists have identified microbes that help leach rare earth elements out of rocks.",\n"Experiments conducted aboard the International Space Station show that a potentially cleaner, more efficient method could work on other worlds: let bacteria do the messy work of separating rare earth elements from rock. The idea is the biology is essentially catalyzing a reaction that would occur very slowly without the biology, said Charles S. Cockell, a professor of astrobiology at the University of Edinburgh.\nOn Earth, such biomining techniques are already used to produce 10 to 20 percent of the world’s copper and also at some gold mines; scientists have identified microbes that help leach rare earth elements out of rocks."))\n \n\n \nfirst<- as.vector(mydata$First)\nsec <- as.vector(mydata$Second)\nage <- as.vector(mydata$Age)\nsubmission <- as.vector(mydata$submission)\n\n```\n \n \n \n \n## \n\n**First:** `r first[1]`   **Second:** `r sec[1]` <br>\n**Age:** `r age[1]` \n\n\n**submission** <br>\n\n`r submission[1]`\n\n\n***\n\n**First:** `r first[2]`   **Second:** `r sec[2]` <br>\n**Age:** `r age[2]` \n\n\n**submission** <br>\n\n`r submission[2]`" ]
[ "r", "loops", "dplyr", "r-markdown", "lapply" ]
[ "How to return a readable string from an object", "I have a function that returns an object\n\nfunction a(){\n return {\n b:1,\n c:2\n }\n}\n\n\ndoing a().b will successfuly return 1, but I also want to return something else than [object Object] when calling a(). Something like this\n\nfunction a(){\n return {\n b:1,\n c:2\n toString: 'you got 2 values'\n }\n}\n\n\nwould render something like that\n\nalert(a()) // you got 2 values\n\n\nIs it possible?" ]
[ "javascript", "object" ]
[ "How can I lock only device administrators setting", "I am working on security application. User can't uninstall the application without applying a correct password. I am on device administrator permission in app. But when user try to install app then he/she can uninstall app by deactivating device administrator setting.\n\nI want when user activate device administrator setting then app set a password on device administrator. At the time of uninstalling it ask password then user show device administrator setting.\n\nCan it be possible? If yes then please suggest me how can I do, if not then please give me some idea how can I prevent user to uninstall app." ]
[ "android", "security", "device-admin" ]
[ "PHP fails to read textbox value", "I'm creating a basic website for class, On my login html page i have 2 textboxes Username and Password and a Login button. On submit i call the php file. It reads the txt_Username but doesn't read txt_Password. Do you have to read a password textbox differently?\n\nThanks in advance. \n\nHTML page code;\n\n</div>\n<div id=\"Content\">\n <form id=\"loginForm\" name=\"loginForm\" method=\"GET\" action=\"Login.php\">\n <table width=\"27%\" border=\"0\" align=\"center\">\n <tr>\n <td width=\"42%\">Username:</td>\n <td width=\"58%\"><input type=\"text\" name=\"txt_Username\" id=\"txt_Username\" /></td>\n </tr>\n <tr>\n <td width=\"42%\">Password:</td>\n <td width=\"58%\"><input type=\"password\" name=\"txt_Password\" id=\"txt_Password\" /> </td>\n </tr>\n <tr>\n <td> </td>\n <td> </td>\n </tr>\n <tr>\n <td> </td>\n <td><input type=\"submit\" name=\"btn_validate\" id=\"btn_validate\" value=\"Login\" /></td>\n </tr>\n <tr>\n\n </table>\n <p> </p>\n</form>\n</div> \n\n\nPHP code;\n\n<?php\n session_start();\n\n$server = \"host.com\";\n$schema = \"Seatter\";\n$uid = \"user\";\n$pwd = \"password\";\n\n $password =$_GET[\"txt_Password\"];\n $username =$_GET[\"txt_Username\"];\n\n\n mysql_connect($server , $uid , $pwd) or die (\"server not found\");\n mysql_select_db($schema) or die (\"Database not found\");\n\n $sql = \"SELECT *\n FROM Login_Details\n WHERE User_ID = '$username' AND Password = '$password'\";\n$record = mysql_query($sql) ;\n\n if(mysql_num_rows($record) == 0){\n\n echo \"Login Failure: \";\n //echo $username; //Username read from html page\n echo $password; //Password not read.\n //header(\"location: Login.html\"); \n }\n\nmysql_close();\n\n?>" ]
[ "php", "html" ]
[ "OpenCV Video Capture", "I am using OpenCV 2.4.8 and Visual Studio 2013 to run the following simple VideoCapture program. The program is intended to capture the video from the webcam and display it.\nHowever, the program works fine only for the FIRST TIME (after signing in windows), and doesn't work second time. \nThe problem I get on debugging is : \nAfter executing this line - \"bool bSuccess = cap.read(frame);\" frame variable is still NULL.\n\n#include \"stdafx.h\"\n#include \"opencv2/highgui/highgui.hpp\"\n#include <iostream>\n\nusing namespace cv;\nusing namespace std;\nchar key;\nint main(int argc, char* argv[])\n{\n VideoCapture cap(0); // open the video camera no. 0\n\n if(!cap.isOpened()) // if not success, exit program\n {\n cout << \"Cannot open the video file\" << endl;\n return -1;\n }\n\n double dWidth = cap.get(CV_CAP_PROP_FRAME_WIDTH); //get the width of frames of the video\n double dHeight = cap.get(CV_CAP_PROP_FRAME_HEIGHT); //get the height of frames of the video\n\n cout << \"Frame size : \" << dWidth << \" x \" << dHeight << endl;\n\n namedWindow(\"MyVideo\",CV_WINDOW_AUTOSIZE); //create a window called \"MyVideo\"\n Mat frame;\n while(1)\n {\n\n\n bool bSuccess = cap.read(frame); // read a new frame from video\n\n if (!bSuccess) //if not success, break loop\n {\n cout << \"Cannot read a frame from video file\" << endl;\n break;\n }\n\n imshow(\"MyVideo\", frame); //show the frame in \"MyVideo\" window\n\n if(waitKey(30) == 27) //wait for 'esc' key press for 30ms. If 'esc' key is pressed, break loop\n {\n cout << \"esc key is pressed by user\" << endl;\n break; \n }\n }\n return 0;\n\n}" ]
[ "c++", "opencv", "visual-studio-2013" ]
[ "Why does std::map::const_iterator call the std::pair constructor during a std::for_each, but a simple for loop does not?", "I have a slightly complex data member of a class, as noted in what follows:\n\nclass BranchOutputRow\n{\n...\n}\n\nclass Foo\n{\n\npublic:\n\n // Slightly complex data member here\n std::map<boost::multiprecision::cpp_int, std::set<BranchOutputRow>> hits;\n\n void DoLoop1()\n {\n // This loop calls the std::pair<> constructor\n\n std::for_each(hits.cbegin(), hits.cend(),\n [&](std::pair<boost::multiprecision::cpp_int,\n std::set<BranchOutputRow>> const & hit)\n {\n ...\n }\n }\n\n void DoLoop2()\n {\n // This loop does NOT call the std::pair<> constructor\n\n for (std::map<boost::multiprecision::cpp_int,\n std::set<BranchOutputRow>>::const_iterator hitsPtr \n = hits.cbegin();\n hitsPtr != hits.cend();\n ++hitsPtr)\n {\n ... \n }\n }\n\n}\n\nint main()\n{\n Foo foo;\n foo.hits[1] = std::set<BranchOutputRow>();\n foo.hits[1].insert(BranchOutputRow());\n\n foo.DoLoop1(); // direct access to map object is not available\n foo.DoLoop2(); // direct access to map object is available\n}\n\n\nAs noted, I find that Loop #1 calls the std::pair constructor, despite the fact that the lambda function accepts its argument by reference. Therefore, in Loop 1, I do not have direct access to the object in the map, but only a copy. In my actual program, I need direct access; therefore, I must use the version indicated by Loop 2.\n\n(In fact, Loop 2 does not call the std::pair constructor - not a surprise - and does provide direct access to the object in the map.)\n\nI would think that std::for_each would have been carefully designed to provide the same semantics as a for loop such as Loop 2, and therefore not call the std::pair constructor, instead allowing direct access to the object in the map.\n\nWhy does Loop 1 call the std::pair constructor, despite the fact that the lambda function accepts its argument by reference?" ]
[ "c++", "c++11", "map", "stl", "lambda" ]
[ "How do you cache results processed by a celery application", "I want to find out whether it is possible to cache results sent to a celery application. For example, suppose I have a basic celery application which looks like:\ntasks.py\nimport os\nfrom celery import Celery\nimport time\n\nredis_url = 'redis://localhost:6379'\napp = Celery('tasks', backend=redis_url, broker=redis_url)\n\[email protected]\ndef add(x, y):\n time.sleep(10) # Added to see whether caching occurs.\n return x + y\n\nIf I call the function add twice with the same arguments as in here:\nfrom tasks import add\n\nadd.delay(10, 10)\nadd.delay(10, 10)\n\nWill the second argument be computed faster? Possibly because the input output pair ((10, 10), 20) is already available in the result backend? If not, how do I achieve this behaviour?" ]
[ "python-3.x", "caching", "redis", "celery" ]
[ "Multiple rows to one comma-separated value in sql", "We want to display multiple column value into the single column with comma separated value\nbelow is the my table data \n\n\n\nBelow is the SQL query i am trying:\n\n select \n name,\n STUFF((SELECT '; ' + facilty FROM leads Name FOR XML PATH('')),1,2,'') \n as facilty,\n address\n from leads\n\n\nQuery Result\n\n\n\nNow when I execute the query in SQL Server, I want reuslt to be like:" ]
[ "sql", "sql-server" ]
[ "Google Apps Script - Impossible operation with an element inside a shared drive", "I need your help on something.\n\nI did a function which goal is to make a copy of a template file and put it in a folder in a shared drive. The problem is that the program returns :\n\n\n \"Exception: This operation cannot be performed on an item in a shared Drive\"\n\n\nYet, I have all the permissions in that shared drive so I don't understand.\n\nI did several tweaks and I've founded that removeFile and addFile are parts of the problem. If I don't run them, the folder is created and the copy is made. But I still need the file to be moved.\n\nI hope someone can help me with this.\n\nPS : You can fin my code below.\n\n\r\n\r\nfunction makeCopyFile(folderID, fileID, newName) {\r\n var getFolder = DriveApp.getFolderById(folderID);\r\n var file = DriveApp.getFileById(fileID);\r\n var copyFile = file.makeCopy();\r\n var newFile = copyFile.setName(newName);\r\n \r\n // Remove the file from all parent folders\r\n var parents = newFile.getParents();\r\n while (parents.hasNext()) {\r\n var parent = parents.next();\r\n parent.removeFile(newFile);\r\n }\r\n getFolder.addFile(newFile);\r\n};" ]
[ "google-apps-script", "google-drive-api", "google-drive-shared-drive" ]
[ "Searching XCode for strings starting with _", "I read: \nRegular Expression to match string starting with "stop"\n\nI want to search for all strings starting with a _ character using regex search in XCode (in case that matters) which I initially thought I would be able to search for with ^_ but that only returns me lines that start with _ they exclude lines with spaces.\n\nI would like my search to return all of the following:\n\n_foo\n _bar\n _baz\n\n\nfor example and exclude things like\n\nfoo_bar \n#_\n wholeWord_anotherWord\n\n\nor any other string that doesnt start with '_' followed by myString (ex _myString is a desired result). Basically I'm looking for all variables following the _ naming convention.\n\nI read: How to ignore whitespace in a regular expression subject string?\n\nI tried \"\\s*^_\" but that returned me only 'new line'_aString. Did I misunderstand the solution? What will give me the correct response of any _variable?" ]
[ "regex", "xcode" ]
[ "Deal with standard library types in scope of dependency injection", "Consider the following type:\n\nclass SomeType\n{\n public void Configure()\n {\n var windowsService = new ServiceController(\"msdtc\");\n windowsService.Start();\n }\n}\n\n\nThere are at least three issues.\n\n\nWe have implicit dependency to ServiceController.\nWe cannot to unit test Configure().\nWe have a new operator that breaks our DI strategy.\n\n\nSo to fix it we can extract another type and input it to our SomeType.\n\ninterface IWindowsService\n{\n void Start();\n}\n\nclass WindowsService : IWindowsService\n{\n private readonly ServiceController _serviceController;\n public WindowsService(string serviceName)\n {\n _serviceController = new ServiceController(serviceName));\n }\n\n public void Start() => _serviceController.Start();\n}\n\nclass SomeType\n{\n private readonly IWindowsService _msdtcService;\n public SomeType(Func<string, IWindowsService> createServiceCallback) //explicit dependency\n {\n _msdtcService = createServiceCallback.Invoke(\"msdtc\");\n }\n\n public void Configure() => _msdtcService.Start();\n}\n\n\nIt fixes the issues #1 and #2 but we still have a new operator in the new type WindowsService. I try to understand should I register standart ServiceController in the DI-container or use it directly as demonstrated above (by new)?\n\ncontainer.RegisterType<ServiceController>();\n\n\nAlso I am not sure whether we should try to test WindowsService or maybe it would be better to rewrite it something like this:\n\nclass WindowsService : ServiceController, IWindowsService\n{\n}\n\n\nSince WindowsService is now just inheriting we cannot test anything here. The type is already tested by Microsoft.\nHowever it breaks incapsulation and maybe ISP from SOLID. Because we can cast IWindowsService to WindowsService or even to ServiceController.\n\nWhat is the best way to deal with standart stable types?\nPlease refer me to another question if we have.\nThanks in advance." ]
[ "c#", ".net", "unit-testing", "dependency-injection" ]
[ "How should I update multiple RavenDB documents from a daily feed?", "I'm using RavenDB to hold several thousand documents. The data comes from a daily xml feed which I'll update by running a C# console app. Below is the code that processes the feed to keep the database in sync with any changes. I've had quite a few problems with this so I'm wondering if I've picked the wrong strategy. Here are some important things to note.\n\n\nNew items may have been added to the feed and existing items may\nhave changed, so each time it runs I want to either add or update a\ndocument depending on whether or not it's new.\nThe xml feed doesn't contain any reference to my RavenDB IDs, only its internal key for each item. So when retrieving an existing\ndocument to update I can only do that by examining the \"SourceID\"\nproperty on the document.\nI'm using \"take\" to only work with 500 docs at a time partly because my db is limited to 1000 docs, and partly because without\nTake() I seem to be only able to retrieve 128 docs.\nAs it stands, this code falls over with a \"can't do more than 30 updates in a session\" error, I think because each time I try to\nretrieve an existing record from dbItems it actually hits the\ndatabase again.\nI can fix the issue at (4) above by calling ToList() on items, but if I do that the existing item doesn't get updated when I call\nsession.SaveChanges() (I'm imagining this like a disconnected\nrecordset).\n\n\nCan anyone give me some pointers?\n\n public void ProcessFeed(string rawXml)\n {\n XDocument doc = XDocument.Parse(rawXml);\n var items = ExtractItemsFromFeed(doc).OrderBy(x => x.SourceId).Take(500);\n using (IDocumentSession session = _store.OpenSession())\n {\n var dbItems = session.Query<AccItem>().OrderBy(x => x.SourceId).Take(500);\n foreach (var item in items)\n {\n var existingRecord = dbItems.SingleOrDefault(x => x.SourceId == item.SourceId);\n if (existingRecord == null)\n {\n session.Store(item);\n _logger.Info(\"Saved new item {0}.\", item.ShortName);\n }\n else\n {\n // update just one field for now\n existingRecord.Village = item.Village;\n _logger.Info(\"Updated item {0}.\", item.ShortName);\n }\n }\n session.SaveChanges();\n } \n }" ]
[ "ravendb", "ravenhq" ]
[ "How do I link to OpenGL?", "I have installed VS 2008, and I have copied these libraries:\n\n\nopengl32.lib \nglu32.lib\nglut32.lib\n\n\ninto the library folder, and the corresponding header files into the include folder.\n\nI have also added these files in project properties->Linker->Input->Additional dependencies:\n\n\nOpengl32.lib\nglu32.lib\nglut32.lib\n\n\nDo i have to use quotes to add them? Like this: \"Opengl32.lib\" \"glu32.lib\" \"glut32.lib\"\n\nI created the following program, which just displays a window:\n\n#include<GL/glut.h>\n\nvoid display(void)\n{\n glClear(GL_COLOR_BUFFER_BIT);\n glLoadIdentity();\n glFlush();\n}\n\nvoid main(int argc,char **argv)\n{\n glutInit(&argc,argv);\n glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);\n glutInitWindowSize(500,500);\n glutCreateWindow(\"3D gasket\");\n glutDisplayFunc(display);\n glClearColor(1.0,1.0,1.0,1.0);\n glutMainLoop();\n}\n\n\nBut linking fails with the following output:\n\n1>------ Build started: Project: vs, Configuration: Debug Win32 ------\n1>Linking...\n1>pr1.obj : error LNK2019: unresolved external symbol _glFlush referenced in function \"void __cdecl display(void)\" (?display@@YAXXZ)\n1>pr1.obj : error LNK2019: unresolved external symbol _glLoadIdentity referenced in function \"void __cdecl display(void)\" (?display@@YAXXZ)\n1>pr1.obj : error LNK2019: unresolved external symbol _glClear referenced in function \"void __cdecl display(void)\" (?display@@YAXXZ)\n1>pr1.obj : error LNK2019: unresolved external symbol _glutMainLoop referenced in function _main\n1>pr1.obj : error LNK2019: unresolved external symbol _glClearColor referenced in function _main\n1>pr1.obj : error LNK2019: unresolved external symbol _glutDisplayFunc referenced in function _main\n1>pr1.obj : error LNK2019: unresolved external symbol _glutCreateWindow referenced in function _main\n1>pr1.obj : error LNK2019: unresolved external symbol _glutInitWindowSize referenced in function _main\n1>pr1.obj : error LNK2019: unresolved external symbol _glutInitDisplayMode referenced in function _main\n1>pr1.obj : error LNK2019: unresolved external symbol _glutInit referenced in function _main\n1>D:\\Program Files\\Microsoft Visual Studio 9.0\\projects\\vs\\Debug\\vs.exe : fatal error LNK1120: 10 unresolved externals\n1>Build log was saved at \"file://d:\\Program Files\\Microsoft Visual Studio 9.0\\projects\\vs\\vs\\Debug\\BuildLog.htm\"\n1>vs - 11 error(s), 0 warning(s)\n========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========\n\n\n\n\nI don't know what is causing these problems, can anyone explain these messages in detail? And how to resolve them?" ]
[ "c++", "c", "visual-studio-2008", "opengl" ]
[ "WCF Service - how to protect so only my clients can use it?", "I am building a client program that interacts with a WCF Service via Internet. Everything works as intended but I am wondering how I can protect my services so that only my client program can make use of it?\n\nRight now everyone with the correct URL to my services can use it with WCFTestClient (e.g).\n\nWhat is the best way to make it private so only my clients can make use of the service? Rotating token strings? Certificate? Password?\n\nI have no idea and haven't found anything useful on the Internet.\n\nBest regards\n\nUPDATE: The client program is intended to be downloaded for the public (everyone). So it is not for internal use, it will be a service we are gonna provide, ones in official production.\n\nMy own thinking was like: Bind a certificate in my client programs (if thats possible even?). On the IIS where the WCF service is running, check for valid certificate. Is that possible? Or better solutions out there?" ]
[ "c#", "wcf", "visual-studio" ]
[ "eigensolver in eigen Library", "I would like to translate [vec,val] = eig(A) from MATLAB to c++ using Eigen library, but I couldn't reach to the same result!\nI tried eigensolver,ComplexEigenSolver and SelfAdjointEigenSolver. None of them give me the result like eig(A) in MATLAB.\n\nSample matrices:\nTv(:,:,223) =\n\n 0.8648 -1.9658 -0.2785\n -1.9658 4.9142 0.8646\n -0.2785 0.8646 0.3447\n\n\nTv(:,:,224) =\n\n 1.9735 -0.4218 1.0790\n -0.4218 3.3012 0.1855\n 1.0790 0.1855 3.7751\n\n\nTv(:,:,225) =\n\n 2.4948 1.0185 1.1633\n 1.0185 1.1732 -0.4479\n 1.1633 -0.4479 4.3289\n\n\nTv(:,:,226) =\n\n 0.3321 0.0317 0.1617\n 0.0317 0.0020 -0.0139\n 0.1617 -0.0139 0.5834\n\n\nEigen:\n\nMatrixXcd vec(3 * n, 3);\nVectorXcd val(3);\nfor (int k = 0; k < n; k++){\n EigenSolver<Matrix3d> eig(Tv.block<3, 3>(3 * k, 0));\n vec.block<3, 3>(3 * k, 0) = eig.eigenvectors();\n cout <<endl << vec.block<3, 3>(3 * k, 0) << endl;\n val = eig.eigenvalues();\n cout << \"val= \" << endl << val << endl;\n\n }\n\n\n//results\n\n (0.369152,0) (-0.830627,0) (-0.416876,0)\n (-0.915125,0) (-0.403106,0) (-0.00717218,0)\n (-0.162088,0) (0.384142,0) (-0.908935,0)\nval=\n (5.86031,0)\n(0.0396418,0)\n (0.223765,0)\n\n (0.881678,0) (0.204005,0) (0.425472,0)\n (0.23084,0) (-0.97292,0) (-0.011858,0)\n(-0.411531,0) (-0.108671,0) (0.904894,0)\nval=\n(1.35945,0)\n(3.41031,0)\n(4.27996,0)\n\n (0.526896,0) (-0.726801,0) (0.440613,0)\n(-0.813164,0) (-0.581899,0) (0.0125466,0)\n(-0.247274,0) (0.364902,0) (0.897609,0)\nval=\n(0.377083,0)\n (2.72623,0)\n (4.89367,0)\n\n (0.88992,0) (-0.43968,0) (0.121341,0)\n (0.13406,0) (-0.00214387,0) (-0.990971,0)\n (-0.43597,0) (-0.898152,0) (-0.0570358,0)\nval=\n (0.257629,0)\n (0.662467,0)\n(-0.00267575,0)\n\n\nMATLAB:\n\nfor k=1:n\n [u,d] = eig(Tv(:,:,k))\nend\n\n\n%results\n\nu =\n\n 0.8306 -0.4169 -0.3692\n 0.4031 -0.0072 0.9151\n -0.3841 -0.9089 0.1621\n\n\nd =\n\n 0.0396 0 0\n 0 0.2238 0\n 0 0 5.8603\n\n\nu =\n\n 0.8817 0.2040 0.4255\n 0.2308 -0.9729 -0.0119\n -0.4115 -0.1087 0.9049\n\n\nd =\n\n 1.3594 0 0\n 0 3.4103 0\n 0 0 4.2800\n\n\nu =\n\n -0.5269 0.7268 0.4406\n 0.8132 0.5819 0.0125\n 0.2473 -0.3649 0.8976\n\n\nd =\n\n 0.3771 0 0\n 0 2.7262 0\n 0 0 4.8937\n\n\nu =\n\n -0.1213 -0.8899 0.4397\n 0.9910 -0.1341 0.0021\n 0.0570 0.4360 0.8982\n\n\nd =\n\n -0.0027 0 0\n 0 0.2576 0\n 0 0 0.6625\n\n\nWhat's your suggestion?" ]
[ "c++", "matlab", "eigen" ]
[ "How to stop CORB from blocking requests to data resources that respond with CORS headers?", "I am developing a Chrome extension which makes requests from certain websites to an API I control. Until Chrome 73, the extension worked correctly. After upgrading to Chrome 73, I started getting the following error:\n\n\n Cross-Origin Read Blocking (CORB) blocked cross origin response\n http://localhost:3000/api/users/1 with MIME type application/json\n\n\nAccording to Chrome's documentation on CORB, CORB will block the response of a request if all of the following are true:\n\n\nThe resource is a \"data resource\". Specifically, the content type is HTML, XML, JSON\nThe server responds with an X-Content-Type-Options: nosniff header, or if this header is omitted, Chrome detects the content type is one of HTML, XML, or JSON from inspecting the file\nCORS does not explicitly allow access to the resource\n\n\nAlso, according to \"Lessons from Spectre and Meltdown\" (Google I/O 2018), it seems like it may be important to add mode: cors to fetch invocations, i.e., fetch(url, { mode: 'cors' }). \n\nTo try to fix this, I made the following changes:\n\nFirst, I added the following headers to all responses from my API:\n\nAccess-Control-Allow-Credentials: true\nAccess-Control-Allow-Headers: Content-Type\nAccess-Control-Allow-Methods: GET, POST\nAccess-Control-Allow-Origin: https://www.example.com\n\n\nSecond, I updated my fetch() invocation on the extension to look like this:\n\nfetch(url, { credentials: 'include', mode: 'cors' })\n\n\nHowever, these changes didn't work. What can I change to make my request not be blocked by CORB?" ]
[ "google-chrome", "google-chrome-extension", "cors", "cross-origin-read-blocking" ]
[ "SonarQube WebServer process spikes CPU after a while", "We're running SonarQube 5.1.2 on an AWS node. After a short period of use, typically a day or two, the Sonar web server becomes unresponsive and spikes the server's CPUs:\n\ntop - 01:59:47 up 2 days, 3:43, 1 user, load average: 1.89, 1.76, 1.11\nTasks: 93 total, 1 running, 92 sleeping, 0 stopped, 0 zombie\nCpu(s): 94.5%us, 0.0%sy, 0.0%ni, 5.5%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st\nMem: 7514056k total, 2828772k used, 4685284k free, 155372k buffers\nSwap: 0k total, 0k used, 0k free, 872440k cached\n\n PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND \n 2328 root 20 0 3260m 1.1g 19m S 188.3 15.5 62:51.79 java \n 11 root 20 0 0 0 0 S 0.3 0.0 0:07.90 events/0 \n 2284 root 20 0 3426m 407m 19m S 0.3 5.5 9:51.04 java \n 1 root 20 0 19356 1536 1224 S 0.0 0.0 0:00.23 init \n\n\nThe 188% CPU load is coming from the WebServer process:\n\n$ ps -eF|grep \"root *2328\"\nroot 2328 2262 2 834562 1162384 0 Mar01 ? 01:06:24 /usr/java/jre1.8.0_25/bin/java -Djava.awt.headless=true -Dfile.encoding=UTF-8 -Djruby.management.enabled=false -Djruby.compile.invokedynamic=false -Xmx768m -XX:MaxPermSize=160m -XX:+HeapDumpOnOutOfMemoryError -Djava.io.tmpdir=/opt/sonar/temp -cp ./lib/common/*:./lib/server/*:/opt/sonar/lib/jdbc/mysql/mysql-connector-java-5.1.34.jar org.sonar.server.app.WebServer /tmp/sq-process615754070383971531properties\n\n\nWe initially thought that we were running on way too small of a node and recently upgraded to an m3-large instance, but we're seeing the same problem (except now it's spiking 2 CPUs instead of one).\n\nThe only interesting info in the log is this:\n\n2016.03.04 01:52:38 WARN web[o.e.transport] [sonar-1456875684135] Received response for a request that has timed out, sent [39974ms] ago, timed out [25635ms] ago, action [cluster:monitor/nodes/info], node [[#transport#-1][xxxxxxxx-build02-us-west-2b][inet[/127.0.0.1:9001]]], id [43817]\n2016.03.04 01:53:19 INFO web[o.e.client.transport] [sonar-1456875684135] failed to get node info for [#transport#-1][xxxxxxxx-build02-us-west-2b][inet[/127.0.0.1:9001]], disconnecting...\norg.elasticsearch.transport.ReceiveTimeoutTransportException: [][inet[/127.0.0.1:9001]][cluster:monitor/nodes/info] request_id [43817] timed out after [14339ms]\n at org.elasticsearch.transport.TransportService$TimeoutHandler.run(TransportService.java:366) ~[elasticsearch-1.4.4.jar:na]\n at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_25]\n at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_25]\n at java.lang.Thread.run(Unknown Source) [na:1.8.0_25]\n\n\nDoes anyone know what might be going on here or has some ideas how to further diagnose this problem?" ]
[ "sonarqube", "sonarqube-ops" ]
[ "Is this a bug or normal: Money - SqlDataReader vs OleDbDataReader", "We recently received complaints that amounts started to show with 4 decimals in the end, like 1.2300 instead of 1.23, with Sql Server DB. Our app is not perfect - by day's end it simply calls \n\nConvert.ToString(reader(\"field\"))\n\n\nBut before we used OleDb provider directly, and few years back we started to use abstract provider that behind scenes uses SqlClient or ODP.NET based on connection settings.\n\nHere is what happening when calling Convert.ToString(reader(\"field\"))\n\nOleDB\n\n\n DB field is Decimal - reader data type is decimal and return is 1.0000\n DB field is Money - reader data type is decimal and return is 1.00 <--\n\n\nSqlClient\n\n\n DB field is Decimal - reader data type is decimal and return is 1.0000 \n DB field is Money - reader data type is decimal and return is 1.0000 <--\n\n\nThe application is >10yo and the whole thing, as far as I can tell, was invested into fact that field Money returns 0.00 and field Decimal returns whatever precision. \n\nBut I am wondering if that is some kind of unintentional behavior? Unless I find genius solution, fixing this globally in rather large code base may take some remarkable effort." ]
[ "c#", ".net", "vb.net", "ado.net" ]
[ "generating mock data from openApi specs", "I've got an openApi spec file in a swagger editor that I am trying to generate test data from. The spec file is a pretty big size so it would be ideal if I didn't have to generate the data manually if possible. I'm currently using node in my application." ]
[ "node.js", "json", "yaml", "swagger", "openapi" ]
[ "Javascript, check array and nodes surrounding", "Ello Chaps and Chapesses!\n\nI have a Javascript array like this:\n\nvar tinkerArray = [\n [0,0,0],\n [0,1,0],\n [0,0,0]\n];\n\n\nMy question is, how can I check the array nodes surrounding each node... \n\ne.g. starting at [0,0], check [0,1] and [1,0] etc etc\n\nThanks!\n\nedit: if possible I would like a scalable solution whereby if the array was 7x7 - the algorithm would still work... :/" ]
[ "javascript", "arrays" ]
[ "Why we don't add try catch when using New operation", ",In C# and C++ , no one uses exception handling for new operator ,what's the reason ?\nIs it guaranteed that the call will always be successful ?" ]
[ "c#", "exception-handling" ]
[ "DRM - how to protect license URL on mobile app", "I see a lot of info regarding DRM itself on internet, but did no find info on how to protect license URL itself. To play DRM on e.g. exoplayer on mobile I need DASH url and license URL, but if one can manage to get those from the code then he can play video anywhere anytime. How do I protect those?" ]
[ "mobile", "exoplayer", "drm" ]
[ "Get-ADUser filter out specific OU, custom column", "trying to get an Audit report of active users. We have an OU that I do not want to report on.\n\nGive me all the active (enabled) AD accounts. EXCEPT in a specific OU.\n\nGet-ADUser -Filter{enabled -eq $true} | Select-object Samaccountname,surname,givenname `\n | Export-Csv -NoTypeInformation C:\\scripts\\ActiveUsers.csv\n\n\nHow can I filter out OU=Service Accounts?\n\nI also need to have a custom column in Column A of the csv output.\nExample: The word \"ACME\" in column A in all rows.\n\nThanks much\nEsther" ]
[ "powershell", "csv", "ou" ]
[ "Downsides of using Makefile rules for deployment?", "I have an open-source project where I'm using Make for things like tests and static checks. The deployment process is approximately this:\n\nmake html\nrsync static_pages my_domain.com:static_pages\nssh my_domain.com \"cp -r static_pages /var/www/webroot\"\n\n\nIs there a reason not to have this deployment process publicly in the Makefile? Does Make have gotchas that make it unsuitable for deployment? Is there a security issue revealing server names or directory structure? Or something else that I haven't though of?" ]
[ "deployment", "makefile" ]
[ "Does Firebase do Geospatial?", "I would like to retrofit Firebase to an existing app. The existing app uses CouchDB and GeoCouch to ensure that the client only retrieves data that is 'near' the user.\n\nDoes/will Firebase support this type of feature or is this something I will need to do myself?" ]
[ "firebase" ]
[ "IEDriverServer on local HTML pages ends with NoSuchWindowException: Unable to get browser", "I'm using 32-bit IE11 on Win8.1.\nI have some Selenium scripts (Python bindings) which I execute on IE11 among others.\n\nWith IEDriverServer, I've done all the steps suggested on the InternetExplorerDriver-wiki page and in general the IEDriver works fine. \n\nHowever, if I try to get a local HTML page, such as:\n\nfrom selenium import webdriver\nie = webdriver.Ie()\nurl = \"file:///D:/dev/proof_of_concept/html/liki.html\"\nie.get(url)\nprint(ie.current_url)\n\n\nI get this exception in return:\n\nTraceback (most recent call last):\nFile \"<stdin>\", line 1, in <module>\nFile \"C:\\Python34\\lib\\site-packages\\selenium\\webdriver\\remote\\webdriver.py\", line 426, in current_url\nreturn self.execute(Command.GET_CURRENT_URL)['value']\nFile \"C:\\Python34\\lib\\site-packages\\selenium\\webdriver\\remote\\webdriver.py\", line 173, in execute\nself.error_handler.check_response(response)\nFile \"C:\\Python34\\lib\\site-packages\\selenium\\webdriver\\remote\\errorhandler.py\", line 166, in check_response\nraise exception_class(message, screen, stacktrace)\nselenium.common.exceptions.NoSuchWindowException: Message: 'Unable to get browser'\n\n\nThere are many threads about the general IE11 issue (with the registry solution) but I weren't able to find any solution for this particular issue with local pages.\n\nIs there some kind of limitation, or something related to the security zones, that I'm not aware of?\n\nThanks!" ]
[ "selenium", "internet-explorer-11", "python-3.4" ]
[ "Why is my java query causing an error but is fine in Workbench?", "Hello I am trying to run this query in my program.\n\nString query = \"SELECT * FROM wcrm_Company WHERE CompanyName LIKE \"+\"%\"+search+\"%\"+\" OR PersonName LIKE \"+\"%\"+search+\"%\"+\" OR Country LIKE \"+\"%\"+search+\"%\";\nSystem.out.println(query);\n\n\nHowever I get this output and error (LUX is the search term)\n\nSELECT * FROM wcrm_Company WHERE CompanyName LIKE %LUX% OR PersonName LIKE %LUX% OR Country LIKE %LUX%\nInternal error - an SQL exception occurred\nSQLException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%LUX% OR PersonName LIKE %LUX% OR Country LIKE %LUX%' at line 1\n\n\nHowever this query works fine in MySQL Workbench\n\nSELECT * FROM wcrm_Company WHERE CompanyName LIKE \"%LUX%\" OR PersonName LIKE \"%LUX%\" OR Country LIKE \"%LUX%\";" ]
[ "mysql" ]
[ "Enlarge android app launch icon", "I used the launcher icon generator link below to create my own launcher icon: \n\nhttps://romannurik.github.io/AndroidAssetStudio/\n\nThen I download the zip package. Unzip it into the right directory and overwrite all the drawable-*/ic_launcher.png correctly with my launcher images.\n\nThe problem is that the launcher icon is small compared to other icons on my phone. Look at the image on the far right below: \n\n\n\nHow do I enlarge it's dimensions in android studio ?" ]
[ "android", "android-studio", "android-icons" ]
[ "connect to ftp server using jdbc ftp driver", "I am looking for an example in Java to connect to ftp server and retrieve data from CSV file." ]
[ "java", "jdbc", "ftp" ]
[ "Scala type class dictionaries?", "In this paper, they give an example of a Scala class:\n\n\n\nclass S[A](l : String, formatD: Format[A]) extends Format[A] {\n def format(s : String) = formatD.format(s+l)\n}\n\n\nand say:\n\n\n\n\n An important difference is that,\n with type classes, we cannot implement a corresponding\n instance for the S[A] model.\n The problem is that, to define S, a String argument is required but\n type class instances can only take type class dictionaries in the\n instance constraints.\n Thus, the following is not allowed:\n\ninstance (String, Format a) ⇒ Format a where ...\n\n\n\nWhat are they referring to when they say \"type class dictionaries\"?" ]
[ "scala" ]
[ "Orchard CMS how to access a modules controller that returns a ContentResult", "I'm new to Orchard CMS and how to extend it. I can't find a descriptive answer on how to call an action from a controller that's located in a module? The action returns a ContentResult with the type being plain text. I want to access it in an jQuery AJAX call. I'm a novice at Orchard CMS. Thanks for any help!" ]
[ "jquery", "ajax", "module", "controller", "orchardcms" ]
[ "Assign float * or int * to mxArray", "I got a typical cpp function in matlab using mex\n\n#include \"mex.h\"\n\nvoid func (int * rowvec, int * colvec, float * valvec, int * nnz){/*fill arguments*/}\n\n\n\nvoid mexFunction(int nlhs, mxArray *plhs[],\n int nrhs, const mxArray *prhs[])\n\n\nwhere I check that in I have enough output variables available\n\nif(nlhs != 4) {\n mexErrMsgIdAndTxt(\"MyToolbox:arrayProduct:nlhs\",\n \"Four outputs required.\");\n}\n\n\nFurthermore, in this function I declare four variables:\n\nint *rowvec; /* 1st output array */\nint *colvec; /* 2nd output array */\nfloat *valvec; /* 3rd output array */\nint *nnz; /* 4th output scalar */\n\n\nThey will be defined/filled in a function:\n\nfunc(rowvec, colvec, valvec, nnz) //arguments get filled with values\n\n\nNow I want to do something like that:\n\nplhs[0] = rowvec;\nplhs[1] = colvec;\nplhs[2] = valvec;\nplhs[3] = nnz;\n\n\nIt unfortunately throws four understandable errors, because those are two different data types. The errors are like this:\n\ncannot convert ‘int*’ to ‘mxArray* {aka mxArray_tag*}’ in assignment plhs[0] = rowvec;\n\n\nHow can I fix this?" ]
[ "c++", "matlab", "mex" ]
[ "std::string operator+() memory leak?", "I'm quite worry because I wrote a little application and it seems that there is a memory leak if I believe valgrind (What I actually do):\n\n==9321== 251 bytes in 7 blocks are definitely lost in loss record 1 of 1\n==9321== at 0x402569A: operator new(unsigned int) (vg_replace_malloc.c:255)\n==9321== by 0x40D3D05: std::string::_Rep::_S_create(unsigned int, unsigned int, std::allocator<char> const&) (in /usr/lib/libstdc++.so.6.0.13)\n==9321== by 0x40D4977: std::string::_Rep::_M_clone(std::allocator<char> const&, unsigned int) (in /usr/lib/libstdc++.so.6.0.13)\n==9321== by 0x40D57AC: std::string::reserve(unsigned int) (in /usr/lib/libstdc++.so.6.0.13)\n==9321== by 0x40D5EE6: std::string::operator+=(char) (in /usr/lib/libstdc++.so.6.0.13)\n==9321== by 0x804E113: xl2::TextParser::getNextLfLine() (TextParser.cpp:162)\n==9321== by 0x804BFD5: xl2::UsbTree::parseStringInfo(xl2::TextParser&, std::string&, std::string&) (UsbTree.cpp:362)\n==9321== by 0x804B881: xl2::UsbTree::parseDevicesFile(std::string) (UsbTree.cpp:204)\n==9321== by 0x804B34E: xl2::UsbTree::updateTree() (UsbTree.cpp:70)\n==9321== by 0x804E2E4: scan(std::string) (testUsbTree.cpp:75)\n==9321== by 0x804E6CC: executeCommand(std::string) (testUsbTree.cpp:132)\n==9321== by 0x804E8F6: hushLoop() (testUsbTree.cpp:153)\n\n\nHere is the function in question :\n\n/**\n * Returns the next line separated by UNIX style LF\n * @return The next line separated by UNIX style LF\n */\nstd::string TextParser::getNextLfLine()\n{\n std::string line; // The builded line\n\n while(this->hasMoreToken())\n {\n line += this->m_pText[this->m_iTokenLocation++];\n\n // Check if we have just seen a CR/LF character\n if(this->m_pText[this->m_iTokenLocation - 1] == '\\n')\n return line;\n }\n\n return line;\n}\n\n\nThe programm terminates correctly by leaving the main funciton (no call to exit()).\n\nI just don't understand why there is a memory leak. As my string is copied in the stack and the original string is supposed to be cleaned when the function is left, right? Or the error could be higher? At top level I also assign the returned value to a local variable that is then put as field into an object (by copy) ... \n\nSo I was wondering if the leak comes from the standard library or valgrind what would be really surprising!\n\nAny pointers to not leaked memory is strongly appreciated :-p!" ]
[ "c++", "string", "stl", "memory-leaks", "valgrind" ]
[ "Node.js Asynchronous Function *Definition*", "Please, just to clear something up in my head...\n\nI am used to writing using asynchronous functions in libraries, but how do I write my own?\n\nTo illustrate my question I have made up a module called 'MadMathz'\n\nI am aware that the following is an example usage of an asynchronous function :\n\n//load module\nvar mM = require('./MadMathz');\n\n//perform a function\nmM.async_function_addthree(12, function(result) {\n console.log(result)\n});\n\n//do something straight afterwards\nconsole.log('Logging this straight after instead of waiting for computation');\n\n\nI'm aware that the second argument to the function is the callback, but how is a function such as 'async_function_addthree' defined? Let's say for the purpose of this example that async_function_addthree just adds 3 to the first argument.\n\nI just confused myself so much trying to write what I thought it might be. Am I totally on the wrong track? I feel like I am close to getting there with node.js but this needs clearing up.\n\nPlease explain rather than linking me somewhere if possible. I'm sure others will benefit from this question." ]
[ "javascript", "node.js", "asynchronous" ]
[ "How to get the access token in a service in .net core?", "I have an application and I want to use a hybrid flow to call an API from my MVC web application. The API is secured and requires an access token (JWT). The code part on the API side is done.\nBut how can I send my access token from my MVC application to the API in a service? I want to use a \"generic\" service for this that uses an httpclient.\n\nI know that in controllers you can use\n\nvar accessToken = await HttpContext.GetTokenAsync(\"access_token\"); \n\n\nor\n\nvar accessToken = await HttpContext.GetUserAccessTokenAsync();\n\n\nBut how can I access the access token in a service? \nTried this too, but didn't work\n\n var accessToken = _httpContextAccessor.HttpContext.Request.Headers[HeaderNames.Authorization];\n\n\nSide question: how can I set the access token for the httpclient in the constructor of my service? (Using async methods is not possible) so I can't use this:\n\nprotected HttpClient HttpClient { get; private set; }\n\npublic MyGenericHttpClientService(IHttpContextAccessor httpContextAccessor)\n\n{\n var accessToken = await httpContextAccessor.HttpContext.GetTokenAsync(\"access_token\");\n HttpClient.SetBearerToken(accessToken);\n}" ]
[ "asp.net-core", "httpcontext" ]
[ "Android: open Map intent with directions with two points", "How to open map intent with directions?\n\nI know about \n\nIntent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.format(Locale.US, \"geo:%.8f,%.8f\", latitude, longitude)));\nstartActivity(Intent.createChooser(intent, \"Select an application\"));\n\n\nThis code works fine for ONE point. But I want to show dialog with ALL map-applications, and open directions from point A to point B with any application (Google Map, Citymapper, web browser, etc)." ]
[ "android", "google-maps" ]
[ "C# methods with multiple return parameters", "Is there a need for multiple return parameters in c#/.net?\n\npublic string, string GetFirstNameAndLastName(int id)\n{\n var person = from p in People\n where p.Id = id\n select p;\n return(p.FirstName, p.LastName);\n}\n\n\nUsage:\n\npublic void Main(string[] args)\n{\n string firstName, lastName;\n (firstName, lastName) = GetFirstNameAndLastName(1);\n\n Console.WriteLine(firstName + \", \" + lastName);\n}" ]
[ "c#", ".net", "language-design" ]
[ "ZF2: Rendering HTML-Tags in navigation menu (turning off HTML-escaper)", "The problem:\n\nIf you want to place HTML markup within your Zend Framework 2 navigation, e.g. like this:\n\n<?php\n'navigation' => array(\n default' => array(\n array(\n 'label' => '<i class=\"fa fa-home\"></i>Home',\n 'route' => 'home',\n ),\n...\n\n\nand we want to display it with the view helper\n\n\n<?php echo $this->navigation('navigation')->menu())?>\n\n\n...ZF will automatically escape all HTML markup. The result will be: \n\n<i class=\"fa fa-home\"></i>Home (No HTML markup was rendered.)\n\n\nSo how can we render HTML markup in menu labels?" ]
[ "php", "zend-framework2" ]
[ "how do i get the value of an array encoded using http_build_query()", "i have an array\n\nArray\n\n(\n [User] => Array\n (\n [id] => 11-11-111\n [branch_id] => \n [last_name] => Doe\n [first_name] => Jhon\n [middle_name] => Mcdonald\n )\n\n [UserOrder] => Array\n (\n [0] => Array\n (\n [id] => 0-01-66168-21 \n [user_id] => 11-11-111\n [date_requested] => 2011-11-16\n [time_requested] => 15:39:08\n )\n\n [1] => Array\n (\n [id] => 0-03-65692-13\n [patient_id] => 11-11-111\n [date_requested] => 2011-11-07\n [time_requested] => 06:48:08\n )\n\n [2] => Array\n (\n [id] => 0-08-56323-24\n [patient_id] => 11-11-111\n [date_requested] => 2011-11-07\n [time_requested] => 07:09:28\n )\n\n )\n\n)\n\n\ni have used http_build_query() for this to be accepted in CURLOPT_POSTFIELDS\n\nIs there a way i can revert it back to its array form? if not, how can i get the value of each array using $_POST?\n\nAny suggestion will be very much appreciated!, thank you in advance! cheers!" ]
[ "php" ]
[ "Would like to specify local file path for WSDL to generate REST APIs from it using Publisher", "I have a WSDL with relative paths for the \".xsd\" schema files on my local machine. I am trying to generate REST APIs from this WSDL using Publisher. I am using the \"file://\" URL pattern to specify the path but am having challenges. I have folder names with spaces between them (e.g., \"My WSDL Folder\"). I would appreciate it if I could be shown an example as to how to go about specifying this. Thanks!\n\nNote: I am using WSO2-AM 2.6.0 and have updated it using WUM as late as midnight of Oct 7, 2019." ]
[ "rest", "soap", "wsdl", "wso2-am" ]
[ "Is it possible to run a java compiled programe through javascript?", "I am developing a local app through a website with javascript. The input for this app is the output of a java command-line program that the user already executed. Is there any way of executing the compiled program through javascript, so that the user only needs to see the web interface? \n\nIn other words, is there anyway of executing a command-line java programm via javascript?" ]
[ "javascript", "java" ]
[ "Java repaint() is not working in jPanel class", "I want to repaint my jPanel everytime I call the method called change(). In this method I'm just changing my boolean variable draw and I call this.repaint(). To paint on panel works but if I click the button the line is still there but the line should be gone. After I call repaint() I can't reach the paintComponent() method. Why is the method repaint() not working properly?\n\nHere is my code from the panel class:\n\nimport java.awt.Graphics;\n\npublic class testPanel extends javax.swing.JPanel {\n\n public boolean draw = true;\n\n public testPanel() {\n initComponents();\n }\n\n @SuppressWarnings(\"unchecked\")\n // <editor-fold defaultstate=\"collapsed\" desc=\"Generated Code\"> \n private void initComponents() {\n\n javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);\n this.setLayout(layout);\n layout.setHorizontalGroup(\n layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGap(0, 603, Short.MAX_VALUE)\n );\n layout.setVerticalGroup(\n layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGap(0, 299, Short.MAX_VALUE)\n );\n }// </editor-fold> \n\n @Override\n protected void paintComponent(Graphics g) {\n super.paintComponent(g);\n if (draw == true) {\n g.drawLine(0, 0, 20, 35);\n }\n }\n\n public void change() {\n draw = !draw;\n this.repaint();\n\n }\n\n}\n\n\nEdit, this is how I access the method change():\n\nprivate void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { \n\n testPanel testPanel = new testPanel();\n testPanel.change();\n\n} \n\n\nEdit, how I add the jPanel to my jFrame:\n\nprivate void initComponents() {\n\n jPanel1 = new testPanel();\n jButton1 = new javax.swing.JButton();\n..." ]
[ "java", "swing", "graphics", "jpanel", "repaint" ]
[ "Can't make font-awesome menu icon to be equivilant with neighboring menu links", "The first link in my site's horizontal main menu is a home-icon taken from font-awsome. This icon + it's neighboring text, both appear higher\\taller than the rest of the links in that menu.\n\nI've tried to play with the Display\\Vertical-align\\Margin\\min-height of the elements of both of them and nothing helped...\n\nThe problem could be seen directly when you enter my site, in any page. Here is a link to my site's homepage.\n\nThe font-icon css is:\n\n.fa-home::before {\n content: \"\";}\n\n\nThe main-menu links css is:\n\n#superfish-1 .sf-depth-1 a {\n color: #779573;\n font-size: 13.5px;\n text-align: right;}\n\n\nAdditional details:\n\nThis is a Drupal 7, RTL site.\n\n\n\nPlease help in making the font-awesome icon link homogenous in position\\tallness to all other, Thanks," ]
[ "css", "font-awesome", "drupal-theming" ]
[ "Recommended way to add a new page to html5 boilerplate project for repeated content", "How should I add a new page to a HTML5 Boilerplate project?\n\nThe problem is that if I copy a base page, if I change the menu or the layout, then I have to change all the pages containing that layout.\n\nI don't want to use server side includes because I want to host the website on IIS or Apache.\n\nOr I should use HTML5 Boilerplate for SPA only?" ]
[ "html", "html5boilerplate" ]
[ "Ionic native Transfer plugin's `file.dataDirectory` shows error", "I'm going to use the Ionic native Transfer plugin as shown below.\nProblem is here this.file.dataDirectory.It shows error like [ts] Property 'dataDirectory' does not exist on type 'File'..Can you tell me what is the solution for this?\n\ndownload() {\n const fileTransfer: TransferObject = this.transfer.create();\n const url = 'http://www.example.com/file.pdf';\n fileTransfer.download(url, this.file.dataDirectory + 'file.pdf').then((entry) => {\n console.log('download complete: ' + entry.toURL());\n }, (error) => {\n // handle error\n });\n }" ]
[ "ionic-framework", "ionic2", "ionic3", "ionic-native" ]
[ "unable to return 0 when no data found in inner query of pivot table, used coalesce as well... but no luck", "Added Actual sample table,along with sample result .... \n\nSELECT 'RESULT' AS Ratio, coalesce([colData1],0) data1, \n coalesce([colData2],0) data2, coalesce([colData4],0) data4, \n coalesce([colData7],0) data7 \nFROM (SELECT columnName1,columnName2 FROM table \nwhere columnName3 = 'ABC' and columnName4='def' and columnName5='fgh' ) AS \n SREC PIVOT ( sum(columnName2) FOR columnName1 IN ([colData1],colData2 \n, colData4 ,colData7 ) ) AS PVT \n\n\nSample Table:\nSample Table\nTable\nResult:\nSample Result for above query\n\n--###################################################\n\nNow If I my change my query:\n\nSELECT 'RESULT' AS Ratio, coalesce([colData1],0) data1,\ncoalesce([colData2],0) data2,\ncoalesce([colData4],0) data4,\ncoalesce([colData7],0) data7\n FROM (SELECT columnName1,columnName2 \n FROM table where columnName3 = 'DEF' and columnName4='def' and columnName5='fgh'\n ) AS SREC\n PIVOT \n (\n sum(columnName2) \n FOR columnName1 IN ([colData1],colData2 ,colData4 ,colData7 )\n ) AS PVT\n\n\nThen it should display: all pivot column data as 0 ...\n\nAs I've 29 unique data values for columnName1, I'm just trying to use pivot table instead individual case statements." ]
[ "sql", "sql-server", "tsql", "pivot", "pivot-table" ]
[ "Hierarchy level in UINavigationController in iPhone", "Is it possible to decide the number of hierarchical level dynamically in UINavigationController in iPhone ? Actually, in my application I have to display hierarchical data but I don't know the number of levels at the coding time. The number of levels can be increase or decrease. The exact number of levels will known to me at the time of display. Please suggest the related code if possible.\n\nWith regards,\n\nanurag85" ]
[ "iphone", "objective-c", "uinavigationcontroller", "hierarchy", "hierarchical-data" ]
[ "Python variable value adding a double quotes", "input_file.txt has below\n\n'123','345','567'|001\n'1234','3456','5678'|0011\n\n\nbelow is the code I am using to assign the values from input_file.txt to v_order_nbr_lst, which is working fine , but when I am using that variable inside a POST message API call like below , it is adding double quotes.\n\nread the input file\n\nfileHandle = open(input_file.txt,'r')\n\nfor line in fileHandle.readlines()[0:]:\n line = line.rstrip('\\n')\n fields = line.split('|')\n v_order_nbr_lst = (fields[0])\n\n\nvariable used below\n\npostdata = {\n \"parameters\": [\n {\n \"Order_Nbr\": [v_order_nbr_lst]\n }\n ]\n }\n\n\nNow I am getting values with double quotes like this , i tried to replace & rstrip but not able to get rid of \".\n\npostdata = {\n \"parameters\": [\n {\n \"Order_Nbr\": [\"'123','345','567'\"]\n }\n ]\n }\n\n\nexpected result\n\npostdata = {\n \"parameters\": [\n {\n \"Order_Nbr\": ['123','345','567']\n }\n ]\n }" ]
[ "python" ]
[ "JavaScript: Try/Catch vs error function passed as a parameter", "I am wondering which approach is better for error handling and debugging in JavaScript for nodeJS?\n\nHaving a pure try/catch block:\n\ntry\n{\n dangerous.function();\n\n}\ncatch(error);\n{\n console.log(error);\n}\n\n\nor \n\nJust using a function as a parameter, which will display if any errors occur\n\ndangerous.function(function(error)\n{\n console.log(error);\n});\n\n\nI am raising this question because I read that try/throw has a potential of logging too much stack trace data as written here: http://nodejs.org/api/domain.html#domain_warning_don_t_ignore_errors" ]
[ "javascript", "node.js", "error-handling", "try-catch", "conceptual" ]
[ "Canvas - Fill a shape created with multiple paths", "What I want to do\n\nI would like to draw a custom shape (for example a simple rectangle) which has different colors for each edge. I can do it with four paths, it works like a charm. BUT, in this way, it seems I can not fill the shape.\n\nTrying the other way, I can draw the shape with one path and fill it, BUT in this case, I can not use different colors for the edges, because the last fillStyle will override the previous ones, even if I stroke the subpaths individually.\n\nIs it possible to mix the two, by coloring subpaths individually, or by filling a shape consisting multiple paths?" ]
[ "javascript", "canvas", "turtle-graphics" ]
[ "How to get all followers from ListFollowers() method of TweetSharp Library using wpf?", "I am developing a demo application using TweetSharp Library and wpf and i want all followers of my users.\n\nI'm using ListFollowers() method of TweetSharp library but it gives only 20 followers.\n\nHelp please.\n\nThanks in advance." ]
[ "wpf", "api", "twitter", "tweetsharp" ]
[ "Retrieving a range of data from Firestore", "How can I retrieve a range of data such as 20 to 40 rows from Firestore?\ni am tryin this\nconnect().collection("users").orderBy("email").startAt(20).limit(20)\n .get()\n .then((querySnapshot) => {\n console.log(querySnapshot.docs.length);\n }\n }\n\n })\n .catch((error) => {\n console.log("Error getting documents: ", error);\n });" ]
[ "javascript", "firebase", "google-cloud-firestore" ]
[ "MongoDB Comparing Dates Inconsistently Working", "I have a chunk of code in mongoDB / javascript that is sometimes working, but other times not. When I go to compare dates, this code works:\n\n let year = new Date().getFullYear();\n User.aggregate([ \n { $match: { emplyID: Number(req.params.emplyID) } },\n { $match: { \"dateReq\": { $gte: new Date(year, 0, 1), $lt: new Date(year+1, 0, 1) } } }\n ], function (err, pto) {\nconsole.log(pto.length)\n }\n\n\nConsole log results = 2\n\nHowever, this does not work:\n\nlet year = new Date().getFullYear();\n User.aggregate([ \n { $match: { emplyID: Number(req.params.emplyID) } },\n { $match: { \"dateReq\": { $gte: new Date(year - 1, 0, 1), $lt: \nnew Date(year, 0, 1) } } }\n ], function (err, pto) {\nconsole.log(pto.length)\n }\n\n\nThe console log is always equal to 0. \n\nIn the current DB, these objects exist:\n\nDateReq : 3/9/19,\nDateReq : 3/8/19,\nDateReq : 10/20/18,\nDateReq: 11/15/18\n\nThe first function is supposed to count the number of entries that exist between 2018 and 2019, and does it correctly, finding two items. The second function is supposed to count the number of entries that exist between 2017 and 2018, but even though the data exists, it can not be found. Any ideas what might be going wrong here?" ]
[ "javascript", "mongodb" ]
[ "Letsencrypt timeout when fetching test file on http-01 challenge", "I had to pause my dev for a few months. My Letsencrypt certificate expired in the meantime and there some changes in the libs.\nI deleted my Letsencrypt directory (the one whith the certificates inside).\nI am using greenlock-express API\nNow,I cannot manage to pass the http-01 challenge when obtaining the certificate.\nI have no problem to curl the file :\n http://myserver.com/.well-known/acme-challenge/hRsScb0ZHcFyaroe73h2lnFcQfCTeDwFhVB8PtKHfYs\n\nBut I get errors when running my app :\nERROR in le-sni-auto:\nError: The CA was unable to validate the file you provisioned.\n\nFetching http://myserver.com/.well-known/acme-challenge/hRsScb0ZHcFyaroe73h2lnFcQfCTeDwFhVB8PtKHfYs: Timeout\n\nI cannot firgure out whet is happenning...\nAny idea ?\n\nEdit 170912 - Configuration details\n\nvar lex = require('greenlock-express').create({\nserver: 'staging'\n,challenges: {'http-01': require('le-challenge-fs').create({ webrootPath: './letsencrypt/tmp' })}\n,store: require('le-store-certbot').create({\nconfigDir: './letsencrypt'\n ,privkeyPath: ':configDir/live/:hostname/privkey.pem'\n ,fullchainPath: ':configDir/live/:hostname/fullchain.pem'\n ,certPath: ':configDir/live/:hostname/cert.pem'\n ,chainPath: ':configDir/live/:hostname/chain.pem'\n ,webrootPath: ':configDir/tmp'\n ,debug: false\n })\n,approveDomains: approveDomains\n});\n\nfunction approveDomains(opts, certs, cb) {\nif (certs) {\n opts.domains = certs.altnames;\n}\nelse {\n opts.email = '[email protected]';\n opts.agreeTos = true;\n opts.domains = [ 'myserver.com'];\n}\n\ncb(null, { options: opts, certs: certs });\n}\n\nhttp.createServer(lex.middleware(require('redirect-https')())).listen(80, _ => {\nconsole.log(\"Listening for ACME http-01 challenges on\", this.address());\n});\n\nhttps.createServer(lex.httpsOptions, lex.middleware(app)).listen(443, function () {\nconsole.log(\"Listening for ACME tls-sni-01 challenges and serve app on\", this.address());\n});" ]
[ "timeout", "certificate", "lets-encrypt", "greenlock" ]
[ "Check for valid email before running remaining javascript", "I have a textbox where the user is required to insert a valid email address.\n\nWhen the user submits a valid email address a loading graphic appears while the data is posted back.\n\nThe code below works fine for showing the loading graphic but it does not check that the email address is valid first. Can anyone help out?\n\n$('#btnEmail1Submit').live (\"click\", function() {\n $('<div class=\"submitBg\"></div>').appendTo(\".emailEditContainer\");\n $('<div class=\"submitLoadingCont\"><img class=\"submitLoading\" src=\"images/mypreferences/loading.gif\" width=\"50\" height=\"50\" /></div>').appendTo(\".emailEditContainer\");\n});\n\n\nI am thinking that I need to put an if statement around the function that is run on click - so something like:\n\n$('#btnEmail1Submit').live (\"click\", function() {\n if(emailvalid == true) { \n $('<div class=\"submitBg\"></div>').appendTo(\".emailEditContainer\");\n $('<div class=\"submitLoadingCont\"><img class=\"submitLoading\" src=\"images/mypreferences/loading.gif\" width=\"50\" height=\"50\" /></div>').appendTo(\".emailEditContainer\");\n }\n});\n\n\nI am using asp.net email validation - it looks something like this:\n\n<asp:RegularExpressionValidator Display=\"Dynamic\" ValidationGroup=\"PrimarySubmit\" ID=\"RegularExpressionValidator1\" runat=\"server\" ValidationExpression=\"\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*\" ControlToValidate=\"tbEmail1\" ErrorMessage=\"Invalid email address - \" />" ]
[ "javascript", "jquery", "validation", "email-validation" ]
[ "How do I read static files in a PIG UDF", "I am new to PIG and Hadoop. I have written a PIG UDF which operates on String and returns a string. I actually use a class from an already existing jar which contains the business logic in the udf. The class constructor takes 2 filenames as input which it uses for building some dictionary used for processing the input. How to get it working in mapreduce mode I tried passing the filenames in pig local mode it works fine. But I dont know how to make it work in mapreduce mode? Can distributed cache solve the problem?\n\nHere is my code\n\nREGISTER tokenParser.jar\n\nREGISTER sampleudf.jar;\n\n\nDEFINE TOKENPARSER com.yahoo.sample.ParseToken('conf/input1.txt','conf/input2.xml');\n\nA = LOAD './inputHOP.txt' USING PigStorage() AS (tok:chararray);\nB = FOREACH A GENERATE TOKENPARSER(tok);\nSTORE B into 'newTokout' USING PigStorage();\n\n\nFrom what I understand is tokenParser.jar must be using some sort of BufferedInputReader. Is it possible to make it work without changing tokenParser.jar" ]
[ "hadoop", "apache-pig" ]
[ "Invalid workflow syntax", "I have a workflow that closes an issue whenever the text \"#close\" is present on comment. Any idea why text.contains() is displayed as an error.\n\nwhen comments.added.isNotEmpty { \n if (!issue.isResolved()) { \n var myComment = comments.added.first; \n\n var commentText = myComment.text; \n\n if (myComment.text.contains(\"#close\", true) { \n issue.State = {Fixed}; \n } \n } \n}" ]
[ "workflow", "youtrack" ]
[ "encryption code not working in android 4.2 onwards", "I was using the below code in my app for encrypting and decrypting passwords. It was working fine until I upgraded my OS from 4.1 to 4.3. Not sure why is it failing now. I am passing the passwords encrypted earlier(in 4.1) on to the decryption code below.\n\nmy decrypt code below\n\nString keyword = \"keyword\";\n int iterationCount = 1000; \n int keyLength = 256;\n String[] fields = encryptedPassword.split(\"]\");\n byte[] salt = fromBase64(fields[0]);\n byte[] cipherBytes = fromBase64(fields[1]);\n KeySpec keySpec = new PBEKeySpec(keyword.toCharArray(), salt, iterationCount, keyLength);\n SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(\"PBEWITHSHA256AND256BITAES-CBC-BC\");\n SecretKey key = keyFactory.generateSecret(keySpec);\n Cipher cipher = Cipher.getInstance(\"AES/CBC/PKCS5Padding\");\n PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, iterationCount);\n cipher.init(Cipher.DECRYPT_MODE, key, pbeSpec);\n byte[] plainBytes = cipher.doFinal(cipherBytes);\n plainStr = new String(plainBytes, \"UTF-8\").trim();\n return plainStr;\n\n\nthe exception is as follows\n\njavax.crypto.BadPaddingException: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt" ]
[ "android", "encryption" ]
[ "Trigger function when date is selected with jQuery UI datepicker", "How can I trigger onSelect event when I select a selected date on jQuery UI datepicker?" ]
[ "jquery", "events", "datepicker" ]
[ "Laravel and Passport, random 401 errors", "I'm writing a single page web application.\n\nI'm using Vue.js in the frontend and Laravel in the backend.\n\nI included Passport token authentication and I'm getting the auth token sending \n\nvar login_data = {\n client_id : 2,\n client_secret : \"SECRET_KEY\",\n grant_type : \"password\",\n username : \"mail\",\n password : \"pass\"\n}\n\n\nTo this Passport endpoint http://IPADDRESS/oauth/token. Then I authenticate my AJAX requests including this header\n\n{ 'Authorization': 'Bearer ' + ACC_TOKEN }\n\n\nMost of the time everything works fine but sometimes I get 401 unauthorized. Usually, if I simply do it again the request goes through. \n\nI removed the VerifyCsrfToken middleware from Kernel.php and also added the API route to the exceptions so I don't think that's the problem.\n\nThe frequency the error appears seems to change from network to network, meaning when connected to certain networks it almost never happens while sometimes it's constant.\n\nI honestly have no idea why this happens." ]
[ "php", "laravel", "authentication", "laravel-passport" ]
[ "Unable to read json file with pyspark in Databricks", "I'm using pyspark to create a dataframe from a JSON file.\n\nThe structure of the JSON file is as follows:\n\n[\n {\n \"Volcano Name\": \"Abu\",\n \"Country\": \"Japan\",\n \"Region\": \"Honshu-Japan\",\n \"Location\": {\n \"type\": \"Point\",\n \"coordinates\": [\n 131.6,\n 34.5\n ]\n },\n \"Elevation\": 571,\n \"Type\": \"Shield volcano\",\n \"Status\": \"Holocene\",\n \"Last Known Eruption\": \"Unknown\",\n \"id\": \"4cb67ab0-ba1a-0e8a-8dfc-d48472fd5766\"\n },\n {\n \"Volcano Name\": \"Acamarachi\",\n \"Country\": \"Chile\",\n \"Region\": \"Chile-N\",\n \"Location\": {\n \"type\": \"Point\",\n \"coordinates\": [\n -67.62,\n -23.3\n}]\n\n\nI will read in the file using the following line of code:\n\nmyjson = spark.read.json(\"/FileStore/tables/sample.json\")\n\n\nHowever, I keep on getting the following error message:\n\n\n Spark Jobs\n myjson:pyspark.sql.dataframe.DataFrame\n _corrupt_record:string\n\n\nCan someone let me know what I might doing wrong?\n\nIs the problem with the structure of the json file?" ]
[ "pyspark", "azure-databricks" ]
[ "Drupal 8 WYSIWYG data programatically insertion make display plain html", "I am working with some migration of content from one website to another. I am doing this using a cron.\n\nWhen I try to insert data to the WYSIWYG fields the data is inserted and showing in the WYSIWYG editor, but when I check this data in the front-end, the data seems to be pure HTML. Does anybody know what type of formatting I have to apply for proper insertion of data?" ]
[ "drupal", "drupal-8" ]
[ "Emulate Android in Swing", "I want to be able to run my Android code/app on Windows/Mac/Linux/etc. but not use an emulator, as they are slow/cumbersome.\n\nI want a real Java SE app, but to reuse my Android code.\nMy idea is to make an Android emulator using Swing, read the layout files and create the widgets in Swing and map between the 2 UI event models, life cycle, and library classes.\n\nQuestion is, does such a thing exist already, I googled it, but could not find anything.\n\nOtherwise I will start an open source project for it myself. Anyone interested in helping is more than welcome." ]
[ "java", "android", "swing", "android-emulator" ]
[ "Getting results from dispatchEvent in Flex 3", "I have the following custom event: \n\npackage com.un.photoManager.events\n{\nimport flash.events.Event;\n\nimport mx.collections.ArrayCollection;\n\n\npublic class CreateAlbumFolderEvent extends Event\n{\n // when creating an album, we need to know which albumfolder to put it in, 0 is the default group;\n public var albumFolderID:int = 0;\n public var name:String;\n\n public function CreateAlbumFolderEvent(type:String, name:String, albumFolderID:int = 0, cancelable:Boolean = false)\n {\n super(type, true, cancelable);\n this.name = name;\n this.albumFolderID = albumFolderID;\n\n }\n\n}\n}\n\n\nThe event gets called from a popup using the following code: \n\nprotected function handleCreate():void\n {\n var event:CreateAlbumFolderEvent;\n var selectedItemType:String;\n\n if (folderAlbum == CREATE_ALBUM)\n {\n event = new CreateAlbumFolderEvent(EventConstants.CREATE_ALBUM, newAlbumFolder.text, selectedAlbumFolderID);\n selectedItemType = \"Album\";\n }\n else\n {\n event = new CreateAlbumFolderEvent(EventConstants.CREATE_ALBUM_FOLDER, newAlbumFolder.text);\n selectedItemType = \"Folder\";\n }\n dispatchEvent(event);\n FolderBrowse.lastSelectedItemType = selectedItemType;\n PopUpManager.removePopUp(this);\n }\n\n\nWhat I am trying to do is to capture the response that is handed back. Here is a screenshot of Charles showing the response. The Result value is what I am looking to be able to use once the dispatchEvent(event); has executed.\n\nScreenshot from Charles\n\nI have been working on this for several hours looking at blog & forum posts and have not been able to get a solution to work. Ideally, code samples would be nice, but right now any help would be appreciated." ]
[ "apache-flex", "flex3", "dispatchevent" ]
[ "Is it possible to solve equations of bit wise operators?", "We can easily find:\n\na=7\nb=8\nc=a|b\n\n\nThen c comes out to be: 15\n\nNow can we find a if c is given?\n\nFor example:\n\nb=8\nc=15\nc=a|b\n\n\nFind a?\n\nAnd also if x=2<<1 is given, then we can get x=4. But if 4=y<<1 is given Can we get y?" ]
[ "python", "python-3.x", "bit-manipulation", "bitwise-operators" ]
[ "Oracle - exchange partitions with a table", "I try to create a table2 on Oracle 11g.2.0.3 with:\n\nCREATE table2 \nLOGGING TABLESPACE TS_table1_2014 PCTFREE 10 INITRANS 1 STORAGE ( INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS UNLIMITED BUFFER_POOL DEFAULT ) NOCOMPRESS\nas (select * from table1 where date_text <= '2015-12-31');\n\n\nand I have received error below when I try to exchange this table2 with a partitioned table3:\n\nalter table table3 exchange partition partition_name WITH TABLE table2;\n\n Error report -\n SQL Error: ORA-14097: column type or size mismatch in ALTER TABLE EXCHANGE PARTITION\n 14097. 00000 - \"column type or size mismatch in ALTER TABLE EXCHANGE PARTITION\"\n *Cause: The corresponding columns in the tables specified in the\n ALTER TABLE EXCHANGE PARTITION are of different type or size\n *Action: Ensure that the two tables have the same number of columns\n with the same type and size.\n\n\nI have test diferences with query below:\n\nSelect a.COLUMN_NAME \n , a.DATA_TYPE, b.DATA_TYPE \n , a.data_length, b.data_length \n , a.data_precision, b.data_precision \n , a.data_scale, b.data_scale \n , a.nullable, b.nullable \nfrom ALL_TAB_COLUMNS a \nfull outer join ALL_TAB_COLUMNS b on a.column_name=b.column_name \n and b.owner=user and b.table_name='&table2' \n where a.owner=user and a.table_name='&table1' \n and ( \n nvl(a.data_type,'#')!=nvl(b.data_type,'#') \n or nvl(a.data_length,-1)!=nvl(b.data_length,-1) \n or nvl(a.data_precision,-100)!=nvl(b.data_precision,-100) \n or nvl(a.data_scale,-100)!=nvl(b.data_scale,-100) \n or nvl(a.nullable,'#')!=nvl(b.nullable,'#') \n ) \n;\n\n\nSome differences resulted are in a column size. This syntax \"create as select\" didn't keep order and size for new table created.\n\nHow can I create table2 as select from table1 with force keep same size columns as primary table1 source?\n\nThanks!" ]
[ "oracle", "database-administration" ]
[ "Custom Callout on MKAnnotationView", "I wish to show a completely custom callout view on top of the MKAnnotationView when tapped. I have stumbled through a few answers but none of them have worked and I have seen it in a few apps so I know it can be done. I would also like to show a few buttons on the callout and perform different actions upon tapping on them. I am working on Objective-C and would really appreciate any help." ]
[ "ios", "objective-c" ]
[ "Use in code HTML for GET in ajax", "I am trying to figure out a way to just use my inline HTML as the URL for the ajax GET method instead of getting the data from a separate webpage. Is this possible?\n\nThis is my ajax code:\n\n $.ajax({\n type: \"GET\",\n url: $(elm).attr(\"href\"),\n success: function(data){\n $(\"#pageslide-content\").html(data)\n .queue(function(){\n $(this).dequeue();\n\n // restore working order to all anchors\n $(\"#pageslide-slide-wrap a\").unbind('click').click(function(elm){\n document.location.href = elm.target.href;\n });\n\n // add hook for a close button\n $(this).find('.pageslide-close').unbind('click').click(function(elm){\n _closeSlide(elm);\n $(this).find('pageslide-close').unbind('click');\n });\n settings.complete();\n });\n }\n });\n });\n\n\nAny help would be great!\n\nUPDATE\n\nSOLVED:\n\n $(\"#pageslide-content\").html('<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><title></title></head?<body><strong style=\"color:#C63; font-size:28px; font-weight:bold;\">TEST</strong></body></html>')\n .queue(function(){\n $(this).dequeue();\n\n // restore working order to all anchors\n $(\"#pageslide-slide-wrap a\").unbind('click').click(function(elm){\n document.location.href = elm.target.href;\n });\n\n // add hook for a close button\n $(this).find('.pageslide-close').unbind('click').click(function(elm){\n _closeSlide(elm);\n $(this).find('pageslide-close').unbind('click');\n });\n settings.complete();\n });" ]
[ "jquery", "ajax", "get" ]
[ "How to retrive the last inserted id using mysql?", "SELECT event.event_name, restaurants.res_name \n FROM event_choices\n INNER JOIN restaurants\n ON event_choices.res_id = restaurants.res_id\n INNER JOIN event\n ON event_choices.event_id = event.event_id \n\n\nI am trying to get the last inserted records based on the event_id this query brings back all the records.\n\nsimilar to what mysql_insert_id() would do.\n\nIs it possible to modify the query to return only the last inserted record?\n\nmy data looks like this I need to return the last event_id and its matching res_id\n\nevent_id | res_id\n116 | 1\n116 | 2" ]
[ "php", "mysql" ]
[ "Chrome extensions that runs JS before every page loads using content script", "I am attempting to write a chrome extension that needs to inject JS before any page loads. I am having trouble getting my JS to execute. \n\nThis is what I have for my manifest:\n\n{\n \"manifest_version\": 2,\n\n \"name\": \"testOne\",\n \"description\": \"This extension inject js\",\n \"version\": \"1.0\",\n\n \"permissions\": [\"<all_urls>\"],\n \"content_scripts\": [\n {\n \"matches\": [\"http://*/*\"],\n \"js\": [\"myscript.js\"],\n \"run_at\": \"document_start\"\n }\n ]\n}\n\n\nAnd this is what I have in my JS right now:\n\nalert('test');\nconsole.log('you tried to log');\n\n\nWhy am I not seeing any alerts of console events?" ]
[ "javascript", "google-chrome-extension" ]
[ "SQL BULK INSERT with on the fly table creation", "I would like to use BULK INSERT to load a few hundred raw data tables into SQL Server. The format of these tables would be similar, although not identical (they come from excel sheets which are not tightly version controlled).\n\nI want to know if there is a way to dynamically generate the table required on SQL Server depending on the headers in the file to be loaded, and then do the BULK INSERT thereafter." ]
[ "sql-server", "sql-server-2008-r2", "bulkinsert" ]
[ "How show text style as bold when in Android EditText was disabled in layout xml?", "In my edit text, I have mentioned text style as bold and the edit text was noneditable. I need to show the text field as in bold but it was not working. \n\nHere is my EditText Sample:\n\n <android.support.design.widget.TextInputLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_marginLeft=\"@dimen/layout_padding_5dp\"\n android:layout_weight=\"1\"\n android:theme=\"@style/TextInputLayoutAppearance\"> \n <EditText\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:hint=\"@string/amount\"\n android:inputType=\"numberDecimal\"\n android:imeOptions=\"actionNext\"\n android:maxLength=\"7\"\n android:text=\"999.99\"\n android:textStyle=\"bold\"\n android:textColor=\"@color/black\"\n android:focused=\"false\"\n android:enabled=\"false\"\n android:editable=\"false\"\n android:textSize=\"18\"/>\n </android.support.design.widget.TextInputLayout>" ]
[ "android", "android-edittext" ]
[ "How to alias a pointer", "I have some class Foo, and I want to do as follows. I have some static instances of pointers to Foo objects, static Foo *foo1; static Foo *foo2;\n\nThen, in some function, I want to have a generic pointer that can act as both of them. For example,\n\nFoo *either;\nif (some_variable == 1)\n{\n either = foo1;\n}\nelse\n{\n either = foo2;\n}\n\n\nThis is how I expected it to work, but it doesn't seem to be functioning correctly. How is it normally done? I want either to actually BE foo1 or foo2 when I use it." ]
[ "c" ]
[ "iOS 9.1 AudioQueueAllocateBuffer requesting a fix buffer size, it returns a smaller one", "In the new iOS 9.1 when sets the AudioSession requesting a fix buffer size, the OS returns a smaller buffer. Why does that happen?? In the early versions <9.1 it worked as a charm\n\n// Create a new audio input queue\nOSStatus result = AudioQueueNewInput(&mAudioFormat,\n IOSAudioRecorder::RecorderCallback,\n this, // userData\n nullptr, // run loop\n kCFRunLoopCommonModes, // run loop mode\n 0, // flags\n &mAudioQueue);\nif (result != 0)\n{\n Logger::Error(this, \"Failed to create new audio input queue, result: \", result);\n mAudioQueue = nullptr;\n}\nelse\n{\n // Allocate memory for the buffers\n for (unsigned int i = 0; i < mNumBuffers; i++)\n {\n AudioQueueAllocateBuffer(mAudioQueue, mBufferFrames * sizeof(short), &mInputBuffer[i]);\n mOutputBuffer[i] = new short[mBufferFrames];\n }\n}\n\n\nAnd in the \"RecorderCallback\" I receive buffers smaller than the requested.\n\nAny clue why does that happen?" ]
[ "ios", "objective-c", "iphone", "audiosession", "ios9.1" ]
[ "iterate through open forms and close particular forms only", "given below is the code i wrote \n\nPrivate Sub CloseTransactionForms()\n Dim ActiveFroms As New List(Of String)\n Dim formToClose As New List(Of Form)\n Dim j As Integer\n ActiveFroms.Add(\"FrmSale\")\n ActiveFroms.Add(\"FrmpPurchase\")\n ActiveFroms.Add(\"FrmSaleReturn\")\n ActiveFroms.Add(\"FrmPurchaseReturn\")\n Try\n For Each frm As Form In My.Application.OpenForms\n For j = 0 To ActiveFroms.Count - 1\n If frm.Name.ToString() = ActiveFroms.Item(j) Then\n formToClose.Add(frm)\n End If\n Next\n Next\n If formToClose.Count > 0 Then\n Dim i As Integer\n For i = 0 To formToClose.Count - 1\n Dim xform As Form = formToClose.Item(i)\n xform.Close()\n Next\n End If\n Catch ex As Exception\n End Try\nEnd Sub\n\nthis code will iterate through the open forms in my application and close the defined forms from the application \nbut it seems not good for me (using 3 for loops in it and it took sometimes while iterating via for loop) i think there will be another good method, please suggest a good solution for me\n\n\nNote : i have already seen this question in SO" ]
[ "c#", "vb.net", "winforms", "openform" ]
[ "Write to CSV file after re.sub Python", "I have done a regex substitution on a CSV file that prints following output, just like anything else:\n\nH1,H2,H3\nA1,GG,98\nB3,KLK,Oe\n\n\nBut when I write it to a CSV file, it writes complete line in one cell (doesn't use commas as delimiters even though specified). I used the writer.writerow(row.split(\"\\n\")) to write, where row is the data obtained after re.sub (i.e. the output posted above)." ]
[ "python", "regex", "string", "csv" ]
[ "How do I do calculations with data from another table using dplyr?", "I am in the process of doing some research that has me running analysis in a few separate df. The results of the separate df are to be used in one main calculation df. Most of the stat categories are used in several df. I'm looking to use the results from the separate df\n\n\n# Table used for league average calculations below\nteams <- tibble::tribble(\n ~Team, ~PA, ~AB, ~H, ~HBP, ~BB, ~HR, ~R, ~RBI, ~SB, ~AVG, ~OBP,\n \"Athletics\", 6255, 5579, 1407, 76, 550, 227, 813, 778, 35, 0.252, 0.325,\n \"Red Sox\", 6302, 5623, 1509, 55, 569, 208, 876, 829, 125, 0.268, 0.339,\n \"Yankees\", 6271, 5515, 1374, 62, 625, 267, 851, 821, 63, 0.249, 0.329,\n \"Indians\", 6300, 5595, 1447, 80, 554, 216, 818, 786, 135, 0.259, 0.332,\n \"Astros\", 6146, 5453, 1390, 61, 565, 205, 797, 763, 71, 0.255, 0.329\n)\n\n\n# Table used for player calculations (main table)\nplayers <- tibble::tribble(\n ~Name, ~Team, ~G, ~PA, ~AB, ~H, ~HBP, ~BB, ~HR, ~R, ~RBI, ~SB, ~AVG, ~OBP,\n \"Mookie Betts\", \"Red Sox\", 136, 614, 520, 180, 8, 81, 32, 129, 80, 30, 0.346, 0.438,\n \"Mike Trout\", \"Angels\", 140, 608, 471, 147, 10, 122, 39, 101, 79, 24, 0.312, 0.46,\n \"J.D. Martinez\", \"Red Sox\", 150, 649, 569, 188, 4, 69, 43, 111, 130, 6, 0.33, 0.402,\n \"Alex Bregman\", \"Astros\", 157, 705, 594, 170, 12, 96, 31, 105, 103, 10, 0.286, 0.394,\n \"Jose Ramirez\", \"Indians\", 157, 698, 578, 156, 8, 106, 39, 110, 105, 34, 0.27, 0.387\n)\n\n\n# Denominators needed for calculations\ncalc_tbl <- tibble::tribble(\n ~data_col, ~calc_denom,\n \"HR\", 14.3,\n \"R\", 19.6,\n \"RBI\", 17.5,\n \"SB\", 26.2,\n \"AVG\", 0.0045,\n \"OBP\", 0.0031\n) %>% \n spread(key = data_col, value = \"calc_denom\")\n\n\n# Get league average of teams\nlg_avg <- teams %>% \n# Divide counting stats by 10 to get the averages for 10 batters\n mutate_at(vars(PA:SB), funs(./10)) %>% \n summarize_if(is.numeric, mean, na.rm=TRUE)\n\nlg_avg\n#> # A tibble: 1 x 11\n#> PA AB H HBP BB HR R RBI SB AVG OBP\n#> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>\n#> 1 625. 555. 143. 6.68 57.3 22.5 83.1 79.5 8.58 0.257 0.331\n\n# Calculate Values\nvalue_tbl <- players %>% \n mutate(calc_R = R / calc_tbl$R,\n calc_HR = HR / calc_tbl$HR,\n calc_RBI = RBI / calc_tbl$RBI,\n calc_SB = SB / calc_tbl$SB,\n calc_BA = (((lg_avg$H * 13 ) + H)/(AB + (lg_avg$AB * 13)) - lg_avg$AVG) / calc_tbl$AVG,\n calc_Total = (calc_R + calc_HR + calc_RBI + calc_SB + calc_BA))\n\n\n\nI really have 2 questions, and both focus on efficiency, and whether there is a better way to do what I'm doing. Am I calling the results from the other df column calculations properly?\nIs there a more direct, and efficient way to write the last piece of code on the mutates?" ]
[ "r", "dplyr", "tidyverse" ]