INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
SQL query that combines 3 tables
In my Access database I have a three different tables based on a pizza company:
!enter image description here
!enter image description here
!enter image description here
What query can I write to show the names of all the delivery staff and the number of items they have delivered? I understand I have to use table aliases but as I am new to SQL I am having problems finding a solution.
|
Try this:
select StaffId, fName, lName, sum(Quantity)
from DeliveryStaff ds, Orders o, OrderItems oi
where StaffId = DeliveryStaffId
and o.OrderId = oi.OrderId
group by StaffId, fName, lName
|
stackexchange-stackoverflow
|
{
"answer_score": -1,
"question_score": 0,
"tags": "sql, sql server"
}
|
Posting Data to another Page ExtJs
I'm trying to post an array using a POST request to a specific page, the target page generates a csv and send me back the stream, right now i'm doing using ExtJs Ajax class, but that won't work as i need to make a normal HTTP request not ajax, my current code is as follows:
Ext.extend(Players.panel.Home,MODx.Panel,{
exportSubscribers: function(btn,e) {
MODx.Ajax.request({
url: Players.config.connectorUrl
,params: {
action: 'mgr/player/getSubscribers'
}
});
}
});
The exportSubscribers function is executed from a normal ExtJs button
{ xtype: 'button'
,text: 'Export Subscribers'
,preventRender: true
,handler: this.exportSubscribers
}
What class should i use to turn this into a normal request?
Thanks.
|
There isn't a class to do a _normal request_. I known two ways to accomplish a file download:
* Use a hidden form in the page, replace the field values and invoke the form's `.sumbit` method from ExtJS button handler to do the POST request you want.
* Replace your button by an HTTP anchor if you can use a GET request to make the server return the file: `<a href="url?params" title="Download CSV">Download CSV</a>'`
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "extjs, modx"
}
|
python: xml.etree.elementtree.ElemenTtree.write() declaration tag
I’ve created an XML document using xml.etree.elementtree.Element, and wanted to print it using the ElementTree.write() function but the declaration tag that comes out is
<?xml version='1.0' encoding='UTF-8'?>
While I need to be in double quotes. is there a way to change that?
|
Eventually I used the tostring function and appended the XML to the correct tag and then the python file.write function. It's ugly (and im lying about the actual encoding of the file) but it works.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 19,
"tags": "python, xml"
}
|
Printing a database as text
I'm an R Markdown newbie. I've got a db as follows:
text <- c("aaa","bbb", "ccc")
year <- c(2003,2004,2005)
author <- c("MV", "RV", "MV")
db <- as.data.frame(cbind(text, year, author))
I would like to print it a bullet point as follows:
> * aaa
>
> 2003, MV
>
> * bbb
>
> 2004, RV
>
> * ccc
>
> 2005, MV
>
>
I tried as follows:
- `r db[1, 1]`
- `r db[1, 2]`
- `r db[1, 3]`
- `r db[2, 1]`
- `r db[2, 2]`
- `r db[2, 3]`
- `r db[3, 1]`
- `r db[3, 2]`
- `r db[3, 3]`
Is there a way to do it automatically without listing each line?
|
You can write R code that prints your data as markdown text, for example using glue:
library(glue)
text <- c("aaa","bbb", "ccc")
year <- c(2003,2004,2005)
author <- c("MV", "RV", "MV")
db <- as.data.frame(cbind(text, year, author))
glue_data(
db,
"* {text} ",
"{year} {author}",
.sep = "\n"
)
#> * aaa
#> 2003 MV
#> * bbb
#> 2004 RV
#> * ccc
#> 2005 MV
If you put this in an RMarkdown chunk with the option `results='asis'`, the generated markdown will be included in your knitted document.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "r, r markdown, markdown"
}
|
BeautifulSoup: what's the difference between 'lxml' and 'html.parser' and 'html5lib' parsers?
**When using Beautiful Soup what is the difference between 'lxml' and "html.parser" and "html5lib"?**
When would you use one over the other and the benefits of each? When I used each they seemed to be interchangeable, but people here correct me that I should be using a different one. I'd like to strengthen my understanding; I've read a couple posts on here about this but they're not going over the uses much in any at all.
Example:
soup = BeautifulSoup(response.text, 'lxml')
|
From the **docs**'s summarized table of advantages and disadvantages:
1. **html.parser** \- `BeautifulSoup(markup, "html.parser")`
* Advantages: Batteries included, Decent speed, Lenient (as of Python 2.7.3 and 3.2.)
* Disadvantages: Not very lenient (before Python 2.7.3 or 3.2.2)
2. **lxml** \- `BeautifulSoup(markup, "lxml")`
* Advantages: Very fast, Lenient
* Disadvantages: External C dependency
3. **html5lib** \- `BeautifulSoup(markup, "html5lib")`
* Advantages: Extremely lenient, Parses pages the same way a web browser does, Creates valid HTML5
* Disadvantages: Very slow, External Python dependency
|
stackexchange-stackoverflow
|
{
"answer_score": 44,
"question_score": 31,
"tags": "python, html, web scraping, beautifulsoup, lxml"
}
|
Adding 20 minutes to number in java
So I need a variable that shows times in 24HR format (01:00, 09:00) and every time I loop through it, to add 20 mins to the time? I then need to use this value in a string.
The time needs to start at any given time. like 00:00 Any ideas how should I go with it?
and output like this 00:00-00:20,00:20-..00:40,00:40-01:00 and so on....
.truncatedTo(ChronoUnit.DAYS);
DateTimeFormatter df = DateTimeFormatter.ofPattern("HH:mm");
System.out.println(dt.format(df));
for (int i = 0; i < 24 * 3; i++) {
dt = dt.plusMinutes(20);
System.out.println(dt.format(df));
}
Its output is as follows:
00:00
00:20
00:40
01:00
01:20
...
**Update**
Sorry, it could be done with simple loop:
for (int min = 0; min < 24 * 60; min += 20) {
int next = min + 20;
String timestamp = String.format("%02d:%02d - %02d:%02d", min/60, min%60, next/60, next%60);
System.out.println(timestamp);
}
/////
00:00 - 00:20
00:20 - 00:40
00:40 - 01:00
...
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "java, java 7"
}
|
Semantic-based recommender Facebook application
As a project of this semester my friend and I are thinking to make a semantic-based recommender Facebook application. For example, if I wanted to go "a trip to Europe", this application is intended to do the following: go search in my friends list and gives me back all photos albums having the name "Italy Travel" or even only containing a comment about "Eiffel Tower", my friends statuses related to anything in Europe, notes of my friends, links they have liked in other websites and other activities that show up in their news feed. And same goes if I want to watch a movie, read a book or study a subject...etc.
And my question is:
1. Is such thing possible to be achieved within 3 months? knowing that we have only the very basis about Facebook API and semantic related subjects.
2. If it is, what Ontology can we rely on? And what other concepts should we have as a starting block?
|
In 3 Months Most probably yes (depends upon how much you already know about Facebook API).
Things you should know before embarking on journey to develop this (Some i think are significant enough..)
* Either you can go about developing whole Interaction Code between your server and Graph API yourself.
* Or use some SDK that are already out there.(Some are mentioned in Facebook docs) Like Facebook C# SDK for C#.
* Understanding of FQL and Graph API (Make some small project first to try and test things like getting user friend list).
* Basic understanding of HTTP GET and POST requests and how to construct them in language of your choice.
* Parsing JSON in your language.
* Get a print out of documentation of selected topics for offline reference ( _I did that..._ )
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "facebook, semantic analysis"
}
|
?ACT not working anymore after upgrade from ExpressionEngine 2.2.1 to ExpressionEngine 2.5.3
I am completely stuck as to why my EE install after the upgrade to EE 2.5.3 suddenly does not allow for some standard ?ACT eg search (?ACT=2), sending off a contact form or logout (?ACT=10) from the front end.
Actions get redirected to the homepage.
No additional modules installed after upgrade.
my htaccess file includes just a basic redirect
RewriteEngine On
RewriteCond $1 !\.(gif|jpe?g|png)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) index.php?$1 [L]
Cheers
|
You should probably have the following in your .htaccess instead - this is likely to be the cause.
`RewriteRule (.*) /index.php/$1 [L]`
Replace your line :
`RewriteRule (.*) index.php?$1 [L]`
with the above and it should work.
|
stackexchange-stackoverflow
|
{
"answer_score": 8,
"question_score": 6,
"tags": "expressionengine"
}
|
Is there any reason to use the 'return' in the second line in the method ?
I have this code that we can write in two ways
**First Way**
void func(int val)
{
if(val == 0)
return;
// Do something ...
}
**Second Way**
void func(int val)
{
if(val != 0)
{
// Do something ...
}
}
The Question:
Is there any reason to use the first way ? Is there any Advantage to use the first way ( in C++ or in C# )
|
The main reason to use the first way is to reduce nesting in your source file.
|
stackexchange-stackoverflow
|
{
"answer_score": 10,
"question_score": 3,
"tags": "c#, c++"
}
|
Playing around with builtin functions
So I was playing around with `dir()` function. I ran a simple `dir(builtins)` function which gave me a list of defined names. What was unexpected is when I ran this just to fool around:
dir('\nbuiltins')
This gave a me a entirely different list of names. Can someone explain what is going on? :) thanks!
|
`dir` returns names of attributes of the given object.
`'\nbuiltins'` is a string literal. So you get attribute names of the string object.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "python"
}
|
where i can find the wacom configuration file in ubuntu 12.04?
I want to know the location of the configuration file created with the wacom tablet tool in ubuntu 12.04, I want to change the preassure curve and another settings manually..
thanks and have a good day
|
You can follow this guide here: < as it details the setup of the pressure curve as follows:
`gksudo gedit /usr/share/X11/xorg.conf.d/50-wacom.conf`
Edit it so it looks like the following with your new Pressure settings:
Section "InputClass"
Identifier "Wacom class"
MatchProduct "Wacom|WACOM"
MatchDevicePath "/dev/input/event*"
Driver "wacom"
Option "PressCurve" "50,0,100,50"
Option "Threshold" "60"
EndSection
Save and unplug and re-plug your device.
|
stackexchange-askubuntu
|
{
"answer_score": 0,
"question_score": 0,
"tags": "12.04, files, configuration, wacom"
}
|
Necessity of physical access to air-gapped computers
In an intriguing paper Fansmitter: Acoustic Data Exfiltration from (Speakerless) Air-Gapped Computers (also see this summary) the authors demonstrate that they are able to exfiltrate data from an air-gapped computer by modulating the rotation speed of the cooling fan. A similar thing has been done using a computer's internal microphone. Obviously this type of attack requires physical access _at some point_ to install the malware.
What I don't fully understand is this: why go to all this trouble if you need physical access to your target anyway, and could then just extract whatever data you're interested in? What am I missing?
|
What I think is important to point out about malware targetting air-gapped systems is that as much as these methods require physical access, _it doesn't require that the attacker himself has physical access_.
The idea is to spread the malware on as many computers as possible around the targeted system so that someone who is allowed to physically access it will eventually plug a contaminated USB key to the said system.
However, these methods seem to still require the attacker to be fairly close to the target to pick up the sounds produced. I think it is usually more efficient when the objective is to cause damage to the air-gapped system (erasing data, causing disfunction in automated industrial tools etc...).
|
stackexchange-security
|
{
"answer_score": 4,
"question_score": 3,
"tags": "attacks, air gap"
}
|
Resizing a UIStackView using AutoLayout
I have the following setup in my storyboard. I want the selected `UIStackView` to stretch across it's parents view so its right edge is the same distance away from the edge of the screen as the left edge.
Control dragging from the stackview to it's parent view and selecting "Trailing space to container margin" doesn't do what I thought it would (I am very new to auto layout). What is the correct way to resize this stackview? TIA
.
here is the code : !enter image description here
|
Unfortunately, media query is not supported in Internet Explorer 8 or older. You can use Javascript to hack around. See these! You can use `<!--[if lt IE <version>]>` for compatibility issues.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 4,
"tags": "html, css, internet explorer, media queries"
}
|
Convert DateTime to long and also the other way around
I want to store dates as numbers in a table. I know how to do that but I don't know how to go back. How can I cast a long variable to ToDateTime.
DateTime now = DateTime.Now;
long t = now.ToFileTime();
DateTime today = t.ToDateTime; // I am looking for something like this line. This Method does not exist
I know there are many ways of converting DateTime to long. I don't mind which technique to use. I just want to have a way where I can convert back and forth.
|
To long from DateTime:
`long DateTime.Ticks`
To DateTime from long:
`new DateTime(long)`
|
stackexchange-stackoverflow
|
{
"answer_score": 124,
"question_score": 62,
"tags": "c#, .net, datetime"
}
|
htaccess как найти на самописе?
Появилась задача на новом проекте отредачить htaccess. У заказчика свой сервер, сайт самопис. Захожу я туда значит, через FTP - вообще непонятная структура, сотни папок и ничего непонятно. В классическом случае этот файл лежит в корне, а здесь не могу найти. Подскажите как можно его найти и понять, если ли он там вообще?
|
Имеется ли доступ к shell?
Способы найти рекурсивно файл.
1. С использованием shell введите в командной строке: __find . -name 'htaccess_ ' -type f_* и найдите ваш файл.
2. С помощью php обойдите рекурсивно каталоги и найдите файл.
3. Может быть у вас не отображаются скрытые файлы просто?
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": ".htaccess"
}
|
Why didn't people of the Leaf Village want to get closer to Naruto if he is the son of the 4th Hokage?
Naruto was always discriminated against by the people of the Leaf Village because he had the Kyuubi inside. However, he is the son of the 4th Hokage and he was the one who sealed it inside him. Why, then, did they discriminate against him if it was in order to save the village?
|
The details of how Minato sealed the Kyuubi inside Naruto, and the fact that Naruto is Minato's son was kept hidden from the villagers. The villagers believed that Naruto is the reincarnation of the Kyuubi, who killed their beloved Hokage. Having experienced the Kyuubi's attack on Konoha, they were also frightened about going near Naruto. Even the people who knew that the Kyuubi was sealed inside Naruto were worried about their own safety, and wanted to stay away from Naruto.
|
stackexchange-anime
|
{
"answer_score": 9,
"question_score": 5,
"tags": "naruto"
}
|
git merge --no-commit vs git cherry-pick --no-commit
Is there any difference between `git merge --no-commit` and `git cherry-pick --no-commit`?
And is there any difference in history if I commit after these two commands?
|
If you commit after `git merge --no-commit`, you'll actually get a merge commit. Whereas after a `git cherry-pick --no-commit` you'll get a commit with a single parent.
Hence, yes, there is a difference between those two commands.
In particular if you have something like
A -- B -- C
\ L HEAD
\
-- D -- E
If you `cherry-pick` commit `E`, you won't get modifications of commit `D`. Whereas if you `merge`, you'll get both.
|
stackexchange-stackoverflow
|
{
"answer_score": 55,
"question_score": 41,
"tags": "git, git merge, git cherry pick"
}
|
Is there a way to query mySql if my connection has started a transaction?
I have found many anwsers of how frameworks handle transaction nesting, but I couldn't found if there is an executable query against mySql RDMS that returns if a transaction has started or not. Is it posible? thanks
|
It is a bit tricky, but you can find an example how to do this at <
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "mysql, transactions"
}
|
How to know if a location is out of my 2D array?
I need to know if a location of a 2D array is out of it. For example i got a 8x8 array and the user needs to add a number in a location, for example `MyArray[3][7]` but first i need to verify if that location is in my array. so... can i ask that like this?
if (MyArray[x - 1][y - 1]==NULL){
printf("Give me another location: \n");
.
.
.
}
|
If the value of `x` and `y` are entered by the user then you could do something like this:
#include <stdio.h>
int main() {
int MyArray[8][8];
int x, y;
printf("Give me a location: ");
scanf("%d %d", &x, &y);
while (x < 0 || x > 7 || y < 0 || y > 7) {
printf("Give me another location: ");
scanf("%d %d", &x, &y);
}
return 0;
}
Otherwise the program could try to access to a memory space that the program shouldn't touch and try to check if it is NULL.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "c, arrays, matrix, null, multidimensional array"
}
|
C/C++ Inline assembly [with C loops]
#include <stdio.h>
#define OPT //define for assembly
int main()
{
char chr;
for(chr = 'A' ; chr <= 'Z' ; chr++)
{
#ifdef OPT
__asm
{
lea eax,chr
push eax
mov eax, putchar
call eax
pop ebx
}
#endif
#ifndef OPT
putchar(chr);
#endif
}
return 0;
}
Upon usage of the assembly code, all that happens is a random trash-character is printed. Note this is in intel syntax.
Also: I'm learning inline assembly, how would you grab the return value of a called function (through mov eax,func then call eax or equiv?)
|
It doesn't work because **lea** instruction is intended to get the address of a variable. (+1 to zebarbox for this note.) We need the value of chr, not its address, so we use this instead:
movsx eax,chr
This pseudoinstruction will compile to something like this:
movsx eax,[ebp-4]
You can also write putchar(chr), put there a breakpoint, run the application and look into disassembly window to see how it is compiled.
Note that I use **movsx** because chr is char and I need here a dword. If chr was int, I would simply use **mov** instruction.
Also, you are not allowed to use **pop ebx** , because ebx must not be changed here. Use **pop eax** or **add esp,4** instead.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "c++, c, assembly"
}
|
Concatenating data in different columns into a single column (pandas, python)
I am looking for the logic to concatenate the values in many columns with related data from an .xlsx file into a single column using pandas in python. The logic to combine each different column would be different depending on what information the column contains. For example:
input:
ID,when_carpool,smoking,vehicle,passengers
0,weekdays,yes,truck,3
1,weekends,no,sedan,4
2,weekdays,no,van,6
3,weekdays,no,van,5
4,weekends,yes,sedan,3
I have thousands of these rows to process, note that I want to transform the value of the 'smoking' column so it's not a simple concatenation of all columns.
output:
ID,carpool_info
0,weekdays+smoking+truck+3
1,weekends+nonsmoking+sedan+4
2,weekdays+nonsmoking+van+6
3,weekdays+nonsmoking+van+5
4,weekends+smoking+sedan+3
|
Join all the columns into a new one:
df["carpool_info"] = df.apply(lambda x: "+".join([str(x[i]) for i in range(len(x))]),axis=1)
and then drop the other columns you don't need (see also here: Delete column from pandas DataFrame) , or just use the series carpool_Info = df["carpool_info"]
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "python, excel, pandas"
}
|
Alternative to <content> tag in HTML5?
I was reading today about Shadow DOM, where the author used this `<content>` tag to pull in `textContent` from the host.
**Tutorial** : <
When I looked it up, I found that the `<content>` tag has been deprecated and should be avoided. What should I do now? Should I learn to use `<content>` tag or not? **Source** : Mozilla Documentation
|
The same documentation (Mozilla FireFox)) states:
> It has now been replaced by the `<slot>` element.
Use the `<slot>` element. When something is deprecated, you should no longer use it. (Mozilla) also states this.) Deprecated means it is no longer approved of/disapproved.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "html"
}
|
How to RegEx match ()'s at the end of a word
I need a regex `@""` to match two brackets `()` at the end of a word.
Tried doing `\w*()\b` but didn't work.
So I need to match something like this: `"Hello, world test(test) testing"`.
I just need it to match the `test(word)` there.
|
If there is a space after the last parenthesis, using a word boundary will not get a match as there is no word boundary between `)` and a space.
Note that using `\w*` will optionally repeat word characters and could possibly also match just `()`
You might use:
\w+\((?:\w+(?:\s*,\s*\w+)*)?\)
* `\w+` Match 1+ word characters
* `\(` Match `(`
* `(?:` Non capture group
* `\w+` Match 1+ word characters
* `(?:\s*,\s*\w+)*` Optionally repeat matching `,` and 1+ word characters
* `)?` Close the group and make it optional
* `\)` Match `)`
Regex demo
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "c#, regex"
}
|
Order in the Windows Explorer context menu
How can I change the order of the entries in the context menu?(e.g. for Directories) I need to know how Windows determines the order when showing that so I can control it. For example I want to place my custom action at the end of the context menu list
Thank in advance!
|
My Google-fu led me to this:
> So the sorting is based on the following elements in decision order:
>
> 1. Key priority (eg, txtfile, *, AFSO)
> 2. Registry Enumeration order of shellex\contextmenuhandlers with a special case for static verbs always being first
> 3. IContextMenu Implementation order
>
>
> So if there is any contention for position, there is no consistent way for an extension to guarantee their relative position within the menu.
Obviously you can't do anything about phase 1. Phase 3 only applies to the verbs implemented in your handler. That leaves phase 2. The only thing you can do is name your entry under ContextMenuHandlers such that it would be enumerated first, but nothing's stopping someone else from doing the same thing.
|
stackexchange-stackoverflow
|
{
"answer_score": 11,
"question_score": 13,
"tags": "windows, contextmenu"
}
|
Computed column '...' in table '...' cannot be persisted because the column is non-deterministic?
I have the following function.
create FUNCTION [dbo].Valid)
RETURNs bit
as
begin
DECLARE @sum int = 0;
return 0
end
And the following SQL
create table test(A char(10))
alter table test add C as dbo.Valid(A) persisted;
has the error of
> Msg 4936, Level 16, State 1, Line 50
>
> Computed column 'C' in table 'test' cannot be persisted because the column is non-deterministic.
|
Functions must be decorated with the `WITH SCHEMABINDING` hint, otherwise SQL Server skips the validation of determinism (a performance optimization), and treats that default result as not being deterministic.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 2,
"tags": "sql server"
}
|
Command Prompt cannot find or run my Java File
New programmer here, in terms of actually using an editor and running it. I have created a simple program that states this.
public class HelloWorld {
public static void main(String[] args) {
// Prints "Hello, World" to the terminal window.
System.out.println("Hello, World");
}
}
I have already set the path to **"C:\Program Files\Java\jdk1.8.0_151\bin\"**.(current version"`1.8.0_151`"). In the cmd input, "java" and "javac" work until I attempt to find a file name either "HelloWorld.java" or "HelloWorld". How do I get cmd to find and run my java file? Thank you!
|
One way to try it:
Open `C:\Temp` (or create if not exists)
Create new file called `HelloWorld.java`
Open `cmd`
Type `cd /d C:\Temp`
Type `javac HelloWorld.java`
Type `java HelloWorld`
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "java, cmd, javac"
}
|
Undefined index error on options array element?
WP_DEBUG is telling me:
> Notice: Undefined index: no_cat_base in myplugin.php on line 20
Here's the lines of code where I'm pulling the value of "no_cat_base" from my options array called "myoptions"...
$myoptions = get_option('my_settings');
if($myoptions['no_cat_base']){//This is line 20}
Is the correct fix for this...
if ( isset($myoptions['no_cat_base'])){//do something}
|
just to be on the safe side use:
if (array_key_exists('no_cat_base', $myoptions) && isset($myoptions['no_cat_base'])){
//do your thing
}
|
stackexchange-wordpress
|
{
"answer_score": 1,
"question_score": 0,
"tags": "errors, wp debug"
}
|
Pass loadBalancerSourceRanges parameter with istioctl
I want to deploy Istio's demo application and pass a source range to the load balancer with the following command:
istioctl manifest apply --set profile=demo --set values.gateways.istio-ingressgateway.loadBalancerSourceRanges={"x.x.x.x/x"}
Unfortunately, I get the following error:
Error: failed to apply manifests: validation errors (use --force to override):
json: cannot unmarshal string into Go value of type []json.RawMessage
How can I pass the parameter in the correct format (ZSH as shell)?
|
You can specify the index of the array directly and in ZSH you have to escape the square brackets.
The working command now looks like this:
istioctl manifest apply --set profile=demo --set values.gateways.istio-ingressgateway.loadBalancerSourceRanges\[0\]=x.x.x.x/x
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "kubernetes, kubernetes helm, amazon elb, istio"
}
|
Sum of powers of nth root of 1
We have $\epsilon \neq 1$ where $\epsilon$ is a solution to $x^n=1$ and we try to evaluate $1 + \epsilon + \epsilon^2 + \epsilon^3 + \dots + \epsilon^{n-1}$. Multiplying this by $\epsilon - 1$, we get $\epsilon^n - 1$ and write the value of the initial expression as $f(\epsilon)={\epsilon^n - 1 \over \epsilon - 1}$. This is equivalent to $${\left(\cos{2 \pi k \over n} + i \sin{2 \pi k \over n}\right)^n - 1 \over \epsilon - 1} = {1 - 1 \over \epsilon - 1} = 0$$
Is there a quicker way to arrive at this conclusion?
|
Yes. In particular, there's no reason to go through the calculation $\left(\cos{2 \pi k \over n} + i \sin{2 \pi k \over n}\right)^n = 1$. From the problem statement, we _already_ know that $\epsilon^n = 1$.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "complex numbers"
}
|
Closing bootstrap modal using ESC
I am using 2 modals, 1st one contains a form and 2nd shows up when an error occurs in the form. 2nd modal contains only text with error message.
My problem is that when 2nd modal show up and I press `Esc`, the first one (with the form) will close instead on the 2nd one.
Is there any way how to focus the 2nd modal when it shows up?
!enter image description here
This is how it looks like, now if I pressed `Esc`, the 1st one would close, but I want to close the 2nd one first.
**UPDATE**
Once I click somewhere on the 2nd modal, it works perfectly. I just need to select/focus it automatically
|
It looks like this is an issue with how the keyup event is being bound.
You can add the "tabindex"attribute to your modal to get around this issue:
tabindex="-1"
So your full code should look like this:
<a href="#my-modal" data-keyboard="true" data-toggle="modal">Open Modal</a>
<div class='modal fade hide' id='my-modal' tabindex='-1'>
<div class='modal-body'>
<div>Test</div>
</div>
For more info you can view the discussion on this issue on github: <
|
stackexchange-stackoverflow
|
{
"answer_score": 45,
"question_score": 14,
"tags": "javascript, jquery, twitter bootstrap"
}
|
Using jQuery $.proxy with $.filter passing "this" as reference
How do I have access to both `this`, one referring to the parent object and the other referring to the $('.report') DOM object being screened in the jQuery filter function?
In the following case, the DOM object `this` is overwritten by the `$.proxy` and `this` now refers to the var `parentObj`. What is the best way to handle a situation like this?
var parentObj =
{
getId: , //some function that returns the id by value
render: function(){
$('.report').filter($.proxy(function(index) {
return $(this).data('id') == this.getId($(this).data('value'))
}, this));
}
}
|
Since you have used `$.proxy()` to pass a custom execution context to the callback, `this` inside the callback does not refer to the current element - it refers to the `parentObj` object.
So to refer to the current `report` element use the second argument to the callback function which is the current element being filtered
var parentObj = {
getId: , //some function that returns the id by value
render: function () {
$('.report').filter($.proxy(function (index, el) {
//use el here to refer tot the current element
return $(el).data('id') == this.getId($(el).data('value'))
}, this));
}
}
Demo: Fiddle
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "javascript, jquery"
}
|
Running rbtimer from emperor
I have a web application managed by an emperor and two distinct vassals. Because they both write to different data sources, I need a file to synchronise both and so I've decided to add a timer job to my emperor.ini:
[uwsgi]
strict = True
die-on-term = True
memory-report = True
uid = www-data
gid = www-data
emperor = xxx.ini
logdate = True
import = synchronize
And this is `synchronize.py`:
from uwsgidecorators import rbtimer, lock
INTERVAL = 10
@lock
@rbtimer(INTERVAL)
def synchronize():
""" Synchronizes data between Redis and PostgreSQL. """
print 'AAA'
I run my emperor thus: `uwsgi --ini emperor.ini` but nothing happens, the console never prints 'AAA'.
What else am I missing?
|
You need a process (a worker or a mule) to run the signal handler. Spawn a worker (adding a socket directive) or a mule (adding mule = true). In the case of a mule you need to add target=mule to the @rbtimer decorator)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "python, uwsgi"
}
|
Grid not showing and blank in cycles
I opened my blender file and I saw the grid and when I went into the rendered mode in cycles everything was blank and there are lights in the scene and the sample progress doesn't change even though it is unpaused. I have turned on the grid in the overlay tab but it didn't work. Can anyone help?
`, the file loads without a problem.
However, when I try to load it from local, using:
simplexml_load_file(Storage::get('public/XML/myfile.xml'))
I get the error:
> simplexml_load_file(): I/O warning : failed to load external entity
The file exists, as the `Storage::exists()` method returns `true` and if I write in the Artisan tinker console, `Storage::get('public/XML/myfile.xml')`, the file will be returned.
I am saving my file using:
Storage::put('public/XML/myfile.xml', file_get_contents($URL));
|
`simplexml_load_file()` interprets an XML file (either a file on your disk or a URL) into an object.
But in your case you want interpret the content of the file => string of XML into an object for that you can use simplexml_load_string
simplexml_load_string(Storage::get('public/XML/myfile.xml'));
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "xml, laravel, storage"
}
|
Android - Logcat doesn't show log activity
I have my app, and I have a `BroadcastReceiver` that starts a `Service`.
The logs in the receiver are displayed ok but all the logs in the service `onCreate()`, `onStartCommand` and other methods are ignored.
I know they are being executed because breakpoints work Ok, but I can't make logcat to print anything there.
Why can this be happening?
|
Ok this was dumb, but may occur to someone so I answer my own question:
The text filter was ON so only some of my texts were showing up.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "android, debugging, service, logcat"
}
|
How to blame previous versions of a specific line of code in VS 2015?
I'm using Visual Studio 2015 with Git integration. What I'm trying to achieve is going back in the history of a specific line of code.
I know there is Source Control > Annotate. But then I get only to see the latest change. Then, I can right-click the line on the annotations gutter and say "Annotate This Version" which will give me the latest change for that specific line. But from there, how to get back in history for that line? "Annotate This Version" is greyed out...
|
The "Annotate This Version" found in the context-menu of the left gutter works just as expected. In my case, the history didn't follow a file rename which was confusing me.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 9,
"tags": "visual studio, visual studio 2015, blame, git blame"
}
|
npm: How to reset the node_modules prefix
i installed node via homebrew. Since i had problems accessing the packages, i tried to change the node_modules prefix to `user/local` but made an error while typing the command:
npm config set prefix /usr/l # See the typo there
^
Now, whenever i run an npm command i get the following error:
$ npm config ls -l
Error: EACCES: permission denied, mkdir '/usr/l'
at Error (native)
i cannot set the prefix again (`npm config set prefix /usr/local`) , or even list the config ( `npm config ls -l` ) – all produce the same error as above. I tried re-installing node/npm.
How do i reset the prefix? Thanks.
|
If it is a permissions error, you should be able to use sudo to run it as root. This should take care of permission problems, which it appears to be in the error message
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "node.js, macos, configuration, npm, npm install"
}
|
WP7 WebBrowser in MVVM
I am using a WebBrowser control in a MVVM WP7 application. I used an attached property to allow binding the control to a generated HTML string, as explained in < . The attached property is bound to my VM which generates HTML code. Problem is that the code is generated before the control has fully loaded, so that I get an exception when the VM property changes:
> You cannot call WebBrowser methods until it is in the visual tree.
I could use some "hack" like avoiding the binding at all, and rather firing an event from my VM and letting the view handle it and pospone the call to WebBrowser.NavigateToString until it's loaded, but I was wondering if anyone could suggest a better, more elegant way...
|
I think the best thing to do is fix the attached property so that it works properly. Here's a suggestion:
private static void OnHtmlChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var browser = d as WebBrowser;
if(browser == null)
return;
var html = e.NewValue.ToString();
try
{
browser.NavigateToString(html);
}
catch (Exception ex)
{
browser.Loaded += (s,e3) =>
{
browser.NavigateToString(html);
}
}
}
The code above tries to display the HTML, if an exception is thrown, the Loaded event is handled (which occurs when a control has been rendered within the visual tree), then the HTML is supplied.
There might be a better methods than try / catch, it is worth checking the API for the `WebControl`. However, the above should work.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 2,
"tags": "windows phone 7"
}
|
Redundancy in C#?
Take the following snippet:
List<int> distances = new List<int>();
Was the redundancy intended by the language designers? If so, why?
|
The reason the code appears to be redundant is because, to a novice programmer, it appears to be defining the same thing twice. But this is not what the code is doing. It is defining two separate things that just happen to be of the same type. It is defining the following:
1. A variable named distances of type `List<int>`.
2. An object on the heap of type `List<int>`.
Consider the following:
Person[] coworkers = new Employee[20];
Here the non-redundancy is clearer, because the variable and the allocated object are of two different types (a situation that is legal if the object’s type derives from or implements the variable’s type).
|
stackexchange-stackoverflow
|
{
"answer_score": 74,
"question_score": 12,
"tags": "c#, .net, generics, programming languages"
}
|
Having problems with mapping forEach and Reduce onto a Map Object
This same approach works with objects when used with object values. But how do I make it work on map objects?
const one = new Map ();
one.set ('part1', {section1: 1, section2: 'one'});
one.set ('part2', {section1: 8, section2: 'eight'});
one.set ('part3', {section1: 5, section2: 'five'});
one.forEach(x => console.log(x.section1));
let temp1 = one.forEach(x => x.section1);
console.log(temp1);
let temp2 = one.forEach(x => x.section1).reduce((sum, cur) => sum + cur);
console.log(temp2);
|
The function `forEach` returns undefined, so you can't call the function reduce.
Additionally, you don't need to call the function `Array.prototype.map`, with a reduce is just fine.
const one = new Map ();
one.set ('part1', {section1: 1, section2: 'one'});
one.set ('part2', {section1: 8, section2: 'eight'});
one.set ('part3', {section1: 5, section2: 'five'});
let temp2 = Array.from(one.values()).reduce((sum, {section1: cur}) => sum + cur, 0);
console.log(temp2);
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, loops, foreach"
}
|
Calendar in Zend Framework
I looking to create a custom calender with Zend Framework, I am hoping that it will be able to list all the days of the month for the coming years and then have a different bg color on the date if there is an event on this. I am however struggling to create this firstly because it needs to go into the layout view, rather than an action, so where does the logic go? I am also unclear as to how the logic with mkdate() would work.
Can someone point me in the right direct please?
Thanks
|
Here is a simple Calendar class that uses Zend_Date and Zend_Locale that you can use as a starting point:
www.arietis-software.com/index.php/2009/05/26/a-php-calendar-class-based-on-zend_date/
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "php, mysql, zend framework"
}
|
Speed of Tampura app during Bansuri practice
I understand Tampura app (I use Tampura droid) must be on during Bansuri practice so player learns to tell (by ear) whether they are in tune.
Since I have A-Scale Bansuri the Tampura is on A-Scale and note PA (from Sa RecGa Ma PA DHA NI SA)
But what 'speed' to keep it. By default the slider is in the middle. When do I speed up the Tampura? When do I slow down the Tampura?
|
It is up to you to use which speed to use. I prefer it a bit slow (slider at about 1/4th position) so that I can hear all the four notes separately. Also before start practicing just keep listening to the tanpur will help you get adjust to it
|
stackexchange-music
|
{
"answer_score": 2,
"question_score": 1,
"tags": "flute, woodwinds, indian classical, bansuri"
}
|
Puppet exec unless doesn't appear to work how I expect
I'm trying to clone a db with exec from mysql, but I don't want to clone it if it has already been cloned.
exec { "clone_from_${name}" :
unless => "/usr/bin/mysql -u${user_to} -p${pwd_to} ${name_to} -e'select count(*) from $test_table_name;' | grep -c ' 0 '",
...
The logic looks a little confusing but basically, the way I understand unless is that if the command returns a 0, then the whole exec wont be run. But it when I try it, it is.
The db has already been created in the vm, and if it's already been cloned, the count returned from the query gives me something other than a ' 0 ', and the grep because it doesn't find the ' 0 ' returns a 0. Unless should make it run then, right?
The output even gives me "Unless: 0" and then "Executing
Thanks.
|
It's the exitcode that is important, not the number that is printed.
If you run this command manually and do an `echo $?` afterwards, you get the exitcode.
Also, you want to surpress the output from the command:
exec { "clone_from_${name}" :
unless => "/usr/bin/mysql -u${user_to} -p${pwd_to} ${name_to} -e'select count(*) from $test_table_name;' | grep ' 0 ' > /dev/null 2>&1",
...
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "puppet"
}
|
Java Swing closing a window with setDefaultCloseOperation Vs. addWindowListener
In a java swing application what is the difference between the following operations? When would I prefer to use one over the other?
I have seen both of these in different examples strewn across the internet:
// Have the window exit on close
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
**\- OR -**
// Set up a window listener to exit on close
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent) {
System.exit(0);
}
});
The second approach seems to be a lot more code so I'm wondering why I see it so widely used. Is there any advantage to this approach over the first one?
|
I would use the first option if you only want a standard close. Like @Berger said, you can add additional functionality if you choose the second method.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "java, swing, user interface, jframe, window"
}
|
Pure exceptions in Haskell
How can exceptions be used in Haskell without going through `IO`?
I have the following code for inserting an element in a binary search tree with minimum comparisons and no copying when the element is a member of the tree. I noticed that `either` is used as `catch` and `Left` as `throw`:
insert x t = either (const t) id (insert' x t Nothing)
where
insert' x E m = maybe (Right (T E x E)) (\v -> if x==v then Left E else Right (T E x E)) m
insert' x t@(T l v r) m = if x<v
then fmap (\l' -> T l' v r) (insert' x l Nothing)
else fmap (\r' -> T l v r') (insert' x r (Just v))
So I tried to rewrite it using `Control.Monad.Error` hoping to make the code simpler, but I got a big mess. Any suggestions?
|
The monadLib package on Hackage has an Exception monad (and an ExceptionT monad transformer) which you can use without IO. When you run it, you get an Either type as a result.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 6,
"tags": "exception, haskell, monads"
}
|
cover letter template which is stylistically similar to moderncv
the Moderncv resumee template is very well color coordinated. It isn't just plain black in comparison with the cover letter. Unfortunately, all cover letters I've found are just plain black , which doesn't fit with the moderncv resumee. (because the moderncv template is colorful)
Basically, **I'm searching for an equal color-coordinated cover letter template like moderncv**. All questions on tex.stackexchange.com are using the plain business format I described above. Of course, i could extend the existing plain black color letters by adding some colors. But I want to know if such a template already exists.
**EDIT** For clarification: I saw the cover letter included in the moderncv package - but it looks still very business like and in my opinion provides a heavy contrast to the moderncv resumee itself.
|
More colour, more joy.
 {
for ( var i = 0; i < 10; i++)
FB.api(apiPath,function(response) {
secondFunction(response,i);
});
}
function secondFunction(response,num) {
alert(num);
}
I wanted the secondFunction to be called asynchronously 10 times, each time receiving a different number in num. Instead, secondFunction is called 10 times and in all of them num is 10.
Can someone explain to me why it is not passed like i expect and how i can fix it to act like i expect ?
Thanks
|
Your synchronous `for` loop increments `i` all the way to 10 before the first `FB.api` async callback executes.
Like this:
function firstFunction() {
for ( var i = 0; i < 10; i++) {
(function(i2) {
FB.api(apiPath,function(response) {
secondFunction(response, i2);
});
})(i);
}
}
The fix puts the async function call into its own function so that `i` can be passed in as a parameter, capturing the value of `i` at the time of the call, rather than when the async callback occurs.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "javascript, facebook, asynchronous, anonymous function"
}
|
how to make array like this
I have an array in the array, and I want to make it just one array, and I can easily retrieve that data i have some like this
but the coding only combines the last value in the first array, not all values
is it possible to make it like that? so that I can take arrays easily
|
I would make use of the unpacking operator `...`, combined with `array_merge`:
$array['test2'] = array_merge(...array_merge(...$array['test2']));
In your case you need to flatten exactly twice, if you try to do it one time too much it will fail due to the items being actual arrays themselves (from PHP's perspective).
**Demo:<
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "php, arrays, json"
}
|
shell command to truncate/cut a part of string
I have a file with the below contents. I got the command to print version number out of it. But I need to truncate the last part in the version file
file.spec:
Version: 3.12.0.2
Command used:
VERSION=($(grep -r "Version:" /path/file.spec | awk '{print ($2)}'))
echo $VERSION
Current output : 3.12.0.2
**Desired output : 3.12.0**
|
Try this:
VERSION=($(grep -r "Version:" /path/file.spec| awk '{print ($2)}' | cut -d. -f1-3))
Cut split string with field delimiter (-d) , then you select desired field with -f param.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "shell, awk, grep, cut"
}
|
SQL INSERT with SELECT inside, maybe inner joins
I have this INSERT:
INSERT INTO gamecodes (gamecode, accountname, premium_points, alreadyused)
VALUES ('$gamecode','$accountorname',$premiumpoints,'N')
I need a help. In variable **$accountorname** I got a PLAYER name, i need to get his account.
Two tables:
TABLE PLAYERS
id, name, account_id..
id, player name, table accounts.id
TABLE ACCOUNTS
id, name ..
id = table players account_id
|
You could try something along the lines of:
INSERT INTO gamecodes (gamecode, accountname, premium_points, alreadyused)
SELECT '$gamecode',accounts.name,$premiumpoints,'N'
FROM accounts
JOIN players
ON accounts.id = players.account_id
WHERE players.name = '$accountorname'
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -5,
"tags": "php, mysql, sql"
}
|
Python 3 sorting "TypeError: 'NoneType' object is not iterable"
When sorting in Python 3, I get:
TypeError: 'NoneType' object is not iterable
Here is my code:
for f in self.db[key].sort():
yield f
I have confirmed none of the items in my list are None.
|
The reason for this is simple, Python3 provides two methods and you're using the wrong one,
* `sorted(foo)` returns a copy sorted, uses core `sorted()`.
* `.sort()` sorts the stuff in place, returns None
You need to call `sorted(foo)` instead. For more information see the docs on Sorting HOW TO
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": -1,
"tags": "python, python 3.x"
}
|
Android - Read preference from service which is running in separate process
I am writing some value to default shared preference using `PreferenceManager.getDefaultSharedPreferences(Context context)` from the Activity(Default process).
I have one more `Foreground Service` which is running in **Separate process** using `android:process=":processName"`.
Now the issue is when I try to read the preference value from `Foreground Service` it is not able to read the value which was written from the `Activity`.
But when I remove the `android:process=":processName"` attribute from the `Foreground Service` registration element in Android Manifest it starts working, service is able to read the value from preference which was written from the `Activity`.
|
Quoting the documentation for `SharedPreferences`:
> Note: This class does not support use across multiple processes.
Create some sort of API between the two processes and communicate that way.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "android, android service, foreground service"
}
|
Is a bad practice mixing function code with preprocessor directive?
In my C++ project I need to use a "TEST mode".
Normally there are processes that need to be spawned by other processes. Because it's a bit tricky to debug an application started by another application, I need this test mode that basically allocate a console, simulate the presence of other processes creating random data and so don't need to use the IPC facilities.
I started to use preprocessor directive in the code, like:
int APIENTRY _tWinMain(...) {
#ifdef TEST_MODE_ON
AllocConsole();
...
#endif
...
#ifdef TEST_MODE_ON
FreeConsole();
...
#endif
}
but I think this is not the best way from the code readability point of view. Is this a bad practice? (why?) Are there any other better ways? Thanks!
|
It is not necessary a bad practice, just makes the code more unreadable. I would go with something like a method caller macro which depending on `TEST_MODE_ON` evaluates to something else:
#include <stdio.h>
#ifdef TEST_MODE_ON
#define DEBUG_CALL(x) x;
#else
#define DEBUG_CALL(x)
#endif
int main(int argc, char** argv)
{
DEBUG_CALL(printf("Hello"));
}
(Yes, I know it's ugly and unsafe, but nevertheless works)
and of course your compilation takes care of defining `TEST_MODE_ON`.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 3,
"tags": "c++, windows"
}
|
simple but useful powershell script not working
this script prompts to .txt all dll used by an exe to all exe running
Get-Process |
ForEach-Object {
$procName = $_.Name
tasklist /m /fi "imagename eq $procName.exe" > $procName.txt
}
I run it in powershell but its "loading" and not giving me the output, but I cant find the problem.
|
Try the code below (note that I used an already created c:\tests folder):
Get-Process |
ForEach-Object {
$procName = $_.Name
tasklist /m /fi "imagename eq $procName.exe" > "c:\tests\$($procName).txt"
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "windows, powershell, debugging, scripting"
}
|
Вывод двух массивов
void ArrOutput(int a[], int n)
{
for (int i = 0; i < n; i++)
{
if (n < 8)
cout << a[i] << ends;
}
}
Есть исходный и отсортированный массивы. Сначала у меня выводятся оба массива, но если элементов в массиве меньше 8, то вывести их повторно, как это сделать?
|
Исправил, можно так:
// Функция вывод массива:
void ArrOutput(int a[], int n) {
for (int i = 0; i < n; i++) {
cout << a[i] << ends;
}
}
// Использование:
ArrOutput(arr, n); // Вывести исходный массив
if (n < 8) {
// Если условие выполнилось
ArrOutput(arr, n); // Вывести исходный массив
ArrOutput(sortedArr, n); // Вывести отсортированный массив
}
ArrOutput(sortedArr, n); // Вывести отсортированный массив
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "c++, c"
}
|
Prove that if $n$ is odd, then $C_n$ is antimagic.
Prove that if $n$ is odd, then $C_n$, the cyclic graph of $n$ vertices, is antimagic.
How would you construct and write the proof for this problem?
|
The construction is as follows... Building on Nathanson's comment, if we construct a sequence of integers from the sums of adjacent edge labels in a cyclic graph, we get the sequence consisting of every odd number in $[1, 2n-1]$ and one value whose parity is variable (the last value in the sequence). This last value is $n+1$. If $n$ is even, $n+1$ is in $\\{1, 3, 5, ..., 2n-1\\}$, otherwise, $n+1$ is even and can't be in this sequence.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "graph theory"
}
|
How to prove equivalence of two norms?
have linear span $E=Span(1,x,x^2,...,x^{2015})$ on the $C[0,1]$.
$$ \left \| f \right \|_{\infty} = \underset{x\in[0,1]}{\max} \left |\sum_{i= 0}^{2015} \alpha_{i} x^{i} \right | $$ $$ \left \| f \right \|_{1} = \left | \alpha_{0} \right | + ...+\left | \alpha_{2015} \right | $$
How to prove that these two norms are equivalent?
$\left \| f \right \|_{\infty} \leq \left \|f \right \|_{1} $
and
$\left \|f \right \|_{1} \leq A \left \| f \right \|_{\infty} $
First inequation is easy, but I cant prove second.
|
On the one hand, by triagle inequality $$ \|f\|_{\infty}=|\sum_i \alpha_ix^i| \le \sum_i|\alpha_ix^i| \le \sum_i |\alpha_i|=\|f\|_1. $$ On the other hand, supposing $f\neq 0$, we have $$ \frac{\|f\|_1}{\|f\|_{\infty}}=\frac{\sum_i |\alpha_i|}{\max_{x \in [0,1]} |\sum_i \alpha_ix^i|}=\frac{1}{\max_{x \in [0,1], \alpha \in S} |\sum_i \alpha_ix^i|}, $$ where $S$ is the set of vectors $(\alpha_0,\ldots,\alpha_{2015})$ for which $\sum_i|\alpha_i|=1$. The denominator is a continuous functions defined on a compact set. Conclude :)
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 3,
"tags": "functional analysis, polynomials, normed spaces"
}
|
Implode / Explode PHP array
I'm trying to manipulate an `$array:`
Array ([0] => General [1] => Custom Title)
Using Implode, I can get the `$array` into individual pieces seperated by a space:
<?php $pieces = implode(" ", $array); ?>
Output:
General Custom Title
However, if the array pieces are two words, it doesn't work as I would prefer the output to be:
General Custom-Title
Any ideas?
|
Replace spaces with hyphens, before you implode.
foreach ($arr as $idx => $val) {
$arr[$idx] = str_replace(" ", "-", $val);
}
$pieces = implode(" ", $arr);
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "php, arrays"
}
|
OpenStreetMap REST Call to find near POIs of specific type
Is there a simple way to get the pois of a type (for example restaurant) that are near me (specific location by latitude/longitude)? With curl -v -G < i can get them near me but not filtered to the restaurants. Can anyone help me? Thanks
|
I misunderstood the osm api. i discovered that what i want is possible with the <
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "java, curl"
}
|
python how to print space per n'th char
I have a big number in a variable, what I want is that every 5'th is separated ba a space
Code:
number = 123456789012345678901234567890
print "the number is:", number #Devide every 5'th
The output I want is:
The number is: 12345 67890 12345 67890 12345 67890
|
In [1]: number = 123456789012345678901234567890
In [2]: num = str(number)
In [3]: print ' '.join(num[i:i+5] for i in xrange(0,len(num),5))
12345 67890 12345 67890 12345 67890
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 2,
"tags": "python"
}
|
Пользовательские переменные mysql java
Подскажите, пожалуйста, как в запросе:
String query2 = "select message from messages_type WHERE str ='qwe'"
вместо `str = 'qwe'` использовать `str = var_qwe`, где `var_qwe` \- моя локальная переменная типа `String`, используемая в программе?
|
Попробуйте:
String var_qwe = "some text";
String query2 = "select message from messages_type WHERE str ='" + var_qwe + "'";
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "java, mysql"
}
|
Prove that $f(x) = 1$ for all $x ∈ [0, 1$] where $y = f(x$) satisfies the differential equation$ g(x)y'(x) + y(x) = 1$
Suppose that $g(0)=g(1)=0$ and that $f: \mathbb{R} \rightarrow \mathbb{R}$ is differentiable at every point and $$) satisfies the differential equation $g(x)y′(x)+y(x)=1$ for all $x∈[0,1]$ . **Prove that $f(x)=1$ for all $x ∈ [0,1].$**
Am not quite sure on how to approach the question and would appreciate some help.
So far I know that because $g(0) = g(1$) and $f$ is differentiable, then for some $c ∈ [0,1]$ there exists $f'(c) = 0$, (by Rolle's Theorem).
Not quite sure how to handle the differential equation with this (assuming that's even the right approach).
|
Putting $x=0$ and $x=1$ in the DE we get $f(0)=f(1)=1$. Suppose $f(x) >1$ for some $x$. There is a point $x_0$ where $f$ attains its maximum. Since $f'(x_0)=0$ the DE gives $f(x_0)=1$, a contradiction (since the maximum value exceeds $1$). Similarly, $f(x)<1$ for some $x$ gives a contradiction. Hence, $f(x)=1$ for all $x \in [0,1]$.
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 0,
"tags": "real analysis, calculus"
}
|
How to disable deployment from particular account in Terraform
Here is my configuration for allowing certain account ID for deployment.
provider "aws" {
#shared_credentials_file = "$HOME/.aws/credentials"
region = "${var.region}"
#profile = "customprofile"
allowed_account_ids=["164*******65"]
}
This is working fine, but I have configured multiple accounts, and I want to disallow some account IDs instead updating each time `allowed_acccount_ids` fields.
Thanks in Advance.
|
You could use `forbidden_account_ids` as a blacklist instead of whitelisting accounts via `allowed_account_ids`.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "terraform, terraform provider aws"
}
|
C++ Derived polymorphic class - does it contain an entire instance of Base, including a vptr?
Say we have
Class A
{
public:
int _i;
virtual int getI();
};
class B : public A
{
public:
int _j;
virtual int getI();
};
So assuming that the size of a class in memory is the sum of its members (i.e. ignoring padding or whatever might actually happen), what is the size of a B instance? Is it sizeof(A) + sizeof(int) + sizeof(vptr)? Or does a B instance not hold an A vptr in it's personal A instance, so that sizeof(b) would be sizeof(int) + sizeof(int) + sizeof(vptr)?
|
It's whatever the implementation needs to make the code work. All you can say is that it is at least `2 * sizeof(int)`, because objects of type `B` contain two `int`s (and possibly other things). In a typical implementation, `A` and `B` will share a vptr, and the total size will be just one pointer more than the two ints (modulo padding for alignment, but on most implementations, I don't think that there will be any). But that's just a typical implementation; you can't count on it.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "c++, class, virtual, sizeof, vptr"
}
|
S3 Replication - destination files deleted replication behaviour
With S3 replication, if a previously replicated file is deleted in the destination bucket, is the default behaviour that the file will be re-copied? I assume this is the case and if so, is there any way to change this behaviour so files are only ever replicated once?
|
> if a previously replicated file is deleted in the destination bucket, is the default behaviour that the file will be re-copied
**NO, it wont be recopied** because according to docs `"By default, replication only supports copying new Amazon S3 objects after it is enabled."`
So literally s3 sees it as an existing object which is already replicated to destination no matter whether it is deleted in destination or not, it won't replicate AGAIN!
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "amazon web services, amazon s3"
}
|
Powershell is there an easy way to covert an int 5 to a string five or 68 to sixty eight?
I'm trying to figure out if there is an easy way to convert numbers into words take 9 and convert it to nine.
|
There is an excellent library for .NET called Humanizer that can do exactly this. I haven't tried this yet, but it looks like there is a PowerShell wrapper for it. I suspect this will do exactly what you need.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "powershell"
}
|
Is the arguments list to a for loop evaluated once in bash?
When writing
for a in `ls`
do
...
done
Is the ls command run only once ?
|
Yes, it's evaluated only once.
But you should never iterate over `ls` output with `for`.
Also, `$(...)` is preferred over ``...``.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "bash"
}
|
In app purchase didReceiveResponse does not show my product
By some mysterious reasons I got myself a jailbroken iPhone 3GS from a vendor whom I am finding difficult to track. My task is to test out in app purchase functionality on it. Currently it has iOS 5.0.1 with cydia installed. No, it does not have Appsync.
I am installing my build through testflightapp API which works without issues with my app so far. However when I initiate in app purchase, I don't get anything in response.products so far.
I have added productIDs and all in itunes-connect already, checked twice that they are fine, since 48 hours.
I tried testing with iPhone simulator 5.1, but all I got was no values from storekit. I would love to hear if there is any workaround with simulator.
|
Worked around this finally - deleted my app from itunes connect, re-added it. It complained about name being already used. I changed the language of name. And it worked.
Maybe, my prior app setup was right, but I had something else messed up. In between, I rejected my app. That maybe one of the reason behind this issue.
Lesson? Don't developer reject your app.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "ios simulator, in app purchase, storekit, iphone 3gs"
}
|
Impact of removing Dragonborn from Khorvaire
I plan on running an `Eberron` campaign and may end up doing it in 4th ed, but am interested in preserving the story of 3.5 `Eberron`. IMO `Dragonborn` should not be common in `Khorvaire` and would be at best exclusively something out of `Argonnessen`. Would their be any major impact in the books if I removed the presence of `Dragonborn` altogether from `Khorvaire`, or will key characters in the new world be removed?
For extra credit: Would their be any other confusions if I tried to run `Eberron` in a 3.5 style story but give the players the 4th ed books?
|
**No.**
Although 4E's `Eberron` campaign setting makes an effort to include all the new races and classes from the new edition, the `Dragonborn` are not given a role of special prominence, or even much of a plot thread of their own.
Removing them would be easy.
|
stackexchange-rpg
|
{
"answer_score": 11,
"question_score": 9,
"tags": "dnd 4e, dnd 3.5e, eberron"
}
|
Is the latest stable release or the latest LTS release more suitable for a development machine?
I was wondering which version of Ubuntu is better for my laptop, the current LTS release or the latest stable (but not LTS) release.
Is it always recommended to go for the latest version for personal laptop?
Is it advised to wait for several months after the version was released before installing it, so that the version can be more stable? If yes, does the CD got right after the release become less useful?
I plan 50 GB for Ubuntu partitions, 20 GB for root and 26 GB for home and 4 GB for swap.
My main use is programming with several popular programming languages and database and typesetting and browsing internet, seldom gaming, and therefore I will install related applications and compile some libraries for use in programming.
|
# Use the latest stable release
As it is predominantly a development machine, I would go with the latest stable version, as it has more up to date libraries and programming tools. As a normal release, it is not supported for as long as the LTS. I don't see this as a problem because you will probably want to have the newer versions installed by the time the support expires.
LTS versions are more suitable for business users and home users who don't want to worry about upgrading every 6 months.
|
stackexchange-askubuntu
|
{
"answer_score": 4,
"question_score": 3,
"tags": "development, versions, lts"
}
|
Is there a possibility to manipulate the raw http-stream from within apache tomcat?
An application which consumes my webservice sends an invalid soap-request, my service can not handle this request.
The applications send an wrong tag (misspelled), but they cannot alter this behaviour.
So my question:
Is there a possibility with a filter or a listner to get the raw http stream, alter something and put it back into the chain.
Thank you, Alex
|
I assume you want to change incoming body of the HTTP request. There is no easy way to do this. I don't know of any Servlet API that would allow you to do this "officially".
"Unofficially" you can do some reflection magic on `org.apache.catalina.connector.Request`. If you look at this object, you will see that both methods which return the actual body (`getReader()` and `getInputStream()`) are building streams on top of input buffer, instance of `org.apache.catalina.connector.InputBuffer`. You would have to manipulate that buffer so it returns tainted data.
Needless to say, this is a very volatile and dangerous hack. There are no guarantees this will work on the next Tomcat version (even minor one) and would be virtually unmaintainable.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "tomcat, httprequest"
}
|
Iterate Hash Map
I have an hashmap declared as private HashMap testMessages = null;
I will be storing string values in both key and value part of the hashmap retrieved from oracle table.
I am not concerned about the hashmap keys. I want to retrieve the hashmap values alone and check whether string variable filename is prefixed with one of the hash map value and return true if it's same. I want to ensure that hash map values are not null and empty.
function (string filename) {..
loop thru hashmap values
check whether the variable file name is prefixed with one of the hashmap values if so return true otherwise return false }
hashmap example: key1,prod key2,test key3,dummy
filename example: test123_20012010.csv
should return true since the file name is prefixed with one of the hashmap values
How can i do it?
|
Here's a brute force approach to iterate over the hash map values and check whether filename begins with the value.
// generics version
private HashMap<String, String> testMessages = buildMap();
for (String v : testMessages.values()) {
if (filename.startsWith(v) {
// found a map value that starts the file name
}
}
// alternative non-generics version
private HashMap testMessages; // assigned somewhere
for (Object v : testMessages.values()) {
if (filename.startsWith((String) v) {
// found a map value that starts the file name
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "java, string, hashmap"
}
|
solr cache configuration for high performance queries
I have configured solr caches for my index in solrcloud 4.3.0.I have also configured autoCommit policy to 1h hard commit and opensearcher false. Though i am not reopening searcher,it seems that after every 1 hour my caches gets flushed and resets.As per my understanding only closing and opening the new searcher can cause caches to be flushed.But i don't understand why this is happening ?
|
Have you tried to change `mergePolicy` settings? You can read about merging segments here. I guess, your rare hard commits and the size of new segments requires Solr to merge segments, in this case the searcher should be reopened anyway.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 2,
"tags": "solr, solr4, solrcloud"
}
|
Aggregating Column Values In Kusto
How do I transform kusto data that looks like this:
let fauxData = datatable (OrgName:string, Status:string, EastUS:long, SouthCentralUS:long, WestUS2:long)
['Apple', 'Red', 50, 10, 90,
'Apple', 'Orange', 30, 30, 10,
'Apple', 'Yellow', 10, 0, 0,
'Apple', 'Green', 10, 60, 0,
'Ball', 'Red', 20, 20, 20,
'Ball', 'Orange', 30, 30, 30,
'Ball', 'Yellow', 0, 0, 0,
'Ball', 'Green', 50, 50, 50,
];
To look like this:
['Apple', 'ComboOfRedandOrange', 80, 40, 100,
'Apple', 'ComboOfGreenandYellow', 20, 60, 0,
'Ball', 'ComboOfRedandOrange', 50, 50, 50,
'Ball', 'ComboOfGreenandYellow', 50, 50, 50,
]
|
You can use next query to achieve your goal:
let fauxData = datatable (OrgName:string, Status:string, EastUS:long, SouthCentralUS:long, WestUS2:long)
['Apple', 'Red', 50, 10, 90,
'Apple', 'Orange', 30, 30, 10,
'Apple', 'Yellow', 10, 0, 0,
'Apple', 'Green', 10, 60, 0,
'Ball', 'Red', 20, 20, 20,
'Ball', 'Orange', 30, 30, 30,
'Ball', 'Yellow', 0, 0, 0,
'Ball', 'Green', 50, 50, 50,
];
fauxData
| extend combo = case(Status in ('Red', 'Orange'), 'ComboOfRedandOrange',
Status in ('Green', 'Yellow'), 'ComboOfGreenandYellow',
'Unknown')
| summarize sum(EastUS), sum(SouthCentralUS), sum(SouthCentralUS) by OrgName, combo
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "azure data explorer, kql"
}
|
Rails - EmailVeracity - setting the domain_check and timeout
I'm using EmailVeracity today as follows:
email = EmailVeracity::Address.new(params[:user][:email])
I would like to know how to disable the domain_check and/or lower the timeout. I tried:
email = EmailVeracity::Address.new(params[:user][:email], :domain_check => false, :timeout => 5, :message => "is not valid")
But get an ArgumentError, any ideas?
|
Ok, look here: <
So (this is untested), something like
EmailVeracity::Config[:skip_lookup] = true
should be what you're looking for.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "ruby on rails, ruby on rails 3"
}
|
Using Sieve of Erastothene to find primes 2 to 1000
I've been trying to find some help on how to use the Sieve of Erastothenes to print the primes from 2 to 1000 using an array. I looked up how the Sieve works but am having trouble figuring out how to code it.
import java.util.*;
public class PrimeArray {
public static boolean isPrime(int n){
if(n<=1){
return false;
}
for(int i = 2; i*i<n; i++){
if(i%n==0)
return false;
}
return true;
}
public static void main(String[] args) {
int[] array = new int[1000];
for(int j = 2; j<array.length; j++){
if(isPrime(j))
System.out.println(array[j]);
}
}
}
|
Your `isPrime()` function uses trial division, and has two bugs. One, test if `n % i == 0` not `i % n == 0` and two `(i * i) <= n` (not `(i * i) < n`). It works correctly if I use,
public static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; (i * i) <= n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
Java arrays aren't dynamic data structures. To use the above to get 2 to the last prime below 1000 into an array, you could do
public static void main(String[] args) {
int[] array = new int[168]; // the 168th prime is 997
int pos = 0;
for (int j = 2; pos < array.length; j++) {
if (isPrime(j)) {
array[pos++] = j;
}
}
System.out.println(Arrays.toString(array));
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "java, arrays, primes"
}
|
Mongodb, get registers from last registered day
I have a collection with many documents structured:
{
"_id" : "skkbbp8TgnT3a2XgT",
// ... other fields
"createdAt" : ISODate("2015-12-08T21:03:37.141Z")
}
How can I find all the documents from the last registered day? And from the last five registered days?
Is it possible to do with only one statement?
Edit: Not duplicated. My question is to get all data from the last **registered** day, not how to query with dates.
|
So you need to pull the last registered date, chop off the time portion, and then compose a `$gte` query using just the date. Using `momentjs` makes it pretty simple. Assuming your collection name is called "Foo":
var lastDate = Foo.findOne({}, {
sort: {
createdAt: -1
}
}).createdAt;
var startOf = moment(lastDate).startOf("day").toDate();
Foo.find({
createdAt: {
$gte: startOf
}
});
So you can do it in one line, but not recommended :)
Foo.find({
createdAt: {
$gte: moment(Foo.findOne({},{sort: {createdAt: -1}}).createdAt).startOf('day').toDate()
}
});
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "mongodb, meteor"
}
|
Explain this factorization: $\sqrt{1+e^x} - \sqrt{e^x}=\sqrt{e^x}(\sqrt{e^{-x}+1}-1)$
I found this factorization in one of my math books: $\sqrt{1+e^x} - \sqrt{e^x}=\sqrt{e^x}(\sqrt{e^{-x}+1}-1)$
I don't understand how that is possible. Can someone explain what rules are used for this factorization? Thanks.
|
Use:
$$\sqrt{1 + e^x} = \sqrt{\underbrace{(e^{-x} e^x}_{1}) (1 + e^x)} = \sqrt{e^x}\sqrt{e^{-x}+1}$$
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 2,
"tags": "factoring"
}
|
Can Employer Destroy Payroll Records of Current Employee?
The employer of one of my family members owes several thousand dollars in unpaid wages, which is documented in the employer's books. The family is considering legal action and they want to demand copies of the books as evidence (the employer never provided any formal pay stubs). The state (Pennsylvania) does have laws requiring employers to permit inspection and copying of payroll documents. However, there is significant concern that the employer (a rather sleazy independent contractor) may simply destroy or doctor the books to hide what is owed.
So, my question is two-fold: Are there any legal tools to allow an employee to obtain copies of his payroll documents without giving the employer an opportunity to destroy said documents, and what sort of repercussions would an employer face for destroying payroll documentation after a request for copies has been made?
|
> what sort of repercussions would an employer face for destroying payroll documentation
Serious ones. Record keeping is required by the Fair Labor Standards Act, independently of whether there is an ongoing dispute or not.
<
Or, for more details:
So, I would not worry about the employer destroying records.
Also, from <
> If an employer does not maintain the required records, the employee is entitled to recover based on good faith, reasonable and realistic estimates.
So, destroying records would not even do the employer much good, as the employee can recover based on estimation of the amount owed.
|
stackexchange-law
|
{
"answer_score": 2,
"question_score": 0,
"tags": "labor law"
}
|
$Watch is not working until a event is fired
I am using $watch for pagination of the data in my page.But It is not showing data till i click on any of the buttons
Here is the code.
.controller('AppCtrl', function ($scope, $modal, Faq) {
$scope.filteredFaqData = [];
$scope.currentPage = 1;
$scope.numPerPage = 5;
$scope.maxSize = 5;
$scope.faqData = [];
$scope.faqData = Faq.getFaqs();
$scope.$watch('currentPage + numPerPage', function () {
var begin = (($scope.currentPage - 1) * $scope.numPerPage)
, end = begin + $scope.numPerPage;
$scope.filteredFaqData = $scope.faqData.slice(begin, end);
});
})
I am getting the data in the **$scope.faqData** from the service.But the **$scope.filteredFaqData** is empty till I click on the paging tabs
|
Actually my function **Faq.getFaqs()** was executing asynchronously . when the page loads for the first time, there was no data to display. So i used $timeout to dilay the $watch and it is working finr now.
Here is the code
$scope.filteredFaqData = [];
$scope.currentPage = 1;
$scope.numPerPage = 5;
$scope.maxSize = 5;
$scope.faqData = [];
$scope.faqData = Faq.getFaqs();
$timeout(function lateDisplay(){
$scope.$watchGroup(['currentPage','numPerPage'], function (newValues, oldValues, scope) {
var begin = ((newValues[0] - 1) * newValues[1])
, end = begin + newValues[1];
$scope.filteredFaqData = $scope.faqData.slice(begin, end);
});
},100);
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, arrays, angularjs, json"
}
|
Pycharm - modules belong to specific projects and not to all projects
I had been working with a older version of pycharm for a long long time, and recently I downloaded a new version.
My problem is that for every projects I open, I need to download all the modules that I'm using, meaning modules belong to project and not to pycharm. In addition, For every project I open, it's open a folder of the project for the code and another folder for the modules meaning for every project I got 2 folders, which is very very disappointing...
Someone have solution? I want to link the modules to my python and not to my projects...
Thanks a lot
Omer
By the way - my english is not my native language, please forgive me for any mistakes...
+++ It's also install me pip ( cause every project needs it's own pip :P every time im open project )
|
This is probably because in your PyCharm, when you create a new project, the interpreter is set to "New Virtualenv environment". Deselect this while creating your project and use the "Existing interpreter" for your project when you create one.
 and 6 dependent variables (5 likert scale). As my data is categorical (likert scale) I thought of using logistic regression (i think ordinal), but I have to reduce my dependent variables for which I used principal component analysis (PCA) to reduce in two factors. But using PCA make my data type continuous as compared to original data that was categorical. My question is that
Could I now run simple regression on the 2 factors, means is it logically correct to change the data type (from categorical to continuous) and using regression instead of logistic regression? OR Do you have any other solution?
|
When you did ordinary (linear) PCA on your likert-scale variables you already treated those variables as scale, or continuous, variables (variables with evenly spaced measuring benchmarks). To put in other words, you haven't regarded them as ordinal so far.
To recognize their ordinal (i.e. potentially not evenly spaced) nature you might consider to perform categorical PCA (CATPCA) which quantifies measuring levels nonlinearly to achieve the "best" principal components.
And yes, principal components are continuous, so usual regression is apt to them.
|
stackexchange-stats
|
{
"answer_score": 2,
"question_score": 1,
"tags": "regression, logistic, pca, categorical data"
}
|
bash arithmetic expansion seems to be prone to injection attacks
Suppose you want your script to take variables from environment:
#!/usr/bin/env bash
set -eu
if (( ${A-} )); then
echo true
else
echo false
fi
Arithmetic expansion seems to be more reasonable here to handle `(empty)`, `0`, `1` cases, or else:
if [ "${A-}" ] && [ "${A-}" != 0 ]; then
But then,
$ A='1 - 1' ./1.sh
false
$ A='B = 1' ./1.sh
true
So now you can basically change variables, which you generally don't want to allow. What would you suggest? How to process boolean flags taken from environment variables?
|
If you're unsure if variable holds an int, you can validate its value:
#!/usr/bin/env bash
set -eu
vint() {
local v
for v; do
if echo "$v" | egrep '[^0-9]' &> /dev/null; then
printf '%s: %s: not an int\n' "$0" "$v" >&2
exit 1
fi
done
}
vint "${A-}"
if (( ${A-} )); then
echo true
else
echo false
fi
This is as far as I could take it.
|
stackexchange-unix
|
{
"answer_score": 1,
"question_score": 3,
"tags": "bash, arithmetic"
}
|
Filling missing dates in each group while querying data from PostgreSQL
I have data in my table of the following form:
| date | type | value |
+----------+------+-------+
|2020-01-01| A | 29|
|2020-02-01| A | 32|
|2020-04-01| A | 56|
|2020-05-01| A | 78|
|2020-01-01| B | 12|
|2020-02-01| B | 89|
|2020-03-01| B | 44|
|2020-05-01| B | 33|
Now while querying this data, I want the missing dates to be filled with null values.
In PostgreSQL, I can use `generate_series()` to create a series of dates and then left join with it. But that only works if I have just a series of dates and values. In this case, since I have two types, I don't really have any missing dates in the series as a whole, but I have missing dates in each group/partition.
Is it possible to use `generate_series()` with left join to fill rows with null in this case?
|
You may cross join with a table which contains all types, and then use the same left join approach you were already considering:
SELECT
date_trunc('day', cal)::date AS date,
t1.type,
t2.value
FROM generate_series
( '2020-01-01'::timestamp
, '2020-12-31'::timestamp
, '1 day'::interval) cal
CROSS JOIN (SELECT DISTINCT type FROM yourTable) t1
LEFT JOIN yourTable t2
ON t2.date = cal.date AND t2.type = t1.type
ORDER BY
t1.type,
cal.date;
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "sql, postgresql"
}
|
UEFI: Installed Ubuntu only to have Ubuntu freeze at the purple loading screen
I know this question has been asked but I have tried the solutions to multiple question and yet to have find a working solution.
This is the photo of the error message after startup
Im sorry that the photo is cropped but I had to in order to meet the 2mb upload limit. I am guessing theres something wrong with my graphics card? Im using a Nvidia gtx 960. The only way i can actually get onto ubuntu in this state is if i set a parameter to the end of the linux line `nouveau.modeset=0`
|
I'm glad that you found the `nouveau.modeset=0` workaround. because that makes this solution a little easier.
Boot with that flag set and log in. Open a terminal and run these commands:
sudo add-apt-repository ppa:graphics-drivers/ppa
sudo apt-get update
Now, search for and open the Additional Drivers app and select the `nvidia-graphics-drivers-361` option. That name will be in parentheses. Hit apply and enter your password to install the driver.
Once you have that driver, you can boot without `nouveau.modeset=0`.
|
stackexchange-askubuntu
|
{
"answer_score": 0,
"question_score": 0,
"tags": "boot, drivers, nvidia, uefi"
}
|
Why Object.create doesn't clone properties as expected?
If I type this into console:
var x = {a: 1};
var y = Object.create(x);
console.log(y);
It shows `{}`. But if I run it in fiddle it shows `{a: 1}`, which is the expected result. Also here:
var x = {a: 1};
var y = Object.create(x);
console.log(y);
So what is going on?
|
Runs as expected even in console. You just have to extend the Object.
_
bzw.
> Zahnmedizinischer Verwaltungsangestellter _(männlich)_
bezeichnet.
Einfachere Bezeichnungen sind u. a. _Sekretär(in) in einer Zahnarztpraxis_. _Zahnarzthelfer(innen)_ wäre auch möglich; der Begriff beinhaltet dann aber evtl. auch einfache zahnmedizinische Tätigkeiten.
|
stackexchange-german
|
{
"answer_score": 5,
"question_score": 2,
"tags": "translation, english to german"
}
|
matlab: expand vector using colon notation
I would like to expand an existing vector into a matrix using colon notation, or some other efficient way.
For example, using colon notation to create a matrix, I can do
< [0:4;5:9]
which will give me
< [
0 1 2 3 4
5 6 7 8 9]
I want to be able to do the same thing but with a provided original vector and range. For example, if my original vector is [1;3] and my range is 1 around the existing values, I wish to obtain the following output:
< [
0 1 2
2 3 4]
I know I can do this using a loop but I was wondering if there's a way I can do without the loop.
|
I think this does what you want; change `vec` and `range` appropriately:
vec = [1; 3]
range = 1
repmat(vec, 1, range * 2 + 1) + repmat([-range:range], size(vec))
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "matlab, matrix, vector"
}
|
SQLite3 browser for mac
Please i want program for mac to make sqlite3 database with db3 extension. I test sqlite manager from firefox add-on but the extension is sqlite. Please give me name or link to download it.
|
I use **SQLite Database Browser.**
It's not perfect but it's free, open-source and works for most usage scenarios. Usability could be better though.
I have never had a problem with using whatever extension I want for the DB file. `.sqlite3`, `.db`, `.db3`, they should all work without a problem.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -2,
"tags": "ios, macos"
}
|
Should you ever repeat the subject "我“ in a sentence?
So, I struggle with a common construction in Chinese where I don't know whether I should use the subject twice or not. For example, in the sentence "After I finished talking with her I went to mcdonalds" uses the word "I" twice in english. However, I'm not sure if this is necessary/common in Chinese.
For that sentence, as an example, I could say
(
Is that
1. Necessary?
2. Unnecessary but acceptable
3. Just kind of awkward
Thanks for all of your help! I know that there are a lot of situations when this happen.
|
1. Unnecessary.
2. In spoken language it is acceptable and actually quite common. In written language it should be avoided.
3. Depends on the context. In your example it doesn't sound awkward at all.
Side note: As pointed out by this article, in Chinese, using the same word again and again is not as awkward as bad repetition in English and sometimes it's the only way to satisfy grammatical requirements. Not directly related but similarly, unnecessary repetitions in general have more appearances in spoken Chinese than in English and sound less awkward. You should not feel bad about it.
|
stackexchange-chinese
|
{
"answer_score": 7,
"question_score": 2,
"tags": "grammar"
}
|
Is this transformation onto and/or one-to-one?
How can I prove that the transformation $$ T: R^3 \to R^2 : \ T(a_1, a_2, a_3) = (a_1-a_2, 2a_3)$$ is one-to-one and/or onto?
|
For one-to-one you need to show that if two points in $\mathbb R^3$ are mapped to the same point, they are the same. So let $x=(x_1,x_2,x_3)$ and similarly for $y$. Then assume $T(x)=T(y)$, insert the definition of $T$ and see if you can prove that $x_1=y_1$ and so on.
For onto, you need to show that all points in $\mathbb R^2$ can be reached. So let $x=(x_1,x_2)$ and see if you can find a $y$ such that $T(y)=x$. You should be able to find many of them. If you do this part first, it answers the other as well.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "linear algebra"
}
|
How can I get the standard colors used in pandas dataframe or series plot?
Pandas plot with multiple graphs has this standard colors (the first four colors are shown here):
['color']
['#1f77b4',
'#ff7f0e',
'#2ca02c',
'#d62728',
'#9467bd',
'#8c564b',
'#e377c2',
'#7f7f7f',
'#bcbd22',
'#17becf']
See this page of the `matplotlib` docs or this SO question for more info.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 2,
"tags": "python, pandas, colors"
}
|
Breath of Life and hp based Death Effects
The spell Breath of Life says quite explicitly:
> Creatures slain by death effects cannot be saved by breath of life.
But I have some issue regarding what "slain by death effects" means. Let's say a character is on the wrong end of a Wail of the Banshee. It doesn't kill instantly, but has a death descriptor and so is supposedly considered a death effect.
The character fails his save and is reduced to -5 hp. Is he considered "slain"? Would a Breath of Life work?
|
If the the death affect failed to kill the character, breath of life can still be used to heal them because they were not 'slain'.
'Slain' is never defined anywhere, so the normal definition of 'killed' applies. The rules text backs this up:
> Unlike other spells that heal damage, **breath of life can bring recently slain creatures back to life**.
Breath of Life only fails when the creature has died as a result of the death affect.
In the particular case, the wounded character could take more damage that would result in its death and have a Breath of Life spell bring them back to life.
|
stackexchange-rpg
|
{
"answer_score": 8,
"question_score": 3,
"tags": "pathfinder 1e, spells, character death"
}
|
Is $f $ constant ? True/false
Is the following statement true/false ?
let $f$ be an analytic function in $\mathbb{C}$.Then $f$ is constant if the zero set of $f$ contains the sequence
$$a_n=\begin{cases}n & 4\not\mid n\\\1/n & 4\mid n.\end{cases}$$
**My attempt** : I think this statement is false . Here the sequence of zeroes is $1,2,3,\frac{1}{4},5,6,7,\frac{1}{8}.........\infty$.
Also,both $0$ and $\infty $ are limit points of the set of zeroes
I think in this case we can not used idenitity theorem because identity theorem hold if and only if the limit point of zeroes is $0$ only
But here $\infty $ is also the limit points of the set of zeroes
Therefore this statement is false
|
You have $f\left(\frac1{4n}\right)=0$ for each $n\in\Bbb N$ and $\lim_{n\to\infty}\frac1{4n}=0$. Therefore, the set of zeros of $f$ has a non-isolated point ($0$), and so $f$ is the null function.
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 1,
"tags": "complex analysis"
}
|
how to show a error when the textbox is empty
How to show a error when the textbox is empty
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim numofmon As Integer
numofmon = TextBox4.Text
If TextBox4.Text = ?? Then
MessageBox.Show("Error")
End If
End Sub
please help
|
You are trying to parse an Integer value, so better that cheking if the textbox text is empty, directly you should call the `Integer.TryParse` function to evaluate whether the text, emptyness or not, could be translated as Integer value.
Dim numofmon As Integer
If Not (Integer.TryParse(TextBox4.Text, numofmon)) Then
MessageBox.Show("Error")
Else
' Logic here...
End If
Note that `numofmon` is passed by refference, so if `Integer.TryParse` success then it assigns the value to the given variable.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "vb.net"
}
|
Good tool for storing server access details
Are there any common/good tools that you sys admin guys use to store lots of server access details i.e. ip addresses, logins etc.
Im getting by with text file at the moment but am considering moving to something more suited to the task.
|
If you're talking about configuration details, you're looking for a CMDB of some sort - read the FAQ for why shopping questions are off-topic for ServerFault and how to better phrase the question so it's answerable. Some folks use plain old text files or spreadsheets, some people spend a crap-ton of money on discovery tools and databases. Depends on what you need and what your budget is, neither of which have you sufficiently explained.
A different and possibly better approach is to implement a configuration management system like Puppet or Chef or CFengine, to declare what the config should be on each server or group of servers and then execute so that the servers conform.
|
stackexchange-serverfault
|
{
"answer_score": 0,
"question_score": 0,
"tags": "web server"
}
|
is there a way to reviews commits to bitbucket repositories without using pull request?
I am trying to have code reviews on each commit done since team members are directly connected to a bitbucket repository... I am trying to do this instead of having team members fork the main repository and create pull request while also avoiding the use of branches.
I know it is not a traditional way of doing things, but keeping it simple would be a huge benefit for this team as I have a a few new git users that do not know how to manage their own repository.
|
I don't think it's possible to have code reviews if all the team members use the same repository and same branch to commit to.
I think the simplest way to achieve this would be to make everyone branch out from a fixed branch (usually `dev`) and to disallow anyone to commit directly to it. The only way to have their latest changes merged into this branch would be via a pull request which needs to be reviewed.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "git, bitbucket, commit, git commit"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.