qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
sequence
response
stringlengths
0
115k
21,000,107
In the course of tracking down some memory leaks in the project I'm working on, I've also been working on updating the various hardware API libraries. A couple of these are unmanaged 32bit libraries, which forces our application to compile to x86; this is not a problem in and of itself. I'm working on upgrading these libraries to 64 bit versions so that our application doesn't have to run in 32 bit, but it led me to wonder about memory leaks and the addressable memory space. Given memory leaks, when running in a 64 bit process, will an application theoretically be able to run for a longer period of time before hitting an `OutOfMemoryException`? There are at least two cases for this * **Memory Fragmentation** - There is not a contiguous memory block to allocate a large object, so this exception could be thrown even though there appears to be enough free memory * **Low Physical Memory** - There simply isn't enough memory available, contiguous or not, to allocate a new object
2014/01/08
[ "https://Stackoverflow.com/questions/21000107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3116365/" ]
Absolutely it will take longer... However, depending on your machine and the leaking process, HOW MUCH longer can vary... While x64 can allow for **8TB** of memory, your machine most likely won't allow for that. So lets say you have **4GB** of ram and a **12GB** pagefile, then you will probably have **~14GB** of memory available for you to allocate. (The system has some overhead preventing the full **16GB**) Check out this [post](https://stackoverflow.com/questions/2052019/net-why-cant-i-get-more-than-11gb-of-allocated-memory-in-a-x64-process) for more information.
14,726,415
I understand the whole business around reference counting and "owning an object" and that if you allocate an object in Objective-c, it's your responsibility to release it However when exactly would you need to call alloc on a newly created object? Would it only be to retain the reference after the end of the scope or is there some other reason
2013/02/06
[ "https://Stackoverflow.com/questions/14726415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2046374/" ]
You need to call alloc in order to allocate the memory for the object. The typical setup of an object is something like: ``` Object *obj = [[Object alloc] init]; ``` The alloc call allocates memory for the object, and the init call initialises it (gives it sensible default values for all attributes/properties). Some object types come with factory methods, eg ``` NSArray *arr = [NSArray array]; ``` In this case, the object is initialised and allocated by the single array call. None of this has anything (directly) to do with reference counting, except that different ownership rules normally apply to the two methods.
251,726
The book I have gives the following derivation: Let the temperature of the atmosphere be $-\theta$ and the temperature of the water be $0$. Consider unit cross sectional are of ice, if layer of thickness $dx$ forms in time $dt$ with $x$ thickness of ice above it, heat released due to its formation is $dx\rho L$ where $L$ is latent heat. If this quantity of heat is conducted upwards in time $dt$, $$dx\rho L=K\frac{\theta}{x}dt$$ Therefore, the time taken $$t=\frac{\rho L}{2K\theta}(x\_{2}^2-x\_{1}^2)$$ What I don't understand is why the same amount of time should be taken for the heat to be conducted and for a new layer of ice to be formed. In other words, why is it that the next layer of ice forms only after the heat is released into the atmosphere?
2016/04/24
[ "https://physics.stackexchange.com/questions/251726", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/98561/" ]
The heat is continually being released to the atmosphere, and the layer is continually getting thicker. The heat has to be conducted from the water-ice interface to the ice-atmosphere interface through the layer of ice. And, as the ice gets thicker, the rate of heat being conducted slows down. And the rate of ice formation slows down. So the amount of time taken for the heat to be conducted and for a new incremental layer of ice to be formed is **not the same** for each incremental layer. Those are $x^2$'s in the equation, not x's.
35,737,202
Is left to right a higher precedence then the object String? For my print statement as below I got this. Please explain. ``` class triangle{ public static void main(String[]args){ System.out.println(1+2+"hello"); System.out.println("hello"+1+2); } } ``` Also why do I need to put a cast to a floating x=1.2F; and not double x=1.2;?
2016/03/02
[ "https://Stackoverflow.com/questions/35737202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5911874/" ]
This happens because the module `FscHelper` defines a constructor called `Target` ([see source](https://github.com/fsharp/FAKE/blob/c544eb7a4a567a91ff0c9f05dab1b2d00458b54e/src/app/FakeLib/FscHelper.fs#L244)), and that constructor conflicts with the `Target` function from the `TargetHelper` module. There is an [issue filed about it](https://github.com/fsharp/FAKE/issues/1155). Until the issue is fixed, there are three ways to work around this ambiguity: 1. Don't open `FscHelper`, just use all its innards in a qualified manner (e.g. `FscHelper.Compile` etc.) 2. Re-alias the `TargetHelper.Target` function in the local scope: ``` open Fake open Fake.FscHelper let Target = TargetHelper.Target Target "Default" (fun _ -> trace "Hello World from FAKE" ) ``` 3. Reorder the `open` statements: ``` open Fake.FscHelper open Fake ``` And since you're using this helper, note that the [documentation](http://fsharp.github.io/FAKE/fsc.html) for it is [outdated](https://github.com/fsharp/FAKE/issues/1156). In particular, the `Fsc` task is deprecated in favor of the `Compile` task ([see source](https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/FscHelper.fs#L520)).
4,246,388
Q: Find the range and domain of the function $$f(x) = \sqrt{1-e^{x+2}}?$$ I've found the domain, which is $x \le -2$ by solving the inequality $1-e^{x+2} \ge 0$. I've tried to find the range by taking the inverse of $f$, which gives me $f^{-1} = \ln(1-x^2)-2$. Then, since for $\ln(1-x^2)$ to be defined, $1-x^2>0$, so solving this inequality gives the interval $x \in (-1,1)$, which I thought is the range of $f$. However, graphing it out on desmos shows that the range is only $[0,1)$. What am I doing wrong?
2021/09/10
[ "https://math.stackexchange.com/questions/4246388", "https://math.stackexchange.com", "https://math.stackexchange.com/users/742592/" ]
Yes, the way your proof would be formalized is by saying $1 - \sum\_{k = 1}^{n}9 \cdot 10^{-k} = 10^{-n}$, and then showing $\lim\_{n \to \infty}10^{-n} = 0$. The "$\infty$" can be formalized by the fact that $\frac{1}{10^n} \to 0$ if and only if $10^n \to \infty$.
11,836,422
My `ajax` looks like ``` // send the data to the server using .ajax() or .post() $.ajax({ type: 'POST', url: 'addVideo', data: { video_title: title, playlist_name: playlist, url: id // csrfmiddlewaretoken: '{{ csrf_token }}', }, done: notify('success', 'video saved successfully'), fail: notify('error', 'There were some errors while saving the video. Please try in a while') }); ``` `notify` looks like ``` function notify(notify_type, msg) { var alerts = $('#alerts'); alerts.addClass('alert'); alerts.append('<a class="close" data-dismiss="alert" href="#">×</a>'); if (notify_type == 'success') { alerts.addClass('alerts-success').append(msg).fadeIn('fast'); } if (notify_type == 'failure') { alerts.addClass('alerts-error').append(msg).fadeIn('fast'); } } ``` * When I save click on button I get success message as > > video saved successfully x(cross mark) > > > * I click cross and notification is gone now * When I AGAIN save click on button, nothing happens, I see firebug complaining `No elements were found with the selector: "#alerts"` * My guess is clicking on cross mark removes the `div="alerts"` tag entirely from DOM. is it correct? **Question** - How can I get the correct behavior. clicking on cross mark removes notification div, clicking on button to create creates the notification div again
2012/08/06
[ "https://Stackoverflow.com/questions/11836422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/379235/" ]
Try doing this. In Mountain Lion, go to Preferences -> General and for `Show scroll bars` choose `Always` like so : ![enter image description here](https://i.stack.imgur.com/FEtw2.png) That should prevent the scroll bar from covering the last option and allow you to click it. Does this help ? **Update** I just checked that this indeed works. In fact for me it's only the `When Scrolling` option that creates a problem. With either of the remaining settings, things are peachy : Unfortunately, I can't post a screen shot since the cmd + click popup disappears as soon as I press the shortcut key for taking a screenshot (Cmd + Shift + 4). **Update 2** I just made this quick screen cast to show the relation between the Mountain Lion Preferences and how it effects eclipse. Take a look at it **[here](http://youtu.be/qV7EmzozI0o)**.
55,082,650
I have a model called Resource configured with: ``` class Resource < ActiveRecord::Base has_many_attached :assets end ``` I created an action in my resources\_controller.rb as follows: ``` def delete_asset_attachment @asset = ActiveStorage::Attachment.find_by(params[:id]) logger.debug "The value of @asset is #{@asset}" @asset.purge redirect_to @resource end ``` I have a form that shows the resource and loops through the attached assets. Below is the snippet of code doing the loop through the assets: ``` <% @resource.assets.each do |asset| %> <%= link_to 'Remove Attachment', delete_asset_attachment_resource_url(@resource, asset.id), method: :delete, data: { confirm: 'Are you sure?' } %> <% end %> ``` The /resources page properly shows the resource along with the attached assets. However, when I try to click the link to delete one of the assets, I receive an error: "undefined method `purge' for nil:NilClass". However, in console I see the attachment exists. Here is the output from the server console: ``` Started DELETE "/resources/10/delete_asset_attachment.18" for ::1 at 2019-03-09 17:27:28 -0500 Processing by ResourcesController#delete_asset_attachment as Parameters: {"authenticity_token"=>"EFZO5V9Bii3dId0I6hn5DajFR5WJYZBc8qPAAi5ppQOFW3cws5I4FjyVP9IlvA+2a2kKUJhobnqd8atG4L3k+g==", "id"=>"10"} Resource Load (0.1ms) SELECT "resources".* FROM "resources" WHERE "resources"."id" = ? LIMIT ? [["id", 10], ["LIMIT", 1]] User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 1], ["LIMIT", 1]] ActiveStorage::Attachment Load (0.1ms) SELECT "active_storage_attachments".* FROM "active_storage_attachments" WHERE (10) LIMIT ? [["LIMIT", 1]] The value of @asset is #<ActiveStorage::Attachment:0x00007f8d7bd4df68> ActiveStorage::Blob Load (0.2ms) SELECT "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = ? LIMIT ? [["id", 27], ["LIMIT", 1]] Completed 500 Internal Server Error in 5ms (ActiveRecord: 0.6ms) NoMethodError - undefined method `purge' for nil:NilClass: ::1 - - [09/Mar/2019:17:27:28 EST] "POST /resources/10/delete_asset_attachment.18 HTTP/1.1" 500 76939 http://localhost:3000/resources/10/edit -> /resources/10/delete_asset_attachment.18 Started POST "/__better_errors/70da0e976a425fce/variables" for ::1 at 2019-03-09 17:27:28 -0500 ActiveStorage::Blob Load (0.2ms) SELECT "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = ? LIMIT ? [["id", 27], ["LIMIT", 11]] ::1 - - [09/Mar/2019:17:27:28 EST] "POST /__better_errors/70da0e976a425fce/variables HTTP/1.1" 200 36499 http://localhost:3000/resources/10/delete_asset_attachment.18 -> /__better_errors/70da0e976a425fce/variables ``` I've searched for solutions everywhere. The couple that exist on stackoverflow didn't address my issue. There is an incredible lack of specific details and examples in the Rails guide or anywhere else on the web for specifically handling deleting attachments. Would appreciate any help. UPDATE: Here are my routes.rb: resources :resources do get 'listing', :on => :collection put :sort, on: :collection member do delete :delete\_asset\_attachment end end UPDATE 2: rails routes output ``` resources GET /resources(.:format) resources#index POST /resources(.:format) resources#create new_resource GET /resources/new(.:format) resources#new edit_resource GET /resources/:id/edit(.:format) resources#edit resource GET /resources/:id(.:format) resources#show PATCH /resources/:id(.:format) resources#update PUT /resources/:id(.:format) resources#update DELETE /resources/:id(.:format) resources#destroy ```
2019/03/09
[ "https://Stackoverflow.com/questions/55082650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/964018/" ]
I've been able to make this work. Ahhhh. The rush, after hours of frustration. Piecing things together after reading this article [Deleting ActiveStorage Attachments From the Controller, 3 Ways](https://nicholasshirley.com/several-strategies-to-delete-activestorage-attachments/) I changed my controller code to be this: ``` def delete_asset_attachment @resource.assets.find_by(params[:attachment_id]).purge redirect_to @resource end ``` and my form to be this: ``` <% @resource.assets.each do |asset| %> <%= asset.filename %> <%= link_to 'Remove Attachment', delete_asset_attachment_resource_url(@resource, asset.id), method: :delete, data: { confirm: 'Are you sure?' } %> <% end %> ``` I believe the issue was that the line in my old code: ``` @asset = ActiveStorage::Attachment.find_by(params[:id]) ``` ...was only passing the @resource id and the attachment was not being found. The key was changing this line: ``` @resource.assets.find_by(params[:attachment_id]).purge ``` ...which more properly points to the correct resource and then the specific asset (attachment) to be purged.
38,559,006
I have sample string as : 1. `'&label=20:01:27&tooltext=abc\&|\|cba&value=6|59|58|89&color=ff0000|00ffff'` 2. `'&label=20:01:27&tooltext=abc\&|\|cba&value=6|59|58|89'` My objective is to select the text from '`tooltext=`' till the first occurrence of '`&`' which is not preceded by `\\`. I'm using the following regex : ``` /(tooltext=)(.*)([^\\])(&)/ ``` and the `.match()` function. It is working fine for the second string but for the first string it is selecting upto the last occurrence of '`&`' not preceded by `\\`. ``` var a = '&label=20:01:27&tooltext=abc\&|\|cba&value=6|59|58|89&color=ff0000|00ffff', b = a.match(/(tooltext=)(.*)([^\\])(&)(.*[^\\]&)?/i) ``` result, ``` b = ["tooltext=abc\&|\|cba&value=40|84|40|62&", "tooltext=", "abc\&|\|cba&value=40|84|40|6", "2", "&"] ``` But what i need is: ``` b = ["tooltext=abc&||cba&", "tooltext=", "abc&||cb", "a", "&"] ```
2016/07/25
[ "https://Stackoverflow.com/questions/38559006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5117872/" ]
I think you can use a regex like this: ``` /tooltext=(.*?\\&)*.*?&/ ``` **[[`Regex Demo`]](https://regex101.com/r/qQ3nH7/1)** and to always found a non-escaped `&`: ``` /tooltext=(.*?\\&)*.*?[^\\]&/ ```
437,218
On [Wikipedia](https://en.wikipedia.org/wiki/Imre_Simon), it is claimed without a source that Imre Simon founded tropical mathematics. The first work of his I was able to find on the subject is [Limited subsets of a free monoid](https://ieeexplore.ieee.org/document/4567973) which uses the semiring $\mathbb N \cup \{\infty\}$ (together with the operations $\min$ and $+$) in the context of automata theory and formal languages and which dates back to 1978. My questions is: Is this the first paper in which a tropical semiring is used? EDIT: To clarify, I am not asking for the origin of the word tropical itself. That has already been answered on this website. I am asking for the origin of tropical mathematics: that is, the study of the tropical semiring, be it in tropical geometry, algebra or analysis, and whether it was in an applied or theoretical context. In other words, what is the first work that studies the tropical semiring? EDIT: I have a follow-up question on the history of the subject [here](https://mathoverflow.net/questions/437235/history-of-tropical-mathematics)
2022/12/25
[ "https://mathoverflow.net/questions/437218", "https://mathoverflow.net", "https://mathoverflow.net/users/496888/" ]
This answer is due to Benjamin Steinberg: > > Simon's paper is likely the first at least to make serious use of [the > tropical semiring] and it was in theoretical computer science to study > star height and limitedness. > > >
75,353
My 10.8.2 MacBook Air is having constant connection errors in Mail.app when the computer has been sent to sleep or hibernate. A small alert triangle appears next to all account names (I have several) in the sidebar. Mail reception only resumes after quitting and relaunching Mail.app. I have verified that the net connection is up, and that connections settings and credentials are okay. Similar problems described [here](https://apple.stackexchange.com/q/59735/26522).
2012/12/19
[ "https://apple.stackexchange.com/questions/75353", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/26522/" ]
This might seem weird and unlikely, but these steps (originally written to [restore broken Dictation](https://apple.stackexchange.com/q/68761/26522)) fixed it for me: 1. Go to `~/Library/Preferences` ( `⇧`+`⌘`+`G` ) 2. Locate `com.apple.assistant.plist` and move it to the Trash 3. Open *Dictation & Speech* preference panel, disable dictation 4. Reboot 5. Re-enable *Dictation & Speech*. **Any hints on why this is working are very welcome!**
18,099,144
I encountered problems to download floodlight from GitHub. I have googled and tried various methods to clone it. Below is the error: ``` mininet@mininet-vm:~$ git clone git://github.com/floodlight/floodlight.git Cloning into 'floodlight'... fatal: unable to connect to github.com: github.com:Temporary failure in name resolution ``` I'm currently running mininet in a virtual machine and i have tried with https/http instead of git. Still, I encountered errors when trying to download floodlight from GitHub. My virtual machine network is connected with NAT and GitHub.com is up and running. However, when I tried to ping to GitHub.com it won't work. How do I resolve this DNS server issue?
2013/08/07
[ "https://Stackoverflow.com/questions/18099144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2651587/" ]
I had a similar issue, but found it to be intermittent. What I found to resolve the issue was the following: 1. Make sure you have the latest version of virtual box. The latest versions support ping from a NAT guest to the Internet - although I've had mixed success with that 2. If I was using a dongle connection to the Internet, i.e. not persistent, I found that I sometime s I had to reboot the guest, after the connection to the Internet had been made. So nothing particularly technical, and ceratinly nothing to do with forwarding rules. But it worked for me, michael
1,538
I've been trying a long time to understand a thing which is obviously extremely simple, but I just can't get it. Read this, please: > > The NTRUEncrypt PKCS uses the ring of truncated polynomials $R$ combined with the modular arithmetic described in Section 1. These are combined by reducing the coefficients of a polynomial a modulo an integer $q$. Thus the expression $$a \pmod q$$ means to reduce the coefficients of $a$ modulo $q$. That is, divide each coefficient by $q$ and take the remainder. Similarly, the relation $$a \equiv b \pmod q$$ means that every coefficient of the difference $a-b$ is a multiple of $q$. > > > This is taken from [NTRU tutorial](http://www.securityinnovation.com/security-lab/crypto/154.html) and that's quite understandable. But. Take a glance at the next excerpt from the same tutorial: > > The inverse modulo $q$ of a polynomial $a$ is a polynomial $A$ with the property that $$a \* A \equiv 1 \pmod q.$$ > > > Not every polynomial has an inverse modulo $q$, but it is easy to determine if $a$ has an inverse, and to compute the inverse if it exists. A fast algorithm for computing the inverse is described in NTRU Technical Note 014, and a theoretical discussion of inverses in truncated polynomial rings is given in NTRU Technical Note 009. These notes may be downloaded from the Technical Center. > > > Example. Take $N=7$, $q=11$, $a=3+2X^2-3X^4+X^6$. The inverse of $a$ modulo 11 is $$A=-2+4X+2X^2+4X^3-4X^4+2X^5-2X^6,$$ since $$(3+2X^2-3X^4+X^6)\*(-2+4X+2X^2+4X^3-4X^4+2X^5-2X^6) \\ = -10+22X+22X^3-22X^6 \equiv 1 \pmod{11}."$$ > > > I do not understand how $-10+22X+22X^3-22X^6$ may be 1 (modulo 11). Why??????? The first excerpt adduced says that each coefficient of the polynomial minus 1 must be a quotient of 11. But it's not. -10? That's not a problem. $-10 - 1 = -11$. $-11 \bmod 11$ is 0, yes, it works, I agree. But how can it work with 22? $22 - 1 = 21$. $21 \bmod 11 = 10$, not 0. also it doesn't work with $- 22$. $-22 - 1 = -23$. $-23 \bmod 11 = -1$. Can anyone, please, explain me this example?
2011/12/26
[ "https://crypto.stackexchange.com/questions/1538", "https://crypto.stackexchange.com", "https://crypto.stackexchange.com/users/1304/" ]
$$(-10+22x+22x^3-22x^6) - 1 = -11+22x+22x^3-22x^6 \equiv 0 \mod 11.$$ When substracting a constant from a polynomial, you do *not* subtract it from every term, only from the constant term. If you need a refresher, see [addition and subtraction of polynomials](http://www.jamesbrennan.org/algebra/polynomials/addition_and_subtraction_of_poly.htm).
10,084,902
I've been dealing with this before but it seems like the problem came back. Let me explain. I have a web page that lets a user upload a big file, after which it may also take several seconds for the ASP.NET server-side script to process it. In the meantime I wanted to show a loader/spinner animation in a web browser to prevent users from clicking the submit button again. I used the following JQuery code: ``` $('#ButtonImportData').click(function () { $('.importSubmitSpinner').css('display', 'inline'); } ``` here's the HTML for the spinner image: ``` <img src="Graphics/spinner_big.gif" width="28" height="28" class="importSubmitSpinner" alt="Spinner" /> ``` and here's CSS: ``` .importSubmitSpinner { margin: 0px 10px 0px 6px; width: 28px; height: 28px; display: none; } ``` spinner\_big.gif is a simple GIF file with an animation to signal for a user that a page is loading. The above approach works in almost all browsers, except ... guess which one? Yes, IE! What happens in IE is that after a user clicks the ButtonImportData button the spinner is displayed but the animation stops immediately, basically giving a user a false indication that a page got hung up which prompts them to click submit again -- an opposite to what I wanted to do. I stopped using IE a long time ago but evidently there is about half of the Internet community that still uses it. Man, how can people use that piece of \*&^%? Anyway, that is not a question :) The question is, how to make this simple task work in IE and make my animation actually play? PS. I've been testing it with IE 9 or whatever is the current "beauty of the web" for Windows 7. **EDIT:** Thanks to, ShadowScripter, I found a solution. Here's what worked for me: 1 Add the following to HTML to determine if we're running on IE (because we don't need to do this "hack" for any other web browser): ``` <![if !IE]> <script type='text/javascript'> var bNotIE = 1; </script> <![endif]> ``` 2 We need to add ID to the img element: ``` <img src="Graphics/spinner_big.gif" width="28" height="28" class="importSubmitSpinner" alt="Spinner" id="imgSpinnerImport" /> ``` 3 Then to display the GIF animation: ``` $('#ButtonImportData').click(function () { //For "normal" browsers $('.importSubmitSpinner').show(); if (typeof (bNotIE) == 'undefined') { //The following must be done only in case of IE //NOTE: We need to load the same file but with a different name // because if you don't change the file name it won't work! setTimeout('document.images["imgSpinnerImport"].src = "Graphics/spinner_big_ie.gif"', 200); } } ```
2012/04/10
[ "https://Stackoverflow.com/questions/10084902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/670017/" ]
I think problem is with URL. It work <http://www.itrain.com.my/v3/> but doesnt work on <http://itrain.com.my/v3/> Set on your server redirection (301) from non-www URL to www URL.
13,791,047
this is possibly much of an elementary question, but I'm having trouble with a procedure I have to write in Scheme. The procedure should return all the prime numbers less or equal to N (N is from input). ``` (define (isPrimeHelper x k) (if (= x k) #t (if (= (remainder x k) 0) #f (isPrimeHelper x (+ k 1))))) (define ( isPrime x ) (cond (( = x 1 ) #t) (( = x 2 ) #t) ( else (isPrimeHelper x 2 ) ))) (define (printPrimesUpTo n) (define result '()) (define (helper x) (if (= x (+ 1 n)) result (if (isPrime x) (cons x result) )) ( helper (+ x 1))) ( helper 1 )) ``` My check for prime works, however the function `printPrimesUpTo` seem to loop forever. Basically the idea is to check whether a number is prime and put it in a result list. Thanks :)
2012/12/09
[ "https://Stackoverflow.com/questions/13791047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1195020/" ]
First, it is good style to express nested structure by indentation, so it is *visually apparent;* and also to put each of `if`'s clauses, the *consequent* and the *alternative*, on its own line: ``` (define (isPrimeHelper x k) (if (= x k) #t ; consequent (if (= (remainder x k) 0) ; alternative ;; ^^ indentation #f ; consequent (isPrimeHelper x (+ k 1))))) ; alternative (define (printPrimesUpTo n) (define result '()) (define (helper x) (if (= x (+ 1 n)) result ; consequent (if (isPrime x) ; alternative (cons x result) )) ; no alternative! ;; ^^ indentation ( helper (+ x 1))) ( helper 1 )) ``` Now it is plainly seen that the last thing that your `helper` function does is to call itself with an incremented `x` value, always. There's no stopping conditions, i.e. this is an infinite loop. Another thing is, calling `(cons x result)` does not alter `result`'s value in any way. For that, you need to set it, like so: `(set! result (cons x result))`. You also need to put this expression in a `begin` group, as it is evaluated not for its value, but for its [*side-effect*](http://en.wikipedia.org/wiki/Side_effect_(computer_science)): ``` (define (helper x) (if (= x (+ 1 n)) result (begin (if (isPrime x) (set! result (cons x result)) ) ; no alternative! (helper (+ x 1)) ))) ``` Usually, the explicit use of `set!` is considered bad style. One standard way to express loops is as [tail-recursive](http://en.wikipedia.org/wiki/Tail_call) code using *named let*, usually with the canonical name "`loop`" (but it can be any name whatever): ``` (define (primesUpTo n) (let loop ((x n) (result '())) (cond ((<= x 1) result) ; return the result ((isPrime x) (loop (- x 1) (cons x result))) ; alter the result being built (else (loop (- x 1) result))))) ; go on with the same result ``` which, in presence of [tail-call optimization](http://en.wikipedia.org/wiki/Tail_call), is actually equivalent to the previous version.
107,822
I am working on this exercise: If $E$ is an intermediate field of an extension $F/K$ of fields. Suppose $F/E$ and $E/K$ are Galois extensions, and every $\sigma\in Gal(E/K)$ is extendible to an automorphism of $F$, then show that $F/K$ is Galois. I can see that any $\sigma$ extended over $F$ fixes elements in $K$ but not in $E-K$. But how to show it doesn't fix elements in $F-E$? Hints only please, this is homework. p.s. we use Kaplansky, he doesn't require Galois extensions to be finite dimensional.
2012/02/10
[ "https://math.stackexchange.com/questions/107822", "https://math.stackexchange.com", "https://math.stackexchange.com/users/24744/" ]
Here is a full solution of the problem. Since the OP already solved it, I think there is no harm in writing a full solution of it here. We denote by $Aut(K/k)$ the group of automorphisms of a field extension $K/k$. Let $K/k$ be a not necessarily finite dimensional algebraic extension field. If $K$ is normal and separable over $k$, we say $K/k$ is Galois. If $K/k$ is Galois, we write $G(K/k)$ instead of $Aut(K/k)$. We need the following characterization of a Galois extension field. **Lemma** An algebraic extension field $K/k$ is Galois if and only if the fixed subfield of $K$ by $Aut(K/k)$ is $k$. Proof. Suppose $K/k$ is Galois. Let $\alpha \in K - k$. Let $f(X)$ be the minimal polynomial of $\alpha$ over $k$. Since $K/k$ is normal and separable, there exists a root $\beta$ of $f(X)$ such that $\alpha \ne \beta$ and $\beta \in K$. Let $\sigma\colon k(\alpha) \rightarrow k(\beta)$ be the unique isomorphism such that $\sigma(\alpha) = \beta$. Since $K/k$ is normal, $\sigma$ can be extended to an automorphism $\sigma'$ of $K/k$. Since $\sigma'(\alpha) = \beta$, we are done. Conversely suppose the fixed subfield of $K$ by $G = Aut(K/k)$ is $k$. Let $\alpha$ be an element of $K$. Let $f(X)$ be the minimal polynomial of $\alpha$ over $k$. Since $\sigma(\alpha)$ is a root of $f(X)$ for every $\sigma \in G$, the set $S = \{\sigma(\alpha)\mid \sigma \in G\}$ is finite. Let $\sigma\_1, \cdots, \sigma\_m$ be elements of $G$ such that $\sigma\_1(\alpha), \cdots, \sigma\_m(\alpha)$ are pairwise distinct and $S = \{\sigma\_1(\alpha), \cdots, \sigma\_m(\alpha) \}$. Let $g(X) = (X - \sigma\_1(\alpha))\cdots (X - \sigma\_m(\alpha))$. Since every coefficient of $g(X)$ is fixed by $G$, $g(X) \in k[X]$. Since $g(\alpha) = 0$, $g(X)$ is divisible by $f(X)$. Since each $\sigma\_i(\alpha)$ is a root of $f(X)$, $g(X) = f(X)$. Hence $\alpha$ is separable over $k$ and $K/k$ is normal. This completes the proof of the lemma. Now let $F/K, E/K$ be as in the problem. By the lemma, it suffices to prove that the fixed subfield of $F$ by $Aut(F/K)$ is $K$. Suppose $\alpha \in F$ is fixed by $Aut(F/K)$. Since $G(F/E) \subset Aut(F/K)$, $\alpha$ is fixed by $G(F/E)$. Hence $\alpha \in E$ by the lemma. Since every element of $G(E/K)$ is extended to an element of $Aut(F/K)$, $\alpha$ is fixed $G(E/K)$. Hence $\alpha \in K$ by the lemma. This completes the proof.
25,903,779
Can you please take a look at [This Demo](http://jsfiddle.net/Behseini/xLea235h/) and let me know how I can loop through and element like `<pre>` and replace all `<` and `>` with some new characters like: ``` .replace("<", "1"); .replace(">", "2"); ``` if we have a `<pre>` like ``` <pre> < This is a test < which must > replace > </pre> ``` Thanks
2014/09/18
[ "https://Stackoverflow.com/questions/25903779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3649067/" ]
You can use [.text()](http://api.jquery.com/text/) and [String.replace()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) using an [RegExp](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) ```js $('pre').text(function(i, text){ return text.replace(/</g, '1').replace(/>/g, '2') }) ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <pre> < This is a test < which must > replace > </pre> ```
23,475
Let me give you a run down of the board state. I had an [Elderscale Wurm](https://gatherer.wizards.com/Pages/Card/Details.aspx?name=Elderscale%20Wurm) enchanted with [Canopy Cover](https://gatherer.wizards.com/Pages/Card/Details.aspx?name=Canopy%20Cover) on the battlefield. Damage could not reduce my life total below 7. My opponent had [Forgestoker Dragon](https://gatherer.wizards.com/Pages/Card/Details.aspx?name=Forgestoker%20Dragon) on the battlefield and a lot of other, smaller creatures. He could pay to kill any other creature that came out on the battlefield, but had no effects in his deck to deal with Elderscale Wurm nor Canopy Cover. Similarly I had no way to deal with his dragon, and if I attacked with my Elderscale Wurm it would die, and I would lose to his horde. But, I had one more card in my library than he did, so we assumed I would eventually win until we looked at the other two cards my opponent had on the battlefield- [Aether Rift](https://gatherer.wizards.com/Pages/Card/Details.aspx?name=Aether%20Rift) and [Library of Leng](https://gatherer.wizards.com/Pages/Card/Details.aspx?name=Library%20of%20Leng). Aether Rift says: > > Enchantment > > > At the beginning of your upkeep, discard a card at random. If you discard a creature card this way, return it from your graveyard to the battlefield unless any player pays 5 life. > > > Library of Leng says: > > Artifact > > > You have no maximum hand size. If an effect causes you to discard a card, discard it, but you may put it on top of your library instead of into your graveyard. > > > My opponent only had creatures in his hand. He wanted to use the interaction between these two cards to randomly discard a card, not pay 5 life,(I could not pay the 5 life cost because it would bring me below 7 life, negating Elderscale Wurm's effect) and have it go back to the top of his library, so that he would have 1 more card than I did, thus I would mill out before he did. Is that how this interaction works?
2015/03/20
[ "https://boardgames.stackexchange.com/questions/23475", "https://boardgames.stackexchange.com", "https://boardgames.stackexchange.com/users/12101/" ]
He would be able to put a card on top of his library in order to not lose, but not quite the way you are thinking it works. What happens is a the beginning of your opponent's upkeep Aether Rift's ability goes on the stack, and when it resolves they discard a card at random. when the card gets discarded Library of Leng's replacement effect occurs allowing your opponent to put the card on top of their library. If they chose to put the card on top of their library the rest of Aether Rift's ability doesn't apply since as far as the game knows a creature card was never discarded (a card was discarded if anything else cares about that, but nothing is known about that card, including its type [[CR 701.7c]](http://mtgsalvation.gamepedia.com/Discard)). Your opponent will then draw the card they just "discarded" at the beginning of their draw step. They can keep repeating this process until you run out of cards in your library.
7,310,084
So, I'm trying to make a transaction with LINQ to SQL. I read that if I use `SubmitChanges()`, it would create a transaction and execute everything and in case of an exception everything would be rolled back. Do I need to use MULTIPLE `SubmitChanges()`? I'm using something like this code and it isn't working because it isn't saving any data on the first table.. (I need it's ID for the children table). If I do use another `SubmitChanges()` right after the first `InsertOnSubmit` doesn't it lose the idea of a transaction? ``` myDataContext db = new myDataContext(); Process openProcess = new Process(); openProcess.Creation = DateTime.Now; openProcess.Number = pNumber; //Set to insert db.Process.InsertOnSubmit(openProcess); Product product = new Product(); product.Code = pCode; product.Name = pName; product.Process_Id = openProcess.Id; //Submit all changes at once? db.SubmitChanges(); ```
2011/09/05
[ "https://Stackoverflow.com/questions/7310084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/110282/" ]
You can make the whole thing transaciotnal using a `TransactionScope` e.g. ``` using (TransactionScope scope = new TransactionScope()) { myDataContext db = new myDataContext(); Process openProcess = new Process(); openProcess.Creation = DateTime.Now; openProcess.Number = pNumber; db.Process.InsertOnSubmit(openProcess); db.SubmitChanges(); //openProcess.Id will be populated Product product = new Product(); product.Code = pCode; product.Name = pName; product.Process_Id = openProcess.Id; db.Products.InsertOnSubmit(product); // I assume you missed this step in your example db.SubmitChanges(); scope.Complete() } ``` If an exception is thrown before `scope.Complete()` is called then the whole thing will be rolled back.
23,972,031
I want to merge few code lines of a commit belonging to a different branch into a new commit of my `master`, i.e. using a difftool apply only some changes of another commit. I tried from `master` with ``` merge --no-commit --no-ff newJob git reset . ``` but then I don't know how to choose only part of the changes. This is because I'm writing my CV in latex and I want to create a different branch when I use a different template, a new layout, or when I want to customize it for a particular job. Then it happens that I update or correct details in the branch, let's say, `newJob` and I have to correct these details also into the `master`. Using a difftool would be really quick.
2014/05/31
[ "https://Stackoverflow.com/questions/23972031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3694516/" ]
A recorded merge says all changes that need to be applied have been; later merges of the two histories won't reexamine changes you discard in this merge. It may not be what you want here. To apply just a few changes from commit B, do e.g. ``` git diff-tree -p B file ... | git apply git add -p . # (this is the pick-my-diffs command you wanted) git checkout file ... # (optional, undo any changes not staged) ```
11,058,984
I'm reading in from a CSV file, parsing it, and storing the data, pretty simple. Right now were using the standard `readLine()` method to do that, and I'm trying to squeeze some extra efficency out of this processing loop. I don't know how much they hide behind the scenes, but I assume each call to `getLine` is a new OS call with all the pain that entails? I don't want to pay for OS calls on each line of input. I would provide a huge buffer and have it fill the buffer with many lines at once. However, I only care about full lines. I don't want to have to handle maintaining partial lines from one buffer read to append to the second buffer read to make a full line, that's just ugly and annoying. So, is there a method out there that does this for me? It seems like there almost has to be. Any method which I can instruct to read in x number of lines, or x bytes but don't output the last partial line, or even an easy way for me to manage the memory buffer so I minimize the amount of code for handling partial strings would be appreciated. I can use Boost, though if there is a method in standard C++ I would prefer that. Thanks.
2012/06/15
[ "https://Stackoverflow.com/questions/11058984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/897272/" ]
It's very unlikely that you'll be able to do better than the built-in C++ streams. They're quite fast. In general, the fastest way to completely read a file is to use a single thread to read the entire file from start to end, especially if the file is contiguous on disk. Furthermore, it's likely that the disk is much more of a bottleneck during reading than the OS. If you need to improve the performance of your app, I have a few recommendations. * Use a profiler. If your app is reading a line then parsing it or processing it in some way, it's possible that the parsing or processing is something that can be optimized. This can be determined in profiling. If parsing or processing takes up substantial CPU resources, then optimization may be worth the effort. * If you determine that parsing or processing is responsible for a slow application, and that it can't be easily optimized, consider multiprogramming. If the processing of individual lines does not depend on the results of previous lines being processed, then use multiple threads or CPUs to do the processing. * Use pipelining if you have to process multiple files. For example, suppose you have four stages in your app: reading, parsing, processing, saving. It may be more efficient to read one file at a time rather then all of them all at once. However, while reading the second file, you can still parse the first one. While reading the third file, you can parse the second file and process the first one, etc. One way to implement this is a [staged mult-threaded application design](http://en.wikipedia.org/wiki/Staged_event-driven_architecture). * Use RAID to improve disk reads. Certain raid modes can create faster reads and writes.
4,509,899
I would like to fetch some data into my Excel Spreadsheet (Excel 2007) from webservice, but I would like to deploy the spreadsheet as one file only (f.e. spreadsheet.xlsx - nothing more). Without this constraint I would use Visual Studio addons and write it in C#, but it would give me some extra dlls and vsto files. In earlier version of excel, there was Webservices Tolkit, but my research indicate, that it won't work with 2007. Are there any solutions out there? I heard something about Microsoft Office Soap Type library 3.0, but I don't know how to start working with it. Any help / sample code / other solutions will be appreciated.
2010/12/22
[ "https://Stackoverflow.com/questions/4509899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/460822/" ]
I find out how to connect with webservice with Ms Office Soap Type library in vba - so no extra files, just xls(x). At this point I know how to get simple datatypes results (like string). But I hope, I'll be able to get and work with more complex types. Here's the code: ``` Dim webservice As SoapClient30 Dim results As String ' Point the SOAP API to the web service that we want to call... Set webservice = New SoapClient30 Call webservice.mssoapinit(par_WSDLFile:="{url to wsdl}") ' Call the web service results = webservice.{method name}() Set webservice = Nothing ``` It's necessary to add "Microsoft Office Soap Type Library v3.0" to your worksheet references.
33,982,545
I've receiving this error in every project I make, new or otherwise. [![Error in Android Studio](https://i.stack.imgur.com/UxnnV.png)](https://i.stack.imgur.com/UxnnV.png) I've attempted reinstalling Android Studio fresh without any luck and I've also scoured the Internet for the exact error and nothing seems to be coming up. Does anyone have an idea of what's causing this error when I add a new layout to my project?
2015/11/29
[ "https://Stackoverflow.com/questions/33982545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5279721/" ]
As your screenshot shows,current package name is layout,but maybe you don't have a package named `layout`,so such error existed. If you want to add a layout file to your project,you should right click **layout** folder under **res** folder,and create a layout file.
67,583,686
So what I want to do is take the input from the radio buttons (**metric** or **imperial**) from *Forecast.js*, use them in a function in *Conditions.js* to determine whether it's hot or cold. I've exported the variable **unit** from *Forecast.js* but when I try to use it in the **clothes()** function it doesn't work. I've tried everything I found online and I tried to understand but I'm new to Reactjs. Conditions.js <https://pastebin.com/RHbLuqZD> ``` import { unit } from '../Forecast/Forecast.js'; function clothes(t) { if (unit === "metric") { if (Number('t') <= 20) return (<> <img src={Cold} alt="wind icon" style={{ width: 50, marginRight: 20, height: 50 }} /> It's cold, dress accordingly! </>); else return (<> <img src={Hot} alt="wind icon" style={{ width: 50, marginRight: 20, height: 50 }} /> It's Warm, dress accordingly! </>); } if (unit === "imperial") { if (Number('t') <= 70) return (<> <img src={Cold} alt="wind icon" style={{ width: 50, marginRight: 20, height: 50 }} /> It's cold, dress accordingly! </>); else return (<> <img src={Hot} alt="wind icon" style={{ width: 50, marginRight: 20, height: 50 }} /> It's Warm, dress accordingly! </>); } } ``` Forecast.js <https://pastebin.com/wcBu8bwA> ``` export default Forecast; export let unit = this.state.unit; ``` The reason it doesn't work could be because I didn't do the import and export properly or because I didn't use the imported variable properly. **Edit:** As I specified I'm a beginner, I don't know a lot, what I want is to see how to solve the problem and then understand how to do it. I just need to understand the problem with my code, or an alternative.
2021/05/18
[ "https://Stackoverflow.com/questions/67583686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6372847/" ]
You switch on `TypeOfDatabase` in the constructor before the property has been set. Move the `switch` statement to the `OnTypeOfDatabaseChanged` callback or to a `Loaded` event handler: ``` public BaseConnection() { InitializeComponent(); _languageCode = Thread.CurrentThread.CurrentCulture.Name; this.Resources = _cultureHelper.FindRessourcesDictionnary(this.Resources, "UserControlsResources", _languageCode); Loaded += OnLoaded; } private void OnLoaded(object sender, RoutedEventArgs e) { List<UcConnection> connectionListByDatabaseType = new List<UcConnection>(); switch (TypeOfDatabase) { case DataBaseType.MySql: foreach (UcConnection ucConnection in UcConnectionList) { if (ucConnection.DriverName.ToLower().Contains("mysql")) { connectionListByDatabaseType.Add(ucConnection); } } UcConnectionList = connectionListByDatabaseType; break; case DataBaseType.SqlServer: break; default: break; } } ```
65,070
I want the user to be able to choose whether to show a description or not for each node in the view. Adding the filter only works on the entire object, I just want to show/hide one field. How can I achieve this?
2013/03/10
[ "https://drupal.stackexchange.com/questions/65070", "https://drupal.stackexchange.com", "https://drupal.stackexchange.com/users/13976/" ]
You can do this with Views out of the box. No need for Views PHP here. 1. Add your boolean field in Views. (This assumes the default boolean set up, i.e. 0 for not checked and 1 for checked.) 2. Use the **Key** formatter - this isn't obvious, but I couldn't get it to work without this. 3. Select **REWRITE RESULTS** and put the description you want in there. This can include tokens so you can grab material from other fields in the node if that's what you need. 4. On **NO RESULTS BEHAVIOR** check all the boxes (Count the number 0 as empty, Hide if empty, Hide rewriting if empty)
2,481,903
i m designing a simple c code to call the iptables command according to the need. i just want to drop the packets from a particular ipaddress using my c code. thats why i have to use the iptables command according to input given. is it possible to call the command using c code? if it is then how??? thanks in advance..
2010/03/20
[ "https://Stackoverflow.com/questions/2481903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/297864/" ]
Assuming that your program is running as root, just use fork() and exec(), and pass the iptables command to exec(). Something like ``` if (0 == fork()) { execl("/sbin/iptables", ...); // supply the proper arguments to iptables. } ``` Edit: I see from other people that system() is a better way than fork/exec. It sounds like Neha is not sure how to use sprintf to format the command so that it contains an IP address which is stored in some other variable. I think it should look like this: ``` char *host_to_block = .... char comm[1000]; snprintf(comm, sizeof(comm), "iptables -A INPUT -s %s -j DROP", host_to_block); system(comm); ``` Note that this will be a **security vulnerability** unless you have code to verify that host\_to\_block contains an IP address and not some other shell command. You may want to use the following question for reference if the source of the string is not already known to be valid: [how to validate an ip address](https://stackoverflow.com/questions/318236/how-do-you-validate-that-a-string-is-a-valid-ip-address-in-c)
3,135,770
$$\sum \_{k=1}^n\sqrt[3]{k}\:>\frac{3}{4}n\sqrt[3]{n}$$ We have the inequality as defined as above. Clearly, one can prove it by induction; it would not be hard. However, it looks suspiciously like it could be done by Jensen's inequality; I am just not sure how. I tried the obvious substitution $f(x)=x^{1/3}$, but then this function is concave, and I cannot use it to prove the inequality. So, I was just wondering if anyone is able to use Jensen's to prove this inequality? Or is there any other inequality that anyone knows that can be used to prove this question without induction?
2019/03/05
[ "https://math.stackexchange.com/questions/3135770", "https://math.stackexchange.com", "https://math.stackexchange.com/users/646705/" ]
$$\sum\_{k=1}^n\sqrt[3]{k}\geq1+\int\limits\_1^n\sqrt[3]xdx=\frac{3}{4}\sqrt[3]{n^4}+\frac{1}{4}>\frac{3}{4}n\sqrt[3]n.$$
66,145,860
I have data with uniquely identified individuals, in groups, which were surveyed multiple times. Sometimes new individuals showed up after the first survey, and I want to find those new individuals by group. E.g., ``` group <- rep(1:2, each=9) surv <- c(1,1,2,2,2,3,3,3,3,1,1,1,2,2,2,2,3,3) ind <- c("a","b","a","b","c","a","b","c","d", "a","b","c", "a", "b","c","d", "a","b") dat <- data.table(surv=surv, group=group, ind=ind) setkey(dat, surv, group) ``` I want a new data table with the new inviduals i.e., ``` survey 2, group 1, "c" survey 2, group 2, "d" survey 3, group 1, "d" ``` I'm flummoxed by this, which the following starter code shows: ``` dat[surv==2, !(ind %in% surv==1), by = group] ```
2021/02/10
[ "https://Stackoverflow.com/questions/66145860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3773126/" ]
This is the first survey each individual appeared in each group, ``` dat[order(ind, surv), .SD[1], .(group, ind)][surv != 1] #> group ind surv #> 1: 1 c 2 #> 2: 2 d 2 #> 3: 1 d 3 ``` Note I've excluded the individuals who first appeared in the first survey.
35,180,409
I've built a password Generator: ``` Public Function PassGen() Dim pool As String = "0123456789abcdefghijklmnopqrstuvwxzyABCDEFGHIJKLMNOPQRSTUVWXYZ+@*#%&/()?!$-" Dim rnd As New Random Dim result As String Dim i As Integer = 0 Do Until i = 10 result &= pool(rnd.Next(0, pool.Length)) i = i + 1 Loop Return result End Function ``` Now I'd like to check if the generated password contains a number, upper- and lowercase and special characters. If the generated password doesn't contain those 4 things, it should generate another password and check it again and so on. I tried to loop a `Regex.Match`: ``` Dim text As String = PassGen() Do Until Regex.Match(text, "^[0-9]$") text = PassGen() Loop ``` What didnt work as it wont let me loop a `regex.match()`. I also tried it with `String.Contains()`. But as far as I know the Contains-method can only check for one string and not for a range or a type(like Integer). Is there a possibility to check my password for those four string-ranges or do I have to modify my function that it has to use one of each?
2016/02/03
[ "https://Stackoverflow.com/questions/35180409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5633942/" ]
You could use the `LIKE` keyword in VB. The `LIKE` is like a mini-regex built in into VB.NET. ``` If text Like "*[A-Z]*" AndAlso text Like "*[a-z]*" AndAlso text Like "*[0-9]*" AndAlso text Like "*[+@*#%&/()?!$-]*" Then ' it is a valid password Else ' password doesn't match required constraints... do whatever to regenerate it here... End If ```
58,475,748
``` name: test-publish on: [push] jobs: test: strategy: ... steps: ... publish: needs: test if: github.event_name == 'push' && github.ref??? steps: ... # eg: publish package to PyPI ``` What should I put in `jobs.publish.if` in order to check that this commit is new release? Is this okay: `contains(github.ref, '/tags/')`? What will happen if I push code and tag at the same time?
2019/10/20
[ "https://Stackoverflow.com/questions/58475748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6689249/" ]
You could do this to check if the current push event is for a tag starting with `v`. ``` publish: needs: test if: startsWith(github.ref, 'refs/tags/v') ``` As you pointed out though, I don't think you can guarantee that this is a new release. My suggestion would be to use `on: release` instead of `on: push`. This will only trigger on a newly tagged release. See the docs for `on: release` here: <https://docs.github.com/en/actions/reference/events-that-trigger-workflows#release>
60,337,287
We are deploying Spring Boot app to the Kubernetes. When the firs user requests comes it takes more than 10s to response. Subsequent requests take 200ms. I have created a warmup procedure to run the key services in `@PostConstruct`. I reduces the time to process the first query to 4s. So I wanted to simulate this first call. I know that Kubernetes rediness probe can make a POST request, but I need authorization and other things. Can I make a real HTTP call to the controller from the app itself?
2020/02/21
[ "https://Stackoverflow.com/questions/60337287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/506078/" ]
Sure, you can always make an HTTP client to localhost The solution isnt specific to k8s or Spring or Java, but any web server You could also try making your readiness probe just the tcp port or some internal script
59,642
Suppose $w(t)$ is a white noise with uniform spectral density $N\_0/2$. It is bandpass filtered to get a narrowband white noise $n(t)$ for $f\_c - B\_T/2 \leqslant |f| \leqslant f\_c + B\_T/2$. We write this in polar form by splitting into inphase and quad-phase wrt $2\pi f\_ct$. $n(t) = n\_I \cos(2\pi f\_ct) - n\_Q \sin(2\pi f\_ct)$ such that we get a phase $\phi\_n = \tan^{-1} (n\_Q/n\_I) $. Is this phase uniformly distributed on $[ 0, 2\pi ]$? If yes, why?
2019/07/20
[ "https://dsp.stackexchange.com/questions/59642", "https://dsp.stackexchange.com", "https://dsp.stackexchange.com/users/44018/" ]
...And now for a differing opinion.... The OP's representation of bandpass white noise as $$n(t) = n\_I \cos(2\pi f\_ct) - n\_Q \sin(2\pi f\_ct)\tag{1}$$ is inadequate; because each sample path of this noise process is a *pure sinusoid* of *fixed* frequency $f\_c$ Hz which is not noise-like at all. Why so? Well, a sample path is what one gets when all the random variables are assumed to have taken on appropriate values, and so with $n\_I = \frac{\sqrt{3}}{2}$ and $n\_Q = \frac 12$ (say), we get the sample path $$\frac{\sqrt{3}}{2}\cos(2\pi f\_ct) - \frac 12 \sin(2\pi f\_ct) = \cos\left(2\pi f\_ct+\frac{\pi}{6}\right)$$ which is a pure sinusoid as claimed. A better representation of $n(t)$ is $$n(t) = n\_I(t) \cos(2\pi f\_ct) - n\_Q(t) \sin(2\pi f\_ct)\tag{2}$$ where $\{n\_I(t)\}$ and $\{n\_Q(t)\}$ are *low-pass* *uncorrelated* white noise processes with *identical* power spectral densities that have constant value for $|f| \leq \frac{B\_T}{2}$. Note that a typical sample path from $(2)$ is "sort of" sinusoidal-looking at frequency *approximately* $f\_c$ Hz, but the instantaneous amplitude and instantaneous phase (as well as instantaneous frequency (derivative of instantaneous phase) are "slowly varying" functions of time. Here, "slowly varying" means in comparison to the approximate time period $f\_c^{-1}$ of each cycle of the sinusoid. --- All this is fine and dandy but has *nothing* to do with the question being considered: the distribution of the instantaneous phase $\operatorname{atan2}(n\_Q(t),n\_I(t))$. The WSS theory tells us *nothing* about the *distributions* of the random variables $n\_Q(t)$ and $n\_I(t)$, except, of course, when $n(t)$ is a *Gaussian* process in which case $\{n\_I(t)\}$ and $\{n\_Q(t)\}$ are *independent* Gaussian processes and we know for sure that $\operatorname{atan2}(n\_Q(t),n\_I(t))$ is indeed uniformly distributed on $[0,2\pi)$. *But*, I contend that since we are discussing *white noise* processes, *any* distribution *other* than $\mathcal U(0,2\pi)$ for the phase would mean that the noise exhibits a *preference* for some phases and a dislike for some other phases, and this idea sticks in my craw as being totally unrepresentative of white noise. Indeed, even the answer by @StanleyPawlukiewicz that $\arctan(n\_Q(t)/n\_I(t))$ is uniformly distributed on $[-\pi/2,\pi/2]$ is disturbing because it *suggests* that it might be the case that $n\_I(t)$ is always positive while $n\_Q(t)$ has a more symmetric distribution. We really need $\operatorname{atan2}(n\_Q(t),n\_I(t))$ for defining the phase; $\arctan$ is inadequate for the job. So, there you have it, folks, The phase is uniformly distributed on $[0,2\pi)$ because it offends my sensibilities to have any other distribution for the phase, and that's all there is to it; ymmv.
1,895,769
Why is the time complexity of node deletion in doubly linked lists (O(1)) faster than node deletion in singly linked lists (O(n))?
2009/12/13
[ "https://Stackoverflow.com/questions/1895769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230582/" ]
The problem assumes that the node to be deleted is known and a pointer to that node is available. In order to delete a node and connect the previous and the next node together, you need to know their pointers. In a doubly-linked list, both pointers are available in the node that is to be deleted. The time complexity is constant in this case, i.e., O(1). Whereas in a singly-linked list, the pointer to the previous node is unknown and can be found only by traversing the list from head until it reaches the node that has a next node pointer to the node that is to be deleted. The time complexity in this case is O(n). In cases where the node to be deleted is known only by value, the list has to be searched and the time complexity becomes O(n) in both singly- and doubly-linked lists.
69,758,091
I am trying to write a window popup function, so whenever person types character v in Chrome, it will open popup. The following is not working, I type "v" on keyboard, and no popup window opens. How can I fix this? Using this in F12 Console to write the function. ``` function doc_keyUp(e) { if (e.keyCode == 86) { alert("Test!"); } } ``` Resource Hotkey: <https://keycode.info/>
2021/10/28
[ "https://Stackoverflow.com/questions/69758091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15435022/" ]
Try it: ``` window.addEventListener("keydown", e => { if ( e.keyCode == 86 ) { //window.open("url") } }); ```
35,022,647
I have the following code:- ``` if( $featured_query->have_posts() ): $property_increment = 0; while( $featured_query->have_posts() ) : $featured_query->the_post(); $town = get_field('house_town'); $a = array($town); $b = array_unique($a); sort($b); var_dump($b); $property_increment++; endwhile; ?> <?php endif; wp_reset_query(); ``` `var_dump(b)` shows:- > > array(1) { [0]=> string(10) "Nottingham" } array(1) { [0]=> string(9) "Leicester" } array(1) { [0]=> string(9) "Leicester" } array(1) { [0]=> string(11) "Mountsorrel" } array(1) { [0]=> string(12) "Loughborough" } array(1) { [0]=> string(12) "Loughborough" } > > > `var_dump($town)` shows:- > > string(10) "Nottingham" string(9) "Leicester" string(9) "Leicester" string(11) "Mountsorrel" string(12) "Loughborough" string(12) "Loughborough" > > > `var_dump($a)` shows:- > > array(1) { [0]=> string(10) "Nottingham" } array(1) { [0]=> string(9) "Leicester" } array(1) { [0]=> string(9) "Leicester" } array(1) { [0]=> string(11) "Mountsorrel" } array(1) { [0]=> string(12) "Loughborough" } array(1) { [0]=> string(12) "Loughborough" } > > > What I want to do is get the unique vales of `$town` and output them into a select option:- ``` <select> <option value="Leicester">Leicester</option>'; <option value="Loughborough">Loughborough</option>'; <option value="Mountsorrel">Mountsorrel</option>'; </select>'; ``` In alpha as above, any help would be much appreciated.
2016/01/26
[ "https://Stackoverflow.com/questions/35022647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1128694/" ]
Your code isn't working, because `WebView` is strecthing to its parent height when you load and url there, so the `Button` will be out of screen. You just need not to place `Button` under `WebView`, but `WebView` above `Button` using `layout_above` property: ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:context="com.webviewwithbutton.WebViewWithButton"> <android.support.design.widget.CoordinatorLayout android:layout_above="@+id/button" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true"> <android.support.design.widget.AppBarLayout android:id="@+id/app_bar" android:layout_width="match_parent" android:layout_height="@dimen/app_bar_height" android:fitsSystemWindows="true" android:theme="@style/AppTheme.AppBarOverlay"> <android.support.design.widget.CollapsingToolbarLayout android:id="@+id/toolbar_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" app:contentScrim="?attr/colorPrimary" app:layout_scrollFlags="scroll|exitUntilCollapsed"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" app:layout_collapseMode="pin" app:popupTheme="@style/AppTheme.PopupOverlay"/> </android.support.design.widget.CollapsingToolbarLayout> </android.support.design.widget.AppBarLayout> <android.support.v4.widget.NestedScrollView android:id="@+id/nested_scroll_view" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_behavior="@string/appbar_scrolling_view_behavior"> <WebView android:id="@+id/webview" android:layout_width="match_parent" android:layout_height="wrap_content"/> </android.support.v4.widget.NestedScrollView> <android.support.design.widget.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="@dimen/fab_margin" android:src="@android:drawable/ic_dialog_email" app:layout_anchor="@id/app_bar" app:layout_anchorGravity="bottom|end"/> </android.support.design.widget.CoordinatorLayout> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_alignParentBottom="true" android:text="test"/> </RelativeLayout> ``` **EDIT:** I've found the way how you can do that - you just need to put your `CoordinatorLayout` and `Button` inside `RelativeLayout`, and make the same thing: place `CoordinatorLayout` above `Button` using `layout_above` property. It should work as expected. Just replace my xml above with yours.
79,291
More or less exactly what it says on the tin: How does the released and upcoming Fantastic Beasts film series, written by JK Rowling, fit into the existing Harry Potter canon? Do they have the same level of authority as the books, the utter lack of authority of the movies, or somewhere in between?
2015/01/15
[ "https://scifi.stackexchange.com/questions/79291", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/-1/" ]
There's no "official" canon in Potterverse the way LucasFilm had. So there's no way to answer your question precisely. Having said that, JKR will (at least according to my interpretation of her quotes) be the screenwriter for the films (unlike the original 8 Potter films) - see the bolded text for confirmation, all quotes from [BBC interview/article](http://www.bbc.co.uk/news/entertainment-arts-24067557): > > "It all started when Warner Bros came to me with the suggestion of turning Fantastic Beasts and Where to Find Them into a film," said Rowling. > > > "I thought it was a fun idea, **but the idea of seeing Newt Scamander, the supposed author of Fantastic Beasts, realised by another writer was difficult**. > > > "Having lived for so long in my fictional universe, **I feel very protective of it and I already knew a lot about Newt**. As hard-core Harry Potter fans will know, I liked him so much that I even married his grandson, Rolf, to one of my favourite characters from the Harry Potter series, Luna Lovegood. > > > She went on: "As I considered Warners' proposal, an idea took shape that I couldn't dislodge. **That is how I ended up pitching my own idea for a film to Warner Bros.** > > > As such, * the realistic out of universe canonicity would definitely be **WAY more than original Potter films** (where JKR wasn't a screenwriter), * but personally I would rate it **slightly less than the books' canonicity** because JKR as a screenwriter is under the control/influence of the director/producer of the movies. * Of course, this could all change if JKR officially states some canon rules. --- In addition, as far as in-universe continuity, Rowling said: > > "Although it will be set in the worldwide community of witches and wizards where I was so happy for 17 years, Fantastic Beasts and Where to Find Them is neither a prequel nor a sequel to the Harry Potter series, but an extension of the wizarding world. > > >
3,893,616
Let $G$ be an Abelian group of order $n$ and for a positive integer $m$ we have that $\text{gcd}(m,n)=1$. Then the function $\Psi:G \to G$ with $g \mapsto g^m$ is an automorphism. --- My try: First I show that the function is homomorphism: Let $g\_1,g\_2 \in G$ and consider $\Psi(g\_1g\_2)=(g\_1g\_2)^m$ and this is true since $G$ is a group,besides it's Abelian and so $\Psi(g\_1g\_2)=g\_1^{m}g\_2^{m}=\Psi(g\_1)\Psi(g\_1)$. The function is clearly surjective. To show that it's injective we need to show $\text{ker}(\Psi)=\left\{e\_G\right\}$, if we assume there exists $e\_G\ne g \in\text{ker}(\Psi)$ then $\Psi(g)=e\_G=g^m$,but I don't know how to continue. Any help is appreciated.
2020/11/04
[ "https://math.stackexchange.com/questions/3893616", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
Any $f\colon X\to X$ is bijective if it is surjective/injective when $X$ is finite. In this case, you can also use the following. Since $\gcd(m, n) = 1$ there are integers $r, s$ such that $rm+sn = 1$, so if $g^m = 1$, then $g^{rm+sn} = g^{sn} = 1$ because $|G| = n$, but at the same time $g^{rm+sn} = g^1 = g$, hence $\Psi$ is injective. To obtain surjectivity, observe that by $rm+sn=1$, we have for any $g\in G, (g^r)^m=g$.
50,819
The ISS recently jettison some garbage and expects it to take 2-4 years to de-orbit and burn up. From Gizmodo's [ISS Ditches 2.9-Ton Pallet of Batteries, Creating Its Most Massive Piece of Space Trash](https://gizmodo.com/iss-ditches-2-9-ton-pallet-of-batteries-creating-its-m-1846476992): > > The pallet is packed with nickel-hydrogen batteries, and it will stay in low Earth orbit for the next two to four years “before burning up harmlessly in the atmosphere,” according to a [NASA statement](https://blogs.nasa.gov/spacestation/2021/03/11/worm-observations-eye-checks-as-weekend-spacewalk-approaches/). SpaceFlightNow [reports that](https://spaceflightnow.com/2021/03/12/garbage-pallet-jettisoned-from-space-station-will-stay-in-orbit-two-to-four-years/) the pallet is the “most massive object ever jettisoned from the orbiting outpost.” > > > How come they don't give it a little extra push towards earth and have it de-orbit sooner? Or perhaps they did shove it as hard as they could and this is just how long it takes. It just seems logical that they would want to get it out of the way ASAP.
2021/03/16
[ "https://space.stackexchange.com/questions/50819", "https://space.stackexchange.com", "https://space.stackexchange.com/users/13320/" ]
I assume you refer to the jettison of the garbage pallet containing the old batteries, which came in at about 2.9 tons. Those were jettisoned using the Canadarm2. The Canadarm2 has the following operational limits: **Speed of Operations** * Unloaded: 37 centimeters / second (1.21 feet / second) * Loaded: + Station Assembly - 2 centimeters / second (.79 inches / second) + EVA Support - 15 centimeters / second (5.9 inches / second) + Orbiter - 1.2 centimeters / second (.47 inches / second) (Numbers from [Canadarm2 and the Mobile Servicing Subsystem](https://www.nasa.gov/mission_pages/station/structure/elements/subsystems.html)) I am not exactly sure where on this range the pallet falls - but presumably somewhere between 2cm/s and 15cm/s. The upper limits is 37cm/s. Orbital velocity of the ISS is ~7660m/s. That means the pallet can only get about 0.005% of change of velocity from the arm. Combine this with the fact that the pallet is very dense and has a small-ish cross-sectional area, the ballistic coefficient is rather high, so it doesn't experience much drag (compared to a large, light object). Going by this [Q&A](https://space.stackexchange.com/questions/50717/this-iss-trash-deployment-looks-more-like-2-feet-than-2-inches-per-second-was-i), jettisoning stuff by hand yields velocities of about 0.6m/s, but only for stuff that is significantly lighter than 2.9 *tons*. @Uwe already gave a good comparison with the Shuttle, which needed 90m/s for the re-entry burn. The jettison was done with 0.37m/s. You can not simply "push harder" because of the operational limits of the Canadarm2 and the human body, depending on who does the jettison. And with such a small change in velocity, it takes a while to de-orbit. Which doesn't really matter. Making it de-orbit faster would incurs high costs for no apparent benefit.
40,986,385
I want to make a script, that measures how fast a participant is to press enter or space bar, only when they hear 2/30 sounds from sound files. So some times the user does not have to press anything, and the script still moves on to the next sound file. How do I do this? What I have right now is this: (instead of sound files, I have text atm.): ``` # Grounding of Words Experiment # #Import libraries import re import glob from psychopy import sound, visual, event, data, core, gui # imports a module for visual presentation and one for controlling events like key presses # ID, age, gender box display myDlg = gui.Dlg(title="Experiment") #, pos=(400,400) myDlg.addField('ID:') myDlg.addField('Age:') myDlg.addField('Gender:', choices = ['Female', 'Male']) myDlg.show()#you have to call show() for a Dlg if myDlg.OK: ID = myDlg.data[0] Age = myDlg.data[1] Gender = myDlg.data[2] else: core.quit() trial=0 #Creates the outfile, that will be the file containing our data, the name of the file, as saved on the computer is the filename out_file="Grounding_experiment_results.csv" #Creates the header for the data header="trial,ID,Gender,Age,Word,rt,SpaceKlik\n" #opens the outfile in writemode with open(out_file,"w") as f: f.write(header)#writes the header in the outfile # define window win = visual.Window(fullscr=True) # defines a window using default values (= gray screen, fullscr=False, etc) # Instruction box display def instruct(txt): instructions = visual.TextStim(win, text=txt, height = 0.05) # create an instruction text instructions.draw() # draw the text stimulus in a "hidden screen" so that it is ready to be presented win.flip() # flip the screen to reveal the stimulus event.waitKeys() # wait for any key press instruct(''' Welcome to the experiment! You will be hearing different words. Whenever you hear the word "Klik" and "Kast" please press the left mouse button. Whenever you hear any other word - do nothing. Try to be as fast and accurate as possible. Please put on the headphones. The experiment will take 5 minutes. Press any key to start the experiment''') # Play sound # Function that makes up a trial trial(word): global trial trial += 1 if word in ["Klik", "Press", "Throw"]: condition = "press" else : condition = "no_press" event.clearEvents() for frame in range(90): text = visual.TextStim(win, text=word, height = 0.05) text.draw() # draw the text stimulus in a "hidden screen" so that it is ready to be presented time_start=win.flip() try: key, time_key=event.getKeys(keyList=['space', 'escape'], timeStamped = True)[0] # wait for any key press except IndexError: key = "0" rt = "NA" else: if key=='escape': core.quit() rt = time_key - time_start if key == "space" and condition=="press": accuracy = 1 elif key == "0" and condition=="no_press": accuracy = 1 else: accuracy = 0 with open(out_file,"a") as f: f.write("{},{},{},{},{},{},{},{}\n".format(trial,ID,Gender,Age,word,accuracy,rt,SpaceKlik)) # s = sound.Sound('sound.wav') # s.play() # Register space bar press or mouse click # Measure reaction time # Check to see if answer is correct to sound - certain sound files are "klik". Others "kast", "løb", "sko" and so on # Write csv logfile with coloumns: "ID", "Gender", "Word", "Correct/incorrect", "Reaction time", "Space/click" ``` I will all run in PsychoPy in the end. Thank you in advance for your kind assistance.
2016/12/06
[ "https://Stackoverflow.com/questions/40986385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7254731/" ]
It may seem entirely logical to you, but the compiler has no idea what *order* your conceptual definition of "priority" means regarding your thing called a `Coord`. Your objects being stored in your queue look like this: ``` std::pair<int, Coord> ``` and understanding how `std::priority_queue` compares elements is warranted. The adapter [`std::priority_queue`](http://en.cppreference.com/w/cpp/container/priority_queue) defaults to using [`std::less`](http://en.cppreference.com/w/cpp/utility/functional/less) for the item comparator to determine order. As you have now-discovered, that comparator does little more than manufacture a simple *`a < b`* construct to compare objects for order, and if the object class (or its bases) provide this, great; if not, you need to do so. as it turns out, [`std::pair` *does* provide an `operator <`](http://en.cppreference.com/w/cpp/utility/pair/operator_cmp), which basically establishes strict weak ordering across `first` and `second`. For two pair objects it essentially does this: ``` return lhs.first < rhs.first || (!(rhs.first < lhs.first) && lhs.second < rhs.second); ``` Why is *that* important? Note that `second` usage in the last expression. It's important because the `second` in the above is of *your* type `Coord`, Therefore, `operator <` is being applied to `Coord` and since there is no such operator, compiler = not-happy. As a side-note, you've noticed this *works* out of the box for `std::pair<int, std::pair<int,int>>` because as mentioned earlier, `std::pair` has an operator <`overload, and in that case two different instantiations of`operator <` are manifested. To solve this, you have to provide such an `operator` for your type. There are essentially only two ways to do this: a member function or a free-function either of which define a `operator <` overload for `Coord`. Usually implemented as a member function, but also possible as a free-function, this essentially provides the operator `std::less` is looking for. This is the most common mechanism for providing order (and imho the easiest to understand): ``` // member function struct Coord { int x, y; bool operator <(const Coord& rhs) { return x < rhs.x || (!(rhs.x < x) && y < rhs.y) } }; ``` or ``` // free function bool operator <(const Coord& lhs, const Coord& rhs) { return lhs.x < rhs.x || (!(rhs.x < lhs.x) && lhs.y < rhs.y) } ``` --- **General Comparator Guidelines** Beyond making `std::less<>` happy for a given type by overloading `operator <`, many containers, adapters, and algorithms allow you to provide your own custom comparator type. For example: * `std::map` * `std::set` * `std::sort` * `std::priority_queue` * many others... To that, there are several possible ways to do this. Examples include: * Provide an `operator <` for instances of your `Type` type (easy, example shown prior). This allows the continued default `std::less` to do it's job of firing `operator <` that is provided by you. * Provide a comparator to the container/algorithm that performs the comparison for you (also easy). In essence you're writing a replacement for `std::less` that *you* specify for the container, adapater, or algorithm when declaring or invoking them. * Provide a template specialization of `std::less<Coord>` (moderately easy, but rarely done and less intuitive for beginners). This *replaces* `std::less` with your specialization wherever it would normally be used. Examples of the last two appear below. We'll assume we're just using your `Coord` rather than your `std::pair<int, Coord>`, explained earlier **Provide custom comparator** You don't have to use `std::less` for ordering. You can also provide your own functor that does the same job. The third template parameter to `std::priority_queue` is what you use to provide this: ``` struct CoordLess { bool operator()(Coord const& lhs, Coord const& rhs) const { return lhs.x < rhs.x || (!(rhs.x < lhs.x) && lhs.y < rhs.y) } }; std::priority_queue<Coord, std::vector<Coord>, CoordLess> myqueue; ``` This is handy when you need to implement different orderings on the same object class for different containers. For example, you could have one container that orders small-to-large, another large-to-small. Different comparators allow you to do that. For example, you could create a `std::set` of `Coord` objects with your comparator by doing ``` std::set<Coord, CoordLess> myset; ``` or sort a vector `vec` of `Coord` objects by doing this: ``` std::sort(vec.begin(), vec.end(), CoordLess()); ``` Note in both cases we specify at declaration or invocation the custom comparator. **Provide a `std::less` specialization** This is not as easy to understand, rarely done, but just as easy to implement. Since `std::less` is the default comparator, so long as the type is a custom type (not a native language type or library type) you can provide a `std::less` specialization for `Coord`. This means *everything* that normally uses `std::less<Coord>` for ordering will get this implicitly if the definition below is provided beforehand. ``` namespace std { template<> struct less<Coord> { bool operator ()(Coord const& lhs, Coord const& rhs) const { return lhs.x < rhs.x || (!(rhs.x < lhs.x) && lhs.y < rhs.y) } }; } ``` With that provided (usually immediately after your custom type in the same header), you can simply use default template parameters, whereas before we had to specify them. For example now we can declare a `std::set` like this: ``` std::set<Coord> myset; ``` or perform a sort like this: ``` std::sort(vec.begin(), vec.end()); ``` Both of those default to using `std::less<Coord>` and since we've specialized that ourselves, it uses *ours*. This is a handy, enveloping way of changing default behavior in *many* places, but with great power comes great responsibility, so be careful, and *never* do this with native or library-provided types. Hopefully that give you some ideas on different ways you can solve your error.
589,657
I want to divide the row into the columns, starting a new row each time the `New Data` phrase is found in the file: Input ``` New Data 52.6114082616 41.8319773432 75.6986111112 74.6176129172 New Data 100.0 100.0 100.0 8.00000000003 99.7916666667 42.435664564566 ``` Output ``` 52.6114082616 41.8319773432 75.6986111112 74.6176129172 100.0 100.0 100.0 8.00000000003 99.7916666667 42.435664564566 ``` I have tried with `xargs`: ``` awk '{print$1}' file.txt | xargs -n2 echo ``` but this will not include blank lines, and I want the blank lines as well.
2020/05/29
[ "https://unix.stackexchange.com/questions/589657", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/415180/" ]
Use `awk` to provide alternate separator: ``` awk '/^New Data/ {sep=ORS; next} {printf "%s", sep $0; sep=OFS} END{print ""}' file ``` If the record matches regular expression `^New Data`, `sep` will be changed to `ORS`/newline, otherwise `sep` will be `OFS`/space.
91,611
Has anyone a good source of **free** information for VFR approach charts in Italy? I know that for major airports (e.g. LIMW), <https://www.enav.it> publishes the charts. However for small airfields (e.g. LIVV), I was not able to find anything. I am looking for something like [this](https://www.sia.aviation-civile.gouv.fr/documents/htmlshow?f=dvd/eAIP_27_JAN_2022/Atlas-VAC/home.htm), from France.
2022/02/03
[ "https://aviation.stackexchange.com/questions/91611", "https://aviation.stackexchange.com", "https://aviation.stackexchange.com/users/31167/" ]
You are right, in Italy, VFR approach charts are published by [ENAV](https://www.enav.it/) for major airports only (you could get them georeferenced for free using [Airmate](https://www.airmate.aero) app). For small airfields and ultralight bases, the main source is [Avioportolano](https://www.avioportolano.it/en/) but it is a commercial source. There is no free information source to the best of my knowledge. In France, the source you quote [SIA Service de l'Information Aéronautique](https://www.sia.aviation-civile.gouv.fr/) is indeed the right one for all airfields having an ICAO code assigned. In addition, you have more than 700 ultralight airfields having numeric codes assigned by the ULM Federation (such LF8357 for Pampelonne). You could find for them free information and charts on [FFPULM BASULM site](https://basulm.ffplum.fr/).
44,505,554
Using the command: ``` describe formatted my_table partition my_partition ``` we are able to list the metadata including hdfs location of the partition `my_partition` in `my_table`. But how can we get an output with 2 columns: ``` Partition | Location ``` which would list all the partitions in `my_table` and their hdfs locations?
2017/06/12
[ "https://Stackoverflow.com/questions/44505554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/147530/" ]
Query the metastore. ### Demo **Hive** ``` create table mytable (i int) partitioned by (dt date,type varchar(10)) ; alter table mytable add partition (dt=date '2017-06-10',type='A') partition (dt=date '2017-06-11',type='A') partition (dt=date '2017-06-12',type='A') partition (dt=date '2017-06-10',type='B') partition (dt=date '2017-06-11',type='B') partition (dt=date '2017-06-12',type='B') ; ``` **Metastore** (MySQL) ``` select p.part_name ,s.location from metastore.DBS as d join metastore.TBLS as t on t.db_id = d.db_id join metastore.PARTITIONS as p on p.tbl_id = t.tbl_id join metastore.SDS as s on s.sd_id = p.sd_id where d.name = 'default' and t.tbl_name = 'mytable' ; ``` --- ``` +----------------------+----------------------------------------------------------------------------------+ | part_name | location | +----------------------+----------------------------------------------------------------------------------+ | dt=2017-06-10/type=A | hdfs://quickstart.cloudera:8020/user/hive/warehouse/mytable/dt=2017-06-10/type=A | | dt=2017-06-11/type=A | hdfs://quickstart.cloudera:8020/user/hive/warehouse/mytable/dt=2017-06-11/type=A | | dt=2017-06-12/type=A | hdfs://quickstart.cloudera:8020/user/hive/warehouse/mytable/dt=2017-06-12/type=A | | dt=2017-06-10/type=B | hdfs://quickstart.cloudera:8020/user/hive/warehouse/mytable/dt=2017-06-10/type=B | | dt=2017-06-11/type=B | hdfs://quickstart.cloudera:8020/user/hive/warehouse/mytable/dt=2017-06-11/type=B | | dt=2017-06-12/type=B | hdfs://quickstart.cloudera:8020/user/hive/warehouse/mytable/dt=2017-06-12/type=B | +----------------------+----------------------------------------------------------------------------------+ ```
42,189,354
ive successfully created a helper and function that display data from a json file in a styled list using handlebars.But im struggling with the view more section of my code.Basically what im trying to achieve is,if user clicks on a list item,handlebars should get the id of that item and display it on a different page.My console correctly displays the correct id for each item clicked on the new page(viewdetail page)but the page only displays the styling but with no content from my json.This is my handlebars code: ``` function getParameterByName(name,url){ 'use strict'; if(!url)url = window.location.href; name = name.replace(/[\[\]]/g, "\\$&"); var regex = new RegExp("[?&]"+name+"(=([^&#]*)|&|#|$)"), results = regex.exec(url); if(!results)return null; if(!results[2])return ''; return decodeURIComponent(results[2].replace(/\+/g,"")); } var ourRequest = new XMLHttpRequest(); ourRequest.open('GET', 'jj.json'); ourRequest.onload = function () { if (ourRequest.status >= 200 && ourRequest.status < 400) { var data = JSON.parse(ourRequest.responseText); createHTML(data); } else { console.log("You are connected to the server, but it returned an error."); } }; ourRequest.onerror = function() { console.log("Connection error"); }; ourRequest.send(); function createHTML(myData) { var rawTemplate = document.getElementById("myTemplate").innerHTML; var compiledTemplate = Handlebars.compile(rawTemplate); var myContainer = document.getElementById("this-container"); var ourGeneratedHTML = compiledTemplate(myData); myContainer.innerHTML = ourGeneratedHTML; var characterId = getParameterByName("id"); console.log(characterId); $.ajax("jj.json").done(function(cast){ if ($("body").hasClass("viewdetail")){ ///i cant seem to figure out how to render it here var ourGeneratedHTML = compiledTemplate(myData); myContainer.innerHTML = ourGeneratedHTML; } else var ourGeneratedHTML = compiledTemplate(myData); myContainer.innerHTML = ourGeneratedHTML; { } }); } ``` And my html is as folows:(The viewdetails page) ``` <body class="viewdetail" <div class="page-wrap"> <div id="this-container"></div> </div> <script id="myTemplate" type="text/x-handlebars-template"> <span class="username"><a href="#">{{cname}}</a></span> </script> ``` Ive tried using {{#each}} and {{#each myjsonobject}} but i keep getting the correct id on the detail page,but no data in the styling. What am i doing wrong here,please help :( my detail page is being hrefed from my index page as follows: ``` <a href="detailpage.php?id={{id}}" class="btn btn-primary btn-xs view-detail"><b>View</b></a> ``` And heres a portion of my json data: ``` {"content":[{"id":"60","cname":"Admin","crep":"wew","sub_type":"memember ","token":"887618243","reference":"#5754","company_email":"rereee@gmail.com","company_phone":"234556566","service1":"erty","service2":"vbnmj","service3":"yjyt","service4":"uikjyj","company_website":"www.memeber.com","company_address":null,"company_location":"namibia","company_shortbio":"sasasa","company_longbio":"bvbvbvbvb","logos":"891319.png","logopath":"","imageA":"309129.png","imageB":"898798.jpg","imageC":"452926.jpg","imageD":"326704.jpg","company_facebook":null,"company_twitter":null,"company_linkedin":null,"company_stumbleupon":null,"company_pinterest":null,"company_googleplus":null,"user_backgroundpicture":null,"created_on":"2017-01-20 15:37:02","company_skype":null,"company_youtube":null,"company_vimeo":null,"headerimg":"993621.png","join_date":"2017-01-20 15:37:02.069147":""} ```
2017/02/12
[ "https://Stackoverflow.com/questions/42189354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7441151/" ]
* I learned that all puppetized hosts within a zone were recently configured for an http apt cache proxy. Once the apt cache proxy was removed from the host and the install began to work properly. * The sbt.list was restored to use the https prefix.
2,854,547
Say my code is as follows: ``` <ul> <li><img /></li> <li> <ul> <li><img /></li> </ul> </li> </ul> ``` I'm trying to set a default size for the first `img` tag, but not affect the second one. everything I do affects the other one as well. Currently I have tried: ``` $('ul#gallery > li').find('img').css('width','650px'); $('ul#gallery > li img').css('width','650px'); ``` among others, but nothing works.
2010/05/18
[ "https://Stackoverflow.com/questions/2854547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/323712/" ]
I do not know such list of words, but can suggest to use a copy of Wikipedia and wiki classification. You can parse the XML version of Wikipedia (i have done that) and collect words from different topics.
23,348,435
I want to configure SVN such that it talks to an external service for authorization. The external service will have its logic to decide the type of access a user has to a path. When a user accesses SVN it should authenticate and then contact the authorization service for the access details - read / write / delete etc. Is this possible and how to configure SVN to implement this. Assume that authorization service is already available.
2014/04/28
[ "https://Stackoverflow.com/questions/23348435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2288034/" ]
> > Each class in the .jar has [package MapRedDesign;] at the top. > > > Based on your comments, make sure you fully qualify your class name with the package, otherwise Java will have no idea where to find it. ``` hadoop jar cloudera/MinMaxCountDriver.jar MapRedDesign.MinMaxCount /user/cloudera/Comments.xml /user/cloudera/SuperUserXML/ ```
9,791,192
Recently I was looking at some source code provided by community leaders in their open source implementations. One these projects made use of IOC. Here is sample hypothetical code: ``` public class Class1 { private ISomeInterface _someObject; public Class1(ISomeInterface someObject) { _someObject = someObject; } // some more code and then var someOtherObject = new SomeOtherObject(); } ``` My question is not about what the IOCs are for and how to use them in technical terms but rather what are the guidelines regarding object creation. All that effort and then this line using "new" operator. I don't quite understand. Which object should be created by IOC and for which ones it is permissible to be created via the new operator?
2012/03/20
[ "https://Stackoverflow.com/questions/9791192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/981375/" ]
As a general rule of thumb, if something is providing a *service* which may want to be replaced either for testing or to use a different implementation (e.g. different authentication services) then inject the dependency. If it's something like a collection, or a simple data object which isn't providing behaviour which you'd ever want to vary, then it's fine to instantiate it within the class.
71,737,908
I am trying to characterise my class with init but the website says I have to add the last two lines of code but I don't know what they do? Could someone explain? Code: ``` class Person: def __init__(self, name, age): self.name = name self.age = age def myfunc(self): print("My awesome name is " + self.name) p1 = Person("bob", 69) p1.myfunc() ```
2022/04/04
[ "https://Stackoverflow.com/questions/71737908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18702372/" ]
It is pretty simple. Let's say you create a string. ``` a = "Hello" ``` This basically creates a new string `object` called `a`. Now you can use a variety of functions like `.isdigit()`, `.isalnum()` etc. These functions are basically the functions of the String `class` and when called, they perform the function in relation to the object they are associated with. So Saying, ``` print(a.isalnum()) ``` Would give `True` as the function is defined to check of the `String object` is alphanumeric. In the same way, ``` p1 = Person("bob", 69) p1.myfunc() ``` First-line creates a new `Person` object with `name='bob'` and `age=69`. The second line then calls the function `myfunc()` in association with the Person `p1` and executes with the attributes of `p1` as its own local variables.
28,510,878
On Android, when the selector is touched, the keyboard input appears. I suspect this is because the generated input is of type="text". **How can I prevent this from happening? If the user is choosing from a drop-down list, it does not make sense for the keyboard to appear.** I'm implementing selectize as an Angular module [angular-selectize](https://github.com/machineboy2045/angular-selectize), but I checked with the developer and the issue is not specific to the angular wrapper. Here is my code: ``` <selectize ng-model="filters.min_bedrooms" options="[ {title:'0', id:0}, {title:'1', id:1}, {title:'2', id:2}, ]"> </selectize> ``` Which generates this markup: ``` <input type="text" autocomplete="off" tabindex="" style="width: 4px; opacity: 0; position: absolute; left: -10000px;"> ```
2015/02/14
[ "https://Stackoverflow.com/questions/28510878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1141918/" ]
I had the same issue, where I want the user to select a value but not enter any new values, and the keyboard always shows up when you tap on the dropdown on an iPad. I've solved it by this: ``` $('#myDropDownId').selectize({ create: true, sortField: 'date' }); $(".selectize-input input").attr('readonly','readonly'); ``` Basically what happens is, the input gets focus when you click/tap on the dropdown, and that is what shows the keyboard. By setting readonly to false, the input no longer gets focus. I've tested this on an iPad Mini 2 in Safari and Chrome.
1,163,030
I can't narrow down this bug, *however* I seem to have the following problem: * `saveState()` of a `horizontalHeader()` * restart app * modify model so that it has one less column * `restoreState()` * Now, for some reason, the state of the headerview is totally messed up. I cannot show or hide any new columns, nor can I ever get a reasonable state back I know, this is not very descriptive but I'm hoping others have had this problem before.
2009/07/22
[ "https://Stackoverflow.com/questions/1163030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122933/" ]
For QMainWindow, the [`save/restoreState`](http://doc.trolltech.com/4.5/qmainwindow.html#restoreState) takes a version number. [QTableView's restoreState()](http://doc.qt.digia.com/qt/qheaderview.html#restoreState) does not, so you need to manage this case yourself. If you want to restore state even if the model doesn't match, you have these options: * Store the state together with a list of the columns that existed in the model upon save, so you can avoid restoring from the data if the columns don't match, and revert to defualt case * Implement your own save/restoreState functions that handle that case (ugh) * Add a proxy model that has provides bogus/dummy columns for state that is being restored, then remove those columns just afterwards.
13,249,356
I have the application (solution in VS2010) with +-10 projects. Some of these projects are quite large (dozens of folders and hundreds of files). When I make a change in project on lower level and I want to run my tests (+-10 seconds) then I have to wait 2 minutes for projects build. This is very inefficient. Is there any way to speed-up build? For example, split current projects into multiple projects or something else? Or are there some general advice and recommendations to speed-up building projects in Visual Studio?
2012/11/06
[ "https://Stackoverflow.com/questions/13249356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1304812/" ]
In my experience solutions with large number of projects build slowly on vs2010 and there is not much you can do about it: 1. Reduce number of projects - larger single project will build faster then many smaller. 2. Prepare set of build configurations Build->ConfigruationManager to build only parts of your project since you don't have to build projects that depend on changed project if public interface is not changed. This can be tricky to use and some unexpected errors might occur in runtime. Also make sure that all your projects point to single `Bin\Debug Bin\Release` folder so that new dlls are loaded on application start. This is requited because if you don't build project its dependencies wont be copied to its output directory. 3. Upgrade to vs 2012. This is the best option you can choose.
2,621,584
My goal is to prenex-normalize the following sentence: $(\exists{z} : S(z)) \wedge \exists{x} :\forall{y} : [\forall{z}: S(z) \Rightarrow P(y,z)] \Rightarrow R(x,y)$ I tried many times but none of the things that I try seem to work. I can't wrap my mind around the part between the []-brackets. This is an exercise in a course that I take and we have a tool to check the correctness of a solution, most other exercises were no problem for me but I really struggle with this one.
2018/01/26
[ "https://math.stackexchange.com/questions/2621584", "https://math.stackexchange.com", "https://math.stackexchange.com/users/401361/" ]
To make the formulas a little more compact, I'm going to use the notation $\binom pq$ rather than $^pC\_q$ for number of combinations. Notice that $^4C\_1 \times {^{13}C\_5} = \binom41\binom{13}{5}$ is a constant, whereas $^{52}C\_n = \binom{52}{n}$ increases as $n$ increases, so $$ \frac{\binom41\binom{13}{5}}{\binom{52}{n}} $$ gets progressively *smaller* as $n$ gets larger, opposite from what you know the correct answer must do. Therefore this cannot be the answer. The formula above is correct in the case $n=5$ only. It is true that the probability of drawing at least one $5$-card flush in $n$ cards can be expressed as a fraction with denominator $\binom{52}{n},$ but in general the numerator is larger than $\binom41\binom{13}{5}.$ Let $K(n)$ be the number of $n$-card hands with at least one $5$-card flush, so that the desired probability is $$ \frac{K(n)}{\binom{52}{n}}, $$ and let's see how we can compute $K(n)$ for a few different values of $n.$ For $n=6,$ we have to consider the $\binom{13}{6}$ different sets of $6$ cards that might be drawn from one suit times the $4$ different suits from which they might be drawn; but we also have to consider the $\binom{13}{5}$ different sets of $5$ cards that might be drawn from one suit times the $\binom{13}{1}$ ways to draw the sixth card from another suite times the $4\times3$ different permutations of suits from which they might be drawn. So $$ K(6) = 4 \binom{13}{6} + 12 \binom{13}{5} \binom{13}{1} = 207636. $$ For $n=7$ the possibilities are not just $7$ of one suit or $6$ of one suit and $1$ of another; it could be $5$ of one suit and $2$ of another, or $5$ of one suit and $1$ each of two others. In that last case, the only choices of suits are $4$ choices for the long suit and which of the other $3$ suits does *not* occur; it doesn't matter which of the two singleton suits we write first. So $$ K(7) = 4 \binom{13}{7} + 12 \binom{13}{6} \binom{13}{1} + 12 \binom{13}{5} \binom{13}{2} + 12 \binom{13}{5} \binom{13}{1}^2 = 4089228 $$ It's hard to imagine how we're going to write a simple formula for $K(n)$ using the usual combinatoric functions, since for the next few $n,$ each time we add a card we increase the number of different possible counts of cards by suit; for example, for $n=8$ the number of cards in each suit can be $8$ (all one suit), $7 + 1,$ $6+2,$ $6+1+1,$ $5+3,$ $5+2+1,$ or $5+1+1.$ The formula would not even fit on one line of this answer format. For $n$ close to $17,$ the formulas are simpler if we count the number of non-flushes, that is, $\binom{52}{n} - K(n).$ For example, for $n=16,$ the only non-flushes obtained by drawing $4$ cards from each suit, $$ \binom{52}{16} - K(16) = \binom{13}{4}^4 = 261351000625. $$ For $n=15,$ we can only have $4$ cards from three of the suits and $3$ from the other, with $4$ different choices of the $3$-card suit, so $$ \binom{52}{15} - K(15) = 4 \binom{13}{4}^3 \binom{13}{3} = 418161601000. $$ For $n=14,$ the possible numbers of cards of each suit are $4+4+4+2$ or $4+4+3+3$, so $$ \binom{52}{14} - K(14) = 4 \binom{13}{4}^3 \binom{13}{2} + \binom62 \binom{13}{4}^2 \binom{13}{3}^2 = 364941033600. $$ Observing that $\binom{52}{6} - K(6) = 20150884$ and $\binom{52}{7} - K(7) = 129695332,$ we can see that the result of the computer calculation [offered in another answer](https://math.stackexchange.com/a/2622642) is correct for $n \in \{4,5,6,7,14,15, 16, 17\}.$
160,057
I want to know where the source is to look all tables available to query. For example, a few months back I came to know we can query `ApexClass`, `TestCoverage`, etc. ``` SELECT Id, CreatedBy.Name FROM ApexClass SELECT Id, RecordType.Name FROM RecordType ``` Is there a way I can know how many tables are available to query through SOQL?
2017/02/13
[ "https://salesforce.stackexchange.com/questions/160057", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/29281/" ]
The SOAP API has a list of [Standard Objects](https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_list.htm), hyperlinked to each object with a list of standard fields and a brief description of those fields, plus any "special rules" that may apply to portal users, queries, etc. In the event that this link somehow breaks, you can just search the Internet for "standard salesforce objects" and you should find it as one of the top organic (non-ad) search results.
764,616
I am 99.9% sure that my system on my personal computer has been infiltrated. Allow me to first give my reasoning so the situation will be clear: Rough timeline of suspicious activity and subsequent actions taken: 4-26 23:00 I ended all programs and closed my laptop. 4-27 12:00 I opened my laptop after it had been in suspend mode for about 13 hours. Multiple windows were open including: Two chrome windows, system settings, software center. On my desktop there was a git installer (I checked, it has not been installed). 4-27 13:00 Chrome history displayed logins to my email, and other search history that I did not initiate (between 01:00 and 03:00 on 4-27), including "installing git". There was a tab, Digital Ocean "How to customize your bash prompt" open in my browser. It reopened several times after I closed it. I tightened security in Chrome. I disconnected from WiFi, but when I reconnected there was an up-down arrow symbol instead of the standard symbol, and there was no longer a list of networks in the drop down menu for Wifi Under 'Edit Connections' I noticed my laptop had connected to a network called "GFiberSetup 1802" at ~05:30 on 4-27. My neighbors at 1802 xx Drive just had google fiber installed, so I'm guessing it's related. 4-27 20:30 The `who` command revealed that a second user named guest-g20zoo was logged into my system. This is my private laptop that runs Ubuntu, there should not be anyone else on my system. Panicking, I ran `sudo pkill -9 -u guest-g20zoo` and disabled Networking and Wifi I looked in `/var/log/auth.log` and found this: ``` Apr 27 06:55:55 Rho useradd[23872]: new group: name=guest-g20zoo, GID=999 Apr 27 06:55:55 Rho useradd[23872]: new user: name=guest-g20zoo, UID=999, GID=999, home=/tmp/guest-g20zoo, shell=/bin/bash Apr 27 06:55:55 Rho su[23881]: Successful su for guest-g20zoo by root Apr 27 06:55:55 Rho su[23881]: + ??? root:guest-g20zoo Apr 27 06:55:55 Rho su[23881]: pam_unix(su:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:55:56 Rho systemd: pam_unix(systemd-user:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:55:56 Rho systemd-logind[767]: New session c3 of user guest-g20zoo. Apr 27 06:55:56 Rho su[23881]: pam_unix(su:session): session closed for user guest-g20zoo Apr 27 06:55:56 Rho systemd-logind[767]: Removed session c3. Apr 27 06:55:56 Rho lightdm: pam_unix(lightdm-autologin:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:55:56 Rho systemd: pam_unix(systemd-user:session): session closed for user guest-g20zoo Apr 27 06:55:56 Rho systemd-logind[767]: New session c4 of user guest-g20zoo. Apr 27 06:55:56 Rho systemd: pam_unix(systemd-user:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:56:51 Rho pkexec: pam_unix(polkit-1:session): session opened for user root by (uid=1000) Apr 27 06:56:51 Rho pkexec: pam_systemd(polkit-1:session): Cannot create session: Already running in a session ``` Sorry it's a lot of output, but that's the bulk of activity from guest-g20zoo in the log, all within a couple of minutes. I also checked `/etc/passwd`: ``` guest-G4J7WQ:x:120:132:Guest,,,:/tmp/guest-G4J7WQ:/bin/bash ``` And `/etc/shadow`: ``` root:!:16669:0:99999:7::: daemon:*:16547:0:99999:7::: . . . nobody:*:16547:0:99999:7::: rhobot:$6$encrypted-passwd-cut-for-length.:16918:0:99999:7::: guest-G4J7WQ:*:16689:0:99999:7::: . . ``` I don't entirely understand what this output means for my situation. Are `guest-g20zoo` and `guest-G4J7WQ` the same user? `lastlog` shows: ``` guest-G4J7WQ Never logged in ``` However, `last` shows: ``` guest-g20zoo Wed Apr 27 06:55 - 20:33 (13:37) ``` So it seems like they are not the same user, but guest-g20zoo was nowhere to be found in the output of `lastlog`. I would like to block access for user guest-g20zoo but since (s)he doesn't appear in `/etc/shadow` and I'm assuming doesn't use a password to login, but uses ssh, will `passwd -l guest-g20zoo` work? I tried `systemctl stop sshd`, but got this error message: ``` Failed to stop sshd.service: Unit sshd.service not loaded ``` Does this mean remote login was already disabled on my system, and therefore the above command is redundant? I have tried to find more information about this new user, like what ip address they logged in from, but I can't seem to find anything. Some potentially relevant information: Currently I'm connected to my university's network, and my WiFi icon looks fine, I can see all my network options, and there aren't any weird browsers popping up on their own. Does this indicate that whoever is logging into my system is within range of my WiFi router at my home? I ran `chkrootkit` and everything *seemed* fine, but I also don't know how to interpret all the output. I don't really know what to do here. I just want to be absolutely sure this person (or anyone else for that matter) will never be able to access my system again and I want to find and remove any hidden files created by them. Please and Thank You! P.S. - I already changed my password and encrypted my important files while WiFi and Networking were disabled.
2016/04/28
[ "https://askubuntu.com/questions/764616", "https://askubuntu.com", "https://askubuntu.com/users/447541/" ]
It looks like someone opened a guest session on your laptop while you where away from your room. If I were you I'd ask around, that may be a friend. The guest accounts you see in `/etc/passwd` and `/etc/shadow` are not suspicious to me, they are created by the system when someone open a guest session. > > Apr 27 06:55:55 Rho su[23881]: Successful su for guest-g20zoo by root > > > This line means `root` has access to the guest account, which could be normal but should be investigated. I've tried on my ubuntu1404LTS and don't see this behaviour. You should try to login with a guest session and grep your `auth.log` to see if this line appear everytime a guest user logs in. All the opened windows of chrome, that you've seen when you opened your laptop. Is it possible that you were seeing the guest session desktop ?
2,234,441
I get an XML string from a certain source. I create a DOMDocument object and load the XML string into it (with DOMDocument::loadXML()). Then I navigate through the XML doc using various methods (e.g. DOMXPath), until I find the node (a DOMNode, of course) that I want. This node has a bunch of descendants, and I want to take that entire node (and its descendants) and create a new DOMDocument object from it. I'm not sure how to do this; I tried creating a new DOMDocument and using DOMDocument::importNode(), but this appears to only work if the DOMDocument already has a main document node in it, in which case it appends the imported node as a child of the main document node, which is not what I want -- I want the imported node to BECOME the DOMDocument main node. Maybe there's an easier way to do this (i.e. an easier way to extract the part of the original XML that I want to turn into its own document), but I don't know of it. I'm relatively new to DOMDocument, although I've used SimpleXMLElement enough to be annoyed by it.
2010/02/10
[ "https://Stackoverflow.com/questions/2234441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20903/" ]
You can also create a new DOMDocument and call appendChild() on it to add a root node: ``` $new = new DomDocument; $new->appendChild($new->importNode($node, true)); ``` That worked for me.
35,427,666
Which method in `vscode-languageserver::IConnection` has to be implemented to provide functionality "Go To Definition" over multiple files? I was studying `Language Server Node Example` and vscode "API documentation", but I didn't find any info.
2016/02/16
[ "https://Stackoverflow.com/questions/35427666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5902074/" ]
The following code snippet illustrates how to implement "Go To Definition" using `vscode-languageserver`: ```ts connection.onInitialize((params): InitializeResult => { ... return { capabilities: { definitionProvider: true, ... } } }); connection.onDefinition((textDocumentIdentifier: TextDocumentIdentifier): Definition => { return Location.create(textDocumentIdentifier.uri, { start: { line: 2, character: 5 }, end: { line: 2, character: 6 } }); }); ```
3,991,377
I have a Master and Detail table, the Detail linking to the Master record on a FK reference. I need to display all the data from the Master table, and the corresponding number of details for each record, i.e. ``` MASTER TABLE ID Name Age 1 John 15 2 Jane 14 3 Joe 15 DETAIL MasterID Subjects 1 Trigonometry 1 Chemistry 1 Physics 1 History 2 Trigonometry 2 Physics ``` Thus, when I ran the SQL statement, I would have the following result: ``` ID Name Age #Subjects 1 John 15 4 2 Jane 14 2 3 Joe 15 0 ``` Thanks!
2010/10/21
[ "https://Stackoverflow.com/questions/3991377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/71406/" ]
This may be useful ``` SELECT mt.ID, mt.NAME, mt.AGE, COUNT(d.MasterID) as [#Subjects] FROM MasterTable mt LEFT OUTER JOIN Detail d on mt.ID = d.ID GROUP BY mt.ID, mt.NAME, mt.AGE ORDER BY mt.ID ```
60,843,085
The columns in my dataframe has long names, so when I make a pairplot, the labels overlaps one another. I would like to rotate my labels 90 degrees, so they don't collide. I tried looking up online and documentation, but could not find a solution. Here is something I wrote & the error message: ``` plt.figure(figsize=(10,10)) g = sn.pairplot(df, kind="scatter") g.set_xticklabels(g.get_xticklabels(), rotation=90) g.set_yticklabels(g.get_yticklabels(), rotation=90) ``` ```none AttributeError: 'PairGrid' object has no attribute 'set_xticklabels' ``` **How can I rotate labels (both x and y) in a Seaborn PairGrid?** *Note: Sorry, my wifi can't upload the image for reference.*
2020/03/25
[ "https://Stackoverflow.com/questions/60843085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8742400/" ]
Thanks to William's answer, I now know what to look for to solve my problem! Below is how I did it. ``` g = sn.pairplot(dfsub.sample(50), kind="scatter", hue=target) for ax in g.axes.flatten(): # rotate x axis labels ax.set_xlabel(ax.get_xlabel(), rotation = 90) # rotate y axis labels ax.set_ylabel(ax.get_ylabel(), rotation = 0) # set y labels alignment ax.yaxis.get_label().set_horizontalalignment('right') ```
766,378
In my debian all files, even the system ones have permissions rw-r--r--, so it means that all users can view ANY file even some system configuration or database files and so on. How do I prevent users from reading all system files ? Is there any way how to set global permissions so users cannot read all the files ?
2016/03/27
[ "https://serverfault.com/questions/766378", "https://serverfault.com", "https://serverfault.com/users/314359/" ]
I don't think that denying access to all system files for all users is a good idea. Some of those files are necessary to work in a system. But there are several ways to restrict specific users. For example, if you wanted to deny user `joe` access to anything in `/etc`, you could use `ACLs` (manipulated with setfacl/getfacl commands), like this: `setfacl -Rm u:joe:--- /etc` Other ideas would be to use selinux policy, or keep users in chroot. I think `chmod 700` on system directories is a bad idea, because it will deny access to various system users like `nobody`, `ftp` or `mail`, which are used by some system services.
7,019
I have a data set with a range of 0 to 65,000. The vast majority of data points (it is a huge sample) are concentrated between 0 and 1000. There is only one point that has 65,000. I want to plot this using a semi-logarithmic plot. However, I would like the graph to have around 50 points. If I use scales like 2,4,6,8,16,32,64,128,256 etc I have only a couple of points. But If I use a multiple of 1.1 or 1.5 etc, the scales are not integers. Is there a standard way to ensure you more concentrated intervals at a lower level on the scale? Cheers, s
2011/02/09
[ "https://stats.stackexchange.com/questions/7019", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/2405/" ]
Can you just use a scale comprised of powers of (1+r) for some small r, and round to the nearest integer? For example, in R, with r = 0.25: ``` > x <- unique(round(1.25^(0:50))) > x [1] 1 2 3 4 5 6 7 9 12 15 18 23 28 36 44 56 69 87 108 136 169 212 265 331 414 [26] 517 646 808 1010 1262 1578 1972 2465 3081 3852 4815 6019 7523 9404 11755 14694 18367 22959 28699 35873 44842 56052 70065 ```
5,134,523
Consider this code: ``` #define F(x, ...) X = x and VA_ARGS = __VA_ARGS__ #define G(...) F(__VA_ARGS__) F(1, 2, 3) G(1, 2, 3) ``` The expected output is `X = 1 and VA_ARGS = 2, 3` for both macros, and that's what I'm getting with GCC, however, MSVC expands this as: ``` X = 1 and VA_ARGS = 2, 3 X = 1, 2, 3 and VA_ARGS = ``` That is, `__VA_ARGS__` is expanded as a single argument, instead of being broken down to multiple ones. Any way around this?
2011/02/27
[ "https://Stackoverflow.com/questions/5134523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/366240/" ]
Edit: This issue might be resolved by using `/Zc:preprocessor` or `/experimental:preprocessor` option in recent MSVC. For the details, please see [here](https://learn.microsoft.com/en-us/cpp/preprocessor/preprocessor-experimental-overview?view=msvc-160). MSVC's preprocessor seems to behave quite differently from the standard specification. Probably the following workaround will help: ``` #define EXPAND( x ) x #define F(x, ...) X = x and VA_ARGS = __VA_ARGS__ #define G(...) EXPAND( F(__VA_ARGS__) ) ```
10,177,524
This is a simple problem but i've been pulling my hair out the past two hours trying to figure a way to get it to work. Basically I have a jquery navigation set-up. I have 4 tabs, each tab is a parent category with child categories. When a tab is clicked, a drop down with the children appears. I have it all set-up but can't figure a way to add a class of "active" to the child categories based on whatever category is selected. Unless i've blanked and this is sitting right in front of my eyes, I can't find an obvious way of doing this. I think the problem is, I haven't hard coded the navigation links as the client want's to manage these themselves, so i've dynamically displayed the categories, adding an 'if' statement to this is adding the if statement to all of the categories so the class is being added to all of the child tabs. Here is my code: ``` <div id="tabbed-cats"> {exp:channel:entries channel="product"} <ul class="tabs"> <li class="nav-one"><a href="#bathroom" {categories}{if category_id == "1"}class="current"{/if}{/categories}>Bathroom</a></li> <li class="nav-two"><a href="#homecare" {categories}{if category_id == "2"}class="current"{/if}{/categories}>Homecare</a></li> <li class="nav-three"><a href="#transfer-equipment" {categories}{if category_id == "3"}class="current"{/if}{/categories}>Transfer Equipment</a></li> <li class="nav-four last"><a href="#mobility" {categories}{if category_id == "4"}class="current"{/if}{/categories}>Mobility</a></li> </ul> {/exp:channel:entries} <div class="list-wrap"> {exp:channel:entries channel="product"} <ul id="bathroom" {categories}{if category_id == "2" OR category_id == "3" OR category_id == "4"}class="hide"{/if}{/categories}> {exp:child_categories channel="product" parent="1" category_group="1" show_empty="yes"} {child_category_start} <li><a {categories}{if category_id == "5"}class="active"{/if}{/categories} href="{path='products/category/{child_category_url_title}'}">{child_category_name}</a></li> {child_category_end} {/exp:child_categories} </ul> {/exp:channel:entries} {exp:channel:entries channel="product"} <ul id="homecare" {categories}{if category_id == "1" OR category_id == "3" OR category_id == "4"}class="hide"{/if}{/categories}> {exp:child_categories channel="product" parent="2" category_group="1" show_empty="yes"} {child_category_start} <li><a {categories}{if category_id == "6"}class="active"{/if}{/categories} href="{path='products/category/{child_category_url_title}'}">{child_category_name}</a></li> {child_category_end} {/exp:child_categories} </ul> {/exp:channel:entries} {exp:channel:entries channel="product"} <ul id="transfer-equipment" {categories}{if category_id == "1" OR category_id == "2" OR category_id == "4"}class="hide"{/if}{/categories}> {exp:child_categories channel="product" parent="3" category_group="1" show_empty="yes"} {child_category_start} <li><a {categories}{if category_id == "8"}class="active"{/if}{/categories} href="{path='products/category/{child_category_url_title}'}">{child_category_name}</a></li> {child_category_end} {/exp:child_categories} </ul> {/exp:channel:entries} {exp:channel:entries channel="product"} <ul id="mobility" {categories}{if category_id == "1" OR category_id == "2" OR category_id == "3"}class="hide"{/if}{/categories}> {exp:child_categories channel="product" parent="4" category_group="1" show_empty="yes"} {child_category_start} <li><a {categories}{if category_id == "7"}class="active"{/if}{/categories} href="{path='products/category/{child_category_url_title}'}">{child_category_name}</a></li> {child_category_end} {/exp:child_categories} </ul> {/exp:channel:entries} </div><!-- END LIST WRAP --> <br style="clear:both;" /> ```
2012/04/16
[ "https://Stackoverflow.com/questions/10177524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/988005/" ]
In EE 2.4 you can now use `{if active}class="foobar"{/if}` try that and see.
32,263,334
My problem - process try change entity that already changed and have newest version id. When i do flush() in my code in UnitOfWork's commit() rising OptimisticLockException and catching in same place by catch-all block. And in this catch doctrine closing EntityManager. If i want skip this entity and continue with another from ArrayCollection, i should not use flush()? Try recreate EntityManager: ``` }catch (OptimisticLockException $e){ $this->em = $this->container->get('doctrine')->getManager(); echo "\n||OptimisticLockException."; continue; } ``` And still get ``` [Doctrine\ORM\ORMException] The EntityManager is closed. ``` Strange. If i do ``` $this->em->lock($entity, LockMode::OPTIMISTIC, $entity->getVersion()); ``` and then do flush() i get OptimisticLockException and closed entity manager. if i do ``` $this->getContainer()->get('doctrine')->resetManager(); $em = $doctrine->getManager(); ``` Old data unregistered with this entity manager and i even can't write logs in database, i get error: ``` [Symfony\Component\Debug\Exception\ContextErrorException] Notice: Undefined index: 00000000514cef3c000000002ff4781e ```
2015/08/28
[ "https://Stackoverflow.com/questions/32263334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2103893/" ]
You should check entity version before you try to flush it to avoid exception. In other words you should not call flush() method if the lock fails. You can use `EntityManager#lock()` method for checking whether you can flush entity or not. ```php /** @var EntityManager $em */ $entity = $em->getRepository('Post')->find($_REQUEST['id']); // Get expected version (easiest way is to have the version number as a hidden form field) $expectedVersion = $_REQUEST['version']; // Update your entity $entity->setText($_REQUEST['text']); try { //assert you edit right version $em->lock($entity, LockMode::OPTIMISTIC, $expectedVersion); //if $em->lock() fails flush() is not called and EntityManager is not closed $em->flush(); } catch (OptimisticLockException $e) { echo "Sorry, but someone else has already changed this entity. Please apply the changes again!"; } ``` Check the example in Doctrine docs [optimistic locking](http://doctrine-orm.readthedocs.org/en/latest/reference/transactions-and-concurrency.html#optimistic-locking)
5,547,844
Please try to help me.. How to open and write commands in Command Prompt using asp.net3.5,C#.net... if i click a Button in my UI it should open the commaond Prompt and i want excute few commands there... Thank you..
2011/04/05
[ "https://Stackoverflow.com/questions/5547844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/692294/" ]
Try to use this code you need to add the namespace ``` using System.Diagnostics; var processStartInfo = new ProcessStartInfo { Arguments = "ping google.com", FileName = "cmd" }; Process process = Process.Start(processStartInfo); ```
30,548,655
I am writing a c++ function to calculate the size of an C-type array in C++ I noticed a very strange behavior when using these two different codes: **code 1:** ``` int sz = sizeof array / sizeof *array; ``` **code 2:** ``` int array_size(const int *pointer) { int count=0; if(pointer) while(*pointer) { count++; pointer++; } return count; } ``` When I applied these two method on a array, it gave me very strange behavior: **example 1 :** ``` int array[10] = {31,24,65,32,14,5};// defined to be size 10 but init with size 6 ``` the code one will give me size = 10, but code 2 will give me size 6,and when I print out the element that is pointed by \*pointer, it will give me the correct array elements: ``` 31 24 65 32 14 5 ``` **example 2** ``` int array[] = {31,24,65,32,14,5}; // no declared size but init with 6 ``` Code 1 will give me size 6, code 2 will give me size 12, and when I print out the element that is pointed by \*pointer in code 2, it gives me : ``` 31 24 65 32 14 5 -802013403 -150942493 1461458784 32767 -1918962231 32767 ``` which is really not right, so what could be the problem that cause this behavior? and what are those numbers? Thanks for your answer
2015/05/30
[ "https://Stackoverflow.com/questions/30548655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3871348/" ]
This array has 10 elements, regardless of how you initialize it: ``` int array[10] = {31,24,65,32,14,5}; ``` But the initialization sets the first 6 elements to certain values, and the rest to `0`. It is equivalent to this: ``` int array[10] = {31,24,65,32,14,5,0,0,0,0}; ``` The first calculation using `sizeof` uses the actual size fo the array (its length times the size of an `int`), while the second one counts elements until it finds a `0`. So it doesn't calculate the length of the array, but the length of the first non-zero sequence in the array. Note that the second method only "works" if the array has an element with value `0`. Otherwise you go out of bounds and invoke undefined behaviour.
38,649,720
I have implemented the BaseActivity pattern in my app and everything works great except when trying to show an Alert Dialog box. This is what happens [![enter image description here](https://i.stack.imgur.com/wmgBG.png)](https://i.stack.imgur.com/wmgBG.png) when I try to cancel the dialog box I'm left with this. [![enter image description here](https://i.stack.imgur.com/jQdvh.png)](https://i.stack.imgur.com/jQdvh.png) Here's the code for showing the dialog box which resides in the base activity: ``` new AlertDialog.Builder(this) .setTitle("Logging out") .setMessage("Are you sure?") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { UIUtils.setAnimation(swipeRefreshLayout, true); UserBaas.logoutUser(); } }) .setNegativeButton("No", null) .show(); ``` This problem is persistent in an emulator and on an actual device. What could be the issue? ``` switch (item) { case NAVDRAWER_ITEM_HOME: startActivity(new Intent(this, MainActivity.class)); break; case NAVDRAWER_ITEM_MEMOS: intent = new Intent(this, MemoGroupActivity.class); intent.putExtra("section", MemoGroupActivity.MEMO); createBackStack(intent); break; case NAVDRAWER_ITEM_GROUPS: intent = new Intent(this, MemoGroupActivity.class); intent.putExtra("section", MemoGroupActivity.GROUP); createBackStack(intent); break; case NAVDRAWER_ITEM_CONNECTIONS: createBackStack(new Intent(this, ConnectionsActivity.class)); break; case NAVDRAWER_ITEM_DOCUMENTS: createBackStack(new Intent(this, DocumentsActivity.class)); break; case NAVDRAWER_ITEM_SETTINGS: createBackStack(new Intent(this, SettingsActivity.class)); break; case NAVDRAWER_ITEM_LOGOUT: showLogoutDialog(); break; } ``` And heres the code for UIUtils.setAnimation() ``` public static void setAnimation(SwipeRefreshLayout swipeRefreshLayout, boolean value) { swipeRefreshLayout.setEnabled(value); swipeRefreshLayout.setRefreshing(value); } ```
2016/07/29
[ "https://Stackoverflow.com/questions/38649720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3716006/" ]
Ok, so over time I've answered my own questions on this topic. First, Elastic Beanstalk uses CloudFormation behind the scenes, so this is why there is a "stack". Next, Spring Cloud AWS tries to make connections to DBs and such easier by binding to other resources that may have been created in the same stack. This is reasonable - if you are expecting it. If not, as @barthand says, it is probably better to turn this feature off with cloud.aws.stack.auto=false than have the app fail to start up. Third, When using Elastic Beanstalk, you have the opportunity to associate an execution role with your instance - otherwise the code in your instance isn't able to do much of anything with the AWS SDK. To explore the resources in a CloudFormation stack, Spring Cloud AWS tries to make some API calls, and by default these are not allowed. To make them allowed, I added these permissions to the role: ``` "Statement": [ { "Effect": "Allow", "Action": [ "cloudformation:DescribeStacks", "cloudformation:DescribeStackEvents", "cloudformation:DescribeStackResource", "cloudformation:DescribeStackResources", "cloudformation:GetTemplate", "cloudformation:List*" ], "Resource": "*" } ] ``` So to answer my original questions: 1. Yes it is definitely possible (and easy!) to run a Spring Cloud AWS program in Elastic Beanstalk. 2. Special requirements - Need to open the permissions on the associated role to include CloudFormation read operations, or... 3. Disable these using cloud.aws.stack.auto=false Hope this info helps someone in the future
21,924,911
Can anyone help me how to change the date format of this jquery validation from YYYY-MM-DD to MM/DD/YYYY. Example: ``` 2014-02-21 must be 02/21/2014 ``` I tried to change this: `new RegExp(/^(\d{4})[\/\-\.](0?[1-9]|1[012])[\/\-\.](0?[1-9]|[12][0-9]|3[01])$/);` To: `new RegExp(/^((0?[13578]|10|12)(-|\/)(([1-9])|(0[1-9])|([12])([0-9]?)|(3[01]?))(-|\/)((19)([2-9])(\d{1})|(20)([01])(\d{1})|([8901])(\d{1}))|(0?[2469]|11)(-|\/)(([1-9])|(0[1-9])|([12])([0-9]?)|(3[0]?))(-|\/)((19)([2-9])(\d{1})|(20)([01])(\d{1})|([8901])(\d{1})))$/);` But still I can't get the right validation I want.. Here's the code: ``` "date": { // Check if date is valid by leap year "func": function (field) { var pattern = new RegExp(/^(\d{4})[\/\-\.](0?[1-9]|1[012])[\/\-\.](0?[1-9]|[12][0-9]|3[01])$/); //<---- The Original Pattern of YYYY-MM-DD var match = pattern.exec(field.val()); if (match == null) return false; var year = match[1]; var month = match[2]*1; var day = match[3]*1; var date = new Date(year, month - 1, day); // because months starts from 0. return (date.getFullYear() == year && date.getMonth() == (month - 1) && date.getDate() == day); }, "alertText": "* Invalid date, must be in YYYY-MM-DD format" } ``` Please help me.. thanks.. :)
2014/02/21
[ "https://Stackoverflow.com/questions/21924911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2897924/" ]
Congratulations! You moved to a much better API than the one you had before. There are many reasons why the `DbContext` API is better than the older `ObjectContext` API, but in your case it may initially feel like a downgrade. ### Where's my `EntityState`, where's my `Reference`? Separation of concerns is the key here. The `DbContext` API aims at *persistence ignorance*: separation between business logic and data layer concerns. Entities generated by the `ObjectContext` API are far too busy tracking their own state, loading their own references and collections and notifying their own changes. Any business logic easily gets entwined with persistence logic. The entity classes generated by the `DbContext` generator are POCOs. All these data-related responsibilities have moved to the change tracker. The POCOs can concentrate on business logic. (They're still not the same as a DDD domain, but that's a different discussion). If you want, you can still go back to the `ObjectContext` API, but I wouldn't recommend it. Your code reveals that the API encourages bad practices: * Objects loading their own references or collections easily lead to the N + 1 anti pattern (1 query loading objects followed by "N" queries per object). * For objects to be able to load their own data the context must be alive, so this encourages the long-lived context anti pattern. The `DbContext` API encourages you to load object graphs as needed and then dispose the context. But it depends. In smart client applications you may have a context per form. In web applications a context per request is highly recommended. As you say in your comment to Tieson T. you can rely on lazy loading to occur whenever you access a navigation property and the [conditions for lazy loading](http://msdn.microsoft.com/en-us/data/jj574232#lazy) are met, but the above-mentioned anti patterns still apply. So I think for the time being you can leave your application code as-is, but take a look at the patterns the `DbContext` API encourages you to adhere to. As for me, lazy loading is close to being an anti pattern.
36,229
A few times in the past week I will wake up to my furnace turning on, hearing a click when it tries to ignite, then turn off. This will happen for a couple minutes before the furnace quits trying. However, after a certain period of time, it will turn on again with no issues. What should I do so it doesn't happen ever?
2013/11/28
[ "https://diy.stackexchange.com/questions/36229", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/2177/" ]
***WARNING:** Furnaces are expensive, complex pieces of equipment. If you don't have the proper tools and/or knowledge, it's often best to let the professionals handle maintenance and repair.* Gas Furnace Ignition Sequence: ============================== 1. Thermostat calls for heat. 2. Pilot gas valve opens. 3. Ignition control starts (spark or glow). 4. Pilot gas ignites. 5. Flame sensor detects pilot flame. 6. Main gas valve opens. 7. Main burners ignite. 8. Blower timer starts. 9. Flame sensor detects main burner flame. 10. Blower starts. High Efficiency Gas Furnace Ignition Sequence: ============================================== 1. Thermostat calls for heat. 2. Draft inducer starts. 3. Vacuum switch detects negative pressure. 4. Pilot valve opens. 5. Ignition control starts (spark or glow). 6. Pilot gas ignites. 7. Flame sensor detects pilot flame. 8. Main gas valve opens. 9. Main burners ignite. 10. Blower timer starts. 11. Flame sensor detects main burner flame. 12. Blower starts. Ignition Problems: ================== Vacuum Switch Not Closing ------------------------- In a high efficiency furnace, if the vacuum switch does not close after a certain timeout. The furnace will shut down, then possibly retry a few times depending on model. If after a given number of tries the switch still does not close, the furnace will enter lock out. Once in lock out, the furnace has to be manually reset (depending on model). The vacuum switch will look something like this... ![Vacuum switch](https://i.stack.imgur.com/JuyoF.jpg) And will have a rubber tube connecting it to the draft inducer. This part cannot be repaired, and must be replaced if it's faulty. Pilot Not Igniting ------------------ If the pilot does not light, you'll first want to check to make sure there is something trying to ignite it. Typically a spark or glow ignitor is used, so first you'll want to determine which is being used. ### Glow Ignitor A glow ignitor looks similar to this, though may not be visible without further disassembly. ![Glow ignitor](https://i.stack.imgur.com/m3OVd.jpg) It works by passing a current through it, causing it to heat up and glow. It should heat up enough to ignite the pilot gas. If it doesn't heat up, it should be replaced. ### Spark Ignitor A spark ignitor looks like this. ![Spark Ignitor](https://i.stack.imgur.com/KugBz.jpg) Take notice of the thick, often orange or red wire that is typically used to connect the ignitor to the ignition control module. This device works by generating an electrical arc between the two probes, causing the pilot gas to ignite. If there is no spark, you'll have to replace the ignition control module and/or the ignitor itself. If the [ignitor is not igniting the gas](https://diy.stackexchange.com/q/32529/33), but there is a spark. You can try cleaning the electrodes with fine steel wool, to remove any carbon buildup. Pilot Not Proving ----------------- For a pilot to "prove", it simply means that the flame sensor has sensed the pilot flame. If there is no pilot or the sensor doesn't detect it, the furnace will often purge the system and then try again. Furnaces will often try a set number of times, before entering lock out. If you can see the pilot flame, but the sensor is not detecting it. Try gently cleaning the sensor with fine steel wool, to remove any built up carbon. Also make sure the sensor is in the proper location with respect to the flame (Check the owners manual for proper placement), and adjust as necessary. If that doesn't work, replace the sensor. Main Burner Not Proving ----------------------- If the main burner ignites, but the furnace shuts down before the blower starts. You'll want to check the main flame (or rollout, high limit, etc) sensor(s). If your furnace has error code indicators, check those and compare to the owners manual for translation. In this case, you'll want to test and/or replace each sensor and/or contact an HVAC technician
40,816,415
I've faced with issue of overwriting root routes, when import child routes using loadChildren() call. App routes declared as: ``` const routes: Routes = [ { path: '', redirectTo: 'own', pathMatch: 'full' }, { path: 'own', component: OwnComponent }, { path: 'nested', loadChildren: () => NestedModule}, ]; export const routing = RouterModule.forRoot(routes); ``` Nested submodule's routes: ``` const routes: Routes = [ { path: 'page1', component: NestedPage1Component }, { path: 'page2', component: NestedPage2Component }, { path: '', redirectTo: 'page1', pathMatch: 'full' }, ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class Module1RoutingModule {} ``` I can get /own, /nested/page1, /nested/page2, but when I try to get root / - I'm getting redirect to /page1. Why does that happen, as it's declared in child module with RouterModule.forChild, how does it redirects not to /own ? I've created simple plunk for repro - <https://plnkr.co/edit/8FE7C5JyiqjRZZvCCxXB?p=preview> Does somebody experienced that behavior?
2016/11/26
[ "https://Stackoverflow.com/questions/40816415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5435640/" ]
Here is your forked and modified plunker: <https://plnkr.co/edit/XilkY55WXle2hFF0Pelx?p=preview> Do not import that lazy-load module and change the root routes like this: ```js //import { Module1Module } from "./module1/module1.module"; // do NOT import it ! export const routes: Routes = [ { path: '', redirectTo: 'own', pathMatch: 'full' }, { path: 'own', component: OwnComponent }, { path: 'module1', loadChildren: 'src/module1/module1.module#Module1Module' }, ]; ``` And the nested routes: ```js const routes: Routes = [ //{ path: 'page1', component: Module1Page1Component }, //{ path: 'page2', component: Module1Page2Component }, //{ path: '', redirectTo: 'page1', pathMatch: 'full' }, // do the routes like this.. { path: '', component: Module1Component, children: [ { path: '', redirectTo: 'page1', pathMatch: 'full' }, { path: 'page1', component: Module1Page1Component }, { path: 'page2', component: Module1Page2Component } ] }, ]; ```
51,316,579
I'm trying to create a JSON file in the following format: ``` [ { "startTimestamp" : "2016-01-03 13:55:00", "platform" : "MobileWeb", "product" : "20013509_825", "ctr" : 0.0150 }, {...} ] ``` And the values are stored in the following way: * `startTimeStamp` is in a list called `timestampsJSON` * `platform` is in a dictionary in this form `productBoughtPlatform[product] = platform` * `product` is in a dictionary in this form `productBoughtCount[product] = count` * `ctr` is in a dictionary in this form `CTR_Product[product] = ctr` I was trying to make something of the kind: ``` response = json.dumps({"startTimestamp":ts, for ts in timestampsJSON.items() "platform":plat, for plat in productBoughtPlatform.items() "product":pro, for pro, key in productBoughtCount.items() "ctr":ctr, for ctr in CTR_Product.items()}) ``` I know the syntax is invalid, but can somebody suggest a way to structure this data in a JSON? Thanks!
2018/07/13
[ "https://Stackoverflow.com/questions/51316579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2356619/" ]
I get same warning even after the new login: [![enter image description here](https://i.stack.imgur.com/Kakkx.png)](https://i.stack.imgur.com/Kakkx.png) I get that if the package name is incorrect, on top of the 404 error. If you need to be logged in just log back in. If you don't need to be logged in just **check that you have the correct package name**. In my case `react-native-create-app` didn't exist.. After adding the correct name: `create-react-native-app` it worked.
15,769,789
<http://jsfiddle.net/Jg3FP/1/> This doesn't line up correctly in various browsers but works fine in js fiddle, I'm not doing anything exotic. Why does it behave like this and how do I fix it? ![enter image description here](https://i.stack.imgur.com/1teFL.jpg) ![enter image description here](https://i.stack.imgur.com/yFHli.jpg) ``` <div id="diceDiv"> <div id="dice1Div">#</div> <input type="checkbox"/> <div id="dice2Div">#</div> <input type="checkbox"/> <div id="dice3Div">#</div> <input type="checkbox" /> <div id="dice4Div">#</div> <input type="checkbox"/> <div id="dice5Div">#</div> <input type="checkbox"/> <div id="dice6Div">#</div> <input type="checkbox"/> <br/> <input type="button" value="Roll" /> </div> <div id="log"></div> <div id="score"></div> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type="text/javascript"> $("div div").css("float", "left"); $("div input").css("clear", "right"); </script> ```
2013/04/02
[ "https://Stackoverflow.com/questions/15769789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1850535/" ]
That's because jsFiddle sets for you the correct headers, especially the doctype without which IE switches to a mode emulating the behavior of older versions. Try to start your HTML file like this : ``` <!DOCTYPE html> <html> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> ```
2,412,582
I'm preparing a query for mySQL to grab record from the previous week, but I have to treat weeks as Monday - Sunday. I had originally done this: ``` WHERE YEARWEEK(contactDate) = YEARWEEK(DATE_SUB(CURDATE(),INTERVAL 7 DAY)) ``` to discover that mySQL treats weeks as Sunday - Monday. So instead I'm parsing getting the begin & end dates in php like this: ``` $i = 0; while(date('D',mktime(0,0,0,date('m'), date('d')-$i, date('y'))) != "Mon") { $i++; } $start_date = date('Y-n-j', mktime(0,0,0,date('m'), date('d')-($i+7), date('y'))); $end_date = date('Y-n-j', mktime(0,0,0,date('m'), date('d')-($i+1), date('y'))); ``` This works - it gets the current week's date for monday (walking backwards until a monday is hit) then calculates the previous week's dates based on that date. My question is: Is there a better way to do this? Just seems sloppy, and I expect someone out there can give me a cleaner way to do it - or perhaps not because I need Monday - Sunday weeks. Edit ---- Apparently, there is: ``` $start = date('Y-m-d',strtotime('last monday -7 days')); $end = date('Y-m-d',strtotime('last monday -1 days')); ``` That's about a million times more readable. Thank you.
2010/03/09
[ "https://Stackoverflow.com/questions/2412582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260302/" ]
you can use [strtotime](http://php.net/manual/en/function.strtotime.php) for this kind of date issues ``` echo strtotime("last Monday"); ```
209,331
I've got a table `t` with ~23 million rows (4248 MB in size). There's a column `row_id` in it, with a `not null` constraint. And a unique index `p1` on `t(row_id)`. When I do `select count(*) from t` to count all the rows in the table, the planner tells me: ``` Seq Scan on t (cost=0.00..686191.06 rows=23176906 width=0) ``` I would have expected a fast `Index Only Scan` (index p1 occupies only 698 MB - 6x less). If I do `SET enable_seqscan = off`, then the planner still insists on reading the table rows: ``` QUERY PLAN -> Bitmap Heap Scan on t (cost=210923.32..897114.38 rows=23176906 width=0) -> Bitmap Index Scan on p1 (cost=0.00..205129.09 rows=23176906 width=0) ``` Why is the unique index ignored in this case? What's the catch? I am using PostgreSQL 10.4 For a clean room test I did the following: ``` create table tmp ( row_id varchar(15) unique not null, <10 original cols> ); insert into tmp (row_id, <10 cols>) select row_id, <10 cols> from t; commit; analyze tmp; set enable_seqscan = on; explain (analyze, buffers) select count(*) from tmp; QUERY PLAN Aggregate (cost=744070.45..744070.46 rows=1 width=8) (actual time=5631.501..5631.502 rows=1 loops=1) Buffers: shared hit=209109 read=245254 -> Seq Scan on tmp (cost=0.00..686128.96 rows=23176596 width=0) (actual time=0.014..3481.967 rows=23176906 loops=1) Buffers: shared hit=209109 read=245254 Planning time: 0.064 ms Execution time: 5631.531 ms SET enable_seqscan = off; explain (analyze, buffers) select count(*) from tmp; QUERY PLAN Aggregate (cost=980282.14..980282.15 rows=1 width=8) (actual time=16224.408..16224.408 rows=1 loops=1) Buffers: shared hit=26285 read=542015 -> Bitmap Heap Scan on tmp (cost=236211.69..922340.65 rows=23176596 width=0) (actual time=10030.115..14157.288 rows=23176906 loops=1) Heap Blocks: exact=454363 Buffers: shared hit=26285 read=542015 -> Bitmap Index Scan on tmp_row_id_key (cost=0.00..230417.54 rows=23176596 width=0) (actual time=9929.582..9929.582 rows=23176906 loops=1) Buffers: shared hit=26285 read=87652 Planning time: 0.051 ms Execution time: 16229.303 ms ``` No parallel index scan so far. PostgreSQL insists on accessing the table for some obscured reason.
2018/06/11
[ "https://dba.stackexchange.com/questions/209331", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/153219/" ]
As to why you do not get an index scan with `SET enable_seqscan = off`, **you should be getting an index-only scan**. Your situation can not yet be recreated with the data you've provided. This certainly works with PostgreSQL 10.4. I can't speak to your own use case, and there are a lot of reasons why you *may* not get an index scan in the real world. Ultimately, debugging a question along those lines will result in an answer that is simply "planner estimates" but will require a lot more data about your environment, configuration, and the plans with and without `SET enable_seqscan = off`. Sample Data =========== ``` BEGIN; CREATE TABLE foo ( x int NOT NULL UNIQUE ); INSERT INTO foo (x) SELECT generate_series(1,1e6); COMMIT; ANALYZE foo; -- don't forget to analyze ``` With `seq_scan` =============== ``` test=# EXPLAIN SELECT count(*) FROM foo; QUERY PLAN -------------------------------------------------------------------------------------- Finalize Aggregate (cost=10633.55..10633.56 rows=1 width=8) -> Gather (cost=10633.33..10633.54 rows=2 width=8) Workers Planned: 2 -> Partial Aggregate (cost=9633.33..9633.34 rows=1 width=8) -> Parallel Seq Scan on foo (cost=0.00..8591.67 rows=416667 width=0) (5 rows) ``` Notice we're doing a *"Parallel Seq Scan"* Without `seq_scan` ================== ``` SET enable_seq_scan = off; test=# EXPLAIN SELECT count(*) FROM foo; QUERY PLAN -------------------------------------------------------------------------------------------------------------- Finalize Aggregate (cost=26616.97..26616.98 rows=1 width=8) -> Gather (cost=26616.76..26616.97 rows=2 width=8) Workers Planned: 2 -> Partial Aggregate (cost=25616.76..25616.77 rows=1 width=8) -> Parallel Index Only Scan using foo_x_key on foo (cost=0.42..24575.09 rows=416667 width=0) (5 rows) ``` **Notice we're doing a *"Parallel Index Only Scan"***
15,477,364
I am trying to display records from a table named **staffpresentee** from a database using the where clause... i am using visual studio 2010... the table design is as follows- ``` .......fieldname..................datatype........allownull 1......staff_id (fk).............numeric(18,0)......yes 2.......date........................date.............no 3......present.....................char(1)..........yes ``` Note that the type of the 2nd field is date and not datetime... I want to display all records from the table that have today's date int the 'date' field... My current query is- ``` cmd = New SqlClient.SqlCommand("select * from staffpresentee where date=" & Date.Now.Date, cn) dr = cmd.ExecuteReader ``` for `dr = cmd.ExecuteReader` i get the error > > "Operand type clash: date is incompatible with int" > > > i tried the `select * from staffpresentee` query without the where clause it runs correctly.
2013/03/18
[ "https://Stackoverflow.com/questions/15477364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2182405/" ]
Try putting the date value in sigle quotes maybe. ``` cmd = New SqlClient.SqlCommand("select * from staffpresentee where date='" & _ Date.Now.Date & "'", cn) dr = cmd.ExecuteReader ```
25,165,387
So i am having an issue in which the bing maps are not rendered completely on Safari 7. They are loaded fine on Chrome and IE. *Example* - copy and paste the link into Safari 7 on a Mac : <http://www.levi.com/GB/en_GB/findAStore> As You can see only half the map renders the other half is gray, i get no errors in the console, the only warning i get is: **"Invalid CSS property declaration at:\* style.css"** Is anyone else running into this issue? is there a fix for it?
2014/08/06
[ "https://Stackoverflow.com/questions/25165387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3915205/" ]
Try `text-align:left` in the style of the mapViewer div, it is likely that the map is inheriting the property `text-align: center` and that also applies to images of the map
5,194,530
I'd like to have a number of dynamic attributes for a User model, e.g., phone, address, zipcode, etc., but I would not like to add each to the database. Therefore I created a separate table called `UserDetails` for key-value pairs and a `belongs_to :User`. Is there a way to somehow do something dynamic like this `user.phone = "888 888 8888"` which would essentially call a function that does: ``` UserDetail.create(:user => user, :key => "phone", :val => "888 888 8888") ``` and then have a matching getter: ``` def phone UserDetail.find_by_user_id_and_key(user,key).val end ``` All of this but for a number of attributes provided like phone, zip, address, etc., without arbitrarily adding a ton of of getters and setters?
2011/03/04
[ "https://Stackoverflow.com/questions/5194530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/436440/" ]
You want to use the delegate command: ``` class User < ActiveRecord:Base has_one :user_detail delegate :phone, :other, :to => :user_detail end ``` Then you can freely do `user.phone = '888 888 888'` or consult it like `user.phone`. Rails will automatically generate all the getters, setters and dynamic methods for you
16,349,073
I have a problem with the following code: ``` question1.setText("question1_" + question_number() + "()"); ``` I have multiple methods that return a string value and are named "question1\_x" (x is a number) and the method question\_number returns a random number. When i run the code like this the "question1" text is set to "question1\_x()" , but what i need it to do is set the text as the "question1\_x()" method returns it. Simply i like ["question1\_" + question\_number() + "()"] to be seen by ".setText" as a method and not as a string. Thank you in advance :)
2013/05/02
[ "https://Stackoverflow.com/questions/16349073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2184672/" ]
Java won't let you do this unless you resort to reflection. **Reflection is almost certainly the wrong solution to this problem.** Any time you want to have numbered methods and/or fields, step back and consider using a proper collection (say, a list) instead. Start by replacing your numbered methods with a single method that takes a number: ``` String question1(int questionNumber) ```
1,604,871
I'm dealing with the following variant of the well-known [Jeep problem](https://en.wikipedia.org/wiki/Jeep_problem): > > A 1000 mile wide desert needs to be crossed in a Jeep. The mileage is one mile / gallon and the Jeep can transport up to 1000 gallons of gas at any time. Fuel may be dropped off at any location in the desert and picked up later. There are 3000 gallons of gas in the base camp. How much fuel can the Jeep transport to the camp on the other side of desert? > > > So instead of "exploring" the desert or trying to drive as far as possible, the problem here is to transport as much fuel as possible for a given distance. I've thought about reducing this problem to the well-studied ones, but I can't come up with anything that makes sense. I don't even know how to approach this. Any pointers?
2016/01/08
[ "https://math.stackexchange.com/questions/1604871", "https://math.stackexchange.com", "https://math.stackexchange.com/users/303693/" ]
Let's represent your starting location as $0$ and the destination as $1000$. Let $f(x)$ be the greatest amount of fuel that can possibly be transported to or past $x$ miles from the starting point. For example, if you pick up $1000$ gallons, drive to $1$ (one mile), drop off $998$ gallons, drive back, repeat the trip to $1$ and back, and on the third trip out you drive to $100$ where you drop $801$ gallons of fuel, then you will have transported $2995$ gallons to point $1$: the $1996$ gallons you cached there and the $999$ gallons that were in the jeep when you passed $1$ on the third trip from $0$. You should be able to show that for $0 \leq x \leq 200$, $f(x) = 3000 - 5x$. The intuitive reason is that you will either have to pass every point between $0$ and $200$ five times (three times outbound and twice in the return direction) have to abandon some fuel without using it; and the latter strategy will deliver less fuel to points beyond where you abandoned the fuel. The previous example that transported $2995$ gallons to or past point $1$ was therefore optimal, or at least was optimal up to $1$. It follows that only $2000$ gallons can reach $200$ no matter where you leave your caches along the way. You should then be able to show that for $0 \leq y \leq \frac{1000}{3}$, $f(200 + y) = 2000 - 3y$. Moreover, you achieve this by delivering exactly $2000$ gallons of fuel to $200$, including the fuel in the jeep the last time you arrive at $200$ in the forward direction, then making sure you have $1000$ gallons in the jeep each time you drive forward from $200$. Finally, for $0 \leq z \leq 1000$, $f\left(200 + \frac{1000}{3} + z\right) = 1000 - z$. You achieve this by delivering exactly $1000$ gallons of fuel to $200 + \frac{1000}{3}$ and then fully loading the jeep with any fuel you have cached at that point and making just one trip forward. The answer is $f(1000)$.
16,424,803
I have the HTML like ``` <div id="abc"> <ul> <li class="first">One<img src="images/plus.png" /></li> <li class="first">Two<img src="images/plus.png" /></li> <li class="first">Three<img src="images/plus.png" /></li> <li class="first">Four<img src="images/plus.png" /></li> </ul> <div class="content"> <h3>Title1</h3> <p>Title1 Description</p> </div> <div class="content"> <h3>Title2</h3> <p>Title2 Description</p> </div> <div class="content"> <h3>Title3</h3> <p>Title3 Description</p> </div> <div class="content"> <h3>Title4</h3> <p>Title4 Description</p> </div> </div> ``` When I click on the first plus image the first div should be displayed below One. When I click on plus image near Two the second image should be displayed below Two. I tried lot of ways but no luck. Please provide a solution. Thanks in advance.
2013/05/07
[ "https://Stackoverflow.com/questions/16424803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1784484/" ]
There are no general rule of thumb for this, depends on application build. For example: 1. For bank website: 15/30 Seconds might be appropriate 2. For a simple CMS application: 15 minutes long session is good enough.
8,000,694
So this is my code, I am wondering why changeUp isn't sending an alert to me or setting the variable value: ``` var selecteduname; var xmlhttp; function changeUp() { document.getElementById("useruname").onChange = function() { selecteduname = this.value; alert(selecteduname); updateAdduser(); } function loadXMLDoc() { if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } } function updateAdduser() {loadXMLDoc(); xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { var json = xmlhttp.responseText; var fields = JSON.parse(json); Object.keys(fields).forEach(function (name) { var input = document.getElementsByName(name); input.value = fields[name]; }); } } xmlhttp.open("GET", "ajaxuseradd.psp?uname="+selecteduname, true); xmlhttp.send(); } </script> ``` and ``` <form action="adduser.psp" method="get"> <fieldset> <label for="uname">Username:</label> <select name="uname" id="useruname" onChange="changeUp();"> <% Blah blah blah Python Code to generate option values %> <%= options %> //More Python code, this actually puts them into the select box </select> </fieldset> <fieldset> <label for="fname">First Name:</label> <input type="text" name="fname" /> </fieldset> <fieldset> <label for="lname">Last Name:</label> <input type="text" name="lname" /> </fieldset> <fieldset> <label for="email">Email:</label> <input type="text" name="email"> </fieldset> ```
2011/11/03
[ "https://Stackoverflow.com/questions/8000694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/756566/" ]
As commented above, the property name is "onchange", not "onChange". Javascript is case-sensitive, so those two are definitely different. Also, the code you posted looks like it's missing a `}` somewhere. As it is, everything's inside the `changeUp` function. Which, coincidentally, never closes before that ending script tag. However, there's something else going on here. This line in your markup: ``` <select name="uname" id="useruname" onChange="changeUp();"> ``` Gets completely wiped out by this line in your code: ``` document.getElementById("useruname").onChange = function() { ``` Here's how I'd fix it up. First, the javascript: ``` function createAjax() { if(window.XMLHttpRequest) return new XMLHttpRequest(); else return new ActiveXObject("Microsoft.XMLHTTP"); } function updateAddUser(username) { var ajax = createAjax(); ajax.onreadystatechange = function() { if(ajax.readyState == 4 && ajax.status == 200) { var json = ajax.responseText; var fields = JSON.parse(json); Object.keys(fields).forEach(function (name) { var input = document.getElementsByName(name); input.value = fields[name]; }); } } ajax.open("GET", "ajaxuseradd.psp?uname=" + username, true); ajax.send(); } ``` Then you can just change the HTML `select` tag to: ``` <select name="uname" id="useruname" onchange="updateAddUser(this.value)"> ``` Having said all that, I would strongly urge you try something like [jQuery](http://jquery.com). It would make the javascript code as trivial as: ``` $('#username').change(function(){ $.get('ajaxuseradd.php', {uname:$(this).val()}, function(data, status, xhr) { $.each(data, function(key,value) { $('#'+key).val(value); }); }, 'json'); }); ``` Yeah, that's really terse, I know. More expressively, it could be written like this: ``` $('#username').change(function() { var userName = $(this).val(); $.ajax({ type: 'GET', url: 'ajaxuseradd.php', data: { uname: userName }, success: function(data, status, xhr) { $.each(data, function(key, value) { $('#' + key).val(value); }); }, dataType: 'json' }) }); ```
16,290,782
I'm currently having a problem when passing an array to a directive via an attribute of that directive. I can read it as a String but i need it as an array so this is what i came up with but it doesn't work. Help anyone? thks in advance Javascript:: ``` app.directive('post', function($parse){ return { restrict: "E", scope:{ title: "@", author: "@", content: "@", cover: "@", date: "@" }, templateUrl: 'components/postComponent.html', link: function(scope, element, attrs){ scope.tags = $parse(attrs.tags) } } } ``` HTML:: ``` <post title="sample title" tags="['HTML5', 'AngularJS', 'Javascript']" ... > ```
2013/04/30
[ "https://Stackoverflow.com/questions/16290782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2334176/" ]
If you're accessing this array from your scope, i.e. loaded in a controller, you can just pass the name of the variable: [Binding array to directive variable in AngularJS](https://stackoverflow.com/questions/14695792/binding-array-to-directive-variable-in-angularjs) **Directive:** ``` scope:{ title: "@", author: "@", content: "@", cover: "@", date: "@", tags: "=" }, ``` **Template:** ``` <post title="sample title" tags="arrayName" ... > ```
54,477,023
I am trying to connect *Google.com* using the below code but getting ``` java.net.ConnectException: Connection Timed out ``` . Please help! ``` private static String getUrlContents(String theUrl) { StringBuilder content = new StringBuilder(); // many of these calls can throw exceptions, so i've just // wrapped them all in one try/catch statement. try { // create a url object URL url = new URL(theUrl); // create a urlconnection object URLConnection urlConnection = url.openConnection(); // wrap the urlconnection in a bufferedreader BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String line; // read from the urlconnection via the bufferedreader while ((line = bufferedReader.readLine()) != null) { content.append(line + "\n"); } bufferedReader.close(); } catch (Exception e) { e.printStackTrace(); } return content.toString(); } ```
2019/02/01
[ "https://Stackoverflow.com/questions/54477023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11000301/" ]
I just tried your code and it works fine. It seems it's a network problem, maybe you don't have Internet access, or firewall is stoping connections. Supposing you are in UNIX system try to: 1. `ping www.google.com -C 1` If this you don't get an answer and you have normal access connection (i.e. from your browser) it may be a firewall problem. 2. `traceroute www.google.com` to check the number of hops that should be normally one or two for google's servers. If you are on CentOS you should try to stop the firewall for testing beacuse it's quite restrictive: `sudo systemctl stop firewalld` Remember to start it again and add the rules you need to perform your requests.
45,165,243
This is an excerpt from a Conway's Game of Life-program that I'm writing. In this part I'm trying to get the program to read a file that specifies what cells are to be populated at the start of the game (i.e. the seed). I get a weird bug. In the `read_line` function, the program crashes on`line[i++] = ch` statement. When I debug the program, I see that the `line`-pointer is NULL when it crashes. Fair enough, I think, I should initialize `line`. But here is the (for me) strange part: The `read_line` function has already successfully execute twice and got me the first two lines (`4\n` and `3 6\n`) from the seed file. And when I look at the execution in the debugger, I see that line is indeed holding a value in those first two executions of `read_line`. How is this possible? How can `line` be initialized without me initializing it and then suddenly not be initialized anymore? ``` #include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> #define MAX_COORDINATE_SIZE 50 #define MAX_FILENAME_SIZE 20 #define MAX_GENERATIONS 10 #define MAX_REPETITION_PERIOD 4 struct coord{ //Holds coordinates to a cell int x; int y; }; struct cell{ int pop; //Populated int age; }; struct coord *read_init(FILE *fp, int *i); static int read_line(FILE *fp, char *line, int max_length); struct coord read_coords(char *line); struct cell **create_board(int x, int y); struct cell **start_game(FILE *fp, int nrows, int ncols); struct cell new_cell(int x, int y, int pop, int age); void print_board(struct cell **board, int nrows, int ncols); void populate_board(struct coord *coords, struct cell ***board, int *n); int main(int argc, const char * argv[]) { int gens; char gens_string[MAX_GENERATIONS]; if(argc != 3){ fprintf(stderr, "Usage: %s <seed-file> <generations>\n<seed-file> can me up to %d characters long\n", argv[0], MAX_FILENAME_SIZE); exit(1); } FILE *fp = fopen(argv[1], "r"); strncat(gens_string, argv[2], MAX_GENERATIONS); gens = atoi(gens_string); int nrows = 10; int ncols = 10; struct cell **board= start_game(fp, nrows, ncols); print_board(board, nrows, ncols); return 0; } struct coord *read_init(FILE *fp, int *n){ //Takes in filename and returns list of coordinates to be populated char raw_n[100]; struct coord *coords; char *line; read_line(fp, raw_n, 100); // get the first line of the file (number of popuated cells) *n = atoi(raw_n);//make an int out of raw_n coords = malloc(sizeof(struct coord)*(*n)); //Allocate memory for each coord for(int i = 0; i<(*n); i++){ // for each line in the file (each populated cell) read_line(fp, line, MAX_COORDINATE_SIZE); coords[i] = read_coords(line); //Put coordinates in coords line = '\0'; } return coords; // return coordinates } static int read_line ( FILE *fp, char *line, int max_length) { int i; char ch; /* initialize index to string character */ i = 0; /* read to end of line, filling in characters in string up to its maximum length, and ignoring the rest, if any */ for(;;) { /* read next character */ ch = fgetc(fp); /* check for end of file error */ if ( ch == EOF ) return -1; /* check for end of line */ if ( ch == '\n' ) { /* terminate string and return */ line[i] = '\0'; return 0; } /* fill character in string if it is not already full*/ if ( i < max_length ) line[i++] = ch; } /* the program should never reach here */ return -1; } struct coord read_coords(char *line){ // Returns coordinates read from char *line struct coord c; char *x; char *y; x = malloc(sizeof(char)*MAX_COORDINATE_SIZE); y = malloc(sizeof(char)*MAX_COORDINATE_SIZE); int i = 0; do{ x[i] = line[i]; //Get the x coordinate i++; }while(line[i] != ' '); i++; do{ y[i-2] = line[i]; i++; }while(line[i] != '\0'); c.x = atoi(x)-1; c.y = atoi(y)-1; return c; } void init_board(int nrows, int ncols, struct cell ***board){ *board = malloc(nrows * sizeof(*board) + nrows * ncols * sizeof(**board)); //Now set the address of each row or whatever stackoverflow says struct cell * const firstrow = *board + nrows; for(int i = 0; i < nrows; i++) { (*board)[i] = firstrow + i * ncols; } for(int i = 0; i < nrows; i++){ //fill the entire board with pieces for(int j = 0; j < ncols; j++){ (*board)[i][j] = new_cell(i, j, 0, 0); } } } void print_board(struct cell **board, int nrows, int ncols){ printf("--------------------\n"); for(int i = 0; i<nrows; i++){ for(int j = 0; j<ncols; j++){ if(board[i][j].pop == 1){ printf("%d ", board[i][j].age); }else if(board[i][j].pop == 0){ printf(" "); }else{ printf("\n\nERROR!"); exit(0); } } printf("\n"); } printf("--------------------"); printf("\n"); } struct cell **start_game(FILE *fp, int nrows, int ncols){ //x,y are no of rows/columns, fn is filename int n; // n is the number of populated cells specified in the seed struct coord *coords = read_init(fp, &n); // get the list of coords to populate board with struct cell **board; init_board(nrows, ncols, &board); // Set up the board populate_board(coords, &board, &n); //populate the cells specified in the seed return board; } void populate_board(struct coord *coords, struct cell ***board, int *n){ for(int i = 0; i < *n; i++){ (*board)[coords[i].x][coords[i].y].pop = 1; //populate the cell } } struct cell new_cell(int x, int y, int pop, int age){ //Return new populated or non-populated cell with specified coordinates struct cell c; c.pop = pop; c.age = age; return c; } ``` The seed file: ``` 4 3 6 4 6 5 6 5 7 ``` EDIT: The error message: `Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)` I shall add that if I add a line `line = malloc(sizeof(char)*MAX_COORDINATE_SIZE+1)` after the declaration of line in `read_init`, I still get the same error.
2017/07/18
[ "https://Stackoverflow.com/questions/45165243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3128156/" ]
In read\_init() : ``` struct coord *read_init(FILE *fp, int *n){ //... char *line; //... for(int i = 0; i<(*n); i++) { read_line(fp, line, MAX_COORDINATE_SIZE); coords[i] = read_coords(line); //Put coordinates in coords line = '\0'; // <<--- you set line to NULL here. *line = 0; // this is what you wanted to do, is not necessary... } // .... } ```
127,227
how would you improve the buttons on the top of the screen? To grab attention of the user I tried to change a bit their color (they are dark blue instead of black), but I think that they are not coherent with the rest of the screen. [![screen](https://i.stack.imgur.com/yiO22.png)](https://i.stack.imgur.com/yiO22.png)
2019/08/02
[ "https://ux.stackexchange.com/questions/127227", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/129146/" ]
Generally, circles are used to show information (think social media profile pics); we see them less as buttons. Try making the buttons rounded rectangles. I don't think coloring the icons necessarily helps make them more discoverable, and color might compete with what the user is trying to do visually on the canvas. Monochrome might be the way to go. [![A screenshot of Apple's Preview image editing buttons](https://i.stack.imgur.com/gSVTC.png)](https://i.stack.imgur.com/gSVTC.png)
67,281,326
I have a form with sub-forms using ControlValueAccessor profile-form.component.ts ``` form: FormGroup; this.form = this.formBuilder.group({ firstName: [], lastName: ["", Validators.maxLength(10)], email: ["", Validators.required] }); get lastNameControl() { return this.form.controls.lastName; } initForm() { ... this.form.patchValue({ firstName: "thompson", lastName: "vilaaaaaaaaaaaaaaaaaaaa", email: "abc@gmail.com" }); ... } ``` profile-form.component.html ``` <label for="last-name">Last Name</label> <input formControlName="lastName" id="last-name" /> <div *ngIf="lastNameControl.touched && lastNameControl.invalid" class="error"> last name max length is 10 </div> ``` Problem: The initial data are loaded to the form, but the validations are not triggered (for example: field Last Name is not validated). I have to touch the field then the validation start working. How to trigger validations right after the `patchValue` done. please refer to the code: <https://stackblitz.com/edit/angular-wg5mxz?file=src/app/app.component.ts> Any suggestion is appreciated.
2021/04/27
[ "https://Stackoverflow.com/questions/67281326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1845475/" ]
> > To prevent the validator from displaying errors before the user has a chance to edit the form, you should check for either the dirty or touched states in a control. > > > When the user changes the value in the watched field, the control is marked as "dirty". > When the user blurs the form control element, the control is marked as "touched". > > > You should delete `lastNameControl.touched` from your `*ngIf` Check <https://angular.io/guide/form-validation> for more information
31,488,517
Is there any built-in function to get the maximum accuracy for a binary probabilistic classifier in scikit-learn? E.g. to get the maximum F1-score I do: ``` # AUCPR precision, recall, thresholds = sklearn.metrics.precision_recall_curve(y_true, y_score) auprc = sklearn.metrics.auc(recall, precision) max_f1 = 0 for r, p, t in zip(recall, precision, thresholds): if p + r == 0: continue if (2*p*r)/(p + r) > max_f1: max_f1 = (2*p*r)/(p + r) max_f1_threshold = t ``` I could compute the maximum accuracy in a similar fashion: ``` accuracies = [] thresholds = np.arange(0,1,0.1) for threshold in thresholds: y_pred = np.greater(y_score, threshold).astype(int) accuracy = sklearn.metrics.accuracy_score(y_true, y_pred) accuracies.append(accuracy) accuracies = np.array(accuracies) max_accuracy = accuracies.max() max_accuracy_threshold = thresholds[accuracies.argmax()] ``` but I wonder whether there is any built-in function.
2015/07/18
[ "https://Stackoverflow.com/questions/31488517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/395857/" ]
``` from sklearn.metrics import accuracy_score from sklearn.metrics import roc_curve fpr, tpr, thresholds = roc_curve(y_true, probs) accuracy_scores = [] for thresh in thresholds: accuracy_scores.append(accuracy_score(y_true, [m > thresh for m in probs])) accuracies = np.array(accuracy_scores) max_accuracy = accuracies.max() max_accuracy_threshold = thresholds[accuracies.argmax()] ```
220,837
I am trying to solve a system of 9 linear coupled ODE using `DSolve`. To try things out I do : ``` e1 = app'[t] == a a03[t] + b app[t] e2 = a03'[t] == d a03[t] - c app[t] DSolve[{e1, e2, a03[0] == 1, app[0] == 2}, {app, a03}, {t}] ``` It works perfectly. Now I try to solve the real thing : ``` ex1 = Derivative[1][app][t] == 2*a03[t]*A21 + 2*A21*a30[t] + 2*I*app[t]*B22 + I*a3p[t]*w + I*Conjugate[a3p[t]]*w - 2*I*app[t]*w + (-4*a33[t] + Conjugate[apm[t]] + apm[t])*Subscript[A, c]^11; ex2 = Derivative[1][apm][t] == (Conjugate[app[t]] + app[t])*Subscript[A, c]^11 - I*((-a3m[t] + Conjugate[a3p[t]])*w + 2*(a03[t] + a30[t])*Subscript[B, c]^11); ex3 = Derivative[1][a30][t] == -2*A21*(Conjugate[app[t]] - app[t]) - 2*I*(Conjugate[a0m[t]] - Conjugate[a0p[t]])*w + 2*I*(4 + Conjugate[apm[t]] + apm[t])*Subscript[B, c]^11; ex4 = Derivative[1][a03][t] == -2*A21*(Conjugate[app[t]] - app[t]) - 2*I*(a0m[t] - a0p[t])*w + 2*I*(4 + Conjugate[apm[t]] + apm[t])*Subscript[B, c]^11; ex5 = Derivative[1][a33][t] == 2*I*((-a3m[t] + a3p[t] - Conjugate[a3m[t]] + Conjugate[a3p[t]])*w + 2*I*(Conjugate[app[t]] + app[t])*Subscript[A, c]^11 + 4*(a03[t] + a30[t])*Subscript[B, c]^11); ex6 = Derivative[1][a0p][t] == 4*I*((-I)*A21*Conjugate[a3m[t]] + a0p[t]*B22 + a03[t]*w - a0p[t]*w - I*a0m[t]*Subscript[A, c]^11 - Conjugate[a3p[t]]*Subscript[B, c]^11); ex7 = Derivative[1][a0m][t] == -4*I*((-I)*A21*Conjugate[a3p[t]] + a0m[t]*B22 + a03[t]*w - a0m[t]*w + I*a0p[t]*Subscript[A, c]^11 + Conjugate[a3m[t]]*Subscript[B, c]^11); ex8 = Derivative[1][a3m][t] == 2*I*(-2*I*A21*Conjugate[a0p[t]] - 2*a3m[t]*B22 - 2*a33[t]*w + 2*a3m[t]*w - Conjugate[app[t]]*w + apm[t]*w - 2*I*(a3p[t] + 2*Conjugate[a3p[t]])*Subscript[A, c]^11 + 2*(2*a0m[t] + Conjugate[a0m[t]])*Subscript[B, c]^11); ex9 = Derivative[1][a3p][t] == 2*I*(2*I*A21*Conjugate[a0m[t]] + 2*a3p[t]*B22 + 2*a33[t]*w - 2*a3p[t]*w - Conjugate[apm[t]]*w + app[t]*w - 2*I*(a3m[t] + 2*Conjugate[a3m[t]])*Subscript[A, c]^11 + 2*(2*a0p[t] + Conjugate[a0p[t]])*Subscript[B, c]^11); DSolve[{ex1, ex2, ex3, ex4, ex5, ex6, ex7, ex8, ex9}, {app, apm, a30, a03, a33, a0p, a0m, a3m, a3p}, t] ``` This however fails and gives the following output : ``` DSolve[{Derivative[1][app][t] == 2*A21*a03[t] + 2*A21*a30[t] + I*w*a3p[t] + 2*I*B22*app[t] - 2*I*w*app[t] + I*w*Conjugate[a3p[t]] + (-4*a33[t] + apm[t] + Conjugate[apm[t]])*Subscript[A, c]^11, Derivative[1][apm][t] == (app[t] + Conjugate[app[t]])*Subscript[A, c]^11 - I*(w*(-a3m[t] + Conjugate[a3p[t]]) + 2*(a03[t] + a30[t])*Subscript[B, c]^11), Derivative[1][a30][t] == -2*I*w*(Conjugate[a0m[t]] - Conjugate[a0p[t]]) - 2*A21*(-app[t] + Conjugate[app[t]]) + 2*I*(4 + apm[t] + Conjugate[apm[t]])*Subscript[B, c]^11, Derivative[1][a03][t] == -2*I*w*(a0m[t] - a0p[t]) - 2*A21*(-app[t] + Conjugate[app[t]]) + 2*I*(4 + apm[t] + Conjugate[apm[t]])*Subscript[B, c]^11, Derivative[1][a33][t] == 2*I*(w*(-a3m[t] + a3p[t] - Conjugate[a3m[t]] + Conjugate[a3p[t]]) + 2*I*(app[t] + Conjugate[app[t]])*Subscript[A, c]^11 + 4*(a03[t] + a30[t])*Subscript[B, c]^11), Derivative[1][a0p][t] == 4*I*(w*a03[t] + B22*a0p[t] - w*a0p[t] - I*A21*Conjugate[a3m[t]] - I*a0m[t]*Subscript[A, c]^11 - Conjugate[a3p[t]]*Subscript[B, c]^11), Derivative[1][a0m][t] == -4*I*(w*a03[t] + B22*a0m[t] - w*a0m[t] - I*A21*Conjugate[a3p[t]] + I*a0p[t]*Subscript[A, c]^11 + Conjugate[a3m[t]]*Subscript[B, c]^11), Derivative[1][a3m][t] == 2*I*(-2*w*a33[t] - 2*B22*a3m[t] + 2*w*a3m[t] + w*apm[t] - 2*I*A21*Conjugate[a0p[t]] - w*Conjugate[app[t]] - 2*I*(a3p[t] + 2*Conjugate[a3p[t]])*Subscript[A, c]^11 + 2*(2*a0m[t] + Conjugate[a0m[t]])*Subscript[B, c]^11), Derivative[1][a3p][t] == 2*I*(2*w*a33[t] + 2*B22*a3p[t] - 2*w*a3p[t] + w*app[t] + 2*I*A21*Conjugate[a0m[t]] - w*Conjugate[apm[t]] - 2*I*(a3m[t] + 2*Conjugate[a3m[t]])*Subscript[A, c]^11 + 2*(2*a0p[t] + Conjugate[a0p[t]])*Subscript[B, c]^11)}, {app, apm, a30, a03, a33, a0p, a0m, a3m, a3p}, t] ``` Can someone please tell me where I went wrong? Edit : I have experimented and discovered that : ``` DSolve[f'[x] == a f[x], f, x] ``` , takes less than one second, but the following takes around 15 seconds to evaluate : ``` DSolve[f'[gh] == a Conjugate[f[gh]], f, gh] ```
2020/05/01
[ "https://mathematica.stackexchange.com/questions/220837", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/72104/" ]
We can simplifier this system up to linear matrix equation $u'(t)=A.u+B$ using code below ``` ex1 = Derivative[1][app][t] == 2*a03[t]*A21 + 2*A21*a30[t] + 2*I*app[t]*B22 + I*a3p[t]*w + I*Conjugate[a3p[t]]*w - 2*I*app[t]*w + (-4*a33[t] + Conjugate[apm[t]] + apm[t])* Subscript[A, c]^11; ex2 = Derivative[1][apm][ t] == (Conjugate[app[t]] + app[t])*Subscript[A, c]^11 - I*((-a3m[t] + Conjugate[a3p[t]])*w + 2*(a03[t] + a30[t])*Subscript[B, c]^11); ex3 = Derivative[1][a30][t] == -2*A21*(Conjugate[app[t]] - app[t]) - 2*I*(Conjugate[a0m[t]] - Conjugate[a0p[t]])*w + 2*I*(4 + Conjugate[apm[t]] + apm[t])*Subscript[B, c]^11; ex4 = Derivative[1][a03][t] == -2*A21*(Conjugate[app[t]] - app[t]) - 2*I*(a0m[t] - a0p[t])*w + 2*I*(4 + Conjugate[apm[t]] + apm[t])*Subscript[B, c]^11; ex5 = Derivative[1][a33][t] == 2*I*((-a3m[t] + a3p[t] - Conjugate[a3m[t]] + Conjugate[a3p[t]])* w + 2*I*(Conjugate[app[t]] + app[t])*Subscript[A, c]^11 + 4*(a03[t] + a30[t])*Subscript[B, c]^11); ex6 = Derivative[1][a0p][t] == 4*I*((-I)*A21*Conjugate[a3m[t]] + a0p[t]*B22 + a03[t]*w - a0p[t]*w - I*a0m[t]*Subscript[A, c]^11 - Conjugate[a3p[t]]*Subscript[B, c]^11); ex7 = Derivative[1][a0m][t] == -4* I*((-I)*A21*Conjugate[a3p[t]] + a0m[t]*B22 + a03[t]*w - a0m[t]*w + I*a0p[t]*Subscript[A, c]^11 + Conjugate[a3m[t]]*Subscript[B, c]^11); ex8 = Derivative[1][a3m][t] == 2*I*(-2*I*A21*Conjugate[a0p[t]] - 2*a3m[t]*B22 - 2*a33[t]*w + 2*a3m[t]*w - Conjugate[app[t]]*w + apm[t]*w - 2*I*(a3p[t] + 2*Conjugate[a3p[t]])*Subscript[A, c]^11 + 2*(2*a0m[t] + Conjugate[a0m[t]])*Subscript[B, c]^11); ex9 = Derivative[1][a3p][t] == 2*I*(2*I*A21*Conjugate[a0m[t]] + 2*a3p[t]*B22 + 2*a33[t]*w - 2*a3p[t]*w - Conjugate[apm[t]]*w + app[t]*w - 2*I*(a3m[t] + 2*Conjugate[a3m[t]])*Subscript[A, c]^11 + 2*(2*a0p[t] + Conjugate[a0p[t]])*Subscript[B, c]^11); exp = {ex1, ex2, ex3, ex4, ex5, ex6, ex7, ex8, ex9}; var = {app, apm, a30, a03, a33, a0p, a0m, a3m, a3p}; rep = Table[ var[[i]][t] -> x[i][t] + I y[i][t], {i, Length[var]}]; par = {B22 -> b22r + I b22, A21 -> a21r + I a21, Subscript[A, c]^11 -> acr + I ac , Subscript[B, c]^11 -> bcr + I bc, w -> w1 + I w2}; rep1 = Table[ var[[i]]'[t] -> x[i]'[t] + I y[i]'[t], {i, Length[var]}]; rep2 = Flatten[Table[{Conjugate[x[i][t]] -> x[i][t], Conjugate[y[i][t]] -> y[i][t]}, {i, Length[var]}], 1]; exp1 = exp /. Join[rep, rep1] /. rep2 /. par; eqs = ComplexExpand[exp1]; X = Array[x, Length[var]]; Y = Array[y, Length[var]]; vars = Join[X, Y]; eq1 = eqs /. {I -> Z}; eqx = eq1 /. {Z -> 0}; eq2 = eq1 /. Z -> 1; eqy = Table[ First[eq2[[i]]] - First[eqx[[i]]] == Last[eq2[[i]]] - Last[eqx[[i]]], {i, Length[eq2]}]; ``` Finally we have 18 equations with separated real and complex part of all variables and parameters ``` eq18 = Join[eqx, eqy] ``` Now we can evaluate matrix of this equation ``` varst = Table[vars[[i]][t], {i, Length[vars]}]; {b, m} = CoefficientArrays[eq18, varst] ``` We can check how it looks like ``` m // MatrixForm b // Normal ``` We can calculate constant vector as follows ``` varst1 = Table[vars[[i]]'[t], {i, Length[vars]}]; b0 = b - varst1; ``` So our matrix equation has a form (don't try to solve it with `DSolve`): ``` eqF = varst1 == m.varst - b0; ```
31,284,003
**Updated with Code:** I have a string array in my controller like below, ``` var app = angular.module('myApp', []); app.controller('mycontroller', function($scope) { $scope.menuitems =['Home','About']; }; }); ``` I need to display it in the navigation pane (navigation should be on the leftside) Below is my html code. ``` <body class="container-fluid"> <div class="col-md-2"> <ul class="nav nav-pills nav-stacked" ng-repeat="x in menuitems track by $index"> <li>{{x}}</li> </ul> </div> </body> ``` I did get the string values bound to the navigation pane. It is showing text like {{x}}. Kindly help
2015/07/08
[ "https://Stackoverflow.com/questions/31284003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4419549/" ]
1. In your javascript code `};` is unnecessary. 2. You haven't attached `controller` to the `div`. Code. Javascript: ``` var app = angular.module('myApp', []); app.controller('mycontroller', function($scope) { $scope.menuitems = ['Home', 'About']; //}; // REMOVE THIS }); ``` HTML: ``` <div class="col-md-2" ng-controller="mycontroller"> <!-- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ --> <ul class="nav nav-pills nav-stacked" ng-repeat="x in menuitems track by $index"> <li>{{x}}</li> </ul> ```
47,832,762
I am looking for a convenient, safe python dictionary key access approach. Here are 3 ways came to my mind. ```py data = {'color': 'yellow'} # approach one color_1 = None if 'color' in data: color_1 = data['color'] # approach two color_2 = data['color'] if 'color' in data else None # approach three def safe(obj, key): if key in obj: return obj[key] else: return None color_3 = safe(data, 'color') #output print("{},{},{}".format(color_1, color_2, color_3)) ``` All three methods work, of-course. But is there any simple out of the box way to achieve this without having to use excess `if`s or custom functions? I believe there should be, because this is a very common usage.
2017/12/15
[ "https://Stackoverflow.com/questions/47832762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4112088/" ]
You missed the canonical method, [`dict.get()`](https://docs.python.org/3/library/stdtypes.html#dict.get): ``` color_1 = data.get('color') ``` It'll return `None` if the key is missing. You can set a different default as a second argument: ``` color_2 = data.get('color', 'red') ```
606,293
I don't see why the custom (temperature) command `\newcommand{\deg}{$^\circ$F}` returns a `"missing $ inserted"` error when writing something like `350\deg` in text mode. More confusingly, it compiles if I use `\renewcommand`, suggesting the command name `\deg` has already been used. But the same error is returned no matter the command name.
2021/07/25
[ "https://tex.stackexchange.com/questions/606293", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/35910/" ]
A bit off-topic, however: * Fahrenheit are not standard unit, instead it is correct to use Celsius degrees. * If you for some reason persist to use it, than is sensible to define them as part od `siunitx` package: ``` \documentclass{article} \usepackage{siunitx} % <--- \DeclareSIUnit{\fahrenheit}{^\circ\mkern-1mu\mathrm{F}} % <--- \begin{document} proposed solution: \qty{350}{\fahrenheit}; by your solution: 350$^\circ$F \end{document} ``` since its use gives typographical more correct form than it would be with your intended definition: [![enter image description here](https://i.stack.imgur.com/d2egd.png)](https://i.stack.imgur.com/d2egd.png)
28,303,972
I have a DataFrame looking like that: ``` df index id timestamp cat value 0 8066 101 2012-03-01 09:00:29 A 1 1 8067 101 2012-03-01 09:01:15 B 0 2 8068 101 2012-03-01 09:40:18 C 1 3 8069 102 2012-03-01 09:40:18 C 0 ``` What I want is something like this: ``` df timestamp A B C id value 0 2012-03-01 09:00:29 1 0 0 101 1 1 2012-03-01 09:01:15 0 1 0 101 0 2 2012-03-01 09:40:18 0 0 1 101 1 3 2012-03-01 09:40:18 0 0 1 102 0 ``` As you can see in rows 2,3 timestamps can be duplicates. At first I tried using pivot (with timestamp as an index), but that didn't work because of those duplicates. I don't want to drop them, since the other data is different and should not be lost. Since *index* contains no duplicates, I thought maybe I can pivot over it and after that merge the result into the original DataFrame, but I was wondering if there is an easier more intuitive solution. Thanks!
2015/02/03
[ "https://Stackoverflow.com/questions/28303972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4170545/" ]
Use get\_dummies. See here: <http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.reshape.get_dummies.html> StackOverflow Example here: [Create dummies from column with multiple values in pandas](https://stackoverflow.com/questions/18889588/create-dummies-from-column-with-multiple-values-in-pandas)
553,857
I need to create a PCB with a transformer on it, and in this case, I unfortunately can't solder on a regular one. I was wondering if there was anything akin to a 2d transformer, or just generally a coil I could print onto my PCB. I know that spirals are used in Radio-Applications, but I'm not sure if you could use something like this as a regular coil.
2021/03/18
[ "https://electronics.stackexchange.com/questions/553857", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/232664/" ]
They are called "Planar transformers" and they are used in the Telecom industry. <https://www.electronicproducts.com/wp-content/uploads/passive-components-magnetics-inductors-transformers-wcjh-1s-jan201618.jpg> They need a multi-layer PCB because the windings are PCB traces. In the following picture you can see the multi-layer structure of the PCB. I saw, time ago, a planar transformer printed on a 24-layer PCB. <https://upload.wikimedia.org/wikipedia/commons/thumb/5/5e/Planar_Transformer.jpg/1024px-Planar_Transformer.jpg> The soft-ferrite core is than manually added by the worker after the PCB gets populated. Often, they are manufactured and sold as single products. That is, it's very rare that people print planar transformers on the very same PCB of your final product.
24,829,726
I'm attempting to create a simple python function which will return the same value as javascript `new Date().getTime()` method. As written [here](http://www.w3schools.com/js/js_dates.asp), javascript getTime() method returns number of milliseconds from 1/1/1970 So I simply wrote this python function: ``` def jsGetTime(dtime): diff = datetime.datetime(1970,1,1) return (dtime-diff).total_seconds()*1000 ``` while the parameter dtime is a python datetime object. yet I get wrong result. what is the problem with my calculation?
2014/07/18
[ "https://Stackoverflow.com/questions/24829726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3599803/" ]
One thing I feel compelled to point out here is: If you are trying to sync your client time and your server time you are going to need to pass the server time to the client and use that as an offset. Otherwise you are always going to be a bit out of sync as your clients/web-browsers will be running on various machines which have there own clock. However it is a common pattern to reference time in a unified manor using epoch milliseconds to sync between the clients and the server. The Python ``` import time, datetime def now_milliseconds(): return int(time.time() * 1000) # reference time.time # Return the current time in seconds since the Epoch. # Fractions of a second may be present if the system clock provides them. # Note: if your system clock provides fractions of a second you can end up # with results like: 1405821684785.2 # our conversion to an int prevents this def date_time_milliseconds(date_time_obj): return int(time.mktime(date_time_obj.timetuple()) * 1000) # reference: time.mktime() will # Convert a time tuple in local time to seconds since the Epoch. mstimeone = now_milliseconds() mstimetwo = date_time_milliseconds(datetime.datetime.utcnow()) # value of mstimeone # 1405821684785 # value of mstimetwo # 1405839684000 ``` The Javascript ``` d = new Date() d.getTime() ``` See this post for more reference on [javascript date manipulation](https://stackoverflow.com/a/221297/1184492).
6,697,220
I'm writing a simple eclipse plugin, which is a code generator. User can choose an existing method, then generate a new test method in corresponding test file, with JDT. Assume the test files is already existed, and it's content is: ``` public class UserTest extends TestCase { public void setUp(){} public void tearDown(){} public void testCtor(){} } ``` Now I have generate some test code: ``` /** complex javadoc */ public void testSetName() { .... // complex logic } ``` What I want to do is to append it to the existing `UserTest`. I have to code: ``` String sourceContent = FileUtils.readFileToString("UserTest.java", "UTF-8"); ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setSource(content.toCharArray()); CompilationUnit testUnit = (CompilationUnit) parser.createAST(null); String newTestCode = "public void testSetName() { .... }"; // get the first type final List<TypeDeclaration> list = new ArrayList<TypeDeclaration>(); testUnit .accept(new ASTVisitor() { @Override public boolean visit(TypeDeclaration node) { list.add(node); return false; } }); TypeDeclaration type = list.get(0); type.insertMethod(newTestCode); // ! no this method: insertMethod ``` But there is no such a method `insertMethod`. I know two options now: 1. Do not use `jdt`, just to insert the new code to the test file, before last `}` 2. use `testUnit.getAST().newMethodDeclaration()` to create a method, then update it. But I don't like these two options, I hope there is something like `insertMethod`, which can let me append some text to the test compilation unit, or convert the test code to a MethodDeclaration, then append to the test compilation unit. --- **UPDATE** I see [nonty's answer](https://stackoverflow.com/questions/6697220/how-to-add-a-method-source-to-an-existing-java-file-with-jdt/6697997#6697997), and found there are two `CompilationUnit` in jdt. One is `org.eclipse.jdt.internal.core.CompilationUnit`, another is `org.eclipse.jdt.core.dom.CompilationUnit`. I used the second one, and nonty used the first one. I need to supplement my question: At first I want to create a eclipse-plugin, but later I found it hard to create a complex UI by swt, so I decided to create a web app to generate the code. I copied those jdt jars from eclipse, so I can just use `org.eclipse.jdt.core.dom.CompilationUnit`. Is there a way to use `org.eclipse.jdt.internal.core.CompilationUnit` outside eclipse?
2011/07/14
[ "https://Stackoverflow.com/questions/6697220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/342235/" ]
A MS SQL Server version... ``` WITH sorted_data AS ( SELECT ROW_NUMBER() OVER (PARTITION BY item_id ORDER BY item_date DESC) AS row_id, * FROM item_data WHERE item_date <= getDate() ) SELECT * FROM sorted_data WHERE row_id = 1 ```
60,190,666
I am just playing around with the setInterval function in JavaScript. I am wondering if there is a way to toggle the setInterval with an HTML button This is my code. ``` let x = 0; const listener = document.getElementById('listener'); const numberPlace = document.getElementById('numberPlace'); const numberCounter = setInterval(() => { x++; numberPlace.innerHTML = x; }, 100); listener.addEventListener('click', numberCounter); ``` The problem is that the number starts counting when the page loads and not on a button click. Please help
2020/02/12
[ "https://Stackoverflow.com/questions/60190666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12322204/" ]
``` const numberCounter = () => setInterval(() => { x++; numberPlace.innerHTML = x; }, 100); ```
40,989,468
Once the cognito-id is created for a user logging via. google, how to find the email id of the user. [![enter image description here](https://i.stack.imgur.com/hN8s7.png)](https://i.stack.imgur.com/hN8s7.png) As shown in the above picture, I can find the cognito-id, but couldn't find any other information that google could have supplied when the user logged in. Any help is appreciated. Thanks in advance,
2016/12/06
[ "https://Stackoverflow.com/questions/40989468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1422950/" ]
You've probably already tried the `?` optional followed by required positional: ``` p=argparse.ArgumentParser() p.add_argument('--foo', nargs='?',default='one', const='two') p.add_argument('bar') ``` which fails with ``` In [7]: p.parse_args('--foo 1'.split()) usage: ipython3 [-h] [--foo [FOO]] bar ipython3: error: the following arguments are required: bar ``` `--foo` consumes the `1`, leaving nothing for `bar`. <http://bugs.python.org/issue9338> discusses this issue. The `nargs='?'` is greedy, consuming an argument, even though the following positional requires one. But the suggested patch is complicated, so I can't quickly apply it to a parser and test your case. The idea of defining an Action that would work with `--foo==value`, but not consume `value` in `--foo value`, is interesting, but I have no idea of what it would take to implement. Certainly it doesn't work with the current parser. I'd have to review how it handles that explicit `=`. ============================ By changing a deeply nested function in `parse_args`, ``` def consume_optional(....): .... # error if a double-dash option did not use the # explicit argument else: msg = _('ignored explicit argument %r') #raise ArgumentError(action, msg % explicit_arg) # change for stack40989413 print('Warn ',msg) stop = start_index + 1 args = [explicit_arg] action.nargs=None action_tuples.append((action, args, option_string)) break ``` and adding a custom Action class: ``` class MyAction(myparse._StoreConstAction): # requies change in consume_optional def __call__(self, parser, namespace, values, option_string=None): if values: setattr(namespace, self.dest, values) else: setattr(namespace, self.dest, self.const) ``` I can get the desired behavior from: ``` p = myparse.ArgumentParser() p.add_argument('--foo', action=MyAction, const='C', default='D') p.add_argument('bar') ``` Basically I'm modifying `store_const` to save the `=explicit_arg` if present. I don't plan on proposing this as a formal patch, but I'd welcome feedback if it is useful. Use at your own risk. :)
48,855,223
I have tried to remove the issue by installing tether.js and utils.js, it seems when I fix one error 2 more pop up. Here is a link to a similar post but I'm having a slightly different issue, this issue that I'm having spawned out of the previous problem. Is there anything I can do? Or should I just revert back to boostrap3 [how to fix the error bootstrap tooltips require tether HTTP github](https://stackoverflow.com/questions/34567939/how-to-fix-the-error-error-bootstrap-tooltips-require-tether-http-github-h/48855088?noredirect=1#comment84713688_48855088) ``` tether.js:1 Uncaught SyntaxError: Identifier 'getScrollParents' has already been declared at tether.js:1 Uncaught Error: Bootstrap tooltips require Tether (http://tether.io/) at bootstrap.min.js?ver=3.0.0:7 at bootstrap.min.js?ver=3.0.0:7 at bootstrap.min.js?ver=3.0.0:7 ```
2018/02/18
[ "https://Stackoverflow.com/questions/48855223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7989522/" ]
You can use `ViewChildren` to reference the inputs based on index. Add template ref `#inputs` to your input field: ```html <ion-input #inputs type="text"></ion-input> ``` In your component import `ViewChildren` and `QueryList` and... ```ts @ViewChildren('inputs') inputs: QueryList<any>; ``` Then on your button click, where you call `doSomething`, in the code you presented, pass the index and set the focus on that field based on index: ```html <ion-row formArrayName="bicos" *ngFor="let item of homeForm.controls.bicos.controls; let i = index" > <button ion-button (click) = "doSomething(i)"> <!-- ... --> ``` TS: ```ts doSomething(index) { this.inputs.toArray()[index].setFocus(); } ``` [StackBlitz](https://stackblitz.com/edit/ionic-3gwv6g?file=pages%2Fhome%2Fhome.ts) ----------------------------------------------------------------------------------
41,468,745
I want to run a function based on a $scope value. In my controller, I have: ``` $scope.value = ""; $scope.selector = function(info) { if ($scope.value === "") { $scope.value = info; } else { $scope.value = ""; } } ``` The function is triggered on ng-click of different images, e.g.: `<img ng-src="..." ng-click="selector(info)">` My problem is the if-operations dont seem to work on the $scope value. I have also tried: ``` $scope.$watch('value', function(val) { if(val === "") { $scope.value = info; } } ``` This works if it is outside a function, but not if I place it in the selector function. Better approaches always welcome. Thanks for any explanations.
2017/01/04
[ "https://Stackoverflow.com/questions/41468745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5919010/" ]
Here is a version of your code. It is a little shorter and probably more straightforward. Also it returns exactly the same result as in the example. ``` let // Data source SourceTable = Excel.CurrentWorkbook(){[Name="Table1"]}[Content], Data = Table.TransformColumnTypes(SourceTable,{{"Role", type text}, {"From", type datetime}, {"To", type datetime}, {"Value", Int64.Type}}), //Get a list of roles. // Roles = {"A", "B", "C", "D"}, //Example line. Comment it Roles = List.Transform(Table.Distinct(Table.SelectColumns(SourceTable, {"Role"}))[Role], each Text.Trim(Text.Upper(_))), // Create table of all possible intervals UnionTables = Table.TransformColumnTypes( Table.Combine({ Table.SelectColumns(SourceTable, "From"), Table.SelectColumns(Table.AddColumn(Table.SelectColumns(SourceTable, "To"), "From", each Date.AddDays([To], 1)), {"From"}) //Add 1 day to ensure next interval starts at the same date to produce no fake 1-day intervals }), {{"From", type datetime}}), SortDates = Table.Sort(Table.Distinct(UnionTables), {{"From", Order.Ascending}}), AddIndex = Table.AddIndexColumn(SortDates, "Index", 0, 1), AllIntervals = Table.RemoveRowsWithErrors(Table.AddColumn(AddIndex, "To", each Date.AddDays(AddIndex[From]{[Index] + 1}, -1), type datetime)), //Substract 1 day to revert intervals to their original values AddColumns = Table.Combine(List.Transform(Roles, (Role) => Table.AddColumn(Table.SelectColumns(AllIntervals, {"From", "To"}), Role, (x) => List.Sum(Table.SelectRows(Data, (y) => Text.Upper(Text.Trim(y[Role])) = Role and ((y[From] >= x[From] and y[To] <= x[To]) or (y[From] <= x[From] and y[To] >= x[To])))[Value]), type number))), GetDistinctRows = Table.Distinct(AddColumns), FilterOutNulls = Table.SelectRows(GetDistinctRows, each List.MatchesAny(Record.FieldValues(Record.SelectFields(_, Roles)), (x) => x <> null) /*List.Match(Table.ColumnNames(AddColumns), Roles) <> null*/), AddSum = Table.AddColumn(FilterOutNulls, "Sum", each List.Sum(Record.FieldValues(Record.SelectFields(_, Roles)))), ListOfNonNullColumns = List.Select( List.Transform(Roles, (x) => if ( Table.RowCount( Table.SelectRows(AddSum, (y) => List.Sum( Record.FieldValues( Record.SelectFields(y, {x}) ) ) > 0 ) ) ) > 0 then x else null) , each _ <> null), CleanAndReorder = Table.SelectColumns(AddSum, List.Combine({{"From", "To"}, ListOfNonNullColumns, {"Sum"}})), DemoteHeaders = Table.DemoteHeaders(CleanAndReorder), Result = Table.Transpose(DemoteHeaders) in Result ```
24,955,666
I am trying to search within the values (table names) returned from a query to check if there is a record and some values in that record are null. If they are, then I want to insert the table's name to a temporary table. I get an error: ``` Conversion failed when converting the varchar value 'count(*) FROM step_inusd_20130618 WHERE jobDateClosed IS NULL' to data type int. ``` This is the query: ``` DECLARE @table_name VARCHAR(150) DECLARE @sql VARCHAR(1000) DECLARE @test int SELECT @table_name = tableName FROM #temp WHERE id = @count SET @sql = 'SELECT * FROM ' + @table_name + ' WHERE jobDateClosed IS NULL' --ERROR is below: select @test = 'count(*) FROM ' + @table_name + ' WHERE jobDateClosed IS NULL' --PRINT @sql -- EXEC(@sql) IF @test > 0 BEGIN INSERT INTO #temp2 (tablename) VALUES ( @table_name); END SET @count = @count + 1 ``` Any ideas how to convert the result of the count into an integer?
2014/07/25
[ "https://Stackoverflow.com/questions/24955666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2280087/" ]
Check for [sp\_executesql](http://msdn.microsoft.com/en-us/library/ms188001.aspx) where you may define output parameters. ``` DECLARE @table_name VARCHAR(150) DECLARE @sql VARCHAR(1000) DECLARE @test int SELECT @table_name = tableName FROM #temp WHERE id = @count DECLARE @SQLString nvarchar(500); DECLARE @ParmDefinition nvarchar(500); SET @SQLString = N'SELECT @test = count(*) FROM ' + @table_name + ' WHERE jobDateClosed IS NULL' SET @ParmDefinition = N'@test int OUTPUT'; EXECUTE sp_executesql @SQLString, @ParmDefinition, @test=@test OUTPUT; IF @test > 0 BEGIN INSERT INTO #temp2 (tablename) VALUES ( @table_name); END SET @count = @count + 1 ```
34,128,799
I have created Azure website ,and upload all OPIGNO files to that website via FTP,so when i am trying to access the `index.php` for OPIGNO project ,it returns **server error 500**????
2015/12/07
[ "https://Stackoverflow.com/questions/34128799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
1. uninstall Cloud Foundry command line... 2. delete your $HOME/.cf/\* 3. run cf installer -- install it to default C: drive download the latest version here: <https://github.com/cloudfoundry/cli/releases>
16,206,173
I'm trying to generate several files so I wrote this code where `value` get **797** but I only get one file created, why? should not be 797 files instead? what's wrong in my code?: ``` private void button3_Click(object sender, EventArgs e) { int value = bdCleanList.Count() / Int32.Parse(textBox7.Text); MessageBox.Show(value.ToString()); string bases_generadas = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bases_generadas"); for (int i = 1; i < value; i++) { string newFileName = "bases_generadas_" + DateTime.Now.ToString("dd-MM-yyyy-hh-mm-ss") + ".txt"; using (System.IO.FileStream fs = System.IO.File.Create( System.IO.Path.Combine(bases_generadas, newFileName))) { for (byte j = 0; j < 10; j++) { fs.WriteByte(j); } } } } ``` **EDIT** as @andrey-shchekin suggest I added a `i` to `newFileName` so now the code is this one: ``` string newFileName = "bases_generadas_" + i + DateTime.Now.ToString("dd-MM-yyyy-hh-mm-ss") + ".txt"; ``` But now I run the code again and `value` takes **4** but just 3 files was created: ``` bases_generadas_124-04-2013-11-45-08.txt bases_generadas_224-04-2013-11-45-08.txt bases_generadas_324-04-2013-11-45-08.txt ``` Why?
2013/04/25
[ "https://Stackoverflow.com/questions/16206173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2238121/" ]
``` string str = "123.1.1.QWE"; int index = str.LastIndexOf("."); string[] seqNum = new string[] {str.Substring(0, index), str.Substring(index + 1)}; ```
1,547,172
Let $A,B\in M\_n$ and $\left( {\begin{array}{\*{20}{c}} A & B \\ B & A \\ \end{array}} \right) \ge 0$ Why does $A \ge B$ ?
2015/11/26
[ "https://math.stackexchange.com/questions/1547172", "https://math.stackexchange.com", "https://math.stackexchange.com/users/226800/" ]
Let $x$ be given. Then $$ 0\le \pmatrix{x\\-x}^T\pmatrix{A&B\\B&A}\pmatrix{x\\-x} = 2x^TAx - 2x^TBx, $$ This implies $$ x^T(A-B)x\ge0 $$ for all $x$, hence $A\ge B$.