INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
How to fit an uniform distribution to a histogram?
I have a set of data that is generated from an **uniform** distribution. Now I want to fit the corresponding histogram to an uniform distribution, such that there is a '' shape of line plotted on that histogram. I tried to fit it by using the MATLAB built-in function `histfit`, but there is no such an option of uniform distribution for histfit. How can I do it?
data = unifrnd(-100,100,1000,1);
%% MATLAB built-in function: 'histfit'
figure(1);
hh = histfit(data); % No options for 'histfit' to fit data to an uniform distribution
%% Manually fitting a histogram to an uniform distribution
figure(2);
numBars = length(hh(1).XData);
histogram(data, numBars);
% TODO: How to do next to plot a line that fits the data to an uniform distribution? | Since a uniform distribution is just 1/(b-a) for a region [a, b), you can define a function that calculates this
x = -200:200;
y = unifdist(x, -100, 100);
figure;
plot(x, y)
function ret = unifdist(x, a, b)
ret = ones(length(x), 1)/(b-a);
ret(x < a | x >= b) = 0;
end
There's probably a much simpler and faster way to do this, but it works. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "matlab, histogram, uniform distribution"
} |
Fatal error cannot run 'mt.exe' at compiling VS 2012 C++ project
I upgraded Visual Studio to VS Professional 2012.
Building old Visual C++ projects resulted in the error:
**LINK : fatal error LNK1158: cannot run 'mt.exe'**
Putting the folder with mt.exe into the path did not help.
Currently I am using mt.exe in the folder C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A\Bin\x64 | Set "Generate manifest" as No in Linker. This helped | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "visual c++, visual studio 2012, build"
} |
How to change IFrame styles from IFrame itself using jquery?
I have an iframe which will be inserted dynamically into the parent page ( _I don't have control over this domain_ ) using following script...
var _hf_iFrame = document.createElement("iframe");
_hf_iFrame.setAttribute("id", "_hf_iFrame");
_hf_iFrame.setAttribute("name", "_hf_iFrame");
_hf_iFrame.setAttribute("style", "height: 354px; width: 445px; border: 0; margin-left: -400px; top: 23%; position: fixed;");
document.body.appendChild(_hf_iFrame);
_hf_iFrame.setAttribute("src", "
I want to change the css properties of the iframe from iframe itself. Is it possible to achieve this? I am using JQuery inside my iframe.
Thanks in advance. | You can't do this.
You have two documents. The parent and the framed. The iframe element exists within the parent, so to modify it you need to modify the parent document.
Your code runs in the framed document, which is on a different domain, so the same origin policy prevents you from reaching the parent document to modify it. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "jquery, html, css, iframe, cross browser"
} |
Как ограничить длину строки при компиляции под Android?
S: String[50];
Компилирую под Win32/64 все нормально. При компиляции под Android - ошибка:
> E2029 ';' expected but '[' found.
Есть другие варианты ограничить строку для использования в типизированном файле? | `String[50]` не поддерживается на мобильных платформах.
Можно конечно попробовать использовать массив
...
S: array [0..49] of Byte;
...
Детали можно посмотреть тут. Также на docwiki.embarcadero.com неплохо описано как мигрировать код на мобильные платформы. | stackexchange-ru_stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "android, delphi, строки"
} |
How can I use generalized regression neural network in python?
I'm trying to find any python library or package which implements newgrnn (Generalized Regression Neural Network) using python.
Is there any package or library available where I can use neural network for regression. I'm trying to find python equivalent of the newgrnn (Generalized Regression Neural Network) which is described here. | I found the library neupy which solved my problem:
from neupy import algorithms
from neupy.algorithms.rbfn.utils import pdf_between_data
grnn = algorithms.GRNN(std=0.003)
grnn.train(X, y)
# In this part of the code you can do any moifications you want
ratios = pdf_between_data(grnn.input_train, X, grnn.std)
predicted = (np.dot(grnn.target_train.T, ratios) / ratios.sum(axis=0)).T
This is the link for the library: < | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "python, neural network, regression"
} |
Set of $r$-th residues.
Let's define the set of $r^{th}$-residues in $\mathbb{Z}_p^*$ as:
$\mathbb{Z}_p^r := \\{ y \in \mathbb{Z}_p* : \exists x \in \mathbb{Z}_p^* \text{ such that } y = x^r\mod{p} \\}$.
I am reading that when $p$ is prime for which $p-1=qr$ with $q$ a prime that is not a divisor of $r$, then:
1. $\mathbb{Z}_p^r$ is an order $q$ cyclic subgroup of $\mathbb{Z}_p^*$
2. For each $y \in \mathbb{Z}_p^*$, $y \in \mathbb{Z}_p^r$ if and only if $y^q \mod{p} = 1$
Why are this both statements true? | First note that $\mathbb{Z}_p^*$ is cyclic, and so is any of its subgroups. Let $\xi$ be a generator of $\mathbb{Z}_p^*$. Then for $\xi^i,\,\xi^j\in\mathbb{Z}_p^*$, $\xi^i=\left(\xi^j\right)^r$ is equivelant to $$i\equiv jr\pmod{p-1}.$$ Let $j$ run through $\\{0,\dots,q-1\\}$, and we obtain $\mathbb{Z}_p^r$, which is exactly the subgroup generated by $\xi^r$. And the first statement follows.
It remains to show that if $y^q\mod p=1$, then $y\in\mathbb{Z}_p^r$. One may see here. | stackexchange-math | {
"answer_score": 2,
"question_score": 0,
"tags": "abstract algebra, field theory, finite groups, finite fields"
} |
WCF WebApi HttpResponseException Issue
I am trying to throw an `HttpResponseException(HttpStatusCode.NotFound)` and I am getting the following error
> The response message returned by the Response property of this exception should be immediately returned to the client. No further handling of the request message is required.
I have removed all of the code in my method and I am just throwing the exception like this
[WebGet]
public MyData Get()
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
If I change my method to return a `HttpResponseMessage` I can get it to work correctly, however it does not solve the issue and I am unable to get my authentication operation handler to work without being able to throw a `HttpResponseException`. | Try using a `WebFaultException` for returning HTTP Status codes in WCF...
throw new WebFaultException(HttpStatusCode.NotFound); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 3,
"tags": "wcf, wcf web api"
} |
writing text into a textbox
I got a form called Form1 and a rich text box called richtextbox1, which is automatically generated, so it's private.
I got another class that connects to a server, I want to output the status of connecting but I can only access the richtextbox1.Text in the Form1 class, I got 2 possible solutions for this, which would be better or is there a better one that I don't know of?
1. making the textbox public
2. instead of :
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
creating a form1 object first and using that to store the form that is running:
//somewhere global
Form1 theform = new Form1();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(theform);
Then using the object somewhere in my connection class. | I'd create a public property in `Form1` that you can use.
`Form1.cs`
public string TextBoxText
{
get { return myTextBox.Text; }
set { myTextBox.Text = value; }
}
You can then set the value from another class.
`AnotherClass.cs`
myForm1.TextBoxText = "Current server status";
How you get access to `myForm1` depends on how you're calling the other class. For example, you could pass the form into the other class's constructor.
private Form1 myForm1 = null;
public AnotherClass(Form1 mainForm)
{
myForm1 = mainForm;
myForm1.TextBoxText = "Current server status";
} | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "c#, windows, forms"
} |
How do you solve an equation that has one variable term on one side and constant terms on the other side?
For example, how can it be possible to solve $4+6=2y$? I think I know two ways to do it: $$4+6=2y$$$$4+6-4=2y-4$$$$6=2y-4$$$$6+4=2y-4+4$$$$10=2y$$$${10\over 2}={2y\over 2}$$$$5=y$$and$$4+6=2y$$$$10=2y$$$${10\over 2}={2y\over 2}$$$$5=y$$See? I get the same answer! Is this how to do it? Tell me what you think and be sure to answer the question. | Almost always combine constants when you can. Sometimes, like when completing a square, you might have separate constants on the same side of an equality, but generally, combine up all your constants as soon as you can. | stackexchange-math | {
"answer_score": 0,
"question_score": 0,
"tags": "algebra precalculus"
} |
How to accept a code block on a method C#
I'm writing an extensions library for C#, and I'm wondering if it's possible to accept code blocks on a method call. Something like below:
foo()
{
var bar = 0;
};
Or something like this would also do:
foo(
{
var bar = 0; //As an argument to the method
}); | You can pass in a delegate/lambda to accomplish this.
public void foo(Action del)
{
var local = del;
if (local != null)
{
local();
}
}
foo(() =>
{
var bar = 0;
});
You can read more here | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "c#, methods, extending"
} |
How can Seq[+A] be covariant in A?
How can Seq[+A] be covariant in A if A occurs in contravariant position:
def :+ (elem: A) : Seq[A] ?
As I understand, a method argument type is a contravariant position. What am I missing ? | That's the _use case_ signature. It is not a real signature, just what you'll usually see in the common use case.
The real signature is:
def :+ [B >: A, That] ( elem : B )(implicit bf : CanBuildFrom[Seq[A], B, That] ) : That
Which, as you see, doesn't even guarantee a `Seq` return, much less `A`. | stackexchange-stackoverflow | {
"answer_score": 10,
"question_score": 6,
"tags": "scala, covariance"
} |
How to add newly discovered cell node as member of exadata storage server grid in oem12c?
I have successfully discovered a new storage node in oem using emcli
./emcli add_target -type=oracle_exadata -name="da13cel04.myhost.com" -host="da13db01.myhost.com" -properties="CellName:da13cel04.myhost.com;MgmtIPAddr:10.92.43.23"
Target "da13cel04.myhost.com:oracle_exadata" added successfully
But now i want to add this cell node under existing exadata storage grid target in em and i tried below,but it didn't helped
./emcli modify_target -type=’oracle_exadata_grid’ -name=’Exadata Grid da13.myhost.com’ -properties=’Members:da13cel01.nyhost.com,da13cel02.myhost.com,da13cel03.myhost.com,da13cel04.myhost.com’
Need help
Thanks in advance | Got answer for my question.Here is the command to add newly discovered cell nodes under existing exadata server grid
emcli modify_system -name='Exadata Grid da13.myhost.com' -type='oracle_exadata_grid' -add_members='da13cel04.myhost.com:oracle_exadata'
output:
System "Exadata Grid da13.myhost.com:oracle_exadata_grid" modified successfully | stackexchange-dba | {
"answer_score": 0,
"question_score": 0,
"tags": "oracle enterprise manager, exadata"
} |
Split maya render layers to files
I am trying to make a script in maya to export render layers to separate files. Though I am not clear on the logic to be applied for the script. I dont want any code just the procedure. Can anyone please help. Thanks in advance to all. | You can get all the render layers with
cmds.ls(type='renderLayer')
and the contents of each layer with
cmds.editRenderLayerMembers('layer-name-here', q=True)
You'l have to decide for yourself how to deal with objects that exist in multiple layers and so on. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "scripting, render, maya, mel, pymel"
} |
mean curvature is not preserved under isometry
I know that mean curvature is not intrinsic, so it seems that it is not preserved under isometry. What is the example that isometry does not preserve mean curvature? | Rolling up a plane into a cylinder can be given by the map $$\phi(x,y) = (\cos x,\sin x,y)$$ The derivatives are easily computed, $$\phi_{x} = (-\sin x,\cos x,0)$$ $$\phi_{y} = (0,0,1)$$ These are orthonormal with respect to the (induced) metric on the cylinder, so the parametrisation is an isometry. The plane has mean curvature $0$ while the cylinder has mean curvature $-1/2$ | stackexchange-math | {
"answer_score": 2,
"question_score": 2,
"tags": "differential geometry, curvature"
} |
jQuery moving MultiSelect values to another MultiSelect
So I have a MultiSelect box with x values which I need the ability to move to another MultiSelect box and vise versa.
<select class="boxa" multiple="multiple">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select class="boxb" multiple="multiple">
</select>
Need to move all or one of the values of boxa to boxb on a button click, also with the ability to move the values back from boxb to boxa.
Does jQuery have anything like this or is this a custom snippet of code? | There's a jquery plugin called crossSelect which seems to do what you want.
jQuery doesn't have this built in, you would need to either find a plugin you like and use that, or write your own. (And of course you don't _have_ to use jQuery to write or use it, you could implement it in pure javascript if you like) | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 21,
"tags": "jquery, select"
} |
Image of a submanifold under a smooth surjective map
Let $f : M \rightarrow N$ be a smooth surjective map, where $M,N$ are smooth manifolds. I have a submanifold $M' \subset M$. If we restrict the map $f|_{M'}:M' \rightarrow N$, is $f(M')$ also a submanifold?
I'm not sure how to give $f(M')$ a smooth structure. Is there a way to do that, or can we find a counter example? | If $M=\mathbf{R}^3$, $N=\mathbf{R}^2$, $f(x,y,z)=(x,y)$ and $M'=\\{x=z=0\\}\cup\\{y=0,z=1\\}$ (which is the union of two disjoint lines), then $f(M')=\\{x=0\\}\cup\\{y=0\\}$ is the union of two intersecting lines, and thus not a manifold. | stackexchange-math | {
"answer_score": 0,
"question_score": 0,
"tags": "smooth manifolds, smooth functions, submanifold"
} |
Arithmetic operation resulted in an overflow
When i send:
Result = CInt(NetApiBufferFree(pBuffer))
I receive (SOME TIMES) this error:
Arithmetic operation resulted in an overflow.
What exactly means that? and how i can resolve it? | It means that `CInt` argument is out of range of `Integer`, -0x80000000 to 0x7FFFFFFF And it happens when `NetApiBufferFree` returns an error: error codes are bigger than 0x80000000.
There is no unsigned int32 type, so use `CLng` instead of `CInt`.
* * *
About source of error. You should find out code of error which you get: call MsgBox or log it to file, or use breakpoint. Next find its description. If it won't help you (for example error would be E_FAIL), add code to check that `pBuffer` value is valid - that it wasn't modified by something, and wasn't already freed. Add logging for `NetApiBuffer*` calls. | stackexchange-stackoverflow | {
"answer_score": 14,
"question_score": 5,
"tags": "vb.net, visual studio 2010, windows xp"
} |
Publish Google Slides to the Web (Specific Page)
Is there a way to publish Google Slides to the web to open up to a specific page and NOT allow access to the other slides? For example, let's say I wanted to open up to a specific id or page number and prevent access to the clicking around on other slides. How would I do that? | Just hide all other slides by right-clicking on those slides and selecting **Skip slide** , except the one slide you want the user to view. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 2,
"tags": "html, google slides"
} |
How can I capture the same text multiple times using regex?
I need to match the occurrence of a character before a string. The string might occur multiple times, meaning the character might change.
**Test subject:**
§aUsername: Message, which happens to contain Username. §3Wow, Username again.
I would want three groups, because `Username` occurs three times in the subject.
**Desired output:**
["Username", 'a']
["Username", 'a']
["Username", '3']
I wrote this regex, but it only works with one occurance of `Username`.
**My (failed) attempt:**
§(.).*?Username
Edit: That regex entirely ignores the second occurence of `Username`, which should match the same character (`a`) as the first one.
**Its output:**
["Username", 'a']
["Username", '3'] | If a quantifier in a lookbehind is supported (.NET, Pyton PiPy module or the newer Javascript engines), you could use a capture group in the lookbehind.
The match will be Username, the group 1 will contain a single any character except a newline.
(?<=§(.)[^§]*)Username
* `(?<=` Positive lookbehind, asser what is to the left is
* `§(.)` Match `§` and capture in **group 1** a single any char
* `[^§]*` Match any char except `§`, using a negated character class, any number of times
* `)` Close lookbehind
* `Username` Match literally
Regex demo | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "regex"
} |
How do you get two \'pī\ out of one \'pī\?
Johnny baked a single \'pī\ for his friends, and when his friends asked for more \'pī\ so that each friend could have one \'pī\ , he responded with
"I gave you two \'pīs\ already!"
His friends were confused, since Johnny had obviously only given them one \'pī\ ...
How do you get two \'pīs\ out of one \'pī\?
(If you are wondering what the slashes are and symbols are, they indicate pronunciation, probably a part of the puzzle...) | He gave them
> one **pie** , which has a total angle of $2\large\pi$. | stackexchange-puzzling | {
"answer_score": 7,
"question_score": 5,
"tags": "mathematics, wordplay"
} |
Can I use an object (an instance of a class) as a dictionary key in Python?
I want to use a class instance as a dictionary key, like:
classinstance = class()
dictionary[classinstance] = 'hello world'
Python seems to be not able to handle classes as dictionary key, or am I wrong? In addition, I could use a Tuple-list like [(classinstance, helloworld),...] instead of a dictionary, but that looks very unprofessional. Do you have any clue for fixing that issue? | Your instances need to be hashable. The python glossary tells us:
> An object is hashable if it has a hash value which never changes during its lifetime (it needs a `__hash__()` method), and can be compared to other objects (it needs an `__eq__()` or `__cmp__()` method). Hashable objects which compare equal must have the same hash value.
>
> Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.
>
> All of Python’s immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are. Objects which are instances of user-defined classes are hashable by default; they all compare unequal, and their hash value is their id(). | stackexchange-stackoverflow | {
"answer_score": 14,
"question_score": 13,
"tags": "python, list, dictionary, tuples"
} |
Open a MacOS application using the hyperref run command without Terminal showing up
I want to open the MacOSX application Photo Booth (starting the iSight camera) from a link in a presentation pdf file. I use the `hyperref` command
\href{run:photoscript}{Link text}
to call 'photoscript', which contains a single line:
open -a Photo\ Booth
The application opens alright, but the undesired effect is that a Terminal window appears with
/Users/me/photoscript ; exit;
logout
[Process completed]
How can I prevent this Terminal window from showing up? | Assuming you're only doing this with OS X, you could use Applescript for your command.
Open the AppleScript Editor (found in the Utilities folder) and make the following script:
tell application "Photo Booth" to activate
Save this as an application, and then make your link:
\href{run:photoscript.app}{PhotoBooth} | stackexchange-tex | {
"answer_score": 2,
"question_score": 3,
"tags": "hyperref, mac"
} |
Is there a difference between table.class tr, th and table .class tr, th?
For the longest time I was styling my elements in this way.
table .class tr, th{
}
Today I had some insane css related bugs and it occurred to me that it may have worked in the past by accident and in fact what it is doing is not selecting tables of a certain class but selecting tables followed by elements of a certain class.
I kind of assumed that css would just ignore the space between table and .class. But does it?
table.class tr, th{
}
Would this work differently? I can't believe I didn't think about this before! (embarrassed)
Thanks! | `table .class tr` selects this:
<table>
<tbody class="class">
<tr></tr>
</tbody>
</table>
While `table.class tr` selects this:
<table class="class">
<tr></tr>
</table> | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "html, css, css selectors"
} |
create a GET request with RequestSpecBuilder
I have tried query Params and path Params but it is giving error `Undefined path parameters are: job_id`
I guess it is because because URI is ending up in wrong format.
builder.addQueryParams(queryParams);
return getAPIResponse();
Expected Format is `
Actual Format is `
How can build the URI in expected format? | The expected is a pathparam ` but you are adding it as a queryParam `addQueryParams`
RequestSpecBuilder builder = new RequestSpecBuilder();
builder.addPathParam("job_id", "abc");
RequestSpecification requestSpec = builder.build();
given().log().all().spec(requestSpec).when().get(" | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "java, rest, rest assured"
} |
How to create AWS CloudFront signed url for s3 video using javascript sdk without NodeJs
I have some videos in my **aws S3 bucket** , I want to play these videos using jwplayer with **CloudFront signed URLs .**
I have created signed URLs **using aws PHP sdk and its working fine.** But, **I want the same thing with aws javascript sdk , without using any nodeJs module** , Need simple javascript script with HTML .
Please share suggestion , if anyone done this thing .
Thank you in advance . | Here is the documentation to generate SignedURL with Javascript.
<
Yo need to share your private key, which is dangerous and not an acceptable practice.
**Cloudfront Signed URL SDK for Javascript:**
<
Hope it helps. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "javascript, amazon web services, amazon s3, amazon cloudfront, aws sdk js"
} |
how to hide the selection of the button in iphone
when i press the button i get the blue color , is there any way to just avoid getting that blue color when i press the button. | sets the button look to be consistent regardless of the state
[UIButton1 setBackgroundImage:[UIImage imageNamed:@"ButtonBack.png"] forState:UIControlStateSelected|UIControlStateNormal|UIControlStateHighlighted];
[UIButton1 setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected|UIControlStateNormal|UIControlStateHighlighted]; | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 5,
"tags": "iphone, objective c"
} |
XQuery: Return value of attribute if it contains another spesific attribute
I want to return a result on all the books which contain the "databases" attribute in inside of "field".
for $e in //testbook[field="databases"]
return $e/title
Sample of the `.xml` file:
<?xml version="1.0" encoding="UTF-?>
<testbook>
<book>
<author> AuthorGuy </author>
<title> theBook</title>
<field> databases </field>
</book>
</testbook> | There are two issues:
1. `<title/>` and `<field/>` elements are contained in a `<book/>` element, and are not direct children of `<testbook/>`, fix the path expressions.
2. The `<field/>` tag contains the field wrapped in whitespace, use `contains($string, $needle)` instead of a simple comparison.
A working example:
let $document := document{<testbook>
<book>
<author> AuthorGuy </author>
<title> theBook</title>
<field> databases </field>
</book>
</testbook>}
for $e in $document//testbook[contains(book/field, "databases")]
return $e/book/title | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "xquery"
} |
StaticQuery 'data' is undefined
I'm a noob using gatsby and strapi. Trying to make a simple component that uses a graphql query.
import React from "react"
import {StaticQuery, graphql } from "gatsby"
export default ({data}) => (
<StaticQuery
query={graphql`
query indQuery {
allStrapiIndustry {
edges {
node {
title
}
}
}
}
`}
render={data.allStrapiIndustry.edges.map(document => (
<header>
<h1>{document.node.title}</h1>
</header>
) )}
/>
)
Any help is appreciated.
, like so:
render={
data => data.allStrapiIndustry.edges.map(document =>
(
<header>
<h1>{document.node.title}</h1>
</header>
)
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "reactjs, graphql, gatsby"
} |
Why can't I use [Space(15)] before a Variable with inline { get; set; }?
I am structuring my variables, so I can edit them bette in the Unity Inspector. I am trying to use a [Space(15)] in front of a few variables, which have a { get; set; }. Visual Studio won't compile it.
I placed a variable without { get; set;} in front of the other variables and it seems to compile, but it's a pretty ugly solution. Google wasn't that helpful in my search for a fix.
This doesn't work:
[Space(15)]
[SerializeField]
private bool baa { get; set; }
This does work:
[Space(15)]
public int foo;
[SerializeField]
private bool baa { get; set; }
It should compile without an extra variable to put a ";" in the code. The compiler shows me following Error-Code: CS0592. | You cannot serialize a property. The `SerializeField` attribute is for serializing a `field`. Same goes for `Space`, which ads space in the inspector **before** the marked `field`.
Unity does not directly support the serialization of properties in the inspector.
A workaround, although a bit messy, is to declare a separate field for the property you want to serialize.
[Space(15)]
[SerializeField]
private bool _baa;
private bool baa { get => _baa; set => _baa = value; } | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 0,
"tags": "c#, unity3d, syntax error"
} |
Удаление после второго символа в строке (DelphiXE4)
В строках есть слова ( **день** ). Как используя процедуру Delete удалить все после второго слова **день** :
Самый лучший день сегодня день 2018.
Не правда ли какой день хороший день сегодня день.
день день Прекрасный.
Что бы получилось:
Самый лучший день сегодня день
Не правда ли какой день хороший день
день день | Точно так же, как и в предыдущем вашем вопросе, комбинируйте поиск и удаление:
program Project1;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils;
const
s0:array[0..2] of string = ('Самый лучший день сегодня день 2018.',
'Не правда ли какой день хороший день сегодня день.',
'день день Прекрасный.');
var
k,i:integer;
s:string;
begin
for i := 0 to High(s0) do
begin
s:=s0[i];
k:=Pos('день',s);
if k > 0 then k:=Pos('день',s,k+1)
else Continue;
Delete(s,k+4,Length(s)-k-3);
Writeln(s);
end;
Readln;
end. | stackexchange-ru_stackoverflow | {
"answer_score": 2,
"question_score": -3,
"tags": "delphi"
} |
Diff between the datatypes decimal(1, 1) and numeric (1, 1) in sql
Can anyone please explain the difference between the datatypes decimal(1, 1) and numeric (1, 1) in SQL with an example? | There is no difference, NUMERIC and DECIMAL are synonyms:Microsoft Docs | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -2,
"tags": "sql"
} |
Get all parents keys in nested dictionary for all items
I want to get all parent keys for all items in a nested python dictionary with unlimited levels. Take an analogy, if you think of a nested dictionary as a directory containing sub-directories, the behaviour I want is similar to what `glob.glob(dir, recursive=True)` does.
For example, suppose we have the following dictionary:
sample_dict = {
"key_1": {
"sub_key_1": 1,
"sub_key_2": 2,
},
"key_2": {
"sub_key_1": 3,
"sub_key_2": {
"sub_sub_key_1": 4,
},
},
}
I want to get the full "path" of every value in the dictionary:
["key_1", "sub_key_1", 1]
["key_1", "sub_key_2", 2]
["key_2", "sub_key_1", 3]
["key_2", "sub_key_2", "sub_sub_key_1", 4]
Just wondering if there is a clean way to do that? | Using generators can often simplify the code for these type of tasks and make them much more readable while avoiding passing explicit state arguments to the function. You get a generator instead of a list, but this is a good thing because you can evaluate lazily if you want to. For example:
def getpaths(d):
if not isinstance(d, dict):
yield [d]
else:
yield from ([k] + w for k, v in d.items() for w in getpaths(v))
result = list(getpaths(sample_dict))
Result will be:
[['key_1', 'sub_key_1', 1],
['key_1', 'sub_key_2', 2],
['key_2', 'sub_key_1', 3],
['key_2', 'sub_key_2', 'sub_sub_key_1', 4]] | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "python, python 3.x, glob"
} |
Proof of the Strenghtened Limit Comparison Test
I'm studying on my own using Bonar and Khoury's Real Infinite Series. I understand the proof of the "regular" Limit Comparison Test( a link to google books, page 23 ) but the book doesn't provide a proof for the strengthened version, which is on the next page on the link, stated as
> Let $\sum_{n=0}^\infty a_n$ and $\sum_{n=0}^\infty b_n $ be two strictly positive series, and suppose that $$\liminf_{n\to\infty} \frac{a_n}{b_n}=L_1\ \ ,\ \ \limsup_{n\to\infty} \frac{a_n}{b_n}=L_2 $$ then
>
> 1.If $L_2 \lt \infty$ and $\sum_{n=0}^\infty b_n $ converges, then $\sum_{n=0}^\infty a_n$ also converges
>
> If $L_1 \gt 0$ and $\sum_{n=0}^\infty b_n $ diverges, then $\sum_{n=0}^\infty a_n$ also diverges.
**Request:** _Can you provide a proof for this theorem? And can you please provide it in a way that stresses on understanding of the limit superior and inferior concept?_ It what I am having trouble getting my head around. Thanks in advance. | To say that $\displaystyle \limsup_{n \to \infty} \frac{a_n}{b_n} = L_2$ means: first, for any positive $\epsilon > 0$ there exists $N$ with the property that $n \ge N$ implies $\dfrac{a_n}{b_n} < L_2 + \epsilon$, and second, $L_2$ is the least number with this property.
This is more than is required. It suffices to know that for some $N$, $\dfrac{a_n}{b_n} < 2L_2$ for all $n \ge N$. Then $$n \ge N \implies a_n < 2L_2 b_n,$$ and since $\displaystyle \sum_{n=N}^\infty 2L_2 b_n$ converges, so does $\displaystyle \sum_{n=N}^\infty a_n$ by the usual comparison test. Adding the first $N-1$ terms does not affect convergence.
You can do the other problem using the comparison test for divergence and use $L_1/2$ as the lower bound of the ratio. | stackexchange-math | {
"answer_score": 2,
"question_score": 0,
"tags": "calculus, real analysis, sequences and series, analysis, limsup and liminf"
} |
how to remove an NSMutableArray object by key?
i have structured an NSMutableArray and here is an example
> ( { Account = A; Type = Electricity; }, { Account = B; Type = Water; }, { Account = C; Type = Mobile; } )
when i try to delete Account B using
> [data removeObject:@"B"];
Nothing Happens
[[NSUserDefaults standardUserDefaults] synchronize];
NSArray *archivedArray = [NSKeyedUnarchiver unarchiveObjectWithFile:[self dataFilePath]];
if (archivedArray == nil) {
data = [[NSMutableArray alloc] init];
} else {
data = [[NSMutableArray alloc] initWithArray:archivedArray];
} | If you're actually using an array and not a dictionary, you need to search for the item before you can remove it:
NSUInteger index = [data indexOfObjectPassingTest:^BOOL (id obj, NSUInteger idx, BOOL *stop) {
return [[(NSDictionary *)obj objectForKey:@"Account"] isEqualToString:@"B"];
}];
if (index != NSNotFound) {
[data removeObjectAtIndex:index];
} | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 1,
"tags": "objective c, ios, xcode"
} |
Macro in Excel 2016
I am using the below macro for extracting data in excel 2013 now i have shifted to excel 2016. In excel 2016 the macro is not working.
Sub simpleXlsMerger()
Dim bookList As Workbook
Dim mergeObj As Object, dirObj As Object, filesObj As Object, everyObj As Object
Application.ScreenUpdating = False
Set mergeObj = CreateObject("Scripting.FileSystemObject")
Set dirObj = mergeObj.Getfolder("path")
Set filesObj = dirObj.Files
For Each everyObj In filesObj
Set bookList = Workbooks.Open(everyObj)
Range("A2:IV" & Range("A65536").End(xlUp).Row).Copy
ThisWorkbook.Worksheets(1).Activate
Range("A65536").End(xlUp).Offset(1, 0).PasteSpecial
Application.CutCopyMode = False
bookList.Close
Next
End Sub
Can someone help me resolving this issue | Try this:
Sub simpleXlsMerger()
Dim bookList As Workbook
Dim mergeObj As Object, dirObj As Object, filesObj As Object, everyObj As Object
Application.ScreenUpdating = False
Set mergeObj = CreateObject("Scripting.FileSystemObject")
Set dirObj = mergeObj.Getfolder("path")
Set filesObj = dirObj.Files
For Each everyObj In filesObj
Set bookList = Workbooks.Open(everyObj)
'EDIT
With bookList.Sheets(1)
.Range("A2:IV" & .Range("A65536").End(xlUp).Row).Copy _
ThisWorkbook.Worksheets(1).Range("A65536").End(xlUp).Offset(1, 0)
End With
'/EDIT
bookList.Close False
Next
End Sub | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "vba, excel"
} |
Libvlc Chromecast .m3u8 in Android
can someone help me with LibVLC. I need create a simple app to cast .m3u8 in Chromecast.
I already try Cast SDK, but won't work for my .m3u8 I think need Transcoding on-the-fly and I think LibVLC v3 can handle with that.
you can help me with that ? | As someone who struggled with LibVLC on Android for too long, I advise you move to ExoPlayer. It supports HLS media source (m3u8) and it is specifically made for Android ease of use.
HLS - ExoPlayer - Implementation Official Docs | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "android, casting, libvlc"
} |
Inserting individual values into table based on a number
Here is my problem: I have a stored procedure in SQL Server 2012 which should do the following thing.
I will pass an input parameter `@Range`, and the stored procedure should insert values into a table starting from 0 to `@Range-1`.
CREATE PROC MyExample
(@Range INT)
AS
BEGIN
// Suppose the value of @Range is 100
// So I should do INSERT into MyTable Values(0,1,2,3,4,5,6,......99)
END
Any idea how to achieve this? | I am thinking your teacher may suspect why you use cte when you just learn a loop
CREATE PROC MyExample
(
@Range INT,
)
AS
BEGIN
;WITH numbers AS
(
SELECT 0 AS Value WHERE @Range >= 0 -- Validate the @Range value too, try 0 or negative values
UNION ALL SELECT Value + 1 FROM numbers WHERE Value + 1 < @Range
)
INSERT INTO MyTable
SELECT * FROM numbers
OPTION (MAXRECURSION 0)
END | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "sql, sql server"
} |
Admin On Rest Show Custom Message
I'm using admin on rest. Sometimes I must show message to user. I'm using alert() function for now but this is worst. How can I show this notification? I didn't find the command for this.
{
$items="120,130,140,150";
Cache::put('Ids', $items, 55);
return response()->json(['success' => true], 200);
}
function getIds(){
$ids = Cache::get('Ids');
var_dump($ids); //null
}
I'm storing cache value to one function and try to access another function but not able to get `null` value
I have set `CACHE_DRIVER=array` .env file of laravel project
Can I change Cache driver runtime? | Yes, you can set and get Cache driver runtime.
**SET**
Cache::store('file')->put('Ids', $items, 55);
**GET**
Cache::store('file')->get('Ids'); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "laravel"
} |
Mac Desktop Version
Is there any way to set a version number for Mac OS Desktop apps in CN1? It always shows 1.0 no matter what I write in build.xml.
I can't find any build hint that could help either.
Thanks | I see a problem here, we'll fix it for the coming update so the version from the Codename One Settings app will be respected. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "codenameone"
} |
Persistence of entity in more than one step (ASP.NET MVC 4)
My friends, i've come trhough a situation i haven't come before. I have one entity (aka Person ;) that i need to save. But the thing is that i have groups of information of a person that i wish to ask for the user to input in more than one controller, this way the user won't have to fill a extense form. He'll go in steps filling the forms for Personal Info, Academic Info, Job History Info, etc. I'm using MVC 4. Do I have to create one controller to each form/view? Because my entity has all atributes i need to persist at once (by the way i plan to use an ORM, haven't decides if it will be NHibernate or Entity Framework yet). Thx. | You do not need to create a new controller for each view. That's actually not what you want to do. Sounds like you may be coming from WebForms, which would require a different page for each form.
MVC doesn't work like this. Just simply create a new action and view for each page.
As far as persisting data, there are numerous ways to do this. You can use session data, or more preferably, a database(model) to store the data. You can use something like ADO.NET/Entity Framework to help with this so you don't have to mess with the dirty database details. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "asp.net, asp.net mvc 4, nhibernate, orm, entity framework 5"
} |
Removing unused Rows from jTable
How do I remove unused rows from a `JTable`?
I first create a table of a fixed size in a `JPanel` and then fill elements as needed.
Now I don't want unused rows to be displayed in my table. Please help. | > I presently get a table with lots of empty rows in bottom, only top 5-6 rows being used, with rest blank. I want to hide them or remove them somehow
Work the other way around. Start with an empty DefaultTableModel. DefaultTableModel supports an `addRow()` method. So, as you get data to add to the model use:
model.addRow(...);
Don't let the GUI editor determine how you code your GUI. Adding cleanup code to remove rows is a bad design. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "java, swing, jtable, rows, defaulttablemodel"
} |
Computing the limit of an alternating series,
I am looking at the series
$$ \sum_{n=1}^\infty\frac{(-1)^n}{n}.$$ This series converges (conditionally) by the alternating series test. How can I compute its limit, which is equal to -log(2)?
a) I considered $I_n = \int_{0}^1$ $\frac{x^n}{1+x} dx$ -- and showed that this goes to 0, as n goes to infinity (use dominated convergence theorem).
b) I computed [$I_k$ + $I_{k-1}$] (for k $\ge$ 1), and it equals $\frac{1}{k}$.
I should be using my results from a) and b) to compute the above limit, which is part c) of the question that I am working on.
So, I have $$ \sum_{n=1}^\infty\frac{(-1)^n}{n} = \sum_{n=1}^\infty(-1)^n[I_n+I_{n-1}].$$
Now I'm stuck. How should I proceed from here?
I checked, by computing explicitly, that $-I_0$ = -log(2). But I don't know how to arrive at $-I_0$ from the summation that I'm currently at.
Thanks in advance, | You should have gotten $\displaystyle\sum_{n = 1}^{\infty}\dfrac{(-1)^n}{n} = \sum_{n = 1}^{\infty}(-1)^n(I_{n-1}+I_n)$. (You forgot the summation sign).
Now, look at the partial sums:
$\displaystyle\sum_{n = 1}^{N}(-1)^n(I_{n-1}+I_n) = -(I_1+I_2)+(I_2+I_3)-(I_3+I_4)+\cdots+(-1)^N(I_{N-1}+I_{N})$.
A lot of terms cancel. Now, take the limit as $N \to \infty$ to get the desired result. | stackexchange-math | {
"answer_score": 2,
"question_score": 2,
"tags": "real analysis, sequences and series, limits, convergence divergence"
} |
Equivalent of "coal plant" for oil
How do you refer to a power generation station that derives its energy from burning oil, rather than coal?
I looked up "oil plant", on onelook.com, thinking that it'd also be used to mean a place where oil is refined, but instead I ended up on Wikipedia's page on vegetable oil, indicating yet another meaning of "oil plant". | I believe the conventional terms are "coal-fired power plant" and "oil-fired power plant". You can drop the "power", especially if the context is clear, and just say "coal-fired plant" and "oil-fired plant". See, e.g. < | stackexchange-ell | {
"answer_score": 6,
"question_score": 4,
"tags": "phrase request"
} |
Python - how to reference one object to another
more basic questions i'm struggling with...
Give the basic code below... how does the person object get the address "attached" to it.
class Person(object):
def __init__(self, fn, ln):
self.uid = Id_Class.new_id("Person")
self.f_name = fn
self.l_name = ln
class Address(object):
def __init__(self, st, sub):
self.uid = Id_Class.new_id("Address")
self.street = st
self.suburb = sub
s = Person('John', 'Doe')
hm = Address('Queen St.', 'Sydney') | Try:
class Person(object):
def __init__(self, fn, ln, address):
self.uid = Id_Class.new_id("Person")
self.f_name = fn
self.l_name = ln
self.address = address
class Address(object):
def __init__(self, st, sub):
self.uid = Id_Class.new_id("Address")
self.street = st
self.suburb = sub
hm = Address('Queen St.', 'Sydney')
s = Person('John', 'Doe', hm) | stackexchange-stackoverflow | {
"answer_score": 9,
"question_score": 5,
"tags": "python, class"
} |
Instantiate dynamically buttons on vertical layout group
I have the following hierarchy:
{
foreach (Question elem in questionList)
{
GameObject child = Instantiate(questionButton);
child.transform.SetParent(questionButton.transform,false);
child.GetComponent<Text>().text = elem.answer;
}
}
But does not seem to work properly, it doens't get ordener with the layout:
;` Should be changed as you are setting the parent as the questionButton. You should be setting it as the layout group. So instead:
public GameObject layoutGroup;
...
child.transform.SetParent(layoutGroup.transform,false); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "unity3d, layout, gameobject"
} |
CURAND properties of generators
CURAND comes with an array of random number generators, but I have failed to find any comparison of the performance (and randomness) properties of each of them; mostly, I'd be interested in which generator to use for which application to gain maximum performance. I'd be happy if someone could quickly outline the differences between them or link me a resource that does so.
Thanks in advance. | This picture shows the performance for different RNGs.
!Speed of cuRAND RNGs
For randomness, it should be only related to the RNG type/algorithm. So you can refer to Intel MKL doc. There's detail info and research papers in it. The type names in both CURAND and MKL are very similar.
< | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "cuda, prng"
} |
AlertDialog and SherlockActivity
Im struggling to get a AlertDialog working whilst in an onClick method of a Sherlock activity. Here is my code.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Ooops!!");
builder.setMessage("Sorry.");
builder.setPositiveButton("OK", null);
AlertDialog dialog =builder.create();
dialog.show();
Its `new AlertDialog.Builder(this)` where the problem is. `This` is underscored as an error, I also tried `getActivity()` which is common in Sherlock but no luck. Any ideas or direction? | Replace this
AlertDialog.Builder builder = new AlertDialog.Builder(this);
By
AlertDialog.Builder builder = new AlertDialog.Builder(ActivityName.this);
I guess you use `AlertDialog.Builder(this)` in `onClick` of your activity in which case it does not refer to the activity context. So use `ActivityName.this` where ActivityName is the name of your Activity. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "android, actionbarsherlock, android alertdialog"
} |
Force SPA Add to home screen popup to display even after adding to home
I am developing a PWA using react JS
There is a requirement that we need to display the add to Home screen even after the App has been added to the Home screen for the first time
Can any body suggest if this is possible and how?
INFO: Mostly this app will be run on Google Chrome and Safari | Refer to this answer. You simply can't do that, unless you want to do it in specific development/test machines where you can set the below chrome flag,
chrome://flags/#bypass-app-banner-engagement-checks
You can't expect all your end users to set this flag, so this can't be a solution for all the real users.
I also don't see why you would have to show the banner even after adding to home screen, for any other use case. Browsers don't allow this for obvious reasons. It will be annoying the user, if the prompting is left to developers. Linked answer have more clarification on the same. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "reactjs, google chrome, progressive web apps"
} |
Does OpenUDID persist even if you have removed the app?
I am researching UDID alternatives, and OpenUDID seems interesting.
I have done some testing and if I remove the app, and re-install again, the value of OpenUDID remain the same, I am just wondering how they do that and is the value always guaranteed to persist if I don't hard reset the phone. | Giving a quick glance at the naming conventions they use, I'd say they are almost certainly using the iOS keychain. This is the same as the OS X keychain, except it doesn't allow end users direct access the way Mac OS X does. Even if the app is uninstalled, this information will not be removed. It is stored in a controlled environment to prevent jailbreakers from getting it. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "iphone, ios, objective c, udid"
} |
When the column values for UID and GID fields in /proc/<pid>/status file will differ
Here is the output of a sample **/proc/pid/status** file.
From the **procfs(5)** Man page, found that those are _Real, Effective, Saved and FileSystem UIDs_
Uid: 998 998 998 998
Gid: 996 996 996 996
Here all are showing same values.
So, in any chance those four columns will show different UIDs. Especially among Real, Effective and Filesystem UIDs. | Taking this as a question:
> So, in any chance those four columns will show different UIDs.
Yes. Subject to various limitations, processes can change their effective and saved UIDs and GIDs. This is what the `setuid()`, `setgid()`, `seteuid()`, and `setegid()` functions do.
The filesystem uid and gid are Linux-specific features that are used mainly, if not entirely, in the context of NFS (see filesystem uid and gid in linux). These can be manipulated with `setfsuid()` and `setfsgid()`, subject, again, to limitations.
For most processes, all the UIDs will the same and all the GIDs will be the same, but it is conceivable that they would all be different. It is a function of the behavior of the process. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "linux, process, procfs"
} |
Differentiate $\frac{-y}{x^2+y^2}$ with respect to $y$
I want to differentiate this, with respect to $y$:
$\frac{-y}{x^2+y^2}$
I try to derivate with the product rule as:
$(-y(x^2+y^2)^{-1})'_y$ => $-(x^2+y^2)^{-1} + 2y^2(x^2+y^2)^{-2}$
However this is not correct, what am I doing wrong? | hint: we get $$\frac{-(x^2+y^2)+y\cdot 2y}{(x^2+y^2)^2}$$ by the Quotient rule. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "calculus, multivariable calculus, derivatives, partial derivative"
} |
How long will take from an average C# developer to an average Java developer?
I know the ideas and features between C# and Java programming language is very similar. So as a senior C# web developer(average) how long will it take to make it feel comfortable programming Java web applications? Will it just like from VB.net to C#? | It won't be just like VB.NET to C#.
If you're an average .NET developer, it shouldn't take long at all before you're comfortable with the Syntax of Java. What is going to take a little longer is learning the different Web frameworks for Java Web Applications and how everything fits together.
That last part is going to take the majority of your time. How long exactly is anybody's guess. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 0,
"tags": "c#, java"
} |
C# inherit from nested class within itself
Is it possible for a class to inherit from a nested class, or to implement a nested interface in C#?
class Outer : Outer.Inner {
class Inner { ... }
...
} | In the way that you wrote, no (see this). But if your inner interface is in another class, then you can.
public class SomeClass : SomeOtherClass.ISomeInterface {
public void DoSomething() {}
}
public class SomeOtherClass {
public interface ISomeInterface {
void DoSomething();
}
} | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "inheritance, c# 3.0"
} |
Application crashed when orientation change
Actually my problem is the same as the question posted in : the same problem
But there is no answer yet..
**Here is the problem I got :**
I've just built an application using sencha touch & phone gap. It runs well on my galaxy tab but when I rotate it to portrait or landscape, it is going crash.
I have added :
android:configChanges="orientation|keyboardHidden"
on my manifest file but it is still going crash when I rotate it.
I don't know how could this happen.
Could someone help me?
Note :
I'm using
\- Galaxy tab
\- Sencha-touch 1.1
\- Phone gap 1.2 | You should have
android:configChanges="keyboardHidden|orientation|screenLayout"
instead of
android:configChanges="orientation|keyboardHidden"
to your activity in the manifest | stackexchange-stackoverflow | {
"answer_score": 9,
"question_score": 7,
"tags": "android, cordova, sencha touch, extjs"
} |
How to make an argument in python accept multiple inputs
I am still new to python; so, sorry for the somewhat vague question. I was just curious if it is possible to add more than one input to an argument. For example:
def censored(sentence, word):
if word in sentence:
sentence = sentence.replace(word, "*" * len(word))
return sentence
print censored("foo off", "foo")
This will print out "**** off". Which is what I wanted; but, what if I want to add another input other than "foo".
Is there another way to do that without having to add a third, fourth, and nth argument in the function? | Of course you could pass a list, but also you could just use *args. It sometimes depends on how you expect to use the function.
def censored(sentence, *args):
for word in args:
if word in sentence:
sentence = sentence.replace(word, "*" * len(word))
return sentence
print censored("foo off", "foo", "bar")
Or as a list or iter
def censored(sentence, words):
for word in words:
if word in sentence:
sentence = sentence.replace(word, "*" * len(word))
return sentence
print censored("foo off", ("foo", "bar"))
print censored("foo off", ["foo", "bar"])
Here is a good SO for *args and **kwargs | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 1,
"tags": "python"
} |
how to start a global thread in swift
Is there any way to start and stop a thread in swift along with it making the thread global also so that it can used anywhere.
As shown below, this is how i create thread in swift
var objThrd = SimpleClass()
let thread = NSThread(target: objThrd , selector: "createSimpleObj", object: nil)
Please give an example if feasible. Or can we achieve this via NSOperation ? | Use Grand Central Dispatch
let myQueue: dispatch_queue_t = dispatch_queue_create("com.example.queue", nil)
dispatch_async(myQueue, { () -> Void in
// Execute some code
}) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 3,
"tags": "ios, iphone, multithreading, swift"
} |
Notifying an admin of a new registration using Devise
All of my users will be unapproved until they are approved by an admin, the admin will be logging into the site to mark the user as approved. I am following the Devise docs here which is working out great but how do I send an email to the admin once a new user has signed up so that the admin is aware and can approve the sign up? | How about in your User model, do something like this:
after_create :send_admin_mail
def send_admin_mail
###Send email stuff here
end
You may want to use ActionMailer.
There may be some built in Devise way, but I can't find anything. This basically just sends an alert to you. | stackexchange-stackoverflow | {
"answer_score": 9,
"question_score": 5,
"tags": "ruby on rails, ruby on rails 3, devise"
} |
Newer CouchDB/Sofa Tutorial
**Is there a newer version of theSofa tutorial for CouchDB?** I'm trying to follow the examples given in the text, but they are wildly different than the Sofa source code cloned from <
If not, are any other step-by-step guides or tutorials for CouchDB beginners recommended? | You might find the Kanso docs useful, there are guides covering lots of topics starting from the basics: < | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "couchdb, couchapp"
} |
how to remove at once text/character from both sides of a given character/text (#regex)?
What is the simplest way of removing text on both left and right side of a given character/text in `r`?
I have an example of the following dataset: `a = c("C:\\final docs with data/Gakenke_New_Sanitation.xlsx", "C:\\final docs with data/Gatsibo_New_Sanitation.xlsx", "C:\\final docs with data/Rutsiro_New_Sanitation.xlsx")`
My expected output is to remain with: **Gakenke, Gatsibo** and **Rutsiro**.
I know, I can breakdown this task and handle it using `mutate()` as the following:
`a %>% mutate(a = str_remove(a, "C.+/"), a = str_remove(a,"_.+"))`.
My question now is which simple `pattern` can I pass to that mutate function to remain with my intended results: **Gakenke, Gatsibo** and **Rutsiro**.
Any help is much appreciated. thank you! | You can use
a = c("C:\\final docs with data/Gakenke_New_Sanitation.xlsx", "C:\\final docs with data/Gatsibo_New_Sanitation.xlsx", "C:\\final docs with data/Rutsiro_New_Sanitation.xlsx")
library(stringr)
str_remove_all(a, "^.*/|_.*")
## => [1] "Gakenke" "Gatsibo" "Rutsiro"
The `stringr::str_remove_all` removes all occurrences of the found pattern. `^.*/|_.*` matches a string from the start till the last `/` and then from the `_` till end of the string (note the string is assumed to have no line break chars). | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 3,
"tags": "r, regex, stringr"
} |
Is it possible to know if function uses empty return statement?
Is it possible to know if a function uses an empty return statement versus simply not using the return keyword?
For example:
function noReturn(){ }
function useReturn(){ return; }
console.log( noReturn() ); // undefined
console.log( useReturn() ); // undefined
I know all about WHEN and WHY one would use an empty return statement, I just want to know if you can tell if `return;` was used at all versus no return statement.
I'm assuming that its not possible, and thats ok. If there was any cool Function prototype trick I didn't know of, that would be sweet.
* * *
Edit: Not trying to solve any particular problem, unless general curiosity is a problem. :) | You cannot distinguish return values of these three functions:
function a() { }
function b() { return; }
function c() { return undefined; }
according to JS specification. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 3,
"tags": "javascript"
} |
Find the minimum value of $|1-1.1y+0.8x|$.
Given $x\le 5$ and $y>5$. I want to minimize th function $|1-1.1y+0.8x|$.
By trial my assumption is $|1-1.1y+0.8x|>0.5$. But I am unable to prove this.
If I'm right then how to prove this ? If I'm wrong then what will be the minimum value ?
Any help plase ? | Given $x\le 5$ and $y>5$. Let $$F=1-1.1y+0.8x$$
$$y>5 \implies -1.1y<-5.5$$ and $$x\le 5\implies 0.8x\le 4$$
So $$F<1-5.5+4 =-0.5\implies |F|>0.5$$ | stackexchange-math | {
"answer_score": 2,
"question_score": -1,
"tags": "real analysis, algebra precalculus, inequality, optimization, maxima minima"
} |
suppress an unused variable warning
How can I suppress the inspection in Kotlin for an unused variable
`val xyz = abc`
I get the squiggly line but `ALT-ENTER` is useless for this, I tried also to create in another method several variables unused and they also lack the `ALT-ENTER` ability to ignore the warning. Although I have definitely used `ALT-ENTER` for this in the past, although maybe it was only in java, can't remember.
So I must manually construct it by hand. I've been trying several variations but I can't get anything to work. Please tell me the correct `//noinspection` or `@SupressWarnings` to use, thanks | In IntelliJ IDEA, a right-side arrow on an ALT+ENTER context menu (like this: 
val unused = ""
If you do not get the initial context menu (`Remove variable '...'`), you may have disabled the "Unused assignment" inspection in your current project. You can fix this by going to Settings -> Editor -> Inspections. | stackexchange-stackoverflow | {
"answer_score": 14,
"question_score": 8,
"tags": "kotlin"
} |
Dart final keyword performance impact
I am aware that once assigned a value, a `final` variable's value cannot be changed. Does the keyword `final` have a positive **performance** impact compared to a not-final variable? | For local variables, there is no advantage. Any competent compiler can detect whether a local variable is assigned to, whether it's declared `final` or not.
For instance variables, it's harder to detect whether there is a subclass overriding the variable, or some other implementation of the interface. That means that even if the variable is final, the compiler can rarely trust that for anything. A compiler with access to the whole program might detect that there is no assignment anywhere. It makes a difference for your API though.
For static and top-level variables there might be a slight advantage in making the variable final. It means that local analysis can know that the value won't change, even without seeing the entire program.
All in all, anything but local variables, you should make unchanging variables final because it's good modelling, not because you worry about performance. For local variables, it doesn't matter. | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 6,
"tags": "dart"
} |
Sort Array in Controller
Hello I'd like to sort an array in a Rails Controller. I want to sort the array before I loop over it in the View
@projects = Project.all.sort #throws error
#and
@projects = Project.all
@projects.sort # throws error
throws this error: undefined method `<=>` for `#<Project:0x101f70b28>` but when I query:
@projects.respond_to?('sort')
I get true
How can I sort the array? Should it be done in the View or in the Controller? Any help is highly appreciated! | Ruby doesn't know how to sort your project. You must specify the field to use for the sort. Example for `created_at`:
@projects = Project.all.sort { |p1, p2| p1.created_at <=> p2.created_at }
or
@projects = Project.all.sort_by &:created_at
Alternatively, you can sort them at database level:
@projects = Project.find(:all, :order => 'created_at') | stackexchange-stackoverflow | {
"answer_score": 15,
"question_score": 2,
"tags": "ruby on rails, ruby"
} |
Wiggle (shake) effect within my app is freezing the iPhone (iOS 5)
In my iOS app I have a screen with a bunch of icons that have a wiggle effect. When I press and hold one of them they start to shake (like iphone's menu) but if I press the home button (to send my app to background) the iphone freezes! After some time, it restarts itself. This is the source I'm using to do the effect:
CABasicAnimation* anim = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
[anim setToValue:[NSNumber numberWithFloat:0.0f]];
[anim setFromValue:[NSNumber numberWithDouble:M_PI/30]];
[anim setDuration:0.1];
[anim setRepeatCount:NSUIntegerMax];
[anim setAutoreverses:YES];
[self.layer addAnimation:anim forKey:@"SpringboardShake"];
And to stop:
[self.layer removeAllAnimations];
This problem only happens in iOS 5. The same code works fine in iOS 4. Any ideas about what would be making my device freezes? | The same problem occured with me. A solution can be found here.
To have a smooth animation, you need to increase your calculations speed. So, one form is decreasing the things we need to calculate. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "ios, objective c, ios5, icons, home button"
} |
Reducing the function from two variables to one
$$S=\max\left\\{{|x-y|\over1+x+y}:0<y<1\right\\}\,\,\,\,\forall\,\,\,0<x<1$$
How do I even start this? I can maxmize the numerator by putting $y=0$ for $x\in[1/2,1)$ and $y=1$ for $x\in(0,1/2]$ but since y is in demonimator too they wont necessarily be maxmimas or minimas
Any hints?
We need to find incresing/decresing intervals for $S$ | Maximize the ratio over $0<y\leq x$, then maximize over $x<y<1$ and then take the maximum of the two numbers you get. For $0<y\leq x$ the ratio is a decreasing function so its maximum is attained at $y=0$. For $x<y<1$ teh ratio is increasing, so its maximum is attained at $y=1$. | stackexchange-math | {
"answer_score": 2,
"question_score": 0,
"tags": "maxima minima"
} |
How are the runways operated at Toronto Pearson?
I have a sort of technical question regarding the operations of runway systems at larger airports, specifically at Toronto Pearson (satellite view here). As far as I can see, the airport has 5 runways: 05, 15L/R, and 06L/R.

Since RW05 and RW15L/R intersect it is clearly infeasible to operate RW05 at the same time as RW15L / RW15R. As for the rest, there are several ICAO guidelines regarding parallel or near-parallel runways. What do those restrictions imply regarding simultaneous operations?
* Is it possible to operate RW06L and RW06R simultaneously, maybe in a segregated mode of operation? What about RW15L/R?
* Similarly, can runways 15 and 06 be operated simultaneously? | According to Toronto Pearson's official website, the airport operates in four main configurations, this is what they look like:
 can be used simultaneously. (It resulted in a near-miss back in 2002.) | stackexchange-aviation | {
"answer_score": 2,
"question_score": 3,
"tags": "air traffic control, runways, icao, transport canada, airport operations"
} |
Jasper Report : set sheet name when export to xls file
I want set sheet name for my xls file when i export from jasper report. I have tried this net.sf.jasperreports.export.xls.sheet.names.all = value. but the value must be set from field that i retreive from database. is it possible? or anyone have tried before? | Yes, you can use something like
<propertyExpression name="net.sf.jasperreports.export.xls.sheet.name">
<![CDATA[$F{FieldName}]]>
</propertyExpression>
For more details you can checkout < | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "jasper reports"
} |
Advantages of using mac version of Ubuntu
I was trying to use the mac alternate ISO to install ubuntu and it wasn't working out. I'm pretty sure I could fix, but I wanna know if it is worth it. What advantages does it offer for MBP 2010 15 inch. | The mac image is designed to be compatible with most macs. The reason being that mac's have specific hardware requirements and tweaks to get things running smoothly. The Apple firmware by default uses a GPT table to boot OSX in EFI or UEFI mode.
The most common reason to use the Mac iso however is that they are more likely to be seen by the firmware and thus be able to boot and install on your Apple machine without issue.
There is a very good explanation by Colin Watson here. | stackexchange-askubuntu | {
"answer_score": 0,
"question_score": 0,
"tags": "system installation"
} |
Problem adding leading zeros to a nested SELECT value using SQL Server 2016
I am trying to add leading zeros to an nvarchar data type value that needs to be a length of 9 but I'm not having any luck with my attempts. I am building a flat file and every field is an nvarchar data type.
Here is my original SQL code:
SELECT (SELECT MAX([Record Number])+1 FROM #tempFINAL) as [Record Number]
After doing some googling here is attempt #1:
SELECT RIGHT(REPLICATE('0', 9) + (SELECT MAX([Record Number]+1) FROM #tempFINAL), 9) as [Record Number]
Here is attempt #2:
SELECT RIGHT('000000000' + (SELECT MAX([Record Number]+1) FROM #tempFINAL), 9) as [Record Number]
Neither attempts worked. Any help/direction would be appreciated. I must be missing something fairly easy. Thanks. | Sean is correct, your mixing a string with an int. Here are 4 quick options:
Select [Record Number] = Format(max([Record Number])+1,'000000000') from #tempFINAL
Select [Record Number] = right(concat('000000000',max([Record Number])+1),9) from #tempFINAL
Select [Record Number] = right('000000000'+convert(varchar(10),max([Record Number])+1),9) from #tempFINAL
Select [Record Number] = right('000000000'+left(max([Record Number])+1,10),9) from #tempFINAL | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -1,
"tags": "sql server, tsql"
} |
Floating Draggable Box Disappearing on Resize
I am trying to create a floating window that stays within the margins on resize:
You can check out the code.
<
How do I accomplish this?
$(function()
{
$("#result").draggable();
});
#result
{
border:1px solid #000;
width:375px;
position:absolute;
z-index:100;
left:75%x;
top:100px;
margin-left: -10px;
margin-top: -50px;
cursor:move;
color:black;
}
<div id="result" class="ui-widget-content" >
<div style="background-color:#096db5;color:white;font-size:9px;text-align:center;">
click window to drag
</div>
<div id="info">
blah
</div>
</div> | I finally found a script that will automatically center the box when it hits an margin on resizing.
source:
<
this is the final code:
$(window).resize(function(){
$("#result").position({
of: "#wrapper",
my: "center middle",
at: "center middle",
collision: "fit flip"
})//$("#result").position({
});//$(window).resize(function(){ | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "jquery, html, css, draggable"
} |
splitting file and how to access certain index python
my code reads in python
>
> openFile=open(filename,"r")
> for lines in openFile.readlines():
> line = lines.strip()
> if line:
> tabsplit=line.split("\t")
> print(tabsplit)
>
>
>> which yeilds this...
>
> ['-120.066667 35.000000 844']
> ['-120.050000 35.000000 916']
> ['-120.033333 35.000000 971']
> ['-120.016667 35.000000 1103']...
>
I am not understanding why when i go to print(tabsplit[2]) it says
IndexError: list index out of range
what i want is to be able to access each value, so that when i say
print(tabsplit[0]) i get all the -120.06,-120.05...
I wrote a code for a different type of file that works just fine, this is why i am confused, to why it is not working.
any ideas? | try
tabsplit=line.split()
you dont actually have a tab character in your file instead you have consecutive whitespace
it mat have been a tab at somepoint... but then some editor changed it to being seperated by consecutive white space | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python"
} |
How can I find this limit? L'hopital's rule is never-ending
I have the following limit $$ \lim_{x\to\infty}\frac{-7^x}{(\ln11-\ln7)\cdot11^x}$$ Graphing gives me $0$ but plugging it in gives infinity over infinity.
I then tried L'Hôpital's rule and it seems to fall into a never ending loop. I can't seem to simplify this - what would be the best way to find the limit?
Edit: would like to clarify I want to know how to find it algebraically | You can write the expression as $-\left(\ln \frac{11}{7}\right)^{-1} \left(\frac{1}{(11/7)}\right)^x$, which goes to zero as $x \rightarrow \infty$ | stackexchange-math | {
"answer_score": 4,
"question_score": 0,
"tags": "calculus, limits"
} |
It's about black holes
If is was to stand deep inside the center of a black hole and was to point a light gun straight up at the center of the event horizon, would the beam of light make it out of the black hole? | Light from OUTSIDE the black hole that passes through the event horizon cannot escape, and observers from the outside will never see light emerging from the interior. I'm not sure what you mean by suggesting that one could stand deep inside with a flashlight. Absent a quantum theory of gravity, we really don't know how physics behaves in the center of a black hole (except, of course, that a person surviving with an intact flashlight is impossible). If your followup question concerns what things are like inside, I'm afraid you will be disappointed. | stackexchange-physics | {
"answer_score": 0,
"question_score": 0,
"tags": "black holes"
} |
How to find the range of this expression
I have :
$$ \frac{x^2+2x+1}{x^2+2x+7} $$
Where x is real.
I need to find out its range.
I tried:
Let $ \frac{x^2+2x+1}{x^2+2x+7} = y $
Which gives me: $ 24y^2 - 28y + 3 =0 $
And I am confused what to do next. | $$ \frac{x^2+2x+1}{x^2+2x+7}\geq0,$$ where the equality occurs for $x=-1$,
which says that $0$ is a minimal value. $$ \frac{x^2+2x+1}{x^2+2x+7}=1-\frac{6}{x^2+2x+7}<1$$ and since $$\lim_{x\rightarrow\infty}\frac{x^2+2x+1}{x^2+2x+7}=1,$$ we see that $1$ is a supremum and since our expression is continuous, we got the answer: $$[0,1)$$ | stackexchange-math | {
"answer_score": 0,
"question_score": 0,
"tags": "quadratics"
} |
Find regex pattern occurence as late as possible
I am trying to extract information from a string such as the following: `"Hello test 1 23 45 678 901 234 C test test2"`
I would like to extract `23 45 678 901 234 C`
The best regex I could come up with is `(\d\s?){13}C?` (C and the spaces are optional)
However, that regex extracts `1 23 45 678 901 23` instead of the pattern I want. I know that regex scans the string from left to right, which explains this behavior... Is there any way to extract this information?
Thanks in advance. | I suggest
\d(?:\s?\d){13,}(?:\s?C)?
See the regex demo.
_Details_
* `\d` \- a digit
* `(?:\s?\d){13,}` \- thriteen or more occurrences of an optional whitespace and then a digit
* `(?:\s?C)?` \- an optional occurrence of an optional whitespace and then a `C`.
You may choose the threshold you want, e.g. `{13,14}` or just `{14}`, and if `C` is obligatory, you need to remove the last `(?:` and `)?` and use `\d(?:\s?\d){13,}\s?C`. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "regex, string, expression"
} |
Which of Terry Tao's co-authors on compressed sensing consulted for Renaissance Technologies?
On Feb 11 2018 on Quora, Vladimir Novakovski commented
> Terry is Tier One in the RenTec world. His coauthor on compressed sensing did some consulting for them, actually.
Who's this co-author? | The is the article you are looking for:
Stable Signal Recovery from Incomplete and Inaccurate Measurements
Emmanuel Candes, Justin Romberg, Terence Tao
It provided the basis for compressed sensing. | stackexchange-quant | {
"answer_score": 2,
"question_score": 2,
"tags": "history"
} |
Visual Microsoft Visual C++ Compiler for Python 2.7 vs MinGW
I am making some functions in c which I am going to call from Python via Cython. I am developing these functions in Code:Block using MinGW C++ compiler. But when building them for Python I have to use Visual Microsoft Visual C++ Compiler for Python 2. Then I have met a strang problem. When compiling with Visual C++ compiler I have after a lot of trial and fail found out that all variables have to be decleared before first in each block (if, for, function). Why is so. Are there difference between compilers for c? | MSVC mostly adheres to the original C89 spec. In later revisions of the language this restriction has been lifted. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python, c, cython"
} |
C# How to check if a string contains a specifc combination of chars
I have a List, named `values` which contains values similar to the following string values:
`GKgpuzjBUh IS1bbf2ffd806f6d IS102a8a395ced93 Dark Von Diakonov IS148159f7c24f78`
I need to check if the specific a string in the starts with `IS1` | You dont need regex. Use `str.StartsWith("IS1")`. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -2,
"tags": "c#, string, list"
} |
PHP Query - Exclude if exist in table
orderfood
orderfood_id food_id total_amount
foodcancel
foodcancel_id food_id status
$query = $this->db->query("SELECT * FROM order_food of LEFT JOIN `foodcancel` fc ON of.food_id = fc.food_id WHERE of.orderfood_id = '" . (int)$orderfood_id . "'");
$order_foods = $query->rows;
above is my query, what i wanted is that if there food_id inside foodcancel table , exclude it from rows, possbile to do it ? | For exclude the existing values you could try checking null for corresponding matching value
SELECT *
FROM order_food of
LEFT JOIN foodcancel fc ON of.food_id = fc.food_id
and of.food_id = your_value
WHERE fc.orderfood_id is null
anyway you should not php var in your sql code because in this way you are are risk for sqlinjection for avoid this you should take a look at prepared statement and binding param | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "php, mysql"
} |
Why does Go use ^ rather than ~ for unary bitwise-not?
Most programming languages use `~` to represent a unary bitwise-not operation. Go, by contrast, uses `^`:
fmt.Println(^1) // Prints -2
Why did the Go designers decide to break with convention here? | Because ^x is equivalent to m ^ x with m = "all bits set to 1" for unsigned x and m = -1 for signed x. Says so in the spec.
It's similar to how -x is 0 - x | stackexchange-stackoverflow | {
"answer_score": 10,
"question_score": 4,
"tags": "go, syntax, operators, conventions"
} |
Loop program again after method is executed
i guess this is a really simple problem, but i just can't get it to work! I want that my menu should show up again after that i have run a method. Thanks in advance.
function menu () {
var choice = prompt("0. Exit \n\n1. Fahrenheit to Celsius \n2. Celsius to Fahrenheit \n3. Guess a number");
choice = parseInt(choice);
if (choice > 4 || choice < 0) {
alert("FEL!!");
} else if (isNaN(choice)) {
alert("Måste vara en siffra");
}
switch (choice) {
case 0:
choice = false;
break;
case 1:
CelsiusToFarenheit();
break;
case 2:
FahrenheitToCelsius();
break;
case 3:
Guess();
break;
}
return choice;
}
do {
menu();
} while(choice == true); | you forgot to store the variable returned by the menu() function :
function menu () {
var choice = prompt("0. Exit \n\n1. Fahrenheit to Celsius \n2. Celsius to Fahrenheit \n3. Guess a number");
choice = parseInt(choice);
if (choice > 4 || choice < 0) {
alert("FEL!!");
} else if (isNaN(choice)) {
alert("Måste vara en siffra");
}
switch (choice) {
case 0:
choice = false;
break;
case 1:
CelsiusToFarenheit();
break;
case 2:
FahrenheitToCelsius();
break;
case 3:
Guess();
break;
}
return choice;
}
var choice;
do {
choice = menu();
} while(choice == true); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "javascript"
} |
Change back-order message for products with certain SKU's in WooCommerce
I would like to have a custom back-order message for certain WooCommerce products based on their ID, SKU or something else unique.
Right now I have this, and this works fine for all products that have back-order enabled, but what if I want this logic conditional for only certain product variations?
function backorder_text($availability) {
if($product->get_sku() == "111100"){
foreach($availability as $i) {
//$availability = str_replace('Available on backorder', 'Yo, allow 3-4 weeks for your shiz!', $availability);
$availability = str_replace('Beschikbaar via nabestelling', 'UITVERKOCHT (U kunt wel bestellen, maar de levertijd is 2-3 werkdagen).', $availability);
}
return $availability;
}
}
add_filter('woocommerce_get_availability', 'backorder_text'); | This actually worked best for me:
function backorder_text_prikkabel_zonder_fittingen( $availability, $product ) {
$product_ids = array( 7631, 7631, 8612, 7629, 7628, 7627 );
if ( in_array( $product->get_id(), $product_ids ) ){
foreach( $availability as $i ) {
$availability = str_replace( 'Default back-order message', 'Your custom back-order message', $availability );
}
}
return $availability;
}
add_filter('woocommerce_get_availability', 'backorder_text_prikkabel_zonder_fittingen', 10, 2 );
**Explanation:** the array contains a list of product variation ID's. If you echo `$product->get_id()`, somewhere around the bottom of the page, you will see a list of ID's for each of the products variations for that product.
Make sure the default order message exactly matches the message you get on your product page so the custom message will be used instead. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "php, wordpress, woocommerce"
} |
Changing a post status name
How do I change the status name "Trash" to "Archive". I don't want to change the functionality of the status or make a new status. I have tried Edit Flow custom status but I get some conflicts with another plugin and it seems a bit of a bulky solution for the small change I want to make.
It must be possible to just change the status name "Trash" to "Archive"?
I have looked through the WP admin files but I cant find any leads, maybe I am missing something.
Thank you in advance. | Found this nice little bit of code from <
add_filter( 'gettext', 'wps_translate_words_array' );
add_filter( 'ngettext', 'wps_translate_words_array' );
function wps_translate_words_array( $translated ) {
$words = array(
// 'word to translate' = > 'translation'
'Posts' => 'Article',
'Post' => 'Articles',
'Pages' => 'Stuffing',
'Media' => 'Upload Images',
'Links' => 'Blog Roll',
);
$translated = str_ireplace( array_keys($words), $words, $translated );
return $translated;
}
Add this to functions.php and change accordingly, although in saying that I have a custom plugin where I add things like this as it deactivates if I make a mistake, rather than functions.php which seems to break the website. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "post status, trash"
} |
How many open source projects are hosted on Maven?
I couldn't find any public data about the number of hosted project in Maven. I'm particularly interested in Java programming language and open source projects.
Is there any official statistics? | Maven Central's site has some stats, like that it contains over 100,000 unique artifacts, but it doesn't break it down by language or license. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -2,
"tags": "java, maven, open source"
} |
Precalculus (Functions) If $f(2x+\frac{y}{8}, 2x-\frac{y}{8}) = xy, $ then $f(m,n) +f(n,m)=0$ only when :
If $f(2x+\frac{y}{8}, 2x-\frac{y}{8}) = xy, $ then $f(m,n) +f(n,m)=0 $
Options are :
(a) only when $m =n$
(b) only when $m \neq n$
(c) only when $m =-n$
(d) for all $m$ and $n$
My approach :
$x=0, y =0 \Rightarrow f(0 , 0) =0 ; $ By putting $x = 1, y = 1$ gives $f(\frac{17}{8}, \frac{15}{8})$ = 1
Is it the right way please suggest... thanks.... | Let $2x+y/8=m,~~~2x-y/8=n$, so by solving two equations with respect to $x$ and $y$, you have $$x=\frac{m+n}4,~~~y=4(m-n)$$ Hence $f(m,n)=xy=m^2-n^2$ so $$f(m,n)+f(n,m)=0, ~~\forall m,n$$ The following codes are while working with Maple:
> d:=solve({m=2x+y/8,n=2x-y/8},{x,y}):
> f:=(x,y)->x*y:
> simplify(subs({d[1],d[2]},f(x,y)));
m^2-n^2 | stackexchange-math | {
"answer_score": 3,
"question_score": 4,
"tags": "algebra precalculus, functions"
} |
How to handle SSH links with Chromium?
I currently use Chromium on a Windows XP desktop. When I click on a link prefixed with ssh:// I'd like it to run Putty, but nothing happens. How can I configure Chromium to execute Putty for such links? | Chrome/Chromium does not handle unknown protocol://s by itself, instead it handles it to OS/DE running on parent system, so you just need to register ssh:// protocol for PuTTY.
As the original developer of PuTTY does not want to implement this feature, there is KiTTY, a modified version that should support this feature. | stackexchange-superuser | {
"answer_score": 4,
"question_score": 5,
"tags": "google chrome, ssh, chromium"
} |
How to pass info from one job to another
I have a jenkins job (jobA) which calls another one (jobB).
I have a string which is generated in a batch file called by jobA which needs to be passed into jobB.
How can I get that string out of jobA and into jobB?
Might it be possible to, say, set an environment variable to that string, somehow turn it into a jenkins parameter, and then pass that parameter into jobB?
Currently, my only other idea is to write the string out to a file in jobA, save that file as an artifact, pass that artifact into jobB, and then have jobB read that file. That seems a really kludgey way to do it, though.
It seems that there must be a better way. | One option is to use Jenkins **Parameterized Trigger Plugin**.
Then, you can for example set jobB's parameters based on a properties file generated by jobA. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "jenkins"
} |
Does h2o.splitFrame account for class proportion for multinomial classification?
Does h2o.splitFrame account for class proportion for multinomial classification? For example, if my original dataset has three classes with proportion of 20%, 70%, and 10%, when I create train, valid and test datasets, would they have similar class proportion?
Thank you for your input! | No it does not.
It does the simplest possible random split, handling each row independently with a "coin flip" row-by-row.
The thinking is, since H2O-3 is intended to handle big data, there are enough samples to not worry about it. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "h2o"
} |
Tips on studying the convergence of this series
Can someone please offer any tips on how to manipulate the series below, or what convergence test I should use to determine its convergence based on $\alpha$?
$$\sum_{n\ge1} \frac{\sqrt[3]{n+1}+\sqrt[3]{n}}{n^\alpha},\ \alpha \in \mathbb{R}$$ | **Hint:** It is easy to see that the numerator is $\gt 2n^{1/3}$. And since $n+1\le 2n$, the numerator is $\le (1+2^{1/3})n^{1/3}$. These inequalities will be sufficient for comparison tests.
We really don't need such tight bounds. Any positive constants $a$ and $b$ such that $an^{1/3}\le (n+1)^{1/3}+n^{1/3}\le bn^{1/3}$ are good enough for the comparisons.
Alternately, you could divide top and bottom by $n^{1/3}$. On top you get $\sqrt[3]{1+\frac{1}{n}}+1$, and at the bottom you get $n^{\alpha-1/3}$. | stackexchange-math | {
"answer_score": 2,
"question_score": 1,
"tags": "sequences and series, convergence divergence"
} |
ListPlot3D with individual colours for each point that blend
If I have a list of points {x,y,z} and for each point an rgb colour, e.g.: `points={{0,0,0,1,0,0}, {1,0,0,0,1,0}, {1,1,1,0,0,1}}` how can I plot the surface covering the given points (ListPlot3D) and colour it with blends of the individual colours?
In the above example, I expect a triangle with a red, green and blue corner and in-between blends of the three colours depending on the distance to the corners. | Use the option `VertexColors` with `ListPlot3D`:
ListPlot3D[points[[All, ;; 3]],
Mesh -> None, BoxRatios -> 1,
Lighting -> "Neutral",
VertexColors -> (RGBColor @@@ points[[All, 4 ;;]])]
]
$, which translates into $o(n^2)$ for the products. But that's too much! An explicit counterexample is $a_n=b_n=n^{2/3}$ when $n=2^k$ and $0$ otherwise. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "real analysis"
} |
Multilingual website: one table or multi-tables?
I'm building a multilingual website in PHP.
At first I was considering to use JSON file with a structure like
{
"TEXT_CODE": {
"LANG_CODE": "TEXT",
"LANG_CODE": "TEXT"
}
}
But then, since the texts could be a lot, I opted for a database solution that should be more handable and readable.
* * *
Assuming we have 200 texts and 5 languages, which is the best option in terms of database design mixed with performances?
## Solution 1
A single table `texts_multilingual` with `200 * 5 = 1000` rows to search among at each page request.
## Solution 2
One table per each language `texts_en`, `texts_it`, etc. so that each research would search only among 200 rows for the _text code_.
* * *
I guess solution #2 is the best way in terms of performances but I would like to know the opinion of more expert developers and how they would handle it. | The first solution is the better solution. Why?
First, you have only one table and you can optimize the table for your queries, using indexes and partitioning.
Second, you can add a new language quite easily. There is no new table to add.
Third, you can readily see what languages you have in the table and whether you have translations for all texts in all languages.
For performance, you simply want an index on the table . . . `texts_multilingual(language, textid, text)`. In fact, you might consider making this a primary key. Personally, I prefer having an auto-incremented primary key. But because this table is rarely updated, used in one specific way, and unlikely to have foreign key relationships, having a composite primary key is also reasonable. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, mysql, database design, multilingual"
} |
Placing variables in absolute memory location (IAR C/C++)
I am working on an STM8S microcontroller with the IAR Compiler.
How can I fix the start location for more then one variable using a pragma or another method?
When I try the below code, the compiler gives this error message:
> Error[Lp025]: absolute section .near.bss (main.o #12) ([0x000100-0x000100]) overlaps with absolute section .near.bss (main.o #8) ([0x000100-0x000100])
I searched on IAR tech notes for "Absolute located variable" but I couldn't find any info.
#pragma location = 0x100 /* Start address of absolute location */
extern uint8_t R0,
R1,
R2,
R3,
extern uint16_t M1;
extern uint8_t M2,
M3; | Use `#pragma location = "my_abs"` or `_Pragma("location=\"my_abs\"")` to place the variables you want in the absolute region in the same elf-section. Since `#pragma location` only applies to the following declaration you may want to create a define that you can prefix when declaring a variable in the absolute block. Note that only the `_Pragma("location=\"my_abs\"")` syntax is allowed in preprocessor macros.
#pragma section="my_abs"
#define IN_ABS _Pragma("location=\"my_abs\"")
IN_ABS char R0, R1, R2, R3;
IN_ABS short M1;
IN_ABS char M2, M3;
int no_abs;
Then add a line to the linker configuration to put this section at the designated address.
`place at address mem:0x100 { rw section my_abs };`
Note that you can not mix initialized and uninitialized variables in the same section. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "c++, c, pragma, iar, stm8"
} |
Check box not updating the DB using Rails 4
I have a column called `vacant` in my `listings` table. It is a Boolean, but it is not updating when I check it and save. I have added it to my strong params in the `listings_controller.rb`, I made sure it's inside my loop, but still not sure.
schema.rb:
t.boolean "vacant", default: false
_form.html.erb:
<div class="field">
<label for="vacant_listing" class="general-text-label">Vacant Listing - Only check if apartment is vacant!</label><br>
<%= f.check_box :vacant %> <br />
</div> | I figured out what was wrong. I have fields_for attributes and I added vacant inside of that. That was keeping the boolean from updating in the DB. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "ruby on rails, postgresql, model view controller, checkbox"
} |
Mysql запрос
> `id`, `eventID`, `round`, `player1`, `player2`, `player3`, `player4`, `player5`, `time`
все поля int. eventID + round - ключ, у каждого eventID максимально 30 раундов, может быть и меньше. Подскажите как максимально **адекватно** найти наиболее часто встречающихся игроков. | Структура явно не годится для такого рода запросов. В первом приближении к пониманию так:
select player, count(*) qty
from (
select player1 as player from table
union all
select player2 from table
union all
select player3 from table
union all
select player4 from table
union all
select player5 from table
) X
Group by player
order by qty desc limit 5 | stackexchange-ru_stackoverflow | {
"answer_score": 3,
"question_score": -1,
"tags": "sql"
} |
is influxdb backward compatible with graphite/carbon api?
We are evaluating replacing graphite as our monitoring system with an InfluxDB based stack and wondering if InfluxDB supports for Graphite line protocol is fully backward compatible with Graphite/Carbon api? | You can write Graphite format data to InfluxDB in two ways.
## Using Telegraf
Using the `socket_listener` in Telegraf you can accept Graphite Format data. This data can then be forwarded on to InfluxDB.
## Using InfluxDB
InfluxDB can process Graphite format data via the Graphite Service that can be configured in the `[[graphite]]` section of the InfluxDB configuration file. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "graphite, influxdb"
} |
How to connect atom with website and read the new content
I created an Atom rss file, how can I now link that with my website and read all the new content the file I created:
< in web < | Put the following line in the head of your webpage:
<link rel="alternate" type="application/atom+xml" href=" title="swqee news">
This is for HTML, if you use XHTML don't forget to terminate the tag. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "xml, rss, atom feed"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.