source
sequence
text
stringlengths
99
98.5k
[ "math.stackexchange", "0001155060.txt" ]
Q: prove that $f$ is periodic A function $f\colon\mathbb{R}\to(0,\infty)$ satisfies equation $f(x)=f(x+64)+f(x+1999)-f(x+2063)$. Prove that $f$ is periodic. I'm quite sure that 1999 and 64 are random numbers (probably 1999 = year of competition) and any positive integers $p$ and $q$ would work fine. I had an idea that in general $pq$ or $pq(p+q)$ should be a period of a positive function $f$ which satisfies $f(x+p+q)+f(x)=f(x+p)+f(x+q)$, so I tried substitutions like $x=p$, $x=q$, $\dots$, $x=pq-p$, $x=pq-q$, $x=pq-p-q$ and adding obtained equations and doing reductions using others, but it was an unsuccessful attempt. I have no idea how to use the assumption that $f$ is positive. A: Robjohn's approach by the theory of linear recurrence relations (along with a minor fix, see below) is the best way of understanding this problem. For those who don't appreciate the beauty of the theory, and want a cruder / more elementary solution, consider the following: $$ f(x ) - f(x+1999) = f( x + 64 ) - f(x+2063) = f(x+128) - f(x+2127) \\= \ldots = f(x+127936) - f(x+129935)$$ $$ f(x) - f(x+64) = f( x+1999) - f(x+2063) = f(x+3998)-f(x+4062) \\ = \ldots = f(x+127936) - f(x+128000)$$ Thus, $$ f(x) - f(x+127946) = f(x+64)-f(x+128000) = f (x+1999) - f(x+129935).$$ Let $g(x) = f(x) - f( x + 127946)$. Then, $$ g(x) = g(x+64) = g( x + 1999) = g ( x + 64 A + 1999 B) $$ Since $ \gcd(64, 1999 ) = 1$, This tells us that $ g(x) = g(x+1) = g(x+ 127946)$. Thus $ f( x + 127946n) = f(x) - n g(x) $ for all integers $n$. If $ g(x) > 0 $, then for integer $n > \frac{ f(x) } { g(x) } $, we have $ f(x + 127946 n ) < 0 $. If $ g(x) < 0 $, then for integer $n < \frac{ f(x) } { g(x) } $, we have $ f(x + 127946 n ) < 0 $. Either of these statements will contradict the assumption that the image is positive (is bounded below). Hence, we have $g(x) = 0$, or that $f(x) $ is periodic with a period of 127936. Note: The condition that the image is bounded (either below or above) is necessary. For example, $f(x) = x$ clearly satisfies the functional equation, but is not periodic. Explanation of my initial comment: As deduced from the theory of linear equations, the solution set (restricted to integers, or equivalently, those with the same fractional part) is $$ f(n) = \alpha n + \beta + \sum \gamma_i \omega ^ {in} + \sum \delta_i \nu^{in}, $$ where $ \omega, \nu$ are respectively the 64th and 1999th roots of unity that are not 1. The work that we're then required to do, is to show that $ \alpha = 0 $. This is almost immediately obvious, since the rest of the terms are bounded, and we just need to take a sufficiently large $n$, to get $ f(n) < 0 $. This is why the theory of linear recurrence relations is (to me) the best way of approaching this problem. It cuts immediately to the heart of the issue, and provides clear motivation for what to do, instead of mucking around with the algebra and hoping that things work. A: The equation given says $$ (1-S^{64})(1-S^{1999})f(x)=0\tag{1} $$ where $Sf(x)=f(x+1)$. The general solution of $(1)$ is the sum of a function which has period $64$ and a function which has a period of $1999$. Since $\mathrm{lcm}(64,1999)=127936$, the sum of two such functions has period $127936$. As Calvin Lin points out, $$ (1-S)^2\mid(1-S^{64})(1-S^{1999})\tag{2} $$ Furthermore, $$ \left(x^{2063}-x^{1999}-x^{64}+1,2063x^{2062}-1999x^{1998}-64x^{63}\right)=x-1\tag{3} $$ so $1-S$ is the only multiple factor of $(1-S^{64})(1-S^{1999})$. However, $(2)$ implies that $(1)$ admits not only the aforementioned periodic functions, but also $f(x)=\alpha x$. The fact that $f(x)\ge0$ for all $x\in\mathbb{R}$ implies that the linear part must vanish; that is, $\alpha=0$. Thus, we can use $f(x)\ge0$ for all $x\in\mathbb{R}$ to conclude that $f$ is periodic.
[ "stackoverflow", "0057005892.txt" ]
Q: How to parse visually coherent text in rendered HTML? The assumption is that we have access to a rendered DOM via Javascript (such as the developer console when the page is loaded). I want to extract text from a node in way similar as we humans interpret the content visually. Example: <div> <span>This</span> <span>Text</span> <div> <span>belongs together</span> </div> </div> My algorithm should be able to recognize this text as one cluster, if it is rendered visually coherent. So it should output: "This text belongs together" instead of ["this, "text", "belongs together"] Any ideas how to proceed? I thought about computing the boundingRect for each Text Node and applying some clusterization algorithm with the viewport dimensions as reference point. A: Your idea of using bounding rectangles and relating them is a good one. This file from Chrome, spatial_navigation.cc, might interest you. "Spatial navigation" is a feature in some browsers where the focus doesn't move in tab order but in up-down-left-right space. It is analogous to your problem because it works over the DOM but cares with how the links appear, not the structure of the DOM. If you examine the primitives spatial navigation is built from, they are: Bounding rectangles. Intersecting the viewport. Whether a rectangle is to the right or below another one. Whether something is obscured. From those primitives higher level things are built up. Some more details on intersecting the viewport: The viewport is the area that's presenting content. You can use window.innerWidth and window.innerHeight for the viewport dimension in pixels and compute whether something is visible accumulating the layout and scroll offsets of it and its parents; or use Intersection Observers to find out whether an element is in the viewport. Some more details on obscured nodes: In general, detecting obscured nodes is hard. display: none; is an easy case: those nodes will have innerWidth and innerHeight of 0. Overlapped content is harder: Detect how content collides and determine the z-index of what is on top. Hardest is near-transparent content, low contrast content, and heavily filtered or transformed content. If you encounter a lot of tricky cases like this it might be simpler to capture the screen and perform OCR on it. This takes advantage of the browser's rendering pipeline to do all of the transforms and layering; you can find text in images; etc. The downside is the getDisplayMedia API doesn't work in all browsers yet and it interrupts the user with a prompt. You can still look to OCR algorithms for inspiration. OCR has to perform a similar problem: once localized characters have been recognized they have to be put into lines of text.
[ "math.stackexchange", "0000725246.txt" ]
Q: Coefficients of an elliptic curve for which the torsion group is trivial Consider an elliptic curve in the short Weierstrass form $$ y^2 = x^3 + bx + c, $$ defined over rational numbers ($b,c$ are integers). My goal is to provide an example of congruence relations on $b$ and $c$ which will provide a trivial torsion subgroup $T(E(\mathbb{Q}))$. We know that, for example, by Lutz-Nagell that by considering square divisors of the determinant $\Delta$ we can find possible points of finite order. However, this does not give any congruence relations on $b$ and $c$. Another idea is to use the reduction modulo $p$, where $p$ is a prime which does not divide $2\Delta$. Then we know that $|T(E(\mathbb{Q}))|$ divides $|E'(F_p)|$, where $E'(F_p)$ is reduced modulo $p$ curve over a field of $p$ elements. This seems to be more helpful, but I still have no idea how to find such relations. Could you provide any hints, please? A: Holden Lee had the right idea in the comments. Here is how it can be implemented. Let $E/\mathbb{Q}:y^2=x^3+x+1$. The discriminant is $-2^4\cdot 31$, so it only has bad reduction at $2$ and $31$. Moreover, When $p=5$, the curve $E/\mathbb{F}_5$ has $9$ points. When $p=7$, the curve $E/\mathbb{F}_7$ has $5$ points. Now let $E_{A,B}/\mathbb{Q}: y^2=x^3+Ax+B$ be any curve with $A,B\in\mathbb{Z}$ that satisfies $$A\equiv B\equiv 1 \bmod 35.$$ In particular, $A\equiv B\equiv 1 \bmod 5$ and $\bmod 7$. Several remarks: $E_{A,B}$ is an elliptic curve. For this we need to check that $\Delta=-16(4A^3+27B^2)\neq 0$. It suffices to realize that $-16(4A^3+27B^2)\equiv -16(4+27)\equiv -16\cdot 31\not\equiv 0 \bmod 5$ (or $\bmod 7$). In particular, $\Delta\neq 0$. Thus, $E_{A,B}$ is smooth. It also follows from our previous calculation that $\Delta\not\equiv 0 \bmod 5$ or $\bmod 7$. Hence, $E_{A,B}$ has good reduction at $5$ and $7$. Since $E_{A,B}\equiv E \bmod 5$ and $\bmod 7$, it follows that $E_{A,B}(\mathbb{F}_5)$ and $E(\mathbb{F}_5)$ have the same cardinality (equal to $9$), and so do $E_{A,B}(\mathbb{F}_7)$ and $E(\mathbb{F}_7)$ (equal to $5$). Thus, the prime-to-$5$ subgroup of $E_{A,B}(\mathbb{Q})_\text{tors}$ embeds into $E(\mathbb{F}_7)$, which has order $5$. This implies that if there is rational torsion, it must have order $5$. But the prime-to-$7$ part of $E_{A,B}(\mathbb{Q})_\text{tors}$ embeds into $E(\mathbb{F}_5)$, which has order $9$, so there is no $5$ torsion either. Hence, $E_{A,B}(\mathbb{Q})_\text{tors}$ is trivial.
[ "stackoverflow", "0021209223.txt" ]
Q: Remove bounce on scroll in browser, issue with position:fixed div I'm trying to remove the bounce when scrolling in chrome. You'll notice the top white black is fixed and behind the second yellow block as desired. What I need to do is remove the scroll to reveal the grey background in the browser without preventing the scroll over the top white block. Hope it makes sense HTML <div class="project"> </div> <div id="content"> <div class="warface"> </div><!-- END warface --> </div><!-- END content --> A: Bounce scroll in the browser is a feature of some versions of iOS / macOS. To prevent it from happening on a website we can use the following: CSS html, body { height: 100%; overflow: hidden; } #main-container { position: absolute; top: 0; bottom: 0; left: 0; right: 0; overflow: auto; } HTML <body> <div id="main-container"> ... </div> </body> Demo A: There's a simpler answer suggested here for a related question: OSX - disable inertia scroll for "single-page" webapp body { overflow: hidden; }
[ "stackoverflow", "0024404628.txt" ]
Q: Get Product id from order_item_info array When I print array of order_item_info using echo ""; print_r($profile['order_item_info']); echo""; It Prints array like This a:74:{s:7:"item_id";s:3:"108";s:8:"quote_id";s:2:"92";s:10:"created_at";s:19:"2014-06-25 08:32:20";s:10:"updated_at";s:19:"2014-06-25 08:32:20";s:10:"product_id";s:1:"6";s:8:"store_id";s:1:"1";s:14:"parent_item_id";N;s:10:"is_virtual";s:1:"0";s:3:"sku";s:10:"one-yr-sub";s:4:"name";s:8:"One Year";s:11:"description";N;s:16:"applied_rule_ids";s:0:"";s:15:"additional_data";N;s:13:"free_shipping";s:1:"0";s:14:"is_qty_decimal";s:1:"0";s:11:"no_discount";s:1:"0";s:6:"weight";s:6:"0.0010";s:3:"qty";i:1;s:5:"price";d:100;s:10:"base_price";d:100;s:12:"custom_price";N;s:16:"discount_percent";i:0;s:15:"discount_amount";i:0;s:20:"base_discount_amount";i:0;s:11:"tax_percent";i:0;s:10:"tax_amount";i:0;s:15:"base_tax_amount";i:0;s:9:"row_total";d:100;s:14:"base_row_total";d:100;s:23:"row_total_with_discount";s:6:"0.0000";s:10:"row_weight";d:0.001000000000000000020816681711721685132943093776702880859375;s:12:"product_type";s:6:"simple";s:24:"base_tax_before_discount";N;s:19:"tax_before_discount";N;s:21:"original_custom_price";N;s:12:"redirect_url";N;s:9:"base_cost";N;s:14:"price_incl_tax";d:100;s:19:"base_price_incl_tax";d:100;s:18:"row_total_incl_tax";d:100;s:23:"base_row_total_incl_tax";d:100;s:17:"hidden_tax_amount";i:0;s:22:"base_hidden_tax_amount";i:0;s:15:"gift_message_id";N;s:20:"weee_tax_disposition";i:0;s:24:"weee_tax_row_disposition";i:0;s:25:"base_weee_tax_disposition";i:0;s:29:"base_weee_tax_row_disposition";i:0;s:16:"weee_tax_applied";s:6:"a:0:{}";s:23:"weee_tax_applied_amount";i:0;s:27:"weee_tax_applied_row_amount";i:0;s:28:"base_weee_tax_applied_amount";i:0;s:30:"base_weee_tax_applied_row_amnt";N;s:11:"qty_options";a:0:{}s:12:"tax_class_id";s:1:"0";s:12:"is_recurring";s:1:"1";s:9:"has_error";b:0;s:10:"is_nominal";b:1;s:22:"base_calculation_price";d:100;s:17:"calculation_price";d:100;s:15:"converted_price";d:100;s:19:"base_original_price";d:100;s:14:"taxable_amount";d:100;s:19:"base_taxable_amount";d:100;s:17:"is_price_incl_tax";b:0;s:14:"original_price";d:100;s:32:"base_weee_tax_applied_row_amount";i:0;s:25:"discount_tax_compensation";i:0;s:20:"base_shipping_amount";d:5;s:15:"shipping_amount";d:5;s:17:"nominal_row_total";d:105;s:22:"base_nominal_row_total";d:105;s:21:"nominal_total_details";a:0:{}s:15:"info_buyRequest";s:225:"a:4:{s:4:"uenc";s:124:"aHR0cDovL2J3Y211bHRpbWVkaWEuY29tL0UvZXh0ZW5zaW9udGVzdC9pbmRleC5waHAvbXVsdGl2ZW5kb3IvdmVuZG9ycHJvZHVjdHMvc3Vic2NyaXB0aW9uLw,,";s:7:"product";s:1:"6";s:8:"form_key";s:16:"be2eDRXu1MC7OXfK";s:3:"qty";i:1;}";} This array contains product_id now i want to separate that product_id from that array . how can i do so? A: That output is not really an array, but rather a serialized, string representation of an array and so you must unserialize it first. (http://www.php.net//manual/en/function.unserialize.php) - you can do that like so: $order_item_info = unserialize($profile['order_item_info']); Then you can access the array as normal for example: print_r($order_item_info['product_id']);
[ "magento.stackexchange", "0000292348.txt" ]
Q: Magento 2.3.1, where's tinymce setup.js? In magento 2.3.1, installed on aws lightsail using bitnami. I'm trying to disable tinymce from inserting <p> tags, and the solution that many agree with is https://stackoverflow.com/a/26396255/1920003 forced_root_block : '', /* <-- Add this setting */ to js/mage/adminhtml/wysiwyg/tiny_mce/setup.js But there are many setup.js files and none look like the standard setup.js file. I really want to apply this solution because I can't upgrade to newer version off magento, I have 50 extensions that will break I can't disable the wysiwyg, there are none technical users editing the site I believe this will work, when I used to create my own hand written CMSes, I used to face a similar problem and fix it like that. A: The user hoangnm gave the right answer on my Reddit post, more testing is needed but it seems that the file I need to edit is lib/web/mage/adminhtml/wysiwyg/tiny_mce/tinymce4Adapter.js I added this option on line 206 and the problem seems, at first glance to be fixed, again more testing is needed to verify that. settings = { selector: '#' + this.getId(), theme: 'modern', 'entity_encoding': 'raw', 'convert_urls': false, 'content_css': this.config.tinymce4['content_css'], 'relative_urls': true, menubar: false, plugins: this.config.tinymce4.plugins, toolbar: this.config.tinymce4.toolbar, adapter: this, forced_root_block: '', /* <-- Add this setting */
[ "stackoverflow", "0027455773.txt" ]
Q: Converting a C char array to a String I have a Swift program that does interop with a C library. This C library returns a structure with a char[] array inside, like this: struct record { char name[8]; }; The definition is correctly imported into Swift. However, the field is interpreted as a tuple of 8 Int8 elements (typed (Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8)), which I have no idea how to transform into a String with Swift. There is no String initializer that accepts an Int8 tuple, and it doesn't seem possible to get a pointer to the first element of the tuple (since types can be heterogenous, that's not really surprising). Right now, my best idea is to create a tiny C function that accepts a pointer to the structure itself and return name as a char* pointer instead of an array, and go with that. Is there, however, are pure Swift way to do it? A: The C array char name[8] is imported to Swift as a tuple: (Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8) The address of name is the same as the address of name[0], and Swift preserves the memory layout of structures imported from C, as confirmed by Apple engineer Joe Groff: ... You can leave the struct defined in C and import it into Swift. Swift will respect C's layout. As a consequence, we can pass the address of record.name, converted to an UInt8 pointer, to the String initializer. The following code has been updated for Swift 4.2 and later: let record = someFunctionReturningAStructRecord() let name = withUnsafePointer(to: record.name) { $0.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout.size(ofValue: $0)) { String(cString: $0) } } NOTE: It is assumed that the bytes in name[] are a valid NUL-terminated UTF-8 sequence. For older versions of Swift: // Swift 2: var record = someFunctionReturningAStructRecord() let name = withUnsafePointer(&record.name) { String.fromCString(UnsafePointer($0))! } // Swift 3: var record = someFunctionReturningAStructRecord() let name = withUnsafePointer(to: &record.name) { $0.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout.size(ofValue: record.name)) { String(cString: $0) } } A: You can actually collect a tuple into an array by using Swift's variadic parameter syntax: let record = getRecord() let (int8s: Int8...) = myRecord // int8s is an [Int8] let uint8s = int8s.map { UInt8($0) } let string = String(bytes: uint8s, encoding: NSASCIIStringEncoding) // myString == Optional("12345678")
[ "stackoverflow", "0052696790.txt" ]
Q: How to specify Dagger 2 Qualifier Annotation to Provider function Constructor parameter? I have my Dagger 2 Qualifier defined @Qualifier @MustBeDocumented @kotlin.annotation.Retention(AnnotationRetention.RUNTIME) annotation class TrackerQualifier(val value: TrackerType) enum class TrackerType { INTERNAL, EXTERNAL } And it works well, with @Provides @TrackerQualifier(TrackerType.INTERNAL) @Singleton UsageTracker providesInternalTracker(InternalTracker analyticsTracker) { return new UsageTracker(analyticsTracker); } @Provides @TrackerQualifier(TrackerType.EXTERNAL) @Singleton UsageTracking providesExternalTracker(ExternalTracker eventTracker) { return eventTracker; } However, if I like to send it though to another injected module. @Provides fun provideCommonImage( imageEngine: ImageEngine, externalUsageTracking: UsageTracking) = CommonImage(imageEngine, externalUsageTracking) It will compile fail, as it doesn't know is the externalUsageTracking: UsageTracking above is INTERNAL or EXTERNAL. How could I annotate it to the parameter? A: try to explicit the qualifier. @Provides fun provideCommonImage( imageEngine: ImageEngine, @TrackerQualifier(TrackerType.EXTERNAL) tracker: UsageTracker) = CommonImage(imageEngine, tracker)
[ "pt.stackoverflow", "0000074412.txt" ]
Q: Uncaught RangeError: Maximum call stack size exceeded Uncaught RangeError: Maximum call stack size exceeded function updateAnalysers(id) { var canvas = document.getElementById(id); canvasWidth = canvas.width; canvasHeight = canvas.height; analyserContext = canvas.getContext('2d'); { var fils = Math.round(canvasWidth / 3); var byts = new Uint8Array(analyserNode.frequencyBinCount); analyserNode.getByteFrequencyData(byts); analyserContext.clearRect(0, 0, canvasWidth, canvasHeight); analyserContext.fillStyle = 'GRAY'; analyserContext.lineCap = 'round'; var multiplier = analyserNode.frequencyBinCount / fils; for (var i = 0; i < fils; ++i) { var magnitude = 0; var offset = Math.floor( i * multiplier ); for (var j = 0; j< multiplier; j++) magnitude += byts[offset + j]; magnitude = (magnitude / multiplier) + 2; analyserContext.fillRect(i * 3, canvasHeight, 1, -magnitude); } } rafID = window.requestAnimationFrame( updateAnalysers("analyser") ); } O erro ocorre nesta última linha: rafID = window.requestAnimationFrame( updateAnalysers("analyser") ); Como corrigilo? A: O erro é porque você está chamando a função dentro dela própria, infinitas vezes, aqui: rafID = window.requestAnimationFrame( updateAnalysers("analyser") ); Na verdade o requestAnimationFrame espera receber uma referência para uma função, mas em vez de passar uma referência você está invocando a função. Passar a referência seria assim: rafID = window.requestAnimationFrame( updateAnalysers ); Porém nesse caso você deixaria de passar o parâmetro. Para passar com o parâmetro engessado, você pode fazer um bind: var funcaoDeUpdate = updateAnalysers.bind(null, id); rafID = window.requestAnimationFrame( funcaoDeUpdate );
[ "stackoverflow", "0002164063.txt" ]
Q: XStream private attributes in Java How does XStream gets my object values since they are private? import com.thoughtworks.xstream.XStream; class Person { private String name; public Person(String n) { name = n; } } public class Main { public static void main(String[] args) { XStream stream = new XStream(); Person p = new Person("Joe"); String xml = stream.toXML(p); System.out.println(xml); } } and how do i highlight and indent my code in stackoverflow? A: How does XStream gets my object values since they are private? It uses reflection. See the Converter listing for details on how XStream convers various java types How do i highlight and indent my code in stackoverflow? Highlight the text and press the code button that looks like 101010
[ "stackoverflow", "0053968745.txt" ]
Q: What is the Excel formula based on the value of a cell between a specific range of numbers? I am using Excel 2016 and I need a formula for cell W2 based on the value of cell C2, with the following logic: if cell C2 is between 1 and 10, then it should output "R", if cell C2 is between 11 and 20, then "B", if cell C2 is between 21 and 30, then "Y", if cell C2 is between 31 and 40, then, "G" I am tinkering with the IF(AND..) formula but I am not getting it right. This is what I have right now: =IF(C2<=10,"R",IF(AND(C2>10,C2<=20,"B"),IF(AND(C2>20,C2<=30),"Y",IF(AND(C2>30,C2<=40),"G","!")))) A: I think that you should do something like this instead (e.g. using VLOOKUP): =VLOOKUP(ROUNDUP(C2, -1), $C$4:$D$7, 2, FALSE) Where which avoids the use of deeply-nested if-else statements. I mean, what are you going to do if you need to do so for 20 letters? A 20-level nested if-else statement? No. A: This should do the trick: =IF(C2<=10,"R",IF(AND(C2>10,C2<=20),"B",IF(AND(C2>20,C2<=30),"Y",IF(AND(C2>30,C2<=40),"G","!")))) You can always double-check functions by double-click on the function suggestions and see if you used all brackets correctly:
[ "stackoverflow", "0014917197.txt" ]
Q: Move folders in Subversion using Tortoise I've been creating milestones of trunk inside branches folder. But they are getting numerous, and are all related, so I decided to create a /branches/milestones/1.0.0/ and throw all 1.0.0 version's milestones in there. If it was a rename, Tortoise has the rename feature. But how about moving all files inside a folder? how to make Subversion understand it and keep track instead of think it was a delete-add? A: In Subversion, rename & move are synonymous. Both are implemented as a copy with history immediately followed by a delete.
[ "stackoverflow", "0003490327.txt" ]
Q: Assembly binding redirect does not work I'm trying to set up an assembly binding redirect, using the following app.config: <configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="Microsoft.AnalysisServices" PublicKeyToken="89845dcd8080cc91" /> <bindingRedirect oldVersion="10.0.0.0" newVersion="9.0.0.0" /> </dependentAssembly> </assemblyBinding> </runtime> </configuration> I'm running the program on a machine with version 9.0.242.0 in the GAC, with the specified public key token. The CLR doesn't seem to be even trying to redirect the binding to use that version though. Here is what I get in fuslogvw.exe: LOG: This bind starts in default load context. LOG: Using application configuration file: \Debug\AssemblyRedirectPOC.exe.Config LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v2.0.50727\config\machine.config. LOG: Post-policy reference: Microsoft.AnalysisServices, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91 LOG: GAC Lookup was unsuccessful. LOG: Attempting download of new URL /Debug/Microsoft.AnalysisServices.DLL. LOG: Attempting download of new URL /Debug/Microsoft.AnalysisServices/Microsoft.AnalysisServices.DLL. LOG: Attempting download of new URL /Debug/Microsoft.AnalysisServices.EXE. LOG: Attempting download of new URL /Debug/Microsoft.AnalysisServices/Microsoft.AnalysisServices.EXE. LOG: All probing URLs attempted and failed. When I tried putting the 9.0.242.0 version dll in the probe path, I get this instead: LOG: Assembly download was successful. Attempting setup of file: \Debug\Microsoft.AnalysisServices.dll LOG: Entering run-from-source setup phase. LOG: Assembly Name is: Microsoft.AnalysisServices, Version=9.0.242.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91 WRN: Comparing the assembly name resulted in the mismatch: Major Version ERR: The assembly reference did not match the assembly definition found. ERR: Failed to complete setup of assembly (hr = 0x80131040). Probing terminated. Note that I also tried changing the redirect to use "9.0.242.0" instead of "9.0.0.0" in the app.config and that didn't work, although I don't think it should make any difference. From what I understand the whole point of redirecting a binding is to use a version that does not match that which the program was built with. Am I completely missing something here? Is what I'm trying to do possible, and if so, any idea of why it's not working? Cheers, Adam A: Any typo in configuration xml can be a cause. Loader just can't see your configuration. I also had a hour of headache until I realize that the error was in character "=" instead of "-" in schema name: <assemblyBinding xmlns="urn:schemas=microsoft-com:asm.v1"> Just check carefully all attribute names and values. I guess "PublicKeyToken" should be "publicKeyToken" This should work: <configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="Microsoft.AnalysisServices" publicKeyToken="89845dcd8080cc91" /> <bindingRedirect oldVersion="10.0.0.0" newVersion="9.0.0.0"/> </dependentAssembly> </assemblyBinding> </runtime> </configuration> A: Make sure your <configuration> tag has no namespace attribute. Otherwise any <assemblyBinding> tag will be ignored. Wrong: <configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"> Right: <configuration> (from https://stackoverflow.com/a/12011221/150370) A: I encountered assembly binding redirect not working, because of a missing namespace on the assemblyBinding element. Correct <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="TIBCO.Rendezvous" publicKeyToken="1a696d1f90f6158a"/> <bindingRedirect oldVersion="1.0.0.0-1.0.3191.28836" newVersion="1.0.3191.28836"/> </dependentAssembly> Incorrect Note missing: xmlns="urn:schemas-microsoft-com:asm.v1" <assemblyBinding> <dependentAssembly> <assemblyIdentity name="TIBCO.Rendezvous" publicKeyToken="1a696d1f90f6158a"/> <bindingRedirect oldVersion="1.0.0.0-1.0.3191.28836" newVersion="1.0.3191.28836"/> </dependentAssembly>
[ "stackoverflow", "0005515310.txt" ]
Q: Is there a standard function to check for null, undefined, or blank variables in JavaScript? Is there a universal JavaScript function that checks that a variable has a value and ensures that it's not undefined or null? I've got this code, but I'm not sure if it covers all cases: function isEmpty(val){ return (val === undefined || val == null || val.length <= 0) ? true : false; } A: You can just check if the variable has a truthy value or not. That means if( value ) { } will evaluate to true if value is not: null undefined NaN empty string ("") 0 false The above list represents all possible falsy values in ECMA-/Javascript. Find it in the specification at the ToBoolean section. Furthermore, if you do not know whether a variable exists (that means, if it was declared) you should check with the typeof operator. For instance if( typeof foo !== 'undefined' ) { // foo could get resolved and it's defined } If you can be sure that a variable is declared at least, you should directly check if it has a truthy value like shown above. Further read: http://typeofnan.blogspot.com/2011/01/typeof-is-fast.html A: The verbose method to check if value is undefined or null is: return value === undefined || value === null; You can also use the == operator but this expects one to know all the rules: return value == null; // also returns true if value is undefined A: function isEmpty(value){ return (value == null || value.length === 0); } This will return true for undefined // Because undefined == null null [] "" and zero argument functions since a function's length is the number of declared parameters it takes. To disallow the latter category, you might want to just check for blank strings function isEmpty(value){ return (value == null || value === ''); }
[ "stackoverflow", "0019529961.txt" ]
Q: Need to get Specific lines of text from a text file C# I have a text file that looks like this: DeltaV User List - 17 Jun 2013 SUPPLY_CHAIN UserID Full Name BAINC C M B BEEMANH H B CERIOJI J M C LADUCK K L MAYC C M NEWTONC C N DeltaV User List - 17 Jun 2013 FERM_OPER UserID Full Name POULIOTM M P TURNERM7 M T I need to get the individual users for each of these sections in C# and I'm not sure how to do it. I was using the StreamReader class and it worked for getting the Area name (the word in all caps) but I cannot seem to get all of the users. I have a user class that has 2 strings Name & Area and I'm trying to make a list of user objects. This is what I've tried so far: (I've declared a list of User objects earlier in the code) // read user list text file var userReader = new StreamReader(File.OpenRead(UserListPath)); while(!userReader.EndOfStream) { var line = userReader.ReadLine(); var newUser = new User(); if(line.Contains("DeltaV User List")) { var Area = userReader.ReadLine(); newUser.Area = Area; userReader.ReadLine(); userReader.ReadLine(); userReader.ReadLine(); var userid = userReader.ReadLine(); Console.WriteLine(userid); var name = userid.Split(' '); Console.WriteLine(name[0]); newUser.UserId = name[0]; } Users.Add(newUser); } Oh, I only need to get the UserId, not the Full Name as well. A: Edited Here is a little piece of code that should achieve what you need : using (var fileStream = File.OpenRead(UserListPath)) using (var userReader = new StreamReader(fileStream)) { string currentArea = string.Empty; string currentToken = string.Empty; while (!userReader.EndOfStream) { var line = userReader.ReadLine(); if (!string.IsNullOrEmpty(line)) { var tokenFound = Tokens.FirstOrDefault(x => line.StartsWith(x)); if (string.IsNullOrEmpty(tokenFound)) { switch (currentToken) { case AreaToken: currentArea = line.Trim(); break; case UserToken: var array = line.Split(' '); if (array.Length > 0) { Users.Add(new User() { Name = array[0], Area = currentArea }); } break; default: break; } } else { currentToken = tokenFound; } } } } This program assumes that your input file ends with a line return. It uses these constants that you will have to declare in your class or anywhere your want by modifying their accessors (private into public for instance) : private const string AreaToken = "DeltaV"; private const string UserToken = "UserID"; private List<string> Tokens = new List<string>() { AreaToken, UserToken }; Of course, i've done it my way, there's probably lots of better way of doing it. Improve it the way you want, it's just a kind of draft that should compile and work. Among other things, you'll notice : the use of using keyword, which is very useful to make sure your memory/ressource/file handles are properly free. i tried to avoid the use of hard coded values (that's the reason why i use constants and a reference list) i tried to make it so you just have to add new constants into the Token reference list (called Tokens) and to extend switch cases to handle new file tokens/scenarios Finally, do not forget to instanciate your User list : List<User> Users = new List<User>();
[ "stackoverflow", "0010775203.txt" ]
Q: Android: Developing a login screen like Facebook I' trying to develop a screen on my android app like facebook login (App iPhone/Android) App Facebook Screenshot How can I draw this separator line between these two edittexts: e-mail and password? Thanks!! A: to make a such effect you have just to make your own 9-patch drawable. i have alreaady done such thing on my app see this Layout top drawable unpressed Layout top drawable pressed Layout bottom drawable unpressed Layout bottom drawable pressed The only thing that left is to build two selector one for the top edit text and another for the bottom edittext and set them as backround for your edittext: selector_top_editText.xml: <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/layout_top_pressed" android:state_pressed="true"/> <item android:drawable="@drawable/layout_top_normal"/> </selector> selector_bottom_editText.xml: <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/layout_bottom_pressed" android:state_pressed="true"/> <item android:drawable="@drawable/layout_bottom_normal"/> </selector> For your login page you can use this layout <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:ems="10" android:inputType="textPersonName" android:background="@drawable/layout_top_selector" /> <EditText android:id="@+id/editText2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:ems="10" android:inputType="textPassword" android:background="@drawable/layout_bottom_selector" android:layout_below="@id/editText1"/> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:layout_marginBottom="46dp" android:text="Login" /> </RelativeLayout> check this and keep me in touch if you find problems Cheers
[ "stackoverflow", "0016762375.txt" ]
Q: Custom Control in WPF I have just started to learn WPF. I have a button with image. like Image+Text <Button Height="67" Name="Button1" Width="228" HorizontalContentAlignment="Left"> <StackPanel Orientation="Horizontal" > <Image Source="Images/add.png" Stretch="Uniform"></Image> <TextBlock Text=" Create Company" VerticalAlignment="Center" FontSize="20"></TextBlock> </StackPanel> </Button> Now I want to add many more buttons in the above format. So I have to write the same code again and again. So I decided to have a customButton to do my job easily. I tried to create the custom control. I added a property named Image there. Now how should I give value to that property? Am I going on the wrong way? A: Here you have tutorial how to create a custom control. [1.] Add new item "Custom Control (WPF)" with name "ButtonImg". After this step, VS create for you two files: "ButtonImg.cs" and "/Themes/Generic.xaml". [2.] Add few dependency properties to "ButtonImg.cs" file: I created properties to: image source, text, image width and height. public class ButtonImg : Control { static ButtonImg() { DefaultStyleKeyProperty.OverrideMetadata(typeof(ButtonImg), new FrameworkPropertyMetadata(typeof(ButtonImg))); } public ImageSource ImageSource { get { return (ImageSource)GetValue(ImageSourceProperty); } set { SetValue(ImageSourceProperty, value); } } public static readonly DependencyProperty ImageSourceProperty = DependencyProperty.Register("ImageSource", typeof(ImageSource), typeof(ButtonImg), new PropertyMetadata(null)); public string Text { get { return (string)GetValue(TextProperty); } set { SetValue(TextProperty, value); } } public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(ButtonImg), new PropertyMetadata(string.Empty)); public double ImageWidth { get { return (double)GetValue(ImageWidthProperty); } set { SetValue(ImageWidthProperty, value); } } public static readonly DependencyProperty ImageWidthProperty = DependencyProperty.Register("ImageWidth", typeof(double), typeof(ButtonImg), new PropertyMetadata((double)30)); public double ImageHeight { get { return (double)GetValue(ImageHeightProperty); } set { SetValue(ImageHeightProperty, value); } } public static readonly DependencyProperty ImageHeightProperty = DependencyProperty.Register("ImageHeight", typeof(double), typeof(ButtonImg), new PropertyMetadata((double)30)); } [3.] In this step you must create Template for your new custom control. So you must edit following file "/Themes/Generic.xaml": <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfButtonImg"> <Style TargetType="{x:Type local:ButtonImg}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:ButtonImg}"> <Button> <Button.Content> <StackPanel Orientation="Horizontal"> <Image Source="{TemplateBinding ImageSource}" Height="{TemplateBinding ImageHeight}" Width="{TemplateBinding ImageWidth}" Stretch="Uniform" /> <TextBlock Text="{TemplateBinding Text}" Margin="10,0,0,0" VerticalAlignment="Center" FontSize="20" /> </StackPanel> </Button.Content> </Button> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary> [4.] Example of using this new custom control is following: First you must add appropriate namespace: xmlns:MyNamespace="clr-namespace:WpfButtonImg" Now you can use it like this: <MyNamespace:ButtonImg ImageSource="/Images/plug.png" Text="Click me!" />
[ "stackoverflow", "0029911822.txt" ]
Q: Django Rest Logout , Integrate Rest under admin Project Url is, urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ) My App Url is urlpatterns = [ url(r'^snippets/$', views.snippet_list),] While openning the browsable api ( 127.0.0.1:8000/snippets/) it ask the username and password to authenticate but while clicking the logout it was not logged out. And how to implement /snippets under admin section like After logged into admin only I can able to access the snippets ( Integrating this API service under django admin) Thanks in Advance A: Take a look at the Django Rest Framework (DRF) permissions documentation. You need to figure out what your default permissions model is for your view and then change the global default or override it appropriately for a specific view. Also, is there a reason you're not using the DRF router in urls.py?
[ "stackoverflow", "0061844515.txt" ]
Q: how to iterate in pandas dataframe columns i need do some operations with my dataframe my dataframe is df = pd.DataFrame(data={'col1':[1,2],'col2':[3,4]}) col1 col2 0 1 3 1 2 4 my operatin is column dependent for example, i need to add (+) .max() of column to each value in this column so df.col1.max() is 2 and df.col2.max() is 4 so my output should be: col1 col2 0 3 7 1 4 8 i have been try this: for i in df.columns: df.i += df.i.max() but AttributeError: 'DataFrame' object has no attribute 'i' A: you can chain df.add and df.max and specify the axis which avoids any loops. df1 = df.add(df.max(axis=0)) print(df1) col1 col2 0 3 7 1 4 8
[ "opendata.stackexchange", "0000010088.txt" ]
Q: Hate crime dataset in the United States I'm looking for a dataset listing hate incidents in the United States with as many following fields as possible: time and date location demographics on attacker(s) demographics on victim(s), or attacked community type of hate incidents legal outcome victim injuries Hate incidents can be based on the following: disability race religion transgender identity sexual orientation. A: List of places to gather that information: Hate Crime Publications & Products - Bureau of Justice Statistics Hate Crime - FBI:UCR Hate/Extremism Reports - Center for the Study of Hate & Extremism Search NCJRS (National Criminal Justice Reference Service) for Keyword "Hate" Public Safety Open Data Portal Lists Police Forces Involved That Publish Hate Crime Data Southern Poverty Law Center (SPLC) Hate Map A: We've just launched a workspace on data.world with the Anti-Defamation League for others to collaborate with us on exploring the data on this topic - would love to hear your thoughts on the discussion thread! https://data.world/adl/hate-crime-laws-and-statistics
[ "stackoverflow", "0035416962.txt" ]
Q: Error while cleaning images from docker When I run docker rmi $(docker images --filter "dangling=true" -q --no-trunc) from the accepted answer to this question I sometimes get docker: "rmi" requires a minimum of 1 argument. am I doing something wrong? How can I prevent this from happening? A: The problem with that answer is that it runs docker rmi even though there might not be any images to delete (that is when the output from docker images --filter.... is empty), and that is when you get the error. @rubicks solution to that question doesn't do a much better job, but points to a usable alternative: docker images --no-trunc --all --quiet --filter="dangling=true" | xargs --no-run-if-empty docker rmi the --no-run-if-empty argument to xargs does what it says and prevents that error from happening, even if you run it and you have nothing to clean. I have the following aliases, because the above is a bit too much to type every time I want to use it (the first is for removing unused containers): alias drrm='docker ps --no-trunc --all --quiet --filter="status=exited" | xargs --no-run-if-empty docker rm' alias drrmi='docker images --no-trunc --all --quiet --filter="dangling=true" | xargs --no-run-if-empty docker rmi'
[ "superuser", "0001148393.txt" ]
Q: How do I get the same CLI tools in a {{Powershell::Powershell as Admin}} tab as in a {{cmd::Cmder as Admin}} tab in Cmder? I recently installed Cmder and I've been using the {{cmd::Cmder as Admin}} task for my tabs because it comes with a lot of nice bash-isms that I find missing in PowerShell. E.g. touch, du, ssh, head, tail. However, I'm aware that PowerShell is the modern choice and is a lot more powerful than plain cmd for Windows-centric tasks. However, I lament not being able to use the bash commands I'm familiar with. Is there a way to get the Cmder tools in my Cmder PowerShell tabs? A: [Oops... sorry, I answered the wrong question. I'm going to leave it anyway because I think it is relevent] Coming from years of use of Cygwin Zsh as my primary shell, I faced the same transition issue. There are at least a couple of approaches. The one I took was to simply bite the bullet and commit myself fully to Powershell. The first thing I did was create a tiny script which removes all the DOS & bash "transition" aliases to keep myself from cheating. Then I added a call to this script in my profile. After that it was just a matter of incrementally learning idiomatic powershell habits to replace my old idiomatic zsh habits. I haven't found anything that I can't do, though sometimes the ps idioms are a bit bulkier than I'd wish. The other approach is to install either Cygwin (my preference) or UnxUtils. Either of these have exact syntactic equivalents of almost all the gnu utilities which can be invoked directly from the powershell command line (or a ps script). Still, my recommendation... force yourself to learn the powershell equivalents
[ "stackoverflow", "0011423419.txt" ]
Q: TeeChart examples I have TeeChart 8 Standard as part off Delphi XE2, recently asked for advice regarding features of TeeChart and was told I could look in the All Features\etc... to find example code. I downloaded the zipped TeeChart2010_Examples file from Steema, and ran the Tee9New.exe which shows the All features... cascade of sub-directories. In this I can find examples of what I want, but the SourceCode tab suggests I need to install TChart Pro to see the source code. Is the source code of the examples only available after installation of the Pro version? I believe I could install the Evaluation version to confirm this, but don't want to 'mess' with my already functioning Standard version that came with Delphi. A: TeeChart Std evaluation version also comes with the source code for the demo. It's available at, for example, C:\Program Files\Steema Software\TeeChart Standard 2012 for RAD XE2\Examples\Features. However, if you need the source code to a specific demo please let me know which is it and I'll send it to you.
[ "stackoverflow", "0038452428.txt" ]
Q: How to launch one thread group from another in jmeter I am very new to Jmeter. In my application I have two scenarios. 1. Create: Here we book a hotel room. After booking application returns a transaction ID. 2. Cancel: We need to pass the transaction Id to the application to cancel booking. I want to test with jmeter in such a way that after a create call is made, the cancel call of the respective create is called with the generated transaction ID automatically. Don't have any clue how to do this. Application is written using spring, REST web service. There is one BeanShell Preprocessor in my existing .jmx file. Using that jmx file I call the create & cancel service individually. A: Normally you can use a variable to store a string and use it later on, however it is not possible to pass a variable from one thread to another. To do this you need to use a property: this site explains how. Of course if you need to save a lot of transaction ID's it might make more sense to have the first thread group store them in a csv file and have the second one read them from the file. Have a look at the CSV Data Set Config.
[ "stackoverflow", "0015486910.txt" ]
Q: Repository and Unit Of Work pattern in non MVC projects Can we use Repository and Unit Of Work pattern in non ASP.Net MVC projects? If so, please let me know how to implement this (project layers/structure) in a normal ASP.NET project. A: Of course you can and the structure is identical. I would have a data repository project, a models project and a business logic project. my web app would then talk to the model and business layers. i throw in AutoMapper in this type of app to translate between the model and data models. i would then return the model back to the asp page and i would implement MVP there too. this is a very high level look at your issue without knowing anything about your project or environment. you might need to give us more to go on OP if you want a more in depth answer http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/a25b0ea8-4bf8-4d29-945a-d65daf89c9ea/ http://www.codeproject.com/Articles/14642/Model-View-Presenter-with-ASP-NET
[ "pt.stackoverflow", "0000132158.txt" ]
Q: Problema com alocação dinâmica Preciso fazer um código em que o usuário preencha um vetor quantas vezes ele quiser, porém o código para de rodar. Se eu registrar apenas 3 valores, como (1) (2) (3) ele funciona normalmente, mas em alguns momentos (não existe padrão) o programa para de ser executado. Não consegui achar minha falha. Segue o código: #include<stdio.h> main(){ int *vetor, i, d, contador=0; char c; vetor=NULL; do{ if(contador==0) vetor=malloc(1*sizeof(int)); else realloc(vetor,1*sizeof(int)); printf("Digite um valor para salvar no vetor: "); scanf("%d", &d); *(vetor+contador)=d; contador++; printf("Deseja cadastrar mais um numero? "); scanf(" %c", &c); system("pause"); } while(c == 's' || c == 'S'); system("cls"); for(i=0; i<contador; i++) printf(" (%d) ", vetor[i]); } A: O principal problema e que a realocação está usando o mesmo tamanho sempre, não está aumentando e não está atribuindo para uma variável, esta realocação se perde, isto gera o erro. Tem maneiras melhores para resolver isto, mas para um exercício está bom. Mude: vetor = realloc(vetor, sizeof(int) * contador + 1); Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura. Reformulei pra um jeito que eu gosto mais e bem mais organizado. Em código real eu faria um pouco diferente ainda
[ "stackoverflow", "0009092869.txt" ]
Q: how to display the data returned by get_by_user_id() in DataMapper Code Igniter? I am new to code igniter data mapper. I have a table called user, and I am trying to retrieve data from the database table and show them to the user. Here is what I have in the model: $u=new User(); $results=$u->get_by_user_id($id); //$results here will be set to huge bunch of none sense data( which also includes the row that I am looking for as well) if ($u->exists()) { foreach ($results->all as $row){ $data['user']['first_name']=($row->user_first); //this where I am stuck .. $data['user']['last_name']=($row->user_last);//this is also where I am stuck.. } I don't know how to treat results to get a required fields I am looking for and store them in the $data I am passing to the user to view. Thanks! A: When you call get_by_x() on the model, the fields will be populated with data and you can access them like this: $u = new User(); $u->get_by_user_id($id); if($u->exists()) { // you can access the table columns as object fields $data['user']['first'] = $u->first; $data['user']['last'] = $u->last; } else { $data['error'] = 'No such user!'; } Have a look at the documentation which is really helpful: see Get and Get By. Also, DataMapper expects all tables to have an id column: see Table Naming Rules. If your column is named id you should then call $u->get_by_id($id) instead of $u->get_by_user_id($id).
[ "stackoverflow", "0002654074.txt" ]
Q: Why does the VS2005 debugger not report "base." values properly? (was "Why is this if statement failing?") I'm working on an existing class that is two steps derived from System.Windows.Forms.Combo box. The class overrides the Text property thus: public override string Text { get { return this.AccessibilityObject.Value; } set { if (base.Text != value) { base.Text = value; } } } The reason given for that "get" is this MS bug: http://support.microsoft.com/kb/814346 However, I'm more interested in the fact that the "if" doesn't work. There are times where "base.Text != value" is true and yet pressing F10 steps straight to the closing } of the "set" and the Text property is not changed. I've seen this both by just checking values in the debugger, and putting a conditional breakpoint on that only breaks when the "if" statement's predicate is true. How on earth can "if" go wrong? The class between this and ComboBox doesn't touch the Text property. The bug above shouldn't really be affecting anything - it says it's fixed in VS2005. Is the debugger showing different values than the program itself sees? Update I think I've found what is happening here. The debugger is reporting value incorrectly (including evaluating conditional breakpoints incorrectly). To see this, try the following pair of classes: class MyBase { virtual public string Text { get { return "BaseText"; } } } class MyDerived : MyBase { public override string Text { get { string test = base.Text; return "DerivedText"; } } } Put a breakpoint on the last return statement, then run the code and access that property. In my VS2005, hovering over base.Text gives the value "DerivedText", but the variable test has been correctly set to "BaseText". So, new question: why does the debugger not handle base properly, and how can I get it to? A: Use String.Compare for comparing strings. There are subtleties with strings. I cannot tell you why the if would fail, other than that your strings might not really be 'equal' A: ... and this just about wraps up my new question. Ah well.
[ "stackoverflow", "0006564246.txt" ]
Q: add text in a button with image? objective-c how would you write some text in a UIButton that already contains an image? i'd like to have a button like "save", but i also have an image that is the "button", so i put a UIButton on the view in IB, then either text first or image first, the text never shows up in front of the image. How would you do that? Thanks ! A: Create a UILabel with the text you need, then add it as a subview to your UIButton. You can do that programmatically in the -viewDidLoad function of the view containing your UIButtons.
[ "stackoverflow", "0032418853.txt" ]
Q: grouping multiple variables - R I want to group a data frame of different topics and different users to generate a table of relative importance of each user in that topic, e.g my data frame is Topic User A U1 A U2 B U2 A U1 B U1 A U1 And I want to reduce it to Topic User Importance A U1 0.75 A U2 0.25 B U1 0.5 B U2 0.5 Can anybody point me how to do it using R preferably dplyr? A: Here's a quick data.table alternative approach library(data.table) setDT(df)[, as.data.table(table(User)/.N), by = Topic] # Topic User N # 1: A U1 0.75 # 2: A U2 0.25 # 3: B U1 0.50 # 4: B U2 0.50 This is basically just runs table(User) by group and divides it by groups size .N Or simiarly with dplyr df %>% group_by(Topic) %>% do(data.frame(table(.$User)/length(.$User))) # Source: local data frame [4 x 3] # Groups: Topic [2] # # Topic Var1 Freq # (fctr) (fctr) (dbl) # 1 A U1 0.75 # 2 A U2 0.25 # 3 B U1 0.50 # 4 B U2 0.50 A: One way to handle this is to count by topic / topic-user separately and join results: topic_count <- df %>% group_by(Topic) %>% summarise(total=n()) user_count <- df %>% group_by(Topic, User) %>% summarise(cnt=n()) user_count %>% left_join(topic_count, by="Topic") %>% mutate(Importance=cnt/total) %>% select(-cnt, -total) # Drop obsolete columns ## Topic User Importance ## 1 A U1 0.75 ## 2 A U2 0.25 ## 3 B U1 0.50 ## 4 B U2 0.50 A: Yet another way: as.data.frame(prop.table(table(DF), margin = 1)) # Topic User Freq #1 A U1 0.75 #2 B U1 0.50 #3 A U2 0.25 #4 B U2 0.50
[ "stackoverflow", "0058467395.txt" ]
Q: strange characters in DNS answer I have found example of DNS client in c: https://www.binarytides.com/dns-query-code-in-c-with-linux-sockets/ And I don't understand one thing in function ReadName(). There *reader is pointer to start of DNS answer, where is URL who’s IP address we wish to find. I don't understand condition which is there: if(*reader>=192) { offset = (*reader)*256 + *(reader+1) - 49152; //49152 = 11000000 00000000 ;) reader = buffer + offset - 1; jumped = 1; //we have jumped to another location so counting wont go up! } else { name[p++]=*reader; } What it mean, when some char of URL is greater than 192? And what exactly we do (in condition)? Thanks! A: There are no "strange" characters in the DNS. The code you show is related to pointers and how names are compressed in DNS packets. You need to read RFC 1035, and specifically §4.1.4 "Message compression". If a two bytes sequence starts with the first two bit set (that is decimal value 128 + 64 = 192 for one byte), then the rest is a pointer to another place in the message where the name is stored. This is exactly what the code above does.
[ "gardening.stackexchange", "0000013354.txt" ]
Q: What is this fungus in my indoor snake plant's pot, and is it harmful? I've had a snake plant growing indoors for about a year. Twice now in the last month I've had to remove some fungus that sprouted over the surface. The planter is located next to a patio door, which was open (we also have a screen door) for most of the spring, but is kept closed in the summer/winter. Is this bad? Should I get rid of the plant, or perhaps re-pot it? What kind of fungus is this? A: The fungus is digesting partly decomposed organic matter in the potting mix. They do not harm the plant. Also, the parts above the ground is only the reproductive body, you can remove them if you don't like the look, and the mycelia will still work on the medium. Throwing away or repotting the plant is unnecessary, the fungus is beneficial if anything, because it breaks down the unusable material in the pot into something the plant can access. I'm not certain what species that is. The picture is not very clear. This isn't very important, but if you want, post closeup picture of the fungus so we can try for a positive id. Your Sansevieria trifasciata cultivar is showing slight signs of etiolation. They tolerate dense shade, but dense shade looks a lot brighter indoors than out. Also, they (unusual) like to be root-bound. From the picture, it looks like you are doing a good job keeping the mix dry, but I'd provide just a little more light.
[ "stackoverflow", "0028921308.txt" ]
Q: vspace attribute applied to only one image not to both I want only one image to have 20px margin on top and bottom. However for some reasons, it applies to both images. Is it possible to apply vspace attribute only to one image without affecting the image next to it ? <p>This is a sample text. This is a sample text</p> <img src="images/cloudy.png" hspace="20" align="middle" alt="Cloud" /> <img src="images/house.png" hspace="20" vspace="20" align="middle" alt="House" /> <p>This is a sample text. This is a sample text</p> Here is how it looks and if you see both images have the same 20px margin on top and bottom A: You would be better off using CSS. But, given what you have, when you use: vspace="20" on one of the images, then it pushes the surrounding paragraphs away vertically. Then the: align="middle" aligns both divs in the middle. If you look at the images in Developer Tools, you can see that the first image has no vertical spacing.
[ "gaming.stackexchange", "0000026973.txt" ]
Q: Do I need an official Hard Drive for Xbox 360? Possible Duplicate: Installing a hard-disk on Xbox 360 4 GB I am thinking of getting a new hard drive for my Xbox 360 (4 GB). I was looking at http://www.xbox.com/en-US/Xbox360/Accessories/HardDrives/Home and it looks like they only have 1 which seems overpriced as I could purchase a 1 TB hard drive for the same amount. Do I have to get that one to work for my Xbox or can I buy a cheap 3rd party one? A: Sadly, the Xbox 360 only works with certain models of hard drives. I know that the old (fat?) Xbox 360s could use certain Seagate drives and certain programs to make it think it's an Xbox 360 drive. However, I believe this trick no longer works for the Xbox 360 S. Sony saw this decision and decided to use the PS3's ability to use any 2.5" drive in their early PS3 advertising.
[ "stackoverflow", "0045820369.txt" ]
Q: Data frame based on transitivity property of I have a data frame as A: V1 V2 1 3 1 4 3 4 1 6 6 5 I want output which satisfies transitive property on V1 and V2 B: V1 V2 V3 1 3 4 A: The idea is you select one source and try to find the transitivity with two targets. if those are the same then you have the right combination. I add additional columns for debug purpose, but the query can be simplify a little bit more. SQL DEMO SELECT * FROM ( SELECT source.[V1], source.[V2], target1.[V1] as t1_v1, target1.[V2] as t1_v2, target2.[V1] as t2_v1, target2.[V2] as t2_v2, CASE WHEN source.[V1] = target1.[V1] THEN target1.[V2] ELSE target1.[V1] END as transitive1, CASE WHEN source.[V2] = target2.[V2] THEN target2.[V1] ELSE target2.[V2] END as transitive2 FROM A as source JOIN A as target1 ON (source.[V1] = target1.[V1] OR source.[V1] = target1.[V2]) AND NOT (source.[V1] = target1.[V1] AND source.[V2] = target1.[V2]) JOIN A as target2 ON (source.[V2] = target2.[V1] OR source.[V2] = target2.[V2]) AND NOT (source.[V1] = target2.[V1] AND source.[V2] = target2.[V2]) ) T WHERE T.transitive1 = T.transitive2 OUTPUT To get the result you want select the right columns and add aditional filter SELECT T.[V1] as [V1], T.[V2] as [V2], T.[transitive1] as [V3] .... WHERE T.[V1] > T.[V2] AND T.[V2] > T.[transitive1] AND T.transitive1 = T.transitive2
[ "stackoverflow", "0030091956.txt" ]
Q: Android Share Image Doesn't Clear the Preview from a previously shared item Simple question, I have code set up to create a bitmap of an image and share it out via Action_Send. When it's shared, the correct image does send, but the preview of the image that shows up in the message field(if you're sending it via text) shows a previously shared item. Is there any way to force that preview to refresh? Below is an image that shows the field I'm talking about. The preview that's there is not the currently shared image, but a previous one from many shares ago that never cleared. http://i.stack.imgur.com/dT78Z.png private Intent getShareIntent() { Intent shareIntent = new Intent(Intent.ACTION_SEND); File sdCard = Environment.getExternalStorageDirectory(); File sharedFile = new File(sdCard+"/SaveDirectory/mypicture.png"); Uri uri = Uri.fromFile(sharedFile); shareIntent.setType("image/*"); shareIntent.putExtra(Intent.EXTRA_STREAM, uri); return shareIntent; } A: I saw same issue. This issue only exists for few apps, like google's apps such as keep, g+, etc. These apps retain the preview if the file is same. Not sure why they made such assumption. In short, the preview is preserved per file and not updated even after the file is changed. We can't fix these apps, so the solution is to avoid updating the same file. Create a temporary file using File.createTempFile() which ensures that a new unique file is created. This way preview will get updated. In my case, I created these temporary files in cache dir (getCacheDir() or getExternalCacheDir()) and clear the cache onDestroy().
[ "stackoverflow", "0001056330.txt" ]
Q: How to display a label next to a Marker for Google Maps? I would like to display a text label next to the markers on google maps. I've used Virtual Earth before and I'm just starting to use Google Maps. I tried setting the Title property but that only changes the roll over text. Is there a way to display a small line of text underneath a marker that will stay there as the user zooms, pans and uses the map? Thanks in advance! A: For Google Maps JavaScript API v3, check out the examples here. Source code available in normal and minimised forms. A: There's a good label class here, though you'll have to add it alongside the markers. A: If you just want to show label below the marker, then you can extend google maps Marker to add a setter method for label and you can define the label object by extending google maps overlayView like this.. Demo: jsFiddle <script type="text/javascript"> var point = { lat: 22.5667, lng: 88.3667 }; var markerSize = { x: 22, y: 40 }; google.maps.Marker.prototype.setLabel = function(label){ this.label = new MarkerLabel({ map: this.map, marker: this, text: label }); this.label.bindTo('position', this, 'position'); }; var MarkerLabel = function(options) { this.setValues(options); this.span = document.createElement('span'); this.span.className = 'map-marker-label'; }; MarkerLabel.prototype = $.extend(new google.maps.OverlayView(), { onAdd: function() { this.getPanes().overlayImage.appendChild(this.span); var self = this; this.listeners = [ google.maps.event.addListener(this, 'position_changed', function() { self.draw(); })]; }, draw: function() { var text = String(this.get('text')); var position = this.getProjection().fromLatLngToDivPixel(this.get('position')); this.span.innerHTML = text; this.span.style.left = (position.x - (markerSize.x / 2)) - (text.length * 3) + 10 + 'px'; this.span.style.top = (position.y - markerSize.y + 40) + 'px'; } }); function initialize(){ var myLatLng = new google.maps.LatLng(point.lat, point.lng); var gmap = new google.maps.Map(document.getElementById('map_canvas'), { zoom: 5, center: myLatLng, mapTypeId: google.maps.MapTypeId.ROADMAP }); var myMarker = new google.maps.Marker({ map: gmap, position: myLatLng, label: 'Hello World!', draggable: true }); } </script> <style> .map-marker-label{ position: absolute; color: blue; font-size: 16px; font-weight: bold; } </style> This will work.
[ "stackoverflow", "0045040442.txt" ]
Q: Moving running cycle in AS3 I want to make a moving character that runs a movie clip when a keyboard arrow is pressed.For example: When no arrows are pressed I want the character not to move when any keyboard arrows are pressed and run a movie clip animation where the character runs when the right arrow is pressed and same with the left arrow. var upPressed:Boolean = false; var downPressed:Boolean = false; var leftPressed:Boolean = false; var rightPressed:Boolean = false; movieClip_1.addEventListener(Event.ENTER_FRAME,fl_MoveInDirectionOfKey); stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_SetKeyPressed); stage.addEventListener(KeyboardEvent.KEY_UP, fl_UnsetKeyPressed); function fl_MoveInDirectionOfKey(event:Event) { if (upPressed) { movieClip_1.y -= 5; } if (downPressed) { movieClip_1.y += 5; } if (leftPressed) { movieClip_1.x -= 5; } if (rightPressed) { movieClip_1.x += 5; } } function fl_SetKeyPressed(event:KeyboardEvent):void { switch (event.keyCode) { case Keyboard.UP: { upPressed = true; break; } case Keyboard.DOWN: { downPressed = true; break; } case Keyboard.LEFT: { leftPressed = true; break; } case Keyboard.RIGHT: { rightPressed = true; break; } } } function fl_UnsetKeyPressed(event:KeyboardEvent):void { switch (event.keyCode) { case Keyboard.UP: { upPressed = false; break; } case Keyboard.DOWN: { downPressed = false; break; } case Keyboard.LEFT: { leftPressed = false; break; } case Keyboard.RIGHT: { rightPressed = false; break; } } } My movie clips are: run_right and run_left. My timeline: A: Create a MovieClip called "movieClip_1". var movieClip_1= new MovieClip_1(); Inside this MovieClip, add "run_right" animation on the first frame and "run_left" on the second frame. I mean, add new MovieClips that contains your animations. Then, go to fl_MoveInDirectionOfKey function and write this: if (rightPressed) { movieClip_1.gotoAndStop(1); } else if (leftPressed) { movieClip_1.gotoAndStop(2); } else { // no animation // movieClip_1.gotoAndStop(3); idle animation could be on frame 3 }
[ "stackoverflow", "0037638753.txt" ]
Q: How to use path from within each clause as helper argument in handlebars.js I have the following scenario {{#each (concatArray setra.features lion.features)}} <tr> <td><h4 class="ui header">{{this}}</h4></td> <td>{{#if contains ../setra.features this}}YES{{/if}}</td> <td>{{#if contains ../lion.features this}}YES{{/if}}</td> </tr> {{/each}} where concatArray is a helper function that returns an array of strings which is a concatenation of all features. How do I properly write the statement above? From within the each clause I am able to access the setra.features and lion.features by escaping the each context: {{#each (concatArray setra.features lion.features)}} {{../setra.features}} <!-- is accessible --> {{/each}} But once I want to use either as an argument in my helper function contains, it gives me errors depending on how I try to implement it. The example above currently gives me a "Cannot read property 'includeZero' of undefined" error, which seems most likely because the path is not properly evaluated. The helper functions are as follows: var contains = function(array, string){ if(array && array.indexOf(string) > -1){ return true; } return false; } exports.contains = contains; var concatArray = function(array1, array2){ var newArray = array1; array2.forEach(function(element){ if(newArray.indexOf(element) < 0){ newArray.push(element); } }); return newArray; } exports.concatArray = concatArray; A: The first issue is that all of the items after your #if are being treated as separate arguments to the Handlebars #if block helper. #if expects a single argument, a boolean expression. Handlebars supports subexpressions. From the docs: Handlebars offers support for subexpressions, which allows you to invoke multiple helpers within a single mustache, and pass in the results of inner helper invocations as arguments to outer helpers. Subexpressions are delimited by parentheses. Following these instructions, the #if blocks in your template must be updated to the following: <td>{{#if (contains ../setra.features this)}}YES{{/if}}</td> <td>{{#if (contains ../lion.features this)}}YES{{/if}}</td> Running the code now should not throw the "includeZero" error. However, there is still a problem. It seems the contains helper always returns true when passed ../setra.features. This is due to the fact that the concatArray helper is changing the value of setra.features. In fact, 'concatArray` modifies its first array argument such that its value becomes the result of all "concatenated" arrays. (Please note that your helper is not strictly "concatentation" because it also removes duplicate elements.) To fix this, we need concatArray to modify a copy of its first array argument, rather than modifying the first array argument itself. There are a few ways to do this, but I will use JavaScript's Array.prototype.concat: //var newArray = array1; var newArray = [].concat(array1); Finally, I would refactor your contains helper a little bit, just for cleanliness. I think the following is much prettier: var contains = function (array, string) { return (Array.isArray(array) && array.indexOf(string) > -1); }
[ "stackoverflow", "0028424574.txt" ]
Q: Static linking does not work with C++/CLI (unresolved external symbol) despite correct options I have 2 projects: a native C project, and a C++/CLI wrapper which will be used to allow the C project to interop with a C# program. Both projects are located in the same Visual Studio 2010 solution. In order to allow for interop, I was planning to have the C++/CLI wrapper statically link with the native C project, so that I can access its global variables and functions, and have both the wrapper and the native C project compile into one loadable DLL. For my C project, I've set the project configuration type to "static library", and with no CLR support. From what I've seen, it builds only to a .lib file, with no DLL. Because VS2010 uses a C++ compiler, I suppose the code is being compiled as C++, which is fine by me. I've used the C++/CLI wizard to create the second project, and then I added the name of the library in the linker options and its directory. If I understand correctly this should make the linker link the static library with the C++/CLI DLL. I also added the native C project as a reference to the C++/CLI wrapper project (in Frameworks and References) To test this, I tried using a global variable from the C project in my C++/CLI .cpp file. This is my code (with unrelated stuff removed (at least, I hope they're unrelated)): Wrapper.cpp (located in C++/CLI wrapper project) #include "stdafx.h" #include "Wrapper.h" #include "Gvar.h" Wrapper::Wrapper() { } Wrapper::~Wrapper() { } Wrapper::!Wrapper() { } void Wrapper::initialize(int year) { g_year = year System::Console::WriteLine(::g_year); } Gvar.h (located in static library project) #ifndef GVAR_H #define GVAR_H extern int g_year; #endif Gvar.c (located in static library project) #include "Gvar.h" int g_year = 2013; When I build the C++/CLI project, I get the following linker error: 2>Wrapper.obj : error LNK2020: unresolved token (0A00003B) "int g_year" (?g_year@@3HA) 2>Wrapper.obj : error LNK2001: unresolved external symbol "int g_year" (?g_year@@3HA) I'm not sure what I'm doing wrong. I clearly defined the variable in the C file. I also know that the linker actually looks at the library I specified, because after enabling "show progress" in the linker options I can see that the linker searches inside the library, but it seems it's not finding anything: (a small snippet of the output): ... 2> 2> Finished searching libraries 2> Search transition ?g_year@@3HA->__t2m@?g_year@@3HA 2> Search transition __pRawDllMain->__t2m@__pRawDllMain 2> Merging metadata 2> Finished merging metadata 2> 2> Searching libraries 2> Searching C:\Users\9a3eedi\Documents\Solution\Static Lib\Debug\Static Lib.lib: 2> Searching C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\lib\MSVCRTD.lib: 2> Searching C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\lib\OLDNAMES.lib: 2> Searching C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\lib\MSVCMRTD.lib: 2> Searching C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\lib\MSCOREE.lib: 2> Found __CorDllMain@12 2> Loaded MSCOREE.lib(mscoree.dll) 2> Found __IMPORT_DESCRIPTOR_mscoree 2> Referenced in MSCOREE.lib(mscoree.dll) 2> Loaded MSCOREE.lib(mscoree.dll) 2> Found mscoree_NULL_THUNK_DATA 2> Referenced in MSCOREE.lib(mscoree.dll) 2> Loaded MSCOREE.lib(mscoree.dll) 2> Searching C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\lib\kernel32.lib: 2> Searching C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\lib\uuid.lib: 2> Searching C:\Users\9a3eedi\Documents\Solution\Static Lib\Debug\Static Lib.lib: 2> Searching C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\lib\MSVCRTD.lib: 2> Searching C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\lib\OLDNAMES.lib: 2> Searching C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\lib\MSVCMRTD.lib: 2> 2> Finished searching libraries 2> Generating clr ijw/native image 2> 2> Searching libraries 2> Searching C:\Users\9a3eedi\Documents\Solution\Static Lib\Debug\Static Lib.lib: ... The static library in question is "Static Lib.lib". It's in the linker output above. Why isn't the linker able to resolve my global variable? I have tried the following after some googling, but none of them do anything or make any difference: Adding #pragma comment(lib, "Static Lib.lib") to Wrapper.cpp Surrounding the #include "Gvar.h" with #pragma managed(push, off) and #pragma managed(pop) Both of the above A: Update your wrapper.cpp to include the gvar.h within extern C. #include "stdafx.h" #include "Wrapper.h" #ifdef __cplusplus extern "C" { #endif #include "gvar.h" #ifdef __cplusplus } #endif ... //other code in wrapper.cpp The cause is name mangling scheme in C and C++ are different. So the variable name defined in library of C code will not be same as the one searched by linker while compiling/linking C++ code. More reference at In C++ source, what is the effect of extern "C"?
[ "stackoverflow", "0035165367.txt" ]
Q: Migrated to Android Studio - now my app requests additional permissions I just migrated an app from Eclipse to Android Studio. I tried exporting a signed APK and uploaded it to Google Play just to check that everything was working. That's when I noticed that my app now requests two additional permissions except the ones that I have declared in my manifest! The two permissions are android.permission.WAKE_LOCK and com.google.android.c2dm.permission.RECEIVE. What's going on here? I haven't changed any code since the last time I uploaded the app, and the manifest doesn't declare these permissions. I'm guessing some Google component is responsible for this, but why did this happen because I migrated to Android Studio? Can I turn off these permissions? I'm using Google Play Services and Google AdMob, but I've been doing that for a long time without these permissions...   manifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.app" android:versionCode="70" android:versionName="7.0" > <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="com.android.vending.CHECK_LICENSE" /> <uses-sdk android:minSdkVersion="10" android:targetSdkVersion="23" /> <application android:name="com.example.app.MyApplication" android:icon="@mipmap/ic_launcher_icon" android:label="@string/app_name" android:allowBackup="true" android:uiOptions="none"> <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> <activity android:name="com.example.app.MainActivity" android:label="@string/app_name" android:theme="@style/Theme.MyTheme.App" android:windowSoftInputMode="adjustPan" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.example.app.OtherActivity" android:label="@string/otherActivityTitle" android:theme="@style/Theme.MyTheme.App" android:parentActivityName="com.example.app.MainActivity" > <meta-data android:name="android.support.PARENT_ACTIVITY" android:value="com.example.app.MainActivity" /> </activity> <activity android:name="com.example.app.PreferencesActivity" android:label="@string/prefsTitle" > </activity> <activity android:name="com.google.android.gms.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:theme="@android:style/Theme.Translucent" /> </application> </manifest>   Here's a screenshot of the APK built using Android Studio: I couldn't change the language to english, but it basically says it's now supporting 22 less devices, requires 2 new permissions and uses OpenGL 2.0+ instead of 1.0+. Here's a screenshot of the same APK built using Eclipse: A: After some more searching I found this thread on Stackoverflow: Android Studio adds unwanted permission after running application on real device. One of the answers there (not the accepted one) solved my issues. It seems that the Android Studio import process added this dependency to my build.gradle: compile 'com.google.android.gms:play-services:+' After changing it to compile 'com.google.android.gms:play-services-base:8.4.0' // Needed for API Availability test compile 'com.google.android.gms:play-services-ads:8.4.0' compile 'com.google.android.gms:play-services-analytics:8.4.0' the APK no longer requests the unwanted permissions, it targets the same devices as before and uses the same OpenGL version as before - i.e. everything is back the way it was with Eclipse! Except now the file size of the APK is 1 MB smaller as an added bonus! For people coming here in the future, you might want to investigate what Google Play Services version numbers you should use at Gradle, please and/or Setting up Google Play Services.
[ "stackoverflow", "0026026043.txt" ]
Q: ArcGIS GeoEvent Processor - javax.xml.ws.soap.SOAPFaultException: Unmarshalling Error Background I'm using wsimport to create what is essentially a Java webservice client, connecting to a .Net webservice that is returning datasets (unfortunately). To be more specific I'm working on a project (inbound transport) for the GeoEvent Processor suite of ESRI ArcGIS Server 10.2, but I think this might be answered on more general terms in relation to JAXB and WSDL bindings. Bear with me as I haven't touched Java since college (10+ years). For purposes of the WSDL, the .Net DataSet is a polymorphic type whose actual layout isn't determined until run time, after the DataSet has been filled with data. This causes problems when you want to use that webservice with anything but .Net. After some research I've managed to use wsimport to generate from the webservice wsdl. I was then able to put together a basic proof of concept program that gets results from the webservice as a DOM, then walks that DOM as a nodelist. Reference: JAX-WS error on WSDL file: "Error resolving component 's:schema'" https://weblogs.java.net/blog/vivekp/archive/2007/05/how_to_deal_wit_1.html The section on Toolkit Bindings and figure 6 in http://msdn.microsoft.com/en-us/magazine/cc188755.aspx My wsimport looks like this (domain names have been changed to protect the innocent): C:\Development\ArcGIS\WSDL>wsimport -b http://www.w3.org/2001/XMLSchema.xsd -b xsd.xjb -keep -p com.somecompany.services -XadditionalHeaders http://services.somecompany.com/DataRetrieval.asmx?wsdl The Problem Unfortunately, the same codebase that worked in my proof of concept, getting results from the webservice, fails once I implement in the ArcGIS GeoEvent Processor. My project is part of an OSGI bundle that the ArcGIS GeoEvent Processor will control. The error below is as shown in the Apache Karaf log for the GeoEvent Processor. Based on the error, my understanding is there is a problem with how I did the binding in wsimport, referencing the generic schema per those links I have listed above. Looks like the generic schema lacks definitions for some of the elements that exist as classes generated by wsimport. Those classes appear to be properly generated when I check the output from wsimport. I've not included the WSDL due to posting limitations, but will include in later responses if needed. What I'm trying to figure out How should this error be interpreted? Why does the same wsimport generated code used to access the webservice in my basic proof of concept fail when run in the ArcGIS GeoEvent Processor? The error mentions JAXB and SAX, I'm not consciously referencing either of those libraries in the proof of concept or the project for the ArcGIS GeoEvent Processor. Could it be that the binding/unmarshalling of the webservice is handled differently, with ArcGIS GeoEvent Processor wrapping in JAXB/SAX and the proof of concept not? What can I do to resolve this? Use a different, custom, xsd and xjb that spells out the expected schema for the webservice? I'm not sure exactly how that would be done. Use something other than wsimport to generate the webservice reference classes? Tweak something in the java environment for the ArcGIS GeoEvent Processor? Other options? Commit seppuku, then it's not my problem? The Error 2014-09-23 16:10:14,365 | ERROR | ansport Listener | SomeInboundTransport | 367 - com.somecompany.arcgis.geoevent.transport.inbound.somecompanyInboundTransport - 1.0.0 | Unable to call Webservice javax.xml.ws.soap.SOAPFaultException: Unmarshalling Error: unexpected element (uri:"http://www.w3.org/2001/XMLSchema", local:"element"). Expected elements are <{http://services.somecompany.com/}complexType>,<{http://services.somecompany.com/}annotation>,<{http://services.somecompany.com/}redefine>,<{http://services.somecompany.com/}element>,<{http://services.somecompany.com/}include>,<{http://services.somecompany.com/}attributeGroup>,<{http://services.somecompany.com/}group>,<{http://services.somecompany.com/}notation>,<{http://services.somecompany.com/}import>,<{http://services.somecompany.com/}simpleType>,<{http://services.somecompany.com/}attribute> at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:156)[120:org.apache.cxf.cxf-rt-frontend-jaxws:2.6.1] at com.sun.proxy.$Proxy198.getCompanyArcgisData(Unknown Source)[367:com.somecompany.arcgis.geoevent.transport.inbound.somecompanyInboundTransport:1.0.0] at com.somecompany.arcgis.geoevent.transport.inbound.SomeInboundTransport.callWebService(SomeInboundTransport.java:184)[367:com.somecompany.arcgis.geoevent.transport.inbound.somecompanyInboundTransport:1.0.0] at com.somecompany.arcgis.geoevent.transport.inbound.SomeInboundTransport.run(SomeInboundTransport.java:257)[367:com.somecompany.arcgis.geoevent.transport.inbound.somecompanyInboundTransport:1.0.0] at java.lang.Thread.run(Thread.java:722)[:1.7.0_17] Caused by: javax.xml.bind.UnmarshalException - with linked exception: [com.sun.istack.SAXParseException2; lineNumber: 1; columnNumber: 651; unexpected element (uri:"http://www.w3.org/2001/XMLSchema", local:"element"). Expected elements are <{http://services.somecompany.com/}complexType>,<{http://services.somecompany.com/}annotation>,<{http://services.somecompany.com/}redefine>,<{http://services.somecompany.com/}element>,<{http://services.somecompany.com/}include>,<{http://services.somecompany.com/}attributeGroup>,<{http://services.somecompany.com/}group>,<{http://services.somecompany.com/}notation>,<{http://services.somecompany.com/}import>,<{http://services.somecompany.com/}simpleType>,<{http://services.somecompany.com/}attribute>] at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.handleStreamException(UnmarshallerImpl.java:425) at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:362) at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:339) at org.apache.cxf.jaxb.JAXBEncoderDecoder.doUnmarshal(JAXBEncoderDecoder.java:784)[91:org.apache.cxf.cxf-rt-databinding-jaxb:2.6.1] at org.apache.cxf.jaxb.JAXBEncoderDecoder.access$100(JAXBEncoderDecoder.java:97)[91:org.apache.cxf.cxf-rt-databinding-jaxb:2.6.1] at org.apache.cxf.jaxb.JAXBEncoderDecoder$1.run(JAXBEncoderDecoder.java:812) at java.security.AccessController.doPrivileged(Native Method)[:1.7.0_17] at org.apache.cxf.jaxb.JAXBEncoderDecoder.unmarshall(JAXBEncoderDecoder.java:810)[91:org.apache.cxf.cxf-rt-databinding-jaxb:2.6.1] at org.apache.cxf.jaxb.JAXBEncoderDecoder.unmarshall(JAXBEncoderDecoder.java:644)[91:org.apache.cxf.cxf-rt-databinding-jaxb:2.6.1] at org.apache.cxf.jaxb.io.DataReaderImpl.read(DataReaderImpl.java:157)[91:org.apache.cxf.cxf-rt-databinding-jaxb:2.6.1] at org.apache.cxf.interceptor.DocLiteralInInterceptor.handleMessage(DocLiteralInInterceptor.java:108)[87:org.apache.cxf.cxf-api:2.6.1] at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:262)[87:org.apache.cxf.cxf-api:2.6.1] at org.apache.cxf.endpoint.ClientImpl.onMessage(ClientImpl.java:798)[87:org.apache.cxf.cxf-api:2.6.1] at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponseInternal(HTTPConduit.java:1667)[118:org.apache.cxf.cxf-rt-transports-http:2.6.1] at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponse(HTTPConduit.java:1520)[118:org.apache.cxf.cxf-rt-transports-http:2.6.1] at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.close(HTTPConduit.java:1428)[118:org.apache.cxf.cxf-rt-transports-http:2.6.1] at org.apache.cxf.transport.AbstractConduit.close(AbstractConduit.java:56)[87:org.apache.cxf.cxf-api:2.6.1] at org.apache.cxf.transport.http.HTTPConduit.close(HTTPConduit.java:658)[118:org.apache.cxf.cxf-rt-transports-http:2.6.1] at org.apache.cxf.interceptor.MessageSenderInterceptor$MessageSenderEndingInterceptor.handleMessage(MessageSenderInterceptor.java:62)[87:org.apache.cxf.cxf-api:2.6.1] at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:262)[87:org.apache.cxf.cxf-api:2.6.1] at org.apache.cxf.endpoint.ClientImpl.doInvoke(ClientImpl.java:532)[87:org.apache.cxf.cxf-api:2.6.1] at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:464)[87:org.apache.cxf.cxf-api:2.6.1] at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:367)[87:org.apache.cxf.cxf-api:2.6.1] at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:320)[87:org.apache.cxf.cxf-api:2.6.1] at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:89)[119:org.apache.cxf.cxf-rt-frontend-simple:2.6.1] at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:134)[120:org.apache.cxf.cxf-rt-frontend-jaxws:2.6.1] ... 4 more Caused by: com.sun.istack.SAXParseException2; lineNumber: 1; columnNumber: 651; unexpected element (uri:"http://www.w3.org/2001/XMLSchema", local:"element"). Expected elements are <{http://services.somecompany.com/}complexType>,<{http://services.somecompany.com/}annotation>,<{http://services.somecompany.com/}redefine>,<{http://services.somecompany.com/}element>,<{http://services.somecompany.com/}include>,<{http://services.somecompany.com/}attributeGroup>,<{http://services.somecompany.com/}group>,<{http://services.somecompany.com/}notation>,<{http://services.somecompany.com/}import>,<{http://services.somecompany.com/}simpleType>,<{http://services.somecompany.com/}attribute> at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:642) at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:254) at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:249) at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportUnexpectedChildElement(Loader.java:116) at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.childElement(Loader.java:101) at com.sun.xml.bind.v2.runtime.unmarshaller.StructureLoader.childElement(StructureLoader.java:243) at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext._startElement(UnmarshallingContext.java:478) at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.startElement(UnmarshallingContext.java:459) at com.sun.xml.bind.v2.runtime.unmarshaller.StAXStreamConnector.handleStartElement(StAXStreamConnector.java:242) at com.sun.xml.bind.v2.runtime.unmarshaller.StAXStreamConnector.bridge(StAXStreamConnector.java:176) at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:360) ... 28 more Caused by: javax.xml.bind.UnmarshalException: unexpected element (uri:"http://www.w3.org/2001/XMLSchema", local:"element"). Expected elements are <{http://services.somecompany.com/}complexType>,<{http://services.somecompany.com/}annotation>,<{http://services.somecompany.com/}redefine>,<{http://services.somecompany.com/}element>,<{http://services.somecompany.com/}include>,<{http://services.somecompany.com/}attributeGroup>,<{http://services.somecompany.com/}group>,<{http://services.somecompany.com/}notation>,<{http://services.somecompany.com/}import>,<{http://services.somecompany.com/}simpleType>,<{http://services.somecompany.com/}attribute> ... 39 more The Code (snippet) import com.somecompany.services.*; //generated by wsimport import javax.xml.ws.*; //... private com.somecompany.services.DataRetrieval myWS; private com.somecompany.services.DataRetrievalSoap port; private byte[] callWebService(String userName, String pwd, long dataTimeFrame) { try { myWS = new com.somecompany.services.DataRetrieval(); port = myWS.getDataRetrievalSoap(); com.somecompany.services.AuthSoapHeader mySoapHeader = new com.somecompany.services.AuthSoapHeader(); mySoapHeader.setUserName(userName); //Hash the password then set it for the SOAP header String pwdHash = hashMD5(pwd); mySoapHeader.setPassword(pwdHash); Holder holder = new Holder<AuthSoapHeader>(mySoapHeader); Date endTime = new Date(); Date startTime = new Date(endTime.getTime() - dataTimeFrame); XMLGregorianCalendar gcEndTime = dateToGregorianTime(endTime); XMLGregorianCalendar gcStartTime = dateToGregorianTime(startTime); GetCompanyArcgisDataResponse.GetCompanyArcgisDataResult companyData = port.getCompanyArcgisData(gcStartTime, gcEndTime, holder); if( ((AuthSoapHeader)holder.value).getError() != null) { log.error("Authentication to web services failed!"); //OSGI stop service this.stop(); return null; }else log.info("Authentication to web services successful."); //Convert the results to a java object and then to a byte array to send to the adapter Object companyDataAny = companyData.getAny(); byte[] companyDataBytes = objectToBytes(companyDataAny); return companyDataBytes; } catch(Exception ex) { log.error("Unable to call Webservice", ex); //OSGI stop service this.stop(); return null; } } Environment Specifics JDK 7u17 (1.7.0_17) 64 bit. The ArcGIS GeoEvent Processor is using this version of the JRE, so I'm locked into that version for execution. Though I've done some development in 1.7.0_51 before I realized that. wsimport - JAX-WS RI 2.2.4-b01 ArcGIS Server 10.2 ArcGIS GeoEvent Processor Extension Karaf (used by ArcGIS Geovent Processor to run OSGI bundles) A: This is probably not the best answer on this, but it's what I came up with. The ArcGIS GeoEvent Processor that wrapped my OSGI project appeared to be doing some additional binding/unbinding of the web service that I referenced in my application. The work-around that I employed to get that .Net (DataSet return values) web service to function in Java just wasn't acceptable to that wrapper from the GeoEvent Processor. My Solution Ultimately what I did was create a secondary .Net web service which took the DataSet values and converted them to JSON, and returned JSON strings. This removed the problems encountered when attempting to reference DataSet return values from the web service, now I was dealing with a simple JSON string. The wsimport of that JSON web service went smooth, no work-around required. I tucked the newly imported web service files into my java project and now have no problems. For Reference on C# DataSet to JSON: Using Newtonsoft.Json (http://james.newtonking.com/json). After playing with a few other libraries for JSON serialization that is what I found worked best for me. Newtonsoft.Json is available via NuGet package Rick Strahl's site was a big help http://weblog.west-wind.com/posts/2008/Sep/03/DataTable-JSON-Serialization-in-JSONNET-and-JavaScriptSerializer
[ "graphicdesign.stackexchange", "0000008704.txt" ]
Q: Can FontLab edit and output a webfont without losing data? A font vendor who shall remain nameless sold me a webfont under the premise that all modern browsers would support switching the old style figures to lining figures without any trouble. Well, by "all modern browsers" then meant Firefox only. Now that I've paid for it, they can't get it to work either. The font is great and I have no intention to refund it, I just want to swap the OSF glyphs with the lining in the font table. I haven't upgraded FontLab in a few years and I'm wondering how the latest and greatest does with exporting web fonts. I'd like to open the file I downloaded and just move the glyphs around on the table. Anyone have experience with this? Will I lose any hinting or metrics data in the process? A: You should go through several steps for each number. 1) double-click on "zero" glyph (this opens glyph editor) 2) remove hints (shift+F7) 3) press ctrl+A, then DEL (remove OSF zero) 4) press ctrl+INS and type 'zero', select lining zero, press ENTER (this action will copy glyph with all the hints as a component which you can "decompose") To remove kerning select all numbers you want an go to Window -> New Metric Window. Then right-click on any number and "Reset kerning". After this you can generate new font with lining figures instead OSF :)
[ "salesforce.stackexchange", "0000092676.txt" ]
Q: Access Document(pdf or doc) without Salesforce login I have 3 Document records with pdf, word document & image respectively. I need to show the files outside Salesforce(i.e without salesforce login). All of the records have 'Externally Available Image' checked. Now using the URL - https://c.ap1.content.force.com/servlet/servlet.ImageServer?id=01590000009hxW6&oid=00D90000000w5zN&lastMod=1442409870000 I am able to open the image file, but forming a similar URL for Pdf or word document is not helping. Its redirecting me to the salesforce login page. Any idea how should I approach for pdfs & word documents? And why is it working for images but not for pdfs? A: An easier approach would be to use Chatter Files. When you upload a file to chatter, you have an option to Share via Link. That link is publically available. E.g. the 2 links below are from my Dev Org. Word Document PDF Document An added advantage is that you can preview the file before downloading.
[ "stackoverflow", "0055989266.txt" ]
Q: Value of 1 is stored In database instead of the text Box value / PHP-MySql Well i want to store 3 textbox values into my mysqli database, after running these codes nothings happen! and if anything happen then number '1' store into database instead Textboxes Value PHP Code: <?php include 'displaycustomersdb.php'; //this file give $Ccode from user sessions and config.php is in it. global $textareamsg; global $title; global $reciver; global $sender; $textareamsg = (isset($_GET['textarea'])); $title = (isset($_GET['title'])); $reciver = (isset($_GET['reciver'])); if (isset($_GET['sendmsg'])) { $sql_msg = mysqli_query($link, 'INSERT INTO messaging (title, message, sender, reciver) VALUES (' . $title . ',' . $textareamsg . ',' . $Ccode . ',' . $reciver . ''); } ?> HTML Code: <?php include 'sendmsg.php'; ?> <form method="get"> <i class="fas fa-envelope-open-text"></i><input type="text" placeholder="Ttitle here ..." name="title"> <br> <br> <i class="fas fa-user-plus"></i><input type="text" placeholder="TO" name="reciver"> <br> <br> <textarea rows="10" cols="100" placeholder="textarea" name="textarea" style="padding:10px;"></textarea> <br> <br> <button type="submit" name="sendmsg"><i class="far fa-share-square"></i>Insert</button> </form> A: You get boolean values instead of the values itself. Remember isset() return true if the given value exists and it store in your DB as 1. I guess you intend to check if value is exists, whitch you can do it like below: $textareamsg = isset($_GET['textarea'])? $_GET['textarea'] : ''; $title = isset($_GET['title'])? $_GET['title'] : ''; $reciver = isset($_GET['reciver'])? $_GET['reciver']: ''; And also you should store string values like this: if (isset($_GET['sendmsg'])) { $sql_msg = mysqli_query($link, 'INSERT INTO messaging (title, message, sender, reciver) VALUES ("' . $title . '","' . $textareamsg . '","' . $Ccode . '","' . $reciver . '"'); } Hope it will be helpful :) A: Well, thank you everyone. i did try this and it's working: $textareamsg = $_GET['textarea']; $title = $_GET['title']; $reciver = $_GET['reciver']; if (isset($_GET['sendmsg'])) { $sql_msg = mysqli_query($link, "INSERT INTO messaging (title, message, sender, reciver) VALUES ('$title','$textareamsg', '$ccode','$reciver')"); }
[ "stackoverflow", "0032158447.txt" ]
Q: Why does explorer.exe automatically restart when I user process.Kill() C#? I wrote this little function that searches for a process by name and kills it: see code below Process[] procList = Process.GetProcesses(); RegistryKey expKey = Registry.LocalMachine; expKey = expKey.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon", true); expKey.SetValue("AutoRestartShell", 0); using (StreamWriter writer = new StreamWriter(@"C:\test\progtemp\Procs1.Txt", true)) { int i = 0; foreach (Process procs in procList) { writer.WriteLine(string.Format("Process Name {0} -- Process ID {1} -- Session ID {2}", procs.ProcessName, procs.Id, procs.SessionId)); if (procs.ProcessName == "explorer") { procList[i].Kill(); } i++; } } expKey.SetValue("AutoRestartShell", 1); I'm curious why when I tell it to kill explorer it automatically restarts. How can I make it so that it does not restart and you have to go into task manager and manually restart it? A: If you run regedit and go into HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon, you can find there a key named AutoRestartShell. Settings that to 0 would disallow explorer.exe from rebooting. Although I personally say it's not the best idea to mess with Registry just for that but if you really need to, make use of Registry.SetValue to change that value to 0 from the code (documentation: https://msdn.microsoft.com/en-us/library/5a5t63w8(v=vs.110).aspx) Edit: inspiration taken from https://technet.microsoft.com/en-us/library/cc939703.aspx Edit 2: digging a bit into google came up with the following result which explains everything slightly better: https://superuser.com/questions/511914/why-does-explorer-restart-automatically-when-i-kill-it-with-process-kill
[ "stackoverflow", "0047593859.txt" ]
Q: How to copy Java object without a change to the original affecting the copy In the function addStartNode, I create a new Node 'temp' whose value is set to equal that of 'head'. Then I set head to be a new Node with value different 'v'. However, when I print both the values for 'temp' and 'head', it displays the same thing. I've tried many different approaches to this, including a copy constructor, but it doesn't seem to be changing anything. Any help would be great! public class DoublyLinkedList { private static class Node { private static int value; Node(int v) { value = v; } int getValue() { return value; } } private static Node head; void addStartNode(int v) { if (head == null) { head = new Node(v); } else { Node temp = new Node(head.getValue()); PRINT VALUES HERE head = new Node(v); PRINT VALUES HERE } } } A: You have declared value as static in the Node class. If the attribute is static then it is shared by all instances of Node. Change : private static int value; To private int value; Imagine you change your code to this one : static class Node { private static int nbOfNode = 0; private int value; Node(int v) { nbOfNode++; value = v; } int getValue() { return value; } static int getNbOfNode() { return nbOfNode; } } Now value is not static then each instance of Node will have its proper value. On the other hand nbOfNode is static then it will be shared among all the instances of the Node class, because it is a class level variable. Now if you run this: Node n1 = new Node(11); System.out.println(n1.getValue()); System.out.println(Node.getNbOfNode()); Node n2 = new Node(22); System.out.println(n2.getValue()); System.out.println(Node.getNbOfNode()); It will produce : 11 - the proper value of the node n1 1 - the incremented shared value 22 - the proper value of the node n2 2 - the second increment of the shared value During the instantiation of n2 the constructor will increment the same variable than the one previously incremented by the instantiation of n1
[ "stackoverflow", "0044268892.txt" ]
Q: Optimal way to negate a floating point value in C# What is faster from a code execution perspective: double a = 1.234; double minus_a = -a; or: double a = 1.234; double minus_a = a * -1; Does the second case actually perform floating point multiplication? Or is the compiler smart enough to optimize the second case to be the same as the first? A: Tested with the 64bit JIT of .NET 4, other JITs such as the old 32bit JIT or the newer RyuJIT can be different (actually the 32bit old JIT must do something else since it does not use SSE) -x translates into vmovsd xmm1,qword ptr [00000050h] ; there's a -0.0 there, so only the sign bit is set vxorpd xmm0,xmm0,xmm1 ; literally flip the sign x * -1 into vmulsd xmm0,xmm0,mmword ptr [00000048h] ; -1.0 Yes, very literal. As for speed, you can pick your model from here and compare, but vxorpd will always be faster than vmulsd. Could it have optimized x * -1 to a XOR? The behavior for NaN is different, with the XOR approach flipping the sign of the NaN, but that doesn't really matter.
[ "stackoverflow", "0002023060.txt" ]
Q: Drop User from SQL Server Database? How can I drop user from a database without dropping it's logging? The script should check if the user exists in database, if does then drop the user. A: Is this what you are trying to do?? IF EXISTS (SELECT * FROM sys.database_principals WHERE name = N'username') DROP USER [username] If you are using SQL Server Management Studio you can browse to the user and right-click selecting delete. A: The accepted answer is working good enough. Additionally that is good to know SQL Server added IF EXIST to some DROP commands from version 2016 (13.x) including 'DROP USER' command. IF EXISTS Applies to: SQL Server ( SQL Server 2016 (13.x) through current version, SQL Database). Conditionally drops the user only if it already exists. So you could just delete user as below: -- Syntax for SQL Server and Azure SQL Database DROP USER IF EXISTS user_name See the full description in this link: DROP USER (Transact-SQL) Hope this help.
[ "stackoverflow", "0054952346.txt" ]
Q: Sticky footer doesn't work with Angular 5 Here is my Angular project: https://stackblitz.com/edit/angular-1g7bvn I've tried getting the sticky footer from this example to work with no avail: html { height: 100%; font-family: sans-serif; text-align: center; } body { display: flex; flex-direction: column; height: 100%; margin: 0; } header{ flex-shrink: 0; background: yellowgreen; } .content { flex: 1 0 auto; background: papayawhip; } footer{ flex-shrink: 0; background: gray; } There must be something small I'm doing wrong but I can't see it. A: Angular is rendering your components as tags, so in your case my-app component is an actual tag on the DOM tree. <body> <my-app> <header></header> <section></section> <footer></footer> </my-app> </body> And all of your styles are applied to the body tag. If you add to your app.component.css your styles from body with a :host selector - it will work just fine. :host { display: flex; flex-direction: column; height: 100%; margin: 0; } here's a stackblitzz example
[ "stackoverflow", "0035386061.txt" ]
Q: Perl: String Repetition Operator in Substituion Regex Is there an easy way to use Perl's repetition operator, x, during a substitution regex? I'm trying to do a quick one-liner on very basic HTML without using a module. Essentially, I'd like to transform lines with opening <h*> and closing </h*> HTML tags into WIKI markup based on the heading number in the HTML tag. So... ___Original DATA___ <h1> This is a header one</h1> <h2> This is a header two</h2> <h3> This is a header three</h3> ___Wanted DATA___ = This is a header one = == This is a header two == === This is a header three === Everything works well with the regex itself, capturing the digit needed from the original header tag into the $1 variable. During the substitution portion, is there a way I can use that variable to create the needed number of = signs (e.g., "=" x $1)? perl -0777 -pe 's/<h(\d)>([^<]*)<\/h\d>/"="x$1 $2 "="x$1/gs', but the latter half ("="x$1 $2 "="x$1) of the command doesn't give me the wanted output. A: Operators are not interpolated in strings. You need the /e switch to interpret the replacement as code, not just string: s/<h(\d)>([^<]*)<\/h\d>/"=" x $1 . $2 . "=" x $1/ge You can also use a different delimiter instead of / to avoid the need to backslash it in </h. /s is not needed, as it changes the behaviour of . which doesn't occur in the regex.
[ "gis.stackexchange", "0000280229.txt" ]
Q: How to find the ID of the selected object in the layer? PyQGIS 3.0 How can I get a list of the ID of these selected objects? QGIS 3.0 A: You can use the QgsVectorLayer::selectedFeatureIds() to get a list of selected feature ids: layer = iface.activeLayer() print(layer.selectedFeatureIds())
[ "stackoverflow", "0008459898.txt" ]
Q: Servlet String Exception I made a Servlet for an online form and every time I try to submit the online form, it gives me the following exception: java.lang.NumberFormatException: For input string: "". The problem is that I don't have any String variables in my jsp file. One more thing: when I try to fill in all the fields from the online form, the information is sent to the database, but when I try this only with some of them, it gives me that exception again. This is my code: import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import database.databases; /** * Servlet implementation class feildsSERVLET */ public class feildsSERVLET extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public feildsSERVLET() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Class.forName("com.mysql.jdbc.Driver"); Connection connection = DriverManager.getConnection( "jdbc:mysql://localhost:3306/WhizzoChocolate", "root", ""); try { /* * int customerID = Integer.parseInt(request * .getParameter("customerID")); */ int frog = Integer.parseInt(request.getParameter("frog")); int redspring = Integer.parseInt(request.getParameter("redspring")); int bluespring = Integer.parseInt(request .getParameter("bluespring")); int silverspring = Integer.parseInt(request .getParameter("silverspring")); int ramsquare = Integer.parseInt(request.getParameter("ramsquare")); int ramoval = Integer.parseInt(request.getParameter("ramoval")); int ramhex = Integer.parseInt(request.getParameter("ramhex")); int rambutt = Integer.parseInt(request.getParameter("rambutt")); int product_id = Integer.parseInt(request .getParameter("product_id")); Statement statement = connection.createStatement(); int upd = statement .executeUpdate("INSERT INTO `product`(`product_id`, `RWA`, `BWA`,`SWA`, `OSA`,`SSA`,`HSA`,`BSA`)" + "VALUES" + "(" + product_id + frog + ", " + redspring + ", " + bluespring + ", " + silverspring + ", " + ramoval + ", " + ramsquare + ", " + ramhex + ", " + rambutt + ")"); request.setAttribute("product_id", product_id); request.setAttribute("frog", frog); request.setAttribute("redspring", redspring); request.setAttribute("bluespring", bluespring); request.setAttribute("silverspring", silverspring); request.setAttribute("ramsquare", ramsquare); request.setAttribute("ramoval", ramoval); request.setAttribute("ramhex", ramhex); request.setAttribute("rambutt", rambutt); } finally { connection.close(); } } catch (Exception e) { throw new ServletException(e); } ServletContext context = getServletContext(); RequestDispatcher dispatcher = context .getRequestDispatcher("/feildsjsp.jsp"); dispatcher.forward(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } } A: I'd guess that the problem is coming from one of these lines similar to this one: int redspring = Integer.parseInt(request.getParameter("redspring")); If the value of request.getParameter("redspring") is an empty string it will give you this exception.
[ "bitcoin.stackexchange", "0000072560.txt" ]
Q: developing a new alt-coin useful or not? I will try just for educational purposes create my alt-coin. But i have some questions before to start. It's possible create the alt-coin since my ubuntu and maintain this alt-coin since my pc if its always turn on? My last question, at this moment is possible that this new altcoin get some real price in the market? Someone can guide me a little or say me if will be useful in something create a new alt-coin? And maybe can get be profitable? A: Is it useful? Probably not for the community, but for you because you learn. It's possible create the alt-coin since my ubuntu and maintain this alt-coin since my pc if its always turn on? There is a difference between creating and running it. But yes, you can create a coin with your Pc. My last question, at this moment is possible that this new altcoin get some real price in the market? If you list it on an exchange and the community believes that it has a value: yes. Otherwise: no. - If you have only one Pc, you could create an ERC20-token (Ethereum based) and let the blockchain handle everything.
[ "stackoverflow", "0054957946.txt" ]
Q: What does V8's ignition really do? On https://v8.dev/docs/ignition we can see that: Ignition is a fast low-level register-based interpreter written using the backend of TurboFan on https://docs.google.com/document/d/11T2CRex9hXxoJwbYqVQ32yIPMh0uouUZLdyrtmMoL44/edit?ts=56f27d9d# The aim of the Ignition project is to build an interpreter for V8 which executes a low-level bytecode, thus enabling run-once or non-hot code to be stored more compactly in bytecode form. The interpreter itself consists of a set of bytecode handler code snippets, each of which handles a specific bytecode and dispatches to the handler for the next bytecode. These bytecode handlers To compile a function to bytecode, the JavaScript code is parsed to generate its AST (Abstract Syntax Tree). The BytecodeGenerator walks this AST and generates bytecode for each of the AST nodes as appropriate. Once the graph for a bytecode handler is produced it is passed through a simplified version of Turbofan’s pipeline and assigned to the corresponding entry in the interpreter table. So it seems that Ignition job is to take bytecode generated by BytecodeGenerator convert it to bytecode handlers and execute it through Turbofan. But here: and here: You can see that it is ignition that produces bytecode. What is more, in this video https://youtu.be/p-iiEDtpy6I?t=722 Ignition is said to be a baseline compiler. So what's it? A baseline compiler? A bytecode interpreter? An AST to bytecode transformer? This image seems to be most appropriate: where ignition is just an interpreter and everything before is no-name bytecode generator/optimizer thing. A: As I mentioned in a comment, sadly some of the docs are out of date, including the one with your first graphic above. Full-codegen and Crankshaft are no longer used at all, it's purely parsing and Ignition + TurboFan. (you've removed the image from the outdated docs that sadly are still linked by some of the V8 docs) Ignition is a high-speed bytecode interpreter. V8's parser produces Ignition bytecode. That bytecode is executed (interpreted) by Ignition. Code that only runs once (startup code and such) or isn't run often stays at the bytecode level and continues to be executed by Ignition. "Hot" code goes to the second phase, where TurboFan kicks in: TurboFan's input is the same bytecode that Ignition interprets (rather than source code, as it was with Crankshaft), which it then aggressively compiles to highly-optimized machine code that runs directly (rather than being interpreted). This article goes into the motivations for moving off Full-codegen and Crankshaft (memory savings in the former case, difficulty implementing and in particular optimizing language features in the second). The design of TurboFan also helps the V8 authors minimize the amount of platform-specific code they have to write (by having an intermediate representation, which amongst other things they can also use to write Ignition's bytecode handlers). A: V8 developer here. On https://v8.dev/docs/ignition we can see that: Ignition is a fast low-level register-based interpreter written using the backend of TurboFan Yes, that sums it up. To add a little more detail: The name "Ignition" refers to both the Bytecode Generator and the Bytecode Interpreter. Often, the entire thing is also seen as one big black box and casually called "the interpreter", which can sometimes lead to a bit of confusion around the terms. The Bytecode Generator takes the AST produced by the Parser for a given JavaScript function, and generates bytecode from it. The Bytecode Interpreter takes the bytecode generated by the Bytecode Generator and executes it by interpreting it by sending it to a set of Bytecode Handlers. The Bytecode Handlers that make up the Bytecode Interpreter are generated using parts of the Turbofan pipeline. This happens at V8 compilation time, not at runtime. In other words, you need Turbofan to build (parts of) Ignition, but not to run Ignition. The Parser (and the AST/Abstract Syntax Tree it produces are not part of Ignition. Once the graph for a bytecode handler is produced it is passed through a simplified version of Turbofan’s pipeline and assigned to the corresponding entry in the interpreter table. So it seems that Ignition job is to take bytecode generated by BytecodeGenerator convert it to bytecode handlers and execute it through Turbofan This section of the design document talks about generating the Bytecode Handlers, which happens "ahead of time" (i.e. when V8 is compiled) using parts of Turbofan. At runtime, bytecode is not converted to handlers, it is "handled" (=run, executed, interpreted) by the existing fixed set of handlers, and Turbofan is not involved. What is more, in this video https://youtu.be/p-iiEDtpy6I?t=722 Ignition is said to be a baseline compiler. At that moment, the talk is referring to the general idea that all modern JavaScript engines have a "baseline compiler" (in a very general, conceptual sense -- I agree that the slide could have made that clearer). Note that the slide does not say anything about Ignition. The next slide says that Ignition fills that role in V8. So more accurate would be to say "Ignition takes the place of a baseline compiler" or "Ignition is a baseline execution engine". Or you could redefine your terms slightly and say "Ignition is a compiler that produces bytecode and then interprets it". ignition is just an interpreter and everything before is no-name bytecode generator/optimizer thing That slide shows the "Interpreter" box as part of the "Ignition Bytecode Pipeline". The Bytecode Generator/Optimizer are also part of Ignition.
[ "stackoverflow", "0023697063.txt" ]
Q: Getting version number in InstallShield Limited edition in prebuild step I want to extract the "Product Version" number (of the form aa.bb.cccc) that you type in the General settings of an InstallShield Limited Edition deployment project. Specifically I want to do this in a custom pre-build step. Ideally I'd code this as an executable written in C++ using WinAPI. Waiting until the post build step and extracting it from the registry is too late - it needs to happen before the project files are copied. Is there a way to do this? I don't know of a macro that InstallShield defines for that. It could simply be that it is not supported in the free version. A: If you really need to do this pre-build then you're pretty much out of luck I'm afraid since the relevant options are disabled in the limited edition. However, once installation is complete, you can extract the version from the windows registry and touch any of the files that the installer has dropped. Here's some code you can use to do the first part: static const std::string key = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"; // Arguably the best place from which to obtain msi version data static const unsigned MAX_KEY_LENGTH = 255; // Maximum length of a registry key static const std::string displayName = /*ToDo - your display name here*/ static const unsigned displayNameSize = /*ToDo - the size of the display name here + 1 for the null terminator*/ int g_version; // The version number as it appears in the registry HKEY hKey = NULL; if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, key.c_str(), 0, KEY_ENUMERATE_SUB_KEYS, &hKey) == ERROR_SUCCESS){ for (DWORD Index = 0; g_version == 0U; ++Index){ DWORD cName = 256; char SubKeyName[MAX_KEY_LENGTH + 1/*Maximum length of a registry key is 255, add 1 for termination*/]; if (RegEnumKeyEx(hKey, Index, SubKeyName, &cName, NULL, NULL, NULL, NULL) != ERROR_SUCCESS){ break; } HKEY hSubKey = NULL; if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, (key + "\\" + SubKeyName).c_str(), 0, KEY_QUERY_VALUE, &hSubKey) == ERROR_SUCCESS){ // Is the DisplayName equal to displayName? DWORD dwType = REG_SZ; TBYTE buf[displayNameSize]; DWORD dwSize = displayNameSize; HRESULT res; if ((res = RegQueryValueEx(hSubKey, TEXT("DisplayName"), NULL, &dwType, (PBYTE)&buf, &dwSize)) == ERROR_SUCCESS){ if (!::strncmp(displayName.c_str(), (PTCHAR)buf, displayNameSize)){ // get the version dwType = REG_DWORD; dwSize = displayNameSize; if (RegQueryValueEx(hSubKey, TEXT("Version"), NULL, &dwType, (PBYTE)&buf, &dwSize) == ERROR_SUCCESS && dwType == REG_DWORD){ g_version = (buf[3] << 24) + (buf[2] << 16) + (buf[1] << 8) + buf[0]; } } } RegCloseKey(hSubKey); } } RegCloseKey(hKey); } You've already mentioned you'll code this in an executable. This can run as a post-build step and the limited edition supports that. Then all you need to do is embed the version number into one of your installation files; which your executable will be able to do.
[ "stackoverflow", "0048184983.txt" ]
Q: asp.net - ef - generic service/repository pattern I'm using a service/repository pattern with a generic repository class EFRepositoryBase where T : ModelBase, new() T is the class from wich all poco's used in ef inherit. EFRepositoryBase has a method Read public IQueryable<T> Read() { try { return db.Set<T>(); } catch (Exception) { throw new IRepositoryException(); } } Each service inherits from ServiceBase that has a repo property of type EFRepository. For performance reasons it is found that I better use a sql-view to display a list of orders because the list gets lots of data from other tabels, has calculated fields, .... To test this I created a view in sql, poco (OrderIndexItem) to map to it, added a DBset vwOrderIndex to the context ... it all works fine. The issue is that for the moment I directly address db.vwOrderIndex in the service. Next step is to make it generic. The idea is to add a static property to ModelBase that contains the type of the related 'view poco'. public static Type IndexItemType { get; set; } = null; and add a static constructor to Order to set that type static Order() { IndexItemType = typeof(OrderIndexItem); } In the generic repository I added an extra method public IQueryable<TIndex> ReadIndex<TIndex>() where TIndex : ModelBase, IModelBaseIndexItem { try { } catch (Exception) { throw new IRepositoryException(); } } The idea is to return a DbSet of the type associated to T via the static property IndexItemType. Any thoughts ? Another acceptable solution might be just by using a naming convention of the associated IndexItemType f.e. Order - OrderIndexItem, Member - MemberIndexItem, ... In both approaches the problem that I cannot solve : How to return the appropriate DbSet ? A third approach might be to change the EFRepositoryBase to public class EFRepositoryBase<T, TIndex> : IRepository<T, TIndex> where T : ModelBase, new() where TIndex : ModelBase, IModelBaseIndexItem, new() Though the impact on the code is huge, so I prefer not to use this approach unless it is the only one. A: Eventually I went for the following solution to not limit the repository to just one type of view per ModelBase POCO. public IQueryable<TSqlView> ReadSqlView<TSqlView>() where TSqlView : ISqlViewItem, new() { try { return (IQueryable<TSqlView>)Db.Set( typeof(TSqlView)); } catch (Exception) { throw new IRepositoryException(); } }
[ "stackoverflow", "0047931269.txt" ]
Q: how to use assertoff from test to disable assertion in side uvm object I am looking for way to disable assert in side uvm component for certain test. Below simple code represent my env, with comment for requirement. I thought I can use $assertoff. I can modify uvm component if required additional instrumentation to achieve this. import uvm_pkg::*; `include "uvm_macros.svh" class tb_env extends uvm_component; `uvm_component_utils(tb_env) int exp_val = 0; int act_val = 0; function new(string name = "tb_env", uvm_component parent = null); super.new(name, parent); endfunction virtual task run_phase (uvm_phase phase); super.run_phase(phase); phase.raise_objection(this); #10us; ASRT: assert ( exp_val == act_val) else `uvm_error(get_name(), "Error"); #10us; `uvm_info(get_name(), "Done env", UVM_LOW); phase.drop_objection(this); endtask : run_phase endclass program tb_run; initial begin tb_env env = new("env"); // Requirement: Disable assertion env.ASRT with system call $assertoff(...) fork run_test(); begin #5us; env.exp_val = 1; end join end endprogram A: Yes you can use $assertoff for your purpose. Here is your code without $assertoff. class tb_env; int exp_val = 0; int act_val = 0; virtual task run_phase (); #10; ASRT: assert ( exp_val == act_val) else $error("Error"); endtask : run_phase endclass program tb_run; tb_env env = new(); initial begin // $assertoff(0, env.run_phase.ASRT); fork env.run_phase(); begin #5; env.exp_val = 1; $display("@%0t : exp_val - %0b, act_val - %0b", $time(), env.exp_val, env.act_val); end join end endprogram // Output - @5 : exp_val - 1, act_val - 0 "a.sv", 7: $unit::\tb_env::run_phase .ASRT: started at 10s failed at 10s Offending '(this.exp_val == this.act_val)' Error: "a.sv", 7: $unit.tb_env::run_phase.ASRT: at time 10 Error $finish at simulation time 10 And here is your code with $assertoff. class tb_env; int exp_val = 0; int act_val = 0; virtual task run_phase (); #10; ASRT: assert ( exp_val == act_val) else $error("Error"); endtask : run_phase endclass program tb_run; tb_env env = new(); initial begin $assertoff(0, env.run_phase.ASRT); fork env.run_phase(); begin #5; env.exp_val = 1; $display("@%0t : exp_val - %0b, act_val - %0b", $time(), env.exp_val, env.act_val); end join end endprogram // Output - Stopping new assertion attempts at time 0s: level = 0 arg = $unit::\tb_env::run_phase .ASRT (from inst tb_run (a.sv:17)) @5 : exp_val - 1, act_val - 0 $finish at simulation time 10
[ "stackoverflow", "0010913312.txt" ]
Q: How to get attribute value and replace it in dynamically generated xml file? I have a xml file . I have to search for an attribute and to replace its value with some value using c# Further i dont know how many times does this attribute come and in how many elements as this xml is generated dynamically. Any help over this? A: One way is to load the document into a System.Xml.XmlDocument instance, then find all occurrences of the respective attribute by using the SelectNodes method of the XmlDocument instance with an XPath expression and modify them accordingly. Here's an example: Assume the following Xml document: <?xml version="1.0"?> <test> <a/> <b myAttribute="someValue"/> <c myAttribute="someOtherValue"/> <d/> <e> <f myAttribute="yetAnotherValue" anotherAttribute="anIrrelevantValue"/> </e> </test> Save the Xml document as test.xml. In the same directory, compile the following program. It will change the values of all attributes that are called myAttribute (selected by the XPath expression //@myAttribute): using System; using System.Xml; class Program { public static void Main(string[] args) { XmlDocument doc = new XmlDocument(); doc.Load("test.xml"); Console.WriteLine("Before:"); Console.WriteLine(doc.OuterXml); foreach (XmlNode node in doc.SelectNodes("//@myAttribute")) { node.Value = "new value"; } Console.WriteLine("After:"); Console.WriteLine(doc.OuterXml); doc.Save("test.xml"); Console.ReadLine(); } } (For your convenience, it also outputs the Xml document before and after the modification.) With Namespaces Now, the example is extended with namespaces (the XLink one, as requested by the OP): Xml file: <?xml version="1.0"?> <test xmlns:xlink="http://www.w3.org/1999/xlink"> <a/> <b xlink:myAttribute="someValue"/> <c myAttribute="someOtherValue"/> <d/> <e> <f xlink:myAttribute="yetAnotherValue" anotherAttribute="anIrrelevantValue"/> </e> </test> C# code: using System; using System.Xml; class Program { public static void Main(string[] args) { XmlDocument doc = new XmlDocument(); doc.Load("test.xml"); Console.WriteLine("Before:"); Console.WriteLine(doc.OuterXml); XmlNamespaceManager nsMgr = new XmlNamespaceManager(doc.NameTable); nsMgr.AddNamespace("xlink", "http://www.w3.org/1999/xlink"); foreach (XmlNode node in doc.SelectNodes("//@xlink:myAttribute", nsMgr)) { node.Value = "new value"; } Console.WriteLine("After:"); Console.WriteLine(doc.OuterXml); doc.Save("test.xml"); Console.ReadLine(); } } Remark 1: Note how only two occurrences of attributes called myAttribute are modified now, the third one (in the <c> element) does not belong to the namespace indicated in the XPath expression. Remark 2: The namespace prefix used in the Xml file and the C# code happens to be the same (xlink), but this is not required. You could, for example, use xl in the C# code instead and obtain the same result (only showing the changed lines): nsMgr.AddNamespace("xl", "http://www.w3.org/1999/xlink"); foreach (XmlNode node in doc.SelectNodes("//@xl:myAttribute", nsMgr)) {
[ "stackoverflow", "0007122305.txt" ]
Q: ActionScript 3 Singleton instantiation - advice I have an AS3 Singleton: package { public class Singleton { public function Singleton(enforcer:SingletonEnforcer):void { if(!enforcer){throw new Error("Only one instance of Singleton Class allowed.");} } private static var _instance:Singleton; public static function getInstance():Singleton { if(!Singleton._instance) { Singleton._instance=new Singleton(new SingletonEnforcer()); } return Singleton._instance; } } } class SingletonEnforcer{} Consider prop and func() to be a property and method respectively of the Singleton class. How should I access them? 1. Make them static and use this: Singleton.getInstance(); Singleton.prop; Singleton.func(); 2. Not make them static and use this: Singleton.getInstance().prop; Singleton.getInstance().func(); Does it matter, or is it just visual prefference? Thank you. A: The reason to use a singleton instance is so that you can have class members used in a (relatively) static way. I won't get into the arguments over whether or not to use a singleton here, there's a very long debate over whether it's a good pattern or not. Typically, when singletons are used, you store access to them in a local variable and use them like any other class instance. The primary difference, is instead of using: foo = new Foo(); You use: foo = Foo.instance; //Actionscript supports properties which makes this a self-initializing call -or- foo = Foo.getInstance(); Followed by foo.bar(); foo.baz(); foo.fizz = 'buzz'; This doesn't mean that Foo can't have static members of the class, but the rules for adding static members on a Singleton are the same for adding static members to any other class. If the function belongs to the instance, it should be used on the instance, if it belongs to the class, it should be static.
[ "stackoverflow", "0036644483.txt" ]
Q: Mongodb:Failed to connect I am new to MongoDB.I installed mongodb and used with Laravel framework.Its had been worked for a long time without any issues.But currently while i try to acess my website it shows: Failed to connect to: localhost:27017: Connection refused when i try to acces mongodb via command line,it shows: warning: Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused Error: couldn't connect to server 127.0.0.1:27017 (127.0.0.1), connection attempt failed at src/mongo/shell/mongo.js:146 exception: connect failed when i try to access it via rock tool,it shows: Unable to connect MongoDB, please check your configurations. MongoDB said:Failed to connect to: 127.0.0.1:27017: Connection refused. what i will do? I can't figure what's wrong from my part since its working after the past months.I do nothing since the last days.Thanks in advance.. A: After a short break, I can find out the solution. The origin of that issue is the unexpected shutdown of the system.So i run the below code in command prompt: sudo rm /var/lib/mongodb/mongod.lock mongod --repair sudo service mongodb start then after the above code run, its working fine :)
[ "stackoverflow", "0046744099.txt" ]
Q: PHP Json not working with jsoncallback $Data = 'jQuery1111014795648865074196_1507974360762({"type":"my","start":1,"end":20,"total":20})'; $D2 = json_decode($Data); echo $Result_Count = $D2->{'total'}; Above code not working for me but if i remove jQuery1111014795648865074196_1507974360762() so it's working fine working example $Data = '{"type":"my","start":1,"end":20,"total":20}'; $D2 = json_decode($Data); echo $Result_Count = $D2->{'total'} A: Try the following: $Data = 'jQuery1111014795648865074196_1507974360762({"type":"my","start":1,"end":20,"total":20})'; $Data = preg_replace("/^[\w]+[(]|[)]$/", '', $Data); $D2 = json_decode($Data); echo $Result_Count = $D2->total; This uses regex to remove the prefix and brackets from the json string.
[ "stackoverflow", "0055137159.txt" ]
Q: distinguishing json column of RowProxy in SQLAlchemy? For example, when I execute following code, resulting data type is str: result = engine.execute(''' SELECT CAST('{"foo": "bar"}' as JSON) as `json` ''') row = result.fetchone() json = row[0] type(json) An json column value having type of str is not so much meta-programming friendly. Question Is there any way to fetch information from the result (or, an instance of ResultProxy) what each column's type was? env MySQL: 8.0.11 SQLAlchemy: 1.3.0 pymysql: 0.9.3 A: You can at least achieve it by explicitly telling SQLAlchemy that the result is JSON: from sqlalchemy.types import JSON stmt = text('''SELECT CAST('{"foo": "bar"}' as JSON) as `json`''') stmt = stmt.columns(json=JSON) row = engine.execute(stmt).fetchone() type(row.json)
[ "askubuntu", "0000007409.txt" ]
Q: Only view the CPU temperature from command `sensors` Ok, so when I run the command: sensors I get a truck load of info: atk0110-acpi-0 Adapter: ACPI interface Vcore Voltage: +1.16 V (min = +0.85 V, max = +1.60 V) +3.3 Voltage: +3.39 V (min = +2.97 V, max = +3.63 V) +5 Voltage: +5.17 V (min = +4.50 V, max = +5.50 V) +12 Voltage: +12.36 V (min = +10.20 V, max = +13.80 V) CPU FAN Speed: 1906 RPM (min = 600 RPM) CHASSIS FAN Speed: 0 RPM (min = 600 RPM) CPU Temperature: +31.0°C (high = +60.0°C, crit = +95.0°C) MB Temperature: +32.0°C (high = +45.0°C, crit = +95.0°C) What would the command be if I just wanted to see this: CPU Temperature: +31.0°C (high = +60.0°C, crit = +95.0°C) or better yet, just this: CPU Temperature: +31.0°C A: You can process the output of sensors command with grep and/or cut to format it the way you want. To get only the line reporting the CPU temperature you can use this (including the high and critical limits): sensors | grep -A 0 'CPU T' The following will give you only the temperature (with the °C suffix) : sensors | grep -A 0 'CPU T' | cut -c18-25 This will give the output as you indicated at the end of your question: sensors | grep -A 0 'CPU T' | cut -c1-25
[ "stackoverflow", "0031188402.txt" ]
Q: Java: Can't find symbol In Javadoc it was written that : public static String toString(double d) Returns a string representation of the double argument. All characters mentioned below are ASCII characters. If the argument is NaN, the result is the string "NaN". But when I am compiling below code it is giving error: Cant find symbol NaN String intStr2 =Double.toString(NaN); A: Since NaN is not defined, it throws a compilation error, use the following to overcome the same, String intStr2 = Double.toString(Double.NaN); A: Double.NaN is defined in Double.java as (ref jdk8) /** * A constant holding a Not-a-Number (NaN) value of type * {@code double}. It is equivalent to the value returned by * {@code Double.longBitsToDouble(0x7ff8000000000000L)}. */ public static final double NaN = 0.0d / 0.0; And it is well converted in String "NaN" String intStr2 =Double.toString(Double.NaN); System.out.println(intStr2);
[ "stackoverflow", "0056306211.txt" ]
Q: Is there any option to do Column split? Need to see maker names against car models something like this: trying to use below function, but it is creating as list strsplit(carz$maker,split = " ") A: Here is an approach that uses lapply() with the Motor Trend Cars data frame. data(mtcars) mtcars$type <- rownames(mtcars) mtcars$make <-unlist(lapply(strsplit(mtcars$type," "),function(x){x[[1]]})) head(mtcars) and the result: > head(mtcars) mpg cyl disp hp drat wt qsec vs am gear carb Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1 type make Mazda RX4 Mazda RX4 Mazda Mazda RX4 Wag Mazda RX4 Wag Mazda Datsun 710 Datsun 710 Datsun Hornet 4 Drive Hornet 4 Drive Hornet Hornet Sportabout Hornet Sportabout Hornet Valiant Valiant Valiant > Note, that some additional data cleaning is necessary, because the Valiant and Duster were made by Plymouth, the Camaro Z28 was made by Chevrolet, and the Hornet 4 Drive was made by American Motor Cars, also known as AMC. Regarding the question in the comments about the syntax used within lapply(), I used lapply() to process the results of strsplit(), including an anonymous function that extracts the first word from each element of the list. Since the output of an R function can be used as the argument to another function, this solution nests functions to produce the desired result. The sapply() answer provided by akrun does the same thing, using output from strsplit() as its input, and using [, one of the four forms of the extract operator to extract the data. sapply() also produces a vector rather than a list as its output.
[ "ru.stackoverflow", "0000723942.txt" ]
Q: Неверный ответ c++ При решении выводится не тот результат, подскажите пожалуйста,что не так. double x,y,z,s,d; cout << "Vvedite x: "; cin >> x; cout << "Vvedite y: "; cin >> y; cout << "Vvedite z: "; cin >> z; d = fabs(y - x); s = (pow(x, y + 1) + exp(y - 1)) / (1 + x* fabs(y - tan(z))); s *=(1 + fabs(y - x) + ((pow(d, 2) / 2) - (pow(d, 3) / 3))); cout << "Result s= "<< s << endl; A: Должно быть не s *=(1 + fabs(y - x) + ((pow(d, 2) / 2) - (pow(d, 3) / 3))); а, например, s = s*(1 + fabs(y - x)) + ((pow(d, 2) / 2) - (pow(d, 3) / 3)));
[ "stackoverflow", "0021729262.txt" ]
Q: Delete all field with autoincrement and reset count There's a way to reset auto-increment field when all rows is deleted from table? I've noticed if i have 300 rows inside my table, and i execute DELETE * FROM myTable; When i insert new row after delete, auto increment count continue count from last value (also if table is empty. It's possible to reset auto increment count when all rows are deleted? A: You need to use TRUNCATE instead of DELETE Like this: TRUNCATE myTable; It also much faster than DELETE (especially on big tables)
[ "math.stackexchange", "0001364507.txt" ]
Q: Explicit solution for equation The claim is that this equation has an explicit solution. $$\frac{\partial}{\partial t}c(x,t)=\frac{a}{\pi}\int_{\mathbb{R}}\frac{c(y,t)-c(x,t)}{(y-x)^2}dy.$$ What can one do to find this solution? Fourier-transformation or similar transformations? Find the operator semigroup? A: This isn't totally rigorous. The Fourier transform of $x\mapsto \frac1{x^2}$ is $\xi\mapsto -\sqrt{\frac \pi2}|\xi|$. (Here I am using $\hat f(w) = \frac1{\sqrt{2\pi}} \int_{-\infty}^\infty f(t) e^{i w t}\,dt$.) So realizing that in your formula you need to subtract the $c(x,t)$ inside the integral to avoid an otherwise unworkable singularity at the origin, you see that the Fourier transform of your equation is $$ \frac{\partial}{\partial t} \hat c(\xi,t) = -a \frac1{\sqrt{2\pi}} |\xi| \hat c(\xi,t) .$$ The solution to this is $$ \hat c(\xi,t) = \exp\left(-a t \frac1{\sqrt{2\pi}} |\xi|\right) \hat c(\xi,0) .$$ So taking the inverse Fourier transform, we get the convolution $$ c(x,t) = \frac{1}{\sqrt{2\pi}} \int_{-\infty}^\infty \frac{2at}{a^2t^2 + 2\pi (y-x)^2} c(y,t) \, dy .$$ So, to make it semi-rigorous, we need to show that the inverse Fourier transform of $\xi \mapsto -|\xi|$ is the distribution $\mu$ which acts on test functions $\phi$ by $$ \langle \mu,\phi\rangle = \sqrt{\frac 2\pi} \int_{-\infty}^\infty \frac{\phi(x) - \phi(0)}{x^2} \, dx.$$ Now, $$ -|\xi| = \lim_{a\to 0^+} \frac{e^{-a|\xi|} -1}a.$$ And the inverse Fourier transforms of $\xi\mapsto e^{-a|\xi|}$ and $1$ are $x\mapsto \sqrt{\frac 2\pi} \frac a{a^2+x^2}$ and $\frac1{\sqrt{2\pi}} \delta$ respectively. So the inverse Fourier transform of $\xi \mapsto -|\xi|$ acting on the test function $\phi$ is the limit as $a\to 0^+$ of $$ \frac1a \left( \sqrt{\frac 2\pi} \int_{-\infty}^\infty \frac a{a^2+x^2} \phi(x) \, dx - \frac1{\sqrt{2\pi}} \phi(0) \right) = \sqrt{\frac 2\pi} \int_{-\infty}^\infty \frac {\phi(x) - \phi(0)}{a^2+x^2} \, dx ,$$ which converges to the desired quantity. Finally, it is worth noting that if $a = \sqrt{2\pi}$, then the formula for $c(x,t)$ is convolution next to the Poisson kernel, and $c(x,t)$ is a harmonic function of $x$ and $t$. So the distribution $\mu$ is actually the negative square root of $-\frac{\partial^2}{\partial x^2}$.
[ "stackoverflow", "0004575214.txt" ]
Q: How to change the layout of the CreateUserWizard control? How to change just the layout (template) of the CreateUserWizard control programmatically? I would to define another layout (not using the horrid table) but continue to use all the event handling and the creation of the user of the CreateUserWizard control. Just for reference, the following code doesn't work, and produces an unexpected result not representing my Template at all. The "InstantiateIn" method of the ITemplate is not called. public partial class b : System.Web.UI.Page { protected void Page_Init(object sender, EventArgs e) { CreateUserWizard createUserWizard = new CreateUserWizard(); createUserWizard.CreateUserStep.ContentTemplate = new Template(); Panel1.Controls.Add(createUserWizard); } } public class Template : ITemplate { void ITemplate.InstantiateIn(Control container) { container.Controls.Add(new TextBox() { ID = "UserName" }); container.Controls.Add(new TextBox() { ID = "Password" }); container.Controls.Add(new TextBox() { ID = "ConfirmPassword" }); container.Controls.Add(new TextBox() { ID = "Email" }); container.Controls.Add(new PlaceHolder() { ID = "ErrorMessage" }); } } } A: I have no idea why this works, but it does: public partial class _Default : System.Web.UI.Page { protected void Page_Init(object sender, EventArgs e) { CreateUserWizard createUserWizard = new CreateUserWizard(); /* Difference Starts Here */ CreateUserWizardStep createUserWizardStep = new CreateUserWizardStep(); createUserWizardStep.ContentTemplate = new Template(); createUserWizard.WizardSteps.Add(createUserWizardStep); /* End Difference */ Panel1.Controls.Add(createUserWizard); } } public class Template : ITemplate { void ITemplate.InstantiateIn(Control container) { container.Controls.Add(new TextBox() { ID = "UserName" }); container.Controls.Add(new TextBox() { ID = "Password" }); container.Controls.Add(new TextBox() { ID = "Question" }); container.Controls.Add(new TextBox() { ID = "Answer" }); container.Controls.Add(new TextBox() { ID = "ConfirmPassword" }); container.Controls.Add(new TextBox() { ID = "Email" }); container.Controls.Add(new PlaceHolder() { ID = "ErrorMessage" }); } } What I did was add a CreateUserWizard control to a page, added a blank ContentTemplate, and followed the instructions for debugging generated ASP.NET code to reverse engineer what the ASP.NET code generator does.
[ "stackoverflow", "0033115244.txt" ]
Q: YII2 call jquery-ui code before bootstrap.js Here is my asset code.. public $js = [ 'js/jquery-ui.min.js', 'js/app.min.js', ]; I have some widgets used in the view file... and here are the order of the js files. What I want is to call the jquery-ui.js before bootstrap.js.. How to do that?? A: Placing jQuery UI after Bootstrap doesn't make any sense since they are not dependent on each other at all. But for including bundle before another, you should add dependency to the related bundle. For custom asset bundle you can just write this: $depends = [ // Write classes of dependent asset bundles here, for example: 'yii\jui\JuiAsset', ]; But because Bootstrap is built-in asset, you can not modify it that way. Instead you can set it globally through config of Asset Manager: return [ // ... 'components' => [ 'assetManager' => [ 'bundles' => [ 'yii\bootstrap\BootstrapAsset' => [ 'depends' => [ 'yii\jui\JuiAsset', ]; ], ], ], ], ]; Or just set dependency in one specific place before rendering view: Yii::$app->assetManager->bundles['yii\bootstrap\BootstrapAsset'] = [ 'depends' => [ 'yii\jui\JuiAsset', ]; ], Official docs: Customizing built-in asset bundles Asset Manager yii\web\AssetBundle $depends
[ "math.stackexchange", "0000415067.txt" ]
Q: How find this equation integer solution:$x^2y^2=4x^5+y^3$ find $x,y\in Z$,and such that $$x^2y^2=4x^5+y^3$$ and I use mathmatical give me: my try: Let $gcd(x,y)=d$ and put $x=da, y=db$, with $a$ and $b$ coprime: $d^4a^2b^2 = 4d^5a^5 + d^3b^3 \Rightarrow da^2b^2=4d^2a^5+b^3$. Hence, we have that $a|b^3$ and as $gcd(a,b)=1$, $a=1$ or $a=-1$. Plugging it back, we have $4d^2-db^2+b^3=0$ or $4d^2+db^2-b^3=0$. The discriminant, in the first case, is $b^4-16b^3$, which must be a perfect square. Therefore, $b^2-16b = k^2$, where $k$ is an integer. This gives us $(b-8)^2 - k^2 = 64$. From this, we get the following pairs: $(125,3025), (27, 486), (54, 972), (32, 512)$. In the second case, the discriminant is $b^4+16b^3$, which must be a perfect square again. Therefore, $b^2+16b=l^2$, where $l$ is an integer. This gives us $(b+8)^2-l^2 = 64$. From this, we get the following pairs: $(0,0), (2,-4), (-1,2), (27, -243)$ my try is true? and have other methods? A: Here's another approach: $$x^2 y^2 = 4 x^5 + y^3$$ This is trivially satisfied by for $x=0, y=0$ and $x=0 \Leftrightarrow y = 0$ Now assume $x,y \ne 0$ For an odd prime $p$ suppose $p^n \parallel x$, and $p^m \parallel y$, with $x = p^n \tilde{x}$ and $y = p^m \tilde{y}$, so that $p \nmid \tilde{x}$ and $p \nmid \tilde{y}$ Then we have $$p^{2(n+m)} \tilde{x}^2 \tilde{y}^2 = 4 p^{5n} \tilde{x}^5 + p^{3m} \tilde{y}^3$$ Now if $m > \frac{5}{3}n$ $$3m - 5n > 3 \frac{5}{3}n - 5n = 0$$ $$2(n+m) - 5n > 2(n+\frac{5}{3}n) - 5n = \frac{1}{3}n \ge 0$$ and $$ p^{2(n+m)-5n} \tilde{x}^2 \tilde{y}^2 = 4 \tilde{x}^5 + p^{3m-5n} \tilde{y}^3 \Rightarrow p | \tilde{x}$$ And if $n > \frac{3}{5}m$ $$5n - 3m > 5 \frac{3}{5}m - 3m = 0$$ $$2(n+m) - 3m > 2(\frac{3}{5}m+m) -3m = \frac{1}{5}m \ge 0$$ and $$ p^{2(n+m)-3m} \tilde{x}^2 \tilde{y}^2 = 4 p^{5n-3m} \tilde{x}^5 + \tilde{y}^3 \Rightarrow p | \tilde{y}$$ Hence we must have $3m = 5n$, and $n = 3k$, $m = 5k$ for some $k \in \mathbb{N}_0$. So for each odd prime, p, $p^{3k} \parallel x$ and $p^{5k} \parallel y$ for some $k \in \mathbb{N}_0$. It follows that $x,y$ are of the form $$x= 2^a z^3, y = \pm 2^b z^5$$ where $a,b \in \mathbb{N}_0, z\in \mathbb{Z}$ is an odd integer. (Note the sign of $x$ is determined by $z$) Now we have $$2^{2(a+b)} z^{16} = 2^{5a+2} z^{15}\pm 2^{3b} z^{15}$$ And with the trivial case $z=0$ excluded $$2^{2(a+b)} z = 2^{5a+2} \pm 2^{3b} $$ Now if $b > \frac{5a + 3}{3}$ then $$3b - (5a+2) > 3 \frac{5a + 3}{3} -(5a+2) = 1 > 0$$ $$2(a+b) -(5a+2) > 2(a+\frac{5a+3}{3}) -(5a+2) = \frac{1}{3}a \ge 0$$ and $$2^{2(a+b)-(5a+2)} z = 1 \pm 2^{3b-(5a+2)} \Rightarrow 2 | 1$$ Now if $a < \frac{3a}{5}b$ then $$5a+2 - 3b > 5 \frac{3}{5}b - 3b = 1 > 0$$ $$2(a+b) - 3b > 2(\frac{3b}{5}+b) -3b = \frac{1}{5}b \ge 0$$ and $$2^{2(a+b)-3b} z = 2^{5a+2-3b} \pm 1 \Rightarrow 2 | 1$$ Hence we must have $5a \le 3b \le 5a+3$ Let $c = 3b - 5a, c=0,1,2,3$ then $$2(a+b) = 2(a+ \frac{5a + c}{3}) = \frac{16a + 2c}{3}$$ $$2^{(16a + 2c)/3} z = 2^{5a+2} \pm 2^{5a+c} $$ $$2^{(a + 2c)/3} z = 4 \pm 2^{c} $$ For $c=0$, $2^{a/3} z = 4 \pm 1 \Rightarrow a=0, b=0, z=3,5$ $(x,y)=(2^0 3^3,- 2^0 3^5), (2^0 5^3, 2^0 5^5) = (27,-243), (125,3125)$ For $c=1$, $2^{(a+2)/3} z = 4 \pm 2 \Rightarrow a=1, b=2, z=1,3$ $(x,y)=(2^1 1^3,-2^2 1^5), (2^1 3^3,2^2 3^5)=(2,-4), (54,972)$ For $c=2$, $2^{(a+4)/3} z = 4 \pm 4 \Rightarrow a=5, b=9, z=0,1$ $(x,y)=(2^5 0^3,-2^9 0^5), (2^5 1^3,2^9 1^5)=(0,0), (32,512)$ For $c=3$, $2^{(a+6)/3} z = 4 \pm 8 \Rightarrow a=0, b=1, z=-1,3$ $(x,y)=(2^0(-1)^3,-2^1(-1)^5), (2^0 3^3,2^1 3^5)=(-1,2), (27,486)$ This is a more generalizable method than the one above which requires that the combined powers of $x$ and $y$ in each term cover no larger a range than $2$ in order to obtain a quadratic in $d$. For instance, a near identical treatment solves $x^2 y^6 = 2^5 x^{13} + y^7$. A: The basic equation is defined here for real $(x,y)$ as well, by: $$ x^2 y^2 = 4 x^5 + y^3 $$ See picture ; window $-200 < x < +200$ , $-4000 < y < +4000$ . It is immediately clear that $(x,y) = (0,0)$ is an (integer) solution of the equation and that $x = 0 \leftrightarrow y = 0$ . $\color{red}{Tangents}\,$ at the curve are calculated by implicit differentation: $$ 2 x y^2 + x^2 2 y y' = 20 x^4 + 3 y^2 y' \quad \Longrightarrow \quad y' = \frac{20 x^4 - 2 x y^2}{2 y x^2 - 3 y^2} $$ Horizontal tangents at: $$ 20 x^4 - 2 x y^2 = 0 \quad \Longrightarrow \quad y^2 = 10 x^3 $$ Substitute into the basic equation to obtain: $$ x^2 y^2 = 4 x^5 + y^3 \quad \Longrightarrow \quad x^2 \cdot 10 x^3 = 4 x^5 + 10 x^3 y $$ We have covered the trivial solution $(0,0)$ so forget about it in the sequel. $$ 6 x^2 = 10 y \quad \Longrightarrow \quad 36 x^4 = 100 y^2 = 1000 x^3 \quad \Longrightarrow \quad (x_S,y_S) = \left(\frac{10^3}{6^2},\sqrt{\frac{10^{10}}{6^6}}\right) $$ The Special point  S  is important for the numerical work that follows. Vertical tangents at: $$ 2 y x^2 - 3 y^2 = 0 \quad \Longrightarrow \quad y = \frac{2}{3} x^2 $$ Substitute into the basic equation to obtain: $$ x^2 \cdot \frac{4}{9} x^4 = 4 x^5 + \frac{8}{27} x^6 \quad \Longrightarrow \quad \frac{4}{27} x = 4 \quad \Longrightarrow \quad (x,y) = (27,486) $$ The latter happens to be one of the required integer solutions !The rest of the method is brute force. It is clear from the picture that there are four branches: one extending from $(0,0)$ towards minus infinity in the quadrant $x > 0$ , $y < 0$indicated as A one extending from $(0,0)$ towards plus infinity in the quadrant $x < 0$ , $y > 0$indicated as B one extending from the special point  S  towards plus infinity on the right sidein the quadrant $x > 0$ , $y > 0$ , indicated as C one extending from the special point  S  towards plus infinity on the left sidein the quadrant $x > 0$ , $y > 0$ , indicated as D Therefore four "crawlers" are contained in the computer program, which is listed below.The crawlers seek for integer solutions by crawling along the four branches of the curve, for some time, until someone hits the Ctrl-C key to halt. It's clearly inferior to the method presented by the other author (: Neil), but it finds all the solutions, except some trivial ones. program krabbel; function pow(x : double; n : integer) : double; var q : double; k : integer; begin q := 1; for k := 1 to n do q := q * x; pow := q; end; function f(x,y : double) : double; begin f := pow(x,2)*pow(y,2) - (4*pow(x,5) + pow(y,3)); end; procedure crawl_A; var x,y : integer; g : double; begin x := 0; y := 0; while true do begin y := y - 1; g := f(x,y); if g = 0 then Writeln(x,' ',y); while g > 0 do begin x := x + 1; g := f(x,y); if g = 0 then Writeln(x,' ',y); end; end; end; procedure crawl_B; var x,y : integer; g : double; begin x := 0; y := 0; while true do begin y := y + 1; g := f(x,y); if g = 0 then Writeln(x,' ',y); while g < 0 do begin x := x - 1; g := f(x,y); if g = 0 then Writeln(x,' ',y); end; end; end; procedure crawl_C; var x,y : integer; g : double; begin x := Round(pow(10,3)/pow(6,2)); y := Round(sqrt(pow(10,10)/pow(6,6))); while true do begin y := y + 1; g := f(x,y); if g = 0 then Writeln(x,' ',y); while g > 0 do begin x := x + 1; g := f(x,y); if g = 0 then Writeln(x,' ',y); end; end; end; procedure crawl_D; var x,y : integer; g : double; begin x := 27; y := 486; while true do begin y := y + 1; g := f(x,y); if g = 0 then Writeln(x,' ',y); while g < 0 do begin x := x + 1; g := f(x,y); if g = 0 then Writeln(x,' ',y); end; end; end; begin { crawl_A; crawl_B; } crawl_C; { crawl_D; } end. Results $\;\rightarrow picture: \color{red}{dots}$ by hand: 0 0 27 486 crawl_A: 2 -4 27 -243 crawl_B: -1 2 crawl_C: 32 512 54 972 125 3125 crawl_D: nothing
[ "stackoverflow", "0049021861.txt" ]
Q: How can I obtain the WLAN ISP name in iOS? Fellow overflowers, I am developing an iOS application using the latest SDK (11.2) and Swift 4. I am looking for a way to obtain the WLAN ISP name. (for example, my ISP at home is called NET1 Ltd.) Thanks in advance! A: CTCarrier will only return carrier info if your iOS device has a SIM card. A better way to obtain it is via an webservice like ipinfo.io. Here's an example in Playground: import PlaygroundSupport import Foundation PlaygroundPage.current.needsIndefiniteExecution = true let url = URL(string: "https://ipinfo.io/org")! URLSession.shared.dataTask(with: url) { data, response, error in guard error == nil else { print(error!); return } guard let data = data else { print("Empty data"); return } if let ispName = String(data: data, encoding: .utf8) { print(ispName) } else { print("Can't obtain ISP name") } }.resume()
[ "stackoverflow", "0057103392.txt" ]
Q: Extend object lifetime/scope from a `if constexpr` branch Say we have the following code struct MyClass { MyClass() = delete; // or MyClass() { } MyClass(int) { } void func() { } }; int main() { if constexpr (std::is_default_constructible_v<MyClass>) { MyClass myObj; } else { MyClass myObj(10); } myObj.func(); // Error } Here I am using if constexpr to determine whether the class is default-constructible (or not), and then create an object accordingly. In a way, I naively thought this would simplify the different branches down to just the one that's true, i.e. if constexpr (true) { /* instruction branch 1 */ } else if constexpr (false) { /* instruction branch 2 */ } simply becomes /* instruction branch 1 */ But in reality, it is probably more like this { /* instruction branch 1 */ } But then the question becomes (going to back to the the very first example), how can I can I keep myObj in scope outside the { ... }? A: You can't extend the lifetime of an object with automatic storage duration beyond the scope in which it's created. What you can do is create uninitialized storage outside your if block and create an object in that storage within the scope of the if. The easiest way to do that is probably std::optional: template <typename T> void foo() { std::optional<T> obj; if constexpr (std::is_default_constructible_v<T>) { obj.emplace(); } else { obj.emplace(10); } obj->func(); } Live Demo This does result in a small amount of overhead though, since std::optional has to hold an extra flag to determine if it holds an object or not. If you want to avoid that overhead you could manage the storage yourself: template <typename T> void foo() { std::aligned_storage_t<sizeof(T), alignof(T)> storage; T* ptr; if constexpr (std::is_default_constructible_v<T>) { ptr = new(&storage) T{}; } else { ptr = new(&storage) T{10}; } struct destroy { destroy(T* ptr) : ptr_{ptr} {} ~destroy() { ptr_->~T(); } T* ptr_; } destroy{ptr}; ptr->func(); } Live Demo Note that in both cases I've moved the functionality to a function template. For if constexpr to discard a branch it must be dependent on a template parameter. If you try to do this directly in main the false branch will not be discarded and you will get an error complaining about a missing default constructor. A: First, your code won't work. if constexpr really needs its condition to be dependent. I'll fix it. template<class MyClass> void func() { MyClass myObj = []{ if constexpr (std::is_default_constructible_v<MyClass>) { return MyClass{}; } else { return MyClass(10); } }(); myObj.func(); } now int main() { func<MyClass>(); } solves your problem. Note that under c++17 rules, no copies or moves of MyClass occur in the above code.
[ "superuser", "0000716749.txt" ]
Q: find all files in a directory without specified permissions I want to list out all the files and directories in a directory without 777 and 755 permissions Whats the command using linux Ubuntu command prompt? A: if Folderpath is the path of folder in which you are interested ls -l Folderpath | egrep -v 'drwxrwxrwx|drwxr-xr-x|-rwxr-xr-x|-rwxrwxrwx' will give result in this format total 82796 -rw-rw-rw- 1 imran imran 40203707 Feb 13 14:32 tmp_13-02.14.log removing files and directories with permission 777 and 755 In case you only want the names of files and folders ls -l Folderpath | egrep -v 'drwxrwxrwx|drwxr-xr-x|-rwxr-xr-x|-rwxrwxrwx' |rev| cut -d ' ' -f 1| rev| tail -n +2 Output will be tmp_13-02.14.log . .
[ "unix.stackexchange", "0000045950.txt" ]
Q: How to remove only the content of directories? I'm in a folder: /var/myfolder. Inside there are some other folders like: /var/myfolder/A/ /var/myfolder/B/ `/var/myfolder/C/ etc. Inside each there are some files with random names. How do I remove all the files from all the folders inside /var/myfolder? The structure (all the directories, eg., A, B, C etc., inside /var/myfolder) should remain intact. A: Try: find /var/myfolder -type f -delete This gets all the regular files under /var/myfolder and deletes them leaving only the directories. A: With zsh, use the . glob qualifier to match only regular files: rm -- **/*(.) This deletes all the (non-hidden) regular files in the current directory and its subdirectories recursively. Add the D glob qualifier to delete hidden regular files (and regular files in hidden directories) as well. A: You can run rm */* in /var/myfolder
[ "stackoverflow", "0003312564.txt" ]
Q: NHibernate to access Oracle stored procedure REFCURSOR and output parameter Does the current version of NHibernate (v2.1.2) support access Oracle stored procedure output REFCURSOR in addition to an output parameter? I can access the output refcursor fine with my code. However i'm not sure i can access the additional output param in the same stored procedure. Some sample of calling syntax would be greatly appreciated. thanks. A: Nope it does not. Only one refcursor is supported and it has to be the first parameter in the sproc. You can always get the IDbConnection from the session and then use plain ODP.Net for such scenarios (you lose nh functionality) or rather change the stored procedure.
[ "stackoverflow", "0048224397.txt" ]
Q: R shiny reactive list of files New to shiny, I want my app to display all files in a directory, and make the list update every time a file is added or removed. I see this is possible with reactivePoll, so I put this in my server: server <- function(input, output, session) { has.new.files <- function() { length(list.files()) } get.files <- function() { list.files() } output$files <- renderText(reactivePoll(10, session, checkFunc=has.new.files, valueFunc=get.files)) } However, I don't know how I can access the character vector containing my files within my ui. I also doubt that renderText in my server is the right choice. Here is my ui (non-reactive, just reads file list once): ui <- fluidPage( ## How to access the files from server function ?? selectInput("file", "Choose file", list.files()) ) Thus, I just don't know hot to access the data, could anyone point me in the right direction? A: You could try this: server <- function(input, output, session) { has.new.files <- function() { unique(list.files()) } get.files <- function() { list.files() } # store as a reactive instead of output my_files <- reactivePoll(10, session, checkFunc=has.new.files, valueFunc=get.files) # any time the reactive changes, update the selectInput observeEvent(my_files(),ignoreInit = T,ignoreNULL = T, { print(my_files()) updateSelectInput(session, 'file',choices = my_files()) }) } ui <- fluidPage( selectInput("file", "Choose file", list.files()) ) shinyApp(ui,server) It updates the selectInput any time a file is added, deleted or renamed. If you only want it to change if a file is added, you can replace the has.new.files function back with your own. Hope this helps!
[ "stackoverflow", "0028814318.txt" ]
Q: Controllers and downloading files with 'send_data' I can create both xl and csv files formats fine, and would like to create a download link for them within a form. A user can generate a search for records using this form =simple_form_for :guestlist_booking_search, controller: 'guestlist_bookings_controller', action: 'index', method: :get do |f| %fieldset %legend Guestlist Booking Search = f.input :lastname = f.input :start, as: :string, class: "form-control auto_picker1", :input_html => { :class => 'auto_picker1', value: guestlist_booking_search.start.strftime('%d-%m-%Y %H:%M') } = f.input :finish, as: :string, class: "form-control auto_picker2", :input_html => { :class => 'auto_picker2', value: guestlist_booking_search.finish.strftime('%d-%m-%Y %H:%M') } = f.submit "Submit" = f.submit "Download CSV", name: "download_csv" So the form has two submit buttons, I would like one to process the search and display the results, and the other to process the search and begin downloading an csv file. So in my index action I have this def index if params[:download_csv] respond_to do |format| format.html format.csv { send_data @guestlist_bookings.to_csv } end end end the guestlist_bookings variable is set in a before block (generating and displaying the search works fine ). What I can't seem to work out is how to get the file to begin downloading. Currently there is no response from the .xls block. From what I can understand the 'send_data' function is what is used to start a download from the controller. A: I think your problem is that it's evaluating the format.html block, not the format.csv block, because you haven't told it that the required format is csv. Try changing your first line like so - this uses a named route which is nicer for various reasons: =simple_form_for :guestlist_booking_search, url: guestlist_bookings_path(format: "csv"), method: :get do |f|
[ "stackoverflow", "0058672215.txt" ]
Q: Automating a script on a cell value change I am a complete novice to Google Script for Sheets. I have a script that works to geocode an address. It works when I select the three columns "Address", "Lat", "Lng" and press the Geocode tab. However, when I use it, I have to press that tab, and then select "run script on selected cells" before it will work. So, what I am after: If an address is entered using another app, into the cell J2 (for example), I would want Google Sheets to automatically select J2, K2, and L2, then run the geocode script on those cells. I hope that makes sense? Sorry, but my script knowledge is minimal, but I can follow clear instructions if anyone is able to help. Here is the code: return PropertiesService.getDocumentProperties().getProperty('GEOCODING_REGION') || 'us'; } /* function setGeocodingRegion(region) { PropertiesService.getDocumentProperties().setProperty('GEOCODING_REGION', region); updateMenu(); } function promptForGeocodingRegion() { var ui = SpreadsheetApp.getUi(); var result = ui.prompt( 'Set the Geocoding Country Code (currently: ' + getGeocodingRegion() + ')', 'Enter the 2-letter country code (ccTLD) that you would like ' + 'the Google geocoder to search first for results. ' + 'For example: Use \'uk\' for the United Kingdom, \'us\' for the United States, etc. ' + 'For more country codes, see: https://en.wikipedia.org/wiki/Country_code_top-level_domain', ui.ButtonSet.OK_CANCEL ); // Process the user's response. if (result.getSelectedButton() == ui.Button.OK) { setGeocodingRegion(result.getResponseText()); } } */ function addressToPosition() { var sheet = SpreadsheetApp.getActiveSheet(); var cells = sheet.getActiveRange(); // Must have selected 3 columns (Address, Lat, Lng). // Must have selected at least 1 row. if (cells.getNumColumns() != 3) { Logger.log("Must select at least 3 columns: Address, Lat, Lng columns."); return; } var addressColumn = 1; var addressRow; var latColumn = addressColumn + 1; var lngColumn = addressColumn + 2; var geocoder = Maps.newGeocoder().setRegion(getGeocodingRegion()); var location; for (addressRow = 1; addressRow <= cells.getNumRows(); ++addressRow) { var address = cells.getCell(addressRow, addressColumn).getValue(); // Geocode the address and plug the lat, lng pair into the // 2nd and 3rd elements of the current range row. location = geocoder.geocode(address); // Only change cells if geocoder seems to have gotten a // valid response. if (location.status == 'OK') { lat = location["results"][0]["geometry"]["location"]["lat"]; lng = location["results"][0]["geometry"]["location"]["lng"]; cells.getCell(addressRow, latColumn).setValue(lat); cells.getCell(addressRow, lngColumn).setValue(lng); } } }; function positionToAddress() { var sheet = SpreadsheetApp.getActiveSheet(); var cells = sheet.getActiveRange(); // Must have selected 3 columns (Address, Lat, Lng). // Must have selected at least 1 row. if (cells.getNumColumns() != 3) { Logger.log("Must select at least 3 columns: Address, Lat, Lng columns."); return; } var addressColumn = 1; var addressRow; var latColumn = addressColumn + 1; var lngColumn = addressColumn + 2; var geocoder = Maps.newGeocoder().setRegion(getGeocodingRegion()); var location; for (addressRow = 1; addressRow <= cells.getNumRows(); ++addressRow) { var lat = cells.getCell(addressRow, latColumn).getValue(); var lng = cells.getCell(addressRow, lngColumn).getValue(); // Geocode the lat, lng pair to an address. location = geocoder.reverseGeocode(lat, lng); // Only change cells if geocoder seems to have gotten a // valid response. Logger.log(location.status); if (location.status == 'OK') { var address = location["results"][0]["formatted_address"]; cells.getCell(addressRow, addressColumn).setValue(address); } } }; function generateMenu() { // var setGeocodingRegionMenuItem = 'Set Geocoding Region (Currently: ' + getGeocodingRegion() + ')'; // { // name: setGeocodingRegionMenuItem, // functionName: "promptForGeocodingRegion" // }, var entries = [{ name: "Geocode Selected Cells (Address to Lat, Long)", functionName: "addressToPosition" }, { name: "Geocode Selected Cells (Address from Lat, Long)", functionName: "positionToAddress" }]; return entries; } function updateMenu() { SpreadsheetApp.getActiveSpreadsheet().updateMenu('Geocode', generateMenu()) } /** * Adds a custom menu to the active spreadsheet, containing a single menu item * for invoking the readRows() function specified above. * The onOpen() function, when defined, is automatically invoked whenever the * spreadsheet is opened. * * For more information on using the Spreadsheet API, see * https://developers.google.com/apps-script/service_spreadsheet */ function onOpen() { SpreadsheetApp.getActiveSpreadsheet().addMenu('Geocode', generateMenu()); // SpreadsheetApp.getActiveSpreadsheet().addMenu('Region', generateRegionMenu()); // SpreadsheetApp.getUi() // .createMenu(); }; A: I would suggest onEdit() trigger, but as you'll not be updating the Spreasheet manually but programmatically, onEdit() trigger won't work for you because triggers are only triggered if the action is done manually [1]. I suggest you use a time-driven trigger, to update the sheet every given time [1], for example: function createTimeDrivenTriggers() { // Trigger every 6 hours. ScriptApp.newTrigger('myFunction') .timeBased() .everyHours(6) .create(); // Trigger every Monday at 09:00. ScriptApp.newTrigger('myFunction') .timeBased() .onWeekDay(ScriptApp.WeekDay.MONDAY) .atHour(9) .create(); } You could obtain the entire data with getDataRange() function [2] and use the values to update all the rows. Other option would be to save the number of rows in an attribute with the Properties Service [3] and use it to compare how many new rows are they and update only those new rows. UPDATE After reviewing you comments I put together the following code: function getGeocodingRegion() { return PropertiesService.getScriptProperties().getProperty('GEOCODING_REGION') || 'us'; } function createTimeDrivenTrigger() { ScriptApp.newTrigger("addressToPosition") .timeBased() .everyMinutes(15) .create(); } function addressToPosition() { var sheet = SpreadsheetApp.openById("[SPREADSHEET-ID]").getSheets()[0]; var cells = sheet.getRange("M2:M" + sheet.getLastRow()).getValues(); var geocoder = Maps.newGeocoder().setRegion(getGeocodingRegion()); var location; var locationsArray = []; for (var addressRow = 0; addressRow<cells.length; addressRow++) { var address = cells[addressRow][0]; locationsArray[addressRow] = []; var err; // Geocode the address and plug the lat, lng pair into the // 2nd and 3rd elements of the current range row. try{ location = geocoder.geocode(address); } catch(error) { err = error; Logger.log(err); } // Only change cells if geocoder seems to have gotten a // valid response. if (location.status == 'OK') { var lat = location["results"][0]["geometry"]["location"]["lat"]; var lng = location["results"][0]["geometry"]["location"]["lng"]; locationsArray[addressRow][0] = lat; locationsArray[addressRow][1] = lng; } else { locationsArray[addressRow][0] = err; locationsArray[addressRow][1] = err; } } //Set all latitudes and longitudes sheet.getRange("N2:O" + sheet.getLastRow()).setValues(locationsArray); } You need to replace your Spreadsheet ID and run the createTimeDrivenTrigger function once, which will create the trigger to run addressToPosition function every 15 min. This will find the last row on the first Sheet, get the addresses from column M and put the latitudes and longitudes in columns N and O respectively. [1] https://developers.google.com/apps-script/guides/triggers/installable#restrictions [2] https://developers.google.com/apps-script/reference/spreadsheet/sheet#getDataRange() [3] https://developers.google.com/apps-script/reference/properties
[ "stackoverflow", "0020007948.txt" ]
Q: No CSS styles seen in email I am unable to see CSS styles when the following html page is emailed(Yahoo/Gmail) using mutt.I just see a plain table.But I get desired styling when viewed it in a browser. Why is that so ? Am I missing something ? mutt -e "set content_type=text/html" [email protected] -s "Test" < Test.html Test.html <!DOCTYPE html> <html> <head> <style> rd{ color: red; } gn{ color: green; } body { background-color:#E0E0E0; font-family: helvetica;font-size: 15px;} </style> </head> <body> <table border="1" align ="left"> <tr><th>No.</th><th>Item</th></tr> <tr><td>1</td><td><gn>abc</gn></td></tr> <tr><td>2</td><td><rd>ghi</rd></td></tr> </table> </body> </html> A: The way to include CSS in an HTML email is to use inline styles. <!DOCTYPE html> <html> <body style='background-color:#E0E0E0; font-family: helvetica;font-size: 15px;'> <table border="1" align="left" style="color:red;"> <tr><th>No.</th><th>Item</th></tr> <tr><td>1</td><td><gn>abc</gn></td></tr> </table> </body> </html> Ref: http://www.htmlgoodies.com/beyond/css/article.php/3679231 A: html-email is very limited to the point where even div and p tags don't always act as expected. Trying to create your own tags is simply asking for trouble. Your two table cells should look like this instead: <tr><td>1</td><td style="font-family: Helvetica, Arial, sans-serif; font-size: 15px; color:#007700;">abc</td></tr> <tr><td>2</td><td style="font-family: Helvetica, Arial, sans-serif; font-size: 15px; color:#770000;">ghi</td></tr> In addition to always inlining your CSS, you need to use the 6-digit hex color for maximum email client support. You must also re-declare your font styles in every table cell. Redundant as it is, unfortunately that is what is needed in html-email. Don't forget the font stack also, as you are currently assuming the reader has Helvetica installed.
[ "chemistry.stackexchange", "0000111513.txt" ]
Q: Are pKa values of acid and conjugate base the same? When you look at $\mathrm{p}K_\mathrm{a}$ table, you can read $\mathrm{p}K_\mathrm{a}$ values of acids. Do conjugate bases also have $\mathrm{p}K_\mathrm{a}$ values? If both can have $\mathrm{p}K_\mathrm{a}$ values, why $\mathrm{p}K_\mathrm{a}$ value of conjugated bases are same as acids? Can acid have only $\mathrm{p}K_\mathrm{a}$ values, not $\mathrm{p}K_\mathrm{b}$ values? A: Let consider the case of the phosphoric acid. The phosphoric acid $\ce{H3PO4}$ has $pK_\mathrm{a1}$. Its conjugate base $\ce{H2PO4-}$ has $pK_\mathrm{b1} = 14- pK_\mathrm{a1}$. But as $\ce{H2PO4-}$ is at the same time a ( weaker ) acid as well, it has its own acidity constant $pK_\mathrm{a2}$ independent on $pK_\mathrm{a1}$ and $pK_\mathrm{b1}$. Generally, acids like $\ce{HA-}$ have $pK_\mathrm{a2}$ and $pK_\mathrm{b1}$ values. The former associated with $\ce{HA- <=> H+ + A^2-}$, the latter associated with $\ce{HA- + H2O <=> H2A + OH-}$
[ "stackoverflow", "0041244695.txt" ]
Q: How to simulate poor Wi-Fi on a Windows Phone 8.1 App I've been trying to review way of simulating a poor Wi-Fi signal on a Windows Phone 8.1 app. When developing a Windows Phone 8 app, Visual Studio 2013 provided the Simulation Dashboard within the Tools menu and looked to do exactly what I wanted: The Simulation Dashboard now looks to have been replaced with the emulator Additional Tools for developing Windows Phone 8.1 apps: As you can see from the screenshot above there is no Wi-Fi option for me to use. I did have a thought that it might be because the Wi-Fi option is off within the emulator. I can't however turn it on and after a quick search found out why here which makes sense. What I would like to do if at all possible, is debug on the device itself and simulate poor Wi-Fi. I would have thought developers would want to test poor Wi-Fi when developing apps that rely on it. Has anybody found a way of doing this? A: In cases I have worked with the network simulation does exactly what you want to achieve via the Wi-Fi connection speed. Basically the network simulation means the Data connection as well as the Wi-Fi connection. It's more based on the speed of the incoming connection rather than the type of the connection(Data Connection or Wi-Fi). The question is do you want to test the application on various network speeds or specific connection type(data connection or Wi-Fi). If you want to test it just on the network speed then I would advise you to use the network simulation and that'll provide you with very accurate results.
[ "physics.stackexchange", "0000465223.txt" ]
Q: What is the difference between Non-Conservative and Dissipative? We often hear these terms. However, they are often confused to be synonyms, but they are not. What are the rigorous definitions of them? A: A dissipative force is a force that transfers energy from the macroscopic degrees of freedom into microscopic ones. For instance, the position and velocity of the center of mass of a block of wood sliding on a surface would correspond to macroscopic degrees of freedom. However, the motion of the individual molecules in the surface or the wooden block are microscopic degrees of freedom. Then, when the wooden block slides on the surface, its molecules collide with the molecules of the surface because of their slight imperfections. As the molecules collide, the energy in the macroscopic motion of the block gets transferred into the random motion of the molecules both in the block and the surface (this random motion is also called heat). However, you are only able to see the motion of the whole block, and you thus describe its motion as under the influence of a dissipative force. Every dissipative force is non-conservative, that is, it does not conserve the energy in the degrees of freedom you keep track of. Nevertheless, there are non-conservative forces that are not dissipative. This occurs when there is a macroscopic entity you do not keep track of, which adds or takes away energy from your system. For instance, you can be describing a ball which is attached to a spring which itself is being periodically pulled up and down by some kind of engine. The force of the spring on the ball will be non-conservative, at least if you are only focusing on the ball as the only degree of freedom you are interested in. This is because it can either take, or add energy to the ball on the spring; its action does not conserve the energy of the ball. Of course, fundamentally speaking, the distinction between non-conservative, dissipative, microscopic, and macroscopic can be a little bit conventional. In fact, physicists generally believe that if we account for all the degrees of freedom involved, every force is conservative. But it is really useful to have effective descriptions in which non-conservative and/or dissipative forces appear.
[ "stackoverflow", "0050068874.txt" ]
Q: How to take value from form1 to form2 AND back? Ok so here is the Situation: I want to take a value of a string in form1 to a textbox in form2, edit it and send it back and save it as the string in form1 again. Its that easy but Im too stupid to succed. Yes I googled and tried very long but I just dont seem to find the right tags. I tried it with the following Method: public partial class form1: Form { public form1() { InitializeComponent(); } Project.form2 newform2 = new Project.form2(); string oldtext = "Text here"; void somefunction() { oldtext = newform2.getUpdateTxt(); } } and public partial class form2: Form { Project.form1 newform1 = new Project.form1(); string UpdateTxt = ""; public form2() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { UpdateTxt = textBox1.Text; this.Hide(); } public string getUpdateTxt() { return UpdateTxt; } private void form2_VisibleChanged(object sender, EventArgs e) { textbox1.Text = newform1.oldtext.Text; } } obviously not working. Because it creates an infinityloop. I also tried it by putting the Project.form newform = new Project.form(); In an own function. Solves the loop but now it resets the values while initializing. Also tried to parent the forms somehow like described here but its not helping. C# - How to make two forms reference each other A: The simplest solution I can think of for this is to put the value you want to share across forms in a static property of a static class: public static class SharedVariables { public static string OldText { get; set; } } Then you can set a TextBox.Text to the value of the property with: textBox1.Text = SharedVariables.OldText; And you can assign a new value entered in another TextBox.Text with: SharedVariables.OldText = textBox2.Text; That being said, depending on what the purpose of the forms are, this may not be the best solution.
[ "math.stackexchange", "0000571054.txt" ]
Q: Integrating trigonometric function problem $\int \frac{3\sin x+2\cos x}{2\sin x+3\cos x}dx$ \begin{eqnarray*} \int \frac{3\sin x+2\cos x}{2\sin x+3\cos x}dx &=& \int \frac{(3\sin x+2\cos x)/\cos x}{(2\sin x+3\cos x)/\cos x}dx\\ \\ &=& \int \frac{3\tan x +2}{2\tan x +3} dx\\ && u = \tan x \text{ and } du = \sec^2 x \ dx \end{eqnarray*} Am I going in the right direction with this one? It seems like not. A: Since the integrand has the form $$\frac{a\sin(x) + b\cos(x)}{c\sin(x) + d\cos(x)},$$ if we write it as $$\frac{P(x)}{Q(x)} = \frac{a\sin(x) + b\cos(x)}{c\sin(x) + d\cos(x)},$$ then we should be able to find constants $A$ and $B$ such that $P(x) \equiv A Q(x) + B Q'(x)$, so that the integral is simply $$\int A + B\frac{Q'(x)}{Q(x)} \, dx,$$ where the second term $Q'(x)/Q(x)$ contributes $\log\left (Q(x)\right )$ to the integral. In our case, we have $$3\sin(x) + 2\cos(x) \equiv A\left ( 2\sin(x) + 3\cos(x) \right ) + B\left ( 2\cos(x) - 3\sin(x) \right ).$$ Equating coefficients of $\sin(x)$ and $\cos(x)$ yields $2A - 3B = 3$ and $3A + 2B = 2$, and thus $A = \frac{12}{13}$ and $B=-\frac{5}{13}$ (you should check this). Therefore the integral is just $$\int \frac{3\sin(x)+2\cos(x)}{2\sin(x)+3\cos(x)} \, dx = \frac{12}{13}x - \frac{5}{13}\log \left ( 2\sin(x)+3\cos(x) \right ) + C.$$
[ "pt.stackoverflow", "0000192835.txt" ]
Q: C# Como enviar o valor do numericUpDown ao textBox em Hexadecimal? então... o numericUpDown até tem o formato de contagem em Hexadecimal, porém ao enviar para o texBox ele contabiliza somente em decimal tem alguma forma do textBox receber o valor dado do numeric em Hexadecimal? Eu envio o valor do numeric ao textBox assim: private void numericUpDown1_ValueChanged(object sender, EventArgs e) { textBox1.Text = Convert.ToString(numericUpDown1.Value); } A: É só você fazer um parse para inteiro e chamar o método ToString com a formatação X2 para dois digitos em hexadecimal. textBox1.Text = ((int)numericUpDown1.Value).ToString("X2");
[ "stackoverflow", "0020443461.txt" ]
Q: Resize Xcode window on OSX 10.9 I am a new mac user and I would like to know if you that use Xcode are able to resize the UI window as you like. On my macbook pro retina Xcode window has a width of minimum 60% of the screen. I cannot shrink it further than this. It is strange since there is a lot of unused window space(about 40% of the Xcode window). I am using Spectacle app that allows me to split the screen. I know that I can switch between desktops but I like to have the documentation always visible. It also happens in iTunes, but I don't care. The important thing is to have a good programming environment. Please can you tell me if there is any solution? In both windows and linux GUI I never experienced a fixed minimum size such annoying... common 60% hardcoded is too much. PS: I know that this is not a programming question. It is only programming related. Please have mercy. I wrote it on this site because here there are both Xcode users and OSX developers. Thank you. A: The minimum window width is due to the Xcode toolbar. If you disable the toolbar you can have a slimmer window, but then you don't have a toolbar :( to hide the toolbar you can right-click it and select "hide toolbar".
[ "stackoverflow", "0040559964.txt" ]
Q: Is asynchronous and synchronous I/O OS independent? My textbook usually explains concepts in terms of unix, linux, and windows. However, when it comes to asynchronous and synchronous I/O, it only explains it in the context of windows OS. Because of this, I am wondering if asynchronous and synchronous I/O is OS independent? Are both types of I/O available to all of unix, linux, and windows? Or is it only windows OS that has these abilities. Thank you. A: This is a very broad question, and the answer depends on the context. For I/O between the CPU and other peripherals, it depends on the hardware I/O interface. Most devices in your system use an synchronous interface, such as the PCI-express bus. Other devices (typically slower performing ones) can use an asynchronous interface to communicate, such as the serial port. If your question is about inter-process communications within an operating system, the OS typically provides both synchronous or asynchronous methods. This is because certain applications specifically requires synchronous communications, while others requires specifically needs asynchronous communications. You can think of the following question instead: is it crucial for your program to wait for a message to be sent or received before doing anything else, or can you ignore them for now and check up on them later? Synchronous communications require the sender to wait and do nothing until the message has been successfully delivered by the recipient. The same applies for receiving a message: the receiving process will wait and do nothing until the intended message has been received. In asynchronous communications, the sender will send out a message, and then proceed with other tasks without waiting. The receiver also do not need to block-wait until a message arrives. It will periodically check to see if any messages are available.
[ "magento.stackexchange", "0000042285.txt" ]
Q: module layout problem (display and redirection) I have made a module with a contact form. The Submit button calls a controller which get $ post and send emails both to client and admin. I would like after form submission to redirect to the form page with a success or error message display (as works the standard magento contact form) It is almost working but I have something not clear in the process… To display my form i have created a CMS page with {{block type="dptrentejours/dptrentejoursformblock" name="dptrentejours_dptrentejoursformblock" template="dptrentejours/dptrentejoursform.phtml"}} Is it the good way, or may i rather call www.myshop.com/dptrentejours/index ? the indexAction does not load the form. I have got an empty page core. after submission if I go back to the url of the CMS page, the success / error message is displayed My controller : <?php class Mine_Dptrentejours_IndexController extends Mage_Core_Controller_Front_Action { public function indexAction() { $this->loadLayout(); $this->renderLayout(); } public function sendrequestAction() { if ($post = $this->getRequest()->getPost()) { $postObject = new Varien_Object(); $postObject->setData($post); ... try { $mail2->send(); try { $mail->send(); Mage::getSingleton('customer/session')->addSuccess(Mage::helper('contacts')->__('Your inquiry was submitted and will be responded to as soon as possible. Thank you for contacting us.')); $this->_redirect('*/*/'); return; } catch(Exception $error) { Mage::getSingleton('customer/session')->addError(Mage::helper('contacts')->__('Unable to submit your request. Please, try again later')); $this->_redirect('*/*/'); return; } } catch(Exception $error) { Mage::getSingleton('customer/session')->addError(Mage::helper('contacts')->__('Unable to submit your request. Please, try again later')); $this->_redirect('*/*/'); return; } } } } My Layout.xml <?xml version="1.0"?> <layout version="0.1.0"> <default> <reference name="content"> </reference> <reference name="head"> <action method="addItem"><type>skin_css</type><name>css/mine_dptrentejours/dptrentejours_form.css</name></action> </reference> </default> <routeurfrontend_index_index> <reference name="content"> <block type="dptrentejours/dptrentejoursformblock" name="dptrentejours_dptrentejoursformblock" template="dptrentejours/dptrentejoursform.phtml" /> </reference> </routeurfrontend_index_index> </layout> config.xml : <?xml version="1.0"?> <config> <modules> <Mine_Dptrentejours> <version>0.0.1</version> </Mine_Dptrentejours> </modules> <frontend> <routers> <dptrentejours> <use>standard</use> <args> <module>Mine_Dptrentejours</module> <frontName>dptrentejours</frontName> </args> </dptrentejours> </routers> <layout> <updates> <dptrentejours> <file>dptrentejours.xml</file> </dptrentejours> </updates> </layout> <translate> <modules> <dptrentejours> <files> <default>Mine_Dptrentejours.csv</default> </files> </dptrentejours> </modules> </translate> </frontend> <adminhtml> </adminhtml> <global> <blocks> <dptrentejours> <class>Mine_Dptrentejours_Block</class> </dptrentejours> </blocks> <models> <dptrentejours> <class>Mine_Dptrentejours_Model</class> </dptrentejours> </models> <helpers> <dptrentejours> <class>Mine_Dptrentejours_Helper</class> </dptrentejours> </helpers> </global> </config> dptrentejoursform.phtml <?php /** Formulaire de demande de paiement 30j */ ?> <div class="page-title"> <h1 style="color: #636363;"><?php echo $this->__('30 days Payment request') ?></h1> </div> <form action="<?php echo Mage::getBaseUrl().'dptrentejours/index/sendrequest' ?>" id="DP30Form" method="post"> <div class="fieldset"> <p class="required" style="color: #FF0000;"><?php echo $this->__('* Required Fields') ?></p> <h2 class="legend" style="color: #636363; margin-left: 2em;"><?php echo $this->__('Contact Information') ?></h2> <ul class="form-list" style="margin-left: 4em;"> <div class="field"> <label for="firstname" class="required"><em>*</em><?php echo $this->__('Firstname') ?></label> <div class="input-box"> <input name="firstname" id="firstname" title="<?php echo $this->__('Firstname') ?>" value="" class="input-text required-entry" type="text" /> </div> </div> <div class="field"> <label for="lastname" class="required"><em>*</em><?php echo $this->__('Lastname') ?></label> <div class="input-box"> <input name="lastname" id="lastname" title="<?php echo $this->__('Lastname') ?>" value="" class="input-text required-entry" type="text" /> </div> </div> <div class="field"> <label for="userid" class="required"><em>*</em><?php echo $this->__('Account Username') ?></label> <div class="input-box"> <input name="userid" id="userid" title="<?php echo $this->__('Account Username') ?>" value="<?php echo $this->escapeHtml($this->helper('contacts')->getUserName()) ?>" class="input-text required-entry" type="text" /> </div> </div> <div class="field"> <label for="email" class="required"><em>*</em><?php echo $this->__('Email') ?></label> <div class="input-box"> <input name="email" id="email" title="<?php echo $this->__('Email') ?>" value="<?php echo $this->escapeHtml($this->helper('contacts')->getUserEmail()) ?>" class="input-text required-entry validate-email" type="text" /> </div> </div> <div class="field"> <label for="telephone" class="required"><em>*</em><?php echo $this->__('Telephone') ?></label> <div class="input-box"> <input name="telephone" id="telephone" title="<?php echo $this->__('Telephone') ?>" value="" class="input-text required-entry" type="text" /> </div> </div> </ul> <h2 class="legend" style="color: #636363; margin-left: 2em;"><?php echo $this->__('Company Information') ?></h2> <ul class="form-list" style="margin-left: 4em;"> <div class="field"> <label for="companyname" class="required"><em>*</em><?php echo $this->__('Company Name') ?></label> <div class="input-box"> <input name="companyname" id="companyname" title="<?php echo $this->__('Company Name') ?>" value="" class="input-text required-entry" type="text" /> </div> </div> <div class="field"> <label for="siret" class="required"><em>*</em><?php echo $this->__('Company immatriculation number') ?></label> <div class="input-box"> <input name="siret" id="siret" title="<?php echo $this->__('Company immatriculation number') ?>" value="" class="input-text required-entry" type="text" /> </div> </div> <div class="field"> <label for="adresse1" class="required"><em>*</em><?php echo $this->__('Address Line 1') ?></label> <div class="input-box"> <input name="adresse1" id="adresse1" title="<?php echo $this->__('Address Line 1') ?>" value="" class="input-text required-entry" type="text" /> </div> </div> <div class="field"> <label for="adresse2"><?php echo $this->__('Address Line 2') ?></label> <div class="input-box"> <input name="adresse2" id="adresse2" title="<?php echo $this->__('Address Line 2') ?>" value="" class="input-text" type="text" /> </div> </div> <div class="field"> <label for="postalcode" class="required"><em>*</em><?php echo $this->__('Postal Code') ?></label> <div class="input-box"> <input name="postalcode" id="postalcode" title="<?php echo $this->__('Postal Code') ?>" value="" class="input-text required-entry" type="text" /> </div> </div> <div class="field"> <label for="city" class="required"><em>*</em><?php echo $this->__('City') ?></label> <div class="input-box"> <input name="city" id="city" title="<?php echo $this->__('City') ?>" value="" class="input-text required-entry" type="text" /> </div> </div> <div class="field"> <label for="country" class="required"><em>*</em><?php echo $this->__('Country') ?></label> <div class="input-box"> <input name="country" id="country" title="<?php echo $this->__('Country') ?>" value="" class="input-text required-entry" type="text" /> </div> </div> </ul> <h2 class="legend" style="color: #636363; margin-left: 2em;"></h2> <ul class="form-list" style="margin-left: 4em;"> <div class="field"> <div class="input-box"> <input name="TermsandCondition" id="TermsandCondition" title="<?php echo $this->__('Terms and Conditions') ?>" value="1" class="checkbox required-entry" type="checkbox" /> <label for="TermsandCondition" class="required"><em>*</em></label> <label for="TermsandCondition"><?php echo $this->__('I have read and I accept the') ?> <a href="<?php echo Mage::getBaseUrl(); ?>/paiement_30j_Terms"><?php echo $this->__('30 days payment Terms and Conditions') ?></a></label> </div> </div> </ul> </div> <div class="buttons-set" style="max-width: 600px;"> <input type="text" name="hideit" id="hideit" value="" style="display:none !important;" /> <button type="submit" title="<?php echo $this->__('Submit') ?>" class="button"><span><span><?php echo $this->__('Submit') ?></span></span></button> </div> </form> <script type="text/javascript"> //< ![CDATA[ var customForm = new VarienForm('DP30Form'); //]]> </script> thank you for your help, A: Take care of the following points. 1) Your router unique alias name is dptrentejours (as per your config.xml). So in your layout file you need to use dptrentejours_index_index as layout handle instead of routeurfrontend_index_index. This is why form is not obtained in frontend. 2) Inside the custom layout handle, you have included your block in the content section. You are right on that point. The custom block type specified there is dptrentejours/dptrentejoursformblock. This means Magento require this block to be really be defined inside your module. Other wise you will not get your form in frontend. So make sure this block is defined like this. File : app\code\local\Mine/Dptrentejours/Block/Dptrentejoursformblock.php <?php class Mine_Dptrentejours_Block_Dptrentejoursformblock extends Mage_Core_Block_Template { } 3) Make sure your template form exist in the right location. As per your layout xml file, it should be held at app\design\frontend\<package>\<theme>\template\dptrentejours/dptrentejoursform.phtml. Since you are adding your custom block directly via layout file, you dont need to use any cms page to show the form. Side Note : Always remember to clear the cache
[ "stackoverflow", "0030841752.txt" ]
Q: Symfony change validation message globally Is there a way to change the basic validation error message to one I need for all entities at once? Currently using Yaml config for every entity, but it's not a way. CF\MyBundle\Entity\User: properties: email: - Email: message: e-mail no válido - NotBlank: message: Campo obligatorio username: -NotBlank: message: Campo obligatorio A: The easiest way is to define an translations file. # app/Resources/translations/validators.es.yml This value should not be blank.: Campo obligatorio This value is not a valid email address.: e-mail no válido
[ "movies.stackexchange", "0000052319.txt" ]
Q: In Breaking Bad season one, A No-Rough-Stuff-Type Deal, why don't they roll the barrels? In S1:E7 of Breaking Bad, Walter and Jesse steal a barrel of methylamine. When they take them from the warehouse, they choose to carry the barrel between the two of them, which looks grueling. Is there a reason, scientific or otherwise, that they would choose to carry the barrel in that way, rather than roll it? A: Their carrying the barrel rather than rolling it is to highlight their naïveté at this. It shows they have never done this before and have no idea if the logistics involved. There is a callback to this in a later episode where they are mocked for it.
[ "stackoverflow", "0009714473.txt" ]
Q: Download file using WCF Rest service? If there is a way to Upload file using rest via stream would there be also for "Download"? If yes, can you please tell me how? Thanks in advance! A: A sample method i use to download the file from my REST service: [WebGet(UriTemplate = "file/{id}")] public Stream GetPdfFile(string id) { WebOperationContext.Current.OutgoingResponse.ContentType = "application/txt"; FileStream f = new FileStream("C:\\Test.txt", FileMode.Open); int length = (int)f.Length; WebOperationContext.Current.OutgoingResponse.ContentLength = length; byte[] buffer = new byte[length]; int sum = 0; int count; while((count = f.Read(buffer, sum , length - sum)) > 0 ) { sum += count; } f.Close(); return new MemoryStream(buffer); }
[ "ell.stackexchange", "0000203421.txt" ]
Q: "Through" and "through to" Could anyone explain the difference between these examples? 1- Does this bus go through to Santa Fe? 2- Does this bus go through Santa Fe? 3- Does this bus go to Santa Fe? A: 1 - This one sounds weird to me. Maybe "through to" in this question means "all the way to", so in that case it's asking if the bus goes all the way to (as far as) Santa Fe. 2 - Does this bus pass through Santa Fe on the way to somewhere else? The bus may or may not make a stop in Santa Fe, but the asker is wondering whether the route goes through Santa Fe. EDIT: in case using the word "through" in my answer doesn't help, it's asking whether the bus goes somewhere (anywhere, Santa Fe or somewhere else) by way of or via Santa Fe. 3 - Does this bus make a stop in Santa Fe?
[ "unix.stackexchange", "0000120710.txt" ]
Q: alternative to nslookup in rhel7? nslookup does not come preinstalled in RHEL 7 Beta. I noticed even dig and host was not pre installed. I read couple of links which mentions nslookup is dead/deprecated, so is there an alternative for nslookup introduced in RHEL7 which comes preinstalled? A: Have you tried getent hosts? [root@test ~]# getent hosts unix.stackexchange.com 198.252.206.140 unix.stackexchange.com It's not give full details like nameserver,other resource record like other tools (dig) do, so if you want full details then you need to install bind-utils package. or just using ping to know ip
[ "stackoverflow", "0014616818.txt" ]
Q: How to use stop() properly in jQuery animation with hover event? I use the method below to make some animation. But when I move my mouse in and out really fast and stop it inside the div , the fadeIn() doesn't work and the div keeps transparent. $(".grids").hover(function() { $('.gridscontrol').stop().fadeIn(200); }, function() { $('.gridscontrol').stop().fadeOut(200); }); A: .stop() without parameters simply stops the animation, still leaving it in queue. In this case you want .stop(true) to clear the animation queue as well. $(".grids").hover(function() { $('.gridscontrol').stop(true).fadeTo(200, 1); }, function() { $('.gridscontrol').stop(true).fadeTo(200, 0); }); Also note the use of .fadeTo() since .fadeIn() and .fadeOut() shortcuts have some undesirable behavior here. You can see a working example here.
[ "stackoverflow", "0013416969.txt" ]
Q: How to use a div tag as a starting point for searching an html document with BeautifulSoup I have an HTML document, and I want to parse out a table with a specific id, which is always within a div tag with a specific id. Here is what I've tried: soup = BeautifulSoup(html) target_div = soup('div', {'id' : 'left'}) target_table = target_div.findNextSibling('table') Clearly that's not working. It seems that my second statement returns a ResultSet instead of moving me around the document (which I suppose makes sense, but I'm not sure how to get what I need otherwise!). What is the correct methodology for doing this kind of parsing? A: findNextSibling looks for tables that are contained in the same parent as the original target_div element. You want to look for a table contained in the div. Use .find() for that: target_div = soup.find('div', {'id' : 'left'}) target_table = target_div.find('table') and for simple cases (such as the contained table) you can use the tagname as an attribute: target_div = soup.find('div', {'id' : 'left'}) target_table = target_div.table You were calling a tag, which is like using the .find_all() method. .find_all() returns all matching tags, a list. You'd have to loop over the result set, but since you are looking for a single div (using its id) you are better off using .find() which returns just one result. If you do need to process more than one match, just treat the result of .find_all() as a list; loop over it: for element in soup.find_all('div') contained_table = element.find('table') or use indices: second_match = soup.find_all('div')[1]
[ "superuser", "0000260229.txt" ]
Q: Can I change&update BIOS settings simply from Windows GUI(ring 3)? Can I change and update my BIOS settings simply from inside Windows? A: For ASUS boards, you can update the BIOS using their utility which will run within windows.
[ "math.stackexchange", "0002391614.txt" ]
Q: Simple field extension's endomorphism is trivial? Denote $C=\bar{K}$ algebraic closure of field $K$ and $E/K$ some finite field extension. Since the separable degree of field extension $E/K$ is defined as $|Hom(E/K, C/K)|$ instead of $|End(E/K)|$ where both $Hom,End$ means the set $K-$algebra homomorphism and endomorphisms, I would like to compute the simple extension's endormorphism and check whether it is trivial. Suppose $E=K(a)$ where $a$ algebraic over $K$. So $E\cong K^n$ for some $n\in N$. $End(E/K)\cong K^{n^2}$ as $K$ vector space. However, not all of them are $K-$algebra homomorphism. Clearly $Id_{K(a)}\in End(K(a)/K$. Any endomorphism of field extension is injecitve and thus isomorphism between $K(a)/K$ and $K(a)/K$. So some element $b\in K(a)$ is being sent to $a\in K(a)/K$. So $K(a)=K(b)$. $a$ and $b$ must differ by a non-zero element of $K$.(i.e $f(a)=k'a,k'\in K^{\star}$). So $|End(E/K)|=|K^{\star}|$ where $K^{\star}$ are non-zero elements. How do I identify the morphism between $End(E/K)$ and $K^{\star}$? Identify them as group? Does this happen to be in Abelian category? I should expect $|Hom(E/K,C/K)|\geq |End(E/K)|$. For simple finite extension I do not see this unless I have made error above. A: The right way to look at your situation is to consider the minimal polynomial for $a$, say $g(X)\in K[X]$, and to ask how many other roots of $g$ lie in $K(a)$. Depending on $a$ (equivalently, on $g$) there may be no other roots lying in $K(a)$, or all roots of $g$ may be there. This is the core of the concept of normality of an extension.
[ "gaming.stackexchange", "0000082471.txt" ]
Q: How do I deal with turrets as a Scout? Playing as scout I try to flank my enemies. My biggest problem is turrets. I cant get close enough to take them out with a scattergun, but I cannot ignore them as they kill me so quickly. What should I be doing about these turrets that block my path as a scout? A: As a Scout, you aren't supposed to deal with sentries. Each class has its counters, and the Scout's high speed and mobility are easily countered by the computer-controlled Sentry. The best way to get around sentries is to drink Bonk! Atomic Punch while your team is distracting the sentry. Rushing in without team support will cause the Sentry to push you away. Invulnerability does not protect you from knockback. However, if you absolutely need to take down a sentry, you will need to take advantage of the fact that sentries take full damage from weapons (no loss of damage from distance). Your pistol could take down a Sentry due to its accuracy, but only if the Engineer is not repairing it. Additionally, many maps have alternate routes you can take. For instance, on the third stage of Dustbowl, there is a tunnel you can take to get behind any sentry guns. So it is really difficult to take out sentries as a scout. Try alerting your team to its presence, or switch to spy/soldier/demo and take it out yourself. A: Here's what you can do to sentries as a scout if no engineer is around: Pistol them down from outside their range (best way to deal with minisentries) Approach them from behind then edge them (sentries need a while to turn around, use that to your advantage) Here's what you can do to sentries as a scout if their engineer is around: Approach them from behind in order to get the sentry to kill its engie. Pick off his dispenser, forcing the engie to multitask (creating an opening for spies, e.g.) Bonk past the nest altogether and go for their unguarded teleporter entrance at spawn. Wait for a damage class to come by and drink bonk. Tank the sentry while the damage dealer stays safely behind you. (Countered by the wrangler, but again that creates an opening for spies.) A: Your strategy is highly dependant on the map type that you're playing. For instance, if you're playing 2Fort, my suggestion would be to ignore the sentries, pound back a Bonk, and make a run for the intelligence. Actually, there are only a handful of cases where I wouldn't do that. On cart maps, your goal might be to get behind Red's line, and Bonk can help you do that. The only time I would take on a sentry as a scout is when it's in the wide open and is unguarded, which will give you room to maneuver around the sentry while taking minimal damage. Sad to say, but that doesn't happen very often against good engineers.