text
stringlengths
175
47.7k
meta
dict
Q: gets (variable) can anyone tell me why gets(abc) works with char[] but not with int? int abc; char name[] = "lolrofl"; printf("Hello %s.\n",name); printf("\n >> "); fflush(stdin); gets (abc); printf("\n die zahl ist %i.\n",abc); system("Pause"); return(0); A: The prototype for gets() is: char* gets(char *s); Note that the function DOES NOT read just a single character and place it in s; it actually reads an entire string into s. However, since gets() does not provide a way of specifying the maximum number of characters to read, this can actually read more characters into s than there are bytes allocated for s. Thus, this function is a serious buffer overflow vulnerability, and you should not use this function, ever. There are alternative, safer functions which allow you to read input from the user such as fgets() and getc(). If you are using C++, then using the C++ I/O Stream Library (std::cin, std::cout, std::ostream, std::istream, std::fstream, etc.) is a far better way to perform input/output than using these other functions. The function gets() is so dangerous, in fact, that in my development and coding custom search engine, I have taken out a promotion on gets and several other such functions warning not to use it! A: Because it only reads characters. Use scanf() for formatted reading. By the way, since you appear to be using C++ (or at least your choice of tags says so), perhaps you should try std::cin/std::cout.
{ "pile_set_name": "StackExchange" }
Q: programmer is not responding with stacked shields I keep getting the following error when trying to upload my code with the Arduino IDE: avrdude: stk500_recv(): programmer is not responding I stacked the following shields: Sparkfun ColorLCD shield (shieldlist reference) Libelium XBee shield (shieldlist reference) on top of a Arduino UNO. I first thought it could be coming from the shields draining too much power from the USB port, but connecting an external power supply hasn't changed the situation (I had to set it up to 7,5V/600mA to avoid overheating). I'm kind of lost here, judging from shieldlist I should only be worried about the power supply, which is obviously not the case. Any idea about my problem? A: The culprit will be the XBee shield. It uses the TX and RX pins. These are also used by the programming system. If anything is connected that uses those pins while you try to program it can interfere with the programming data. I usually design shields that use the UART to include a pair of diodes to isolate them from the rest of the UART system and allow programming to work while the shield is connected.
{ "pile_set_name": "StackExchange" }
Q: How to synchronously find instance and create in LoopBack I am quite new with NodeJS and it is obviously causing some problems as things have a very asynchronously nature. I am trying to find to instances which has to be used to create a new one (relation): countryId and clientId. Obviously things are happening asynchronously so the variables are undefined. How do i make it synchronously? This is my boot script in LoopBack module.exports = function(app) { var Client = app.models.Client var Country = app.models.Country var BillingAddress = app.models.BillingAddress Client.create([ {username: 'test@test.gov', email: 'test@test.gov', password: 'nasapassword'}, {username: 'test2@test2.gov', email: 'test2@test2.gov', password: 'nanapassword'} ], function(err, clients){ if(err) throw err }) Country.findOne({where: {name: 'Spain'}}, function(err, country) { if(err) throw err } ) Client.findOne({where: {email: 'john@nasa.gov'}}, function(err, client) { if(err) throw err } ) BillingAddress.create([ {first_name: 'Jimbo', last_name: 'Juice', address_line_1: 'Loool street', postal_code: '23232', countryId: country.id, clientId: client.id} ], function(err, billingaddress) { if(err) throw err }) } A: It is not possible. The async function should be treated as an async call. You can use async module. module.exports = function(app, cb) { var Client = app.models.Client; var Country = app.models.Country; var BillingAddress = app.models.BillingAddress; var clientData = [{username: 'test@test.gov', email: 'test@test.gov', password: 'nasapassword'}, {username: 'test2@test2.gov', email: 'test2@test2.gov', password: 'nanapassword'}]; async.parallel({ clients: function(callback){ async.map(clientData, Client.create.bind(Client), function(err, clients){ if(err) return callback(err); callback(null, clients); }); }, country: function(callback){ Country.findOne({where: {name: 'Spain'}}, callback); }, nasaClient: function(callback){ Client.findOne({where: {email: 'john@nasa.gov'}}, callback); } }, function(err, results){ if(err) return cb(err); BillingAddress.create([ {first_name: 'Jimbo', last_name: 'Juice', address_line_1: 'Loool street', postal_code: '23232', countryId: results.country.id, clientId: results.nasaClient.id} ], function(err, billingaddress) { if(err) return cb(err); cb(null); }); }); } Some points : The boot script should be async too Avoid throwing exceptions. Just handle it by callbacks
{ "pile_set_name": "StackExchange" }
Q: Authorship allocation - is it common to grant equal credit to two last authors? I am working on a project in which I have a direct supervisor in addition to the head professor of the lab. The direct supervisor only agrees to being written first or last on the article we are writing. Needless to say, my professor won't agree to be anywhere but last. He also feels that I deserve to be written in the first place. Is it possible to write both of them in the last place as co-last authors? A: Is it possible to write both of them in the last place as co-last authors? No. As expected, an author list is not a tree or a weighted graph, but a simple flat (one-dimensional) list. There is exactly one last author. Possible solutions or mitigation of the issue include: Alphabetical author list. This happens in some field, and is totally unheard of in some others (including chemistry and biology, which is your field, so this might not be a possibility). Having two contact authors, or have the professor who is not last author to be the contact author. In the past I have used this as a way to “pacify” a co-author who wasn't happy with his spot on the author list. (Needless to say, it's a perversion of the system, and should only be done if the author can actually act as contact author.) Have a statement indicating the contributions of each author (“X and Y contributed to this work equally”). Some journals require such statements, some will refuse to include them, so your mileage may vary. I doubt this will pacify your reluctant supervisor, though: people who are worried about their rank in the author list are most probably thinking about how it looks like on a publication list or CV. Have the head professor take responsibility for the final decision (as senior professor and project instigator). That's the most sound solution, but it does not mean it's an easy one. Good luck with your negotiation! And remember that they're not yours to handle (see my last point)! A: This happens in biology quite frequently. Take a look at this example: § Both authors contributed equally to this work. In this case it can be any two authors on the list. If the notes are on the first two or last two authors, then this is often viewed as the two primary and equal collaborators.
{ "pile_set_name": "StackExchange" }
Q: Why does math.stackexchange use single transferable vote? Isn't the Schulze method superior to single transferable vote? It takes preferences, and it's Condorcet (i.e., if everyone prefers A to B for all B in hypothetical two person elections, then A wins.) STV is not Condorcet. I can understand national elections using STV since the Schulze method would be impossible to explain to an average electorate, but math.stackexchange is made of mathematicians. Why do we use STV? A: Within STV you have to specify the variant. We use "Meek". http://en.wikipedia.org/wiki/Meek%27s_method#Meek.27s_method If you are electing multiple people and simplicity is not important, then we recommend Meek STV. Most people agree that Meek STV is the best variant of STV, but it can only be implemented with a computer program. http://www.openstv.org/faq
{ "pile_set_name": "StackExchange" }
Q: AWS SageMaker notebook list tables using boto3 and PySpark Having some difficulty executing the following code in AWS SageMaker. It is supposed to just list all of the tables in DynamoDB. import boto3 resource = boto3.resource('dynamodb', region_name='xxxx') response = resource.tables.all() for r in response: print(r.name) If the SageMaker notebook kernel is set to "conda_python3" the code executes fine and the tables are listed out in the notebook as expected (this happens pretty much instantly). However, if I set the kernel to "Sparkmagic (PySpark)" the same code infinitely runs and doesn't output the table list at all. Does anyone know why this would happen for the PySpark kernel but not for the conda3 kernel? Ideally I need to run this code as part of a bigger script that relies on PySpark, so would like to get it working with PySpark. A: Figured out what the issue was, you need to end an endpoint to tour VPC for DyanmoDB. To do this navigate to: AWS VPC Endpoints Create Endpoint Select the dynamodb service (will be type Gateway) Select the VPC your Notebook is using
{ "pile_set_name": "StackExchange" }
Q: Tensorflow rnn: name 'seq2seq' is not defined I am trying this notebook: https://github.com/sjchoi86/Tensorflow-101/blob/master/notebooks/char_rnn_sample_tutorial.ipynb I have a problem with this line In[6]: outputs, final_state = seq2seq.rnn_decoder(inputs, istate, cell, loop_function=None, scope='rnnlm') I get this error: NameError: name 'seq2seq' is not defined I am using tensorflow 1.0.1. I tried tf.contrib.seq2seq but I am getting error: AttributeError: 'module' object has no attribute 'rnn_decoder' I think it is a probleme with the new implementation of rnn network in tensorflow 1.0.1 but I don't know how to fix it. A: Because seq2seq has been moved to tf.contrib.legacy_seq2seq. You should change this line to: outputs, final_state = tf.contrib.legacy_seq2seq.rnn_decoder(inputs, istate, cell, loop_function=None, scope='rnnlm')
{ "pile_set_name": "StackExchange" }
Q: State not updating immediately I'm building a web app that calculates BMR by asking the user for age, weight, gender, feet, inches. After the user submits the form, there should be an alert box with the state of all objects. The only problem is, BMR is the only one that stays at 0; it doesn't update until I click submit again. I am working with two Classes: Macros(main) and Form. My code is below class Macros extends React.Component{ constructor(props){ super(props); this.state = { age: '', weight: '', male: true, feet: '', inches: '', BMR: 0, }; this.handleAgeChange = this.handleAgeChange.bind(this); this.handleWeightChange = this.handleWeightChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.handleGenderChange = this.handleGenderChange.bind(this); this.handleFeetChange = this.handleFeetChange.bind(this); this.handleInchChange = this.handleInchChange.bind(this); this.calculateBMR = this.calculateBMR.bind(this); } handleAgeChange(event) { this.setState({age: event.target.value}); } handleWeightChange(event) { this.setState({weight: event.target.value}); } handleSubmit(event) { this.calculateBMR(); event.preventDefault(); alert('Age: ' + this.state.age + ' Weight: ' + this.state.weight + ' Male: ' + this.state.male + ' Feet: ' + this.state.feet + ' Inches: ' + this.state.inches + ' BMR: ' + this.state.BMR) } handleGenderChange(event) { this.setState({male: !this.state.male}); } handleFeetChange(event) { this.setState({feet: event.target.value}); } handleInchChange(event) { this.setState({inches: event.target.value}); } calculateBMR() { let calBMR = 0; if(this.state.male){ calBMR = ((10 * ((this.state.weight) / 2.20462)) + (6.25 * ((this.state.feet * 30.48) + (this.state.inches * 2.54))) - (5 * this.state.age)) + 5; } else { calBMR = ((10 * ((this.state.weight) / 2.20462)) + (6.25 * ((this.state.feet * 30.48) + (this.state.inches * 2.54))) - (5 * this.state.age)) - 161; } this.setState({BMR: calBMR}); } render(){ const title = 'Macro Apps'; const subtitle = 'Calculate Your Macro-Nutrient Intake for Flexible Dieting'; return ( <div> <Header title={title} subtitle={subtitle} /> <Form onAgeChange={this.handleAgeChange} onWeightChange={this.handleWeightChange} onGenderChange={this.handleGenderChange} onFeetChange={this.handleFeetChange} onInchChange={this.handleInchChange} onSubmit={this.handleSubmit} /> </div> ); } } ReactDOM.render(<Macros />, document.getElementById('root')); Form Class import React from 'react'; export class Form extends React.Component{ render(){ return ( <div> <form onSubmit={this.props.onSubmit}> Age: <input type="text" onChange={this.props.onAgeChange}/><br /> Weight: <input type="text" onChange={this.props.onWeightChange} /><br /> <label> <input type="radio" name="gender" checked="checked" onChange={this.props.onGenderChange} /> Male </label> <label> <input type="radio" name="gender" onChange={this.props.onGenderChange} /> Female<br/> </label> <input type="text" onChange={this.props.onFeetChange}/>ft <input type="text" onChange={this.props.onInchChange}/>in<br/> <input type="submit" value="Submit" /> </form> </div> ) } } A: In ReactJS setting state is asynchronous. You can simply pass a callback to setState method like this: setState({ "something": "needs to change" }, () => { /* will be invoked when the state changes. */ }) So this lines of code: handleSubmit(event) { this.calculateBMR(); ... } calculateBMR() { ... this.setState({BMR: calBMR}); } Could be look like this: handleSubmit(event) { this.calculateBMR(() => { alert('Age: ' + this.state.age + ' Weight: ' + this.state.weight + ' Male: ' + this.state.male + ' Feet: ' + this.state.feet + ' Inches: ' + this.state.inches + ' BMR: ' + this.state.BMR) }); } calculateBMR(callback) { this.setState({ BMR: calBMR }, callback); }
{ "pile_set_name": "StackExchange" }
Q: Specifying Notepad as OLE object For word application, we have Word.Application as program identifier. What is the program identifier for Notepad and Calculator? A: Word.Application is the name of the a COM object which forms part of the Word API. Notepad is a simple application which does not have a COM API. If you just wish to start an instance of notepad, then locate the notepad.exe file in %WINDIR% or %WINDIR%\System32 (for W2k8), and start it as a new process from your application. The same applies for calc.exe.
{ "pile_set_name": "StackExchange" }
Q: Application Created with Processing.org Won't Launch on Linux I have created an application using Processing.org. Everything works fine when I "Export Application" and run it on my Mac. When I "Export Application" and move the application.linux folder to my computer that is running Linux Mint, I click the Shell Script file and nothing happens. Any ideas what could be the cause of this? I am not particularly practiced with Linux, so it could be something basic. Thank You. A: The real issue here was that once I got the file onto the Linux machine I had to right-click on the shell file and set permissions to "Make This File Executable"
{ "pile_set_name": "StackExchange" }
Q: How to retrieve Parse.com User details in php I am using parse php sdk to handle data in my web page. I have a User class in my database. I am trying to display all user details into my web page. The server connection is correct and working, since it displays all other class details. But it is not working for the User class. Following is my php code. <?php $query = new ParseQuery("User"); $results = $query->find(); echo "Successfully retrieved " . count($results) . " scores."; for ($i = 0; $i < count($results); $i++) { $object = $results[$i]; echo $object->getObjectId() . ' - ' . $object->get('name'); } ?> When I run this code I get the following result Successfully retrieved 0 scores. But I have 6 users in my User class. A: Use $query = new ParseQuery("_User"); instead of $query = new ParseQuery("User");
{ "pile_set_name": "StackExchange" }
Q: Deserialize JSON Root Array I'm having so trouble deserializing a JSON stream that contains an array as the root: [ { "object": { "property1":"000000", "property2":"000000" } }, { "object": { "property1":"000000", "property2":"000000" } } ] I tried using JSON.deserializeUntyped and assigning to a Map, but I keep getting a "invalid conversion runtime type LIST to MAP". This method worked fine when I was dealing with single JSON objects, but loading multiples into an array trips this error. Should I be using a different type for deserialization? A: You have to cast it into a List<Object>, and for each element in the list, you can access the values as a Map<Object,Object>.
{ "pile_set_name": "StackExchange" }
Q: C# Prevent Hotkeys while TextBox focus I have a program containing multiple C# Forms TextBoxes. I've set up Hotkeys for the entire form activating certain functions. My problem is that my Hotkeys have been set onto the Form KeyDown event and they activate if I write something on a TextBox. Example: One Hotkey might be I. Everytime I write the letter onto a textbox the Hotkey activates. Alterior solutions and problems: I've thought about putting a Key in front of the Hotkey like CTRL+Hotkey, but these also present problems as CTRL+C is Windows Copy command etc. SHIFT is an UpperKey button. Question: Can I prevent Hotkeys from activating when I am writing onto a TextBox without having to go through all of them in the form? EDIT: Some code as requested. The button codes come from a stored XML file or the Hotkeys Form+Class (separate) where I've set up a window for them. public Hotkeys hotkeysForm = new Hotkeys(); void Form1_KeyDown(object sender, KeyEventArgs e) { toggleInformation = hotkeysForm.toggleInformation; if (e.Control && e.KeyCode == toggleInformation) { showInfo(true); } else if (e.KeyCode == toggleInformation) { if (!isInfoActive) showInfo(); else hideInfo(); } } A: You can disable hotkeys while texbox is an active control. Add the Enter and Leave events for all textboxes: private void textBox_Enter(object sender, EventArgs e) { KeyPreview = false; } private void textBox_Leave(object sender, EventArgs e) { KeyPreview = true; }
{ "pile_set_name": "StackExchange" }
Q: Observable fromEvenet mouseup is not accurate With this code you can drag blue line to right and left, splitting two contents. The problem is if I hold down my mouse and quickly move to one of the sides and let go my mouse, it still is active. So the take until doesn't execute I guess, or there an other problem with this? var split = $('.drag'); var parent = $('.Container'); var mouseDowns = Rx.Observable.fromEvent(split, "mousedown"); var parentMouseMoves = Rx.Observable.fromEvent(parent, "mousemove"); var parentMouseUps = Rx.Observable.fromEvent(parent, "mouseup"); var drags = mouseDowns.flatMap(function(e){ return parentMouseMoves.takeUntil(parentMouseUps); }); drags.subscribe(function(e) { var $containerWidth = $('.Container').width(); var clientX = $containerWidth - e.clientX; if (clientX >= 50 && e.clientX >= 50) { $('.left').css('right', clientX); $('.right').css('width', clientX); } }); jsbin.com A: So the problem is you are listening mouseup event only on parent which is your .Container but when you quickly move your mouse either to the left or right such that it goes out of the Container and you release you mouse, the mouseup event is registered there and not on the .Container. One way to fix this you can listen for the mouseups on the entire page. //.... var parentMouseMoves = Rx.Observable.fromEvent(parent, "mousemove"); var parentMouseUps = Rx.Observable.fromEvent($('html'), "mouseup"); //.... I've modified your code a bit which is working as expected, check it here Jsbin
{ "pile_set_name": "StackExchange" }
Q: How to Detect Special Key Presses in a Notebook? We can use: SetOptions[EvaluationNotebook[], NotebookEventActions -> {{"KeyDown","s"} :> Print["triggered"]}] to make the current notebook respond to s button press, also we can do the same to Modifier Keys like Ctrl, Shift, Alt or so. Can we do the same with Backspace, Delete or F1~F12? Additionally, can we detect the mouse-wheel's scrolling state? A: Following detects backspace on Mac: SetOptions[EvaluationNotebook[],NotebookEventActions-> {{"KeyDown","\.08"}:>Print["triggered"]}] This code can be helpful for finding out different codes for non-standard keys. SetOptions[EvaluationNotebook[],NotebookEventActions-> {"KeyDown":>Print[FullForm@CurrentValue["EventKey"]]}] A: So after BlacKow's insight I found more of these by playing with this: EventHandler[ Panel["", ImageSize -> 100], "KeyDown" :> Print[Row@{FullForm@CurrentValue@"EventKey", " pressed"}] ] A few more points of interest (this is potentially Mac specific as I am a Mac user): "\[RawEscape]" is the escape key "\.1c" is "LeftArrowKeyDown" "\.1e" is "UpArrowKeyDown" "\.1d" is "RightArrowKeyDown" "\.1f" is "DownArrowKeyDown" "\r" is "ReturnKeyDown" "\[GreaterEqual]" is control-. (and various other special characters can be found as a control-key combo, but these can be easily figured out I think) "\.10" is function-(any function key not bound) Hopefully someone can extend this further and to Windows / Linux? Useful collection of keys to have out there. A: @BlacKow's answer works well on Mac, but Mathematica cannot handle special keys (s.a. F2 or PAUSE) on Windows. Thus, Here is a Windows workaround: The idea is to create a dynamic link library that runs in a separate thread, as explained here. In this separate thread, the keyboard status is continuously tested. Once the specified key is pressed, an event is raised to the MMA kernel. The following code requires a working C-compiler on a Windows PC: Needs["CCompilerDriver`GenericCCompiler`"]; keyListen[keycode_, action_] := With[{ libMain = First@FileNames["async-examples-libmain.c", {$InstallationDirectory}, Infinity], src = " #include <stdlib.h> #include \"WolframLibrary.h\" #include \"WolframCompileLibrary.h\" #include \"WolframStreamsLibrary.h\" #include \"windows.h\" // for GetAsyncKeyState() /**********************************************************/ typedef struct keyTrackerArgs_st { WolframIOLibrary_Functions ioLibrary; mint key; }* keyTrackerArgs; static void key_tracker(mint asyncObjID, void* vtarg) { keyTrackerArgs targ = (keyTrackerArgs)vtarg; WolframIOLibrary_Functions ioLibrary = targ->ioLibrary; const mint key = targ->key; free(targ); while(ioLibrary->asynchronousTaskAliveQ(asyncObjID)) { if(GetAsyncKeyState(key) & 0x0001) { ioLibrary->raiseAsyncEvent(asyncObjID, \"KeyPress\", NULL); } } } DLLEXPORT int start_key_tracker(WolframLibraryData libData, mint Argc, MArgument *Args, MArgument Res) { mint asyncObjID; WolframIOLibrary_Functions ioLibrary = libData->ioLibraryFunctions; keyTrackerArgs threadArg = (keyTrackerArgs)malloc(sizeof(struct keyTrackerArgs_st)); if(Argc != 1) return LIBRARY_FUNCTION_ERROR; threadArg->ioLibrary = ioLibrary; threadArg->key = MArgument_getInteger(Args[0]); asyncObjID = ioLibrary->createAsynchronousTaskWithThread(key_tracker, threadArg); MArgument_setInteger(Res, asyncObjID); return LIBRARY_NO_ERROR; } " }, Module[{srcFile}, srcFile = CreateFile["src.c"]; WriteString[srcFile, src]; Close[srcFile]; lib = CreateLibrary[{srcFile, libMain}, "keyLib", "IncludeDirectories" -> {DirectoryName[libMain]}]; DeleteFile[srcFile]; keyListener = LibraryFunctionLoad[lib, "start_key_tracker", {Integer}, Integer]; Internal`CreateAsynchronousTask[keyListener, {keycode}, action]; ] ] Let's say we want to make a sound (Beep[]) every time the "PAUSE" key is hit. Then we evaluate keyListen[19, Beep[] &] where 19 is the code for "VK_PAUSE". Here are all the Windows key codes, in case you need them: virtualKeyList = {"VK_LBUTTON" -> 1, "VK_RBUTTON" -> 2, "VK_CANCEL" -> 3, "VK_MBUTTON" -> 4, "VK_XBUTTON1" -> 5, "VK_XBUTTON2" -> 6, "VK_BACK" -> 8, "VK_TAB" -> 9, "VK_CLEAR" -> 12, "VK_RETURN" -> 13, "VK_SHIFT" -> 16, "VK_CONTROL" -> 17, "VK_MENU" -> 18, "VK_PAUSE" -> 19, "VK_CAPITAL" -> 20, "VK_KANA" -> 21, "VK_HANGUEL" -> 21, "VK_HANGUL" -> 21, "VK_JUNJA" -> 23, "VK_FINAL" -> 24, "VK_HANJA" -> 25, "VK_KANJI" -> 25, "VK_ESCAPE" -> 27, "VK_CONVERT" -> 28, "VK_NONCONVERT" -> 29, "VK_ACCEPT" -> 30, "VK_MODECHANGE" -> 31, "VK_SPACE" -> 32, "VK_PRIOR" -> 33, "VK_NEXT" -> 34, "VK_END" -> 35, "VK_HOME" -> 36, "VK_LEFT" -> 37, "VK_UP" -> 38, "VK_RIGHT" -> 39, "VK_DOWN" -> 40, "VK_SELECT" -> 41, "VK_PRINT" -> 42, "VK_EXECUTE" -> 43, "VK_SNAPSHOT" -> 44, "VK_INSERT" -> 45, "VK_DELETE" -> 46, "VK_HELP" -> 47, "VK_LWIN" -> 91, "VK_RWIN" -> 92, "VK_APPS" -> 93, "VK_SLEEP" -> 95, "VK_NUMPAD0" -> 96, "VK_NUMPAD1" -> 97, "VK_NUMPAD2" -> 98, "VK_NUMPAD3" -> 99, "VK_NUMPAD4" -> 100, "VK_NUMPAD5" -> 101, "VK_NUMPAD6" -> 102, "VK_NUMPAD7" -> 103, "VK_NUMPAD8" -> 104, "VK_NUMPAD9" -> 105, "VK_MULTIPLY" -> 106, "VK_ADD" -> 107, "VK_SEPARATOR" -> 108, "VK_SUBTRACT" -> 109, "VK_DECIMAL" -> 110, "VK_DIVIDE" -> 111, "VK_F1" -> 112, "VK_F2" -> 113, "VK_F3" -> 114, "VK_F4" -> 115, "VK_F5" -> 116, "VK_F6" -> 117, "VK_F7" -> 118, "VK_F8" -> 119, "VK_F9" -> 120, "VK_F10" -> 121, "VK_F11" -> 122, "VK_F12" -> 123, "VK_F13" -> 124, "VK_F14" -> 125, "VK_F15" -> 126, "VK_F16" -> 127, "VK_F17" -> 128, "VK_F18" -> 129, "VK_F19" -> 130, "VK_F20" -> 131, "VK_F21" -> 132, "VK_F22" -> 133, "VK_F23" -> 134, "VK_F24" -> 135, "VK_NUMLOCK" -> 144, "VK_SCROLL" -> 145, "VK_OEM_PLUS" -> 187, "VK_OEM_COMMA" -> 188, "VK_OEM_MINUS" -> 189, "VK_OEM_PERIOD" -> 190, "VK_OEM_2" -> 191, "VK_OEM_5" -> 220, "VK_OEM_8" -> 223, "VK_PACKET" -> 231};
{ "pile_set_name": "StackExchange" }
Q: window.location.href not working in form onsubmit So i have a form, and onsubmit="return reg_check(this)" where reg_check() is a javascript function in the header which is supposed to check the form data, and since one of its tasks is to check if the username is in the database which requires php, i want to redirect to a php page that does this task. Problem is: window.location.href is not working! Here's the function (reduced version) and of course the main.php is just a random page i got: function reg_check(myForm) { alert("before redirect.."); window.location.href = "http://localhost/main.php?width=" + screen.width + "&height=" + screen.height; alert("after redirect.."); } The before redirect and after redirect alerts work, it just doesn't redirect? It remains in the same page. Also, if I tried to redirect from the body by just typing : <script type="text/javascript"> alert("before redirect.."); window.location.href = "http://localhost/main.php?width=" + screen.width + "&height=" + screen.height; alert("after redirect.."); </script> it redirects. Any ideas of how I could get this to work? A: You need to return false; from your reg_check function and then in your onsubmit, change it to: onsubmit="return reg_check(this);" This will cancel the form submission. And if you want to let the form submit as normal, just return true from reg_check. Edit (to be more clear you need to add return false; from your function): function reg_check(myForm) { alert("before redirect.."); window.location.href = "http://localhost/main.php?width=" + screen.width + "&height=" + screen.height; return false; }
{ "pile_set_name": "StackExchange" }
Q: How to analyze a large core dump generated when JVM crashes My web application using Java one day crashed and generated a large core dump (5.5GB). I tried to use IBM Thread and Monitor Dump Analyzer for Java to analyze this core dump, but while reading the core dump, the console said: Exception in thread "Thread-0" java.lang.OutOfMemoryError: Requested array size exceeds VM limit at java.util.Arrays.copyOf(Arrays.java:3332) at java.lang.AbstractStringBuilder.expandCapacity(AbstractStringBuilder.java:137) at java.lang.AbstractStringBuilder.ensureCapacityInternal(AbstractStringBuilder.java:121) at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:569) at java.lang.StringBuffer.append(StringBuffer.java:369) at java.io.BufferedReader.readLine(BufferedReader.java:370) at java.io.BufferedReader.readLine(BufferedReader.java:389) at com.ibm.jinwoo.thread.FileTask.processThreadDump(FileTask.java:1858) at com.ibm.jinwoo.thread.FileTask$ActualTask.<init>(FileTask.java:215) at com.ibm.jinwoo.thread.FileTask$1.construct(FileTask.java:1368) at com.ibm.jinwoo.thread.ThreadHandler$1.run(ThreadHandler.java:31) at java.lang.Thread.run(Thread.java:745) It seems that the core file is too large to analyze with this tool. Increasing the heap size with the option -Xmx10g did not work. What tool can be used to analyze such large core file? Updated 2016-08-17 13:07: I tried to use Eclipse MAT tool but I encountered an following error when I tried to read the dump file. Error opening heap dump 'jvm-core.13074'. Check the error log for further details. Error opening heap dump 'jvm-core.13074'. Check the error log for further details. Not a HPROF heap dump (java.io.IOException) Not a HPROF heap dump Do I need to do kind of pre-processing or something to make the dump file readable to Eclipse MAT tool? A: It seems that this core file is not for Java-related tools like Eclipse MAT tool or IBM Thread and Monitor Dump Analyzer for Java. The tools for the core file are gdb or pmap, pstack. I thought I can debug why application crashes JVM, but the core file seems to have little information about application-level things.
{ "pile_set_name": "StackExchange" }
Q: How to Interpret This Response to a LOR Request As I mentioned in my last post, I experienced a lot of stress during my last undergraduate semester as well as an episode of depression due to my professor's upcoming retirement. (I deeply admired her and wanted her to be my graduate advisor.) Honestly, I think the depression affected me even more than the stress, but I couldn't tell her about it at the time. She had taught me a total of 2 semesters, and I thought we had a good rapport. When I asked to be in her graduate level course toward the end of my first class with her, she enthusiastically replied "..You have been a terrific student this summer and it would be my pleasure to continue working with you..." I also asked about a letter of recommendation when I had written to her, and she said that we could discuss it the next semester but "given your excellent work so far, I am inclined to write." Fast forward to that semester, and a lot happened that I feel affected the quality of my work. First, I spent nearly half the semester moving every few days (she knew about the situation), and that gave me a late start on the research paper. However, my housing stabilized mid-semester, which still gave me ample time to produce quality work. Later in the semester, however, when I asked her to be my graduate advisor, she met with me to explain that she was in the process of retiring and not taking on new students. (She was also living out of state.) This news of her not being in my life anymore after that semester caused me to have a mental breakdown, and I lost a lot of my motivation and had difficulty concentrating on the research paper. Additionally, I decided to change topics just a couple of weeks before it was due. (I don't even know why I did this, it was just part of my breakdown/reaction.) I received an A in the course and an A- on the paper, but it was the sloppiest paper ever written and the writing was horrible. Had I graded a paper like that, I would have given it no more than a C-. She probably did take my housing situation into consideration with the grade, but I don't feel that sufficiently explains such poor quality work. (Again, I couldn't tell her that I was depressed because she was retiring.) So, from her perspective, I might just not have been cut out for graduate school, at least that's what I worried that she thought. Nonetheless, I emailed her after the semester asking her if I could still use her as a job reference and asked if I could "contact her in the future" for a letter of recommendation for grad. school. I figured that she would be less likely to decline to be a job reference, so I deliberately coupled these requests. I also mentioned being inspired by her work etc., but it probably sounded insincere. It wasn't, though, honestly, I don't think I could have handled her declining the lor because of how much I admired her. (So I admittedly made it difficult for her to directly decline.) Anyway, she responded right away (wishing me a Happy New Year) and saying that I could still use her as a job reference and "contact her in the future re: grad. school applications." However,given her previous enthusiasm when I asked to be in the grad. level course, I perceived this as a hint that she wouldn't write the letter. She also signed this letter with "Sincerely" instead of "Best" or something similar, which further confirmed my impression. Having an anxiety disorder, I sometimes read a lot into nothing, as I'm always anticipating the worst. However, given the quality of my paper, I don't know...So I wanted to ask how others would interpret her response. Does it sound like my initial thoughts were probably right? Alternatively, does it seem like she may have written a weak letter, the kind that says you're not recommending the student? Or, does it sound like I indeed read too much into everything and ruined our good rapport? In retrospect, I should have sent another email directly asking if she felt comfortable writing a supportive letter of recommendation and explained that I would understand if she didn't. However, having permission to "contact her in the future," I instead submitted a proposal (in an area I had no background in) to a conference she was attending, and the rest is history.(see previous post) A: After having read your last post, and now this post, it sounds like you have developed an unhealthy relationship towards this professor that is approaching harassment... From your previous post... "Long story short, after continuously trying to have the grievance dismissed, the university sent me a cease and desist letter, which seems to be functioning as a no contact order, as it prohibits me from communicating with anyone except the General Counsel's office." From this post... " I don't think I could have handled her declining the lor because of how much I admired her. (So I admittedly made it difficult for her to directly decline.)" " I instead submitted a proposal (in an area I had no background in) to a conference she was attending, and the rest is history" ... This made me uncomfortable to read. You went through all of this trouble just for the slim chance of seeing one person that you filed an official complaint against regarding their "tone" ... From your previous post and this post, you are demonstrating unhealthy, manipulative, and I would say borderline abusive behavior by any standard. At this point, it seems as if you have put this professor through something they did not really deserve and the continuation, by means of this forum, is a sign that you need to speak with somebody about your unhealthy fixation on the professor and their thoughts about you. While I understand that you might have G.A.D, it is not an excuse for forcing yourself into someone's life simply because you would like it to be that way. They gave you a letter, now you need to move on, both for your sake and for theirs.
{ "pile_set_name": "StackExchange" }
Q: What is the difference between 'ls --color' and 'ls --color=tty'? I am making an alias for ls in my .zshrc profile so that it always has a colored output. As it turns out, I stumbled across either alias ls="ls --color=tty" or, without the tty value alias ls="ls --color" Is there any particular situation where either the commands $ ls --color=tty and $ ls --color, or the above aliases, can behave differently ? A: With no argument attached to the option (--color), the output is always colorized. With --color=tty, it is only colorized when stdout is connected to a tty. This matters when the output of ls is piped or redirected.
{ "pile_set_name": "StackExchange" }
Q: How to use Turkish characters in xml? I am using xml and have a problem with Turkish characters. Just like this <Ürün></Ürün>... I use str_replace for solution but it's not giving desired results. What do I have to do? A: The above XML snippet is perfectly valid, as long as you've saved the XML with the correct character encoding. The default encoding for XML, if you don't specify a different one in the <?xml declaration, is UTF-8. If you have saved the file containing <Ürün> in a different encoding to UTF-8 — presumably Windows code page 1254 Turkish — it will not parse as UTF-8, so either add a <?xml version="1.0" encoding="windows-1254"?> declaration or, much better and more portable, simply save it as UTF-8 instead. Use ‘Save as’ in your text editor and pick out that encoding. (If your text editor does not afford you that option, or it insists on re-loading UTF-8 files in code page 1254, get a better text editor.)
{ "pile_set_name": "StackExchange" }
Q: Pyspark remove columns with 10 null values I am new to PySpark. I have read a parquet file. I only want to keep columns that have atleast 10 values I have used describe to get the count of not-null records for each column How do I now extract the column names that have less than 10 values and then drop those columns before writing to a new file df = spark.read.parquet(file) col_count = df.describe().filter($"summary" == "count") A: You can convert it into a dictionary and then filter out the keys(column names) based on their values (count < 10, the count is a StringType() which needs to be converted to int in the Python code): # here is what you have so far which is a dataframe col_count = df.describe().filter('summary == "count"') # exclude the 1st column(`summary`) from the dataframe and save it to a dictionary colCountDict = col_count.select(col_count.columns[1:]).first().asDict() # find column names (k) with int(v) < 10 bad_cols = [ k for k,v in colCountDict.items() if int(v) < 10 ] # drop bad columns df_new = df.drop(*bad_cols) Some notes: use @pault's approach if the information can not be retrieved directly from df.describe() or df.summary() etc. you need to drop() instead of select() columns since describe()/summary() only include numeric and string columns, selecting columns from a list processed by df.describe() will lose columns of TimestampType(), ArrayType() etc
{ "pile_set_name": "StackExchange" }
Q: splitting string as per regex in typescript is not working as expected for multiple space In typescript I want to divide a name as per space. So, I used something like this const splitted = name.split(' '); It is working as expected, but if wrongly someone gave more than one space. So, i tried to handle multiple space to split. Like this, const splitted = name.split('\\s+'); But, it is taking the whole string as 1 And, length of splitted varabel it is showing 1 It is working in java Any explanation? A: If you want to split along a regular expression, you need to pass an actual regular expression to split: const splitted = name.split(/\s+/); Your current code will split along a literal backslash, followed by a literal s and +, eg: const name = 'foo\\s+bar'; const splitted = name.split('\\s+'); // splitted: ['foo', 'bar'];
{ "pile_set_name": "StackExchange" }
Q: back img button position on resize window or rotate mobile device Starting here tag img position on resize window or rotate mobile device , now I need to add another image (like a back button), before "Search..." (the magnifying glass is now ok). Default, this second image (back button) is hidden, and when I press the Search input, I want to show it. And when I hit enter, disappears. I tried to multiple backgrounds, but I don't know how to make the back button clickable. I tried this, but when I resize the window or when I rotate the mobile device, the back image move and does not look good. HTML: ... <div id="input_search"> <form method="post"> <input type="text" name="search" id="search" maxlenght="50" value="" placeholder="Cautati..."> </form> <img id="back" src="img/back.png"> </div> ... CSS: #input_search input { background-color: #ffa366; color: black; padding: 15px 0px; float: left; border: 0px; font-size: 16px; margin: 1% 0px 1% 0px; width: 100%; } #search { background-image: url('/img/loupa.png'); background-size: 25px 25px; background-repeat: no-repeat; background-position: right 7px bottom 11px; } .indent1 { text-indent: 17px; } .indent2 { text-indent: 57px; } #back { float: left; position: relative; display: none; height: 24px; margin-top: -11%; margin-left: 1%; } JS: $(document).ready(function() { $('#input_search #search').addClass('indent1'); }); $('#search').click(function() { $('#input_search #search').removeClass('indent1'); $('#input_search #search').addClass('indent2'); $('#back').show(); }); $('#search').keypress(function(event) { var keycode = (event.keyCode ? event.keyCode : event.which); if(keycode == '13') { $( function() { $('#back').hide(); $('#search').removeClass('indent2'); $('#input_search #search').addClass('indent1'); }); } }); How can I fix this also? Thank you PS. Please, excuse my bad English. A: You can use flex on your form element (that way you can get rid of float) and wrap your image inside an a tag to make it clickable. $(document).ready(function() { $('#input_search #search').addClass('indent1'); }); $('#search').click(function() { $('#input_search #search').removeClass('indent1'); $('#input_search #search').addClass('indent2'); $('#back').show(); }); $('#search').keypress(function(event) { var keycode = (event.keyCode ? event.keyCode : event.which); if(keycode == '13') { $( function() { $('#back').hide(); $('#search').removeClass('indent2'); $('#input_search #search').addClass('indent1'); }); } }); #input_search input { background-color: #ffa366; color: black; padding: 15px 0px; border: 0px; font-size: 16px; margin: 1% 0px 1% 0px; width: 100%; display:inline-block; } #input_search form { width: 100%; background-color: #ffa366; display:flex; align-items:center; padding:0 5px; } #search { background-image: url('http://www.chinabuddhismencyclopedia.com/en/images/thumb/b/b8/Nature.jpg/240px-Nature.jpg'); background-size: 25px 25px; background-repeat: no-repeat; background-position: right 7px bottom 11px; } .indent1 { text-indent: 17px; } .indent2 { text-indent: 17px; } #back { position: relative; display:none; height: 24px; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="input_search"> <form method="post"> <a href="#"><img id="back" src="http://images.financialexpress.com/2015/12/Lead-image.jpg"></a> <input type="text" name="search" id="search" maxlenght="50" value="" placeholder="Cautati..."> </form> </div>
{ "pile_set_name": "StackExchange" }
Q: Tkinter - bug that shows forgotten labels on corner of screen? Screenshot: http://puu.sh/wiuP7/957bca09ea.png My code is attached and roughly does the following: Grabs data from SQL server For each product it lists all printed products and all scanned products. There could be multiple prints (see P039 on the bottom). It does this using labels. Every 5 seconds it runs using after(), and when it does it uses grid_forget() to remove all of the "old" labels.. it runs the for loop and the updated labels are there, 5 seconds later with no blinking or any noticeable interruption. The issue: After an undetermined amount of time it will no longer loop correctly. It will not show any labels and there will be what looks like a pile of labels sitting on the top left corner of my window. However in the screenshot, the pile in the corner is actually because of an instance of the script that I had closed, so the open instance (with the labels all there correctly) is good, so far. The bug in the corner is from a previously closed instance. Nonetheless, if I haven't had opened it again, you would see nothing instead of the list of products and numbers. This always occurs, no matter what. I have learned that increasing the after() delay also increases the time it takes for it to happen. For example, it happened in roughly 20-30 mins when the delay was 2000 ms, but it took hours (not sure how long, at least 5) when the delay was 10000 ms. Manually running the for loop at the top of the function using a different function and a button does not fix it. I am using tkinter on python 3.6.1. I have seen it on windows 10 and Windows Server 2008 r2 through remote desktop The code of interest is below, this does all the work with updating and such. My entire code is long, but here are my includes as well: EDIT: It appears that if the program is minimized it will not occur. import time import threading import logging import datetime import tkinter as tk from tkinter import * import tkinter.scrolledtext as ScrolledText from tkinter.ttk import Separator, Style from collections import Counter import pypyodbc And here is the updating function: def build_productionrpt(self, LotDate, Shift): for label in self.grid_slaves(): if int(label.grid_info()["column"]) >= 0 and int(label.grid_info()["row"]) >= 3: label.grid_forget() self.products = [] self.r = 3 self.c = 0 # Get all printed labels for current date and shift labels = ProductionReport.LabelsByShift(LotDate,Shift,option="Labels") # Only look at the DatePrinted and the ProductID product_batch_sets = [(record[0], record[1]) for record in labels] # Sort so that we only get unique values, otherwise there would be a duplicate for every unit. product_batch_unique_sets = list(set(product_batch_sets)) # Get all units for each batch and sort by PrintedDate, UnitNumber, and RFIDSerial. Currently we are not using RFIDSerial for anything in this report batch_unit_sets = [(record[0], record[6], record[5]) for record in labels] # Sort so that we only get unique values, otherwise there would be a duplicate for every unit. batch_unit_unique_sets = list(set(batch_unit_sets)) # Get all scanned labels for current date and shift, sort by PrintedDate, UnitNumber, and RFIDSerial. Currently we are not using RFIDSerial for anything in this report units_scanned_sets = [(record[0], record[6], record[5]) for record in ProductionReport.LabelsByShift(LotDate,Shift,option="Scanned")] # Remove all duplicate scans units_scanned_unique_sets = list(set(units_scanned_sets)) # Begin by going through each row for record in product_batch_unique_sets: # Get each unique product from the list, if it's already in self.products then it's been Labeled and we can move on if record[1] not in self.products: # Add to self.products so we don't label it twice self.products.append(record[1]) # Label it on the GUI, using row 3 as the first row. # First, make sure the labels haven't gotten too far. If it has, reset the row count and change the column if self.r > 35: self.c = 1 self.r = 2 elif self.r > 35 and self.c == 1: self.c = 2 self.r = 2 Label(self, text=record[1], font=("Helvetica", 16, "bold")).grid(row=self.r, column=self.c, sticky="nw", rowspan=3) # Add 3 rows to r, to make room for the Product label. self.r+=3 # Set the current product to what we just labeled, so we know what to use as a reference when getting batches. current_product = record[1] # Get all batches for this product and put them in a list all_batches = [i for i,v in product_batch_unique_sets if v == current_product] # Now take each batch from the list we just made.. for batch in all_batches: # Label it # Label(self, text=str(batch), font=("Helvetica", 10)).grid(row=self.r, column=0, sticky="nw") # Add 2 rows to make room for the batch and for the unit numbers # Get all unitnumbers printed for this specific batch all_unitnumbers = [v for i,v,u in batch_unit_unique_sets if i == batch] # Sort them so it's readable all_unitnumbers.sort() # Get all units that were scanned from this batch all_scannedunits = [v for i,v,u in units_scanned_unique_sets if i == batch] # Sort them so it's readable all_scannedunits.sort() # Label the scanned units, they are green Label(self, text=str(all_scannedunits), font=("Helvetica", 8), wraplength=500, justify="left", fg="green").grid(row=self.r, column=self.c, sticky="nw", padx=20) # Add 2 rows to make room for the unscanned units self.r+=2 # This takes all printed units, and subtracts all scanned units from that. What's left is the units that were printed but not scanned a = Counter(all_unitnumbers) b = Counter(all_scannedunits) c = a - b # Label all units printed but not scanned Label(self, text=str(list(c.elements())), font=("Helvetica", 8), wraplength=500, justify="left", fg="red").grid(row=self.r, column=self.c, sticky="nw", padx=20) # Add two rows to make room for the next Product self.r+=2 # all_noscans = [v for i,v,u in units_noscan_unique_sets if i == batch] # Label(self, text=str(all_noscans), font=("Helvetica", 8)).grid(row=self.r, column=0, sticky="nw", padx=20) # self.r+=3 if should_continue_prod_report: self.after(5000, lambda:self.build_productionrpt(self.lotdate_e.get(), self.shift_e.get())) A: I was able to fix this issue by: Storing all labels in a dictionary with the key being something like ProductVariable + "_label" and the value would be the label Storing all textvariables in the same dictionary. I had to change the label(root, text=..) to label(root, textvariable=..) In every for loop, check and see if the label existed. If it does, use set() to update it. Basically, it was bad practice to create labels every 5 seconds and forget the old ones as a method to updating data live.
{ "pile_set_name": "StackExchange" }
Q: Joomla form field required even though required attribute changed to false I have a form with a field that is required in some instances and not in others so I have changed the required attribute on the fly in the edit view file with the setFieldAttribute function: if (_condition_) { $this->form->setFieldAttribute('transprice', 'required', 'false'); } this works and is reflected in the html output. However when I try to save the form I'm still getting: Warning Field required: Transfer Price Is there something else I need to consider to get this to work? A: Without seeing all your code it's hard to answer this question but our best option would be to use javascript to set and unset the required part of this field. If you're using a form that uses Validation.js then you can dynamically set the requrired class on the page via javascript. So long answer short: 1) Leave it un-required in the XML. Because if you're using JForm, JForm is going to rely on that no matter what you set. 2) Dynamically set the required class so validation.js can refer to it and see if the form should be required or not. This is only a client side validation. 3) For server side validation you will need to override the data model and the controller to determine (again) if the field should be required based on your other dynamic data. Read more about that here: http://docs.joomla.org/Form_field#Client-side_validation
{ "pile_set_name": "StackExchange" }
Q: Can I make a HTML5 updateable database to search locally? I'm making a site with huge focus on index searching inside the site. The problem lies with the querys, as the production server is very cheap. I thought that could be a good idea to start with node.js instead of PHP for developing. But the problem lies far more ahead. I want to push part (Name, Surname, Tags, URL) of the database of the site to the client browser and make a search locally, push live updates every time a new entry in the database is added by a user, and re-download everything after 24 hours more or less. That way the server doesn't work too much putting the results in the client, only pushing the new entries instead or the database. Can I do that? What should I need? I thought about using IndexedDB and add a polyfill for WebSQL browsers, but I don't know if these technologies can do that I'm asking for today. A: IndexedDB is the perfect tool for this job, presuming the compatibility works for your customer base. While WebSQL would be an enviable alternative, know that for all intents and purposes the spec is "dead" and will not be developed further. IDB is an "indexed" JavaScript object store, so you can add indexes on your object attributes and "cursor" across them without a huge performance overhead associated with trying to do this using something like localStorage. For example, say you have a customer list. You can add customer objects { 'name': 'blah', 'surname': 'McBlaherson', 'tags': [ 1, 2, 3] }, add some indexes and use IDB to, say, return all customers by surname. The big challenge in what you're describing is handling the "sync" aspects of a client-server model. Say the user opens up the site on a browser and on his mobile phone. How do you merge the data stores? It sounds easy but I assure you it's not (which is why git and other version control systems are so magic).
{ "pile_set_name": "StackExchange" }
Q: Onchange input event isn't fired on jquery I'm working with jquery. And i have text input in a form, i would like to process the change event. $("#my_input").change(function(){alert('123');}); the event is fired normally when i edit the field manually, but when i change the field's value with a script (sometimes with an external script) it doesn't work. is there any solution ? and thanks in advance. A: The change event is not designed to detect programmatic changes. You can trigger the event manually when setting the value, though: $('#my_input').trigger('change'); shortcut: $('#my_input').change();
{ "pile_set_name": "StackExchange" }
Q: Javascript convert canvas to img I am using cropper js to crop images. more info at: https://github.com/fengyuanchen/cropperjs so this is my javascript code to get cropped picture as canvas var result = document.getElementById('result'); result.innerHTML = ''; result.appendChild(cropper.getCroppedCanvas()); Result div: <div id="result"></div> after cropped it returns to me canvas inside result div <div id="result"> <canvas width="137" height="137"></canvas></div> My question is how to return as <img src=""></img> instead of <canvas> tag ? A: var image = new Image(); image.id = "pic" image.src = cropper.getCroppedCanvas().toDataURL(); document.getElementById('image_for_crop').appendChild(image);
{ "pile_set_name": "StackExchange" }
Q: Using SSH Keys in Transmit to connect via SFTP I'm using Transmit to connect via SFTP to a server. I know that the public key is properly uploaded etc. because I can connect via SSH on the command line. For some reason I can't connect with SFTP in Transmit. My keys are in the default location (~/.ssh) so I can't imagine Transmit is having a hard time finding them. A: I sent an email to the makers of transmit to get technical support and it was confirmed that I had encountered a bug. It seems a key with a . in the name will not be recognized by the software -- it can not be loaded up either manually or automatically. Renaming my keys to remove the . solved the problem.
{ "pile_set_name": "StackExchange" }
Q: Do I need an Ubuntu compatible router? Im' thinking about formatting my HD and reinstalling with Ubuntu instead. However I'm concerned about losing internet access. I currently use XP and connect to the net via a router which I can access by typing its IP address into my browser. Will there be any compatibility issues with Ubuntu doing the same? Do i need an ubuntu compatible router or something, or any special software to setup internet access using Ubuntu? A: Other answers have addressed your options while installing and the issue of Ubuntu accessing the Internet. The key points are that it's a good idea to test Ubuntu first on the live CD/DVD/USB (same as what you use to install from), and that your options are explained in various resources that explain how to install it, like this. I'd like to address the question about whether or not you can connect to your router's setup page and configure it, from Ubuntu. Yes. You can access your router's setup page. You do not need a special, compatible router. This is just a web page--the router is itself a machine on your network, and it is running a web server. Any machine that can browse the web can access this. Some devices are configured by plugging them into a computer with a USB cable. Often Windows-only software is necessary to perform this configuration, and this is usually not possible with Ubuntu. Some routers provide this as one way to configure them. But even if your router has a USB port, you don't have to use that to configure it. If your router lets you connect to it in a web browser on Windows, you can do the same thing in Ubuntu. It's possible to design a web page that can only be used by clients on certain operating systems. But routers don't have that sort of client-side active content. Their setup pages are relatively simple, as web pages go. The authentication that is performed is done through universal web protocols. You're good. You should be aware, though, that being able to connect to the router is not actually the same thing as being able to connect to the Internet through it. When you access the Internet through your router, your router's web-based setup page is not actually being used. You can use it to change settings that affect (or even disable and enable) your Internet connection. But when you open a web page other than your router's setup page (and I'm specifically thinking of page whose web server is in a remote location on the Internet), or update Ubuntu, or use instant messaging or bittorrent, or play an online game... the data that's transmitted and received does not go through the router's web page. It goes through the router, but the web page is just there for configuration.
{ "pile_set_name": "StackExchange" }
Q: Cascading - cascading.tuple.TupleException: failed to set a value I am trying to apply ScrubFunction on each tuple and return the tuple with updated values. But i am getting the Exception like.. Caused by: cascading.tuple.TupleException: failed to set a value, tuple may not be initialized with values, is zero length Sample Code: TupleEntry argument = functionCall.getArguments(); Tuple result = new Tuple(); result.setInteger(0, argument.getInteger(0)); result.setString(1, argument.getString(1).toUpperCase()); result.setString(2, argument.getString(2)); result.setString(3, argument.getString(3)); result.setString(4, argument.getString(4)); result.setString(5, argument.getString(5)); functionCall.getOutputCollector().add(result); What if i want to update few fields in a Tuple and return the updated values. Can i update directly in TupleEntry and return it. A: To your first question: don't set values to a tuple, instead, add. Tuple result = new Tuple(); result.addInteger(argument.getInteger(0)); // ... To your second question: yes. See the API doc here: TupleEntry.setObject Hope this helps :)
{ "pile_set_name": "StackExchange" }
Q: f and g are bounded . if 1/g is bounded, then f/g is bounded. I would like some help understanding how to go about this question. I think that f/g is not bounded, but I cannot figure how to show that f/g is not bounded. A: We have $|f| < P$, $|g| < Q$, and $|1/g| < R$ for some $P$, $Q$, and $R$, so $$\left|\frac{f}{g} \right|= \left| f\frac{1}{g} \right| < PR.$$
{ "pile_set_name": "StackExchange" }
Q: Implicit conversion to Runnable? As an exercise, I tried to create an implicit conversion that would accept a function and produce a Runnable. That way you could call Java methods that accept Runnable objects and use them like closures. The implicit conversion is easy enough: implicit def funToRunnable(fun : Unit) = new Runnable() { def run = fun } However I don't know how to call it. How do you pass in a no-arg function that returns Unit, without having it be evaluated at once? For example, I'd like the following to print "12" but instead it prints "21" because print("2") is evaluated at once. var savedFun : Runnable = null def save(r : Runnable) = { savedFun = r } save(print("2")) print("1") savedFun.run() How do I tell the compiler to treat print("2") as the body of a function, not something to be evaluated at once? Some possibilities I tried, such as save(() => print("2")) or save(=> print("2")) are not legal syntax. A: arg, just answered my own question. I implemented the implicit conversion incorrectly. The correct implementation is implicit def funToRunnable(fun: () => Unit) = new Runnable() { def run() = fun() } and you call it like this: save(() => print("2")) This will yield "2" A: If you wanted to live dangerously, you could convert anything to a runnable: implicit def whateverToRunnable[F](f: => F) = new Runnable() { def run() { f } } scala> val t = new Thread(println("Hello")) t: java.lang.Thread = Thread[Thread-2,5,main] scala> t.start() Hello Or you could create your own thread-creator-and-starter: def thread[F](f: => F) = (new Thread( new Runnable() { def run() { f } } )).start scala> thread { println("Hi"); Thread.sleep(1000); println("Still here!") } Hi scala> Still here! If you wanted to return the thread, then def thread[F](f: => F) = { val t = new Thread( new Runnable() { def run() { f } } ) t.start() t } But all of this, while useful, is perhaps even less useful than scala.actors.Futures (tested only on 2.8): scala> import scala.actors.Futures scala> val x = Futures.future { Thread.sleep(10000); "Done!" } x: scala.actors.Future[java.lang.String] = <function0> scala> x.isSet res0: Boolean = false scala> x.isSet res1: Boolean = false scala> x() // Waits until the result is ready.... res2: java.lang.String = Done! A: Interesting, this way you can execute code that receives a Runnable and pass it a closure. See: scala> new Thread( () => print( "Hello" ) ).start() <console>:5: error: overloaded method constructor Thread with alternatives (java.lang.ThreadGroup,java.lang.Runnable,java.lang.String,Long)java.lang.Thread <and> (java.lang.ThreadGroup,java.lang.Runnable,java.lang.String)java.lang.Thread <and> (java.lang.Runnable,java.lang.String)java.lang.Thread <and> (java.lang.ThreadGroup,java.lang.String)java.lang.Thread <and> (java.lang.String)ja... new Thread( () => print( "Hello" ) ).start() scala> implicit def funcToRunnable( func : () => Unit ) = new Runnable(){ def run() = func() } funcToRunnable: (() => Unit)java.lang.Object with java.lang.Runnable scala> def doRun( runnable: Runnable ) = runnable.run doRun: (Runnable)Unit scala> doRun( () => print("Hola")) Hola scala> new Thread(()=>print("Hello")).start() scala> Hello
{ "pile_set_name": "StackExchange" }
Q: Is it possible to create proxy type of integer? That was just a test I tried. I want to make a type which behaves exactly like int. I tried to make a proxy type like this: class myint : int { } but then myint won't be value type. Is there a way to create a proxy type of int? P.S. I know about extension methods. A: Value types can only implement interfaces - you can't inherit from another value type. So, you can't inherit from int. You can wrap an int in a class/struct as a field.
{ "pile_set_name": "StackExchange" }
Q: QML: passing JS object to C++ member function I'm trying to pass a JS object (map) to a C++ member function with a signature Q_INVOKABLE virtual bool generate(QObject* context); by using a.generate({foo: "bar"}); The method is called (detected via breakpoint), but the passed context parameter is NULL. Since the documentation mentions that JS objects will be passed as QVariantMap, I've tried using the signature Q_INVOKABLE virtual bool generate(QVariantMap* context); but this failed during MOC. Using Q_INVOKABLE virtual bool generate(QVariantMap& context); causes the method to not be found at runtime by QML (error message is "Unknown method parameter type: QVariantMap&"). The documentation only has an example of passing a QVariantMap from C++ to QML, not in the other direction. Using a public slot instead of a Q_INVOKABLE shows exactly the same behavior and errors. A: Don't use references to pass values from QML world to CPP world. This simple example works: test.h #ifndef TEST_H #define TEST_H #include <QObject> #include <QDebug> #include <QVariantMap> class Test : public QObject { Q_OBJECT public: Test(){} Q_INVOKABLE bool generate(QVariantMap context) {qDebug() << context;} }; #endif // TEST_H main.cpp #include <QGuiApplication> #include <QQmlApplicationEngine> #include <QQmlContext> #include "test.h" int main(int argc, char *argv[]) { QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication app(argc, argv); QQmlApplicationEngine engine; engine.rootContext()->setContextProperty(QStringLiteral("Test"), new Test()); engine.load(QUrl(QLatin1String("qrc:/main.qml"))); if (engine.rootObjects().isEmpty()) return -1; return app.exec(); } main.qml import QtQuick 2.7 import QtQuick.Controls 2.0 import QtQuick.Layouts 1.3 ApplicationWindow { visible: true width: 640 height: 480 title: qsTr("Hello World") MouseArea { anchors.fill: parent onClicked: { Test.generate({foo: "bar"}); } } } click in window, this will print following msg in output console: QMap(("foo", QVariant(QString, "bar")))
{ "pile_set_name": "StackExchange" }
Q: Prolog list adding --the question has been edited-- Using this data, I need to create a list: team(milan,1). team(napoli,2). team(lazio,3). team(roma,4). team(inter,4). team(juventus,5). So, given a query like: check([milan,lazio,roma,inter]). make a new list with their respective team number. X=[1,3,4,4] What I'm trying to do is creating a list, adding elements one at a time. check([H|T]) :- team(H,R), append([R],_, X), check(T). Could someone help me complete this? A: You need to find all the team numbers for which the name of the team is a member of the list of team names that you are interested in: ?- findall(Number, ( team(Name, Number), member(Name, [milan, lazio, roma, inter])), Numbers). Numbers = [1, 3, 4, 4]. To return the numbers in a given order, just apply member/2 before team/2, in this case member/2 generates names (in the given order), and team/2 maps them to numbers: ?- findall(Number, ( member(Name, [lazio, milan, inter]), team(Name, Number)), Numbers). Numbers = [3, 1, 4].
{ "pile_set_name": "StackExchange" }
Q: Outlook email alerts every hour? (not immediate) I'm starting to use MS Outlook 2010 for work and I would like email alerts only to show up every hour or so, instead of showing up right when the message is received. Is there a way to make Outlook do this? After having gone through the Options menu and after some research in Google, I haven't found anything useful. Any pointers would be appreciated! A: What version of outlook are you using? and do you want to only receive emails once an hour or just have it alert you every hour? because in later version of outlook you can make it to where it will only send and receive once every hour and then it will alert you about your emails.
{ "pile_set_name": "StackExchange" }
Q: jCarousel Image gallery with thumbnails I currently have an image gallery with 30 - 40 images. Upon page load the user can visually see the images loading for a pretty significant amount of time (less than pretty). The gallery is using jcarousel prev / next buttons to navigate to images as well as thumbnails. I am looking for ways to optimize the way the gallery loads or at least the look of how the gallery is loading. One thought I had is below but wanted to know what the Stack Overflow community thoughts were on best way to address this. Should I load first image and thumbnails, then images upon request? Thank you in advance! A: We implemented this in our website do the following thing. When you construct the carousel , don't construct all the images with src value with images For the first four or five images have the images for src attributes for the next all images store the image valvue in some custom value and give src as some other dummy value Once you click next in the carouse swap the values of src and your custom variables for loading you can show a default loading symbol You can improve performance way better with this approach for example all your next images in your carouse should look something like this <img height="0px" width="0px" border="0" alt="Hidden Depths" title="Hidden Depths" id="yourimage.jpg" class="carouselImage"> once you click swap the image src $('yourimage').attr('src','yourimage'); after that your code should look as below <img height="0px" width="0px" border="0" alt="Hidden Depths" title="Hidden Depths" src="yourimage.jpg" class="carouselImage">
{ "pile_set_name": "StackExchange" }
Q: How to return JSONObject from doInBackground() method to onPostExecute() method on AsyncTask? In Android app i want to return JSONObject from doInBackground() method to onPostExecute() method. Here is the code: private class AddAsyncTask extends AsyncTask<String, Void, String> { JSONObject jsonObjRecv; String result; @Override protected JSONObject doInBackground(JSONObject... params) { AssetObj assetObj = new AssetObj(); assetObj.setAssetName(txtname.getText().toString()); assetObj.setMobileNo(txtmobile.getText().toString()); assetObj.setOwnerId(myApp.getOwnerId()); assetObj.setStartTime(startTime.getText().toString()); assetObj.setEndTime(endTime.getText().toString()); assetObj.setInterval(interval.getText().toString()); JSONObject jsonObjRecv = SyncService.AddNewAssetRequest(assetObj); return jsonObjRecv; } protected void onPostExecute(JSONObject obj){ if(obj != null) { //do something } I have try this code i got error. Is it possible to return JSONObject from doInBackground() method to onPostExecute() method? A: Edited: This could Help you, private class AddAsyncTask extends AsyncTask<String, Void, JSONOnject> { JSONObject jsonObjRecv; String result; @Override protected JSONObject doInBackground(String... params) { AssetObj assetObj = new AssetObj(); assetObj.setAssetName(txtname.getText().toString()); assetObj.setMobileNo(txtmobile.getText().toString()); assetObj.setOwnerId(myApp.getOwnerId()); assetObj.setStartTime(startTime.getText().toString()); assetObj.setEndTime(endTime.getText().toString()); assetObj.setInterval(interval.getText().toString()); JSONObject jsonObjRecv = SyncService.AddNewAssetRequest(assetObj); } protected void onPostExecute(JSONObject obj){ if(obj != null) { //do something } Here is it clearly , private class AddAsyncTask extends AsyncTask<What type of input you need to pass to doInBackground(), Void, What type of return value you need to return to onPostExcute()> Probably you dont need to change return values and params in the method declaration. Just create the following line private class AddAsyncTask extends AsyncTask<String, Void, JSONOnject> the methods will be created automatically according to the params and return types you mentioned in private class AddAsyncTask extends AsyncTask<String, Void, JSONOnject>
{ "pile_set_name": "StackExchange" }
Q: Place arithmetic signs in correct order to get the number Given a list of numbers, place signs + or - in order to get the required number. If it's possible then return true, otherwise return false [1, 2, 3, 4, 5, 7]; 12 -> true, because 1 + 2 + 3 + 4 - 5 + 7 = 12 [5, 3]; 7 -> false, because 5 + 3 != 7 and 5 - 3 != 7 I came up with the following brute force solution: public static boolean trueOrNot(int number, List<Integer> numbers) { boolean found = false; int i = 0; while (!found && i < (1 << numbers.size())) { int tmpResult = 0; for (int j = 0; j < numbers.size(); j++) { int num = numbers.get(j); if ((i & (1 << j)) > 0) { num = -num; } tmpResult += num; } found = tmpResult == number; i++; } return found; } Basically, I took for consideration binary representations of numbers 0000, 0001, 0010...2^n and iterate over every bit, thus getting all possible combinations. 0 is a + sign and 1 is - sign. Then I calculate temporal result and once it is equal to the sought number I break out from loop. Time complexity: O(2n) Space complexity: O(1) I just wondering is there any more effective solution with the help of Dynamic Programming, for example? Feedback for the current solution? A: Actually after some studying I figured out another optimal way of solving this problem: public static boolean trueOrNot(int T, ArrayList<Integer> nums) { Map<Integer, Map<Integer, Boolean>> cache = new HashMap<>(); return trueOrNot(nums, T, 0, 0, cache); } private static boolean trueOrNot(ArrayList<Integer> nums, int T, int i, int sum, Map<Integer, Map<Integer, Boolean>> cache) { if (i == nums.size()) { return sum == T; } if (!cache.containsKey(i)) cache.put(i, new HashMap<>()); Boolean cached = cache.get(i).get(sum); if (cached != null) return cached; boolean result = trueOrNot(nums, T, i + 1, sum + nums.get(i), cache) || trueOrNot(nums, T, i + 1, sum - nums.get(i), cache); cache.get(i).put(sum, result); return result; }
{ "pile_set_name": "StackExchange" }
Q: Swap Characters Using Command Prompt Trying to write a program called SwapChars.java using command line arguments that allows any two characters to be swapped. For example if the program was called SwapChars then to swap all ‘a’s and ‘b’s in a file test.txt we would type java SwapChars test.txt ab I typed the following code which kept giving me an exception error and I'm not sure where I'm going wrong... import java.util.*; import java.io.*; public class SwapChars { public static void main(String[] args) throws IOException { String a = args[0]; //file name (test.txt entered into command line) FileReader fr = new FileReader(a); String b = args[1];//which characters to swap int t = fr.read(); while(t!=-1) { if(t==b.charAt(0)) { System.out.println(b.charAt(1)); } else if(t==b.charAt(1)) { System.out.println(b.charAt(0)); } else { System.out.println((char)t); } t=fr.read(); } // TODO Auto-generated method stub } } Exception error as follows: Exception in thread "main" java.io.FileNotFoundException: test.txt (The system cannot find the file specified) at java.io.FileInputStream.open0(Native Method) at java.io.FileInputStream.open(Unknown Source) at java.io.FileInputStream.<init>(Unknown Source) at java.io.FileInputStream.<init>(Unknown Source) at java.io.FileReader.<init>(Unknown Source) at SwapChars.main(SwapChars.java:7) I can get the desired output when I change my code to remove the need for commands as follows: import java.util.*; import java.io.*; public class SwapCharsTest { public static void main(String[] args) throws IOException{ FileReader fr = new FileReader("test.txt"); String swap = "ab"; int t = fr.read(); while(t!=-1) { if(t==swap.charAt(0)) { System.out.print(swap.charAt(1)); } else if(t==swap.charAt(1)) { System.out.print(swap.charAt(0)); } else { System.out.print((char)t); } t=fr.read(); } // TODO Auto-generated method stub } } A: The exception is because the file cannot be found. Try to refer to the file with a full path. Also, when the file is found, your program will loop forever. And the printout can easily be improved. Make these two changes: else { System.out.println((char) t); } t = fr.read(); } (t = fr.read(); reads a new char for every loop, (char) casts the integer so it looks better on screen) If you don't want to use a full path, you need to figure out where Java will look for the file. This will (most likely) show you where to put the file: System.out.println(new File("dummy").getAbsolutePath());
{ "pile_set_name": "StackExchange" }
Q: Expo build:ios fails with "Error while gathering & validating credentials" I'm trying to run exp build:ios and it returns the following error: Running: bash.exe -c PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin /mnt/c/Users/MyName/AppData/Roaming/npm/node_m odules/exp/node_modules/@expo/traveling-fastlane-linux/traveling-fastlane-1.4.7-linux-x86_64/validate_apple_credentials "USERNAME PASSWORD" Error while gathering & validating credentials 04:55:52 [exp] Error: Reason:Unknown reason, raw:"{\"authType\"=>\"sa\"}\naa=11CECD94B0A448A2CA74B798F957D91C; Domain=idmsa.apple.com; Path=/; Secure ; HttpOnly, dslang=US-EN; Domain=apple.com; Path=/; Secure; HttpOnly, site=USA; Domain=apple.com; Path=/; Secure; HttpOnly, acn01=ecHGTzyh6KpEMYGK3/n dp5OBSctZ7OhjWIMEzX9jeHHDdeMxlEYAEHHyjSOfEg==; Max-Age=31536000; Expires=Wed, 22-May-2019 01:55:52 GMT; Domain=apple.com; Path=/; Secure; HttpOnly" 04:55:52 [exp] Reason:Unknown reason, raw:"{\"authType\"=>\"sa\"}\naa=11CECD94B0A448A2CA74B798F957D91C; Domain=idmsa.apple.com; Path=/; Secure; HttpO nly, dslang=US-EN; Domain=apple.com; Path=/; Secure; HttpOnly, site=USA; Domain=apple.com; Path=/; Secure; HttpOnly, acn01=ecHGTzyh6KpEMYGK3/ndp5OBSc tZ7OhjWIMEzX9jeHHDdeMxlEYAEHHyjSOfEg==; Max-Age=31536000; Expires=Wed, 22-May-2019 01:55:52 GMT; Domain=apple.com; Path=/; Secure; HttpOnly" 04:55:52 I'm trying to build on the following platform: OS: Windows 10(with WSL Ubuntu 18.04) Expo: 27.0.2 And have the following on package.json: { "name": "APP_NAME", "version": "0.1.0", "private": true, "devDependencies": { "jest-expo": "^27.0.0", "react-native-scripts": "1.11.1", "react-test-renderer": "16.2.0" }, "main": "./node_modules/react-native-scripts/build/bin/crna-entry.js", "scripts": { "start": "react-native-scripts start", "eject": "react-native-scripts eject", "android": "react-native-scripts android", "ios": "react-native-scripts ios", "test": "node node_modules/jest/bin/jest.js" }, "jest": { "preset": "jest-expo" }, "dependencies": { "@expo/vector-icons": "^6.3.1", "exp": "^54.0.0", "expo": "^27.0.2", "native-base": "^2.4.4", "npm": "^6.0.1", "react": "16.3.1", "react-native": "https://github.com/expo/react-native/archive/sdk-27.0.2.tar.gz", "react-native-animatable": "^1.2.4", "react-native-autocomplete-input": "^3.5.0", "react-native-collapsible": "^0.11.2", "react-native-modal": "^5.4.0", "react-native-scrollable-tab-view": "^0.8.0", "react-native-simple-twitter": "^1.2.1", "react-native-slider": "^0.11.0", "react-native-snap-carousel": "^3.7.0", "react-native-svg-uri": "^1.2.3", "react-native-swiper": "^1.5.13", "react-navigation": "^1.5.12", "react-redux": "^5.0.7", "redux": "^3.7.2" } } And also app.json: { "expo": { "name": "APP_NAME", "description": "APP_NAME description", "slug": "Appname", "privacy": "public", "sdkVersion": "27.0.0", "version": "1.0.0", "orientation": "portrait", "androidStatusBar": { "backgroundColor": "#000000" }, "packagerOpts": { "assetExts": ["ttf", "mp4"] }, "ios": { "bundleIdentifier": "com.mycompany.myapp", "supportsTablet": false }, "android": { "package": "com.mycompany.myapp", "versionCode": 4 } } } P.S: running exp build:android works fine. What is the cause of this error, and how can I resolve it? A: Just connect to https://appleid.apple.com/ or http://itunesconnect.apple.com and accept the privacy update.
{ "pile_set_name": "StackExchange" }
Q: Is this a right and effcient way of checking AND in a for loop Just saw this at work in a code review and was wondering if this style of coding - for loop, doing && like that, seems fine to you or is there a better way of doing the same? for (int j = 1; j <= ETtop; j++) { // Check everything. int k = ET[j].PriIdx; for (int z = 1; z <= ET[k].ArgTop; z++ ) { // Check to make sure every Argument in the equation is valid. // If it's a calc this is only true if it's been evaluated. ready = ready && ET[k].Arg[z].Valid; } } A: Currently, once you get ready to be false, all other checks after that will fail (as false && condition2 will always be false). Why not just break out of the inner for loop when ET[k].Arg[z].Valid is false? If ready is needed, you may keep the assignment line, but break when it's false.
{ "pile_set_name": "StackExchange" }
Q: When performing a Core Data migration, how can I carry over old values from the source store from a different entity? I'm performing a migration using Core Data's standard mapping model approach, and it seems to be working fine, except for one thing: I've moved an attribute from one entity to another, and I want to move the underlying value from the source store to that new entity as part of the migration. This should be possible, but I'm having trouble figuring out which steps I need to take to accomplish this. A: I think one way is to subclass NSEntityMigrationPolicy and put your logic there. There you can import the class files of the other needed entity. In Xcode you can set the "Expression" under "Attribute Mapping" as FUNCTION($entityPolicy, "yourMethodName", $source).
{ "pile_set_name": "StackExchange" }
Q: Vue.js transition to appear/occur on element entering viewport Firstly please no jQuery. I could do this in jQuery etc., the point of the question is to do it without unnecessary dependencies. The scenario here is I'm creating a single page website with several sections to scroll through. I want to use Vue.js's transitions to simply fade in once the browser has scrolled to that section. I've managed to make the transitions work with the appear attribute but the problem is this initial render trigger works on elements that are off screen and I want to defer that trigger until when the browser has scroll the element on screen. I've found a library like vue-observe-visibility which would kind of works for what I need but honestly I don't want to create a load of data properties simply for the trigger to change it to true for a v-if statement to trigger the fade in effect. Hopefully that makes some sense. A: one way, using directives, would be have an on-scroll listener. when the element is in view, then add a class that transitions opacity to 1 (or x-offset). Then once it's in view, destroy the listener. This makes is easy to add to elements, as you don't need to manage state for each item, just change <div> to <div class="hidden hidden-left" v-infocus="'showElement'">, for every object you want to do this for. new Vue ({ el: '#app', data() {}, methods: {}, directives: { infocus: { isLiteral: true, inserted: (el, binding, vnode) => { let f = () => { let rect = el.getBoundingClientRect() let inView = ( rect.width > 0 && rect.height > 0 && rect.top >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) ) if (inView) { el.classList.add(binding.value) window.removeEventListener('scroll', f) } } window.addEventListener('scroll', f) f() } } } }) #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } div { min-height: 120px; } h1, h2 { font-weight: normal; } ul { list-style-type: none; padding: 0; } li { display: inline-block; margin: 0 10px; } a { color: #42b983; } /* the classes */ .hidden { opacity: 0; } .hidden-right { transform: translate(50px, 0); } .hidden-left { transform: translate(-50px, 0); } .showElement { opacity: 1; transform: translate(0, 0); -webkit-transition: all 0.5s ease-out; -moz-transition: all 0.5s ease-out; transition: all 0.5s ease-out; } <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.8/vue.min.js"></script> <div id="app"> <div class="hidden" v-infocus="'showElement'"> <h2>Ecosystem</h2> <ul> <li><a href="http://router.vuejs.org/" target="_blank">vue-router</a></li> <li><a href="http://vuex.vuejs.org/" target="_blank">vuex</a></li> <li><a href="http://vue-loader.vuejs.org/" target="_blank">vue-loader</a></li> <li><a href="https://github.com/vuejs/awesome-vue" target="_blank">awesome-vue</a></li> </ul> </div> <div class="hidden hidden-left" v-infocus="'showElement'"> <h2>Ecosystem</h2> <ul> <li><a href="http://router.vuejs.org/" target="_blank">vue-router</a></li> <li><a href="http://vuex.vuejs.org/" target="_blank">vuex</a></li> <li><a href="http://vue-loader.vuejs.org/" target="_blank">vue-loader</a></li> <li><a href="https://github.com/vuejs/awesome-vue" target="_blank">awesome-vue</a></li> </ul> </div> <div class="hidden hidden-right" v-infocus="'showElement'"> <h2>Ecosystem</h2> <ul> <li><a href="http://router.vuejs.org/" target="_blank">vue-router</a></li> <li><a href="http://vuex.vuejs.org/" target="_blank">vuex</a></li> <li><a href="http://vue-loader.vuejs.org/" target="_blank">vue-loader</a></li> <li><a href="https://github.com/vuejs/awesome-vue" target="_blank">awesome-vue</a></li> </ul> </div> <div class="hidden" v-infocus="'showElement'"> <h2>Ecosystem</h2> <ul> <li><a href="http://router.vuejs.org/" target="_blank">vue-router</a></li> <li><a href="http://vuex.vuejs.org/" target="_blank">vuex</a></li> <li><a href="http://vue-loader.vuejs.org/" target="_blank">vue-loader</a></li> <li><a href="https://github.com/vuejs/awesome-vue" target="_blank">awesome-vue</a></li> </ul> </div> <div class="hidden hidden-left" v-infocus="'showElement'"> <h2>Ecosystem</h2> <ul> <li><a href="http://router.vuejs.org/" target="_blank">vue-router</a></li> <li><a href="http://vuex.vuejs.org/" target="_blank">vuex</a></li> <li><a href="http://vue-loader.vuejs.org/" target="_blank">vue-loader</a></li> <li><a href="https://github.com/vuejs/awesome-vue" target="_blank">awesome-vue</a></li> </ul> </div> <div class="hidden hidden-right" v-infocus="'showElement'"> <h2>Ecosystem</h2> <ul> <li><a href="http://router.vuejs.org/" target="_blank">vue-router</a></li> <li><a href="http://vuex.vuejs.org/" target="_blank">vuex</a></li> <li><a href="http://vue-loader.vuejs.org/" target="_blank">vue-loader</a></li> <li><a href="https://github.com/vuejs/awesome-vue" target="_blank">awesome-vue</a></li> </ul> </div> <div class="hidden" v-infocus="'showElement'"> <h2>Ecosystem</h2> <ul> <li><a href="http://router.vuejs.org/" target="_blank">vue-router</a></li> <li><a href="http://vuex.vuejs.org/" target="_blank">vuex</a></li> <li><a href="http://vue-loader.vuejs.org/" target="_blank">vue-loader</a></li> <li><a href="https://github.com/vuejs/awesome-vue" target="_blank">awesome-vue</a></li> </ul> </div> <div class="hidden hidden-left" v-infocus="'showElement'"> <h2>Ecosystem</h2> <ul> <li><a href="http://router.vuejs.org/" target="_blank">vue-router</a></li> <li><a href="http://vuex.vuejs.org/" target="_blank">vuex</a></li> <li><a href="http://vue-loader.vuejs.org/" target="_blank">vue-loader</a></li> <li><a href="https://github.com/vuejs/awesome-vue" target="_blank">awesome-vue</a></li> </ul> </div> <div class="hidden hidden-right" v-infocus="'showElement'"> <h2>Ecosystem</h2> <ul> <li><a href="http://router.vuejs.org/" target="_blank">vue-router</a></li> <li><a href="http://vuex.vuejs.org/" target="_blank">vuex</a></li> <li><a href="http://vue-loader.vuejs.org/" target="_blank">vue-loader</a></li> <li><a href="https://github.com/vuejs/awesome-vue" target="_blank">awesome-vue</a></li> </ul> </div> <div class="hidden" v-infocus="'showElement'"> <h2>Ecosystem</h2> <ul> <li><a href="http://router.vuejs.org/" target="_blank">vue-router</a></li> <li><a href="http://vuex.vuejs.org/" target="_blank">vuex</a></li> <li><a href="http://vue-loader.vuejs.org/" target="_blank">vue-loader</a></li> <li><a href="https://github.com/vuejs/awesome-vue" target="_blank">awesome-vue</a></li> </ul> </div> <div class="hidden hidden-left" v-infocus="'showElement'"> <h2>Ecosystem</h2> <ul> <li><a href="http://router.vuejs.org/" target="_blank">vue-router</a></li> <li><a href="http://vuex.vuejs.org/" target="_blank">vuex</a></li> <li><a href="http://vue-loader.vuejs.org/" target="_blank">vue-loader</a></li> <li><a href="https://github.com/vuejs/awesome-vue" target="_blank">awesome-vue</a></li> </ul> </div> <div class="hidden hidden-right" v-infocus="'showElement'"> <h2>Ecosystem</h2> <ul> <li><a href="http://router.vuejs.org/" target="_blank">vue-router</a></li> <li><a href="http://vuex.vuejs.org/" target="_blank">vuex</a></li> <li><a href="http://vue-loader.vuejs.org/" target="_blank">vue-loader</a></li> <li><a href="https://github.com/vuejs/awesome-vue" target="_blank">awesome-vue</a></li> </ul> </div> <div class="hidden" v-infocus="'showElement'"> <h2>Ecosystem</h2> <ul> <li><a href="http://router.vuejs.org/" target="_blank">vue-router</a></li> <li><a href="http://vuex.vuejs.org/" target="_blank">vuex</a></li> <li><a href="http://vue-loader.vuejs.org/" target="_blank">vue-loader</a></li> <li><a href="https://github.com/vuejs/awesome-vue" target="_blank">awesome-vue</a></li> </ul> </div> <div class="hidden hidden-left" v-infocus="'showElement'"> <h2>Ecosystem</h2> <ul> <li><a href="http://router.vuejs.org/" target="_blank">vue-router</a></li> <li><a href="http://vuex.vuejs.org/" target="_blank">vuex</a></li> <li><a href="http://vue-loader.vuejs.org/" target="_blank">vue-loader</a></li> <li><a href="https://github.com/vuejs/awesome-vue" target="_blank">awesome-vue</a></li> </ul> </div> <div class="hidden hidden-right" v-infocus="'showElement'"> <h2>Ecosystem</h2> <ul> <li><a href="http://router.vuejs.org/" target="_blank">vue-router</a></li> <li><a href="http://vuex.vuejs.org/" target="_blank">vuex</a></li> <li><a href="http://vue-loader.vuejs.org/" target="_blank">vue-loader</a></li> <li><a href="https://github.com/vuejs/awesome-vue" target="_blank">awesome-vue</a></li> </ul> </div> <div class="hidden" v-infocus="'showElement'"> <h2>Ecosystem</h2> <ul> <li><a href="http://router.vuejs.org/" target="_blank">vue-router</a></li> <li><a href="http://vuex.vuejs.org/" target="_blank">vuex</a></li> <li><a href="http://vue-loader.vuejs.org/" target="_blank">vue-loader</a></li> <li><a href="https://github.com/vuejs/awesome-vue" target="_blank">awesome-vue</a></li> </ul> </div> <div class="hidden hidden-left" v-infocus="'showElement'"> <h2>Ecosystem</h2> <ul> <li><a href="http://router.vuejs.org/" target="_blank">vue-router</a></li> <li><a href="http://vuex.vuejs.org/" target="_blank">vuex</a></li> <li><a href="http://vue-loader.vuejs.org/" target="_blank">vue-loader</a></li> <li><a href="https://github.com/vuejs/awesome-vue" target="_blank">awesome-vue</a></li> </ul> </div> <div class="hidden hidden-right" v-infocus="'showElement'"> <h2>Ecosystem</h2> <ul> <li><a href="http://router.vuejs.org/" target="_blank">vue-router</a></li> <li><a href="http://vuex.vuejs.org/" target="_blank">vuex</a></li> <li><a href="http://vue-loader.vuejs.org/" target="_blank">vue-loader</a></li> <li><a href="https://github.com/vuejs/awesome-vue" target="_blank">awesome-vue</a></li> </ul> </div> </div> ... only, I wish I could remove the listener when the component is unmounted. I think in a SPA this could cause some listeners to stick around.
{ "pile_set_name": "StackExchange" }
Q: Question on using or equals (||=) in application controller I have seen the or equals ||= often used in application controller methods to set a variable if it doesn't exist. The most recent in Railscasts 270. But I have a question.. take for example this helper method def current_user @current_user ||= User.find(session[:user_id]) if session[:user_id] end From my understand @current_user is set if it doesn't already exist. This means that rails doesn't have to go out to the database, performance win, etc. However I'm confused as to the scope of @current_user. Lets say we have two users of our website. The first one (lets call him "bob") comes to the site and sets @current_user to be his user object. Now when the second one ("john") comes in and rails asks for @current_user... why isn't the user object still bob's? After all @current_user was already set once when bob hit the site so the variable exists? Confused. A: Variables prefixed with @ are instance variables (that is, they are variables specific to a particular instance of a class). John's visit to the site will be handled by a separate controller instance, so @current_user will not be set for him.
{ "pile_set_name": "StackExchange" }
Q: Why not write the solutions of a cubic this way? For the solution of the cubic equation $x^3 + px + q = 0$ Cardano wrote it as: $$\sqrt[3]{-\frac{q}{2} + \sqrt{\frac{q^2}{4} + \frac{p^3}{27}}}+\sqrt[3]{-\frac{q}{2} - \sqrt{\frac{q^2}{4} + \frac{p^3}{27}}}.$$ but this is ambiguous because it does not tell you which cube roots to match up. Why don't people write it this way today: $$\sqrt[3]{-\frac{q}{2} + \sqrt{\frac{q^2}{4} + \frac{p^3}{27}}}+\frac{-p}{3\sqrt[3]{-\frac{q}{2} + \sqrt{\frac{q^2}{4} + \frac{p^3}{27}}}}$$ which is unambiguous. A: Since no one has posted an answer and since my comment is a sort of tangential answer (and relevant to another question): In UCSMP Precalculus and Discrete Mathematics, 3rd edition, p553 (in the "exploration" question), the cubic formula is given in a form analogous to what you describe (though it is for the general monic cubic, not the depressed cubic). It is given that way for the reason you describe—in particular, because of the way that most calculators and computer algebra systems define the principal root, the "traditional" way of writing the formula does not always yield correct results when computing blindly with technology. The formula as printed in the first printing run of PDM is actually missing a term, though it should be correct in subsequent printing runs. The correct formula reads: Let $$A=\frac{\sqrt[3]{-2p^3+9pq-27r+3\sqrt{3}\sqrt{-p^2q^2+4q^3+4p^3r-18pqr+27r^2}}}{3\sqrt[3]{2}}$$ and $$B=\frac{-p^2+3q}{9A}.$$ Then, $$x_1=-\frac{p}{3}+A-B,$$ $$x_2=-\frac{p}{3}+\frac{-1-i\sqrt{3}}{2}A-\frac{-1+i\sqrt{3}}{2}B,$$ and $$x_3=-\frac{p}{3}+\frac{-1+i\sqrt{3}}{2}A-\frac{-1-i\sqrt{3}}{2}B$$ are the solutions to $$x^3+px^2+qx+r=0.$$
{ "pile_set_name": "StackExchange" }
Q: Getting indices of list based on a second list I have a list a which contains all the possible values in list b a = ['foo', 'bar', 'baz'] and b = ['baz', 'baz', 'foo', 'foo', 'foo', 'bar', 'foo', 'baz'] I'd like to return a list c which has the number of elements found in b where each element is the index of a in for which the value of b can be found. Example c = [2, 2, 0, 0, 0, 1, 0, 2] A: One-liner: c = [a.index(x) for x in b]
{ "pile_set_name": "StackExchange" }
Q: Adding media support to a timeline plugin (Wordpress) I have installed this plugin -> http://wordpress.org/plugins/wordpress-posts-timeline/ . With this plugin you can create a post and it displays in a timeline. My problem is that images don't show when inserted in the post box. I tried modifying the plugin code and put some get_attachment code inside the loop there but unfortunately didn't work.. I can get all images to show, but not by ID of the post. Youtube support would be nice too, but maybe that gets clear if this question is answered. Current state -> http://erwin.my89.nl/stage/sieh // Edit I have tried alot of code with wp_get_attachment stuff. <?php wp_get_attachment_image( $attachment_id, $size, $icon ); ?> & <?php $uri = wp_get_attachment_image_src( $post->ID, 'medium' ); echo $uri[0];?> But cant get it to work.. Thanks in advance. A: The plugin is stripping HTML tags when building the content: function timeline_text($limit){ $str = get_the_content('', true, ''); $str = strip_tags($str); // etc... You have to add <img> (and others) as an allowed tag on strip_tags(): $str = strip_tags($str, '<img>');
{ "pile_set_name": "StackExchange" }
Q: Laravel filesystem sftp cached adapter I am struggling with this issue for some time. I am using the sftp adapter to connect to another server where i read/write files a lot. For thumbnail creation i use background jobs with laravel horizon to retrieve pdf contents from the remote sftp server and then generate a jpg and place in local filesystem. For first setup i need to make around 150k of thumbnails. When i use a lot of processes in horizon the remote server can't handle this number of connections. I must limit to max 2 processes at the moment (10 secs~ * 150k~) not optimal. I want to cache the connection because i know it is possible and probably solves my problem, but can't get it to work:( The only reference/tutorial/example/docs i could find is https://medium.com/@poweredlocal/caching-s3-metadata-requests-in-laravel-bb2b651f18f3 https://flysystem.thephpleague.com/docs/advanced/caching/ When i use the code from the example like this: Storage::extend('sftp-cached', function ($app, $config) { $adapter = $app['filesystem']->createSftpAdapter($config); $store = new Memory(); return new Filesystem(new CachedAdapter($adapter->getDriver()->getAdapter(), $store)); }); I get the error: Driver [] is not supported. Is there anyone here who can help me a bit further on this? A: It appears necessary to adjust your configuration: In your config/filesystems.php file, add a 'caching' key to your storage: 'default' => [ 'driver' => 'sftp-cached', // ... 'cache' => [ 'store' => 'apc', 'expire' => 600, 'prefix' => 'laravel', ], ], This example is based on official documentation (https://laravel.com/docs/5.6/filesystem#caching), but it is not described well how the 'store' key is used here (where memcached is the example), and you would need to change the implementation of your driver to new Memcached($memcached); (with an instance to inject) instead. In your case, since the sftp-cached driver implements $store = new Memory();, the cache config must reflect this with 'store' => 'apc' (which is RAM based cache). Available 'store' drivers are found in config/cache.php. (If you use APC and get an error message Call to undefined function Illuminate\Cache\apc_fetch(), this PHP extension must be installed, see e.g. http://php.net/manual/en/apcu.installation.php) Finally, I believe the 'prefix' key in config/filesystems.php must be set to the same as the cache key prefix in config/cache.php (which is 'prefix' => 'cache' by default).
{ "pile_set_name": "StackExchange" }
Q: Web App. Vs. Desktop App (Java Swing App) I want to develop an application where server pushes a lot of data to client. (20 kb every 20 milliseconds) 500kbps. All of the data are double/float values. I am trying to answer the question, if there is something inherent to desktop apps (Java Swing app) which will make it a better option for this use case as compared to a web app where data will be pushed over http. Is there something about Java swing app and how data transfer takes place there from server to client, that makes them faster as compared to web apps (tomcat as app server .. JS at client side). And how answer varies, if I say that web server and application are on the same local network. A: My vote is desktop, but I'm bias (when the only tool you have is a hammer...) My first thought is threads and custom networking. You get the added benefit of push and pull protocols as you need (yeah you can get this in a web environment to, but Java was designed for this, AJAX has been bent this need) I'd also push a diverse and customisable UI toolkit, but one might argue that you can achieve this using HTML, but I've, personally, found the Swing toolkit faster to get running & easier to maintain, IMHO. The downside would have to the need to install the app on each client machine and deal with updating That's my general opinion anyway, hope it helps The other question is, what does the app need to do?
{ "pile_set_name": "StackExchange" }
Q: "InstallTrigger" is not defined In my html page i have code something like this, where i have installed an extension only if the browser is Firefox: if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)) { //relevant code InstallTrigger.install(InstallXPI); } It works fine in every browser. But when the same page is used through htmlunit framework and using browserversion.FIREFOX_3_6 argument in webclient. It shows an error there: com.gargoylesoftware.htmlunit.ScriptException: Wrapped com.gargoylesoftware.htmlunit.ScriptException: Wrapped com.gargoylesoftware.htmlunit.ScriptException: ReferenceError: "InstallTrigger" is not defined. Any idea about this? A: This is a reminder for you: don't use browser detection, use feature detection. The issues with your code: InstallTrigger is a feature of the Gecko engine, not Firefox. You are explicitly looking for "Firefox" in the user agent string however and might exclude other browsers based on the Gecko engine (there are e.g. SeaMonkey, K-Meleon, Camino). User agent strings can be spoofed which is apparently what htmlunit is doing - it claims to be Firefox despite using a different browser engine. Your code will run into trouble then. Here is how you would do it properly: if ("InstallTrigger" in window) { // Gecko platform, InstallTrigger available InstallTrigger.install(InstallXPI); }
{ "pile_set_name": "StackExchange" }
Q: What is the axiomatic (set theory) context of the P vs NP and NP=EXPTIME conjectures? When the conjecture $\mathbf{P} = \mathbf{NP}$ or $\mathbf{P} \neq \mathbf{NP}$ is set (e.g. by the Clay Mathematical Institute by S. Cook, see here) what mathematical axiomatic system is assumed? In order to prove or disprove such statements, you need to assume some axioms. Which ones? Only the Peano (2nd order formal language) arithmetic? The Zermelo–Fraenkel set theory with the axiom of choice? Smaller axiomatic set theories (e.g. Gödel's constructible sets, where the continuum hypothesis holds too, see here)? Obviously, it should be an axiomatic theory that accepts the countable infinite. But which in particular? Is there any published result that would prove them consistent in a particular axiomatic set theory? (In other words, defining a model in which it is true, but not claiming to be true in all models). A: It's not specified. When there is a serious enough candidate paper purporting to resolve P ≟ NP, a Special Advisory Committee will be formed to decide whether (and to whom) to award the prize. I presume that the Special Advisory Committee will decide whether your system of axioms is acceptable. If you assume Z-F with choice, I guarantee you they will take it. If you assume P ≠ NP as an axiom, I guarantee you they won't.
{ "pile_set_name": "StackExchange" }
Q: How to select recent errors that were raised in an SQL-Server database? is there a way to do something like: select top 100 * from sys.recent_raised_errors order by date My scenario was that I had an application that executed a stored procedure in the database, and after installing a new trigger on a table, that procedure had an error raised inside of it, that caused the app to crash. It was obvious to me that the app is crashing due to a DB issue, but I had to debug the app or read its logs to find out what went wrong in the stored procedure. A: try to do below step: In Object Explorer, connect to an instance of the SQL Server and then expand that instance. Find and expand the Management section Right-click on SQL Server Logs, select View, and choose View SQL Server Log. Or you can start profile to tracking the exception I just did a testing with SQL Profiler Create a tiger that will get a exception. CREATE TRIGGER trig_test ON dbo.T AFTER INSERT,DELETE,UPDATE AS BEGIN SET NOCOUNT ON; SELECT 1/0 END GO INSERT INTO dbo.T( remark )VALUES ( '') The following is the message that got from Profiler.
{ "pile_set_name": "StackExchange" }
Q: Moiré patterns in viewport but not in render? When rendering overlapping meshes (I know this is bad practice, but in this case it is done purely out of curiosity) You get strange artifacts. However, these differ from the viewport render and the F12 render: Here is a screenshot of the viewport render in camera view: And here is the render: Why are these different? A: Rendering has higher sampling per pixel, hence the precision, diminishing visible moire.
{ "pile_set_name": "StackExchange" }
Q: Inputs for jedis.incr(byte[] key) I'm currently using Jedis version 2.9.0, and according to the Redis Jedis documentation, the method long jedis.incr(byte[] key) accepts a byte array as its key. The thing is, I'm using hash values (MessageDigest.getInstance("MD5")) as keys, but I'm not sure about the types/sizes of keys allowed in this command. I also don't know if this is the 'best practice' in this cases. Does anyone know how big a byte array can be and still be passed as an argument in this method? A: Redis' key names can be up to 512MB long and are binary-safe. As an MD5 hash is a 128-bit integer, it takes only 16 bytes as a key name and that is well within the limits.
{ "pile_set_name": "StackExchange" }
Q: Software "Robots" - Processes or work automation I have being toying with the idea of creating software “Robots” to help on different areas of the development process, repetitive task, automatable task, etc. I have quite a few ideas where to begin. My problem is that I work mostly alone, as a freelancer, and work tends to pill up, and I don’t like to extend or “blow” deadline dates. I have investigated and use quite a few productivity tools. I have investigated CodeGeneration and I am projecting a tool to generate portions of code. I use codeReuse techniques. Etc. Any one as toughs about this ? as there any good articles. A: I wouldn't like to use code generation, but I have developed many tools to help me do many of the repetitive tasks. Some of these could do nice things: Email Robots These receive emails and do a lot of stuff with them, they need to have some king of authentication to protect you from the bad stuff : Automatically logs whatever was entered in a database or excel spreadsheet. Updates something in a database. Saves all the attachments in a specific shared folder. Reboot a server. Productivity These will do repetitious tasks: Print out all the invoices for the month. Automatically merge data from several sources. Send reminders of GTD items. Send reminders of late TODO items. Automated builds Automated testing Administration These automate some repetitive server administration tasks: Summarize server logs, remove regular items and send the rest by email Rebuild indexes in a database Take automatic backups A: Meta-programming is a great thing. If you easily get access to the data about the class structure then you can automate a few things. In the high level language I use, I define a class like 'Property' for example. Add an integer for street number, a string for street name and a reference to the owning debtor. I then auto generate a form that has a text box for street number and street name, a lookup box for the debtor reference and the code to save and load is all auto-generated. It knows that street number is an integer so its text box can only accept integers. If I declare a read only property it will also make sure the text box is read only.
{ "pile_set_name": "StackExchange" }
Q: Adb error: device not found while device is connected I'm compiling and installing Android apps using command line and this is what happens when I'm trying to install it on a device: $> adb devices List of devices attached 8c092420 device $> adb install TestApp.apk error: device not found - waiting for device - There is no problem when I use adb -s 8c092420 install TestApp.apk. I would like to make some aliases for Linux bash (when I have to do something with a device without copying the device ID as I use several of them), could you please give me an advice how to make this working? Or what may be wrong? A: Problem solved. It was because of the environmental variable ANDROID_SERIAL was set to an old device. Use the next command if that happens to you too on linux/unix. unset ANDROID_SERIAL
{ "pile_set_name": "StackExchange" }
Q: ASP.NET MVC Validation Groups? I have a form in which I would like to require different fields depending on which submit button is pressed. Example: Field A is required if you press Submit Button 1, but only Field B is required if you press Submit Button 2. If I was still using web forms, I would assign different "validation groups" to each button/validator combination. Is there a way to do this in MVC, preferably with data annotations on the model? I would prefer to implement client and server validation with a single solution, but I will take what I can get... Thanks in advance! A: How about a custom validation attribute with client validation enabled (so you get both client and server validation)? The solution below uses jQuery unobtrusive validation. To use this you will need to give all your buttons specific names and pass the name to the validation attribute. The button will also need to have a value of some sort so it can be posted back (so the server side code can test it, i.e. <input type="submit" name="myButton" value="1" />). I haven't tested this code, so I'm not sure if it runs out of the box. You may need to make some mods: The validation attribute for your model: public class RequiredIfButtonClickedAttribute : ValidationAttribute, IClientValidatable { private RequiredAttribute _innerAttribute = new RequiredAttribute(); public string ButtonName { get; set; } public RequiredIfButtonClickedAttribute(string buttonName) { ButtonName = buttonName; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if ((value == null && !string.IsNullOrEmpty(HttpContext.Current.Request.Form[ButtonName]))) { if (!_innerAttribute.IsValid(value)) { return new ValidationResult(this.ErrorMessage, new[] { validationContext.MemberName }); } } return ValidationResult.Success; } #region IClientValidatable Members public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { var rule = new ModelClientValidationRule() { ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()), ValidationType = "requiredifbuttonclicked" }; rule.ValidationParameters.Add("buttonname", ButtonName); yield return rule; } #endregion } The client script: /// <reference path="jquery-1.4.4-vsdoc.js" /> /// <reference path="jquery.validate.unobtrusive.js" /> // When a button is clicked remove the clicked button class from all buttons and add it to the on that was clicked $(":submit").click(function () { $(":submit").removeClass('clickedButton'); $(this).addClass('clickedButton'); }); $.validator.addMethod('requiredifbuttonclicked', function (value, element, parameters) { // if the condition is true, reuse the existing // required field validator functionality if ($(".clickedButton").val("name") === parameters['buttonname']) return $.validator.methods.required.call( this, value, element, parameters); return true; } ); $.validator.unobtrusive.adapters.add( 'requiredifbuttonclicked', ['buttonname'], function (options) { options.rules['requiredifbuttonclicked'] = { buttonname: options.params['buttonname'] }; options.messages['requiredifbuttonclicked'] = options.message; }); And use it like this: [RequiredIfButtonClicked("myButtonName")] public string Name { get; set; } A: You could give the same name to each submit button and different value. Then have a property on your view model having this name of type string. When the form is submitted its value will match the value of the button that was clicked. Now you could design a custom validator attribute that will be used to decorate your view model with. In its IsValid implementation you will fetch the instance of your view model and based on the value of the special property you will perform the validations. It's ugly, I know, but DataAnnotations are really useful for simple validation situations, but when you start writing real world applications you realize their limitations. Personally I use FluentValidation.NET and a scenario like the one being described here is pretty trivial to implement.
{ "pile_set_name": "StackExchange" }
Q: Define table name Ruby on Rails 3.2.1 I've got a legacy database that I'm connecting to via the sqlserver adapter. One of the databases is called "SiteIndex_Players". I've generated the following model: class SiteIndexPlayer < ActiveRecord::Base set_table_name = "SiteIndex_Players" end I've also tried: class SiteIndexPlayer < ActiveRecord::Base table_name = "SiteIndex_Players" end Both ways, when I run the rails console rails c, I get this: 1.9.2-p290 :001 > SiteIndexPlayer.first SiteIndexPlayer Load (352.1ms) EXEC sp_executesql N'SELECT TOP (1) [site_index_players].* FROM [site_index_players]' ActiveRecord::StatementInvalid: TinyTds::Error: Invalid object name 'site_index_players'.: EXEC sp_executesql N'SELECT TOP (1) [site_index_players].* FROM [site_index_players]' from /home/ubuntu/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-sqlserver-adapter-3.2.1/lib/active_record/connection_adapters/sqlserver/database_statements.rb:412:in `each' from /home/ubuntu/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-sqlserver-adapter-3.2.1/lib/active_record/connection_adapters/sqlserver/database_statements.rb:412:in `handle_to_names_and_values_dblib' from /home/ubuntu/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-sqlserver-adapter-3.2.1/lib/active_record/connection_adapters/sqlserver/database_statements.rb:401:in `handle_to_names_and_values' from /home/ubuntu/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-sqlserver-adapter-3.2.1/lib/active_record/connection_adapters/sqlserver/database_statements.rb:373:in `_raw_select' from /home/ubuntu/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-sqlserver-adapter-3.2.1/lib/active_record/connection_adapters/sqlserver/database_statements.rb:367:in `block in raw_select' from /home/ubuntu/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.2.1/lib/active_record/connection_adapters/abstract_adapter.rb:280:in `block in log' from /home/ubuntu/.rvm/gems/ruby-1.9.2-p290/gems/activesupport-3.2.1/lib/active_support/notifications/instrumenter.rb:20:in `instrument' from /home/ubuntu/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.2.1/lib/active_record/connection_adapters/abstract_adapter.rb:275:in `log' from /home/ubuntu/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-sqlserver-adapter-3.2.1/lib/active_record/connection_adapters/sqlserver/database_statements.rb:367:in `raw_select' from /home/ubuntu/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-sqlserver-adapter-3.2.1/lib/active_record/connection_adapters/sqlserver/database_statements.rb:350:in `do_exec_query' from /home/ubuntu/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-sqlserver-adapter-3.2.1/lib/active_record/connection_adapters/sqlserver/database_statements.rb:24:in `exec_query' from /home/ubuntu/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-sqlserver-adapter-3.2.1/lib/active_record/connection_adapters/sqlserver/database_statements.rb:293:in `select' from /home/ubuntu/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.2.1/lib/active_record/connection_adapters/abstract/database_statements.rb:16:in `select_all' from /home/ubuntu/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.2.1/lib/active_record/connection_adapters/abstract/query_cache.rb:63:in `select_all' from /home/ubuntu/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.2.1/lib/active_record/querying.rb:38:in `block in find_by_sql' from /home/ubuntu/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.2.1/lib/active_record/explain.rb:40:in `logging_query_plan' from /home/ubuntu/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.2.1/lib/active_record/querying.rb:37:in `find_by_sql' from /home/ubuntu/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.2.1/lib/active_record/relation.rb:170:in `exec_queries' from /home/ubuntu/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.2.1/lib/active_record/relation.rb:159:in `block in to_a' from /home/ubuntu/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.2.1/lib/active_record/explain.rb:33:in `logging_query_plan' from /home/ubuntu/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.2.1/lib/active_record/relation.rb:158:in `to_a' from /home/ubuntu/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.2.1/lib/active_record/relation/finder_methods.rb:377:in `find_first' from /home/ubuntu/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.2.1/lib/active_record/relation/finder_methods.rb:122:in `first' from /home/ubuntu/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.2.1/lib/active_record/querying.rb:5:in `first' from (irb):1 from /home/ubuntu/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.2.1/lib/rails/commands/console.rb:47:in `start' from /home/ubuntu/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.2.1/lib/rails/commands/console.rb:8:in `start' from /home/ubuntu/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.2.1/lib/rails/commands.rb:41:in `<top (required)>' from script/rails:6:in `require' from script/rails:6:in `<main>'1.9.2-p290 :002 > Makes sense, the table is "SiteIndex_Players", not "site_index_players" (notice the missing underscore). Is there a way I can define the table to have the name "SiteIndex_Players"? Thanks A: Instead of set_table_name = "SiteIndex_Players" you need set_table_name "SiteIndex_Players" without the equals sign. See: http://apidock.com/rails/ActiveRecord/Base/set_table_name/class
{ "pile_set_name": "StackExchange" }
Q: How to write a simple JQuery integer division function My webpage displays realtime data that is updated every 10 seconds from our PI server(historian server). I was recently tasked to take two peices of data that are allready displayed on my page and divide them, displaying the new result on a graph. I have very little experience with AJAX/JQuery, so I was wondering if someone out there can lend me a hand? Clarification: Hypethetically- Say I have "Number of Grades" and "Sum of Grades" displayed on my page as basic integers. They are updated every 10 seconds from the server. I want to take those two pieces of live data, divide them, and display the result (in this case it would be the overall average grade). So, my page will display Number of Grades, Sum of Grades, and Average Grade all updated in real time, every 10 seconds. I am unclear as to whether JQuery can simply take those values off the server and perform division on them and return a value, or if other steps need to be taken to achieve this. I'm completely shooting in the dark here so sorry in advance for any vagueness or lack of required information.Thank you. Some example code is given below: <span class = 'PIdata' data-tag = 'NumOfGrades' data-on_pi_change = 'NumOfGradeChange'></span> <span class = 'PIdata' data-tag = 'SumOfGrades' data-on_pi_change = 'SumOfGradeChange'></span> I want to display a value that divides NumOfGrades by SumOfGrades. A: var sumOfGrades = parseFloat($.('#SumOfGradesId').text()); var numberOfGrades = parseFloat($.('#NumberOfGradesId').text()); var result = fn(sumOfGrades , numberOfGrades); $.('#AverageGradeId').text(result); This will set the required value.
{ "pile_set_name": "StackExchange" }
Q: Widest tyre you can safely fit on 700c wheel (17mm rim width) I am riding a no-suspension hybrid with rigid reinforced fork and 700c wheels. I go on touring trips with very flexible itinerary. I stay on gravel/tarmac/trail 80% of the time but occasionally I like to link parts of the tour by going off-road or on rough trails. I currently run 700x35C touring tires and I am very pleased with their performance on good surface. However I would like to get some oversized (preferably foldable) tires that I can pack when touring and put on for a day or two during the tour when necessary. Here are some cases from my recent trips when my 35c's felt "not enough" and I wish I had wider tire: Here are few details: Rims are WTB 700C Rim inner width measures just under 17mm I currently run 700x35C Disc brakes, so brake assembly will not be a limiting factor Frame and fork will not be an issue as well (both look like they could accommodate 55+ size and still have plenty of clearance) Rim inner width: Ample tire clearance (pictures taken with Schwalbe Marathon Plus 35c tire in place): Sheldon Brown says I should not go above 37mm... Yet I know that this bike came from the manufacturer with 47c continentals fitted... Any advice is appreciated. I would like to hear not only what is OK for this particular case but also what are general considerations. How does one decide when tire is too wide and unsafe. UPDATE: Additional problem that I am facing is that it is hard to find wider 700c tires. For gravel / hybrid tires advertised as 700c sizes go from 25mm up to 37mm. For mountain bikes (29 inch wheel) sizes begin at 2.25 inches which is approx 57mm. There appears to be a gap between 37mm and 57mm and it is very rear that one come across a tire that falls in that gap category. Or am I not looking for a right thing? A: There are loads of 2.1" MTB tyres, and a few 2.0. I've got some WTB nano 2.1s that were on my hardtail when I got it, and I've got a Rapid Rob 2.1 on it now. But your current tyres look pretty slick. Putting a dirt touring tyre like a marathon mondial on there would certainly help (and that comes in 35, 40, and 50mm widths). Those are OK on road, though slower than I'd choose for all-tarmac use. I take my tourer off road too (though not laden) and have really noticed the difference between the marathon mondials and the slick marathon supremes I switched to (or indeed the marathon plus on my hybrid), even with both at 35mm. The footnote to the table you link suggests you can go a fair bit wider - in fact my hardtail has narrower rims than my tourer. You're likely to be limited more by the clearance batten the chainstays/seatstays/forks. The tyres I mention are just examples, based on what I've used.
{ "pile_set_name": "StackExchange" }
Q: Screen orientation landscape change activity I'm making an app that change the colors depending of the color you select this change the background, but when I make the screen orientation to landscape this automatically change the color to the predefined and if I'm not wrong this happen because it's being destroy after I change the orientation... so I would like to know where and how I can solve that problem. A: Android gives you a chance to save state before changing the layout @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { mColor = savedInstanceState.getString(COLOR_VALUE); } @Override //this method is called before android trashes and recreates your activity protected void onSaveInstanceState (Bundle outState) { super.onSaveInstanceState(outState); outState.putString(COLOR_VALUE, mColor); } If your UI is expensive to recreate then look into retained fragments instead
{ "pile_set_name": "StackExchange" }
Q: Android actionbar background image не работает Не могу установить картинку на задний фон ActionBar. Содержимое файла styles.xml: <resources> <style name="BlackSkyBaseTheme" parent="Theme.AppCompat.Light"> </style> <style name="BlackSkyTheme" parent="BlackSkyBaseTheme"> <item name="actionBarStyle">@style/BlackSkyTheme.ActionBar</item> </style> <style name="BlackSkyTheme.ActionBar" parent="@style/Widget.AppCompat.ActionBar"> <item name="android:background">@drawable/menu_background</item> </style> </resources> В файле AndroidManifest.xml: <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/BlackSkyTheme" > Что я делаю не так? Картинка точно существует во всех папках res\drawable-****\menu_background.png. A: Пропишите в коде: getSupportActionBar().setBackgroundDrawable(ContextCompat.getDrawable(this, R.drawable.menu_background));
{ "pile_set_name": "StackExchange" }
Q: Qt Testing QMessageBoxes (or a general QDialog) with exec() loop I want to test a custom QMessageBox that I created. In particular, my API will execute automatically the exec() loop of the QMessageBox, and I want to check the result when the user clicks a button or closes the widget. The problem is that I am blocked in the exec() loop. The only solution I found is creating a QTimer that will do what I want just before the loop is executed. References to this solution are this and this. The tests are working correctly, but really there isn't a more native way in Qt to test the exec() loop of the QDialogs? I mean, there are ways to activate/simulate signals in QTest, there is nothing that can simulate the exec() loop? A: Why would you want to "simulate" the event loop? You want to run the real event loop! You just want to inject your code into it, and that's what timers are for (or events in general). Qt Test has all sorts of convenience wrappers around the event loop, e.g. keyClick delivers the event and drains the event queue, etc., but you don't need to simulate anything. If you don't find something that you need, you can make your own. The API you're using is of course broken: it pretends that an asynchronous action is synchronous. It should invert the control into a continuation passing style, i.e.: // horrible int Api::askForValue(); // better Q_SIGNAL void askForValueResult(int); void Api::askForValue(); // emits the signal template <typename F> void Api::askForValue(F &&fun) { // convenience wrapper auto *conn = new QMetaObject::Connection; *conn = connect(this, &Class::askForValueResult, [fun = std::forward<F>(fun), c = std::unique_ptr<QMetaObject::Connection>(conn)] (int val){ fun(val); QObject::disconnect(*c); }); askForValue(); } The synchronous APIs like make a lot of application code have to face reentrancy, and this is not a hypothetical problem. Questions about it are not uncommon. Few people realize how bad of a problem it is. But assuming that you are forced to stick with the horrible API: what you really want is to react to the message window being shown. You can do this by adding a global, application-wide event filter on the QEvent::WindowActivate. Simply install your event filter object on the application instance. This could be wrapped in some helper code: /// Invokes setup, waits for a new window of a type T to be activated, /// then invokes fun on it. Returns true when fun was invoked before the timeout elapsed. template <typename T, typename F1, typename F2> bool waitForWindowAnd(F1 &&setup, F2 &&fun, int timeout = -1) { QEventLoop loop; QWidgetList const exclude = QApplication::topLevelWidgets(); struct Filter : QObject { QEventLoop &loop; F2 &fun; bool eventFilter(QObject *obj, QEvent *ev) override { if (ev.type() == QEvent::WindowActivate) if (auto *w = qobject_cast<T*>(obj)) if (w->isWindow() && !exclude.contains(w)) { fun(w); loop.exit(0); } return false; } Filter(QEventLoop &loop, F2 &fun) : loop(loop), fun(fun) {} } filter{loop, fun}; qApp->installEventFilter(&filter); QTimer::singleShot(0, std::forward<F1>(setup)); if (timeout > -1) QTimer::singleShot(timeout, &loop, [&]{ loop.exit(1); }); return loop.exec() == 0; } Further wrappers could be made that factor out common requirements: /// Invokes setup, waits for new widget of type T to be shown, /// then clicks the standard OK button on it. Returns true if the button /// was clicked before the timeout. template <typename T, typename F> bool waitForStandardOK(F &&setup, int timeout = -1) { return waitForWindowAnd<T>(setup, [](QWidget *w){ if (auto *box = w->findChild<QDialogButtonBox*>()) if (auto *ok = box->standardButton(QDialogButtonBox::Ok)) ok->click(); }, timeout); } Then, supposed you wanted to test the blocking API QDialogInput::getInt: waitForStandardOK<QDialog>([]{ QInputDialog::getInt(nullptr, "Hello", "Gimme int!"); }, 500); You could also make a wrapper that builds the bound call without needing to use a lambda: /// Binds and invokes the setup call, waits for new widget of type T to be shown, /// then clicks the standard OK button on it. Returns true if the button /// was clicked before the timeout. template<typename T, class ...Args> void waitForStandardOKCall(int timeout, Args&&... setup) { auto bound = std::bind(&invoke<Args&...>, std::forward<Args>(args)...); return waitForStandardOK<T>(bound, timeout); } And thus: waitForStandardOKCall<QDialog>(500, &QInputDialog::getInt, nullptr, "Hello", "Gimme int!"); For more about std::bind and perfect forwarding, see this question.
{ "pile_set_name": "StackExchange" }
Q: "Closed" message with Community User is over-encoded Spotted at this question The HTML source looks like this: <h2> <b>marked</b> as duplicate by <a href="/users/140890/martijn-pieters">Martijn Pieters</a>, <span class="voter-history" title="This question&#39;s author approved a pending duplicate vote."> &lt;a href=&quot;/users/-1/community&quot;&gt;Community&lt;/a&gt;&lt;span class=&quot;mod-flair&quot; title=&quot;moderator&quot;&gt;&amp;#9830;&lt;/span&gt;</span> <span dir="ltr"><span title="2015-04-17 13:09:02Z" class="relativetime">Apr 17 at 13:09</span></span> </h2> (line breaks added for readability) A: Fixed now, thanks. I'm in the process of auditing a ton of places in our code to make sure that we don't HTML-encode too little. It's somewhat surprising that in the process of doing that, so far I seem to have caused double-encoding only in a single place :)
{ "pile_set_name": "StackExchange" }
Q: Retrofit. POST with request body without response body I try to POST these login and password { "userLogin": "Mark", "userPassword": "Pencil" } According to POSTMAN, where I put above JSON as a raw code, I got an empty response body and response code: 200 (Logging is succesful). But I can't achieve it in Android Studio. Here is an API interface interface LoginService { @POST("login") fun userLogin( @Query("userLogin") userLogin: String, @Query("userPassword") userPassword: String ):Call<Void> } And here is Retrofit: fun checkLoginData() { val retrofit = Retrofit.Builder() .baseUrl("myurl...") .addConverterFactory(GsonConverterFactory.create()) .build() val service = retrofit.create(LoginService::class.java) val call = service.userLogin("Mark", "Pencil") call.enqueue(object : Callback<Void>{ override fun onResponse(call: Call<Void>, response: Response<Void>) { if(response.code() == 200){ Toast.makeText(applicationContext,"Logged in", Toast.LENGTH_SHORT).show() } } override fun onFailure(call: Call<Void>, t: Throwable) { Toast.makeText(applicationContext,"Error", Toast.LENGTH_SHORT).show() } }) } I suppose that my LoginService is created incorrectly because there is always onFailure response. How should I do it rightly? A: Using POST you'll probably not use @Query, but rather a @Body. E.g. data class LoginRequest( val userLogin: String, val userPassword: String ) and in your interface : @POST("login") fun userLogin(@Body request: LoginRequest):Call<Void> EDIT: Since it's an issue with ClearText: You need to add android:usesCleartextTraffic="true" to your AndroidManifest. Refer to Android 8: Cleartext HTTP traffic not permitted Option 2 for more info.
{ "pile_set_name": "StackExchange" }
Q: Also select parents up to the root when selecting child in TreeTableView We try to achieve the following: When a node gets selected in a JavaFX TreeTableView, also "the path to the root", i.e., the parent, the grandparent, and so on should get selected. Selected in this case means highlighted with a different background color, see the image (in the example, the node on Level 2 has been clicked by the user). Is there a built-in function how to achieve this? We tried using CSS but did not succeed. A: There's no "built-in function" to do this. Use a row factory on the tree table view to create rows that observe the selected item, and set a pseudoclass on the row accordingly. For example: import java.util.ArrayList; import java.util.List; import java.util.Random; import javafx.application.Application; import javafx.beans.property.IntegerProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleStringProperty; import javafx.css.PseudoClass; import javafx.scene.Scene; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeTableColumn; import javafx.scene.control.TreeTableRow; import javafx.scene.control.TreeTableView; import javafx.stage.Stage; public class TreeTableViewHighlightSelectionPath extends Application { @Override public void start(Stage primaryStage) { TreeTableView<Item> table = new TreeTableView<Item>(); PseudoClass ancestorOfSelection = PseudoClass.getPseudoClass("ancestor-of-selection"); table.setRowFactory(ttv -> new TreeTableRow<Item>() { { table.getSelectionModel().selectedItemProperty().addListener( (obs, oldSelection, newSelection) -> updateStyleClass()); } @Override protected void updateItem(Item item, boolean empty) { super.updateItem(item, empty); updateStyleClass(); } private void updateStyleClass() { pseudoClassStateChanged(ancestorOfSelection, false); TreeItem<Item> treeItem = table.getSelectionModel().getSelectedItem(); if (treeItem != null) { for (TreeItem<Item> parent = treeItem.getParent() ; parent != null ; parent = parent.getParent()) { if (parent == getTreeItem()) { pseudoClassStateChanged(ancestorOfSelection, true); break ; } } } } }); TreeTableColumn<Item, String> itemCol = new TreeTableColumn<>("Item"); itemCol.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getValue().getName())); table.getColumns().add(itemCol); TreeTableColumn<Item, Number> valueCol = new TreeTableColumn<>("Value"); valueCol.setCellValueFactory(cellData -> cellData.getValue().getValue().valueProperty()); table.getColumns().add(valueCol); table.setRoot(createRandomTree()); Scene scene = new Scene(table); scene.getStylesheets().add("style.css"); primaryStage.setScene(scene); primaryStage.show(); } private TreeItem<Item> createRandomTree() { TreeItem<Item> root = new TreeItem<>(new Item("Item 1", 0)); Random rng = new Random(); List<TreeItem<Item>> items = new ArrayList<>(); items.add(root); for (int i = 2 ; i <= 20 ; i++) { TreeItem<Item> item = new TreeItem<>(new Item("Item "+i, rng.nextInt(1000))); items.get(rng.nextInt(items.size())).getChildren().add(item); items.add(item); } return root ; } public static class Item { private final String name ; private final IntegerProperty value = new SimpleIntegerProperty(); public Item(String name, int value) { this.name = name ; setValue(value); } public String getName() { return name ; } public IntegerProperty valueProperty() { return value ; } public final int getValue() { return valueProperty().get(); } public final void setValue(int value) { valueProperty().set(value); } } public static void main(String[] args) { launch(args); } } Now you can just style the "ancestor of a selected node" in CSS: File style.css: .tree-table-row-cell:ancestor-of-selection { -fx-background: -fx-selection-bar; -fx-table-cell-border-color: derive(-fx-selection-bar, 20%); } (You may want to modify the CSS to get better control, e.g. set different colors for selected rows in a non-focused table, etc. See the default stylesheet for details on the default style.) Here's a screenshot of the above test app:
{ "pile_set_name": "StackExchange" }
Q: How many solutions to $z^{6!}-z^{5!}\in \mathbb{R}$ and $|z|=1$ How many solutions $\Im(z^{720}-z^{120})=0$ where $|z|=1$? (AIME I $2018$ #$6$) The following is my interpretation of the first solution. The next step is to see how many solutions to $\sin(720\theta)-\sin(120\theta)=0$. (1) One way to do this is consider $\sin(6\omega)-\sin(\omega)$, which has $12$ solutions. (2) For each solution to (2), corresponds $120$ solutions to (1). I understand that. But how do I know that $sin(6\omega)=sin(\omega)$ has $12$ solutions? I'd say during a real contest I could come up with everything but the $12$ solutions part. I tried sketching both graphs on the same plane for $0<x<2\pi$ and I only got 9 intersections, while I can see all $12$ clearly on Desmos, so my drawing is unreliable. A: $$\sin6w=\sin w\iff 6w=2k\pi+w \text{ or } 6w=2k\pi+\pi-w\iff w=\dfrac{2k\pi}{5} \text{ or } w=\dfrac{2k+1}{7}\pi$$ with $k\in\mathbb{Z}$. then $$w=0, \dfrac{2\pi}{5}, \dfrac{4\pi}{5}, \dfrac{6\pi}{5}, \dfrac{8\pi}{5}, \dfrac{\pi}{7}, \dfrac{3\pi}{7}, \dfrac{5\pi}{7}, \dfrac{7\pi}{7}, \dfrac{9\pi}{7}, \dfrac{11\pi}{7}, \dfrac{13\pi}{7}$$
{ "pile_set_name": "StackExchange" }
Q: Convert table to hierarchical vs linear I'm looking if exists for any standard functions in PHP to change a tabular array into a deeper grouped array as below: $table = [ [1, "group1", "Name 1", "Value 1"] , [2, "group1", "Name 2", "Value 2"] , [3, "group1", "Name 3", "Value 3"] , [4, "group1", "Name 4", "Value 4"] , [5, "group2", "Name 5", "Value 5"] , [6, "group2", "Name 6", "Value 6"] , [7, "group2", "Name 7", "Value 7"] ]; $table_result = [ "group1" => [ [1, "Name 1", "Value 1"] , [2, "Name 2", "Value 2"] , [3, "Name 3", "Value 3"] , [4, "Name 4", "Value 4"] ] , "group2" => [ [5, "Name 5", "Value 5"] , [6, "Name 6", "Value 6"] , [7, "Name 7", "Value 7"] ] ]; A: Not with a signle function, but it's quite simple : foreach ($table as $v) { $table_result[$v[1]][] = array($v[0], $v[2], $v[3]); }
{ "pile_set_name": "StackExchange" }
Q: To burnate, or not to burnate? I have found a couple of tags that look too much like meta-tags: computer: has been used once, where the question is also tagged zx-spectrum. (Retagged) color: both times used with display: maybe color-display would be better? (Retagged) There are probably more of these on the site, and more will definitely be created in the future. I know we are only just out of private beta, but it is often easier to sort out such problems whilst they are small. In situations like these, what should we do? A: Burnination is probably unnecessary at the moment. But I could see an argument for making computer an intrinsic tag. If it comes up again, please let me know so that I can make the change. color is potentially ambiguous, so color-display seems like a better choice. My guess is that most people mean something-other-than-monochrome monitor/graphics card when they use "color" in the context of this site. So a synonym (with color-display as the master) seems the right thing to do. A: The two you mention are meta tags and unnecessary. We should nip them in the bud before they become a nuisance. Retag the questions and let the Roomba do its thing.
{ "pile_set_name": "StackExchange" }
Q: Why do the horsemen bother passing the item from one to another while being searched? In Now You See Me 2, the main characters need to steal a card from a secured vault. At some point, each of them is searched for the stolen item and each performs a nifty collection of tricks to keep holding on to it without the searcher realizing: What confuses me is that each of them then passes the card to another "horseman" just as they finished confounding their searcher. Then, the new horseman now has to go through the same song and dance again to avoid detection. What's the point of this? Obviously, it looks cool, but is there an in-universe explanation? Why doesn't the first one just hold on to the card after he managed to be searched without the searcher finding it? Why pass it on to the next horseman? A: Just my take of course : Each of the horsemen is subject to not just one search, but two. There is the initial frisking, but that is followed by the "magic wand" detector. The second is the more worrying, since anyone carrying the card when they are "wanded" would be detected. So Daniel, who we see being searched first, after being frisked is then being stepped away some distance to be "wanded" - so he HAS to get rid of the card while he can, otherwise he'd be too far and/or surrounded by guards to pass it away (see 2:00). The others realise the same, and that their only safety is to stick close together as a group - if one of them gets separated with the card, they'll get detected when that one is "wanded", but two can pass it between them. So they're all weighing multiple factors - how separated are they, who is currently or about to be frisked, who is likely to get taken away to be "wanded" next, where are the guards, etc. It is this multitude of factors that leads to the multiple card passing.
{ "pile_set_name": "StackExchange" }
Q: How can I deserialize Array inside of Array google-gson I have JSON like that: { "Answers": [ [ {"Locale":"Ru","Name":"Name1"}, {"Locale":"En","Name":"Name2"} ], [ {"Locale":"Ru","Name":"Name3"}, {"Locale":"En","Name":"Name4"} ] ] } As you can see, I have array inside of array. How can I deserialize such JSON structure into an object using google-gson library on Android (https://code.google.com/p/google-gson/)? A: After Json format we got something like this: MyObject public class MyObject { public List<List<Part>> Answers; public List<List<Part>> getAnswers() { return Answers; } } Part public class Part { private String Locale; private String Name; public String getLocale() { return Locale; } public String getName() { return Name; } } Main public static void main(String[] args) { String str = " {" + " \"Answers\": [[{" + " \"Locale\": \"Ru\"," + " \"Name\": \"Name1\"" + " }," + " {" + " \"Locale\": \"En\"," + " \"Name\": \"Name2\"" + " }]," + " [{" + " \"Locale\": \"Ru\"," + " \"Name\": \"Name3\"" + " }," + " {" + " \"Locale\": \"En\"," + " \"Name\": \"Name4\"" + " }]]" + " }"; Gson gson = new Gson(); MyObject obj = gson.fromJson(str, MyObject.class); List<List<Part>> answers = obj.getAnswers(); for(List<Part> parts : answers){ for(Part part : parts){ System.out.println("locale: " + part.getLocale() + "; name: " + part.getName()); } } } Output: locale: Ru; name: Name1 locale: En; name: Name2 locale: Ru; name: Name3 locale: En; name: Name4
{ "pile_set_name": "StackExchange" }
Q: Best practice for null-checking in Scala I understand that null is frowned upon in Scala, and that one should always wrap optional values within an Option (or a "null type" if one is available). The advantages are clear, there should never be a need to check against null values, and the resulting code is both safer and more pleasant to read. In practice however, nothing prevents a value from being null - the rule is not enforced by the compiler and is more of a gentleman's agreement. This can easily break when interacting with Java APIs, for example. Is there a best-practice for this? Say, for example, that I need to write an Url case class, and that instances of this class can be created from a java.net.URI: object Url { def apply(uri: URI): Url = Url(uri.getScheme, uri.getHost, uri.getRawPath) } case class Url(protocol: String, host: String, path: String) { def protocol(value: String): Url = copy(protocol = value) def host(value: String): Url = copy(host = value) def path(value: String): Url = copy(path = value) } An URI instance can return null for getScheme, getHost and getRawPath. Is it considered sufficient to protect against these in the apply(URI) method (with require statements, for example)? Technically, in order to be entirely safe, it'd be better to protect the protocol, host and path helper methods, as well as the constructor, but that sounds like an awful lot of work and boilerplate. Is it considered safe, instead, to protect against APIs known to accept / return null values (URI in our example) and to assume that external callers will either not pass null values or only have themselves to blame if they do? A: When dealing with pure functions, it is always better to stick to total implementations and instead of using null, require or exception throwing, to encode all failures in data. The types like Option and Either are there exactly for that. Both of them are monads, so you can use the "for"-syntax to with them. The following modification to your code shows a total function apply, which only produces a meaningful value, when the input Java URI provides no nulls. We encode the notion of "meaningful" by wrapping the result in Option. object Url { def apply(uri: java.net.URI): Option[Url] = for { protocol <- Option(uri.getScheme) host <- Option(uri.getHost) path <- Option(uri.getRawPath) } yield Url(protocol, host, path) } case class Url(protocol: String, host: String, path: String) The function Option is a standard null-checking function, which maps null to None and wraps values in Some. Concerning your "setting" functions, you can implement null-checking in them similarly, using Option. E.g.: case class Url(protocol: String, host: String, path: String) { def protocol(value: String): Option[Url] = Option(value).map(v => copy(protocol = v)) // so on... } However I would advice against that. In Scala it is conventional to never use nulls, so it is as well conventional to only implement null-handling for "bridge" APIs, when you get values from Java libs. That's why the null-checking does make perfect sense when converting from java.net.URI, but after that you are in Scala world, where there should be no nulls, and hence null-checking simply becomes redundant.
{ "pile_set_name": "StackExchange" }
Q: Odd behavior with division in Python I'm completely stumped dealing with something quite simple. The following lines are a part of a much much larger program. Thing and stuff are two objects on a grid, and I need to find the angle between them, in relation to the y-axis. math.atan takes in a floating point number, which I why I need to type cast the distance between the objects. m_angle = math.degrees(math.atan(float(thing.position()[1]-stuff.position()[1]) / float(thing.position()[0]-stuff.position()[0]))) m_angle = math.degrees(math.atan(float(thing.position()[1]-stuff.position()[1]) / thing.position()[0]-stuff.position()[0])) The .position calls all return integers. I get different results while running my program, for each line. The first two should return exactly the same result, a float. What I don't understand, is how I can possibly get different results depending on whether I run line 1 or line 2 :/ This is a part of a simulation, A: Difficult to answer at the rate you are editing but: m_angle = math.degrees(math.atan(float(thing.position()[1]-stuff.position()[1]) / float(thing.position()[0]-stuff.position()[0]))) the bit inside the atan is equivalent to something/(a-b) m_angle = math.degrees(math.atan(float(thing.position()[1]-stuff.position()[1]) / thing.position()[0]-stuff.position()[0])) the bit inside the atan is equivalent to (something/a)-b
{ "pile_set_name": "StackExchange" }
Q: Turning my desk's smile upside down I have a largely jerryrigged desk - its a particleboard table top that's sitting on a pair of metal A frame trestle legs. I recently got a 27 inch monitor and the weight of it is causing the desk to sag. Its an inch thick particleboard that used to have a pair of I frame and a board across it. I don't have a wood shop or a machine shop so reinforcing the desk is unlikely. How would I keep this from happening in future? Would adding a single table leg be enough or should I add another trestle help? Would having a even wider base for the monitor help spread the load? A: Depending on if you can find/buy any materials, you could add some metal/wood rails between the trestles to support the weight of the desk. Essentially you need to distribute the load and cross pieces could serve. Extremely crude drawing: ======desk surface======= |--------support beam----------| | /\<-----------trestles --------->/\ ------- A possible way to build supports: ------- Color key: red=particle board tabletop, black=2x4 support beams, green=trestles, orange=lag bolts or screws A: A single table leg might be too rickety; the cross section is too small. But if you use a 10" or 12" wide board, standing on end directly under the monitor's base, I think that would do the trick! You can stand it up parallel to the sides of the desk, or parallel to the front & back of the desk. Just make sure it's exactly the height of the trestles. A: You can move the monitor so as it stays right above another leg, though, depending on the construction of the leg, it may be not enough place for your legs. Personally I also have a deck, but mine monitor is attached to the wall via the "robo arm".
{ "pile_set_name": "StackExchange" }
Q: Definition of e, how to relate that to other interest rates I understand that one way of understanding the meaning of the number $e$ is to form a compound interest formula, $A = \left(1+\frac{1}{n}\right)^{nx}$ and then let $n\rightarrow \infty$ for which this converges to $e$. However, this occurs by setting the principle to 1, the rate to 1, and the time to $x$. And I see how you can manipulate this to get any other principle--you just multiply by the principle you want. So $Pe^{x}$ would be any other principle. But how do you get any other rate? That is to say, suppose you have $A = \left(1+\frac{r}{n}\right)^{nx}$ and let $n\rightarrow \infty$. To what does this converge? A: It converges to $$e^{rx}$$ To see this you can write $$A = \left(1+\frac{r}{n}\right)^{nx} = \left(1+\frac{1}{\frac{n}{r}}\right)^{\frac{n}{r}xr} \to e^{xr}$$
{ "pile_set_name": "StackExchange" }
Q: How to change the time format of timedelta Hi I hv a timedelta in the following format 0days 01:25:53.0000000 I want to change this time delta to equivalent minutes(I.e. 85.88) Thanks A: Using total_seconds pd.Series(pd.Timedelta('0days 01:25:53.0000000')).dt.total_seconds()/60 Out[334]: 0 85.883333 dtype: float64
{ "pile_set_name": "StackExchange" }
Q: Does Lazy Writer spend resources on flushing out pages from the buffer pool? In MS SQL Server, does Lazy Writer spend resources to make pages out of the buffer pool after periodically checking free buffer list and marking some clean pages as free? Or free marked clean pages continue to stay in the buffer pool until another page is needed to retrieve from the disk and the latter overwrites the free marked clean page? A: does Lazy Writer spend resources to make pages out of the buffer pool after periodically checking free buffer list and marking some clean pages as free Yes it does, this is primary responsibility of Lazy writer. Its job is to make sure there is some free buffer so that new pages can be brought into memory when required. Lazy writer would periodically scan buffer pool, look for pages which are least recently used, or you can say "cold pages" and flush them to disk. In case there is sufficient memory available Lazy writer would not do anything. In case of memory being required to bring more page into buffer pool Lazy writer would flush old pages, create space and bring new pages. It does not marks pages as clean
{ "pile_set_name": "StackExchange" }
Q: How do I combine lenses which contain context? I'm starting from authorityL via authorityHostL to hostBSL - I know you can combine lenses via (authorityL . authorityHostL . hostBSL) but that fails with Couldn't match type ‘Authority’ with ‘Maybe Authority’. How do I properly deal with the Maybe here? A: You can add a _Just in between to only focus in on the successful results. (authorityL . _Just . authorityHostL . hostBSL) does the trick like it's said in the comments.
{ "pile_set_name": "StackExchange" }
Q: Recovering a conic from a pole-polar pair Consider a conic section $C$ in $\mathbb{R}^2$. Every point $P$ in the plane has a "dual" (pole-polar duality) line $L$ with respect to $C$ such that lines $PA$ and $PB$ are tangent to $C$, where $L \cap C = \{A, B\}$. However, given $P, A, B$, is it possible to recover $C$? Is $C$ even uniquely determined by those three points? My vain attempt is as follows. Suppose $C$ has the matrix representation $\mathbf{C}$, and the images of $P, A, B$ under the map $(x, y) \mapsto \begin{bmatrix}x & y & 1\end{bmatrix}^\intercal$ are $\mathbf{p}, \mathbf{a}, \mathbf{b}$ respectively. Since $A, B \in C$, $\mathbf{a}^\intercal\mathbf{C}\mathbf{a} = 0$ and $\mathbf{b}^\intercal\mathbf{C}\mathbf{b} = 0$. That is, $\mathbf{C}\mathbf{a}$ is orthogonal to $\mathbf{a}$ (note that $(\mathbf{a}^\intercal\mathbf{C})^\intercal = \mathbf{C}\mathbf{a}$ because $\mathbf{C}$ is symmetric). Similarly, $\mathbf{C}\mathbf{b}$ is orthogonal to $\mathbf{b}$. From tangency we also have $\mathbf{p}^\intercal\mathbf{C}\mathbf{a} = 0$ and $\mathbf{p}^\intercal\mathbf{C}\mathbf{b} = 0$. Since scaling $\mathbf{C}$ doesn't change the fact that it represents $C$, we may set $\mathbf{C}\mathbf{p} = \mathbf{a} \times \mathbf{b}$. Is it possible to proceed further than this? A: It's not possible to recover C from P, A, B. One way to see this ... consider A, P, B (in order) to be the control points of a rational quadratic Bezier curve. This curve will be tangent to PA at A, and tangent to PB at B, and it's a conic section curve (all rational quadratic Bezier curves are conics). But, you can adjust the weights of this curve however you please, thereby producing an infinite family of conics. Another argument ... it's generally well-known that you need 5 positional or tangency constraints to define a conic section curve. You only have four constraints -- two points and two tangent directions. There's probably an argument based on the idea of "pencils" of conics, too, but two is enough, I hope.
{ "pile_set_name": "StackExchange" }
Q: Virtual PC Performance Issue on 64-bit Vista I am running 64-bit Vista with 8 GB ram and 4 cores. It supports hardware-assited virtualization. Using Virtual PC 2007, my newly built 32-bit Windows XP Pro VM is running incredibly poorly. Even the simplest actions like showing the start menu will cause the CPU usage to hit 100%. The same VM setup hosted on a dual-core 32-bit XP Pro box without hardware-assited virtualization work just fine. Any suggestions? Right now it is almost unusable on my Vista box and I don't even know where to start looking for the cause. A: Enable Hardware Assisted Virtualization in the BIOS. Install the VM Tools on the guest OS. Run your VM's from a separate spindle if you can. A lot of times the bottleneck is disk. Give VM's the right amount of memory for the task. If the VM is constantly swapping it can play havoc with performance. Make sure the host and guest operating systems are defragmented. Cut off fancy gui effects on the guest systems. Exclude your .vhd,.vmdk and associated files from the host systems active anti-virus scanning. Just a few tips that should help. By the way I have the same exact setup on my desk as well (Quad Core Intel Q9400, 8Gb RAM, Vista 64) and have been using Vmware Server 2 with multiple VM's without issue.
{ "pile_set_name": "StackExchange" }
Q: How to represent X and Y axis data in an SQL table I have a table of data in excel that looks like this: I need to get this data imported into an SQL table. Eventually I need to be able to query the table by saying something like: Select the value where x-axis equals 762 and y-axis equals 889 - this should return 30.60. What is the best way to represent this data in an SQL table to make it easy to query? A: What is the best way to represent this data in an SQL table to make it easy to query? The answer quite lies in your pseudo code. The most relevant way to store your data is in a table with three columns: x and y, and value, and a unique constraint on the first two columns. the dataset provided in your example would translate as follows: x y value ---------------- 762 635 26.23 762 762 28.41 762 889 30.60 1016 635 27.61 1016 762 29.91 1016 889 32.31 1270 635 29.06 1270 762 31.48 1270 889 33.91 Select the value where x-axis equals 762 and y-axis equals 889 - this should return 30.60. With this table structure, that's a simple query now: select value from mytable where x = 762 and y = 889
{ "pile_set_name": "StackExchange" }
Q: Reading from files passed as command line arguements I am trying to parse a given textfile, but so far, my program does not seem to be reading properly. #include <stdio.h> int main(int argc, char *argv[]) { FILE *fr; //file pointer int buildingFloors = 1; printf("sanity check\n"); fr = fopen (argv[0], "r"); fscanf(fr, "%d", &buildingFloors ); printf("%d\n", buildingFloors); fclose(fr); return 0; } I compile the program and run it on my redhat linux machine with the following command: ./sjf file.text file.text is a text document with a "4" as the first character. So I would expect my output to be sanity check 4 However, when I run my program I instead get sanity check 1 Which implies that fscanf didn't properly read in the first character -- 4. Do I have some syntax error that's preventing the expected code functionality? Am I supposed to scanf for a character, and then convert that to an int somehow? A: argv[0] is the name of the program (./sjf in your case), so you're trying to read in your own program's executable. Use argv[1] instead to get the first real program argument. A: One thing which immediatly comes to mind is that the program args include the executable name as the first element argv[0] is "sjf" argv[1] is "file.text" so you should be using fr = fopen (argv[1], "r"); Remember when debugging to always try and narrow the problem down, if you know the location of the error the cause often becomes obvious or at least investigatable. In this case you should check argc >= 2, print out argv[1] to ensure you are trying to open the right file, then also check that the file was opened successfully. Finally check the fscanf error codes to see that fscanf was able to read the number.
{ "pile_set_name": "StackExchange" }
Q: Property of subgroups Is the following property correct? Property: let $(G;f_G)$ group, $B \subseteq G$ and $B \neq \emptyset $, then $(B;f_G|_B)$ is group iff $\forall a,b \in B$ we have that $a f_G|_B b'\in B $ and $ b $ is symmetry element of $b'$. Thanks in advance!! A: That statement is true. To show that a subset of a group is a subgroup, the subset must contain the identity, must contain the inverse of each of its elements, and must be closed under the group operation. $B$ contains the identity because $bf_G|_Bb' \in B$. Write $e$ for the identity element. The product $ef_G|_Bb'$ lies in $B$ for any $b \in B$, so $B$ contains the inverses of each of its elements. Finally, to show closure, write $(b')' = b$. Then $af_G|_B(b')' = af_G|_Bb \in B$ (I'm unfamiliar with your notation and vocabulary. I'm answering as if $f_G$ means the group operation, $af_Gb$ means "the product of $a$ and $b$," and "symmetry element" means "inverse." Most users of this site would say "If $B \subset G$ and $ab^{-1} \in B$ for all $a, b \in B$, then $B$ is a subgroup of $G$.) Edit: As egreg and Thomas Anderson point out, the first step relies on the assumption that $B$ is non-empty. Were $B$ empty, there would be no $b$ to use in the product $bf_G|_Bb'$.
{ "pile_set_name": "StackExchange" }
Q: In AngularJS tutorial select only one instance, or the first instance in an array I want to select only the first instance of an array in angular instead of using ng-repeat. I was thinking something like ng-instance, or ng-specificinstance but they don't exist. Also how should I define my javascript variable and what is the standard for referencing it in my html: "phoneinfos" or "phoneinfo" if its only one entity. Also should all things with lots of items should it always end in an s? Current HTML: <div id="searchtab-1" style="height:1.5em;" ng-controller="PhoneListCtrl"> <label ng-repeat="phoneinfo in phoneinfos">{{phoneinfo.count}}</label> </div> HTML Attempt: <div id="searchtab-1" style="height:1.5em;" ng-controller="PhoneListCtrl"> <label ng-instance="phoneinfo">{{phoneinfo.count}}</label> </div> javascript: Defined variable: $scope.phoneinfo = [{ 'count': '555' }, {'type': 'mobile'}]; A: What about: <div id="searchtab-1" style="height:1.5em;" ng-controller="PhoneListCtrl"> <label>{{phoneinfo.count}}</label> </div> Javascript: $scope.phoneinfo = { count: '555', type: 'mobile' }; If you actually need the data to stay exactly as is, you could do this as well (but it doesn't look very pretty to me): <div id="searchtab-1" style="height:1.5em;" ng-controller="PhoneListCtrl"> <label>{{phoneinfos[0].count}}</label> </div> As for the names ending in s, I find it a good practice for the exact reason that you can write item in items, and it also signals that it's an array, but that is a matter of personal taste.
{ "pile_set_name": "StackExchange" }
Q: Get/store Facebook access token from REQUEST in PHP SDK 3.0 Let's say I get a valid access token from an external application that does Facebook Connect and sends me the token on GET. Is it normal/good for me to get that token and save it in the $facebook = new Facebook(...); object? Something like: $facebook = new Facebook(array( 'appId' => $this->app_id, 'secret' => $this->app_secret, )); $token = $facebook->getAccessToken(); if(empty($token) && isset($_REQUEST['access_token'])) $facebook->setAccessToken($_REQUEST['access_token']); $userID = $facebook->getUser(); if(!$userID) { return false; } return $facebook; And if this is OK to do, does the SDK also store this value in the SESSION or COOKIE array, or do I need to pass it to every script that requires it? A: Found out how this works. The SDK doesn't set my SESSION when calling setAccessToken(), I have to set it manually and it will work.
{ "pile_set_name": "StackExchange" }
Q: list attachment on wordpress i have this code: <?php $valid_ext = array("pdf", "doc"); $args = array( 'post_type' => 'attachment', 'post_mime_type' => 'application/pdf', 'numberposts' => 40, 'post_status' => null, 'post_parent' => null, // any parent ); $attachments = get_posts($args); if ($attachments) { foreach ($attachments as $post) { $ext = getFileExt(wp_get_attachment_url($post_id, false)); if(in_array($ext, $valid_ext)) { ?> <li> <div class="entry-date"> <abbr class="published" title="<?php the_time('Y-m-d\TH:i:sO')?>"> <?php unset($previousday); printf( __( '%1$s &#8211; %2$s', 'sandbox' ), the_date( '', '', '', false ), get_the_time() )?> </abbr> </div> <div id="post-<?php the_ID()?>" class="<?php sandbox_post_class()?> " style="padding:0; margin:0;"> <p style="font-size:11px; text-transform:uppercase;"> <?php setup_postdata($post);the_attachment_link($post_id, true);?> </p> </div> </li> <?php } } } ?> it gives me as output a date and a link with the document name. <li> <div class="entry-date"> <abbr title="2011-06-15T17:30:29+0200" class="published"> 15 giugno 2011 &ndash; 17:30 </abbr> </div> <div style="padding:0; margin:0;" class="hentry p11 attachment inherit author-daniela-santanch category-senza-categoria untagged y2011 m06 d15 h17 " id="post-2158"> <p style="font-size:11px; text-transform:uppercase;"> <a title="la_stampa_07_06_2011" href="http://www.mpli.it/wp/wp-content/uploads/2011/06/la_stampa_07_06_2011.pdf">la_stampa_07_06_2011</a> </p> </div> i'd like to get the post title linking directly to the document. any help? A: Try this: <?php $args = array( 'post_type' => 'attachment', 'numberposts' => -1, 'post_status' => null, 'post_parent' => null ); $attachments = get_posts( $args ); if ($attachments) { foreach ( $attachments as $post ) { setup_postdata($post); the_title(); the_attachment_link($post->ID, false); the_excerpt(); } } ?>
{ "pile_set_name": "StackExchange" }
Q: node-canvas: output PNG file as interlaced/progressive node-canvas is a Node.js version of the HTML5 canvas library that depends on Cairo. My app creates a bunch of PNG files depending on that data that is sent to the app. node-canvas offers two functions toBuffer() and toDataURL() which outputs raw PNG or Base64 encoded PNG to a string which I can send to the browser. However there is no way to add support for interlacing in the library. I'd like to extend the functionality of the library and add support for interlaced PNGs. I have the raw PNG data in a string, and also an array of pixels for the image (if need be). I do not have an understanding of how PNG encoding works. Can someone please point me to the algorithm I need to use to convert the data I have, either the non-interlaced raw PNG data or the pixel array and convert it to an interlaced/progressive PNG? This is a necessary step for the graphing calculator app that I am building that graphs complex equations. It would be good to have a blurry image that appears quickly and sharpens over time than a non-interlaced PNG that loads from top to bottom for my app. Thanks! A: You can't convert a non-interlaced raw PNG data to a interlaced PNG stream. Interlaced vs non-interlaced PNG are two different ways of PNG encoding (they basically differ in the pixel stream ordering, but after that a filter-compression is applied, so you can't simply alter the final stream to switch between interlaced and non-interlaced modes). TO generate an interlaced PNG is work of the PNG encoder, the one which is used to write your PNG files (or stream) from the raw image pixels. Nevertheless, I'd advise you against interlaced images; the compression efficiency suffers (specially with PNG) and the advantage for the user experience is at least debatable. See eg. Today, interlaced PNG is seldom used.
{ "pile_set_name": "StackExchange" }
Q: 3D printer simulation i am trying to build something like a primitive 3D printer in blender using fluid dynamics . I am having real problems to control the fluid dynamics . i was looking for something like this as a start but better if the fluid is a little less viscous when reaching the print bed ... https://www.youtube.com/watch?v=Se4v-QRWtYA the idea is to build a fun low polly structure then actually print the results . any pointers would be great thanks. A: A 3D printer doesn't really push out fluids... Fluid dynamics is the wrong way to approach it I would say. I would personally try to simulate it more using a particle system replicating small spheroids or cubes, where the particles have 0 motion and randomness out of the nozzle, and become children of the bed plate object to move along with the bed plate in your motion system. I've designed the chassis of my printer with Blender and am looking at doing something similar for video demo purposes, will post an update if you still need help with that when I get over the hurdles I'm facing.
{ "pile_set_name": "StackExchange" }
Q: Python read Linux memory process error (/proc/$pid/mem) I have the following code tested on some Linux distros (Debian, Linux Mint...) and working, but under CentOS I get an error even I run it as root: #!/usr/bin/env python import re maps_file = open("/proc/18396/maps", 'r') mem_file = open("/proc/18396/mem", 'r', 0) for line in maps_file.readlines(): # for each mapped region m = re.match(r'([0-9A-Fa-f]+)-([0-9A-Fa-f]+) ([-r])', line) if m.group(3) == 'r': # if this is a readable region start = int(m.group(1), 16) end = int(m.group(2), 16) mem_file.seek(start) # seek to region start chunk = mem_file.read(end - start) # read region contents print chunk, # dump contents to standard output maps_file.close() mem_file.close() The script reads the process' memory and dumps the readable region. Under CentOS 5.4 x64 I get the following error: Traceback (most recent call last): File "./mem.py", line 11, in ? chunk = mem_file.read(end - start) # read region contents IOError: [Errno 3] No such process The process is alive and readable: [root@localhost ~]# ps xa|grep 18396 18396 ? S 0:00 /usr/sbin/httpd [root@localhost ~]# ls -al /proc/18396/maps && ls -al /proc/18396/mem -r--r--r-- 1 root root 0 Jan 31 17:26 /proc/18396/maps -rw------- 1 root root 0 Jan 31 17:26 /proc/18396/mem any idea? I tried it under Python 2.4 and Python 2.7 works on Debian-like distros but not under CentOS. A: Found the answer myself after some digging: #!/usr/bin/env python import ctypes, re, sys ## Partial interface to ptrace(2), only for PTRACE_ATTACH and PTRACE_DETACH. c_ptrace = ctypes.CDLL("libc.so.6").ptrace c_pid_t = ctypes.c_int32 # This assumes pid_t is int32_t c_ptrace.argtypes = [ctypes.c_int, c_pid_t, ctypes.c_void_p, ctypes.c_void_p] def ptrace(attach, pid): op = ctypes.c_int(16 if attach else 17) #PTRACE_ATTACH or PTRACE_DETACH c_pid = c_pid_t(pid) null = ctypes.c_void_p() err = c_ptrace(op, c_pid, null, null) if err != 0: raise SysError, 'ptrace', err pid = "18396" ptrace(True, int(pid)) maps_file = open("/proc/"+pid+"/maps", 'r') mem_file = open("/proc/"+pid+"/mem", 'r', 0) for line in maps_file.readlines(): # for each mapped region m = re.match(r'([0-9A-Fa-f]+)-([0-9A-Fa-f]+) ([-r])', line) if m.group(3) == 'r': # if this is a readable region start = int(m.group(1), 16) end = int(m.group(2), 16) mem_file.seek(start) # seek to region start chunk = mem_file.read(end - start) # read region contents print chunk, # dump contents to standard output maps_file.close() mem_file.close() ptrace(False, int(pid))
{ "pile_set_name": "StackExchange" }
Q: Ploting matrix in matplotlib, while taking indexed data for positive and negative values, returns wrong plot axis or data Having a list of variables representing some geographical data plus one variable expressed as possitive or negative, I try while plotting two variables in a scatterplot, plot their negative values and positive values in separate colours. The problem comes in already while plotting f.e. just positive values: despite their min-max values, the ploted values does not correspond with scale, seems like completely other values were ploted, or values are rescaled with other axis. As x and y axes, both get the same scaling. System: windows8 64bits, though python 2.7 on 32 bits (comes with ARcGIS), numpy 1.8.1., matplotlib (Can't check the version).. code is smth like that: >>> df.head() ## DATA SAMPLE ## dem_sl events gwflabst kipp_macht luftb_hydgr_add 5056 4.01518 0 0.174846 3.56536 2.666560 5057 3.84420 0 0.000000 6.70155 2.193530 5058 3.95850 0 0.000000 7.18019 2.350860 5059 4.42980 0 0.661806 1.23403 3.514760 5496 1.25325 0 0.070530 9.10564 -0.821533 # df = ''pandas data frame, cleaned from NaN, lat lon dropped'' pos = np.where(df['events'] == 1) neg = np.where(df['events'] == 0) out = np.asmatrix(df) # while looping through var: for t in var: for tt in var: if t! = tt: I added later here extra printing the max value of both var. [Dbg]>>> print '...Plotting '+t, ' with min-max: ', df[t].min(), '---', df[t].max() ...Plotting kipp_macht with min-max: 0.0 --- 52.7769 [Dbg]>>> print '...Plotting '+tt, ' with min-max: ', df[tt].min(), '---', df[tt].max() ...Plotting luftb_hydgr_add with min-max: -2.70172 --- 34.7528 And when I plot the first scatterplot: #col index of the var plt.scatter(out[np.array(neg), df.columns.get_loc(t)],out[np.array(neg), df.columns.get_loc(tt)], marker='x', c='r') plt.scatter(out[np.array(pos), df.columns.get_loc(t)],out[np.array(pos), df.columns.get_loc(tt)], marker='+', c='b') plt.show() del var[0] # del the first var Seems like I get the data on both axis scaled by overall (from both axis) max and minimum. It is the same when I try on other data with bigger diff. in scales. The most interesting part, that once before, just trying to plot once, without loops, I tried to scatterplot accesing data by using simple structure as out[0], so not 'searching' for indexes and I got what I expected. And so now, I am not sure where is the problem, as even when I just plot negative values or just positive theay are already in a strange scale.. I tried creating fig and saving then fig to a file, tried cleaning the plot with plt.clf(). Simply by accessing the same values, tired to plot histograms to look at the dispersion, and all is fine except scatterplot. Would appreciate any help! A: If I understand correctly, you want to plot kipp_macht against luftb_hydgr_add separately for cases where events == 0 and events == 1. You could just use the contents of the events column to make boolean indices, and use these to index into kipp_macht and luftb_hydgr_add: plt.scatter(df.kipp_macht[df.events == 1], df.luftb_hydgr_add[df.events == 1], 'b+', label='pos') plt.scatter(df.kipp_macht[df.events == 0], df.luftb_hydgr_add[df.events == 0], 'rx', label='neg') Or you could get the corresponding row indices and use these to index into kipp_macht and luftb_hydgr_add, although this is a slightly more roundabout way to do things: pos = np.where(df.events == 1)[0] neg = np.where(df.events == 0)[0] plt.scatter(df.kipp_macht[pos], df.luftb_hydgr_add[pos], 'b+', label='pos') plt.scatter(df.kipp_macht[neg], df.luftb_hydgr_add[neg], 'rx', label='neg') You could also filter your entire dataframe according to the events column: df_pos = df[df.events == 1] df_neg = df[df.events == 0] Which would then allow you to plot the relationship between any pair of parameters for the 'positive' and 'negative' case, e.g.: plt.scatter(df_pos.kipp_macht, df_pos.luftb_hydgr_add, 'b+', label='pos') plt.scatter(df_neg.kipp_macht, df_neg.luftb_hydgr_add, 'rx', label='neg')
{ "pile_set_name": "StackExchange" }
Q: SharePoint Document or Item Download/View Event Handler? Is there any way to capture document download or item view actions in SharePoint 2010/2007? Thanks. A: I had a similar requirement in that I had to send an email when a document was downloaded. In WSS 3.0, I wrote an Http Module that looked at the request url and if the prefix of the request matched my document library URL, I captured that download/view.
{ "pile_set_name": "StackExchange" }
Q: Member function with multi-level list in Common Lisp I'm trying to understand how it works member function with list and list of lists. Here an example. (member '(A 6) '((A 7) (B 6) (E 6) (D 5)) :test #'string-equal :key #'second) I want to check with the member function if the second argument of the list '(A 6) is member of the second list in input. The answer should be true but I'm doing something wrong, because Common Lisp reply: Error: Cannot coerce (A 6) to type STRING. So how can I take the second argument from the first list? Thank you for the help. A: What you are missing is that the :key argument is not applied to the first argument of member. Another thing is that second will return the number, not the symbol. Thus: (member 'A '((A 7) (B 6) (E 6) (D 5)) :test #'string-equal :key #'first) ==> ((A 7) (B 6) (E 6) (D 5)) (member 'C '((A 7) (B 6) (E 6) (D 5)) :test #'string-equal :key #'first) ==> NIL (member 'E '((A 7) (B 6) (E 6) (D 5)) :test #'string-equal :key #'first) ==> ((E 6) (D 5)) Note that the return value is the tail, not the matched list element. This is to allow the use of member as a predicate, i.e., to distinguish between finding nil and finding nothing: (member nil '(1 2 nil 3)) ==> (NIL 3) (find nil '(1 2 nil 3)) ==> NIL (find t '(1 2 nil 3)) ==> NIL
{ "pile_set_name": "StackExchange" }
Q: How to "source" ~/.bashrc automatically once it has been edited? I would like to create an alias that does the following: Opens TextMate with ~/.bashrc and allows me to edit it Once I close TextMate, "sources" ~/.bashrc (so if I add a new alias, for example, it will be available immediately) I tried the following: alias b="/usr/bin/mate -w ~/.bashrc; source ~/.bashrc" but it doesn't work: when I close TextMate, the shell doesn't return. Any ideas? A: I hesitate to suggest it, but if this is a feature you really want, you can make something similar happen by setting the PROMPT_COMMAND variable to something clever. PROMPT_COMMAND is run every time the shell shows the shell prompt So, if you're okay with the shells updating only after you hit Enter or execute a command, this should nearly do it. Put export PROMPT_COMMAND="source ~/.bashrc" into your ~/.bashrc file. Re-source it into whichever shell sessions you want the automatically updating behavior to work in. This is wasteful -- it re-sources the file with every prompt. If you can get your editor to leave the old version in a specific file, say ~/.bashrc~ (where the first ~ means your home directory and the last ~ is just a ~, a common choice for backup filenames) then you could do something more like (untested): export PROMPT_COMMAND="[ ~/.bashrc -nt ~/.bashrc~ ] && touch ~/.bashrc~ && source ~/.bashrc " then it would stat(2) the two files on every run, check which one is newer, and re-source only if the ~/.bashrc is newer than its backup. The touch command is in there to make the backup look newer and fail the test again.
{ "pile_set_name": "StackExchange" }
Q: Textbox Shows before Label Text Not sure why the textbox shows first an then my text which I'm not using a real label tag shows up AFTER the textbox <p>Token: <input type="text" id="txt_Token" /></p> [ textbox ] Token: A: May be you are floating your input element left: #txt_Token{ float:left; } Check this fiddle
{ "pile_set_name": "StackExchange" }
Q: CSS z-Index with position: relative I am using css to create a "gantt-chart" style progress bar. It consists of an empty progress bar, inside which is a green bar which represents expected progress. On top of this should be another (thinner) black bar which represents actual progress. The "actual" and "expected" bars are independent - i.e. Actual could be more or less than expected, so I can't just nest the Actual bar inside the div for Expected. I want to have a number of these little progress bars, in a GridView or Repeater, so I can't use position absolute. How can I get the z-index to work so the Actual bar sits "on top" of the actual bar? The CSS I have is: div.progressBarEmpty { height:11px; background-color:Silver; border: 1px solid black; font-size: 0.1em } div.progressBarGreen { position:absolute; top:0;left:0; height:11px; background-color:#00ff33; border-right: 1px solid black; font-size: 0.1em z-index:0; } div.progressBarActual { position:absolute; top:3;left:0; height:5px; background-color:black; border-style: none; font-size: 0.1em z-index:1; } And the html: <div class="progressBarEmpty" style="width:100px"> <div class="progressBarGreen" style="width:40%" > </div> <div class="progressBarActual" style="width:80%"> </div> </div> (Just to be clear, the "progressBarActual" div should be 80% of the width of the "progressBarEmpty" div, not the "progressBarGreen") EDIT Here's a mockup of what I'm after. A: Live Demo (updated) The only change from my last demo: I changed top: 3 to top: 3px. See here for why that was required: (in short, you forgot the px) absolute positioning not working with XHTML? Live Demo Add position: relative to div.progressBarEmpty? I'm not entirely sure what it's supposed to look like, but it does now look vaguely like a Gantt chart. If this isn't quite right (as I suspect is the case), it's probably just a matter of adding a few more properties, so let me know what's wrong with it. See: http://css-tricks.com/absolute-positioning-inside-relative-positioning/ http://css-tricks.com/absolute-relative-fixed-positioining-how-do-they-differ/
{ "pile_set_name": "StackExchange" }
Q: convert a node object to a JSON object in groovy With this code, it returns a node object of a xml document def rootNode = new XmlParser().parseText(text) How can you parse this object into a JSON object (perhaps using JsonBuilder) ? I did try to pass by a String object (XmlUtil.serialize(rootNode)) but it didn't work out. Is there anything that I could use or do I need to create something of my own ? Thanks in advance A: You have to roll your own solution. Json has no concept of attributes, and you will need to decide what to do with sibling tags of the same name. There's no immediate obvious way to map from xml to Json
{ "pile_set_name": "StackExchange" }
Q: Parallel for and Progressbar I have this code: Parallel.For(0, img.Count(), i => { img[i].Scale = escala_axial; Bitmap tmp_b = new Bitmap((System.Drawing.Image)img[i].RenderImage(0)); tmp_b = filtro.Apply(tmp_b); imagenes[i] = tmp_b; Progress_Bar_Loading_Images.Invoke((MethodInvoker)(delegate() { Progress_Bar_Loading_Images.Value++; })); }); It works fine without the ProgressBar invoke thing. Now, when I use the Invoke, then it looks like it never ends the loop and the screen freezes. Any ideas what may be the issue? Thanks! EDIT: Here's the answer: Thanks for the feedback! Parallel.For(0, img.Count(), i => { img[i].Scale = escala_axial; Bitmap tmp_b = new Bitmap((System.Drawing.Image)img[i].RenderImage(0)); tmp_b = filtro.Apply(tmp_b); imagenes[i] = tmp_b; this.Invoke(new Action(() => Progress_Bar_Loading_Images.Value++)); }); A: Instead of progressbar.Invoke() use this: //rest of loop.... this.Invoke(/*your code here*/);
{ "pile_set_name": "StackExchange" }
Q: What is the implication of Perron Frobenius Theorem? The Perron Frobenius theorem states: Any square matrix $A$ with positive entries has a unique eigenvector with positive entries (up to a multiplication by a positive scalar), and the corresponding eigenvalue has multiplicity one and is strictly greater than the absolute value of any other eigenvalue. So I tempted fate using this matrix: $$ A =\begin{bmatrix} 1 & 1 \\ 1 & 1 \end{bmatrix}$$ I find my eigenvalues to be $\lambda_1 = 0, \lambda_2 = 2$ Now I find my eigenvector, taking $v_{11} = 1$, $v_{21} = 1$ I find $v_1 = \begin{bmatrix} v_{11} & v_{12} \end{bmatrix}$ = $\begin{bmatrix} 1 & -1 \end{bmatrix}$ $v_1 = \begin{bmatrix} v_{21} & v_{22} \end{bmatrix}$ = $\begin{bmatrix} 1 & 1 \end{bmatrix}$ This verifies the Perron-Frobenius theorem. Now what is the great implication that every positive square matrix has a real eigenvector with an eigenvalue that is the largest of all eigenvalues? Can someone show me an application of this theorem? A: The Perron-Frobenius theorem is used in Google's Pagerank. It's one of the things that make sure that the algorithm works. Here it's explained why the the theorem is useful, you have a lot of information with easy explanations on Google. A: For example, there are important applications in the theory of finite Markov chains. Among other things, it implies that a Markov chain with strictly positive transition probabilities has a unique stationary distribution. A: First of all, the conclusion is more interesting if you also try an example where the matrix entries are still real, but not positive. For example, if $A$ is the $2\times2$ rotation matrix $$A=\pmatrix{\cos\theta&\sin\theta\\ -\sin\theta&\cos\theta}$$ then you can check that the eigenvectors are no longer real, and there's no longer a unique eigenvalue of maximum modulus: the two eigenvalues are $e^{i\theta}$ and $e^{-i\theta}$. I second Robert Israel's nomination of Markov chains as a great application. I'll add the following, though. (I'll remark that you don't actually need the matrix to have positive entries - just for some power of it to have positive entries.) Suppose you have a finite connected graph (or strongly connected digraph) such that the gcd of the cycle lengths is $1$. Then if $A$ is the adjacency matrix for the graph, some power $A^r$ will have positive entries so Perron-Frobenius applies. Since the entries of $A^n$ count paths in the graph, we conclude that for any pair of vertices in the graph, the number of paths of length $n$ between them is $c\lambda_1^n(1+o(1))$, where $\lambda_1$ is the Perron-Frobenius eigenvalue and $c$ is a computable constant. Applications of this particular consequence of Perron-Frobenius include asymptotic growth rate results for "regular languages," which are defined in terms of paths on graphs. In particular, there is a cute formula giving the $n$-th Fibonacci number as $$F_n=\left\langle \frac1{\sqrt5}\phi^n\right\rangle$$ where $\phi$ is the "golden ratio" $(1+\sqrt5)/2$ and $\langle\cdot\rangle$ denotes "closest integer." This formula, and many others like it, become less surprising once you check that $$\pmatrix{1&1\\1&0}^n=\pmatrix{F_{n+1}&F_n\\ F_n&F_{n-1}}$$ and note that $\phi$ is the Perron-Frobenius eigenvalue (and the other eigenvalue is smaller than $1$ in absolute value.)
{ "pile_set_name": "StackExchange" }