INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Distribution of the maximum of absolute value of multivariate Gaussian
I am currently working on some simulations. However, I encounter a statistical problem as following.
Suppose $ 0 < t_1 < t_2 < \dots < t_m < 1 $ and $ B(t) $ denotes Brownian bridge. Let $ {\bf B} = (B(t_1), \dots, B(t_m))' $. Given $ {\bf w}_i = (w_{i1}, \dots, w_{im})' $ for $ i = 1, \dots, L $, what is the distribution of $\max_{1\leq i \leq L} | {\bf w}_i' \bf{B} |$ ?
I think the problem is equivalent to the following.
Suppose we have multivariate normal random vector $(z_1, z_2, \dots z_L)' \sim N({\bf 0}, \Sigma)$. Want to figure out the distribution of $\max( |z_1|, |z_2|, \dots |z_L| )$.
Could anyone help me out? Thank you very much in advance.
|
$x$ being a nonnegative real number you can write $$P\\{\max( |z_1|, |z_2|, \dots |z_L| ) \leq x\\} = P\\{ -x \leq z_1 \leq x, \dots, -x \leq z_L \leq x \\}$$
Since we are dealing with a Gaussian vector, $$P\\{ -x \leq z_1 \leq x, \dots, -x \leq z_L \leq x \\} = \int_{[-x,x]\times\ldots\times[-x,x]}f_{N(0,\Sigma)}(z)\, dz$$
Here $f_{N(0,\Sigma)}$ is the density of the Gaussian vector you have. Without further information on the covariance matrix $\Sigma$, this is the most specific answer one can give.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "probability, statistics, probability distributions, stochastic processes"
}
|
Evolution of reduced density matrix
Suppose we have two density matrices of an n-partite system, $\rho$, $\rho'$, with $\rho$ $\neq$ $\rho'$, but $\rho_A$ = $\rho_A'$, where A is a certain subset of the n parties. Is it true that $(U$$\rho$$ $$U^{-1}$$)_A$ = $(U$$\rho'$$ $$U^{-1}$$)_A$, where U is a unitary operator acting on the whole system of n parties?
|
The answer is no. Let $\rho_1 = \frac 1 2 \begin{pmatrix} 1 & 0 \\\ 0 & 1 \end{pmatrix}$ and $\rho_2 = \frac 1 2 \begin{pmatrix} 1 & 1 \\\ 1 & 1 \end{pmatrix}$. From those, construct two density matrices $$ \rho = \rho_1 \otimes \rho_1 , \quad \rho' = \rho_1 \otimes \rho_2 $$ on the full Hilbert space $\mathbb C^2 \otimes \mathbb C^2$. Note that $\operatorname{tr}_B \rho = \operatorname{tr}_B \rho' = \rho_1$.
Now we define the unitary $U$ that swaps the two subspaces: $$ U|1,1\rangle = |1,1\rangle, \quad U|1,2\rangle = |2,1\rangle, \quad U|2,1\rangle = |1,2\rangle, \quad U|2,2\rangle = |2,2\rangle. $$ It's easy to see that $$ \operatorname{tr}_B U \rho U^\dagger = \rho_1 , \quad \text{but} \quad \operatorname{tr}_B U\rho'U^\dagger = \rho_2 .$$
|
stackexchange-physics
|
{
"answer_score": 3,
"question_score": 0,
"tags": "quantum mechanics, quantum information, density operator"
}
|
Why does Windows think that my wireless keyboard is a toaster?
I've inherited an old PC from my girlfriend's dad and when setting up the printer I got a bit of a surprise:
!Toaster keyboard
Two questions spring to mind here:
1. Why does Windows think my wireless keyboard is a toaster?
2. Why does Windows even have an icon for a toaster in the devices menu?
|
**Reason 1**
Because Microsoft made a toaster driver sample. In the sample there is the line `<DeviceIconFile>Toaster.ico</DeviceIconFile>` and there is a chance that your keyboard manufacturer took that sample.
**Reason 2**
Look at the back of the keyboard for some place to insert a slice of bread…
|
stackexchange-superuser
|
{
"answer_score": 2118,
"question_score": 2148,
"tags": "windows 7, device manager"
}
|
7.1.1 - Check if SHORTCUT was used
So, basically what I want to achieve is: get to know when I am accessing the activity through a shortcut and when not. I am using static shortcuts.
Went through the documentation but no luck. Maybe it's related more to the intent, which is a part of Android programming I am not mastering.
Thanks.
|
Use an action string that is unique to the app shortcut. Note that the action string does not need to be on the `<intent-filter>` for the `<activity>` in the manifest -- the `<activity>` does not need an `<intent-filter>` at all, AFAIK.
You have to have an `android:action` attribute in the `<intent>` element for the app shortcut anyway (for inexplicable reasons). So, set that to some string. Then, in your activity, you can use `getIntent()` to see the `Intent` that was used to create the activity and see if it has this particular action string. If it does, then the activity was created through an app shortcut.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "android, android intent, android 7.1 nougat, android appshortcut"
}
|
Error: ‘void*’ is not a pointer-to-object type error while dynamically opening multiple shared libraries
I need to open multiple shared libraries at run time. I don't know their number(count), so I am using dynamic memory allocation:
void* handle= new void* [n]; // n refers to number of handles
handle[0] = dlopen("./fileN.so", RTLD_LAZY); // doesn't work : Error: ‘void*’ is not a pointer-to-object type
However if I do static allocation, it works-
void* handle[10];
handle[0] = dlopen("./file0.so", RTLD_LAZY); // works
Why is that when I am dynamically accessing the handle, I am getting error? and how do I fix it?
|
You need an extra level of indirection. A pointer to a pointer:
void** handle= new void* [n];
^
Your code would be invalid on another type:
int* handle= new int* [n]; // error assigning int** to int*
But it works with `void*` as `void*` can point to `void**`.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "c++, pointers, dynamic, casting, shared libraries"
}
|
Call graph generation from matlab src code
I am trying to create a function call graph for around 500 matlab src files. I am unable to find any tools which could help me do the same for multiple src files.
Is anyone familiar with any tools or plugins?
In case any such tools are not available, any suggestions on reading 6000 lines of matlab code without documentation is welcome.
|
Let me suggest M2HTML, a tool to automatically generate HTML documentation of your MATLAB m-files. Among its feature list:
* Finds dependencies between functions and generates a dependency graph (using the dot tool of GraphViz)
* Automatic cross-referencing of functions and subfunctions with their definition in the source code
Check out this demo page to see an example of the output of this tool.
|
stackexchange-stackoverflow
|
{
"answer_score": 11,
"question_score": 14,
"tags": "matlab, dependencies, code analysis, call graph"
}
|
Save Valuable Time Reverse Engineering
As we know, time is the bane of reverse engineering. I am wanting to know how are some ways that I can save time in reverse engineering? I have taken some thought and I have been going through many programs and finding that even if the program is considerably different I am able to find up to 255+ identical garbage/redundant functions. I was thinking this morning if there was a way to somehow fingerprint these, that it would save me a considerable amount of time.
In short, I would like to know:
Has anyone tried to fingerprint or make a database of these redundant functions?
Also, what are some other ways that I can save time in my reversal process?
|
This is a common task when looking at binaries with statically linked code. The static code varies in register assignment, relative pointer addressing to external object code and other details but is mostly identical across binaries.
IDA uses the FLIRT system to solve this problem. <
Basically it filters those bits that vary across linker executions and matches the remaining pattern against a list. For very short functions there are many collisions, but for functions longer than ~30 bytes or so it's very good at identifying what you're looking at.
If you're using IDA then it comes with the tools to create your own FLIRT signatures. If you're not using IDA then you would have to make a tool to pull apart your particular static libraries, disassemble the first opcodes, filter the variable bits (this is tricky), and create a database to link names to patterns. You could apply the patterns as appropriate: borland libraries for borland program, MS runtime for visual studio, etc.
|
stackexchange-reverseengineering
|
{
"answer_score": 1,
"question_score": 0,
"tags": "functions"
}
|
TEA algorithm constant 0x9e3779b9 said to be derived from golden ratio, but the golden number is 1.618?
I'm trying to understand a constant 0x9e3779b9.
What kind of data is this? It's not binary, not decimal, what is this?
It's a constant used on the TEA algorithm. It says it's derived from the golden number, but the golden number is 1.618?
|
As others have said, the constant is an integer in hexadecimal form. Specifically, it is a 32-bit integer in hexadecimal form. If the constant is a signed integer, then 0x9e3779b9 is negative 1640531527 decimal in two's complement form; therefore, it may be a scaled integer fraction that has been adjusted to deal with non-integral of 2 related problems.
Two's complement negative to positive conversion in hex
0x9e3779b9 ⊕ 0xffffffff + 0x00000001 = 0x61C88647 = 1640531527 in decimal
or using the 1's complement operator ~ in the C family of languages
~0x9e3779b9 + 0x00000001 = 0x61C88647 = 1640531527 in decimal
Two's complement negative to positive conversion in binary
10011110001101110111100110111001 ⊕ 11111111111111111111111111111111 + 00000000000000000000000000000001 = 01100001110010001000011001000111 = 1640531527 in decimal
|
stackexchange-softwareengineering
|
{
"answer_score": 9,
"question_score": 6,
"tags": "math, algorithms"
}
|
Can i redirect user after login from one https server to another one in Laravel
When a user logs in (using Laravel), can I redirect them from HTTPS one server to another HTTPS server? If so, how can I accomplish this using "plain" PHP without SSO or LDAP?
In my specific situation, I have two servers:
1. Running Ubuntu with SSL, Apache, MySQL, and a Laravel DB where users will log in and
2. Same setup as as #1 but without a database
let me rephrase that: WILL THAT BE SECURITY ISSUE ?? and how will i know that user is loged in on 1site?
|
In order to achieve what you want then the following flow, probably modified, could work:
1. Log into site1
2. Upon successful login site1 cURLs site2 using HTTPS with predefined credentials to a RESTful interface
3. Site2 checks the predefined credentials and creates a temporary id which is stored in the DB and responds to the cURL with the ID stored in the DB
* ^ run a cron job every minute to clear ID's older than 5 seconds
4. Site1 puts the ID in the URL and redirects to Site2
5. Site2 gets the ID from the DB and authenticates the user
6. Site2 deletes DB entry upon authentication
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "php, laravel, single sign on"
}
|
Test-driven development (TDD) in .NET Visual Studio 2010
I am beginner in .NET, how can I install NUnit test in Visual Studio 2010?
I have tried this:
PM> install-package Nunit
But I get this error message:
Install-Packag : The schema version of 'NUnit' is incompatible with version 1.2.20325.9034 of NuGet. Please upgrade NuGet to the latest version from
Au niveau de ligne : 1 Caractère : 16
+ Install-Package <<<< NUnit
+ CategoryInfo : NotSpecified: (:) [Install-Package], InvalidOperationException
+ FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.InstallPackageCommand
|
Per the error message....click the link to go and upgrade NuGet to the latest version. Then try again.
Or, go to nunit.org, download the NUnit DLL files and then reference them in your project.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "visual studio 2010, nunit"
}
|
How to move all installed programs from my computer to another computer or laptop?
If I have installed a lot of programs/games on my computer(desktop) and now buy a new laptop and I have installed a Ubuntu 11.10 on it too then,how to move all installed programs on my desktop to my laptop instead of installing them again on my laptop ???
|
1)open nautilus with sudo nautilus command , go to var/cache/ apt/archives select and copy the folder with packages u have downloaded .(if it gives error , just click on skip and Dont worry )
2)paste it to a external drive . also copy and paste your home folder . 3)copy and paste both folders in your second pc. 4)install synaptic package manager in second pc , click on add downloaded packages from menu and point to the location u copied archive folder. it will add them and mark them automatically . if it gives error for broken packages , update cache with update manager or reload and click on 'fix broken packages' from menu . 5)click on apply . u will have to download only if there is new version available for something . 6)after installation copy the home folder to your home. restart your system.
by following this procedure u will have clean system and u will have to download least .
|
stackexchange-askubuntu
|
{
"answer_score": 0,
"question_score": 5,
"tags": "installation, package management"
}
|
Git will not ignore Gemfile.lock
I have a Gemfile.lock that git simply will not ignore. It's in my gitignore file (see below) but it keeps showing under unstaged changes whenever I `bundle install`. Anyone else ever run into something like this? Thanks in advance.
My Gitignore looks like this:
/.tags*
/log
/tmp
/db/*.sqlite3
/public/system
/coverage/
/spec/tmp
**.orig
rerun.txt
Gemfile.lock
...
|
Is it because the `Gemfile.lock` is already committed to your repository? Is it showing as a new file (with `??` in git status) or a modification (with `M` in git status). If it's the latter then you will need to remove the file with `git rm Gemfile.lock`. Once you commit that change then the file should stop showing up in `git status`.
As an aside, it's generally best practice to keep the `Gemfile.lock` committed to the repository (unless this is a gem). Here's a good SO question about that topic: Should Gemfile.lock be included in .gitignore?
|
stackexchange-stackoverflow
|
{
"answer_score": 8,
"question_score": 2,
"tags": "ruby on rails, git, ruby on rails 4, gitignore, gemfile.lock"
}
|
Can Camera Permission be requested from from Native Code(C/C++)?
I am trying to write an Android Native program using NDK that will access camera from the native code. But to access the camera I need permission even for native code. I found a sample provided by google to access camera from the native code but it checks the permission by calling a Java method written in the activity [[ref]]( Is there any way to check for the permission form the native code only, without extending the `NativeActivity`[[ref]]( Possibly not even accessing the Dalvik VM at all (which I believe will give me a better performance)
|
There is an easy way to check whether the permission was granted: try to open the camera device, and it will fail, or succeed.
To request the permission, you must use framework API explicitly. There is no C API for requestPermissions()) or her alternatives (that's to answer _“Possibly not even accessing the Dalvik VM”_ ).
Note that you can avoid permissions request: you can instruct your user to grant the permission in System Settings for your App (no, I am not endorsing this approach, but if you have some special reason to _not_ extend NativeActivity and have no Java code in your APK, you still can.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "android, android ndk, native"
}
|
Error Passing Variable to SQL Query Python
Error message 'Execution failed on sql ... expecting string, unicode or buffer object' is returned when trying to pass a Python string variable to a SQL query using cx_Oracle. Any help on this issue is greatly appreciated, thanks!
import pandas as pd
import cx_Oracle as ora
var = 'string'
conn = ora.connect('connection_string')
df = pd.read_sql(("SELECT * FROM table WHERE field LIKE '%s'", (var)), conn)
df.head()
|
To avoid the chance of SQL-injection attack you should pass the variable in the `params` keyword argument:
df = pdsql.read_sql("""SELECT *
FROM table
WHERE field LIKE %(var)s""", conn, params={'var':'string%',})
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "python, sql, oracle, pandas, cx oracle"
}
|
json parse fails on IE8
**json -> the response returned back**
{"msg":"<DIV><P>Unfortunately we were unable to process your application.</p><BR>Please upload a CV<BR></DIV>", "status":"error"}
**The error**
`SCRIPT1015: Unterminated string constant`
The line with the error
var data = $(this).contents().find('body').html();//I have console logged this and holds the above json as a string.
data = jQuery.parseJSON(data);// problem is here.
for some reason I think, it may be because the html tags because `.text()` works as oppose to `.html()`, however I need to use the `.html()` because it's formatted there with html tags.
Any suggestions ?
|
Is that a line break in the json? If that's the case, then that's your error. Try eliminating it with something like `data.replace( '\n', ' ' )`.
**Update from the comments** : Val realized that the IE8 parser was in fact borking on his test case, while the original javascript JSON parser handled it just fine. If you need that original parser, it's at: < as linked to from: < and is pretty much a drop in replacement.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "jquery, json"
}
|
DataFrame, count unique values, Java
I have a DataFrame and I want to count the uniqe lines of two columns in this Data Frame. For example:
a x
a x
a y
b y
b y
b y
should be to:
a x 2
a y 1
b y 3
I know the solution for this operation in pandas DataFrame, but now I want to do it direct in Java (the best way is Java 8).
|
I have found the next solution by myself. Copy here, if somebody has an interest....
DataFrame df2 = df.groupBy("Column_one", "Column_two").count();
df2.show();
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "java 8, apache spark sql"
}
|
How to disable frame rate counter and live visual tree toolbar when debugging UWP?
I am using VS 2017. When I run a UWP project by clicking the following button (enclosed by red rectangle),
?
|
To turn off the counters in the top left comment out the following line of code or set the proerty to false in app.xaml.cs
this.DebugSettings.EnableFrameRateCounter = true;
You can turn off the toolbar in the "live visual tree" tools
<
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "visual studio, uwp, visual studio 2017"
}
|
Programmatically Verify an email message reached an exchange mail box
I have a job that runs which sends out emails to our users to which starts off a work flow process in our company. Periodically, a user will swear up and down that they didn't receive the email - though, when we go to the mail administrator to pull an exchange report, 10 times out of 10 it's in their deleted items. :P
I'd like to be able to programmatically verify that messages sent via .net C# (System.Net.Mail I think) reached the user's mail box.
It's exchange 2007 and all messages are internal.
|
You can't with System.Net.Mail. You'll have to dig through Exchange's APIs to determine if an email is present in someone's email account.
<
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "c#, exchange server 2007, system.net.mail"
}
|
Strongly Typed Multidimensional Array/Collection
I want to create a strongly typed multidimensional array or collection containing the following values from a database:
* FileName (As String)
* FileSize (As Integer)
Requirements:
* Accessible via index (e.g. Arr(i)(j), Arr.Row(i), etc)
* Efficient (i.e. fast & not resource intensive)
* Easily manipulated, added to, appended, etc.
* .NET 3.5 compatible
* * *
Thanks for the great answers everyone. Here's what I went with... :)
Structure FileRecord
Dim Name As String
Dim Size As Integer
Sub New(ByVal FileName As String, ByVal FileSize As Integer)
Me.Name = FileName
Me.Size = FileSize
End Sub
Sub New(ByVal Files() As FileRecord)
For Each f As FileRecord In Files
Dim fr As New FileRecord(f.Name, f.Size)
Next
End Sub
End Structure
|
You can't have a multidimensional array containing two separate types.
Instead, you'd typically make a single dimensional array (or `List(Of T)`) containing a custom class with your data.
In your case, you might want something like:
Public Class FileRecord
Public Property Name As String
Public Property Size as Integer
End Class
Then, make a `List(Of FileRecord)` to hold your data. You'd then be able to access this as:
Dim nameAtIndex = theList(i).Name
Dim sizeAtIndex = theList(i).Size
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "vb.net, multidimensional array, strongly typed dataset"
}
|
How to figure out whether a certain function takes a specific value, if the ranges of variables are known
I have a function of six variables, a known function, say y= F(x1, x2, x3, x4, x5, x6). I know the ranges of these variables: a1<x1<b1, a2<x2<b2, a3<x3<b3, a4<x4<b4, a5<x5<b5, a6<x6<b6. Is it possible to figure out whether a certain value of this function is reached for any set of the variables. I suspect that a certain value of y, say y0=10^{-12} can be achieved for at least one set of variables x1, x2, x3, x4, x5, x6. is it possible to find this set in Mathematica?
|
I would try:
Assuming[{a1<x1<b1, ...},
FindInstance[f(x1,...,x6) == desiredValue, {x1,...,x6}]]
If you give us your full problem (with details), we can better help you.
|
stackexchange-mathematica
|
{
"answer_score": 1,
"question_score": 1,
"tags": "functions"
}
|
Problemas com "active" ReactJS
Estou tentando criar um estado para setar um ícone como `active` mudando sua cor, porém estou falhando miseravelmente por ter pouco conhecimento.
Criei um estado com o `useState` e coloquei o valor true por padrão para poder testar se iria funcionar.
No meu ícone, passei `active={active}` e nos meus estilos, eu peguei ele como:
**styled-components** :
svg{
color: ${props => props.active ? 'cornumero1' : 'cornumero2'};
}
* * *
**index.js** :
<li>
<Icon.GoGraph size={20} active={active} />
<p>Gestão de cobrança</p>
</li>
Eu estou errando em alguma coisa ou esquecendo algo, porque o ícone vem diretamente no `else`, ou seja, como `false`.
Como resolver?
|
Meu problema era estar passando a `props` no Icon, o correto é na `<li>` como um novo componente e agradeço a todos que me ajudaram e em especial ao Carlos Queiroz que me orientou.
Final:
**index.js** :
<Item active={active}>
<Icon.GoGraph size={20} />
<p>Gestão de cobrança</p>
</Item>
* * *
**styles** :
export const Item = styled.li`
width: 100%;
height: 45px;
display: flex;
align-items: center;
cursor: pointer;
svg {
transition: 0.3s ease;
color: ${props => (props.active ? '#47B248' : '#939393')};
}`
|
stackexchange-pt_stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "react, react hooks, styled components"
}
|
Difference between symmetric and asymmetric hash function?
The Linux kernel supports symmetric and asymmetric hash functions. E.g. sha1, sha256, ...
See tcrypt.c and search for `test_hash_speed` and `test_ahash_speed`.
I know what the difference is between symmetric and asymmetric ciphers, where the encryption and decryption key is not the same.
**Question**
What is the difference between symmetric and asymmetric hash functions?
|
Hashes like SHA-x are _symmetric_ and unkeyed. I have never heard of _asymmetric_ hashes.
Your question is based on a misunderstanding. You can implement computations in an _asynchronous_ fashion, where you request some computation, then your thread is free to do something else, and at some later point when the computation is finished you do something with the result. The code file you link implements hash functions in an asynchronous fashion.
_Async/asynchronous_ and _asymmetric_ are not related in any way.
|
stackexchange-crypto
|
{
"answer_score": 6,
"question_score": 6,
"tags": "hash, public key, symmetric, encryption"
}
|
creating metadata template or add field to existing template with box api
Is there api call where User can append value on to pre existing metadata template
for example lets say I have metadata template called author and has dropdown of [bob, bill, mary , mark] but i want to push "dan" to the dropdown so the dropdown will be [bob, bill, mary , mark , dan]
OR
Is there a api call that allows for creating new metadata template?
I have looked for documents but most of them were creating metadata on to file with the existing template
|
Metadata template creation and editing is only done through the Admin Console in the Web App at this time. The API only supports working with the values within the templates, not the keys.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "api, metadata, box api, box"
}
|
Only show SUM value if it is negative
I am summing the values in one column but I only want the query to show me the summed values if it is less than zero. How would I do this?
|
lets say you have a table name your_table which have two columns
name balance
A -1
B 10
A -5
Now According to your description output will be
name balance
A -6
For this output query will be
select name,sum(balance)
from your_table
group by name
having sum(balance)<0
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -3,
"tags": "sql, database, ms access, database design"
}
|
C# - String IndexOf method with second argument equal to String length
At some point in my code, I use this method:
IndexOf(string str, int startIndex)
I am also doing some calculations before, and I invoke this method with second argument (startIndex) equal to length of a string passed as first argument. Of course, no such an index exists in a string, and if we did something like this:
string[string.Length]
we would get an `IndexOutOfRangeException`
How does that method work exactly? In MSDN documentation it is clearly said, that startIndex is zero-based index of a string. Does it work and doesn't throw because a char array that `String` class operates on is null-terminated? I want to make sure that my program won't throw at any point.
|
It's mentioned explicitly in the documentation.aspx):
> Index numbering starts from 0. The startIndex parameter can range from 0 to the length of the string instance. **If startIndex equals the length of the string instance, the method returns -1**.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 2,
"tags": "c#, .net"
}
|
Security using Django 1.10 + AJAX without any HTML form
I make a POST request via AJAX without HTML form. Are there any security issues? Why is there no csrf error? Because I do not send any csrf data and csrf is enabled in django?
toggle-status.js
jQuery(document).ready(function($) {
$("#switch-status").click(function(){
$.ajax({
url: '/account/switches/',
data: {'toggle': 'status'}
});
});
});
view.py
@login_required
def switches(request):
toggle = request.GET.get('toggle', None)
current_user = request.user
update = Switches.objects.get(owner=current_user)
if toggle == 'status':
if update.status is True:
update.status = False
else:
update.status = True
update.save()
return HttpResponse('')
|
The default method of the `ajax` function is a `GET` one, not a `POST`. So, doing a:
$.ajax({
url: '/account/switches/',
data: {'toggle': 'status'}
});
implies that an ajax `GET` is made. So, you're not doing a `POST` request.
If you want a `POST` request, do it like this:
$.ajax({
method: 'POST',
url: '/account/switches/',
data: {'toggle': 'status'}
});
Of course you have to include the CSRF token then, since it will fail if you try to `POST` without including one. Look here how to acomplish that.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, ajax, django, security"
}
|
tableofcontents in beamer
I need to do tableofcontents ,where the was only one section on frame,other section on next frame ,but only one section at slide, like this

* Config var to disable all error messages (for production sites)
I use the Master Config bootstrap with multiple environment, so you can guarantee it will work for stuff like that too.
Email support[at]objectivehtml.com to get a copy of the latest beta once it's available. (A valid license is required for beta access.)
|
stackexchange-expressionengine
|
{
"answer_score": 1,
"question_score": 5,
"tags": "add on, config, email, postmaster, config overrides"
}
|
How not to disable internet connection while screen is locked?
How not to disable internet connection in service while screen is locked or application went to background? I have such problem. I need service in my application to send request to the server every 5 minutes. But after locking screen internet connection stops. I heard about Power Manager but i dont know hot to use it.
|
If your service is solely for running every 5 minutes you should use the AlarmManager instead.
Have a look at this
Anyway, the service should not lose internet connection when running in the background unless you bound it to your activities lifetime.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -3,
"tags": "android, service, powermanager"
}
|
How many anycast ips can be created per /24 net?
How many anycast ips can I create with one ipv4 /24 net? I know I need a whole /24 net to do anycast, but how many of those ips can I do with one? With a anycast ip address I mean one address for doke servers.
Here an example what I mean:
What I got:
- 1.1.1.0/24
- 6 Servers (a-f)
What I want to do:
- 1.1.1.1 is for server a, b and c
- 1.1.1.2 is for server d, e and f
I searched a long time but I couldnt find an answer.
|
Anycast means you are announcing a route to your assigned /24 via BGP from multiple physical networks on the Internet. In general, the closest (on the network, not necessarily physical distance) one to any given user's ISP gets used for any given connection.
Because the entire /24 is announced, _every usable address in the block is anycast_.
|
stackexchange-serverfault
|
{
"answer_score": 2,
"question_score": -2,
"tags": "ipv4, anycast"
}
|
How to write python expression to filter out certain strings
There is a string consisting several numbers, for example:
12.03 5.897 7.10.74 0.103 12.05 6.4.1 8.98
I want to use **Python regular expression** to output only those numbers with ONLY `single dot (.)`, such as `"12.03"` and `"5.897"`, not `"7.10.74"` and `"6.4.1"`.
I know this is a trivial question without regex, I just want to solve this with regex. But I really couldn't figure out how to solve this with regex. Can somebody help me?
|
If you want a pure regex solution then use lookarounds:
>>> s = "12.03 5.897 7.10.74 0.103 12.05 6.4.1 8.98"
>>> print re.findall(r'(?<!\.)\b\d+\.\d+\b(?!\.)', s)
['12.03', '5.897', '0.103', '12.05', '8.98']
RegEx Demo
* `(?<!\.)` is negative lookbehind to assert failure when previous char is DOT.
* `(?!\.)` is negative lookahead to assert failure when next char is DOT.
* `\b` is word boundary which is required on both sides to make sure we match full decimal number
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 2,
"tags": "python, regex"
}
|
Repository Query:searching inside an array
I have a MongoDb Document, quiz...
/**
* @MongoDB\Document(
* collection = "Quizzes",
* repositoryClass = "Company\MyBundle\Repository\QuizRepository",
* slaveOkay = true
* )
*/
class Quiz extends QuizEntity
The quiz contains many questions
/**
* @MongoDB\EmbedMany(targetDocument="QuizQuestion", name="questions")
*/
protected $questions = array();
If i have the main ID of a question, how can i query the repository of the Quiz for it?
(meaning, find a quiz contains my question with the id=4333)
|
I'll use something like
/* $question = your question */
$dql = 'SELECT z FROM YourBundle:Quiz z INNER JOIN z.questions q WITH q= :question';
$yourQuery->setParameter('question', $question);
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "mongodb, symfony, doctrine orm"
}
|
Which tool is most suitable for cutting thick cardboard with ease?
I have a big scissor but cutting very thick cardboards like tv case in different shapes like butterfly wings consume too much effort.
What kind of tool will make my life easy w.r.t very thick cardboards?
|
My preferred tool for heavy card is the classic Stanley 99 knife. The blade is slightly stiffer than those of the snap-off craft knives, and the metal handle is good and solid.
If you do go for a snap-off knife, for heavy card stick to one that takes 18 mm or even the rare 25 mm blades, rather than 9 mm blades, which are too flexible (but great for finer work on thin card). The cheapest of these 18 mm and 9 mm knives are rather flimsy and don't latch very well, so it's worth buying a good one (probably sold singly rather than in a big pack).
You should buy plenty of blades, as card can blunt them fairly quickly and a blunt blade tears the workpiece more easily than a new blade.
|
stackexchange-crafts
|
{
"answer_score": 5,
"question_score": 3,
"tags": "cardboard"
}
|
Django admin URL query string "OR". Is it possible?
I love being able to write quick and dirty query strings right into the URL of the Django admin. Like: `/admin/myapp/mymodel/?pub_date__year=2011`
AND statements are just as easy: `/admin/myapp/mymodel/?pub_date__year=2011&author=Jim`
I'm wondering if it's possible to issue an 'OR' statement via the URL. Anyone heard of such functionality?
|
Django < 1.4 doesn't support OR queries. Sometimes it is possible to translate OR queries to __in - queries which are supported (they are equivalent to OR queries but only for single field values).
You can also upgrade to django development version: it has more versatile list_filter implementation (see < ) which can be used for providing advanced admin filters (including OR-queries).
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 5,
"tags": "django, query string, admin"
}
|
What exception do we get upon low RAM in memory?
If I am doing a recursive algorithm to traverse a tree...and I know it has a lot of data, huge..and after like 20 minutes I get a "Stack Overflow" exception. But StackOverFlow might be because of some other error in code , maybe because of an infinite-loop ... so I am just trying to make sure this SOF error I get in VisualStudio is because my recursive algorithm is running out of RAM and not because of other errors...Do we have a special type of error message or exception when we are running out of memory in a recursive algorithm at all?
|
System.OutOfMemoryException can be thrown when memory is low. System.StackOverflowException is that you've busted the call stack with something recursively ultra-complex or without a terminating case.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#"
}
|
sed command is working in solaris but not in Linux
I am new to shell scripting and `sed` command.
The following `sed` command is working in Solaris but giving error in Linux:
sed -n 's/^[a-zA-z0-9][a-zA-z0-9]*[ ][ ]*\([0-9][0-9]*\).*[/]dir1[/]subdir1\).*/\2:\1/p'
**The error is** :
sed: -e expression #1, char 79: Invalid range end
I have no clue why it is giving invalid range end error.
|
It seems like Linux Sed doesn't like your `A-z` (twice). It doesn't really make sense, anyway.
Use `[A-Z]` (upper-case Z)
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 3,
"tags": "regex, linux, bash, shell, sed"
}
|
particle vs preposition? How to know the difference?
I tried to research the difference beween particle and preposition in phrasal verb, but the information on this website is not very clear. According to the website, in "She is making up excuses" up is called particle, but in the sentence "stop picking on your brother " on is preposition because the information comes immediatey after the phrasal verb completes a prepositional phrase. Without these prepositional phrase, the sentence would be incomplete. Can't the same be said about "she is making up excuses"? Without the preposition, the sentence would also be incomplete. I would appreciate greatly a more detailed explanation.
|
One test is to use a pronoun for the object. If the order _verb object particle_ is acceptable, then the particle is an adverb, not a preposition. If the order _verb particle object_ is acceptable, then the particle is a preposition.
1a. Stop picking on him.
1b. *Stop picking him on.
2a. *Stop leading on him.
2b. Stop leading him on.
So here, in "pick on", "on" is a preposition, but in "lead on", "on" is an adverb.
(All this assumes that it's meaningful at all to assign a part of speech to a phrasal verb's particle.)
|
stackexchange-english
|
{
"answer_score": 0,
"question_score": 2,
"tags": "prepositions, particles"
}
|
what is the difference between these two coding style in JS?
**Option 1:**
<script>
var myObject = function(){
this.iAm = 'an object';
this.whatAmI = function(){
alert('I am ' + this.iAm);
};
}
var myNewObject = new myObject();
myNewObject.whatAmI();
</script>
**Option 2:**
<script>
function myObject(){
this.iAm = 'an object';
this.whatAmI = function(){
alert('I am ' + this.iAm);
};
};
var myNewObject = new myObject();
myNewObject.whatAmI();
</script>
**Question:**
Both of these codes can work. But what is the difference between them? And which is the better way when doing `OOP` coding in `js`?
|
The first example will not be hoisted. In your second example the function will be hoisted.
In your example, with option 1 (Not Hoisted):
If you called this code:
var myNewObject = new myObject();
myNewObject.whatAmI();
Before the function declaration you would receive an error. However in your 2nd example the function is moved to the top of the enclosing scope, declared and ready for use (hoisted).
<
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 3,
"tags": "javascript, oop"
}
|
Binding width c# wpf
How can I bind width in C#?
In XAML it would be
Width="{Binding Path=ActualWidth, ElementName=img}"
I need to bind it in C# to update the width
|
Binding mybinding = new Binding();
mybinding.Path.Path = "ActualWidth";
mybinding.ElementName = "img"
Mytarget.SetBinding(MYTARGET.WidthProperty, mybinding);
`MYTARGET` is class and `Mytarget` is object name.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "c#, wpf, binding"
}
|
Basic if else statements
Consider this code that I have written which uses and `if` `else` statement
#include <iostream>
#include <stdio.h>
using namespace std;
int main() {
int a = 5;
if(a)
{
printf("if %d\n" , ++a);
}
else
printf("else %d\n" , a);
}
If I set `int a = 5` it prints outputs "if 6"
But if I set `int a = 0` it prints the value "else 0"
Why is it happening what is the reason?
|
`++a` increases the value of `a` by one and is an expression that equals that incremented value.
1. When `a` is 5, `if (a)` is `if (true)` as `a` is non-zero. So `printf("if %d\n" , ++a);` runs, the `++a` in that statement increments `a` and evaluates to that incremented value, 6.
2. When `a` is 0, `if (a)` is `if (false)`. So `printf("else %d\n" , a);` runs. `a` is not changed in that case.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": -5,
"tags": "c++"
}
|
Is there a way to apply filters on a count function in Kafka streams?
My use case is as follows - I have a topic containing messages which a specific ID. I've created a Kafka Streams application which aggregates messages with the same ID and counts them (similarly to the example WordCount implementation in <
I would like the Kafka stream to send a message to the output topic only when a certain threshold was exceeded. For example, if I define the threshold to be 10, I want a message to be sent to the output topic once 10 messages with the same ID were processed by the stream.
I understand that this could be done by having an additional topic and another stream that would process that topic, but is there any way to do this in a single stream?
|
After converting the KStream to a Stream using the count() aggregation function, it is possible to filter the count value, convert it to a Stream and send to a specific topic:
.selectKey((k, v) -> v)
.groupByKey()
.count()
.filter((key, count) -> count > 3)
.toStream()
.filter((key, count) -> count != null)
.to("output", Produced.with(Serdes.String(), Serdes.String()));
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "apache kafka, apache kafka streams"
}
|
changing the background of element A when hovering over element B - mouseleave not working
I'm trying to change the background of element A when hovering over element B, and changing it back upon mouseleave. B is a descendant of A. The mouseenter part seems to be working fine (background color changes upon hover), but the mouseleave does not work - the background stays the same.
The HTML:
<div class="A" style="height: 500px; background:blue">
<div class="B" style="height:400px; width:100px"><img src="someimg.jpg" style="height:400px"></div>
</div>
The jQuery:
$(document).ready(function(){
$('.B').mouseenter(function(){
$('.A').css('background', 'black');
});
$('B').mouseleave(function(){
$('.A').css('background', 'blue');
});
});
What am I doing wrong? Thanks in advance.
|
You didn't add the `.B`
Try this:
$(document).ready(function(){
$('.B').mouseenter(function(){
$('.A').css('background', 'black');
});
$('.B').mouseleave(function(){
$('.A').css('background', 'blue');
});
});
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, jquery, html, css"
}
|
I'm unable to connect Docker Remote API using nodejs hosted in AWS
I have created t1.micro instance in Amazon web-services(AWS), and installed docker.io. I executed following commend in SSH client "sudo docker -H tcp://0.0.0.0:4243 -H unix:///var/run/docker.sock -d &".
when I am trying to get all images : myipaddres:4243/images/json. I'am getting "This webpage is not available" page.
|
Finally I found < expose remote api on my host. :)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "node.js, amazon web services, docker, remoteapi"
}
|
pmrep command execution in Informatica cloud
Can anyone tell me is it possible to execute pmrep commands in Informatica Cloud services to import and export workflow object?
pmrep connect -r MY_REP -d MY_DOMAIN -n MY_USER -x MY_PASSWORD ./pmrep objectexport -o workflow -f $FOLDER -n $WORKFLOW -m -s -b -r -u ${EXPORTDIR}/${FOLDER}_${WORKFLOW}.xml
|
That's not possible in Informatica cloud, you don't have access to the repository it's hosted by Informatica.
You need to use REST API to import and export objects from IICS repository, the document is in the following link.
<
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "informatica cloud"
}
|
Pre-Pre-build Steps in Hudson
I'm in a bit of a pickle. I'm trying to run some environmental scripts before I run the build in a m2 project, but it seems no matter how hard I try - the 'pre' build script are never run early enough.
Before the 'pre-build' scripts are run, the project checks to see if the correct files are in the workspace - files that won't be there until the scripts I've written are executed.
To make them 'pre-build', I'm using the M2 Extra Steps plugin - but's it's not 'pre' enough.
Has anyone got any suggestions as to how I can carry out what I want to do?
Cheers.
|
My problem stemmed from the fact I wanted to set-up my workspace before I ran anything due to an issue with Dynamic Views (ClearCase) not being accessible from the workspace - I wanted to add a symlink to fix this.
However, Andrew Bayer has made a change to the plugin that I'm currently testing that should fix this...so the question is probably invalid in it's current form.
Will edit it once we come to a conclusion.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "maven 2, hudson, clearcase"
}
|
Which package update(s) triggered the 'Server reboot required' message?
After updating a number of packages, I get the 'Server reboot required' message upon login. What specific package or package(s) triggered this message?
Note: Two other questions address _why_ a reboot is required for some updates e.g. this and this, but my question is specifically asking how to identify the package(s) that triggered this. It's also worth linking to this related question that asks how to identify the packages that would require a restart before performing the update
|
One way to identify this info is to look in `/var/run` at these files
$ cat /var/run/reboot-required
*** System restart required ***
$ cat /var/run/reboot-required.pkgs
linux-base
linux-image-4.4.0-93-generic
These files will not exist unless a reboot is required, so checking if they exist is also a nice trick to know if a reboot is required:
[ -e /var/run/reboot-required* ] && echo "Reboot is required!" || echo "Reboot is not required."
|
stackexchange-askubuntu
|
{
"answer_score": 10,
"question_score": 9,
"tags": "server, apt, package management, updates"
}
|
What is requestScope equivalent in Thymeleaf to use flash messages?
In typical Spring JSP application I have a controller method like:
@RequestMapping(method = RequestMethod.POST)
public String save(@Valid Customer customer, BindingResult bindingResult, Model model, RedirectAttributes redirectAttributes) {
if (bindingResult.hasErrors()) {
model.addAttribute("customer", customer);
return "customer/create";
}
customerRepository.save(customer);
redirectAttributes.addAttribute("id", customer.getId());
redirectAttributes.addFlashAttribute("flash.message", "customer.created");
return "redirect:/customer/{id}";
}
Note the redirectAttributes to set a the `flash.message`. In JSP I would use:
<c:if test="${not empty requestScope['flash.message']}">
${requestScope['flash.message']}
</c:if>
How would I implement this with Thymeleaf?
|
This worked:
${#vars['flash.message']}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 3,
"tags": "spring, jsp, spring mvc, thymeleaf"
}
|
Is it possible to use type hint validation directly?
With version 3.6 python has type hints:
from typing import List, Union
def foo() -> List[Union[str, int]]:
return 3
However can we use this syntax outside of intended scope?
i.e. Can we use this syntax to validate some object?
objects = [['foo', 1], ['bar', 2.2]]
for object in objects:
if not isinstance(object, List[Union[str, int]]):
print(f'error, invalid object: {object}')
|
You can install the `typeguard` module:
from typeguard import check_type
from typing import Tuple
objects = [('foo', 1), ('bar', 2.2)]
for object in objects:
try:
check_type('object', object, Tuple[str, int])
except TypeError as e:
print(e)
This outputs:
type of object[1] must be int; got float instead
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "python, types"
}
|
Function REGEXP with a list of numbers
I have several comma delimited lists of numbers. I need to match specific lines with a sql query. I want to build correct RegExp for this and i need your help.
Example of my rows with comma delimited lists of numbers :
* 1,8,33,44
* 1,8,44
* 1,8,22,33
* 8,22,44
* 1,88,44
* 1,22,44,66
I need to match lines that contain only numbers 8 and 44
My sql query looks like this :
SELECT id FROM my_list WHERE id_list REGEXP '^[0-9,]8,[0-9,]44[0-9,]$'
Thanks in advance !
|
Use **FIND_IN_SET** Function:
SELECT id FROM my_list WHERE FIND_IN_SET('8', id_list) AND FIND_IN_SET('44', id_list)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "mysql, sql, regex"
}
|
Versioning system for database
We have a java application which uses spring boot and hibernate.
There are many changes on entities and fields. That's why, I want to follow changes and rollback mechanism. So that, I need a version control system over database. I checked flyway and liquibase, but I think those don't solve my problem. Because my table creations and updates are handled by hibernate.
Is there any way to see which queries are executed by hibernate to change the database and which changes have occurred since the latest database change (I mean new table, column creation or refactoring)?
|
One way to do it (how we do it):
Use 2 databases. A reference database and a development database. On the development database use hibernate to let it create the strucutre.
Once a development cycle is done you run liquibase `diffChangelog` on the reference database. It will create a changelog.xml with all changes that have been done by hibernate on the development db. Manually correct it (names, etc). When your happy with changelog file and the development cylce is done apply the changelog onto the reference database.
Start your next development cycle and repeat.
That way you can combine the advantages of letting hibernate generate the schema and still use liquibase to have a versioned DB-Schema that is re-creatable.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "java, hibernate, spring boot, liquibase, flyway"
}
|
How to put "www" in front of my domain in simple html based website.?
I have a website named **redpeppermedia.in** and I wish to see it's url as **www.redpeppermedia.in** instead of _redpeppermedia.in_
Do you have any idea how to do it? It's a simple website, I'm not using wordpress or drupal or any sort of website creation tool.
Thank You..
|
add file `.htaccess` to your website's root, then add the the following lines
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www.redpeppermedia.in$ [NC]
RewriteRule ^(.*)$ [L,R=301]
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "jquery, html"
}
|
Rename and move files from one directory to another directory
Need your help on a command that run on a path1 to rename and move files from path2 to path3
Assume
path1 = /data/run/
path2 = /data/output/
path3 = /data/archive/
path 2 contains few files like 'one.txt', 'two.txt' etc...
I want to run a command in path1 which can rename the files 'one.txt' to 'archive_one.txt' and move them to path3
I tried the below command from '/data/run' , but it is taking the whole path as file name and throwing error.
$for FILENAME in /data/output/*.txt; do mv $FILENAME /data/archive/archive_$FILENAME; done
How can I do that. Thanks.
|
what you want to do is
for FILENAME in /data/output/*.txt;
do
mv "$FILENAME" "/data/archive/archive_$(basename "$FILENAME")" ;
done
this can be one lined of course.
where
* `basename "$FILENAME"` extract last part of filename
* `basename "$FILENAME" .txt` would do the ame, striping `.txt` part.
and when posting here thou shall quote filename always.
|
stackexchange-unix
|
{
"answer_score": 1,
"question_score": 0,
"tags": "mv, for"
}
|
What is the best way to write a GUI in Codename One : Use the designer or code the GUI?
I am looking for a way to quickly (but surely) design mobile app. So far I have been using the designer because I've been watching the video tutorials from CN1. But when I read the manual from CN1 the GUI is often coded by hand. And sometimes I struggle with the designer and the styles to make the GUI look how I want it to look.
So I was wondering if I should still go with the Designer for my future app or coding is much faster (the GUI I design are very simple) now that I know more about CN1 and the styles?
Thanks for your advices,
Cheers
|
We are shifting focus to the new gui builder which generates a more hand coded styled app instead of the current StateMachine approach, so going forward we recommend coding the UI manually until the new gui builder will become more solid.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "user interface, codenameone"
}
|
How is temperature measured using thermometer?
I know that there is mercury present inside a mercury thermometer and it expands or contracts depending on temperature of object we are measuring. Now I don't understand why thermal equilibrium plays a role in this. (I read it in a book and I have no idea why is this true?). I think as follows: Say a body has temperature of 40°c, now say temperature of mercury in the thermometer is around 10°c, so thermal transfer happens until there is thermal equilibrium. But I don't see it giving the required temperature of object. I request the answer to my problem
|
The scale on a mercury thermometer is actually measuring the amount by which the mercury in the thermometer has expanded, which can in turn be used to find the temperature of the mercury (the scale, which will be labelled in degrees centigrade and/or degrees Fahrenheit, does this conversion for you).
If the mercury in the thermometer is not in thermal equilibrium then it is exchanging heat with the outside environment, so the reading from the thermometer will be changing. However, if you wait until the thermometer reaches thermal equilibrium then you know it is at the same temperature as whatever it is in contact with, so by measuring the temperature of the mercury you are also measuring the temperature of the other object.
|
stackexchange-physics
|
{
"answer_score": 3,
"question_score": 2,
"tags": "thermodynamics, temperature"
}
|
jquery fadeIn or fadeOut
Here i'm trying to blink (fadeIn/fadeOut) link and on hover, mouseOn - blink should stop and mouseOut should again start blinking. It works in case of div but not on a link. Please suggest am going somewhere wrong. Thanks in advance !
**HTML:**
<div class="myclass" ><a class="myBlink">Click here!</a></div>
**jQuery**
$(".myclass a").fadeIn(500).delay(500).fadeOut(500, fadeContent); // this is not working
|
`div` is a block level element and `a` anchor is an inline element. Try to make it a block level element by adding style on it as given below:
<div class="myclass" >
<a class="myBlink" style="display: block;">Click here!</a>
</div>
Hope it will work. Thanks!
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "jquery"
}
|
How do I prove that $ax+by+cz=d$ has infinitely many solutions on $S^2$?
Let $a,b,c,d$ be reals such that $a^2+b^2+c^2>d^2$.
How do I prove that $\\{(x,y,z)\in S^2: ax+by+cz=d\\}$ is infinite?
This is geometrically trivial, but I'm stuck at proving it rigorously..
|
Both $D^3$ and the plane are convex sets, hence their intersection is a convex set and its boundary is connected, hence if you prove that there are at least two different points in the intersection between the sphere and the plane, there are an infinite number of them, since the intersection has to be connected.
An alternative way is to use the implicit function theorem, or the fact that both the plane and the sphere are invariant with respect to a rotation around $(a,b,c)$, so their intersection has to be invariant, too.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 1,
"tags": "real analysis"
}
|
Elementary matrix transformations
Prove that pre-multiplying a matrix $A_m $ by the elementary matrix obtained with any matrix elementary line transformation $ I_m \underset{l_1 \leftrightarrow l_2}{\longrightarrow} E $ is the same as applying said elementary line transformation on the matrix $ A_m $.
|
Let $e_1,\dots, e_n$ be the standard basis row vectors, and observe the following facts about matrix multiplication:
1. $e_iA$ gives the $i$th row of the matrix $A$
2. For row vectors $v_1,\dots, v_m$, we have $$\pmatrix{\ v_1\ \\\ \vdots \\\ v_m} A=\pmatrix{\ v_1A\ \\\ \vdots \\\ v_mA} $$
Combine these to get the desired result for any elementary row operations.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 2,
"tags": "linear algebra, matrices, proof writing"
}
|
Alter Views arguments from URL
I'd like to alter Views arguments which is currently Term name. Is there any way to use term name slug instead of complete Term name and use this slug as views argument? If not what hook should I use to convert these parameters from URL (as taxonomy term slug) to full name Taxonomy term which can be used as views argument. I tried to use hook_views_query_alter and hook_views_pre_view, but it's too late for any changes.
|
It is a build in function in drupal views. When you add a contextual filter there would a section called more. You can put the case to lower case and check "Transform spaces to dashes in URL"
|
stackexchange-drupal
|
{
"answer_score": 1,
"question_score": 0,
"tags": "taxonomy terms, views"
}
|
Is there a way to tell what changes are in a central CVS repo comparing to my local working copy?
I need a way to figure out what files were added/removed/modified in the CVS repository comparing to my local working copy, i.e. what will happen to my local copy if I run "cvs update". It is safe to assume that I don't have any uncommitted changes in my local copy.
The output of "cvs update" marks added and modified files as:
U filename
which helps, but it doesn't tell what files are deleted.
Is there an easy way to get all changed files and how they are changed? Any help would be appreciated.
|
i deleted the file b from another checkout of the project.
$ cvs status | grep Status
cvs status: Examining .
cvs status: `b' is no longer in the repository
File: a Status: Up-to-date
File: b Status: Entry Invalid
File: c Status: Up-to-date
you can see that file b is missing from the repository.
updating:
$ cvs up
cvs update: Updating .
cvs update: `b' is no longer in the repository
afterwards the file b was also gone in this checkout and the message about file b is never displayed again.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "version control, cvs"
}
|
Add an extra text that appears on selected variations in WooCommerce
I would like to add a function that fires when the customer selects a product variant. Just as the price appears (after choosing variants).
It is a simple function (from functions.php) that reads additional information about productions from the database. However, I do not know if there is such a hook?
|
To add a text on selecting a variation you can use the following:
add_filter('woocommerce_available_variation', 'variation_custom_text', 10, 3 );
function variation_custom_text( $variation_data, $product, $variation ) {
// Here your custom text
$custom_text = __("This is my custom text…", "woocommerce");
$variation_data['availability_html'] .= '<p>' . $custom_text . '</p>';
return $variation_data;
}
Code goes in function.php file of the active child theme (or active theme). Tested and works.
 you can vibrate the device using Ext.device.Notification. This is not possible using Ext.Msg though.
That being said these two classes are not completely interchangeable.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "extjs, sencha touch 2"
}
|
How to create a class(page) from a string in Navigator
I want to redirect the user to the desired page depending on the "navigation" key, I tried in such ways:
final _bottomAppBarItem = [
{
'iconData': Icons.airplay,
'text': 'news',
'navigation': NewsPage(),
},
{
'iconData': Icons.person,
'text': 'profile',
'navigation': UserProfilePage(),
}];
Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => item['navigation']));
OR
final _bottomAppBarItem = [
{
'iconData': Icons.airplay,
'text': 'news',
'navigation': 'NewsPage',
},
{
'iconData': Icons.person,
'text': 'profile',
'navigation': 'UserProfilePage',
}];
Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => item['navigation']()));
But in both cases it turns out a mistake, how can I live with it?
|
You can use named routing as decribed in here. You can parameterize your route with custom strings.
A simple use case of named route:
onPressed: () {
// Navigate to the second screen using a named route.
Navigator.pushNamed(context, '/second');
}
Another solution, which is overhead for this situation, is to use mirrors.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "flutter, dart"
}
|
Excel X Y (Scatter) Chart using more than one value per cell
Is it possible to have more then one value in a cell and then use an X Y (Scatter) chart to represent the dots on the X and Y Axis ?
Here is what I mean:
Instead of having just one value per cell like in the image below, I want to have all the values in one cell, but the same X Y Scatter chart. Is it possible ?
, you would need to parse it into separate cells in a layout that the charting features can handle.
|
stackexchange-superuser
|
{
"answer_score": 2,
"question_score": 0,
"tags": "microsoft excel, microsoft excel 2013, charts"
}
|
GRANT REFERENCE on all user defined types
The original problem is: a user, who has the permission to create/alter view granted is getting this message when trying to perform either operation:
> Cannot find the type 'nvarchar', because it does not exist or you do not have permission.
Through some internet digging I found it may be caused because he does not have `GRANT REFERENCE` permission on types. However,
select * from sys.types order by name
Returns over 2000 records, and `GRANT REFERENCE` command accepts a single type as parameter. How can I grant this user the reference permission for **ALL** types?
|
If you need to do something like this, just use dynamic SQL to generate the command.
SELECT t.name,
'GRANT REFERENCES ON TYPE::'
+ SCHEMA_NAME(t.schema_id)
+ '.'
+ t.name
+ ' TO public;' AS command_to_run
FROM sys.types AS t;
|
stackexchange-dba
|
{
"answer_score": 2,
"question_score": 0,
"tags": "sql server, sql server 2008 r2"
}
|
How to get Label view in ViewModel to set accessibility focus in xamarin forms
I have `Label` in view, I need that `Label`'s view in my `ViewModel`. I am using Dependency Service to set focus on Controls for Accessibility service, DS requires `view` as a param.
This is my Label
<Label
AutomationProperties.IsInAccessibleTree="{Binding ShowNoResults}"
IsVisible="{Binding ShowNoResults}"
Text="{Binding ResultsHeader}"/>
I tried `Command` but Label doesn't support command. Below code also not working
var view = GetView() as HomeworkView;
I am getting `view` always `null`. How can I fix this?
|
I am not quite sure what are you trying to achieve, but you can't access the View elements from you view model.
If you want to do something with the control, you can use the messaging center to do it, here is an example
in your ViewModel
MessagingCenter.Send(this, "your message here");
then in your page, you need to subscribe to this message from that view model and do the desired action
MessagingCenter.Instance.Unsubscribe<ViewModelClassNamedel>(this, "your message here");
MessagingCenter.Instance.Subscribe<ViewModelClassName>(this, "your message here", (data) =>
{
this.youControlName.Focus();
});
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "xamarin, xamarin.forms, accessibility"
}
|
How can I extend config values
Example
Ext.define('ClassA', {
plugins: [ 'PluginA' ]
});
Ext.define('ClassB', {
extend: 'ClassA',
plugins: [ 'PluginB' ]
});
Ext.create('ClassB', {
plugins: [ 'PluginC' ]
});
So I would like to have an instance of `ClassB` with plugins `PluginA`, `PluginB`, `PluginC`.
|
You'll need to merge them in the constuctor. Here's a possible solution:
Ext.define('ClassA', {
constructor: function (config) {
var me = this;
config.plugins = Ext.Array.merge(config.plugins ? config.plugins : [], ['PluginA'])
Ext.apply(me, config);
me.callParent(arguments);
}
});
And here's a fiddle: <
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "javascript, extjs, extjs4"
}
|
What method(s) are needed from an imageview to save its current instancestate?
I have an imageview whose image is selected and changed by the user and I need to save its instancestate so the current image is displayed when the screens orientation changes or they switch to a different activity etc. I've been searching for a while but cant figure out the method(s) I need to use to pull the information from the imageview that I need to pass into the onSaveInstanceState bundle. Could someone point me in the right direction please?
|
There is nothing that you can "use to pull the information from the imageview". You need to know the source of the image in the `ImageView` by some other means, and elect to save that in your instance state.
For example, the code that updates the `ImageView` could store the image source data in a data member of your fragment or activity that hosts the `ImageView`.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "android, imageview, instance"
}
|
Serialising POST requests jQuery/Javascript
I am working on an application which sends an AJAX POST request (I'm using jQuery currently) every 1500ms. I have noticed that most of the times, these requests succeed within 350-450ms and are sent to the server nicely in the same order as they are generated.
However sometimes, one or two requests take nearly 3-4 seconds and they are delivered later. In my application I need to ensure that these requests are received by the server in the same order as they are sent from the client. How do I do that? I am using currently setInterval of 1500ms to call a function (which generates the data to be posted) and which POSTs it using $.ajax(). However, how do I serialise the requests?
|
Don't know exactly how this would work out in javascript, but you could create a list or array of your request, first in first out type of list, so when ready you push your request or whatever values needed to create your request into the array, after set interval you take from the array and send request. Basically you'll queue your request that way.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 3,
"tags": "javascript, jquery"
}
|
Combining Elastic Search completion suggester with IBoolQuery in Nest
I have tried to filter my documents based on certain exclusions before invoking the completion suggester.
var response = Client.Search<Suggestion>(s => s
.Query(q => q.Bool(MustNot(m => m.SpanTerm(st => st.Field("foo").Value("bar"))))
.Suggest(su => su
.Completion("title", cs => cs
.Field(f => f.TitleSuggest)
.Prefix(searchText) .
)
.Size(10)
)
)
);
But this doesn't seem to work. The same result set is returned.
|
After further reading, this doesn't seem possible using standard bool operators. Context suggesters are the solution, however this doesn't support e.g. MustNot modifiers
<
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "c#, nest, elasticsearch 6"
}
|
PHP date time format for UK
I have date variable i need to convert to a another type of date formats
//the date and time
$date="16-03-2014 00:16:01";
the format i want convert is like below
Sunday 16th of March 00:16:01
can someone please help me to do this.
|
try using this, also set default timezone of UK
<?php
$tm = strtotime("16-03-2014 00:16:01");
echo "<br>".date("l jS \of F H:i:s",$tm);
?>
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 3,
"tags": "php, datetime"
}
|
Letter Arrangements of M,A,R,Y
List all possible arrangements of the four letters m,a,r,and y. Let $\; C_1 \;$be the collection of the arrangements in which y is in the last position. Let $\; C_2\;$ be the collection of the arrangements in which m is the first position. Find the union and the intersection of $\; C_1\;$ and $\;C_2\;$.
|
$C_1$={ ** _MARY** ,RAMY,ARMY,AMRY, **MRAY** ,RMAY,}_
So, n($C_1$)=3!=6
$C_2$= _{ **MARY** , **MRAY** ,MAYR,MYAR,MRYA,MYRA}_
So, n($C_2$)=3!=6
$C_1∩C_2$= **{MARY,MRAY}** ; n($C_1∩C_2$)=2
$C_1UC_2$={ ** _MARY** ,RAMY,ARMY,AMRY, **MRAY** ,RMAY,MAYR,MYAR,MRYA,MYRA}_ ; n($C_1UC_2$)=10.
Hope it helps.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "probability distributions"
}
|
Most important things about C# generics... lesson learned
What are most important things you know about generics: hidden features, common mistakes, best and most useful practices, tips...
I am starting to implement most of my library/API using generics and would like to collect most common patterns, tips, etc., found in practice.
Let me formalize the question: What is the most important thing you've learned about generics?
**Please try to provide examples -- it would be easier to understand, as opposed to convoluted and overly-dry descriptions**
Thanks
This question is somewhat similar to Jon's question, though, on a different subject.
|
One of the most important things I've learned is that you can constrain the generic type parameter(s). This can be very powerful, allowing you to take customize the class for only certain types of objects and allowing you to use the members of that type in your generic class. I realize that this is pretty fundamental, but it's one of the things that makes generics incredibly useful.
|
stackexchange-stackoverflow
|
{
"answer_score": 14,
"question_score": 11,
"tags": "c#, .net, generics"
}
|
What opening music was played at the beginning of the anime Kaiketsu Zorro?
One of my favorite animes used to be Kaiketsu Zorro, and I especially loved the opening music of the Portuguese version of the cartoon.
My question is, is the music custom made for the anime series, or does it exist outside the anime?
If it's an actual piece, what is its name/who is it by?
|
It looks like the OP of the Portuguese dub of Kaiketsu Zorro is the instrumental (i.e. no lyrics) version of the original Japanese OP.
The original Japanese OP was presumably made specifically for the series, seeing as it is titled "ZORRO" (cf. the ANN entry for Kaiketsu Zorro). The piece was sung by MASAAKI Endoh (probably better known for his involvement in JAM Project); composed and arranged by TOBISAWA Hiromoto, who also did the music for Kaiketsu Zorro; and featured lyrics by ARIMORI Satomi
|
stackexchange-anime
|
{
"answer_score": 1,
"question_score": 1,
"tags": "theme song, kaiketsu zorro"
}
|
ATtiny85 serial communication, bootloader and setting up fuses
I have been reading some articles about ATtiny and how to burn the bootloader. And I have two questions which I can't figure out.
1. Do I need to manually setup fuses to run 8 MHz on my ATtiny when I'm using my Arduino board as my ISP (there we can select the internal clock and that confuses me)?
2. For the SoftwareSerial.h library, do I need to setup my ATtiny to 8 Mhz in order to work?
|
If you load this into the IDE < the fuses will be set correctly for the different selectable clock speeds.
|
stackexchange-arduino
|
{
"answer_score": 0,
"question_score": 1,
"tags": "softwareserial, bootloader, attiny85, fuses"
}
|
Maven - can i include third-party dependencies during app's runtime?
Maven - can i include third-party dependency during app runtime (mb using command line)?
|
If dependency is not required for compilation, but is required for execution or test execution you can use "runtime" dependency scope. For example:
<dependency>
...
<scope>runtime</scope>
</dependency>
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "java, maven, plugins, dependencies"
}
|
pipe Certificate Signing Request into opennsl x509 command
In the openssl docs it states (at < that the '-in' option
> specifies the input filename to read a certificate from or standard input if this option is not specified.
I am trying to figure out how to sign a CSR (using a private CA) using `stdin` to send the CSR. The following line generates an error
openssl x509 -req -CA CA.pem -passin pass:abcdefg -set_serial 40 "-----BEGIN CERTIFICATE REQUEST-----###########-----END CERTIFICATE REQUEST-----"
(where ###### represents the CSR data)
The error is:
unknown option -----BEGIN CERTIFICATE REQUEST-----###########-----END CERTIFICATE REQUEST-----
It takes the input to be an option.
Doing
openssl x509 -req -CA CA.pem -passin pass:abcdefg -set_serial 40 -in request.pem
where request.pem contains the EXACT same data that is between the two `"`'s in the first line is SUCCESSFUL.
What am I doing wrong?
|
Erm, you're not providing the CSR on stdin, you're specifying it as a parameter. To provide it from stdin you either need to redirect it from a file, or pipe it from another command. For example:
echo "-----BEGIN CERTIFICATE REQUEST-----###########-----END CERTIFICATE REQUEST-----" | openssl x509 -req -CA CA.pem -passin pass:abcdefg -set_serial 40
Or, if the CSR is stored in csr.pem:
openssl x509 -req -CA CA.pem -passin pass:abcdefg -set_serial 40 < csr.pem
|
stackexchange-serverfault
|
{
"answer_score": 5,
"question_score": 3,
"tags": "ssl"
}
|
How to use a user input variable across multiple unit tests?
I have a C++11 project with many googletest unit tests looking like
TEST_F(GTest, testSomething) {
int64_t n = 42;
// following code depends on input size n
...
}
Rather than having a local constant `n` in each test, I'd like to be able to set the input size from one location, preferably the command line:
./RunMyProgram --gtest_filter=* --n=1000
The `main` should look like:
int main(int argc, char **argv) {
// TODO: parse command line argument n here
INFO("=== starting unit tests ===");
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
With what should I replace `?` in my test functions?
TEST_F(GTest, testSomething) {
int64_t n = ?;
// following code depends on input size n
...
}
|
First of all, if you use the same value/parameter in more than one of your test functions, consider to use Fixtures.
What you are trying to do for me looks like a "value parameterized test". I guess thats rather common in testing world, and - tadaa, Google Test has a chapter in its advanced guide, called "Value Parameterized Test" (and oh, it uses fixtures).
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 3,
"tags": "c++, unit testing, global variables, googletest"
}
|
Calorie Meter refresh input
I am creating Vue.Js calorie counter application, how can I reset values in my input fields after I add the new item?
app.foodItems.push({
name: app.newFoodItems[0].name,
calories: app.newFoodItems[0].calories,
protein: app.newFoodItems[0].protein,
fats: app.newFoodItems[0].fats,
carbs: app.newFoodItems[0].carbs,
});
When i add the new item I want to refresh the input field so user can input the new Item from scratch.
|
You can do something like the following inside your `app.foodItems.push`
app.newFoodItems[0].name = '';
app.newFoodItems[0].calories = '';
app.newFoodItems[0].protein = '';
app.newFoodItems[0].fats = '';
app.newFoodItems[0].carbs = '';
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "vue.js"
}
|
Stop-Service not interating through each service
I'm trying to disable all Windows services (using a Win10 test VM) and go through each individually, to disable all unnecessary services based off services I'm using (web server, ftp, etc).
I was going to loop through it but basically ended up with similar syntax. I also tried to implement `Sleep-Timer` but I probably put it in the wrong place.
Get-Service | Where-Object {$_.Status -eq "Running"} | Stop-Service -Force
At least error messages for all of them. It's only showing error messages for the first two:

{
Stop-Service $service -Force
}
I also found an open source script that does it cleaner: <
The link giving by James C. is one I will reference through my learning process of these services. Thank you all!
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "powershell"
}
|
Pug (Jade) add presence of attribute inline dynamically
Depending on a variable, the `style` attribute can be present or not.
label(for='ff'
class='ff1'
varFlag != undefined ? eval(style= 'letter-spacing: -5px;') : eval('')
)
\-- that does not work. And the following code adds empty style, that is not accaptable:
label(for='ff'
class='ff1'
style= varFlag != undefined ? 'letter-spacing: -5px;' : ''
)
How can we have an attribute depending on a condition?
Checked similar questios - found nothing relevant.
|
One approach would be to have two separate elements for that scenario:
if !varFlag
label(for='ff' class='ff11')
else
label(for='ff' class='ff1' style="letter-spacing: -5px")
Or if you want to get really fancy, you could use a `mixin`, but that might be more heavy lifting than is needed.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, pug, dhtml"
}
|
Tracking number of IOs to disk on Windows
I'm trying to compare 2 versions of a backup software product. I setup all IO to go to a dedicated drive.
Is there a way with performance monitor (or anything else) to track the number of IO operations.
I know I can measure disk queue length and different stats like that, but I'd like to know the exact number of IO operations.
|
The metric you are looking for is "Disk Transfers/sec" under "Physical Disk" in Performance Monitor. !Screen-capture of PerfMon setting
|
stackexchange-serverfault
|
{
"answer_score": 4,
"question_score": 0,
"tags": "backup, windows 7, performance monitoring, performance"
}
|
divide each value by unique value from a level of factor
I would like to divide each value by "q" grouped on id. So each id´s unique "q" should divide each id´s unique "comb_abc" and "q". The end result for id A1 would be comb_abc = 3.333 and q = 1. I have more levels for each id than these two, but this example is for the sake of simplicity. What kind of code would do the trick? THANKS! I have a data that looks like this:
# id event value
# <chr> <chr> <dbl>
#1 A1 comb_abc 10
#2 A1 q 3
#3 B2 comb_abc 18
#4 B2 q 6
#5 C3 comb_abc 15
#6 C3 q 7
|
We can use `match` to get the index of `value` corresponding to `'q'` event.
library(dplyr)
df %>%
group_by(id) %>%
mutate(val = value/value[match('q', event)])
# id event value val
# <chr> <chr> <int> <dbl>
#1 A1 comb_abc 10 3.33
#2 A1 q 3 1
#3 B2 comb_abc 18 3
#4 B2 q 6 1
#5 C3 comb_abc 15 2.14
#6 C3 q 7 1
If the `'q'` event is `last` in each group we can also use :
df %>%
group_by(id) %>%
mutate(val = value/last(value))
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "r, dplyr"
}
|
Test attribute of the json response returned by open policy agent with opa test
Is there a way to test value of a key/attribute inside the json response of the decision returned by OPA.(Response returned is not yes/no but a json with key allow which dictates the decision) For example:
test_get_user_allowed_for_admin {
decision["allow"] with input as {"path": ["users", "kate"], "method": "GET", "user_id": "bob"}
}
Let’s say the policy evaluated is of the form:
get_user_info = decision{
decision := {
"allow": input.user_id == "bob", "user_id": input.user_id,
}
}
currently I get a `var decision is unsafe` error because decision is not defined in the `test_get_user_allowed_for_admin` but that is just a filler
|
Your test can check the value generated by the rule `get_user_info` just like any other value (e.g., `input`, a local variable, etc.)
For example:
test_get_user_allowed_for_admin {
in := {
"path": ["users", "kate"],
"method": "GET",
"user_id": "bob"
}
result := get_user_info with input as in
result.allow == true
result.user_id == "bob"
}
# OR
test_get_user_allowed_for_admin_alt {
in := {
"path": ["users", "kate"],
"method": "GET",
"user_id": "bob"
}
result := get_user_info with input as in
result == {"allow": true, "user_id": "bob"}
}
Technically you don't have to assign the value generated by `get_user_info` a variable:
test_get_user_allowed_for_admin_oneline {
in := {
"path": ["users", "kate"],
"method": "GET",
"user_id": "bob"
}
get_user_info.allow with input as in
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "open policy agent"
}
|
nested forEach doesn't change its elements
This is what I'm trying to do:
{
emp.carl.forEach(function(pass){
pass="change";
});
});
but no changes are being made or whatsoever, What is wrong?
Expected output: change all elements inside `carl` to `changed`. all `test` elements will contain a property `carl` that contains an array of string.
|
Assigning a parameter to some value won't have any effect outside that function.
Instead, you should assign a property:
emp.carl.forEach(function(pass, i, arr){
arr[i] = "change";
});
var doc = {
"name": "aaa",
"test": [{
"carl": [
"huh",
"two"
]
}]
};
doc.test.forEach(function(emp) {
emp.carl.forEach(function(pass, i, arr) {
arr[i] = "change";
});
});
console.log(doc);
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": -1,
"tags": "javascript, mongodb"
}
|
How to stop XCode replacing system commands in run script phase?
My situation: OSX 10.9 + Xcode 4.6.3 + run script phase + script:
#!/bin/bash
/usr/bin/svn --version
ls -la /usr/bin/svn
exit 1
I receive the outputs:
svn, version 1.6.18 (r1303927)
-rwxr-xr-x 1 root wheel 14224 26 oct 05:08 /usr/bin/svn
This is unbelievable. The size and date of the real file correspond with v1.7.10 (which is really placed at the path `/usr/bin/svn`) but calling this file from within XCode will call the `/Application/Xcode463.app/Content/Developer/usr/bin/svn` command!
How can I prevent this? How can I call my default `/usr/bin/svn` command? How is it possible to do hidden replacement of one command with another without replacing the real file?
|
The right answer is that `/usr/bin/svn` is a link to the `xcrun` wrapper. Command to see it:
nm /usr/bin/svn
So root cause of issue is next command:
xcode-select --print-path
in the run script phase will print current Xcode instead of system default Xcode.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "xcode, bash, sdk, command"
}
|
Grabbing values from HTML with BS4
I am having a hard time figuring out how to grab certain data from this HTML snippet that I've obtained from parsing through HTML via BeautifulSoup.
Here is my code:
productpage = '
rr = requests.get(productpage)
soup1 = BeautifulSoup(rr.content, 'xml')
productIDArray = soup1.find_all("div", class_="size-button property available")
#print for debugging purposes
print(productIDArray[0])
productIDArray[0] returns
<div class="size-button property available" data-productId="207789">
<span class="size-type" title="UK 3.5 | 36">
US 4
</span>
</div>
How would i grab the value of data-productID and the title of the span so that I can place them into variables?
Thank you.
|
productIDArray['data-productId']
out:
'207789'
* * *
productIDArray.span['title']
out:
'UK 3.5 | 36'
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "python, html, beautifulsoup, python requests"
}
|
How To maintain ViewState of PlaceHolder in asp.net
please tell me how to maintain state of placeholder. i have a placeholder in which i add many image controls dynamically but when my page get refresh all controls from placeholder gets removed from it. the enableViewstate of placeholder is set to true.. please tell me how to maintain its state..
|
ViewState registration happens just after the Init events in the Page lifecycle.
If you are adding your dynamic images after Init, then they are not registered as part of ViewState. Your issue will be solved if you add them to your Placeholder control during `Page_Init`.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 0,
"tags": "asp.net, placeholder"
}
|
How to set default encoding to utf-8, and default line ending to linux style?
I use this piece of code to set the default line ending to linux-style `\n`
;;
(add-hook 'find-file-hook 'find-file-check-line-endings)
(defun dos-file-endings-p ()
(string-match "dos" (symbol-name buffer-file-coding-system)))
(defun find-file-check-line-endings ()
(when (dos-file-endings-p)
(set-buffer-file-coding-system 'undecided-unix)
(set-buffer-modified-p nil)))
And this - to set the default encoding to utf-8
;; emacs set default codepage
;;
(prefer-coding-system 'utf-8)
(setq coding-system-for-read 'utf-8)
(setq coding-system-for-write 'utf-8)
But it looks like because of the second one, first isn't working. Now line ending is `\r\n` on saving, even if I manually change it.
|
;; make unix lineendings default
(setq default-buffer-file-coding-system 'utf-8-unix)
|
stackexchange-emacs
|
{
"answer_score": 2,
"question_score": 4,
"tags": "character encoding, newlines"
}
|
Python convert html ascii encoded text to utf8
I have a xml file, which I need to convert to utf8. Unfortunately the entities contain text like this:
/mytext,
I'm using the codec library to convert files to utf8, but html entities won't work with it.
Is there an easy way to get rid of the html encoding?
Thanks
|
You can pass the text of the file through an unescape function before passing it to the XML parser.
Alternatively, if you're only parsing HTML, lxml's http parser does this for you:
>>> import lxml.html
>>> html = lxml.html.fromstring("<html><body><p>/mytext,</p></body></html>")
>>> lxml.html.tostring(html)
'<html><body><p>/mytext,</p></body></html>'
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "python, encoding, utf 8, ascii, html entities"
}
|
JavaScript convert string into literal comma list
Is there a way to convert `"1,2"` into `1,2` using native JS without some sort of wrapper?
`"1,2".someMagic() \\ 1,2`
Ultimately, I want to pass this as arguments to a function.
|
Firstly, no there is no way to convert `"1,2"` to literally `1,2`. Because it is invalid type. 1,2 is better represented as an array
You can use .apply like below to send 1,2 as parameters (array format) to the function someMagic
someMagic.apply(context, [1,2]);
Apply would call someMagic and send 1,2 as parameters
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, string"
}
|
Mean value theorem application
Prove that $$\lim_{x \to 0} \frac{\cos x -1}{x}=0$$ **using the mean value theorem**.
I understand that this may be shown with a different method, but I am required to use MVT. How can I prove this expression? I don't see how MVT is applicable here at all.
|
Mean value theorem states that there is $c \in (a,b)$ such that: $$ f'(c) = \frac{f(b)-f(a)}{b-a} $$
Let $f(x) = \cos (x)\text{, } b=x \text{ and }a = 0$. This gives $$ \- \sin(c) = \frac{\cos(x)-\cos(0)}{x-0}=\frac{\cos(x)-1}{x} $$ $$ x\rightarrow 0 \Rightarrow c\rightarrow0 \Rightarrow \sin(c) \rightarrow 0 $$
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "limits"
}
|
How do population genetics people define a population?
How do population genetics people define a population?
Do they define it as a layman will do? say Africans, Americans, or so? Or is there a more scientific way of doing so? For example, I think defining one's population as one's allele frequencies makes more sense, but has this point been discussed previously?
|
It really depends on the study and the ethnicity. Mostly they use self-defined ethnicity and often they will require that three or four grandparents are of that ethnicity. Here's some detailed info on how the ethnicity was defined for the 1000 Genomes populations. You'll see that some populations (such as ASW) require all four grandparents to identify as that ethnicity, but some (such as ACB) only need three, and the cultural sensitivities in Japan meant that JPT participants weren't questioned directly but told that the study was only interested in people with Japanese grandparents. The mixed American super-population (AMR) is an exception to this rule due to the extreme admixture of ethnicity in these regions, and is based more in geography than ethnicity – this means that the individuals had to be from the place and have grandparents from the place.
|
stackexchange-bioinformatics
|
{
"answer_score": 2,
"question_score": 5,
"tags": "phylogenetics, genetics"
}
|
Existence of Fixed Point in Proof of Second Sylow Theorem
I was reading this proof of the Second Sylow Theorem: < And I didn't fully understand how the author proved that a fixed point exists. If Q has cardinality $p^{\beta}$ and the left coset space of P has cardinality $m$, then couldn't it be possible that $p^{\beta} < m$, then the action of Q on any particular coset of P can map that coset to $p^{\beta}$ other cosets but not the same one?
|
So more generally: assume that $G$ is a $p$-group that acts on $X$ such that $p$ does not divide $|X|$.
Assume that $x\in X$ **is not** a fixed point. It follows that the subgroup $G_x=\\{g\in G\ |\ gx=x\\}$ **is proper**. Recall that $Gx\simeq G/G_x$ where $Gx=\\{gx\ |\ g\in G\\}$ is the orbit of $x$. Since $G$ is a $p$-group then it follows that $p$ divides $|Gx|$.
Now assume that there are no fixed points. Then $p$ divides the size of every orbit. In particular $p$ divides $|X|$ because $X$ is a disjoint union of orbits. It's a contradiction.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "group theory"
}
|
coffeescript throw Error("ExecJS::RuntimeError: SyntaxError: unexpected , in function
I have written this function in coffeescript:
doCalculate = (old, new) ->
difference = roundNumber (old - new, 5)
but when compiled generates the error:
throw Error("ExecJS::RuntimeError: SyntaxError: unexpected ,
If I remove the `, 5` part I get no error any more.
I can't figure what's wrong with a comma.
The function `roundNumber` is defined as follows, in the same file:
roundNumber = (rnum, rlength = 6) ->
pow = Math.pow( 10, rlength )
newnumber = Math.round ( rnum * pow ) / pow
parseFloat(newnumber)
|
ahhhh I figured it out. coffeescript requires that there is no space between the function name and the open parenthesis.
it even works with no parentheses at all.
but not if there's a space between the function name and the (.
this works:
difference = roundNumber old - new, 5
Thanks :)
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "syntax, coffeescript"
}
|
Variable in the exponent?
**This is straight from my homework, so please do NOT solve it for me!!**
This is the easiest of the kind from my homework, and is under the 'Logarithms' chapter.
$$10^{-4x} = 62$$
Round to the nearest hundredth.
I'm not sure how to start it, if it did not have the x in the exponent, I'd take the -4th root of both sides.
Because this is under Logorithms, I'd start with:
$10^{62} = -4x$
Is this the next step? ${log_{10}}^{62} = -4x$
|
$$(-4x)\log_{10}10=\log_{10}62\\\ \implies x=-\dfrac{\log_{10}62}{4}$$ Now, use a calculator.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 1,
"tags": "linear algebra"
}
|
comparison of two numbers in python in if condition does not work correctly, why?
I have part of code that compares two numbers in python,
if (vw_q==vw_q):
if dst<=th:
cnd= not cnd
print vw_d,vw_q,dst
matched_index[j]=cnd
and the condition (first if) compares two numbers if thwo numbers are equal go to the next if condition, however, the output is not correct. This is first few outputs:
24 38 44.929686067367584
20 14 22.70541826128124
10 11 35.3443227053815
24 44 1.650238537037012
39 42 11.848092479431216
39 28 11.848092479431216
23 46 0.18987032267705217
23 15 0.18987032267705217
.
.
.
Do you have point about this, why?
|
You're comparing the first number to itself in the first if statement.
Change it to:
if (vw_d==vw_q):
if dst<=th:
cnd= not cnd
print vw_d,vw_q,dst
matched_index[j]=cnd
You should spend some time trying to work out errors yourself before posting on here, as this one is something you could definitely have resolved yourself.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -3,
"tags": "python, python 3.x, python 2.7, if statement"
}
|
In Skyrim, how can I keep my companion after getting married?
After I got married in Skyrim, my companion ran away! When I tried to talk to her, all she said was, "congratulations on your wedding, I hope you two are happy together", in a tone in which you can sense she is hurt, deep down, that you did not choose her. She then proceeds to run way from you.
She even takes all your items! I was able to pickpocket my items back from her, but I want her to continue following me! How can I get her to continue following me after getting married? What console commands can I use to force her to continue following me?
|
I wasn't able to get Lydia following me again, but I did just find a mod that lets me get another companion, just tried it and it works: Skyrim Everplayer - Add Muiri As A Second Companion Even If You Are Married
|
stackexchange-gaming
|
{
"answer_score": 1,
"question_score": 0,
"tags": "the elder scrolls v skyrim"
}
|
What does good condition mean in a Pokemon Contest?
In Pokemon Ruby/Sapphire/Emerald, the description for Rock Smash on the Contest Moves page says "The appeal works well if the user's condition is good". What does this mean? How can I tell if my condition is good in a Pokemon Contest?
 could help recalculating the layout.
Another option is to embrace the adding/removing of items with the following code:
Ext.suspendLayouts();
... // add/remove items here
Ext.resumeLayouts(true);
BTW: More details on your problem would be helpful (e.g. code snippets, ExtJS version).
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "extjs, panel, formpanel"
}
|
Angular2 Read from Configuration File
I'm making a new angular2 application which will hit an endpoint on all of our applications on all of our servers to get build numbers, and then it will display them in a grid so we can see which servers have which build numbers.
When I built a similar application using Angular1, I was able to use gulp-ng-config to read a JSON file and output an angular module with the values from the JSON. I'm looking to do something similar in Angular2, but I have no idea how to accomplish this. Any ideas?
|
This way you go read `.json` file in `Angular2`.
**_Note_** : This way you can read `.json` file. This demo shows `.json` file example.
working demo => click `friends tab`
http.get('friends.json (=filepath)')
.map(res => res.json())
.subscribe((data) => { this.result=data; },
err=>console.log(err),
()=>console.log('done')
);
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 1,
"tags": "angular"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.