texts
sequence | tags
sequence |
---|---|
[
"Access @section defined in view from partial",
"I have a page with a tab, each tab content is placed as a partial view with some scripts\n\nAs a best practice, I want to add all the scripts in the bottom of the page. Since the partial views are unable to access the @section i placed all the scripts in page itself, it is hard to read.\n\nTabs are loaded based on permission. Even though user doesnt have permission, still i render those scripts.\n\nHow can i add all the scripts referred in page/partial view at the bottom? \n\nWebForm Context: I think it is similar to accessing the content place holder from a user control"
] | [
"c#",
"asp.net",
"asp.net-mvc",
"asp.net-mvc-4"
] |
[
"EF Core save value from method instead of property",
"I like to add some data to a column, from a method instead of a property. Is this somehow possible in EF Core?\n\nFor example, the config code could look like this:\n\ninternal class MyEntityTypeConfiguration : IEntityTypeConfiguration<MyEntity>\n{\n public void Configure(EntityTypeBuilder<MyEntity> builder)\n {\n builder.ToTable(\"Table1\");\n\n // Add column \"Value1\" and set it with the return value of myEntity.GetValue()\n builder.Property<string>(\"Value1\").WithValue(myEntity => myEntity.GetValue()); // TODO create WithValue\n\n builder.HasKey(o => o.Id);\n }\n}\n\n\nin this case, the WithValue method won't exist. \n\nExample:\n\nFor example, I will save 2 entities. \n\n\nGetValue() for entity 1 returns \"I am Entity 1\"\nGetValue() for entity 2 returns \"I am Entity 2\"\n\n\nThen I like store \"I am Entity 1\" and \"I am Entity 2\" in the column Value1\n\nSolution\n\nJairo's solution with the ValueGenerator worked perfect for me! I made the WithValue like this:\n\ninternal class ValueRetriever<TEntityEntry, TResult> : Microsoft.EntityFrameworkCore.ValueGeneration.ValueGenerator<TResult>\n{\n private readonly Func<TEntityEntry, TResult> _retrieve;\n\n public ValueRetriever(Func<TEntityEntry, TResult> retrieve)\n {\n _retrieve = retrieve;\n }\n\n public override bool GeneratesTemporaryValues => false;\n\n public override TResult Next(EntityEntry entry) => _retrieve((TEntityEntry)entry.Entity);\n}\n\n\nWithValue extension:\n\npublic static void WithValue<TEntityEntry, TResult>(this PropertyBuilder<TResult> propertyBuilder, Func<TEntityEntry, TResult> retrieve)\n{\n propertyBuilder.HasValueGenerator((property, type) => new ValueRetriever<TEntityEntry, TResult>(retrieve));\n}\n\n\nUsage: \n\nbuilder\n .Property<string>(\"Value1\")\n .WithValue<MyEntity, string>(myEntity => myEntity.GetValue());"
] | [
"c#",
"entity-framework-core",
"entity-framework-core-3.0"
] |
[
"Pan responder automatically disables video recording",
"I have a button, that when long pressed, starts recording a video. The video only records as long as a finger is held down on it, and it stops recording when you lift your finger.\nNow, when I add a pan responder to find the position of the person's finger, and I move my finger while recording, the recording automatically stops without me having to lift my finger.\nAny idea why this happens?\nHere is my pan responder function:\nconst panResponder = React.useRef(\n PanResponder.create({\n onMoveShouldSetPanResponder: (evt, gestureState) => true,\n \n onPanResponderMove: (evt, gestureState) => {\n \n console.log(gestureState);\n },\n \n }),\n ).current;\n\n\nHere is my recording function on longpress:\nconst startRecord = async () => {\n setRecording(true);\n growIn();\n\n if (cameraRef.current) {\n setRecording(true);\n const recordedVideo = await cameraRef.current.recordAsync();\n\n setVideo(recordedVideo);\n }\n };\n\nHere is the component that I render:\n<Container {...panResponder.panHandlers}>\n <CircleWrapper>\n {recording == true && (\n <Animated.View>\n <ImageIconContainer onPress={() => console.log('Yoooo')}>\n <ImageIcon fill={'white'} height={30} width={30} />\n </ImageIconContainer>\n </Animated.View>\n )}\n <Animated.View style={[styles.box]}>\n <Circle\n activeOpacity={0.8}\n style={animatedStyles}\n onPress={handlePhoto}\n onLongPress={startRecord}\n onPressOut={stopRecord}\n delayLongPress={100}\n hitSlop={{ top: 50, bottom: 50, left: 200, right: 200 }}>\n {!recording && (\n <ImageIconContainer onPress={pickImage}>\n <ImageIcon fill={'white'} height={30} width={30} />\n </ImageIconContainer>\n )}\n\n <Animated.View style={fadeInStyle}>\n <CircleBackground />\n </Animated.View>\n </Circle>\n </Animated.View>\n </CircleWrapper>\n \n </Container>"
] | [
"react-native",
"react-native-gesture-handler"
] |
[
"get all files from resources directory in a Jenkins pipeline",
"I have several yaml files in my /resources directory and I would like to get a list of ALL of them.\nI've set a shared library and I'm able to get a specific file by using libraryResource:\nlibraryResource("some_file.yaml")\nHow can get a list of all yaml files from this path?"
] | [
"jenkins-pipeline",
"jenkins-groovy"
] |
[
"Can I assign a variable to check multiple arrays inside a loop?",
"I am trying to check through multiple arrays inside of a loop, all with the same index. Instead of manually coding through every list I wanted to soft code it so every time the function loops it can check through all of my arrays. All of my arrays are named: score1-score8, but whenever this code runs it doesn't actually check any of the lists.\n\nfunction checkHorizontal()\n{\n\n var rowcount=0;\n var checkLists;\n var player1=0;\n var player2=0;\n\n checkLists=\"score\"+rowcount;\n\n for (var i = 0; rowcount <= 8; i++) \n {\n rowcount+=1;\n if(checkLists[rowcount]==1) \n {\n player1+=1;\n player2=0; \n }\n else if (checkLists[rowcount]==2)\n {\n player2+=1;\n player1=0;\n }\n\n }\n\n}"
] | [
"javascript",
"arrays",
"variables"
] |
[
"How to disable ECHO DIALOGS for Windows Script Host running a vbs file?",
"Ran into a problem today. I have a Windows Server 2003 with a bunch of .bat files that essentially start .vbs scripts. Every time an ECH is used in the script I get that annoying dialog box that contains content of an echo and requires to click ENTER all the time. How can I just disable the dialogs and keep ECHOs in the command prompt window only?"
] | [
"windows",
"wsh"
] |
[
"installing numpy for pypy 2.3.5 (python 3.2.5 compatible) on windows 7 with mingw32",
"Here is mine small research about how-to install numpy for pypy3 on windows 7 with mingw32 compiler. \nAt first,tried to make it simple:\n\npypy setup.py install build --compiler=mingw32\n\n\nBut, here i got this error. Fortunately, i found this solution. Now, i'm trying again:\n\npypy setup.py install build --compiler=mingw32\n\n\nAnd the error is:\n\ndata=DATA_RE.findall(nm_output)\nTypeError:can't use a bytes pattern in string-like object\n\n\nThis error occurs in file pypy_numpy\\numpy\\distutils\\lib2def.py.\nSo,the question is about how to handle this?"
] | [
"numpy",
"distutils",
"pypy"
] |
[
"Lua - Removing words that are not in a list",
"i want to remove words that are not in a list, from a string. \n\nfor example i have the string \"i like pie and cake\" or \"pie and cake is good\" and i want to remove words that are not \"pie\" or \"cake\" and end out with a string saying \"pie cake\".\n\nit would be great, if the words it does not delete could be loaded from a table."
] | [
"string",
"lua"
] |
[
"Drupal multi-site setup with sub-directories",
"I have a multi-site setup with a single codebase.\nIs it possible to have my sites directory set up like this with sub folders:\nmysite.com in /home/drupal/sites/mysite.com\n\nothersite1.com in /home/drupal/sites/cluster1/othersite1.com\n\nothersite2.com in /home/drupal/sites/cluster1/othersite2.com\n\nothersite3.com in /home/drupal/sites/cluster2/othersite3.com\n\nothersite4.com in /home/drupal/sites/cluster2/othersite4.com\n\nI'm trying to find a way to organize all my sites.\n\nthanks"
] | [
"drupal",
"subdirectory",
"single-instance"
] |
[
"JBox2D - Drawing with DebugDraw",
"How do you draw elements with JBox2D? I'm fine using the DebugDraw, I just want to find a quick way to do this in Java since I haven't worked much with graphics.\n\nDo I need to use a Canvas? Or a JFrame? And how does the world know when I call \n\nworld.drawDebugData()\n\n\nwhere to draw it to?\n\nHow could I devise a class that just drew points where I want them, and integrate this with JBox2D?\n\n...\n\nwhile(true)\n world.step(timeStep, velocityIterations, positionIterations);\n Vec2 position = body.getPosition();\n float angle = body.getAngle();\n System.out.printf(\"%4.2f %4.2f %4.2f\\n\", position.x, position.y, angle);\n}\n\n\nI imagine I could put this code somewhere inside this while loop, but I'm not exactly sure where. Is there a function that's called every time a World steps? Can I put a draw function in there? I'm even ok using the DebugDraw if I could figure it out...\n\nCould you please help me understand what kind of class would take all the objects in the World object and draw them continually? (and where to draw to?)"
] | [
"java",
"box2d",
"paint",
"jbox2d"
] |
[
"Call Java Function using JSNI from servlet",
"I have created JSNI methods i am registering 'createCallbackFunction' method from another method using\n\ncreateCallbackFunction(new NTFileUploadUtil());\n\n\npublic void uploadComplete(String fileId){\n SC.say(\"I am back...with fileId:\" + fileId);\n System.out.println(\"I am back...with fileId: \" + fileId);\n}\n\n\nprivate native static void createCallbackFunction(NTFileUploadUtil obj ) /*-{\n //$wnd.alert(fileName); \n var tmpcallback = function(fileName){ \n [email protected]::uploadComplete(Ljava/lang/String;)( fileName);\n };\n alert(\"NTFileUploadUtil-- createCallbackFunction:\\n \" + tmpcallback);\n $wnd.uploadComplete=tmpcallback;\n}-*/;\n\n\nI am getting \n\nfunction (fileName) {\n __gwt_makeJavaInvoke(1)(obj, 83361821, fileName);\n}\n\n\nin alert as output .\n\nI am trying to call this from a struts action class\n\nresponse.setContentType(\"text/html\");\n\nout.println(\"<html>\");\n out.println(\"<head>\");\n out.println(\"<script type=\\\"text/javascript\\\">\");\n out.println(\"function foo() { \");\n out.println(\"alert('From Servlet');\");\n out.println(\"window.top.uploadComplete('\"+ft.getId()+\"');\");\n out.println(\"}\");\n out.println(\"</script>\");\n out.println(\"</head>\");\n out.println(\"<body onload=\\\"foo();\\\">\");\n out.println(\"</body>\");\n out.println(\"</html>\");\n\n\nBut Javascript is not getting executed.\nNeither alert is working nor upload method is getting called."
] | [
"gwt",
"smartgwt",
"jsni"
] |
[
"MapKit Overlays consuming massive CPU resources",
"I'm overlaying the contents of a third-party shapefile. Some of the polygons consist of 138,000 points, most of them of about 3,000-8,000. In total there are 125 polygons.\n\nIs that normal? Can I in some way, reduce the granularity of the polygons? CPU consumption peaks at over 190% on iPhone 5, and it takes a few minutes before the first overlays pop up."
] | [
"ios",
"overlay",
"mapkit",
"shapefile",
"proj"
] |
[
"PHP Regex to format links",
"Possible Duplicate:\n convert url to links from string except if they are in a attribute of a html tag \n\n\n\n\nI'm looking for help with a PHP Regex expression.\n\nI'm creating an input page for an invitation-only blog, so I don't need to worry about spammers. I want to make it simple for people to add a URL, but I also want to make it possible for them to use HTML mark-up if that's what makes them happy.\n\nIn the example below, the $text variable contains three links. I want to create <a > ... </a> tags around the first 2, but the third already has these tags, so I want to leave it alone. My regular expression works will for the last 2 cases, but not the first one.\n\nMy regex starts with [^<a href *?= *?\\'\\\"] which I want to mean \"Don't create a match if the string start with <a href='> (or similar), but that's not how it works in practice. Here, the ^ behaves as a \"start of line\" character not as a negator.\n\nI would like the output to appear something like this:\n\nVisit <a ...>http://www.example.com/</a> for more info.\n\n<a ...>http://www.example.com/index.php?q=regex</a>\n\nHere is a <i><a ...>link</a> to visit</i>.\n\n\nThanks in advance for any help with rewriting the regex.\n\nJames\n\n<?php\n$text = \"Visit http://www.example.com/ for more info.\n\nhttp://www.example.com/index.php?q=regex\n\nHere is a <i><a href='http://www.google.ca/search?q=%22php+regex%22&hl=en'>link</a> to visit</i>.\";\n\n// Ignore fully qualified links but detect bare URLs...\n$pattern = '/[^<a href *?= *?\\'\\\"](ftp|https?):\\/\\/[\\da-z\\.-]+\\.[a-z\\.]{2,6}[\\/\\.\\?\\w\\d&%=+-]*\\/?/i';\n\n// ... and replace them with links to themselves\n$replacement = \"<a href='$0'>$0</a>\";\n\n$output = preg_replace($pattern, $replacement, $text);\n\n// Change line breaks to <p>...</p>...\n$output = str_replace(\"\\n\", \"\", $output);\n$output = \"<p>\".str_replace(\"\\r\", \"</p><p>\", $output).\"</p>\";\n\n// Allow blank lines\n$output = str_replace(\"<p></p>\", \"<p>&nbsp;</p>\", $output);\n\n// Split the paragraphs logically in the HTML\n$output = str_replace(\"</p><p>\", \"</p>\\r<p>\", $output);\n\necho $output;\n?>"
] | [
"php",
"regex",
"url",
"hyperlink"
] |
[
"Store a phone number with a custom label in call log and then call it with my app",
"I have an application which uses the Agora library to facilitate a videochat between two parties.\n\nWhat I want to do is to store the number that calls in the phone's call log, and then, when the user goes into the call log and presses on that number, that number to be passed into my app and used inside my app to call the respective user.\n\nHere's how I currently log the number that is calling the user:\n\n@Override\n public void onInviteReceived(final String channelName, final String contactPhone, int uid, final String s2) { //call out other remote receiver\n Log.i(TAG, \"onInviteReceived channelName = \" + channelName + \" contactPhone = \" + contactPhone);\n runOnUiThread(new Runnable() {\n @SuppressLint(\"MissingPermission\")\n @Override\n public void run() {\n Gson gson = new Gson();\n CallExtra callExtra = gson.fromJson(s2, CallExtra.class);\n\n ContentValues values = new ContentValues();\n values.put(CallLog.Calls.CACHED_NUMBER_LABEL, \"FairyApp\");\n values.put(CallLog.Calls.CACHED_NAME, \"FairyApp\");\n values.put(CallLog.Calls.TYPE, CallLog.Calls.INCOMING_TYPE);\n values.put(CallLog.Calls.DATE, System.currentTimeMillis());\n values.put(CallLog.Calls.DURATION, 50);\n values.put(CallLog.Calls.NUMBER, contactPhone);\n\n getContentResolver().insert(CallLog.Calls.CONTENT_URI, values);\n\n\nAs you can see, I've just hardcoded the information just to see if it works, and indeed it does - the number is being recorded into the call log of the phone (obviously, I took care of the permissions to do this already).\n\nThen, I created a broadcast receiver that intercepts an intent of type android.intent.action.NEW_OUTGOING_CALL , in order to intercept the user calling that number and redirecting him or her to my app and then initiate the call from there.\n\nHere's how the Broadcast Receiver looks in the AndroidManifest:\n\n<receiver android:name=\".broadcastreceivers.OutgoingCallReceiver\" >\n <intent-filter>\n <action android:name=\"android.intent.action.NEW_OUTGOING_CALL\" />\n </intent-filter>\n</receiver>\n\n\nHere's what the Receiver currently does (it's hardcoded, for now):\n\npublic class OutgoingCallReceiver extends BroadcastReceiver {\n\n@Override\npublic void onReceive(Context context, Intent intent) {\n String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);\n if (phoneNumber.equals(\"4444\")){\n context.startActivity(new Intent(context, HomeActivity.class));\n }\n}\n\n\n}\n\nSo, it basically intercepts the intent to call, gets the phone number, and if the phone number is \"4444\", then it goes into my HomeActivity.\n\nThis works.\n\nThe problem that I'm having is trying to save a \"label\" for the stored number - I want to store an information that \"this number is of type \"MyApp\"\" and then, when the user presses to call that number from the phone's call log, I want to use that information in my Broadcast Receiver and check \"if this is type \"MyApp\" then open my HomeActivity, else just ignore this broadcast\".\n\nSo, my question is - how do I store a label into the call log, or some custom piece of information that I can then use in my Broadcast Receiver to identify calls that \"belong\" to my application?\n\nThank you."
] | [
"android",
"label",
"call",
"broadcast",
"receiver"
] |
[
"Remove multiple commas in PHP",
"Sorry if this is really basic but I am just learning PHP.\n\nI have some code that looks like: \n\n<h4><?=$prop['house_number']?>, <?=$prop['street']?>, <?=$prop['town']?></h4>\n\n\nThat is bring back from the database eg: 55, main street, townname\n\nWhen the address does not contain a street name it comes back as eg: 55, , townname.\n\nI want to know how to remove the commer so it just brings back eg: 55, townname.\n\nHopefully it is a really easy one but I have tried a couple of things and cannot seem to get it right.\n\nMany thanks"
] | [
"php",
"codeigniter",
"replace"
] |
[
"QProcess : Reset working directory during runtime",
"I'm using the QProcess class from Qt to communicate between a Qt-GUI Application and program written in C. When I start the GUI I set the working directory of QProcess.\n\nNow I'm wondering if it's possible to reset the chosen working directory of QProcess during runtime. I did not find any function in the QT documentation.\n\nThe User should enter some file-paths into the GUI which passes them to the C Program (Crypto program). Besides the file paths entered in the GUI the C Program loads some files on his own from the current working Directory.\n\nE.g. The User wants to verify a File which is stored together with a Signature at a Directory A. The public Key from the Signer is in Directory B. \nThe User can enter the path to the public Key in the GUI (works)\nThe User can enter the path to a new working Directory in the GUI (does not work)\n\nI have a QPushButton \"set new working Directory\" which emits the SIGNAL clicked to a SLOT where I call : \n\n// _dataWDict->text() gets the Text Input from a QLineEdit Widget\n// from the _userWidget (= \"GUI\")\n\nQString pathWDict = _userWidget->_dataWDict->text();\n_process->setWorkingDirectory(pathWDict);\n\n// displays me the output in the GUI\n_userWidget->_log->append(_process->workingDirectory());\n\n\nCalling QProcess::setWorkingDirectory purports to be diffrent but I still can only access the Files in the working Directory from the start. From the Qt-Docs : \" QProcess will start the process in this directory\""
] | [
"c++",
"qt",
"directory",
"reset",
"qprocess"
] |
[
"SOLVED Python and Selenium, Trying to accept cookies on website results: Unable to locate element",
"SOLVED: The 'accept cookies window' was in the iframe so I had to switch to that frame to be able to locate the element. Switching done with following code:\niframe = self.driver.find_element(By.XPATH, '//iframe[@id="sp_message_iframe_433571"]')\nself.driver.switch_to.frame(iframe)\n\nORIGINAL QUESTION:\nI'm trying to enter a website with python (selenium) code and I'm required to accept cookies. For some reason, no matter what I've tried, I always get the result: Unable to locate element. Below 'accept cookies button' from the website's HTML code.\n<button tabindex="0" title="Hyväksy kaikki evästeet" aria-label="Hyväksy kaikki evästeet" class="message-component message-button no-children buttons-row" path="[0,3,1]">Hyväksy kaikki evästeet</button>\n\nI've tried the following:\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom time import sleep\nimport pandas as pd \nimport requests as req\n\nclass trackerBot(): \n \n def __init__(self):\n self.driver = webdriver.Chrome()\n # Tried with and without implicitly wait\n self.driver.implicitly_wait(10)\n \n def loadWebsite(self, uri):\n \n self.driver.get(uri)\n cookies_accept_btn = self.driver.find_element_by_xpath('/html/body/div/div[3]/div[5]/button[2]')\n cookies_accept_btn.click()\n \ndef main():\n bot = trackerBot()\n bot.loadWebsite("https://www.tori.fi") \n return(0)\n \nmain()\n\nCan someone advise what I'm missing?\nMany thanks in advance!"
] | [
"python",
"html",
"selenium"
] |
[
"libGDX throwing an error for the default vertex shader in a SpriteBatch",
"I am new to libGDX and am using it to complete a big game for a school project. I have been following an online tutorial for most of the code, but can't seem to run because of a Vertex Shader error. \nError: \n\n\n Fragment shader:\n ERROR: 0:1: '' : #version required and missing.\n ERROR: 0:7: 'varying' : syntax error: syntax error\n at com.badlogic.gdx.graphics.g2d.SpriteBatch.createDefaultShader(SpriteBatch.java:161)\n at com.badlogic.gdx.graphics.g2d.SpriteBatch.(SpriteBatch.java:124)\n at com.badlogic.gdx.graphics.g2d.SpriteBatch.(SpriteBatch.java:78)\n at com.tootireddevelopmentco.games.Splash.show(Splash.java:41)\n at com.badlogic.gdx.Game.setScreen(Game.java:61)\n at com.tootireddevelopmentco.games.RabbitRun.create(RabbitRun.java:17)\n at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:149)\n at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:126)\n\n\nI do not have any experiences with shaders, and have not created a shader during my project, or declared a version of any sort. The shader error seems to trace back to the SpriteBatch created in my program. Is there something wrong with my code, or is libGDX and my settings for it the issue. \n\nSome extra code from my classes: \nFrom the splash class - error points to SpriteBatch declaration. \n\npublic void show() {\n // apply preferences\n\n batch = new SpriteBatch();\n\n tweenManager = new TweenManager();\n Tween.registerAccessor (Sprite.class, new SpriteAccessor ());\n\n splash = new Sprite(new Texture (\"img/splash.png\"));\n\n Tween.set (splash, SpriteAccessor.ALPHA).target(0).start(tweenManager); \n Tween.to(splash, SpriteAccessor.ALPHA, 1.5f).target(1).repeatYoyo(1, 2).setCallback(new TweenCallback () {\n\n @Override\n public void onEvent(int arg0, BaseTween<?> arg1) {\n // TODO Auto-generated method stub\n ((Game) Gdx.app.getApplicationListener()).setScreen (new MainMenu ());\n }\n });\n\n\n}\n\nThanks, \nJulia"
] | [
"java",
"eclipse",
"libgdx",
"game-engine",
"scene2d"
] |
[
"Return certain fields with .populate() from Mongoose",
"I'm getting returned a JSON value from MongoDB after I run my query. The problem is I do not want to return all the JSON associated with my return, I tried searching the docs and didn't find a proper way to do this. I was wondering what if it is at possible, and if so what is the proper way of doing such. Example:\nIn the DB \n\n{\n user: \"RMS\",\n OS: \"GNU/HURD\",\n bearded: \"yes\",\n philosophy: {\n software: \"FOSS\",\n cryptology: \"Necessary\"\n },\n email: {\n responds: \"Yes\",\n address: \"[email protected]\"\n },\n facebook: {}\n}\n\n{\n user: \"zuckerburg\",\n os: \"OSX\",\n bearded: \"no\",\n philosophy: {\n software: \"OSS\",\n cryptology: \"Optional\"\n },\n email: {},\n facebook: {\n responds: \"Sometimes\",\n address: \"https://www.facebook.com/zuck?fref=ts\"\n }\n} \n\n\nWhat would be the proper way of returning a field if it exists for a user, but if it doesn't return another field. For the example above I would want to return the [email][address] field for RMS and the [facebook][address] field for Zuckerburg. This is what I have tried to find if a field is null, but it doesn't appear to be working.\n\n .populate('user' , `email.address`)\n .exec(function (err, subscription){ \n var key;\n var f;\n for(key in subscription){\n if(subscription[key].facebook != null ){\n console.log(\"user has fb\");\n }\n }\n }"
] | [
"javascript",
"json",
"node.js",
"mongodb",
"mongoose"
] |
[
"Get part of string after a whitespace",
"So let's say I have a string called Hi there.\n\nI am currently using\n\nm:match(\"^(%S+)\") \n\n\nto get just Hi from the string, now all I need to do is just get \"there\" from the string but I have no idea how."
] | [
"string",
"lua",
"roblox"
] |
[
"How to get the scroll position of a specific content in a repeating div",
"Is there any way to find the scroll position of a specific content in a div.\nI have a chat application running on Angularjs using ng-repeat to display the name and message of the sender.\n\nHere is the HTML code for displaying the message.\n\n<div ng-repeat=\"(key,value) in list\" >\n <div ng-init=\"compare(value.name,key,value.date);\">\n <div id=\"date\" ng-if=\"date[key]=='not_same'\" > {{value.date|convert }} </div>\n <div id=\"recipent\" > \n <div ng-if=\"name[key]=='not_same'\">\n <span class=\"glyphicon glyphicon-user\" ></span> :<b> {{value.name}}</b>\n </div>\n </div>\n </div>\n <div class=\"msgInfo\" ng-if=\"value.name=='Yash'\" align='right' >\n <div id=\"msg\" > <b id=\"ms\"> {{value.msg}}</b>&nbsp;&nbsp;&nbsp;<b id=\"time\">{{value.time|change_time}}&nbsp;&nbsp;</b></div>\n </div> \n <div class=\"msgInfo\" ng-if=\"value.name!=='Yash'\" align='left' >\n <div id=\"msg\" > <b id=\"ms\"> {{value.msg}}</b>&nbsp;&nbsp;&nbsp;<b id=\"time\">{{value.time|change_time}}&nbsp;&nbsp;</b></div>\n </div> \n</div>\n\n\nHere the div id=\"msg\" contains the message.\n\nI also have a \"Load previous Messages\" button to load the previous messages.\nWhen i click the Load prev Msg button it loads the previous messages and displays in a chronological order. I want to display the oldest message that was present before the previous messages loaded like you seen in Whatsapp.\n\nI use this code to get the content of the specific message\n\nvar msg=document.getElementById(\"ms\").innerHTML;\n\n\nI want to get the Scroll position of that specific message after the old messages have also been displayed."
] | [
"javascript",
"jquery",
"html",
"angularjs"
] |
[
"Javascript, determine which button was selected in a function, similar to (id)sender in iOS?",
"I'm taking a Javascript class and was wondering if there was a way to tell which button was selected when a function is called. I basically have a method like this:\n\nfunction sendRequest()\n{\n var url = \"http://classwebsite/bookmarks.php\";\n url += \"?userid=crystal\";\n var transmission = document.getElementById(\"transmission\").value;\n url += \"&response=\" + transmission;\n var callback = {success:handleResponse, \n failure:handleFailure,\n timeout:5000\n };\n\n var transaction = YAHOO.util.Connect.asyncRequest(\"GET\", url, callback, null);\n}\n\n\nThis method gets called when a button is pressed. It basically gets back the prof's response in the appropriate JSON, XML, etc format and displays it. I want to add an \"add\" feature to add new rows to the table. That's done by calling the same URL in the above method and just manually putting this in the address bar:\n\nhttp://classwebsite/bookmarks.php?userid=crystal&action=add&name=yahoo&url=yahoo.com&desc=Yahoo+website\n\n\nIn this scenario, if I had another button called \"Add\" to add in fields from a form, would I call the same sendRequest() method, and modify the url accordingly? If so, how do I know which button was pressed if both the \"List\" button and \"Add\" button would be tied to the same event handler.\n\nOr is it a better design to have another method, that handles addRequest() and just adds fields from the form? Thanks."
] | [
"javascript",
"ajax"
] |
[
"include JST template inside JST",
"I am using underscopre ( grunt-contrib-jst) JST template to render VIEW.\n\nHowever, I am in a situation where I need to make reusable html as a partials from template.\n\ncan I make a separate .tmpl & include it in parent .tmpl ?\n\nmy code looks like\n\nvar tmpl = my.namespace['template/hello.tmpl'];\n$(\"#content\").html(tmpl({ \n data:data\n}));\n\n//where as I need to spearate templates inside hello.tmpl"
] | [
"javascript",
"underscore.js",
"underscore.js-templating",
"jst"
] |
[
"how to use onload to run javascript in a search box that removes the keyword \"script\"",
"I dont know how to do it. Any tips? My project is due tomorrow\n\n<body onload=\"loadImage()\">; <script> \"function loadImage() { alert(\"Image is loaded\"); }\" </script>\n\n\nI am trying to replace the alert(1) by actual script without using the word script because it is filtered...\n\n<body onload=\"loadImage()\">;\n\"function loadImage() {\n alert(\"Image is loaded\");\n}\"\n\n\nI want to run something like this, like this function but I cannot use the word script. I am taking EECS388: Computer Security at the University of Michigan. And I am trying to do an Cross site scripting alias xss. The search removes the keyword \"script\" so it is not possible to run javascript unless it is in some sort of tag (body or img)"
] | [
"javascript",
"jquery",
"python",
"html"
] |
[
"How to detect The movement of the device?",
"I want to detect a movement like a Moo Box, I reverse the phone and when I turn it back it fire an action...\nFor Android.\nWhat is the best way\n\nIt is possible to custom an event listenner"
] | [
"android"
] |
[
"python3: sum (union) of dictionaries with \"+\" operand raises exception",
"I'd like to avoid the update() method and I read that is possible to merge two dictionaries together into a third dictionary using the \"+\" operand, but what happens in my shell is this:\n\n>>> {'a':1, 'b':2}.items() + {'x':98, 'y':99}.items()\nTraceback (most recent call last):\n File \"<pyshell#84>\", line 1, in <module>\n {'a':1, 'b':2}.items() + {'x':98, 'y':99}.items()\nTypeError: unsupported operand type(s) for +: 'dict_items' and 'dict_items'\n>>> {'a':1, 'b':2} + {'x':98, 'y':99}\nTraceback (most recent call last):\n File \"<pyshell#85>\", line 1, in <module>\n {'a':1, 'b':2} + {'x':98, 'y':99}\nTypeError: unsupported operand type(s) for +: 'dict' and 'dict'\n\n\nHow can I get this to work?"
] | [
"python",
"python-3.x",
"dictionary",
"dictview"
] |
[
"JMeter - Wrong number of users in results from remote load testing",
"I was using non-GUI mode to perform a remote load testing with Jmeter from master server (Linux) to 5 slave servers (Linux). 5x \"n\" users have been run, \"n\" users on each server.\nThe results have been written to master server. \nThere are samples from all servers in results file but they relate to the number of active users from particular servers (\"n\") and not from all servers (5x \"n\").\nThere are no information in the result file about the real number of active users on all the servers.\nAs a result, a maximum number of active users is \"n\" on generated graphs which does not reflect the real load (5x \"n\" users).\nHas anyone got a similar problem?\nIs there anything I can do to correct the results already gathered?\nShould I change any JMeter parameter to get the correct results in the next run?"
] | [
"jmeter"
] |
[
"What is the disadvantage of using a bulk enabled connection for non bulk operations",
"There are lots of articles on how to use Sybase Open Client bulk interface saying that it will only work if the connection used is \"bulk enabled\". Which begs the question why wouldn't I always create connections that are bulk enabled, even if I may not use them for bulk operations. I can't find anything that talks about this."
] | [
"sap-ase"
] |
[
"R - Calculate difference for each first value in group",
"I have the following dataframe in R:\n#dataframe\ndata <- cbind.data.frame(Line = 1:6,\n Group = c(rep("A", 3), rep("B", 3)),\n Value = c(1, 2, 4, 1, 2, 3))\n\nSo the table looks like this:\nLine Group Value\n1 A 1\n2 A 2\n3 A 4\n4 B 1\n5 B 2\n6 B 3\n\nNow I want to calculate for each group, the difference to the first value in the group (which is a control value),\nso:\nLine 1 - Line 1\nLine 1 - Line 2\nLine 1 - Line 3\nLine 4 - Line 4\nLine 4 - Line 5\nLine 4 - Line 6\n\nI think this should work in a loop but I wanted to ask if there is maybe an easier way to that calculation?\nThank you very much!"
] | [
"r",
"dplyr"
] |
[
"Spring Data JPA & MyBatis",
"I am trying to use Spring Data JPA with MyBatis. Since there isnt a Vendor Adapter for MyBatis, what is the alternative here?\n\n<bean id=\"entityManagerFactory\"\n class=\"org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean\">\n <property name=\"dataSource\" ref=\"dataSource\" />\n <property name=\"packagesToScan\" value=\"com.abc.xyz.domain\"/>\n</bean>\n\n\nI am getting the below exception when I tried to initialize my application.\n\nInvocation of init method failed; nested exception is java.lang.IllegalArgumentException: No PersistenceProvider specified in EntityManagerFactory configuration, and chosen PersistenceUnitInfo does not specify a provider class name either\n\n\nThanks"
] | [
"java",
"spring-data-jpa",
"mybatis",
"spring-mybatis"
] |
[
"Allow user to install 32bit version on 64bit windows",
"I have a simple inno-setup script that allows my setup to install either the 32bit or 64bit version of my program based on the Is64BitInstallMode value. This works great, but I'd like to give users the option to install the 32bit version even if they are on 64bit Windows. I'd like the choice to be made before choosing the application install path so that it can default to either the 32bit or 64bit program files folder based on their choice. I'd also like to avoid the question entirely if they are on 32bit windows. I've been playing with the various features, but haven't figured a way to do it yet. If I can't do it easily I'll just do two separate installs (and I'm trying to decide what makes the most sense!) Any suggestions are greatly appreciated!"
] | [
"windows",
"32bit-64bit",
"inno-setup"
] |
[
".net create user interactive flow charts and workflow diagrams",
"I am trying to develop a new asp.net system (c#/ vb) that:\n\n\nAllows users to: draw workflow / flow chart diagrams (have boxes / circles connectors etc), edit / create them.\nEach part of the workflow ie box will be able to have a name, description and have files uploaded against it. \nThen once the user has created the flow along with providing all the details needed for it ie files descriptions etc i will need to be able to redraw the diagram when they choose to view / edit it.\n\n\nI have been searching and searching along with trying examples but I can't get even the basic drawing and saving to work. I have seen in orchard CMS that there is a new module workflow, by Sébastien. This looks very good and I would like to try and do similar but only for the drawing / charting I don't need to be able to create a user interactive workflow, just the diagram with details against each node/ entity\n\nAny help will be greatly appreciated!\n\nThanks, Jon"
] | [
"jquery",
".net",
"asp.net-mvc",
"orchardcms"
] |
[
"Tensorflow stuck for seconds at the end of every epoch",
"I'm training a Neural Network over a TFRecordDataset. However, at the end of every epoch, i.e. with ETA: 0s, the training gets stuck for tens of seconds. For reference, one epoch takes around a minute to be completed over a dataset of around 25GB (before parsing a subset of the features).\nI'm running TensorFlow 2.3.1 with a Nvidia Titan RTX GPU. Is this the intended behavior? Maybe due to the preprocessing in the input pipeline? Is that preprocessing performed by the CPU only or offloaded to the GPU? Thanks!"
] | [
"python",
"tensorflow",
"keras",
"dataset",
"nvidia"
] |
[
"simple search algorithm in excel spread sheet",
"I have a table full of wights, first cells in rows are prices and columns header is numbers from 1 to 10 .. something like this:\n\n 1 2 3 4 5 6 ..\n1$ 1g 9g 7g\n\n2$ 4g 6g 8g 0g 0g 3g\n\n3$ 4g 6g 8g 0g 0g 3g\n\n4$ 4g 6g 8g 0g 0g 3g\n\n.\n.\n\n\nI need to write a small algorithm in this sheet in excel that takes 2 params (param1,param2)\nparam1 to filter some columns and param 2 to filter some rows and then pick the appropriate weight needed.. I am not asking about the algorithm, but I am asking how can I do it in in excel, my office skills are none existed, so if I need macro, could u please give me a good link that explains macro instructions read ranges of cells and things like that .."
] | [
"excel",
"vba"
] |
[
"How to facilitate extremely long rebalances in Apache Kafka",
"I'm writing a kafka consumer that batches the incoming records and flushes them periodically to durable storage.\nThe nature of the storage system is such that flushes can take a long time - occasionally more than a minute.\nComplicating things somewhat, the way I'm partitioning the data as I batch it does not match the partitioning within kafka, so there is a many-to-many relationship between kafka partitions and storage files.\nThe requirement for this application is at-least-once semantics, minimizing duplicates to the extent possible, but never committing an offset for a kafka partition until all batches containing earlier messages from the same partition have been flushed to storage.\nThis is all fairly straightforward until the time comes to rebalance, at which point I need to commit wait for pending flushes to complete and then commit whatever offsets I can in the rebalance listener.\nGiven this, is there any way for me to tune the consumer configuration to allow onPartitionsRevoked to run for up to a few minutes? What exactly must I do to permit this?\nI understand that my consumer group will not process any records for as long as the rebalance is in progress. I am ok with this (though I'm open to any suggestions for alternative means of handling a rebalance in a less hamfisted fashion)."
] | [
"java",
"apache-kafka",
"kafka-consumer-api"
] |
[
"Node Js Async Await giving first response Empty",
"I am New To async/await coding in node js. I am trying to fetch data from mongodb and then populate the result into an object. But I am facing a bizarre issue here when I exit the server and turn it back on and then hit the API in node js the first response is always empty. I start getting the response as soon as I hit the API after 1st attempt below is my code\n\nlet resu={};\n\nrouter.get('/getTarrifDetails',async (req,res,next) => {\n await Tarrif.find().distinct('tarrif_type',(err,docs) => {\n docs.forEach(async (ele) => {\n let count= User.countDocuments({tarrif_type:ele});\n result.push(ele);\n result[ele] = await count;\n result.push(count);\n });\n });\n\n getAll(res);\n});\n\nasync function getAll(res) {\n if(await resu.length!=0) {\n res.send(resu);\n }\n}"
] | [
"node.js",
"async-await"
] |
[
"Using slidingmenu(jfeinstein10),how could know if the slidingmenu is shown(some method don't take effect)",
"Using slidingmenu(jfeinstein10),how could know if the slidingmenu is shown(some method don't take effect).\nI want to know the status of the slidingmenu ,I have already tried:\n\n Log.d(\"slidingMenu.isShown()\", slidingMenu.isShown()+\"\");\n Log.d(\"slidingMenu.isShown()\", slidingMenu.getVisibility()+\"\");\n Log.d(\"slidingMenu.isShown()\", slidingMenu.isActivated()+\"\");\n Log.d(\"slidingMenu.hasFocus()\", slidingMenu.hasFocus()+\"\");\n Log.d(\"slidingMenu.hasFocusable()\", slidingMenu.hasFocusable()+\"\");\n Log.d(\"slidingMenu.hasWindowFocus()\", slidingMenu.hasWindowFocus()+\"\");\n Log.d(\"slidingMenu.isActivated()\", slidingMenu.isActivated()+\"\");\n Log.d(\"slidingMenu.isClickable()\", slidingMenu.isClickable()+\"\");\n Log.d(\"slidingMenu.isEnabled();\", slidingMenu.isEnabled()+\"\");\n Log.d(\"slidingMenu.isFocusable()\", slidingMenu.isFocusable()+\"\");\n Log.d(\"slidingMenu.isFocused()\", slidingMenu.isFocused()+\"\");\n Log.d(\"slidingMenu.isSlidingEnabled()\", slidingMenu.isSlidingEnabled()+\"\");\n Log.d(\"slidingMenu.isSelected()\", slidingMenu.isSelected()+\"\");\n\n\nBut no matter the menufragment is shown or gone,these methods return the same value."
] | [
"android",
"slidingmenu"
] |
[
"Terminal retains bg color after closing vim - using color scheme and putty-256color term",
"After closing an app that uses color formatting (e.g. vim) the terminal retains some properties like background color.\nThis happens only when using putty-256color or screen term.\nI'm observing similar behavior in RHEL 6.5 and Ubuntu 14.04LTS.\n\nThe only solution is to reset the terminal.\n\nWhen using xterm-256color term (also w/ Putty terminal emulator) the problem isn't present.\n\nIs there a solution/explanation why this happens and what could I be loosing when using xterm under Putty terminal emulator, i.e. would it be preferable to actually use putty-256color or xterm-256color term?"
] | [
"vim",
"putty",
"xterm",
"256color"
] |
[
"Correct way to reconnect to database after disconnect using Qt and QSqlDatabase",
"What is the correct way to reconnect to database using Qt4 upon disconnect?\n\nI'm using Sql Server 2012 over ODBC. If I detect disconnection using SELECT 1 query, and then do\n\ndb.close();\ndb.open()\n\n\nI receive exceptions on other opened SqlQueries (in driver) which are trying to use next() method.\n\nIf I do nothing with database, only trying to execute new queries using the same database - any exec() returns false with warning \"Connection error\"."
] | [
"qt",
"reconnect",
"qsqldatabase",
"disconnection"
] |
[
"git : How to uncomment the default commit message text?",
"The default git commit message is :\n\n# Please enter the commit message for your changes. Lines starting\n# with '#' will be ignored, and an empty message aborts the commit.\n# On branch master\n# Changes to be committed:\n# (use \"git reset HEAD <file>...\" to unstage)\n#\n# modified: file1\n# modified: file2\n#\n\n\nThat's fine for me. But by default, I would prefer to have some lines uncommented :\n\n# Please enter the commit message for your changes. Lines starting\n# with '#' will be ignored, and an empty message aborts the commit.\n On branch master\n# Changes to be committed:\n# (use \"git reset HEAD <file>...\" to unstage)\n\n modified: file1\n modified: file2\n#\n\n\nso I don't have to uncomment them each time.\nIs it possible ?\n\nThanks"
] | [
"git"
] |
[
"How Spring aspects work internally?",
"Say Service calls Dao class on which logging aspect(annotational) needs to be applied. I am wondering how\naspects actually gets applied. \n\nAs per my understanding at the time of DAO injection under Service object, spring finds out that there is some \naspect(in this case logging) is configured for DAO, so it injects the proxy object instead of actual target object.\nNow when actual call is made to any method inside DAO, proxy applies the aspects and then call the actual target\nobject. Is that correct ? Also i believe this is called Run time weaving. \n\nOn the other hand same can be done with load time weaving(with javaagent configuration) where byte code manipulation\nis done for classes on which aspects needs to be applied. So proxy does not come into picture here.\n\nPlease correct me if i am wrong as this is the foundation for all spring modules?"
] | [
"java",
"spring",
"aspectj",
"spring-aop"
] |
[
"How to move button to random position? (Swift)",
"I'm creating a very simple app for iPhone.\n\nJust don't know how to make the button (image) move to random position (but on the screen) when it's touched, in Swift.\n\nI'm using Xcode 6."
] | [
"ios",
"xcode",
"swift",
"uikit"
] |
[
"Jquery Smooth scroll in AngularJS1.0.7",
"is it possible to do Smooth Scroll with Jquery 1.10.2 in AngularJs 1.0.7? I have tried many examples, but none of them are working. I think I have always the same issue. \n\nAccording to this example: https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_eff_animate_smoothscroll\n\nI have:\n\n<body ng-cloak>\n<script src=\"//code.jquery.com/jquery-1.10.2.min.js\"></script>\n<script src=\"//code.jquery.com/ui/1.10.3/jquery-ui.min.js\"></script>\n...\n<a href=\"#section2\">Click Me to Smooth Scroll to Section 2 Below</a>\n...\n<div id=\"section2\">\n ...\n<script>\n $(document).on('click', 'a[href^=\"#\"]', function (event) {\n event.preventDefault();\n\n $('html, body').animate({\n scrollTop: $($.attr(this, 'href')).offset().top\n }, 500);\n });\n</script>\n</body>\n\n\nThis is not working. I think it´s because Angular is parsing the link. Any ideas? I know there are a couple of directives but not working for me neither. I would like to approach it with Jquery."
] | [
"javascript",
"jquery",
"angularjs"
] |
[
"KnockoutJS and Autocomplete Saving both Value and Selected Text",
"I'm using the KnockoutJS Autocomplete code found here:\n\nHow to create an auto-complete combobox?\n\nGenerally it's working just fine. I'm using a JQuery Ajax call to get the data for the Autocomplete. When I type into the input field, then select a value from the list, the corresponding value is set in the Knockout ViewModel. However, I can't get it to set the selected text value from the autocomplete.\n\n(This is to be able to look up SIC numbers, given a partial description)\n\nI have defined:\n\nfunction Sic(SICCode, SICDescription) {\n var self = this;\n self.SICCode = ko.observable(SICCode);\n self.SICDescription = ko.observable(SICDescription);\n}\n\n\nMy ViewModel has:\n\n self.SICCode = ko.observable(\"\");\n self.SICDescription = ko.observable(\"\");\n self.SicCodes = ko.observableArray();\n\n\nand the lookup function is:\n\n self.getSicCode = function (searchTerm, sourceArray) {\n $.getJSON(_serviceURL + \"/GetSicFromDescription/\" + searchTerm, function (data) {\n if (data.length > 0) {\n var result = [];\n $.map(data, function (item) {\n result.push(new Sic(item.SicCode, item.Description));\n });\n sourceArray(result);\n }\n });\n }\n\n\nIn the input tag (it's actually a .NET page (and actually a DotNetNuke custom module, but that doesn't matter for this) ) I have:\n\n <div>SIC:<br />\n <input type=\"text\" maxlength=\"30\" \n data-bind=\"value: SICDescription, \n jqAuto: {minLength: 3, autoFocus: true}, jqAutoQuery:getSicCode,\n jqAutoSource: SicCodes, jqAutoSourceLabel: SICDescription, \n jqAutoValue: SICCode, jqAutoSourceInputValue: 'SICDescription', \n jqAutoSourceValue: 'SICCode'\" />\n <span data-bind=\"text: SICCode\"></span>\n </div>\n\n\n(I've tried with and without the value: binding) Typing into the input box will correctly do the lookup and present the list of matching items. I can then select one and see the corresponding number in the span.\n\nHowever, when I then click a button that then sends the ViewModel data to the server, the self.SICDescription() is empty... self.SICCode() contains the correct value.\n\nSo, how do I get the selected description populated into the ViewModel? I would have assumed using the value binding for the input field should have done the trick. But no go.\n\nIs there anyway to do what I need, or am I going to have to do some work around (looping through the array of returned values and pluck out the right description)?\n\nThanks."
] | [
"knockout.js",
"jquery-ui-autocomplete"
] |
[
"Can I reduce code in repeat declarations?",
"Is there a way to reduce code for repeat declarations in Obj-C?\n\nE.g.:\n\nI have \n\n localNotification.fireDate = self.dueDate;\n localNotification.timeZone = [NSTimeZone defaultTimeZone];\n localNotification.alertBody = self.text;\n localNotification.soundName = UILocalNotificationDefaultSoundName;\n\n\nCan it be simplified to something like this?\n\n localNotification\n .fireDate = self.dueDate;\n .timeZone = [NSTimeZone defaultTimeZone];\n .alertBody = self.text;\n .soundName = UILocalNotificationDefaultSoundName;\n\n\nThanks!"
] | [
"ios",
"objective-c",
"cocoa-touch"
] |
[
"FiddlerCore - Multithreading webbrowser, getting same session",
"I am with a very specific question, and I'll try to explain the best I can. I'm using windows forms, with webbrowser, multithread and fiddler.\n\nMy application executes different forms in multiple threads. There is an webbrowser on each form, that is running at the same time as the other webbrowsers on the other forms.\nEach of them uses fiddlercore, and some of them navigate to the same website, searching for some information.\n\nIn the fiddlercore code, I use the event FiddlerApplication_AfterSessionComplete to capture all the traffic from the website (on each of the webbrowsers). \n\nThe main problem is that fiddler doesn't distinguish from which thread I'm navigating, so sometimes it takes the information that's supposed to be on another thread to the form that's navigating to the same page, but searching another things.\n\nSo, what I really need is a way to check if the Session I got from fiddler is the same as launched from that specific form.\n\nIf you need, I can post some code, but I don't think it's actually necessary.\n\nI appreciate any help."
] | [
"c#",
"multithreading",
"webbrowser-control",
"fiddlercore"
] |
[
"Better way to add types to props in a functional component in NextJS Typescript project",
"I want to add types when there are multiple props. For ex:\nexport default function Posts({ source, frontMatter }) {\n...\n}\n\nOne way I found is to first create wrapper type and then create parameter type. For ex:\ntype Props = {\n source: string;\n frontMatter: FrontMatter;\n};\n\ntype FrontMatter = {\n title: string;\n author: string;\n date: string;\n};\n\n\nexport default function Posts({ source, frontMatter }:Props) {\n...\n}\n\nBut is there a way to avoid that extra Props type because I'm using that for only this function. I'm hoping to achieve something like this:\nexport default function Posts({ source:string, frontMatter:FrontMatter }) {...}"
] | [
"reactjs",
"typescript",
"next.js"
] |
[
"how to make a clr-datagrid selectable (single/multi) dynamically?",
"Here's an outline of a component called \"my-clr-list\" that uses clarity datagrid like:\n\n<clr-datagrid>\n bunch of clr-dg-column definitions...\n <clr-dg-row *clrDgItems=\"let user of users$ | async\">\n <clr-dg-action-overflow>\n bunch of buttons...\n <\\clr-dg-action-overflow>\n bunch of <clr-dg-cell> ...\n </clr-dg-row>\n <footer>\n</clr-datagrid>\n\n\nI want to be able to pass a boolean input to this component based on which I can dynamically(load time) add\n\n[(clrDgSingleSelected)]=\"selectedUser\"\n[clDgRowSelection]=\"true\"\n\n\nto the clr-datagrid. \n\nI am able to achieve this by duplicating the clr-datagrid using *ngIf, but is there another way to add the options dynamically?"
] | [
"vmware-clarity"
] |
[
"Mark one of the elements in xsd mandatory (soap) and both element can also be present",
"I have schema where I want either of element is mandatory and they should not repeat.\n\nEDITED -- Here valid request can contain both query and id in request or with only query or id element is also valid.\ne.g:\n\n <soapenv:Body>\n <ws:SomeOperation>\n <SoapOperation>\n <query>test</query>\n <id>1</id>\n </SoapOperation>\n </ws:SomeOperation>\n </soapenv:Body>\n\n\nValid Requests:\n\n\nwith query and id element.\nwith only query element.\nwith only id element.\n\n\nInvalid Requests:\n\n\nwithout query and id element.\nwith multiple query element.\nwith multiple id element.\n\n\nI want query or id must be present. One of them is mandatory. \nI tried below things:\n\n<xs:sequence>\n <xs:element minOccurs=\"0\" name=\"id\">\n <xs:simpleType>\n <xs:restriction base=\"xs:string\">\n <xs:minLength value=\"1\" />\n </xs:restriction>\n </xs:simpleType>\n </xs:element>\n <xs:element minOccurs=\"0\" name=\"query\">\n <xs:simpleType>\n <xs:restriction base=\"xs:string\">\n <xs:minLength value=\"1\" />\n </xs:restriction>\n </xs:simpleType>\n </xs:element> \n</xs:sequence>\n\n\nHere the problem is none of them is mandatory and making any one as minoccurs=1 will make that field mandatory ( e.g. if i mark id as minoccurs=1 then id field is mandatory but my valid request can have only query and not id) and there can be possibility of both tags to be present as well.\n\nAlso I tried choice tag.\n\nUsing simple choice with will make these tags repeat which also i do not want. The tag should not repeat."
] | [
"soap",
"xsd"
] |
[
"Comments for multiple objects",
"I have 2 objects (articles, products) for which I will have comments. How can I store comments for both objects?\n\nWhat is a better solution: create an object for each new table (article_comments, product_comments) or store comments in one table and create a new table for each object contains a link between the object table and comments table?"
] | [
"mysql"
] |
[
"Unable to get WCF service authentication working with IIS 6.0",
"I am going to try to keep this question as brief as possible since the problem is a little tricky to explain for me. Please ask any queries if something is left unclear. So here you go,\n\nThis is the error message I have been getting for a while as I am working on this,\n\"The HTTP request is unauthorized with client authentication scheme 'Ntlm'. The authentication header received from the server was 'Negotiate,NTLM'. The remote server returned an error: (401) Unathorized\"\n\nI have two Windows boxes, Box1 and Box2. I have 2 WCF services (ServiceA and ServiceB) hosted in IIS 6 on each of them. Functionally, ServiceA talks to db only. ServiceB talks to ServiceA and gets results. Both services have anonymous access and Integrated Windows authentication enabled. ServiceA runs under Application pool ServiceAPool and ServiceB runs under ServiceBPool. Each of these app pools have configured identity of a domain user. \nThese app pools are exactly same on Box1 and Box2.\n\nFirst, My client application (just a small console app), calls ServiceA on Box1 with my Windows credentials. It works.\n\nSecond, My client application , calls ServiceB on Box1 with my Windows credentials. This ServiceB calls ServiceA internally with domain user (app pool identity) It works.\n\nThe Second point I mentioned above does not work on Box2, it gives the above error. Just to be clear, the service code including web.config file etc is exactly same on both boxes. The domain user for app pool is the same. Both boxes are on same domain.\n\nWhat I have observed is (probably), on Box2, when I call ServiceA with my windows credentials, it works, but when there is a hop between services with some other domain account (like my app pool account) it fails with the error above.\n\nIf anyone has seen such kind of behavior please share some information."
] | [
"wcf",
"iis"
] |
[
"Google Play Store Release Issue",
"I am trying to release a new version of my Android App.\nI can upload the APK file but after I click the \"Review\" Button I am getting below error.\n\nReview summary\nErrors\n\nResolve these errors before starting the rollout of this release.\nYou can't rollout this release because it doesn't allow any existing users to upgrade to the newly added APKs.\n\nPlease note that this app was developed using CORDOVA\n\nThe app version details are as below image. The only difference from the previous and this new version is the Target SDK is changed from 24 to 26\n\nCan someone please give some idea to fix this issue. Thanks for your help"
] | [
"android",
"cordova",
"google-play",
"cordova-3"
] |
[
"Mongoose updates a field with null value throws exception",
"Here is the model definition:\n\npricing: { type: Number, default: null }\n\n\nthis is the exception I get when Mongoose tries to update a record with the source data being null:\n\nError message I got:\n\n message: 'Cast to number failed for value \"NaN\" at path \"pricing\"',\n name: 'CastError',\n type: 'number',\n value: NaN,\n path: 'pricing'\n\n\nI do need to update the existing value with null for this case since the application treat the field to be a null-able Number field.\n\nHow to fix it? Thanks in advance!"
] | [
"node.js",
"mongoose"
] |
[
"How to change auto generated cs file in asp.net",
"I have an autogenerated class from entity framework I have changed the type from a string to long in the database along with the name as well thereafter transformed the templates and rebuilt the project however I get an error \"The 'Phase' property on 'PropertyDescription' could not be set to a 'Int64' value. You must set this property to a non-null value of type 'String'. \"\n\nSo it is my thinking that it needs to be changed in the autogenerated cs file somehow but everytime that I change it manually and regenerate the T4 templates it gets over written."
] | [
"asp.net",
"entity-framework"
] |
[
"How to run Jupyter notebook and Tensorboard at the same time inside virtualenv?",
"I already found its workaround inside Docker. But, in my case, I am running TensorFlow inside virtualenv so that I could run my Jupyter notebook to make a code and to run it.\n\nBut I also needed to run the Tensorboard. How can I run two web application inside virtualenv? I have never run two things at the same time. If I want to, I don't know how to run it in a background."
] | [
"tensorflow",
"virtualenv"
] |
[
"Azure Mobile App Not Available Among Existing Apps",
"Back in March 2015, Microsoft announced that \"Azure Mobile Apps\" are replacing \"Azure Mobile Services.\" A few days ago, I spotted the documentation explaining how to create an Azure Mobile App. I followed the doc and successfully got my \"TestDroid\" mobile app service running locally. However, I cannot publish the app to Azure from Visual Studio 2015 Community Edition.\n\nTo publish my \"TestDroid\" app, I right-clicked on the project and selected \"publish.\" \n\n\n\nThis dialogue is already the \"first sign of trouble.\" Technically my Mobile App service does not match any of the categories shown in the above dialogue. Still, because Web Apps and Mobile Services have been merged into one, the best choice is \"Microsoft Azure Web Apps.\" So that is the choice I made...\n\nUnfortunately, Visual Studio 2015 CE does not show my already-provisioned \"TestDroid\" app as an option:\n\n\n\nHowever, I know that it exists because I created it a day earlier, per the instructions, and it does appear in a resource group blade on the Azure portal:\n\n\n\nAlso, in the Visual Studio \"Server Explorer\" I can see the \"TestDroid\" service:\n\n\n\nThe Server Explorer entry for \"Mobile Services\" is empty, but in this case I expect it to be empty because, as already stated, creating a \"Mobile Service\" is now considered the old way, and creating a \"Mobile App\" is the new way. \n\nI'm guessing this is merely a glitch in preview material, but I would like to know how to resolve this."
] | [
"visual-studio",
"azure",
"visual-studio-2015",
"azure-web-app-service"
] |
[
"Is there a way to install the .NET 3.5 Framework without rebooting?",
"I have been writing a GUI application for rsync on Windows and I have been deploying it to servers. \n\nI have a problem because I use the .NET framework, and server does not have it installed, and the 3.5 framework requires the server to be rebooted after installation. This is not acceptable. Does 2.0 require this same behavior or can I avoid it? If not, is there a way to bypass the forced reboot?"
] | [
".net"
] |
[
"Continuous columns sum based on another column in sql server",
"I have data like below\n\n\n\n\nAppName\nStart\nFinish\nTotaltime\n\n\n\n\nMS Word\n2021-02-28 7:30:25\n2021-02-28 7:31:25\n1\n\n\nMS Word\n2021-02-28 7:31:26\n2021-02-28 7:33:25\n2\n\n\nMS Word\n2021-02-28 7:33:27\n2021-02-28 7:35:25\n2\n\n\nMS Word\n2021-02-28 7:35:28\n2021-02-28 7:37:25\n2\n\n\nGoogle Chrome\n2021-02-28 7:37:29\n2021-02-28 7:39:25\n2\n\n\nWindows Explorer\n2021-02-28 7:39:30\n2021-02-28 7:41:25\n2\n\n\nWindows Explorer\n2021-02-28 7:41:31\n2021-02-28 7:43:25\n2\n\n\nMS Word\n2021-02-28 7:43:32\n2021-02-28 7:45:25\n2\n\n\nMS Word\n2021-02-28 7:45:33\n2021-02-28 7:47:25\n2\n\n\nGoogle Chrome\n2021-02-28 7:47:34\n2021-02-28 7:49:25\n2\n\n\nGoogle Chrome\n2021-02-28 7:49:35\n2021-02-28 7:51:25\n2\n\n\nGoogle Chrome\n2021-02-28 7:51:36\n2021-02-28 7:53:25\n2\n\n\nMicrosoft Excel\n2021-02-28 7:53:37\n2021-02-28 7:55:25\n2\n\n\n\n\nand need the coninuoues column Totaltime sum based on App name\noutput something like this\n\n\n\n\nAppName\nStart\nFinish\nTotaltime\n\n\n\n\nMS Word\n2021-02-28 7:30:25\n2021-02-28 7:37:25\n7\n\n\nGoogle Chrome\n2021-02-28 7:37:29\n2021-02-28 7:39:25\n2\n\n\nWindows Explorer\n2021-02-28 7:39:30\n2021-02-28 7:43:25\n4\n\n\nMS Word\n2021-02-28 7:43:32\n2021-02-28 7:47:25\n4\n\n\nGoogle Chrome\n2021-02-28 7:47:34\n2021-02-28 7:53:25\n6\n\n\nMicrosoft Excel\n2021-02-28 7:53:37\n2021-02-28 7:55:25\n2"
] | [
"sql",
"sql-server"
] |
[
"VBA Save As Current Filename +01",
"I'm looking to write a macro to save my current version filename +1 instance of the version. For each new day the version would reset to v01. Ex. Current = DailySheet_20150221v01; Save As = DailySheet_20150221v02; Next Day = DailySheet_20150222v01\n\nWhile increasing the version number, I am hoping the version won't have to contain the v0 once v10+ has been reached.\n\nI was able to workout how to save the file with today's date:\n\nSub CopyDailySheet()\n\nDim datestr As String\n\ndatestr = Format(Now, \"yyyymmdd\")\n\nActiveWorkbook.SaveAs \"D:\\Projects\\Daily Sheet\\DailySheet_\" & datestr & \".xlsx\"\n\nEnd Sub\n\n\nbut need additional help in finding the version addition. Could I set the SaveAs to a string, then run it through a For/If - Then set?"
] | [
"vba",
"excel",
"iteration",
"filenames",
"save-as"
] |
[
"clear cache in Nightmare.js (Electron)",
"I'm using nightmare js to log into a site that sets a token in local storage. However, any future tests I run the user is already logged in. I'm guessing the local storage wasn't cleared. Is there any way to do this? My code in test.js\n\nrequire('mocha-generators').install();\n\nvar Nightmare = require('nightmare');\nvar expect = require('chai').expect;\n\ndescribe('test login', function() {\n var nightmare = Nightmare({show: true})\n\n after(function*() {\n yield nightmare.end();\n })\n\n it('should login given right credentials', function*() {\n this.timeout(50000);\n console.log(\"running test\");\n var link = yield nightmare\n .goto('http://127.0.0.1:3000/login')\n .wait(1000)\n .type('.email-field', '[email protected]')\n .type('.password-field', 'password')\n .click('.login button')\n .wait(1000)\n\n });\n})\n\n\nI run the test using: mocha\n\nthe test runs fine and closes. However when I run again the user starts off as logged in. Is there anyway to clear the cache or local storage in nightmarejs?\n\nElectron has a way to clear session info via session.clearCache (http://electron.atom.io/docs/v0.32.0/api/session/) but I don't know how to access the session object from nightmare."
] | [
"javascript",
"local-storage",
"electron",
"nightmare"
] |
[
"Need help downloading a file using java in my app, it tries but quickly disappears",
"I am trying to download a zip file and save it to the sdcard.\n\nI have a button with the id \"download\"\n\nWhen I click the button, the dialog shows up and quickly disapears.\n\nHere's what the code section looks like.\n\npublic static final int DIALOG_DOWNLOAD_PROGRESS = 0;\nprivate ProgressDialog mProgressDialog;\n\npublic void download(View view) {\n switch (view.getId()) {\n case R.id.download:\n startDownload();\n }\n}\n\nprivate void startDownload() {\n String url = \"https://mydownloadurl\";\n new DownloadFileAsync().execute(url);\n}\n\n@Override\nprotected Dialog onCreateDialog(int id) {\n switch (id) {\n case DIALOG_DOWNLOAD_PROGRESS:\n mProgressDialog = new ProgressDialog(this);\n mProgressDialog.setMessage(\"Downloading file..\");\n mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n mProgressDialog.setCancelable(false);\n mProgressDialog.show();\n return mProgressDialog;\n\n default:\n return null;\n }\n}\n\nclass DownloadFileAsync extends AsyncTask<String, String, String> {\n @Override\n protected void onPreExecute() {\n super.onPreExecute();\n showDialog(DIALOG_DOWNLOAD_PROGRESS);\n }\n\n @Override\n protected String doInBackground(String... aurl) {\n int count;\n try {\n URL url = new URL(aurl[0]);\n URLConnection conexion = url.openConnection();\n conexion.connect();\n int lenghtOfFile = conexion.getContentLength();\n Log.d(\"ANDRO_ASYNC\", \"Lenght of file: \" + lenghtOfFile);\n InputStream input = new BufferedInputStream(url.openStream());\n OutputStream output = new FileOutputStream(\"/sdcard/mydownload.zip\");\n byte data[] = new byte[1024];\n long total = 0;\n while ((count = input.read(data)) != -1) {\n total += count;\n publishProgress(\"\" + (int)((total * 100) / lenghtOfFile));\n output.write(data, 0, count);\n }\n\n output.flush();\n output.close();\n input.close();\n }\n catch (Exception e) {\n }\n return null;\n }\n\n protected void onProgressUpdate(String... progress) {\n Log.d(\"ANDRO_ASYNC\",progress[0]);\n mProgressDialog.setProgress(Integer.parseInt(progress[0]));\n }\n\n @Override\n protected void onPostExecute(String unused) {\n dismissDialog(DIALOG_DOWNLOAD_PROGRESS);\n }\n\n\nAnd the only thing that shows in the logcat is\n\n\n 17586-17586/com.tyler.myapp D/qdmemalloc: ion: Mapped buffer base:0x6da9b000 size:1892352 offset:0 fd:47\n 17586-17586/com.tyler.myapp D/qdmemalloc: ion: Mapped buffer base:0x4002a000 size:4096 offset:0 fd:52\n 17586-17586/com.tyler.myapp D/OpenGLRenderer: Flushing caches (mode 0)\n 17586-17586/com.tyler.myapp D/qdmemalloc: ion: Unmapping buffer base:0x6da9b000 size:1892352\n 17586-17586/com.tyler.myapp D/qdmemalloc: ion: Unmapping buffer base:0x4002a000 size:4096\n 596-5470/system_process W/InputMethodManagerService: Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@42942fe8 attribute=null, token = android.os.BinderProxy@41dab9b0, pid=17586, inputType=0x(null)"
] | [
"java",
"android"
] |
[
"The alpha value doesn't work if ArrayList is involved",
"Shorty, I have a ArrayList that stores multiple objects to itself. Everytime when I draw those objects, i also do set the color to a greenish color. My problem is, the alpha value is being somehow completely overseen. Why? (But not the actual Color, so just the alpha value doesn't show up).\n\nI firstly tried to do the ordinary way with setColor method. But that didn't worked. I also wrote a method that made sure that i go over all of the objects. That didn't worked either.\n\nThe usual way to do this: (didn't worked)\n\n\nprivate void drawWatchers(Graphics2D g) {\n for (int i = 0; i < watcher.size(); i++) {\n g.setColor(new Color(46, 139, 87, 150));\n g.fillRect(watcher.get(i).getX(), watcher.get(i).getY(), 30, 30);\n }\n}\n\n\n\nThe code that i have written to be sure that i am going through all the objects\n(didn't worked either)\n\n\npublic Color setColor(int r, int g, int b, int a){\n return new Color(r, g, b, a);\n}\n\n//On the other class:\n\nfor (int i = 0; i < watcher.size(); i++) {\n g.setColor(watcher.get(i).setColor(46, 139, 87, 150));\n g.fillRect(watcher.get(i).getX(), watcher.get(i).getY(), 30, 30);\n}"
] | [
"java",
"arraylist",
"colors"
] |
[
"Is there a way to load an Excel file through Apache POI when the sheet names have invalid characters in them",
"I am being provided with Excel files that seem to have been generated outside of excel and often have '[' or ']' in one of the worksheet names.\n\nPOI doesn't seem to load these files, just throws an error, how can I make Apache-poi load these files and strip out the invalid characters?"
] | [
"java",
"excel",
"apache-poi"
] |
[
"Java and Windows Regional Settings",
"Sorry if this is a re-post. I did not find a suitable answer. \n\nPlease ignore best practices and use of deprecated apis.\n\nI want to format the following date \"Mon May 19 02:16:52 EDT 2003\" into \"MM/dd/yyyy HH:mm:ss\". Again, I only want to change the output format and this is being executed from my laptop which is in EST.\n\nMy Windows Regional Settings are:\n\nCurrent time zone: Eastern Daylight Time\n\nTimezone: (GMT-05:00) Eastern Time (US & Canada)\n\nAutomatically adjust clock for daylight saving changes: Checked\n\nThis java code does it:\n\nDate aDate = new Date(\"Mon May 19 02:16:52 EDT 2003\");\nSimpleDateFormat sdf = new SimpleDateFormat( \"MM/dd/yyyy HH:mm:ss\");\nSystem.out.println(\"Formatted Date: \" + sdf.format(aDate));\n\n\nOutput is\n\nFormatted Date: 05/19/2003 02:16:52\n\n\nNow I change the windows setting to the following (only uncheck the DST setting)\n\nCurrent time zone: Eastern Daylight Time\n\nTimezone: (GMT-05:00) Eastern Time (US & Canada)\n\nAutomatically adjust clock for daylight saving changes: Checked\n\nOutput is:\n\nFormatted Date: 05/19/2003 01:16:52\n\n\nQuestions:\n\n\nWhy is the output off by an hour?\nDoes java use Windows DST settings even when formatting? I though java maintains its own data for DST settings times for various timezones."
] | [
"java",
"date-format",
"dst"
] |
[
"Find Compound Words in List of Words using Trie",
"Given a list of words, I am trying to figure out how to find words in that list that are made up of other words in the list. For example, if the list were [\"race\", \"racecar\", \"car\"], I would want to return [\"racecar\"]. \n\nHere is my general thought process. I understand that using a trie would be good for this sort of problem. For each word, I can find all of its prefixes (that are also words in the list) using the trie. Then for each prefix, I can check to see if the word's suffix is made up of one or more words in the trie. However, I am having a hard time implementing this. I have been able to implement the trie and and the function to get all prefixes of a word. I am just stuck on implementing the compound word detection."
] | [
"python",
"algorithm",
"trie"
] |
[
"How to build a Laravel route that requires a specific URL query parameter?",
"Let's say I have URLs like this:\n\n\nlocalhost/admin/users/ <--- Main Admin Users page\nlocalhost/admin/users/?data=refresh <---- A typical ajax request made from that page\n\n\nAnd a simple controller like this:\n\nclass UsersController extends Controller {\n\n public function index()\n\n // call some services\n // return a view\n }\n\n public function dataRefresh {\n\n // call some services\n // return some JSON\n }\n}\n\n\nAnd here's my routes.php I'm working on:\n\n Route::get('admin/users', array('as' => 'admin.users', 'uses' => 'Admin\\Users\\UsersController@index'));\n Route::get('admin/users????' , array('before' => 'ajax', 'as' => 'admin.users', 'uses' => 'Admin\\Users\\UsersController@dataRefresh'));\n\n\nWhat can I do in my second route to require a URL query parameter ?data and furthermore require it is set to data=refresh? And how do I ensure it doesn't conflict with the other route?\n\nNote:\nI'm aware this may not be considered \"pretty URL\" by some. I do implement pretty URLs / slugs when appropriate, however I also think there are many cases where the query parameters are more clearer and cleaner (ie. give a user a clear understanding of what part of the page's URL is for filtering the data in a datagrid...and assures a user the parameters can be removed without causing the page to break or go missing). Google does this themselves, as well as many other reputable sites.\n\nNote: I have applied an ajax route filter to the second route. I've also set the route to point towards the dataRefresh method in my controller. \n\nThis is as far as I've got. Any ideas?"
] | [
"php",
"laravel",
"laravel-4",
"query-parameters",
"laravel-routing"
] |
[
"Error: need MAIL command when using smtp with perl",
"I was trying to send emails using Mime::Lite perl module and through smtp authentication. But unfortunately that doesn't work. It shows \n\n\n Error: need MAIL command, Error: command not implemented\n\n\nHere is the updated code snippet and Debug output.\n\n#!/usr/bin/perl\nuse warnings;\nuse strict;\nuse MIME::Lite;\nuse Net::SMTP;\nuse MIME::Base64;\n\n\nmy $smtp = Net::SMTP->new(<mail host>,Port=>587,Debug=>1)or die;\n$smtp->starttls();\n$smtp->auth($username,$password) or die $!;\nmy $msg = MIME::Lite -> new ( \n From => '[email protected]',\n TO => '[email protected]', \n Subject => 'Testing Text Message',\n Data => 'How\\'s it going.' );\n\n$smtp->mail(<from mail>);\n$smtp->to(<to mail>);\n$smtp -> data();\n$smtp -> datasend( $msg->as_string() );\n$smtp -> dataend(); \nprint $smtp ->message();\n$smtp -> quit;\n\n\nDebug output:\n\nNet::SMTP>>> Net::SMTP(3.10)\nNet::SMTP>>> Net::Cmd(3.10)\nNet::SMTP>>> Exporter(5.68)\nNet::SMTP>>> IO::Socket::INET6(2.71)\nNet::SMTP>>> IO::Socket(1.36)\nNet::SMTP>>> IO::Handle(1.34)\nNet::SMTP=GLOB(0x1e0a920)<<< 220 email-smtp.amazonaws.com ESMTP SimpleEmailService-2108164273 5RjAQr5ZFI284sDt1KWu\nNet::SMTP=GLOB(0x1e0a920)>>> EHLO localhost.localdomain\nNet::SMTP=GLOB(0x1e0a920)<<< 250-email-smtp.amazonaws.com\nNet::SMTP=GLOB(0x1e0a920)<<< 250-8BITMIME\nNet::SMTP=GLOB(0x1e0a920)<<< 250-SIZE 10485760\nNet::SMTP=GLOB(0x1e0a920)<<< 250-STARTTLS\nNet::SMTP=GLOB(0x1e0a920)<<< 250-AUTH PLAIN LOGIN\nNet::SMTP=GLOB(0x1e0a920)<<< 250 Ok\nNet::SMTP=GLOB(0x1e0a920)>>> STARTTLS\nNet::SMTP=GLOB(0x1e0a920)<<< 220 Ready to start TLS\nNet::SMTP::_SSL=GLOB(0x1e0a920)>>> EHLO localhost.localdomain\nNet::SMTP::_SSL=GLOB(0x1e0a920)<<< 250-email-smtp.amazonaws.com\nNet::SMTP::_SSL=GLOB(0x1e0a920)<<< 250-8BITMIME\nNet::SMTP::_SSL=GLOB(0x1e0a920)<<< 250-SIZE 10485760\nNet::SMTP::_SSL=GLOB(0x1e0a920)<<< 250-STARTTLS\nNet::SMTP::_SSL=GLOB(0x1e0a920)<<< 250-AUTH PLAIN LOGIN\nNet::SMTP::_SSL=GLOB(0x1e0a920)<<< 250 Ok\nDied at test_script.pl line 17.\n\n\nPlease let me know the solution for this.\n\nThank you in advance!"
] | [
"perl",
"email",
"smtp",
"amazon-ses",
"smtp-auth"
] |
[
"Packer images vs Vagrant images",
"Mitchell Hashimoto said somewhere that vagrant should be not used in production. As I understand packer.io is exactly filling that gap - one can build EC2/Rackspace/.. images. What are the underyling differences in terms of virtualization? Both are VM's, but they must be different type of VM's. How does an AWS prebuild image different from a Virtualbox image or VMWare image? Any general hints at the underlying technologies would be appreciated."
] | [
"packer"
] |
[
"find exact numbers of true postive in weka",
"In WEKA, I can easily find the TP Rate and total True Classified Instances from Confusion Matrix but is there any way to see exact number of tp and/or tn?\n\nAnd do you know any way to find these values in matlab-anfis?"
] | [
"matlab",
"statistics",
"machine-learning",
"classification",
"weka"
] |
[
"Add CSV Connection to Excel with c#",
"I have tried many methods, I want to add a csv connection to excel with c#\nthings I have tried:\n\nstring textpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);\nstring path = textpath + \"\\\\filename.csv\"\n\n\n\n\nstring csvconectionstring = \"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=\" + textpath + \";Extensions=asc,csv,tab,txt;\";\n SaturnAddIn.getInstance().Application.ActiveWorkbook.Connections.Add2(\"csv\", csvconectionstring,null, 6, true, false);\n\n\n\n\nstring csvconectionstring = \"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\" + path + \";Extended Properties=\\\"text;HDR=Yes;FMT=Delimited\";\n SaturnAddIn.getInstance().Application.ActiveWorkbook.Connections.Add2(\"csv\", csvconectionstring,null, 6, true, false); \n\n\n\n\nthis is the exception i get\n\nSystem.ArgumentException was unhandled by user code\n HResult=-2147024809\n Message=The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG))\n Source=\"\"\n StackTrace:\n at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData& msgData)\n at Microsoft.Office.Interop.Excel.Connections.Add2(String Name, String Description, Object ConnectionString, Object CommandText, Object lCmdtype, Object CreateModelConnection, Object ImportRelationships)\n at Saturn.DataImportForm.CouchImport() in c:\\Users\\dtaylor\\Documents\\Visual Studio 2013\\Projects\\Saturn\\Saturn\\Saturn\\CouchImport.cs:line 43\n at Saturn.DataImportForm.ImportButton_Click(Object sender, EventArgs e) in c:\\Users\\dtaylor\\Documents\\Visual Studio 2013\\Projects\\Saturn\\Saturn\\Saturn\\DataImportForm.cs:line 41\n at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)\n at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)\n at System.Windows.Forms.Control.WndProc(Message& m)\n at System.Windows.Forms.ButtonBase.WndProc(Message& m)\n at System.Windows.Forms.Button.WndProc(Message& m)\n at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)\n InnerException:"
] | [
"c#",
"excel",
"csv"
] |
[
"Python Runtime Error not working as expected",
"I have an input file as follows \n\n3\n01\n0010100\n11011\n\n\nand the output is supposed to look like this\n\nLIVES\nDIES\nLIVES\n\n\nHowever my code returns,\n\nDIES\n[1, 0]\nDIES\n[0, 1, 0, 0, 0, 1, 0]\nDIES\n[1, 1, 0, 1, 1]\n\n\nI am working with this problem (https://open.kattis.com/problems/whowantstoliveforever). Basically, I am looking at the current value of the bits at positions i−1 and i+1 (if they exist; otherwise assume them to be 0). If my program sees exactly one 1, then the next value of the i-th bit is 1, otherwise it is 0. All the bits change at once, so the new values in the next state depend only on the values in the previous state. The universe is dead if it contains only zeros. \n\nI am trying to say if the program catches infinite loop that probably means the universe will live, 0 and 1s keep repeating continuesly. And if len(set(x)) is 1 then I am returning False. \n\nimport sys\n\n\ndef get_bit(bits, i):\n if 0 <= i < len(bits):\n return int(bits[i])\n else:\n return 0\n\n\ndef print_result(boolean):\n print(\"LIVES\" if boolean else \"DIES\")\n\n\ndef recursion(in_list, output_list):\n try:\n for index in range(len(in_list)):\n if (get_bit(in_list, index-1) == 0 and get_bit(in_list, index+1) == 0) or (get_bit(in_list, index-1) == 1 and get_bit(in_list, index+1) == 1):\n output_list.append(0)\n elif(get_bit(in_list, index-1) == 0 and get_bit(in_list, index+1) == 1) or (get_bit(in_list, index-1) == 1 and get_bit(in_list, index+1) == 0):\n output_list.append(1)\n if len(set(output_list)) == 1:\n return False\n else:\n in_list = output_list\n output_list = []\n recursion(in_list, output_list)\n except RuntimeError:\n return True\n\n\nnum_cases = int(sys.stdin.readline().strip())\nfor i in range(num_cases):\n _list = []\n case = sys.stdin.readline().strip()\n for char in case:\n _list.append(char)\n output_list = []\n print_result(recursion(_list, output_list))\n print(output_list)\n\n\nIs there any way to handle this problem if not except RuntimeError won't work?"
] | [
"python",
"python-3.x",
"python-2.7",
"error-handling",
"runtime-error"
] |
[
"Pytorch CUDA error: invalid configuration argument",
"I recently added a new component to my loss function. Running the new code works on a CPU, but I get the following error when I run it on a GPU, clearly relating to the backward pass:\n\n---------------------------------------------------------------------------\nRuntimeError Traceback (most recent call last)\n<ipython-input-12-56dcbddd5230> in <module>\n 20 recall = Recall(N_RECALL_CAND, K)\n 21 #run the model\n---> 22 train_loss, val_loss = fit(triplet_train_loader, triplet_test_loader, model, loss_fn, optimizer, scheduler, N_EPOCHS, cuda, LOG_INT)\n 23 #measure recall\n\n~/thesis/trainer.py in fit(train_loader, val_loader, model, loss_fn, optimizer, scheduler, n_epochs, cuda, log_interval, metrics, start_epoch)\n 24 scheduler.step()\n 25 # Train stage\n---> 26 train_loss, metrics, writer_train_index = train_epoch(train_loader, model, loss_fn, optimizer, cuda, log_interval, metrics, writer, writer_train_index)\n 27 \n 28 message = 'Epoch: {}/{}. Train set: Average loss: {:.4f}'.format(epoch + 1, n_epochs, train_loss)\n\n~/thesis/trainer.py in train_epoch(train_loader, model, loss_fn, optimizer, cuda, log_interval, metrics, writer, writer_train_index)\n 80 losses.append(loss.item())\n 81 total_loss += loss.item()\n---> 82 loss.backward()\n 83 optimizer.step()\n 84 \n\n/opt/anaconda3/lib/python3.7/site-packages/torch/tensor.py in backward(self, gradient, retain_graph, create_graph)\n 116 products. Defaults to ``False``.\n 117 \"\"\"\n--> 118 torch.autograd.backward(self, gradient, retain_graph, create_graph)\n 119 \n 120 def register_hook(self, hook):\n\n/opt/anaconda3/lib/python3.7/site-packages/torch/autograd/__init__.py in backward(tensors, grad_tensors, retain_graph, create_graph, grad_variables)\n 91 Variable._execution_engine.run_backward(\n 92 tensors, grad_tensors, retain_graph, create_graph,\n---> 93 allow_unreachable=True) # allow_unreachable flag\n 94 \n 95 \n\nRuntimeError: CUDA error: invalid configuration argument\n\n\nHere is a copy of the code that causes it to break in the loss function:\n\ndef forward(self, anchor, positive, negative, model, size_average=True):\n #regular triplet loss. This works on GPU and CPU\n distance_positive = (anchor - positive).pow(2).sum(1) # .pow(.5)\n distance_negative = (anchor - negative).pow(2).sum(1) # .pow(.5)\n losses = F.relu(distance_positive - distance_negative + self.margin)\n\n #the additional component that causes the error. This will run on CPU but fails on GPU\n anchor_dists = torch.cdist(model.embedding_net.anchor_net.anchors, model.embedding_net.anchor_net.anchors)\n t = (self.beta * F.relu(self.rho - anchor_dists))\n regularization = t.sum() - torch.diag(t).sum()\n\n return regularization + losses.mean() if size_average else losses.sum()\n\n\nThe error occurs with a batch size of 1 and on the first backward pass. Answers from here suggest that it has to do with a lack of memory, but my model isn't particularly large:\n\nTripletNet(\n (embedding_net): EmbeddingNet(\n (anchor_net): AnchorNet(anchors torch.Size([128, 192]), biases torch.Size([128]))\n (embedding): Sequential(\n (0): AnchorNet(anchors torch.Size([128, 192]), biases torch.Size([128]))\n (1): Tanh()\n )\n )\n)\n\n\nThe available memory on my GPU is the 8GB, which is much smaller than the model and the size of the cdist result which is 128x128.\n\nI have no idea how to begin debugging this. If it is the case that I'm running out of memory because its keeping track of intermediate states, how do I navigate around this? Any help is appreciated! \n\nEDIT: Monitoring the GPU memory usage shows that I’m well under the memory limit when it crashes."
] | [
"python",
"pytorch"
] |
[
"how to disable sound on push notification?",
"I saw the documentation:\n\npublic Uri sound\n\nAdded in API level 1\nThe sound to play.\n\nTo play the default notification sound, see defaults.\n\n\nbut how do I disable sound playing? sending Uri == null ?"
] | [
"java",
"android",
"push-notification"
] |
[
"Is there a way to reference indexed file entries for future operations?",
"BLUF: I'm trying to write a script that identifies RTS packets with a certain duration and then stripping the Destination MAC out of it and writing it to a file. Then, once the sniff() operation is complete, I'd like to have the script configure my interfaces with those indexed Destination MAC addresses.\nimport os\nimport time\nimport pandas\nimport sys\nfrom scapy.layers.all import Dot11,sniff\niface = "wlan0"\niface2 = "wlan0mon"\niface3 = "wlan1"\niface4 = "wlan1mon"\nap_list = []\n\ndef PacketHandler(pkt):\n if pkt.haslayer(Dot11):\n if pkt.type==1 and pkt.subtype==11:\n if pkt.addr1 not in ap_list:\n ap_list.append(pkt.addr1)\n\nsniff(iface=iface2, filter='wlan[2] == 0x80 && wlan[3] == 0x3e', prn=PacketHandler, count=100)\n\nIs there a way to index the answers (in my situation, I'm only expecting 2 total entries) so that I can follow up with referencing those MAC addresses as indexed items for a 'macchanger -m' command?"
] | [
"python",
"scapy"
] |
[
"Assigning image from assets returns nil",
"let backgroundImage = UIImageView(frame: UIScreen.main.bounds) \nbackgroundImage.image = UIImage(named:\"SignIn\")\nbackgroundImage.contentMode = UIViewContentMode.scaleAspectFill\nself.view.insertSubview(backgroundImage, at: 0)\n\n\nSignIn is name of my imageSet created in assets"
] | [
"swift",
"uiimageview",
"uiimage"
] |
[
"How to keep a div constantly above a single point on the background?",
"I have a div which has a background of a map. The map is centred and has a background size of 'contain'. The page is responsive so when the window resizes, so does the map. I need to be able to have a div on top of a certain country on the map, and on resize of the background map, the div stays directly on top of it.\n\nSo far I have\n\n<div id=\"map-holder\">\n <div class=\"content\">\n <div class=\"placeholder\"></div>\n </div>\n</div>\n\n\nThe div with the class of placeholder is the div i wish to keep on top of a certain country. The div with map-holder for ID is the div with the map background. Content is just to keep it all in place.\n\nCSS\n\n .content { \n text-align: center;\n width: 1200px;\n margin: 0 auto;}\n\n#map-holder {\n position: relative;\n height: 1000px;\n width: 100%;\n background: #F0F0F0;\n background-image: url(../images/image-mapster.min.png);\n background-size: contain;\n background-position: center center;\n background-repeat: no-repeat;\n padding: 30px;\n}\n\n.placeholder {\n position: absolute;\n right: 30px;\n background: #fff;\n width: 80px;\n height: 50px;\n border: 1px solid #000;\n margin: 5px;\n padding: 5px;\n padding: 0;\n cursor: pointer;\n}\n\n.placeholder img {\n width: 100%;\n height: 100%;\n padding: 0;\n}\n\n.placeholder:before {\n position: absolute;\n top: 30%;\n left: 45%;\n font-weight: bold;\n content: '+';\n}"
] | [
"html",
"css"
] |
[
"adb pull file in Arabic Language(UTF-8) encoding",
"i tried to pull it using\n\nadb pull /sdcard/جهات الإتصال.vcf D:/\n\n\nbut when i write it in CMD it's shows as non-understood language \nany ideas please"
] | [
"batch-file",
"cmd",
"adb"
] |
[
"Combination of letters as parameters in python",
"I wondered if there is a way - didn't find in on the internet but I heard it was possible- to get many parameters in a python script as a combination of letters ? I explain myself : if the user wants to send many optional parameters\nExample : If the options are tiger, frog, cat and dog: instead of writing \n\npython ./myScript.py --tiger --frog --cat --dog\n\n\nTo write : \n\npython ./myScript.py --tfcd\n\n\nIs there a way to do that ?\n\nThanks"
] | [
"python"
] |
[
"HTTP Guzzle not returning all data",
"I have created a function that contacts a remote API using Guzzle but I cannot get it to return all of the data available.\nI call the function here:\n$arr = array(\n 'skip' => 0,\n 'take' => 1000,\n);\n$sims = api_request('sims', $arr);\n\nAnd here is the function, where I have tried the following in my $response variable\njson_decode($x->getBody(), true)\n\njson_decode($x->getBody()->getContents(), true)\n\nBut neither has shown any more records. It returns 10 records, and I know there are over 51 available that it should be returning.\nuse GuzzleHttp\\Client;\nfunction api_request($url, $vars = array(), $type = 'GET') {\n $username = '***';\n $password = '***';\n \n //use GuzzleHttp\\Client;\n $client = new Client([\n 'auth' => [$username, $password],\n ]);\n \n $auth_header = 'Basic '.$username.':'.$password;\n $headers = ['Authorization' => $auth_header, 'Content-Type' => 'application/json'];\n $json_data = json_encode($vars);\n $end_point = 'https://simportal-api.azurewebsites.net/api/v1/';\n \n try {\n $x = $client->request($type, $end_point.$url, ['headers' => $headers, 'body' => $json_data]);\n $response = array(\n 'success' => true,\n 'response' => // SEE ABOVE //\n );\n } catch (GuzzleHttp\\Exception\\ClientException $e) {\n $response = array(\n 'success' => false,\n 'errors' => json_decode($e->getResponse()->getBody(true)),\n );\n }\n \n return $response;\n}"
] | [
"php",
"guzzle"
] |
[
"Ajax call fails to receive a list of objects from controller action method",
"Here is my controller\n\n[HttpPost]\npublic JsonResult UpdateCountryDropDownList(string ContinentId)\n{\n HotelContext H = new HotelContext();\n int ContinentID = int.Parse(ContinentId);\n List<Country> Co = H.Country.Where(x => x.ContinentId == ContinentID).ToList();\n List<string> mylist = new List<string>(new string[] { \"element1\", \"element2\", \"element3\" });\n\n return Json(new { ListResult = Co }, JsonRequestBehavior.AllowGet);\n}\n\n\nWhen I pass mylist instead of Co it work\n\nAnd here is my ajax call.\n\n$(document).ready(function () {\n $(\"#Name\").change(function () {\n var ContinentoId = $(this).val();\n\n $.ajax({\n type: \"Post\",\n dataType: \"json\",\n\n data: { ContinentId: ContinentoId },\n url: '@Url.Action(\"UpdateCountryDropDownList\",\"Home\")',\n\n success: function (result) {\n alert(\"worked\");\n },\n error: function (xhr, ajaxOptions, thrownError) {\n alert(\"failed\");\n }\n\n\nIt give my failed message when passing list of country object but success when passing list of strings. What is going wrong here?"
] | [
"ajax",
"asp.net-mvc"
] |
[
"Parse period of time in Java",
"I want to be able to parse period of time (days, hours, minutes) + optional string so the input looks like this: <time>(white_spaces)<optional_string>. As i know regex is the right tool for such things so i came up with such expression: \n\nPattern.compile(\"((?<days>\\\\d+)d)?((?<hours>\\\\d+)h)?((?<minutes>\\\\d+)m)?\\\\s+?(?<reason>.+)?\");\n\n\nBasically it works as expected however in this expression all times groups (days, hours, minutes) are optional and i want the input to atleast contain minutes group. However if hours or days are specified, minutes are not required. Also, all combinations of time groups (d+h, h+m, d+m, d+h+m) are possible. So how can i correct my expression? Or maybe there is other way to parse period of time? \n\nEDIT:\nexamples of inputs:\n\n12h64m - correct\n\n12d43m dsd - correct \n\n - empty string - not correct\n\n12m - correct \n\n12d32h43m - correct\n\nsdsds - not correct - no \"time group specified\""
] | [
"java",
"regex",
"date",
"iso8601"
] |
[
"Get absolute path to project directory in application.properties",
"I am writing a Quarkus application which reads data over http. In my application.properties file, I have this line:\nmy.resource=http://path/to/file\n\nEvery time I run the app, it has to download the file so I created a smaller version of the file locally for developing purpose. The problem is that I don't know how to put it in the properties file.\nIdeally, I want something like this:\nmy.resource=http://path/to/file\n%dev.my.resource=file://${project-dir}/sample_data/file\n\nAnd I have to use the absolute path because I used new URI(resource).toURL() method which requires an absolute URI.\nThanks in advance."
] | [
"java",
"configuration",
"quarkus"
] |
[
"Multiplying array numbers sequentially",
"The best and the easiest way to multiply array numbers sequentially\nI have got an array with some values:\n const arr = [1, 5, 12, 3, 83, 5];\n\nNow I want to get the product of all values from arr. It should works like this: 1 * 5 * 12 * 3 * 83 * 5\nI have tried with this code:\n\n const arr = [1, 5, 12, 3, 83, 5];\n\n multiply(arr);\n\n function multiply(arr) {\n for(i = 0; i < arr.length; i++) {\n product = array[i] * array[i];\n console.log(product);\n }\n }\n\n\nThis code above works like this: 1 * 1, 5 * 5, 12 * 12, 3 * 3, 83 * 83, 5 * 5 and that is not result that I need. I think I know why it works like this but I'm not sure how to write code that I need.\nSo what's the best option for this kind of tasks?\nEdit.\nFor non-experienced people looking here in future this is the best option that we've found:\nLeo Martin answer:\n\n const array = [1, 5, 12, 3, 83, 5];\n\n console.log(multiply(array)); // we log function return value\n\n function multiply(array) {\n let score = array[0];\n for (i = 1; i < array.length; i++) {\n score = score * array[i];\n }\n return score;\n }\n\n\n\nand also the shorter version:\n\nBy the way, you could use Array.reduce:\n\n const array = [1, 5, 12, 3, 83, 5];\n\n const result = array.reduce((acc, value, index) => { \n if (index === 0) return value;\n acc = acc * value;\n\n return acc;\n }, 0);\n\n console.log(result);"
] | [
"javascript",
"arrays",
"multiplication",
"console.log"
] |
[
"What AWS Resources Does Terraform Know About",
"Recently, we had issues with tfstate being deleted on S3. \n\nAs a result, there are a number of EC2 instances still running (duplicates if you will)\n\nIs there a way to query Terraform and list which EC2 instances (and other resources) Terraform has under its control? I want to delete the duplicate AWS resources without messing up Terraform state."
] | [
"amazon-web-services",
"terraform"
] |
[
"PHP in_array is not finding value that is there",
"I have this code:\n\n$sql_zt = \"SELECT\n inh_pr.extra_bew_zetten AS extra_bew_zetten\n FROM 5_offerte_id AS off\n LEFT JOIN 6_offerte_inh AS off_inh\n ON off_inh.offerte_id = off.id\n LEFT JOIN 3_product_folder AS fld\n ON fld.folder_id = off_inh.folder_id\n LEFT JOIN 0_calculatie_inh_id_geg_lntk_product AS inh_pr\n ON inh_pr.calculatie_inh_id = fld.product_id\n WHERE off.dossier_id = \".$row['id'].\" AND inh_pr.extra_bew_zetten = 'ja' AND off.offerte_nr = (SELECT MAX(offerte_nr) FROM 5_offerte_id WHERE dossier_id = \".$row['id'].\") \";\n\nif(!$res_zt = mysql_query($sql_zt,$con))\n{\n include('includes/errors/database_error.php');\n}\n\nif(mysql_num_rows($res_zt) > 0)\n{\n if(in_array('ja', mysql_fetch_array($res_zt)))\n {\n echo '<img border=\"0\" src=\"images/icon/zetten.png\" title=\"'.$lang['zetten'].'\"> ';\n }\n}\n\n\nThis is my output example with the query:\n\n\nValue 'ja' is not found with in_array. What might be the problem?"
] | [
"php",
"mysql"
] |
[
"Extract scrape after browser is open",
"I want to extract values from a webpage, I have to make multiple inputs and clicks before I can get to the data I want so I don't want to scrape until after I've selected all the search parameters.\n\nI need the values after object and navigate happens after changing the search/narrowing down. I created a module, loaded internet controls etc. that's all working, page loads. After loading I change the search params on the page and I get updated results and THEN I want to extract the values. Any help would be appreciated….\n\nupdate code involved:\n\nI was trying to use shdocvw.internetexplorer \n\nSub PULLDATA()\n\nDim IE As Object\nDim ieObj As InternetExplorer\nDim htmlEle As IHTMLElement\nDim i As Integer\n\n\nSet IE = GetIE(\"'URL Hidden\")\n\n' initialize i to one\ni = 2\nFor Each htmlEle In IE.document.getElementsByClassName(\"number\") (0).getElementsByTagName(\"li\")\n With ActiveSheet\n .Range(\"B\" & i).Value = htmlEle.Children(0).textContent\n .Range(\"C\" & i).Value = htmlEle.Children(1).textContent\n .Range(\"D\" & i).Value = htmlEle.Children(2).textContent\n .Range(\"E\" & i).Value = htmlEle.Children(3).textContent\n .Range(\"F\" & i).Value = htmlEle.Children(4).textContent\n End With\n\n i = i + 1\n\nNext htmlEle\n\nEnd Sub\n\n .Quit\n\nEnd With\n\nSet ie = Nothing\n\nEnd Sub\n\n\nI am just starting to build this but the bones are here\n\nI just need clarification, surely someone has a base code to add elements to the worksheet instead of automating then retrieve the values... I'm sure to make it once I've checked the various filters on the page, which contains the classes and divs, and updated the page which I have to do MANUALLY and can populate the specific sheet in the workbook"
] | [
"excel",
"vba",
"web-scraping"
] |
[
"asp.net web api json not returning when on server",
"I've built a web api for my mobile app. I test it on the localhost in browser and it returns json as expected, but whenever I host it on azure and hit the same URL I receive no data, but google network (developer console) in chrome says it has retrieved 408B of data, but no content shows up where the json should be present?\n\nWhat could I not have configured correctly?\n\nI have gone into the Global.ascx file and added the following line of code\n\n public static void Register(HttpConfiguration config)\n {\n config.EnableCors();\n }\n\n\nand added the EnableCors attribute on top of the webapi controller class and set the prefix router too.\n\nWhat am I missing?\n\nController code see below for a snippet of it. the database is an EF Code First generated from a database that already existed. Please note.\n\n [EnableCors(origins: \"*\", headers: \"*\", methods: \"*\")]\n [RoutePrefix(\"api/numbers\")]\n [AllowAnonymous]\n public class NumbersController : ApiController\n {\n private MegaMillions db = new MegaMillions();\n\n [HttpGet]\n public HttpResponseMessage Get()\n {\n return db.Numbers.Take(10).ToList();\n }\n\n // GET: api/Numbers\n public List<Number> GetNumbers()\n {\n return db.Numbers.ToList();\n }\n} \n\n\nif I can figure out how to get the list working the other CRUD operations will follow suit."
] | [
"asp.net",
"json",
"rest",
"asp.net-web-api"
] |
[
"Display '-' instead of '0' in Interactive report",
"I have the following sql query which is used to create a report to show revision history for a product. Intial record is revision 0, if something is edited it becomes revision 1, and so on.\nInstead of showing '0' in the report i would prefer to show '-', is there a way this can be achieved?\n\nSELECT\nproduct_id,\nname,\ndescription,\nrevision,\nrevision,reason,\n'DETAILS' \"VIEW DETAILS\"\nFROM product_table\nWHERE product_id = :P2_product_id\nORDER BY REVISION DESC\n--order by case when Revision is null then 1 else 0 end, revision desc\n\n\nproduct_id - numeric\nname - varchar2\ndescription - varchar2\nrevision - numeric\nrevision_reason - varchar2\n\nI did try the line which is commented out however the repor continues to show the 0 rather than a -."
] | [
"oracle-apex"
] |
[
"How to request a delta using Microsoft.Graph C# API",
"In the following code, GraphService is a GraphServiceClient instance that is already connected, and the value returned into foo is a collection of Intune devices.\n\nvar foo = GraphService.Devices.Request().GetAsync().Result;\n\n\nAs is, this gets all devices. Best practice documentation suggests use of a delta query as documented here https://docs.microsoft.com/en-us/graph/delta-query-overview but Intellisense is not reporting a chainable Delta() method on IGraphServiceDevicesCollectionRequestBuilder (the type of Devices) or IGraphServiceDevicesCollectionRequest (returned by Request())\n and I have yet to find any documentation for anything but the REST URLs.\n\nHow is one supposed to make a delta request using this library? \n\nThe request URL is surfaced as a mutable string property. Should I hack the URL to include \"/delta\" or is there a recommended way in documentation I have yet to read?\n\nThe Request method can take a parameter IEnumerable<Option> options but I have yet to find documentation of supported options so it's hard to know whether this is relevant."
] | [
"c#",
"microsoft-graph-intune"
] |
[
"Illegal Characters in Path only on internal VS-Server",
"I got an MVC-Application that creates a parameter using jQuery. In that jQuery method I create a string value that concatinates two GUIDs: s=guid1+'|'+guid2;\n\nthe jS looks like this:\n\n $('.editUser').click(function () {\n var userId = $(this).attr(\"userId\") + \"|\" + $(this).attr(\"itemprop\");\n\n $(\"#editUserPopup\").html(\"\")\n .dialog(\"option\", \"title\", \"Edit Note\")\n .load(\"./Services/EditUser/\" + userId, function () { $(\"#editUserPopup\").dialog(\"open\"); });\n });\n\n\nInside the controller I got an actionmethod that uses that parameter. The generated URL is like:\n\nlocalhost:57465/Services/EditUser/7d2ee650-fd14-4589-a10e-2030d261d4e7%7C717f91f1-2f38-4e89-ad5d-14621ebdcfcf\n\n\nthe code snippet is:\n\n[OutputCache(Duration=0) ]\n public ActionResult EditUser( string id)\n {\n string userId = id.Split('|')[0];\n string serviceId = id.Split('|')[1];\n...}\n\n\nWhen I debug this project with the internal Visual Studio Deployment Server from VS I receive the following error:\n\n\n [ArgumentException: Illegal characters in path.]\n\n\neven before the method is entered. When using IIS Express, no error is thrown.\n\nWhat could be the problem here? Is there maybe something wrong that the IIS fixed \"automatically\" but not the internal server?"
] | [
"jquery",
"asp.net-mvc",
"iis"
] |
[
"AWS S3 policy to allow access to buckets ending with particular name",
"Is it possible to write an AWS S3 policy such that\n\n\ncan read all objects in bucket which names ending in \"archive\" (the bucket name ending in archive, no constraint on object names)\ncan read-write all objects in buckets ending in \"output\"\n\n\nCan that be done?\n\nI can't find \"conditions\" that would allow me to do that...\n\nThanks\n\nPS: \n1) I just edited the question because there was ambiguity as whether it was the bucket or the object name ending in \"...\"\n2) I have since gathered that I can't filter the names of the buckets that can be listed\n3) The comment from bruno-reis makes it clear that it would be a bad idea anyway"
] | [
"amazon-s3",
"amazon-iam"
] |
[
"YouTube player in ScrollView android",
"When youtube player fragment nested in ScrollView I get error when rotate device to landscape:\n\nYouTubePlayer.ErrorReason.UNAUTHORIZED_OVERLAY\n\n\nAnd what is more interesting, is that the problem disappears when I remove ScrollView! But I can\n\n<ScrollView\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\">\n <LinearLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n >\n <TextView\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"/>\n />\n <fragment\n android:name=\"com.google.android.youtube.player.YouTubePlayerFragment\"\n android:id=\"@+id/youtubeplayerfragment\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"/>\n </LinearLayout>\n</ScrollView>"
] | [
"android",
"youtube",
"youtube-api"
] |
[
"how to add a script value dynamically in html head tag in javascript",
"I am new to javaScript and html.\nI am trying to create a script value dynamically and add to html head tag from java script and i am using angularjs also as following..\n\nmy script.js\n\n$http.get(URL).success(function (response) {\n $scope.trailers = response;\n var js = document.createElement('script');\n js.setAttribute('type', 'text/javascript');\n js.value = \"api_gallery = [\"+trailers[0].youtubeId +\", \"+trailers[1].youtubeId +\"];api_titles = ['video1', 'video2'];api_descriptions = ['description1', 'description2'];\";\n\n document.getElementsByTagName('head')[0].appendChild(js);\n});\n\n\nActually the above code is for youtube videos popup.for that I have to assign the youtube urls to the above script.\n\nand my details json is \n\n[{\"youtubeId\": \"https://www.youtube.com/watch?v=_eZh4R_6WtA\"},{\"youtubeId\": \"https://www.youtube.com/watch?v=ynDAZ8-xcSE\"}]\n\n\nthanks in advance..."
] | [
"javascript",
"html",
"angularjs"
] |
[
"Group hierarchically into levels",
"I have a list of string that contains numbers in ascending order. The numbers are formatted like this:\n\n02 (main group - first level)\n02.00 (first level.second level)\n02.00.00 (first level.second level.Third level)\n\nThe two digits of level one are static. The two digits after the first level can be any number and the same goes for the third level. It is hierarchically structured.\nHow can I group these levels into groups by looping the list?"
] | [
"c#",
"loops",
"hierarchical-data"
] |
[
"Index large pdf file into SOLR",
"I am in the process of indexing a large pdf file into SOLR.\nFor text extraction I am using apache TIKA and SOLRJ for posting the files.\nMy current approach is to split each page into separate file and then extract (With apache TIKA) then post (with SOLRJ).\nFor accessing this information on UI(Custom UI),I need to have one field as-\n\n\"url= http://localhost:8080/data/apache-solr-ref-guide-5.1.pdf#page=3\"\nAs you can see here I am capturing page number of each page for above mentioned url part.this is easy for me as I am splitting the whole file into multiple files.\neverything works fine till now.\n\nBut now my requirement is to eliminate the process of splitting the files into multiple file.I mean,I want to extract full file without splitting into parts and at the same time in SOLR it should be stored as different pages,so that I can distinguish each page for creating URL.\n\nCould you please let me know how to do that.?"
] | [
"solr"
] |
[
"How to prioritize data based on a given value",
"Hi is there a way I can prioritize the order by of an sql result?\n\nExample I have a $_POST['city_id'] request that has a value of 2, 5 and my table I had a rows of city_id of 1,2,3,4,5\n\nAnd when I use the query below example:\n\nSELECT * FROM table_name WHERE status = 0 ORDER BY city_id ASC\n\n\nI can get a result of 2,5,1,3,4 in an order by of a city_id."
] | [
"php",
"mysql"
] |
[
"how to access ng-model in nested controller in angularjs",
"I'm working with a parent controller and several children (in parallel).\n\nrouter\n\n$stateProvider\n .state('page', {\n url: '/page1',\n templateUrl: 'templates/page.html',\n controller: 'pageCtrl'\n})\n\n\npage.html\n\n<label class=\"item item-input\">\n <span class=\"input-label\">Pedido</span>\n <input type=\"number\" ng-model=\"pedido\">\n</label>\n\n<div class=\"item item-input\" ng-controller=\"matriculaCtrl as vm\">\n <label class=\"item-input-wrapper\">\n <span class=\"input-label\">Matricula</span>\n <input type=\"text\" placeholder=\"\" ng-model=\"vm.matricula\">\n </label>\n <button class=\"button button-small button-positive\" ng-click=\"vm.scan()\">\n <i class=\"icon ion-qr-scanner\"></i>\n </button>\n</div>\n\n<!--more controllers-->\n\n<button \n class=\"button button-block button-positive icon-right ion-chevron-right\"\n ng-click=\"send(pedido, vm.matricula)\">\n Enviar \n</button> \n\n\ncontroller\n\n.controller('pageCtrl', ['$scope', '$stateParams', 'CustomerService', function ($scope, $stateParams, CustomerService) {\n $scope.send = function(pedido, matricula){\n console.log(pedido+'-'+matricula);\n }\n}])\n\n.controller('matriculaCtrl', function ($scope, $rootScope, $cordovaBarcodeScanner, $ionicPlatform) {\n var vm = this;\n\n vm.scan = function () {\n $ionicPlatform.ready(function () {\n $cordovaBarcodeScanner\n .scan()\n .then(function (result) {\n vm.matricula = result.text;\n }, function (error) {\n vm.matricula = 'Error: ' + error;\n });\n });\n };\n vm.matricula = '';\n})\n\n\nIn the send function of the button, the first model works fine, but I can not access the second model, it always returns me undefined. Is there another way to do this?\n\nthanks in advance"
] | [
"angularjs",
"controller",
"nested"
] |
[
"INNER JOIN two BigQuery tables based on common timestamps within a range of each other?",
"I have two table in BigQuery. Basically one has a bunch of data that is based around a Timestamp. The second set of data has another feature to add to the first set, also with a Timestamp. However, the timestamps aren't necessarily the same. However, I do know that they will be within 30 seconds of each other.\n\nI was thinking I could do JOIN... ON abs(Timestamp1 - Timestamp2) < 30, but that's not working."
] | [
"google-bigquery"
] |
[
"Unable to handle two links having different pagination using decorator",
"I've written a script in python using two different links (one has pagination but the other doesn't) to see whether my script can fetch all the next page links. It is necessary that the script must print this No pagination found line if there is no pagination option. \n\nI've applied @check_pagination decorator to check for the existance of pagination and I want to keep this decorator within my scraper.\n\nI've already achieved what I've described above complying the following:\n\nimport requests\nfrom bs4 import BeautifulSoup\n\nurls = [\n \"https://www.mobilehome.net/mobile-home-park-directory/maine/all\",\n \"https://www.mobilehome.net/mobile-home-park-directory/rhode-island/all\"\n ]\n\ndef check_pagination(f):\n def wrapper(lead):\n if not lead.pages:\n print('No pagination found')\n return f(lead)\n return wrapper\n\nclass LinkScraper:\n def __init__(self, url):\n self.url = url\n self.home_page = requests.get(self.url).text\n self.soup = BeautifulSoup(self.home_page,\"lxml\")\n self.pages = [item.text for item in self.soup.find('div', {'class':'pagination'}).find_all('a')][:-1]\n\n @check_pagination\n def __iter__(self):\n for p in self.pages:\n link = requests.get(f'{self.url}/page/{p}')\n yield link.url\n\nfor url in urls:\n d = [page for page in LinkScraper(url)]\n print(d)\n\n\nNow, I wish to do the same without using class and with keeping the decorator within my script to check the pagination but It seems I'm going somewhere wrong within the decorator and that is the reason it doesn't print No pagination found even when the link doesn't have pagination. Any help to fix this will be appreciated.\n\nimport requests\nfrom bs4 import BeautifulSoup\n\nurls = [\n \"https://www.mobilehome.net/mobile-home-park-directory/maine/all\",\n \"https://www.mobilehome.net/mobile-home-park-directory/rhode-island/all\"\n ]\n\ndef check_pagination(f):\n def wrapper(*args,**kwargs):\n if not f(*args,**kwargs): \n print(\"No pagination found\")\n return f(*args,**kwargs)\n return wrapper\n\ndef get_base(url):\n page = requests.get(url).text\n soup = BeautifulSoup(page,\"lxml\")\n return [item.text for item in soup.find('div', {'class':'pagination'}).find_all('a')][:-1]\n\n@check_pagination\ndef get_links(num):\n link = requests.get(f'{url}/page/{num}')\n return link.url\n\nif __name__ == '__main__':\n for url in urls:\n links = [item for item in get_base(url)]\n for link in links:\n print(get_links(link))"
] | [
"python",
"python-3.x",
"function",
"web-scraping",
"decorator"
] |
[
"Delay when loading CSS into shiny server",
"First of all, fairly new to Shiny, so bear with me.\nI have tried to create R studio shiny page with authorization. First page is login page and if you pass the authorization process (e.g. User and Pass are correct) you are taken to main Shiny page. In reality it just means that two different UI's are rendered.\n\nHowever since implementing authorization page, CSS code which changes sidebar and header colors, seems to run with delay (as can be seen by running an app, you can notice that Shiny default style is loaded onto a sidebar and later it is overwritten by CSS). What could be the problem here?\n\nCode as follows:\n\nui.R\n\nshinyUI(\nfluidPage(\n\nui <- dashboardPage(\n\nheader <- dashboardHeader(uiOutput(\"header\")),\nsidebar <- dashboardSidebar(uiOutput(\"sidebarpanel\")),\nbody <- dashboardBody(uiOutput(\"body\"))\n)))\n\n\nserver.R\n\nlibrary(shinydashboard)\nlibrary(writexl)\nlibrary(shinyjs)\nlibrary(shinythemes)\nlibrary(openssl)\nlibrary(shinyWidgets)\n\nshinyServer(function(input, output, session) {\n\nLogged <- FALSE\nUSER <<- reactiveValues(Logged = Logged)\n\nmy_username <- \"demo\"\nmy_password <- \"369\"\n\nobserve({ \n if (USER$Logged == FALSE) {\n if (!is.null(input$Login)) {\n if (input$Login > 0) {\n Username <- isolate(input$userName)\n Password <- isolate(input$passwd)\n Id.username <- which(my_username == Username)\n Id.password <- which(my_password == Password)\n if (length(Id.username) > 0 & length(Id.password) > 0) {\n if (Id.username == Id.password) {\n USER$Logged <<- TRUE\n }}\n else sendSweetAlert(session = session, title = \"Incorrect Username or \n Password!\",\n text = \"Please check.\", type = \"error\",\n btn_labels = \"Ok\")\n\n }}} \n })\n\n output$body <- renderUI({ \n dashboardBody(\n tags$style(HTML('\n /* logo */\n .skin-blue .main-header .logo {\n background-color: #FFFFFF;\n }\n\n /* logo when hovered */\n .skin-blue .main-header .logo:hover {\n background-color: #FFFFFF;\n }\n\n /* sidebar */\n .skin-blue .main-sidebar {\n background-color: #873260;\n }\n\n /* logo when hovered */\n .skin-blue .main-header .navbar {\n background-color: #873260;\n }\n ')),\n\n if (USER$Logged == FALSE) {\n box(title = \"Login\",textInput(\"userName\", \"Username\"),\n passwordInput(\"passwd\", \"Password\"),\n br(),\n actionButton(\"Login\", \"Log in\")\n )})\n})\n\n output$sidebarpanel <- renderUI({\n if (USER$Logged == TRUE) { \n dashboardSidebar( \n\n sidebarMenu(\n menuItem(\"Home\", icon = icon(\"home\")),\n menuItem(\"Panel 1\", icon = icon(\"th-large\")),\n menuItem(\"Panel 2\", icon = icon(\"dashboard\")),\n menuItem(\"Panel 3\", icon = icon(\"dashboard\")),\n menuItem(\"Panel 4\", icon = icon(\"pencil\")),\n menuItem(\"Panel 5\", icon = icon(\"pencil\")),\n menuItem(\"Panel 6\", icon = icon(\"th\"))\n )\n )\n }})\n})"
] | [
"r",
"shiny",
"loading"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.