INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Beatifulsoup doesnt return href it returns None >>> soup_brand <a data-role="BRAND" href="/URL/somename"> Some Name </a> >>> type(soup_brand) <class 'bs4.BeautifulSoup'> >>> print(soup_brand.get('href')) None Documentation followed: < Hi people from all over the world, does someone now whats going wrong or am I targeting the object wrong ? Need to get the href.
Have you tried: soup.find_all(name="a") or soup.select_one(selector="a") it should also be possible to catch with all_anchor_tags = soup.find_all(name="a") for tag in all_anchor_tags: print(tag.get("href")) #prints the href element of each a tag, thus each link Although the all bs4 looks for multiple elemnts (the reason why we have a loop here) I encountered, that bs4 sometime is better in catching things, if you give it a search for all approach and then iterate over the elements
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "python, beautifulsoup" }
jQuery Tabs and Sliding effect - Doesn't work together **Hi,** I’m working on a website where I need a vertical tab system. I also have an arrow-image indicating which tab/thumbnail the user clicked. The arrow should slide between the two thumbnails. Have a look here: Look here - www.imterkel.com/test/index.html _Don’t freak out. The Jesus-like thumbnail is just a dummy-image from Google._ I’ve got the tabs working. And I’ve got the sliding arrow to work. But when I combine these to, it doesn’t work. I’ve also tried other jQuery Tab plugins.
I'm not entirely sure why — but changing the selector on the click binding to `$("#thumbs li a")` and grabbing the top position from the parent seems to work. My guess is that the $.idTabs plugin is canceling the event otherwise. < // Hook up the click event $("#thumbs li a").click(function() { // Get position of current image arrow.stop().animate({'top' : $(this).parent().position().top }, 500); });
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "javascript, jquery, tabs, sliding" }
Does a trailing plus sign on the left make sense in SASS I came across a piece of code in SASS similar to .foo { + .someClass { padding: 1rem; } } Plus sign obviously has a function of an adjacent combinator. Shouldn't it be written as `& + .someClass`? Is it still valid if the left of the operator is blank? Does it select `.someClass` adjacent to `.foo` or what else could be intended? Is it a good practice to omit `&` provided that it is valid?
While valid, adding an ampersand before the combinators is not necessary at all. The ampersand is only needed for attribute selectors, pseudo classes, and pseudo elements, because the real difference between those using `&` and those not (in theory) is the space in the output. Here's a good article on this.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sass, css selectors" }
git revert --continue stuck never finishes I did a git revert {commithash} in my project to go to a previous feature deployed. The merge was resolved, all the changes were added and I got into the status: > On branch develop > > You are currently reverting commit {commithash}. > (all conflicts fixed: run "git revert --continue"). > > (use "git revert --abort" to cancel the revert operation) > > nothing to commit, working tree clean I use git revert --continue and nothing happens, and I still am in the state of pending revert... Anyone knows what has gone wrong? Thanks.
When you get that "nothing to commit" message, it means that while resolving the conflicts, you chose the code that was already in the latest commit. The end result is that your revert _makes no changes to the state of the code_. The `git revert --continue` you're trying to issue can't finish the revert. You can, if you really want to, use `git commit --allow-empty` to commit this revert even though it does nothing at all. Having done that, you can then use `git revert --abort` to terminate the reversion process. It's usually a mistake to make a "no changes" commit like this one: it means that your `git revert` did not accomplish anything, so one has to wonder why you bothered.
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 11, "tags": "git, revert" }
Make Dynamic Download link WGET friendly I'm trying to make a PHP page which gets the latest version of my scripts and then initiates the download. Currently it is brower friendly but doesn't seem to be WGET friendly. Here is the PHP code: $sql = mysqli_query($mysqli, "SELECT * FROM downloads ORDER BY id DESC LIMIT 1"); $row = mysqli_fetch_array($sql); $name = $row['name']; $pathToFile = '/home/phasec/PingEZ-Downloads/'.$name.''; header("Content-Type: application/octet-stream"); header("Content-Disposition: attachment; filename=PingEZ-Latest.zip"); readfile($pathToFile); It is meant to download a ZIP file, which it does when accessing via the web address in a browser. But I need it to be browser friendly AND WGET friendly for servers.
First, ZIP file MIME-type is `application/zip`, though it should work fine with what you're specifying too. I would also suggest adding a `Content-Length` header with the size of the file, the `filesize()` function should do just fine.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "file, dynamic, download, wget" }
Is the linear span of irrep matrices a complete matrix basis? Let $G$ be a finite or compact group and $\rho: G \to \mathrm{U}(d)$ a $d$-dimensional unitary representation of $G$. If $\rho$ is irreducible then the following seems to be true: $$ \mathrm{span}_\mathbb{C} \\{\rho(g) : g \in G\\} = \mathbb{C}^{d \times d} $$ i.e., the complex linear span of $\rho(g)$, taken over all $g \in G$, coincides with the set of all $d \times d$ complex matrices. Is this claim true and does this result have a name?
This is known as Burnside's theorem. Nowadays people formulate it as any algebra of matrices over an algebraically closed field acting irreduciblly is the whole matrix algebra.
stackexchange-mathoverflow_net_7z
{ "answer_score": 5, "question_score": 3, "tags": "rt.representation theory, unitary representations" }
Space being treated as a delimiter in UNIX array I have a piece of code where I have a string delimited by / . The last element of the code is a value "Cars & bikes" But the code treats space as a delimiter and i get a wrong output. ARG="s3://this-is-my-bucket/Load/Data/Cars & Bikes" ARR=(${ARG//// }) S3=${ARR[0]} AWS=${ARR[1]} TYPE=${ARR[2]} FIELD=${ARR[3]} ITEM=${ARR[4]} echo $S3 S3: echo $AWS this-is-my-bucket echo $TYPE Load echo $FIELD Data echo $ITEM Cars **What I want the o/p be like is** : echo $ITEM Cars & Bikes Any suggestion is appreciated.
You can use `read -a` with `/` as `IFS`: s="s3://this-is-my-bucket/Load/Data/Cars & Bikes" IFS=/ read -ra arr <<< "$s" && declare -p arr declare -a arr=([0]="s3:" [1]="" [2]="this-is-my-bucket" [3]="Load" [4]="Data" [5]="Cars & Bikes") Or else you can avoid array creation and directly use variables in `read` with `IFS=/` as this: IFS=/ read -r s3 _ aws type field item <<< "$s" && declare -p s3 aws type field item declare -- s3="s3:" declare -- aws="this-is-my-bucket" declare -- type="Load" declare -- field="Data" declare -- item="Cars & Bikes"
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "arrays, linux, shell, unix" }
too many values error message in oracle I want to select some records using two tables `avion` and `vol`, but when I run my statement I get this error : > ORA-00913: too many values This is my statement : select distinct avion.avnum, avion.avnom from avion, vol where avion.avnum = vol.avnum AND vol.plnum in ( select pilote.plnum, pilote.salaire from pilote where salaire > ( select salaire from pilote where plnom ='Tsukishima' ) ) AND avion.avnom <> 'Boeing 777'; How can I solve this problem ?
Try this: select distinct avion.avnum, avion.avnom from avion, vol where avion.avnum = vol.avnum AND vol.plnum in ( select pilote.plnum from pilote where salaire > ( select salaire from pilote where plnom ='Tsukishima' ) ) AND avion.avnom <> 'Boeing 777';
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql, oracle" }
Can a paralyzed creature targeted by an Evocation Wizard's Sculpt Spells feature actually succeed a Dex save? Say a friendly barbarian is currently paralyzed. Part of the description of the paralyzed condition says: > The creature automatically fails Strength and Dexterity saving throws. Its friend, the School of Evocation wizard, casts a _fireball_ in the room, using its Sculpt Spells feature to protect the Barbarian: > When you cast an evocation spell that affects other creatures that you can see, you can choose a number of them equal to 1 + the spell’s level. **The chosen creatures automatically succeed on their saving throws against the spell** , and they take no damage if they would normally take half damage on a successful save. _Fireball_ requires a Dex save, but paralyzed creatures normally fail Dex saves; you can easily see the conundrum. **Does the Barbarian fail its Dex save?**
While these are two contrary rules exceptions, and therefore ambiguous, from a story perspective, Sculpt Spell is intended to represent the evoker guiding their damaging spell to avoid the target, so it doesn't matter if they actively dodge the attack or not; it just doesn't hit them (or at least has the minimum possible effect). So I would say Sculpt Spell overrides the condition -- the paralyzed character takes no damage, because the fireball just isn't intruding into their space. The argument could also be made that these are 'simultaneous effects' as discussed on page 77 of _Xanathar's Guide to Everything_ , in which case the character whose turn it is -- the caster -- chooses which effect happens first, so the 'sculpt spell' effect can be the last one, overriding all previous effects. But I think the conceptual storytelling aspect should be enough to make a decision in this case.
stackexchange-rpg
{ "answer_score": 62, "question_score": 44, "tags": "dnd 5e, spells, wizard, saving throw, conditions" }
Does there exist any $x\in S_{10}$ such that $x(1\ \ 2\ \ 3)x=(9\ \ 10)$? I have tried it a lot by many trial and error methods, I didn't get any such $x\in S_{10}$. One this that I can observe that $\operatorname{Order}(x)>2$, because if $\operatorname{Order}(x)=2$ then $x(1\ \ 2\ \ 3)x=x(1\ \ 2\ \ 3)x^{-1}=(x(1)\ \ x(2)\ \ x(3))\ne(9\ \ 10)$ But I even can't prove that there doesn't exist such $x$. I haven't any idea how to solve the problem. Can anybody give a solution to it? Thanks for assistance idn advance.
$x(1\,2\,3)x$ must be an even permutation. But $(9\,10)$ isn't. In general, to solve $xax=b$ in $S_n$where $a$ and $b$ are given permutations, note that this is the same as $(xa)^2=ba$, so this is soluble iff $ba$ is a square in $S_n$.
stackexchange-math
{ "answer_score": 7, "question_score": 3, "tags": "abstract algebra, group theory, symmetric groups, permutation cycles" }
get wikipedia interlinks doen't give the complete result I am trying to get the wikipeida intelinks for a specific page, looking into I could figure out the query. For example to get the links in page: Family_of_Barack_Obama: Wikipedia link: Dbpeida link: This is my query: But the results are partial, for example it gives the link to the page with title: `145th Ohio Infantry` but not `Associated Press`. I don't know why the result is incomplete? I can't find what is wrong with my query. I would appreciate any help.
You need to use the **& gpllimit=max** parameter to get all the results. Try this:
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "wikipedia, wikipedia api" }
Why doesn't 2.__add__(3) work in Python? The integer `2` has an `__add__` method: >>> "__add__" in dir(2) True ... but calling it raises a SyntaxError: >>> 2.__add__(3) File "<stdin>", line 1 2.__add__(3) ^ SyntaxError: invalid syntax Why can't I use the `__add__` method?
`2.` is parsed as a float, so `2.__add__` is a SyntaxError. You can evaluate `(2).__add__(3)` instead. * * * In [254]: (2).__add__(3) Out[254]: 5
stackexchange-stackoverflow
{ "answer_score": 21, "question_score": 14, "tags": "python, methods, int, syntax error" }
SQL Server 'Login failed for user' not recorded in error log The following exception is returned to our code during the following: m_cnn = new SqlConnection(); m_cnn.ConnectionString = sxCnn; m_cnn.Open(); \---EXCEPTION INFORMATION--- > > Exception: in OpenEx. > Msg=OpenEx failed. > Errors: Index #0 > Message: Login failed for user 'xyz'. > LineNumber: 65536 > Source: .Net SqlClient Data Provider > Procedure: > Number: 18456 > State: 1 > The problem I am having is that I cannot find this entry in the SQL error logs in order to look-up the state. For instance, we saw this exception at 11:43am today and when I go to the logs, there is no entry for that time. Is there something that we need to do in order to enable this logging? We have the 'Failed logins only' option selected in the database properties under Security | Login auditing. Yet, we see nothing in there for this issue. Any help is much appreciated.
This issue was occurring because of two main issues: 1. A few switches on our network were bad 2. We are making an obscene amount of concurrent connections to the database We have fixed 1 and the number of issues has drastically reduced. We are in the process of rewriting the connections made from apps (I actually asked another question while trying to implement a fix here)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "sql, database, sql server 2008" }
Should non-English member names be changed to English? Situation: Automatically generated memebers, such as MenuStrip items, have their (automatically generated) names based on the text entered when the item was created. My most common situation is creating a menu-strip and adding menu-items by entering their text (using the graphical designer). Since my GUI is in Hebrew, all these members have a name which contains a Hebrew string. Something like "(hebrew-text)ToolStripItem". When I create event handlers, the event handlers "inherit" the hebrew text: "(hebrew-text)ToolStripMenuItem_Click". This actually works well, IntelliSense has no problem with Hebrew text, and so does the compiler. The question is: should I change these names (or prevent them from being created in the first place)? What are the possible consequences of keeping those names? EDIT: To clarify, when I say Hebrew text, I don't mean Hebrew words written in English text, I mean actual Hebrew characters.
Always program in English. All the successful development teams I've had experience of in several EU countries do this. It makes it a lot easier if a (say) Dutch team wants to sell code to a (say) Spanish one.
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 3, "tags": ".net, code generation, non english" }
Bash case in using variable that is piped wildcard values CONDITION="*boss*|*mwc*|*puppet*|*nexus*" case in ${myvar1} ${CONDITION} ) echo HIT ;; * ) echo MISS ;; esac I have couple of issues with this: 1. Above code does not work 2. I want insensitive matches to be hit, eg. "Boss1234" or "system MWc", at the moment I know I can do eg. CONDITION=" _[mM][wW][cC]_ " but that is not very useful for longer strings.
Use `shopt -s extglob` to enable `extglob` shell option change the condition: CONDITION="@(*boss*|*mwc*|*puppet*|*nexus*)" The correct case syntax: case ${myvar1} in ${CONDITION} ) echo HIT ;; * ) echo MISS ;; esac
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "bash, wildcard, case insensitive, case statement" }
What's the difference between socket.to(id) and socket.broadcast.to(id)? I'm write an application using socket.io. I'm confused by the official document about socket.broadcast. From my testing, the below code has the same effect: socket.to(id).emit('some event') socket.broadcast.to(id).emit('some event') What's does broadcast do?
`broadcast` sets a flag in socket, Socket.prototype.__defineGetter__('broadcast', function () { this.flags.broadcast = true; return this; }); which tells the manager to omit current socket from broadcasting Socket.prototype.packet = function (packet) { if (this.flags.broadcast) { this.log.debug('broadcasting packet'); this.namespace.in(this.flags.room).except(this.id).packet(packet); } else { ... Thus `socket.broadcast.to(room)` will have the following effect: client that is connected to the `socket` will not receive the message. Whereas when `socket.to(room)` all room's clients will receive the message including the one who is connected to `socket`. I've just verified this for socket v0.9 but I doubt these mechanics are different for v1.+
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "socket.io" }
iOS Swift XMPPFramework, how to force authentication mechanism? My jabber server gives response with 3 supported methods: DigestMD5, SCRAM-SHA-1, and Plain. Is there any way to force authentication mechanism of XMPP to, for example, XMPPPlainAuthentication? Well, in android we can blacklist the mechanisms and unblock the only mechanism we need to use. Like this code in android: SASLAuthentication.blacklistSASLMechanism("SCRAM-SHA-1"); SASLAuthentication.blacklistSASLMechanism(SASLMechanism.DIGESTMD5); SASLAuthentication.blacklistSASLMechanism(SASLMechanism.EXTERNAL); SASLAuthentication.blacklistSASLMechanism(SASLMechanism.GSSAPI); SASLAuthentication.unBlacklistSASLMechanism(SASLMechanism.PLAIN); Any thoughts?
When i was trying to look for it, i tried to find it out inside the XMPPFramework code about how they use authentication when they already have received lists of supported mechanisms. And then it is dead simple, for example if you want to use XMPPPlainAuthentication with password, instead of using this code `xmppStream!.authenticatWithPassword(passwordString, error: &error) ` try to use this one `let auth = XMPPPlainAuthentication(stream: xmppStream, password: passwordString) xmppStream!.authenticate(auth, error: &error) ` that's what i did.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "ios, xmppframework" }
Dynamically load a detail-template with sub-menu and nested view in expandeble table row I'm building a webpage with Angularjs and Django. There is a main navbar in the top and a main div for the content. Click "list" and load a list of objects as a table with the ng-repeat. Basic single page app. But each row will have a empty hidden row with no content under it. When I click the row I want to dynamically get a detail-template inside the extra row and display it. This detail-template would have a detail-sub-menu (extra info, files, comments, etc) and a small detail-sub content to display in. (So I dont have to load every objects extra content at the list level) Is this kind of nesting possible with Angular or should I go with another framework?
What you are looking for is a `directive` there is a kind of a directive that is template expanding, meaning you can add in your template together with its functionality by just simply adding your custom element `<your-element></your-element>` Here's the the official docs , look for the `element` one
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "angularjs" }
Is there any wmctrl alternatives on OS X? Is there an alternative of wmctrl on OS X? It seems that wmctrl (installed from Homebrew) only works for X Applications on OS X.
You can do some of the things wmctrl can do on OS X via AppleScript. Here is an example. Do some research into AppleScript. It can be very useful. Also, there is an application called stay. Definitely doesn't have near as many options as wmctrl, but who knows, it might be all you need. **Edit:** Per askers request, here is a free one! ShiftIt. I still recommend AppleScript, it is the hardest of the three to master, but it is also the most powerful.
stackexchange-superuser
{ "answer_score": 2, "question_score": 5, "tags": "macos, wmctrl" }
.htaccess - two conditions – for https and for non-https subdomain I have a ssl certificate for my site. I’m using htaccess to redirect everyone to the https url of my site. ie anyone typing in ` or just `www....` will get redirected to the https address. That all works fine. But now I’ve created the subdomain ` This is not ssl protected. So I need this url not to get redirect to the https This as what i currently have as my htaccess: Header set Strict-Transport-Security "max-age=31536000; " RewriteEngine On RewriteCond %{HTTP_HOST} ^example.com [NC] RewriteRule (.*) [L,R=301,NC] RewriteCond %{HTTP_HOST} ^blog.example.com [NC] RewriteRule ^(.*)$ [R=301] Tried quite a few things but doesn’t work. have been searching other questions on here but their solutions dont seem to work. any help? Thanks
try: Header set Strict-Transport-Security "max-age=31536000; " RewriteEngine On RewriteCond %{HTTPS} off RewriteCond %{HTTP_HOST} !blog\.example\.com$ [NC] RewriteCond %{HTTP_HOST} ^www\. [NC] RewriteRule ^(.*)$ [L,R]
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": ".htaccess, ssl" }
Proof problem with connected graphs, weights and spanning trees Let $G$ be connected and weighted graph, and let the weight of edge $e$ be strictly larger than the weight of any other edge. Prove that edge $e$ belongs to some spanning tree with minimal weight in graph $G$ if and only if edge $e$ is a bridge. I have a hard time with graphs because I always tend to miss some details with the proofs or get stuck on having too many different options to do them. So any help will be greatly appreciated.
One direction is trivial; here’s a HINT for the other. Suppose that $e$ is not a bridge and that $T$ is a spanning tree of $G$ that includes $e$. Deleting $e$ from $T$ breaks $T$ into two connected components that between them include all of the vertices of $G$. Show how to use those components to get a spanning tree whose weight is less than that of $T$.
stackexchange-math
{ "answer_score": 4, "question_score": -1, "tags": "discrete mathematics, graph theory" }
How to create link_to from Ruby/Non-ruby-mixed string In my view file (*.html.erb), I would like to create a link that shows two model datapoints (name and vote count). In the case of Bobby, who has five votes, it would look graphically like: Bobby(5). How do I do this with a link_to, given that the string I want to show includes non-ruby parentheses? Before turning it into a link, the code is, <%= user.name %>(<%= link.user.reputation_value_for(:votes).to_i %>) Thanks very much for your help!
Try this: <%= link_to "#{user.name}(#{user.reputation_value_for(:votes).to_i})", whatever_path %> When building a string with ruby code in it, just type it normally and put the ruby code you need in between this: #{} When the page loads, the erb is compiled first and in my string above #{user.name} will be replaced with Bobby and #{user.reputation_value_for(:votes).to_i} will be replace with 8 (if that's his reputation value) giving you Bobby(8)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ruby on rails, view" }
Prove that for $a_k>0,$ if $\sum a_k^2$ converges, then $\sum \frac{a_k}k$ converges. Prove that for for $a_k>0,$ if $\sum a_k^2$ converges, then $\sum \frac{a_k}k$ converges. I was given this in an introductory calculus class, where I was only taught the basic convergence tests. I’ve tried limit comparison, power series, direct comparison, all to no avail. I have tried proving the contrapositive, using integrals as well, but the limit comparison with any series I’ve tried just goes to 0 or infinity which is inconclusive. My searches on MSE just yield the simpler problem of “if$\sum a_k$ converges then prove $\sum a_k^2$ converges“, and searches on google turned up nothing. Thank you for any help.
$a^2+b^2-2ab=(a-b)^2\ge0$ hence, $ab\le \frac{a^2+b^2}{2}$. Hence, for any $n$ you have that $0\le \frac{a_n}{n}\le\frac{a_n^2+\frac{1}{n^2}}{2}$, so $$0\le \sum_{n=1}^\infty \frac{a_n}{n}\le\frac{1}{2}\left(\sum_{n=1}^\infty a_n^2+\sum_{n=1}^\infty \frac{1}{n^2}\right).$$ So, if $\sum a_n^2$ converges, so it does $\sum\frac{a_n}{n}$.
stackexchange-math
{ "answer_score": 8, "question_score": 1, "tags": "sequences and series" }
Describe REST service What is the most standardized form how to describe a very simple REST service producing JSON responses? Something what WSDL is for XML (but here WSDL would be an obvious overkill and not recommended).
Responses from a REST service should be self-describing so having a separate description document would be redundant.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "xml, json, web services, rest, wsdl" }
Corpus with many elements to dataframe and then save in csv I have a set of 9 csv files and I use the commands below to import them and do some data preprocessing: library(tm) filenames <- list.files(getwd(),pattern=”*.txt”) files <- lapply(filenames,readLines) docs <- Corpus(VectorSource(files)) Then i removed stop words. Now, I have a corpus with 9 elements. I need to save them in 9 separate CSV files. Does anyone know how to do it?
You can use `writeCorpus(docs)` to write your corpus to 9 separate `.txt` files. You can consequently convert these to `.csv` if you like.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "r, csv, corpus" }
regex to match page[0-9] and nothing before or after I have a regex but it's not quite working the way i want page[0-9]* /pages/search.aspx?pageno=3&pg=232323&hdhdhd/page73733/xyz In the above example, the only thing I want to match is `page73733`. But my regex matches the page in `/pages` and it matches page in pageno=3 i also tried `page[0-9].*`, then it matches `page73733` but it also matches everything that comes after it so that it actually matches `page73733/xyz` page[0-9].*[^a-zA-Z&?/=] That seems to do what i want, but that also seems like a ugly way to do it. Plus if i had something like `/page123/xyz/page456` it'll match that whole string. So is there a better way to do this? I want to match ONLY the string page when it is followed by any number of digits, and if anything comes after the digits it should stop.
You almost got it. Just use + instead of * as that will force a match that has numbers after it. Another way to type that expression would be /page[0-9]+ note the / , this would be helpful because without it you might get a match with something like "notApage123"
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "asp.net, regex, c# 4.0" }
Merge result of two cells if have the same column flag I have the following table structure: Number Type Year ------ ---- ---- 10 a 2000 20 b 2000 20 b 2000 10 c 2001 where I want to merge the results of cells where the column flag is the same. For example the two cells for type b, have two separate results, 20 and 20, both in the same year. I would like to end up with a data frame like this: Number Type Year ------ ---- ---- 10 a 2000 40 b 2000 10 c 2001 I can only seem to "melt" columns together at the moment. Can anyone help?
aggregate(yourdata$Number,by=list(Type=yourdata$Type,Year=yourdata$Year),sum)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "r, merge, dataframe" }
iPhone provisioning: Certificate does not install key in keychain I need help: My profile expired and I can't renew it - don't know why. I deleted everything, set up everything new but nothing worked so far… When I double click the certificate, it will put this one into the keychain under ceritficates, but not install the private and the public key. Error message is: Xcode could not find a valid private-key/certificate pair for this profile in your keychain. Does anyone know a solution? Thanks in advance.
The certificate isn't meant to install the public/private keys; they're not included in the certificate. If you've deleted them and not kept a copy around then you'll need to generate a new pair and resubmit to Apple to generate a new certificate.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "iphone, ios, certificate, provisioning, keychain" }
How to make an image round using CSS2.1? I am using flying-sauccer version 9. It uses itext version - 2.1.7 (Free license). This iText version uses CSS2.1 I have a requirement to round an image. CSS3 has the border-radius property which works but what shall i do to achieve the same in CSS2.1?
Image overlapping workaround worked though. CSS applied to both images: img{ height: 225px; left: 50%; top: 20%; position: absolute; } Individual image tags: <img style="width: 227px; height: 227px;z-index: 1;" src="{path to file}/circleImage.png" /> <img src="{path to picture}/picture.jpg" /> check the image below(It might not be visible, you may download and see.) ![Circle Image with hollow in between]( Hope this helps some one.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "html, css, itext, flying saucer" }
Computing likelihood / AIC from correlations I would like to compare prediction qualities of three different dynamical models (model A has three free parameters, model B has two free parameters and model C has zero free parameters). To achieve this I computed correlation coefficients between simulated and empirical time series for each model and tested parameter set. Now I would like to compute Akaike's information criterion for each model to formally compare the three models. How do I compute the (maximum of the) likelihood function for each of the three models using the obtained correlations coefficients between simulated and empirical time series?
To calculate an AIC, you need a likelihood. Correlation coefficients are not a likelihood (crucially, they don't change when you change the data size, while the likelihood is proportional to the number of observations). Here is an example of how to define a likelihood for a dynamical model < Note that you will have to recalibrate your model parameters, as the parameters might depend on the definition and parameters of your error term, which is part of the likelihood. For a time-series model, you should probably specify a likelihood that accounts for autocorrelation, e.g. AR1
stackexchange-stats
{ "answer_score": 1, "question_score": 0, "tags": "model selection, likelihood, aic" }
Drop event in backbone view I'm trying to add a `drop` event in my backbone view but I can't get it right. Below is the code I'm using and you can also check out this jsfiddle. var View = Backbone.View.extend({ events: { 'drop .dropzone': 'drop' }, drop: function(e) { e.preventDefault(); alert('Dropping'); }, initialize: function() {}, render: function() {} }); $(function() { var view = new View({ el: $('.dropzone'); }); });​
if your view's el == .dropzone then you should do events: { 'drop': 'drop' }, if you specify just event type without selector it will listen to event on the view's root element - $('.dropzone') in this case. The way you did it here would try to find .dropzone element among children of .dropzone element - and clearly it would fail to find this element at all
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, backbone.js, backbone events" }
Altering item data from store_order_item_add hooks (_start or _end) I'm not sure if is deliberate, but the way hooks have been implemented in Exp:resso Store don't seem to allow the modification of data? Using pass by reference has no effect (because of EE's hook calling approach?); any changes made to the data passed in the params is not available in the same variables in the hook calling method. And there doesn't seem to be any point returning data from the extension method because there is no assignment in the Order model's addItem method, where the hook is called. Are the hooks designed to expose data for reading-only? If I have to start hacking the Store logic code to add an assignment, or messing about modifying the records in the database, then the likelihood of functionality breaking with an update is high. I'm disappointed this type of situation wasn't envisioned by the module developers. Why limit the hooks like this?
I have often used `store_order_item_add_end` to modify product attributes. `$item` is an object, and pass by reference does indeed work in this context. So this code in your extension should change every item's price to $20: $item->price = '20.00'; I have several sites doing this for items which I have javascript-driven price configurations for, and for which I want to confirm server-side to protect from being artificially modified in the browser.
stackexchange-expressionengine
{ "answer_score": 2, "question_score": 2, "tags": "expresso store, hook" }
Problem with Git Repository in Xcode 4 In my iPhone app, I am using the in-built Git repository of Xcode 4 so that all the team members can work on the same project. Now the problem is that even after I commit my changes to the repository, It still shows modified (M) symbol in front of the committed file. What could be wrong? I want to ensure that once I commit the changes it should not show "M" for that file. Is there any setting which I have to do to make it work fine? What can be done?
The built-in Git repository is a local repository only. How do you share that with your team? If you hooked that repository to GitHub, for example, you will experience problems as the implementation is not 100% reliable. I would use the command line in this case and git add/commit/push the changes. There are discussions and tutorials in the GitHub Blog.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "iphone, objective c, xcode, git, xcode4" }
Как проверить тип переменной Необходимо проверить является ли переменная x числом. Пробовал if (typeof x != "number") { console.log('Не число') } else { console.log('Число') } Но оно не работает. Оно всегда пишет "Не число". Как можно проверить переменную?
var year = prompt('Write a number'); if (year.replace(/\s/g, '').length === 0 || isNaN(year)) { alert('Не число!'); } else { alert('Число!'); }
stackexchange-ru_stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "node.js" }
How do I get JSON data using Sencha New to Sencha, I am using the following code to try to get JSON data. For some reason, it returns null, yet I know the URL is returning values, as I am using it in another project. // Make the JsonP request Ext.data.JsonP.request({ url: ' crossDomain: true, type: "GET", dataType: "json", callbackKey: 'jsoncallback', callback: function(successful, data ) { alert( JSON.stringify(data) ); } }); Can someone please point out what I am missing.
You need to add scope:this property to call callback function, try like this. Ext.data.JsonP.request({ url: ' crossDomain: true, type: "GET", dataType: "json", callbackKey: 'callback', scope: this, callback: function (response, value, request) { var result = Ext.decode(response.responseText); alert(result.propertyName); } });
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "extjs, jsonp" }
Primitive type casting I have been working with Java's byte primitive lately, and I came across a silly problem: byte a = 10; byte b = 9; byte c = 8; b += b*c; // how come this statement is correct without any explicit type casting b = b*c; // while this statement is incorrect; it requires explicit cast, of course b = b+(b*c); // this is wrong too. So my question is, does `+=` specify any assignment other than just add and assign, or is this a bug in Java (which I am almost sure is not)?
Because `b += b*c` is equivalent to `b += (byte) ((b) + (b*c))`. From the Java language specification on compound assignment operators: > A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 2, "tags": "java" }
How to use BSKeyboardControls on Swift project? How can i use this lib which name BSKeyboardControls on swift project? < The problem is i don't know how to convert this part [self setKeyboardControls:[[BSKeyboardControls alloc] initWithFields:fields]]; [self.keyboardControls setDelegate:self]; into swift. How to fix this? Thanks!
Assuming the code lives inside a view controller that implements the `BSKeyboardControlsDelegate` protocol, we first add a `keyboardControls` property to the view controller to hold a reference to the keyboard controls: class SomeViewController: UIViewController, BSKeyboardControlsDelegate { var keyboardControls: BSKeyboardControls? // Here's our property // Remaining view controller code here... } (It's an Optional, with the trailing question mark, because it will be nil before we set it.) Then, assuming you have an array called `fields` that contains the fields you're working with, we can translate the two lines in question as follows: self.keyboardControls = BSKeyboardControls(fields: fields) self.keyboardControls?.delegate = self
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "ios, objective c, swift" }
Render Menu using embed token Is it possible to render a menu in a block or a node's body using [embed] or any similar token? What I want to achieve is to render the main menu in a custom block. I don't want any solution that involves PHP or changes in source code. Token seems like a good option but I'm unable to find a token to render the main menu. Thanks for the help in advance!
There is no way to achieve that without coding, you have to create your own module, which will create this token (implementing hook_token_info and hook_tokens) - see example here - < EDIT: I created a simple module out of this - Token Menu Render.
stackexchange-drupal
{ "answer_score": 1, "question_score": 1, "tags": "routes, tokens, nodes" }
Iterating through a ViewBag list in MVC 5? I have a dropdown list (ViewBag) of items and I want to extract the last item. How can I do that in my razor view? Also, is there a way to find the index of a specific item in the ViewBag?
Assuming **Items** as your ViewBag property, you need to do following to get last item: var lastItem = ViewBag.Items[ ViewBag.Items.Count-1];
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, asp.net mvc, razor, asp.net mvc 5" }
JavaScript: Using await to make asnyc code look more synchronous I am trying to understand the asnyc await functionality. Therefore, i want to use an asnyc function, resolve it and do the following logs _sequentially afterwards_. How do I achieve this? Or am I understanding something fundamentally wrong? const test = async function() { console.log('hi 1'); await setTimeout(() => { console.log('timout1') }, 1000); console.log('hi 2'); console.log('hi 3'); } test() **Result** hi 1 hi 2 hi 3 timout1 **Expected Result** hi 1 timout1 hi 2 hi 3
You can use `await` for promises only and the `setTimeout` function doesn't return a Promise. However you can await a Promise that is resolved using `setTimeout` like so which will give you the desired result. So, the function execution will halt untill either the Promise being `await`ed gets resolved or gets rejected and then continue. const test = async function() { console.log('hi 1'); // return a new promise resolved after setTimeout callback is fired await (new Promise((resolve, reject) => { setTimeout(() => { console.log('timout1') resolve() }, 1000) })) console.log('hi 2'); console.log('hi 3'); } test() Hope this helps !
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript, asynchronous" }
A discrete optimal control problem I've been looking into control theory recently, but have been struggling to find ways to solve a particular question of mine. It seems to be formulated as a discrete optimal control problem with constraints, and either I'm looking in the wrong places, or there isn't much on it. I've put together this toy example to illustrate. Let's say dynamics are governed by the recursive relationship, $$y(t+1)=y(t)\cdot e^{-x(t)}$$ $$y(0)=y_0$$ and you can control the value of $x$ at each timestep. For some maximum time $T \geq 1$, is it possible to find $[x_0, ..., x_{T-1}]$ that minimizes $y(T)$ s.t. $\sum_{i=0}^{T-1} x_i = c$, for some constant $c$? I've just quickly put together this example, so there may be a trivial solution here, but in general, are there methods (outside of maybe reinforcement learning) to solve these types of problems? If so, what are they?
In the case of your example system it doesn't matter what you choose for $x(t)$. Namely, by recursively substituting in the discrete dynamics one gets \begin{align} y(T) &= y_0 \cdot e^{-x_0} \cdots e^{-x_{T-1}},\\\ &= y_0 \cdot e^{-(x_0 + \cdots + x_{T-1})}, \\\ &= y_0 \cdot e^{-c}. \end{align} In the general case one can, as RobPratt also suggested, use dynamic programming, but this does require you to discretise the values each $x(t)$ can have. Such discretization does mean that one usually doesn't obtain the exact optimal solution. One can also use more general optimization techniques, using Lagrange multipliers for the constraints. This approach can also be used to derive the discrete time equivalent of Pontryagin’s maximum principle, see slide 4 of these lecture slides.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "control theory, recursive algorithms, optimal control, discrete optimization, constraints" }
Create project from existing code issue I'm trying to open an existing project into Idea Community Edition (it is a netbeans project). I tried using create project from existing code. One of the modules ends with .Lib (something like MyApp.Lib). For some reason Idea doesn't import that module, and even if I try to create a project with just that module it doesn't let me (it doesn't even show up in the directory browser, even though that it is there if I check with windows explorer). I'm guessing it has to do something with the Lib at the end, probably it considers it as a library folder. Does anyone happen to know a way around this? Renaming the module is not an option, as it is under version control.
I found the solution to this. Needed to remove .lib from the `Ignore files and folders` in the `Settings>File Types` section.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "intellij idea, project" }
Need to embed a "confirmation link" in an email sent from AS3/PHP So a component in an app I'm currently developing sends a confirmation email to whoever the user puts in as their "emergency contact" which simply states that the user has chosen them to be the contact. **What I also want to do, which is what I'm stuck on, is embed a URL in the email that the "emergency contact" would click to confirm that they are fine with being the contact.** Once clicked, the status "confirmed" in the database would have to change to "true", and from there the app can act differently based on an (if confirmed == true) kind of thing. Everything is currently built in AS3, with PHP and SQL acting as the backend user database (URLLoader being the connection between AS3 & PHP). If anyone needs me to be more clear, or give a better example of what I currently have just let me know.
For anyone else wondering how to send a confirmation code, check & validate confirmation etc.. this is a really good link that I ended up referencing, which really helped! **< Kudos to Irwan who wrote it.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "php, mysql, actionscript 3, email, confirmation" }
How to get request country using JavaScript? I need to retrieve requesting country using JavaScript or a free 3rd party service. Anyways, do you know how I can simply get information like country, city, etc. from latitude and longitude values?
Use this web service that can return JSON (along with using fetch API to make things simpler) let apiKey = '1be9a6884abd4c3ea143b59ca317c6b2'; fetch(' + apiKey) .then((res) => res.json()) .then((data) => { console.log(JSON.stringify(data, null, 2)); });
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "javascript" }
Does an ethernet checksum include padding bits? For ethernet II (aka ethernet DIX) frames that are padded to contain 64 bytes total, is the checksum in the last 4 bytes computed with the padding bits as input?
Yes. The whole point of the CRC is to verify the integrity of the frame on the medium.
stackexchange-networkengineering
{ "answer_score": 2, "question_score": 3, "tags": "ethernet, layer2" }
Add 'TimeOut' parameter to 'Func<>' in C# 4.0 Using `C# 4.0` features I want a generic wrapper for encapsulating functions and add a `TimeOut` parameter to them. For example we have a function like: T DoLengthyOperation() Using `Func` we have: Func<T> This is good and call the function even `Sync` (`Invloke`) or `Async`(`BeginInvoke`). Now think of a `TimeOut` to be added to this behavior and if `DoLengthyOperation()` returns in specified time we have `true` returned, otherwise `false`. Something like: FuncTimeOut<in T1, in T2, ..., out TResult, int timeOut, bool result>
Implement C# Generic Timeout
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "c# 4.0, timeout, func" }
Can I use scikit learn's cross_val_predict with cross_validate? I am looking to make a visualization of my cross validation data in which I can visualize the predictions that occurred within the cross validation process. I am using scikit learn's cross_validate to get the results of my bayesian ridge model's (scikit learn BayesianRidge) performance, but am unsure if my plot using cross_val_predict expresses the same predictions? My plot is a one-to-one plot of the predicted labels that occurred during cross validation versus the observed labels the model trained on. I use the same number of folds in both cross_validate and cross_val_predict. Basically, I just want to know if the plot I make with cross_val_predict can be described by the returned performance metrics from cross_validate? Thanks for the help
No, the folds used will (almost surely) be different. You can enforce the same folds by defining a CV Splitter object and passing it as the `cv` argument to both cross-validation functions: cv = KFold(5, random_state=42) cross_validate(model, X, y, cv=cv, ...) cross_val_predict(model, X, y, cv=cv, ...) That said, you're fitting and predicting the model on each fold twice by doing this. You could use `return_estimator=True` in `cross_validate` to retrieve the fitted models for each fold, or use the predictions from `cross_val_predict` to generate the scores manually. (Either way though, you'd need to use the splitter object to slice to the right fold, which might be a little finicky.)
stackexchange-datascience
{ "answer_score": 1, "question_score": 0, "tags": "scikit learn, regression, visualization, cross validation" }
Get highest zorder object from matplotlib figure Given a matplotlib figure or plot, how can I retrieve the value of the highest zorder object? For instance, retrieving the value of `5` in this example: import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots(1) ax.plot(np.arange(10), np.arange(10), zorder=5, linewidth=5) ax.plot(np.arange(10), np.arange(10)[::-1], zorder=1, linewidth=5) # implement: get_maximum_zorder(ax) ![enter image description here](
This can be done by accessing the axes's children, each of which has a `zorder` attribute. max([_.zorder for _ in ax.get_children()])
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "python, matplotlib" }
how to use iphone simulator 5.1 in xcode 4.6.2 I install xcode 4.6 in my mac and I want to use simulator 5.1 in my xcode. I could put iphone simulator 5.1 in my new xcode but when use xcode this simulator dont show in my xcode. **I want run my project with iphone simulator 5.1 not iphone 6.1 simulator.** I have xcode 4.4.1 and 4.6.2 setup. this is my simulator and xcode picture : !enter image description here !enter image description here
It seems that you have the 5.1 simulator but you're targeting your app for the 6.1 Select your project -> Targets -> Summary tab -> And set the Deployment Target to 5.1
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ios, xcode, ios simulator" }
How to add image to view programmatically? Say you have a `UIImage *image` and a `UIView *v` How would you display the image on top of the view programmatically?
If you just want to add the UIImage to the UIView then you need an UIImageView inbetween the UIView and UIImage, such as: UIImage *image = [[UIImage alloc] init]; UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)]; UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)]; [iv setImage:image]; [v addSubview:iv]; Note that the above is just dummy code and I've created all UI elements with a zero frame.
stackexchange-stackoverflow
{ "answer_score": 24, "question_score": 12, "tags": "uiimage" }
Divide Notation for Sets? In the book "Abstract Alegbra" by Dummit and Foote, on page 260, problem 41c states: An ideal Q of R is primary iff every zero divisor in R/Q is a nilpotent element of R/Q. What does the `R/Q` notation stand for? I have seen it used with other sets, and cannot seem to find an answer online.
This is the quotient set, or in this case the quotient ring. If $E$ is an equivalence relation on $X$ then $X/E$ is the set of equivalence classes. In this context (and others like it) $R$ is a ring and $Q$ is an ideal which induces an equivalence relation on $R$. Therefore $R/Q$ is the set of equivalence classes from that induces relation, and it turns out that the operations of $R$ sort of "translate" naturally to make $R/Q$ a ring as well, which is called the quotient ring.
stackexchange-math
{ "answer_score": 3, "question_score": 1, "tags": "elementary set theory" }
What is the limit of $2x/(x^2+\epsilon^2)$ in the distributional sense? What is the limit of $2x/(x^2+\epsilon^2)$ in the distributional sense, as $\epsilon\to 0$? For any $\phi\in C_c^\infty(\Bbb R)$, $\int \frac{2x}{x^2+\epsilon^2}\phi(x)dx\to what$? as $\epsilon\to 0$? then we have the limit. If the limit do not have an explicit formula, how can we show the convergence of $2x/(x^2+\epsilon^2)$ in the distributional sense.
A rigorous treatment isn't very hard: Let $u_\epsilon(x) = \frac{2x}{x^2+\epsilon^2}$ and take $\phi \in C_c^\infty(\mathbb R)$. Then $$ \langle u_\epsilon, \phi \rangle = \int \frac{2x}{x^2+\epsilon^2} \, \phi(x) \, dx = \int \left( \ln |x^2+\epsilon^2| \right)' \, \phi(x) \, dx \\\ = \\{ \text{ partial integration } \\} = - \int \ln |x^2+\epsilon^2| \, \phi'(x) \, dx \\\ = \\{ \text{ $\ln |x^2+\epsilon^2|$ converges to integrable function $\ln |x^2|$ } \\} \\\ \to - \int \ln |x^2| \, \phi'(x) \, dx = - 2 \int \ln |x| \, \phi'(x) \, dx = - 2 \, \langle \ln |x|, \phi' \rangle \\\ = \\{ \text{ definition of distributional derivative } \\} \\\ = 2 \, \langle \left( \ln |x| \right)', \phi \rangle = 2 \, \langle \operatorname{pv} \frac{1}{x}, \phi \rangle = \langle 2 \operatorname{pv} \frac{1}{x}, \phi \rangle $$
stackexchange-math
{ "answer_score": 3, "question_score": 2, "tags": "distribution theory" }
Principal points of rectified images in opencv In Open, I have calibrated my cameras using stereo calibration function. then I have rectification left and right images. Until now, everything is working well. But I don't know how to get the principal points of images for the left and right camera. I need them for triangulation the features from left and right images. I have extrinsic and intrinsic parameters of the camera but I don't know how to calculate these principal points of rectified image.
When you do rectification you get projection matrix in the new (rectified) coordinate systems, P(0, 2) and P(1, 2) should correspond to cx and cy(principal points) . Proof: `P = [KR, -Kt]`, since rectified therefore `R = I` , hence `P = [K, -Kt]`.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "opencv, triangulation, stereo 3d, calibration, principal" }
cancan authorization rule I have a cancan authorization problem. My scenario is like this. User has_one Student In StudentsController I have I get user and student like this @user = User.where(:username => params[:username]).first @student = @user.student Now how can I write cancan authorization rule to edit/update **@student record** so that the **logged user can only edit his student record** , provided that **@user** may or may not be the logged in user. Its just the user with the username form params. I hope the question is clear :) Thanks
Check out the wiki for CanCan: < You should be able to define that ability in the ability model by doing something like: can :edit, Student, :user_id => user.id
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ruby on rails, authorization, cancan" }
does ejb commits on connection? i am using session bean in my application and transaction is controlled at EJB layer only. The problem that i am facing is with some commit. I am using the same connection as used by EJB to insert into one table, but if the transaction is committed then that insert is not committed into the database.. can any one help me with the problem..
I'm not an EJB expert, I usually work with plain old java objects, but... Your problem probably has to do with the fact that EJBs don't do transaction management on the connection level. They use the Java Transaction Service to create transactions that can use multiple connections. So for your insert to become part of the EJB's transaction you have to obtain that transaction from the transaction server and make your insert part of that transaction. I believe that how you do this exactly depends on what kind of EJB environment you have (EJB2 or 3 and so on) But if your in an EJB environment and want to insert stuff within the same transactions as a EJB does its stuff, would it not make sense to also make an EJB for the table that you want to insert into and let the application server figure it out?
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "java, transactions, ejb" }
Finding mid-point of $BC$ if point $A$, orthocenter and circumcenter are given in a triangle > If in a triangle $ABC$, $A \equiv (1,10)$, circumcenter $\equiv (-\frac13, \frac23)$ and orthocenter $\equiv (\frac{11}3, \frac43)$ then the coordinates of mid-point of side opposite to A is? ![enter image description here]( Here clearly point $Q$ is circumcenter and point $P$ is orthocenter. The only thing I see here is $AP ||DQ$. So their slopes are same. So we can get an equation using this. But how am I supposed to get another equation? Any other way of solving this problem would also be appreciated.
**Hint:** $~$ You were given the orthocenter _H_ and the circumcenter _O_. But what were you **not** given ? The centroid _G_. Now, do you, by any chance, know that the latter is found on the segment uniting the former two, and, not only that, but it divides said segment in a ratio of $1:2$ ? $($Remember that the centroid also divides each median into the same ratio as well$).$ In other words, $G\in(OH)$ and $GH=2GO.~$ At the same time, $G=\dfrac{A+B+C}3,~$ and $M=\dfrac{B+C}2.$
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "analytic geometry" }
Is compressing data prior to encryption necessary to reduce plaintext redundancy? As explained in William Stallings' Book, in PGP encryption is done after compression, since it reduces redundancy. I couldn't relate encryption strength with redundancy. Could anyone explain more on that?
There is at least one way in which compression can _weaken_ security; it has to do with the fact that essentially all methods of encrypting arbitrarily long message will inevitably leak information about the length of the input. The only way to avoid this leak is to pad all messages to a constant length before encrypting them -- but if the messages are compressed, the compression will change their length in a way that will depend on their content, which may allow an attacker to obtain information about the content based on the length of the ciphertext. For a practical example of such an attack, see e.g. "Uncovering Spoken Phrases in Encrypted Voice over IP Conversations" by Wright _et al._ (2010).
stackexchange-crypto
{ "answer_score": 21, "question_score": 20, "tags": "encryption, cryptanalysis, pgp, compression" }
Download parent pom from remote repository Is it possible (and how) to download the parent pom from a remote repository? Why? I have a project setup with many modules. The parent pom specifies dependencies to third-party jars. If one of the modules needs a new feature in a later version of one of the jars, I'd like to: * update the parent pom with reference to the new jar * update the single module pom referring to the new parent pom. However, this breaks the build for all other modules depending on the older parent pom. I get the error message Non-resolvable parent POM: Could not find artifact company:modbase:pom:2.0.6 in mirrored.repo.com (http:((mirrored.repos.com/pub/java/maven2) and 'parent.relativePath' points at wrong local POM ... The desired older parent pom is deployed at a remote maven repository specified in the pom file, however, maven tries to search in a repo specified as mirror in settings.xml.
Just make a separate maven module out of the parent pom and after changing it make a new release which results in a new version which can be used as parent in other modules.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 4, "tags": "maven 3" }
JSON Validation and parsing in PHP I am parsing JSON using the following example php syntax $carModel = strip_tags($_REQUEST['car']['model']); The only problem is that some times the "model" array is missing from the provided JSON. When this is the case my php script shuts down when it reaches that line. Can any one recommend a way to check for the model array before parsing so that my php scrip will still run if "model" isn't present.
Just check to see if it's there. If not assign a default value to it: $carModel = (isset($_REQUEST['car']['model'])) ? strip_tags($_REQUEST['car']['model']) : '';
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "php, json, validation, parsing" }
Direct wrapper to function in C++ class I am trying to make a function which can be called as a class member. Here is some code: #include <iostream> using namespace std; class CTest; void CTestSum(CTest* ptr, int a, int b); class CTest{ public: int i; void sum(int a, int b); CTest() : i(0), sum(CTestSum) { } }; void CTestSum(CTest* ptr, int a, int b) { ++ptr->i; cout << (ptr->i)+a+b << endl; } int main() { CTest instance; instance.sum(2, 4); return 0; } Eventually, the function will end up in a dll or library. See also < Compilation failed with the following error message: prog.cpp: In constructor 'CTest::CTest()': prog.cpp:12:18: error: class 'CTest' does not have any field named 'sum' CTest() : i(0), sum(CTestSum) What am I doing wrong?
`sum` is not a data member of the class, so you cannot initialize it in the constructor's member intialization list. There is no need to initialize `sum()`, simply give it a body that calls the real function as needed, eg: #include <iostream> using namespace std; class CTest; void CTestSum(CTest* ptr, int a, int b); class CTest{ public: int i; void sum(int a, int b) { CTestSum(this, a, b); } CTest() : i(0) { } }; void CTestSum(CTest* ptr, int a, int b) { ++ptr->i; cout << (ptr->i)+a+b << endl; } int main() { CTest instance; instance.sum(2, 4); return 0; } Your DLL can then implement and export the `CTestSum()` function as needed, and your `CTest` class can be a header-only implementation for better portability across different compilers.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c++, linux, windows, dynamic library" }
Finding an active Hadoop mirror I'm currently using a setup script that launches EC2 instances and installs Hadoop/Spark from the binaries. The author currently has hardcoded a mirror from this list, but any mirror could change/be removed at any point. Is there a more "principled" way to get mirrors/download locations for Apache projects?
From here > wget --trust-server-names "
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "apache spark, hadoop" }
scp (secure copy) to ec2 instance without password I have an EC2 instance running (FreeBSD 9 AMI ami-8cce3fe5), and I can ssh into it using my amazon-created key file without password prompt, no problem. However, when I want to copy a file to the instance using scp I am asked to enter a password: scp somefile.txt -i mykey.pem [email protected]:/ Password: Any ideas why this is happening/how it can be prevented?
I figured it out. I had the arguments in the wrong order. This works: scp -i mykey.pem somefile.txt [email protected]:/
stackexchange-stackoverflow
{ "answer_score": 949, "question_score": 484, "tags": "amazon web services, amazon ec2, ssh, scp, pem" }
Can LDAP entry belong to OU that not in its DN? Can LDAP entry belong to OU that not in its DN? For example, can the entry with the following DN belong to `OU=QA`? CN=bob, OU=RnD ,DC=test,DC=com Or it belongs only to one `OU=RnD`? In another words can I find all OU of an entry by looking on its path in LDAP?
With this given LDAP string CN=bob,OU=RnD,DC=test,DC=com user `Bob` is part of the `RnD` OU - nothing else. The LDAP path (or DN) **defines** where in the hierarchy the object resides. `Bob` can be **member** of any number of groups that are located anywhere in the directory tree - but the `Bob` user object itself is **in the`RnD` OU** \- nowhere else. So to answer your question: > Can LDAP entry belong to OU that not in its DN? **No** , it **cannot** \- the DN **fully defines** where object exists.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "ldap, ldap query" }
How to configure Tmux so that windows monitored for activity and/or silent are marked in the status bar? In the status bar of Tmux, the last window is marked with `-`, a window which is monitored for activity and has had an activity is marked with `#`, analog for inactivity with `~`. But I would like to know which windows are currently monitored, ideally in the status bar marked with `(#). E.g. for the second window being monitored for activity: `0*:vim 1(#):mutt`
In version 3.0a upwards of tmux you can set the window list format: set-option -g window-status-format "#I#{?monitor-activity,(,}#{?window_flags,#{window_flags}, }#{?monitor-activity,),}:#W" set-option -g window-status-current-format "#I#{?monitor-activity,(,}#{?window_flags,#{window_flags}, }#{?monitor-activity,),}:#W" The expression form `#{var,if-true,if-false}` is extensively used to select between two values depending on whether a variable setting is on or off (or empty or not).
stackexchange-superuser
{ "answer_score": 1, "question_score": 1, "tags": "tmux" }
Extracting function variables from a list Evaluating the following func[x_, y_] := x^2 + y^2 listn = {{a, b}, {c, d}, {e, f}}; Map[func[##] &, listn, {1}] yields > {func[{a, b}], func[{c, d}], func[{e, f}]} What I want to end up with is > {func[a, b], func[c, d], func[e, f]} How do I do this?
Use `Apply` at level 1 i.e `@@@`, like this func[x_, y_] := x^2 + y^2 listn = {{a, b}, {c, d}, {e, f}}; Then func @@@ listn This gives: `{a^2 + b^2, c^2 + d^2, e^2 + f^2}.` Which is equivalent to > {func[a,b], func[c,d], func[e,f]}
stackexchange-mathematica
{ "answer_score": 1, "question_score": 0, "tags": "functions, function construction, assignment" }
Deleted the data while Amazon EBS Volume While Snapshot in Pending After I triggered the snapshot of a volume, I go ahead to work on the mounting due to the long hours of waiting and accidentally deleted the data in the volume. Will the snapshot still snap-shoting the previous data of the volume? Thanks.
> Will the snapshot still snap-shoting the previous data of the volume? Yes. From TFM (emphasis mine): > Snapshots occur asynchronously; the point-in-time snapshot is created immediately, but the status of the snapshot is pending until the snapshot is complete (when all of the modified blocks have been transferred to Amazon S3), which can take several hours for large initial snapshots or subsequent snapshots where many blocks have changed. **While it is completing, an in-progress snapshot is not affected by ongoing reads and writes to the volume**.
stackexchange-serverfault
{ "answer_score": 0, "question_score": 2, "tags": "amazon ec2, amazon ebs, snapshot" }
How Many Features Are Used in Random Forest When max_features is not an integer? In the `RandomForestClassifier` function in `sklearn.ensemble`, one of the parameters is `max_features`, which controls the size of the random subset of features that are considered at each node splitting. I would think this needs to be an integer, since of course the size of a subset needs to be an integer. But one of the options here is `"log2"`, which sets `max_features` to `log_2(n_features)`. I was wondering how that works, considering `log_2(n_features)` will not be an integer unless `n_features` is a power of 2. Thanks.
The argument for the number of features gets passed down to the `BaseDecisionTree` class. Looking at the code, you can see that the value that is used is calculated by first taking log with base two and then converting it to an integer (i.e. rounding it). if self.max_features == "auto": if is_classification: max_features = max(1, int(np.sqrt(self.n_features_))) else: max_features = self.n_features_ elif self.max_features == "sqrt": max_features = max(1, int(np.sqrt(self.n_features_))) elif self.max_features == "log2": max_features = max(1, int(np.log2(self.n_features_))) else: raise ValueError("Invalid value for max_features. " "Allowed string values are 'auto', " "'sqrt' or 'log2'.")
stackexchange-datascience
{ "answer_score": 1, "question_score": 1, "tags": "random forest" }
Need to convert Range of number notation into Comma separated values? My input would be string PageRange = "1,2-5,9"; and i need to convert them into string TotalRange = "1,2,3,4,5,9"; pls share your ideas.
List<string> result = new List<string>(); string PageRange = "1,2-5,9"; var strings = PageRange.Split(','); foreach (var s in strings) { var split = s.Split('-'); if (split.Count() == 1) { result.Add(s); continue; } for (int i = int.Parse(split[0]); i <= int.Parse(split[1]); i++) { result.Add(i.ToString()); } }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c# 4.0" }
How can you "construct" a high pressure? To create high pressure you have to enclose material in another material. Does this mean that the force involved in the pressure you want to create can never be higher than the binding forces which hold the constituents of the enclosing material together?
Yes, that is correct. But note however that most common materials yield and fail at stress levels far, far below that represented by the strength of the binding forces between their constituent atoms. This is because of defects in their crystalline structure which allow the material to bend and distort i.e., they contain _deformation mechanisms_ that reduce their strength. This means that pressure vessels require walls that are far thicker than you would expect in the absence of deformation mechanisms.
stackexchange-physics
{ "answer_score": 1, "question_score": -2, "tags": "experimental physics, pressure" }
The orbit map and the restriction of the orbit map both are open. Let $\phi: G \times X \to X$ (Often denoted by $(X,G)$) is a topological group action. We know that for any $x\in X$, the orbit map $\phi_x:G \to X$ is a continuous mapping and the restriction $\varphi_x:G \to Gx$ is also a continuous mapping, where $Gx=\\{gx:g \in G\\}$. I need an example about a dynamical system$(X,G)$, such that, the first, $\forall x\in X$, $\phi_x$ and $\varphi_x$ both are open mappings. Second, for any $x\in X$, $Gx\neq X$. The following questions may help you: < Restriction of the orbit map must be open? Thanks a lot.
Take X be the disjoint union of two copies of G, and G acts by left translation on each copy
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "dynamical systems" }
Error saving to iOS keychain using KeychainItemWrapper I get an error every time I try to store data into the keychain The error comes from the dictionaryToSecItemFormat method at these lines NSString *passwordString = [dictionaryToConvert objectForKey:(id)kSecValueData]; [returnDictionary setObject:[passwordString dataUsingEncoding:NSUTF8StringEncoding] forKey:(id)kSecValueData]' The error is I'm calling the KeychainItemWrapper methods like this KeychainItemWrapper *keychain = [[KeychainItemWrapper alloc] initWithIdentifier:@"credentials" accessGroup:nil]; [keychain setObject:username forKey:kSecAttrAccount]; [keychain release]; The error is *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSConcreteData dataUsingEncoding:]: unrecognized selector sent to instance"
dataUsingEncoding is a method from the NSString class, make username a NSString.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "objective c, ios, xcode, keychain" }
Strange silverlight behavior in chrome lately Lately (starting in January 2014) I have noticed that Chrome sometimes does not display Silverlight application unless your press F11 (full screen) on Ctrl+Shift+C (inspect element). It mostly happens when you follow a link from Skype or from another page, so I will place a link here so anyone can experience this bug. It happens in roughly 50% of cases when you follow a link. Pasting a link into address bar doesn't trigger the bug for me. Here is the link: < Also hitting F11 doesn't always help. but hitting Ctrl+Shift+C helps. So here are my questions: 1. Anyone else is experiencing this problem? 2. Is there a way to make a page "refresh" (as F11 or Ctrl+Shift+C seems to do) from javascript or using any other means? 3. Any idea on how to deal with this bug is also welcome.
This is a known bug of Chrome 32. It will be fixed in the next version. See < The plugin object is displayed only if you load the page in the default tab of the browser. In any new tab, you must resize the window (or press F12 twice). In the meanwhile, you can open your links in a popup window when Chrome is detected. For instance : if(/chrome/.test(navigator.userAgent.toLowerCase())) { var links = document.getElementsByTagName("a"); for(i = 0; i < links.length; i++) { links[i].url = links[i].href; links[i].href = "javascript:return false;"; links[i].onclick = function(e) { window.open(e.target.url, "_blank", "height =" + screen.height + ",width=" + screen.width).moveTo(0,0); }; } }
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 8, "tags": "javascript, silverlight, google chrome" }
Clear All Event subscriptions (Clone linked) I just implemented Clone from ICloneable and realized that the event subscriptions from my source instance also followed. Is there a good way to clear all those? Currently I am using a couple of these loops for every event I have to clear everything. foreach (var eventhandler in OnIdChanged.GetInvocationList()) { OnIdChanged -= (ItemEventHandler) eventhandler; } foreach (var eventhandler in OnNameChanged.GetInvocationList()) { ... This works fine but clutters the code a bit. Mostly worried to get event dangling.
I think you could just set `OnIdChanged = null` in your cloned object. After you have created the clone you just call the `ClearEvents` method on the clone. public class ClonedObject { public event EventHandler OnIdChanged; public event EventHandler OnNameChanged; public void ClearEvents() { OnIdChanged = null; OnNameChanged = null; } }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 5, "tags": "c#, events, clone" }
Create a moodle course which links directly to a SCORM pacakge I have installed a moodle environment and uploaded a SCORM package. I run all my courses through SCORM therefore the additional activities are not needed. Is there any way I can make the Course button link directly into the SCORM package to cut the additional clicking?
Here are a couple options: * Select the "single activity" course format: This prevents the /course/view.php page from appearing. Users still have to click a button to enter the SCORM activity, but takes clicks and page views out of the UX. This option can be selected in the course settings. * Customize: Create a version of the SCORM activity that launches without requiring the user to click the entry button on the SCORM activity page. This requires replicating what occurs when the the user clicks the entry button on the SCORM page, but is possible. Hope one of these is helpful - good luck w/ it!
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "moodle" }
Rewriting CNAME subdomain I have a sub domain that I want to redirect to a different location using mod_rewrite. For example: subdomain.example.com -> www.example.com/subdomain I don't want to send a redirect to the browser though (so it doesn't know the page is different). BTW subdomain.example.com has a CNAME record pointing to example.com. **Edit** Another example, just to clarify. It is very simple: If < is entered in to the browser, Apache returns the contents of <
In addition to what Gumbo stated above, you can use Apache's VirtualDocumentRoot statement to dynamically map URL to a dynamic location on disk. It allows you to use parts of the URL to build a path on disk. Check out this link for more information: < Example: `URL = < Server Path = /var/www/site.com/htdocs/sub/dir/page.html VirtualDocumentRoot = /var/www/%-2.0.%-1.0/htdocs/%-3/`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "mod rewrite, apache2" }
Analyzing react app performance using chrome For my react application, I am using chrome developer tool to record the performance. But I am not able to point out to specific function that is computationally intensive. Can someone tell me how to find out the specific function/areas in the code that are taking a lot of time? ![enter image description here]( Leads here is appreciated.
You may sort by "Self time" rather then Total time. Even on your screen you may notice that grid.js takes 14.6 ms as "Self time" i.e. 140 times bigger compared to majority of the others on the screen.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, reactjs, google chrome devtools" }
C++ start new process and terminate the current one under linux This question has been asked several times here, but I can't find answer for the following situation: My program uses statically linked libraries, which open file handles, so, I'm unable to set FD_CLOEXEC on those file handles simply calling exec causes alot of errors in new process, because of unavailable file handles Basically I need: 1\. spawn new process without blocking current one 2\. terminate current process (close all handles) Can I do it on linux?
Closing all filedescriptors should be as simple as #include <unistd.h> for (i=getdtablesize();i>=0;--i) close(i); /* close all descriptors */ This is also a standard step during daemonizing, see e.g. <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c++, linux, exec" }
Eeek! - Resin in my hair I have long hair and like being out in the woods. Unfortunately this means I sometimes get resin (or sap) in my hair. It's always a pain to get it out, sometimes I have no choice but cutting the "afflicted" strain of hair. ### How can I _painlessly_ remove resin from my hair without cutting it? Ideally this would also work for clothing.
I had the same problem with it sticking in clothing which I couldn't really put in the washer. My mothers neat trick: Put peanut-butter on it... Leave it for some time and wash it with hot water. I hope this applies to hair as well...
stackexchange-lifehacks
{ "answer_score": 3, "question_score": 4, "tags": "cleaning, personal care, hair" }
Insert linebreak in a file after a string I have a unique (to me) situation: I have a file - `file.txt` with the following data: "Line1", "Line2", "Line3", "Line4" I want to insert a linebreak each time the pattern `", ` is found. The output of `file.txt` shall look like: "Line1", "Line2", "Line3", "Line4" I am having a tough time trying to escape `", `. I tried `sed -i -e "s/\",/\n/g" file.txt`, but I am not getting the desired result. I am looking for a one liner using either `perl` or `sed`.
You may use this `gnu sed`: sed -E 's/(",)[[:blank:]]*/\1\n/g' file.txt "Line1", "Line2", "Line3", "Line4" Note how you can use single quote in `sed` command to avoid unnecessary escaping. If you don't have `gnu sed` then here is a POSIX compliant `sed` solution: sed -E 's/(",)[[:blank:]]*/\1\ /g' file.txt * * * To save changes inline use: sed -i.bak -E 's/(",)[[:blank:]]*/\1\ /g' file.txt
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "perl, sed" }
python relative import weirdness I have a file: STARTDIR/module/submodule/config.py I have another file: STARDIR/utils/filesys/getAbsPath.py Why does this line work, in `config.py`? from ..utils.filesys import getAbsPath It seems like `..` refers to `module`, not `STARTDIR`. There is no `utils` in `module` at all. In fact, doing from .. import utils yields ImportError: cannot import name utils
This should work: from ...utils.filesystem import getAbsPath This is because: * `from . import …` imports from `STARTDIR/module/submodule/` * `from .. import …` imports from `STARTDIR/module/` * `from ... import …` imports from `STARTDIR/`
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "python, import" }
A dash/dolar in a pattern passed to preg_match_all strangely make the pattern does not match I have a problem with my regular expression. I am trying to match all rows from a file that contain word "RewriteBase" with possible spaces before it. The example file is: #RewriteBase /yardley/development RewriteBase /yardley/ My patterns and their results: @RewriteBase\s*(.*)@ //matches both lines - OK @RewriteBase\s*(.*)$@ //matches first line only - why? @^.*RewriteBase\s*(.*)@ //doesn't match any - why? It should accept all characters before "RewriteBase" I'm completely stuck on it. Thanks a lot
Since you're using line start anchor `^` or line end anchor `$` therefore 2nd regex will match only 2nd line and 3rd regex will match only 1st line. You can use multiline (m) switch to match all the lines in your 3 regex: $s = <<< EOF #RewriteBase /yardley/development RewriteBase /yardley/ EOF; if (preg_match_all('@RewriteBase\s*(.*)$@m', $s, $arr)) var_dump($arr[0]); **OUTPUT:** array(2) { [0]=> string(32) "RewriteBase /yardley/development" [1]=> string(21) "RewriteBase /yardley/" }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "regex, preg match, preg match all" }
filtering based on tag Hi Smart People of UX Stackechange community! Recently, I had this debate with some of folks in my team and I thought I should also get your valuable comment. Assume we have following names with the associated tag: Alice (tag A and B), John (tag A), Jack(tag A and B and C) We display the above data in a list and imagine we have a multi select drop down with the available tags to trigger a search. ![multi select drop down]( If the user wants to search based on tags "A and B" what should be the expected result? Should it be A and B only (Alice)? or should we also include A and B and C(Jack)? My personal opinion is, we should include A and B and C to the result
As @codeinthehole mentioned, it strictly depends on boolean logic you use in a particular filtering system. I think that mostly useful is using conjunction (AND operator), which means that after selecting A and B from your example, displayed will be only items that has been assigned BOTH to A and B, which is Alice and Jack. Most of the search engines work in mutual way - it would be stupid to get search results for both every website that contains keyword 'beach' and different ones which contain keyword 'boys', while user was searching for Beach Boys.
stackexchange-ux
{ "answer_score": 0, "question_score": 0, "tags": "filter, tags" }
Knuckle Joint: compressive strength equal to tensile strength I was studying the design of joints and came to knuckle joints. Generally compressive strength is greater than tensile strength, but **considering knuckle joints compressive strength and tensile strength are considered equal** (as mentioned below). What are the reasons for assuming equal strengths? ![enter image description here]( Here is a link to the page, shown above, in Google Books.
Assuming they're equal, it allows you to use the more commonly available tensile strength data, while also getting a conservative solution. If it turns out they're not equal, then your design will still work correctly but might not make optimal use of the materials. Assuming uniaxial tensile and compressive strengths are equal is a common practice in engineering and is built into the popular von Mises and Tresca yield criteria which are used for all kinds of structures. If you want to take advantage of higher compressive strength, you can use less common failure criteria like Mohr-Coulomb.
stackexchange-engineering
{ "answer_score": 2, "question_score": 1, "tags": "design" }
Python3 cant detect<class 'NoneType'> I am running some python3 code which will occasionally get a list, dict, and None. fieldType = type(raw_data[root_key].get("oslc_cm:ChangeRequest")) print('fieldType=') print(fieldType) if fieldType is None: print('its none') else: print('its not none') this works for everything except when fieldType is 'None': fieldType= <class 'collections.OrderedDict'> its not none #this output works as expected but when fieldType is `<class 'NoneType'>` it reports it as being 'not none' fieldType= <class 'NoneType'> its not none why cant my code correctly identify when an object is of type 'None'?
`fieldType` is `<class 'NoneType'>`, which is different from `None`. It can never be `None`, because `type` always returns some type. Looks like you want raw_data[root_key].get("oslc_cm:ChangeRequest") is None instead of fieldType is None
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python 3.x, nonetype" }
Get object apiname based on recordid in lightning web component Is it possible to het the object apiname based on a recordId in a lwc without a call to apex? Something like apex but then without going to backend: Id recordId = '001g000001jmmCA'; System.debug('Object Name: '+ recordId.getsobjecttype()); I currently have a handleRowAction(event) which gets the record id from a lightning-datatable which dynamically gets fields and values as a replacement of related lists. I use this component several times on e.g. account record, so on handle handleRowAction(event) it would be easy to get the object by recordId so I can pass recordId and object to a lightning-record-form: <lightning-record-form record-id={recId} object-api-name={sObj} mode="readonly" layout-type="Full" columns="5" fields="Name"> I already solved this by an apex call to the backend but was wondering if this could be done easier.
You can use getRecord and pass in the `recordId` parameter to get the Record response, which includes the `apiName` property. You still will need a call to the server, but you won't need any Apex.
stackexchange-salesforce
{ "answer_score": 0, "question_score": 0, "tags": "lightning web components, custom object, describesobject, record" }
Can comments or brace style break C# code? I have seen comments breaking Java code, and I remember that brace style could mess with C++ code. Are there any cases in which comments or brace style (or coding style in general) can influence the correctness or source code? I can't think of any off the top of my head. (I am explicitly not asking how to comment and which brace style to chose, unless it is a direct consequence of trying to keep code correctness.)
As you've brought up the "unicode escape sequences in comments" issue (in the comments to the question) - C# is _not_ vulnerable to this. Escape sequences such as `\u000d` are _only_ converted to corresponding Unicode characters in string and character literals, and in identifiers. As for the bracing aspect: my guess is that's to do with macros in C++, although again an example would be handy. Not a problem in C#, which doesn't have macros. There are some subtle issues with other style choices, such as whether your `using` directives appear inside or outside the namespace declaration. But nothing in terms of comments and braces as far as I'm aware.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "c#, coding style" }
Python No module named model in tia.analysis My code has this import code: import tia.analysis.ta as ta And this is on **init**.py line 2 in "/usr/local/lib/python2.7/dist-packages/tia/analysis" after import code above: from tia.analysis.model import * Then the python **2.7.12** shell show this: import tia.analysis.ta as ta File "/usr/local/lib/python2.7/dist-packages/tia/analysis/__init__.py", line 2, in <module> from tia.analysis.model import * ImportError: No module named model Can somebody tell me why the **'model'** module in tia.analysis is unavailable even after I successfully install tia and using **Python 2.7**? If somebody can also tell me the solution, I will be grateful.
I am not sure why that is happening, but I would check the physical location where the library is and see if you have all the files installed. If not, you can grab the tia analysis model folder here. Make sure you have this folder and then try again, hopefully that should fix it.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "python, python 2.7" }
Combine multiple rows of table in single row in SQL I have table with stricture as follows : Ticket Comment UpdatedBy 100 Text 1 23 100 Text 2 24 100 Text 3 25 100 Text 4 26 Can i get this in one row table as **(Ticket will be same for all rows)** Ticket Comment 100 23 Said Text 1 - 24 Said Text 2 - 25 Said Text 3 - 26 Said Text 4 By some SQL Query ?(Sql Server 2008)
You can use `FOR XML PATH`: SELECT Ticket, STUFF((SELECT distinct ' - ' + cast(UpdatedBy as varchar(20)) + ' ' + comment from yourtable t2 where t1.Ticket = t2.Ticket FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,2,'') comments from yourtable t1 group by ticket See SQL Fiddle with Demo Result: | TICKET | COMMENTS | ----------------------------------------------------------- | 100 | 23 Text 1 - 24 Text 2 - 25 Text 3 - 26 Text 4 |
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "sql, sql server, sql server 2008" }
How to install GWT plugin in the browser? Is it possible to download GWT plugin for say Firefox on one machine and install it later on another machine. I don't want to install it automatically. The machine on which I want to install the plugin is not connected to internet. Thanks
You can download gwt browser plugin's from the page: < . Instead of installing(clicking on the link), right click and save the plugin file.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "gwt" }
Running SolrJ on Eclipse I'm trying to setup a SolrJ using Eclipse by following the example in < However, when I try to run the code using Run As -> Java Application, it came back with an error saying that 'Selection does not contain a main type'. But I see that that there's a main method in the code, and it has already been added to my code in Eclipse. My eclipse has got the same code as the example, except for the path name and document name. Is there any thing required that I missed out in order for the code to run successfully in Eclipse?
Ok so that means in alternative: A) your're doing "run as -->> Java application" from the wrong class. Open then class that contains the main, right click on that and choos "Runs as Java Application" B) your main method has a wrong signature (and therefore is not a valid main method) \-
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, eclipse, solr, solrj" }
how to reach into PHP nested arrays? I've a nested array whose print_r looks like this- Array ( [keyId] => Array ( [hostname] => 192.168.1.127 [results] => Array ( [1] => false [2] => false [3] => false ) [sessionIDs] => Array ( [0] => ed9f79e4-2640-4089-ba0e-79bec15cb25b ) ) I would like to process(print key and value) of the "results" array. How do I do this? I am trying to use array_keys function to first get all the keys and if key name is "results", process the array. But problem is array_keys is not reaching into the "results"
foreach($array['keyId']['results'] as $k => $v) { // use $k and $v }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, arrays, nested" }
How to access directories with flask So I am making a website that has different accounts stored under the accounts folder path so for example I have a account folder for Bob and an account for John under each folder they both have a `achivements.dat` file how can I access that file from bobs account meanwhile John is trying to access his own achivements.dat file without getting crossed or changing the entire os's system path? Thank you all for answering
For bob : with open('/path_to_files/bob/achivements.dat', 'r', encoding='utf-8') as inbob: ...do some awesomness for bob here... For john : with open('/path_to_files/john/achivements.dat', 'r', encoding='utf-8') as injohn: ...do some awesomness for john here... Of course this code can sit in 1 function and be called as needed with parameter for user specific path passed. For example : def read_file(path_for_some_user): from os import path with open(path.join('path_for_some_user','achivements.dat'), 'r', encoding='utf-8') as injohn: ...do some awesomness for john here...
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "python, file, flask" }
How can I display these values with spaces to separate the words? If I'll `console.log(JSON.stringify(selected["1"]?.others))`, this is what it shows: ["Cars","Books","Necklaces"] However, displaying this in the screen, this will display all of the data, however, there are no spaces between each words. It shows like this > CarsBooksNecklaces the `others` in `selected["1"]?.others` is an array. This is what it looks like in firestore: ![enter image description here](
Since this is an array of string values you could use `join` method like this: selected["1"]?.others.join(' ')
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "javascript, reactjs, firebase, google cloud firestore" }
Do I have to apply NSThread or pthread to set the priority of concurrent queue you create yourself via dispatch_queue_create GCD GCD concurrent Queue that is created via dispatch_queue_create("com.xxx.yyyyy", DISPATCH_QUEUE_CONCURRENT); You cannot set the priority of concurrent queue you create yourself, or can you? and how? Do I have to apply NSThread or pthread?
On iOS 8 or Yosemite, use dispatch_queue_create("com.xxx.yyyyy", dispatch_queue_attr_make_with_qos_class( DISPATCH_QUEUE_CONCURRENT, qos, prio)); (with `qos`/`prio` the desired quality of service/relative priority values) On earlier OS versions, use `dispatch_set_target_queue()` to target your queue at the global concurrent queue with the desired priority. Both of these topics have been covered in some detail in past WWDC session on GCD and are documented in the headers. Don't try to change the priority of the anonymous worker threads brought up to service the work submitted to your queue (with pthread or any other API).
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "grand central dispatch, objective c runtime" }
Creating one database per Client in MySql We have a finance related application in which we are creating a database(schema) for each client(Company). There will be many rows for single client. I want to know if it is best to keep data separate(like it is now) or combine. We are looking for more than 10000 databases per server. Even though not all users will be online at same time buy 10% of users my be online at same time easily. My questions are.. 1) Is there any serious problem (performance wise) for keeping multiple databases. 2) Is it common practice to keep different databases when it comes to financial data of companies.
"10000 databases per server" - that's a lot of databases! [Assuming 5 users per DB, and 10% active that's still 5000 active user connections per server] Putting that aside: your primary concern here is probably the security of each client's database. Keeping them separate will make it easier to manage security. To answer your questions: 1. No, there is no performance problem having multiple databases (other than the sheer volume of transactions being handled by the server). In fact, there might be performance gains in terms of row range locks being held. 2. Yes, it is common practice to keep separate databases for financial data. Security, backups are often better handled in per company silos.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "mysql, database, performance, finance" }
Error by schedule ssis package in sql server 2008 agent When I execute my SSIS Package manually it works just fine, But when I try to execute it from SQL agent i always get an error. In my case the SSIS is called from a certain path in the server. . The error is as follows: !enter image description here Also when I See the Job Scrip I see the following under @command N'/FILE "N:\HRSSource\SSIS-Pakete IUT-NAV-MSSQL-2 ..... Maybe the error is comming from the N'FILE?
Don't use the mapped drive use the UNC path instead, something like \servername\filepath. For the Job to access network folders I think you need to set up a proxy with a domain account credentials and that is configured to run jobs of type SQL Server Integration Services Packages.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql server, sql server 2008, ssis" }
WCF Data Services updating entity error and type of table's primary key For some time I couldn't find out the cause of an error when trying to update a field in a table using WCF Data Services plus Entity Framework: MydbEntities context = new MydbEntities(new Uri(" MyEntity entitytoedit = context.MyEntity.FirstOrDefault(); entitytoedit.Name = "TheNewName"; context.UpdateObject(entitytoedit); context.BeginSaveChanges(OnChangesSaved, context); ... The error was like following: **_RequestException An error occurred while processing this request._** The fix was to add an autoincremental `decimal(18, 0)` field as the Primary Key with Identity Specification `IsIdentity = yes` instead of just a `varchar(20)` field as the Primary Key. Please, could anybody explain the nature of the problem: should I always use autoincremental Primary Keys with WCF Data Services? If not, where in fact am I wrong?
I think it is more Entity Framework question than WCF Data Services. You can either have primary key field that you set by hands and you must set `StoreGeneratedPattern` to `None`. Or you can use `AutoIncrement` field as primary key and in this case you must set `StoreGeneratedPattern` for it to `Identity`. Mixing this to cases always break the things. In addition when you do Model First, primary key field by default has type `int` and `StoreGeneratedPattern` set to `Identity`, so just changing the type to `decimal` as in your case is not enough.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "sql server, wcf, entity framework, wcf data services" }
Undefined window.innerWidth in Safari 10.1.1 I have a script, which adjusts font-size based on viewport size. Looks like it works everywhere but in Safari (I checked only 10.1.1 version). ![enter image description here](
Make sure you have selected "All" in the top part of your developer tools. Otherwise it will only show you errors and therefore you will only see `undefined`.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, css, browser, safari, cross browser" }
How can I increase Angular/Node performance by making one API call instead of several? Using Angular/Node to build a Proof of Concept project. I have accomplished on finishing the first task which is "making it work." Since the MVP works, I now need to focus on performance. The latency is really really bad and I don't know how to approach it or fix it. Tried various methods but no luck. **Overview:** Using Node Server to call an external API for Data in JSON format. Using Angular Service to make 5 API calls and rendering data on Angular Controller. Is there a way I can only make one API call instead of 5? Since it is making 5 API call the CPU processing is at 90% on the server side and following is the Client performance: ![enter image description here](
If it takes X amount of time to collect the results for one API call, then you are stuck with X * 5 times to collect the results for five API calls. If you cannot change the API to consolidate it, at least you can cut down on waiting for round trips across the network by sending all five API calls at the same time (i.e. one right after the other, asynchronously). That is, if X = (N * 2) + P for twice the network travel, plus processing, then instead of 5 * ((N * 2) + P) you could see something like (N * 2) + (5 * P). It may still be that the server processes them one at a time, but you don't have the travel time on the network in between the requests. If the server is not busy, and has multiple cores, and is multi-threaded or multi-process, and database locking is in your favor, you might see some concurrency between the five competing requests and the 5 * P could be less.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "javascript, angularjs, node.js, api, angular services" }
Convergence of a composite trigonometric series I was asked to determine the convergence of following series.$$\sum_{n=1}^\infty \frac{\tan(\sin n)}{n^3}$$ It seems comparison test doesn't work since the terms can be negative. I also try root test and ratio test. But the calculations of limit are a bit too complicated due to two trigonometric functions there. Any hint about this question?
Since $-1 \le \sin n \le 1$, we have $|\tan(\sin n)| \le \tan(1)$ as $|\tan(x)|$ is increasing on $[0, 1]$ and decreasing on $[-1, 0]$ . Consequently, $$ \frac{|\tan(\sin n)|}{n^3} \le \frac{\tan(1)}{n^3}. $$ Hence your series converges absolutely by comparison with $\sum_{n=1}^{\infty}\frac{\tan(1)}{n^3}$, and thus converges.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "real analysis, sequences and series" }