INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Easy way to rename a project in android
I have downloaded an Android project. To avoid name conflicts I want to move it from com.android.zzz to com.my.zzz. At the moment I'm using Ecplise with the standard android toolkit. Is there a better way to do the rename than to go manually through the files?
|
This is basic IDE refactoring.
Right click the package in Eclipse -> Refactor -> Rename.
You will probably want to check all the options that come up in the Rename dialog.
Another option would be to right click the class files in Eclipse -> Refactor -> Move.
|
stackexchange-stackoverflow
|
{
"answer_score": 39,
"question_score": 21,
"tags": "android, eclipse"
}
|
Как скопировать массив в динамический массив? (Си)
Есть массив `char str[] = "abcdef";`
И динамический массив: `char *dstr = (char*)malloc(sizeof(char) * N);`
Как скопировать `str[]` в `dstr[]` ?
P.S. Заранее извиняюсь, если вопрос глупый.
|
Есть 3 способа, нативное копирование области памяти, специальной функцией копирования строк, посимвольный перебор массива и запись в `dstr`.
memcpy(&str, &dstr, strlen(str) + 1); // Копирование области памяти
strcpy(dstr, str); // Специальная функция для строки
// Перебор массива циклом.
int strsize = strlen(str) + 1;
for(int i = 0; i < strsize ; i++)
{
dstr[i] = str[i];
}
Имейте ввиду, в обоих случаях вы должны быть уверены что размер `dstr` больше на `1` чем **длина** строки `str`.
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "c, массивы, указатели, malloc"
}
|
How to unscrew faucet nut with no room to rotate?
I need to remove a bottom mount sink faucet to replace a clogged cartridge. Unfortunately, there's no room to spin the faucet nut as it bumps into the edge of the sink. Any ideas?
 (k-1) * n `div` k
Is it possible to modify it and make it tail recursive?
|
Yes. There is a standard trick of using an accumulator to achieve tail recursion. In your case, you'll need two of them (or accumulate one rational number):
binom :: Int -> Int -> Int
binom = loop 1 1
where
loop rn rd _ 0 = rn `div` rd
loop _ _ 0 _ = 0
loop rn rd n k = loop (rn * n) (rd * k) (n-1) (k-1)
**Update:** For large binomial coefficients, better use `Integer` as `Int` can easily overflow. Moreover in the above simple implementation both numerator and denominator can grow much larger than the final result. One simple solution is to accumulate `Rational`, another would be to divide both by their gcd at every step (which AFAIK `Rational` does behind the scenes).
|
stackexchange-stackoverflow
|
{
"answer_score": 11,
"question_score": 4,
"tags": "haskell, recursion, tail recursion, binomial coefficients"
}
|
Discord bot fetching a random submission from a subreddit using praw (Python3)
Hey so basically I want to make it so my discord bot sends out a random submission from r/animemes when the user types out the command. I am very new to Python (and coding in general) and don't quite know how to do this. The code i've written currently sends out all 50 submissions at the same time but it does not pick out 1.
Here's my code:
@commands.command(aliases=['Animeme'])
async def animeme(self, ctx):
reddit = praw.Reddit.(client_id="XXXXX",
client_secret="XXXXX",
user_agent="XXXXX")
limit = random.randint(0, 50)
for submission in reddit.subreddit("animemes").hot(limit=limit):
await ctx.send(submission.url)
Thank you for your help =)
|
The PRAW documentation shows how to get a random post from a subreddit:
>
> submission = reddit.subreddit("AskReddit").random()
>
So, you can use this in your code as follows:
reddit = praw.Reddit.(client_id="XXXXX",
client_secret="XXXXX",
user_agent="XXXXX")
submission = reddit.subreddit("animemes").random()
await ctx.send(submission.url)
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "python 3.x, chatbot, discord.py, praw"
}
|
When applying location of a translated object with mirror modifyer the global axes are used
I really don't know how I archived this. Can anybody tell me how to get the mirror modifier to use local axes when applying the object's location?
.
You can create a new object (maybe an empty) and use it as new pivot point selecting its name in the mirror modifier "Mirror object" menu.
This empty can be moved and rotated along with the object, to get the mirroring performed on any desired local axes.
). Task splitting however seems wildly more complex. Since I don't think you can have two threads of the same program run on different machines, meaning you have to split up the work.
How though does one split up the work? I can see some stuff like rendering or video encoding just because you can tell each node to work on a different part of the video, but when you want to do things like calculate the 5 trillionth digit of pie, how would you split that up? Or even in science where you need to simulate weather or other resource intensive tasks?
In short, how do you split up tasks that aren't really designed for splitting up?
|
Not every task is suitable for parallel processing. Factoring is, but long division isn't. We use the term Parallel algorithm to describe tasks which are designed to be executed in parallel (potentially on multiple computers, or using multiple cores of a single computer).
|
stackexchange-softwareengineering
|
{
"answer_score": 4,
"question_score": 3,
"tags": "cloud computing, cluster"
}
|
Battlefield 3 last patch: weapons efficiency decreased?
Playing BF3 on XBOX360 after yesterday's patch, I noticed that my efficiency in killing enemies decreased.
It is not about aiming, I had a concrete sensation that every weapon is less effective than it was before the patch.
I was aware of the fact that USAS-12 was due to be nerfed (and indeed it has been, especially if you consider fragmentation ammo); now even if a shot hits an enemy in plain face at a distance slightly greater than extremely close range, that shot alone doesn't kill him. This is very different from USAS-12 previous behavior.
But after the patch it seems that using every weapon has increased its level of difficulty.
Am I having the right perception?
|
It seems that a good portion of the weapons have had _some_ change to them. You can check out the changes in the patch notes here: <
So to answer the question: it probably depends on which weapon/s you mostly use and get used against you. For example, the M16A4 has had its vertical recoil increased, but horizontal recoil decreased, while the M416 has not changed at all.
|
stackexchange-gaming
|
{
"answer_score": 5,
"question_score": 0,
"tags": "battlefield 3"
}
|
How to fill a df column with range of values of 2 columns from another df?
Df1
A B C1 C2 D E
a1 b1 2 4 d1 e1
a2 b2 1 2 d2 e2
Df2
A B C D E
a1 b1 2 d1 e1
a1 b1 3 d1 e1
a1 b1 4 d1 e1
a2 b2 1 d2 e2
a2 b2 2 d2 e2
How to make Df2 from Df1 in the fastest possible way? I tried using groupby and then within for loop used np.arange to fill Df2.C and then used pd.concat to make the final Df2. But this approach is very slow and doesn't seem very elegant and pythonic as well. Can somebody please help with this problem.
|
Try this:
df1.assign(C = [np.arange(s, e+1) for s, e in zip(df1['C1'], df1['C2'])])\
.explode('C')
Output:
A B C1 C2 D E C
0 a1 b1 2 4 d1 e1 2
0 a1 b1 2 4 d1 e1 3
0 a1 b1 2 4 d1 e1 4
1 a2 b2 1 2 d2 e2 1
1 a2 b2 1 2 d2 e2 2
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "python, pandas, dataframe"
}
|
How To Run a Script in WinSCP
I am using winSCP GUI to connect to linux terminal and then copy the files and other stuff.
_Now i have some scripts on the UNIX server,I am connected but how to run the script from the Win SCP._
what basically is needed is `sh scriptname.sh` through the WinSCP.Please let me know if anyone else found out how to do that.AS loging into putty and running the command is time taking for me. **WinSCP Custom Command option tried to click on Execute,but the error pops up like no such directory.**
Tried google but to the point information is not coming up.
|
Try this **sh "!"**
OR
First of all executing commands from WinSCP can be tricky and if you are able to run few commands also,there are restrictions which you can not do fro WinSCP and should have to ultimately take help of **PUTTY**.
Here is the link Integrate WinSCP with Putty which will help you integrate your WinSCP to Putty,so that when you open any server through WinSCP putty will automatically connect without even asking for the password.And then you can run you command,hope that wound be of any trouble to you.
Remember you can store the connection details in WinSCP and in just one click it will connect to the server on SCP and also on Putty.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 5,
"tags": "linux, shell, unix, winscp"
}
|
Can internal linking create excessive web server load?
SE sites allow tags chaining like this:
/questions/tagged/seo+google+search-engines+research+keywords
This site has more than 700 tags. If up to 5 tags can be chained, there are
700*700*700*700*700 = 168070000000000
links that google can crawl. Can it be harmful?
|
> Can internal linking create excessive web server load?
Not unless your server is already struggling - Googlebot (unlike many poorly-conceived spiders and some recursive downloading agents) throttles requests and even allows webmasters to specify how often Googlebot should visit pages via Google Webmaster Tools (if your server is already struggling).
> Can it be harmful?
Yes, because there are plenty of poorly-conceived spiders and recursive downloading agents out there which can bring your server to its knees if you've created interlinked quagmires (particularly so if these are resource-intensive dynamically-generated pages).
I am having a hard time seeing how your site's users benefit from this feature if there are hundreds of tags.
Wouldn't a site search feature be better-suited to users' needs?
Why is there a need to map up to five categories' union to a unique URI?
|
stackexchange-webmasters
|
{
"answer_score": 1,
"question_score": 0,
"tags": "web crawlers, load"
}
|
How to generate WCF proxy for .NET 4.0 from assembly in .NET 4.5 using svcutil?
I have written a server side application (system service) running WCF service host and client application, both in .net 4.5, using duplex net.tcp connection. Everything works fine (generating proxy on client side from server assembly using svcutil).
Now I get a request to transform client side application to .NET 4.0, to be able to run on Windows Embedded (XP based).
The problem is, I am not able to generate client proxy without async methods using `svcutil` for .NET 4.5, nor to generate proxy using `svcutil` for .NET 4.0, because server assembly is written in .NET 4.5.
Is there any solution for this situation?
|
I have found the solution. Because generating client proxy is two step process (generating metadata and generating client from metadata), I split these steps and used for each step different svcutil:
* used svcutil from .NET 4.5 to generate metadata
* used svcutil from .NET 4.0 to generate proxy from metadata
-
"C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\svcutil" "..\ServerApplication\ServerApplication\bin\Debug\ServerApplication.exe"
"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\svcutil" *.wsdl *.xsd /language:C# /out:ClientApplication\ServerApplicationClient.cs /noConfig
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": ".net, wcf, svcutil.exe"
}
|
From what horror film is this clip of a grey-skinned, clawed hand emerging from a tree root?
There are a lot of film clips used in the folk horror documentary, _Woodlands Dark And Days Bewitched: A History Of Folk Horror_ , and as far as I can tell, not all them are identified for the viewer.
Toward the end of the documentary, a few minutes into the sixth and final segment, "Folk Horror Revival," there were two such unidentified clips back-to-back that caught my eye.
I took photos of both from the TV screen. This one shows a grey-skinned, clawed hand emerging from a tree root:
.
From Wikipedia):
> _The Wretched_ is a 2019 American supernatural horror film written and directed by the Pierce Brothers. It stars John-Paul Howard, Piper Curda, Zarah Mahler, Kevin Bigley, Gabriela Quezada Bloomgarden, Richard Ellis, Blane Crockarell, Jamison Jones, and Azie Tesfai. The film follows a defiant teenage boy who faces off with an evil witch posing as the neighbor next door.
The shot in question is visible at around the 1:00 mark in the video below.
|
stackexchange-scifi
|
{
"answer_score": 5,
"question_score": 6,
"tags": "story identification, movie, horror, folklore"
}
|
how do you ignore non-test files with ava?
Can I ignore a setup or support folder so that ava doesn't try to run the files inside?
I have some common utility files used for mocking that should logically live inside the `test/` folder alongside tests but I don't want to run them as tests.
|
To ignore files prefix them with an underscore `_` or an exclamation mark `!`
* * *
In ava's documentation for configuration under the files bulletpoint it states:
> Files with an underscore prefix are ignored
And the documentation at the top also explicitly states:
> To ignore files, prefix the pattern with an `!` (exclamation mark).
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 5,
"tags": "javascript, unit testing, ava"
}
|
Definition of Fourier Transform on $\frac{2\pi}{L}\mathbb{Z}^{d}$
The usual inversion formula for the Fourier transform is: $$f(x) = \frac{1}{(2\pi)^{d}}\int_{\mathbb{R}^{d}}e^{ip\cdot x}\hat{f}(p)dp$$ What is the analogous formula when $p$ ranges in a infinite lattice $\frac{2\pi}{L}\mathbb{Z}^{d}$, where $L>1$ is fixed? I know the integral becomes a sum, but what about the pre-factor $(2\pi)^{-d}$?
|
The term $2 \pi$ will be included but it usually is inside the coefficients of the series. See this lecture.
<
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "real analysis, fourier analysis, fourier transform"
}
|
Do Not Track header
Does Stack Overflow honor the Do not track header... or is support going to be added later? ...(it doesn't seem to honor the header at the moment).
|
We do **not** do anything special for the **proposed** spec. There is no requirement anywhere that we implement anything. A bill may be passed in congress one day, who knows.
If this proposal gains tons of traction and the industry starts following this practice we will stop serving the quantcast and google analytics tracking if the header is present.
Keep in mind, the proposal says nothing about _internal_ tracking, its about 3rd parties. You will not be able to use this header to hide your tracks we will always continue storing every hit to our sites in our mega haproxy database.
|
stackexchange-meta
|
{
"answer_score": 4,
"question_score": 3,
"tags": "support, so engine"
}
|
Problem involving contraction mappings
Let $f_1, f_2, \dots f_n : \mathbb R \to \mathbb R$ be $n$ contraction mapings. Prove that there is a unique $(x_1, x_2, \dots, x_n) \in \mathbb R^n$ such that $x_1 = f_1(x_n)$ and $x_i = f_i(x_{i-1})$ for $i = 2, 3, \dots, n$.
So far I have proved this holds for $n = 2$, i.e., there is a unique $(x_1, x_2)\in \mathbb R^2$ such that $x_1 = f_1(x_2)$ and $x_2 = f_2(x_1)$. How can I generalize this result?
|
Composition of contractions is a contraction. Let $f=f_1\circ f_n \circ f_{n-1}...\circ f_2$. let $x_1$ be fixed point of this contraction (which exists by Contraction Mapping Theorem). Now define $x_i=f_i(x_{i-1})$ for $2 \leq i \leq n$. Verify that this defines $(x_1,x_2,..,x_n)$ satisfying the required property.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 1,
"tags": "real analysis"
}
|
Clear clipboard with xsel on Ubuntu 14.04
I'm trying to clear the clipboard from command line but it doesn't seem to work. Here goes what I'm doing:
Firstly, I put the string 'hello' in the clipboard and it works as expected:
echo hello|xsel -b
xsel -b
> hello
But when I'm trying to clear it up, it doesn't work because I'm still getting the string 'hello' when I ask for it:
xsel -bc
xsel -b
> hello
I've also tried with `xsel -c`, `xsel --clear`, `xsel -b -c`, ... but unsuccessfully. Any help?
I know that `echo |xsel -b` is a workaround but I would like to use just a command and would like also to understand the `--clear` option.
Thanks in advance!
|
You have to type `xsel -cb` first 'clear' then 'what to clear'
Works on Ubuntu 12.04.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "ubuntu, clipboard"
}
|
Differentiating and proving equation FM Pure
I am seriously unable to just prove this equation. I end up with x^3's always and am unable to proceed just after differentiating it. I tried thinking of binomial theorem but it would only help in decreasing the power more and more. So I am seriously out of ideas. Please share the compete answer! Thank you!(<
|
You can apply the product rule:
$$\left[x(1+x^3)^{-n}\right]'=1\cdot(1+x^3)^{-n}+x(-n)3x^2(1+x^3)^{-n-1}=$$
$$=(1+x^3)^{-n-1}\left[1+x^3-3nx^3\right]=\color{red}{(1+x^3)^{-n-1}\left[1+(1-3n)x^3\right]}$$
Or you can apply the quotient rule:
$$\left(\frac x{(1+x^3)^n}\right)'=\frac{1\cdot(1+x^3)^n-x\cdot3nx^2(1+x^3)^{n-1}}{(1+x^3)^{2n}}=$$
$$=\color{red}{\frac{1+x^3-3nx^3}{(1+x^3)^{n+1}}}$$
You can make sure both final expressions above are the same
**Added** Observe the right hand of the expression you were given is
$$-(3n-1)(1+x^3)^{-n}+3n(1+x^3)^{-n-1}=-\frac{3n-1}{(1+x^3)^n}+\frac{3n}{(1+x^3)^{n+1}}=$$
$$=\frac1{(1+x^3)^n}\left[-3n+1+\frac{3n}{1+x^3}\right]=\frac1{(1+x^3)^n}\left[\frac{(1-3n)x^3+1-3n+3n}{1+x^3}\right]=$$
$$=\frac{(1-3n)x^3+1}{(1+x^3)^{n+1}}$$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": -1,
"tags": "derivatives"
}
|
How to generate ASP.NET page every time when using master pages?
I'm moving an old VBScript web site over to ASP.NET, so I'm starting to use master pages instead of #includeing lots of other files with server side VBScript in them.
How can I stop the pages (as in the ones that are based on master pages) from being generated once and then stored? If I make a change to the master page (or any page based on them) those changes are not visible, because the web server is still giving out the previous versions.
|
It sounds like you have caching enabled, as normal behaviour without caching is to regenrate.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "asp.net, master pages"
}
|
IE errors on file download through .ashx file with caching turned off
I have a simple 'file download' generic handler which sets the response contenttype and headers before sending the file through the same response.
I also have Response.Cache.SetCacheability(HttpCacheability.server) set in the global.asax.
As I have noticed from various sources, Internet Explorer doesn't like this no-cache setting and gives an error when trying to download the file (requested site unavailable or cannot be found).
I thought maybe I could override this setting in the .ashx page, so I alter the response's cacheability setting to public. This did not solve the issue... removing the line from global.asax does solve the problem but obviously affects the whole site.
Is there a way of setting the cachability just for my generic handler?
Cheers :D
|
Can you just check whether the request is made to your generic handler and provide the appropriate cache settings depending on the result ? Something like this:
public void Application_OnPreRequestHandlerExecute(object sender, EventArgs e)
{
if (!HttpContext.Current.Request.Url.AbsolutePath.EndsWith("MyHandler.asxh", StringComparison.InvariantCultureIgnoreCase))
{
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.Server);
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "asp.net, internet explorer, caching, generic handler"
}
|
Android JSONReader no class found
I have an error with android development. In fact i try to parse a JSON flux with stringtree library. So i import the library in build path but i have this error when i launch my application : java.lang.NoClassDefFoundError: org.stringtree.json.JSONReader
Have you an idea ?
Best regards
|
It is an error with the latest `ADT tools`. You should place your jar inside a folder called `libs` not `lib` or something different.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "java, android"
}
|
Does the cond control structure allow multiple cases to be matched?
Is there something like a fallthrough feature for Elixir `cond` statements that would allow me to match for multiple cases? I want to do this to avoid repeating the same line of code. I also want to avoid a long chained logical OR `||` (disjunctive) statement in an `if` block. Right now, I'm repeating code like so:
cond do
top == nil -> eval(rest, [operator | output_queue], opstack)
top == "(" -> eval(rest, [operator | output_queue], opstack)
compare_to(operator, top) < 0 -> # keep popping
_-> # some catchall
end
|
> I also want to avoid a long chained logical OR `||` (disjunctive) statement in an `if` block.
You don't need to switch to `if` to make use of `||` \-- `cond`, unlike `case`, accepts any expression and you can join `top == nil` and `top == "("` with `||` to get what you want:
cond do
top == nil || top == "(" -> eval(rest, [operator | output_queue], opstack)
compare_to(operator, top) < 0 -> # keep popping
_-> # some catchall
end
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "elixir"
}
|
Django App build failing with Visual Studio 2017
I am currently getting this error when Using the Python->Publish feature in Visual Studio 2017 (Enterprise).
Severity Code Description Project File Line Suppression State
Error Cannot evaluate the item metadata "%(FullPath)". The item metadata "%(FullPath)" cannot be applied to the path "C:\"path to static files"/static
Illegal characters in path. C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Microsoft\VisualStudio\v15.0\Python Tools\Microsoft.PythonTools.Django.targets 105
It is coming from this line in Microsoft.PythonTools.Django.targets `<FilesForPackagingFromProject Include="@(_DjangoStaticFiles)" Condition="'%(FullPath)' != ''">`
It seems like the target files are having trouble gathering the static files.
Any help would be great! Thank you.
|
Was reluctant to change Python Tools files, but this change worked.
From:
<FilesForPackagingFromProject Include="@(_DjangoStaticFiles)" Condition="'%(FullPath)' != ''">
To:
<DestinationRelativePath>$([System.IO.Path]::Combine(`a`, `b`))</DestinationRelativePath>
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "python, django, visual studio 2017"
}
|
Pipelining listing and copying files
I have a server which is hosting my files which I can list with the following command:
xrdfs servername ls path/to/file
Similarly, I can copy file using the following command:
xrdcp server/path/to/file .
For, some reason the server doesn't support copying an entire folder(of course with -r option). So, I am trying to pipeline these two commands such a way that xrdfs will list the files and xrdcp will copy it to my destination. I tried the following line:
xrdfs servername ls path/to/file | xrdcp server/$() .
I get the following message:
Prepare: [ERROR] Invalid arguments
This is not very enlightening. Can somebody help with this?
|
Ok, I found an answer and I am posting here for reference
xrdfs servername ls path/to/file | while read -r out; do xrdcp server$out .; done
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "terminal, pipeline, ls, cp"
}
|
Command \pod with \frac argument dives too small parenthesis
If I use \pod or \pmod command with \frac argument the parenthesis around \frac is too small. For example
\documentclass{article}
\usepackage{amsmath}
\begin{document}
\[
a\equiv{b}\pod{\frac{a}{b}}
\]
\[
a\equiv{b}\pmod{\frac{a}{b}}
\]
\end{document}
gives
{}{#1}
\DeclarePairedDelimiterXPP\pmodX[1]{\if@display\mkern18mu\else\mkern8mu\fi}(){}{{\operator@font mod}\mkern6mu#1}
\makeatother
\begin{document}
\[
a\equiv{b}\pod{\frac{a}{b}}
\]
\[
a\equiv{b}\podX*{\frac{a}{b}}
\]
\[
a\equiv{b}\pmod{\frac{a}{b}}
\]
\[
a\equiv{b}\pmodX*{\frac{a}{b}}
\]
\end{document}
`), and each worker would use a child logger (`logging.GetLogger('Service.Worker1')`, `logging.GetLogger('Service.Worker2')`, etc.). However, I'm not sure if I have a way to differentiate worker processes.
Can I pass somehow different arguments for each new gunicorn worker?
Right now when I'm using the same logger in each worker (`logging.GetLogger('Service')` for all), I have no way to tell which worker created the log. This might not be an issue, but if I'm using a `logging.FileHandler` then separate processes may collide.
|
One workaround that I came up with is simply using `os.getpid()`, which will be unique in each worker. While this does the job and allows me to create unique names for logging, I'm still wondering if there is a better way.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 3,
"tags": "python, logging, gunicorn"
}
|
trying to port container to ARM
Im trying to port the following container to ARM. so i did the following
I downloaded the `Dockerfile` and the `entrypoint.sh` then i replaced the first line in `Dockerfile` with `FROM arm32v7/mono:4.8` and built it successfully.
but when i try to use the finished image i get the following error:
standard_init_linux.go:178: exec user process caused "no such file or directory"
Does this mean that it does not find the `entrypoint.sh` or something that it does not find something that `entrypoint.sh` tries to start?
Any ideas how to debug this?
|
`exec user process caused "no such file or directory"`
Linux/Unix Shell generally throws this error when either the file is not present physically at that location or if the file format is not in compliance to that of Linux/Unix.
There is a workaround for this situation on the docker forum.
You can try changing the file format from DOS to UNIX, all you need is `dos2unix` tool installed.
Use `dos2unix entrypoint.sh` and also change the permission to make it `-rwx-` for everyone.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "docker, mono, arm, dockerfile"
}
|
Delete query in mysql
I want to delete rows from multiple tables. I know the select query, but I need an exact delete query for all the columns that are defined below:
SELECT j.application_id,
j.first_name,
j.last_name,
c.description,
l.description,
p.description, " +
"j.email,
j.date_applied,
j.application_status,
j.dob, j.current_city, j.phone_mobile, j.phone_residence " +
"FROM jobapp.job_applications j,
jobapp.countries c,
jobapp.countries l ,
jobapp.job_locations p " +
"WHERE j.preferred_location = p.id
AND j.current_country = l.id
AND j.nationality = c.id "; //+
//"and application_status like ? and first_name like ? and last_name like ? and email like ?";
The query works fine using MySQL, but I need an delete query for the exact columns where the rows are get deleted...
|
delete statements are structured like:
DELETE FROM table WHERE condition.
you should replace condition with the primary key from you query above (if it is present) and reference each table one at a time.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -2,
"tags": "java, mysql, sql, sql delete"
}
|
five integer sequences
I want to find a satisfactory set of five legal increasing sequences of positive integers. A satisfactory set has the following two properties:
1) every integer appears in at least 2 of the five sequences
2) no pair of integers appears in more than 1 sequence.
A "legal"sequence is one where all numbers differ by at least 2. For example the sequence of all odd integers is legal.
I have several examples of satisfactory sets when the largest integer allowed is finite.
For example a satisfactory set when the upper limit is 9 is {1357, 369, 1468, 2479, 258}, and I have no counterexample. I would like to find either a counterexample for some finite limit, or a way of generating a satisfactory set when there is no upper limit. Does anybody know anything about this?
|
Call the five sequences $A,B,C,D,E$. Suppose $A$ contains the numbers $u,v,w,x,y$. Then $u$ must appear somewhere else; without loss of generality, $u$ is in $B$. Then $v$ must appear somewhere else, and it can't be in $B$, so say it's in $C$. $w$ must be somewhere else, and it can't be in $B$ or $C$, so say it's in $D$. Then $x$ must be somewhere else, and it can't be in $B,C,D$, so it's in $E$. Then $y$ must be somewhere else, but there's nowhere else it can be. So $A$ can't contain as many as five numbers. So all told the five sequences can't contain more than $20$ numbers. So the upper limit can't exceed $10$.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 2,
"tags": "sequences and series"
}
|
Why do linearly independent constraints correspond to a basic solution?
Let $P$ be a polyhedron in $[0,1]^n$ defined by the constraints $Ax \leq b$ for $A \in \mathbb{R}^{m \times n}$, $x \in \mathbb{R}^n$, and $b \in \mathbb{R}^m$.
In the solutions of an exercise, the following is mentioned:
"Since the first $n$ constraints are linearly independent, they correspond to a basic solution of the system which, a priori, may be feasible or infeasible. This solution is obtained by replacing inequalities with equalities and computing the unique solution of this linear system."
So I am quite confused about this:
1. Why does "linear independent constraints" imply that "basic solution"?
2. Is a basic solution not always feasible?
|
1) Linearly independant constraints define linearly independant hyperplanes at equality ($Ax=b$ for the lines concerned), the intersection of which is a point (or a vector, depending on your way of looking at this).
2) You have no guarantee that this point will satisfy all the other constraints.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 0,
"tags": "linear programming"
}
|
Animating only part of a UIView drawn context?
I am drawing some text and images to a view in the "DrawRect" method. I wish to understand :
1. does my drawings are separated objects?
2. i know how to animate UIViews but how do i reach one of them so i can animate his properties ?
thanks
shani
|
O.k
if any one wants to know the answer. you can not animate drawn text or objects unless you draw it to CALayer.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "iphone, ios, uiview, drawing"
}
|
Differences between C++ string == and compare()?
I just read some recommendations on using
std::string s = get_string();
std::string t = another_string();
if( !s.compare(t) )
{
instead of
if( s == t )
{
I'm almost always using the last one because I'm used to it and it feels natural, more readable. I didn't even know that there was a separate comparison function. To be more precise, I thought == would call compare().
**What are the differences? In which contexts should one way be favored to the other?**
I'm considering only the cases where I need to know if a string is the same value as another string.
|
This is what the standard has to say about `operator==`
> **21.4.8.2 operator==**
>
>
> template<class charT, class traits, class Allocator>
> bool operator==(const basic_string<charT,traits,Allocator>& lhs,
> const basic_string<charT,traits,Allocator>& rhs) noexcept;
>
>
> Returns: lhs.compare(rhs) == 0.
Seems like there isn't much of a difference!
|
stackexchange-stackoverflow
|
{
"answer_score": 554,
"question_score": 468,
"tags": "c++, string"
}
|
Creating task in feed
From salesforce help we can create task in feed.But I don't see an option to create it.Can someone help me.
|
Check Chatter is enabled, and then that Global Publisher Actions are enabled - I think they are what the help post is referring to
|
stackexchange-salesforce
|
{
"answer_score": 3,
"question_score": 1,
"tags": "chatter, tasks, activities"
}
|
$\mbox{Im}(A^*S^{1/2})\subseteq \mbox{Im}(S^{1/2}) \Leftrightarrow \exists \,M>0;\;\|S^{1/2}Ay\| \leq M \|S^{1/2}y\| ,\;\forall y \in E\;?$
Let $E$ be a complex Hilbert space and $\mathcal{L}(E)$ be the algebra of all bounded linear operators on $E$.
> If $S\in \mathcal{L}(E)^+$ and $A\in \mathcal{L}(E)$, why the following equivalence holds $$\mbox{Im}(A^*S^{1/2})\subseteq \mbox{Im}(S^{1/2}) \Leftrightarrow \exists \,M>0;\;\|S^{1/2}Ay\| \leq M \|S^{1/2}y\| ,\;\forall y \in E\;?$$
Thank you everyone !!!
|
It's just an application to following Douglas's theorem
> Let $P,Q\in \mathcal{L}(E)$, then $$\mbox{Im}(P)\subset \mbox{Im}(Q)\Longleftrightarrow \exists M>0\,; PP^*\leq M QQ^*.$$
So, $$\mbox{Im}(A^*S^{1/2})\subseteq \mbox{Im}(S^{1/2}) \Leftrightarrow \exists M>0;\;A^*SA\leq M S$$ Hence, $$\mbox{Im}(A^*S)\subseteq \mbox{Im}(S) \Leftrightarrow \exists M>0;\;\|S^{1/2}Ay\| \leq M \|S^{1/2}y\| ,\;\forall y \in E.$$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "functional analysis"
}
|
Powershell to find registry key and delete it
I have created a small powershell script to find where registry exist or not. It it exist, then use command REG DELETE to delete it. But after run it successful in the first time, I check regedit and see it was delete yet. But if I try to run script again, it still return that it found a registry key was deleted before.
$a = Test-Path -Path 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{23170F69-40C1-2702-1604-000001000000}'
if ($a = "True")
{
echo "Found!"
REG DELETE "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{23170F69-40C1-2702-1604-000001000000}"
}
else
{
echo "Not found!"
}
|
The Problem is with your if-clause.
In the expression you assign the variable `$a` the value "True" instead of checking if `$a` equals "True". In that case the if-clause only checks if the assignment was successful which should always be the case.
Since Test-Path returns a boolean you could check like this:
if($a){
#$a = true
} else {
#a = false
}
If you want to make it more clearly readable you could also do
if($a -eq $true){
#$a = true
} else {
#a = false
}
Here is a link to the documentation regarding comparison operators in powershell: Link
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 1,
"tags": "powershell"
}
|
Program crashes when I try to add contents of a class to on array
I am trying to add a class to an array and I get **Exception in thread "main" java.lang.NullPointerException** in my `addAstronaut` class.
package gov.nasa.spacevehicles;
import gov.nasa.personnel.Astronaut;
public class SpaceStation {
//private members
private String name;
private double stationWeight;
private double altitude;
private Object[] Astronauts;
private int totalAstronauts;
//overloaded constructor
public SpaceStation(String name, double weight) {
int altitude = 0;
int totalAstronauts = 0;
}
//method
public void addAstronaut(String name, double height, double weight) {
Astronauts[0] = new Astronaut(); // Exception in thread
Astronauts[1] = new Astronaut();
Astronauts[2] = new Astronaut();
stationWeight = stationWeight + weight;
}
|
You need to initialize the `Astronauts` array. Try something like:
Astronauts = new Object[10];
in the constructor for `SpaceStation`, take the size of the array as an input to that constructor, or use an `ArrayList` for variable size lists.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "java"
}
|
Meta tags with HTML special character codes?
This question is regarding best practices on SEO development meta tag filling.
A name written in the Latin or the Cyrillic alphabet has certain special characters, such as the ccedil `C`, for example.
**When populating meta tags and other SEO assets in a page** , what should be used, the HTML character code (for the given example: `ç`), the actual character or another character that looks close (using a `C` for the given example)?
|
It depends on the character set used on your page. I would always try to use UTF-8 when building a webpage. That would mean that the page would have the following header:
Content-Type: text/html; charset=UTF-8
In that case, it is fine to use the actual characters anywhere in the page, including in the meta tags:
<meta name=description content="My name is совестью">
If your page were in a character set that does not support all unicode characters such as ISO-8859-1, then you would have to fall back to using character entities like `ç`. If possible, it would be better to use UTF-8 because the character entities increase the page size quite a bit if they are heavily used.
You should never have to substitute other characters that look similar. Search engines today are Unicode aware. They should have no problem understanding words in any alphabet that are placed into meta descriptions.
|
stackexchange-webmasters
|
{
"answer_score": 4,
"question_score": 3,
"tags": "seo, html, meta tags"
}
|
SQL Server alternative for the following function in Oracle SQL
**Intro**
Consider the following @string ( '4533-32424-324', '212-323213-21223', 'FSE24-2313', '432D232')
In Oracle SQL, we just use `REGEXP_SUBSTR(@STRING, '[^-]+')` to get anything before the first '-' occurrence.
The output I get in Oracle is `4533, 212, FSE24, 432D232` which is correct.
DBFIDDLE for Oracle is here with output desired:
**Question**
I am trying to do this in SQL Server, and I get BLANK not a NULL value but BLANK if there is no '-' occurrence.
This is the statement I use in SQL Server:
SUBSTRING (@STRING, 0, CHARINDEX('-', @STRING))
|
To get the value even when there is no hyphen, add that to the search string:
select substring(@STRING, 1, CHARINDEX('-', @STRING + '-') - 1)
Oracle treats the empty string and `NULL` as the same thing -- which violates the standard and is different from other databases. An empty string is appropriate if `@STRING` starts with a hyphen. If you want to convert this to `NULL`, use `NULLIF()`:
select nullif(substring(@STRING, 1, CHARINDEX('-', @STRING + '-') - 1), '')
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": -1,
"tags": "sql, sql server, string, oracle"
}
|
Trying to access an object with a vector iterator
I'm new to iterators and I'm facing a problem.
This is a part of code where I create a vector and push some pointers to objects:
vector<MyClass*> MyVector;
MyVector.push_back(new object);
MyVector.push_back(new object);
MyVector.push_back(new object);
vector<MyClass*>::iterator temp;
temp = MyVector.end(); //because I want to use a function for the last one
Sum += temp->get_num(); //function that returns an object member
By this I want to achieve getting and summing some numbers that are stored inside objects. But as it seems it won't compile.
The error is the following.
> 240 27 ~\test.cpp [Error] request for member 'get_num' in '* temp.__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator-> >()', which is of pointer type 'MyClass*' (maybe you meant to use '->' ?)
|
You should first dereference the pointer, before using the MyClass object.
Second, you should not dereference the end iterator (<
Third, the compiler should have warned you about an expected initializer before '+=' token.
double sum = 0.0;
sum += (*temp)->get_num();
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -9,
"tags": "c++"
}
|
Converting a timestamp to a unix_timestamp in Postgres
I need to convert a timestamp to a unix_timestamp in Postgres.
The timestamp being in the following format: 2019-05-09 11:40:01
Thanks
|
Use `extract(epoch from . . . )`:
select extract(epoch from '2019-05-09 11:40:01'::timestamp)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "sql, postgresql, unix timestamp"
}
|
Is there any difference between "it's dead to me" and "it's dead for me?"
I read iTunes Is Dead to Me and was curious if there is any difference between saying "iTunes is dead _to_ me" and "iTunes is dead _for_ me?"
|
> "Dead to me" is an idiom. It's an extreme rejection on the order of, "You're no son of mine".
>
> "Dead for me" is not idiomatic and could be easily taken to mean you can't get iTunes to work.
So while a literal reading might see them as the same, in common usage they aren't.
|
stackexchange-english
|
{
"answer_score": 7,
"question_score": 1,
"tags": "word choice, differences"
}
|
c# private boolean error inside method
Sorry for the noobish question and there is probably a very easy fix to this, but I am making an application and I am trying to return a boolean to be used in another method when a checkbox is ticked. Though here I receive an error after the first `{` saying `} expected`. Thanks in advance, P
private void CheckImgur_Checked(object sender, RoutedEventArgs e)
{
private bool imgurChecked = true;
}
|
> I am trying to return a boolean to be used in another method
You can't return a value from an event handler. it's return type is void.
It seems like you meant to assign the value into some field of the class itself.
class MyTerrificClass
{
private bool imgurChecked;
private void CheckImgur_Checked(object sender, RoutedEventArgs e)
{
this.imgurChecked = true;
}
private void SomeOtherMethod()
{
// Use this.imgurChecked somewhere
}
}
And in any case local variable doesn't have an access (private/public) modifier.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#"
}
|
How can I get mouse location in javascript?
I am working recently with a js game which requires the _mouse position_ to change the _background color_ , I have tried with
`event.clientX, event.clientY` and `event.pageX , event.pageY`
and now it had became:-
function l(){
let x = event.pageX ;
let y = event.pageY;
document.bgColor = 'rgb($(x),$(y),$((x/2+y/2))'
};
document.body.addEventListener('mousemove',l());
but ,still it gives error,
uncaught TypeError: Cannot read property 'pageX' of undefined
If anyone solves my problem, a Great Thanks for him in advance Have a good time :-)
|
Try this:
var movementFunction = function (event) {
console.log(event.pageX, event.pageY);
let x = event.pageX ;
let y = event.pageY;
document.bgColor = `rgb(${x}, ${y}, ${(x/2+y/2)}`
}
document.body.addEventListener('mousemove', movementFunction);
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, dom, addeventlistener"
}
|
How can I close this message that looks like dialog?

The example image is a low-battery warning image but what I want to remove is the battery temperature warning message.
I'd like to use the java code to detect that message and close it.
|
If your activity is on the screen then whenever a new dialog comes up, you receive a callback onWindowsFocusChanges(boolean)
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (! hasFocus) {
Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
sendBroadcast(intent);
}
}
<
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "android, dialog, system, broadcast, battery"
}
|
How can i change date format(sed command)
I have log file, and here is output:
2014109 13:42:17;10.8.0.6;/home/spy/www/index.html;13
yearmonthday
I need to change date format -> `2014109` to `20141009`.
I change `Oct` format to `10`, using sed:
sed -i 's/Oct/10/g;
How can i use sed for day format?
|
If the first field is only 7 digits, insert a zero before the last digit:
sed -r -i 's/^([0-9]{6})([0-9])\b/\10\2/'
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "linux, bash, sed"
}
|
Export Members in AzureAD Group
Running script to export all Members in a specific AzureAD Group, but only get half and not all users.
I verified that there are members in Azure Portal, but export only gives me half
This is the script I ran:
Get-AzureADgroupmember -objectid "xxxxxxxxxxxxxxxxxxxxxx" | get-azureaduser | Export-Csv -path C:\temp\memberexport.csv
Any reason on why this is exporting only half and not all users in group?
Thank you,
|
When you don't specify `-All` as well as `-Top` optional parameters, then `Get-AzureADGroupMember` command may return you only a default number of records (like say 100. I'm not sure on this exact number).
So if you want all the members, try to specify that explicitly by using `-All` parameter. Example below:
Get-AzureADgroupmember -objectid "xxxxxxxxxxxxxxxxxxxxxx" -All $true | get-azureaduser | Export-Csv -path C:\temp\memberexport.csv
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "azure active directory, azure powershell"
}
|
Capture network traffic through proxy with Appium and C#
I have spent a lot of time browsing for a solution to my problem: I am testing an Android app and will be testing the same app on iOS too very soon, using Appium and C#. My app receives response from the server, which I would want to go through a proxy so that I can sniff as part of my NUnit test to ensure that the response returned from the server is correct and compare it with the response I receive on the app (through SDK).
I understand I can use BrowserMob (using Automated Tester C# library) to do this on desktop browsers using Selenium but I cant find any info for doing this using Appium. 1\. Firstly, is it possible to sniff network traffic going to the mobile app? 2\. Are there any other possibilities that I should consider to achieve my goal?
I want the response to pass through the proxy so that I can assert my tests at run time. Please help/suggest.
|
I was able to do this using FiddlerCore library. A lot of usage documentation can be found here: Rick Stahl's web log
Configured fiddlerCore to constantly listen on port 8888 and loop back address and starts running when my test is started and interecepts the traffic going to or coming from the server.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 2,
"tags": "c#, android, proxy, appium, browsermob"
}
|
Do any natural languages have phrase-coordinators that surround their coordinands?
For those who came in late, there are such things as discontinuous morphemes, i.e. single morphemes that are interrupted by other morphemes. Note this example from this SIL link:
<
"A circumfix surrounding a root from Tuwali Ifugao (Philippines):
baddang: root ‘help’v. ka--an: circumfix ‘NOMR’
kabaddangan: word ‘helpfulness’"
My question is, do any natural languages have discontinuous coordinators that surround coordinated phrases? For example, are there coordinators that work like the ones in this nonce example?
"Bob and Carol and Ted and Alice" = "and1 Bob Carol Ted Alice and2"
"my money or my life" = or1 my money my life or2"
"the tall man and the suspicious dog" = and1 tall man suspicious dog and2"
|
Short answer: no. Slightly longer answer: not that we know of. The closest you can get is polysyndetic coordination, which follows the pattern "and A and B". Note that this isn't really circumfixation, it's just each conjunct being preceded by its own instance of "and". A nice example of this is Brad Pitt's speech in _Ingloriuous Basterds_ :
> And the Germans will not be able to help themselves from imagining the cruelty their brothers endured at our hands, and our boot heels, and the edge of our knives. And the Germans will be sickened by us. And the Germans will talk about us. And the Germans will fear us. And when the Germans close their eyes at night, and their subconscious tortures them for the evil they’ve done, it will be with thoughts of us that it tortures them with.
|
stackexchange-linguistics
|
{
"answer_score": 2,
"question_score": 4,
"tags": "syntax, morphology, coordination"
}
|
how to assign elements of an excel file data to a 2D matrix in Python?
I want to use the data in an excel sheet as a 2D matrix, but though iterating the extracted data I faced some errors.
I want to load a dataset from excel to python code. I used xlrd library, thought after iterating through the elements, it results an array. While I expected to have a 2-D matrix.
import xlrd
workbook = xlrd.open_workbook('test1.xlsx')
sheet = workbook.sheet_by_index(0)
N =sheet.nrows
M =sheet.ncols
mat_d = [ [0] * N for _ in range(M)]
mat=[]
for i in range(N):
for j in range(M):
mat.append(sheet.cell(i, j).value)
k = 0
for i in range(N):
for j in range(M):
mat_d[i][j]= mat[k]
k += 1
The code gives me the correct answer here,mat_d[1][1] = mat[79], though when I want to iterate it in a for loop it ends up an error: IndexError: list index out of range
|
import os
import csv
data = []
with open(os.path.join(sys.path[0], file), newline='') as dataset:
reader = csv.reader(dataset)
for row in reader:
rowlist = []
for numeric_string in row:
value = int(numeric_string)
rowlist.append(value)
data.append(rowlist)
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "python, excel, python 3.x, xlrd"
}
|
Beeswarm with logarithmic X axis
I am trying to plot a "beeswarm" which is essentially a single-dimensional scatterplot
library(beeswarm)
data(breast)
beeswarm(breast$time_survival,horizontal=TRUE)
What I want to achieve is logarithmic transformation of the X axis.
Obviously, I can do `beeswarm(log(breast$time_survival),horizontal=TRUE,method="hex")` but it plots logarithmically transformed data and X axis no longer reperesents survival time numerically. Is there a way to directly affect the X axis? In regular scatterplot, I would do `plot(breast$time_survival,log="x")` but not sure how to behave with `beeswarm`
|
option for beeswarm is log=TRUE, not log="x"
library(beeswarm)
data(breast)
beeswarm(breast$time_survival,horizontal=TRUE, log=T)
.str.contains('LIMITED')) |
(df['NAME'].str.upper().str.contains('INC')) |
(df['NAME'].str.upper().str.contains('CORP'))
They are all linked with an `or` condition and if any of them is true, the name is the name of a company rather than a person.
But to me this doesn't seem very elegant. Is there a way to check a pandas string column for "does the string in this column contain any of the substrings in the following list" `['LIMITED', 'INC', 'CORP']`.
I found the pandas.DataFrame.isin function, but this is only working for entire strings, not for my substrings.
|
You can use regex, where '|' is an "or" in regular expressions:
l = ['LIMITED','INC','CORP']
regstr = '|'.join(l)
df['NAME'].str.upper().str.contains(regstr)
MVCE:
In [1]: import pandas as pd
In [2]: df = pd.DataFrame({'NAME':['Baby CORP.','Baby','Baby INC.','Baby LIMITED
...: ']})
In [3]: df
Out[3]:
NAME
0 Baby CORP.
1 Baby
2 Baby INC.
3 Baby LIMITED
In [4]: l = ['LIMITED','INC','CORP']
...: regstr = '|'.join(l)
...: df['NAME'].str.upper().str.contains(regstr)
...:
Out[4]:
0 True
1 False
2 True
3 True
Name: NAME, dtype: bool
In [5]: regstr
Out[5]: 'LIMITED|INC|CORP'
|
stackexchange-stackoverflow
|
{
"answer_score": 12,
"question_score": 10,
"tags": "python, pandas, select, substring"
}
|
Is this a valid way of solving modular equations?
Some of the exercises in my abstract algebra textbook involve solving congruence equations, for example $$5x \equiv 1 \pmod 6$$ I convert that to a linear equation by rewriting $$x = \frac{k6+1}{5} = k + \frac{k+1}{5}$$ The solution for $k$ is obvious, and an x comes up pretty quick.
Since I only have the book, I was wondering if this is a valid method of solving these types of equations, i.e. are there any flaws to it. Thanks
|
What you want to do is find the inverse of $5$ modulo $6$. Modulo $6$ there are only $6$ elements, namely the equivalence classes of $0,1,2,3,4$ and $5$. In this case since $6$ is such a small number you can just try them out and notice that $5 \cdot 5 = 25 \equiv 1 \pmod 6$ so that $5x \equiv 1$ implies $5 \cdot 5x \equiv 5$, hence $x \equiv 5 \pmod 6$ is the unique solution to this equation.
In general, to solve a linear equation of the type $ax \equiv b \pmod c$, you want to find $k \in \mathbb Z$ such that $ax - b = kc$, which means $ax - kc = b$. This is a question which is easily answered by the Euclidean algorithm ; feel free to google about that, the information is out there. This algorithm is well-documented.
Hope that helps,
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 3,
"tags": "abstract algebra, modular arithmetic, solution verification"
}
|
PHP function working differently for return and echo. Why?
By using the following class:
class SafeGuardInput{
public $form;
public function __construct($form)
{
$this->form=$form;
$trimmed=trim($form);
$specialchar=htmlspecialchars($trimmed);
$finaloutput=stripslashes($specialchar);
echo $finaloutput;
}
public function __destruct()
{
unset($finaloutput);
}
}
and Calling the function, by the following code, it works fine.
<?php
require('source/class.php');
$target="<script></script><br/>";
$forminput=new SafeGuardInput($target);
?>
But if in the SafeGuardInput class if I replace **echo $finaloutput;** with **return $finaloutput;** and then **echo $forminput;** on the index.php page. It DOES NOT WORK. Please provide a solution.
|
You can't return anything from a constructor. The `new` keyword always causes the newly created object to be assigned to the variable on the left side of the statement. So the variable you've used is already taken. Once you remember that, you quickly realise there is nowhere to put anything else that would be returned from the constructor!
A valid approach would be to write a function which will output the data when requested:
class SafeGuardInput{
public $form;
public function __construct($form)
{
$this->form=$form;
}
public function getFinalOutput()
{
$trimmed = trim($this->form);
$specialchar = htmlspecialchars($trimmed);
$finaloutput = stripslashes($specialchar);
return $finaloutput;
}
}
Then you can call it like in the normal way like this:
$obj = new SafeGuardInput($target);
echo $obj->getFinalOutput();
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "php, function, return, echo"
}
|
Merge common objects in array and add frequency
I have an array :
[
{
"id": "#1",
"quantity": 2
},
{
"id": "#2",
"quantity": 1
},
{
"id": "#3",
"quantity": 1
},
{
"id": "#1",
"quantity": 2
},
{
"id": "#2",
"quantity": 1
},
{
"id": "#3",
"quantity": 1
}
]
I want the result to look like
[
{
"id": "#1",
"quantity": 4
},
{
"id": "#2",
"quantity": 2
},
{
"id": "#3",
"quantity": 2
}
]
Basically combine the objects with same ID, and add up the quantity. I can do this using 2 for loops. But is there a more optimized way to solve this in Javascript?
|
Something like this will do the job:
function transform(a) {
const seen = {};
const ret = [];
a.forEach(o => {
const id = o.id;
seen[id] = (seen[id] || 0) + o.quantity;
});
for (let key in seen) {
ret.push({
id: key,
quantity: seen[key]
});
}
return ret;
}
console.log(transform([{
"id": "#1",
"quantity": 2
}, {
"id": "#2",
"quantity": 1
}, {
"id": "#3",
"quantity": 1
}, {
"id": "#1",
"quantity": 2
}, {
"id": "#2",
"quantity": 1
}, {
"id": "#3",
"quantity": 1
}]));
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, arrays"
}
|
C# method overloading with params
Please Help!
What am I doing wrong?
static void f1(Color color, params float[] f)
{
System.Console.WriteLine("Here is f1 for float");
}
static void f1(Color color, params int[] f)
{
System.Console.WriteLine("Here is f1 for int");
}
static void Main()
{
f1(null,0);
}
I can't invoke `f1(null,0);` I get compile time error.
How this staff can be overcome assuming I indeed need those method signatures?
**EDIT:** As for Compile-tme error - ReSharper complains:
_Cannot resolve method f1(null,int), candidates are:_
_void f1(Syste.Drawing.Color, params[] float)_
_void f1(Syste.Drawing.Color, params[] int)_
|
I think the problem is you are passing null for Color which might be upsetting the function, either change that to `Color?` (since it is a struct) or pass a valid Color value
static void f1(Color? color, params float[] f)
static void f1(Color? color, params int[] f)
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "c#, parameters, overloading"
}
|
PHP preg_replace pattern inside curly brackets, but ignoring "flags" inside square brackets
Given the following string:
Tags are inside {{ curvy }} brackets, but may also include {{ [f] flags }} in square brackets
I need to return just the "variables" \- in this case "curvy" and "flags", while ignoring the flags.
I have 2 seperate regexs to achieve this, but I need the original string to remain unchanged, so I need to find a way to merge into a single regex which finds the variables, but ignores the flags.
Here are the two regexes I have now:
Grabs variables in {{ var }} --> `~\{\{\s+(.*?)\s+\}\}~`
Grabs flags [f] OR [fdc] --> `~/\[.*?\]/~`
The first regex works, but returns the variables with the flag.
|
You may use
\{\{(?:\s*\[[^][{}]*])?\s*(.*?)\s*\}\}
See the regex demo
**Details**
* `\{\{` \- `{{` substring
* `(?:\s*\[[^][{}]*])?` \- an optional non-captuiring group matching 0+ whitespaces, `[`, any 0 or more chars other than `[`, `]`, `{` and `}` and then `]`
* `\s*` \- 0+ whitespaces
* `(.*?)` \- Group 1 capturing any zero or more chars other than line break chars as few as possible
* `\s*` \- 0+ whitespaces
* `\}\}` \- `}}` substring
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "php, regex, brackets"
}
|
useBean setProperty not behaving as advertised
I'm trying to use "auto wiring" between request attributes and a bean with
<jsp:useBean id="cib" class="(fqn).CarInfoWebBean" scope="request">
<jsp:setProperty name="cib" property="*" /></jsp:useBean>
but the setter of the (only) property doesn't get called.
The bean property is of type long, and the property name and attribute name are matching.
The strange thing is that
<jsp:setProperty name="cib" property="carId" param="carId"/>
isn't working either, but
<jsp:setProperty name="cib" property="carId" value="${carId}"/>
is working just fine.
|
It turns out that param attribute and property(*) can get only request parameters, not request attributes...
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "java, jsp tags, javabeans"
}
|
How to display three grid in netzke
How to display three grid in netzke.
The tables I want display are,
Boss => Clerk => Task
has_many relation between Boss and Clerk and also, has_many relation between Clerk and Task.
Please help me..
Thanks.
|
You can check the following tutorial as a starting point: <
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "ruby on rails, ruby, extjs, netzke"
}
|
How to hide a div when the mouse is clicked outside the div
I've a HTML div and I want to hide it whenever the user clicks on the page anywhere outside the div. Which clicking on which element should I trigger the onclick event??
|
Assuming you're using the latest jQuery, v1.4.4:
$(<the div you want hidden>).click(false); //stop click event from bubbling up to the document
$(document).one('click', function(){
$(<the div you want hidden>).hide(); //which will hide the div
});
In other words, this code says 'hide the div if you click on this page, unless you click on the div'.
Re: Toggle button
Then you'll have something like:
$('button').click(function(){
$('div').toggle();
});
$('div').click(false);
$(document).click(function(){
$('div').hide();
//reset the toggle state, e.g.
$('button').removeClass('selected');
});
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 3,
"tags": "javascript, jquery, jquery ui"
}
|
Is HTTP POST insecure?
Is it possible to perform a MITM attack or even bruteforce a HTTP POST? If so how does one perform an attack and how can a developer protect his/her site from such an attack?
|
**Is it possible to perform MITM on HTTP POST?**
HTTP is not encrypted, so if you "get in the middle" you can read the communication and modify it. You can get in the middle by e.g. hacking a router or cutting a cable. Your ISP is already in the middle and can read your HTTP communication.
This is true for all HTTP methods - POST, GET, etc.
**Is it possible to brute-force HTTP POST?**
Since HTTP is not encrypted there is nothing to brute force.
**How do you protect your site?**
Use HTTPS (that is, HTTP with TLS). If you do it right, a MITM can not read or modify the traffic, and the cryptography can not be brute forced.
|
stackexchange-security
|
{
"answer_score": 7,
"question_score": 0,
"tags": "http, man in the middle, brute force"
}
|
create a UIModalPresentationFormSheet
I would like to create a user guide for my app to show only once. How can I create a simple UIModalPresentationFormSheet with some text in it?
EDIT:
UIViewController *newItemViewController = [[UIViewController alloc] initWithNibName:@"View.xib" bundle:nil];
newItemViewController.modalPresentationStyle = UIModalPresentationFormSheet;
[self presentModalViewController:newItemViewController animated:YES];
|
You could store value in NSUserDeafualts. So in your main UIViewController in viewDidAppear :
#define SHOULD_SHOW_KEY @"shouldShowKey"
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
//Get user defaults
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
//if there is no object for SHOULD_SHOW_KEY present modal contoroler
if (![defaults objectForKey:SHOULD_SHOW_KEY]) {
//Set object for key and synchronize defaults
[defaults setObject:SHOULD_SHOW_KEY forKey:SHOULD_SHOW_KEY];
[defaults synchronize];
//Present any custom modal controller
UIViewController *yourModalVC=[self.storyboard instantiateViewControllerWithIdentifier:@"myModalVC"];
[self presentModalViewController:yourModalVC animated:YES];
}
}
Hope this helped.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "ios, xcode"
}
|
Looking for 16-bit c compiler for x86
I am working on porting uc/OS-II from DOS to x86 (real mode). I need:
1. A compiler to generate real mode 16-bit x86 assembly
2. An assembler to assemble the generated assembly into an object file
3. A linker to link the object files together and output an executable (raw binary, COFF, PE, or ELF formats are fine)
4. A standard library without invoking any DOS services (`int 21h`), only depend on BIOS service.
I am wondering whether there is any tool-chain could do it.
|
Check out the FreeDOS project. They have developer tools that include compilers, assemblers, and linkers. You'll probably have to modify the standard library, though, so that it uses BIOS calls rather than int 21h.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 11,
"tags": "compiler construction, x86, real mode"
}
|
How to leash train a ferret?
I have three ferrets. I bought a small harness from Petco similar to this one
. But as soon as they notice they immediately flip out and start fighting to get it off. They always manage to squeeze out.
|
I can finally answer my own question.
It helps that they are older now and less psycho.
What finally worked was:
1. slip it on when she's half asleep
2. make sure it's even tighter than I thought necessary so she can't wiggle out
3. take her outside immediately so that she's distracted and preoccupied with exploring instead of escaping the harness
4. lots of treats!
That was the first successful attempt. On later attempts I could put it on her while she was awake as long I was firm but gentle.
Then I always made sure to take her outside immediately, both for the distraction and for positive reinforcement that the leash means exploration time! Now she accepts it without struggling.
|
stackexchange-pets
|
{
"answer_score": 0,
"question_score": 2,
"tags": "leash training, outdoor, ferrets, leashes"
}
|
Pointing to Google that a specific website is for mobiles
I have 2 websites: let's call them A and B.
* A is a Desktop optimized website.
* B is a mobile version of A, but it's not on the same domain. It also has a smaller amount of content/pages than A
**How do I tell Google** , and other search engines, that I would prefer to have only mobile users on B (no desktop users) and **that B is a mobile version of A**.
I already have user agent detection and BIG BIG messages inviting users to switch platforms when convenient for them, but I want Google to send them directly to the appropriate site.
I use Google Analytics and Webmaster tools on both.
|
Sorry, there is no method to do this currently. Google results on mobile are largely the same as on desktop.
However, Google has a special mobile user agent, `Googlebot-Mobile`, so you could detect this (if you don't already) and make sure there is a link to the mobile version.
I've also seen a few sources that list this meta tag, but I don't know if it's actually used by any search engines:
<link rel="alternate" media="handheld" href="mobile-version.html">
|
stackexchange-webmasters
|
{
"answer_score": 2,
"question_score": 2,
"tags": "seo, google, google search, robots.txt, mobile"
}
|
Arabic not urlencoding correctly
I have the string:
$str = 'ماجد';
This need to be encoded as:
'%E3%C7%CC%CF'
But I cannot figure out how to reach this encoded string. I believe it is Windows-1256. The above encoded string is how it is being encoded by a program I have.
Does anyone know how to reach this string?
|
If you know you want to use `Windows-1256` then all you have to do is to change the encoding of the input string (which is `UTF-8`) to `Windows-1256`. Then you apply `urlencode()` to the returned string and that's all.
There are several ways to change the encoding of a string in PHP. One of them (that I tested and provides the result you expect) is using `iconv()`:
$str = 'ماجد';
$conv = iconv('utf-8', 'windows-1256', $str);
echo(urlencode($conv));
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "php, character encoding, arabic, url encoding"
}
|
PHP $_GET Method ORDER BY
<a href="?sayfa=oyun_listesi&siralama=isim-az">A-Z</a>
<a href="?sayfa=oyun_listesi&siralama=isim-za">Z-A</a>
<?php
echo $_GET['siralama'];
if(empty($_GET['siralama'])){
$oyunlar = mysqli_query($con,"SELECT * FROM oyunlar");
}
else if(isset($_GET['siralama'])){
if($_GET['siralama']='isim-az'){$oyunlar = mysqli_query($con,"SELECT * FROM oyunlar ORDER BY oyun_isim");}
else if($_GET['siralama']='isim-za'){$oyunlar = mysqli_query($con,"SELECT * FROM oyunlar ORDER BY oyun_isim DESC");}
}
while($oyun = mysqli_fetch_array($oyunlar))
{
?>
SQL Variables + HTML
<?php } mysqli_close($con);?>
i have two link with $_GET variable i can echo $_GET['siralama'] but it wont change $oyunlar variable it should ORDER BY DESC while isim_za but it wont.
|
Change
if($_GET['siralama']='isim-az')
to
if($_GET['siralama']=='isim-az')
\-- edit
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "php, mysql"
}
|
Force image to match dimension of parent flexbox in Tailwind
I would like to force an image to match the dimensions of a parent div with no overflow.
<
<div class="flex flex-col max-h-screen">
<div class="flex flex-1">
<div class="flex w-1/2 max-h-full">
<img src="image.jpg" class="max-h-full object-cover overflow-hidden" />
</div>
<div class=""><p>Column Two</p></div>
</div>
</div>
I would like for the image to match both the width and height of the flexbox (e.g. No scrolling) Is there a way to acheive this?
|
use `object-scale-down` to scale down the image and fit in container or use `object-fit`
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "css, flexbox, tailwind css"
}
|
A variable contributes less to R2 value in the multiple regression model than alone in the linear regression model
I would like to ask a basic question. A multiple regression model, y ~ x1 + x2 + x3, has R2 value of 0.152. Now I have a new variable z, and its linear regression model, y ~ z, has R2 value of 0.051. However, when I put z in the multiple regression model, y ~ x1 + x2 + x3 + z, then R2 value is 0.153. Why is it not 0.152 + 0.051?
|
Remember that $R^2$ is the percent of variability in $y$ that is explained by your independent variables. Based on your data, this means that $z$ on its own explains about $5.1\%$ of the variability in $y$ but that it only explains $0.01\%$ of the variability in $y$ once $x_1$, $x_2$, and $x_3$ have already been taken into account.
Depending on the statistical software you use, this _might_ be different. It will depend on which "sums of squares" each software uses. R, for example, uses sequential sums of squares, which means that the first independent variable $x_1$ in will explain some of that variability in $y$, then the next independent variable $x_2$ may explain some more variability in $y$ or it might not once $x_1$ is already taken into account. Thus the $R^2$ when adding in a new variable $z$ will not necessarily increase by the same $R^2$ value when you merely regress $y$ on $z$.
|
stackexchange-stats
|
{
"answer_score": 0,
"question_score": 0,
"tags": "regression, multiple regression"
}
|
PInvokeStackImbalance while using "static extern int system(string str)"
I'm trying to use the system(string str) Command for dos-operations in C#.
namespace XYZ
{
internal class Program
{
[DllImport("msvcrt.dll")]
static extern int system(string str);
static void Main(string[] args)
{
string Command = Console.ReadLine();
system(Command);
/* Excutes command, then "PInvokeStackImbalance". */
}
}
}
I know using `static extern int system(string str)` is a bad solution, but I've tried other solutions which did not work.
|
You forgot to specify the calling convention:
[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
static extern int system(string str);
I normally try to explain why but that seems unnecessary here ;) This is otherwise unlikely to fix your problem, whatever it may be, it is the same thing as
Process.Start("cmd.exe", "/c " + str);
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "c#, msvcrt"
}
|
Change of measure Radon-Nikodym
Let $(\Omega, \mathcal{F}, P)$ be a measure space where $P$ is a probability measure. Let $Q$ be another probability measure that is absolutely continuous with respect to $P$. By Radon-Nikodym, there is $L \in \mathcal{L}^1(P)$ subject to $$ Q(A) = \int_A L(\omega) P(\mathrm{d} \omega) $$ Does it generally hold that $\mathbb{E} \left[L X\right] = \mathbb{E}_Q \left[ X \right]$ for integrable r.v. $X$? I see this result again and again with densities $X = f \cdot m$, but I want to know whether or not this holds without the assumption of having densities.
EDIT: $X, L$ are in $\mathcal{L}^2$.
|
There is a little bit of ambiguity when you say "$X$ is an integrable random variable." Assuming you mean "$X$ is a $Q$-integrable random variable," yes, this is true. I don't know for sure whether it is true if we only have $X$ is $P$-integrable. To show it is true when $X$ is $Q$-integrable, use the standard method of showing it is true when $X$ is a simple random variable, then show it for general $X$ by approximating with an increasing sequence of simple functions and applying the monotone convergence theorem.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 2,
"tags": "measure theory, stochastic processes, random variables, radon nikodym"
}
|
forward slash not followed by any character
I've the following challenge.
I need a regex to find all lines that contain an URL that ends with .net or .net/ but not followed by any other character.
my regex so far:
r'://[a-zA-z0-9.]+\.net(/*)'
But how to ignore an URL like www.xxxxxx.net/search or www.xxxxxx.net/q=
URL is not always at end of line !
Example lines:
"xxxxxxxxxxx, 2 subscribers)"
"yyyyyyyyyyy, 2 subscribers)"
"zzzzzzzzzzz, 2 subscribers)"
"rrrrrrrrrrr,
"rrrrrrrrrrr,
|
The following might work for your sample input:
r'https?://[a-zA-z0-9.]+\.net/?'
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "regex, python 2.7"
}
|
Convert numpy array to a string using numpy.array_str()
I have a 2 dimensional numpy array. I am trying to make pairs of each row with every other row.
For example:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
It should have the following pairs(comma separated):
Pair(1,2) 1 2 3 4 5, 6 7 8 9 10
Pair(1,3) 1 2 3 4 5, 11 12 13 14 15
Pair(2,1) 6 7 8 9 10, 1 2 3 4 5
Pair(2,3) 6 7 8 9 10, 11 12 13 14 15
Pair(3,1) 11 12 13 14 15, 1 2 3 4 5
Pair(3,2) 11 12 13 14 15, 6 7 8 9 10
To achieve this task, I am converting each row to string then removing multiple white spaces, end line chars and [ ] chars.
But when I use numpy.array_str() for converting a large array (1500*100) it converts the row to:
1 2 ...., 4 5, 6 7 ....,8 9
Why is this happening and how can I fix this problem such that it doesn't slows down my program? If there is no possible way to do this without compromising speed then how can I achieve this task?
|
Maybe then a posible answer is:
import numpy as np
def pair(matrix,i,j):
str1=''
for value in matrix[i]:
str1+=str(value)+' '
# Delete one extra space
str1=str1[:-1]
str2=''
for value in matrix[j]:
str2+=str(value)+' '
str2=str2[:-1]
return str1+', '+str2
matrix=np.array([[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]])
print pair(matrix,0,1)
print pair(matrix,0,2)
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "python, arrays, numpy"
}
|
PerformanceGoal option ignored in V11.1
**Bug introduced in 11.1 and fixed in 11.2**
> [CASE:3892079] was created
>
> [...] I have reproduced this problem with `PerformanceGoal` in version 11.1 and reported the issue to our developers [...]
* * *
Take this code:
Animate[
Plot3D[
Sin[t x y], {x, -3, 3}, {y, -3, 3}
, PlotRange -> {0, 1.2}, PerformanceGoal -> "Quality"
]
, {t, 0, 2}
, AnimationRunning -> False
, DisplayAllSteps -> True
]
### V10.4 correct behavior

{
//calculate a highlight color from c
return highlighted;
}
Thanks in advance
|
You need to convert your RGB color to HSL (follow this post). Then increase L value (lightness) and convert back to RGB. Changing R, G, B directly will not give you "natural" looking of highlighted color. But all depends of what will you do in your application. Converting gives best result but need a lot of code. On the other hand, changing RGB directly will work very fast.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "c#, .net, winforms, drawing"
}
|
Is the 'Ton an impossible shape?
In Deus Ex's Hell's Kitchen, it seems to me that there is an inconsistency in the 'Ton.
If you check your compass as you enter or exit the 'Ton through Paul's apartment window, I think you get transported to another side of the building. It's very weird, can anyone else see this?
|
The 'Ton map has two exists, one is the main entrance and the other is the Paul's apartment window.( fire escape )
When in outside map ( Hell's Kitchen ) and standing towards the main entrance, the window to Paul's apartment is at the right wall of the building.
But when you walk in the 'Ton map the window is in the wall directly in front of you.
Yes, the 'Ton map is incorrect with regards to the outside map and is also 2-3 times larger than it should be.
|
stackexchange-gaming
|
{
"answer_score": 5,
"question_score": 5,
"tags": "deus ex"
}
|
trim last ip octet and reverse
I am looking for a one liner solution that remove the last octet of an ip address and reverse the ip.
For e.g
`206.195.152.176` should become `152.195.206`
I am having trouble with the reverse part Below is the trim part
echo 206.195.152.176 | sed 's/\.[0-9]*$//'
|
### With `awk`:
echo "206.195.152.176" | awk -F'.' '{print $3,$2,$1}' OFS='.'
### With `sed`:
echo "206.195.152.176" |sed -r 's/([0-9]{1,3}).([0-9]{1,3}).([0-9]{1,3}).([0-9]{1,3})/\3.\2.\1/'
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "bash, awk, sed"
}
|
In FFVII, when the final boss is defeated, can I return to the world map?
Basically, when I defeat the last boss in FFVII, can I keep on playing the game? I.e. return to the world map and fight other super bosses? Or should I get everything done before the final fight?
I seem to remember completing it once and I just got credits and the game ended. Seems a bit lame not be able to play on!
|
Once you defeat the final boss, the ending FMVs and credits start to roll and eventually brings you to a screen with a never-ending pattern of stars. There's no way to get back to your playthrough - or even the main menu - without resetting the console.
So in short, yes, you remember correctly - get all the side quests completed before taking the last boss on.
|
stackexchange-gaming
|
{
"answer_score": 14,
"question_score": 13,
"tags": "final fantasy 7"
}
|
What params are available with the_content filter?
I am looking for what params are passed to my filter function. Where can I find such info in the codex?
< didn't provide much info
I wanted to know if the post is a child of another
|
I don't think there are any additional parameters passed, per se, to `the_content`, but global variables like **$post** are accessible.
So something like this would work:
add_filter( 'the_content', 'check_for_post_parent' );
function check_for_post_parent($content) {
global $post;
if ($parent_id == $post->post_parent) {
//do what you want to $content here,
//now that you know $parent_id
//...
}
return $content;
}
|
stackexchange-wordpress
|
{
"answer_score": 6,
"question_score": 3,
"tags": "filters, the content"
}
|
Copy Paste Worksheets names to another workbook
I'm having trouble to do this. When I start the macro, It doesn't produce any error, but neither throws me any result.
Sub EmpresasCubiertas()
Dim x As Workbook
Dim y As Workbook
'## Open both workbooks first:
Set x = Workbooks.Open("G:\Estudios\Biblioteca\Mercado Accionario Chileno\InsertarEmpresa.xlsm")
Set y = Workbooks.Open("G:\Estudios\Biblioteca\Mercado Accionario Chileno\Procesamiento.xlsm")
For i = 3 To x.Sheets.Count
'Now, paste to y worksheet:
y.Sheets(1).Range(“A” & i) = x.Sheets(i).Name
Next i
End Sub
Note that workbook "y" is the workbook that I open first to run the macro. i.e It is already open, if it is of any help.
|
The issue lies with the missing Value property next to the Range, in your loop. It should read,
y.Sheets(1).Range(“A” & i).Value = x.Sheets(i).Name
I am assuming that you deliberately chose to start copying worksheet names from i = 3. If you need all worksheets, just change the value of i to 1.
Try This:
Sub CopyWorkBookNames()
Application.ScreenUpdating = False 'To avoid screen flickering
Dim y As Workbook
Dim x As Workbook
Set y = Application.ActiveWorkbook
Set x = Application.Workbooks.Open("FilePathToCopyFrom.xlsx")
'Copy and paste worksheet names, in the workbook running the code, starting from cell A3.
'If You want to paste into cell A1, decrement i in the range below accordingly
For i = 3 To x.Sheets.Count
y.ActiveSheet.Range("A" & i).Value = x.Sheets(i).Name
Next i
x.Close 'Add SaveChanges Options as needed
Application.ScreenUpdating = True
End Sub
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "excel, vba, loops, macros, worksheet"
}
|
Search engines that do _not_ respect robots.txt?
Are there any search engines that do not care about robots.txt?
|
All of the major, and minor, search engines respect robots.txt. Generally speaking only robots with bad intentions, or are poorly written, ignore robots.txt. You can find a list of bad bots here.
|
stackexchange-webmasters
|
{
"answer_score": 5,
"question_score": 5,
"tags": "search engines, robots.txt"
}
|
Toggle a button counter
I would like to do the like increment and decrements with same button. I have written this, but it just increment the like counts, how can I change it in order to decrements it after increment?
<button (click)="increment()">{{count}}</button>
export class TheComponent {
public count = 10;
public increment() {
this.count++;
}
}
|
You can simply maintain your count state when clicked. If it is already counted, then decrement else increment the count:
Try the following:
export class TheComponent {
public count = 100;
private isCounted: boolean = false;
public updateCount() {
this.count += this.isCounted? -1 : 1;
this.isCounted= !this.isCounted;
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 3,
"tags": "typescript"
}
|
Regex to add spaces around '=' in C++ code, what have I done wrong?
I would like to create a regex which will allow me to add spaces around assignment operators in C++ code (as I prefer this style), e.g. so that
x=something
becomes
x = something
but
if(y==x)
does not become
if(y = = x)
and so on including `!=`,`<=`,`>=`
I am relatively new to regular expressions and have tried the following:
(?<![\s=])(=)(?!=)
I thought this would be a good starter, but this does not seem to match. Could someone explain what I have not understood about regex here?
**Edit**
Example using regex which does not match in Code::Blocks IDE
!Code::BLocks regex attempt
|
Try something like this: `(?<![<>=!])\s*=\s*(?!=)` replaced with `=`.
OR
`([^<>=!])\s*=\s*([^=])` replaced with `\1 = \2`
Both lookaround assertions are needed since the pattern is not anchored.
Your own regex was, in reality, just missing `<>` in the character class. I have improved on it a tiny bit, look at the demo.
Demo+explanation for first regex: < Demo+explanation for second regex: <
Note: `\s` matches whitespace!
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "c++, regex"
}
|
Did Money Magazine say 78% of people have major negative financial event per decade?
Dave Ramsey says that:
> Money magazine states that 78% of us will have a major negative financial event in any given 10-year period
The only other source that I can find for this online seems to have the same wording which makes me think that it's quoting Dave. I can't find any primary source for this claim.
Did Money magazine actually make this claim?
|
Ramsey gives a citation, specifically:
> "Financial Planning 101" _Money_ (March 1989)
Back issues are available for $11.11 if you want to be 100% sure, but it seems like a reasonably well-referenced, but outdated and non-specific, statement.
(originally, in his 2003 book, Ramsey said 75%, not 78%, however)
Another reference specifies that by "major" _Money_ means "$10,000+"
|
stackexchange-skeptics
|
{
"answer_score": 2,
"question_score": 3,
"tags": "quotes, personal finance"
}
|
Markov inequality with coin flips
Let's say Dave has a biased coin with P(heads)=0.6. He tosses this coin $N$ times and, out of the $N$ times, the coin lands on heads 134 times. He says that the probability of seeing at least this many heads is at most 0.8. The best lower bound, using Markov inequality, on the number of times John tossed the coin = $0.8 * \frac{134}{0.6}$. However, I do not quite understand the intuition behind this. Given that he saw 134 heads, it makes sense to say that the total number of flips is 268. However, I don't quite understand how the information about the probability of seeing at least 134 heads can be factored in. Can someone explain this on a high level and explain how it leverages the markov inequality?
|
I think I understand now. What we have is the following: $$P(X \geq 134) = \frac{N*P(\text{heads})}{134}$$ $$0.8 = \frac{N*0.5}{134}$$ $$N = \frac{0.8*134}{0.5}$$
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "probability"
}
|
Asks a question; never responds to answers/comments
What do we call someone who asks a question and never responds to answers/comments?
Think of it more as "a pattern of behavior" (somebody who has asked many questions and never responded).
I had _unresponsive_ in mind, but that doesn't say that they _asked_ in the first place.
|
Perhaps _drive-by asker_ or _drive-by participant_ , to convey that he comes in, makes his post/comment/etc, and then continues on his merry way. Related, from @onomatomaniak in comments: _ask and run_.
In other contexts we call someone who takes but never gives -- for example, communal snacks at work -- a _mooch_ (or _moocher_ ) or a _parasite_. Depending on the specific case I don't see a problem with using those words online. _Freeloader_ also comes to mind, though it is more general.
Edited for question revision: _mooch_ , _parasite_ , and _freeloader_ are all perjorative; the _drive-by_ phrases are probably slightly negative but not as much as those.
|
stackexchange-english
|
{
"answer_score": 15,
"question_score": 11,
"tags": "nouns, phrase requests"
}
|
Configure PhpStorm to use .htaccess
I added `.htaccess` (for rewriting URLs) in my project's root directory but it's not working. I checked twice, the same file is working fine in Eclipse.
How do I configure PhpStorm to use .htaccess?
|
Do you use the same server/configuration when working with PhpStorm and Eclipse?
As it was explained in the comments, it has nothing to do with the IDE, but with the web server (Apache) and its configuration.
You can edit `.htaccess` with any editor, if this virtualhost/directory configuration has `AllowOverride All`, ModRewrite is enabled and your rewrite rules are correct, it will work just fine.
You need to ensure that your PHP files are served from the correctly configured web server.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 8,
"tags": ".htaccess, phpstorm"
}
|
Python Pandas: How to groupby and count and select a portion of counts?
I have a df like this:
new_org old_org asn cc
0 85736 pcizzi 85736 - Pcizzi S .a 23201 PY
1 001 001 Host 40244 US
2 85736 blah 85736 - whatevs 23201 PY
3 001 001 IT Complex 55734 IN
4 001 hospedagem 001 Hospedagem Ltda 36351 US
5 001web action.us.001web.net 36351 US
and I would like to groupby my df based on 'asn' column and select those groups which have more than one row. This is how I am doing it now but I am not sure if it is correct:
df.groupby('asn').apply(lambda x:x.count()>1)
Can anybody help?
|
You can filter a group.
Try `df.groupby('asn').filter(lambda x: len(x) > 1)` which will return you a `DataFrame`. You could group it again further if necessary.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "python, pandas, count, group by"
}
|
Blob data for PNG
im working with a lib, exstending on it, and i have this method that checks if data is a Media
function isMedia($blob) {
// Check for a JPG header.
if ($blob[0] == chr(0xFF) && $blob[1] == chr(0xD8)) {
return TRUE;
}
// Check for a MP4 header.
if ($blob[0] == chr(0x00) && $blob[1] == chr(0x00)) {
return TRUE;
}
return FALSE;
}
Im not that good with Blob data, i understand that it checks the first part of the data for special encoding, how would i check for PNG ?
|
I would normally recommend you use PHP's built in image detection stuff from GD or ImageMagick but I assume you have a good reason. So to check for PNG header you need to make sure the first part of the blob matches (according to <
89 50 4e 47 0d 0a 1a 0a
So something like
// Is PNG
if (
$blob[0] == chr(0x89) &&
$blob[1] == chr(0x50) &&
$blob[2] == chr(0x4e) &&
$blob[3] == chr(0x47) &&
$blob[4] == chr(0x0d) &&
$blob[5] == chr(0x0a) &&
$blob[6] == chr(0x1a) &&
$blob[7] == chr(0x0a)
) {
// Yes
}
I haven't tested the above code so there may be slight errors but you can use it as a bases but it should work ;)
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "php"
}
|
Matrix Exponential for Nilpotent Matrix
I want to prove that Id-A=${ e }^{ -{ \sum _{ k=1 }^{ n }{ \frac { { A }^{ k } }{ k } } } }$ whereas ${ A }^{ n }=0$ because A is nilpotent. What i did was setting z(t)=${ e }^{ -{ \sum _{ k=1 }^{ n }{ \frac { { At }^{ k } }{ k } } } }$ than obviously, we have z(0)=Id and
z'(t)=$-\sum _{ k=1 }^{ n }{ { A }^{ k }{ t }^{ k-1 }{ e }^{ -{ \sum _{ k=1 }^{ n }{ \frac { { A }^{ k } }{ k } } } } } =-A\sum _{ k=0 }^{ n-1 }{ { (At) }^{ k }exp( } -\sum _{ k=1 }^{ n }{ \frac { { (At) }^{ k } }{ k } }) $=$-A{ (Id-At) }^{ -1 }z(t)$.
Now we obtained a Differential equation.
z'(t)=$-A{ (Id-At) }^{ -1 }z(t)$
z(0)=Id
One can easily conclude now that z(t)=(Id-At) is a solution, hence because of the uniqueness of solutions we get
${ e }^{ -{ \sum _{ k=1 }^{ n }{ \frac { { A }^{ k } }{ k } } } }$=(Id-At)
which finishes the proof. Is this proof correct? And if it is are there any points which could be done better?
|
You still have some typos, $A$ should be $A^k$ in the definition of $z(t)$, etc.
> On the correctness, you only need to note that ${\rm Id}-At$ is invertible for small $t$ (which is sufficient for your purposes).
Also, depending on what you have learned (or on what you can refer to) you may need to consider instead the functions $z(t)c$ with $c\in\mathbb R^m$ when $A$ is $m\times m$. This would give equations on $\mathbb R^m$ and then it suffices to note that if two matrices $B,C$ satisfy $Bc=Cc$ for all $c$, then $B=C$.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "ordinary differential equations"
}
|
Excel formula to change cell background color and/or set text bold
I have a .net application which generates excel from simple string variable where every cell gets its value like this:
For iCol = 0 To Cols.Rows.Count - 1
str &= Trim(Cols.Rows(iCol)("capt")) & vbTab
Next
I am looking for a way to change cell background and/or set text bold via excel formula.
Something like
str &= "=<b>"
str &= Trim(Cols.Rows(iCol)("capt"))
str &= "</b>"
or
str &= "=<p bgcolor=" + "color" + ">"
str &= Trim(Cols.Rows(iCol)("capt"))
str &= "</p>"
Macro or conditional-formatting is not an option.
|
You're looking for the `Range.Font` and `Range.Interior` properties.
For iCol = 0 To Cols.Rows.Count - 1
str &= Trim(Cols.Rows(iCol)("capt")) & vbTab
Cells(row, iCol).Font.Bold = True
Cells(row, iCol).Interior.Color = ColorConstants.vbCyan
Next
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "html, .net, excel, vba"
}
|
Can't uninstall npm module on OSX
I have installed cordova on my mac and want to uninstall it.
I've tried the following:
npm uninstall cordova -g
but I get the following error:
npm WARN uninstall not installed in /usr/local/Cellar/node/0.10.32/lib/node_modules: "cordova"
Any ideas?
|
There are know issues with the way `homebrew` and `npm` play together. From this article by Dan Herbert
> There's an NPM bug for this exact problem. The bug has been "fixed" by Homebrew installing npm in a way that allows it to manage itself once the install is complete. However, this is error-prone and still seems to cause problems for some people. The root of the the issue is really that npm is its own package manager and it is therefore better to have npm manage itself and its packages completely on its own instead of letting Homebrew do it.
Aside from that your node version is out of date. If you can upgrade you should do so to Node v4.1.2. Follow the instructions on the node.js site.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "node.js, cordova, npm"
}
|
Retrieving Boolean value as text
In my application i have one value which is stored as boolean. How can i change that Boolean value to text when displaying in grid view.
I have this sql
SELECT Driver.FirstName + Driver.LastName AS DriverName, Driver.PhoneNumber,
Booking.BookingId, Booking.DriverRating, Driver.CarId AS CarUsed
FROM Booking
INNER JOIN Driver ON Booking.DriverId = Driver.DriverId
WHERE Booking.DriverRating = 0
I am retrieving all the all the driver rating which is false(0). Now when i display it to grid view i want to change boolean value false to unsatisfactory.
How can i do it within sql query?
|
How bout retrieving it from the server as a string to begin with?
For example
SELECT Driver.FirstName + Driver.LastName AS DriverName, Driver.PhoneNumber, Booking.BookingId,
Case Booking.DriverRating When 0 then 'Unsatisfactory' else 'Satisfactory' end as DriverRating,
Driver.CarId AS CarUsed
FROM Booking
INNER JOIN Driver ON Booking.DriverId = Driver.DriverId
WHERE (Booking.DriverRating = 0)
Or in your case since you are already using a where clause:
SELECT Driver.FirstName + Driver.LastName AS DriverName, Driver.PhoneNumber, Booking.BookingId,
'Unsatisfactory' as DriverRating,
Driver.CarId AS CarUsed
FROM Booking INNER JOIN Driver ON Booking.DriverId = Driver.DriverId
WHERE (Booking.DriverRating = 0)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#, sql, gridview"
}
|
Is it possible to somehow start an activity with a given content?
I have to buttons which should start the same activity, but use a different XML file. What I was hoping to be able to do was something like this, from "main":
button1: startActivity(new Intent(main.this, next.class, R.layout.xmlfile1)); button2: startActivity(new Intent(main.this, next.class, R.layout.xmlfile2));
I guess I could save the xml-name in the application context / with a global variable, but that wouldn't be very elegant.
Anyone know if there is any way to accomplish what I'm looking for? At the moment I'm creating duplicate class-files, and that's not really a smooth way to do it...
|
You can pass the data to the activity by putting extra data on the Intent. See the Intent's method `putExtra` and `getIntExtra` and friends.
The integer you put is the xml resource id. On the activity you cat use `getIntExtra` on the activities intent (`getIntent`) to retrieve the id.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "android, android activity"
}
|
Is there an audio commentary for Ghost In The Shell series and movies?
I'd like to know if there are audio commentaries from the creators of GITS series and movies. Of all the things I've seen GITS has the most unexplained moments, so I'd like to find out what those things could mean. I'm also interested in commentary for the new Arise series.
I also think asking a bunch of separate questions might not be the best idea, so I'd like to find out some answers by myself listening to the commentary track(s).
|
I found a page that lists Blu-Ray sets you can buy for SAC, and those contain audio commentaries. That indicates that there are audio commentaries, but I'm not sure if they can be gotten not on the Blu-Ray set. As far as I can tell, there is no audio commentary for _Arise_ , but considering that it hasn't been released on any sort of disc form, that might change.
On Wikipedia, it says about the original Ghost in the Shell film that:
> Manga Entertainment released the film on Blu-ray on November 24, 2009; this version contains the original film and the remastering, but omits the audio commentary and face-to-face interview with Oshii which was listed on its box.
But from what I can tell, the 2004 DVD release and the 2007 Blu-Ray releases have the commentary, and the 2004 special edition also included things like character dossiers and a creator's biography.
|
stackexchange-anime
|
{
"answer_score": 3,
"question_score": 2,
"tags": "ghost in the shell sac, ghost in the shell, ghost in the shell arise"
}
|
Downloading the pruned blockchain file directly from external source
Using the bitcoin client to have a pruned version of the blockchain can take a lot of time, I was wondering what would be the drawback to simply download an already pruned bitcoin blockchain file from a reliable source like bitcoin.org then put it in my bitcoin directory and then use/update it from it there.
|
It introduces too much trust into the download source. It's the same thing as just uploading a datadir. You aren't verifying any of the blockchain history; what you download could be a fork of the blockchain. Having such a download completely defeats the point of running a full node.
Furthermore, with downloading a pruned datadir, you will have to download the chainstate. This isn't even verifiable without downloading the blockchain itself. The uploader could have modified the chainstate to include UTXOs that don't exist, and your node wouldn't know that. You could be forked onto a separate chain or just contain invalid things in the UTXO set.
At least with a full blockchain datadir download, you could ignore the given chainstate and just verify the blocks. But that's equivalent to the old bootstrap.dat download, and isn't actually faster.
|
stackexchange-bitcoin
|
{
"answer_score": 5,
"question_score": 3,
"tags": "bitcoin core, security, synchronization, pruning"
}
|
Front fork preloader is not stopping to spin in any directions!
My front suspension has a preloader in the left side and lockout in the right side. The preloader was hard to spin so I applied a little bit of force to it while riding the bike. Now its free but there is no end to the adjustment in both sides. The preloader knob is not detached but it isnt working. Can someone please help regarding this above issue?
Brand is "Zoom suspension 100mm with lockout"
|
Based on the brand, this is a chinese fork for a 26" wheel.
<
There will likely not be a rebuild kit available for it, nor any parts assembly diagrammes.
Your two options are
1. Buy a new fork, or
2. Tear into the old fork, see what you see, and if it is not fixable then buy a new fork.
3. Ride it as-is with no preload adjustment.
Sorry, that is my opinion. Consider buying a decent used bike locally for cheap, as a parts source. Good luck!
|
stackexchange-bicycles
|
{
"answer_score": 1,
"question_score": 1,
"tags": "suspension"
}
|
What does \'.- mean in a Regular Expression
I'm new to regular expression and I having trouble finding what "\'.-" means.
'/^[A-Z \'.-]{2,20}$/i'
So far from my research, I have found that the regular expression starts (^) and requires two to twenty ({2,20}) alphabetical (A-Z) characters. The expression is also case insensitive (/i).
Any hints about what "\'.-" means?
|
The character class is the entire expression `[A-Z \'.-]`, meaning any of `A`-`Z`, space, single quote, period, or hyphen. The `\` is needed to protect the single quote, since it's also being used as the string quote. This charclass must be repeated 2 to 20 times, and because of the leading `^` and trailing `$` anchors that must be the entire content of the matching string.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 1,
"tags": "regex"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.