source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0021059763.txt" ]
Q: how to change font size on html list using css O. Guys. i got an apex app and i am using Jquery Mobile Theme, but basically i got some list items i need to display on my screen, but my screen is a handheld, which has small screen size, so when i display the list item the size is too big, i will like to reduce font size. in my apex html page i got a "CSS Inline" section and actually got some code like this one below in which i reduced the font size of text and number fields, but i don’t know how to reduce font size of list item, i guess is easy but actually i am new on html and css stuff.. thanks in advance. input[type="text"] {font-size:8px} input[type="number"] {font-size:8px} A: you can apply the font size for list item as below in css file ul li{ font-size:8px; } In inline css: <ul > <li style="font-size:50px";>item1</li> </ul> A: Give your UL class a name: <ul class="bigFont"> Add your <li> items <li>Hello world</li> <li>Hello world1</li> </ul> add style .bigFont li{ font-size:8px; } A: If is a list, you can do @media screen and (max-width: 400){ ul li { font-size: .8em; } } nested in media query for only apply in small screen if you have a link nested in li, select tag a or put class name is a good practice use unit relative
[ "stackoverflow", "0023430109.txt" ]
Q: KeyPress event doesn't trigger on WinForm UserControl I have a user control in my winforms application with this code in the KeyPress event: private void txtCodigo_KeyPress(object sender, KeyPressEventArgs e) { if ((this.txtCodigo.Text.Length == 0) && (e.KeyChar == '\r')) { this.Limpiar(); if (LimpiarEvento != null) LimpiarEvento(this, new EventArgs()); if (NextControl != null) NextControl(this, new EventArgs()); } if ((this.txtCodigo.Text.Length > 0) && (e.KeyChar == '\r')) this.txtCodigo_Leave(sender, e); if (NUMEROS.IndexOf(e.KeyChar) < 0) { e.Handled = true; } } Now, my problem is that this UserControl is in many forms in my application and works perfectly when i press the enter key in the txtCodigo textbox but in one form the enter key is not being fired. Even if i put a breakpoint it doesn't fire at all. Why this could be happening? Edit: I just try to add a KeyPress event to the form itself and set the KeyPreview to true and the Enter key is not being captured... all the other keys are being captured except the Enter key. I really don't know what is happening. And yes... the enter key works fine in the keyboard :) A: Does that particular form have its AcceptButton set? (Already answered in comments) This SO question might be relevant for fixing up the Form: Prevent WinForm AcceptButton handling Return key
[ "mathematica.stackexchange", "0000039866.txt" ]
Q: Generating a list of integers that roughly satisfy a distribution Say I have a normal distribution, NormalDistribution[25, 7] I'd like integers from 1 to 50, not sampled at random from that distribution, but sampled in a way that the mean is more common than the bounds, following that distribution. What is that called, and is there a way of doing it concisely within Mathematica? I suppose one way to do it would be selecting a number from 1-50 with the probabilities given by Table[NormalDistribution[25, 7], {x, 1, 50, 1}] {0.00015967, 0.000257934, 0.000408253, 0.000633121, 0.000962014, \ 0.00143223, 0.00208921, 0.00298598, 0.00418147, 0.0057373, 0.007713, \ 0.0101596, 0.0131119, 0.0165803, 0.0205426, 0.0249376, 0.0296614, \ 0.0345672, 0.0394707, 0.0441593, 0.0484068, 0.051991, 0.0547124, \ 0.0564132, 0.0569918, 0.0564132, 0.0547124, 0.051991, 0.0484068, \ 0.0441593, 0.0394707, 0.0345672, 0.0296614, 0.0249376, 0.0205426, \ 0.0165803, 0.0131119, 0.0101596, 0.007713, 0.0057373, 0.00418147, \ 0.00298598, 0.00208921, 0.00143223, 0.000962014, 0.000633121, \ 0.000408253, 0.000257934, 0.00015967, 0.0000968449} Where each position is the probability that that number would be selected: 1 would show up with p = .00015967, etc. Is that right? I'm not really sure how to map and select the integers 1-50 along these probabilities, or even if that's on track. I'm not sure because I don't want it to be left to probability: the function that makes these should be deterministic. I don't think I'm describing this very well. The idea is to have parameters vary normally around the mean, 25, but are integers and not randomly sampled, as I only need a few (though in this case 50) though that number may change. I hope this makes some semblance of sense. The end result would be a list {1, 5, 10, 13, 17, 20, 22, 23, 24, 25, 25, 26, 27, 28, 30, 33, 37, 40, 45, 50} Or something like that, but with whatever distribution and number of numbers (I'd like to do it for something like MixtureDistribution[{1, 1}, {NormalDistribution[25, 7], NormalDistribution[75, 7]}] as well). A: One way to approach your question is to generate a list of integers whose cumulative distribution function (CDF) is as close as possible to that of the normal distribution. For a discrete statistical distribution the CDF is a staircaise function whose steps correspond to the numbers in the list. Ideally the numbers would correspond to where the discrete CDF is just 1/2 under the continuous CDF on the left and 1/2 above on the right. I suggest getting those points and then rounding them to get integers, which should be good enough as long as you have a reasonable number of integers. Here the continuous and discrete CDF's are F and G. (* your distribution is from 1 to a (a=50), you are looking for n numbers *) a = 50; n = 20; X = CensoredDistribution[{0, a}, NormalDistribution[25, 7]]; F := CDF[X] cuttingPoints = Range[n]/n - 1/(2 n); numbers = Round[InverseCDF[X, cuttingPoints]] Print["Mean = ", N@Mean[numbers], " Standard deviation = ", N@StandardDeviation[numbers]] (* the discrete CDF *) G[x_] := Length@Select[numbers, # <= x &]/n Plot[{F[x], G[x]}, {x, 0, a + 1}, PlotRange -> {0, 1}, PlotPoints -> 200] Output (note that there are two "25"'s): {11, 15, 17, 18, 20, 21, 22, 23, 24, 25, 25, 26, 27, 28, 29, 30, 32, 33, 35, 39} Mean = 25. Standard deviation = 6.98871 Check the results ShapiroWilkTest[numbers, {"PValue", "TestConclusion"}] // TableForm QuantilePlot[numbers] Show[ Plot[PDF[NormalDistribution[25, 7]][x], {x, 0, a}], SmoothHistogram[numbers, PlotStyle -> Red]] Output: 1. The null hypothesis that the data is distributed according to the NormalDistribution[\[FormalX],\[FormalY]] is not rejected at the 5 percent level based on the Shapiro-Wilk test.
[ "stackoverflow", "0021638462.txt" ]
Q: Given an number N, how to count the number of all m and n int pairs such that m*m + n*n < N? The naive solution would be to have a O(sqrtRoot of N) search for all pairs but there should be a smarter solution... I was hinted to use a threaded binary tree... Any idea? A: If you need a ballpark figure, and N is sufficiently large, you can answer in O(1): if you are interested in non-negative (m,n) pairs just reply pi*N*N/4; if you allow negatives reply pi*N*N. Noticing that each pair (m,n) such that m*m+n*n < N, m>0, n>0 corresponds to a point inside upper right quadrant inside a disk of radius sqrt(N). The area of such quarter-disk is pi*N*N/4. Each point (m,n) corresponds to a 1x1 square. Therefore you can expect approximately pi*N*N/4 such pairs to cover all the area of the quarter-disk. If you need a precise number then I don't know of any algorithm that would run faster than O(sqrt(N)).
[ "stackoverflow", "0051055086.txt" ]
Q: Is it possible to setup ElasticSearch and Grafana on a Service Fabric node? Is it possible to deploy an application with both Grafana and ElasticSearch using service fabric. A: Yes, it is. You can run them in containers On a Linux based cluster: how to for elasticsearch how to for grafana Elasticsearch on windows: how to for elasticsearch there is windows support for grafana, but I haven't found a docker file. So you'd have to create that
[ "drupal.stackexchange", "0000031038.txt" ]
Q: Node translation syncing problem with entity references I have a content type with multilingual support (node translation). This content type also has an entity reference (module: entityreference) field. My content is: /node/1 English story 1 /node/2 French story 1 (translation of #1) /node/3 English story 2 with reference to #1 /node/4 French story 2 (translation of #3) **entityreference problem here** I've configured the reference to be synchronized. The problem is that whenever I translate or edit a node, it'll try to sync the reference to other translations. So I'll always end up with: #3 -> #1 (correct) #4 -> #1 (wrong) or: #3 -> #2 (wrong) #4 -> #2 (correct) I can solve this by disabling syncing on the reference field but then I will have to be maintaining the references for all translations manually which is a problem in a website with many translations. A: Had the same problem, wrote this little workaround: function YOURMODULE_i18n_sync_translation($entity_type, $translation, $translation_language, $source, $source_language, $field_names) { foreach ($field_names as $field_name) { $info = field_info_field($field_name); if ($info['type'] == 'entityreference') { $items = field_get_items($entity_type, $source, $field_name); foreach ($items as $delta => $item) { $translations = translation_node_get_translations($item['target_id']); if (isset($translations[$translation_language])) { list($id, $vid, $bundle) = entity_extract_ids($entity_type, (object) $translations[$translation_language]); $translation->{$field_name}['und'][$delta]['target_id'] = $id; } } } } A: You should try module "Synchronize entity references" (i18n_entityreference) from project Internationalization contributions (i18n_contrib). So far, for me it looks perfect. It even works with inline entity form widgets. To install and use it: Install and enable the module. If you use drush: drush dl i18n_contrib && drush en i18n_entityreference (This requires the core module i18n_sync and will enable it automatically if not already done. It is needed for synchronizing field values across translations.) Configure "Synchronize translations". Basically go to "Structure → Content Types → [your content type]" in the admin menu, switch to tab "Synchronize translations", select your node reference field, and save. See here for details. Use. If you have existing content, the node reference field will be synced in a language-aware way when you save any node of a translation set for the next time.
[ "stackoverflow", "0058852966.txt" ]
Q: Remove dropdownlist one by one while is added Is it a way to remove dropdownlist one by one? i'm using jquery to create and append dropdownlist with button in div, the button is use for delete dropdownlist. Requirement: Able delete dropdownlist one by one. Here is a snippet showing the problem: $(document).ready(function() { $("#btnAddItem").click(function(){ var text = $('#ddl_device_option').val(); if(text == "device_1"){ $('#dvTable').append('<font face="Arial" size="4"> </font>&nbsp;'); $('#dvTable').append(text); $('#dvTable').append(' <select id="test"> <option>1</option> <option>2</option><option>3</option><option>4</option><option>5</option><option>6</option><option>7</option> <option>8</option> </select> '); var i = "1"; $('#dvTable').append('<input type="button" id='+ i +' value="x" class="btn btn-danger" >'); } else if(text == "device_2") { $('#dvTable').append('<font face="Arial" size="4"> </font>&nbsp;'); $('#dvTable').append(text); $('#dvTable').append(' <select> <option id="1">1</option> <option>2</option><option>3</option><option>4</option><option>5</option><option>6</option><option>7</option> <option>8</option> </select> '); var i = "2"; $('#dvTable').append('<input type="button" id='+ i +' value="x" class="btn btn-danger">'); } else if(text == "device_3"){ $('#dvTable').append('<font face="Arial" size="4"> </font> &nbsp;'); $('#dvTable').append(text); $('#dvTable').append(' <select> <option>1</option> <option>2</option><option>3</option><option>4</option><option>5</option><option>6</option><option>7</option> <option>8</option> </select> '); var i = "3"; $('#dvTable').append('<input type="button" id='+ i +' value="x" class="btn btn-danger">'); } }); }); $( "#dvTable" ).click(function() { // alert("clicked"); $(this).remove(); // it will remove entire div }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="itemOptions" class="panel panel-info"> <div > &nbsp;&nbsp;&nbsp; <font face="Arial" size="4" >Select Device:</font> &nbsp;&nbsp;&nbsp; <select id="ddl_device_option"> <option id="1">device_1</option> <option id="2">device_2</option> <option id="3">device_3</option> <option id="4">device_4</option> <option id="5">device_5</option> <option id="6">device_6</option> <option id="7">device_7</option> <option id="8">device_8</option> <option id="9">device_9</option> </select> &nbsp;&nbsp;&nbsp; <input id = "btnAddItem" type="button" value="+" class="btn btn-warning"> </div> </div> <div id="dvTable"> </div> A: There are two issues with your code. The first is that your click event fires on the wrong element: $( "#dvTable" ).click(function() { // alert("clicked"); $(this).remove(); // it will remove entire div }); This will cause any click on #dvTable to delete #dvTable. This is clearly not what you want. However, simply adding the click event to the #dvTable > input[type=button] selector won't work correctly. The way you build your new elements means that your dynamic HTML is buggy. I've modified your HTML output to this: var newElement; newElement = '<div>'; newElement += '<font face="Arial" size="4">&nbsp;' + text + '</font>' newElement += '<select id="test"> <option>1</option> <option>2</option><option>3</option><option>4</option><option>5</option><option>6</option><option>7</option> <option>8</option> </select>' var i = "1"; newElement += '<input type="button" id='+ i +' value="x" class="btn btn-danger" >'; newElement += '</div>'; $('#dvTable').append(newElement); This builds the text for the new element and wraps it in a div. It then adds the whole element at once to #dvTable. It then becomes much easier to remove the item you added. Your code then becomes: $(document).on('click', '#dvTable > div > select + input[type=button]', function() { $(this).parent().remove(); }); Essentially, when you click on any button that is under a div under #dvTable, it removes the parent element, which is the div. This removes all of the dynamic content you added previously, instead of only part of it. Take a look at the following working snippet showing this: $(document).ready(function() { $("#btnAddItem").click(function(){ var text = $('#ddl_device_option').val(); if(text == "device_1"){ var newElement; newElement = '<div>'; newElement += '<font face="Arial" size="4">&nbsp;' + text + '</font>' newElement += '<select id="test"> <option>1</option> <option>2</option><option>3</option><option>4</option><option>5</option><option>6</option><option>7</option> <option>8</option> </select>' var i = "1"; newElement += '<input type="button" id='+ i +' value="x" class="btn btn-danger" >'; newElement += '</div>'; $('#dvTable').append(newElement); } }); }); $(document).on('click', '#dvTable > div > select + input[type=button]', function() { $(this).parent().remove(); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="itemOptions" class="panel panel-info"> <div > &nbsp;&nbsp;&nbsp; <font face="Arial" size="4" >Select Device:</font> &nbsp;&nbsp;&nbsp; <select id="ddl_device_option"> <option id="1">device_1</option> <option id="2">device_2</option> <option id="3">device_3</option> <option id="4">device_4</option> <option id="5">device_5</option> <option id="6">device_6</option> <option id="7">device_7</option> <option id="8">device_8</option> <option id="9">device_9</option> </select> &nbsp;&nbsp;&nbsp; <input id = "btnAddItem" type="button" value="+" class="btn btn-warning"> </div> </div> <div id="dvTable"> </div> Note: I removed device_2 and device_3 from the code to show you an example of this working. You can fix those based on the code I've provided here.
[ "rpg.stackexchange", "0000119733.txt" ]
Q: Does the Pathfinder Cat animal companion get minus AC and Atk Roll for being large? Here's what the SRD says for Cat, Big Starting statistics: Size Medium; Speed 40 ft.; AC +1 natural armor; Attack bite (1d6), 2 claws (1d4); Ability Scores Str 13, Dex 17, Con 13, Int 2, Wis 15, Cha 10; Special Attacks rake (1d4); Special Qualities low-light vision, scent. 7th-level advancement: Size Large; AC +2 natural armor; Attack bite (1d8), 2 claws (1d6); Ability Scores Str +8, Dex –2, Con +4; Special Attacks grab, pounce, rake (1d6). It doesn't mention anything about minuses (AC/Atk Roll) when it gets the 7th level advancement. Does this imply it doesn't get bonus in cmb and cmd? A: Yes, the creature gets bonuses/penalties for being Large The size bonuses to AC, attack and CMB/CMD (and space/reach) are a standard that apply equally to all creatures. It does list those minuses and pluses, as "Size Large"; that includes all the standard bonuses and penalties of being large. Note that the stat blocks don't include "final" statistics like attack bonuses and AC, but only those base statistics needed to calculate the others. For example, it doesn't list that AC goes down by 1 because of the reduction in Dex when becoming large, because that is the standard result of Dex being reduced by 2 points.
[ "electronics.stackexchange", "0000132083.txt" ]
Q: Transistor: Mix both GND I Googled a little bit about transistors and I figured out I have a general understanding problem. Can I simply connect the emitter of the transistor to the GND of my microcontroller that controls the transistor but also to the GND of the 12V I try to control with the transistor, to close both circuits? Would the circuit shown below work? simulate this circuit – Schematic created using CircuitLab A: The circuit you show in your scheme will not work. Chances are that the transistor is damaged. For a transistor connected as a switch, it is normal to place the load in the collector circuit, as I show below simulate this circuit – Schematic created using CircuitLab This is the basic way to connect a NPN transistor in the output of a microcontroller to activate a load. When the output pin is in high, the transistor will conduct, feeding the load, in this case an LED. The value of the base resistance depends on the supply voltage of the microcontroller and the maximum current that support. The value of the collector resistor depends on the source Vcc, and the load that would like to activate. This way, you can share the GND connection between the microcontroller and the power supply to the load.
[ "gaming.stackexchange", "0000132732.txt" ]
Q: What is this face doing underneath my world? My people refused to settle in a particular area of my world, so I dug away at the landscape to try and work out (think there would be diamonds or something under there) but instead I found a face: What is this face doing underneath my world? A: It seems that it's only an easter egg for now, according to the FAQ on the wiki.
[ "stackoverflow", "0017382528.txt" ]
Q: "File Copying" section in KR I'm new to programming and I can't seem to get my head around why the following happens in my code, which is: #include <stdio.h> /*copy input to output; 1st version */ main() { int c; c = getchar(); while (c != EOF) { putchar(c); c = getchar(); } } So after doing some reading, I've gathered the following: Nothing executes until I hit Enter as getchar() is a holding function. Before I hit Enter, all my keystrokes are stored in a buffer When getchar() is called upon, it simply goes looks at the first value in the buffer, becomes that value, and then removes that value from the buffer. My question is that when I remove the first c = getchar() the resulting piece of code has exactly the same functionality as the original code, albeit before I type anything a smiley face symbol immediately appears on the screen. Why does this happen? Is it because putchar(c) doesn't hold up the code, and tries to display c, which isn't yet defined, hence it outputs some random symbol? I'm using Code::Blocks if that helps. A: The function you listed will simply echo back to you every character you type at it. It is true that the I/O is "buffered". It is the keyboard input driver of the operating system that is doing this buffering. While it's buffering keys you press, it echoes each key back at you. When you press a newline the driver passes the buffered characters along to your program and getchar then sees them. As written, the function should work fine: c = getchar(); // get (buffer) the first char while (c != EOF) { // while the user has not typed ^D (EOF) putchar(c); // put the character retrieved c = getchar(); // get the next character } Because of the keyboard driver buffering, it will only echo back every time you press a newline or you exit with ^D (EOF). The smiley face is coming from what @YuHao described: you might be missing the first getchar in what you ran, so putchar is echoing junk. Probably a 0, which looks like a smiley on your screen.
[ "stackoverflow", "0038975292.txt" ]
Q: How to count the number of calls to a method? I'm working with the pi2go lite robot. This is my code import pi2go, time import sys import tty import termios import time pi2go.init() def stepCount(): countL += 0 countR += 0 speed = 60 try: pi2go.stepForward(60,16) print stepCount finally: pi2go.cleanup() The question is I am wondering how to count everytime the "pi2go.stepForward(60,16)" is used. A: counter = dict(ok=0, fail=0, all=0) try: pi2go.stepForward(60,16) counter['ok'] += 1 except: counter['fail'] += 1 finally: counter['all'] += 1 pi2go.cleanup()
[ "stackoverflow", "0051646158.txt" ]
Q: Compare 2 CSV files line by line and print new lines only I am trying to compare 2 CSV files i.e. Old.csv and new.csv. I want to compare and print only those lines which are not in old.csv as compared to the new.csv. I want to print only new files which are not there in old file. $a = Import-Csv -Path C:\Users\subhatnagar\Desktop\old.csv $b = Import-Csv -Path C:\Users\subhatnagar\Desktop\new.csv $Green = $b | Where {$a -notcontains $_} $green A: Given that you want to find the new lines between two .csv files, you can use Compare-Object. $a = Import-Csv -Path C:\Users\subhatnagar\Desktop\old.csv $b = Import-Csv -Path C:\Users\subhatnagar\Desktop\new.csv Compare-Object -ReferenceObject $a -DifferenceObject $b | Select-Object -ExpandProperty InputObject | Export-Csv C:\Users\subhatnagar\Desktop\difference.csv -NoTypeInformation Explanation of the Command: Compare-Object -ReferenceObject $a -DifferenceObject $b - Find the Difference between to Objects Select-Object -ExpandProperty InputObject - Show only the different Objects and not the Indicator of Compare-Object Export-Csv -NoTypeInformation - Stores the piped values into a .csv file without Type-Header. If you only want to store the difference in a variable just delete the Export-Csv part: $green = Compare-Object -ReferenceObject $a -DifferenceObject $b | Select-Object -ExpandProperty InputObject
[ "stackoverflow", "0003878612.txt" ]
Q: Getting an error about an undefined method(constructor) when I'm looking right at it? (Java) I'm getting an error here that says I haven't defined a method, but it is right in the code. class SubClass<E> extends ExampleClass<E>{ Comparator<? super E> c; E x0; SubClass (Comparator<? super E> b, E y){ this.c = b; this.x0 = y; } ExampleClass<E> addMethod(E x){ if(c.compare(x, x0) < 0) return new OtherSubClassExtendsExampleClass(c, x0, SubClass(c, x)); //this is where I get the error ^^^^^^ } I did define that Constructor for SubClass, why is it saying that I didn't when I try to pass it in that return statement? A: You probably want new SubClass(c, x) instead of SubClass(c, x). In java you invoke constructor in different way than method: with new keyword. More on the subject.
[ "stackoverflow", "0008248832.txt" ]
Q: Lazy UITableView load I load a portion of data from server and show it in UITableView. When the user scrolls tableView to the bottom of tableView (last cell), I load next portion of data and show it in new cells in tableView (add new cells). My goal is to show in the bottom cell activity indicator while the data is loading from the server. Is there any standard beautiful and elegant way of implementation? I searched a lot, but found no answer. Thanks a lot for the answer! A: I keep a BOOL isLoadingData in my data model that tracks when data is loading. My tableViewController observes this property via KVO and updates the tableView. I've used the following methods to show the activity indicator. in tableView:viewForFooterInSection:, if isLoadingData = YES return a view that contains a UIActivityIndicatorView and a UILabel indicating that data is loading. Otherwise return nil. if isLoadingData = YES, in numberOfSectionsInTableView: add additional section to the count and return 1 for this section in tableView:numberOfRowsInSection:. In tableView:cellForRowAtIndexPath return a "loading" cell that contains a UIActivityIndicatorView and a UILabel.
[ "stackoverflow", "0019544321.txt" ]
Q: Issue with this.$el.find in Backbone framework I get am "TypeError: this.$el is undefined" in my backbone View. Here is my simple backbone view code var tableViews = Backbone.View.extend({ initialize: function() { console.log("initialized"); }, render: function() { this.$el.find(".clgcrt").removeClass("hidden"); } }); I included "http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js" url for my backbone. Is there any problem with above backbone version? A: You're using a very, very old version of Backbone. this.$el didn't get introduced until version 0.9.0. You'll, at a minimum, need to use this version: http://ajax.cdnjs.com/ajax/libs/backbone.js/0.9.0/backbone-min.js. Also, Justin in the comments mentioned you'll also need to use a recent version of Underscore.js, http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js. This needs to be included before you include Backbone.
[ "stackoverflow", "0012046694.txt" ]
Q: Send header 404 if id != $_get['id'] SQL query like this, $uid = $_GET['id']; $result = mysql_query("SELECT name, lastname, email FROM users WHERE id = '$uid'"); How to print a 404 header if the id != value of $_GET['id']? A: $uid = mysql_real_escape_string($_GET['id']); $result = mysql_query("SELECT name, lastname, email FROM users WHERE id = '{$uid}'"); if (!result || mysql_num_rows($result) == 0) header("Status: 404 Not Found"); Also note, you should move away from deprecated mysql_* functions. Also also note, Bobby Tables.
[ "tex.stackexchange", "0000166036.txt" ]
Q: Comma in front of & in the reference section I'm handling with a problem concerning referencing and citing sources in APA-Style. Here is my example code: \documentclass[a4paper, 12pt, bibtotoc, liststotoc, pointlessnumbers ]{scrartcl} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage{textcomp} \usepackage[american,ngerman]{babel} \usepackage[babel=true]{csquotes} \usepackage[style=apa,backend=biber, doi=false, url=false]{biblatex} \DeclareLanguageMapping{ngerman}{ngerman-apa} \DefineBibliographyStrings{ngerman}{andothers={et\ \addabbrvspace al\adddot}} \renewcommand\finalandcomma{\addcomma} \usepackage{filecontents} \begin{filecontents}{literatur.bib} @article{DroitVolet2007, author = {Droit-Volet, S. and Meck, W. H.}, year = {2007}, title = {{H}ow emotions colour our perception of time}, pages = {504--513}, volume = {11}, number = {12}, issn = {13646613}, journal = {Trends in Cognitive Sciences}, doi = {10.1016/j.tics.2007.09.008 Titel anhand dieser DOI in Citavi-Projekt übernehmen } @article{Gibbon1984, author = {Gibbon, J. and Church, R. M. and Meck, W. H.}, year = {1984}, title = {{S}calar timing in memory}, pages = {52--77}, volume = {423}, issn = {0077-8923}, journal = {Annals of the New York Academy of Sciences} } } \end{filecontents} \bibliography{literatur} \begin{document} There is no comma in this citation \parencite{DroitVolet2007}, but the comma is missing in the references. For more than two authors there has to be a comma in front of & \parencite{Gibbon1984}. \printbibliography \end{document} Latex misses a comma in front of & in the reference section, when there are only two authors. The intext-citation is totally fine for two authors, but the entry in the references should look like this: Droit-Volet, S., & Meck, W. H. (2007). .... For more than two authors there has to be a comma in front of & in in text-citations as well. While searching for a solution, I tried to fix it by using \renewcommand*{\finalnamedelim}{% \finalandcomma \addspace \bibstring{and}% \space } or \renewcommand\finalandcomma{\addcomma} But unfortunately neither of these solution worked in my case ... Help or any advice would be highly appreciated. Best wishes, Ferdinand A: Suppress the \renewcommand{\finalandcomma}{\addcomma} (in the apa style, \finalendcomma prints an ampersand, and you want to keep it). Replace it with the following in your preamble: \usepackage{xpatch} \xpatchnameformat{apaauthor}{% {\ifmorenames{\andothersdelim\bibstring{andothers}}{}}{}}% {% {\ifmorenames{\andothersdelim\bibstring{andothers}}{}}{\addcomma\space}}% {}{}% A: For some reason biblatex-apa redefines \finalnamedelim in the \AtBeginBibliography hook. So we will have to do the same to override the setting; additionally, we redefine the \finalandcomma in the \AtBeginDocument hook \AtBeginDocument{\renewcommand\finalandcomma{\addcomma}} \AtBeginBibliography{% \renewcommand*{\finalnamedelim}{% \ifthenelse{\value{listcount}>\maxprtauth} {} {\finalandcomma\addspace\&\space}}} This always print the \finalandcomma (it is normally only printed if there are more than two authors). MWE \documentclass{scrartcl} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage[american,ngerman]{babel} \usepackage{csquotes} \usepackage{xpatch} \usepackage[style=apa,backend=biber, doi=false, url=false]{biblatex} \DeclareLanguageMapping{ngerman}{ngerman-apa} \DefineBibliographyStrings{ngerman}{andothers={et\addabbrvspace al\adddot}} \AtBeginDocument{\renewcommand\finalandcomma{\addcomma}} \AtBeginBibliography{% \renewcommand*{\finalnamedelim}{% \ifthenelse{\value{listcount}>\maxprtauth} {} {\finalandcomma\addspace\&\space}}} \addbibresource{biblatex-examples.bib} \begin{document} There is no comma in this citation \parencite{baez/article}, but the comma is missing in the reference. \printbibliography \end{document}
[ "tex.stackexchange", "0000300033.txt" ]
Q: How to enable protrusion for superscript numbers? I am using the memoir class in XeTeX with the microtype package. As generally protrusion works as expected, it doesn't work for superscript numbers, which occur as footnote references. According to this article it ought to work with some extra settings: \SetProtrusion{encoding={*},family={bch},series={*},size={6,7}} {1={ ,750},2={ ,500},3={ ,500},4={ ,500},5={ ,500}, 6={ ,500},7={ ,600},8={ ,500},9={ ,500},0={ ,500}} But in my example it does not work: \documentclass[a4paper,10pt,twoside]{memoir} \usepackage{fontspec} \usepackage[protrusion=true,final]{microtype} % rubber: set program xelatex \setmainfont[Numbers={OldStyle},Ligatures={Common, Historic}]{Liberation Serif} \SetProtrusion{encoding={*},family={Liberation Serif},series={*},size={6,7,8,9}} {1={ ,750},2={ ,500},3={ ,500},4={ ,500},5={ ,500}, 6={ ,500},7={ ,600},8={ ,500},9={ ,500},0={ ,500}} \usepackage[]{blindtext} \begin{document} \chapter{Dies ist eine Kapitelüberschrift} Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam lobortis facilisis sem. Nullam nec mi et neque pharetra sollicitudin. Praesent imperdiet mi, nec ante. Donec, ullamcorper, felis non sodales commodo, lectus velit ultrices augue, a dignissim nibh\footnote{\blindtext} lectus placerat pede. Vivamus nunc nunc, molestie ut, ultricies vel, semper in, velit. Ut porttitor. Praesent in sapien. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Duis fringilla tristique neque. Sed interdum libero ut metus. Pellentesque placerat. Nam rutrum augue a leo. Morbi sed elit sit amet ante lobortis sollicitudin. Praesent blandit blandit mauris. Praesent lectus tellus, aliquet aliquam, luctus a, egestas a, turpis. Mauris lacinia lorem sit amet ipsum. Nunc quis urna dictum turpis accumsan semper. \blindtext \end{document} What is wrong in the above example? A: Protrusion is inhibited here because the memoir class inserts infinitesimal kerns after footnote markers to check whether there are two consecutive footnotes12, in which case it would insert a separating comma1,2. While these kerns are only meant to be a way of carrying on information (if memoir finds this very, very small kern of 3sp it assumes that the previous thing typeset was a footnote marker) without being visible (not only because the kern is so small, but also because there are actually two kerns - one positive, one negative, cancelling each other out), they will still prevent pdftex from applying protrusion. To allow protrusion of footnote markers, you therefore have to disable this feature by adding the following to your preamble: \makeatletter \let\m@mmf@prepare\relax \let\m@mmf@check\relax \makeatother resulting in: (This of course means that memoir will no longer be able to automatically identify consecutive footnotes, so that you would have to insert \multfootsep manually.)
[ "stackoverflow", "0034377458.txt" ]
Q: Unexpected jump from an x86 interrupt handler I am making my custom 8x86 64 bit OS, and I have some problem for an interrupt handler. When I added interrupt handlers for common exceptions and interrupts, I enabled interrupt by "sti" instruction. Then, "General Protection Fault" occurs right after enabling interrupt. So, I checked GDB. The stack is (gdb) bt #0 kISR::kISRGeneralProtection () at /home/xaliver/WorkSpace/kOdin/kernel64/./ISR.cpp:70 #1 0x000000000000fee8 in ?? () #2 0x0000000000202e30 in _kISRTimer () Backtrace stopped: frame did not save the PC The weird part is 0xfee8. I uses memory below 0x10000 as a stack for the 32 bit protected mode. Now, the system is in 64 bit mode, so the value is empty as "00 00". So, I checked the frame 2, _kISRTimer. The saved rip of 0xfee8 is 0x202e30. It is "iretq" instruction of _kISRTimer. here is assembly code. ; #32, Timer ISR _kISRTimer: KSAVECONTEXT ; Store the context and change selector to 202dd3: 55 push %rbp 202dd4: 48 89 e5 mov %rsp,%rbp 202dd7: 50 push %rax 202dd8: 53 push %rbx 202dd9: 51 push %rcx 202dda: 52 push %rdx 202ddb: 57 push %rdi 202ddc: 56 push %rsi 202ddd: 41 50 push %r8 202ddf: 41 51 push %r9 202de1: 41 52 push %r10 202de3: 41 53 push %r11 202de5: 41 54 push %r12 202de7: 41 55 push %r13 202de9: 41 56 push %r14 202deb: 41 57 push %r15 202ded: 66 8c d8 mov %ds,%ax 202df0: 50 push %rax 202df1: 66 8c c0 mov %es,%ax 202df4: 50 push %rax 202df5: 0f a0 pushq %fs 202df7: 0f a8 pushq %gs 202df9: 66 b8 10 00 mov $0x10,%ax 202dfd: 8e d8 mov %eax,%ds 202dff: 8e c0 mov %eax,%es 202e01: 8e e8 mov %eax,%gs 202e03: 8e e0 mov %eax,%fs ; kernel data descriptor ; Insert interrupt number to the hander and call the handler mov rdi, 32 202e05: bf 20 00 00 00 mov $0x20,%edi call _kCommonInterruptHandler 202e0a: e8 75 e3 ff ff callq 201184 <_kCommonInterruptHandler> KLOADCONTEXT ; Restore the context 202e0f: 0f a9 popq %gs 202e11: 0f a1 popq %fs 202e13: 58 pop %rax 202e14: 8e c0 mov %eax,%es 202e16: 58 pop %rax 202e17: 8e d8 mov %eax,%ds 202e19: 41 5f pop %r15 202e1b: 41 5e pop %r14 202e1d: 41 5d pop %r13 202e1f: 41 5c pop %r12 202e21: 41 5b pop %r11 202e23: 41 5a pop %r10 202e25: 41 59 pop %r9 202e27: 41 58 pop %r8 202e29: 5e pop %rsi 202e2a: 5f pop %rdi 202e2b: 5a pop %rdx 202e2c: 59 pop %rcx 202e2d: 5b pop %rbx 202e2e: 58 pop %rax 202e2f: 5d pop %rbp iretq ; Return the event point after interrupt 202e30: 48 cf iretq I think there is no point to jump 0xfee8. I also tried to remove the interrupt handler for timer. However, "GPF" occurs at other interrupt handler. The other interrupt handler is the same as _kISRTimer, but the call function is different. Do you know why GPF occurs from the code? Or, the jump is not from code? Please let me know why this problem happens. Thank you. A: The iretq instruction, or return from interrupt handler to a 64-bit address, expects the return address and the flags to be on the top of the stack, and produces a general protection fault if the return address is not valid (for example, because it points to a no-execute memory page). Therefore, you should inspect the values on the stack when your handler gets called, the calling code, and the CS selector. If any of these have changed, your stack might contain garbage. Your comment about “memory below 0x10000 as a stack for the 32 bit protected mode” suggests that one or both of these might be the case.
[ "math.stackexchange", "0001564609.txt" ]
Q: Evaulate $\cosh(1-i\sqrt{3})$ Going through some exercises in complex functions and I get $\frac{1}{2}(ee^{-i\sqrt{3}} + e^{-1}e^{i\sqrt{3}})$ but not sure if I can simplify this further? Thanks A: Yes, you can, you have to use that $e^{ix}=cos(x)+isin(x)$ and you get to the final result. A: Notice, $$\cosh(1-i\sqrt 3)=\frac{e^{1-i\sqrt 3}+e^{-1+i\sqrt 3}}{2}$$ $$=\frac{ee^{-i\sqrt 3}+e^{-1}e^{i\sqrt 3}}{2}$$ $$=\frac{e(\cos(\sqrt 3))-i\sin(\sqrt 3))+e^{-1}(\cos(\sqrt 3)+i\sin(\sqrt 3))}{2}$$ $$=\frac{(e+e^{-1})\cos(\sqrt 3)-i(e-e^{-1})\sin(\sqrt 3)}{2}$$ $$=\left(\frac{e+e^{-1}}{2}\right)\cos(\sqrt 3)-i\left(\frac{e-e^{-1}}{2}\right)\sin(\sqrt 3)$$ $$=\cosh (1)\cos(\sqrt 3)-i\sinh (1)\sin(\sqrt 3)$$ A: it is $$\cosh \left( 1 \right) \cos \left( \sqrt {3} \right) -i\sinh \left( 1 \right) \sin \left( \sqrt {3} \right) $$
[ "gis.stackexchange", "0000229041.txt" ]
Q: Estimation of volume from DTM I'm using QGIS for quite a while now but I'm having some problems in measuring the volume of a depression zoned North of a waste dump I'm studying. For the analysis I'm using a recent 1mx1m DTM of the area: As I said the main element of the study is an estimation of the volume of the depression North of the dump. Here's the hillside of the area: where I highlighted the boundaries of the depression. As tool for the estimation I used the SAGA GIS tool Raster Volume in Qgis. As Input GRID information I used the 1mx1m DTM but after running it on the log message panel here's the result: Usage: saga_cmd grid_calculus 2 [-GRID <str>] [-METHOD <str>] [-LEVEL <str>] -GRID:<str> Grid Grid (input) -METHOD:<str> Method Choice Available Choices: [0] Count Only Above Base Level [1] Count Only Below Base Level [2] Subtract Volumes Below Base Level [3] Add Volumes Below Base Level Default: 0 -LEVEL:<str> Base Level Floating point Default: 0.000000* I used the "Count only above base level" method considering the lowest point of the DTM as base level, but as you can see the result is a 0 value volume. Am I mistaking anything? Here is the .asc DTM. A: Using QGIS 2.18.3, it seems to work fine. I set the "County Only Above Base Level", with base level equals to 0 and I get this log: Algorithm Raster volume starting... grid_calculus "Grid Volume" -GRID "C:\Users\xxxxx\AppData\Local\Temp\processingdd38dbc0f5ec434f922835f11ed2d9d0\3ddfa5d81c1744819d54de14d3c7a8f1\DTMdiscarica.sgrd" -METHOD 0 -LEVEL 0 C:\OSGeo4W\bin>set SAGA=C:/OSGeo4W/apps\saga C:\OSGeo4W\bin>set SAGA_MLB=C:/OSGeo4W/apps\saga\modules C:\OSGeo4W\bin>PATH=C:\OSGeo4W\apps\Python27\lib\site-packages\Shapely-1.2.18-py2.7-win32.egg\shapely\DLLs;C:\OSGeo4W\apps\Python27\DLLs;C:\OSGeo4W\apps\qgis\bin;C:\OSGeo4W\bin;C:\Windows\system32;C:\Windows;C:\Windows\WBem;C:\OSGeo4W\apps\msys\bin;C:\OSGeo4W\apps\Python27\Scripts;C:/OSGeo4W/apps\saga;C:/OSGeo4W/apps\saga\modules C:\OSGeo4W\bin>saga_cmd grid_calculus "Grid Volume" -GRID "C:\Users\xxxxx\AppData\Local\Temp\processingdd38dbc0f5ec434f922835f11ed2d9d0\3ddfa5d81c1744819d54de14d3c7a8f1\DTMdiscarica.sgrd" -METHOD 0 -LEVEL 0 ERROR 1: Can't load requested DLL: C:\OSGeo4W\apps\saga\dll\gdal_MrSID.dll 127: Impossibile trovare la procedura specificata. ERROR 1: Can't load requested DLL: C:\OSGeo4W\apps\saga\dll\gdal_MrSID.dll 127: Impossibile trovare la procedura specificata. _____________________________________________ ##### ## ##### ## ### ### ## ### ### # ## ## #### # ## ### ##### ## # ##### ##### # ## ##### # ## _____________________________________________ _____________________________________________ library path: C:\OSGeo4W\apps\saga\modules\grid_calculus.dll library name: Grid - Calculus tool name : Grid Volume author : (c) 2005 by O.Conrad _____________________________________________ Load grid: C:\Users\xxxxx\AppData\Local\Temp\processingdd38dbc0f5ec434f922835f11ed2d9d0\3ddfa5d81c1744819d54de14d3c7a8f1\DTMdiscarica.sgrd... Parameters Grid system: 1; 1290x 1792y; 624079.089172x 4919509.290207y Grid: DTMdiscarica Method: Count Only Above Base Level Base Level: 0.000000 Grid Volume: Volume: 890177920.097229 C:\OSGeo4W\bin>exit Converting outputs Loading resulting layers Algorithm Raster volume finished So, I get Volume: 890177920.097229 (I think it's expressed in the project units). EDIT Before running the algorithm, remember to check this option from Processing > Options: Otherwise, you won't see any result.
[ "serverfault", "0000363888.txt" ]
Q: Cronjob not running as apache I have a cron job that runs a PHP script and creates files (images). But the cron job is running as me (being me my own username), not apache, nobody, httpd, www... and all the files created belongs to this user. If I run the the same script through a browser, it runs as apache. I've tested it with whoami and checked the file permissions. The problem is that if I develop an web-interface to remove files (which is how users/admin will be able to manage the images), it will run as apache and it won't be able to remove the files, as apache is not the owner nor belongs to the same group as me. What would be the correct way to deal with this? Add me to apache group or the other way around? Save the files with permission 0777? This looks 'ugly' Try to run the cron job as apache? How? A: It's best run the cron job as your apache user: sudo crontab -u apache_user -e This is a cleaner solution compared to running the job as you, because what belongs to apache should stay such. Mixing of users will bring mess and could produce problems at some point. A: There are different solutions: Add your user to apache group www-data, nobody, or whatever it is called on your system. You need also to grant the group write permission. Run the cron job under apache user. This can be done using a command like: sudo su apache_user -c "crontab -e". However, this may not work depending on whether it is allowed to switch to apache user and add cron jobs for apache_user. I think point 1 should be better.
[ "stackoverflow", "0045812387.txt" ]
Q: How to validate structure (or schema) of dictionary in Python? I have a dictionary with config info: my_conf = { 'version': 1, 'info': { 'conf_one': 2.5, 'conf_two': 'foo', 'conf_three': False, 'optional_conf': 'bar' } } I want to check if the dictionary follows the structure I need. I'm looking for something like this: conf_structure = { 'version': int, 'info': { 'conf_one': float, 'conf_two': str, 'conf_three': bool } } is_ok = check_structure(conf_structure, my_conf) Is there any solution done to this problem or any library that could make implementing check_structure more easy? A: You may use schema (PyPi Link) schema is a library for validating Python data structures, such as those obtained from config-files, forms, external services or command-line parsing, converted from JSON/YAML (or something else) to Python data-types. from schema import Schema, And, Use, Optional, SchemaError def check(conf_schema, conf): try: conf_schema.validate(conf) return True except SchemaError: return False conf_schema = Schema({ 'version': And(Use(int)), 'info': { 'conf_one': And(Use(float)), 'conf_two': And(Use(str)), 'conf_three': And(Use(bool)), Optional('optional_conf'): And(Use(str)) } }) conf = { 'version': 1, 'info': { 'conf_one': 2.5, 'conf_two': 'foo', 'conf_three': False, 'optional_conf': 'bar' } } print(check(conf_schema, conf)) A: Without using libraries, you could also define a simple recursive function like this: def check_structure(struct, conf): if isinstance(struct, dict) and isinstance(conf, dict): # struct is a dict of types or other dicts return all(k in conf and check_structure(struct[k], conf[k]) for k in struct) if isinstance(struct, list) and isinstance(conf, list): # struct is list in the form [type or dict] return all(check_structure(struct[0], c) for c in conf) elif isinstance(struct, type): # struct is the type of conf return isinstance(conf, struct) else: # struct is neither a dict, nor list, not type return False This assumes that the config can have keys that are not in your structure, as in your example. Update: New version also supports lists, e.g. like 'foo': [{'bar': int}]
[ "stackoverflow", "0030836791.txt" ]
Q: How to re-write templated function to handle type deduction So, I have this search function for the map container: template <typename Key, typename T> void searchInMapByKey(std::map<Key,T> Map, T keyValue) { if(Map.empty()) { std::cout << "Map is empty, nothing to search for..." << "\n"; } else { for(const auto & element : Map) { if(element.first==keyValue) { std::cout << keyValue << "matches a key value " << " in the map" << "\n"; } } } } and I seem to be running into deducing type issues, specifically this error: candidate template ignored: deduced conflicting types for parameter 'T' ('std::__1::basic_string<char>' vs. 'int') when I try to test it with the following code: map<int,string> myMap; myMap.emplace(1,string("a")); myMap.emplace(2,string("b")); myMap.emplace(3,string("c")); searchInMapByKey(myMap,1); Because the compiler doesn't know which type to associate with the "T", integer or string. Now, I asked a similar question about the same type of error and was able to solve the issue by using C++ style strings. However, I don't want to keep handling conflicting type deduction errors on a case by case basis, and was wondering how I could write this function (using templates) to help the compiler better deduce which type should be associated with the "T" from the outset? A: The problem is a mismatch between the type of the Map and the key types. But I would fix it not by correcting the order of the parameters std::map argument, but by changing the definition to be more generic. template <typename MapType, typename KeyType> void searchInMapByKey(const MapType & Map, KeyType key) { if(Map.empty()) { std::cout << "Map is empty, nothing to search for..." << "\n"; return; } for(const auto & element : Map) { if(element.first==keyValue) { std::cout << keyValue << "matches a key value " << " in the map" << "\n"; } } }
[ "stackoverflow", "0003403773.txt" ]
Q: Using multiple property files (via PropertyPlaceholderConfigurer) in multiple projects/modules We are currently writing an application which is split into multiple projects/modules. For example, let's take the following modules: myApp-DAO myApp-jabber Each module has its own Spring context xml file. For the DAO module I have a PropertyPlaceholderConfigurer which reads a property file with the necessary db connection parameters. In the jabber module I also have a PropertyPlaceHolderConfigurer for the jabber connection properties. Now comes the main application which includes myApp-DAO and myApp-jabber. It reads all the context files and starts one big Spring context. Unfortunately it seems like there can only be one PropertyPlaceholderConfigurer per context, so whichever module gets loaded first is able to read it's connection parameters. The other one throws an exception with an error like "Could not resolve placeholder 'jabber.host'" I kind of understand what the problem is, but I don't really know a solution - or the best practice for my usecase. How would I configure each module so that each one is able to load its own property file? Right now I've moved the PropertyPlaceHolderConfigurer out of the seperate context files and merged them into the main application's context (loading all property files with a single PropertyPlaceHolderConfigurer). This sucks though, because now everyone who uses the dao module has to know, that they need a PropertyPlaceHolderConfigurer in their context .. also the integration tests in the dao module fail etc. I'm curious to hear about solutions/ideas from the stackoverflow community.. A: If you ensure that every place holder, in each of the contexts involved, is ignoring unresolvable keys then both of these approaches work. For example: <context:property-placeholder location="classpath:dao.properties, classpath:services.properties, classpath:user.properties" ignore-unresolvable="true"/> or <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:dao.properties</value> <value>classpath:services.properties</value> <value>classpath:user.properties</value> </list> </property> <property name="ignoreUnresolvablePlaceholders" value="true"/> </bean> A: I know that this is an old question, but the ignore-unresolvable property was not working for me and I didn't know why. The problem was that I needed an external resource (something like location="file:${CATALINA_HOME}/conf/db-override.properties") and the ignore-unresolvable="true" does not do the job in this case. What one needs to do for ignoring a missing external resource is: ignore-resource-not-found="true" Just in case anyone else bumps into this. A: You can have multiple <context:property-placeholder /> elements instead of explicitly declaring multiple PropertiesPlaceholderConfigurer beans.
[ "ru.stackoverflow", "0000090539.txt" ]
Q: Возможность выдачи сервером исходного кода Вот в этом вопросе меня заинтересовал приведенный в одном из ответов код. /* безопасное соединение с базой данных, файл лежит перед корнем сайта если вдруг упадет php, логин и пароль к базе данных никто не сможешь увидеть */ include_once('../db-site.php'); Как я понимаю, автор боится того, что сервер Apache+PHP вместо выполнения PHP-сценария выдаст исходный код чистым текстом. Но ведь это должно быть невозможно в принципе (как я понимаю), ведь даже если PHP упал, то Apache при запросе в адресе *.php попытается запустить php, который лежит, а значит пользователь получит в ответ ошибку, или ничего. Вопрос: при каких условиях возможна выдача сервером исходного кода? A: Есть PHP ляжет, то сервер отдаст PHP-листинг (исходный код). A: к чему столько паники, пишем адекватный .htaccess перенаправляющий все запросы на index.php , в index.php только инклюды необходимых файлов (ядра, контроллера и т.д.) и всё даже если пхп упадет пользователь получит листинг только файла index.php а извращаться и хранить файл подключения к бд под корнем сайта это, извините, параноя. A: Не извращайтесь так) В index.php пишем инклуд, весь остальной код ограничиваем какой-то папкой. У меня получилось такое: #.htaccess ErrorDocument 404 /404.html RewriteEngine On RewriteRule ^system/.*/$ /404.html [L] #папки RewriteRule ^system/.*\.php$ /404.html [L] #.php Ну а если ляжет поддержка .htaccess - скорее всего это будет означать, что лег апач.
[ "math.stackexchange", "0000411658.txt" ]
Q: Is there a contradiction is this exercise? The following exercise was a resolution to this problem Let $\displaystyle\frac{2x+5}{(x-3)(x-7)}=\frac{A}{(x-7)}+\frac{B}{(x-3)}\space \forall \space x \in \mathbb{R}$. Find the values for $A$ and $B$ The propose resolution was: In order to isolate $A$ on the right side, multiply all the equation by $x-7$ $\displaystyle\frac{(2x+5)(x-7)}{(x-3)(x-7)}=\frac{A(x-7)}{(x-7)}+\frac{B(x-7)}{(x-3)}$ Now is my doubt. The resolution suggests that $x-7$ cancel out. $\displaystyle\frac{(2x+5)}{(x-3)}=A+\frac{B(x-7)}{(x-3)}$ But, $x-7$ can be equal zero. In this situation, is allowed to perform this operation? One can say "for every $x\neq7$", but on the next step the resolution says "for $x=7$ we have". $\displaystyle\frac{(14+5)}{(7-3)}=A+\frac{B(0)}{(7-3)} \Leftrightarrow A=\frac{19}{4}$ I think there is a contradiction is this resolution. A: The incorrect bit is "$\forall x\in\Bbb R$." We must indeed rule out $x=7$ and $x=3$ in order to avoid problems. What we can still do in that case is take the limit as $x$ approaches $7$ (we can't just plug $x=7$ in, if we've declared that $x\ne 7$), and get the same result.
[ "movies.stackexchange", "0000061960.txt" ]
Q: Did Patrick Stewart appear as an uncredited extra in this episode of Stargate Atlantis? In Stargate: Atlantis, Season 1, Episode 8 "Underground," Major Shepard's team meet the Genii. This marks the first appearance of Colm Meaney (Chief O'Brien on Star Trek: TNG) as Cowen, leader of the Genii. Near the end of the episode, Cowen orders his men from hiding to surround Major Shepard and his team. As one of those soldiers moves into place, we get a pretty tight close-up. I swear it's Patrick Stewart. However, I can't find anything from IMDB, Stargate's wiki, or other internet sources to confirm this. Was that Patrick Stewart, or just a guy who looks like Patrick Stewart? This badly ripped video from youtube is all I could find to provide a link for, but pausing on my DVD gives a clear picture, and I swear it's him. A: I reviewed my blu-ray copies and can say that the answer is no. Please see this attached, HD screen grab. Perhaps the low res version could pass, but not in glorious high definition!
[ "unix.stackexchange", "0000310844.txt" ]
Q: Running Cron every 2 hours and 5 minutes I need create a cron job running every 2 hours and 5 minutes, is this possible? This doesn't work since is running each 5 minutes :( user@server$ crontab -l 0,5,10,15,20,25,30,35,40,45,50,55 0,2,4,6,8,10,12,14,16,18,20,22 * * * date >> /tmp/cron-test01.out user@server$ cat /tmp/cron-test01.out Mon Sep 19 10:05:00 GMT 2016 Mon Sep 19 10:10:00 GMT 2016 Mon Sep 19 10:15:00 GMT 2016 Mon Sep 19 10:20:00 GMT 2016 Mon Sep 19 10:25:00 GMT 2016 Mon Sep 19 10:30:00 GMT 2016 user@server$ A: cron does not naturally handle this kind of interval. You could try running a job every five minutes and adding a time check within the job to allow it to execute every 125 minutes: */5 * * * * [ $(expr $(date +\%s) / 60 \% 125) -eq 0 ] && date >> /tmp/cron-test01.out
[ "stackoverflow", "0023783655.txt" ]
Q: R_Sample with probabilities I am having some problem with understanding the prob in sample. For example I want to create a sample data set of size 100 with integers 1,2,3 & 4. I am using a probability of 0.1,0.2,0.3 & 0.4 respectively. sample1<-sample(1:4,100,replace=T,prob=seq(0.1,0.4,0.1)) So, now I am expecting a sample with integers of 1,2,3 & 4 repeating 10,20,30 & 40 times respectively. But the result is different > table(sample1) sample1 1 2 3 4 7 24 33 36 Can anyone explain this? And what should I do if I want to get the expected results which is > table(sample1) sample1 1 2 3 4 10 20 30 40 A: sample(...) takes a random sample with probabilities given in prob=..., so you will not get exactly that proportion every time. On the other hand, the proportions get closer to those specified in prob as n increases: f <- function(n)sample(1:4,n,replace=T,prob=(1:4)/10) samples <- lapply(10^(2:6),f) t(sapply(samples,function(x)c(n=length(x),table(x)/length(x)))) # n 1 2 3 4 # [1,] 1e+02 0.090000 0.220000 0.260000 0.430000 # [2,] 1e+03 0.076000 0.191000 0.309000 0.424000 # [3,] 1e+04 0.095300 0.200200 0.310100 0.394400 # [4,] 1e+05 0.099720 0.199800 0.302250 0.398230 # [5,] 1e+06 0.099661 0.199995 0.300223 0.400121 If you need a random sample with exactly those proportions, use rep(...) and randomize the order. g <- function(n) rep(1:4,n*(1:4)/10)[sample(1:n,n)] samples <- lapply(10^(2:6),g) t(sapply(samples,function(x)c(n=length(x),table(x)/length(x)))) # n 1 2 3 4 # [1,] 1e+02 0.1 0.2 0.3 0.4 # [2,] 1e+03 0.1 0.2 0.3 0.4 # [3,] 1e+04 0.1 0.2 0.3 0.4 # [4,] 1e+05 0.1 0.2 0.3 0.4 # [5,] 1e+06 0.1 0.2 0.3 0.4
[ "stats.stackexchange", "0000052527.txt" ]
Q: Unable to fit negative binomial regression in R (attempting to replicate published results) Attempting to replicate the results from the recently published article, Aghion, Philippe, John Van Reenen, and Luigi Zingales. 2013. "Innovation and Institutional Ownership." American Economic Review, 103(1): 277-304. (Data and stata code is available at http://www.aeaweb.org/aer/data/feb2013/20100973_data.zip). Am having no problem recreating the first 5 regressions in R (using OLS and poisson methods), but am simply unable to recreate their negative binomial regression results in R, while in stata the regression works fine. Specifically, here's the R code I've written, which fails to run a negative binomial regression on the data: library(foreign) library(MASS) data.AVRZ <- read.dta("results_data2011.dta", convert.underscore=TRUE) sicDummies <- grep("Isic4", names(data.AVRZ), value=TRUE) yearDummies <- grep("Iyear", names(data.AVRZ), value=TRUE) data.column.6 <- subset(data.AVRZ, select = c("cites", "instit.percown", "lk.l", "lsal", sicDummies, yearDummies)) data.column.6 <- na.omit(data.column.6) glm.nb(cites ~ ., data = data.column.6, link = log, control=glm.control(trace=10,maxit=100)) Running the above in R, I get the following output: Initial fit: Deviance = 1137144 Iterations - 1 Deviance = 775272.3 Iterations - 2 Deviance = 725150.7 Iterations - 3 Deviance = 722911.3 Iterations - 4 Deviance = 722883.9 Iterations - 5 Deviance = 722883.3 Iterations - 6 Deviance = 722883.3 Iterations - 7 theta.ml: iter 0 'theta = 0.000040' theta.ml: iter1 theta =7.99248e-05 Initial value for 'theta': 0.000080 Deviance = 24931694 Iterations - 1 Deviance = NaN Iterations - 2 Step halved: new deviance = 491946.5 Error in glm.fitter(x = X, y = Y, w = w, etastart = eta, offset = offset, : NA/NaN/Inf in 'x' In addition: Warning message: step size truncated due to divergence Have tried using a number of different initial values for theta, as well as varying the maximum number of iterations with no luck. The authors' supplied stata code works fine, but I still can't seem to coerce R into making the model work. Are there alternative fitting methods for glm.nb() that may be more robust to the problem I'm encountering? A: There is a lot of literature about the stable parameterization of nonlinear models. For some reason this seems to be largely ignored in R. In this case the "design matrix" for the linear predictor benefits from some work. Let $M$ be the design matrix and $p$ be the parameters of the model. The linear predictor for the means $\mu$ is given by $$\mu=\exp(Mp)$$ The reparameterization is accomplished by modified gram-Schmidt which produces a square matrix $\Sigma$ such that $$M=O\Sigma$$ where the columns of $O$ are orthonormal. (In fact some of the columns in this case are 0 so that the method must be modified slightly to deal with this.) Then $$Mp=O\Sigma p$$ Let the new parameters $q$ satisfy $$p=\Sigma q$$ So that the equation for the means becomes $$\mu=\exp(Oq)$$ This parametrization is much more stable and one can fit the model for $q$ and then solve for the $p$. I used this technique to fit the model with AD Model Builder, but it might work with R. In any event, having fit the model one should look at the "residuals" which are the squared difference between each observation and its mean divided by the estimate for the variance. As seems to be common for this type of model there are some huge residuals. I think these should be examined before the results of the paper are taken seriously.
[ "gaming.stackexchange", "0000166460.txt" ]
Q: How do I get a lot of Stunt Driver points? I've been driving around in Just Cause 2 like a maniac at full speed but I very rarely get any stunt driver points. I'll occasionally get one - or, rarely, two - when I drive into a sharp incline that makes my car jump into the air, but it doesn't seem to work consistently. Very often I won't get anything. In 20+ hours of play I've only got around 15 points, so getting the 'Stunt Driver' achievement seems a long way off. Are there specific types of stunt that are rewarded more? Do certain vehicles make it easier (fast ones, I guess)? Are there prime 'farming' spots? A: The way I did this is the way shown in this video: Essentially, go to the airport and steal the Titus ZJ sports car parked on the pedestal out in front. Drive at full speed around the circular road that is at the end of the entry road to the airport. The car is fast enough to earn Stunt Driver points easily, but the circular road's radius is great enough that you shouldn't have problems staying on the road at the car's full speed. It's a bit tedious, but it's a very fast way of getting this achievement. Another method I found: For this one, take the Titus into the airport, and attach it to one of the jets as it takes off. Get in the car, and the jet will pull you and the car along through the air. If you hold the accelerator even while the car is in mid-flight, you'll continue to earn Stunt Points. Going into the airport is likely to raise the ire of the military, though. Despite the risk, this seems like a more "fun" way to get this achievement.
[ "stackoverflow", "0058943496.txt" ]
Q: Angular lazy loading routing I have lazy load app routing like below: app.routing.ts { path: 'reports', loadChildren: () => import('../Reporting/reporting.module').then(m => m.ReportingModule) }, { path: 'report-builder', loadChildren: () => import('../Reporting/reporting.module').then(m => m.ReportingModule) }, My lazy load module routes look like this const routes: Routes = [ { path: '', children: [ { path: '', component: ReportsComponent }, { path: ':id',component: ViewReport}, { path: '**', component: ViewReport } ] }, { path: '', children: [ { path: '', component: ReportBuilderComponent }, { path: 'edit/:id', component: DesignReport }, { path: '**', component: DesignReport } ] } I am trying to achieve, when user clicks on reports route, navigate to default Reportscomponent and when clicked on reportBuilder route, navigate to ReportBuilderComponent. How to achieve this. A: Method 1 Create two modules one for reports and one for report-builder. app.report-routing.ts const routes: Routes = [ { path: '', children: [ { path: '', component: ReportsComponent }, { path: ':id',component: ViewReport}, { path: '**', component: ViewReport }] } ] Configure above routes in report.module app.report-builder-routing.ts const routes: Routes = [ { path: '', children: [ { path: '', component: ReportBuilderComponent }, { path: 'edit/:id', component: DesignReport }, { path: '**', component: DesignReport } ] } ] configure above routes in report-builder.module app.routing.js { path: 'reports', loadChildren: () => import('../Reporting/report.module').then(m => m.ReportingModule) }, { path: 'report-builder', loadChildren: () => import('../Reporting/report-builder.module').then(m => m.ReportBuilderModule) } Method 2 app.report-routing.ts const routes: Routes = [ { path: '', children: [ { path: '', component: ReportsComponent }, { path: ':id',component: ViewReport}, { path: '**', component: ViewReport } ] }, { path: 'builder', children: [ { path: '', component: ReportBuilderComponent }, { path: 'edit/:id', component: DesignReport }, { path: '**', component: DesignReport } ] } app.routing.ts { path: 'report', loadChildren: () => import('../Reporting/reporting.module').then(m => m.ReportingModule) } I hope this works for you. Reference Angular: Lazy loading feature modules
[ "stackoverflow", "0014824811.txt" ]
Q: rails records push Controller.rb @payments = PaymentDetail.joins(:project) in view file @payments.count is equal to 550 When I change my controller like this @payments = PaymentDetail.joins(:project) @payment_errors = PaymentError.joins(:project) @payment_errors.each {|payment_error| @payments << payment_error} Still in view file @payments.count is equal to 550 while it have to be (550+@payment_errors.count) Why I can't push @payment_error records into the @payments ? A: You are trying to add PaymentError data into PaymentDetail table which is wrong. If you need it in array use to_a. You can do like this: @payments = PaymentDetail.joins(:project).to_a + PaymentError.joins(:project).to_a To use will_paginate for arrays. Add this line in your controller: `require 'will_paginate/array'`
[ "chemistry.stackexchange", "0000002617.txt" ]
Q: Can silica gel beads cause silicosis if crushed? Can silica gel beads (which I believe are amorphous) when crushed to dust cause silicosis? A: No, it won't. Silica beads dust may cause irritation to the skin and eyes. Unlike silica crystalline, synthetic amorphous silica gel is indurated, and so does not cause silicosis.
[ "stackoverflow", "0027932356.txt" ]
Q: Using Selinium, Scrapy, Python to retrieve public facebook wall post of user profile I'm trying to retrieve my wallpost of a public profile. I need to check that a message is arriving to my wall and is being delivered within a given timestamp. I am essentially writing a monitoring check to validate message delivery of our messaging system. I'm getting a No Connection could be made because the target machine actively refused it. Not quite sure why? #!/usr/bin/env python # Many times when crawling we run into problems where content that is rendered on the page is generated with Javascript and therefore scrapy is unable to crawl for it (eg. ajax requests, jQuery craziness). However, if you use Scrapy along with the web testing framework Selenium then we are able to crawl anything displayed in a normal web browser. # # Some things to note: # You must have the Python version of Selenium RC installed for this to work, and you must have set up Selenium properly. Also this is just a template crawler. You could get much crazier and more advanced with things but I just wanted to show the basic idea. As the code stands now you will be doing two requests for any given url. One request is made by Scrapy and the other is made by Selenium. I am sure there are ways around this so that you could possibly just make Selenium do the one and only request but I did not bother to implement that and by doing two requests you get to crawl the page with Scrapy too. # # This is quite powerful because now you have the entire rendered DOM available for you to crawl and you can still use all the nice crawling features in Scrapy. This will make for slower crawling of course but depending on how much you need the rendered DOM it might be worth the wait. from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import HtmlXPathSelector from scrapy.http import Request import time from selenium import selenium class SeleniumSpider(CrawlSpider): name = "SeleniumSpider" start_urls = ["https://www.facebook.com/chronotrackmsgcheck"] rules = ( Rule(SgmlLinkExtractor(allow=('\.html', )), callback='parse_page',follow=True), ) def __init__(self): CrawlSpider.__init__(self) self.verificationErrors = [] self.selenium = selenium("localhost", 4444, "*chrome", "https://www.facebook.com/chronotrackmsgcheck") self.selenium.start() def __del__(self): self.selenium.stop() print self.verificationErrors CrawlSpider.__del__(self) def parse_page(self, response): item = Item() hxs = HtmlXPathSelector(response) #Do some XPath selection with Scrapy hxs.select('//div').extract() sel = self.selenium sel.open(response.url) #Wait for javscript to load in Selenium time.sleep(2.5) #Do some crawling of javascript created content with Selenium sel.get_text("//div") yield item SeleniumSpider() A: Here is the answer. This will parse the users profile using selenium and then parse only what is considered text on the page. You will have to do your own algorithm for data mining if you want to use it, but it works for my purposes. from selenium import webdriver from selenium.common.exceptions import TimeoutException from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys import Keys from bs4 import BeautifulSoup driver = webdriver.Firefox() driver.get("https://www.facebook.com/profileusername") inputEmail = driver.find_element_by_id("email") inputEmail.send_keys("facebookemail") inputPass = driver.find_element_by_id("pass") inputPass.send_keys("facebookpassword") inputPass.submit() page_text = (driver.page_source).encode('utf-8') soup = BeautifulSoup(page_text) parse_data = soup.get_text().encode('utf-8').split('Grant Zukel') #if you use your name extactly how it is displayed on facebook it will parse all post it sees, because your name is always in every post. latest_message = parse_data[3] driver.close() print latest_message This is how I'm getting the latest post by the user: #!/usr/bin/python # -*- coding: utf-8 -*- from selenium import webdriver from selenium.common.exceptions import TimeoutException from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys import Keys from bs4 import BeautifulSoup driver = webdriver.Firefox() driver.get("https://www.facebook.com/fbusername") inputEmail = driver.find_element_by_id("email") inputEmail.send_keys("fbemail") inputPass = driver.find_element_by_id("pass") inputPass.send_keys("fbpass") inputPass.submit() page_text = (driver.page_source).encode('utf-8') soup = BeautifulSoup(page_text) parse_data = soup.get_text().encode('utf-8').split('Grant Zukel') latest_message = parse_data[4] latest_message = parse_data[4].split('·') driver.close() time = latest_message[0] message = latest_message[1] print time,message
[ "stackoverflow", "0010840954.txt" ]
Q: Creating a new WebDriver causes StackOverflowError I'm just trying to get setup and have the ability to run the example from Selenium's website. However I've narrowed it down to the FirefoxDriver constructor causing a StackOverflowError. I get the same behavior with InternetExplorerDriver, but not HtmlUnitDriver. The following code import org.junit.Test; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class WebDriverTest { @Test public void test() { WebDriver driver = new FirefoxDriver(); } } Produces the following stacktrace: java.lang.StackOverflowError at java.lang.Exception.<init>(Unknown Source) at java.lang.reflect.InvocationTargetException.<init>(Unknown Source) at sun.reflect.GeneratedMethodAccessor2.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.json.JSONObject.populateMap(JSONObject.java:937) at org.json.JSONObject.<init>(JSONObject.java:272) at org.json.JSONObject.wrap(JSONObject.java:1539) at org.json.JSONObject.populateMap(JSONObject.java:939) at org.json.JSONObject.<init>(JSONObject.java:272) at org.json.JSONObject.wrap(JSONObject.java:1539) at org.json.JSONObject.populateMap(JSONObject.java:939) at org.json.JSONObject.<init>(JSONObject.java:272) at org.json.JSONObject.wrap(JSONObject.java:1539) at org.json.JSONObject.populateMap(JSONObject.java:939) at org.json.JSONObject.<init>(JSONObject.java:272) at org.json.JSONObject.wrap(JSONObject.java:1539) at org.json.JSONObject.populateMap(JSONObject.java:939) at org.json.JSONObject.<init>(JSONObject.java:272) at org.json.JSONObject.wrap(JSONObject.java:1539) at org.json.JSONObject.populateMap(JSONObject.java:939) at org.json.JSONObject.<init>(JSONObject.java:272) : : I'm using selenium-java-2.22.0 and the json jar that was packaged with the download (which is json-20080701.jar) Also of note, when running the new FirefoxDriver, Firefox does launch and you see a new tab page. With InternetExplorerDriver, no window opens, but it produces the same stacktrace with JSONObject looping infinitely. I'm running Firefox 12.0 and IE9 on Windows 7. A: Welcome to JAR hell Some of the JAR files in your classpath are conflicting with Selenium dependencies. It is kinda strange that it happened even though you are using Ivy. One of your dependencies most likely includes the conflicting classes inside its jar file - or your dependencies need two different versions of the same library. Anyway, for future user reading this - use some dependency manager to do the hard work with jars for you. Don't try to maintain your libraries manually if you have more that 10 projects with dependencies - you'll most likely screw it up soon. This is quite a reasonable read on dependency solutions, follow some of the links there, don't be lazy. Dependency managers take some time to master, they are a world for themselves. But they help a lot. Don't use multiple versions of the same library. And if you use multiple libraries from which two use a different version of the same thing ... good luck to you! Other than that ... our only hope is Java Module System which will be introduced in Java 8 Java 9.
[ "unix.stackexchange", "0000346087.txt" ]
Q: How to output process stats after completion? I would like to run a process from bash in Cygwin so that I have some short summary after execution like peak memory usage or average CPU usage, like time but with more information. Are there any options? A: You can do this by running the command inside GNU time. By default, time shows you the real (wall clock), user (CPU-seconds used in user mode), and sys (CPU-seconds used in kernel mode) data items. However, you can also ask it to measure other things, such as RAM and disk usage: /usr/bin/time -f "File system outputs: %O\nMaximum RSS size: %M\nCPU percentage used: %P" <command> where <command> is replaced by the command you wish to run. The output will be something like: File system outputs: 18992 Maximum RSS size: 40056 CPU percentage used: 367% where "CPU percentage used" is a percentage and shows here that 3.6 cores were used, "Maximum RSS size" is as close as it gets to "maximum memory used" and is expressed in kilobytes, and "File system outputs" is expressed in number of operations (i.e., it does not say how much data is written). The du and df commands you gave should help there. Note: you need to use /usr/bin/time rather than just time, as many shells have that as a builtin, which doesn't necessarily support the -f option. For more information, see man time https://unix.stackexchange.com/a/331707/213127 Same goes for Cygwin: there is a bash built-in which can be substituted by GNU time.
[ "stackoverflow", "0006243252.txt" ]
Q: Problem converting nvarchar to decimal t-sql I'm trying to convert nvarchar to decimal (18,2) and I'm receiving the following message: Msg 8115, Level 16, State 6, Line 2 Arithmetic overflow error converting nvarchar to data type numeric. The CAST is: CAST(bm_onnet AS decimal(18,2)) as bm_onnet_corr, it works only if the value has only maximum 3 decimals, doesn't work for value below: 21.8333333333333333333333333333333333333 How should I modify my SELECT? A: Use the round function example declare @v nvarchar(100) = '21.8333333333333333333333333333333333333' select convert(decimal(18,2),round(@v,2)) a select would look like this SELECT CAST(round(bm_onnet,2) AS decimal(18,2)) as bm_onnet_corr
[ "stackoverflow", "0047473663.txt" ]
Q: Extended JPanel ruins GridLayout I am wanting to modify my JPanel like this: public class Square extends JPanel { private Checker fromChecker; private int x; private int y; Square(int x, int y){ this.x = x; this.y = y; } public int getX(){ return this.x; } public int getY(){ return this.y; } void setPossibleMoveChecker(Checker fromChecker){ this.fromChecker = fromChecker; } Checker getPossibleMoveChecker(){ return this.fromChecker; } } and I call Square here: JPanel panel = new JPanel(); panel.setLayout(new GridLayout(Game.grid_size, Game.grid_size)); for(int x=1; x <= Game.grid_size; x ++){ for(int y=1; y <= Game.grid_size; y ++) { Square square = new Square(x, y); // grid colour Color square_color = Game.grid1_colour; if((x + y) % 2 == 0){ square_color = Game.grid2_colour; } square.setBackground(square_color); square.addMouseListener(new Mouse()); panel.add(square); } } Unfortunately this comes out like: Where as if I change the line: Square square = new Square(x, y); to JPanel square = new JPanel(); it comes out perfectly like: A: You're overriding two key JComponent methods, getX() and getY(), and this is messing with the placement of components since this is one of the key behaviors the layout managers use for component placement. Solution: Re-name those methods! public class Square extends JPanel { private Checker fromChecker; private int column; private int row; Square(int column, int row){ this.column = column; this.row = row; } public int getColumn(){ return this.column; } public int getRow(){ return this.row; } // .... Yet another reason to favor composition over inheritance, especially when dealing with complex classes that have many potentially overrideable methods.
[ "stackoverflow", "0010261672.txt" ]
Q: Why must a char array end with a null character? Why does a char array have to end with a null character? Is there any reason that I have to add the null character to to every char array ? It seems that they get treated the same way. A: A char array doesn't have to be null terminated (standard library functions which don't depend on this include memcpy, memmove, strncpy -- badly named this latest one --, printf with the right format string). A NUL Terminated Character String (NTCS) needs by definition to be terminated by a NUL. It is the format expected by string handling utilities of the C standard library and the convention used by most C program (in C++, one usually use std::string) A: In C, if you have a pointer to an array, then there is not way to determine the length of that array. As @AProgrammer points out, the designers could have left it at that and forced the programmer to keep track of the length of all character arrays. However, that would have made text processing in C even harder than it already is. Therefore the language designers settled on a convention that would allow string length to be inferred by the presence of a null character indicating the end of the string. For example, consider strcpy: char *strcpy(char *destination, const char *source); There is no way in C to determine the length of the array that the pointers destination and source point to. So, without the presence of a sentinel value to indicate the end of the string, the only other solution would have been to pass extra parameters indicating the length of the source string. Of course, in light of modern security considerations, string processing functions that receive buffer length parameters have been introduced. But the computing landscape looked very different at the time that the null-terminated string was invented.
[ "stackoverflow", "0033992088.txt" ]
Q: change button color based on condition ionic Just I need to add two different color button but the button need to show color based on the web-service response if status= "open" green button if status= "closed red button <a class="button icon button-block button-calm icon-right ion-android-arrow-dropright-circle" href="#" ng-repeat= "file in file">File Ref No:{{file.num}}<br> Description:{{file.descript}}<br> Status:{{file.status}}</a><br> A: Please try this, function MyCtrl($scope) { $scope.file = [{ num: '1', descript: 'File Description 1', status: 'closed' }, { num: '2', descript: 'File Description 2', status: 'open' }] } <link href="http://code.ionicframework.com/nightly/css/ionic.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app ng-controller="MyCtrl"> <a class="button icon button-block button-calm icon-right ion-android-arrow-dropright-circle" ng-class="{'button-balanced': f.status == 'open', 'button-assertive': f.status == 'closed'}" href="#" ng-repeat="f in file" >File Ref No:{{f.num}}<br> Description:{{f.descript}}<br> Status:{{f.status}}</a> <br> </div>
[ "ru.stackoverflow", "0000424443.txt" ]
Q: Как скачать файл из ресурсов в Visual Basic? В ресурсах проекта есть zip архив. Надо при нажатии на кнопку, чтобы этот файл скачался на рабочий стол. В каком направлении двигаться? A: Если zip архив отмечен как embedded resource, то примерно так: Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) Dim targetPath = IO.Path.Combine(desktopPath, "TextFile.zip") ' "WindowsApplication1.TextFile1.zip" нужно заменить на настоящее имя ресурса ' в формате "<default namespace>.<папка>.<файл>" Using resourceStream = Me.GetType().Assembly.GetManifestResourceStream("WindowsApplication1.TextFile1.zip") Using fileStream = IO.File.OpenWrite(targetPath) resourceStream.CopyTo(fileStream) End Using End Using End Sub
[ "stackoverflow", "0003647454.txt" ]
Q: Increment counter or insert row in one statement, in SQLite In SQLite, given this database schema CREATE TABLE observations ( src TEXT, dest TEXT, verb TEXT, occurrences INTEGER ); CREATE UNIQUE INDEX observations_index ON observations (src, dest, verb); whenever a new observation tuple (:src, :dest, :verb) comes in, I want to either increment the "occurrences" column for the existing row for that tuple, or add a new row with occurrences=1 if there isn't already one. In concrete pseudocode: if (SELECT COUNT(*) FROM observations WHERE src == :src AND dest == :dest AND verb == :verb) == 1: UPDATE observations SET occurrences = occurrences + 1 WHERE src == :src AND dest == :dest AND verb == :verb else: INSERT INTO observations VALUES (:src, :dest, :verb, 1) I'm wondering if it's possible to do this entire operation in one SQLite statement. That would simplify the application logic (which is required to be fully asynchronous wrt database operations) and also avoid a double index lookup with exactly the same key. INSERT OR REPLACE doesn't appear to be what I want, and alas there is no UPDATE OR INSERT. A: I got this answer from Igor Tandetnik on sqlite-users: INSERT OR REPLACE INTO observations VALUES (:src, :dest, :verb, COALESCE( (SELECT occurrences FROM observations WHERE src=:src AND dest=:dest AND verb=:verb), 0) + 1); It's slightly but consistently faster than dan04's approach. A: Don't know of a way to do it in one statement, but you could try BEGIN; INSERT OR IGNORE INTO observations VALUES (:src, :dest, :verb, 0); UPDATE observeraions SET occurrences = occurrences + 1 WHERE src = :src AND dest = :dest AND verb = :verb; COMMIT;
[ "stackoverflow", "0014056165.txt" ]
Q: How do I get all the elements of data.d I have a server method that returns a collection of instances of my custom class. I know that to access those objects in AJAX success callback function I can say data.d. And to access the first object I'd write data.d[0]. But how do I get all the elements of data.d? I won't to iterate through all the objects. A: Well, you know data.d is an array.. In your success callback simply iterate through the items in the array: success: function (data) { for (var i = 0; i < data.d.length; i++) { console.log(data.d[i]); } } If you're using jQuery you can also use $.each(). It takes a callback with two parameters - the index into the collection and the value at that index: success: function (data) { $.each(data.d, function (i, v) { console.log(i, v); }); }
[ "stackoverflow", "0000244179.txt" ]
Q: Are there open source CAPTCHA solutions available? I'm in the process of adding CAPTCHA validation to one of my websites and need to know what open source solutions exist. Please note strengths and weaknesses and what platform they work with. I'm primarily interested in ASP.NET solutions but feel free to include PHP, Java, etc. A: ReCAPTCHA is the same one StackOverflow uses. It has an ASP.NET implementation. It uses a webservice to provide the captcha images; this is an university trying to digitize difficult to OCR texts. I'm not sure how easy it would be to replace this portion. There are many open source client implementations, as the API is quite well documented.
[ "stackoverflow", "0015964988.txt" ]
Q: Filtering records by user email in App Engine Datastore? I have an app hosted on app engine. It has some fields along with the UserProperty() as shown below: class Post(db.Model): title = db.StringProperty(required=True) created_by = db.UserProperty(required=True) ...#some other fields I am trying to filter records by created_by field, so that app will display records created by logged in user. I tried: p = Post.all() p.filter('created_by =', users.get_current_user()) Which is not working. Please help. A: If you don't have a separated model for your logged in users you should store in the post also the user_id and not the email, since the former is more unique. Just add one more field in the Post class Post(db.Model): title = db.StringProperty(required=True) created_by = db.UserProperty(required=True) user_id = db.StringProperty(required=True) ... And on Post creation do something like this: post_db = Post(title='Hello world', created_by=users.get_current_user(), user_id=users.get_current_user().user_id()) Now if you want to show all the posts that was made by the logged in user you should: p = Post.all() p.filter('user_id =', users.get_current_user().user_id())
[ "stackoverflow", "0016407868.txt" ]
Q: Header redirect error with head part of site Im having a problem with header to redirect. When I try to redirect, it says this... Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at .../head.php:7) in .../init.php on line 3 head.php is as follows: <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>grand exchange</title> <link href="style.css" rel="stylesheet" type="text/css" /> <link href="activate.css" rel="stylesheet" type="text/css" /> </head> init.php is as follows: <?php ob_start(); session_start(); //error_reporting(0); require 'core/database/connect.php'; require 'core/functions/general.php'; require 'core/functions/users.php'; if(logged_in() === true){ //bans users $session_user_id = $_SESSION['id']; $user_data = user_data($session_user_id, 'id','username', 'password','first_name', 'last_name', 'email', 'areacode'); if(user_active($user_data['username']) === false) { session_destroy(); header('Location: index.php'); exit(); } } $errors = array(); ob_flush(); ?> I added an ob_start and ob_flush to init.php because ive seen many of the same problems solved with that. Do you guys have an ideas for me? Thanks so much! A: ob_start needs to be done before you start any output at all (i.e. before head.php is even called, or at the start of head.php). Ideally you would design your application to build all of the HTML first and emit it at the end.
[ "stackoverflow", "0032732954.txt" ]
Q: How to escape equal sign for HTTP request? In PowerShell I want to call something like this: Invoke-WebRequest -Uri "http://localhost:3000/test" -Method POST -Body "a=" Note the body contains an equal sign (=), but in the server side (I'm using node.js+express.js), if I call request.body, it appears to be {a:""}, while what I want is {"a=":""}. If I call something like this: Invoke-WebRequest -Uri "http://localhost:3000/test" -Method POST -Body "`"a=`"" request.body is "a: """, i.e. a broken JSON string! A: I got the solution: Invoke-WebRequest -Uri "http://localhost:3000/test" -Method POST -Body "`"a%3D`""
[ "cs.stackexchange", "0000053521.txt" ]
Q: what is difference between multilayer perceptron and multilayer neural network? When do we say that a artificial neural network is a multilayer Perceptron? And when do we say that a artificial neural network is a multilayer? Is the term perceptron related to learning rule to update the weights? Or It is related to neuron units? A: A perceptron is always feedforward, that is, all the arrows are going in the direction of the output. Neural networks in general might have loops, and if so, are often called recurrent networks. A recurrent network is much harder to train than a feedforward network. In addition, it is assumed that in a perceptron, all the arrows are going from layer $i$ to layer $i+1$, and it is also usual (to start with having) that all the arcs from layer $i$ to $i+1$ are present. Finally, having multiple layers means more than two layers, that is, you have hidden layers. A perceptron is a network with two layers, one input and one output. A multilayered network means that you have at least one hidden layer (we call all the layers between the input and output layers hidden).
[ "mathematica.stackexchange", "0000115407.txt" ]
Q: How to convert arbitrary raw boxes directly into String? This question is motivated by the recent question about searching inside of the NB files. According to the Documentation, ToString expects a high-level WL expression as the first argument: expr = Row[{Style["Format", Bold], "ted", " string"}] ToString[expr] Formatted string Formatted string Unlike Rasterize it does not interpret raw boxes as an expression in the low-level box language: cell = Cell[BoxData@ToBoxes@expr, "Output"]; Rasterize[cell] ToString[cell] Cell[BoxData[TemplateBox[{StyleBox["Format", Bold, StripOnInput -> False], "ted", " string"}, RowDefault]], Output] Unfortunately MakeExpression isn't always able to convert a valid raw boxes into the corresponding high-level expression (although in the above simple case it can). Also conversion from raw boxes into high-level expression breaks the original formatting (for example, it does not preserve the infix, prefix and postfix notations, and the author's line breaks etc.) and should best be avoided. Is it possible to convert arbitrary raw boxes directly into the corresponding String without resorting to MakeExpression? I'm especially interested in converting raw Cells into pure strings for the purposes of textual searching inside of NB files. A: As Kuba notices in the comment, undocumented FrontEnd`ExportPacket allows conversion of a whole Notebook into plain text: nb = NotebookGet@EvaluationNotebook[]; First[FrontEndExecute[FrontEnd`ExportPacket[nb, "PlainText"]]] "nb=NotebookGet@EvaluationNotebook[]; First[FrontEndExecute[FrontEnd`ExportPacket[nb,\"PlainText\"]]]" But it isn't the whole story. Surprisingly FrontEnd evaluates and updates the Dynamic objects in the Notebook sent as the first argument of FrontEnd`ExportPacket! With Mathematica 10.4.1 when trying to convert to plain text the "Views.nb" Documentation Notebook (warning: evaluation of the following code can make Mathematica not responding for several minutes!) nbWithDynamic = Get@FileNameJoin[{$InstallationDirectory, "Documentation", "English", "System", "Tutorials", "Views.nb"}]; First[FrontEndExecute[FrontEnd`ExportPacket[nbWithDynamic, "PlainText"]]]; I observe that Kernel downloads a lot of data from the Wolfram paclet server obviously in order to update the Dynamic expressions in this Notebook (the most of the data should be due to the second example under the "SlideView" section which downloads shapes for all countries available via CountryData[]). This behavior is especially strange because no Dynamic objects from that Notebook are displayed on the screen (according to the Documentation, Dynamic is updated only when displayed on the screen). So this is a bug and serious security violation. (UPDATE: As explained by John Fultz, exporting in some fundamental sense is equivalent to displaying and this behavior is by design.) To prevent this one should set the DynamicUpdating -> False option for a Notebook before sending it to the FrontEnd: nb = NotebookGet@EvaluationNotebook[]; nbDynamicOff = Insert[nb, DynamicUpdating -> False, 2]; First[FrontEndExecute[FrontEnd`ExportPacket[nbDynamicOff, "PlainText"]]] "nb=NotebookGet@EvaluationNotebook[]; nbDynamicOff=Insert[nb,DynamicUpdating->False,2]; First[FrontEndExecute[FrontEnd`ExportPacket[nbDynamicOff,\"PlainText\"]]]" Disabling the DynamicUpdating also solves the problem with FrontEnd`ExportPacket sometimes returning just Null (but at the second attempt on the same file it returns the expected result). Of course it also speeds up the conversion several times and solves the problem with the Dynamic updating timeout dialog appearing during the conversion (what stops the process of computation until you press the "Continue waiting" button).
[ "superuser", "0001538539.txt" ]
Q: Searches in Chrome Omnibox randomly use Yahoo instead of Google My search engine is set to Google and has been for years. I do dozens of searches from the omnibox a day (IT Manager). About a week ago, I noticed that occasionally I would get a Yahoo search result page. It probably happens once or twice a day. If I immediately do the search again, I get the expected Google results. Does anyone have ANY idea what would be causing this? My only thought would be an extension. I've disabled the only one I installed recently, but is there any way to confirm or troubleshoot this issue? Edit: This is happening on two PCs. Must be an extension. A: I tracked this problem down to the Chrome extension "Ratings Preview for YouTube" (extension has been removed from the Chrome and Firefox add-ons store), as I was having the same problem and it was driving me nuts. I used the LinkResearchTools extension on Chrome to log redirects and found my Google redirects were going to: https://searchingcafe.com/?a=gsp_dventures_00_00&q={original query} Which then were redirected to: https://search.yahoo.com/yhs/search?hspart=dcola&hsimp=yhs-001&type=gsp_dventures_00_00&param1=1&param2=cat%3Dweb%26sesid%3D3147d16554fc40d80a8319989e89c2b7%26ip%3D98.206.52.10%26b%3DChrome%26bv%3D80.0.3987.149%26os%3DWindows-10%26os_ver%3D10.0%26pa%3Dgencoll12%26sid%3Dd5630a969f5ff68effba73db31a6971d%26abid%3D%26abg%3D%26a%3Dgsp_dventures_00_00%26sdk_ver%3D%26cd%3D%26cr%3D%26f%3D%26uref%3D&p={original query} I was able to use this to find a recent Reddit post describing how "Ratings Preview for YouTube" had started doing these redirects for other people in Firefox; I was using this extension on Chrome so I disabled it, haven't had the problem since, and am now using the extension Thumbnail Ratings Bar for YouTube.
[ "stackoverflow", "0057119981.txt" ]
Q: IE 11 "Expected :" using React Babel 7 Typescript I have followed recommended React/ Babel configurations, however I cannot get my site to load in IE 11. The error which persists: These are my related files: .babelrc { "presets": [ [ "@babel/preset-env", { "targets": { "browsers": [ "last 2 versions" ] }, "modules": "commonjs", "useBuiltIns" : "entry" } ], [ "@babel/preset-react" ] ], "plugins": [ "@babel/plugin-transform-runtime", [ "import", { "libraryName": "antd", "style": false } ], "@babel/syntax-dynamic-import", "react-hot-loader/babel" ] } index.tsx import 'react-app-polyfill/ie11'; import 'react-app-polyfill/stable'; ... tsconfig.json { "compilerOptions": { "outDir": "build/dist", "target": "es2015", "lib": [ "es6", "dom" ], "esModuleInterop": true, "module": "esnext", "sourceMap": true, "allowJs": true, "jsx": "react", "downlevelIteration": true, "alwaysStrict": true, "moduleResolution": "node", "resolveJsonModule": true, "rootDir": "src", "forceConsistentCasingInFileNames": true, "noImplicitReturns": true, "noImplicitThis": true, "noImplicitAny": true, "strictNullChecks": true, "suppressImplicitAnyIndexErrors": true, "noUnusedLocals": true, "allowSyntheticDefaultImports": true, "skipLibCheck": true, // Similar to webpack's resolve.alias for the tsc compilation stage "baseUrl": ".", "paths": { "~/*": ["./src/*"] } }, "include": [ "./src/**/*", "./typings/**/*.d.ts" ], "exclude": [ "./node_modules", "./dist" ] } package.json { ... "dependencies": { "antd": "^3.6.6", "apollo-boost": "^0.1.16", "apollo-cache-persist": "^0.1.1", "bootstrap": "^4.0.0", "bootstrap-daterangepicker": "^3.0.3", "classnames": "^2.2.5", "core-js": "^3.1.4", "cucumber": "^5.1.0", "debug": "^3.1.0", "file-saver": "^2.0.1", "graphql": "^0.11.0", "history": "^4.6.3", "jquery": "^3.3.1", "moment": "^2.22.2", "moment-timezone": "^0.5.21", "prop-types": "^15.7.2", "react": "^16.4.1", "react-adopt": "^0.6.0", "react-apollo": "^2.2.4", "react-app-polyfill": "^1.0.1", "react-bootstrap-daterangepicker": "^4.1.0", "react-data-export": "^0.5.0", "react-day-picker": "^7.3.0", "react-dom": "^16.4.1", "react-hot-loader": "^4.3.4", "react-infinite": "^0.13.0", "react-markdown": "^3.3.4", "react-moment": "^0.7.9", "react-redux": "^5.0.7", "react-resize-detector": "^3.0.1", "react-router": "^4.3.1", "react-router-dom": "^4.3.1", "react-router-redux": "next", "react-select": "^1.2.1", "react-switch": "^3.0.4", "react-toggle": "^4.0.2", "react-virtualized-select": "^3.1.3", "reactstrap": "^5.0.0-beta.3", "redux": "^3.7.2", "redux-observable": "^0.19.0", "reselect": "^3.0.1", "rxjs": "^5.5.10", "ts-loader": "^6.0.4", "typescript-fsa": "^2.5.0", "typescript-fsa-reducers": "^0.4.4", "uuid": "^3.2.1", "xlsx": "^0.14.2" }, "devDependencies": { "@babel/core": "^7.4.4", "@babel/plugin-syntax-dynamic-import": "^7.2.0", "@babel/plugin-transform-runtime": "^7.4.4", "@babel/preset-env": "^7.4.4", "@babel/preset-react": "^7.0.0", "@babel/register": "^7.4.4", "@babel/runtime": "^7.4.4", "@types/classnames": "^2.2.3", "@types/debug": "^0.0.30", "@types/geojson": "^7946.0.4", "@types/jest": "^22.2.3", "@types/lodash": "^4.14.106", "@types/moment-timezone": "^0.5.6", "@types/node": "^10.5.2", "@types/rc-slider": "^8.2.3", "@types/react": "^16.4.6", "@types/react-bootstrap-daterangepicker": "^0.0.26", "@types/react-csv": "^1.1.1", "@types/react-dom": "^16.0.6", "@types/react-redux": "^6.0.4", "@types/react-resize-detector": "^2.2.0", "@types/react-router-dom": "^4.2.7", "@types/react-router-redux": "5.0.15", "@types/react-select": "^1.2.9", "@types/react-toggle": "^4.0.1", "@types/react-virtualized-select": "^3.0.5", "@types/reactstrap": "^5.0.20", "@types/uuid": "^3.4.3", "@types/webpack-env": "^1.13.0", "apollo": "^1.7.1", "app-root-path": "^2.0.1", "autoprefixer": "9.0.1", "babel-loader": "^8.0.6", "babel-plugin-import": "^1.11.2", "babel-plugin-transform-eval": "^6.22.0", "babel-preset-env": "^1.7.0", "case-sensitive-paths-webpack-plugin": "2.0.0", "chalk": "1.1.3", "cli-highlight": "1.1.4", "connect-history-api-fallback": "^1.5.0", "copy-webpack-plugin": "^4.5.2", "css-loader": "0.28.1", "dotenv": "6.0.0", "file-loader": "^1.1.11", "fork-ts-checker-notifier-webpack-plugin": "^0.4.0", "fork-ts-checker-webpack-plugin": "^0.4.3", "fs-extra": "3.0.1", "html-webpack-plugin": "3.2.0", "jest": "22.4.3", "koa-connect": "^2.0.1", "less": "^3.8.0", "less-loader": "^4.1.0", "mini-css-extract-plugin": "^0.4.1", "object-assign": "4.1.1", "postcss-flexbugs-fixes": "4.0.0", "postcss-loader": "2.1.6", "promise": "7.1.1", "rimraf": "^2.6.2", "source-map-loader": "^0.2.3", "style-loader": "0.17.0", "sw-precache-webpack-plugin": "0.11.5", "tslint": "^5.11.0", "tslint-loader": "^3.6.0", "tslint-react": "^3.2.0", "typescript": "^3.4.1", "typings-for-css-modules-loader": "^1.7.0", "url-loader": "^1.0.1", "webpack": "^4.16.3", "webpack-cli": "^3.1.0", "webpack-dev-server": "^3.1.5", "webpack-manifest-plugin": "2.0.3", "webpack-merge": "^4.1.3", "webpack-serve": "^2.0.2", "whatwg-fetch": "2.0.4" }, "scripts": { "start": "webpack-dev-server --config webpack.dev.config.js --content-base /advanced --port 3000" } } A: Seems like the babel config wasn't being read (still unsure why). I resorted to using babel.config.js, which fixed the issue. My final file: babel.config.js: module.exports = function (api) { api.cache(true); const presets = [ [ "@babel/preset-env", { "targets": { "browsers": [ "last 2 versions", "ie 11" ] }, "modules": "commonjs", "useBuiltIns" : "usage" } ], [ "@babel/preset-react" ] ]; const plugins = [ [ "import", { "libraryName": "antd", "style": false } ], "@babel/syntax-dynamic-import", "react-hot-loader/babel" ]; return { presets, plugins }; } Also followed the guide here regarding Pollyfills: https://github.com/facebook/create-react-app/releases?after=v2.0.5 (added correct imports to index.tsx)
[ "stackoverflow", "0046805851.txt" ]
Q: Create multiple dataframe in loops I have a population data. I want to create separate dataframes for each state and year. The idea is the following: for i in province_id: for j in year: sub_data_i_j = data[(data.provid==i) &(data.wave==j)] However, I am not sure how to generate sub_data_i_j dynamically. A: This should do it: for i in province_id: for j in year: locals()['sub_data_{}_{}'.format(i,j)] = data[(data.provid==i) & (data.wave==j)] I initially suggested using exec, which is not usually considered best practice for safety reasons. Having said so, if your code is not exposed to anyone with malicious intentions, it should be OK, and I'll leave it here for the sake of completeness: for i in province_id: for j in year: exec "sub_data_{}_{} = data[(data.provid==i) & (data.wave==j)]".format(i,j) Nevertheless, for most use cases, it's probably better to use a collection of some sort, e.g. a dictionary, because it will be cumbersome to reference dynamically generated variable names in subsequent parts of your code. It's also a one-liner: data_dict = {key:g for key,g in data.groupby(['provid','wave'])}
[ "stackoverflow", "0063585588.txt" ]
Q: Azure Functions triggered by servicebus complains about connection string 'AzureWebJobsServiceBus' is missing or empty I have a .netcore Azure Functions project working well in Visual Studio 2019 when I have a valid AzureWebJobsServiceBus in local.settings.json, but would not compile if that's missing or empty. I am using AD to authenticate my function to service bus, not through connection string. AzureWebJobsServiceBus is not used anywhere in my project. Here's my project.cs I use Azure.Identity package and follow this post to use my credential to log in to Azure, and here's my function that's working: [FunctionName("ProcessNewMessage")] public async Task ProcessPaymentMessage([ServiceBusTrigger("topic", "subscription")] Message message, ILogger log) { var tokenProvider = TokenProvider.CreateManagedIdentityTokenProvider(); QueueClient queueClient = new QueueClient($"sb://{Environment.GetEnvironmentVariable("ServiceBusEndPoint")}", Environment.GetEnvironmentVariable("GenericAuditQueueName"), tokenProvider); await queueClient.SendAsync(message); } Before using AD to authenticate, I was using connection string and that's working too, but it's recommended to use AD. To summarize, my Azure Function works with Service bus trigger when connection string is provided but not used by my code. How can I make my function work with AD without connection string? Thanks a lot A: You cannot remove Service Bus connection string from Azure function app Service bus trigger as internal SDKs use it to make connection. Saving your connection string of Service bus in Function App using key Vault: The Key Vault references feature makes it so that your app can work as if it were using App Settings as they have been, meaning no code changes are required. You can get all of the details from our Key Vault reference documentation, but I’ll outline the basics here. This feature requires a system-assigned managed identity for your app. Later in this post I’ll be talking about user-assigned identities, but we’re keeping these previews separate for now. You’ll then need to configure an access policy on your Key Vault which gives your application the GET permission for secrets. Learn how to configure an access policy. Lastly, set the value of any application setting to a reference of the following format: @Microsoft.KeyVault(SecretUri=secret_uri_with_version) Where secret_uri_with_version is the full URI for a secret in Key Vault. For example, this would be something like: https://myvault.vault.azure.net/secrets/azurewebjobsservicebussecret/ec96f02080254f109c51a1f14cdb1931 You can use MSI for Azure Function App and Service Bus: MSI for Function App: https://docs.microsoft.com/en-us/azure/app-service/overview-managed-identity?tabs=dotnet#add-a-system-assigned-identity MSI for Service bus: https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-managed-service-identity#use-service-bus-with-managed-identities-for-azure-resources
[ "stackoverflow", "0018166072.txt" ]
Q: How to UUEncode in android Using which libraries, I can UUENcode some binary in Android java? I just couldn't find any UUEncoder api available in java for android. Does anybody know such an api? A: The only libraries that I'm aware of for UUEncoding are Oracle's, which ships with Java SDK (and is not replicated in the Android SDK), and the one in Ant. I'm guessing that you're not going to want to include the Ant library in your Android application. I did find source for Sun/Oracle's UUEncoder at http://www.docjar.com/html/api/sun/misc/UUEncoder.java.html It's GPL2 licensed, so if you feel that your software can meet the demands of that license, you could just copy the source for that one class into your application. Failing that, you could implement the algorithm yourself. See, for example, http://www.herongyang.com/encoding/UUEncode-Algorithm.html
[ "stackoverflow", "0024622303.txt" ]
Q: Can you call an Action Extension from the IOS 8 Mail App It is clear that the new IOS 8 action extensions have to be initiated by a user and from a system provided UI. My question is, will the IOS 8 Mail app have a system provided UI so that an action extension can be called when a user is reading an email or writing an email? A: Currently, no. I did file a feature request for this, many opportunities for action extensions in Mail! I would suggest that you do the same to possibly get some priority behind this.
[ "stackoverflow", "0025876673.txt" ]
Q: Navigation using Assemble Part I I created a 'static' navigation in my handlebar file for the header (header.hbs - below). I'd like to create this simple, one-level navigation using handlebars (which I'm new too currently). Also would like to add an "active" class based on the page the user is on. <nav class="left"> <ul> <li><a href="index.html" title="Home">Home</a></li> <li><a href="products.html" title="Products">Products</a></li> <li><a href="find-us.html" title="Find Us">Find Us</a></li> </ul> </nav> Part II I was able to get this working (see answer below). How does one achieve sort-order? Right now the links seem to be in random order. A: I should have RTFM :) There's a whole section in the FAQ for this exact thing, ha! Go figure. {{#each pages }} {{#is data.section "main"}} <li{{#is ../../page.dest this.dest}} class="active"{{/is}}> <a href="{{relative ../../page.dest this.dest}}">{{data.menutitle}}</a> </li> {{/is}} {{/each}} http://assemble.io/docs/FAQ.html
[ "stackoverflow", "0016464222.txt" ]
Q: Caught VariableDoesNotExist while rendering: Failed lookup for key [time_filter] in u'[{}, views.py def when(request): user = request.user report = Report.objects.get(user=request.user) reportform = ReportForm(instance=report) settings = Settings.objects.get(user=request.user) settingsForm = SettingsForm(instance=settings) settings=Settings.objects.get(user=2) if settings.date_format == '0': date_filter = 'd/m/Y' else: date_filter = 'm/d/Y' if settings.time_format == '0': time_filter = 'I:Mp' else: time_filter = 'H:M' if request.method == 'POST': reportform = ReportForm(instance=report,data=request.POST) if reportform.is_valid(): report = reportform.save(commit=False) report.user = request.user report.save() return redirect('/member/media/') return render_to_response('incident/when.html',{ 'newreport_menu': True, 'form': reportform, }, context_instance=RequestContext(request)) template is {{ form.manual_time|date:time_filter }} {{ form.manual_date|date:date_filter }} Giving error in date_filter and time_filter in template,the error is "Caught VariableDoesNotExist while rendering: Failed lookup for key [time_filter] in u'[{}," A: You haven't included time_filter or date_filter in the context dictionary you pass to render_to_response.
[ "stackoverflow", "0037547399.txt" ]
Q: How to deserialise a subclass in Firebase using getValue(Subclass.class) I'm using the new firebase sdk for android and use the real database feature. When i use the getValue(simple.class) everything is fine. But when i want to parse a class which is a subclass, all the attribute of the mother class are null, and i have this type of error: No setter/field for name found on class uk.edume.edumeapp.TestChild public class TestChild extends TestMother { private String childAttribute; public String getChildAttribute() { return childAttribute; } } public class TestMother { protected String motherAttribute; protected String getMotherAttribute() { return motherAttribute; } } this function snapshot.getValue(TestChild.class); motherAttribute attribute is null, and I get No setter/field for motherAttribute found on class uk.edume.edumeapp.TestChild the Json that i parse is: { "childAttribute" : "attribute in child class", "motherAttribute" : "attribute in mother class" } A: Firebaser here This is a known bug in some versions of the Firebase Database SDK for Android: our serializer/deserializer only considers properties/fields on the declared class. Serialization of inherited properties from the base class, is missing in the in releases 9.0 to 9.6 (iirc) of the Firebase Database SDK for Android. It was added back in versions since then. Workaround In the meantime you can use Jackson (which the Firebase 2.x SDKs used under the hood) to make the inheritance model work. Update: here's a snippet of how you can read from JSON into your TestChild: public class TestParent { protected String parentAttribute; public String getParentAttribute() { return parentAttribute; } } public class TestChild extends TestParent { private String childAttribute; public String getChildAttribute() { return childAttribute; } } You'll note that I made getParentAttribute() public, because only public fields/getters are considered. With that change, this JSON: { "childAttribute" : "child", "parentAttribute" : "parent" } Becomes readable with: ObjectMapper mapper = new ObjectMapper(); GenericTypeIndicator<Map<String,Object>> indicator = new GenericTypeIndicator<Map<String, Object>>() {}; TestChild value = mapper.convertValue(dataSnapshot.getValue(indicator), TestChild.class); The GenericTypeIndicator is a bit weird, but luckily it's a magic incantation that can be copy/pasted. A: This was apparently finally fixed in release 9.6. Fixed an issue where passing a derived class to DatabaseReference#setValue() did not correctly save the properties from the superclass.
[ "stackoverflow", "0019798069.txt" ]
Q: Ember-data hasMany association not working I have a couple models set up like follows: WT.WorkoutPlan = DS.Model.extend({ workouts: DS.hasMany('planWorkout'), name: DS.attr() }); WT.PlanWorkout = DS.Model.extend({}); When I attempt to load the model with the following JSON, the workout is loaded fine as evidenced by plan.get('name'); returning the name correction, but plan.get('workouts') always has 0 members. Anyone know why the association isn't loading? Here's the JSON: { "planWorkouts": [ { "id": 991, "name": "Lower Body" } ], "workoutPlan": { "id": 343, "name": "male-20to39-fat-loss", "planWorkouts": [991] } } I'm using ember-data 1.0beta3 A: This "workoutPlan": { "id": 343, "name": "male-20to39-fat-loss", "planWorkouts": [991] } should be "workoutPlan": { "id": 343, "name": "male-20to39-fat-loss", "workouts": [991] } aka the key should be workouts, not planWorkouts in your json
[ "stackoverflow", "0004466520.txt" ]
Q: Is there a simple way to compute a "smooth" function with the following characteristics in C/C++? In order to specify some things first: The user should be able to create a graph by specifying 3 to 5 points on a 2D field. The first and the last points are always at the bounds of that field (their position may only be changed in y direction - not x). The derivation of the graph at these positions should be 0. The position of the 3rd and following points may be specified freely. A graph should be interpolated, which goes through all the points. However, this graph should be as smooth and flat as possible. (please apologize for not being mathematically correct) The important thing: I need to sample values of that graph afterwards and apply them to a discrete signal. Second thing: Within the range of the x-Axis the values of the function should not exceed the boundaries on the y-Axis.. In my pics that would be 0 and 1 on the y-Axis. I created some pics to illustrate what I am talking about using 3 points. Some thoughts I had: Use (cubic?) splines: their characteristics could be applied to form such curves without too many problems. However, as far as I know, they don't relate to a global x-Axis. They are specified in relation to the next point, through a parameter usually called (s). Therefore it will be difficult to sample the values of the graph related to the x-Axis. Please correct me when I am wrong. create a matrix, which contains the points and the derivations at those points and solve that matrix using LU decomposition or something equivalent. So far, I don't have in depth understanding of these techniques, so I might miss some great technique or algorithm I haven't known about yet. There is one more thing, that would be great to be able to do: Being able to adjust the steepness of the curve via the change of one or a few parameters. I illustrated this by using a red and a black graph in some of my pictures. Any ideas or hints how to solve that efficiently? A: Do you understand how splines are arrived at? Summary of doing splines You break the range into pieces based on the control points (splitting at the control points or putting the breaks between them), and plop some parameterized function into each sub-range, then constrain the functions by the control points, artificially introduced end-point constraints, and inter-segment constrains. If you've counted your degrees of freedom and constraints right, you get a solvable system of equations which tells you the right parameters in terms of the control points and away you go. The result is a set of parameters for a piecewise function. Generally a piecewise continuous and differentiable function, because what would be the point otherwise. How you can use that in this case So consider making each interior point the center of a segment which will be occupied by a peak-like function (Gaussian on a linear background, maybe) and use the end points as constraints. For n total points you'd have D*(n-2) parameters if each segment has D parameters. You have four end-point constraints f(start)=y_0, f(end)=y_n, f'(start) = f'(end) = 0), and some set of match constraints between the segments: f_n(between n and n+1) = f_n+1(between n and n+1) f'_n(between n and n+1) = f'_n+1(between n and n+1) ... plus each segment is constrained by it's relationship to the control point (usually either f(point n) = y_n or f'(point n) = 0 or both (but you get to decide). How many matching constraints you can have depends on the number of degrees of freedom (total number of constraints must equal total number of DoF, right?). You have have to introduce some extra endpoint constraints in the form f''(start) = 0 ... to get it right. At that point you're just looking at a lot of tedious algebra to earn how to translate this into a big system of linear equation which you can solve with a matrix inversion. Most numeric methods books will cover this stuff.
[ "stackoverflow", "0002741662.txt" ]
Q: Can't run os.system command in Django? We have a Django app running on apache server (mod_python) on a windows machine which needs to call some r scripts. To do so it would be easiest to call r through os.system, however when django gets to the os.system command it freezes up. I've also tried subprocess with the same result. We have a possibly related problem in that Django can only access the file system of the machine it's on, all network drives appear to be invisible to it, which is VERY frustrating. Any ideas on both of these issues (I'm assuming it's the same limitation in both instances) would be most appreciated. A: Instead of os.system, would RPy2 meet your needs? I've used it in a similar case to the one you're describing with Django, and it's worked quite well. The high-level interface in rpy2 is designed to facilitate the use of R by Python programmers. R objects are exposed as instances of Python-implemented classes, with R functions as bound methods to those objects in a number of cases.
[ "physics.stackexchange", "0000314125.txt" ]
Q: Possible spherically symmetric solutions with a cosmological constant Why de sitter and Schwarzschild de sitter, and anti de sitter and Scharzschild anti de sitter are the only possible spherically symmetric solutions with a cosmological constant? I have read this fact but unable to prove it.(An intuitive proof may be even more helpful). (Please do note that I am from Physics background) Thank you in advance! A: The Birkoff's theorem imposes strong constraints on spherically symmetric solutions in vacuum spacetime (with possible singularities at r= 0) - basically they have to be isometric to a maxim ally extended Schwarzschild (Sch) solution.(if I remember right if it's spherically symmetric and static it has to be Schwarzschild up to coordinate transformations). See https://en.m.wikipedia.org/wiki/Spherically_symmetric_spacetime Since deSitter and AntideSitter (dS and AdS)come in for a lambda (cosmological constant) solution it's not unreasonable to think that adding lambda may bring in something similar. The paper below shows that the dS - Sch solution is the only one, with lambda any constant (so I'm guessing he includes the AdS but I did not read the full paper, you can read it in the link) http://msp.warwick.ac.uk/~cpr/paradigm/uniqueness.pdf Still, I am not sure that the uniqueness has really been proven. The following pdf paper finds other non-equivalent solutions. See http://redshift.vif.com/JournalFiles/V09NO3PDF/V09N3ABA.pdf. I can't vouch for its correctness. General Relativity, being very nonlinear, is not something where if you find one solution and combine it somehow with another it automatically works as another solution. Hard to get general theorems on uniqueness and manipulation so of solutions to get another. This is not meant to be a complete answer, but maybe it helps some.
[ "stackoverflow", "0002746303.txt" ]
Q: FreeText Query is slow - includes TOP and Order By The Product table has 700K records in it. The query: SELECT TOP 1 ID, Name FROM Product WHERE contains(Name, '"White Dress"') ORDER BY DateMadeNew desc takes about 1 minute to run. There is an non-clustered index on DateMadeNew and FreeText index on Name. If I remove TOP 1 or Order By - it takes less then 1 second to run. Here is the link to execution plan. http://screencast.com/t/ZDczMzg5N Looks like FullTextMatch has over 400K executions. Why is this happening? How can it be made faster? UPDATE 5/3/2010 Looks like cardinality is out of whack on multi word FreeText searches: Optimizer estimates that there are 28K records matching 'White Dress', while in reality there is only 1. http://screencast.com/t/NjM3ZjE4NjAt If I replace 'White Dress' with 'White', estimated number is '27,951', while actual number is '28,487' which is a lot better. It seems like Optimizer is using only the first word in phrase being searched for cardinality. A: Edit From http://technet.microsoft.com/en-us/library/cc721269.aspx#_Toc202506240 The most important thing is that the correct join type is picked for full-text query. Cardinality estimation on the FulltextMatch STVF is very important for the right plan. So the first thing to check is the FulltextMatch cardinality estimation. This is the estimated number of hits in the index for the full-text search string. For example, in the query in Figure 3 this should be close to the number of documents containing the term ‘word’. In most cases it should be very accurate but if the estimate was off by a long way, you could generate bad plans. The estimation for single terms is normally very good, but estimating multiple terms such as phrases or AND queries is more complex since it is not possible to know what the intersection of terms in the index will be based on the frequency of the terms in the index. If the cardinality estimation is good, a bad plan probably is caused by the query optimizer cost model. The only way to fix the plan issue is to use a query hint to force a certain kind of join or OPTIMIZE FOR. So it simply cannot know from the information it stores whether the 2 search terms together are likely to be quite independent or commonly found together. Maybe you should have 2 separate procedures one for single word queries that you let the optimiser do its stuff on and one for multi word procedures that you force a "good enough" plan on (sys.dm_fts_index_keywords might help if you don't want a one size fits all plan). NB: Your single word procedure would likely need the WITH RECOMPILE option looking at this bit of the article. In SQL Server 2008 full-text search we have the ability to alter the plan that is generated based on a cardinality estimation of the search term used. If the query plan is fixed (as it is in a parameterized query inside a stored procedure), this step does not take place. Therefore, the compiled plan always serves this query, even if this plan is not ideal for a given search term. Original Answer Your new plan still looks pretty bad though. It looks like it is only returning 1 row from the full text query part but scanning all 770159 rows in the Product table. How does this perform? CREATE TABLE #tempResults ( ID int primary key, Name varchar(200), DateMadeNew datetime ) INSERT INTO #tempResults SELECT ID, Name, DateMadeNew FROM Product WHERE contains(Name, '"White Dress"') SELECT TOP 1 * FROM #tempResults ORDER BY DateMadeNew desc
[ "stackoverflow", "0017720663.txt" ]
Q: MS terminal services client for windows 7 I need to access a system using ms terminal services client. i m confuse about those thing 1-MS terminal services client is already install in windows 7 if yes then from where i can found it ? 2-Do we need to install it in window 7 ? 3-IS Remote Application and Desktop Connections in control panel is also known as MS terminal services client for windows 7 ? A: Terminal Services was the old name for Remote Desktop Services. Remote Desktop Connection is the name of client software in Windows 7.
[ "stackoverflow", "0007383433.txt" ]
Q: How to get all possible combinations of n number of data set? I have 9 data sets, each having 115 rows and 742 columns and each data set contains results from a spectrometer taken under specific conditions. I would like to analyze all combinations of these 9 data sets to determine the best conditions. Edit: The data are spectral measurements(rows= samples,columns =wavelengths) taken at 10 different temperatures. I would like to get all combinations of the 9 data sets and apply a function cpr2 to each combination. cpr2 takes a data set and makes a plsr model,predicts 9 test sets(the individual sets),and returns bias of prediction. My intention is to find which combination gave the smallest prediction biases i.e how many temperature conditions are need to give acceptable bias. Based on suggestion: I'm looking to do something like this g<-c("g11","g12","g13,g21","g22","g23","g31","g32","g33") cbn<-combn(g,3) # making combinations of 3 comb<-lapply(cbn,cpr2(cbn)) for reference cpr2 is cpr2<-function(data){ data.pls<-plsr(protein~.,8,data=data,validation="LOO") #make plsr model gag11p.pred<-predict(data.pls,8,newdata=gag11p) #predict each test set gag12p.pred<-predict(data.pls,8,newdata=gag12p) gag13p.pred<-predict(data.pls,8,newdata=gag13p) gag21p.pred<-predict(data.pls,8,newdata=gag21p) gag22p.pred<-predict(data.pls,8,newdata=gag22p) gag23p.pred<-predict(data.pls,8,newdata=gag23p) gag31p.pred<-predict(data.pls,8,newdata=gag31p) gag32p.pred<-predict(data.pls,8,newdata=gag32p) gag33p.pred<-predict(data.pls,8,newdata=gag33p) pred.bias1<-mean(gag11p.pred-gag11p[742]) #calculate prediction bias pred.bias2<-mean(gag12p.pred-gag12p[742]) pred.bias3<-mean(gag13p.pred-gag13p[742]) pred.bias4<-mean(gag21p.pred-gag21p[742]) pred.bias5<-mean(gag22p.pred-gag22p[742]) pred.bias6<-mean(gag23p.pred-gag23p[742]) pred.bias7<-mean(gag31p.pred-gag31p[742]) pred.bias8<-mean(gag32p.pred-gag32p[742]) pred.bias9<-mean(gag33p.pred-gag33p[742]) r<-signif(c(pred.bias1,pred.bias2,pred.bias3,pred.bias4,pred.bias5, pred.bias6,pred.bias7,pred.bias8,pred.bias9),2) out<-c(R2(data.pls,"train",ncomp=8),RMSEP(data.pls,"train",ncomp=8),r) return(out) } Any insights into solving this will be appreciated. A: You don't say how you want to assess the pairs of matrices, but if you have your matrices as per the code you showed with those names, then g <- c("g11", "g12", "g13", "g21", "g22", "g23", "g31", "g32", "g33", "g2") cmb <- combn(g, 2) which gives: > cmb [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [1,] "g11" "g11" "g11" "g11" "g11" "g11" "g11" "g11" "g11" "g12" "g12" "g12" [2,] "g12" "g13" "g21" "g22" "g23" "g31" "g32" "g33" "g2" "g13" "g21" "g22" [,13] [,14] [,15] [,16] [,17] [,18] [,19] [,20] [,21] [,22] [,23] [,24] [1,] "g12" "g12" "g12" "g12" "g12" "g13" "g13" "g13" "g13" "g13" "g13" "g13" [2,] "g23" "g31" "g32" "g33" "g2" "g21" "g22" "g23" "g31" "g32" "g33" "g2" [,25] [,26] [,27] [,28] [,29] [,30] [,31] [,32] [,33] [,34] [,35] [,36] [1,] "g21" "g21" "g21" "g21" "g21" "g21" "g22" "g22" "g22" "g22" "g22" "g23" [2,] "g22" "g23" "g31" "g32" "g33" "g2" "g23" "g31" "g32" "g33" "g2" "g31" [,37] [,38] [,39] [,40] [,41] [,42] [,43] [,44] [,45] [1,] "g23" "g23" "g23" "g31" "g31" "g31" "g32" "g32" "g33" [2,] "g32" "g33" "g2" "g32" "g33" "g2" "g33" "g2" "g2" are the set of combinations of your matrices taken 2 at a time. Then iterate over the columns of cmb doing your assessment, e.g.: FUN <- function(g, ...) { ## get the objects for the current pair g1 <- get(g[1]) g2 <- get(g[2]) ## bind together dat <- rbind(g1, g2) ## something here to assess this combination cpr2(dat) } assess <- apply(cmb, 2, FUN = FUN, ....) A: Did you try combn? For example, if you want combinations of 3 drawn from a group of 10 elements you can use combn(10, 3)
[ "math.stackexchange", "0002861111.txt" ]
Q: Is $\left( {{2}^{x}}-1 \right)\left( {{5}^{x}}-1 \right)$ a square number for integer $x>1$ Motivated by this question. How to prove that $\left( {{2}^{x}}-1 \right)\left( {{5}^{x}}-1 \right)$ is not a square number for integer $x>1$? Thanks for any suggestions. Edition by the notification of @gimusi: The answer of this post that is mentioned by @crskhr, is provided by the dear user @Robert Z. Thanks to all users that have been contributed in this post. A: This is Problem 12019 in the American Math Monthly. A solution can be found in the link: AMM 12019
[ "stackoverflow", "0024989245.txt" ]
Q: PHP Laravel recursive function with nested array I am using Laravel 4 with MySQL back-end. I want to store records of a nested array into database using recursive function. The input array is as below : Array ( [0] => Array ( 'id' => 561, 'type' => 'q', 'subtype' => 'boolean', 'title' => 'Did you..?', 'parent' => 560, 'created_at' => '2014-07-09 09:45:50', 'updated_at' => NULL, 'deleted_at' => NULL, 'children' => Array ( [0] => Array ( 'id' => 562, 'type' => 'o', 'subtype' => NULL, 'title' => 'Yes', 'parent' => 561, 'created_at' => '2014-07-09 09:45:50', 'updated_at' => NULL, 'deleted_at' => NULL, 'children' => Array ( ) ) [1] => Array ( 'id' => 563, 'type' => 'answer', 'subtype' => NULL, 'title' => 'No', 'parent' => 561, 'created_at' => '2014-07-09 09:45:50', 'updated_at' => 'NULL', 'deleted_at' => NULL, 'children' => Array ( ) ) ) ) ) The recursive function I am using store the records into the database is as below : public function addRecursiveChildren(array $surveychildren, $parentid, $userid){ foreach ($surveychildren as $item) { /* Error : HTTPRequest Error :: 500: {"error":{"type":"ErrorException","message":"Cannot use a scalar value as an array Error is in the statement below in the second recursion when child is passes as an input. */ $item['survey_id'] = $item['id']; $item['user_id'] = $userid; $item['id'] = null; $item['parent'] = $parentid; $routine = routine::create($item); if(count($item["children"]) > 0) { foreach ($item["children"] as $child) { /* The $child I found is as below : $child = array( 'id' => 562, 'type' => 'o', 'subtype' => NULL , 'title' => 'Yes', 'parent' => 561, 'created_at' => '2014-07-09 09:45:50', 'updated_at' => NULL, 'deleted_at' => NULL, 'children' => Array ( ) ); */ RoutineRepository::addRecursiveChildren($child, $routine->id, $userid); } } } } Edit : I know that cause of error is the $child I am passing as an input array to the recursive function above : The $child is something like this : array( 'id' => 562, 'type' => 'o', 'subtype' => NULL , 'title' => 'Yes', 'parent' => 561, 'created_at' => '2014-07-09 09:45:50', 'updated_at' => NULL, 'deleted_at' => NULL, 'children' => Array ( ) ) Instead of this if $child will be something like this : Array ( [0] => array( 'id' => 562, 'type' => 'o', 'subtype' => NULL , 'title' => 'Yes', 'parent' => 561, 'created_at' => '2014-07-09 09:45:50', 'updated_at' => NULL, 'deleted_at' => NULL, 'children' => Array ( ) ) ) Then there will be no error. Can anybody help me to overcome it? Thanks. A: This should work class Routine extends \Eloquent { // The relation public function subRoutine() { return $this->hasMany('Routine', 'parent'); } public function saveSubroutine(array $children) { foreach($children as $childData) { $child = new self($childData); $this->subRoutine()->save($child); $child->saveSubroutine($childData['children']); } } } $routine = Routine::create($data); $routine->saveSubroutine($data['children']);
[ "stackoverflow", "0057618145.txt" ]
Q: How does converting css pixels to device pixels work for Iphones? Xiaomi Redmi 4A that has a resolution: 1280 X 720 (in device pixels) and 640 x 360 (in CSS pixels). CSS pixel-ratio is 2. To convert CSS pixels to Device pixels I multiply CSS pixels by CSS pixel-ratio, so 640*2 X 360*2 = 1280 X 720. At this moment everything is as I expect it to work Iphone 8 Plus has a resolution 1920×1080 (In device pixels) and 732 X 414 (in CSS pixels). CSS pixel-ratio is 3. When I do the same multiplication that I did above for Redmi 4A, I don't get the expected result, so 732*3 X 414*3 doesn't equal to 1920×1080 Could you explain what is wrong? A: In iOS screen are expressed in terms of points (pt.) which is used as a unit of measurement across all iOS designs. 1 point is always 1 point and is an abstract unit, only having meaning when referenced in relation to other points. You can get the css screen size by using Native scale given by Apple for every device. Refer this link: For different iPhone models refer the dimension sheet below for sizes in pt. https://developer.apple.com/library/archive/documentation/DeviceInformation/Reference/iOSDeviceCompatibility/Displays/Displays.html px = pt. x (Native scale) Let see how native scale is derived taking into special case of iPhone 8 and 8+ models. As per Apple the value of 1pt = 1 px at 163 dpi (1px x 1px = 1 pt) (Render @ 1x) 4 px at 326 dpi (2px x 2px = 1 pt) (Render @ 2x) 9 px at 489 dpi (3px x 3px = 1 pt) (Render @ 3x) ... To calculate px from point use the following formula px = (pt * DPI)/163 Considering case for iPhone 8 DPI: 326, Screen Size: 325pt x 667pt L: (325 * 326)/163 = 650px H: (667 * 326)/163 = 1334px Making css screen as 650px x 1334px, where UI will be rendered are 2x and native scale @ 2.0 Considering case for iPhone 8 plus DPI: 401, Screen Size: 414pt x 736pt L: (414 * 401)/163 = 1018.5px H: (736 * 401)/163 = 1810.6px Making screen as 1018.5px x 1810.6px Now it is not possible to render screen @ 2.46x as we cannot have a grid for 2.46px x 2.46px (Pixel is absolute unit not divisible) Getting to nearest whole number the screen is rendered are 3x. The native scale of iPhone 8+ is 2.608, which makes screen size as L: 414 * 2.608 = 1080px H: 736 * 2.608 = 1920px This is how native scale factor is derived for devices to render UI at 1x, 2x or 3x and its relation with sizes and pixels.
[ "stackoverflow", "0035860678.txt" ]
Q: Pass a dynamic value to a function in angular with ng-click I'm trying to use a link to dynamically translate a website. This is my HTML: <a ng-click="switchLanguage('{{language.value}}')" >Translate</a> {{language.value}} is a dynamic value taken from a json file and I can verify that upon runtime, it does get populated with the proper value ('en-us','ja-jp', etc...) And here's my function inside a controller: function switchLanguage(newlan) { console.log(newlan); } However, everytime I click on the link, the console shows the value as {{language.value}}, instead of the proper value (ex: en-us). How do I make the value inside the ng-click pass the correct parameter to the function? A: use ng-click="switchLanguage(language.value)" Here is the PLUNKER: http://plnkr.co/edit/uOUD9f1P3tKp3IlGsjBK?p=preview A: Instead of <a ng-click="switchLanguage('{{language.value}}')" >Translate</a> Use this <a ng-click="switchLanguage(language.value)" >Translate</a>
[ "stackoverflow", "0046258927.txt" ]
Q: Scrapy get text from function () I want to get the branchId in function but couldnt. Do you have any idea about how to get from a function. item["branchId"] = row.xpath('//div[@class="branchprofile"]//script/text()').extract()[0] HTML Code: <div id="branchprofile"> <script> (function(k,v){RMVH.ANALYTICS.DataLayer.pushKV(k,v);}('branch',{"branchId":5112345,"companyName":"KLM","brandName":"London KLM",,"pageType":"Standard"})); </script> A: You need to use the re method on the xpath and not extract. Extract will give just the text item['branchId'] = response.xpath("//div[@id='branchprofile']/script/text()").re('branchId":\s*(\d+)')[0]
[ "askubuntu", "0000068571.txt" ]
Q: How do I get the bleeding edge Chromium? The following versions of Chromium are available at the moment : Chromium Stable PPA (13.0.782.218) Chromium Beta PPA (14.0.835.126) Ubuntu Repo (14.0.835.202) Chromium Dev PPA (15.0.865.0) Chromium Daily PPA (15.0.871.0) All packages for Ubuntu Oneiric Ocelot. However, as per Chromium Developer Calendar, the following versions are released for Linux: linux dev 16.0.904.0 linux beta 15.0.874.92 linux stable 14.0.835.202 Is there any way I can get the latest developer build running on my system (without compiling it) A: Alternative Chromium PPA The PPAs above are not being updated at all. Alex Shkop has taken up responsibility to keep a better, more updated PPA set for chromium. They include: Chromium Stable (currently at 21.0.1180.79) Chromium Dev (currently at 23.0.1246) Note: The above PPAs are only for 12.04 at the moment. Bleeding Edge Chromium Binaries You can download the continuous builds from here. This will get you the last bleeding-edge chromium revision which passed the test suite. To install them, just extract the zip file somewhere (I use ~/apps/) and run the chrome binary inside. A: Sorry, you found the right place to get them, but they were just not up to date, the Chromium daily PPA has been restarted.
[ "tex.stackexchange", "0000219910.txt" ]
Q: Format of text within Tabular environment I want to make the words "words words words" be directly below n^k. What I have tried so far has not worked. That is, \newline, \\, and \underset{} cannot accomplish what I desire. Example Code \begin{center} \begin{tabular}{ | l | l | p{5cm} |} \hline & Order Matters & Order Doesn't Matter \\ \hline Repetition Allowed & $\displaystyle{n^k} $\par{ words words words}& $\displaystyle {n+k-1 \choose k-1}$ \\ \hline No Repetition Allowed& $\frac{n!}{(n-k)!}$ & ${n \choose k}$ \\ \hline \end{tabular} \end{center} A: You can only use \par inside a fixed-width p-column. Here is a toned-down implementation of your tabular: \documentclass{article} \usepackage{amsmath,booktabs} \begin{document} \begin{center} \begin{tabular}{ l c c } \toprule & Order Matters & Order Doesn't Matter \\ \cmidrule{2-3} Repetition Allowed & $\underset{\text{words words words}}{n^k}$ & $\binom{n+k-1}{k-1}$ \\[.5\normalbaselineskip] No Repetition Allowed & $\frac{n!}{(n-k)!}$ & $\binom{n}{k}$ \\ \bottomrule \end{tabular} \end{center} \end{document} It uses \binom from amsmath instead of the plain-TeX \choose. A \displaystyle version is available as \dbinom. Another option that allows for paragraph breaks as needed (with the aid of varwidth. A fixed-width column is created using L{<width>} which will produce a Left-aligned column no wider than <width>: \documentclass{article} \usepackage{amsmath,booktabs,varwidth,collcell} \newcommand{\fixedwidthcolumn}[1]{% \begin{varwidth}[t]{\fcolwidth}% \raggedright \strut#1\strut \end{varwidth}} \newcolumntype{L}[1]{>{\gdef\fcolwidth{#1}\collectcell\fixedwidthcolumn}l<{\endcollectcell}} \begin{document} \begin{center} \begin{tabular}{ l c c } \toprule & Order Matters & Order Doesn't Matter \\ \cmidrule{2-3} Repetition Allowed & $\underset{\text{words words words}}{n^k}$ & $\binom{n+k-1}{k-1}$ \\[.5\normalbaselineskip] No Repetition Allowed & $\frac{n!}{(n-k)!}$ & $\binom{n}{k}$ \\ \bottomrule \end{tabular} \bigskip \begin{tabular}{ L{130pt} c c } \toprule & Order Matters & Order Doesn't Matter \\ \cmidrule{2-3} Repetition Allowed & $\underset{\text{words words words}}{n^k}$ & $\binom{n+k-1}{k-1}$ \\[.5\normalbaselineskip] No Repetition Allowed & $\frac{n!}{(n-k)!}$ & $\binom{n}{k}$ \\ \bottomrule \end{tabular} \bigskip \begin{tabular}{ L{130pt} c c } \toprule & Order Matters & Order Doesn't Matter \\ \cmidrule{2-3} Some text that is long and will most like span multiple lines (but be not wider than \texttt{130pt}) & $\underset{\text{words words words}}{n^k}$ & $\binom{n+k-1}{k-1}$ \\ No Repetition Allowed & $\frac{n!}{(n-k)!}$ & $\binom{n}{k}$ \\ \bottomrule \end{tabular} \end{center} \end{document}
[ "stackoverflow", "0032605153.txt" ]
Q: Bootstrap lock icon not displaying I am trying to add the lock icon on my website using the following code, <div style="width:10%; background-color:#D6B300; height:50px;"> <p style="color:#044B29;padding: 10px 10px 10px 10px;"><span class="glyphicon glyphicon-lock"></span> Lock</p> </div> But for some reason it is not displaying on the site. Please guide. Thanks. A: Your site includes Font Awesome CSS but you were using Gylphicon classes in your span. Right code: <span class="fa fa-lock"></span>
[ "stackoverflow", "0003904674.txt" ]
Q: Design pattern(s) for a webservice enabled telerik treeview for navigation of a document site I am currently working on a document management system in ASP.NET 3.5 using the Telerik AJAX toolkit. It consists of masterpage with a title banner across the top and a RadTreeview down the left hand side for navigation through the site. The treeview uses a combination of static nodes and dynamic ones. The dynamic nodes are populated via a webservice. When a node is clicked the relevant page is navigated to, reloading the masterpage and displaying the content of the target page. The problem comes from the fact the treeview's dynamic nodes are populated via a webservice and therefore as the user navigates through the tree to find a document the treeview behaves as you would expect. However, when you get to the bottom of a tree of dynamic nodes the navigation to the page of the navigateurl causes the relevant page to be loaded and then the treeview resets itself to a collapsed state. This means the user could be deep in a nest of documents but when they view one, the tree collapses and they have to start their navigation all over again. This limitation is not going to be acceptable from an ease of use perspective. According to Telerik, this is the designed behaviour for performance reasons - the node only ever worries about populating the next set of nodes and therefore the treeviews state is not remembered in viewstate. So, the meat of question is... Is the masterpage/async treeview navigation design pattern a valid one? Are there any other ways to have an ajax treeview on a masterpage, that remembers it's state when another page is navigated to? I have considered a siglepage/updatepanel/partial page rendering model but the opinions I've seen on the net infer that this is bad idea. It confuses users that expect back/forward browser behaviour to navigate through the site but in a single page world they would end up leaving the site. I also thought that maybe using a single page container and an iframe may work but this seems to be moving away from the "standard" design pattern of using masterpages. A: If the treeview is going to collapse every time the user is navigating to another page/node, it is going to annoy the hell out of them. It is not acceptable from an end-users perspective if they are going to make more than at most two rounds at it. I would say that it is very good that you uses good old pages if the users are going to bookmark and/or send links to the different parts of the application, or especially if you want Google, Yahoo! et.c. to index your application. Else you can use an IFrame / #hash-link combination for your application; the IFrame can generate history events, thus forward and backward navigation even if the user is on the same top-page. On the state for the treeview you can use localstorage for the most browsers to store the current state including all the data, for other browsers you can use "Flash cookies", which allows for storage up to 100kb.
[ "stackoverflow", "0009360231.txt" ]
Q: Dojo bar chart, onmouseover hand cursor I have dojo bar chart. Onmouseover the bar i would like a hand cursor. I was trying something like this chart1.connectToPlot("default",function(evt) { var type = evt.type; if(type == "onmouseover"){ } how do i get my mouse pointer to show as hand when i move it over the bar? A: Try this, assuming you have a div in your html (the container of your chart), with id="chartNode" : chart.connectToPlot("default",function(evt) { var type = evt.type; if(type == "onmouseover") { dojo.style("chartNode", "cursor", "pointer"); } else if(type == "onmouseout") { dojo.style("chartNode", "cursor", "default"); } });
[ "music.stackexchange", "0000016032.txt" ]
Q: X or Y guitarist doesn't know music theory - how true is this statement? We've all heard a statement similar to the following: X didn't / doesn't know any music theory and is one of the all time greats replacing X with a famous guitarist. Being a novice, I am trying to figure out if this statement can ever make sense: Take the example of playing and improvising chord progressions (since in my mind this would be more difficult to "fake" than lead guitar): is the above statement really saying that these guitarist essentially make up chords as they go along based upon intuition and ear alone? To me, this would be extraordinarily impressive (of course there are prodigies, but I'm wondering if this is the commonplace explanation for the provided statement). On the other hand, say they initially learned to play by mimicking the songs and styles of other guitarists. Maybe at that point they built up a lexicon of available chords (and maybe even they can name them) and which sound good together. In my mind, this is, in some sense, knowledge of music theory. Is this what people usually mean when they claim lack of music theory knowledge? Is this not considered knowing (to some degree) music theory? A: I would say that the last paragraph of your question is closer to the truth. I wouldn't consider knowing the names and shapes of some chords as knowing theory. I know for a fact that people can play very well with little to no theoretical knowledge, since I have friends with this ability. Theory wasn't there before music, theory is a tool to understand and explain music. A: One last update. The question as I understand it has numerous nested questions: "...if this statement can ever make sense: "X didn't / doesn't know any music theory and is one of the all time greats..." "...is the above statement really saying that these guitarist essentially make up chords as they go along based upon intuition and ear alone?" "...Is this what people usually mean when they claim lack of music theory knowledge? Is this not considered knowing (to some degree) music theory?" While I completely agree with the person asking the question that it would be "extraordinarily impressive" for some one to "...make up chords as they go along based upon intuition and ear alone" and would like to add that even a prodigy would have had some memory or experience even if it is a tiny amount to produce an impressive result. Let's consider music like a language. When a child learns to talk it is both learning from the environment and exploring the voice box, and consequently learning how to imitate sounds and make sounds. A child does not immediately know what the words mean until there is an association, e.g. da da = dad. At some point the child has learned enough to communicate in a language associated with his parents, siblings, and eventually teachers. Once the child is in school, a formal presentation, a standardization of the language is taught and hopefully learned. So in turn a musician may learn the language of music by ear, by rote, before being introduced to formal theory or only learn from imitation, hearing and repeating, and further by taking the learned information and building on this a self taught methodology. The success to either form of learning, only from ear or only from studying music theory is only limited by the amount of time the musician practices what is in his or her mind and translates this to muscle memory e.g. for guitar, the hands. The key question that an adversary has pointed out so brutally that I have omitted is, "what does it mean to know music theory?" which is not even asked in the original question per se, but in an effort to save my butt here I will attempt to answer. To know music theory is to understand a formal peer reviewed pedagogical dogma based on the history of western culture musical practices from the Pre-Baroque era until the late Romantic era and up to the beginning of the Contemporary era, roughly pre-1600 to 15 October 1905 in Paris at the premiere of Debussy's "Le Mer" which has often been sited as the beginning of 20th Century Art Music. This theory rarely covers the following: Jazz, American Blues, Rock'n'Roll, Folk music of Africa, Australian Aboriginal people's music, to name a few world music idioms. This training is taught in almost every western music school including universities and private institutions such as the Juilliard School of Music or the Eastman School of Music in addition to covering such things as modes, scales, harmony, melodic line, analysis, counterpoint (both tonal and species) but also challenges the student with intensive ear training, sight reading, private lessons on one or more instruments, composition, and playing in an ensemble. Pretty darn near covers it all. There is nothing missing in this training. If you understand it and you practice what you learn you will have all the tools to perform, compose, and debate anything written in the last 1000 years of western music culture. Nothing missing ? Well, if you were Robert Johnson, or Jimi Hendrix, or Miles Davis you might want to debate this. I agree with Shevliaskovic in that some people have their blinders on and can not perform outside their comfort zone of what they were taught in music theory. However, I disagree with Shevliaskovic, music is not evolution. Music history does not evolve in a linear way as to be predictable like a land walking fish. No music is after all art, there is no scientific way to explain how human art has changed because human creativity is neither predictable or static. Yes, to say loosely that music is evolving makes sense in that it is growing but the word evolution is too confining. Let's agree that music is a sky with no limit, and the practitioners of great music understand there are no limits or specific directions but only their passion to guide them. Most people will need to see it before they believe it, but the wisest musician will be able see it because they believe it. You can not create until you see the vision you model in your head. ---- the prologue -- Theory or not to theory. You don't have to go to Le Cordon Bleu to learn how to cook a hot dog or roast a marshmellow, however, if you want to truly cook up something exciting in a 5 course meal for 250 people, having knowledge and practice will trump theory only any day. The best [musical] jams are served up fresh, hot, and spicy. How much does experience factor into a great performance vs. only theoretical knowledge? There are countless guitarists that have sold millions of albums that have no "formal" guitar training less college level music theory yet they perform wonderfully, creatively, and make lovely music. What gives? Knowledge from experience, a knowledge that is not only in the musician's head but in this case his or her hands makes a difference. While theory is great as it accounts for how something "was" practiced, knowing the fingerboard and many chords and the ability to create new chords on the fly is something that only the practice can foster. The X and the Y may have very easily learned by ear or by rote but it is what they practiced that gives them the edge. A: You don't really need to know music theory to play music. Just like @Meaningful Username said, theory is used to understand music, and also to communicate with other musicians. Imagine someone trying to explain that he is playing in C major scale, but without knowing the name of the scales. That would be hard. Also, just consider that there are people that have a 'good' ear. I've seen people without any music theory knowledge that just try chord progressions. They play a chord, then they play another and another and another, until they find one or two or three or any number that sound good together. Moreover, I've seen people being restricted by music theory. I used to play with a pianist that had really really studied classical theory. That made him think only in that kind of music. He wouldn't even listen to anything that was different from what he knew from the theory. But music evolves. Think how music evolved from classical into blues,jazz, atonal etc.People used to know classical theory, but they wanted to play something different from it. There wasn't any other theory. So they played what they liked / sounded good to them etc. Thus, they created a new theory. In conclusion, don't think that people need theory in order to play music. You can really just play music with your emotions, and that is what makes music so beautiful. It cannot be restrained by any kind of theory.
[ "stackoverflow", "0050773877.txt" ]
Q: Create for loop to plot histograms for individual columns of DataFrame with Seaborn So I'm trying to plot histograms for all my continous variables in my DatFrame using a for loop I've already managed to do this for my categorical variables using countplot with the following code: df1 = df.select_dtypes([np.object]) for i, col in enumerate(df1.columns): plt.figure(i) sns.countplot(x=col, data=df1) Which I found here by searching SO. However now I want to do the same with distplot so I tried modifying the above code to: df1 = dftest.select_dtypes([np.int, np.float]) for i, col in enumerate(df1.columns): plt.figure(i) sns.distplot(df1) But it just gived me one empty plot. Any ideas on what I can do? edit: e.g of DataFrame: dftest = pd.DataFrame(np.random.randint(low=0, high=10, size=(5, 5)), columns=['a', 'b', 'c', 'd', 'e']) A: It seems like you want to produce one figure with a distplot per column of the dataframe. Hence you need to specify the data in use for each specific figure. As the seaborn documentation says for distplot(a, ...) a : Series, 1d-array, or list. Observed data. So in this case: for i, col in enumerate(df1.columns): plt.figure(i) sns.distplot(df1[col])
[ "math.stackexchange", "0001846691.txt" ]
Q: If the volume of a cylinder is fixed, derive the radius and height that will maximize the surface area I know how to find the radius and height for minimum surface area. [https://www.physicsforums.com/threads/maximum-surface-area-of-cylinder.332279/ ]. For it to be minimum, h=r/2. It would be great if someone could tell me how to find the values for maximum value. A: There is no maximal surface area. To see that, start with an arbitary cylinder with the given volume. Then, divide the height by $4$ and double the radius. The volume does not change, but the area of the circle is $4$ times larger. You can repeat this process as often as you want. It is clear that there is no upper bound for the surface area.
[ "stackoverflow", "0040589467.txt" ]
Q: Loading menu from a partial view in MVC I am trying to seperate the menu from _Layout.cshtml but I am having difficulties. My files are located like below. Views/Home/Index Views/Shared/_Layout Views/Shared/_Menu In _Layout.cshtml file, I have the code below... @Html.Partial("_Menu") Menu action is located in HomeController, and it looks like below public ActionResult Menu() { MenuModel menu = new MenuModel(); return PartialView("_Menu", menu); } _Menu has the code below as first line @model DomainModel.MenuModel When I run the project on VS, everything looks perfect but I doesnt call Menu() action in HomeController. It somehow finds _Menu and displays it perfectly. But I dont understand why it doesnt call Menu() action? A: @Html.Partial("_Menu") will just render HTML view, nothing to do with controller. If you want to call a controller use @{ Html.RenderAction("Menu", "Home"); }
[ "stackoverflow", "0025194024.txt" ]
Q: java.lang.NoClassDefFoundError: com.acme.R$layout referencing android library I have an Android library project with a custom authenticator and an Activity that provides a login screen for the authenticator. The authenticator works fine when included directly in my main app, but I would like to put the authenticator into a separate android library. When I run the main android application project which references this library, I get a 'java.lang.NoClassDefFoundError: com.acme.R$layout' in the Activity's onCreate method when it calls setContentView with the R.layout. I am using an android gradle build. I have published the libraries to a local maven repository and the main project seems to be building without any issues. I have decompiled the class.dex file in the debug apk in build/outputs/apk and I can see that the R$layout.class file from the library is present, so I am at a complete loss as to what might be the problem. Here is the service which implements the custom authenticator: public class AcmeAuthenticatorService extends Service { public static final String ACME_ACCOUNT_TYPE = "acme-oauth"; public static final String ACME_ACCESS_TOKEN_TYPE = "acme-oauth-access-token"; private static Authenticator authenticator; private Authenticator getAuthenticator() { if (authenticator == null) authenticator = new Authenticator(this); return authenticator; } @Override public IBinder onBind(Intent intent) { if (intent.getAction().equals(AccountManager.ACTION_AUTHENTICATOR_INTENT)) return getAuthenticator().getIBinder(); return null; } private static class Authenticator extends AbstractAccountAuthenticator { private final Context context; Authenticator(Context ctx) { super(ctx); this.context = ctx; } @Override public Bundle addAccount(AccountAuthenticatorResponse response, String accountType, String authTokenType, String[] requiredFeatures, Bundle options) throws NetworkErrorException { return makeAuthIntentBundle(response, options); } private Bundle makeAuthIntentBundle(AccountAuthenticatorResponse response, Bundle options) { Bundle reply = new Bundle(); Intent i = new Intent(context, AcmeAccountAuthenticatorActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); i.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response); if (options != null) i.putExtras(options); reply.putParcelable(AccountManager.KEY_INTENT, i); return reply; } @Override public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException { return null; } @Override public Bundle updateCredentials(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException { return null; } @Override public Bundle confirmCredentials(AccountAuthenticatorResponse response, Account account, Bundle options) throws NetworkErrorException { return null; } @Override public Bundle editProperties(AccountAuthenticatorResponse response, String accountType) { return null; } @Override public String getAuthTokenLabel(String authTokenType) { return null; } @Override public Bundle hasFeatures(AccountAuthenticatorResponse response, Account account, String[] features) throws NetworkErrorException { return null; } } } Here is the Activity which handles login: import com.acme.R; public class AcmeAccountAuthenticatorActivity extends AccountAuthenticatorActivity { private AccountManager accountManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //NoClassDefFoundError occurs for this line setContentView(R.layout.activity_account_auth); accountManager = AccountManager.get(this); WebView webview = (WebView)findViewById(R.id.web_view); WebSettings webSettings = webview.getSettings(); webSettings.setJavaScriptEnabled(true); if ( webview == null ) { Log.e("TAG", "Web view not found!!"); } else { //Do authentication } } } Here is the layout xml for the login activity: <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.acme.AcmeAccountAuthenticatorActivity" tools:ignore="MergeRootFrame" > <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="8dp"> <WebView android:id="@+id/web_view" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> </FrameLayout> In the applications section of the manifest for the library I have: <activity android:name="com.acme.AcmeAccountAuthenticatorActivity" android:label="Login"> </activity> <service android:name="com.acme.AcmeAuthenticatorService" android:permission="com.acme.AUTHENTICATE_ACME_ACCOUNTS"> <intent-filter> <action android:name="android.accounts.AccountAuthenticator"/> </intent-filter> <meta-data android:name="android.accounts.AccountAuthenticator" android:resource="@xml/authenticator"/> </service> And the build.gradle for the library: buildscript { repositories { jcenter() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:0.12.+' } } apply plugin: 'com.android.library' apply plugin: 'maven-publish' version '1.0-SNAPSHOT' group 'com.acme' repositories { mavenLocal() mavenCentral() } android { compileSdkVersion 19 buildToolsVersion "20.0.0" defaultConfig { applicationId "com.acme.test" minSdkVersion 16 targetSdkVersion 19 } buildTypes { release { runProguard false proguardFiles getDefaultProguardFile('proguard-project.txt'), 'proguard-rules.txt' } } } dependencies { compile 'com.android.support:support-v4:19.0.0' compile 'com.android.support:appcompat-v7:19.0.0' } def getArtifactFullPath() { return "${buildDir}/outputs/aar/${project.name}-${project.version}.aar" } android.libraryVariants publishing { publications { maven(MavenPublication) { artifact getArtifactFullPath() } } } Then in the android application I do the following to trigger the auth activity: final AccountManagerFuture<Bundle> future = accountManager.addAccount(AcmeAuthenticatorService.ACME_ACCOUNT_TYPE, AcmeAuthenticatorService.ACME_ACCESS_TOKEN_TYPE, null, null, this, new AccountManagerCallback<Bundle>() { @Override public void run(AccountManagerFuture<Bundle> future) { try { Bundle bnd = future.getResult(); showMessage("Account was created"); Log.d("acme", "AddNewAccount Bundle is " + bnd); } catch (Exception e) { e.printStackTrace(); showMessage(e.getMessage()); } } }, null); Here is the build.gradle for the android application: buildscript { repositories { jcenter() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:0.12.+' } } apply plugin: 'com.android.application' apply plugin: 'maven' repositories { mavenLocal() mavenCentral() } android { compileSdkVersion 19 buildToolsVersion '20.0.0' defaultConfig { applicationId "com.acme.myapp" minSdkVersion 16 targetSdkVersion 19 } buildTypes { release { runProguard false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' } } } dependencies { compile 'com.acme:acme-auth:1.0-SNAPSHOT' compile 'com.android.support:support-v4:19.+' compile 'com.android.support:appcompat-v7:19.+' } and here is the logcat: E/AndroidRuntime(27992): FATAL EXCEPTION: mainE/AndroidRuntime(27992): Process: com.acme.myapp, PID: 27992 E/AndroidRuntime(27992): java.lang.NoClassDefFoundError: com.acme.R$layout E/AndroidRuntime(27992): at com.acme.AcmeAccountAuthenticatorActivity.onCreate(AcmeAccountAuthenticatorActivity.java:29) E/AndroidRuntime(27992): at android.app.Activity.performCreate(Activity.java:5231) E/AndroidRuntime(27992): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) E/AndroidRuntime(27992): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148) E/AndroidRuntime(27992): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233) E/AndroidRuntime(27992): at android.app.ActivityThread.access$800(ActivityThread.java:135) E/AndroidRuntime(27992): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) E/AndroidRuntime(27992): at android.os.Handler.dispatchMessage(Handler.java:102) E/AndroidRuntime(27992): at android.os.Looper.loop(Looper.java:136) E/AndroidRuntime(27992): at android.app.ActivityThread.main(ActivityThread.java:5001) E/AndroidRuntime(27992): at java.lang.reflect.Method.invokeNative(Native Method) E/AndroidRuntime(27992): at java.lang.reflect.Method.invoke(Method.java:515) E/AndroidRuntime(27992): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785) E/AndroidRuntime(27992): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) E/AndroidRuntime(27992): at dalvik.system.NativeStart.main(Native Method) W/ActivityManager( 575): Force finishing activity com.acme.myapp/com.acme.AcmeAccountAuthenticatorActivity W/ActivityManager( 575): Force finishing activity com.acme.myapp/.MainActivity W/ActivityManager( 575): Activity pause timeout for ActivityRecord{42071a70 u0 com.acme.myapp/com.acme.AcmeAccountAuthenticatorActivity t75 f} Update I've created a sample project that demonstrates the issue on github. Please see the README for instructions on building and reproducing the error. A: As long as the Bug in current Android-Gradle Plugin (Version 0.12.2) is not fixed, the only way to solve the problem, is to remove the applicationId from the build.gradle I will update this Post, as soon as this bug has been fixed Update: current version 0.13.3 still produces the same error
[ "stackoverflow", "0041943210.txt" ]
Q: Using an overloaded operator to perform operations at time of function call? I'm trying to figure out how I can perform an operation at the time in which a function is called, for example: ExampleClass eco; eco.DoStuff(); At the point of eco.DoStuff(), I'd like to log to a file. I'm trying to get something with overloaded operators but with no luck? E.g. void operator>>(ExampleClass eco, std::function<void(void)> DoStuff) { //Perform logging into a file DoStuff; } int main() { ExampleClass eco; std::function<void(void)> func_pointer = std::bind(&ExampleClass::DoStuff, &eco, 2); eco >> func_pointer; } This works, however I can't use a flexible parameter for DoStuff, as this has to be explicitly set in func_pointer. Additionally, creating function pointers for every single method in my class isn't an option. What's the best way of doing this? A: What about using a templated definition for the output operator? template<typename Function> void operator>>(ExampleClass eco, Function DoStuff) { //Perform logging into a file DoStuff(); } A possible variation on this method is to supply functors to the operator>> overload that take eco as an lvalue argument: template <typename MemberCall> ExampleClass& operator>>(ExampleClass& eco, MemberCall mem_call){ eco.log(); mem_call(eco); return eco; // returned lvalue eco allows chaining } Ease of use could be improved by creating a helper function to convert member function pointers and arguments to functors taking an ExampleClass lvalue argument: template <typename MemberFunctionType, typename...Args> auto member_call(MemberFunctionType mem_fn, Args&&...args){ return [=](ExampleClass& object){ return (object.*mem_fn)(args...); }; } to be used like so: eco >> member_call(&ExampleClass::DoStuff, 2) >> member_call(&ExampleClass::DoStuff, 4); It should be noted that the errors should you supply an invalid argument to this construct may not be pretty, since member_call returns lambdas. If it becomes a problem, creating and returning a custom functor type will likely improve error message quality.
[ "stats.stackexchange", "0000128812.txt" ]
Q: Confidence interval for sample $\{x_1, x_2, x_3, x_4\} = \{5,10,6,7\}$ Suppose this sample is generated from a $N(\mu, 9)$ distribution, $\mu$ is unknown. The question asks for a 95% confidence interval sample for $\mu$. I think this is a pretty straightforward case of population mean estimate when $\sigma^2$ is known. So I use the following formula, where $\bar{x}=7, \sigma=3,$ and $n=4$ $\bar{X}_n-\frac{\sigma}{\sqrt{n}}z_{\alpha/2}< \mu <\bar{X}_n+\frac{\sigma}{\sqrt{n}}z_{\alpha/2}$ Can someone verify that my solution is correct? More generally, how do I interpret the resulting confidence interval? A: The confidence interval you list is correct. Plugging your numbers in, I get a 95% confidence interval of $(4.06;\,9.94)$. Concerning the interpretation, a quick search on the site revealed many interesting posts. The Wikipedia page also has a section on the interpretation of confidence intervals. In short, there is not 95% probability that the above interval contains $\mu$ (the true mean). Rather, if you would calculate 100 95% confidence intervals in this way, 95% of them are expected to include $\mu$. But after you calculated your confidence interval, $\mu$ is either included or not. Here is a small simulation in R to illustrate the procedure: set.seed(123) pop <- rnorm(1e7, mean = 7, sd = 3) CI <- function(x, alpha = 0.05, true.sd) { res <- c(mean(x) - qnorm(1-alpha/2)*(true.sd/sqrt(length(x))) , mean(x) + qnorm(1-alpha/2)*(true.sd/sqrt(length(x)))) res } n.sim <- 200 n <- 4 cis <- replicate(n.sim, CI(x = sample(pop, size = n, replace = TRUE), alpha = 0.05, true.sd = 3)) does.not.cover <- (cis[1, ] > 7) | (cis[2, ] < 7) sum(does.not.cover)/n.sim [1] 0.04 a <- min(cis[1, ]) b <- max(cis[2, ]) plot(0, 0, type = 'n', xlim = c(a, b), ylim = c(0, n.sim), ann = FALSE, yaxt = "n") axis(1, at = 7, label = 7) segments(cis[1, ], 1:n.sim, cis[2, ], 1:n.sim, col = ifelse(does.not.cover, 'red', 'black')) abline(v = 7) I simulated 200 95% confidence intervals based on samples of $n=4$ from a population with mean $7$ and standard deviation $3$ (assumed to be known). 4% (i.e. 8) of the 200 95% confidence intervals don't contain the true mean of 7 (red segments in the picture). In the long run, the proportion of confidence intervals that don't contain the true mean is $\alpha$ (5% in this case).
[ "stackoverflow", "0003861906.txt" ]
Q: Xml structure with XStream I have class: public class EnglishWord implements Serializable, Comparable, Cloneable { static Logger logger = Logger.getLogger(EnglishWord.class); private static final long serialVersionUID = -5832989302176618764L; private String word;// in lowercase if not personal name private int occurenceNumber = 1;// 0,1,2,3, private int rating;// 1-first, 2 - second... private Set<String> builtFrom; private String translation; private boolean isVerb; private boolean isNoun; private boolean isIrregular; .... } I have Set words = new TreeSet(); And I use XStream for serialization: XStream xs = new XStream(); xs.alias("englishWord", EnglishWord.class); FileOutputStream fs = null; try { fs = new FileOutputStream(fileName); } catch (FileNotFoundException e) { logger.error(e.getMessage()); } xs.toXML(words, fs); try { fs.flush(); fs.close(); } catch (IOException e) { logger.error(e.getMessage()); } After this I get structure of file like this: <englishWord> <word >the </word > <occurenceNumber >7480 </occurenceNumber > <rating >1 </rating > <builtFrom class="tree-set" > <no-comparator/ > <string >The </string > <string >the </string > </builtFrom > <isVerb >false </isVerb > <isNoun >false </isNoun > <isIrregular >false </isIrregular > </englishWord> Can I get something like this with XStream: <englishWord word="the" occurenceNumber="7480" rating="1" isVerb="true"> <builtFrom class="tree-set" > <no-comparator/ > <string >The </string > <string >the </string > </builtFrom > </englishWord > ??? A: To convert them to attributes try the following: xs.useAttributeFor(EnglishWord.class, "word"); xs.useAttributeFor(EnglishWord.class, "occurenceNumber"); xs.useAttributeFor(EnglishWord.class, "rating"); xs.useAttributeFor(EnglishWord.class, "isVerb");
[ "stackoverflow", "0022153276.txt" ]
Q: how to create colored buttons like Xcode using gray template images If I have an NSButton that uses a template image, how do I colorize it like Apple does in Xcode? A: There is no API to colorize template images in buttons. In one of my latest applications I just wrote a small factory which created the colorized images on the fly from gray ones. I'm using core image filters which are processing the images incredible fast. This is the main method of the factory which does the colorization: - (NSImage *)imageNamed:(NSString *)name withOptions:(HcToolbarImageOptions)options { NSString *key = [self keyForName:name withOptions:options]; NSImage *image = _cache[key]; if (!image) { NSImage *sourceImage = [NSImage imageNamed:name]; NSAssert1(sourceImage != nil, @"Could not find any image named %@", name); if (options == 0) { image = sourceImage; } else { image = [NSImage imageWithSize:sourceImage.size flipped:NO drawingHandler:^BOOL(NSRect dstRect) { CIContext *context = [[NSGraphicsContext currentContext] CIContext]; CGContextRef cgContext = [[NSGraphicsContext currentContext] graphicsPort]; NSRect proposedRect = dstRect; CGImageRef cgImage = [sourceImage CGImageForProposedRect:&proposedRect context:[NSGraphicsContext currentContext] hints:nil]; CIImage *result = [CIImage imageWithCGImage:cgImage]; if (options & HcToolbarImage_Enabled) { CIFilter *filter1 = [CIFilter filterWithName:@"CIGammaAdjust"]; [filter1 setDefaults]; [filter1 setValue:result forKey:kCIInputImageKey]; [filter1 setValue:@0.6 forKey:@"inputPower"]; result = [filter1 valueForKey:kCIOutputImageKey]; CIFilter *filter2 = [CIFilter filterWithName:@"CIColorMonochrome"]; [filter2 setDefaults]; [filter2 setValue:result forKey:kCIInputImageKey]; [filter2 setValue:@1.0f forKey:kCIInputIntensityKey]; [filter2 setValue:[CIColor colorWithRed:0.2 green:0.5 blue:1.0] forKey:kCIInputColorKey]; result = [filter2 valueForKey:kCIOutputImageKey]; } CGRect extent = [result extent]; CGImageRef finalImage = [context createCGImage:result fromRect:extent]; if (options & HcToolbarImage_NotKeyWindow) { CGContextSetAlpha(cgContext, 0.5); } CGContextDrawImage(cgContext, dstRect, finalImage); return YES; }]; } [_cache setObject:image forKey:key]; } return image; } The final images are cached in a NSMutableDictionary.
[ "japanese.stackexchange", "0000058439.txt" ]
Q: し at the end of the sentence I learned that shi is used to connect two or more sentences. But sometimes I hear it at the end of the sentence. What does it mean? Can you explain on these sentences? 濃くなってきちゃったら、部分レーザー脱毛に通えばいいし。 穴があいた後ろから好きな当て布してもいいし。 「ねえ、マッギー」「わたしマギーだし…」 簡単にYou're right.とかHe's right.で良いと思います。または、論争していて相手の言うことを認めるみたいなときはOK, you win!でいいし。 あんな人のことは忘れたし! せっかく来たんだからゆっくりしてけし。 A: As you have correctly understood, し after the dictionary form of a copula/verb/i-adjective is usually used to connect two clauses. The first part often works as the reason of the second part. In English it's like "and" or "so", depending on the context. If a sentence ends with し, it's either one of the following: The "consequence" part is omitted because it can be inferred. It's like ending a sentence with "so". わたしマギーだし… But I'm Maggie, so... The following part is something like "don't call me like that", but it's left unsaid. It works as the reason for the previous statement. In this case it's like "(it's) because ...", "coz ...", "I mean" or "you know". 見てよ、面白いし! Watch it, (because) it's fun! 帰ろう。もう夜だし。 Let's go home. (Because) It's night. If you are a beginner, you can stop reading here. Your sixth example is different from the other five. #6 does not sound particularly weird to me, but し after the imperative form of a verb is recent nerdy slang mainly used on the net. (It's originally a dialectal particle, but it somehow became a nationwide slang expression in the last 20 years or so.) This し emphasizes the imperative, like "hey", "yo" or "come on". This usage is not in a serious dictionary, and you should not use this unless you really understand how it sounds. ゆっくりしてけし。 Make yourself at home. (slangy) 嘘言うなし。 Don't tell a lie. (slangy) A: If I remember correctly, 「ゆっくりしてけし」is a dialect in Yamanashi prefecture. It is equivalent to 「ゆっくりしていってください」「ゆっくりしていきなさい」.
[ "stackoverflow", "0015242090.txt" ]
Q: Store quote requests and email if user is inactive Looking to be able to take what is essentially an editorial page for a product and add a "request a quote" button. The user will then need to be prompted for basic info: name, email & phone. Users can have guest status or be logged in. The client would simply like to be notified via email of the request. The part I'd appreciate thoughts on, or a pre-boiled plugin for (clients site built in Wordpress, looked but can't see anything), is the best method for preventing the system from sending multiple emails if the user makes multiple quote requests within this session. The solution should effectively allow the user to only enter their details once -> click as many "request quote" buttons as they like -> then after a certain amount of inactivity, email what they are after to the site owner. This is the bit I'm stuck on, the best way of sending the users request, without the user actually hitting a 'checkout' type button. I'd really appreciate some thoughts on the best methods to achieve this, which keep it simple for the end user. A: You save the details in some way I presume. For this answer I'm assuming it's a database, but it really doesn't matter. When you save name, email and phone, also register a field for the send datetime. This "sendmail_at" is scanned by a process and the mail is send when the time is past. Every time the user presses a quote button you update the time a bit to give the user time to browse more. Example: 09:00: User requests the first quote. You ask for name/email/phone, and save this togehter with time 10:00 in the database 09:10 User browses, sees another thing he likes a quote for, and presses the button. The name/email/phone are still there, but the datetim is updated to 10:10 (and the extra quote id ofcourse) etc 09:20 Last quote request ... 10:20 The mailer checks the database and sees that the 'send' time is past, so gathers all the quotes and sends the email. For mailing: there are 3 parts to this: Periodically calling your function you function for checking if you should mail a mailer function. The first and last are probably ready made. You can use your servers cron-system, or even wordpress's cron system (that on turn can use the servers cronsystem or it's own thing) for this. You can probably find a plugin for wordpress, but I'm not sure how you would integrate it, or which one to choose. As you are going to fix point 2. anyway, you might just want to use something like PHPMailer. For the middle part you need to write a script that isn't too complicated. You read your database/file/whatever of users, and filter all users that still have to receive a mail, but where the "senddate" is in the past. If you have those email adresses, you compose your mail, and use the function of the mailer I discussed above to actually send the mail. Tying it all together: Make a script that when given a user, it's email and the quotes, generates an email and sends it (with phpmailer for instance) Make a second script that looks in your database for users to mail, and calls that script Make a cronjob to call that second script every x minutes .... profit!
[ "stackoverflow", "0051855606.txt" ]
Q: When MongoDB aggregate can't find any result, it returns an array with an empty object I want to get the list of my single project's bids within the project's aggregate. but when I run my Mongodb aggregate, if it can't find any result for bids of the project, it returns this result: [ { _id: 5b69f6afa1ad1827cc9e1dc6, projectID: 100029, bidsArray: [ { freelanceArray: {} } ] } ] But I want to return empty bidsArray if it can't find related bids, (something like this): [ { _id: 5b69f6afa1ad1827cc9e1dc6, projectID: 100029, bidsArray: [] } ] Here is my aggregate: [ { $match: { projectID: projectID } }, { $lookup: { from: "bids", localField: "projectID", foreignField: "projectID", as: "bidsArray" } }, { $unwind: { path: "$bidsArray", preserveNullAndEmptyArrays: true } }, { $lookup: { from: "users", localField: "bidsArray.freelanceID", foreignField: "userID", as: "freelanceArray" } }, { $unwind: { path: "$freelanceArray", preserveNullAndEmptyArrays: true } }, { $group: { _id: "$_id", projectID: { $first: "$projectID" }, bidsArray: { $addToSet: { bidID: "$bidsArray.bidID", daysToDone: "$bidsArray.daysToDone", freelanceArray: { userID: "$freelanceArray.userID", username: "$freelanceArray.username", publicName: "$freelanceArray.publicName", } } } } }, { $project: { projectID: 1, bidsArray: { bidID: 1, daysToDone: 1, freelanceArray: { userID: 1, username: 1, publicName: 1, } } } } ] A: In MongoDB 3.6, you can use the variable $$REMOVE in aggregation expressions to conditionally suppress a field. Remove the last $project stage and update the freelanceArray expression inside $group as below. The $cond expression basically checks freelanceArray value when present ( not null value) output the fields else remove the freelanceArray. "freelanceArray":{ "$cond":[ {"$gt":["$freelanceArray",0]}, {"userID":"$freelanceArray.userID","username":"$freelanceArray.username","publicName":"$freelanceArray.publicName"}, "$$REMOVE"] }
[ "stackoverflow", "0060079689.txt" ]
Q: Angular application cannot find symbolic link after angular 8 on linux server I recently upgraded an Angular 7 application to Angular 8. Tests, build and runs of the application worked perfectly on my windows machine. During the continuous integration build on a unbuntu, it however fails when trying to run the tests: Could not list contents of '/etc/atlassian-bamboo-5.9.7/xml-data/build-dir/MyProjectDir/client/node_modules/@angular-devkit/build-angular/node_modules/cacache/node_modules/.bin/rimraf'. Couldn't follow symbolic link. I tried removing the node_modules, the .bin folder or even cleaning the build repository and pull the code again, but I still get this error. My CI server has npm 6.13.7 and node 10.16.3. How to go around the symbolic link issue? A: Removing the node_modules folder and doing a npm install solved the issue. Let's note that I'm using yarn, but yarn installs doesn't work, it needs to be a npm install. If the issue happens in CI and you rely on yarn for most tasks, run npm install before yarn does anything.
[ "japanese.meta.stackexchange", "0000002006.txt" ]
Q: New tag for (video) games? I saw that we repeatedly get questions about Japanese from video games. I think it might be useful to create a tag for such questions, as grammar/usage/vocabulary of Japanese can be different from Japanese from other sources. I tagged three questions with gaming, but maybe video-games is a better name...? In any case, I would like to ask for some feedback before introducing a new tag. A: The tag video-games is now live and gaming is a tag synonym. The tag excerpt currently reads ゲーム. Japanese grammar, expressions, vocabulary as used in the context of video games. Of course comments are still welcome.
[ "stackoverflow", "0019513618.txt" ]
Q: How to set vhost in Expressjs without hard coding? So i know this works: app.use(express.vhost('sub.xyz.com', subdomainApp)); app.use(express.vhost('xyz.com', mainApp)); But when i try set the host part in express.vhost dynamically, it simply doesn't work. (I need to set it dynamically in order to avoid changing the hard coded domains while i move between production and development.) I tried the code below and i dont know why this doesn't work: app.use(function(req, res){ return express.vhost('xyz.'+req.host, subdomainApp); }); app.use(function(req, res){ return express.vhost(req.host, mainApp); }); So how do i pass 'request host' dynamically to express.vhost? A: I don't know exactly your implementation details, but what I suggest and I think it's the most common practice, is to set those configuration params in envrionment variables. so you would have. app.use(express.vhost('xyz' + process.env.APP_HOST, subdomainApp)); so you can have different env vars in production / development environments. to set env variables from command line use export APP_HOST=wahtever or append just before execute the node command APP_HOST=whatever node server.js or add them to your *.bash_profile* or equivalent for your OS
[ "stackoverflow", "0030174337.txt" ]
Q: UnsatisfiedLinkError on iOS but not Android, loadLibrary always succeeds I have some Java and C++ code that I can compile on both platforms and build native libraries. I can verify that the libraries contain the functions I expect, and Java is able to load the libraries on Android and iOS. On Android everything goes smoothly with no crash, but on iOS I get a very frustrating error: 2015-05-11 11:34:48.418 IOSLauncher[52454:851038] [info] test: initializing native libraries... 2015-05-11 11:34:48.418 IOSLauncher[52454:851038] [info] test: library path set to: "/Users/test/Library/Developer/CoreSimulator/Devices/A189459D-B2D5-4E78-A6E4-A7EAD19DA017/data/Containers/Bundle/Application/DF265D55-DA3C-4C10-851D-20591C4C8C06/IOSLauncher.app" 2015-05-11 11:34:48.419 IOSLauncher[52454:851038] [info] test: loading native libraries on x86_64... 2015-05-11 11:34:48.419 IOSLauncher[52454:851038] [info] test: test 2015-05-11 11:34:48.424 IOSLauncher[52454:851038] [info] test: loaded libraries successfully java.lang.UnsatisfiedLinkError: com/test/Native.getPointer()J at com.test.Native.getPointer(Native Method) at com.test.WavApp.initNativeEngine(WavApp.java) at com.test.WavApp.create(WavApp.java) at com.badlogic.gdx.backends.iosrobovm.IOSGraphics.draw(IOSGraphics.java) at com.badlogic.gdx.backends.iosrobovm.IOSGraphics$1.draw(IOSGraphics.java) at com.badlogic.gdx.backends.iosrobovm.IOSGraphics$1.$cb$drawRect$(IOSGraphics.java) at org.robovm.apple.uikit.UIApplication.main(Native Method) at org.robovm.apple.uikit.UIApplication.main(UIApplication.java) at com.test.IOSLauncher.main(IOSLauncher.java) BUILD SUCCESSFUL Total time: 18.262 secs A snapshot of the java code in com/test/Native.java: static { System.loadLibrary("test"); Log.i("loaded libraries successfully"); } public static native long getPointer(); public static native void freePointer(long enginePointer); And the C++ code that compiles into libtest.dylib: extern "C" { JNIEXPORT jlong JNICALL Java_com_test_Native_getPointer(JNIEnv* env, jobject thiz) { return (jlong)(new PointerTest()); } JNIEXPORT void JNICALL Java_com_test_Native_freePointer(JNIEnv* env, jobject thiz, jlong enginePtr) { if ((PointerTest*)enginePtr) delete (PointerTest*)enginePtr; } } Some more info about the built shared library: Release$ file libtest.dylib libtest.dylib: Mach-O 64-bit dynamically linked shared library x86_64 And verifying the exports: $ nm -g libtest.dylib | grep Native 0000000000011ce0 T _Java_com_test_Native_freePointer 0000000000011c40 T _Java_com_test_Native_getPointer Any ideas? This has been driving me crazy for hours. I can reproduce this error on my Android device by simply using a different library and searching for that function. I'm guessing xcode is somehow hiding or stripping the symbols, but that doesn't seem to correlate with my nm output above which shows they are there. A: The solution was in front of me, as usual, in this line: libtest.dylib: Mach-O 64-bit dynamically linked shared library x86_64 Building for iOS, the architecture should be armv7+. Misconfigured xcode subproject.
[ "stackoverflow", "0063588690.txt" ]
Q: Is this the proper way to use requestAnimationFrame? I have a piece of software that I wrote which fires repaints of the screen as soon as the updating logic is finished. The issue is that the updating logic happens over 1000 times per second. The browser cannot update the screen this quickly, so I figured that a requestAnimationFrame would allow me to update the screen for the user in a slower manner. I structured the code like so: function repaint(){ now = Date.now(); elapsed = now-then; if(elapsed > 2000){ . . . //animation goes here . . . then = Date.now(); } } function startRepaint(){ then = Date.now(); requestAnimationFrame(repaint); } while(count < 1000){ . . . startRepaint(); . . . } Can I use requestAnimationFrame in this way to achieve my desired functionality? A: What you have here is not what you’re looking for. Every time you go through the while loop, you call startRepaint() which sends off a request for an animation frame. After the first call to that function you go through the while loop and call it again. By the time you have called this function a second time, you may not have received your first animation frame yet. Ideally, you want to set it up so that you call an update function which in turn sends the next request. function repaint() { ... requestAnimationFrame(repaint); } Doing it this way ensures that you always complete a full frame of your code before trying to start the next one. You could use a counter variable in the repaint function to track the iterations.
[ "ru.stackoverflow", "0000947309.txt" ]
Q: Нахождение суммы максимально близкой к числу Представим, что у нас есть n чисел. Дано определенное число k. Нам необходимо вывести на экран числа, которые в сумме будут давать максимально близкое число к k из всех возможных комбинаций. Например: Даны 4 числа: 8, 6, 3, 1. Дано число k: k=13. Ответом будет являться: 8, 3, 1, т.к. 8 + 3 + 1 = 12 - это максимально близкое к 13 число из возможных комбинаций. P.S.: определенных ограничений нет. Это не олимпиадная задача, просто нужно для проекта в школе. 1<n<50. 1<k<1000. Если будет возможность, пожалуйста напишите программу на паскале, но можно и на C++. Мне главное понять алгоритм. A: Заведите массив длиной K+1 A:array[0..K] of Integer, заполните нулями, A[0] := -1 Для каждого номинала C[i] сканируйте массив c конца. Значение P можно составить из cc=С[i] и предварительно набранной суммы pс = P - С[i], если соответствующая ячейка A[pc] ненулевая. В таком случае запишем в A[P] значение cc После нужно проверить массив с конца. Если K-я или предыдущие ячейки ненулевые - соответствующую сумму набрать можно и пройдя к началу, можно выяснить её составляющие
[ "stackoverflow", "0015718669.txt" ]
Q: Image navigation in android I just wanted to add multiple images into android activity. And I will have to navigate that images by using next and previous buttons.. Just help me with the code that how can we store multiple images and how can we navigate them? Thank you. A: One of the simplest solution is to store drawable ids in array and show one of them in ImageView. Look at this. public class MainActivity extends Activity implements View.OnClickListener { private static final int PREV_BUTTON_ID = 0; private static final int NEXT_BUTTON_ID = 1; private ImageView mImage; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mImage = (ImageView) findViewById(R.id.image); mImage.setImageResource(getFirstImageId()); Button prevButton = (Button) findViewById(R.id.btnPrev); prevButton.setId(PREV_BUTTON_ID); prevButton.setOnClickListener(this); Button nextButton = (Button) findViewById(R.id.btnNext); nextButton.setId(NEXT_BUTTON_ID); nextButton.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()) { case PREV_BUTTON_ID: mImage.setImageResource(getPrevImageId()); break; case NEXT_BUTTON_ID: mImage.setImageResource(getNextImageId()); break; default: break; } } private static final int[] sImages = { R.drawable.image1, R.drawable.image2, R.drawable.image3 }; private int mCurrentImageId; private int getFirstImageId() { return sImages[mCurrentImageId]; } private int getNextImageId() { mCurrentImageId++; if (mCurrentImageId > sImages.length - 1) { mCurrentImageId = sImages.length - 1; } return sImages[mCurrentImageId]; } private int getPrevImageId() { mCurrentImageId--; if (mCurrentImageId < 0) { mCurrentImageId = 0; } return sImages[mCurrentImageId]; } } and layout is <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Prev" android:id="@+id/btnPrev" android:layout_gravity="center_vertical"/> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/image" android:layout_gravity="center" android:layout_weight="1" android:scaleType="center" android:focusableInTouchMode="false"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Next" android:id="@+id/btnNext" android:layout_gravity="center"/> </LinearLayout>
[ "stackoverflow", "0002109148.txt" ]
Q: How to resolve communication between my WPF application and a hosted IExplorer? For a rather large project i have to figure out how (if possible) to resolve this problem. I have a full screen WPF application doing a slideshow - following an interval of e.g. 20 secs per slide. Now I have to investigate into the possibility of replacing the slideshow with a URL instead and have the user navigate the slides instead of changing slides every 10 seconds. The setup is like this: First the timed slideshow will run, e.g. 5 slides I show my web page and lets the user interact with the website (navigating) When the user "Does something (this is the problem)" the website is removed from "slide" and the original slideshow is resumed The container being shown is a WPF UserControl with an event that allows it to change to the next slide (call a Next() method). The IExporer is hosted within this control. The problem im facing is this: how do i communicate from the website that my hosting application has to call the NExt() method? The IExplorer showing the website is hosted within my WPF UserControl. Is there any way i can access some kind of event or anything else to help me determine if a particular page or a particular link has been pressed?? WebServices, files on disc, you name it, im ready to try anything :-) Any advice or possible solution is appreciated. A: If you use the WebBrowser control in your WPF application, you can call into C# classes using javascript from your html. For example, let's say you have a class similar to the following: [ComVisible(true)] public class JavaScriptBackEnd { public void onclick(string s) { MessageBox.Show(s); } } Then initialize the WebBrowser control with the following code: private void Window_Loaded(object sender, RoutedEventArgs e) { webBrowser1.ObjectForScripting = new JavaScriptBackEnd(); webBrowser1.Navigate(new Uri(@"HTMLPage1.htm")); } From HTMLPage1.htm you can now call the JavaScriptBackEnd.onclick method with the following javascript: function testclick() { window.external.onclick('blabla'); }
[ "stackoverflow", "0006943367.txt" ]
Q: window.focus() of JavaScript not working on IE9 This is my code protected void LoginButton_Click(object sender, EventArgs e) { if (DAL.DAOKullanici.Login(KullaniciTextBox.Text,SifreTextBox.Text)) { VeriyazPROTicari.Sessionlar.Variables.loginkontrol = true; Session["kullaniciAdi"] = KullaniciTextBox.Text; Session["kullaniciId"] = DAL.DAOKullanici.GetEntity(DAL.DAOKullanici.KullaniciAdiIleKullaniciIdCek(KullaniciTextBox.Text)).ID; bool main_window_open = false; if (!main_window_open) { Page.RegisterClientScriptBlock("Main_Window", "<script>" + "var newwindow; " + "newwindow = window.open('" + "/dashboard/dashboard.aspx" + "', 'main_app_window', ' toolbar=0,location=0,directories=0,status=1,menubar=0,left=1,top=1,scrollbars=" + "1" + ",resizable=1,width=" + "1280" + ",height=" + "800" + "'); " + "if (window.focus) " + "{newwindow.focus();} " + "</script>"); main_window_open = true; } HataLabel.Text = ""; } else { HataLabel.Text="Hatalı Giriş"; } } I have no problem with it except the JavaScript part. What I am trying to is after LoginButton is clicked opening dashboard.aspx and setting focus on it.And this code opens dashboard.aspx and sets focus in Google Chrome and Mozilla Firefox 4.However,when I try it on IE9 dashboard.aspx is opened but focus does not work and dashboard.aspx remains under the login page. How can I set focus on a new window on IE9? A: I have had a similar problem to this and it seemed to happen because in IE9 (and any IE) that the focus() method is run before the window is rendered. To get round this there are two ways that I can see that will fix this: Set a timer to load the focus after a small amount of time. Defer the JavaScript from being read until the window is fully rendered. The timer method to me is not my preferred choice as in my personal opinion it is messy and if the page takes longer to load than the timer you are stuck with the same problem. To implement the timer you could use something like: Page.RegisterClientScriptBlock("Main_Window", "<script>" + "setTimeout(function() { " + "var newwindow; " + "newwindow = window.open('" + "/dashboard/dashboard.aspx" + "', 'main_app_window', ' toolbar=0,location=0,directories=0,status=1,menubar=0,left=1,top=1,scrollbars=" + "1" + ",resizable=1,width=" + "1280" + ",height=" + "800" + "'); " + "if (window.focus) " + "{newwindow.focus();} " + "}, 5);" + "</script>"); I have set a delay of 5 seconds, which may be overkill. The defer method is my preferred choice as I feel it is cleaner and simpler, but it may or may not work: Page.RegisterClientScriptBlock("Main_Window", "<script type="text/javascript" defer="defer">" + "var newwindow; " + "newwindow = window.open('" + "/dashboard/dashboard.aspx" + "', 'main_app_window', ' toolbar=0,location=0,directories=0,status=1,menubar=0,left=1,top=1,scrollbars=" + "1" + ",resizable=1,width=" + "1280" + ",height=" + "800" + "'); " + "if (window.focus) " + "{newwindow.focus();} " + "</script>");
[ "math.stackexchange", "0001353300.txt" ]
Q: Please give me an example $d:C[\mathbb{R}]\times‎ C[\mathbb{R}]\longrightarrow\mathbb{R}$ Such that: I need an example $d$ such that: $$d:C[\mathbb{R}]\times‎ C[\mathbb{R}]\longrightarrow\mathbb{R}$$ $$C[\mathbb{R}]=\lbrace f:\mathbb{R}\longrightarrow\mathbb{R}\ | \ f ‎‎\text{is differentiable on }‎\mathbb{R}\rbrace$$ And $\forall f,g \in C[\mathbb{R}]$ $$1.\ \ d(f,g)=-d(g,f)$$ $$2.\ \ d(f,g)=0 \Longrightarrow f=g$$ Thanks to all of you. A: Pick an enumeration of the rationals $r_1,r_2,r_3,...$. Let $d(f,g) = 0$ if $f = g$. Else let $r_n$ be the first rational in the enumeration for which $f(r_n) \neq g(r_n)$. Define $d(f,g) = f(r_n) - g(r_n)$. This is well defined since if $f \neq g$, there must be some rational number for which $f(r) \neq g(r)$, since $f$ and $g$ are continuous, and the rationals are dense. A: The construction I present below is a little bit contrived, but I think it works. In fact, no differentiability or even continuity is needed; it works on the space of all real-valued functions. Define a function $s:C[\mathbb R]\times C[\mathbb R]\to\mathbb R$ as follows. If $f\in C[\mathbb R]$, $g\in C[\mathbb R]$, and $f=g$, then $s(f,g)\equiv 0$. If $f\neq g$, then define $s(f,g)$ to be any one point $x\in\mathbb R$ such that $f(x)\neq g(x)$. Specify also that $s(f,g)=s(g,f)$, so that one avoids considering the same pair of functions twice and assigning two different points at which they do not agree. (Note that I need to rely on the axiom of choice to construct such a function $s$.) Define another function $t:C[\mathbb R]\times C[\mathbb R]\to\mathbb R$ as follows: \begin{align*} t(f,g)\equiv\begin{cases}\phantom{-}1&\text{if $f(s(f,g))>g(f(s,g))$,}\\\phantom{-}0&\text{if $f(s(f,g))=g(f(s,g))$,}\\-1&\text{if $f(s(f,g))<g(f(s,g))$} \end{cases} \end{align*} for each $(f,g)\in C[\mathbb R]\times C[\mathbb R]$. Intuitively, $t$ “orders” each pair $(f,g)$ according as which one has a greater value at the distinguished point $s(f,g)$ at which they do not agree. [If $f(s(f,g))=g(s(f,g))$, then $f=g$ because of the way $s$ was constructed, but this doesn't really matter.] Now define the desired function $d:C[\mathbb R]\times C[\mathbb R]\to\mathbb R$ as follows for each $(f,g)\in C[\mathbb R]\times C[\mathbb R]$: \begin{align*} d(f,g)\equiv t(f,g)\times\sup_{x\in\mathbb R}\left\{\frac{|f(x)-g(x)|}{1+|f(x)-g(x)|}\right\}. \end{align*} Note that the supremum is always finite, given that the range of the function $y\mapsto y/(1+y)$ is $[0,1)$ on the domain $[0,\infty)$. Also, the supremum is zero if and only if $f(x)=g(x)$ for all $x\in\mathbb R$. Finally, the way $t$ is defined ensures that $d$ changes sign when you swap the roles of $f$ and $g$ (but the quantity defined by the supremum remains unchanged). ADDED #1: Actually, ignore the last paragraph. One can just take the desired function to be $t$. ADDED #2: Some details about how to construct the function $s$. It is well-known that the axiom of choice is logically equivalent to the well-ordering theorem. According to it, $\mathbb R$ can be endowed with such a linear order $\succsim$ that every non-empty subset of $\mathbb R$ has a well-defined least element according to this ordering. If $X\subseteq\mathbb R$ is not empty, let $\min_{\succsim} X$ be that least element. (The purpose of having this ordering $\succsim$ at hand is for one to be able to choose one and only one well-defined element from any non-empty subset of $\mathbb R$.) One can then define $s$ for each $(f,g)\in C[\mathbb R]\times C[\mathbb R]$ as follows: \begin{align*} s(f,g)\equiv\begin{cases}0&\text{if $f=g$,}\\\min_{\succsim}\{x\in\mathbb R\,|\,f(x)\neq g(x)\}&\text{if $f\neq g$.} \end{cases} \end{align*} With this definition, it is not difficult to see that $s(f,g)=s(g,f)$. This implies that the function $t$ as defined above satisfies $t(f,g)=-t(g,f)$ and $t(f,g)=0$ if and only if $f=g$.