qid int64 10 74.7M | question stringlengths 15 26.2k | date stringlengths 10 10 | metadata list | response_j stringlengths 27 28.1k | response_k stringlengths 23 26.8k |
|---|---|---|---|---|---|
1,229,743 | Can someone please explain traits in Scala? What are the advantages of traits over extending an abstract class? | 2009/08/04 | [
"https://Stackoverflow.com/questions/1229743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43222/"
] | The short answer is that you can use multiple traits -- they are "stackable". Also, traits cannot have constructor parameters.
Here's how traits are stacked. Notice that the ordering of the traits are important. They will call each other from right to left.
```
class Ball {
def properties(): List[String] = List()
override def toString() = "It's a" +
properties.mkString(" ", ", ", " ") +
"ball"
}
trait Red extends Ball {
override def properties() = super.properties ::: List("red")
}
trait Shiny extends Ball {
override def properties() = super.properties ::: List("shiny")
}
object Balls {
def main(args: Array[String]) {
val myBall = new Ball with Shiny with Red
println(myBall) // It's a shiny, red ball
}
}
``` | This is the best example I've seen
Scala in practice: Composing Traits – Lego style:
<http://gleichmann.wordpress.com/2009/10/21/scala-in-practice-composing-traits-lego-style/>
```
class Shuttle extends Spacecraft with ControlCabin with PulseEngine{
val maxPulse = 10
def increaseSpeed = speedUp
}
``` |
889,934 | this is quite related to [this question regarding GCP](https://serverfault.com/questions/859348/using-ftp-client-not-server-on-google-compute-instance), but on AWS, and also trying to solve it with a different approach.
I have an FTP client trying to connect in ftp active mode to some ftp servers located on the Internet.
The FTP client has private address, and it is behind a NAT instance server (not NAT Gateway)
This NAT-server has private address too, and is itself behind the VPC Internet GW.
Diagram:
FTP client (10.60.0.0/24) --> NAT server (10.254.254.0/24) --> IGW --> Internet --> Firewall/NAT --> FTP Servers
NAT Server is AWS NAT Linux (kernel 4.9) with masquerading turned on.
With Active-FTP (port mode), this is not working.
I already activated CT FTP helper (nf\_nat\_ftp) and its triggering iptables rule:
```
iptables -A PREROUTING -t raw -p tcp --sport 1024: --dport 21 -j CT --helper ftp
```
and I can see that the "PORT" command is being correctly translated from the private IP address of FTP client to the private IP of the NAT server.
Unfortunately, this isn't enough, because the FTP Server is receiving an FTP "PORT" command still with a private address (the one of the NAT server).
So the ftp data connection, initiated from the ftp server, of course never reaches back.
I cannot, at least for now, "replace" the ftp client (it's part of a legacy application).
Is there any way to "inject" the public IP in the PORT command ?
Some ideas came to my mind, but I could not find proofs whether they are realistic or I'm wasting my time:
1. creating a "fake" interface on the nat server with the public ip address, and selectively enabling/disabling CT helper to modify the PORT command. I have troubles with the correct routing for this, though (let alone convincing myself it's worth trying)
2. modifying the nf\_nat\_ftp helper module with hard-coded public IP (so uglyyy!)
3. modifying the port command on the ftp client (it's a Windows machine), don't know if a driver/tool already exists for that purpose
4. brute-patching the ftp client (might be the most realistic way...?)
About option 3: I tried [NETSED](https://github.com/xlab/netsed), **which actually can change the PORT command**, but it seems to mess up the nat for the ftp client! :(
Other solutions are of course welcome!
Thank you. | 2017/12/28 | [
"https://serverfault.com/questions/889934",
"https://serverfault.com",
"https://serverfault.com/users/440567/"
] | Trying to answer my own question **on a limited use-case**
The limit is: only 1 ftp client in active mode behind the nat server (it does not work with masquerading)
* ftp client: 10.60.10.11
* nat server: 10.254.254.203
* public ip : 1.2.3.4
First, fire up netsed on the nat server, local port 21, converting all packets containing "PORT 10,60,10,11," to "PORT 1,2,3,4," (thus leaving port numbers unchanged):
```
./netsed tcp 21 0 0 s/PORT%2010,60,10,11,/PORT%201,2,3,4,
```
Second, redirect traffic from ftp client to netsed:
```
iptables -t nat -A PREROUTING -p tcp --dport 21 -j REDIRECT --to 21
```
This will make the ftp server "happy" and it will effectively try to open a new connection from port 20 to the **public IP**.
IGW will let pass, but the NAT server does not know how to handle the connection (it's not in CT, it's a new connection).
So, *as ugly as it may be*, now forward all incoming traffic from port 20 to the internal FTP client:
```
iptables -t nat -A PREROUTING -p tcp -d 10.254.254.203 --sport 20 --dport 1024:65535 -j DNAT --to-destination 10.60.10.11:1024-65535
```
**This is working!!**
**But, a part from being a hack, it seems it is limited to only 1 ftp-client.**
Thank @Steffen for pointing out that CT state was not set. | >
> Is there any way to "inject" the public IP in the PORT command ?
>
>
>
Even if this would be possible this would not help. While the server would probably accept the PORT command with the public IP address it would not be able to connect back to the FTP client using this IP address and port since there is no matching NAT state at the IGW.
If you have two NAT's as in your case (NAT server and IGW) then both of these would need to translate the address in the PORT command **and create a state** to pass the connection from the server to the newly set IP,port to the IP,port from the original PORT command.
I really recommend to move away from FTP and use alternatives which don't need dynamic data connections like FTP does. Such dynamic connections give you only problems if one of the NAT gateways will not be able to translate the PORT/PASV - maybe because of missing FTP helper or maybe because you are using FTPS (i.e. FTP with TLS) where the NAT gateway will not even be able to see the original IP,port and can also not modify the control connection as needed. Use protocols like SFTP (FTP over SSH) instead which have no problems with NAT since they only use a single TCP connection. |
14,633,926 | How can you check for the presence of both Bundler as well as a Gemfile?
My initial guess was `defined?(Bundler) && File.exist?('Gemfile')`, but since you can have a Gemfile with a different name, this won’t cover all cases. | 2013/01/31 | [
"https://Stackoverflow.com/questions/14633926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/108369/"
] | I had exactly the same problem and can say it's all a matter of size and most likely an **error in the compression module of hhc**.
When I added some lines of documentation the size of the CHM-file increased from 1.6 to 3.1 MB and it could not be opened anymore.
**This problem could not only be fixed by removing files but also by adding files.**
So I wrote some additional documentation, added it to the project and everything was fine again. | I see 0 byte files in the input? Maybe the compiler can't handle that? |
193,910 | **CODE HTML:**
```
<div id="element">
<div class="col-md-3">
<div data-role="collapsible">
<div data-role="trigger">
<span>Title 1</span>
</div>
</div>
<div data-role="content">Content 1</div>
</div>
<div class="col-md-3">
<div data-role="collapsible">
<div data-role="trigger">
<span>Title 2</span>
</div>
</div>
<div data-role="content">Content 2</div>
</div>
<div class="col-md-3">
<div data-role="collapsible">
<div data-role="trigger">
<span>Title 3</span>
</div>
</div>
<div data-role="content">Content 3</div>
</div>
<div class="col-md-3">
<div data-role="collapsible">
<div data-role="trigger">
<span>Title 4</span>
</div>
</div>
<div data-role="content">Content 4</div>
</div>
</div>
```
**CODE JS:**
```
require(['jquery','accordion'], function ($) {
$("#element").accordion({
"openedState": "active",
"collapsible": true,
"active": [0,1,2,3], /** Integrat Dynamic open tab */
"multipleCollapsible": true,
});
});
```
I have a function called an accordion and I want it's initialization to be only on the mobile (do not call on the desktop).
How can I do this? | 2017/09/20 | [
"https://magento.stackexchange.com/questions/193910",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/49726/"
] | The [recommended](https://devdocs.magento.com/guides/v2.3/frontend-dev-guide/responsive-web-design/rwd_js.html) way would be to use `matchMedia`.
```
require(['jquery','accordion', 'matchMedia' ], function ($, mediaCheck) {
mediaCheck({
media: '(min-width: 768px)',
// Switch to Desktop Version
entry: function () {},
// Switch to Mobile Version
exit: function () {
$("#element").accordion({
"openedState": "active",
"collapsible": true,
"active": [0,1,2,3], /** Integrat Dynamic open tab */
"multipleCollapsible": true,
})
}
})
})
``` | Less then 640 width would be mobile you can check this below way
```
require(['jquery','accordion'], function ($) {
if ($(window).width() < 640) {
$("#element").accordion({
"openedState": "active",
"collapsible": true,
"active": [0,1,2,3], /** Integrat Dynamic open tab */
"multipleCollapsible": true,
});
}
});
``` |
46,664 | I have some mail messages that OSX Mail puts in my junk folder but does not show the header saying "Mail thinks this message is Junk Mail" and so does not show the button allowing me to mark the mail as not junk.
How do I get Mail to allow me to mark the mail as not junk.
These emails are put in the junk folder by me.com/iCloud so I would hope Apple would allow control via their apps. | 2012/03/29 | [
"https://apple.stackexchange.com/questions/46664",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/237/"
] | It seems iCloud is marking the message as junk using its algorithm. I don't believe you can adjust this from within the Mail.app. You will need to log into iCloud.com, enter Mail, find the particular message in your Junk Mail folder and then with the message selected, select the gear menu and you should be able to Mark as Not Junk.
To recap, as iCloud is flagging message as junk you must unflag message within iCloud. | all you need to do in Mail toolbar is click on the thumbs up icon to the right of the trash bin. |
35,291,376 | Right now I am practicing on creating a header section, which contains an image which is used as a logo and and a un-ordered list which is used as a navigation menu.
Both of these elements are kept in a div element and I want to align the image to the left in the div element and the un-ordered list to the right of the div element. So how can I do it?
Second, I am willing only to use relative property. Not 'Absolute'! As I want to align the list vertically in the middle of the div element and with position absolute I am unable to vertically align the list with vertical align property.
if I am using float than the same situation is there. I am unable to vertically align the list to the middle, which I want to do.
So, I just want to know how can I position my list to the right of the div element using the relative positioning property.
```css
<style>
.header-section {
background-color:red;
}
ul {
display:inline-block;
list-style:none;
}
ul li {
display:inline-block;
}
</style>
```
```html
<!DOCTYPE html>
<html>
<body>
<div class="container">
<div class="header-section">
<img src="some-image.jpg">
<ul>
<li>Home</li>
<li>About Us</li>
</ul>
</div>
</div>
</body>
</html>
``` | 2016/02/09 | [
"https://Stackoverflow.com/questions/35291376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2992433/"
] | Use `display:flex` to parent div and give `justify-content: space-between;`
```css
.header-section
{
background-color:red;
display: flex;
justify-content: space-between;
}
ul
{
display:inline-block;
list-style:none;
}
ul li
{
display:inline-block;
}
```
```html
<!DOCTYPE html>
<html>
<body>
<div class="container">
<div class="header-section">
<img src="some-image.jpg">
<ul>
<li>Home</li>
<li>About Us</li>
</ul>
</div>
</div>
</body>
</html>
``` | You could use [float](https://developer.mozilla.org/en-US/docs/Web/CSS/float) like this:
```
ul {
display:inline-block;
list-style:none;
float: right;
}
img {
float: left;
}
``` |
1,309,820 | Some text editors for programming support auto-closing brackets. For example, on Jupyter Notebook or Jupyterlab for Python, given a line, say
>
> asdf wert xcvb
>
>
>
If I double-click to highlight *wert*, and I type *(*, it will give me
>
> asdf (wert) xcvb
>
>
>
Similarly, if I highlight *asdf*, and type *'*, it will give me
>
> 'asdf' wert scvb
>
>
>
Is there a way to do so in the entire Mac OS? | 2018/04/01 | [
"https://superuser.com/questions/1309820",
"https://superuser.com",
"https://superuser.com/users/889963/"
] | I don't know of any such global behavior, as what you describe is the
special behavior of this one specific app.
To recreate this for the entire operating system, you will need a
system macro, activated by some chosen keyboard key,
that will translate it to a series of keys to achieve the desired effect.
For example (taken from Windows and needs to be translated to the Mac),
the keyboard combination of
`Win`+`(` could be translated to
`Ctrl`+`X`,
`(`,
`Ctrl`+`V`,
`)`.
For the Mac, substitute `Win` by `Cmd`.
This will cut the selection to the clipboard, enter `(`,
paste the selection, finally enter `)`.
This combination should work for most applications.
You may do the same with characters other than parenthesis, such as quotes.
For a discussion of macro programs on the Mac, see the post
[AutoHotkey Equivalent for OS X](https://apple.stackexchange.com/questions/153930/autohotkey-equivalent-for-os-x). | The simplest way to do this is through **System preferences.**
* Go to **System Preferences > Keyboard > Text**
* Click the '**+**' button in the bottom left.
* Enter the shortcut text you want in the **Replace** column(In our case it will be *'('* ).
* Enter the target phrase that you want to expand to in the **With** column (In this case, "()").
* Repeat the above steps for all the different types of brackets(if required)
* Each time you type an opening bracket, the system will show the expansion below the text, and will automatically replace it with the desired result when you press "Space" or "Enter".
Enveloping highlighted text in brackets or quotes doesn't seem possible with this, though.
**Source:**
<https://www.laptopmag.com/articles/autocomplete-with-text-shortcuts-os-x> |
30,170,408 | I know browserify can consume UMD modules by means of transforms, but when I want to build a lib using browserify, how can I build an UMD module? Is there any transform I can use? | 2015/05/11 | [
"https://Stackoverflow.com/questions/30170408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2633697/"
] | Find the max index of each value seen in `x`:
```
xvals <- unique(x)
xmaxindx <- length(x) - match(xvals,rev(x)) + 1L
```
Rearrange
```
xvals <- xvals[order(xmaxindx,decreasing=TRUE)]
xmaxindx <- xmaxindx[order(xmaxindx,decreasing=TRUE)]
# 2 4 1 3
# 5 4 3 2
```
Select from those:
```
xmaxindx[vapply(1:6,function(z){
ok <- xvals < z
if(length(ok)) which(ok)[1] else NA_integer_
},integer(1))]
# <NA> 1 2 2 2 2
# NA 3 5 5 5 5
```
It handily reports the values (in the first row) along with the indices (second row).
---
The `sapply` way is simpler and probably not slower:
```
xmaxindx[sapply(1:6,function(z) which(xvals < z)[1])]
```
---
**Benchmarks.** The OP's case is not fully described, but here are some benchmarks anyway:
```
# setup
nicola <- function() max.col(outer(y,x,">"),ties.method="last")*NA^(y<=min(x))
frank <- function(){
xvals <- unique(x)
xmaxindx <- length(x) - match(xvals,rev(x)) + 1L
xvals <- xvals[order(xmaxindx,decreasing=TRUE)]
xmaxindx <- xmaxindx[order(xmaxindx,decreasing=TRUE)]
xmaxindx[vapply(y,function(z){
ok <- xvals < z
if(length(ok)) which(ok)[1] else NA_integer_
},integer(1))]
}
beauvel <- function()
Vectorize(function(u) ifelse(length(which(x<u))==0,NA,max(which(x<u))))(y)
davida <- function() vapply(y, function(i) c(max(which(x < i)),NA)[1], double(1))
hallo <- function(){
test <- vector("integer",length(y))
for(i in y){
test[i]<-max(which(x<i))
}
test
}
josho <- function(){
xo <- sort(unique(x))
xi <- cummax(1L + length(x) - match(xo, rev(x)))
xi[cut(y, c(xo, Inf))]
}
require(microbenchmark)
```
(@MrHallo's and @DavidArenburg's throw a bunch of warnings the way I have them written now, but that could be fixed.) Here are some results:
```
> x <- sample(1:4,1e6,replace=TRUE)
> y <- 1:6
> microbenchmark(nicola(),frank(),beauvel(),davida(),hallo(),josho(),times=10)
Unit: milliseconds
expr min lq mean median uq max neval
nicola() 76.17992 78.01171 99.75596 98.43919 120.81776 127.63058 10
frank() 25.27245 25.44666 36.41508 28.44055 45.32306 73.66652 10
beauvel() 47.70081 59.47828 67.44918 68.93808 74.12869 95.20936 10
davida() 26.52582 26.55827 33.93855 30.00990 35.55436 57.24119 10
hallo() 26.58186 26.63984 32.68850 28.68163 33.54364 50.49190 10
josho() 25.69634 26.28724 37.95341 30.50828 47.90526 68.30376 10
There were 20 warnings (use warnings() to see them)
>
>
> x <- sample(1:80,1e6,replace=TRUE)
> y <- 1:60
> microbenchmark(nicola(),frank(),beauvel(),davida(),hallo(),josho(),times=10)
Unit: milliseconds
expr min lq mean median uq max neval
nicola() 2341.96795 2395.68816 2446.60612 2481.14602 2496.77128 2504.8117 10
frank() 25.67026 25.81119 42.80353 30.41979 53.19950 123.7467 10
beauvel() 665.26904 686.63822 728.48755 734.04857 753.69499 784.7280 10
davida() 326.79072 359.22803 390.66077 397.50163 420.66266 456.8318 10
hallo() 330.10586 349.40995 380.33538 389.71356 397.76407 443.0808 10
josho() 26.06863 30.76836 35.04775 31.05701 38.84259 57.3946 10
There were 20 warnings (use warnings() to see them)
>
>
> x <- sample(sample(1e5,1e1),1e6,replace=TRUE)
> y <- sample(1e5,1e4)
> microbenchmark(frank(),josho(),times=10)
Unit: milliseconds
expr min lq mean median uq max neval
frank() 69.41371 74.53816 94.41251 89.53743 107.6402 134.01839 10
josho() 35.70584 37.37200 56.42519 54.13120 63.3452 90.42475 10
```
Of course, comparisons might come out differently for the OP's true case. | Try this:
```
vapply(1:6, function(i) max(which(x < i)), double(1))
``` |
52,191 | The original article is on [Newsweek](https://www.newsweek.com/indonesian-army-two-finger-virginity-tests-female-recruits-1618611) which I personally consider a reliable source.
>
> The virginity check, which extended to military fiancées, involves someone placing two fingers into the vagina to determine whether or not they've had intercourse, due to the state of the hymen.
>
>
> | 2021/08/12 | [
"https://skeptics.stackexchange.com/questions/52191",
"https://skeptics.stackexchange.com",
"https://skeptics.stackexchange.com/users/15834/"
] | Yes
The invasive virginity test:
1. began at an unknown time but [probably around 1965](https://asaa.asn.au/beautiful-virgins-the-hard-road-to-becoming-an/) (a retired police officer [remembered having the test](https://www.hrw.org/news/2014/11/17/indonesia-virginity-tests-female-police) in 1965).
2. was [exposed by Human Rights Watch](https://www.hrw.org/news/2015/05/13/indonesia-military-imposing-virginity-tests) in 2014. At this time, according to the HRW report, it was defended by the military.
3. was criticized by the Indonesian government's own [Center for Political Studies in 2015](http://www.politik.lipi.go.id/kolom/kolom-2/politik-nasional/1090-tentang-perempuan-dan-pertahanan) as a nonsensical practice and a violation of human rights.
4. was [still conducted in 2018](https://kumparan.com/kumparansains/pengakuan-mereka-yang-pernah-terlibat-dalam-tes-keperawanan-1543053379149882065/full). This article mentions how the test was given to police recruits as well as prospective wives of soldiers.
5. [abandoned in 2021](https://www.cbsnews.com/news/indonesian-army-virginity-testing-female-cadets/) as you discovered.
Sharyn Graham Davies ([2015](https://asaa.asn.au/beautiful-virgins-the-hard-road-to-becoming-an/), [2018](https://www.researchgate.net/publication/322311311_Skins_of_Morality_Bio-borders_Ephemeral_Citizenship_and_Policing_Women_in_Indonesia)) traces the practice to the superstitious masculinity of the totalitarian Suharto regime. The worry was that the appearance of an unchaste woman would put the masculine integrity of the Indonesian state in doubt. Although the regime fell in 1999 and at that time Indonesia legally adopted a commitment to human rights, the military maintains many beliefs from Suharto times. From the 2018 study, explaining normative practices for hiring policewomen in Indonesia:
>
> Recruits must: be between the ages of 17.5 and 22; be unmarried and remain so for at least two years – after two years women can marry and with their husband’s permission continue working; pass psychological tests; have strong religious beliefs; have graduated from high school; not wear glasses; and be prepared for transfer to any region across Indonesia. Further, recruits must be over 165cm tall and have a body in proportion to their height, and they must be pleasing to the eye (*enak dilihat*), which often means having fair skin (see Saraswati, 2013). Body measurements are taken of recruits, with male officers literally measuring women’s bust sizes (Chanel Bombon, 2014). Recruits must also parade on a cat-walk in front of a male selection committee where their beauty is assessed.
>
>
>
The general consensus [among Indonesian activists](https://www.satuharapan.com/read-detail/read/lbh-apik-tes-keperawanan-polwan-hina-martabat-perempuan) seems to be that this practice was illegal but the law could not be enforced, as it was practiced by police themselves. Most Indonesians were probably not aware of this practice -- it was an internal police behavior. While America certainly doesn't do this, Americans sometimes are shocked to learn [what police learn in training](https://slate.com/news-and-politics/2020/08/warrior-cop-class-dave-grossman-killology.html) as well. | From the article linked in the question itself, their army chief of staff basically admitted they had hymen "rupture" tests:
>
> Andika Perkasa, the Indonesian army chief of staff, told reporters on Tuesday the controversial practice had ceased.
>
>
> "Previously we looked at the abdomen, genitalia in detail with the examinations of the pelvis, vagina and cervix. Now, we have done away with these examinations, **especially with regards to the hymen, whether it has been ruptured and the extent of the rupture**," he said.
>
>
>
So, I suppose the only doubtful aspect is the "two-finger" issue, i.e. how the tests were conducted in practice, as the army commander didn't explicitly admit to that aspect.
The "two-finger test" is/was definitely practiced as such in some countries, e.g. [in Pakistan](https://www.france24.com/en/live-news/20210113-raped-twice-pakistan-virginity-tests-block-justice-for-victims).
>
> "She told me to open my legs and inserted her fingers," Shazia, not her real name, told AFP in a written statement.
>
>
> "It was very painful. I didn't know why she was doing it. I wish my mother had been with me." [...]
>
>
> The "two-finger test" endured by Shazia requires a doctor to insert their fingers into the victim's vagina and record whether they "entered easily" or not. [...]
>
>
> Similar virginity tests are employed in at least 20 countries around the world from Brazil to Zimbabwe, according to the World Health Organization. [...]
>
>
>
Besides the recent flood of articles that just use that term in the context of Indonesia, there's a [BBC one from 2015](https://www.bbc.com/news/world-asia-32748248), which has a modicum of detail on the procedure, as was done in the Indonesian army:
>
> Andreas Harsono was one of the HRW researchers who interviewed 11 Indonesian women, who were all military wives and female officers. **He said they described two fingers being used to open the vagina while one finger was placed in the anus.**
>
>
> He said that on one occasion, when a woman told others waiting outside an examination room what had been done to her, all 23 applicants left.
>
>
> He said that most were embarrassed by the procedure, and many were traumatised.
>
>
> A female military physician told researchers that when she performed the tests in Jakarta, she found it difficult to persuade the women to take part. "It was not [just] a humiliating act... It was a torture. I decided not to do it again," she said.
>
>
>
Somewhat more detailed description found [in another 2015 article](https://www.smh.com.au/world/indonesian-surgeongeneral-says-torn-hymen-shouldnt-stop-women-join-military-20150518-gh4844.html):
>
> "**Indonesian military medical professionals insert a finger into the anus of the woman, widen her vulva with the other hand, and then press the woman's hymen forward so that her whole hymenal ring is visualised**," International Rehabilitation Council for Torture Victims secretary general Victor Madrigal-Borloz said in an open letter to delegates.
>
>
>
So one could quibble this isn't exactly "two-finger"... but still invasive in an "original" way. (Hymen visualization as described in Western medicine manuals [doesn't](https://www.sciencedirect.com/science/article/pii/B9780128000342000732) involve anal penetration, for a start... it's also not done for virginity determination...)
On the other hand, the Indonesian police seems to have [had] practiced the two-finger test (for their female recruits) in a more [literal manner](https://nymag.com/intelligencer/2014/11/indonesian-lady-cops-must-be-god-fearing-virgins.html), as per a 2014 account:
>
> “Entering the virginity test examination room was really upsetting,” one woman told Human Rights Watch, a group that has been investigating these requirements. “I feared that after they performed the test I would not be a virgin anymore. They inserted two fingers with gel … it really hurt. My friend even fainted.”
>
>
>
---
Footnote: there were some comments (deleted because of other tangential matters) that protested that we only know of a handful of examples that were all publicly communicated through some (Western) human rights organizations. (As exemplified in Avery's answer, the Indonesian press also reported on the matter, but their reporting ultimately cited HRW for the details.) However, consider that the Indonesian military initially chose to
respond to those reports (around May 2015) simply by defending their testing policy, [e.g.](http://web.archive.org/web/20150721213146/http://thejakartaglobe.beritasatu.com/news/good-thing-military-chief-virginity-testing-female-recruits/) as reported in the Jakarta Globe:
>
> Asked for his response to growing international condemnation of the practice, Gen. Moeldoko insisted to reporters at the State Palace in Jakarta on Friday that the so-called two-finger test was one of the requirements for women joining the Indonesian Military, or TNI.
>
>
> “So what’s the problem? It’s a good thing, so why criticize it?” he said.
>
>
> He conceded, though, that there was no direct link between a woman being a virgin and her abilities as a member of the armed forces, but insisted that virginity was a gauge of a woman’s morality – one of the three key traits he said a woman must have to serve in the TNI, along with high academic aptitude and physical strength.
>
>
> The virginity test “is a measure of morality. There’s no other way” to determine a person’s morality, Moeldoko claimed.
>
>
> His statements came a day after the group Human Rights Watch urged Indonesia to abolish the practice, pointing out that international treaties had described it as degrading and cruel.
>
>
>
(Aside, according to Wikipedia [Moeldoko](https://en.wikipedia.org/wiki/Moeldoko) retired from active military service in 2016, and entered politics.)
Likewise, Euronews [quoted](https://www.euronews.com/2015/05/14/human-rights-group-denounces-indonesias-virginity-test) another top Indonesian general, who at the time [May 2015] had a similar position:
>
> But Major-General Fuad Basya, speaking for the Indonesian military, defended the tests, which he said takes place to ensure the hymen is intact, and to make sure they recruit the “best people both physically and mentally” to the armed forces.
>
>
> Doctors would know, he said, if the candidates had lost their hymen due to an accident or another reason. She would then be required to explain why her hymen was not intact.
>
>
> “If it is due to an accident we can still consider it but if it’s due to another reason, well, we cannot accept her,” said Major-General Basya.
>
>
>
I'm not aware at any point at which the military (or anyone else) contested the *accuracy* of those reports by human rights organizations on the matter. |
31,464,806 | I have been using PostgreSQL for a couple of days and it has been working fine. I have been using it through both the default postgres database user as well as another user with permissions.
In the middle of the day today (after everything had been working fine) it stopped working and I could no longer get back into the database. I would try: `psql` and it would come up with `psql: FATAL: role "postgres" does not exist`.
Similarly, if I tried from my other user, `psql -d postgres` it would come up with `psql: FATAL: role "otheruser" does not exist`. (Note that I have a database named postgres and it has been working up until now).
**UPDATE**
It appears that one of the computers accessing the server crashed and may have somehow deleted all of the users of the database. I will try a fresh reinstall. | 2015/07/16 | [
"https://Stackoverflow.com/questions/31464806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2591505/"
] | No, the variables will maintain state without the static modifier | It seems after some research a singleton did the job. Creating one singular instance but calling on it more then once.
See Here:
<http://www.tutorialspoint.com/java/java_using_singleton.htm> |
93,824 | Given a text like this:
```
# #### ## #
## # ## #
#### ##
```
Output the same text but by connecting the pixels with the characters `─│┌┐└┘├┤┬┴┼`. If a pixel doesn't have any neighbours, don't change it.
So the output of the last text is:
```
│ ─┬── ┌─ │
└─ │ ┌┘ │
└──┘ ─┘
```
* You can take input as a boolean array.
* The input will always contain at least 1 pixel.
* You can count box-drawing chars as 1 byte.
* You can assume the input is padded with spaces.
Test cases
----------
```
## #
=>
── #
```
```
###
#
=>
─┬─
│
```
```
##### ##
# # #
########
=>
─┬─┬─ ┌─
│ │ │
─┴─┴──┴─
```
```
# #
#####
# #
=>
│ │
─┼─┼─
│ │
```
```
# # # # #
# # # #
# # # # #
# # # #
# # # # #
=>
# # # # #
# # # #
# # # # #
# # # #
# # # # #
```
```
#####
#####
#####
#####
#####
=>
┌┬┬┬┐
├┼┼┼┤
├┼┼┼┤
├┼┼┼┤
└┴┴┴┘
```
Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code wins. | 2016/09/19 | [
"https://codegolf.stackexchange.com/questions/93824",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/53745/"
] | [Jelly](http://github.com/DennisMitchell/jelly), ~~60~~ ~~52~~ ~~51~~ ~~50~~ ~~49~~ 48 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
======================================================================================================================================================
```
ṖḤ0;+Ḋ×
“µ³Q~E!G⁸ṗṫ\’ḃ61+9471Ọ⁾# j
ZÑ€4×Z++Ñ€ị¢Y
```
Saved a byte thanks to @[Dennis.](https://codegolf.stackexchange.com/users/12012/dennis)
The input is a boolean array of 1's and 0's. Iterates over each column and each row converting the head and tail of each infix of size 3 from a pair of binary digits to a decimal, and multiplies that with the center of each infix. Then it sums it with itself to find the index into `'#───│┌┐┬│└┘┴│├┤┼ '`.
[Try it online!](http://jelly.tryitonline.net/#code=4bmW4bikMDsr4biKw5cK4oCcwrXCs1F-RSFH4oG44bmX4bmrXOKAmeG4gzYxKzk0NzHhu4zigb4jIGoKWsOR4oKsNMOXWisrw5Higqzhu4vColk&input=&args=W1sxLDAsMSwxLDEsMSwwLDEsMSwwLDFdLFsxLDEsMCwxLDAsMCwxLDEsMCwwLDFdLFswLDAsMCwxLDEsMSwxLDAsMCwxLDFdXQ) ([case 2](http://jelly.tryitonline.net/#code=4bmW4bikMDsr4biKw5cK4oCcwrXCs1F-RSFH4oG44bmX4bmrXOKAmeG4gzYxKzk0NzHhu4zigb4jIGoKWsOR4oKsNMOXWisrw5Higqzhu4vColk&input=&args=W1sxLDEsMSwxLDFdLFsxLDEsMSwxLDFdLFsxLDEsMSwxLDFdLFsxLDEsMSwxLDFdLFsxLDEsMSwxLDFdXQ)) ([case 3](http://jelly.tryitonline.net/#code=4bmW4bikMDsr4biKw5cK4oCcwrXCs1F-RSFH4oG44bmX4bmrXOKAmeG4gzYxKzk0NzHhu4zigb4jIGoKWsOR4oKsNMOXWisrw5Higqzhu4vColk&input=&args=W1sxLDAsMSwwLDEsMCwxLDAsMV0sWzAsMSwwLDEsMCwxLDAsMSwwXSxbMSwwLDEsMCwxLDAsMSwwLDFdLFswLDEsMCwxLDAsMSwwLDEsMF0sWzEsMCwxLDAsMSwwLDEsMCwxXV0)) ([case 4](http://jelly.tryitonline.net/#code=4bmW4bikMDsr4biKw5cK4oCcwrXCs1F-RSFH4oG44bmX4bmrXOKAmeG4gzYxKzk0NzHhu4zigb4jIGoKWsOR4oKsNMOXWisrw5Higqzhu4vColk&input=&args=W1sxLDEsMCwxXV0))
Explanation
-----------
This relies on the same idea as my [answer](https://codegolf.stackexchange.com/a/93854/6710) in J but instead of processing on each 3x3 subarray, I process over each row and each column while still obtaining the same table of indices.
Over half of the bytes are spent generating the list of box characters `'#───│┌┐┬│└┘┴│├┤┼ '`. String literals start with `“` in Jelly and have different meanings depending on their terminator. Here the terminator `’` means that the string will be parsed as the code points of each character according to the Jelly [code page](https://github.com/DennisMitchell/jelly/wiki/Code-page), and convert from a list of base 250 digits to a decimal.
```
“µ³Q~E!G⁸ṗṫ\’ => 10041542192416299030874093
(bijective base 61) => [1, 1, 1, 3, 13, 17, 45, 3, 21, 25, 53, 3, 29, 37, 61]
(add 9471 and convert to char) => '───│┌┐┬│└┘┴│├┤┼'
```
Then convert that decimal to a list of digits in bijective base 61 and increment each by 9471 to move it into the range of the box characters and convert each using Python's `chr`. Then prepend it with a character literal `”#` and append a space `⁶`.
```
ṖḤ0;+Ḋ× Helper link - Input: 1d list A
Ṗ Get all of A except the last value
Ḥ Double each value in it
0; Prepend a 0
+ Add elementwise with
Ḋ All of A except the first value
× Multiply elementwise by A
“µ³Q~E!G⁸ṗṫ\’ḃ61+9471Ọ⁾# j Nilad. Represents '#───│┌┐┬│└┘┴│├┤┼ '
“µ³Q~E!G⁸ṗṫ\’ Get the code points of each char in the string and
convert from a list of base 250 digits to decimal
ḃ61 Convert that to a list of digits in bijective base 61
+9471 Add 9400 to each
Ọ Convert from ordinals to chars, gets '───│┌┐┬│└┘┴│├┤┼'
⁾# A pair of chars ['#', ' ']
j Join the pair using the box characters
ZÑ€4×Z++Ñ€ị¢Y Input: 2d list M
Z Transpose
Ñ€ Apply the helper link to each row of the transpose (each column of M)
4× Multiply each by 4
Z Transpose
+ Add elementwise with M
+ Add elementwise with
Ñ€ The helper link applied to each row of M
ị¢ Use each result as an index to select into the nilad
Y Join using newlines
Return and print implicitly
``` | MATL, 102 characters
====================
I assign a neighbour a value (1, 2, 4 or 8); their sum will match a character in a string containing the drawing characters. I think there is still lots of room for improvements, but for a rough draft:
```
' #│││─┌└├─┐┘┤─┬┴┼' % String to be indexed
wt0J1+t4$( % Get input, and append zeros at end of matrix (solely to avoid
% indexing a non-existent second row/column for small inputs)
ttttt % Get a whole load of duplicates to work on
3LXHY) % Select rows 2:end from original matrix (one of the many dupes)
w4LXIY) % Select rows 1:end-1 from the 'destination' summing matrix)
+HY( % Add the neighbors below, store in 'destination' matrix
tIY)b3LY)2*+IY( % +2* the neighbors above +-------------------------------+
tHZ)b4LZ)4*+HZ( % +4* the neighbors right |(note: H and I contain 1:end-1 |
tIZ)b3LZ)8*+IZ( % +8* the neighbors left | and 2:end respectively) |
HH3$) % Select the original matrix +-------------------------------+
* % Make sure only cells that originally had a # get replaced
1+) % Add one because the original string is one-indexed. Index using ).
```
Improvements to be made:
* Possibly replace the whole summing part with some kind of loop working on rotated copies of the matrix
* Ditch the entire thing and make something based on a single loop working through the matrix
* *Use modular indexing to work on a flattened vector from the original array* **(?)**
[Try it Online!](http://matl.tryitonline.net/#code=JyAj4pSC4pSC4pSC4pSA4pSM4pSU4pSc4pSA4pSQ4pSY4pSk4pSA4pSs4pS04pS8J3d0MEoxK3Q0JCh0dHR0dDNMWEhZKXc0TFhJWSkrSFkodElZKWJIWSkyKitJWSh0SFopYklaKTQqK0haKHRJWiliSFopOCorSVooSEgzJCkqMSsp&input=WzEgMSAxOzAgMSAwOyAxIDAgMV0) (may not have box drawing characters support) |
22,505,664 | ```
<html>
<head>
<title> Algebra Reviewer </title>
<style type="text/css">
h2
{
color: white;
font-family: verdana;
text-shadow: black 0.1em 0.1em 0.2em;
text-align: center;
}
table
{
font-family:verdana;
color: white;
text-shadow: black 0.1em 0.1em 0.2em;
}
</style>
<script type="text/javascript">
function question1()
{
if ("quiz.question1.value=='d'")
{
alert ("That's the correct answer!");
}
else
{
alert ("Oops! try again!");
}
}
</script>
</head>
<body>
</br>
<h2>
Here are 10 items for you to answer. You might need scratch paper- so get one before taking this reviewer.
</h2>
</br>
</br>
<center>
<table border="0" bgcolor="tan">
<tr> <td>
<ol>
<li> What is the equation of the line passing through point (3,8) and parallel to the line x - 3y = 5 ? </li>
</br>
</br>
<input type = "radio" name = "question1" onclick = "quiz.question1.value=='a'"/> y = 1/3 x + 5
</br>
<input type = "radio" name = "question1" onclick = "quiz.question1.value=='b'"/> y = 3x + 7
</br>
<input type = "radio" name = "question1" onclick = "quiz.question1.value=='c'"/> y = 3/5 x + 3
</br>
<input type = "radio" name = "question1" onclick = "quiz.question1.value=='d'"/> y = 1/3 x + 7
</br>
</br>
<input type = "button" onclick = "question1()" name = "question1" value = "Submit"/>
<br/>
<br/>
</td> </tr> </table> </center>
</body>
</html
```
The answer here should be the 4th radio button, but I think that the `if / else` statement is wrong. | 2014/03/19 | [
"https://Stackoverflow.com/questions/22505664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3437488/"
] | You never defined the quiz variable. Use value attribute to get selected radio button. Use the following code.
```
<html>
<head>
<title> Algebra Reviewer </title>
<style type="text/css">
h2 {
color: white;
font-family: verdana;
text-shadow: black 0.1em 0.1em 0.2em;
text-align: center;
}
table {
font-family:verdana;
color: white;
text-shadow: black 0.1em 0.1em 0.2em;
}
</style>
<script type="text/javascript">
function question1() {
var option = document.querySelector('input[name = "question1"]:checked').value;
if (option == 'd') {
alert("That's the correct answer!");
}
else {
alert ("Oops! try again!");
}
}
</script>
</head>
<body>
</br>
<h2>
Here are 10 items for you to answer. You might need scratch paper- so get one before taking this reviewer.
</h2>
</br>
</br>
<center>
<table border="0" bgcolor="tan">
<tr>
<td>
<ol>
<li> What is the equation of the line passing through point (3,8) and parallel to the line x - 3y = 5 ? </li>
</br>
</br>
<input type = "radio" name = "question1" value="a" /> y = 1/3 x + 5
</br>
<input type = "radio" name = "question1" value="b" /> y = 3x + 7
</br>
<input type = "radio" name = "question1" value="c" /> y = 3/5 x + 3
</br>
<input type = "radio" name = "question1" value="d" /> y = 1/3 x + 7
</br>
</br>
<input type = "button" onclick = "question1()" name = "question1" value = "Submit"/>
<br/>
<br/>
</td>
</tr>
</table>
</center>
</body>
</html>
``` | The `name` attribute for radio buttons and the submit button should not be same I guess.
Try changing `name` attribute of submit button. |
54,011,125 | Laravel echo server is started event is broadcasted but users are not able to join channel hence not able to listen the event.
```
1. ExampleEvent file:
class ExampleEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel('test-event');
}
public function broadcastWith()
{
return [
'data' => 'key'
];
}
}
2. Laravel-echo-server.json file
{
"authHost": "http://localhost",
"authEndpoint": "/broadcasting/auth",
"clients": [],
"database": "redis",
"databaseConfig": {
"redis": { },
"sqlite": {
"databasePath": "/database/laravel-echo-server.sqlite"
}
},
"devMode": true,
"host": null,
"port": "6001",
"protocol": "http",
"socketio": {},
"sslCertPath": "",
"sslKeyPath": "",
"sslCertChainPath": "",
"sslPassphrase": "",
"subscribers": {
"http": true,
"redis": true
},
"apiOriginAllow": {
"allowCors": false,
"allowOrigin": "",
"allowMethods": "",
"allowHeaders": ""
}
}
3. boostrap.js file laravel echo section
import Echo from 'laravel-echo'
window.io = require('socket.io-client');
window.Echo = new Echo({
broadcaster: 'socket.io',
host: window.location.hostname + ':6001'
});
window.Echo.channel('test-event')
.listen('ExampleEvent', (e) => {
console.log(e);
});
4.Channels.php file
<?php
Broadcast::channel('App.User.{id}', function ($user, $id) {
return (int) $user->id === (int) $id;
});
Broadcast::channel('test-event', function ($user, $id) {
return true;
});
5.env file redis section
BROADCAST_DRIVER=redis
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
Output: When i open http://127.0.0.1:8000/test-broadcast and on other browser http://127.0.0.1:8000/ not shown that user joined the channel etc and event details is not listen on other browser. Also not getting any error on command line or console log.
L A R A V E L E C H O S E R V E R
version 1.5.0
⚠ Starting server in DEV mode...
✔ Running at localhost on port 6001
✔ Channels are ready.
✔ Listening for http events...
✔ Listening for redis events...
Server ready!
Channel: test-event
Event: App\Events\ExampleEvent
Channel: test-event
Event: App\Events\ExampleEvent
Channel: test-event
Event: App\Events\ExampleEvent
Channel: test-event
``` | 2019/01/02 | [
"https://Stackoverflow.com/questions/54011125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10859050/"
] | I had the same issue.
Try this with this version `"socket.io-client": "2.3.0"`
Also debug the queue `php artisan queue:work sqs --sleep=3 --tries=3`
and resolve error if any | You have to choices in listening
1- Put full namespace of your event
```
window.Echo.channel('test-event')
.listen('App\\Events\\ExampleEvent', (e) => {
console.log(e);
});
```
2- To put name of this event in event file
```
public function broadcastAs()
{
return "example-event";
}
```
and call event in Echo with (dot) before the name of the event
```
window.Echo.channel('test-event')
.listen('.example-event', (e) => {
console.log(e);
});
``` |
17,985,666 | I want to join two below model class with entity framework in controller for present factor in accounting system in a view
```
<pre>
namespace AccountingSystem.Models
{
public class BuyFactor
{
public int BuyFactorId { get; set; }
public DateTime CreateDate { get; set; }
public string Seller { get; set; }
public string Creator { get; set; }
public decimal SumAllPrice { get; set; }
public ICollection<BuyFactorDetail> BuyFactorDetails { get; set; }
}
}
namespace AccountingSystem.Models
{
public class BuyFactorDetail
{
public int BuyFactorDetailId { get; set; }
public int Number { get; set; }
public string Description { get; set; }
public decimal SumPrice { get; set; }
public int BuyFactorId { get; set; }
public virtual BuyFactor BuyFactor { get; set; }
public virtual Commodity Commodity { get; set; }
}
}
</pre>
``` | 2013/08/01 | [
"https://Stackoverflow.com/questions/17985666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2640592/"
] | Just create another model then calls the other model in there
```
public class ParentModel
{
public BuyFactor BuyFactor {get; set;}
public BuyFactorDetail BuyFactorDetail {get; set;}
}
```
So when you will call it in view
```
@model IEnumerable<AccountingSystem.Models.ParentModel>
@Html.DisplayNameFor(model => model.BuyFactor.Creator)
``` | Use a Linq join query like
```
var query = (from b in context.BuyFactors
join d in context.BuyFactorDetail
on
..
select new
{
BuyFactorId = b.BuyFactorId,
....
BuyFactorDetailId = d.BuyFactorDetailId,
...
..
}));
``` |
13,143,713 | I have been following a tutorial on ListView and the following code gives errors. I have searched all the forums I can find but I keep coming up with the same recommended code. Maybe all the forums are quoting old versions and perhaps Android has moved on.
Anyway, here is the code and the error message:
```
getListView().setOnItemClickListener(new OnItemClickListener()
{
//@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
// TODO Sort out error and add function code
}
});
```
Error message:
```
Multiple markers at this line
-The method setOnItemClickListener(AdapterView.OnItemClickListener in the type
AdapterView <ListAdapter> is not applicable for the arguments (new OnItemClickListener(){})
-OnItemClickListener cannot be resolved to a type
```
Any offers? | 2012/10/30 | [
"https://Stackoverflow.com/questions/13143713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1716514/"
] | You should be able to solve this by specifying the parent class of **onItemClickListener** like this:
```
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
``` | I suggest like that,If there is ListView, `extends ListActivity` and handle listitem click in `onListItemClick`
```
@Override
protected void onListItemClick(ListView list, View view, int position, long id) {
super.onListItemClick(list, view, position, id);
//handle listitem click.
}
``` |
13,803 | What is the easiest way to disable the touch pad on a laptop?
I have a laptop which lacks a means to turn off the touchpad with a simple Function key sequence. I would like to disable the touchpad so that it stops detecting movement when I am typing. This is quite an annoyance as it sometimes results in deletions of sections of a sentence I am typing. Right now I have a thick piece of paper over the top to decrease the sensitivity.
Any other suggestions on how to do this? | 2009/07/27 | [
"https://superuser.com/questions/13803",
"https://superuser.com",
"https://superuser.com/users/2310/"
] | Original post isn't real clear on if you need something that can be quickly turned back on or not. Typically, the connector from the touchpad to the mobo is easily reached under the keyboard. You could unplug it as long as you don't need to be able to turn it on/off on the fly (and you're not worried about warranty/possible accidental damage concerns). Obviously, don't do this unless you're quite certain of what you're doing, etc. Poking/proding the wrong thing could cause permanent damage. Insert additional disclaimers here, etc. | Often the manufacturer will have custom software that does this. |
34,673 | >
> For God so loved the world, that he gave his only begotten Son, that whosoever believeth in him should not perish, but have everlasting life. [John 3:16 KJV]
>
>
>
I don't see how most Christians define the word "whosoever" as "anybody" and "all." If the word does mean "anybody" and "all," why did the Lord Jesus Christ said in John 17:9 that He is not praying for the world, but for those whom the Father has given Him? John 17 speaks of a people whom the Father has given to the Son and to whom the Son gave His life for their eternal security (verses 2-3, 6-7, 9, 11-12, 24).
Is it rather appropriate to think of the possibility that "whosoever" means all nations and that salvation is not only for the Jews but also for all kinds and sorts of people, since Jesus was talking to Nicodemus, a Jew and a Pharisee at the same time. | 2018/09/22 | [
"https://hermeneutics.stackexchange.com/questions/34673",
"https://hermeneutics.stackexchange.com",
"https://hermeneutics.stackexchange.com/users/26664/"
] | The Greek text uses a participle, so a more literal reading might be *everyone believing in Him ...*
In the phrase:
>
> πᾶς / ὁ πιστεύων / εἰς / αὐτὸν
>
> *Pas* / *ho* *pisteuōn* / *eis* / *auton*
>
>
>
the *ho pisteuōn* literally means "the believing [one]" - it is in the singular. *Pas* means "every". The perfectly literal Greek is clumsy - "every the believing [one]".
---
The verse does not specify any particular person or race. It refers, as the text said, to everyone believing in Him. This is reiterated in verse 36 (following KJV):
>
> *He that believeth on the Son*
>
> *Ho pisteuōn eis ton uion* - "The [one] believing in the Son"
>
> *hath everlasting life:*
>
> *echei zōēn aiōnion* - "has life eternal"
>
>
>
> *And he that believeth not the Son*
>
> *ho de apeithōn tō uiō* - "but/and the [one] disobeying the Son"
>
> *shall not see life*
>
> *ouk opsetai zōēn* - "shall/will not see life"
>
>
>
It is interesting to note here, I think, that, contrary to many translations, the Greek text does not say:
>
> *He that believes in the Son has eternal life*
>
> *And he that does not* believe *in the Son shall not see life*
>
>
>
but rather
>
> *He that believes* [*pisteuōn*] *in the Son has eternal life*
>
> *And he that does not* **OBEY** [*apeithōn*] *the Son shall not see life*
>
>
> | I believe in Romans it says he Foreknew, therefore he predestined. So that would mean on his foreknowledge, he predestined people who would be saved based on the decision he knew they would make. |
55,696,920 | I am trying to use Scaffold-DbContext from Entity Framework Core to create Models from an existing MS Access Database.
In Package Manager Console when I run the command:
```
Scaffold-DbContext "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Folder\Database.mdb;" EntityFrameworkCore.Jet
```
I get the following error:
```
Could not load type 'System.Data.OleDb.OleDbConnection' from assembly 'System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=123123123'.
```
I'm using a ClassLibrary project with the following setup:
```
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<PlatformTarget>AnyCPU</PlatformTarget>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="EntityFrameworkCore.Jet" Version="2.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.2.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.2.4">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
</ItemGroup>
</Project>
```
I'm using the [EntityFrameworkCore.Jet](https://github.com/bubibubi/EntityFrameworkCore.Jet) provider.
Both x32 and x64 OleDb Dll's are in the machine:
```
C:\Program Files\Common Files\microsoft shared\OFFICE14\ACEOLEDB.DLL
C:\Program Files (x86)\Microsoft Office\root\VFS\ProgramFilesCommonX86\Microsoft Shared\OFFICE16\ACEOLEDB.DLL
```
The x64 installed from Microsoft Access Database Engine 2010 Redistributable
and the x32 from Office Professional Plus 32-bit
Scaffold SQL database works fine.
Already went to <https://github.com/bubibubi/EntityFrameworkCore.Jet/wiki/Limitations>
Is something missing or this setup should work? Any help would be appreciated. | 2019/04/15 | [
"https://Stackoverflow.com/questions/55696920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5454582/"
] | You need to target .Net Framework.
Actually OleDb is not ported to .Net Core.
<https://github.com/dotnet/corefx/issues/23542>
You can try with .Net Framework 4.6 or 4.7. | System.Data.OleDb for .NET Core is now available on NuGet.org as per: <https://github.com/dotnet/runtime/issues/23321#issuecomment-502413964> |
72,195,673 | I want to get the list of all file names in a directory but the order of files matters to me. (And I'm using ***Google Colab*** if that matters)
---
>
> P.S: I've accepted the first answer, but just in case know that when I
> moved my files from google drive to my local PC and run the code, it
> worked and printed those with the original order. I think there is
> something with the Google Colab
>
>
>
---
Suppose my files are in this order in my directory:
```
file1.txt
file2.txt
file3.txt
...
filen.txt
```
>
> P.S: These file names are just examples to be clear. In reality my
> filenames don't have any pattern to be sorted, they are like
> `1651768933554-b6b4deb3-f245-4763-b38d-71a4b19ca948.wav`
>
>
>
When I get the file names via this code:
```
import glob
for g in glob.glob(MyPath):
print(g)
```
I'll get something like this:
```
file24.txt
file5.txt
file61.txt
...
```
I want to get the file names in the same order they are in the folder.
I searched as far as I could but I didn't find any SO post solving my problem. Appreciate any help.
P.S: I tried `from os import listdir` too but didn't work. | 2022/05/11 | [
"https://Stackoverflow.com/questions/72195673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7339624/"
] | The way they exist in the folder isn't really a thing. In reality they are all sitting somewhere in memory and not necessarily next to each other in any way. The GUI usually displays them in alphabetical order, but there are also usually filters you can click to sort them in whatever way you choose.
The reason they are printing that way is because it is alphabetical order. Alphabetically `2` comes before `5` so `24` comes before `5`. | Although I agree with the other comment, there is the option to use natural language sorting. This can be accomplished with the [natsort](https://github.com/SethMMorton/natsort) package.
```py
>>> from natsort import natsorted
>>> files = ['file24.txt', 'file5.txt', 'file61.txt']
>>> sorted_files = natsorted(files)
>>> sorted_files
['file5.txt', 'file24.txt', 'file61.txt']
```
**Edit:**
Sorry I didn't see this in the package before. Even better for your needs, see `os_sorted` from `natsort`.
```py
>>> from natsort import os_sorted
>>> files = ['file24.txt', 'file5.txt', 'file61.txt']
>>> sorted_files = os_sorted(files)
>>> sorted_files
['file5.txt', 'file24.txt', 'file61.txt']
```
Or, in the essence of `os.listdir()`...
```py
>>> sorted_directory = os_sorted(os.listdir(directory_path))
``` |
33,881,446 | In VBA, when you use the OR statement, will the processor check through all criteria regardless of whether it has already found a FALSE statement?
i.e. for:
```
If CriteriaA OR CriteriaB OR CriteriaC OR CriteriaD Then
Exit Function
End If
```
If CriteriaA is false, will the other criteria be checked unnecessarily? And is CriteriaA always checked first?
I'm wondering since each of these checks takes a significant amount of time and I only need to know whether one is false. In this case, I have put the most commonly failed criteria check first in the list, so that it will cause the function to fail before having to do any more work. Is this a correct assumption? | 2015/11/23 | [
"https://Stackoverflow.com/questions/33881446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2566283/"
] | Alright guys, I took some bits and pieces from other answers and came up with what I think is the best solution for me:
```
$domain = 'example.com';
$hostname = 'www.' . $domain;
$file_contents = '127.0.0.1 {{domain}} {{hostname}}';
$result = preg_replace_callback(
"/{{(.+?)}}/",
function ($matches) {
return $GLOBALS[$matches[1]];
},
$file_contents
);
```
This answer combines ideas from @TonyDeStefano, @dops, and @fschmengler. So please up-vote them. @BugaDániel also helped with his comments. | You could use a `preg_replace_callback` to do this, you will need to put your replacements into an array though.
e.g
```
$domain = 'example.com';
$newString = preg_replace_callback(
'/{{([^}}]+)}}/',
function ($matches) {
foreach ($matches as $match) {
if (array_key_exists($match, $_GLOBALS))
return $replace[$match];
}
},
$file_contents
);
```
The matches returned for that particular regex would be an array
```
array [
'{{hostname}}',
'hostname',
'{{domain}}',
'domain'
]
```
Which is why we would do a check with `array_key_exists` |
9,529 | In the first major action between the Germans and Americans, at [the battle of Kasserine Pass](http://en.wikipedia.org/wiki/Battle_of_the_Kasserine_Pass) , the Germans inflicted casualties against (mostly) the inexperienced Americans at the rate of about 5 to 1. Fortunately, the Americans were able to improve substantially on this ratio in the days and weeks ahead.
The early American experience was by no means atypical; the [Poles suffered physical casualties of between 3 and 4 to 1 in 1939](http://en.wikipedia.org/wiki/Invasion_of_Poland_(1939)), with this rising to about 15 to 1 counting prisoners. Allied to German casualty rates in France 1940 were similarly lopsided.
In the first few months of the 1941 campaign, the Soviets suffered casualties at six or seven times the German rate.
With the notable exception of Kasserine Pass, where American artillery held the day, the massive German kill ratios (in Poland in 1939, in France in 1940, and in the Soviet Union in 1941) were accompanied by massive territorial gains.
This ratio fell steadily in 1942, with the Soviet to German casualty ratio of roughly 2 to 1, in line with their respectively populations, at the "turning point" campaign of Stalingrad. Diminishing kill ratios accompanied "diminishing returns" for the Germans in 1942.
In a war between 80 million (ethnic) Germans on one side, 130 million Americans, 170 million Soviets, and 50 million Britons on the other, the Germans would have won if they could inflict casualties at the rate of 5 to 1 (or "better") on the Allies throughout the war, the latter' superiority in manpower and material notwithstanding. The Soviets, British, and Americans won because they were able to bring their loss ratios below their overall numerical preponderance.
Have any historical accounts tied Germany's early successes to the their massive early "kill ratios," and their subsequent lack of success to the fact that their "kill ratios" fell below their overall numerical disadvantage? | 2013/07/12 | [
"https://history.stackexchange.com/questions/9529",
"https://history.stackexchange.com",
"https://history.stackexchange.com/users/120/"
] | The only time "kill ratios" really matter all that much is when using [attrition warfare](http://en.wikipedia.org/wiki/Attrition_warfare).
While important in World War I, to the best of my knowledge, this strategy was never employed in a large scale on the fronts Germany was involved in.\* The Germans themselves went out of their way to avoid this kind of warfare, instead preferring fast exploitation of front breakthroughs to cut the communications (and force the surrender) of large numbers of enemy units.
The Germans' basic problem was that they had less resources (in both men and material) than their opponents, so in the long run any serious losses on their side, regardless of ratios, would doom them. Russia could have afforded to operate at a deficit in losses the entire war, and still could have won, as long as they could make it up more than the Germans could.
Eventually the Germans stretched themselves too thin on the Russian front, and the Russians were able to gather enough forces to start achieving their own breakthroughs. If you keep track of "ratios", perhaps things started to swing in the UN's favor at this point, but the underlying issue was that the German forces couldn't replace their losses on anywhere near the scale that the Russians could. Any changes in loss ratios you may see at that point are a symptom, not the cause. | As mentioned by many here, kill ratios are only really significant if you're talking attrition warfare or at a basic tactical level. Otherwise they're an effect of losing the war, not a cause.
The underlying question of *why* those kill ratios turned against Germany is a very complicated one, but one important aspect is that the Germans had invented a new kind of mobile warfare and the Allies had to play catch up.
People often fail to appreciate just how much tactics and technology changed from 1939 to 1945. In the air, all-metal, monoplane military aircraft had only just replaced the biplane in front-line service (and in some cases, such as the [Fairey Swordfish](https://en.wikipedia.org/wiki/Fairey_Swordfish), it hadn't). On the ground, radios were bulky and expensive, and communication was still a laborious process often done by runners or cable. Tactically, many units and vehicles still lacked radios limiting the sophistication of their maneuvers and tactics; you can only get so fancy with flags and flares. At sea, the aircraft carrier was still untried, and the submarine still unconquered.
The Germans exploited this technological change by increasing the pace of warfare dramatically. They introduced radios at the tactical level, in individual tanks and aircraft. They trained their air, infantry, artillery, and armor to work in concert. They imbued local commanders with the know-how and ability to adapt to the local situation and make local decisions without waiting for orders form higher command. They added paratroopers to overcome strategic obstacles, and tactical air strikes to support deep penetrations.
The situation was now liable to change in hours rather than days. This is a pace the Allies were not prepared for. It's a pace that allowed the German army to find gaps and exploit them before the Allies could react. At this pace, the Allies could never be quite sure of where the Germans were. Superior Allied forces were surrounded and cut off as they raced to defend positions that had already been overrun. Faced with this chaotic situation, the Allies often retreated if they were unsure of their flanks.
The Germans ran rampant with this new style of warfare from 1939 to 1941, but the remaining undefeated Allies were learning. The Soviets and British learned through facing the Germans, being defeated, and having to rebuild their armies. The Americans were also building an army, but they had the luxury of doing it in peacetime, observing what was going on in Europe, and learning from it. The North African campaign let the US Army learn some hard lessons at a relatively small cost through defeats like [Kasserine](https://en.wikipedia.org/wiki/Battle_of_Kasserine_Pass). |
7,413,111 | When send sms from a device to another sometime it received in both devices.
I don't find any error in source code.
Please help me.
NOTE:
this is send source code:
```
try {
String addr = "sms://" + txt_number.getString()+":1234";
MessageConnection conn = (MessageConnection) Connector.open(addr);
TextMessage msg = (TextMessage) conn.newMessage(MessageConnection.TEXT_MESSAGE);
msg.setPayloadText(txtSMS.getString());
conn.send(msg);
conn.close();
} catch (IOException ex) { ex.printStackTrace(); }
<blink>and this is receive opretion .this opration support by a thread <blink>
public void run() {
String addr="sms://:1234";
Message msg=null;
try {
conn = (MessageConnection) Connector.open(addr);
while(true)
{
msg=conn.receive();
String mSenderAddress = msg.getAddress();
if (msg instanceof TextMessage) {
String msgTReceived = ((TextMessage)msg).getPayloadText();
Analize_TEXT_message(mSenderAddress,msgTReceived);
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
``` | 2011/09/14 | [
"https://Stackoverflow.com/questions/7413111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/941923/"
] | I realise this question has already been answered, but for those looking for somewhat different (not saying better) approach, here is the Magento extension I wrote <https://github.com/ajzele/Inchoo_LoginAsCustomer>. It does not rewrite any blocks, it uses event/observer to inject Login as Customer button on the customer edit screen. It further uses combination of admin and frontend controller to pass the encrypted customer info around so it knows which customer to login. | For those who does not want to debug the solution you can install the extension via magento connect:
<http://www.magentocommerce.com/magento-connect/login-as-customer-9893.html>
It allows to login from customer view and order view pages from admin. The extension is stable and works fine in all cases |
68,499,676 | I just want to iterate over "banana" and exchange each letter with "A" to obtain a new string "AAAAAA". Why this code doesn't work?
```
let word = "banana";
for (letter of word)
{
letter = "A";
return word;
}
``` | 2021/07/23 | [
"https://Stackoverflow.com/questions/68499676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16510560/"
] | You are actually overwritting the [local variable](https://developer.mozilla.org/docs/Glossary/Local_variable) `letter` once, then you return the unchanged `word`
If you want to replace all letters by a `'A'`, you can [`repeat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat) that letter as much time as the length of the string :
```js
let word = 'banana';
word = 'A'.repeat(word.length);
console.log(word);
``` | If you want to replace each character, you can use .replace() with a regex for exchange each letter. <https://developer.mozilla.org/en-US/docs/Glossary/Regular_expression>.
```
let word = "banana";
let regex = /([A-z])/g //
let pSplit = word.replace(regex,"A");
console.log(pSplit);
```
<https://jsfiddle.net/tw85bnp4/> |
42,904 | Sweden was one of the warring parties in the [First Barbary War](https://en.wikipedia.org/wiki/First_Barbary_War) (1801-1805) with 3 frigates from the Swedish navy.
I had read that Sweden had a [colony in Gold Coast](https://en.wikipedia.org/wiki/Swedish_Gold_Coast) (modern Ghana), taken from the Dutch, from 1650 to 1663, but was not aware that the Scandinavian country was doing any business in Africa in 1800's.
One thought was that perhaps this had something to do with pirates from Africa stealing Europeans to slavery, but the sources I have found on this do not mention Swedish victims. For example the [Wikipedia article on Barbary Wars](https://en.wikipedia.org/wiki/Barbary_Wars) says that British and American ships had been attacked:
>
> Since the 1600s, the Barbary pirates had attacked British shipping
> along the North Coast of Africa, holding captives for ransom or
> enslaving them. Ransoms were generally raised by families and local
> church groups. The British became familiar with captivity narratives
> written by Barbary pirates' prisoners and slaves.[5]
>
>
> During the American Revolutionary War, the pirates attacked American
> ships.
>
>
>
This Wikipedia article does also mention that the pirates from northern Africa had attacked coastal towns in Europe all the way to Iceland:
>
> In addition to seizing ships, they engaged in razzias, raids on
> European coastal towns and villages, mainly in Italy, France, Spain,
> and Portugal, but also in England, Scotland, the Netherlands, Ireland,
> and as far away as Iceland. The main purpose of their attacks was to
> capture European slaves for the Arab slave market in North Africa.[4](http://www.bbc.co.uk/history/british/empire_seapower/white_slaves_01.shtml)
>
>
>
The source referenced by the above section is a BBC article titled "[British Slaves on the Barbary Coast](http://www.bbc.co.uk/history/british/empire_seapower/white_slaves_01.shtml)". This article estimates the number of Europeans taken as slaves to be as high as 1,250,000:
>
> for the 250 years between 1530 and 1780, the figure could easily have
> been as high as 1,250,000 - this is only just over a tenth of the
> Africans taken as slaves to the Americas from 1500 to 1800, but a
> considerable figure nevertheless.
>
>
>
Still none of these sources explicitly mention Swedish prisoners.
**Question:**
What kind of business or involvement did Sweden have in northern Africa and what developments lead to it being a party in the First Barbary War? | 2018/01/12 | [
"https://history.stackexchange.com/questions/42904",
"https://history.stackexchange.com",
"https://history.stackexchange.com/users/28581/"
] | There is a detailed account of the events available [here](https://books.google.se/books?id=dSw5AQAAIAAJ), in swedish. I will summarize briefly.
First we must note that Tripoli declared war all the time, versus different countries. It was part of their strategy. A declaration of war from Tripoli was nothing but a pretext for demanding additional sums when negotiating for peace, in addition to raising the annual tributes that all countries who did commerce in the mediterranean sea (that includes Sweden) had to pay to the barbary states as protection money against piracy.
An example of what could happen: Tripoli makes up an excuse to go to war (e.g. through ridiculous demands that the extorted party could not agree to). Once at war, the Tripolitan fleet captures trading ships, turning the sailors into slaves. There is but one way to peace: A new peace negotiation which means increased annual tributes, plus a large sum of money for the release of the slaves and ships that have been captured. To get a better position in those negotiations however, some countries (such as Sweden in this case) decided to send frigates to the shores of Tripoli to blockade its port, protecting its own trade vessels and putting pressure on Tripoli at the same time.
The point I am making is that the exact events of what led up to Sweden's involvement in the first Barbary war is not that important, still I promised a summary:
Two years after Yusuf Karamanli became Pasha, in 1797, he captured two swedish ships. He then complained to the swedish consul about not receiving a gift from Sweden upon ascending the throne, and for not receiving a gift for Gustav IV Adolf's ascension in 1796. He was promised such gifts and the ships were allowed to set sail. The transportation of the gifts took too long for the impatient Karamanli, hence he declared war. Sweden negotiated for peace and signed an expensive treaty in 1798.
The peace did not last long, in 1799 a french commander selected a swedish ship to transport gifts from France to Tripoli. The ship was captured by the portuguese, who were already at war with Tripoli. Karamanli decided to blame Sweden and required that Sweden should arrange the return of the gifts from the portuguese. The Pascha also provoked Sweden further by e.g. capturing swedish ships despite the peace. The swedish consul Cöster agreed to pay the Pascha a substantial amount, worth in total about the same amount as a decade of tributes. Gustav IV Adolf was not pleased and so in February of 1800 he declared war on Tripoli himself, and so the war began. | This answer focuses on the *casus belli*, the cause for Swedish participation in the Barbary Wars.
Quoting [James L. Cathcart](https://en.wikipedia.org/wiki/James_Leander_Cathcart), Monticello.org states:
>
> **The First Barbary War**
>
>
> ... Cathcart explained to the Secretary of State why America owed nothing to the pasha and how he was regularly at war with some country or other from which he would demand beneficial negotiations. (He was then ***at war with Sweden which would soon agree to pay annual tribute and ransom for 131 captives; Swedish merchantmen had been seized by Tripolitan corsairs since the angered Pasha had broken an existing treaty and declared war a few months earlier***)
>
>
>
source: [Monticello.org](https://www.monticello.org/site/research-and-collections/first-barbary-war#footnote14_h6mxey6)
"*Pasha*" in the quote refers to [Yusef Caramanli](https://en.wikipedia.org/wiki/Yusuf_Karamanli). |
102,710 | Lately I've been thinking of a saying that describes the following:
>
> *Ruining something for someone else, for the sole purpose of it not being useful any more to the other party, even though you do not need it yourself in any way.*
>
>
>
I thought that "spoils of war" / "warspoils" was a saying / "proverb" that was used for the above description, but apparently it's not really what I thought it was.
So my question is twofold:
1. What exactly does "spoils of war" mean?
2. Is there a certain saying/proverb that "matches" my description? | 2013/02/02 | [
"https://english.stackexchange.com/questions/102710",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/-1/"
] | How about *raze to the ground*?
Conquering armies would often raze a city to the ground, ie completely demolish it so that it was no longer habitable. | A (very) late answer, but the first thing I thought of when reading the description was
>
> Being a [spoil-sport](http://www.thefreedictionary.com/spoilsport).
>
>
>
Meaning that you ruin someone's pleasure in something, usually without any direct benifits to one-self except the "pleasure" of hurting the other person. (Although it does not have to be done on purpose or with the goal of hurting someone.)
This expression might explain the confusion with *spoils of war* as well. |
394,121 | I'm having a debate with a friend. He claims that if you change the rotation of the shaft of a dynamo the output DC current changes direction. I, however, claim otherwise. The way I see it is that a dynamo rotates a coil inside a magnetic field, this produces an AC sine wave which then gets rectified to DC by the commutator. If you rotate the coil in the other direction it still produces AC and then gets rectified to DC in the same direction as if the shaft were rotating in the original way, right?
So who is correct? If it's my friend then why does the DC current change direction?
Any help is greatly appreciated. | 2018/09/03 | [
"https://electronics.stackexchange.com/questions/394121",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/197289/"
] | Sorry, your friend is correct.
A permanent magnet dynamo is the same as a permanent magnet motor. If the motor polarity is reversed the motor spins in reverse. Similarly the EMF generated by the dynamo will reverse with rotation reversal.
[](https://i.stack.imgur.com/SAZKk.gif)
*Figure 1. A really simple motor/dynamo. Source [S-Cool](https://www.s-cool.co.uk/gcse/physics/magnetism-and-electromagnetism/test-it/exam-style-questions).*
The brushes aren't providing rectification of the supply - they're rectifying the windings. Notice that current can flow either direction but that the coil's orientation doesn't matter as the brushes correct it. | Your friend is closer. If the dynamo has permanent magnet, then the brushes would act as rectifier. Or we can say it's a brush DC motor with a permanent magnet.
The rotor is a coil with a commutator, meanwhile the stator has a constant field produced from permanent magnet. If you change polarity on rotor, the motor will spin in the opposite direction.
The dynamo is the same machine, as electrical machine are dual acting they can work as motor or generator. Therefore if you spin the rotor in both directions, the polarity will change. |
2,128,986 | I know the following:
asp.net webforms, mvc, sql server 2005/2008, web services, and windows services.
I want to expand so I can be a little more versatile.
What things should I be focusing on? (this is general guidance, with a web focus)
I am thinking:
SSIS
windows workflow
sharepoint
What other common skills should I know that seem to be go well with what I know already? | 2010/01/24 | [
"https://Stackoverflow.com/questions/2128986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39677/"
] | Not technologies but principles really
[SOLID](http://www.lostechies.com/blogs/chad_myers/archive/2008/03/07/pablo-s-topic-of-the-month-march-solid-principles.aspx)
[ORM](http://www.lalitbhatt.com/tiki-index.php?page=Introduction+to+ORM)
[TDD](http://www.artofunittesting.com/)
[DDD](http://domaindrivendesign.org/) | Architectural/design patterns are a big plus. Understanding how technology should be applied when in charge of an application, what technologies to choose in different situations.
If you like the web focus, AJAX, the MS AJAX framework, JQuery, is good to know. Silverlight is also good to know... |
48,805,886 | I had a .NET core 1.0 webapp working fine. I had to upgrade to .NET Core 2.0. I also had to add a migration step for my SQLite database.
If I launch this command:
>
> Add-Migration MyMigrationStepName
>
>
>
I get this error:
>
> Unable to create an object of type 'ServicesDbContext'. Add an
> implementation of 'IDesignTimeDbContextFactory' to
> the project, or see <https://go.microsoft.com/fwlink/?linkid=851728> for
> additional patterns supported at design time.
>
>
>
I've seen plenty of answers on SO and on other blogs and website but none of them actually say where to implement such interface and what code the concrete method should contain! | 2018/02/15 | [
"https://Stackoverflow.com/questions/48805886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/958464/"
] | **Sample**:
```
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }
}
public class ApplicationContextDbFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
{
ApplicationDbContext IDesignTimeDbContextFactory<ApplicationDbContext>.CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
optionsBuilder.UseSqlServer<ApplicationDbContext>("Server = (localdb)\\mssqllocaldb; Database = MyDatabaseName; Trusted_Connection = True; MultipleActiveResultSets = true");
return new ApplicationDbContext(optionsBuilder.Options);
}
}
```
**Location**:
Put that class where the ApplicationDbContext is put. It will then be automatically picked up when you use dotnet ef cli commands. | I solve the problem by simply updating Program.cs to the latest .NET Core 2.x pattern:
**From 1.x:**
```
using System.IO; using Microsoft.AspNetCore.Hosting;
namespace AspNetCoreDotNetCore1App {
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseApplicationInsights()
.Build();
host.Run();
}
} }
```
**To 2.x:**
```
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
namespace AspNetCoreDotNetCore2App
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
}
```
Source: <https://learn.microsoft.com/en-us/ef/core/miscellaneous/cli/dbcontext-creation> |
45,900,542 | I have a div of text that I wish to be able to scroll through without showing the vertical scroll bar. I have followed this but to no avail, the text scrolls however the scroll bar is still visible.
[Hide scroll bar, but while still being able to scroll](https://stackoverflow.com/questions/16670931/hide-scroll-bar-but-while-still-being-able-to-scroll)
```css
#activity_parent {
height: 100%;
width: 100%;
overflow: hidden;
}
#activity_child {
width: 100%;
height: 100%;
overflow-y: scroll;
padding-right: 17px; /* Increase/decrease this value for cross-browser compatibility */
}
```
```html
<div id="activity_parent">
<div id="activity_child">
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
good<br/>bye.
</div>
</div>
``` | 2017/08/26 | [
"https://Stackoverflow.com/questions/45900542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1567212/"
] | What browser are you working with because after testing your code, the vertical scroll bar is not showing here.
Better still place the CSS within a style tag as shown below
```
<html>
<style>
#activity_parent {
height: 100%;
width: 100%;
overflow: hidden;
}
#activity_child {
width: 100%;
height: 100%;
overflow-y: scroll;
padding-right: 17px; /* Increase/decrease this value for cross-browser
compatibility */
}
</style>
<body>
<div id="activity_parent">
<div id="activity_child">
<!-- you content goes here -->
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
hello<br/>I<br/>am<br/>here<br/>
good<br/>bye.
</div>
</div>
</body>
</html>
``` | you can use Web-kit Css, just set "width: 0px" and u stil will be able to scroll.
```css
::-webkit-scrollbar {
background-color: #042654;
width: 0px;
}
::-webkit-scrollbar-track {
background-color: #bebebe;
border-radius: 0px;
}
::-webkit-scrollbar-thumb {
background-color: #8192A9;
border-radius: 0px;
}
``` |
2,842,232 | What are the use cases of having two constructors with the same signature?
Edit: You cannot do that in Java because of which Effective Java says you need static factory. But I was wondering why would you need to do that in the first place. | 2010/05/16 | [
"https://Stackoverflow.com/questions/2842232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/82368/"
] | The reason you would want to have two (or more) constructors with the same signature is that data type is not synonymous with meaning.
A simple example would be a Line class.
Here's one constructor: `public class Line(double x1, double y1, double x2, double y2)`
Here's another: `public class Line(double x1, double y1, double angle, double distance)`
The first constructor defines two end points of a line. The second constructor defines one end point, and the angle and distance to the second end point.
Java cannot distinguish between the two Line class constructors, true. But there are good reasons for 2 or more constructors to have the same signature. | You wouldn't, and you can't anyway. It wouldn't compile the class files into bytecode as there's no way for the program to differentiate between them to decide which one to use. |
47,833,759 | I have the following problem:
Path of image is being stored to DB, but the actual file in Storage folder as a complete different name and I can't find a way to retrieve to display in view:
public function savePicture(Request $request){
```
if($request->hasFile('image')) {
$image_name = $request->file('image')->getClientOriginalName();
$image_path = $request->file('image')->store('public');
$image = Image::make(Storage::get($image_path))->resize(320,240)->encode();
Storage::put($image_path,$image);
$image_path = explode('/',$image_path);
$user_id = $request->input('user_id');
$user = User::find(Auth::user()->id);
$user->image = Storage::url($image_name);
$user->save();
return back();
} else{
return "No file selected";
}
```
This is the Query to get the path, but cant make it work, because its an object and $pic->image not working in view
```
$imagen = DB::table('users')
->select('image')
->where('id', '=', Auth::user()->id);
return view('/tablero', [
'posts' => $posts,
'pic' => $image,
]);
```
My Database loos like
image: /storage/name.png
But in my Storage folder I get d7f7r87RmMy4NtCFvbJ8sQeutfC5wtsiak7GZXcn.png
I've been trying different ways to display the Image but it's not working. What am I missing? | 2017/12/15 | [
"https://Stackoverflow.com/questions/47833759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9073203/"
] | Try something like that;
```
int index = 0;
foreach (var s in varEnclist)
{
Mystring = Mystring.Replace(s, varDataList[index]);
index++;
}
```
**Output:**
```
1214arajark
``` | I am not sure what is your exact requirement hope this helps
```
string Mystring = "adhbegadhjmqadguvaadgaegadguvabdh";
StringBuilder sb = new StringBuilder(Mystring);
sb.Replace("dfd", "a");
sb.Replace("fee", "b");
sb.ToString();
```
or this one will help
```
string[] str = { "dfd", "dfdf" };
string[] abc = { "a", "b" };
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.Length; i++)
{
str[i] = abc[i];
sb.Append(str[i]);
}
sb.ToString();
``` |
38,842,129 | I am working on an app which requires communication with OData service (Microsoft Dynamics CRM to be exact). I have a requirement where I only need to know what all properties does the entity have.
e.g.
```
[Organization URI]/api/data/v8.1/contacts
```
returns all the contacts, however I want only property definitions of the contact.
Right now `[Organization URI]/api/data/v8.1/contacts` returns the JSON with values, however what I am looking is something schema of contacts entity. It should return me what all properties it has (e.g. `firstname`, `lastname`) and possibly the type of properties.
I tried using `$metadata` but without any luck. Is it possible to get information about entity only?
Any help would be appreciated. | 2016/08/09 | [
"https://Stackoverflow.com/questions/38842129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1635060/"
] | See [Query Metadata using the Web API](https://msdn.microsoft.com/en-us/library/mt607522.aspx "Query Metadata using the Web API"). The previous answer is close but you need the `$expand=Attributes` to get the list of Attributes. Plus it gets all entities where you want to filter on Contact.
```
GET [Organization URI]/api/data/v8.1/EntityDefinitions?$select=LogicalName&**$expand=Attributes($select=LogicalName)**&$filter=SchemaName eq 'Contact'
```
In the returned JSON you'll find the attributes at
```
value[0].Attributes
```
Which is an array. In this case I `$select=LogicalName` so each one has the property LogicalName (as well as the MetadataId which is the GUID for that property).
So the first `$select` is for properties from the entities.
The `$expand` tells CRM to include the Attributes. The inner `$select` tells which fields to return on the Attribute. The `$filter` makes sure they only return all this metadata for Contact. | If you are using the Web Api (looks like you are), then you can retrieve the `EntityMetadata` which has a navigation property for `AttributeMetadata`, which will describe attributes (aka; fields, properties).
`[Organization URI]/api/data/v8.1/EntityDefinitions`
[Use the Web API with CRM metadata](https://msdn.microsoft.com/en-us/library/mt607833.aspx)
For example: `GET [Organization URI]/api/data/v8.1/EntityDefinitions?$select=DisplayName,IsKnowledgeManagementEnabled,EntitySetName&$filter=SchemaName eq 'Contact' HTTP/1.1`
Further examples at [Query Metadata using the Web API](https://msdn.microsoft.com/en-us/library/mt607522.aspx) |
808,617 | A sort is said to be stable if it maintains the relative order of elements with equal keys. I guess my question is really, what is the benefit of maintaining this relative order? Can someone give an example? Thanks. | 2009/04/30 | [
"https://Stackoverflow.com/questions/808617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/70935/"
] | It means if you want to sort by Album, AND by Track Number, that you can click Track number first, and it's sorted - then click Album Name, and the track numbers remain in the correct order for each album. | The advantage of stable sorting for multiple keys is dubious, you can always use a comparison that compares all the keys at once. It's only an advantage if you're sorting one field at a time, as when clicking on a column heading - [Joe Koberg](https://stackoverflow.com/questions/808617/what-is-the-benefit-for-a-sort-algorithm-to-be-stable/808658#808658) gives a good example.
Any sort can be turned into a stable sort if you can afford to add a sequence number to the record, and use it as a tie-breaker when presented with equivalent keys.
The biggest advantage comes when the original order has some meaning in and of itself. I couldn't come up with a good example, but I see [JeffH](https://stackoverflow.com/questions/808617/what-is-the-benefit-for-a-sort-algorithm-to-be-stable/808668#808668) did so while I was thinking about it. |
2,452,973 | I have a project which has a set of binary dependencies (assembly dlls for which I do no have the source code). At runtime those dependencies are required pre-installed on the machine and at compile time they are required in the source tree, e,g in a lib folder.
As I'm also making source code available for this program I would like to enable a simple download and build experience for it. Unfortunately I cannot redistribute the dlls, and that complicates things, since VS wont link the project without access to the referenced dlls.
Is there anyway to enable this project to be built and linked in absence of the real referenced dlls?
Maybe theres a way to tell VS to link against an auto generated stub of the dll, so that it can rebuild without the original? Maybe there's a third party tool that will do this? Any clues or best practices at all in this area?
I realize the person must have access to the dlls to run the code, so it makes sense that he could add them to the build process, but I'm just trying to save them the pain of collecting all the dlls and placing them in the lib folder manually. | 2010/03/16 | [
"https://Stackoverflow.com/questions/2452973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/78828/"
] | Maybe one of these ideas will help you to solve the problem:
* Derive interfaces from all classes in the 3rd party dlls. Put these interfaces into an own project (same solution) and add a reference to this interface assembly. Also add an EventHandler to [AppDomain.AssemblyResolve](http://msdn.microsoft.com/de-de/library/system.appdomain.assemblyresolve(VS.80).aspx) and try to find and load the assemblies at run-time. (Credits go to NG)
+ Depending on how big the dlls are and how often changes are made to the public part this can get a real pain.
* Provide a readme.txt where you explain how to get the needed assemblies and where the user should put them relative to the project path. Normally VS is smart enough to remove the exclamation mark right after you put the assembly into the right spot, where the project references it from (maybe you have to press refresh in Solution Explorer) (Credits go to Paul)
+ Don't forget to add the readme.txt also to your **solution** by right clicking on your solution and select 'Add -> Existing Item'. In this case it will get a quite prominent place within visual studio Solution Explorer and the user can read it on a double click.
* Create another project within your solution that is able to download all the needed dlls automatically and to put them into the right spot. Maybe it should check beforehand if these needed files are already there before it starts to download. Set the Project Dependencies of your original project, so that it will depend on this one. So it will always be built before your original one. Then start this download helper tool in the pre-build event of your original project and don't forget to exit your program with an int value. 0 means success, any other error and so also Visual Studio knows if your tool was successfull and stops the compile process before hanging on missing dlls.
+ Maybe it is nearly impossible to automatically download the files, cause you need a login to a webpage or some cookies, flash, captcha, etc. is used which can't be automated by a tool. | To all the good advice above, agreed. That being said, maybe there is a valid scenario where the external DLL's are generally not needed? So here is what you do. You wrap and isolate them. (Its a higher level of abstraction than creating interfaces, so a bit easier to maintain).
In Visual Studio, if you do not recompile the specific VS Projects which reference the external DLL's then you can get away with compiling the rest of the VS Solution's Projects without having those DLL's handy. Thus if you somehow wrap the external DLL's with your own DLL's and then distribute those wrappers as binary only, the person sharing your source code will not need the external DLL's to compile the main solution.
**Considerations**:
1. Extra work to separate out the wrapper code into isolated Projects.
2. The other VS Projects must add references to your wrapper DLL's as "File System" references to a "LIB" folder, rather than "Project References".
3. The VS Solution configurations must disable compile for the wrapper DLL's. A new configuration should be added to explictly re-compile them, if needed.
4. The VS Project definition for each of the Wrapper DLL's should include a post-build event to copy them to the expected "LIB" folder location.
5. At runtime, the external DLL's must be present in the application's bin directory, or the machine's GAC, or otherwise explictly loaded. NOTE: If they are missing, it is only when they actually invoked at runtime that their absence will result in a runtime error. i.e. You do not need to have them if the code doesn't happen to call them in a general situation.
6. At runtime, you can catch errors loading the external DLL's and present a pretty error message to the user to say "In order to user this function, please install the following product: xyz". Which is better than displaying "AssemblyLoadException... please use FusionLogViewer... etc"
7. At application startup, you can test and detect missing DLL's and then disable specific functions which depend upon them.
For example: According to this pattern I could have an application which integrates with Microsoft CRM and SAP, but only for a specific function, i.e. Import/Export.
At design time, if the developer never neeeds to change the wrapper, they will be able to recompile without these external DLL's.
At runtime, if the user never invokes this function, the application will never invoke the wrapper and thus the external DLL's are not needed. |
9,667,228 | I need to get value from a href button. Here I have just developed a code which show all href value. Actually I need to get value from where I click.
here is my code
```
$(document).ready(function() {
$("a.me").click(function(){
var number = $('a').text();
alert(number);
});
});
``` | 2012/03/12 | [
"https://Stackoverflow.com/questions/9667228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/884521/"
] | You should do
```
$(document).ready(function() {
$("a.me").click(function(){
//It's not clear if you want the href attribute or the text() of the <a>
//this gives you the href. if you need the text $(this).text();
var number = this.href;
alert(number);
});
});
``` | one of the answers above will work or you could use
```
...
$("a.me").click(function(e){
var number = $(e.target).text();
alert(number);
});
``` |
5,530,005 | I'm not sure of the best way to ask this question, so I'll start with an example:
```
public static void ConvertPoint(ref Point point, View fromView, View toView) {
//Convert Point
}
```
This call is recursive. You pass in a point, it converts it relative to `fromView` to be relative to `toView` (as long as one is an ancestor of the other).
The call is recursive, converting the point one level at a time. I know, mutable structs are bad, but the reason I'm using a mutable point is so that I only need to create a single point and pass it along the recursive call, which is why I'm using ref. Is this the right way to go, or would it be better to use an out parameter, or simply declare the method to return a point instead?
I'm not very familiar with how structs are handled as opposed to classes in these circumstances. This is code being ported from Java, where point obviously had to be a class, so it made sense to use the same temporary point over and over rather than create a new point which had to be garbage collected at every call.
This may be a confusing question, and to heap on some more confusion, while I'm at it, should I keep a temporary static `Point` instance around for quick conversions or would it be just as simple to create a new point whenever this method is called (it's called a *lot*)? | 2011/04/03 | [
"https://Stackoverflow.com/questions/5530005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36007/"
] | Fretting over the garbage collector is never not a mistake when dealing with short-lived objects such as the Point, assuming it is actually a class. Given that this is C#, it is likely to be a struct, not bigger than 16 bytes. In which case you should *always* write the method to return a Point. This gets optimized at runtime, the struct fits in cpu registers.
Only ever consider passing structs by ref when they are large. | I tend to make everything a class to simplify things. If you find that this creates unwanted memory pressure in your application only then should you investigate a solution that involves a mutable struct.
The reason I say this is that the GC tends to be very good at optimizing collections around the needs of your app and mutable structs are a notorious headache. Don't introduce that headache if the GC can handle the memory pressure of multiple objects. |
9,945,265 | I got [this SVG image from Wikipedia](http://upload.wikimedia.org/wikipedia/commons/e/e8/BlankMap-World6-Equirectangular.svg) and embedded it into a website using this code:
```
<embed src="circle1.svg" type="image/svg+xml"/>
```
If you run this, you can inspect the element and see the source code. All countries in the image are separate elements. If I click on a country, I want to alert the id of that country, since every country has an id of two letters in the SVG. Does anyone know a way to do this? Would it be easier if I place it into a element? | 2012/03/30 | [
"https://Stackoverflow.com/questions/9945265",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1066924/"
] | Okay using your comments I found an answer to my problem. I added this code in the svg itself.
```
<script type="text/javascript"> <![CDATA[
function addClickEvents() {
var countries = document.getElementById('svg1926').childNodes;
var i;
for (i=0;i<countries.length;i++){
countries[i].addEventListener('click', showCountry);
}
}
function showCountry(e) {
var node = e.target;
if (node.id != 'ocean') {
node = getCorrectNode(node);
}
alert(node.id);
}
function getCorrectNode(node) {
if (node.id.length == 2 || node.id == 'lakes') {
return node;
}
return getCorrectNode(node.parentNode);
}
]]> </script>
```
The function addClickEvents is triggered when the svg loads.
But I still have another problem with this. I have to embed this svg (with the code) into a HTML document using
```
<embed src="circle1.svg" type="image/svg+xml" />
```
Instead of alerting the id, I have to place it into a div in the HTML document.
How do I get this id from the svg? | If your SVG is contained in the DOM, you can attach event listeners to separate elements in the same manner as basic HTML. Using jQuery one example would be: <http://jsfiddle.net/EzfwV/>
Update: Most modern browsers support inline svg, so to load your source into the DOM, all you have to do is load it in from a resource, (using something like jQuery's load()).
Edit: more specific example <http://jsfiddle.net/EzfwV/3/> |
52,165,484 | Got a situation that is unclear to me.
What I want is this: Play an audio and after audio has finished playing, start the microphone recording.
The problem: In FF and Chrome the code works just fine. On Safari however, when the audio has stopped playing and the microphone recording function starts, the audio is at the same time played again.
Start and end hooks are done with jQuery. Here is the ended bind.
```
var on_audio_stop = function() {
start_microphone_recording();
}
$( 'audio' ).bind( 'ended', on_audio_stop );
```
start\_microphone\_recording function calls a function where the icon is changed and then the init\_recording is called, nothing more so I've not included that one.
Start mic function:
```
function init_recording() {
AudioContext = window.AudioContext || window.webkitAudioContext;
context = new AudioContext();
processor = context.createScriptProcessor( buffer_size, 1, 1 );
processor.connect( context.destination );
var handle_success = function ( stream ) {
global_stream = stream;
input = context.createMediaStreamSource( stream );
input.connect( processor );
processor.onaudioprocess = function ( e ) {
microphone_process( e );
};
};
navigator.mediaDevices.getUserMedia( constraints ).then( handle_success );
}
```
When mic is activated in Safari, the "play" bind function is executed. I've tried with pause() and muted but doesn't work. Also tried removing the audio tag and clearing src from the audio tag.
Anyone has any ideas as to why Safari is doing this and what the solution might be?
---
Example:
I set up 5 MP3 audios in the AUDIO tag in html, I play one by one, the I run the "init\_recording" functions and Safari will play all the 5 MP3 audios at the same time, over each other while mic has started to record. | 2018/09/04 | [
"https://Stackoverflow.com/questions/52165484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3537395/"
] | >
> Is it really necessary to go through the process of accepting a string as input and convert it to a numeral to perform the calculation?
>
>
>
It isn't strictly necessary but it does enforce good habits. Let's assume you are going to ask for 2 numbers from the users and use something like
```
std::cout << "Enter first number: ";
std::cin >> first_number;
std::cout << "Enter second number: ";
std::cin >> second_number;
```
For the first number the user enters `123bob`. `operator>>` is going to start reading it in and once it hits `b` it is going to stop and store `123` into `first_number`. Now the stream has `bob` still in it. When it asks for the second number since `bob` is still in the stream it will fail and `second_number` will get set to `0`. Then the program will continue on and you will get garbage output because you accepted garbage input.
Now, if you read in as a `std:string` and then convert to what you want it makes it easier to catch these types of errors. `getline(std::cin, some_string);` would get all of `123bob` out of the input buffer so you don't have to worry about having to clean it up. Then using `stoi` (or any of the `stox` functions) it will read the valid value of of it. The functions also have a second parameter which is a pointer to a `size_t` and if you pass it one it will store the position of the first unconverted character in the string and you can use that to tell if the entire input string is valid or not. So, if you had
```
std::string input;
std::cout << "Enter some number: ";
std::getline(std::cin, input);
std::size_t pos;
double number = std::stod(input, &pos);
if (pos == input.size())
std::cout << "valid input\n";
else
std::cout << "invalid input\n";
```
Then `1.23bob` would cause `invalid input` to print where `1.23` cause `valid input` to print. You could even use this in a loop to make sure you get only valid input like
```
double number;
do
{
std::string input;
std::cout << "Enter some number: ";
std::getline(std::cin, input);
std::size_t pos;
number = std::stod(input, &pos);
if (pos != input.size())
std::cout << "invalid input\n";
else
break;
} while(true)
```
---
TL;DR: If you rely on the user to only input valid input eventually you are going to get burned. Reading in as a string and converting offers a consistent way to ensure that you are only getting good input from your user. | >
> I was advised to refrain from using cin unless it is really necessary.
>
>
>
First of all, there is a misunderstanding, because you are still using `std::cin`. I will interpret your question as using `std::cin::operator >>` vs `getline(std::cin,...)`. Next I would rather suggest you the opposite: Use `operator>>` directly if you can and fall back to `getline` if you have to.
**A very contrived example:**
Imagine you have integers stored in a file in this (unnecessarily complex) format,
```
3123212
^-------- number of digits of the first number
^^^----- first number
^---- number of digits of the second number
^^-- second number
```
You cannot use a bare `std::cin >>` to read those numbers. Instead you need to read the whole line and then parse the numbers. However, even for this I would highly recommend to provide an overload for `operator>>`, something along the line of
```
struct NumbersReadFromStrangeFormat {
std::vector<int> numbers;
};
std::isstream& operator>>(std::istream& in,NumbersReadFromStrangeFormat& num) {
// use getline and parse the numbers from the string
return in;
}
```
Such that you can again write:
```
NumbersReadFromStrangeFormat numbers;
std::cin >> numbers;
```
**Conclusion:**
Overloading the `operator>>` is the idomatic way to read something from an input stream. "Using `std::cin`" or "using `getline`" are not really alternatives. "Refraining from using `std::cin`" must be a misunderstanding. If there is no overload of `operator>>` that already does what you need, you can write your own and nicely hide any `getline` or other parsing details. |
117,952 | I have two tables containing Tasks and Notes, and want to retrieve a list of tasks with the number of associated notes for each one. These two queries do the job:
```
select t.TaskId,
(select count(n.TaskNoteId) from TaskNote n where n.TaskId = t.TaskId) 'Notes'
from Task t
-- or
select t.TaskId,
count(n.TaskNoteId) 'Notes'
from Task t
left join
TaskNote n
on t.TaskId = n.TaskId
group by t.TaskId
```
Is there a difference between them and should I be using one over the other, or are they just two ways of doing the same job? Thanks. | 2008/09/22 | [
"https://Stackoverflow.com/questions/117952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14072/"
] | In most cases, the optimizer will treat them the same.
I tend to prefer the second, because it has less nesting, which makes it easier to read and easier to maintain. I have started to use SQL Server's common table expressions to reduce nesting as well for the same reason.
In addition, the second syntax is more flexible if there are further aggregates which may be added in the future in addition to COUNT, like MIN(some\_scalar), MAX(), AVG() etc. | I make it a point to avoid subqueries wherever possible. The join will generally be more efficient. |
3,732,101 | I find myself needing to synthesize a ridiculously long string (like, tens of megabytes long) in JavaScript. (This is to slow down a CSS selector-matching operation to the point where it takes a measurable amount of time.)
The best way I've found to do this is
```
var really_long_string = (new Array(10*1024*1024)).join("x");
```
but I'm wondering if there's a more efficient way - one that doesn't involve creating a tens-of-megabytes array first. | 2010/09/17 | [
"https://Stackoverflow.com/questions/3732101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/388520/"
] | For ES6:
```
'x'.repeat(10*1024*1024)
``` | Simply accumulating is vastly faster in Safari 5:
```
var x = "1234567890";
var iterations = 14;
for (var i = 0; i < iterations; i++) {
x += x.concat(x);
}
alert(x.length); // 47829690
```
Essentially, you'll get `x.length * 3^iterations` characters. |
40,004 | Et non, ce n’est pas le pays. Dans le livre « Le canard de bois » par Louis Caron, on utilise le mot « catalogne » comme le suivant:
>
> Il la souleva doucement entre ses mains et glissa la catalogne sous le corps inerte
>
>
>
Je n’ai absolument rien pu trouver de ce que veut dire ce mot. | 2019/10/14 | [
"https://french.stackexchange.com/questions/40004",
"https://french.stackexchange.com",
"https://french.stackexchange.com/users/22006/"
] | Dans une [autre réponse](https://french.stackexchange.com/a/40005) on a établi qu'il s'agissait d'une *couverture* dans l’œuvre ; plus [généralement](https://www.btb.termiumplus.gc.ca/tpv2alpha/alpha-fra.html?lang=fra&i=1&srchtxt=CATALOGNE&index=alt&codom2nd_wet=1#resultrecs) la [*lirette*](https://larousse.fr/dictionnaires/francais/lirette/47377?q=lirette#47308) ou *catalogne* (au Québec) c'est aussi le :
>
> Tissage artisanal dont la chaîne est le plus souvent en coton ou en
> lin et la trame faite de fines bandes de tissu. (Au Québec, il est
> appelé *catalogne*.) (Larousse en ligne, *lirette*)
>
>
>
Ou l'*étoffe* qui « peut servir à la fabrication de tissus, de tapis, de couvertures, etc. » ([GDT](http://granddictionnaire.com/ficheOqlf.aspx?Id_Fiche=8358852)). Le mot *catalogne* était attesté en français classique (1635, voire [avant](https://www.erudit.org/fr/revues/haf/1961-v15-n3-haf2036/302137ar.pdf)) et il demeure en usage au Québec pour désigner l'étoffe et les couvertures, tapis que l'on confectionne avec (DHLF). L'article au [GPFC](http://bibnum2.banq.qc.ca/bna/numtxt/179630.pdf) résume bien le tout et mentionne aussi la présence du terme signifiant « couverture de lit » dans les anciens dialectes (Bourgogne, Auvergne, Normandie, Picardie, Savoie, Bretagne) ; j'ajoute un détail de la technique permettant de l'identifier aisément :
[](https://i.stack.imgur.com/004gB.jpg)
[](https://i.stack.imgur.com/rJKxP.jpg)
Détails de catalognes (voir aussi [ici](http://collections.textilemuseum.ca/fr/search?criteria=catalogne) et [ici](http://canadiantapestry.ca/fr/det-T04_29_1.html) pour d'autres exemples) / Article « catalogne » au *Glossaire du parler français au Canada* (1930) | Pour ajouter aux autres réponses. *Car c'est une couverture faite à la mains, mais de caractéristique spéciale.*
Une catalogne peut être faite à la main avec des morceaux de restant de coton ou de laine, mais une catalogne à la base reste **lourde** et compacte. C’est une de ses caractéristiques principales.
Le tissu est tissé serré et/ou bien en plusieurs couches de retailles. L'originalité de la catalogne est qu'elle est très chaude et le fait qu'elle est lourde crée un effet recherché pour se sentir enveloppé en exemple. Due aux mauvaises isolations et chauffage au bois, dans le temps de mes grands-parents on la trouvait souvent dans les maisons d’époque au Canada Français. En temps normal, dans un lit, la catalogne est mise au dessus d'un autre drap de lit car la catalogne est chaude mais moins confortable qu'un drap ou une couverture normale.
Voici en exemple deux catalognes que j'ai chez moi;
[](https://i.stack.imgur.com/ea6Ou.jpg)
[](https://i.stack.imgur.com/bLCp5.jpg) |
177,778 | I have an employee that went straight to my boss to ask for a raise. This employee never approached me about her wages.
We do reviews annually, and the last review was about 6 months ago, so it really wasn't something I was even thinking about. If she would have, I would have listened to her reasoning and more than likely, given her a raise.
**Boss instructed me to give her the raise**.
It's not that I am against a raise, I just get a feeling of sneakiness.
Should I
a) go ahead and call her in, tell her she is getting a raise, and let her know that her going over me instead of asking me herself was inappropriate?
b) wait for her to get tired of waiting and ask me herself.
Also, this question will probably get asked, but I am a very approachable and understanding manager. I a flexible with work schedules and never berate my employees for any mistakes, but encourage them. I feel pretty confident that I'm not a "scary" boss. | 2021/08/20 | [
"https://workplace.stackexchange.com/questions/177778",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/129064/"
] | >
> a) go ahead and call her in, tell her she is getting a raise, and let her know that her going over me instead of asking me herself was inappropriate?
>
>
>
Fixed that for you. Tell her that she is getting a raise and tell her that you think she deserves it and are pleased to offer it. You might even strongly imply that you have neglected it all this time and are glad she is finally getting it. It may not be sincere, but most workplace relations are not anyway.
>
> b) wait for her to get tired of waiting and ask me herself.
>
>
>
>
> I am a very approachable and understanding manager.
>
>
>
I personally don't think there can be such a thing as employee/employer incentives are fundamentally in conflict. Even if there were, the fact that you are considering passive-aggressive solutions here indicates that you likely use them in other scenarios too, making engaging with you a potential future landmine for anyone who knows that about you. Your employees probably know.
I once had two managers. I always asked for stuff from the manager who I spent the least time with as they were less likely to have seen my mistakes and less likely to be annoyed with me as a result. | >
> a) go ahead and call her in, tell her she is getting a raise, and let her know that her going over me instead of asking me herself was inappropriate?
>
>
>
>
> b) wait for her to get tired of waiting and ask me herself.
>
>
>
No, c) Talk to your boss about how responding to your employees like that removes your agency.
Your boss should've asked the employee, "Have you talked this with @William?" If your boss understands how management works, they will agree with you, and this won't happen again. If your boss is on a power trip, then when the next employee asks you for a raise, send them to your boss. "P. Trip likes to do this themselves, please talk to them." I've had bosses who wanted to manage my team, and I just let them. Some people just don't have enough to do already. |
61,468,770 | Source code:
```
#include <glfw3.h>
int main(void){
GLFWwindow* window;
/* Initialize the library */
if (!glfwInit())
return -1;
/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
if (!window)
{
glfwTerminate();
return -1;
}
/* Make the window's context current */
glfwMakeContextCurrent(window);
/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window))
{
/* Render here */
glClear(GL_COLOR_BUFFER_BIT);
/* Swap front and back buffers */
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
glfwTerminate();
return 0;
}
```
Compiler:
```
g++ (MinGW.org GCC Build-20200227-1) 9.2.0
```
Commands I've tried and errors:
1. `g++ -I <pathHeaderFolder> Application.cpp -Wl, -BStatic -L <pathLibraryFolder> -lglu32 -lopengl32 -lkernel32 -luser32 -lgdi32 -lws2_32`:
```
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: cannot find : Invalid argument
collect2.exe: error: ld returned 1 exit status
```
2. `g++ Application.cpp -I <pathHeaderFolder>`:
```
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: C:\Users\Bruh\AppData\Local\Temp\cctDJEee.o:Application.cpp:(.text+0x17): undefined reference to `glfwInit'
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: C:\Users\Bruh\AppData\Local\Temp\cctDJEee.o:Application.cpp:(.text+0x56): undefined reference to `glfwCreateWindow'
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: C:\Users\Bruh\AppData\Local\Temp\cctDJEee.o:Application.cpp:(.text+0x64): undefined reference to `glfwTerminate'
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: C:\Users\Bruh\AppData\Local\Temp\cctDJEee.o:Application.cpp:(.text+0x76): undefined reference to `glfwMakeContextCurrent'
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: C:\Users\Bruh\AppData\Local\Temp\cctDJEee.o:Application.cpp:(.text+0x81): undefined reference to `glfwWindowShouldClose'
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: C:\Users\Bruh\AppData\Local\Temp\cctDJEee.o:Application.cpp:(.text+0x96): undefined reference to `_imp__glClear@4'
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: C:\Users\Bruh\AppData\Local\Temp\cctDJEee.o:Application.cpp:(.text+0xa6): undefined reference to `glfwSwapBuffers'
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: C:\Users\Bruh\AppData\Local\Temp\cctDJEee.o:Application.cpp:(.text+0xab): undefined reference to `glfwPollEvents'
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: C:\Users\Bruh\AppData\Local\Temp\cctDJEee.o:Application.cpp:(.text+0xb2): undefined reference to `glfwTerminate'
collect2.exe: error: ld returned 1 exit status
```
3. `g++ Application.cpp -I <pathHeaderFolder> -Wl, -BStatic -<pathLibraryFolder>\libglfw3.a`:
```
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: cannot find : Invalid argument
collect2.exe: error: ld returned 1 exit status
```
4. `g++ -I <pathHeaderFolder> Application.cpp -Wl, -BStatic -L <pathLibraryFolder> -libglfw3.a`:
```
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: cannot find : Invalid argument
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: cannot find -libglfw3.a
collect2.exe: error: ld returned 1 exit status
```
5. `g++ -I <pathHeaderFolder> Application.cpp -Wl, -BStatic -L <pathLibraryFolder>libglfw3.a -mwindows`:
```
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: cannot find : Invalid argument
collect2.exe: error: ld returned 1 exit status
``` | 2020/04/27 | [
"https://Stackoverflow.com/questions/61468770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13420564/"
] | Spaces in arguments matter!
Here:
```
-Wl, -BStatic
```
Try removing the extra space:
```
-Wl,-BStatic
```
The reason is that the part after `-Wl,` is the argument passed to the linker.
See questions like [I don't understand -Wl,-rpath -Wl,](https://stackoverflow.com/questions/6562403/i-dont-understand-wl-rpath-wl) and [`-Wl,` prefix to compiler flag](https://stackoverflow.com/questions/47396525/wl-prefix-to-compiler-flag) | OK, I tried deleting space but it didn't fix the problem. I was getting error:
```
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: unrecognized option '-BStatic'
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: use the --help option for usage information
collect2.exe: error: ld returned 1 exit status
```
I was going through the gcc and linker documentation, but while not knowing how it works, finally tried and **it worked**:
```
g++ -I<pathHeaderFolder> Application.cpp -Wl,<pathLibraryFolder>libglfw3.a -lglu32 -lopengl32 -lkernel32 -luser32 -lgdi32 -lws2_32
```
I don't really know why it worked, but I read in the linker documentation that if passing options to the linker it must be done through the -Wl
Also, adding "-L" before library path for linker
```
-Wl,-L<pathLibraryFolder>libglfw3.a
```
was giving me an error like I didn't link a library. I don't know why
But anyway it worked, so thanks a lot for help! I wouldn't come up that spaces in arguments matter |
52,257 | In velocity map imaging (photo-dissociation and photo-emission), the ejected particles form a newton sphere. I didn't really get the concept why it is called a ["newton sphere"](http://www.google.com/search?q=velocity+map+imaging+newton+sphere) and also why at the poles the distribution is $\cos^2(\theta)$? | 2013/01/26 | [
"https://physics.stackexchange.com/questions/52257",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/20190/"
] | **The outcomes are not supposed to be the same.**
There are two ways to interpret your question:
**1. You want to calculate the kinetic energy in different *reference frames*.**
Let's think for example of a point-like body moving in a constant velocity $\mathbf{v}$. It's kinetic energy is $\frac{1}{2}mv^2$, but if we calculate it in a reference frame that is moving with the body, in that frame the body is at rest and we get zero. So we don't expect the same outcome when calculating kinetic energy in different reference frames.
**2. You want to stay in the laboratory reference frame, but pick different points as the axis of rotation for your calculations.**
Here there is a subtle point we need to be aware of. It's true that some calculations involving the rotation of rigid bodies can be done in several different ways, each time picking a different axis, and still resulting in the correct outcome. For example this works if we want to calculate the linear and angular acceleration of a body when a given force is applied to it.
However, if a rigid body has linear movement and rotation simultaneously, and we want to calculate it's kinetic energy, we need to be careful when using the formula:
$$ E\_k = \frac{1}{2}M V^2 + \frac{1}{2} I \omega^2,$$
where $\mathbf{V}$ is the velocity of the axis point and $\omega$ is the angular velocity of rotation around that point.
This is the formula you used in your calculations, but in fact it is valid **only** in the following cases (and I give a proof of this below):
1. When we use the *center of mass* as the axis of rotation.
2. When the axis of rotation is at rest (i.e. $\mathbf{V}=0$).
3. When the velocity is parallel to the line connecting the axis point to the center of mass.
Regarding the calculations you showed in your question:
When you used the fixed point of the cylinder as the axis case 2 applied. When you used the center of mass case 1 applied. When you used the moving extreme none of the cases applied, and you cannot use the above formula in this case.
**Proof:**
We model the rigid body as a collection of point-like masses $m\_i$ with their positions relative to the axis of rotation denoted as $\mathbf{r}\_i$. The velocity of mass $i$ is:
$$\mathbf{v}\_i = \mathbf{V} + \boldsymbol\omega \times\mathbf{r}\_i.$$
The total kinetic energy is then:
$$E\_k = \sum\_i \frac{1}{2} m\_i v\_i^2 = \frac{1}{2} MV^2 + \frac{1}{2} I \omega^2 + M \mathbf{V} \cdot (\boldsymbol\omega \times \mathbf{R}\_{CM}),$$
where $M=\sum\_i m\_i$ is the total mass, $I=\sum\_i m\_i |\hat{\boldsymbol\omega} \times \mathbf{r}\_i|^2$ is the moment of inertia and $\mathbf{R}\_{CM} = (\sum\_i m\_i \mathbf{r}\_i )/M$ is the center of mass relative to the axis of rotation.
We see that we need the last term to vanish in order to get the formula we want to prove, and we can get this if $\mathbf{R}\_{CM}=0$ (case 1), $\mathbf{V}=0$ (case 2) or $\mathbf{V} \cdot (\boldsymbol\omega \times \mathbf{R}\_{CM})=0$ (case 3). | I think I found your mistake. The moment of intertia of a rod fixed about the center is
\begin{equation}
\frac{1}{12} m L^2
\end{equation}
You can derive this in several ways. I derived it by considering two rods moving separately (but still rigid), so then the moment of intertia is as before, but
\begin{equation}
\frac{2}{3} \frac{m}{2} \bigg(\frac{1}{2} L \bigg)^2 = \frac{1}{12} m L^2
\end{equation}
You can consider that the angular velocity $\dot{\phi}$ of each rod is the same as before.
When you then take the speed of the center of mass, you should have
\begin{equation}
v\_{cm} = \bigg(\frac{1}{2} L \bigg) \dot{\phi}
\end{equation}
Since the part that is translating is center of mass, at half the total length from the fixed point (think of the rolling wheel problems).
You should be able to solve for the energy now. |
12,935,398 | Given the following html in a Winforms Webbrowser DOM, I'm attempting to get the second element with `value="type102"`
```
<div class="Input"><input type="radio" name="type" value="type101"
onclick="setType('type101');"><a href="javaScript:setType('type101');"
onclick="s_objectID="javascript:setType('type101');_1";return this.s_oc?
this.s_oc(e):true">type101</a></div>
<div class="Input"><input type="radio" name="type" value="type102"
onclick="setType('type102');" checked="checked"><a href="javaScript:setType('type102');"
onclick="s_objectID="javascript:setType('type102');_1";return this.s_oc?
this.s_oc(e):true">type102</a></div>
```
I've used
`HtmlElement htmlElem = browser.Document.GetElementById(....`
and
`HtmlElement htmlElem = browser.Document.All.GetElementsByName(....`
before, but in this instance they are both the same so would need to get by value or href
Is it possible to get the second element directly without external libraries or would I have to get a collection of GetElementsByName and iterate through them? | 2012/10/17 | [
"https://Stackoverflow.com/questions/12935398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | ```
var elems = webBrowser1.Document.GetElementsByTagName("input");
var myInputElement = elems.First(e => !string.IsNullOrEmpty(e) && e.Trim().ToLower().Equals("type102"));
foreach (var elem in elems)
{
var value = elem.GetAttribute("value");
if (string.IsNullOrEmpty(value) && value.Trim().ToLower().Equals("type102"))
{
MessageBox.Show(value);
break;
}
}
```
Or to make it shorter
```
var elems = webBrowser1.Document.GetElementsByTagName("input");
var myInputElement = elems.First(e => !string.IsNullOrEmpty(e) && e.Trim().ToLower().Equals("type102"));
```
Is this what you are looking for? you can also have a look at [HtmlAgilityPack](http://htmlagilitypack.codeplex.com/) for things like these. | ```
HtmlElement htmlElem = browser.Document.All.GetElementsByName(...)[1]
``` |
183,519 | There are few different formats I have seen so far:
1. With quotes and brackets:
```
PATH="/usr/local/bin:${PATH}"
```
2. With quotes only:
```
PATH="/usr/local/bin:$PATH"
```
3. None:
```
PATH=/usr/local/bin:$PATH
```
Export all the same:
```
export PATH
```
Which is the correct/preferred way? | 2015/02/07 | [
"https://unix.stackexchange.com/questions/183519",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/102280/"
] | This is about shell variables in general, not just PATH.
Here are some examples of why `""` and `{}` can reduce errors.
Putting it in quotes is safer: if you do `a=hello world` then you will not get what you expect, but for `a="hello world"` you will.
Using `{}` is also safer: doing `h="hello"; echo "$hword"` will not work, but `h="hello"; echo "${h}word"` will. | They all are effective. One isn't drastically better than the other, but I prefer:
```
export PATH=$PATH:/usr/local/bin
```
It takes care of the export and the setting of the path in one line. I also tend to not put the new path before the existing `$PATH`, but there are cases when that might be necessary to load newer self-compiled libraries before older system ones.
---
If you are trying to export variables then yes, you want to quote them, for instance:
```
export myservers="server1 server2 server3"
```
Now when you `echo $myservers` you will see:
```
[user]# echo $myservers
server1 server2 server3
```
But since this question relates to `$PATH` and not shell variables, then my original post still stands since there will never be a time where you are printing `'hello world'` into your system path.
```
[user]# echo $PATH ## Something you shouldn't be doing
/usr/local/bin:HELLO WORLD/sbin:/bin:/usr/sbin:WHY AM I DOING THIS?/usr/bin:/root/bin
``` |
1,100,840 | I want to build a bot that basically does the following:
1. Listens to the room and interacts with users and encourages them to PM the bot.
2. Once a user has PMed the bot engage with the client using various AI techniques.
Should I just use the IRC library or Sockets in python or do I need more of a bot framework.
What would you do?
Thanks!
Here is the code I'm currently using, however, I haven't gotten it to work.
```
#!/usr/bin/python
import socket
network = 'holmes.freenet.net'
port = 6667
irc = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
irc.connect ( ( network, port ) )
irc.send ( 'NICK PyIRC\r\n' )
irc.send ( 'USER PyIRC PyIRC PyIRC :Python IRC\r\n' )
irc.send ( 'JOIN #pyirc\r\n' )
irc.send ( 'PRIVMSG #pyirc :Can you hear me?\r\n' )
irc.send ( 'PART #pyirc\r\n' )
irc.send ( 'QUIT\r\n' )
irc.close()
``` | 2009/07/08 | [
"https://Stackoverflow.com/questions/1100840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/417449/"
] | Use [Twisted](http://twistedmatrix.com) or [Asynchat](http://docs.python.org/library/asynchat.html) if you want to have a sane design. It is possible to just do it with sockets but why bother doing it from scratch? | If what you want is to create the AI portion, why bother writing all the code needed for the IRC connection by yourself?
I suggest using [SupyBot](http://sourceforge.net/projects/supybot/), and simply write your AI-code as a plugin for it. There is reasonably understandable documentation and lots of example-code to find. Also, it comes with a decent amount of plugins for all sorts of uses that might complement your AI. |
7,781,847 | How to write `FORMAT_OF(type)`,so that it will be `%d` for `int`,`%s` for `char *`,etc.
Is there a macro to get the format for basic data types? | 2011/10/16 | [
"https://Stackoverflow.com/questions/7781847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/807893/"
] | No. Currently standardized versions of C does not support type introspection of this sort. | Well, if you only want the macro to take a type, you could:
```
#define FORMAT_int "%d"
#define FORMAT_char "%c"
...
#define FORMAT(x) FORMAT_##x
```
and use `FORMAT(int)` later on; but
```
int i;
FORMAT(i);
```
would **not** work, and `FORMAT(char*)` would not work either. |
1,407,113 | I need a component/class that throttles execution of some method to maximum M calls in N seconds (or ms or nanos, does not matter).
In other words I need to make sure that my method is executed no more than M times in a sliding window of N seconds.
If you don't know existing class feel free to post your solutions/ideas how you would implement this. | 2009/09/10 | [
"https://Stackoverflow.com/questions/1407113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117459/"
] | If you need a Java based sliding window rate limiter that will operate across a distributed system you might want to take a look at the <https://github.com/mokies/ratelimitj> project.
A Redis backed configuration, to limit requests by IP to 50 per minute would look like this:
```
import com.lambdaworks.redis.RedisClient;
import es.moki.ratelimitj.core.LimitRule;
RedisClient client = RedisClient.create("redis://localhost");
Set<LimitRule> rules = Collections.singleton(LimitRule.of(1, TimeUnit.MINUTES, 50)); // 50 request per minute, per key
RedisRateLimit requestRateLimiter = new RedisRateLimit(client, rules);
boolean overLimit = requestRateLimiter.overLimit("ip:127.0.0.2");
```
See <https://github.com/mokies/ratelimitj/tree/master/ratelimitj-redis> fore further details on Redis configuration. | My implementation below can handle arbitrary request time precision, it has O(1) time complexity for each request, does not require any additional buffer, e.g. O(1) space complexity, in addition it does not require background thread to release token, instead tokens are released according to time passed since last request.
```
class RateLimiter {
int limit;
double available;
long interval;
long lastTimeStamp;
RateLimiter(int limit, long interval) {
this.limit = limit;
this.interval = interval;
available = 0;
lastTimeStamp = System.currentTimeMillis();
}
synchronized boolean canAdd() {
long now = System.currentTimeMillis();
// more token are released since last request
available += (now-lastTimeStamp)*1.0/interval*limit;
if (available>limit)
available = limit;
if (available<1)
return false;
else {
available--;
lastTimeStamp = now;
return true;
}
}
}
``` |
35,719,119 | I am trying to resize a viewpager to the rest of the page. I have this globallayout listener:
```
ViewTreeObserver viewTreeObserver = pager.getViewTreeObserver();
viewTreeObserver
.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
int viewPagerWidth = pager.getWidth();
float viewPagerHeight = Constants.screenHeight - findViewById(R.id.view_above_pager).getBottom();
Log.i("","viewpager height:" + viewPagerHeight);
layoutParams.width = viewPagerWidth;
layoutParams.height = (int) viewPagerHeight;
pager.setLayoutParams(layoutParams);
pager.setMinimumHeight((int)viewPagerHeight);
pager.getViewTreeObserver()
.removeGlobalOnLayoutListener(this);
Log.i("","viewpager height2:" + pager.getHeight());
}
});
```
Apparently the first log, on the viewPagerHeight shows:viewpager height:530.0
BUT the second on the pager shows 0. Why is this happening? Shouldn't it refresh the height? | 2016/03/01 | [
"https://Stackoverflow.com/questions/35719119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1307987/"
] | This Example explains everything regarding POSTFIX and PREFIX.
```
Operator Name Description
++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one
```
Example:-
```
<?php
echo "<h3>Postincrement</h3>";
$a = 5;
echo "Should be 5: " . $a++ . "<br />\n";
echo "Should be 6: " . $a . "<br />\n";
echo "<h3>Preincrement</h3>";
$a = 5;
echo "Should be 6: " . ++$a . "<br />\n";
echo "Should be 6: " . $a . "<br />\n";
echo "<h3>Postdecrement</h3>";
$a = 5;
echo "Should be 5: " . $a-- . "<br />\n";
echo "Should be 4: " . $a . "<br />\n";
echo "<h3>Predecrement</h3>";
$a = 5;
echo "Should be 4: " . --$a . "<br />\n";
echo "Should be 4: " . $a . "<br />\n";
?>
```
Check this [link](http://php.net/manual/en/language.operators.increment.php) for more detail:-
Operators are used to perform operations on variables and values.
>
> PHP divides the operators in the following groups:
>
>
> -Arithmetic operators
>
>
> -Assignment operators
>
>
> -Comparison operators
>
>
> -Increment/Decrement operators
>
>
> -Logical operators
>
>
> -String operators
>
>
> -Array operators
>
>
>
Check this [link](http://www.w3schools.com/php/php_operators.asp) for PHP operators | Yes that's correct, you can read everything about that back on php.net
<http://php.net/manual/en/language.operators.increment.php>
this will cover it |
2,000,983 | Here's what I want to do:
```
public function all($model) {
$query = 'SELECT ' . implode(', ', $model::$fields) ....;
}
```
Called like this:
```
$thing->all(Account);
```
I get this error:
```
Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM in /home/mark/public_html/*/account.php on line 15
```
When inspecting `$model` with `var_dump` it turns out its a string. In the the first example if I change `$model` to `Account` on the $query line it works fine.
How can a take a string and turn it back into a class?
Edit: Updated example and title to reflect the problem isn't with `self`.
Solution: Since I'm not using PHP5.3, I had to resort to using eval() to get what I wanted. Thanks everybody! | 2010/01/04 | [
"https://Stackoverflow.com/questions/2000983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1103052/"
] | You cannot use `self` this way : it can only be used in a static context (i.e. inside a static method) to point to the class -- and not its name.
If you are working with non-static methods (seems you are), you should use `$this`, instead of `self`.
Actually, before PHP 5.3, you cannot use a static method/data with a "dynamic" (i.e contained in a variable) class name -- see the examples on the page [Static Keyword](http://php.net/manual/en/language.oop5.static.php) : they only work with PHP 5.3, for that kind of manipulation.
Which means a portion of code like this one :
```
class ClassA {
public static $data = 'glop';
}
$className = 'ClassA';
var_dump($className::$data);
```
Will not work with PHP < 5.3 | I find this similar line works in my Laravel app:
```
$thing->all(new Account);
``` |
5,370,786 | We have been using asp.net mvc for development. Sometimes, we need to put some hidden fields on form that are shoved in the model by modelbinder (as expected). Nowadays, users can easily temper the form using firebug or other utilities. The purpose of hidden field is mostly to provide some information back to server on as is basis and they are not meant to be changed.
For example in my edit employee form I can put EmployeeID in hidden field but if user changes the employeeID in hidden field, wrong employee will be updated in the database. in this scenario how can we keep the integrity of hidden fields. | 2011/03/20 | [
"https://Stackoverflow.com/questions/5370786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/331174/"
] | >
> if user changes the employeeID in
> hidden field, wrong employee will be
> updated in the database
>
>
>
This is a *major* security hole in your website. In everything you do with web development, no matter how clever someone's code might be or how much you think you'll be ok as long as users don't do something, remember one golden rule: *Never implicitly trust data received from the client.*
In order to modify anything in your website, the user must be logged in. (Right?) So in any attempt a user makes to post a form to the website (especially one which can modify data), double-check that the user submitting the form has permission perform the action being requested on the data being specified.
Ideally, every action which isn't completely public and unsecured should have a server-side permissions check. Never, ever trust what the client sends you. | One potential alternative would be to store that static, single-use information in TempData on the server and not pass it to the client where it could be tampered with. Keep in mind that by default TempData uses Session and has limitations of its own - but it could be an option. |
70,158,942 | **(solution is at the end)**
I have a tilemap with tiles that can spread to the adjacent tiles based on data I store in a dictionary by position.
[](https://i.stack.imgur.com/XFa3r.png)
While the check for that is done in no time at all it does take considerable resources resulting in a lag everytime I call the function.
Currently I'm making sure the code doesn't get executed too fast by actually waiting a little each time we finished a loop-iteration. While I'm okay with my code not being executed as fast as it could, this just isn't the right way to go about it.
So basically: Is there a way to limit the execution of a single script/function in unity/c# to not use more than a certain percentage of the games resources (or something to that effect)? Or maybe there's a way to increase the functions performance significantly I just can't find?
Thanks in advance!
**Solution <-----------**
**Thanks to** the great advice from [Michael Urvan](https://stackoverflow.com/users/938829/michael-urvan) and [akaBase](https://stackoverflow.com/users/2929738/akabase) I was able to vastly increase performance by using chunks. I wasn't able to implement all the suggested improvements, so check out (and upvote) their respective answers for even more performance.
**How**: I reset a bool every couple of seconds. When that bool is set, I loop through part of the necessary tiles (chunk) in the `Update()`-method and remember the last index for the next `Update()`-call. When I reach the end of the tile-list I'm done and can set the bool to false and reset the index.
Here's a simplified version of my **finished code**:
```
{
[SerializeField] private Tilemap tilemap;
[SerializeField] private List<TileType> tileTypes;
[SerializeField] private List<TileType> growthTileTypes;
private Dictionary<Vector3Int, TileData> tileDataByPosition;
private List<TileData> spreadingTileDatas;
private Dictionary<TileBase, TileType> tileTypeByTile;
private bool spreading;
private spreadIndex = 0;
private int chunkSize = 10;
private void Awake()
{
// set up stuff here
InvokeRepeating("ResetSpreading", 10, 10);
}
private void Update()
{
if (spreading == true)
{
Spread();
}
}
private void Spread()
{
for (
int index = spreadIndex;
index < spreadingTileDatas.Count && index < spreadIndex + chunkSize;
index++
)
{
// do stuff here
}
spreadIndex += chunkSize;
if (spreadIndex >= spreadingTileDatas.Count)
{
spreadIndex = 0;
spreading = false;
}
}
}
``` | 2021/11/29 | [
"https://Stackoverflow.com/questions/70158942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3120417/"
] | `async` functions *always* return promises. You can't fetch data asynchronously during rendering.
You need a `useEffect` hook to run the function which gathers the data, and then a `useState` hook to store it, along with logic to show a loading state while you wait for it.
```
const MyRow = ({ info }) => {
const [currentPrice, setCurrentPrice] = useState(null);
useEffect(() => {
fetchCurrentPrice.getPrice(info.name).then(setCurrentPrice);
}, [info]);
return <tr>
<td key={info.name}>{info.name}</td>
<td key={info.price}>{info.price}</td>
<td key={info.amount}>{info.amount}</td>
<td>{currentPrice ?? <Loading />}</td>
</tr>
}
```
with
```
{tableInfo.map(info => <MyRow key={info.name} info={info} />)}
``` | Use a separate component for the tr tag and call it within it.
```js
const Component = (props) => {
const {info} = props
useEffect(() => {
// call your api and set it to state
}, [])
return <tr>
<td key={info.name}>{info.name}</td>
<td key={info.price}>{info.price}</td>
<td key={info.amount}>{info.amount}</td>
<td>
{async () => await fetchCurrentPrice.getPrice(info.name)}
</td>
</tr>
}
{tableInfo.map(info => <Component info={info} />)}
``` |
50,542,764 | [Flutter's wiki](https://github.com/flutter/flutter/wiki/Flutter%27s-modes#artifact-differences) mentions obfuscation is an opt-in in release mode.
And yet, the **flutter build** command has no relevant option - see:
`flutter help -v build apk`
Am I missing something here?
Did they make obfuscation the default?
Is obfuscation even relevant for flutter?
Any pointers on this would be very appreciated. | 2018/05/26 | [
"https://Stackoverflow.com/questions/50542764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9850927/"
] | Obfuscation is needed - a flutter app knows its function names, which can be shown using Dart's StackTrace class. There's **under-tested** support for obfuscation. To enable it:
---
**For Android**:
Add to the file `[ProjectRoot]/android/gradle.properties` :
```
extra-gen-snapshot-options=--obfuscate
```
---
**For iOS:**
First, edit `[FlutterRoot]/packages/flutter_tools/bin/xcode_backend.sh`:
Locate the `build aot` call, and add a flag to it,
```
${extra_gen_snapshot_options_or_none}
```
defined as:
```
local extra_gen_snapshot_options_or_none=""
if [[ -n "$EXTRA_GEN_SNAPSHOT_OPTIONS" ]]; then
extra_gen_snapshot_options_or_none="--extra-gen-snapshot-options=$EXTRA_GEN_SNAPSHOT_OPTIONS"
fi
```
To apply your changes, in [FlutterRoot], run
```
git commit -am "Enable obfuscation on iOS"
flutter
```
(Running "flutter" after the commit rebuilds flutter tools.)
Next, in your project, add following to `[ProjectRoot]/ios/Flutter/Release.xcconfig` file:
```
EXTRA_GEN_SNAPSHOT_OPTIONS=--obfuscate
```
---
*PS: Haven't tried the --save-obfuscation-map flag mentioned at <https://github.com/dart-lang/sdk/issues/30524>
Again, obfuscation **isn't** very well **tested**, as mentioned by @mraleph.* | All the above answers are correct, but no answer tells you that we need to add a relative path or directory path while generating build.
**Example using Relative Path:**
```
flutter build apk --obfuscate --split-debug-info=./ProjectFolderName/debug
```
**Example using Folder Path:**
```
flutter build apk --obfuscate --split-debug-info=/Users/apple/Desktop/items/debug
```
The above command will generate a build inside the given project directory, it will create a new folder called `ProjectFolderName` or 'debug' on the respective command, and there you can find the release build. |
1,330,282 | I'm trying to diagnose why my Outlook plugin written in C#/VSTO 3.0/VS 2008 doesn't load after being installed.
The plugin works awesomely on my development machine, which has Visual Studio 2008 installed. I can't expect all my users to have all the prerequisites though so I went through these steps to write an installer:
<http://msdn.microsoft.com/en-us/library/cc563937(loband).aspx>
I installed the add-in on a fresh Windows XP SP 2 machine with a fresh install of Outlook 2007. It installs all the prereqs ok (.NET 3.5, VSTO 3.0 runtime, Windows Installer 3.1, 2007 PIAs). Outlook starts but the add-in isn't run. If I go to the Add-ins tab in the Trust Center, I see my add-in in the "Inactive Application Add-ins" section with the message "Not loaded. A runtime error occurred during the loading of the COM Add-in.".
Not sure how to find the specific error so I can fix it.
The reg keys look ok. Under HKEY\_CURRENT\_USER\Software\Microsoft\Office\Outlook\Addins\BlahAddin I see Description, FriendlyName, LoadBehavior (set to 3 until it fails after which if becomes set to 2), and Manifest.
Tried the VSTO\_SUPPRESSDISPLAYALERTS environment variable trick and then launched Outlook from the command line but no output came out.
I have remote debugging more or less working but I'm not sure what to look for. I don't see my DLL loaded when I attach to Outlook, but then again maybe managed DLLs don't show up the same way in VS.
Any other ideas on next steps I could follow to produce a specific error I can diagnose? | 2009/08/25 | [
"https://Stackoverflow.com/questions/1330282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3284/"
] | Make sure you have try-catch handlers at the top level of all methods called by Outlook and log any exceptions you are unable to handle in some way. Focus your troubleshooting on methods like the `Startup` method and other methods called during initialization. | On your machine, when you run the addin from Visual Studio, it should create a registry key in HKEY\_CURRENT\_USER\Software\Microsoft\VSTO\Security\Inclusion{SomeGuid}. Make sure that these registry settings are also being deployed with your addin. They are the ones that allow your code to be trusted. |
38,407,803 | I was recently asked this question at an interview and I wasn't able to solve it. I wanted to post it here and see if anyone can give me some ideas on how to approach on solving such problems.
**Question: Given positive X axis and Y axis...**
1. **Start by drawing a square of width=A (say A=1000)**
2. **Next draw a circle of maximum possible radius inside the square such that the circle touches all 4 sides of the square.**
3. **Next draw a square inside this circle such that all 4 vertices of the square are touching the circle.**
4. **Keep repeating the above process and keep drawing circles and squares alternatively until the area of the shape just drawn is < B (say B=10).**
***Write the pseudocode/logic to achive this.***
Here is a sample diagram showing what the interviewer asked (excuse the mishapen portion).
[](https://i.stack.imgur.com/Fgn9l.png) | 2016/07/16 | [
"https://Stackoverflow.com/questions/38407803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1334148/"
] | If you have your html in string form you can perform some regex and loops on the string and get the desired outcome in array from, i'm not sure if this is what you're looking for..
```js
var result = html.match(/<td>(.*?)<\/td>/g).reduce(
function(new_array,x,i,arr) {
if(i % 3 == 0){
new_array.push('<tr class="new">' + arr[i] + (arr[i+1] || '') + (arr[i+2] || '') + '</tr>');
return obj;
}
}
,[])
``` | You just need to set counter for this, example :
```
$counter = 0;
foreach ($table_data as $single_table_date){
if ($counter % 3 == 0) {
echo '</tr>';
echo '<tr>';
}
echo '<td>';
echo $single_table_date;
echo '</td>';
$counter++;
}
``` |
9,235,309 | Using Java, is there a way to look at some content, say, String representation of a file and either confirm or deny that it represents an XML file?
What library would you chose to parse the file? Could you possibly provide an example? | 2012/02/10 | [
"https://Stackoverflow.com/questions/9235309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/359862/"
] | IMO the *quickest* way would be to see if it parses, particularly if you have a DTD/XSD. You can check for well-formedness without either using any of the normal XML parsing libs.
Otherwise, not really sure what you could do. | Well, you could just examine the root tag: `<?xml version="" ?>` to check whether it's XML. But if your looking to validate an XML document that has specified a schema or DTD, then just create a validating parser from one of the two JAXP parser factories: SAXParserFactory and DOMBuilderFactory. If your validating only, go with the SAX parser, as it has a smaller memory footprint. |
9,462,356 | I found that I am confusing between web framework and web server.
`Apache is a web server.`
`Tornado is a web server written in Python.`
`Nginx is a web server written in C`
`Zend is a web framework in php`
`Flask/Bottle is a web framework in Python`
`RoR is a web framework written in Ruby`
`Express is a web framework written in JS under Node.JS`
Can we say node.js is a web server??? I am so confused between web server/ framework.
If somehow node.js is kind of webserver, not webframework (Express does), why do we need to put the whole node.js on top of Nginx server in useful practice??
[Question on SO](https://stackoverflow.com/questions/9287747/why-do-we-need-apache-under-node-js-express-web-framework)
Who can help???
Kit | 2012/02/27 | [
"https://Stackoverflow.com/questions/9462356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/514316/"
] | How I feel your pain !
Like many, I found it hard to get to the essence of Node.js because most people only write/talk about the part of Node that they find useful - and the part they find interesting is usually a secondary benefit of Node rather than its primary purpose. I must say that I think it's mad for people to say that Node is just a JavaScript runtime. Node's use of JavaScript - and its selection of the V8 runtime - are simply *means to an end*, the best tools for the problem that Node's developers wanted to solve.
Node's primary purpose was to make the management of user events in a web app more efficient. So Node is *overwhelmingly* used on the back end of a web app. Event management demands that something is listening at the server machine for these user events. So a http server must be set up to route each event to its appropriate handler script. Node provides a framework for quickly setting up a server to listen on a dedicated port for user requests. Node uses JavaScript for event handling *because JavaScript allows functions to be called as objects*. This allows the task to be executed immediately after an asynchronous request (e.g. to a file system, database or network) to be wrapped in a function and referenced as a parameter of the asynchronous request function call.
```
const mysql = require('mysql2');
const conn = mysql.createConnection(
{
host: "XXXXXXXXXXXXX",
database: "doa_statsbase",
user: "uoalabama_doas",
password: "*************"
});
. . .
. . .
const analyse_bigwheat_farmers = (err, result, fields) =>
{
. . . . .
. . . . .
return data_object;
}
. . .
. . .
let query = "SELECT * FROM us_farmers WHERE acreage > '1000' AND crop='wheat'";
mysql.query(query, (err, result, fields) =>
{
analyse_bigwheat_farmers(err, result, fields);
}
. . .
. . .
. . .
```
Not many other languages treat functions as objects and those that do may not have an interpreter as efficient as Google's V8 runtime. Most web developers already know JavaScript so there's no additional language learning with Node. What's more, having callback functions *allows all user tasks to be put on a single thread* without having explicit blocking applied to tasks demanding access to the database or file system. And this is what leads to the superior executional efficiency of Node under heavy concurrent use - the primary purpose for its development.
Today, most Node web applications use callbacks sparingly as JavaScript ES6 introduced the *Promise* construct in 2015 to handle asynchronous calls more easily and readably.
To help Node users quickly write back end code, Node's developers also organized both a built-in JS library for routine tasks (e.g. matters related to HTTP requests, string (de)coding, streams etc) and the NPM (Node Package Manager) repositary: this is an open source, user-maintained set of script packages for various standard and custom functions. All Node projects allow importation of NPM packages into a project via the established ***npm install*** command.
User requests handled via Node will be things needed by the web app like authentication, database querying, content management system (ApostropheCMS, Strapi CMS) updates, etc. All these will be sent to the Node port. (Where analysis of data got from a database is takes a lot of CPU time, this type of process is best put on a separate thread so it doesn't slow simpler user requests.) Other types of user request, e.g. to load another webpage, download CSS/JS/image files, etc, will continue to be sent by the browser to the default ports (typically ports 80 (HTTP) and 443 (HTTPS) on the server machine where the web server program (Apache, NGinx, etc) will handle them in the mode of a traditional website.
*[A side note here on request streaming to the server. Since most server machines' firewalls only allow the default ports 80/443 open, it is not usually allowed to **directly** send a Node.js request with another port in the URL, e.g. https://mynodeapp.com:3001/fetch-members. If one did, the server machine's firewall would simply ignore it as it directly references an illegal port.
Instead one could apply a URL to the request that has no explicit port number but which contains a virtual folder name that identifies the Node.js app, e.g. https://mynodeapp.com/mynodeapp/fetch-members. Then append some server directive code on the .htaccess file like:*
```
RewriteEngine On
RewriteRule ^mynodeapp/(.*) https://localhost:3001/$1 [P]
```
*Node.js requests given URLs in this way will thus find their way to the Node.js server for that web app via the nominated ports for the Node application, i.e. 3001 in the example here.]*
So, in practice, Node is principally a framework for rapid server-creation and event-handling but one that replaces only some of the functions of the web server program.
Other non-backend uses of Node simply exploit one or other of its features, e.g. the JavaScript V8 engine. For example, the frontend build tools **Grunt** and **Gulp** use a frontend Node.js app to process a build script that can be coded to convert SASS to CSS, minify CSS/JS files, optimize image size or image loading, generate page-state HTML files for refreshing page-states in a single page application site, etc. But this sort of work is really just a by-product use of Node and not its principal use which is for making efficient backend processes for modern web applications. | I think the problem is that the terminology of "web server" or "web application server" is dominated by the JEE world, and products, that are not as modularized as today's Javascript world of frameworks, which in turn can be combined more or less freely.
I see no reason why a technology, that can serve complex applications over the web, should **not** be called a web server, or web application server!
If you combine, let's say [Nuxt](https://nuxtjs.org/guide) as a frontend, with [Feathers](https://feathersjs.com/) as a backend - you'll have a backend serving a REST API and a server-side rendered UI!
Of course, you could (mis)use that to serve static content - then I'd call it a web server, or you could use it to make and serve a full application - then I'd call it a web application server.
It's the combined features or qualities that sum up to serve a purpose - right? - Features like stability, scalability and such are IMHO something that will be added to those technologies, over time. For now, they're pretty new still. |
33,814,687 | I have two JS objects, I want to check if the first Object has all the second Object's keys and do something, otherwise, throw an exception. What's the best way to do it?
```
function(obj1, obj2){
if(obj1.HasAllKeys(obj2)) {
//do something
}
else{
throw new Error(...);
}
};
```
For example in below example since FirstObject has all the SecondObject's key it should run the code :
```
FirstObject
{
a : '....',
b : '...',
c : '...',
d : '...'
}
SecondObject
{
b : '...',
d : '...'
}
```
But in below example I want to throw an exception since XXX doesnt exist in FirstObject:
```
FirstObject
{
a : '....',
b : '...',
c : '...',
d : '...'
}
SecondObject
{
b : '...',
XXX : '...'
}
``` | 2015/11/19 | [
"https://Stackoverflow.com/questions/33814687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/140903/"
] | You can use:
```
var hasAll = Object.keys(obj1).every(function(key) {
return Object.prototype.hasOwnProperty.call(obj2, key);
});
console.log(hasAll); // true if obj2 has all - but maybe more - keys that obj1 have.
```
As a "one-liner":
```
var hasAll = Object.keys(obj1).every(Object.prototype.hasOwnProperty.bind(obj2));
``` | Another way to do this, that seems to work fine as well.
```
const o1 = {
a : '....',
b : '...',
c : '...',
d : '...'
},
o2 = {
b : '...',
d : '...',
};
///////////////////////
///// I. IN ONE LINE
///////////////////////
/**/
/**/ if(Object.keys(o2).every(key =>
/**/ key in o1
/**/ // Object.keys(o1).includes(key)
/**/ // Object.keys(o1).filter(x => x==key).length
/**/ ))
/**/ console.log(true);
/**/ else throw new Error("...");
/**/
///////////////////////
///////////////////////
///// II. IN A FUNCTION
///////////////////////
/**/
/**/ var hasAll = (o1 , o2) => {
/**/ let r = Object.keys(o2).every(key =>
/**/ // Object.keys(o1).includes(key)
/**/ // key in o1
/**/ // Object.keys(o1).filter(x => x==key).length
/**/
/**/ Object.keys(o1)
/**/ .reduce((acc,act,arr) =>
/**/ acc && (key in o1) // , true
/**/ )
/**/
/**/ );
/**/ return r;
/**/ }
/**/
/**/ let cond = hasAll(o1 , o2);
/**/
/**/ console.log(cond);
/**/
/**/ if (cond) console.log(true)
// /**/ else throw new Error("At least, one key doesn'e exist");
/**/
/**/ ////////
/**/
/**/ cond = hasAll(o2 , o1);
/**/
/**/ console.log(cond);
/**/
/**/ if (cond) console.log(true)
/**/ else throw new Error("At least, one key doesn'e exist");
/**/
///////////////////////
``` |
72,384,377 | I have a URI like this:
```
spotify:image:ab67616d0000b2737005885df706891a3c182a57
```
I want to know how to get the image from this URI? I'm currently using the Web API. I imagine I might need to convert the URI into the image URL some how.
I can't see anything elsewhere on Google or in the API docs.
Any help would be much appreciated, thanks! | 2022/05/25 | [
"https://Stackoverflow.com/questions/72384377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3846032/"
] | It's a simple while loop:
```
n = 23452436
while n >= 10:
print(n)
n = sum(int(i) for i in str(n))
print(n)
``` | This is a suitable place to use a recursive method.
```
def digit_sum(n: int):
curr_sum = sum(int(digit) for digit in str(n))
if curr_sum < 10:
return curr_sum
else:
return digit_sum(curr_sum)
``` |
533,183 | I have created this bash function to recursively find a file.
```
ff() {
find . -type f -name '$1'
}
```
However, it returns no results. When I execute the command directly on the commandline, I do get results. I am not sure why it behaves differently, as shown below.
```
mattr@kiva-mattr:~/src/protocol$ ff *.so
mattr@kiva-mattr:~/src/protocol$ find . -type f -name '*.so'
./identity_wallet_service/resources/libindystrgpostgres.so
```
Why does my function not work as expected? I am using MacOS and bash shell.
Thnx
Matt | 2019/07/31 | [
"https://unix.stackexchange.com/questions/533183",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/364914/"
] | You may also try the `<<<` (Here Strings) operator to save on lines:
```
$ python <<< 'print("MyTest")'
MyTest
``` | You can also set python path while calling the python file from bash script:
```
export PYTHONPATH=/tmp/python_dep.zip && python test_my.py
``` |
44,810,511 | I'm struggling to add empty spaces before the string starts to make [my GitHub `README.md`](http://github.com/noduslabs/8os/) looks something like this:
[](https://i.stack.imgur.com/S5eT4.png)
Right now it looks like this:
[](https://i.stack.imgur.com/PhzaX.png)
I tried adding `<br />` tag to fix the new string start, now it works, but I don't understand how to add spaces before the string starts without changing everything to ` `. Maybe there's a more elegant way to format it? | 2017/06/28 | [
"https://Stackoverflow.com/questions/44810511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/712347/"
] | Instead of using HTML entities like ` ` and ` ` (as others have suggested), you can use the Unicode em space (8195 in UTF-8) directly. Try copy-pasting the following into your `README.md`. The spaces at the start of the lines are em spaces.
```
The action of every agent <br />
into the world <br />
starts <br />
from their physical selves. <br />
``` | Markdown really changes everything to html and html collapses spaces so you really can't do anything about it. You have to use the ` ` for it. A funny example here that I'm writing in markdown and I'll use couple of here.
Above there are some ` ` without backticks |
8,992,113 | I am building a WPF calculator application, and while testing it (comparing with the behavior of the Windows built in calculator) i have seen some differences.
Here's a print out from one of my tests:
>
> Test 'Comparison.Tests.ComparisonTests' failed:
>
>
> Expected string length 17 but was 16. Strings differ at index 16.
>
> Expected: "175641.7874709774"
>
> But was: "175641.787470977"
>
>
>
I am using a *double* for all my calculations and finally displaying them as a string to a TextBox.
What is the reason of this difference? is double not enough for storing the results for the basic operations (Add, Multiply, Subtract, Divide, SQRT, etc). | 2012/01/24 | [
"https://Stackoverflow.com/questions/8992113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/494143/"
] | Double is plenty if you're willing to accept its limitations (15-16 digits of precision).
If you're using Windows Calculator as the gold standard, you should be aware that it does not use Double internally -- it was [rewritten in Windows 95](http://en.wikipedia.org/wiki/Calculator_%28Windows%29) to use an arbitrary-precision arithmetic library. Per [a blog post by Raymond Chen](http://blogs.msdn.com/b/oldnewthing/archive/2004/05/25/141253.aspx):
>
> Today, Calc's internal computations are done with infinite precision for basic operations (addition, subtraction, multiplication, division) and 32 digits of precision for advanced operations (square root, transcendental operators).
>
>
>
Most apps don't need more than 15 digits of precision. If yours does, you'll need to find a library that supports arbitrary-precision math. | Double will give you 53 bits of precision (52 bits in a 64-bit value, with an implicit extra bit for most values).
Decimal will give you 96 bits of precision (in a 128-bit value).
That the exponent of the former is in binary and of the later is decimal means that the "round" numbers in double can be more surprising to users than in decimal.
On the other hand, decimal doesn't do well in contexts where you need to represent infinity or not-a-number.
Most likely, decimal will serve much better double. If you need yet more precision, you could roll your own big-decimal by combining `BigInteger` and a number to hold the scale. |
56,561,964 | I want to remove the words having : sign (Like :word:) in its both side.I have already use a regular expression to remove all between two : sign. But i need to remove just single words exists between two : sign, not a full sentence (Like :I like to play cricket:).
```
string txt = "Hello, i :want: to remove :some word from: my text";
var output = Regex.Replace(txt, @" ?\:.*?\:", " ");
```
Expected Output:
>
> Hello, i to remove some word from my text
>
>
> | 2019/06/12 | [
"https://Stackoverflow.com/questions/56561964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5243258/"
] | the problem is your regex. try this:
```
var output = Regex.Replace(txt, @":([A-Za-z0-9]*):", "");
``` | In your regex you're using `.*` this matches any character except newline. Instead I assume you would like any non-whitespace character. In regex this would be `\S`, so in total you would get:
```
string txt = "Hello, i :want: to remove :some word from: my text";
var output = Regex.Replace(txt, @" ?\:\S*?\:", " ");
``` |
67,699,561 | How to solve **ReferenceError: window is not defined**? this is my code
```
let timestamp = new Date();
var str = params.email;
var enc = window.btoa(str);
var dec = window.atob(timestamp);
console.log(window)
if (window == "undefine"){
var template = handlebars.compile(html);
var htmlToSend = template({email:enc + "|" + dec});
var mailOptions = {
from: 'support@google.com',
to: params.email,
subject: 'Sending Email using Node.js',
html: htmlToSend
};
```
[](https://i.stack.imgur.com/tYQcV.png) | 2021/05/26 | [
"https://Stackoverflow.com/questions/67699561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14823468/"
] | Adding to what @Nabeel said, use this : if(typeof window === "undefined") | ***window is a browser thing that doesn't exist on Node.*** |
15,208 | Other than frequency response, what makes a mic sound **good**? Say there is a cheap microphone, and an expensive microphone with same frequency response/selfnoise/sensitivity/polar pattern.
Now we compare the recordings, they probably will sound different..and the winner will probably be expensive one. | 2012/08/29 | [
"https://sound.stackexchange.com/questions/15208",
"https://sound.stackexchange.com",
"https://sound.stackexchange.com/users/1055/"
] | I think your main issue with understanding this is that you're looking at it from too simplified a view.
* Frequency response curves can only be so accurate, and even within a manufactured line of a particular mic by a particular company there may be slight variations.
* Polar response is not identical between two different model microphones (even though they're both labelled as hyper-cardioid). They will be very close, but not identical. In addition, polar response changes based on frequency within the spectrum.
* Sensitivity can be misleading, because truly quiet sounds can be identified in a signal even if their in the noise floor. The sensitivity measurement is not necessarily tied to the mic's signal to noise ratio. Many manufacturers will say that a mic can respond to "X" level sounds, even if they're in the noise floor...because there is a measurable pickup.
There are other issues involved as well: such as response time (which factors in to sensitivity, though it is rarely mentioned), or subtle phase differences that contribute to the mic's overall tone/color (independent of frequency response).
As has been mentioned it's largely a case of design. Mics are designed for specific purposes, and trade offs are allowed to control cost versus specified use. It can also depend on the source you're recording. I've been editing some fabric sound I recorded, and two of the mics I used are nearly identical sounding in some of those files (a Neumann TLM-170R in hyper-cardioid and an AKG SE 300B with with CK93 capsule). They would sound very different on a voice recording though. | There are some complex well thought out answers here, but to me the straight up question "can you make a cheap mic sound like an expensive one?" The answer is still unequivocally NO! You cannot skirt around it with long winded explanations.
Making two different mics "work well" together with use of eq is a totally different topic. |
20,691,463 | Is there any difference in how `Data.Text` and `Data.Vector.Unboxed Char` work internally? Why would I choose one over the other?
I always thought it was cool that Haskell defines `String` as `[Char]`. Is there a reason that something analagous wasn't done for `Text` and `Vector Char`?
There certainly would be an advantage to making them the same.... Text-y and Vector-y tools could be written to be used in both camps. Imagine Ropes of Ints, or Regexes on strings of poker cards.
Of course, I understand that there were probably historical reasons and I understand that most current libraries use `Data.Text`, not `Vector Char`, so there are many practical reasons to favor one over the other. But I am more interested in learning about the abstract qualities, not the current state that we happen to be in.... If the whole thing were rewritten tomorrow, would it be better to unify the two?
Edit, with more info-
To put stuff into perspective-
1. According to this page, <http://www.haskell.org/haskellwiki/GHC/Memory_Footprint>, GHC uses 16 bytes for each Char in your program!
2. Data.Text is not O(1) index'able, it is O(n).
3. Ropes (binary trees wrapped around text) can also hold strings.... They have better complexity for index/insert/delete, although depending on the number of nodes and balance of the tree, index could be close to that of Text.
This is my takeaway from this-
1. `Text` and `Vector Char` are different internally....
2. Use String if you don't care about performance.
3. If performance is important, default to using Text.
4. If fast indexing of chars is necessary, and you don't mind a lot of memory overhead (up to 16x), use Vector Char.
5. If you want to insert/delete a lot of data, use Ropes. | 2013/12/19 | [
"https://Stackoverflow.com/questions/20691463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2827654/"
] | It's a fairly bad idea to think of `Text` as being a list of characters. `Text` is designed to be thought of as an opaque, user-readable blob of Unicode text. Character boundaries might be defined based on encoding, locale, language, time of month, phase of the moon, coin flips performed by a blinded participant, and migratory patterns of Venezuela's national bird whatever it may be. The same story happens with sorting, up-casing, reversing, etc.
Which is a long way of saying that `Text` is an abstract type representing human language and goes far out of its way to not behave just the same way as its implementation, be it a `ByteString`, a `Vector UTF16CodePoint`, or something totally unique (which is the case).
To clarify this distinction take note that there's no guarantee that `unpack . pack` witnesses an `isomorphism`, that the preferred ways of converting from `Text` to `ByteString` are in `Data.Text.Encoding` and are partial, and that there's a whole sophisticated plug-in module [`text-icu`](http://hackage.haskell.org/package/text-icu) littered with complex ways of handling human language strings.
You absolutely should use `Text` if you're dealing with a human language string. You should also be really careful to treat it with care since human language strings are not easily amenable to computer processing. If your string is better thought of as a machine string, you probably should use `ByteString`.
The pedagogical advantages of `type String = [Char]` are high, but the practical advantages are quite low. | To add to what J. Abrahamson said, it's also worth making the distinction between iterating over runes (roughly character by character, but really could be ideograms too) as opposed to unitary logical unicode code points. Sometimes you need to know if you're looking at a code point that has been "decorated" by a previous code point.
In the case of the latter, you then have to make the distinction between code points that stand alone (such as letters, ideograms) and those that modify the text that follows (right-to-left code point, diacritics, etc).
Well implemented unicode libraries will typically abstract these details away and let you process the text in a more or less character-by-character fashion but you have to drop certain assumptions that come from thinking in terms of ASCII.
A byte is not a character. A logical unit of text isn't necessarily a "character". Not every code point stands alone, some decorate/annotate the following code point or even the rest of the byte stream until invalidated (right-to-left).
Unicode is hard. There is no one true encoding that will eliminate the difficulty of encapsulating the variety inherent in human language. Data.Text does a respectable job of it though.
To summarize:
The methods of processing are:
* byte-by-byte - totally invalid for unicode, only applicable to latin-1/ASCII
* code point by code point - works for processing unicode, but is lower-level than people realize
* logical rune-by-rune - what you actually want
The types are:
* String (aka [Char]) - has a limited scope. Best used for teaching Haskell or for legacy use-cases.
* Text - the preferred way to handle "human" text.
* Bytestring - for byte streams, raw data, binary etc. |
643,040 | I have the following integral I'm trying to solve:
$$\frac{3}{2\pi}\int\_0^{2\pi}\frac{e^{-ikx}}{5 - 4\cos(x)} \mathrm dx, \quad k \in \mathbb{Z}.$$
I've tried writing the exponential in terms of sines and cosines and then using the usual rational trig function substitutions, i.e. rewriting the integrand as
$$\frac{\cos(kx)}{5 - 4\cos(x)} - \frac{i\sin(kx)}{5 - 4\cos(x)}$$
and then using the substitution $t = \tan{x/2}$, but this doesn't result in anything useful that I could come up because of the different fequencies in the trig functions. I also tried writing the cosine in terms of complex exponentials, but didn't end up with anything useful either.
If the only solution involves residue calculus then please let me know, as I'm not familiar with that subject so I haven't tried anything like that. Thanks!
UPDATE: As was suggested I wrote the $\frac{1}{5 - 4\cos(x)}$ term as a geometric series $\frac{1}{5}\sum\limits\_{n = 0}^\infty (\frac{4}{5}\cos(x))^n$, so now I am trying to evaluate
$$\int\_0^{2\pi} \cos^n(x) e^{-ikx} dx,$$
but am stuck here again. I am trying to do this without using the residue theorem, but if that's the only way then so be it! | 2014/01/18 | [
"https://math.stackexchange.com/questions/643040",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/99261/"
] | Careful when differentiating. With $y=Ate^{-2t}$ I got,
$$y'=-2Ate^{-2t}+Ae^{-2t} $$
and so when we plug that into the differential equation we are looking for values of $A$ such that the following equation is satisfied,
$$ 2(-2Ate^{-2t}+Ae^{-2t})+4Ate^{-2t}=3e^{-2t} $$
So we are looking for $2A=3$. So I do think there is a solution for $A$. You do have the correct solution method though! Then do the same thing for $B$. | You are right there are no values of $A$ and $B$ that for which your $y$'s are solutions. Actually the solution is a linear function $y = 3t +C$. |
3,203,321 | Can anybody give pointers how I can implement lzw compression/decompression in low memory conditions (< 2k). is that possible? | 2010/07/08 | [
"https://Stackoverflow.com/questions/3203321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/158163/"
] | The lowest dictionary for lzw is **trie on linked list**. See original implementation in [LZW AB](https://github.com/dbry/lzw-ab/blob/master/lzw-lib.c). I've rewrited it in fork [LZWS](https://github.com/andrew-aladev/lzws). Fork is compatible with `compress`. Detailed documentation [here](https://github.com/andrew-aladev/lzws/blob/master/doc/compressor_with_linked_list.txt).
`n` bit dictionary requires `(2 ** n) * sizeof(code) + ((2 ** n) - 257) * sizeof(code) + (2 ** n) - 257`.
So:
1. **9 bit** code - **1789** bytes.
2. **12 bit** code - **19709** bytes.
3. **16 bit** code - **326909** bytes.
Please be aware that it is a requirements for dictionary. You need to have about 100-150 bytes for state or variables in stack.
Decompressor will use less memory than compressor.
So I think that you can try to compress your data with `9 bit` version. But it won't provide good compression ratio. More bits you have - ratio is better. | ```
typedef unsigned int UINT;
typedef unsigned char BYTE;
BYTE *lzw_encode(BYTE *input ,BYTE *output, long filesize, long &totalsize);
BYTE *lzw_decode(BYTE *input ,BYTE *output, long filesize, long &totalsize);
``` |
15,820,760 | I'm trying to test the following:
```
protected IHealthStatus VerifyMessage(ISubscriber destination)
{
var status = new HeartBeatStatus();
var task = new Task<CheckResult>(() =>
{
Console.WriteLine("VerifyMessage(Start): {0} - {1}", DateTime.Now, WarningTimeout);
Thread.Sleep(WarningTimeout - 500);
Console.WriteLine("VerifyMessage(Success): {0}", DateTime.Now);
if (CheckMessages(destination))
{
return CheckResult.Success;
}
Console.WriteLine("VerifyMessage(Pre-Warning): {0} - {1}", DateTime.Now, ErrorTimeout);
Thread.Sleep(ErrorTimeout - 500);
Console.WriteLine("VerifyMessage(Warning): {0}", DateTime.Now);
if (CheckMessages(destination))
{
return CheckResult.Warning;
}
return CheckResult.Error;
});
task.Start();
task.Wait();
status.Status = task.Result;
return status;
}
```
with the following unit test:
```
public void HeartBeat_Should_ReturnWarning_When_MockReturnsWarning()
{
// Arrange
var heartbeat = new SocketToSocketHeartbeat(_sourceSubscriber.Object, _destinationSubscriber.Object);
heartbeat.SetTaskConfiguration(this.ConfigurationHB1ToHB2_ValidConfiguration());
// Simulate the message being delayed to destination subscriber.
_destinationSubscriber.Setup(foo => foo.ReceivedMessages).Returns(DelayDelivery(3000, Message_HB1ToHB2()));
// Act
var healthStatus = heartbeat.Execute();
// Assert
Assert.AreEqual(CheckResult.Warning, healthStatus.Status);
}
```
Message\_HB1ToHB2() just returns a string of characters and the "Delay Delivery" method is
```
private List<NcsMessage> DelayDelivery(int delay, string message)
{
var sent = DateTime.Now;
var msg = new NcsMessage()
{
SourceSubscriber = "HB1",
DestinationSubscriber = "HB2",
SentOrReceived = sent,
Message = message
};
var messages = new List<NcsMessage>();
messages.Add(msg);
Console.WriteLine("DelayDelivery: {0}", DateTime.Now);
Thread.Sleep(delay);
Console.WriteLine("DelayDelivery: {0}", DateTime.Now);
return messages;
}
```
I'm using Moq as the mocking framework and MSTest as the testing framework. Whenever I run the unit test, I get the following output:
```
DelayDelivery: 04/04/2013 15:50:33
DelayDelivery: 04/04/2013 15:50:36
VerifyMessage(Start): 04/04/2013 15:50:36 - 3000
VerifyMessage(Success): 04/04/2013 15:50:38
```
Beyond the obvious "code smell" using the Thread.Sleep in the methods above, the result of the unit test is not what I'm trying to accomplish.
Can anyone suggest a better/accurate way to use the Moq framework to simulate a delay in "delivery" of the message. I've left out some of the "glue" code and only included the relevant parts. Let me know if something I've left out that prevents you from being able to understand the question. | 2013/04/04 | [
"https://Stackoverflow.com/questions/15820760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83661/"
] | If running asynchronous code, Moq has the ability to delay the response with the second parameter via a `TimeSpan`
```
mockFooService
.Setup(m => m.GetFooAsync())
.ReturnsAsync(new Foo(), TimeSpan.FromMilliseconds(500)); // Delay return for 500 milliseconds.
```
If you need to specify a different delay each time the method is called, you can use `.SetupSequence` like
```
mockFooService
.SetupSequence(m => m.GetFooAsync())
.Returns(new Foo())
.Returns(Task.Run(async () =>
{
await Task.Delay(500) // Delay return for 500 milliseconds.
return new Foo();
})
``` | I had a similiar situation, but with an Async method. What worked for me was to do the following:
```
mock_object.Setup(scheduler => scheduler.MakeJobAsync())
.Returns(Task.Run(()=> { Thread.Sleep(50000); return Guid.NewGuid().ToString(); }));
``` |
2,669,652 | i wonder if Doctrine 2 is stable enough to use for a production project?
i guess the project will be finished 3 months from now so maybe then Doctrine 2 will be released in a complete version.
i'm wondering if its smarter to use learn and use doctrine 2 right away instead of learning the current version and then convert everything to version 2. cause i've read that the difference is huge between them.
thanks | 2010/04/19 | [
"https://Stackoverflow.com/questions/2669652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/224922/"
] | Are you able to scroll using touches to the last row? It may be a contentSize issue. | The easiest way is to set this [statusMessagesTableView setContentInset:UIEdgeInsetsMake(0, 0, 80, 0)]; |
34,600,932 | I ran
```
npm config set prefix /usr/local
```
After running that command,
When trying to run any npm commands on Windows OS I keep getting the below.
```
Error: EPERM: operation not permitted, mkdir 'C:\Program Files (x86)\Git\local'
at Error (native)
```
Have deleted all files from
```
C:\Users\<your username>\.config\configstore\
```
It did not work.
Any suggestion ? | 2016/01/04 | [
"https://Stackoverflow.com/questions/34600932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5236174/"
] | Sometimes, all that's required is to stop the dev server before installing/updating packages. | If cleaning the cache(`npm cache clean --force`) doesn't help you just delete
manually the folder `C:\Users\%USER_NAME%\AppData\Roaming\npm-cacheand` and reinstall NodeJS |
60,559,434 | I would like to manipulate the code from an answer found in the following link:
[Compare md5 hashes of two files in python](https://stackoverflow.com/questions/36873485/compare-md5-hashes-of-two-files-in-python)
My expected outcome would be to search for the two files I want to compare, and then execute the rest of the script allowing for an answer of whether it is "True" that the MD5 files matches, otherwise "False".
I have tried the following code:
```
import hashlib
from tkinter import *
from tkinter import filedialog
digests = []
z = filedialog.askopenfilenames(initialdir="/", title="Browse Files", filetypes=(("excel files", "*.xlsx"),
("all files", "*.*")))
b = filedialog.askopenfilenames(initialdir="/", title="Browse Files", filetypes=(("excel files", "*.xlsx"),
("all files", "*.*")))
filez = z, b
for filename in filez:
hasher = hashlib.md5()
with open(filename, 'rb') as f:
buf = f.read()
hasher.update(buf)
a = hasher.hexdigest()
digests.append(a)
print(a)
print(digests[0] == digests[1])
```
Unfortunately I receive the following error:
"TypeError: expected str, bytes or os.PathLike object, not tuple"
Thanks in advance. | 2020/03/06 | [
"https://Stackoverflow.com/questions/60559434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11915729/"
] | The `filedialog.askopenfilenames` returns a tuple. This means means that `z` and `b`, and in turn the `filename` iterator of the for loop, are tuples. You are getting the error because you are passing `filename`, which is a tuple, into the open function.
A way to fix this could be to simply concatenate the tuples.
```
filez = z + b
``` | Fixed above error as stated using this line of code:
```
filez = z[0], b[0]
``` |
29,618,187 | l1 and l2 are arrays that I input. I want to merge l1 and l2 into l3 and sort them in ascending order. When i tried to add l1 and l2 into l3 i get a syntax error stating, "The left-hand side of an assignment must be a variable".
```
import java.util.ArrayList;
import java.util.Scanner;
public class Array {
public static void main(String[] args) {
String david;
String bert;
Scanner input = new Scanner(System.in);
System.out.println("Enter a list of integers: ");
bert = input.next();
System.out.println("Enter a second list of integers: ");
david = input.next();
String parts[] = bert.split(" ");
String parts2[] = david.split(" ");
int[] l1 = new int[parts.length];
for(int n = 0; n < parts.length; n++) {
l1[n] = Integer.parseInt(parts[n]);
}
int[] l2 = new int[parts2.length];
for(int n = 0; n < parts2.length; n++) {
l2[n] = Integer.parseInt(parts2[n]);
}
int w = 0;
int s = 0;
int a = 0;
ArrayList<Integer> l3 = new ArrayList <Integer> ();
while(w>s)
if (l1[w]<=l2[s])
l3.add(a++) = l1[w++];
else
l3.add(a++) = l2[s++];
while(w>s)
if (l1[w]<=l2[s])
l3.add(a++) = l1[w++];
else
l3.add(a++) = l2[s++];
while(w==s)
if (l1[w]<=l2[s])
l3.add(a++) = l1[w++];
else
l3.add(a++) = l2[s++];
for (int i = 0; i < l3.size(); i++) {
System.out.print(l3.add(i) + " ");
}
}
}
``` | 2015/04/14 | [
"https://Stackoverflow.com/questions/29618187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4771787/"
] | The [`ArrayList.add(int, E)`](http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#add%28int,%20E%29) method can take an index and a value (that is, you can't assign the value to the result of `add` **or** *the left-hand side of an assignment must be a variable*). Also, please use braces. Something like
```
while (w > s) {
if (l1[w] <= l2[s]) {
l3.add(a++, l1[w++]);
} else {
l3.add(a++, l2[s++]);
}
}
``` | You are trying to do a .add() method at the same time as assigning it to another variable. This doesn't work. You should stick with just:
```
l3.add(a++);
``` |
61,943,014 | It works just once for the below code
```
import {
graphql,
GraphQLSchema,
GraphQLObjectType,
GraphQLString,
buildSchema,
} from "https://cdn.pika.dev/graphql/^15.0.0";
import { serve } from "https://deno.land/std@0.50.0/http/server.ts";
var schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: "RootQueryType",
fields: {
hello: {
type: GraphQLString,
resolve() {
return "world";
},
},
},
}),
});
var query = "{ hello }";
graphql(schema, query).then((result) => {
console.log(result);
});
```
---
How to keep it listening, just like `express`
Something like this
```
var express = require('express');
var graphqlHTTP = require('express-graphql');
var { buildSchema } = require('graphql');
// Construct a schema, using GraphQL schema language
var schema = buildSchema(`
type Query {
hello: String
}
`);
// The root provides a resolver function for each API endpoint
var root = {
hello: () => {
return 'Hello world!';
},
};
var app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true,
}));
app.listen(4000);
console.log('Running a GraphQL API server at http://localhost:4000/graphql');
``` | 2020/05/21 | [
"https://Stackoverflow.com/questions/61943014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8407705/"
] | ```
import {
graphql,
buildSchema,
} from "https://cdn.pika.dev/graphql/^15.0.0";
import {Application, Router} from "https://deno.land/x/oak/mod.ts";
var schema = buildSchema(`
type Query {
hello: String
}
`);
var resolver = {hello: () => 'Hello world!'}
const executeSchema = async (query:any) => {
const result = await graphql(schema, query, resolver);
return result;
}
var router = new Router();
router.post("/graph", async ({request, response}) => {
if(request.hasBody) {
const body = await request.body();
const result = await executeSchema(body.value);
response.body = result;
} else {
response.body = "Query Unknown";
}
})
let app = new Application();
app.use(router.routes());
app.use(router.allowedMethods());
console.log("Server running");
app.listen({port: 5000})
``` | I have created [gql](https://github.com/deno-libs/gql) for making GraphQL servers that aren't tied to a web framework. All of the responses above show Oak integration but you don't really have to use it to have a GraphQL server. You can go with `std/http` instead:
```
import { serve } from 'https://deno.land/std@0.90.0/http/server.ts'
import { GraphQLHTTP } from 'https://deno.land/x/gql/mod.ts'
import { makeExecutableSchema } from 'https://deno.land/x/graphql_tools/mod.ts'
import { gql } from 'https://deno.land/x/graphql_tag/mod.ts'
const typeDefs = gql`
type Query {
hello: String
}
`
const resolvers = {
Query: {
hello: () => `Hello World!`
}
}
const schema = makeExecutableSchema({ resolvers, typeDefs })
const s = serve({ port: 3000 })
for await (const req of s) {
req.url.startsWith('/graphql')
? await GraphQLHTTP({
schema,
graphiql: true
})(req)
: req.respond({
status: 404
})
}
``` |
469,063 | I’ve joined a writer’s forum that has critiquing workshops, and I’m merrily participating. Some of the work is really good. But I keep running across usages of the word “whilst”, which to me is old fashioned and outdated.
Many of the posters there have English as a second (or third) language, and are (sometimes clearly) using translation engines to post their work for review. Before commenting on their use of *whilst*, I thought I’d check to make sure I am correct. So...
Is *whilst* proper English, as in, “...whilst snow fell gently outside her window”? Is *while* a more appropriate word here? If it is proper, is it still in common use in other countries (other than the U.S.), or is it old fashioned and outdated for English everywhere? | 2018/10/18 | [
"https://english.stackexchange.com/questions/469063",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/-1/"
] | My understanding is that 'whilst' is rarely used anywhere, but it's much more common in UK English than US English.
One quick link:
<https://blog.oxforddictionaries.com/2016/02/18/while-or-whilst/> | It's almost never used in verbal communications in the American English. It is often used in British English verbally. Both are acceptable in written communication, though American readers may find it pretentious at worst and "British" at best. In dialog, it can be used to denote someone with a British accent. Americans do know what is being stated (Actually, Americans are quite familiar with British idiomatic dialects and get a lot of humor out of the changes. This is not true with other English Dialects, like Scottish, Australian, and Kiwi. The former two, when thick, are another language entirely to Americans, and the later is "definitely not American, but we know it's odd enough to not be British. My Kiwi boyfriend has gotten responses of London, South Africa, and Wales to his accent.). |
844 | Just curious, what are the requirements for leaving the beta stage and becoming a full-fledged site like, say, English Language & Usage? | 2012/01/11 | [
"https://christianity.meta.stackexchange.com/questions/844",
"https://christianity.meta.stackexchange.com",
"https://christianity.meta.stackexchange.com/users/1039/"
] | As David notes, [instructions for deleting your account can be found here.](https://meta.stackexchange.com/questions/5999/can-i-delete-my-account/7979#7979) Note that you *should* have been able to self-delete your account, since you've never used it. However, since you've already gone ahead and emailed us about it, I've removed your account.
Reminder to anyone reading this that account deletion is irreversible under normal circumstances. But feel free to create a new account at any time should you later decide you want one... | In case anyone is looking how to delete his Christianity.SE account, [here is the form](https://christianity.stackexchange.com/help/user-deletion). |
8,414,189 | I need to generate reports from database (billing forms for example) from ASP.NET interface. So I'm wondering which approach is better : Use Crystal Reports, reports based on RDLC or SQL Reporting Services ? I need to create an interface, which allows user to select data and through pre-created report definition generate that report. I want to use ASP.NET with AJAX, so it will act as a real application, but with no need for installation - and this is primary requirement.
So, if somebody knows which technology suits best those requirements...I will be grateful :) | 2011/12/07 | [
"https://Stackoverflow.com/questions/8414189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/876588/"
] | Personally I would go for [DevExpress XtraReports](http://devexpress.com/Products/NET/Reporting/).
I have used it in the past in both windows forms and web forms; it costs few hundreds of bucks but with the package you also get plenty of other UI controls, or you spend less and only buy XtraReports. It pays off in a flash, main advantages in my opinion are:
* each report can be designed with a Visual Studio integrated designer and becomes a simple c# class, easy to instantiate and use, no magic and no external report definitions, all pure 100% .NET code;
* end user designed is royalty free and users are amazed by the power and quality of the designer, with Ribbon or classic UI, plenty of features;
* so many out of the box zero coding ready to use features like print preview, export to excel, pdf etc...
**Disclaimer:** I do not work for DevExpress, I am not paid by them, simply I am a satisfied customer and used their products before with joy and good results, we are now in the process of starting a major MVC application development in my company and we are buying licenses of their DXperience Enterprise subscription these days.
you are free to also evaluate or test Crystal Reports or similar reporting solutions offered by ActiveReports, Telerik etc, I can only speak about XtraReports because I used it a lot, Crystal I used in the past with Visual Studio 2003 but I was not so impressed by the designer and deployment was really a mess in windows forms... always missing some files and having errors on client machines... | I would suggest taking a look at [ActiveReports 6](http://www.datadynamics.com/Products/ActiveReports/Overview.aspx). It provides great features and allows you to make almost unlimited customization to your report. For ASP.NET you can either opt for the standard edition which allows you to custom export your reports to different formats like PDF, Excel etc and display them to the users.
The professional edition provides you a webviewer control which allows you to display reports directly on the viewer and the user has the option to chose from PDF, HTML and FlashViewer format. In addition to this it also provides a silverlight based viewer control.
You may also want to check the [blogs](http://www.gcpowertools.info/) and the forums just in case you want to get more information about the product.
Thanks,
Sankalp (GrapeCity) |
2,565 | Suppose you have a standard hotel with a set of rooms. If you have booked a room for a fixed period of time, would allocating a specific room in advance potentially cause a conflict when trying to allocate rooms for other bookings in the future?
I have thought about this and can not think of an example where allocating in advance would make any difference, given the rooms are all interchangeable within their class (single/double etc.). Assuming that every booking **has to be** assigned a room eventually, there must be a solution so that every booking is associated with a matching room. Which specific room within the set of matching rooms should be irrelevant, hence a pre-allocation of a specific room should make no difference.
Is this in fact the case or am I missing something? I would like to have an example of where pre-allocation would cause an issue.
*Background*: I was told at checkin that my requested room could not be allocated because I would have been blocking it for other guests. | 2019/09/15 | [
"https://or.stackexchange.com/questions/2565",
"https://or.stackexchange.com",
"https://or.stackexchange.com/users/2352/"
] | I know that you explicitly ask for a statistical test, but maybe this is because you don't know about alternatives that are rather established in the community. When comparing algorithms, my number one is *performance profiles*.
They were introduced in this article: Elizabeth D. Dolan and Jorge J. Moré, [Benchmarking optimization software with performance profiles](https://link.springer.com/article/10.1007/s101070100263), Mathematical Programming, 91(2):201–213, 2002. | I think there are many different factors to consider. There's a very good paper by [Coffin and Saltzman](https://doi.org/10.1287/ijoc.12.1.24.11899) (Statistical Analysis of Computational Tests of Algorithms
and Heuristics, *INFORMS JOC* 12(1): 24-44, 2000) that discusses this issue in detail. |
52,234,523 | As far as I could understand, if one wants to contribute code to a repository, one would clone/pull and edit.
After that, one would push the changes to, e.g. github.
Aren't they actually "pushes"? | 2018/09/08 | [
"https://Stackoverflow.com/questions/52234523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9681577/"
] | If you like to send a contribution to a GitHub repository, it would be easy to just push it to the repository.
But if everyone just pushes code into one repository, it could get a mess. So therefor you ask the owner to get (and check) your changes, and he **pulls** the changes from your repository into his repository. | >
> Aren't they actually "pushes"?
>
>
>
Actually, **pushing** consists of transmitting by yourself an information to people around that could need it, while **pulling** is about fetching the information YOU need and bring it to you.
Since you generally don't have the right to directly write into a public repository, you make your changes available somewhere then *ask* the maintainer to *pull* them by himself into his repository. Thus the "pull request". |
58,281,356 | I've been making a Car Parking System for a school project, and I've been stuck on this problem for a while now. The goal of the project is to have a maximum of 10 parking slots, where the user is able to select which slot they want to be in from a drop-down box. So far, I've managed to get the drop-down box to show along with the 10 parking slots, but I could never get it to update on the row selected on the drop-down box. Here are my codes so far:
```
<?php
$CustomerName = $PlateNumber = $CarName = $CarColor = $Slot = "";
$CustomerNameErr = $PlateNumberErr = $CarNameErr = $CarColorErr = "";
if($_SERVER["REQUEST_METHOD"] == "POST")
{
if(empty($_POST["CustomerName"]))
{
$CustomerNameErr = "Please fill out this field";
}
else
{
$CustomerName = $_POST["CustomerName"];
}
if(empty($_POST["PlateNumber"]))
{
$PlateNumberErr = "Please fill out this field";
}
else
{
$PlateNumber = $_POST["PlateNumber"];
}
if(empty($_POST["CarName"]))
{
$CarNameErr = "Please fill out this field";
}
else
{
$CarName = $_POST["CarName"];
}
if(empty($_POST["CarColor"]))
{
$CarColorErr = "Please fill out this field";
}
else
{
$CarColor = $_POST["CarColor"];
}
}
?>
<form class="logintext" method="POST" action="<?php htmlspecialchars("PHP_SELF");?>">
<br><b>Register Parking</b><br><br>
<!-- Slot select-->
Select Slot: <select name="slots">
<?php
$mysqli = NEW mysqli('localhost','root','','sad');
$slot_query = $mysqli->query("SELECT slot FROM parkingrecords");
while ($rows = $slot_query->fetch_assoc())
{
$SlotVal = $rows['Slot'];
echo "<option value='".$rows['Slot']."'>".$rows['Slot']."</option>";
}
?>
</select><br><br>
<!-- fill-up form; this is the data that replaces the "empty" slots on the table-->
Customer Name: <input type="text" name="CustomerName" value="<?php echo $CustomerName ?>"><br>
<span class="error"><?php echo $CustomerNameErr; ?></span><br>
Plate Number: <input type="text" name="PlateNumber" value="<?php echo $PlateNumber ?>"><br>
<span class="error"><?php echo $PlateNumberErr; ?></span><br>
Car Name: <input type="text" name="CarName" value="<?php echo $CarName ?>"><br>
<span class="error"><?php echo $CarNameErr; ?></span><br>
Car Color: <input type="text" name="CarColor" value="<?php echo $CarColor ?>"><br>
<span class="error"><?php echo $CarColorErr; ?></span><br>
<input type="submit" value="Register">
</form>
<?php
include("carpark_connections.php");
if($Slot && $CustomerName && $PlateNumber && $CarName && $CarColor)
{
$query = mysqli_query($connections, "UPDATE parkingrecords SET CustomerName = '$CustomerName', PlateNumber = '$PlateNumber', CarName = '$CarName', CarColor = '$CarColor' WHERE Slot = '$SlotVal' ");
echo "<script language = 'javascript'>alert('You have been registered!')</script>";
echo "<script>window.location.href='ParkNow.php';</script>";
} ...
```
Nothing happens when I try to submit the update form. The data I type in doesn't seem to go anywhere at all, but it still executes the query since the javascript alert is working. I don't know what I'm missing here. Any help would be appreciated!
EDIT: I fixed a little bit of the code and now instead of nothing happening, it just keeps on updating the 10th slot no matter which slot i select on the dropdown. | 2019/10/08 | [
"https://Stackoverflow.com/questions/58281356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11355228/"
] | To match the required number of digits and no more, lookahead at the beginning of the pattern for `(?:\d\.?)` 1 to 8 times, and then match `\d*(?:\.\d{1,2})?$` to match a number which, if containing decimals, contains at maximum 2 decimal characters:
```
^-?(?=(?:\d\.?){1,8}$)\d*(?:\.\d{1,2})?$
```
<https://regex101.com/r/rQMRVX/5>
(unless you *need* to capture the decimal part, it can be a non-capturing group like above) | You can try this
```
^-?\d{1,8}.?\d{1,2}$
```
Link : <https://regex101.com/r/x7yw5M/2> |
141,677 | I tried installing ubuntu server alongside my windows 7 from a usb drive. After the partitioner level, the installation gives this:
warning: file:///cmrom/pool/main/c/coreutils/coreutils\_8.5-1ubuntu6\_amd64.deb was corrupted.
Should I download another server file? Or is there another way to solve this problem? Thanks in advance | 2012/05/24 | [
"https://askubuntu.com/questions/141677",
"https://askubuntu.com",
"https://askubuntu.com/users/65853/"
] | If you're having NVidia drivers and experiencing frequent crashes and frozen desktops, try to switch to propitiatory NVidia driver instead of open source one. | This may help. Open the GParted program and check if the you see an error message on one of the Ubuntu partitions.
I recently wiped my mac partitions and installed Ubuntu on my hard drive. I see that Ubuntu has created a small 977 KB partition which has the flag `bios_grub`.
I wonder if that is what is causing the system errors. Macs do not have a BIOS. |
5,803,999 | I am trying to silently install apk into the system.
My app is located in /system/app and successfully granted permission "android.permission.INSTALL\_PACKAGES"
However I can't find anywhere how to use this permission. I tried to copy files to /data/app and had no success. Also I tried using this code
```
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.parse("file:///sdcard/app.apk"),
"application/vnd.android.package-archive");
startActivity(intent);
```
But this code opens standard installation dialog. How can I install app silently without root with granted `android.permission.INSTALL_PACKAGES`?
PS I am writing an app that will install many apks from folder into the system on the first start (replace Setup Wizard). I need it to make firmware lighter.
If you think that I am writing a virus: All programs are installed into /data/app. Permission Install\_packages can only be granted to system-level programs located in /system/app or signed with the system key. So virus can't get there.
As said <http://www.mail-archive.com/android-porting@googlegroups.com/msg06281.html> apps CAN be silent installed if they have install\_packages permission. Moreover you don't need Install\_packages permission to install packages not silently. Plus <http://www.androidzoom.com/android_applications/tools/silent-installer_wgqi.html> | 2011/04/27 | [
"https://Stackoverflow.com/questions/5803999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/705297/"
] | I checked all the answers, the conclusion seems to be you must have root access to the device first to make it work.
But then I found these articles very useful. Since I'm making "company-owned" devices.
[How to Update Android App Silently Without User Interaction](https://www.sisik.eu/blog/android/dev-admin/update-app)
[Android Device Owner - Minimal App](https://www.sisik.eu/blog/android/dev-admin/set-dev-owner)
Here is google's the documentation about "managed-device"
[Fully managed device](https://developers.google.com/android/work/requirements/fully-managed-device) | I made a test app for silent installs, using PackageManager.installPackage method.
I get installPackage method through reflection, and made android.content.pm.IPackageInstallObserver interface in my src folder (because it's hidden in android.content.pm package).
When i run installPackage, i got SecurityException with string indication, that my app has no android.permission.INSTALL\_PACKAGES, but it defined in AndroidManifest.xml.
So, i think, it's not possible to use this method.
PS. I tested in on Android SDK 2.3 and 4.0. Maybe it will work with earlier versions. |
66,318 | I'm slowly working towards buying my first home (yay!), and have been playing around with the numbers. As far as I can tell, there's literally zero advantage for getting a 10 or 15-year mortgage since I can just get the exact same mortgage in a 30-year version, and just pay it off within whatever year window I choose.
So let's say I wanted to pay off my house in 10 years. If I get a 30-year mortgage and pay it off in 10 years then the same interest is paid as if I got a 10-year mortgage to begin with. Plus, if I get a 30-year mortgage then I have a cushion in case I run into major financial hardship.
Yet everywhere I look I see people online going on about how unwise 30-year mortgages are, as if they are irresponsible or something. Why is this? | 2016/06/19 | [
"https://money.stackexchange.com/questions/66318",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/-1/"
] | I haven't heard 30-year mortgages called unwise. As @jared said, the shorter terms often will be cheaper if you are going to pay off within that term anyway, but the extra cost of the 30 may still be justified because it gives you the "safety net" of being able to fall back to the lower payment if money gets tight. Cheap insurance if you might need that insurance.
That wasn't something I was worried about, so I took a 20-year, later refinanced as 15-year, and got a slightly better rate by doing so.
Consider how long you expect to own this house, and shop for the best deal you can find. Remember to figure points into the real cost the loan. There are calculators on many bank/credit-union websites that can help you do this comparison. | At this time there is one advantage of having a 30 year loan right now over a 15 year loan. The down side is you will be paying 1% higher interest rate.
So the question is can you beat 1% on the money you save every month.
So Lets say instead of going with 15 year mortgage I get a 30 and put the $200 monthly difference in lets say the DIA fund. Will I make more on that money than the interest I am losing? My answer is probably yes. Plus lets factor in inflation. If we have any high inflation for a few years in the middle of that 30 not only with the true value of what you owe go down but the interest you can make in the bank could be higher than the 4% you are paying for your 30 year loan.
Just a risk reward thing I think more people should consider. |
38,798,841 | I want to write a simple scan over an array. I have a `std::vector<int> data` and I want to find all array indices at which the elements are less than 9 and add them to a result vector. I can write this using a branch:
```
for (int i = 0; i < data.size(); ++i)
if (data[i] < 9)
r.push_back(i);
```
This gives the correct answer but I would like to compare it to a branchless version.
Using raw arrays - and assuming that `data` is an int array, `length` is the number of elements in it, and `r` is a result array with plenty of room - I can write something like:
```
int current_write_point = 0;
for (int i = 0; i < length; ++i){
r[current_write_point] = i;
current_write_point += (data[i] < 9);
}
```
How would I get similar behavior using a vector for `data`? | 2016/08/05 | [
"https://Stackoverflow.com/questions/38798841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1794469/"
] | ```
std::copy_if(std::begin(data), std::end(data), std::back_inserter(r));
``` | Well, you could just resize the vector beforehand and keep your algorithm:
```
// Resize the vector so you can index it normally
r.resize(length);
// Do your algorithm like before
int current_write_point = 0;
for (int i = 0; i < length; ++i){
r[current_write_point] = i;
current_write_point += (data[i] < 9);
}
// Afterwards, current_write_point can be used to shrink the vector, so
// there are no excess elements not written to
r.resize(current_write_point + 1);
```
---
If you wanted no **comparisons** though, you can use some bitwise and boolean operations with short-circuiting to determine that.
First, we know that all negative integers are less than 9. Secondly, if it is positive, we can use the bitmask to determine if an integer is in the range 0-15 (actually, we'll check if it's NOT in that range, so greater than 15). Then, we know that if the result of subtracion of 8 from that number is negative, then the result is less than 9:
Actually, I just figured a better way. Since we can easily determine if `x < 0`, we can just subtract `x` by 9 to determine if `x < 9`:
```
#include <iostream>
// Use bitwise operations to determine if x is negative
int n(int x) {
return x & (1 << 31);
}
int main() {
int current_write_point = 0;
for (int i = 0; i < length; ++i){
r[current_write_point] = i;
current_write_point += n(data[i] - 9);
}
}
``` |
1,896,096 | Morning all. I have the folowing problem:
```
$(document).ready(function(){
$("#actContentToGet").load(function(){
var htmlCODE = document.getElementById('actContentToGet').contentWindow.document.body;
var elements = [];
var z = 1;
function alterContent(htmlCODE){
$("#createdDivs").html("");
htmlCODE.$("*").each(function(){
alert("w");
if($(this).attr("rel")!="nbta"){
var style = '#div' + z + ' style: ' + 'display:block; width:' + $(this).outerWidth( true ) + 'px; height:' + $(this).outerHeight( true ) + 'px; position:absolute; top:' + $(this).position().top + 'px; left:' + $(this).position().left + 'px; cursor:pointer; z-index:' + $(this).parentNumber() + ';';
var newDiv = '<div name="maskBox" id="div' + z + '" class="' + $(this).attr("id") + '" style="display:none;"> </div>';
$("#createdDivs").append(newDiv);
$("#div" + z).attr("style", style);
z++;
}
});
}
});
});
```
im not sure how to go about this but i want to be able to use `$("*").each()` using the content from the iframe if you understand what i mean?
i used `htmlCODE.$("*").each(function(){` htmlCODE is undefined
any help much appreciated | 2009/12/13 | [
"https://Stackoverflow.com/questions/1896096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/201469/"
] | It looks like you're trying to do a join, so it would be:
```
var query = context.A_Collections.Join(
context.B_Collections,
a => a.PK,
b => b.PK,
(a, b) => new {
A_key = a.PK,
A_value = a.Value,
B_Key = b.PK,
B_value = b.value
});
```
EDIT: As Jon Skeet points out however, the actual translation done by the compiler will use SelectMany although using group will probably be more efficient. | Try using Resharper this will help you to convert all Linq queries in Linq Methods if you prefer that. |
1,627,422 | I am calling SSIS package from a .Net windows UI. Both SSIS & .Net app are created in 2008. The SSIS package is stored in file system. When I ran .Net app I got error:
>
> The package failed to load due to
> error 0xC0011008 "Error loading from
> XML. No further detailed error
> information can be specified for this
> problem because no Events object was
> passed where detailed error
> information can be stored.". This
> occurs when CPackage::LoadFromXML
> fails.
>
>
>
Exception Detail -
```
Microsoft.SqlServer.Dts.Runtime.DtsRuntimeException was unhandled
HelpLink="#-1073659847"
Message="The package failed to load due to error 0xC0011008 \"Error loading from XML. No further detailed error information can be specified for this problem because no Events object was passed where detailed error information can be stored.\". This occurs when CPackage::LoadFromXML fails.\r\n"
Source=""
ErrorCode=-1073672184
StackTrace:
at Microsoft.SqlServer.Dts.Runtime.Application.LoadPackage(String fileName, IDTSEvents events, Boolean loadNeutral)
at SSISCall.Form1.Execute_Click(Object sender, EventArgs e) in D:\SSISCall\SSISCall\Form1.cs:line 36
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at SSISCall.Program.Main() in D:\SSISCall\SSISCall\Program.cs:line 17
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.Runtime.InteropServices.COMException
HelpLink="#-1073659847"
Message="The package failed to load due to error 0xC0011008 \"Error loading from XML. No further detailed error information can be specified for this problem because no Events object was passed where detailed error information can be stored.\". This occurs when CPackage::LoadFromXML fails.\r\n"
Source=""
ErrorCode=-1073672184
StackTrace:
at Microsoft.SqlServer.Dts.Runtime.Wrapper.ApplicationClass.LoadPackage(String FileName, Boolean loadNeutral, IDTSEvents90 pEvents)
at Microsoft.SqlServer.Dts.Runtime.Application.LoadPackage(String fileName, IDTSEvents events, Boolean loadNeutral)
InnerException:
```
The code that I am using is very simple:
```
string packageLocation;
Package ssisPackage;
Microsoft.SqlServer.Dts.Runtime.
Application ssisApplication;
DTSExecResult ssisPackageResult;
packageLocation =@"D:\SSISCall\Package.dtsx";
ssisApplication =new Microsoft.SqlServer.Dts.Runtime.Application();
ssisPackage = ssisApplication.LoadPackage(packageLocation,null); ----Getting error here
ssisPackageResult = ssisPackage.Execute();
Console.WriteLine(ssisPackageResult.ToString());
Console.ReadKey();
```
**Please suggest.** | 2009/10/26 | [
"https://Stackoverflow.com/questions/1627422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/196914/"
] | Do you have SSIS components installed on the computer where you are executing this package? If not, it won't run - see <http://msdn.microsoft.com/en-us/library/ms403348.aspx>
Is the version of SSIS installed on the computer 2008? If not, it won't run - 2005 and 2008 parts are not interchangeable.
Is drive "D" a mapped drive? If so, your code probably won't run unattended (with a not-logged-in user session) - use UNC paths instead. | Getting exactly same error on the Lame loadPackage call.
This code was working fine for SQL 2005.
EnvDTE90 doesn't look like add any functionality to the DTS Application model.
Referencing both EnvDTE80 and EnvDTE90 doesn't make any differnece |
185,931 | Is it a good practice to implement event handling through WeakReference if that event is the only thing holding the reference and that we would need the object to be garbage collected?
As an argument to this:
Folks say that if you subscribe to something it’s your responsibility to unsubscribe and you should do it. | 2008/10/09 | [
"https://Stackoverflow.com/questions/185931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22039/"
] | Weak references in their own right, don't solve the problem as the delegate holds the reference. In the Composite Application Library which ships with Prism (www.microsoft.com/compositewpf) there is a WeakDelegate class that you could pull from the source. The WeakDelegate basically ues reflection and creates a delegate only for a moment in time and then releases it, thereby no holding any pointers. Within CAL it is used by the EventAggregator class, but you are free to rip it out for your own usage as it is under MS-PL. | While what you suggest solves one set of problems (event reference management and memory leak prevention), it is likely to open up a new set of problems.
One problem I can see is during event handling process if the source object is garbage collected (as it was only held with a weak reference), any code that access the source object will result in null reference exception. You can argue that the event handler should either not access the source object or it must have a strong reference, but it can be argued that this could be a worse problem than the one you are trying to solve in the first place. |
1,612,594 | $i + cj - 3k$ is a linear combination of $i + j$ and $j + 3k$.
How do I do this question, if it's not in vector form?
Should my approach be
$i + cj - 3k = a(i + j) + b(j + 3k)$? | 2016/01/14 | [
"https://math.stackexchange.com/questions/1612594",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/299748/"
] | Let $a \in (0,1)$.
For any $\epsilon > 0$, choose $N \in \mathbb{N}$ such that $1/N < \epsilon$.
There are only a finite number of rational numbers $r = p/q \in (0,1)$ in lowest terms with $q \leqslant N$. Indeed, $r \in S\_a =\{1/2, 1/3, 2/3, 1/4, 3/4, ..., (N-1)/N\}.$
Since $S\_a$ is finite we can choose $\delta$ such that $0 <\delta < \min\{|r - a|: r \in S\_a\, r \neq a\}$.
Consider any $x \in (0,1)$ with $ 0 < |x-a| < \delta$. If $x$ is irrational then $f(x)=0$ and $|f(x) - 0|= 0 < \epsilon.$
If $x$ is rational and $x = p/q$ in lowest terms, then $q > N$ and $|f(x) - 0| = 1/q < 1/N < \epsilon.$
Hence, $\lim\_{x \to a}f(x) = 0.$ | Hint: for $a \in (0, 1)$ and $1/a < n \in \Bbb{N}$, consider the interval $I = (a - 1/2n, a + 1/2n)$ (which has length $1/n$): how many rational numbers $p/q \in I$ (with $p$ and $q$ coprime) can have $q \le n$? |
40,183 | Did Kaori know that Arima loved her? From the letter she gave to Arima, she confessed everything and even gave that photograph, but at the same time, she told him to throw it away if he wanted to. This according to me suggests that she didn't know if Arima loved her. If she knew about Arima's feelings, she wouldn't have said it to him. Is there any strong evidence whether Kaori knew about Arima's feelings in the Manga/Anime? | 2017/05/04 | [
"https://anime.stackexchange.com/questions/40183",
"https://anime.stackexchange.com",
"https://anime.stackexchange.com/users/29779/"
] | This question eventually led me to a translation of the letter she had written for Arima.
Roughly translated, the ending part of the letter gives us an insight in what she knew and what she thought about Arima his feelings. She thought that he loved Tsubaki, or rather everyone knew that but apart from those 2. She, however, did love Arima. She factually said that at the end of the letter multiple times and asked him to remember her... if the letter reaches him. The way it was written indicates that she is "aware" about him loving someone else which means that he doesn't love her as a lover, in her eyes, but probably as a friend or musical partner.
Whether this thought from her is right or wrong is something I can't validate. If anything, I'd say that he loves her more than Tsubaki, but Tsubaki was most likely his first love though.
But to answer your question, according to the letter written by her, she was unaware about his feelings for her. As she wrote "I wonder if I made it into yours".
(It's been a while since I watched this one, watched it when it was airing)
Sources: finishing the anime and of course, [the translated version of the letter](http://miridesu.tumblr.com/post/110072094317/kaoris-letter-to-kousei-spoiler). | Towards the ending of the anime, we realize that Kaori's sole motivation in life was Kousei and the love she had for him. Everything she did, including using contacts, changing her hairstyle, "liking" Watari just so that she could get closer to Kousei, was all done in mind that she may not live to continue the ballad. Keeping all this in mind and noticing that she executed her plan quite successfully, we can conclude that Kaori was intelligent enough to know that Kousei loved her. Also there were moments when Kousei told her personally that he loved her, though worded a bit differently (like that scene where they saw the fireflies).
(I just finished watching the anime and the plot is freshly imprinted in my mind. This is my honest opinion and I am quite sure of it too) |
1,547,862 | The solution says $2x^{219}+3x^{74}+2x^{57}+3x^{44}=\_52x^3+3x^2+2x^1+3x^0$ but I don't see how they arrived at that, even with Fermat's theorem | 2015/11/26 | [
"https://math.stackexchange.com/questions/1547862",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/272288/"
] | $5$ is prime, thus by Fermat's theorem $a^4 \equiv 1 (\text{mod } 5)$ for all $a \in \mathbb{Z}\_5$, such that $a \neq 0$. Therefore you can reduce any power of $x$ to its remainder after the division by $4$.
For the first coefficient we have then
$$
2x^{219} = 2\cdot (x^4)^{54}\cdot x^3 = 2\cdot 1 \cdot x^3.
$$
And as pointed out by André Nicolas, solving the case $a = 0$ aside we can easily see, that it is also a root. | $\forall$ prime $P$, and $\forall$ $a\in \mathbb Z$, $a<P$, Fermat's theorem says that $a^{(P-1)} \equiv 1 (mod P)$ Here $5$ is Prime and hence each power can be reduced to a power less than $5$ because obviously the solution belongs to $\mathbb Z\_5$ |
7,044,065 | I have two tables that need to line up side by side. In order to achieve this I have to specify a `td` height.
In IE the height should be 2.1em. In Mozilla it needs to be 1.76em.
There does not appear to be a
`-moz-height:1.76em;`
Any idea how I can achieve my goal? | 2011/08/12 | [
"https://Stackoverflow.com/questions/7044065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/87796/"
] | You can put the IE height into a separate stylesheet and load it after the default one, using IE-conditional comments so the other browsers ignore it. Otherwise, you can use jQuery to change the height after it's loaded (if ($.browser.msie)) | Browser detect IE using IE's conditional comments and write out separate BODY tags:
```
<!--[if IE]><body class="ie"><!--<![endif]-->
<!--[if !IE]><!--><body><!--<![endif]-->
```
Then whenever you have a style, you can be more specific by adding the ie class to over-ride only IE:
```
.mystyle {styles for good browsers}
.ie .mystyle {styles for IE}
``` |
32,588,352 | I am using Spring(boot) on my project and I access a JMS Queue (ActiveMQ) using :
```
@JmsListener(destination = "mydestinationQueue")
public void processMessage(String content) {
//do something
}
```
And it works perfectly but I need to be able to stop/pause/start this bean programatically (a REST call or something like that)
When I stop or pause this bean I want to be sure to have fully processed the current message.
any idea about that ?
thanks | 2015/09/15 | [
"https://Stackoverflow.com/questions/32588352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3938606/"
] | Here is the solution I've found
```
@RestController
@RequestMapping("/jms")
public class JmsController {
@Autowired
ApplicationContext context;
@RequestMapping(value="/halt", method= RequestMethod.GET)
public @ResponseBody
String haltJmsListener() {
JmsListenerEndpointRegistry customRegistry =
context.getBean("jmsRegistry", JmsListenerEndpointRegistry.class);
customRegistry.stop();
return "Jms Listener Stopped";
}
@RequestMapping(value="/restart", method=RequestMethod.GET)
public @ResponseBody
String reStartJmsListener() {
JmsListenerEndpointRegistry customRegistry =
context.getBean("jmsRegistry", JmsListenerEndpointRegistry.class);
customRegistry.start();
return "Jms Listener restarted";
}
@RequestMapping(value="/stopApp", method=RequestMethod.GET)
public @ResponseBody
String stopApp() {
String[] args={};
SpringApplication.run(FacturationApplicationFrontDaemon.class, args).close();
return "stopped";
}
}
``` | There's a bean of type `JmsListenerEndpointRegistry` (name `org.springframework.jms.config.internalJmsListenerEndpointRegistry`).
You can access the JMS listener containers from the registry (all or by name) and call `stop()` on the one(s) you want; the container will stop after any in-process messages complete their processing. |
24,122,149 | ```
Decimal money = 7;
var result=money.Tostring("C);
```
result displays $7.00
How can i show result as **"7.00"**( with 2 numerics after point) without currency symbol? | 2014/06/09 | [
"https://Stackoverflow.com/questions/24122149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3713890/"
] | [`"C"` Format Specifier](http://msdn.microsoft.com/en-us/library/dwhawy9k%28v=vs.110%29.aspx#CFormatString) is for currency representation of numbers. It uses your `CurrentCulture`'s [`CurrencySymbol`](http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.currencysymbol%28v=vs.110%29.aspx) and [`CurrencyDecimalSeparator`](http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.currencydecimalseparator%28v=vs.110%29.aspx) properties as a result. (If you don't use `IFormatProvider` as a second parameter, of course..)
You can use `N2` format insead. Like;
```
decimal money = 7;
money.ToString("N2").Dump(); //7.00
```
or
```
Console.WriteLine(money.ToString("N2"));
```
Read:
* [`"N"` Format Specifier](http://msdn.microsoft.com/en-us/library/dwhawy9k%28v=vs.110%29.aspx#NFormatString)
>
> **Result: Integral and decimal digits**, group separators, **and a decimal
> separator** with optional negative sign.
>
>
> Supported by: All numeric types.
>
>
> **Precision specifier: Desired number of decimal places.**
>
>
> | Try this :
```
var result = money.ToString("f");
``` |
38,548,314 | I have tried searching, but I am stuck.
Basically I am making a jeopardy game board; which I created using a table. I would like to change the background-color of the td after it has been clicked on. The challenge I am facing is that (1) I am using a link to direct to the question/answer (yes, I know this could be done other ways, but I need to learn more to advance and I am working on that); (2) After searching for answers, I can't seem to get it to work with the code I have.
Here is my [JSFiddle]<https://jsfiddle.net/hLyauL5a/>)
```
Html:
<table>
<thead>
<tr>
<th>Stuff</th>
<th>Stuff </th>
<th>Stuff</th>
<th>Stuff</th>
<th>Stuff</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="question1.html" id="value">100</a></td>
<td><a href="question2.html" id="value">100</a></td>
<td><a href="question3.html" id="value">100</a></td>
<td><a href="question4.html" id="value">100</a></td>
<td><a href="question5.html" id="value">100</a></td>
</tr>
<tr>
<td><a href="question6.html" id="value">200</a></td>
<td><a href="question7.html" id="value">200</a></td>
<td><a href="question8.html" id="value">200</a></td>
<td><a href="question9.html" id="value">200</a></td>
<td><a href="question10.html" id="value">200</a></td>
</tr>
<tr>
<td><a href="question11.html" id="value">300</a></td>
<td><a href="question12.html" id="value">300</a></td>
<td><a href="question13.html" id="value">300</a></td>
<td><a href="question14.html" id="value">300</a></td>
<td><a href="question15.html" id="value">300</a></td>
</tr>
<tr>
<td><a href="question16.html" id="value">400</a></td>
<td><a href="question17.html" id="value">400</a></td>
<td><a href="question18.html" id="value">400</a></td>
<td><a href="question19.html" id="value">400</a></td>
<td><a href="question20.html" id="value">400</a></td>
</tr>
<tr>
<td><a href="question21.html" id="value">500</a></td>
<td><a href="question22.html" id="value">500</a></td>
<td><a href="question23.html" id="value">500</a></td>
<td><a href="question24.html" id="value">500</a></td>
<td><a href="question25.html" id="value">500</a></td>
</tr>
</tbody>
</table>
CSS:
jQuery code:
$("table tr td").click(function() {
$(this).css("background", "#626975");
});
```
I would appreciate any help! | 2016/07/24 | [
"https://Stackoverflow.com/questions/38548314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6308715/"
] | ```
$('a').click(function(e){
e.preventDefault();
$(this).parent().css('background-color','blue');
});
```
So,using JQuery, if you click on an tag, don't jump on whatever link it is, you prevent the default event, then you get its parent which is the element and you add the css style as shown. Here is the html that I used as an example:
```html
<table>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td ><a href="/link">Table</a></td>
<td bgcolor="#00FF00">$100</td>
</tr>
``` | Generally, a hyperlinks like `<a herf="" onclick="">`contain two events: onclick and herf. The order of execution --- 'onclick' in front of 'herf'. so making onclick method return 'false' if you want to page can't jump on whatever link it is when you click hyperlink. Code is as follows.
```js
$(function(){
$("a").on("click",function(){
$(this).css("background", "#626975");
return false;
});
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Stuff</th>
<th>Stuff</th>
<th>Stuff</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="question1.html" id="value">100</a></td>
<td><a href="question2.html" id="value">100</a></td>
<td><a href="question3.html" id="value">100</a></td>
</tr>
</tbody>
</table>
``` |
569,118 | My Bibliography is arranged like in the example beneath. So the equal initial letters are merged together (without extra line in between). How I'm able to have an extra line in any cases?
```
Kieviet, André (Lean Digital Transformation, 2019): Lean Digital Transformation: Ge schäftsmodelle transformieren, Kundenmehrwerte steigern und Effizienz erhöhen, Wies baden, 2019
Prof. Dr. Bonin, Holer, Dr. Gregory, Terry, Dr. Zierahn, Ulrich (Übertragung auf Deutsch land, 2015): Übertragung der Studie von FreyOsborne 2013 auf Deutschland, in: Kurz expertise (2015), Nr. 57
Prof. Dr. Kagermann, Henning, Prof. Dr. Wahlster, Wolfgang, Dr. Helbig, Johannes, M.A. Hellinger, Ariane, M.A. Stumpf, Veronika (Digitalisierung Industrie, 2013): Di gitalisierung der Industrie – Die Plattform Industrie 4.0, Frankfurt am Main, 2013
Rische, MarieChristin, Vöpel, Henning (Digitalökonomie, 2016): Schwerpunkt Kreative Zerstörung 4.0 Die Neuvermessung der Welt Grundprinzipien und Konsequenzen der Digitalökonomie, in: Wirtschaftspolitische Blätter (2016), Nr. 2
```
---
```
\usepackage[
backend=biber,
style=ext-authoryear,
maxcitenames=3,
maxbibnames=999,
mergedate=false,
date=iso,
seconds=true,
urldate=iso,
innamebeforetitle,
dashed=false,
autocite=footnote,
doi=false,
useprefix=true,
mincrossrefs = 1
]{biblatex}
\input{modBib}
...
\printbibliography[nottype=online,heading=bibintoc,title={Literaturverzeichnis}]
``` | 2020/10/31 | [
"https://tex.stackexchange.com/questions/569118",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/134693/"
] | `biblatex` has three parameters to adjust the spacing *between* entries (§3.11.4 *Lengths and Counters*, p. 131, v3.15a of [the `biblatex` documentation](http://mirrors.ctan.org/macros/latex/contrib/biblatex/doc/biblatex.pdf)).
* `\bibitemsep` is the space inserted between individual entries.
* `\bibnamesep` is the space inserted between entries by different authors/editors.
* `\bibinitsep` is the space inserted between entries with different initial letter of the authors/editors.
Note that if several of those spaces would apply between two entries, the largest space wins. The spaces are not added.
The result you describe in the question looks like the result of setting `\bibinitsep` to a non-zero value, e.g.
```
\documentclass[british]{article}
\usepackage[T1]{fontenc}
\usepackage{babel}
\usepackage{csquotes}
\usepackage[backend=biber, style=authoryear]{biblatex}
\setlength{\bibinitsep}{2\itemsep}
\addbibresource{biblatex-examples.bib}
\begin{document}
Lorem \autocite{sigfridsson,nussbaum,knuth:ct:a,
knuth:ct:b,kastenholz,aksin,herrmann}
\printbibliography
\end{document}
```
[](https://i.stack.imgur.com/jwBhF.png)
You can change this by setting `\bibnamesep` to 0. If you want more space between all entries, set `\bibitemsep` to a larger value. | Thanks a lot moewe, you nailed it. It works fine with \bibitemsep instead of \bibinitsep, if this will help someone, someday I set: \setlength{\bibitemsep}{0.75cm}. Also thanks for the hint about academic titles, I will double check this one. |
20,466,718 | I am a beginner for android platform.. I'm using dropbox for android api to download all the images from the users dropbox account to the loacal device. I have followed the demo application provided by dropbox and I got the way how to download the images. but now i want to get all the images from dropbox and priview in my application. can anybody help to acheve this. | 2013/12/09 | [
"https://Stackoverflow.com/questions/20466718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | `function()` is a.. method. Consider this:
```
private boolean function() {
/* block of code */
return true;
}
```
When you reach the `if` statement, `function()` is called. Meaning that the *block of code* was executed. Then, `function()` returns *true*.
Now, you entered the `if` block, there.. you execute `function()` again.. Meaning that *block of code* will be executed again.
Usually, when you have a method that returns a `boolean` and do something, you assign the result to a variable:
```
boolean result = function();
```
And then you can ask whatever you want on `result` to see the output of the method (Usually `true` indicates successful run, `false` indicates that something went wrong). | The `method` is called twice (provided it returns true on the first run), and whatever changes that `method` makes are permanent unless you explicitly reverse them somehow. |
63,654,874 | TEXT FILE IM READING
```
1 1 1
1.2 -2.3 0.4
-2 -3 -4
+0 -2 8.85
2.345
```
My code:
```cpp
#include <iostream>
#include <fstream>
using namespace std;
double readFile(ifstream &myfile, double &a, double &b, double &c);
int main()
{
int counter = 0;
double a, b, c;
string line, inputFile, outputFile;
cout << "Enter the name of your input file: ";
cin >> inputFile;
cout << "Enter the name of your output file: ";
cin >> outputFile;
ifstream myfile(inputFile);
if(myfile.is_open())
{
while(!myfile.eof())
{
readFile(myfile, a, b, c, counter);
calculations(a, b, c);
}
}
else cout << "unable to open file";
return 0;
}
double readFile(ifstream &myfile, double &a, double &b, double &c)
{
//Reads one line of the file
myfile >> a >> b >> c;
cout << a << " " << b << " " << c << endl;
}
```
What i want to do is that if the last line does not have 3 values i want to have some sort of stop code where it stops the processing if it has less than 3 values and the leftovers values from the previous line wont be assigned | 2020/08/30 | [
"https://Stackoverflow.com/questions/63654874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10487269/"
] | Your biggest issue is that `>>` skips leading whitespace, so it doesn't differentiate between a `' '` (space) or `'\n'` -- it's just whitespace. To handle it correctly, you need to read each line into a `std::string` and then create a `std::stringstream` from the line.
Then read your three `double` values from the `std::stringstream` with `>>`. That way you can read no more `double` values than are present in the line. Otherwise if you just try and use `>>`, you will happily read 2 `double` values from one line and the third from the next without any indication of that happening.
You next need your function to indicate success/failure of reading the three `double` values from the line. A return type of `bool` is all you need. If you read three valid `double` values, return `true` and do your `calculations()` otherwise, if you return `false`, stop trying to read from the file.
A short example would be:
```
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
bool read3doubles (std::ifstream& f, double& a, double& b, double& c)
{
std::string line {}; /* std::string to hold line */
if (getline (f, line)) { /* if line read from file */
std::stringstream ss(line); /* create stringstream from line */
if (ss >> a >> b >> c) /* if 3 doubles read from line */
return true; /* return true */
}
return false; /* otherwise, return false */
}
void calculations (double& a, double& b, double& c)
{
std::cout << a << " " << b << " " << c << '\n';
}
int main (int argc, char **argv) {
if (argc < 2) { /* validate at least 1 argument given */
std::cerr << "error: insufficient number of arguments.\n"
"usage: " << argv[0] << " <filename>\n";
return 1;
}
std::ifstream f (argv[1]); /* open file-stream with 1st argument */
double a, b, c;
if (!f.good()) { /* validate file open for reading */
std::cerr << "errro: file open failed '" << argv[1] << "'.\n";
return 1;
}
while (read3doubles(f, a, b, c)) /* while 3 doubles read from file */
calculations (a, b, c); /* do your calculation */
}
```
(**note:** the `calculations()` function just outputs the three doubles when successfully read)
**Example Use/Output**
Using your input in the file `dat/3doubles.txt`, you would have:
```
$ ./bin/read3doubles dat/3doubles.txt
1 1 1
1.2 -2.3 0.4
-2 -3 -4
0 -2 8.85
```
Let me know if you have further questions. | I added a different function that chops a line by space and converts them to numbers. Your main function remains largely unaffected. Though I made some changed like adding a `std::vector`, early return to remove some nesting.
Also, I changed the main `while` condition from `eof` to `std::getline`.
* Operations on `std::string_view` are very cheap.
* This way you can check on *every line* that the number of values read is always what you need.
* For bad input, you can easily debug if a line/ word is not number by printing it in the exception catcher.
```
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
void read_values(std::string_view line, std::vector<double> &values);
void calculations(int, int, int);
int main()
{
string inputFile, outputFile;
cout << "Enter the name of your input file: ";
cin >> inputFile;
cout << "Enter the name of your output file: ";
cin >> outputFile;
ifstream myfile(inputFile);
if (!myfile.is_open()) {
cout << "unable to open file";
return -1;
}
std::string line;
std::vector<double> values;
while (std::getline(myfile, line, '\n')) {
read_values(line, values);
std::cout << values.size();
}
return 0;
}
void read_values(std::string_view line, std::vector<double> &values)
{
while (!line.empty()) {
const std::string_view::size_type pos_space{line.find(' ')};
try {
values.push_back(std::stod(std::string(line.substr(0, pos_space))));
}
catch (const std::invalid_argument &ex) {
std::cout << ex.what() << std::endl;
return;
}
line.remove_prefix(pos_space + 1);
}
}
``` |
29,071,337 | I have scanned my project with the help of sonar runner and sonar qube, but in the results i am not able to see the coverage details and test cases details. can any one tell me the process for code coverage with sonar for a non maven project.
Thanks in advance | 2015/03/16 | [
"https://Stackoverflow.com/questions/29071337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3588496/"
] | Use this :-
```
<a href="https://www.facebook.com/sharer/sharer.php?u=<?php echo $_SERVER['REQUEST_URI']; ?>">Share on Facebook</a> <br>
``` | I'm assuming client only solution is needed here, server can be anything (PHP, ASP, etc.)
All you've to do is to modify the href property of anchor tag. You can modify your code as -
```
var elm = document.getElementById("demo");
var URLBase = elm.getAttribute("href");
var fullURL = URLBase.window.location.host;
elm.setAttribute("href", fullURL);
``` |
54,952,754 | I'm adding some optional functionality to an existing project that uses npm and webpack. This functionality makes use of a rather large module (tfjs to be exact), and I'd like to prevent loading it by default, since it approximately doubles the application's payload. Ideally, I'd be able to import it dynamically for users who navigate to this functionality.
Anyway, I'm the first to admit I'm totally out of my depth here. I'm not very well versed in webpack in particular. So my question is:
What is a general strategy for dynamically loading an npm module dependency?
I've looked at code splitting - this seems to only work for sources and not dependencies. I'm considering creating a subdirectory with a separate package.json and node\_modules/ and exporting them as static resources. | 2019/03/01 | [
"https://Stackoverflow.com/questions/54952754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2859006/"
] | You could take a funky [destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) by taking the object with key zero (just the first element of the array) and then the `value` property.
```js
var array = [{ label: "1", value: "11" }, { label: "2", value: "22" }, { label: "3", value: "33" }, { label: "4", value: "44" }],
{ 0: { value } } = array;
console.log(value);
``` | Use
```js
var array = [{label:"1",value:"11"},
{label:"2",value:"22"},
{label:"3",value:"33"},
{label:"4",value:"44"},
];
console.log(array[0].value);
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.