INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Wireguard or TLS for encrypting database connection?
I need to secure/encrypt exchanged data between app and database and I've thought on:
1. SSL/TLS
2. VPN (Wireguard)
What option do you suggest for PROD env?
|
It depends on what do you want to protect. For protecting all communication between two machines use a VPN like Wireguard. For protecting the communication of a single service use TLS.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "database, ssl, vpn, wireguard"
}
|
Inserting new line under \exists in math mode
> **Possible Duplicate:**
> Separate long math text under sum symbol into different lines?
Minimal example of my document. I'm using redesigned `exists`.
\documentclass{article}
\usepackage{amsfonts}
\usepackage{amsmath}
\let\stdexists\exists
\renewcommand{\exists}{\mathop{\vphantom{\sum}\mathchoice
{\vcenter{\hbox{\huge$\stdexists$}}}
{\vcenter{\hbox{\Large$\stdexists$}}}{\stdexists}{\stdexists}}\displaylimits}
\begin{document}
\begin{equation}
\exists_{j\in S j\neq i}\exists_{n \in \mathbb{N}} {p_{ij}}^{(n)}>0
\end{equation}
\end{document}
This code gives an output:
}>0
\end{equation}
\end{document}
|
stackexchange-tex
|
{
"answer_score": 6,
"question_score": 1,
"tags": "math mode, equations, amsmath"
}
|
Reading float value from string upto 6 precision
i have to read a flot value from string up to 6 precision , Current code is reading first 6 digits only. Thanks in Advance
template <class T>
bool from_string(T& t, const std::string& s,
std::ios_base& (*f)(std::ios_base&))
{
std::istringstream iss(s);
return !(iss >> f >> t).fail();
}
int main()
{
int i;
float f;
// the third parameter of from_string() should be
// one of std::hex, std::dec or std::oct
if(from_string<int>(i, std::string("ff"), std::hex))
{
std::cout << i << std::endl;
}
else
{
std::cout << "from_string failed" << std::endl;
}
if(from_string<float>(f, std::string("1456.909"), std::dec))
{
std::cout << f << std::endl;
}
else
{
std::cout << "from_string failed" << std::endl;
}
return 0;
}
|
I'm quite certain it's reading all digits. The problem appears to be in what you expect. Let's put it a bit stronger: What would you expect to happen if you read `1456.90900000000000000000000000000` in a `float`?
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "c++, string, floating point"
}
|
why i am not able to edit or create system variables in windows?
I was trying to set the GRADLE_HOME system variable for my system as per this video in youtube. I am admin user and only user in my system.
enter image description here
This image is screenshot from my desktop. As you can see that **I am not able to create or edit the system variable**.
can somebody tell me how to solve this problem?
|
Press the windows key and type env, the first result should be "Edit the system environment variables". Clicking on that should bring you straight to "System Properties" where you can click on "Environment Variables..." in the bottom right corner. There you should be able to change system variables.
Or you can run regedit and the variables are in Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "environment variables, system variable"
}
|
emacs: how to set the default database type for a sql file in SQL mode
In SQL mode, we could select the product type such posgres, mysql, oracle etc, and the default one is ANSI, how to set the default type as postgresql after startup emacs? What needs to be put in .emacs?
|
SQL mode has `sql-set-product` function which is used to set the product.
`C-h f sql-set-product RET` lists the details of the function.
>
> sql-set-product is an interactive compiled Lisp function.
>
> (sql-set-product PRODUCT)
>
> Set `sql-product' to PRODUCT and enable appropriate highlighting.
>
So, you can add
(sql-set-product 'postgres)
to your .emacs file to make it as default.
At any point of time, if you want to change it mysql or something else, you can use
M-x sql-set-product RET mysql RET
Alternatively, as shown in @teaforthecat's answer, the product can be set from a comment on the first line
-- -*- mode: sql; sql-product: mysql; -*-
|
stackexchange-stackoverflow
|
{
"answer_score": 12,
"question_score": 8,
"tags": "emacs, elisp, dot emacs"
}
|
Online Database instead of wamp
Ok so I created an Android app with use of WAMP. Is there any way to put it online in a cloud or website or do I have to rent a server? I have been looking all over the place for that but I still did not manage to answer that question.
Can you guys help me ?
Thanks
|
I'm a little puzzled by your question. You have an app and you need a server for it? Yes, you _can_ rent a server, or buy one, but I wouldn't suggest that. The most popular way to host databases nowadays is using Cloud Computing. You should probably look into Amazon AWS. Many people use EC2.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "android, wamp"
}
|
Mod-rewrite rule for external pages?
Is it possible use mod_rewrite to resolve addresses hosted on another server?
Say I want to setup this URL:
To actually resolve to:
If so, could you provide a RewriteRule example?
|
You can use the _P_ flag in a mod_rewrite rule to get that substitution URL requested by mod_proxy:
RewriteEngine on
RewriteRule ^myfolder/$ [P]
Now when a client is requesting `/myfolder/` from your server, it will request ` and send the response from that server back to the client.
|
stackexchange-stackoverflow
|
{
"answer_score": 20,
"question_score": 11,
"tags": "mod rewrite, cross domain"
}
|
Is there an option to use postprocessor in nesting translations in i18next?
I use i18next for localization. I am using a postprocessor that applies custom format. I have recently noticed that in nested translations this postprocessor is not applied. Is there something I can do to have it applied in nested translations?
|
I've debugged the code of i18next, and found out that for nested translations post-processors are disabled by default.
You can enable this flag inside the translation:
// translations.json
nested: "You have $t(files, {'N': 10, 'applyPostProcessor': true})"
// ------------------------------------------^
A working example :]
<
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "i18next, react i18next"
}
|
Remove all lines in single file NOT matching keywords aligned in first column
I need to extract a series of lines identified by a keyword in the first column and print them in the same linear order.
The file is divided into sections delimited by a line of hyphens or equal signs and contain a keyword line (possibly followed by a paragraph), there are several keywords, but I only need to extract these:
Date:
Name:
Contact:
RefID:
Status:
Thank you for your suggestions.
|
Try this: `grep -e "^Name.*" -e "^Date.*"` and so on
|
stackexchange-unix
|
{
"answer_score": 0,
"question_score": 0,
"tags": "text processing, grep, sort, emacs, printf"
}
|
Someone posting to /wp-login.php every 2 minutes. Is it commonly happens?
When I check my nginx access.log there are requests (GET request followed by POST) every two minutes on /wp-login.php.
Then I log those POST requests (changing login page to empty page and save POST requests to file). The request contains login credentials, with correct username and wrong password. Those requests didn't stop even the response is empty page (may be a script).
Then, I deny that ip address on nginx config. In the next day, the same happens with different IP (but same country).
What bugging me is how that _client_ knows my admin username? Is it common for wordpress site to be like that? Because it's my first time to have wordpress write on real server.
|
As those in the comments have stated, it is common. Likely those ips originate from the Western countries. Most of these insophisticated brute force attacks can be credited to bots or a botnet simply automated for trying known user names like admin, root, guest and their counterpart passwords.
A few methods you can implement to protect yourself is using fail2ban and configuring it to filter http traffic. Use ipset to blacklist those ips. It can always help if you report those ips to abuseipdb to let others know of misdoings. Htaccess and htpasswd are good files to keep unwanted visitors from certain files/ directories. And if you feel like you want more protection, you can sign up for cloudflare. And as you are doing right now, Always keep an eye on those access logs.
|
stackexchange-serverfault
|
{
"answer_score": 2,
"question_score": 2,
"tags": "wordpress, brute force attacks"
}
|
How to get key values from JsonObj
I have a `json` object like this actually it is coming dynamically. For example we can use this Json object.
var JsonObj= { "one":1, "two":2, "three":3, "four":4, "five":5 };
But i want to change it some thing like this using `javascript` or `jquery`.
var sample = [
{
"label":"one",
"value":1
},
{
"label":"two",
"value":2
},
{
"label":"three",
"value":3
},
{
"label":"four",
"value":4
},
{
"label":"five",
"value":5
}
];
|
var JsonObj= { "one":1, "two":2, "three":3, "four":4, "five":5 };
var arr = [];
for(property in JsonObj) {
arr.push(
{"label":property,
"value":JsonObj[property]})
};
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 3,
"tags": "javascript, jquery, json"
}
|
Term for a specific hand motion?
Is there a term describing the motion Mel Brooks makes with his hand here in a scene from Robin Hood - Men in Tights.
!hand waggle
|
He's fluttering his hand, which is usually interpreted as uncertainty. Maybe yes, maybe, no, but probably no. Wavering in regard to a decision.
Flutter: to move with quick, wavering or flapping motions. Webster's New Collegiate.
|
stackexchange-english
|
{
"answer_score": 1,
"question_score": 1,
"tags": "single word requests"
}
|
Practical limit on groups in AD?
Our company is trying to rethink our approach to managing permissions among employees for access to project files in our domain. We're considering creating a new AD Group for each office project and then adding users to the groups as employees work on projects. (Right now, user accounts are individually added or removed from relevant project folders by a script when they join or leave a project.)
The concern is that we have ~300 new projects a year, so there would potentially be thousands of these groups. Also, users may work on many projects over the years, so each user would potentially be a member of hundreds of groups.
Are either of those numbers a concern? We don't want to create a situation that causes the domain controller to struggle or push the limits of AD.
|
You don't really define your replication topology, which can come into play here. Assuming you have a single site with all DCs in the same LAN, replication won't be your issue. Simply having thousands of groups normally isn't a problem, unless you have severe restrictions on replication (like you do it across the country over two soup cans and a piece of string).
The problem that you may face is that a user's access token can only contain 1024 SIDs. Once the user is a member of about 1000 groups, some SIDs can't be added to the token, which will cause an access failure when trying to use a resource that requires that token.
In short, if you have a user being a member of 1,000 groups you'll have problems. If not, you're fine.
This TechNet article covers the problem pretty well and this Microsoft document explains it in depth (warning: word document direct link).
|
stackexchange-serverfault
|
{
"answer_score": 8,
"question_score": 5,
"tags": "active directory"
}
|
Нумерация изображений и других объектов по главам, ("Рисунок 1.1" в главе 1, "Рисунок 2.1" в главе 2) в LibreOffice Writer
Оформляю диплом. Есть требование к нумерации рисунков как указано в заголовке вопроса. Пример:
> ## Глава 1
>
> Бла-бла-бла на рисунке 1.1
> [рисунок]
> _Рисунок 1.1: Бла-бла-бла_
>
> Бла-бла-бла на рисунке 1.2
> [рисунок]
> _Рисунок 1.2: Бла-бла-бла_
>
> ## Глава 2
>
> Бла-бла-бла на рисунке 2.1
> [рисунок]
> _Рисунок 2.1: Бла-бла-бла_
Сейчас у меня нумерация рисунков сквозная по всему документу, то есть подписи просто "Рисунок 1", "Рисунок 2" и т.д.
В тексте ссылки на рисунки тоже хочется автоматические, а не писать руками.
Как добиться форматирования как в примере?
_P.S. Знаю что вопрос не совсем по теме этого сайта. Буду благодарен, если кто-нибудь подскажет куда правильнее обратиться._
|
Это не сложно. Вставляете рисунок, щёлкаете правой кнопкой и выбираете из меню "Вставить название" (обычно это предпоследний пункт контекстного меню). Или выбираете пункт **Название** из меню Вставка (активируется, если выделен графический объект, в т.ч. рисунок)

**Update:** See follow up question
|
You do not need any outside software, just use this document to show you how to configure it natively:
< (read the section "Configuring the Windows Time service to use an external time source")
|
stackexchange-superuser
|
{
"answer_score": 2,
"question_score": 0,
"tags": "windows server 2008, ntp"
}
|
web2py application logging
What is the recommended way to log application-specific messages in web2py? I found the documentation on HTTP logging, but I'm thinking more of messages for debugging and tracking.
Should I simply use the logging module in each separate controller file? Is there a central place in which I could initialize a logger that can be shared between controllers? Or, is something built-in to web2py that I should use?
Update: It looks like I can't even fully use the logging module in web2py. It looks like web2py ships with it's own version of the python libraries (in library.zip), which I'm not a big fan of. Is that by design? I'm guessing there will be issues with simply adding my installed Python libraries to the sys.path at run-time, so what should I do?
|
<
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 6,
"tags": "logging, web2py"
}
|
Helidon background task
I have a **@ApplicationScoped** bean in my Helidon MP microservice, is there a way to force the creation of the bean at server startup instead at first method call?
I need this bean ready and running just after server startup but every attempt I made it's inconclusive
|
I found a way to solve it. If your bean observes the initialization of `ApplicationScoped` it will be instantiated during startup phase. It's a trick but it works fine.
public void init(@Observes @Initialized(ApplicationScoped.class) Object init) {
}
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "java, helidon"
}
|
glOrtho equivalent to VBO's
I am trying to port a `ClickTeam Fusion` game to `Java` using `LWJGL`. I decided to simply use pixel measurements as everything in this game is done using `PNG` files, even animations (Yes, really). And I have heard of the function called `glOrtho()` which is supposed to let you set how things are drawn in `OpenGL`.
While I managed to get this working with functions like `glVertexf()`, those functions including `glOrtho()` are deprecated and if I am correct completely removed in `OpenGL 3.1`. So, I am using the modern way of doing it which is using `VBO's, Indices, Shaders`, etc. Is there any way to accomplish `glOrtho()`'s effect using a `VBO`?
If you need me to, I can upload the current code I have here as well; just leave a comment and I will update the post with the current code I have.
|
For OpenGL >= 3.1 you need to define your own matrices. There are some libs that defined them for you. GLM, to name a famous one.
glOrtho matrix defintion can be found here: <
glOrtho is not an "effect", but a way to project things onto the screen. Ortho refers to "orthogonal", which means "no perspective".
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "java, opengl, lwjgl"
}
|
Question about $\xi(x)$ in Taylor remainder term
I am studying numerical analysis in Burden & Faires book. The Taylor remainder term is written as $$R_{n}(x)=\frac{f^{(n+1)}(\xi(x))}{(n+1) !}\left(x-x_{0}\right)^{n+1}$$
The book states that "$\xi(x)$ is some (generally unknown) number between 0 and x." In examples, when $x = .01$, the book uses this term to set some bounds. For example, "$0 \leq \xi < .01$" and "$0 < \xi(x) < .01$" These different usages are confusing me.
My question is: What are the appropriate bounds for $\xi(x)$ in the Taylor remainder term? Are they less than signs, or less than or equal to signs? And in the last example, shouldn't it be $\xi(.01)$ instead of $\xi(x)$?
|
The point $ξ=ξ(x)$ is obtained via application of the mean value theorem. This means that it will be an interior point of the interval.
In computing the bounds of the derivative, it makes generally no difference if one takes the supremum over the open interval or the maximum over the closed interval.
And yes, if you fix $x=0.01$, then you can use both interchangeably, it is a question of emphasis which one is used.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "calculus, numerical methods, taylor expansion"
}
|
If $\sin x+\cos x=1+\sin x\cos x,$ then which of the following is/are correct?
> If $\sin x+\cos x=1+\sin x\cos x,$ then which of the following is/are correct?
> A) $\sin(x+\frac\pi4)=\frac1{\sqrt2}$
> B) $\sin(x-\frac\pi4)=\frac1{\sqrt2}$
> C) $\cos(x+\frac\pi4)=\frac1{\sqrt2}$
> D) $\cos(x-\frac\pi4)=\frac1{\sqrt2}$
**My Attempt:**
Squaring both sides, $$1+2\sin x\cos x=1+\sin^2x\cos^2x+2\sin x\cos x\\\\\implies\sin x\cos x=0\\\\\implies\sin2x=0\implies x=n\frac\pi2,n\in I$$
Thus, I am not able to match with any of the options.
Answer given is A, D.
|
Rearranging the equation without doing anything complicated gives us:
$sin(x)$ $[$ $1-cos(x)$ $]$ $=$ $[$ $1-cos(x)$ $]$
This is only true when one of the following statements hold:
* $sin(x)= 1$ and $cos(x)$ is unrestricted
* $cos(x) =1$ and $sin(x)$ is unrestricted
Now we can find values of $x$ that allow the original equation to hold. And from here, we can substitute in these values in order to test the statements that you have provided.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "trigonometry"
}
|
Inheritance - UIAlertView in superclass and subclass
I have a superclass where I sometimes show an UIAlertView and handles the delegation (clickedButtonAtIndex). When I then have a subclass that also handles the "clickedButtonAtIndex" only the subclass delegation is called.
In both cases the UIAlertView is show like this:
[[[UIAlertView alloc] initWithTitle:@"" message:@"message" delegate:self cancelButtonTitle:@"Close" otherButtonTitles:@"Open", nil]show];
Am I doing something wrong or is it bad design to have the same delegation in both the superclass and subclass. I thought the "delegate:self" separated them.
I can see in the debugger that "self" references to my subclass even though I'm in my superclass so this is probably the problem? Any thoughts?
|
I was kind of surprised that 'self' references to the subclass when called in a superclass.
Thus I decided to create my own delegation for the UIAlertView to distinguish from the subclass' delegation. This because I dont think: \- That the subclasses should know about my private UIAlertView in the superclass and call it. \- That the superclass should know about my subclasses delegation.
Feel free to add you thoughts :-)
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "ios, objective c, inheritance, delegates, uialertview"
}
|
Finding all triplets of positive integers with certain property
Fix a $k \in \mathbb{N}$
> * How do I find all sets of positive integers $a_{1},a_{2},...,a_{k}$ such that the sum of any triplet is divisible by each member of the triplet.
>
I couldn't see any pattern. But the simplest example which I could see is the set $\\{1,2,3\\}$. This satisfies the hypothesis. And even sets like $\\{2,4,6\\}$ does satisfy.
In search of finding a solution I attempted the following: Let $\\{a_{1},a_{2},a_{3}\\}$ be a triplet. Then by our hypothesis we should have $$a_{1}\mid (a_{1}+a_{2}+a_{3}), \quad a_{2} \mid (a_{1}+a_{2}+a_{3}) \quad a_{3}\mid (a_{1}+a_{2}+a_{3})$$ Using all this I arrive at $$k_{1}a_{1} = k_{2}a_{2} = k_{3}a_{3}$$ But all this doesn't seem to help.
|
If $a_1\lt a_2\lt a_3$, their sum $S$ satisfies $a_3\lt S\lt 3a_3$. Since $a_3\mid S$, this implies $S=2a_3$, thus $a_1+a_2=a_3$ and thus $a_2\gt a_3/2$. The only divisor of $2a_3$ greater than $a_3/2$ and less than $a_3$ is $\frac23a_3$. Thus we have $a_2=2a_1$ and $a_3=3a_1$. This cannot continute to hold if we add a fourth number, so the only sets with this property are those of the form $\\{a_1,2a_1,3a_1\\}$ with $a_1\in\mathbb N$.
|
stackexchange-math
|
{
"answer_score": 6,
"question_score": 3,
"tags": "elementary number theory"
}
|
Fail webpack build when plugin throws an error
How do I make my webpack build fail if `scripts.js` throws an error? Adding `--bail` as a flag or as a configuration option does not work.
// webpack.config.js
const SynchronizableShellPlugin = require('webpack-synchronizable-shell-plugin');
...
bail: true, // this does not work like I expect it to
plugins: {
new SynchronizableShellPlugin({
onBuildStart: {
scripts: ['node script.js'],
blocking: true
}
}),
}
...
|
The issue is that this specific plugin does not throw an error in case of script failure. You can use different plugin, e.g. pre-build-webpack.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "webpack"
}
|
Slow in filling .NET DataSet from Oracle 9i
This is a problem that my friend asked over the phone. The C# 3.5 program he has written is filling a Dataset from a Patient Master table which has 350,000 records. It uses the Microsoft ADO.NET driver for Oracle. The ExecuteQuery method takes over 30 seconds to fill the dataset. However, the same query (fetching about 20K records) takes less than 3 second in Toad . He is not using any Transactions within the program. It has an index on the column (Name) which is being used to search.
These are some alternatives i suggested :-
1) Try to use a Data Reader and then populate a Data table and pass it to the form to bind it to the Combo box (which is not a good idea since it is likely to take same time)
2) Try Oracles' ADO.NET Driver
3) Use Ants profiler to see if you can identify any particular ADO.NET line.
Has anyone faced similar problems and what are some ways of resolving this.
Thanks, Chak.
|
You really need to do an extended SQL trace to see where the slowness is coming from. Here is a paper from Cary Millsap (of Method R and formerly of Hotsos) that details doing this:
<
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "oracle, c# 3.0, dataset, performance"
}
|
`shift` in Bash but on arrays instead of arguments?
Titel pretty much has it. I'm trying to do the `--options args` thing but instead of running `./command --option1 args --option2 args` I'm doing `./command '--option1 args --option2 args`.
array=( $1 )
POSITIONAL=()
while [[ ${#array[@]} -gt 0 ]]; do
key="${array[0]}"
case $key in
--title)
title="${array[1]}"
echo 1
shift
shift
;;
--artist)
artist="${array[1]}"
echo 2
shift
shift
;;
*) # unknown option
POSITIONAL+=("${array[0]}") # save it in an array for later
shift
;;
esac
done
set -- "${POSITIONAL[@]}" # restore positional parameters
In this code, `shift` doesn't work. Is there a way to use `shift` but on arrays?
|
You can use array slicing to simulate shifting:
array=(aardvark baboon "clouded leopard" dolphin)
while (( ${#array[@]} ))
do
echo "Animal: ${array[0]}"
array=( "${array[@]:1}" )
done
And you if you have existing code that processes positional parameters, you can just set those from your array:
array=(aardvark baboon "clouded leopard" dolphin)
set -- "${array[@]}"
while (( $# ))
do
echo "Animal: $1"
shift
done
|
stackexchange-stackoverflow
|
{
"answer_score": 13,
"question_score": 3,
"tags": "arrays, bash"
}
|
QGIS 2.10.1 (64bit) rotation field setting missing
I cannot find the the rotation field setting under the properties-layer settings-advanced (for styles) menu in the new release of QGIS (2.10.1 64bit). The only setting what is available there is the "symbol levels". Any idea where can I find this function?
|
In QGIS 2.10.1, the option **Change angle** is availabe for the _Rule-based_ style which can be used for rotation. This can be accessed by right-clicking on an item.
|
stackexchange-gis
|
{
"answer_score": 3,
"question_score": 1,
"tags": "qgis, style, qgis 2.10"
}
|
Loop through list of 2 tuples to replace part of a string
I'm trying to replace chained `String.Replace()` calls with a more functional version. Original:
let ShortenRomanNumeral (num : string) : string =
num.Replace("VIIII", "IX").Replace("IIII", "IV").Replace("LXXXX", "XC").Replace("XXXX", "XL").Replace("DCCCC", "CM").Replace("CCCC", "CD")
Functional version that works with one key value pair:
let ShortenRomanNumeral' (str : string) (k : string) (v : string) : string =
let strAfterReplace =
str.Replace(k, v)
strAfterReplace
I'm struggling to extend it to work with a list of tuples, such as
let replacements = [("VIIII", "IX"); ("IIII", "IV"); ...]
How can I write this function to apply the `Replace()` to the string for each key and value in the replacements list?
|
A `fold` will do the job:
let ShortenRomanNumeral' (str : string) (k : string, v : string) : string =
let strAfterReplace =
str.Replace(k, v)
strAfterReplace
let replacements = [("VIIII", "IX"); ("IIII", "IV"); ]
let replaceValues str = List.fold ShortenRomanNumeral' str replacements
replaceValues "VI VII VIIII I II III IIII" // "VI VII IX I II III IV"
Note that I only modified the last parameter of `ShortenRomanNumeral'` to accept tupled values.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "f#"
}
|
Retrieving the array of selected values in select2
I have the following issue where i cannot retrieve the selected array from select2 in my JS.
<select class="js-example-basic-multiple"
name="states[]"
multiple="multiple"
style="width:500px;">
<option>"dynamic value"</option>
<option>"dynamic value2"</option>
And the associated script:
var caseCodes = $('.js-example-basic-multiple option:selected').text()
The above javascript function retrieves all my selected values as a single long string.
Is there any way i can retrieve the array and loop through it to find each individual selected value?
|
Just read the `<select>`'s value :
$('.js-example-basic-multiple').val()
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "javascript, jquery, html, jquery select2"
}
|
Adding Venstar Add-a-wire ACC0410 to HVAC with Nest Thermostat E
I purchased a Nest Thermostat E and found that I don't have C-wire. With the research, including adding venstar to HVAC and Youtube video by Venstar, I tried to add c-wire to my Nest Thermostat E with the Venstar Add-a-wire (ACC0410). However, I can't find exact match with my HVAC control board system. So, I hope that someone experienced with these can help me what to do.
As you see below, it is different from Venstar Youtube video setting. The video doesn't have lines from compressor but mine does. Could you please help me how to connect my Venstar ACC0410 to my control board and what to do with Nest Thermostat E setting?
First, here is my current HVAC control board setting as below.
]="stringItem"></material-input>
</div>
The **()** around **ngModel** casues the error. It is compiling when I use only **[ngModel]** , but this doesn't write back 'item' changes into the entity object.
|
In this case you want to use the indexing feature: <
to have something like:
<div *ngFor="let stringItem of entity.stringList; let i=index">
<material-input [(ngModel)]="entity.stringList[i]"></material-input>
</div>
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "angular dart"
}
|
Concatenate lists in constant time in scala?
In Scala, is there a built-in function or external library for concatenating two lists (or arrays, or vectors, or listbuffers, etc) in constant time? Such an operation would presumably destroy / mutate the two original lists. All the functions I see for concatenating lists run in linear time, as far as I can tell.
Thanks much.
|
There is the `UnrolledBuffer` which has the `concat` method taking another `UnrolledBuffer` and returning their concatenation in `O(1)`. It is destructive to the argument buffer - the second buffer will be empty after this calling this method.
|
stackexchange-stackoverflow
|
{
"answer_score": 13,
"question_score": 12,
"tags": "list, scala, data structures, concatenation"
}
|
How to make a dynamic list based on MULTIPLE criteria?
So I want to make a dynamic list based on multiple criteria . I've copied and changed to my needs this formula :
=IFERROR(INDEX($B$2:$B$26,SMALL(IF($C$2:$C$26="Stire",ROW($B$2:$B$26)),ROW(2:2))-1,1),””).
it works but since I need multiple criteria I've tried to change it but I get the #NAME? error :
=IFERROR(INDEX($B$2:$B$26,SMALL(IF(($C$2:$C$26="Stire")*($E$2:$E$26>=TIME(19,0,0))*($F$2:$F$26<=TIME(20,0,0)),ROW($B$2:$B$26)),ROW(2:2))-1,1),””)
I've tried the IF statement alone to see if it works and it did :
=IF(($C$2:$C$26="Stire")*($E$2:$E$26>TIME(19,0,0))*($F$2:$F$26<=TIME(20,0,0)),$B$2:$B$26)
I also tried doing this via AND but I get the same error .
I use EXCEL 2016.
|
You may want to try nesting the IF tests instead of using the *
`IF($C$2:$C$26="Stire", IF($E$2:$E$26>TIME(19,0,0), IF($F$2:$F$26<=TIME(20,0,0),$B$2:$B$26)),"")`
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "excel, excel formula"
}
|
Can Services implement the SensorEventListener
Can I use the SensorEventListener with a service?
I want to do something when my application is running in background with a service being active. When a user shakes the phone I want a code to run in background. So is it possible for services to detect shake changes??
Thanks in advance!
|
Yes, it is possible. Because, I saw an application (Avast) in which there is an option like whenever we lost the phone, we can request the device to get the GPS location with out the permission of the user and will send it to us to the web. The webservice will activate the Android services in the mobile which will automatically activate the GPS with out the users interface and will send the location.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "android, android intent, android service"
}
|
LESS selector for element and child?
With LESS how can I apply styles to both a selector and the selector within it?
My demo I need to apply opacity and z-index to the class a, and to label that come directly after it.
.a {
color: red;
opacity: 0.9;
z-index: 2;
& + label {
color: blue;
opacity: 0.9;
z-index: 2;
}
}
|
Here the complete answer, to help others with same doubt. To achieve desired result, original code could become:
**SOLUTION 1:**
.a
{
&,
& + label
{
color: red;
opacity: 0.9;
z-index: 2;
}
& + label
{
color: blue;
}
}
Firstly you define common properties for both selectors with `,` separator and then you'll override only `color` property for `& + label` one.
**SOLUTION 2:**
If you want, you could achieve the same result using first class `.a` as a mixin and then overriding again `color` property:
.a
{
color: red;
opacity: 0.9;
z-index: 2;
}
a + label
{
.a;
color: blue;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "less"
}
|
How do I add this Change Log library to my current Android project in Eclipse?
Okay, so I'm having difficulties implementing this Change log library into my android app in eclipse: <
I tried using the clone url and importing the library into eclipse and then going into the properties of my android project and adding it as a library but that didn't work. I do not have Maven installed nor do I know anything about it. Is there a way I can just get a jar of this library somewhere? Can someone please help me? Thank you!
|
Its most likely not setup as an Android Library project and that is why it can't be accessed that way.
You can create the jar yourself though by using: < eclipse itself or running the jar command in a terminal. (Eclipse might be a little more user friendly if you don't use the terminal.
I would however highly recommend learning how to incorporate Maven in your projects because it is a huge time saver. If you migrate to Android Studio then Maven will become your best friend.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "java, android, eclipse, maven"
}
|
How to fix numpy importerror in JythonMusic
I am working on a music composition AI program using JythonMusic on Linux Mint 19.1. When I attempt to test my code, I get an import error say that the numpy module is not found. I have verified that numpy is installed for both Python 2.7 and Python 3.6 by trying to import the module in IDLE, and that has worked both times. Is there something that I can do to get all of my installed modules to import normally in JythonMusic?
|
There is a difference between Python and Jython. Python is built in C, whereas Jython is built on top of the Java VM. Therefore, packages installed under Python 2.7 and Python 3.6 are NOT available directly to Jython.
However, there is a Java version of numpy called numjy, available here.
I just downloaded it, unzipped it, and copied the numjy folder into the JythonMusic folder (same folder as where JEM.jar is stored).
Then, I restarted JEM, and was able to run the following code:
import numjy as np
a = np.arange(10)
print a
a = a.reshape(2, 5)
print a
print a * 10
which gave me the following output:
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
array([[0, 1, 2, 3, 4]
[5, 6, 7, 8, 9]])
array([[0, 10, 20, 30, 40]
[50, 60, 70, 80, 90]])
I hope this helps!
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "python, numpy, importerror, linux mint, jython music"
}
|
JSON field tag issue not taken into account during encoding
I have the following Go code
type Version struct {
Name string `json: "name"`
Project string `json: "project"`
ProjectId int `json: "projectId"`
}
b := new(bytes.Buffer)
if err := json.NewEncoder(b).Encode(&Version{"foo", "bar", 42}); err != nil {
log.Fatal(err)
return false
}
fmt.Printf("JSON %v", b)
The output is:
{"Name":"foo","Project":"bar","ProjectId": 42}
instead of:
{"name":"foo","project":"bar","projectId": 42}
Any thoughts why?
Thanks
|
Your struct tags aren't proper so the parser isn't working as expected
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
)
type Version struct {
Name string `json:"name"`
Project string `json:"project"`
ProjectId int `json:"project_id"`
}
func main() {
b := new(bytes.Buffer)
if err := json.NewEncoder(b).Encode(&Version{"foo", "bar", 42}); err != nil {
log.Fatal(err)
}
fmt.Printf("JSON %v", b)
}
works as expected
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "json, go"
}
|
NSTimeZone timeZoneWithName abbreviation shows different Abbreviations on different devices
I want to display "EDT" on label. I used below line and I found it to be working on iphone6, 6+ and iphone4 (iOS 7.1). But testing it on iPhone5s(iOS 8.2), iPhone5(iOS 7.1) I noticed it showing "GMT-4"
NSString *labelString = [NSString stringWithFormat:@"%@",[[NSTimeZone timeZoneWithName:@"America/New_York"] abbreviation]]
Is it device time zone related issue or can someone point out where am I making mistake please. Thanks in advance.
|
This was because of the timezone which was set on the devices. Different devices had different timezones set and that made this change in
[[NSTimeZone timeZoneWithName:@"America/New_York"] abbreviation]]
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "ios, nsdateformatter, nstimezone"
}
|
c# StreamReader ReadLine() Keep Quotes
I have the following, and need to get the first line from the socket, but not have c# remove the quotes. I can't escape the quotes in the input as they come from a source I don't control.
StreamReader sr = new StreamReader(socketStream);
string firstLine = sr.ReadLine();
Example Input Line: GET "/aaaadoe"
firstLine equals GET /aaaadoe and not GET "/aaaadoe".
Any suggestions?
|
`StreamReader` does not remove quotes. Some ideas:
1. The quotes were not sent
2. Something else removed them
3. You are not looking at the right string, or misinterpreting the debugger display of it
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "c#, networking"
}
|
Problemas Con INNER JOIN PONER UN CASE WHEN cuandoes un CONCAT
No logro redondear , lo que necesito es que tengo un `left join` de la cual el `ON` es de dos `concat`
LEFT JOIN BD_MigracionQV.dbo.TBL_QV_Hecho_Produccion_IF Produccion
ON CONCAT(Cita.IdPaciente, Cita.IdMedico,
convert(char(10), Cita.FechaCita,101))=CONCAT(Produccion.IdPaciente,Produccion.IdMedicoAtencion,convert(char(10),Produccion.Fecha,101))
lo que pasa es que en esta parte se unes la dos tablas que uno ahí esta bien pero el problema es la fecha que cambia En el primer `CONCAT` esta bien pero en el segundo varia en la fecha como comente,El `concat` puede ser uno así
CONCAT(Produccion.IdPaciente,Produccion.IdMedicoAtencion,convert(char(10),
Produccion.Fecha,101)) o CONCAT(Produccion.IdPaciente,Produccion.IdMedicoAtencion,
convert(char(10),Produccion.FechaInicioOa,101))
|
Lamentablemente no comprendo del todo la pregunta y en verdad creo que falta más información o falta que apliques tu solución de otra manera.
¿Por qué necesitas una unión tan compleja entre dos tablas utilizando concatenaciones? Tal vez lo que buscas se realiza más por un where que por la unión en sí.
Puedes unir las columnas por separado así:
left join tabla2 tbl2 on tbl1.idMedico=tbl2.idMedico and tbl1.idPaciente=tbl2.idPaciente
|
stackexchange-es_stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "sql"
}
|
Shutdown server using PHP
I know this sounds just wrong, but stay with me for a second.
I have a Raspberry pi which is currently running, I forgot the password, and I want to shut it down so I could remove the SD card and reset the password.
I happen to have an IDE setup with the password, but the IDE has encrypted the password. As such, I could upload PHP and run it on the ngix webserver I earlier installed. I'v tried the following, but all it displays is "done".
Recommendations?
PS. I've asked < and if you know, please either comment or post an answer.
<?php
echo(shell_exec('sudo halt'));
echo(shell_exec('sudo shutdown'));
echo(shell_exec('shutdown'));
echo('done');
?>
|
if your webserver is not running as root you need to use sudo and add your password
try this command
'echo your_passwd | /usr/bin/sudo -S shutdown -h -f 0'
If you have lost your password, just could pull the plug and change the password in /etc/shadow
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "php, linux, shell"
}
|
CSS Split a responsive circle div into halves
I have divs with a border which make them look "circle shape". The last div should be split horizontally into halves with different text, however, still, it should be a circle.
I use Bootstrap and I have no clue how to round half of circle for one div and another div in the responsive design. Could anybody help me out? Thanks a lot! <
With fixed size, it seems to be easy Half circle with CSS (border, outline only)
P.S. I don't want to use background image if possible.
|
You have used the percentage value in `border-radius`, and percentage values depend on the elements `width` and `height` and takes the percentage of small dimension(i.e. width or height).
In your case(in the 3rd circle), the height and width of `.bublina` not same i.e. height is smaller than width, thats why `border-radius:100%` is not making it circle.
So you have to use `px` value instead of `%` value here like:
.bublina.upper {
border-top-right-radius: 300px;
border-top-left-radius: 300px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.bublina.lower {
border-top-right-radius: 0;
border-top-left-radius: 0;
border-bottom-right-radius: 300px;
border-bottom-left-radius: 300px;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "css"
}
|
Colors, label in Python
`X` is a 100x2 vector that contains sepal and pethal length data for 2 kinds of flowers. `y` is a 100x1 vector that contains label values for my data: -1 and 1. I create a meshgrid, then I plotted my meshgrid using `countourf` method and now I load the data in the meshgrid with this code:
for idx, cl in enumerate (np.unique(y)):
plt.scatter (x=X[y == cl, 0], y= X[y == cl, 1], alpha=0.8, c=colors[idx], marker= markers [idx], label = cl, edgecolor = 'black')
`alpha, colors, marker, edgecolor` are just secondary things. Also `np.unique(y) = [-1 1]` .
My question is, Why `[y==cl,0]` is a false and `[y==,1]` is a true argument? and, How using `==` can I classifier my data?
|
In the for loop, `cl` loops over the two _unique_ values of `y` i.e. `[-1, 1]`. So in the first loop iteration, `cl=-1` and `y == cl` returns the rows where your y values are -1. Therefore, `[y == cl, 0]` returns the locations where y is -1 and the data is the first column (index 0) which is Sepal length. Similarly, `[y == cl, 1]` returns the locations where y is -1 and the data is the second column (index 1) which is Petal length.
The same applies in the second iteration of the loop when `cl` is 1.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "python, matplotlib, enumerate"
}
|
Find values of constants a and b such that the given improper integral converges
Find values of constants a and b such that:$$\int_{3}^\infty \left(\frac{ax+2}{x^2+3x}-\frac{b}{3x-2}\right) dx=k$$ then by partial fractions we get: $$\lim_{N \to \infty} \int_{3}^N \left(\frac{2}{3}\frac{1}{x}+\frac{a-\frac{2}{3}}{x+3}-\frac{b}{3x-2}\right) dx=k$$ then $$\lim_{N \to \infty} \left[\frac{2}{3}ln(x)+(a-\frac{2}{3})ln (x+3)-\frac{b}{3}ln(3x-2)\right]_3^N =k$$ By logarithm properties: $$\lim_{N \to \infty} \left[ln\frac{(x)^\frac{2}{3}(x+3)^\left(a-\frac{2}{3}\right)}{(3x-2)\frac{b}{3}}\right]_3^N =k$$ Evaluating: $$\lim_{N \to \infty} \left[ln\frac{(N)^\frac{2}{3}(N+3)^\left(a-\frac{2}{3}\right)}{(3N-2)^\frac{b}{3}}\right]-\left[ln\frac{(3)^\frac{2}{3}(6)^\left(a-\frac{2}{3}\right)}{(7)^\frac{b}{3}}\right] =k$$ But, I do not know what to do after this step. Any recommendation will be appreciated
|
**Hint** : It converges when
> $$ \lim _{ n\to \infty } \ln { \left[ \sqrt [ 3 ]{ \frac { { n }^{ 2 }{ \left( n+3 \right) }^{ 3a-2 } }{ { \left( 3n-2 \right) }^{ b } } } \right] } \\\ \\\ 2+3a-2=b\quad \Rightarrow b=3a $$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 2,
"tags": "calculus, integration, convergence divergence, improper integrals"
}
|
ramification of prime in Normal closure
Let $K$ be an algebraic number field and let $p$ be a prime in $\mathbb{Q}$ such that $p$ ramifies in $L$, the Galois closure of $K$. How can I show that $p$ ramifies in $K$ itself?
|
> **Important fact:** If $K, K'$ are extensions of $\mathbb Q$, and $p$ is a prime which is unramified in both $K$ and $K'$, then $p$ is unramified in the compositum $K\cdot K'$.
One can prove this, for example, by considering the inertia group $I$ of the Galois closure $L$ of $K\cdot K'$: if $K, K'\subset L^I$, then $K\cdot K'\subset L^I$.
* * *
We can use this in the following way: let $K = \mathbb Q(\alpha)$, and let $\alpha_2,\ldots,\alpha_n$ be the Galois conjugates of $\alpha$. Then for each $i$, $$\mathbb Q(\alpha)\cong\mathbb Q(\alpha_i),$$so in particular, $p$ is unramified in $\mathbb Q(\alpha)$ if and only if it is unramified in $\mathbb Q(\alpha_i)$ for each $i$.
But the Galois closure $$L=\mathbb Q(\alpha)\cdot\mathbb Q(\alpha_2)\cdot\ldots\cdot\mathbb Q(\alpha_n),$$ so if $p$ ramifies in $L$, it cannot be unramified in $K$.
|
stackexchange-math
|
{
"answer_score": 5,
"question_score": 2,
"tags": "algebraic number theory"
}
|
How to efficiently invert $K \otimes M+I_T\otimes \Sigma$?
I'm looking for a way to efficiently invert $$K \otimes M+I_T\otimes \Sigma$$ where the inverses for $M,K$ exist. $I_T$ is the identity matrix of dimension $T$, and $\Sigma$ is a diagonal matrix, with positive only elements along the main diagonal.
If I had only $K \otimes M$, I would just do $K^{-1}\otimes M^{-1}$. However, with the extra term, I don't see how to efficiently invert it.
|
Generally there isn't a way to compute the inverse of a sum of Kronecker products. However, suppose there is a factor in common, let's say $I_T$ here and your sum is
$$ A = K \otimes I_T + I_T \otimes \Sigma $$
Then solving linear systems with $A$ becomes equivalent to solving a Sylvester equation. Thus perhaps one way to approach your problem would be to try and introduce $I_T$ as a common factor by say
$$ (I \otimes M)^{-1} (K \otimes M + I_T \otimes \Sigma) = K \otimes I_T + I_T\otimes \Sigma M^{-1} $$
You can find a list of helpful formulas for Kronecker products on this wikipedia page
|
stackexchange-scicomp
|
{
"answer_score": 7,
"question_score": 4,
"tags": "linear algebra, efficiency"
}
|
What's the name of this Heteroptera bug from Toronto, Canada?
My friend already identified it as belonging to the Heteroptera order, but I was wondering if anyone knows the name of the species.
Found in Toronto, Ontario, Canada, on July 21 2017, in a residential bathroom.
!Mystery bug !Mystery bug
|
This is, indeed, a Heteroptera bug.
Luckily, this is not a kissing bug (which could be infected with _Trypanosoma_ ), but just an _assassin bug_ , from the Species _Reduvius personatus_. Its common name is masked hunter.
Here is an image of the same bug, also in Ontario, from the Canada Pest Control website:
, have a look at this video from the Smithsonian Channel: <
|
stackexchange-biology
|
{
"answer_score": 9,
"question_score": 6,
"tags": "species identification, entomology"
}
|
If singular Quarks cannot exist on their own, then how is Quark-Gluon Plasma possible?
To my understanding, QGP is a theoretical form of matter where quarks are freely floating around. I understand immense temperature and pressure is required to form this. Also to my knowledge, quarks cannot exist on their own, and must be binded to others in the form of protons/neutrons/pions. These two facts seem to contradict each other, and I am curious how QGP can exist when singular quarks cannot exist on their own.
|
An attempt to remove a quark from a gluon stores enough potential energy in the colour field to form a meson, which happens instead of the quark's removal. This effect results in confinement. However, the hadron has a nonzero size, in part because of asymptotic freedom (the colour force is very weak at short length scales). In extremely dense matter, the volume to which a hadron would theoretically confine its quarks is larger than the volume per hadron. Assigning a volume to each hadron, they now overlap, allowing quarks to move between such volumes despite the otherwise expected confinement. This results in the quark-gluon plasma, which has already been empirically achieved.
|
stackexchange-physics
|
{
"answer_score": 1,
"question_score": 1,
"tags": "particle physics, quarks, states of matter, quark gluon plasma"
}
|
Java: Converting UTF 8 to String
When I run the following program:
public static void main(String args[]) throws Exception
{
byte str[] = {(byte)0xEC, (byte)0x96, (byte)0xB4};
String s = new String(str, "UTF-8");
}
on Linux and inspect the value of s in jdb, I correctly get:
s = "ì–´"
on Windows, I incorrectly get:
s = "?"
My byte sequence is a valid UTF-8 character in Korean, why would it be producing two very different results?
|
It correctly prints "``" on my computer (Ubuntu Linux), as described in _Code Table Korean Hangul_. Windows command prompt is known to have issues with encoding, don't bother.
Your code is fine.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "java, utf 8"
}
|
How do I echo a string to a text file before the content that's already in?
I don't know if it is possible but if it is how do I, for example, `ECHO FOR /F blah blah blah >>output.txt` to the first line or before a certain line inside `output.txt` when it is not empty.
|
This is pretty simplistic but it answers part of your question.
It adds a line at the very top of the file.
echo First line >newfile.txt
type oldfile.txt >>newfile.txt
move newfile.txt oldfile.txt >nul
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "string, batch file, text files, echo"
}
|
Como deletar um documento específico de uma collection no MongoDB?
O método **remove()** usado dessa forma: db.nome_da_collection.remove(), remove todos os documents de uma collection, como eu faço pra remover um document específico?
|
Se você quiser remover pelo id pode usar a seguinte query:
db.collection.remove({"_id": ObjectId("5798ffcd60b2d8a4066b482d")});
Você pode remover usando a mesma estrutura de um find. Por exemplo, você pode remover todos os registros que estiverem com a quantidade maior que 10.
db.collection.remove({quantidade : {$gt :10}})
|
stackexchange-pt_stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "mongodb"
}
|
how to restart unicorn manually
I'm not confident that unicorn is restarting properly when I run `cap deploy` as certain changes are not showing in the app, therefore I wanted to restart unicorn manually on my remote server. I have navigated into `etc/init.d` and see a listing for `unicorn_myapp` but it's not a directory (i.e. I can't cd into it). Based on the code below from my deploy.rb file, is there something I can do from here to restart unicorn?
I tried to do `run unicorn_myapp restart` but it said `run` isn't a command
namespace :deploy do
%w[start stop restart].each do |command|
desc "#{command} unicorn server"
task command, roles: :app, except: {no_release: true} do
run "/etc/init.d/unicorn_#{application} #{command}"
end
end
|
you didn't list the OS. but one of the following should work.
you will need to be root / use sudo
/etc/init.d/unicorn_myapp restart
/etc/init.d/unicorn_myapp stop
/etc/init.d/unicorn_myapp start
service unicorn_myapp restart
service unicorn_myapp stop
service unicorn_myapp start
Try the restart versions first, but depending upon how the init script was written it might not have a restart command, if that doesn't work you can do the stop / start version.
|
stackexchange-stackoverflow
|
{
"answer_score": 31,
"question_score": 16,
"tags": "ruby on rails, unicorn"
}
|
Sequence corresponding to the generating function
> Find the sequence corresponding to the generating function $$G(x) = \frac{2x^4}{2x^3-x^2-2x+1}$$
First of all, I wrote this equation like that;
$\sum\limits_{n=0}^\infty(a_n)x^n = \frac{2x^4}{2x^3-x^2-2x+1}$
Then, I think right hand side should be;
$\frac{2x^4}{2x^3-x^2-2x+1} = \frac{A}{2x-1} + \frac{B}{x-1} + \frac{C}{x+1}$
I found
$A = \frac{-2x^2}{3}$ , $B = x^2$ , $C = \frac{x^2}{3}$
However, I cannot continue after that point.
|
Assuming the partial fraction decomposition is correct (I haven't checked it, but I suppose you have), remember that $\frac{1}{1-x}=\sum_{n=0}^\infty x^n$. Hence $$\frac{1}{2x-1}=-\frac{1}{1-2x}=-\sum_{n=0}^\infty (2x)^n=-\sum_{n=0}^\infty 2^nx^n$$ and $$\frac{1}{x-1}=-\frac{1}{1-x}=-\sum_{n=0}^\infty x^n$$ and $$\frac{1}{x+1}=\frac{1}{1-(-x)}=\sum_{n=0}^\infty (-1)^nx^n$$ Remember also that multiplying a power series by $x^n$ shifts the coefficients $n$ steps upwards. Can you continue from here?
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 2,
"tags": "functions, discrete mathematics, generating functions"
}
|
React-Semantic-UI, Accordion, title in label. "Inline" within arrow icon
### Testcase
<
### Expected Result
Label "inline" within "arrow" icon.
### Actual Result
!image
### Version
React-Semantic-UI 0.77.2
|
**override** the semantic-UI CSS like this :
.ui.accordion .title:not(.ui){
display: flex;
}
_to act labels like boxes_
.ui.accordion .title .dropdown.icon{
display: inline-flex;
flex-shrink: 0;
}
_to organize icons vertically_
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "css, semantic ui"
}
|
How to get into image manipulation programming?
How can I do simple thing like manipulate image programmatically ? ( with C++ I guess .. ) jpgs/png/gif .....
|
check out BOOST , it has a simple Image Processing Library called GIL. It also has extensions to import common formats.
<
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 3,
"tags": "c++, image processing, image manipulation"
}
|
Select only not null column values and display only that values using sql query
Like I have table Like this
col1 col2 col3 col4
---- ---- ---- ----
1 NULL NULL NULL
NULL 2 NULL NULL
3 NULL NULL NULL
NULL NULL NULL 4
The expected result is:
col5
----
1
2
3
4
How can I get this kind of Output using SQL query?
|
You are looking for `coalesce()`, if you want the first non-NULL value:
select t.*, coalesce(col1, col2, col3, col4) as col5
from t;
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "sql"
}
|
How to access object provided by onloadedmetadata?
Im trying to acceess a value in a object resulting from `onloadedmetadata`. When I console log the entire object `audioDuration` i can see and access the contained value. When i console log the exact element `AudioDuration.length` it returns undefined.
var audioDuration = {};
convertedAudio.onloadedmetadata = () => {
audioDuration.length = convertedAudio.duration
};
console.log (audioDuration) // displays object {length: 25.547755}
console.log (audioDuration.length) // displays undefined
I want to use the value of `AudioDuration.length` directly and not the entire object.
|
your problem is due to the value of audioDuration is set only in callback and the console.log is used directly after onloadedmetadata so the console.log will run before the value is set. Two ways to fix that, one way is to do console.log inside onloadmetadata. The other way is to return a promise and await for the result.
const audioDuration = {}
const getDuration = () => new Promise(resolve => {
convertedAudio.onloadedmetadata = () => {
resolve(convertedAudio.duration);
}
})
getDuration().then(l => { console.log(l); audioDuration.length = l; })
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, reactjs"
}
|
IF condition throwing error in Unix Command Prompt
Below is my simple if command which throws command not found but any it prints else part value...
-bash-3.00$ if ["$a"="10"]; then echo "hello"; else echo "hi"; fi;
output:
-bash: [10=10]: command not found
hi
Can any one please let me know what is the problem ?
|
Add spaces between `[`/`]` and predicate expression:
if [ "$a" = "10" ]; then echo "hello"; else echo "hi"; fi;
# ^ ^
`[` is a program:
$ which [
/usr/bin/[
Without space, `[10=10]` is recognized as a program name and is executed instead of `[`.
* * *
$ a=10
$ if [ "$a" = "10" ]; then echo "hello"; else echo "hi"; fi;
hello
$ a=20
$ if [ "$a" = "10" ]; then echo "hello"; else echo "hi"; fi;
hi
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "linux, bash, shell, unix"
}
|
Regex replacing hyphens in attributes name only
I have a string that looks something like this.
<tag-name i-am-an-attribute="123" and-me-too="321">
All I want to do is replace the dashes into an underscore, but the tag-name should remain like it is.
Hope there are some regex guru's who can help me out.
[solution] In case someone needs this.
I ended up with a perl oneliner command
`echo '<tag-name i-am-an-attribute="123" and-me-too="321">' | perl -pe 's/( \K[^*"]*)-/$1_/g;' | perl -pe 's/ / /g;'`
results in
<tag-name i_am_an_attribute="123" and_me_too="321">
|
Using sed:
sed ':l;s/-\([^- ]*\)\( *=\)/_\1\2/g;tl' input
_Gives:_
<tag-name i_am_an_attribute="123" and_me_too="321">
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "regex, sed"
}
|
If I assign null to an object or a property, will the garbage collector in C# always run and release its memory space?
A a = new A();
a.Name = null;
Will the garbage collector release the properties' space?
In addition:
B b = new B();
b = null;
Will the garbage collector release the objects' space?
|
In your first example `a.Name` only occupies so much space as is needed to hold a reference to an object of `a.Name`'s type. Wether it contains `null` or a reference does not matter. This space will only get collected when the whole object `a` gets collected. An object which `a.Name` points to might be collected when you set `a.Name` to `null`.
In your second example, `b` might or might not get collected.
In any case you can't trigger a garbage collection just by assingning `null` as the collection can occur at any time the runtime sees fit. You might want to read the details in the documentation.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "c#, garbage collection"
}
|
scala - how to avoid using mutable list and casting
I have written the following code which works fine. However, I wanted to check if there is a way I can avoid using mutable list and casting datatype from any to string.
import scala.collection.mutable.ListBuffer
val databases = spark.catalog.listDatabases.select($"name").collect().map(_(0)).toList
var tables= new ListBuffer[String]()
databases.foreach{database =>
val t = spark.catalog.listTables(database.asInstanceOf[String]).filter($"isTemporary" === false).filter($"tableType" =!= "VIEW").select($"name").collect.map(database+"."+_(0).asInstanceOf[String]).toList
tables = tables ++ t
}
tables.foreach(println)
|
You can use row deconstructor to get rid of casting:
val databases: List[String] = listDatabases.select($"name").collect().map {
case Row(name: String) => name
}.to[List]
As for mutability, just use `flatMap` instead of `foreach`:
val tables = databases.flatMap { db => listTables(db).filter .... }
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "scala, apache spark"
}
|
How to use Window Manager of Linux inside VirtualBox?
I have the same problem in Redhat Linux and Debian Linux. I cannot use the normal switching between windows. I mean this square window manager:
!enter image description here
I tried all keys CMD, ALT, CTRL, FN and SHIFT and their combinations unsuccessfully.
In VirtualBox preferences > Input, I have Left CMD as the host key, similarly as explained here. However, I have not managed to use it browse between windows and use the 9-window manager. I do not know if the host key is the key which I should be changing.
How can you move between the nine windows in Linux inside VirtualBox?
|
You should change your VirtualBox host key to not conflict with your workspace switching keys.
You can do this by opening the VirtualBox Preference window, select "Input" and change the host key. (Reference: <
|
stackexchange-superuser
|
{
"answer_score": 1,
"question_score": 0,
"tags": "virtualbox"
}
|
recurring payment backend system for municipality (utilities)
I'm able and willing to develop a frontend web-based UI (and any server-side code to support the frontend) but I'm stuggling to find a proven, low-cost automatic payment processing system with a nice API that I can use to handle the actual payments.
I envision the system will only accept checking account payments (no credit cards). Once the user supplies the relevant info, they will be automatically billed for their village utility use every month, based on that month's usage of course. I'll use the UI to allow the user to track history, change billing info, etc.
Any recommendations?
|
Authorize.Net offers eCheck services. Their APIs are all easy to use so this one should meet your criteria.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 2,
"tags": "api, payment processing"
}
|
DHCP Server Authorized But Won't Work
I have 2 DHCP servers that I have had to replace. On I unauthorized the old servers and when I go to authorize the new servers, it is added to the authorized list but the IPV4/IPV6 areas still show not authorized. It looks like this:
 <
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "разметка"
}
|
Python- Do not want letters or numbers outside of range input
I want the program to only allow the numbers 1-4 to be used as input and not any letters or numbers outside of that range. This is the code I have right now but it is not working:
# Get the user's choice.
choice = int(input("what would you like to do ? "))
# Validate the choice.
while choice < 1 or choice > 4:
try:
choice = int(raw_input("Enter a valid choice: "))
except ValueError:
print ("Please enter a numeric value.")
# return the user's choice.
return choice
|
**Here is your solution**
while True:
try:
choice = int(input("what would you like to do ? "))
except ValueError:
print ("Invalid choice.Valid choises are between 1-4.")
continue
if choice<1 or 4<choice:
print ("Invalid choice.Valid choises are between 1-4.")
continue
else:
print ("some codes will work on here..")
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "python, exception, input"
}
|
XeTeX logo with reversed E
How do I type XeTeX logo with rotated E in XeTeX itself as can be seen here ?
|
Load the package `xltxtra` by issuing the command
\usepackage{xltxtra}
in the preamble. Then the controls sequence
\XeLaTeX
yields the XeLaTeX logo with a mirror reflected E.
|
stackexchange-tex
|
{
"answer_score": 2,
"question_score": 3,
"tags": "xetex, logos"
}
|
Searching for strings within a string in C++
everyone. I am an experienced C programmer trying to get adjusted to C++. I would like to do the equivalent of this C statement...
sscanf(str, "%s %s", sub1, sub2);
...but with C++'s string object. Say str is "hello world", doing the above sscanf statement would put "hello" in sub1, and "world" in sub2. I know I can use C functions like that in C++, but I would like to use the C++ string object instead of an array of chars. I've tried this:
string q, h, w;
cout << "Type \"hello world\": ";
cin >> q;
istringstream x(q);
x >> h >> w;
if (h == "hello")
cout << "Yes!\n";
else
cout << "No!\n";
if (w == "world")
cout << "Yes!\n";
else
cout << "No!\n";
But it outputs "Yes! No!", which means it picked up the "hello" but not the "world". Any ideas?
|
That is because the `operator>>` used with `cin` will only capture the "hello" phrase, and will stop at the first delimiter (in this case a space). If you want to capture the entire input line up to the first line-delimiter typed by the user, you will have to use `getline(cin, q)`. The two-argument version of `getline()` uses a newline as the delimiter, but there is a three-argument version that allows you to specify a custom line-delimiter character as well.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "c++, string, istringstream"
}
|
android studio SharedPreferences doesn't work
i am trying to use `SharedPreferences` to login or register
SharedPreferences sp=getSharedPreferences("Login", MODE_PRIVATE);
SharedPreferences.Editor Ed=sp.edit();
Log.d("my id",jsonObject.getString("id"));
Ed.putString("userid",jsonObject.getString("id"));
Ed.commit();//or Ed.apply();
and in the other code while trying to get it
SharedPreferences sharedpreferences= getSharedPreferences("login", MODE_PRIVATE);
String id= sharedpreferences.getString("userid",null);
if(id==null)//sharedpreferences.contains("userid")==false)
{
Log.d("pref","No Id");
}
and it's always printing `No Id`
|
A **`SharedPreferences`** object points to a file containing **`key-value pairs`** and provides simple methods to read and write them. Each SharedPreferences file is managed by the framework and can be private or shared.
Your **`KEY`** must be same. Read official guideline about **`getSharedPreferences`**).
SharedPreferences sharedpreferences = getSharedPreferences("Login", MODE_PRIVATE);
And
SharedPreferences sp = getSharedPreferences("Login", MODE_PRIVATE);
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "java, android"
}
|
Different of input start with colon and without colon
What is the different between
$("input[name='ABC']") // without ":"
$(":input[name='ABC']") // with ":"
both work same to me, so should we write it with colon ":" or without? which is more correct?
|
`input` will just select specifically the `<input>` element.
`:input` selects `<input>`, `<textarea>`, `<select>`, and `<button>`.
|
stackexchange-stackoverflow
|
{
"answer_score": 13,
"question_score": 9,
"tags": "jquery"
}
|
How to enable TLS to windows server?
These servers are running Windows server Datacenter 2016 on Azure.
As per the documentation, by default TLS 1.2 is enabled on Windows server Datacenter 2016 but when i checked the registry and registry keys related to TLS does not exist.
Then how can i enable TLS on this server
|
On Windows Server 2016, if there are no specific Registry values for TLS 1.2, it means it is enabled for both server and client purposes. There is nothing you need to do.
You need registry entries to turn it off.
You can have registry to have it on, but if they are not there, it is on by default.
|
stackexchange-serverfault
|
{
"answer_score": 2,
"question_score": 0,
"tags": "ssl, azure, windows server 2016"
}
|
Does downloading a folder/file from steam use as much internet data as the game's files weight?
My brother wants to download a game on steam using a portable internet SIM thingy (same thing as a phone internet access) that weighs about 3 giga bytes, will this download use more than 3Gb of internet data (up to 64 Gb and we are at 56) or more?
|
# Generally, No
I download quite a few games on Steam, and the download is often smaller than how much disk space eventually gets used. (This is probably due to compression.)
I can't recall any games having downloads bigger than the disk space used, but no promises.
|
stackexchange-superuser
|
{
"answer_score": 1,
"question_score": -2,
"tags": "internet, download, steam"
}
|
Get Username from Get-WinEvent
I am trying to find a user who uninstalled a program on the Server. Here's the script I am using and the result. From Event Viewer, I am able to see the User but looks like the Get-WinEvent returns UserId but no Username. Is there a way to return Username for event 1034 from Get-WinEvent?
Get-WinEvent -FilterHashtable @{LogName='Application'; Id=1034} -MaxEvents 1 | format-list
* * *
TimeCreated : 6/17/2013 1:41:27 PM
ProviderName : MsiInstaller
Id : 1034
Message : Windows Installer removed the product. Product Name: PAL. Product Version: 2.3.2. Product Language:
1033. Manufacturer: PAL. Removal success or error status: 0.
|
Using .NET's SecurityIdentifier, as described here.
Get-WinEvent -MaxEvents 1000 | foreach {
$sid = $_.userid;
if($sid -eq $null) { return; }
$objSID = New-Object System.Security.Principal.SecurityIdentifier($sid);
$objUser = $objSID.Translate([System.Security.Principal.NTAccount]);
Write-Host $objUser.Value;
}
For non-null user IDs, I was able to successfully identify user names.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 4,
"tags": "windows, powershell"
}
|
Можно ли получить название активного приложения?
Пишу сервис который должен получать название активного приложения, и сохранять его, как это можно реализовать ?
|
На самом деле есть решение, работающее с 4 и до 6 версии включительно. На 7 не проверял. Оно основано на чтении /dev/proc псевдодиректории. Там достаточно информации для определения процесса. Но вручную работать сложновато, поэтому можно использовать уже написанную библиотеку <
Объединив с ответом выше вы получите универсальное решение.
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 1,
"question_score": 3,
"tags": "android, android service"
}
|
Is Backtrack 5 equal to Ubuntu + Security tools?
I just ran backtrack 5 live cd, and it basically seems to me as if I had Ubuntu + the security tools backtrack includes...
Is there any difference between backtrack 5 and Ubuntu desktop 10.04? Apart from having the security tools...
Because if there isn't I don't see why you couldn't use backtrack 5 as a main OS...
|
Currently Backtrack Linux is a derivative of Ubuntu, and besides a bit of rebranding, it is just like an Ubuntu system with all the tools installed. Since it supports installing to a hard disk, you certainly can run it as your main operating system. Alternatively you could install an Ubuntu system and install whatever tools you want (all of them, if you want all of them). Furthermore, you could even customize an Ubuntu live CD or DVD (or live USB flash drive) yourself to include the tools included with Backtrack.
|
stackexchange-askubuntu
|
{
"answer_score": 2,
"question_score": 3,
"tags": "10.04"
}
|
How do I use select with multiple like conditions in T-SQL?
I would like to select all records from a table which are not `like '%select%'` but except these which contains `'%select some_string%'` and `'%select some_other_string%'`.
How do I do this in T-SQL?
|
A straightforward translation from English to SQL should work fine:
WHERE (NOT (s LIKE '%select%'))
AND NOT ((s LIKE '%select some_string%') OR (s LIKE '%select some_other_string%'))
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "sql, tsql"
}
|
Prove the existence of a one-to-one function for a recursive definition
 = \\{f(x)\\}$ means, thus I’m not sure how to proceed with the proof. Is it implied that I need to define another function $f(x)$ or do I need to prove the latter $f(x)$?
|
Now you want to define a function $g:A\to\mathcal{P}(Y)$, that is, for any element $x\in A$, you need to associate a subset of $Y$. The subset is chosen to be the singleton $\\{f(x)\\}$.
It is of course a well-defined function. The problem is to show that $g$ is one-to-one. However, since $f$ is one-to-one, we have $g(x)=g(x')\implies \\{f(x)\\}=\\{f(x')\\}\implies f(x)=f(x')\implies x=x'$.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "discrete mathematics, proof writing, proof explanation"
}
|
.net webservice with XElement return type
There is a way to make a webservice that returns a parameter of the type XElement? Now I'm working with XmlNode return type, but I want to get rid of using this old xml library.
I'm using this:
XDocument doc = new XDocument();
XElement xml = new XElement("produtos");
doc.Add(xml);
//...
var xmlDoc = new XmlDocument();
using (var xmlReader = doc.CreateReader())
{
xmlDoc.Load(xmlReader);
}
return xmlDoc;
I can't figure out why the webservice dont work with the XmlLinq lib
|
You should be able to do this:
[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
public XElement GetSomething()
{
return new XElement("Something");
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "c#, web services"
}
|
In python, how to transform the string slash to a escape sequence
I would like to know how to transform a string containing a Unicode ASCII descriptor into an actual Unicode character.
For example, how can I transform u"\\\u1234" to u"\u1234" ?
Thank you.
|
`decode('unicode-escape')`, for example:
>>> s = u'\\u03be'
>>> s
u'\\u03be'
>>> print s
\u03be
>>> e = s.decode('unicode-escape')
>>> e
u'\u03be'
>>> print e
ξ
This works, but it would be better to fix the root of the problem. Where does the string come from in the first place? Is it JSON? Some Python code?
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "python, escaping"
}
|
Who is the manufacturer of this shower faucet brand?
Does anyone know who is the manufacturer of this brand? I need it in order to buy the appropriate diverter.
 takes exactly 3 arguments (2 given)
Here is my code:
class Car:
carCount = 0
def __init__(self,brand,cost):
self.brand = brand
self.cost = cost
Car.carCount +=1
def displayCount(self):
print "Number of cars: %d" % Car.carCount
def __str__(self):
return 'Brand: %r Cost: %d' % (self.brand, self.cost)
def __del__(self):
class_name = self.__class__.__name__
print class_name,'destroyed'
def __add__(self,other):
return Car(self.cost+other.cost)
c=Car("Honda",10000)
d=Car("BMW",20000)
print c
a= c+d
|
The problem is that your `__init__` takes three arguments (including `self`) and you have supplied just two in your `__add__` method, hence the `TypeError` for `__init__`:
TypeError: __init__() takes exactly 3 arguments (2 given)
So in your `__add__` you should add (no pun intended) the `brand` argument:
def __add__(self, other):
return Car(self.brand+other.brand, self.cost+other.cost)
So you'll get a `"Honda BMW"` in this case which probably isn't what you want.
Either way, I'm sure you understand the error now and you'll fix it to get the functionality you want.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "python, operators, overloading, typeerror"
}
|
What does print()'s `flush` do?
There is a boolean optional argument to the `print()` function `flush` which defaults to False.
The documentation says it is to forcibly flush the stream.
I don't understand the concept of flushing. What is flushing here? What is flushing of stream?
|
Normally output to a file or the console is buffered, with text output at least until you print a newline. The flush makes sure that any output that is buffered goes to the destination.
I do use it e.g. when I make a user prompt like `Do you want to continue (Y/n):`, before getting the input.
This can be simulated (on Ubuntu 12.4 using Python 2.7):
from __future__ import print_function
import sys
from time import sleep
fp = sys.stdout
print('Do you want to continue (Y/n): ', end='')
# fp.flush()
sleep(5)
If you run this, you will see that the prompt string does not show up until the sleep ends and the program exits. If you uncomment the line with flush, you will see the prompt and then have to wait 5 seconds for the program to finish
|
stackexchange-stackoverflow
|
{
"answer_score": 45,
"question_score": 65,
"tags": "python, python 3.x"
}
|
Adding Git to /bin/bash
I have a cron and when it runs in the e-mail it states `/bin/bash: git command not found`
`git` works fine via terminal but how can I add it to `/bin/bash`?
|
Presumably the cron job runs under another user which has an empty profile. This means git is not in the path.
The easiest way to fix this i to use the full path to git in the cron job.
You can find the full path to git by the command:`which git`
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "linux, git, bash"
}
|
Inline date picker in iOS 7.1 SDK
I updated XCode yesterday (March 12 2014) with Version 5.1 (5B130a) and all of a sudden my Inline Date pickers stopped working properly.
!enter image description here
However, they remain working fine on my phone.
!enter image description here
This is how I implemented the date picker:
<
Any advice on what can be done?
|
You should set the `clipsToBounds` property of the cells to `YES`.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 3,
"tags": "ios, objective c, uidatepicker, ios7.1"
}
|
How Do I Wire My Nest Hello Doorbell With A Plug In Transformer?
I wired up a nest hello doorbell to my existing chime. It rings fine but lacks enough power to operate properly. That’s ok, it was a little expected.
Unfortunately, changing the old transformer is not an option due to its placement and some external factors.
Per hello instructions, I have bought a plug in transformer. This allows the hello to work without the chime.
What I would like to be able to do is power the hello with the plug in transformer and have the chime ring at the same time. Is this possible to achieve safely?
I have attached an image of my chime currently wired.textFieldDidBeginEditing:(UITextField *)textField {
//some code here...
NSInteger theTag = textField.tag; //I set the tag to 5 in IB
if (theTag == 5) {
//self.showDatePicker;
[textField resignFirstResponder];
}
}
The problem is, the keyboard never disappears. Another thing to note is that I have some other methods that move the view up and down based on the position of the textfield selected. Maybe that's messing up my Responder, but I just don't understand why the keyboard won't go away.
Also, I might just be doing this all wrong. I want this textField, when pressed, to hide the keyboard and show a date picker. Should this be in a different method?
|
If you're targeting iOS 3.2+, I'd suggest looking into `UITextField`'s `inputView` property. You can assign a custom view (i.e. a data picker) to be displayed when the text field becomes the first responder instead of the keyboard.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "iphone, objective c, keyboard"
}
|
How to select an object's class in Hibernate HQL?
How can I select an object's class in HQL? When I do the following:
select e.class, e.name from Entity e
Hibernate returns an Integer (e.g. [12, "name"]) instead of a class object. How can I return a Java class, or at least the class or entity name? Or, if this is not possible, how can I convert the 12 to a Java class?
For performance reasons, I can't query the full objects, i.e. I can't do
select e from Entity
Regards, Jochen
|
if you are hibernate4, you can use HQL function 'type()' to get entity type
select type(e), e.name from Entity e
If you are hibernate3, the session.iterate() return entity as HibernateProxy with id only, and you can get entity name & id from it without initializing.
Iterator iterator = session.createQuery("from Entity e").iterate();
while(iterator.hasNext()) {
HibernateProxy object = (HibernateProxy)iterator.next();
System.out.println(object.getHibernateLazyInitializer().getIdentifier());
System.out.println(object.getHibernateLazyInitializer().getEntityName());
}
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 7,
"tags": "hibernate, hql"
}
|
htaccess Apache to Litespeed
I'm using the following rewrite on my dev environment (Apache 2) and it works fine, I uploaded to my live environment (LiteSpeed) and it no longer works :(
Any ideas why given the following?
I'm using the "P" directive "mod_proxy" which my host doesn't support. How can I get around this?
<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond $1 !\.(gif|jpe?g|png)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^([^.]+)\.example\.com
RewriteRule ^(.*)$ [QSA,NC,P]
# Removes index.php
RewriteCond $1 !\.(gif|jpe?g|png)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>
|
I took a different approach to this problem. Apparently the mod_proxy method is inefficient so I solved it in PHP using some simple code to determine the subdomain and apply a conditional to check that $subdomain is not an empty string.
$url_parts = explode('.', str_replace('.example.com', '', $_SERVER['HTTP_HOST']));
$subdomain = ($url_parts[0] !== '') ? $url_parts[0] : '';
I'm just redirecting to the correct page once I know that there is a subdomain.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": ".htaccess, litespeed"
}
|
Clipping raster by mask layer polygon produces Nodata values in QGIS
I have a raster .tif Digital Elevation Model I am trying to clip to an irregular polygon using the GDAL\Clip raster by mask layer. I ticked 'Crop the extent of target dataset to extent of cutline'.
However, the output raster has the grid cells outside the mask layer cutline converted to 'Nodata' (apart from being annoying, it also retains the large file size of the source raster). I tried setting the destination nodata value to 'None', but this resulted in values of zero instead. (Please note that I do not know how to use the Commander/Python.) Any advice please?
processing.runalg("gdalogr:cliprasterbymasklayer","Input Raster", "Clip layer.shp",
"",False,True,False,5,4,75,6,1,False,0,False,"","Output raster")
|
This is normal behaviour, since raster data are _matrices_ defined by **extent** (rectangle by default) and cell size- resolution (each cell have same size) or number of columns and rows in extent.
|
stackexchange-gis
|
{
"answer_score": 4,
"question_score": 2,
"tags": "qgis, raster, gdal, dem, clip"
}
|
Where do we go after death?
I am very confused. When someone dies, people say "He's in a better place" or "He's in paradise inshallah". The thing is, I heard that humans live in the grave first until judgement day and then if they are good they go to paradise. Or after death do they go to paradise directly if they are good? If they stay in the grave, how is life there for the good and bad?
Thank you.
|
we are alive because of soul. When a person dies his body burried in grave and his soul remain there as mentioned **aalm e barzakh**
yeh it is true if they are good people there soul kept in place **"illeyeen "** and others soul kept in place **"sijyeen"**
so in that way you can say soul of good people kept seperate from others..on the day of Judgement soul placed back to body and after **hisab kitab** they will entered in Paradise. hope it clear many of your confusion
you can check out this too: **islamqa.info**
|
stackexchange-islam
|
{
"answer_score": 2,
"question_score": 2,
"tags": "jannah, death, day of judgement, grave"
}
|
mongodb.countDocuments is slow when result set is large even if index is used
`mongodb.countDocuments` is slow when result set is large
Test data on users collection:
* 10M documents with status `'active'`
* 100k documents with status `'inactive'`
The field `status` is indexed {status: 1}
`db.users.countDocuments({status: 'active'})` takes 2.91 sec `db.users.countDocuments({status: 'inactive'})` takes 0.018 sec
I understand that `countDocuments` uses an aggegation to find and count the results.
`estimatedDocumentCount`() does not work in this case because query filter is needed
Any suggestions for improvement?
|
Counting _seems_ like one of those things that should be cheap, but often isn't. Because mongo doesn't maintain a count of the number of documents that match certain criteria in its b-tree index, it needs to scan through the index counting documents as it goes. That means that counting 100x the documents will take 100x the time, and this is roughly what we see here -- `0.018 * 100 = 1.8s`.
To speed this up, you have a few options:
1. The active count is roughly `estimatedDocumentCount() - db.users.countDocuments({status: 'inactive'})`. Would this be accurate enough for your use case?
2. Alternatively, you can maintain a `counts` document in a separate collection that you keep in sync with the number of active/inactive documents that you have.
|
stackexchange-stackoverflow
|
{
"answer_score": 11,
"question_score": 7,
"tags": "mongodb"
}
|
How to use the range variable for the workbook which generated at the runtime
I am trying to access a excel workbook which is generated at the run time
I am using this code '
Dim w2 As Workbook
Dim r as range
Set w2 = Workbooks.Add
Set w2 = ActiveWorkbook
Set r = w2.Sheets("Sheet1").Range(Cells(5, 4), Cells(5, 4))
r.PasteSpecial Paste:=xlPasteValues'
Line no. 5 shows this error "application defined or object defined error"
can someone help me to fix this...
|
**1)** There is no need for this line:
Set w2 = ActiveWorkbook
because next line already returns new workbook object:
Set w2 = Workbooks.Add
**2)** You should fully qualify `Cells` object, i.e. you should specify to which workbook/sheet cells belongs:
Set r = w2.Sheets("Sheet1").Range(w2.Sheets("Sheet1").Cells(5, 4), w2.Sheets("Sheet1").Cells(5, 4))
or shorter:
With w2.Sheets("Sheet1")
Set r = .Range(.Cells(5, 4), .Cells(5, 4))
End With
But since your `Range` object conatins only single cell, you can simply use:
Set r = w2.Sheets("Sheet1").Cells(5, 4)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "excel, vba"
}
|
How to implement a MIDI driver for the Roland UM 4?
My Roland UM4 works only with 32-bit OS but it's good hardware and I think if I can get it working then I won't need to buy a new MIDI interface.
I've previously written assembler in C for an operating system but I've never written a device driver.
Could you tell whether this is a project that can be done for Windows 64 bit, and if so how it can be done? I have Visual Studio 2012 and I know C/C++ but, again, I have never written a driver before. Do I have to know x86 assembler to write the device driver or is C/C++ enough?
|
Since it's a USB device, I would have hoped it just used the standard USB MIDI class. But then it would have worked, so I guess it doesn't. Bummer.
To implement a driver, you're going to need to reverse-engineer the USB protocol between the 32-bit driver and the hardware.
This is not super-easy (I've not done it, but I have some knowledge). You must capture the traffic, which is typically done with a USB protocol analyzer, which are not cheap. I think it _can_ be done with a regular PC in the middle (perhaps running Linux) but that can get kind of complicated, too.
So, the limiting factor here is probably not your programming skills per se, but rather the fact the reverse-engineering is hard.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "c++, c, windows, driver, midi"
}
|
Confidence interval difference for the difference of two estimators
Let us assume that we havo two parameters $\alpha$ and $\beta$ and the two maximum likelihood estimators $\hat{\alpha}$ and $\hat{\beta}$. We have also the confidence interval of these estimators, standard error and the covariance is known. How can I derive the confidence interval of the difference $\hat{\alpha}$ - $\hat{\beta}$? I think there is a method called Delta method for this, but I'm not sure and I don't know well how it works. Thank you for anyone able to help me
|
Given MLEs $\hat{\alpha}$ and $\hat{\beta}$ and their corresponding standard errors, $\mbox{SE}[\hat{\alpha}]$ and $\mbox{SE}[\hat{\beta}]$, approximate 95% Wald-type CIs for $\alpha$ and $\beta$ can be obtained with $$\hat{\alpha} \pm 1.96 \mbox{SE}[\hat{\alpha}]$$ and $$\hat{\beta} \pm 1.96 \mbox{SE}[\hat{\beta}].$$ If you also know the covariance between $\hat{\alpha}$ and $\hat{\beta}$ (let's denote this $\mbox{Cov}[\hat{\alpha}, \hat{\beta}]$), then an approximate 95% Wald-type CI for $\alpha - \beta$ can be obtained with $$(\hat{\alpha} - \hat{\beta}) \pm 1.96 \sqrt{\mbox{SE}[\hat{\alpha}]^2 + \mbox{SE}[\hat{\beta}]^2 - 2\mbox{Cov}[\hat{\alpha}, \hat{\beta}]}.$$
|
stackexchange-stats
|
{
"answer_score": 3,
"question_score": 0,
"tags": "confidence interval, estimators"
}
|
Connecting and printing to a printer in Java
Is there an easy way in Java to do the following?
1. Connect to a printer (will be a local printer and the only printer connected to the machine).
2. Print pages that are 2 pages in 2 different printer trays.
3. Get the current print queue count, i.e. I have 100 items to print and 34 have been currently printed, the printer queue should now read 66.
|
Some quick hints:
* print from java: see A Basic Printing Program
* status of printing job: you might be able to get something useful by using a PrintJobListener:
> Implementations of this listener interface should be attached to a DocPrintJob to monitor the status of the printer job. These callback methods may be invoked on the thread processing the print job, or a service created notification thread. In either case the client should not perform lengthy processing in these callbacks.
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 11,
"tags": "java, printing"
}
|
How to extract individual Pipeline names from .gitlab-ci.yml file?
I have two pipelines in my gitlab.yml file. I want to extract the pipeline name individually in my python. I tried using the pyyamil package but it does not do anything specfically to every pipeline. Basically, code.py in SCAN1 pipeline should return 'SCAN1' and code.py in SCAN2 pipeline should return 'SCAN2'. I want to return a value which is specific to each pipeline to be used in the code
script SCAN1:
stage: test
tags:
- linux-default
script:
- bash exp.sh & python3 code.py
script SCAN2:
stage: test
tags:
- linux-default
script:
- bash exp.sh & python3 code.py
|
You can use predefined variables. Have a look at <
In your case you can use `CI_JOB_NAME`. It's just environment variable so in your python just get it by:
from os import getenv
job_name = getenv('CI_JOB_NAME')
print(job_name)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, gitlab"
}
|
Add $ symbol to column values
I want to add $ symbol to column values and convert the column values to western number system
**Dollars**
4255
25454
467834
**Expected Output:**
$ 4,255
$ 25,454
$ 467,834
**My Query:**
select ID, MAX(Date) Date, SUM(Dollars) Dollars, MAX(Funded) Funding from Application
Dollars is the int datatype and needs to be changed.
|
You can do something like that. Converting from `money` to `varchar` with style 1 adds thousand separator:
declare @value int = 4255
select '$ ' + replace(convert(varchar(100), convert(money, @value), 1), '.00', '')
-- output: $ 4,255
If you process the data from SQL Server in any application, formatting is much easier to do in the code though.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "sql, sql server"
}
|
In GWT, why image.setURL("/SimpleCaptcha.jpg") to refresh the image doesn't work in firefox?
I'm building a system to let user type in captcha, & user can refresh the image to get another captcha words. so I used this code to refresh image.
captchaImage.setUrl("/SimpleCaptcha.jpg");
it works fine in Chome, but not working in Firefox.
So is there any other simple way to refresh image that work in all Browsers in GWT?
|
It does nothing if your new URL is the same one as it was before. If you generate a new image with the same filename, an easy workaround is to make the URL unique so it forces the browser to reload:
captchaImage.setUrl("/SimpleCaptcha.jpg?" + System.currentTimeMillis());
This makes the URL say something like `"/SimpleCaptcha.jpg?89109801890180130189"`
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "image, gwt"
}
|
Alternative to PHP eval?
I have some code that is returned to my script in a variable. I need to execute it as PHP code but am nervous to use the `eval` function. Here is the code that is generated in an include file:
/include.php:
$preLoadFields .= '$2 = new KoolDatePicker("datepicker");
$2->id="field_2";
$2->scriptFolder = "/KoolPHP";
/main.php
eval($preLoadFields);
Even when I try to run it using `eval`, I get this error:
Parse error: syntax error, unexpected '2' (T_LNUMBER), expecting variable (T_VARIABLE) or '$'
Is there a better / safer way to do accomplish this? Thank you in advance!
|
Just don't let the include.php generate PHP code in a variable. But directly execute it.
$2 = new KoolDatePicker("datepicker");
$2->id="field_2";
$2->scriptFolder = "/KoolPHP";
If you are worried about HTML being generated and outputted to the screen. Then don't output it using `ob_start` `ob_get_contents` `ob_end_clean`:
ob_start();
$2 = new KoolDatePicker("datepicker");
$2->id="field_2";
$2->scriptFolder = "/KoolPHP";
$generated_html = ob_get_contents();
ob_end_clean();
Anything the piece of PHP will try to output to the screen will be buffered. Then later in your code use the `$generated_html` variable to output it wherever you want.
(You still need to fix the invalid variable name)
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "php, eval"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.