text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Rails aws dynamo insert into database
I use this code to insert into dynamo db:
require "aws"
AWS.config(
access_key_id: 'xxxxxxxxxxxxxxxxxx',
secret_access_key: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
region: 'eu-west-1'
)
dynamo_db = AWS::DynamoDB.new
table = dynamo_db.tables['mytable']
table.hash_key = [:string, :string]
# add an item
table.items.create(id: '12345', 'foo' => 'bar')
Everything is ok, the data is inserted but I still get this error:
missing hash key value in put_item response
What did I missed? According their documentation seems to be ok.
A:
table.hash_key = [:string, :string]
needs be changed to [:name_of_hash_key, :type_of_hash_key], for example
table.hash_key = [:id, :string]
| {
"pile_set_name": "StackExchange"
} |
Q:
Why any countable subset of $\mathbb{R}→\mathbb{R}$ is generated by a finite set under composition?
There is an infinite sequence of functions $g_1,g_2,\ldots$, each of them is $\Bbb R\to\Bbb R$. Prove that there exists a finite set of functions $f_1,f_2,\ldots,f_n$ such that any function $g_k$ can be expressed as a composition $f_{k_1}\circ f_{k_2}\circ\cdots\circ f_{k_m}$.
A:
The main ingredient in my answer is the following fact:
$|\mathbb{R}^{\mathbb N}| = |\mathbb{R}|$.
Its proof isn't directly related to this question so I won't put it right here. But you can find it in the answer to this question.
Due to this fact we can talk about the $\mathbb R$ as about the disjoint union $\coprod\limits_{i=1}^\infty R_i$ where all of the $R_i$'s are the copies of $\mathbb{R}$.
Now we can define two functions $\mathbb{R} \to \mathbb{R}$: $F$ and $G$. $F$ sends $R_i$ due to the map $g_i$ (namely, $F|_{R_i} = g_i \circ T_i$, where $T_i$ is an arbitrary bijection from $R_i$ to $\mathbb R$) and $G$ works by the following rule: it's defined as a function $\coprod\limits_{i=1}^\infty R_i \to \coprod\limits_{i=1}^\infty R_i$ which sends $T_{i-1}^{-1}(a)$ to $T_i^{-1}(a)$ for all $a$ in $\mathbb R$. It's a well-defined map since all $T_i$'s are bijections.
The rest of the proof is quite elementary: you can easily check that $g_i = F \circ G^{i-1} \circ {T_1}^{-1}$. So your finite set of functions $f_i$ is just $\{F, G, T_1\}$.
A:
More generally:
Theorem. For any infinite set $S$ and any countable set $F$ of functions $f:S\to S$, there are two functions $g,h:S\to S$ such that $F$ is contained in the semigroup generated by $\{g,h\}$ under composition. (On the other hand, if $S$ is a finite set with more than two elements, then three selfmaps of $S$ are needed in order to generate them all.)
Since you already accepted an answer, I won't bother to give a proof, but I will give references. The theorem is due to Sierpiński:
W. Sierpiński, Sur les suites infinies de fonctions définies dans les ensembles quelconques, Fund. Math. 25 (1935) 209–212.
A simpler proof of Sierpiński's theorem was given by Banach:
Stefan Banach, Sur un théorème de M. Sierpiński, Fund Math. 25 (1935) 5–6.
(By the way, if the given functions are bijections, then the functions $g,h$ can also be taken to be bijections; see Theorem 3.5 of Fred Galvin, Generating countable sets of permutations, J. London Math. Soc. (2) 51 (1995) 230–252.)
Sierpiński's theorem resurfaced in Monthly problem 6244, proposed by John Myhill; the solution appeared in Amer. Math. Monthly 87 (1980) 676–678.
Since every semigroup is isomorphic to a semigroup of mappings, as a corollary to Sierpiński's theorem we have:
Corollary. Every countable semigroup is embeddable in a $2$-generator semigroup.
This was proved in a different way by Trevor Evans, Embedding theorems for multiplicative systems and projective geometries, Proc. Amer. Math. Soc. 3 (1952) 614–620.
A:
Let $b:{\Bbb R}\to [0,1)$ be a bijection and $u:x\mapsto x+1$ be a unit shift. We can define $G:[1,\infty)\to{\Bbb R}$ as
$$
G(x)=g_{[x]}\left(b^{-1}\left(\{x\}\right)\right)
$$
where $[x]$ and $\{x\}=x-[x]$ are integer and fractional parts of $x$ respectively. Now we can write the $n$-th function in the original sequence as
$$
g_n(x) = G\left(n+b(x)\right)\quad\mbox{for $n\in{\Bbb N}$.}
$$
In other words, each $g$ can be expressed as a composition of $f_1=b$, $f_2=G$ and some number of $f_3=u$'s:
\begin{equation}
\qquad g_n = G\circ u^{(n)}\circ b\qquad ∎
\end{equation}
| {
"pile_set_name": "StackExchange"
} |
Q:
Unable to Render 3D Graphic using Three.js
Question:
Why isn't the 3D graphic rendering?
Details:
I am trying to load the json format of this graphic in the loading.component.ts file. I am using Angular 2 and Three.js. I've looked at several examples, but cannot find what I did wrong. This is my first time trying to load a 3D image. Any help appreciated.
The entire project can be found here.
Console Error:
core.es5.js:1084 ERROR TypeError: Cannot read property 'scene' of undefined
at loading.component.ts:46
at ObjectLoader.parse (three.module.js:33413)
at three.module.js:33372
at XMLHttpRequest.<anonymous> (three.module.js:29460)
at ZoneDelegate.invokeTask (polyfills.bundle.js:3132)
at Object.onInvokeTask (core.es5.js:4119)
at ZoneDelegate.invokeTask (polyfills.bundle.js:3131)
at Zone.runTask (polyfills.bundle.js:2899)
at XMLHttpRequest.ZoneTask.invoke (polyfills.bundle.js:3194)
loading.component.ts
import { Component, OnInit } from '@angular/core';
import * as THREE from 'three'
declare var require: any;
@Component({
selector: 'app-loading',
templateUrl: './loading.component.html',
styleUrls: ['./loading.component.css']
})
export class LoadingComponent implements OnInit {
"use strict";
scene = new THREE.Scene();
renderer = new THREE.WebGLRenderer();
light = new THREE.AmbientLight(0xffffff);
camera;
box;
renderCallback;
constructor() { }
ngOnInit() {
// size of content
this.renderer.setSize( window.innerWidth, window.innerHeight);
// where to render content
document.getElementById("webgl-container").appendChild(this.renderer.domElement);
this.scene.add(this.light);
this.camera = new THREE.PerspectiveCamera(
35, // Field of view (FOV) from top to bottom.
window.innerWidth / window.innerHeight, // boundries of image
1,
1000
);
this.camera.position.set(0, 0, 5);
this.scene.add(this.camera);
var loader = new THREE.ObjectLoader();
loader.load('assets/img/pac-man-threejs/pac-man.json', function (obj) {
this.scene.add(obj);
})
// this.render();
this.renderCallback = {
callRender: (this.render).bind(this)
};
this.renderCallback.callRender();
}
render() {
this.renderer.render(this.scene, this.camera);
// requestAnimationFrame(this.render);
requestAnimationFrame(this.renderCallback.callRender);
}
}
A:
You don't have the correct this inside the loader.load() callback, which is exactly what the browser is telling you.
var _this = this
loader.load(..., function(obj){ _this.scene.add(obj })
or bind it.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to change a MS Acess database into a MySql database or atleast move the data across quickly?
I created a program that stores the scores of a competition into a MS Access database but now I need to change in to use MySql. How can I transfer all the tables and data across?
A:
The easiest way to do this in bulk is to right click on the tables in MS Access and select Export > Text File. This will allow you to save each table as a csv file.
Once you've done that, you can use whatever management program you're using to import the csv files. If you're using MySQL's workbench, this tutorial should help you. If you want to do it manually, this one should help.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I distinguish values sent from Arduino
Having in my visual basic app something like:
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
*whatever* value = serialPort1.Read*whatever*();
}
Suppose my Arduino sends in every loop, the value read by a photoresistor. Suppose my Arduino also sends a 0 if certain led is LOW or a 1 if certain led is HIGH. Finally suppose my Arduino also sends a value that is equal to the number of times the loop has been executed.
In the 25th execution, lets suppose my Arduino sends something like:
Serial.write(LED_state) // 0 or 1 for LOW or HIGH
Serial.write(photoresistor_value) //lets suppose 25
Serial.write(loop_number) //25
Question: if all the values are sent using Serial.write or Serial.print, and all values are ints, how can I distinguish in my app if the value 25 received belongs to the photoresistor or to the loop? Is there any way to send something like (key, value) from Arduino so I can distinguish between the ints received so I can assign them correctly to my app variables?
A:
Is there any way to send something like (key, value)
Sure:
Serial.print("LED state: ");
Serial.println(LED_state);
You will have to modify your VB code to parse that.
| {
"pile_set_name": "StackExchange"
} |
Q:
Does Sql Server 2000 support SSIS transactions?
I am running an SSIS package, that pulls data from two SQL Servers, One is a SQL Server 2008 and the other is a SQL Server 2000. I have been trying to implement transactions in SSIS lately.
The problem i am facing now is, the package always fail reading the SQL Server 2000 when transaction level in the packages is set to required, with an Error The Acquire Connection manager failed with error code 0xC0202009
Tried:
Checking if the DTC service is started in both machine, the client and the Database Server and they are both started.
On the Client, went to Control Panel >> Component Services >> Computers >> My Computer >> Distributed Transaction Coordinator >> Local DTS (Right Click, then Chooose Properties ) >> Security Tab
( Allow Remote Clients, Allow Inbound, Allow Outbound ) are all selected
On the 2000 SQL Server,went to Control Panel >> Component Services >> Computers >> My Computer >> Distributed Transaction Coordinator >> (No Local DTS) and right clicking will not give me properties of the DTC, cant find a way to access the options ( Allow Remote Clients, Allow Inbound, Allow Outbound )
Now I was wondering does SQL Server 2000 support SSIS transactions?
A:
SSIS was first released with SQL Server 2005 - so it is not supported on SQL Server 2000.
Look at DTS which was what SSIS replaced.
Use DTCPing to ensure that distributed transactions are setup correctly on both servers.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to speedup binary transformation from integer values
I wrote the following method (in python 2.7) that generates a set of integers and transform them into binary representation. It takes self-explanatory two parameters: total_num_nodes and dim. It returns numpy matrix-like containing the binary representation of all these integers:
def generate(total_num_nodes, dim):
# Generate random nodes from the range (0, dim-1)
nodes_matrix = [random.randint(0, 2 ** dim - 1) for _ in range(total_num_nodes)]
# Removes duplicates
nodes_matrix = list(set(nodes_matrix))
# Transforms each node from decimal to string representation
nodes_matrix = [('{0:0' + str(dim) + 'b}').format(x) for x in nodes_matrix]
# Transforms each bit into an integer.
nodes_matrix = np.asarray([list(map(int, list(x))) for x in nodes_matrix], dtype=np.uint8)
return nodes_matrix
The problem is that when I pass very large values, say total_num_nodes= 10,000,000 and dim=128, the generation time takes really long time. A friend of mine hinted me that the following line is actually a bottleneck and it is likely to be responsible for the majority of computation time:
# Transforms each node from decimal to string representation
nodes_matrix = [('{0:0' + str(dim) + 'b}').format(x) for x in nodes_matrix]
I cannot think of other faster method that can replce this line so that I get to speedup the generation time when it is running on a single processor. Any suggestion from you is really really appreciated.
Thank you
A:
Do it all in numpy and it will be faster.
The following generates total_num_nodes rows of dim columns of np.uint8 data, then keeps the unique rows by providing a view of the data suitable for np.unique, then translating back to a 2D array:
import numpy as np
def generate(total_num_nodes, dim):
a = np.random.choice(np.array([0,1],dtype=np.uint8),size=(total_num_nodes,dim))
dtype = a.dtype.descr * dim
temp = a.view(dtype)
uniq = np.unique(temp)
return uniq.view(a.dtype).reshape(-1,dim)
| {
"pile_set_name": "StackExchange"
} |
Q:
MonoMac - AVAudioPlayer crash
We are having an issue using AVAudioPlayer on MonoMac.
We get this warning on the console:
Class AVAudioPlayer is implemented in both ?? and /System/Library/Frameworks/AVFoundation.framework/AVFoundation. One of the two will be used. Which one is undefined.
Which is followed by Segmentation fault: 11 and an immediate crash.
I'm assuming my MonoMac app is somehow loading the iOS libraries for AVAudioPlayer. Any ideas?
A:
Xamarin just released Xamarin.Mac, which fixes this issue.
| {
"pile_set_name": "StackExchange"
} |
Q:
Eigenvalue of a matrix where a row is proportional to a versor
Consider a real square matrix $A = \{a_{i,j}\} \in \mathbb{R}^{N \times N}$. Suppose that $A$ has a row which entries are $0$, except for the element on the diagonal, i.e. the $i$-th row of $A$ is proportional to the versor $\bf{e}_i$.
Is it always true that at least one eigenvalue of $A$ is equal to $a_{i,i}$?
A:
Yes, it is true that at least one eigenvalue of $A$ is equal to $a_{ii}$.
Let ${\bf e}_i$ be the column vector with all entries $0$ with the exception of the $i$-th entry which is $1$.
Since the $i$-th row of $A$ has all entries 0 with the exception for the element on the main diagonal, it follows that ${\bf e}_i^T A=a_{ii}{\bf e}^T_i$ which is equivalent to
$$A^T{\bf e}_i=a_{ii}{\bf e}_i.$$
Hence $a_{ii}$ is an eigenvalue of $A^T$ (with eigenvector ${\bf e}_i$).
and
$$0=\det(A^{T} - a_{ii} I) = \det((A - a_{ii} I)^{T}) = \det (A - a_{ii} I).$$
Therefore $a_{ii}$ is also an eigenvalue of $A$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Unable to use 'class' as a key in NSDictionary
I'm trying to use a class as a key in an NSDictionary. I looked at the answer to this question and what I have is pretty much the same; I'm using setObject: forKey:. However, XCode complains, saying Incompatible pointer types sending 'Class' to parameter of type 'id<NSCopying>'. The call I have is:
[_bugTypeToSerializerDictionary setObject: bugToStringSerializer
forKey: [bugToStringSerializer serializedObjectType]];
bugToStringSerializer is an instance of BugToStringSerializer whose concrete implementations implement serializedObjectType. An example of a concrete implementation looks like this:
- (Class) serializedObjectType {
return [InfectableBug class];
}
What am I doing wrong here?
A:
(It seems that classes do conform to NSCopying, however their type is not id <NSCopying>.) Edit: classes do not conform to protocols. Of course the essential is that classes respond to the copy and copyWithZone: messages (and that's why you can safely ignore the warning in this case). Their type is still not id <NSCopying>.) That's why the compiler complains.
If you really don't want that ugly warning, just perform an explicit type conversion:
[dictionary setObject:object forKey:(id <NSCopying>)someClass];
A:
Aha,I just fixed the bug in my project.
use this:
NSStringFromClass([Someclass class]);
A:
The other answers are certainly helpful, but in this case it probably makes more sense to just use an NSMapTable, which does not copy the key unlike NSDictionary, and just retains it with a strong pointer (by default, although this can be changed).
Then you can just use your original code with no modifications.
NSMapTable *_bugTypeToSerializerDictionary = [NSMapTable new];
...
[_bugTypeToSerializerDictionary setObject: bugToStringSerializer
forKey: [bugToStringSerializer serializedObjectType]];
It's less hacky, and is clearer at conveying programmer intent.
For extra style points you could give the instance variable a slightly more fitting name like_bugTypeToSerializerMap.
| {
"pile_set_name": "StackExchange"
} |
Q:
Reference to a formula with inputbox method
I wanted to apply a Text(E2,"MM/DD/YYYY") formula via excel VBA. I use multiple sheets, Cell destination and the Cell reference is not fixed. Hence i used Input-box method to for Cell destination which is working perfect, and wanted to manually select or change cell reference in the formula via inputbox method.
E.g. if i write above formula in A2 cell and my target cell is E2. Cell selection should happen via inputbox.
Initially my plan was to select both the things with inputbox, but i am just a beginner and did not managed to do that hence changed the plan and re-written the code. But the codes seems to be having some issues while editing formula range in inputbox, sometimes it doesn't consider my iputs. If i Say Text(E2,"MM/DD/YYYY") then it selects Text(D2 or something,"MM/DD/YYYY")
Option Explicit
Sub FinalTxtDte()
Dim Rng As range
Dim LastRow As Long
Dim Frmla As String
Dim DestRng As range
On Error Resume Next ' if the user presses "Cancel"
Set Rng = Application.InputBox("Select a Cell which needs to be converted in Date format.", "Range Selection", Type:=8)
Err.Clear
On Error GoTo 0
If Not Rng Is Nothing Then
Frmla = "=TEXT(" & Rng.Address("False", "False") & ",""MM/DD/YYYY"")"
On Error Resume Next ' if the user presses "Cancel"
Set DestRng = Application.InputBox("Select a Cell where you would like to get a Converted Date.", "Range Selection", Type:=8)
Err.Clear
On Error GoTo 0
If Not DestRng Is Nothing Then
DestRng.Formula = Frmla
LastRow = Rng.End(xlDown).Row
DestRng.Select
range(Selection, Selection.Offset(LastRow - Rng.Row, 0)).Select
Selection.FillDown
range(Selection, Selection.Offset(LastRow - Rng.Row, 0)).Value _
= range(Selection, Selection.Offset(LastRow - Rng.Row, 0)).Value
End If
End If
End Sub
A:
The code below will let you use 2 InputBoxes to select the cell and the formula target (currently according to your post requaet it's for 1 Cell).
I've modifed the 2nd InputBox to select the destination range for the formula.
You need to keep the On Error Resume Next (and later the On Error GoTo 0) in case the user selects the "Cancel" option in the InputBox.
Code
Option Explicit
Sub TextDateFormula()
Dim Rng As Range
Dim LastRow As Long
Dim Frmla As String, Txt As String
Dim DestRng As Range
On Error Resume Next ' if the user presses "Cancel"
Set Rng = Application.InputBox("Select a cell.", "Range Selection", Type:=8)
Err.Clear
On Error GoTo 0
If Not Rng Is Nothing Then
Frmla = "=TEXT(" & Rng.Address(True, True) & ",""MM/DD/YYYY"")"
On Error Resume Next ' if the user presses "Cancel"
Set DestRng = Application.InputBox("Select a range to add Decimal Hours.", "Range Selection", Type:=8)
Err.Clear
On Error GoTo 0
If Not DestRng Is Nothing Then
DestRng.Formula = Frmla
End If
End If
End Sub
Edit 1: In order for the formula not to take the absolute address, modify the code line below:
Frmla = "=TEXT(" & rng.Address(False, False) & ",""MM/DD/YYYY"")"
You need to modify the section inside the brackets after the Address("Row Absolute", "Column Absolute") , so modify column and row setting according to your needs.
| {
"pile_set_name": "StackExchange"
} |
Q:
Convert JavaScript Object / JSON into PHP Array Trouble
This question is not related at all to the mentioned duplicate answer/question...
I have a large list of over 1,000 items in JavaScript i this format...
var plugins = [
{
name: "Roundabout - Interactive, turntable-like areas",
url: "http:\/\/fredhq.com/projects/roundabout/",
tag: "slide"
},
{
name: "Slides - Simple slideshow plugin for jQuery",
url: "http://slidesjs.com/",
tag: "slide"
}
......lots more
]
My goal is to import them into a PHP array like this....
Array
(
[0] => Array
(
[name] => Roundabout - Interactive, turntable-like areas/
[url] => http://fredhq.com/projects/roundabout/
[tag] => slide
)
[1] => Array
(
[name] => Slides - Simple slideshow plugin for jQuery
[url] => http://slidesjs.com/
[tag] => slide
)
[2] => Array
(
[name] => Orbit - jQuery Image Slider Plugin
[url] => http://www.zurb.com/playground/jquery_image_slider_plugin/
[tag] => slide
)
)
I tried using PHP's json_decode() function however the source JS does not have the keys wrapped in " so it does not work.
When I manually added "'s around the keys and some backslashes then PHP json_decode() works....
$json = '[{
"name": "Roundabout - Interactive, turntable-like areas/",
"url": "http:\/\/fredhq.com/projects/roundabout/",
"tag": "slide"
},
{
"name": "Slides - Simple slideshow plugin for jQuery",
"url": "http:\/\/slidesjs.com\/",
"tag": "slide"
},
{
"name": "Orbit - jQuery Image Slider Plugin",
"url": "http:\/\/www.zurb.com/playground/jquery_image_slider_plugin/",
"tag": "slide"
}]';
echo '<pre>';
print_r(json_decode($json, true));
echo '</pre>';
The issue though is my large list does not have the keys wrapped in quotes so I need a way to automate it.
Could someone help me to achieve the end goal since my attempts have all failed so far please?
A:
It looks like the problem can be solved manually by taking this method, as having said that the JSON presented here is valid, it is better to use either console or something to make the JSON valid for everywhere not only in JavaScript by using:
plugins = JSON.stringify(plugins);
This will make the plugins to look like:
"[{"name":"Roundabout - Interactive, turntable-like areas","url":"http://fredhq.com/projects/roundabout/","tag":"slide"},{"name":"Slides - Simple slideshow plugin for jQuery","url":"http://slidesjs.com/","tag":"slide"}]"
Removing the quotes and putting it in JSONLint will give out a valid JSON like the below:
[
{
"name": "Roundabout - Interactive, turntable-like areas",
"url": "http://fredhq.com/projects/roundabout/",
"tag": "slide"
},
{
"name": "Slides - Simple slideshow plugin for jQuery",
"url": "http://slidesjs.com/",
"tag": "slide"
}
]
Now the best way is to copy this output and save it in the text.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I remove all lines in a file that are less than 6 characters?
I have a file containing approximately 10 million lines.
I want to remove all lines in the file that are less than six characters.
How do I do this?
A:
There are many ways to do this.
Using grep:
grep -E '^.{6,}$' file.txt >out.txt
Now out.txt will contain lines having six or more characters.
Reverse way:
grep -vE '^.{,5}$' file.txt >out.txt
Using sed, removing lines of length 5 or less:
sed -r '/^.{,5}$/d' file.txt
Reverse way, printing lines of length six or more:
sed -nr '/^.{6,}$/p' file.txt
You can save the output in a different file using > operator like grep or edit the file in-place using -i option of sed:
sed -ri.bak '/^.{6,}$/' file.txt
The original file will be backed up as file.txt.bak and the modified file will be file.txt.
If you do not want to keep a backup:
sed -ri '/^.{6,}$/' file.txt
Using shell, Slower, Don't do this, this is just for the sake of showing another method:
while IFS= read -r line; do [ "${#line}" -ge 6 ] && echo "$line"; done <file.txt
Using python,even slower than grep, sed:
#!/usr/bin/env python2
with open('file.txt') as f:
for line in f:
if len(line.rstrip('\n')) >= 6:
print line.rstrip('\n')
Better use list comprehension to be more Pythonic:
#!/usr/bin/env python2
with open('file.txt') as f:
strip = str.rstrip
print '\n'.join([line for line in f if len(strip(line, '\n')) >= 6]).rstrip('\n')
A:
It's very simple:
grep ...... inputfile > resultfile #There are 6 dots
This is extremely efficient, as grep will not try to parse more than it needs, nor to interpret the chars in any way: it simply send a (whole) line to stdout (which the shell then redirects to resultfile) as soon as it saw 6 chars on that line (. in a regexp context matches any 1 character).
So grep will only output lines having 6 (or more) chars, and the other ones are not outputted by grep so they don't make it to resultfile.
A:
Solution #1: using C
Fastest way: compile and run this C program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_BUFFER_SIZE 1000000
int main(int argc, char *argv[]) {
int length;
if(argc == 3)
length = atoi(argv[2]);
else
return 1;
FILE *file = fopen(argv[1], "r");
if(file != NULL) {
char line[MAX_BUFFER_SIZE];
while(fgets(line, sizeof line, file) != NULL) {
char *pos;
if((pos = strchr(line, '\n')) != NULL)
*pos = '\0';
if(strlen(line) >= length)
printf("%s\n", line);
}
fclose(file);
}
else {
perror(argv[1]);
return 1;
}
return 0;
}
Compile with gcc program.c -o program, run with ./program file line_length (where file = path to the file and line_length = minimum line length, in your case 6; the maximum line length is limited to 1000000 characters per line; you can change this by changing the value of MAX_BUFFER_SIZE).
(Trick to substitute \n with \0 found here.)
Comparison with all the other solutions proposed to this question except the shell solution (test run on a ~91MB file with 10M lines with an average lenght of 8 characters):
time ./foo file 6
real 0m1.592s
user 0m0.712s
sys 0m0.160s
time grep ...... file
real 0m1.945s
user 0m0.912s
sys 0m0.176s
time grep -E '^.{6,}$'
real 0m2.178s
user 0m1.124s
sys 0m0.152s
time awk 'length>=6' file
real 0m2.261s
user 0m1.228s
sys 0m0.160s
time perl -lne 'length>=6&&print' file
real 0m4.252s
user 0m3.220s
sys 0m0.164s
sed -r '/^.{,5}$/d' file >out
real 0m7.947s
user 0m7.064s
sys 0m0.120s
./script.py >out
real 0m8.154s
user 0m7.184s
sys 0m0.164s
Solution #2: using AWK:
awk 'length>=6' file
length>=6: if length>=6 returns TRUE, prints the current record.
Solution #3: using Perl:
perl -lne 'length>=6&&print' file
If lenght>=6 returns TRUE, prints the current record.
% cat file
a
bb
ccc
dddd
eeeee
ffffff
ggggggg
% ./foo file 6
ffffff
ggggggg
% awk 'length>=6' file
ffffff
ggggggg
% perl -lne 'length>=6&&print' file
ffffff
ggggggg
| {
"pile_set_name": "StackExchange"
} |
Q:
R language - count of multiple columns group by one column
I got data frame in R that looks like this:
> df
c1 c2 c3
1: 10 c1 i1
2: 10 c1 i2
3: 10 c1 i3
4: 10 c2 i1
5: 10 c2 i2
6: 10 c2 i3
7: 20 c11 i1
8: 20 c11 i2
9: 20 c11 i3
10: 20 c12 i1
11: 20 c12 i2
12: 20 c12 i3
I need to sum distinct counts of columns c2 and c3 group by c1 - to get the following result:
10 2 3
20 2 3
How would I get that done in R?
Thanks
A:
Using base R aggregate
aggregate(cbind(c2,c3)~c1, df, function(x) length(unique(x)))
# c1 c2 c3
#1 10 2 3
#2 20 2 3
| {
"pile_set_name": "StackExchange"
} |
Q:
How do you replace a match, using regex, only if it is not preceded by a given character?
I have a foreach statement that is searching for a string value within a List<string>. If the current line being read contains the string, I want to replace it, but with certain caveats.
foreach (string shorthandValue in shorthandFound)
{
if (currentLine.Contains(shorthandValue))
{
// This method creates the new string that will replace the old one.
string replaceText = CreateReplaceString(shorthandValue);
string pattern = @"(?<!_)" + shorthandValue;
Regex.Replace(currentLine, pattern, replaceText);
// currentline is the line being read by the StreamReader.
}
}
I'm trying to get the system to ignore the string if the shorthandValue is preceded by an underscore character ("_"). Otherwise, I want it to be replaced (even if it is at the start of the line).
What am I not doing correctly?
UPDATE
This is working mostly correctly:
Regex.Replace(currentFile, "[^_]" + Regex.Escape(shorthandValue), replaceText);
However, while it does ignore the underscore, it it removing any space before the shorthandValue string. So if the line read "This is a test123.", and the "test123" is replaced, I end up with this result:
"This is aVALUEOFTHESHORTHAND."
Why is the space being removed?
UPDATE AGAIN
I changed the regex back to my (?<!_) and it is preserving the spaces.
A:
Your regex is correct. The problem is that Regex.Replace returns a new string.
You are ignoring the returned string.
| {
"pile_set_name": "StackExchange"
} |
Q:
python removing lines from file
Question:
I am trying to remove empty lines from my .txt files.
Because my .txt files are generated by Python through HTML download and i want to save them at a certain location, i have to use Os.path.join.
This is the code that saves the HTML on the location after removing all TAGS and keeping only the inside of the tags:
cntent = re.sub('<[^>]+>',"\n", str(cntent))
with open(os.path.join('/Users/Brian/Documents/test',titles), "wb") as file:
file.writelines(str(cntent))
how can i achieve this?
The outcome of the file:
Productspecificaties
Uiterlijke kenmerken
Gewicht
185 g
What i tried:
filtered = filter(lambda x: not re.match(r'^\s*$', x), original)
Desired outcome
Productspecificaties
Uiterlijke Kenmerken
Gewicht
185Gr
Please note that in the first line of code re.sub... i use "\n" because otherwise there would be no spaces at all.
A:
You don't need to use regular expression:
cntent = re.sub('<[^>]+>',"\n", str(cntent))
with open(os.path.join('/Users/Brian/Documents/test', titles), "wb") as f:
f.writelines(line for line in cntent.splitlines(True) if line.strip())
str.strip() strips spaces (includign newline) at the beginning and at the end of the string. For the line that consists of only spaces, it will return empty string; which is evaluated as false value.
str.splitlines with True was used to split lines, but not to exclude new lines.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is this how to make a keyword finder/density check?
Hi I have a relatively big block of text and am wanting to find the most common keywords within it and calculate the density of these keywords. The way that I have thought of seems as though it could be slow or performance demanding and difficult:
Iterate over each word in the block of text.
Find all the same matches for each of these words
Count the total matches for each of these words
Take say the top 5 most matches and then calculate their density relative to total block.
output results
Is there any easy quick better way of doing this using jquery?
A:
var text = "Lorem ipsum ...";
var word_list = text.split(/\W+/); // Split the text into words.
var counts = {};#
Allocate a dictionary
for (var i = 0; i < word_list.length; ++i) {
var word = word_list[i];
counts[word] = (counts[word] || 0) + 1; // Increment count by one.
}
var densities = {};
for (word in counts) {
densities[word] = parseFloat((counts[word] / word_list.length) * 100).toFixed(2); // Calculates all the densities percentage.
}
All that's left is to get the most frequent ones.
You may want to change how the text is split into keywords, or filter very common/short words out. Right now "it's" ends up split into 'it', 's'. This may not be what you want.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use Vue on click to toggle/ deactive an active html class?
I am trying this peace of code to toggle class by vue on-click event. But not working and showing bunch or errors in console. Can you help me ?
<div id="app5">
<h1>Dynamic CSS</h1>
<h2>Example 1</h2>
<div
v-bind:class="{available: value}"
v-on:click="available = !available">
<span>Click</span>
</div>
</div>
var app5=new Vue({
el:'#app5',
data:{
value: true,
nearby:false
}
});
sylesheet
span{
background:red;
color: #fff;
}
.available span{
background: green;
}
I am expecting the span background will initially green but red after click.
A:
In your click handler, you're trying to toggle the available variable, which is actually the name of your css class. The syntax for class binding is the following: v-bind:"{classtotoggle: variable}".
So you should have written:
<div v-bind:class="{available: value}" v-on:click="value = !value">
<span>Click</span>
</div>
As an advice, I'd always use a function to handle event (v-on directive), It makes it easier to add behaviour in the future.
Hope that helps,
| {
"pile_set_name": "StackExchange"
} |
Q:
Android webview not displaying html with external js links
I have used the following code to display a website that i have included in the assets directory in my android app:
WebView myWebView = (WebView)findViewById(R.id.myWebView);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("file:///android_asset/my_site/index.html");
In the index.html file i have called some external js files. But the external js files are not being called. Why is this happening? I have loaded the same website locally from iOS, and it is working perfectly. What can I do to rectify this?
A:
I was actually doing a HTML5 game using phaser.js. It seems like the only way out was cocoonjs. Didn't find any other solution. Why does android's webview doesn't show the game by default without using any wrappers? I had the same game working perfect in iOS and windows webview without using any kind of wrappers.
| {
"pile_set_name": "StackExchange"
} |
Q:
Como chamar método Linq na View?
Bom dia pessoal.
a minha dúvida é a seguinte, tenho o seguinte método no meu model:
public IQueryable GetConsulta()
{
var q = (from c in Datacontext.Tabela1
join b in Datacontext.Tabela2 on c.CodClase equals b.CodClase
join d in Datacontext.Tabela3 on b.CodImobilizado equals d.CodImobilizado
where c.CodClase == b.CodClase && b.CodImobilizado == d.CodImobilizado
select new
{
taxa = c.Taxa,
ano = DateTime.Parse(b.Data).Year,
data = d.Data,
valorAquisicao = b.Valor,
});
return q;
}
Na View está assim:
void getConsulta(){
var a = model.GetConsulta();
foreach(var linha in a){
//faça algo
}
}
O problema é que não consigo acessar as variáveis criadas no método do model no foreach da View.
Alguém poderia me ajudar.
A:
O problema está no tipo de retorno que você está utilizando, nesta abordagem, você não especifica qual o retorno do IQueryable, consequentemente na view, você não vai conseguir visualizar os dados desejados.
Uma sugestão seria você tipar seu retorno com uma classe de modelo:
class Modelo {
public string taxa { get; set; }
public int ano { get; set; }
public DateTime data { get; set; }
public decimal valorAquisicao { get; set; }
}
public IQueryable<Modelo> GetConsulta()
{
var q = (from c in Datacontext.Tabela1
join b in Datacontext.Tabela2 on c.CodClase equals b.CodClase
join d in Datacontext.Tabela3 on b.CodImobilizado equals d.CodImobilizado
where c.CodClase == b.CodClase && b.CodImobilizado == d.CodImobilizado
select new Modelo()
{
taxa = c.Taxa,
ano = DateTime.Parse(b.Data).Year,
data = d.Data,
valorAquisicao = b.Valor,
});
return q;
}
Na View ficaria assim:
void getConsulta(){
var a = model.GetConsulta();
foreach(Modelo linha in a){
//faça algo
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Уменьшение меню при прокручивании колесом мыши
Пример кода здесь:
`https://codepen.io/alexseveneight/pen/LjPVym`
Проблема в том, что если курсор находится на области меню, то изменения не происходят. Если же курсор поставить на белый фон содержания, то меню плавно уменьшается, как и указано в js-коде.
A:
Используйте событие onscroll объекта window
window.onscroll = function(event){
var y = window.pageYOffset;
var menu = document.getElementById('menu');
if(y >= 250) {
menu.style.height = '75px';
menu.style.transition = '1s';
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How do i find the maximum number in an Array using a function
In my c++ class, i'm supposed to use this " int mymaximum(int a[], int numberOfElements); " function to find the maximum number in an Array. The function should return the largest in this array.
This is the code I have so far without the function I need to use. Thanks in advance and sorry about the messy code, still learning.
#include <iostream>
using namespace std;
int main() {
int Array[] = {23,2,90,53,38};
int mymaximum = 0;
for(int i = 0; i < 5; i++){
if(Array[i] > mymaximum){
mymaximum = Array[i];
}
}
cout << "The Max is: " << mymaximum << "\n";
return 0;
}
A:
I'll show the overall structure without solving the homework for you:
#include <iostream>
using namespace std;
int mymaximum(int a[], int numberOfElements) {
int ret = 0;
// compute the maximum and store in `ret'
...
return ret;
}
int main() {
int Array[] = {23,2,90,53,38};
cout << "The Max is: " << mymaximum(Array, sizeof(Array) / sizeof(Array[0])) << "\n";
return 0;
}
In case you're wondering, sizeof(Array) / sizeof(Array[0]) computes the size of the array so that you don't have to hard-code it here.
A:
Just wrap around the logic to find maximum in a function. Like this:
int mymaximum(int a[], int numberOfElements)
{
// moved code from main() to here
int mymaximum = 0;
for(int i = 0; i < numberOfElements; i++)
{
if(a[i] > mymaximum)
{
mymaximum = a[i];
}
}
return mymaximum;
}
Aso, in order to support negative numbers, modify your logic like this:
int mymaximum(int a[], int numberOfElements)
{
// moved code from main() to here
int mymaximum = a[0];
for(int i = 1; i < numberOfElements; i++)
{
if(a[i] > mymaximum)
{
mymaximum = a[i];
}
}
return mymaximum;
}
Note that now I initialize maximum with the first entry in the array!
In main() call your method like this:
int main() {
int Array[] = {23,2,90,53,38};
cout << "The Max is: " << mymaximum(Array, sizeof(Array) / sizeof(Array[0])) << "\n";
return 0;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Is the amount of energy in the universe a finite quantity Joules?
We know from the first law of thermodynamics that the amount of energy in the universe is conserved. However, doesn't this law presuppose that the amount of energy in the universe is a finite quantity of Joules?
As David Hume reasoned, all of science depends on inductive generalization. But wouldn't it be a fallacy of hasty generalization to conclude from models and experiments where the quantity of joules are finite and contained by an adiabatic wall that therefore the universe at large is like this?
A:
Ideally, yes. Energy is conserved, so all interactions just release (e.g. chemical reactions) shift and distribute energy around. But the sum should stay the same. All stored chemical energy sources will eventually be exhausted, heat exchanges between any bodies at different temperatures will keep happening until the whole universe is in thermal equilibrium. Maximum entropy. No more thermal exchanged. Heat death of the Universe.
However, energy is not conserved in the Universe.
This is because of General Relativity and the (accelerated) expansion of the Universe. The universe is expanding, which means that something is driving the expansion - dark energy. But the expansion is accelerating, so this dark energy is somehow increasing. From where? Nobody really knows.
If you have physics background, then you will know that energy conservation is linked to time invariance of the Hamiltonian. From Noether's theorem, the conserved charge in time translations is the energy of the system. Since the accelerated expansion of the universe breaks the time translation invariance of the system (i.e. the whole universe), energy in said system is not conserved.
| {
"pile_set_name": "StackExchange"
} |
Q:
maximum property of sequence of functions
Let $T>0$, $w:\mathbb R^n\times (0,T]\to \mathbb R$ be continuous and $w$ has a strict lokal maximum in $(x_0,T)$ for some $x_0\in\mathbb R$. Define $$\tilde w(x,t):= w(x,t) - \frac{\varepsilon}{T-t}$$ for $x\in\mathbb R^n, 0<t<T$.
For $\varepsilon >0$ small enough, $\tilde w$ has a local maximum in some point $(x_\varepsilon,t_\varepsilon)$ with $0<t_\varepsilon<T$ and we can choose this point such that $(x_\varepsilon,t_\varepsilon)\to (x_0,t_0)$ for $\varepsilon\to 0$.
I am trying to formally prove this, but I already get stuck calculating the maximum.
What I want to do is calculate the maximum and then show that $(x_\varepsilon,t_\varepsilon)\to (x_0,t_0)$. Since $x_\varepsilon=x_0$ we already have $x_\varepsilon \to x_0$, but I am a little stuck with the $t_\varepsilon$-part:
So we obviously have $\frac{\partial\tilde w}{\partial x} = w_x(x,t)$ for which we already know that this is zero at $x_\varepsilon=x_0$.
But how about $$\frac{\partial \tilde w}{\partial t} = w_t(x,t) - \frac{\varepsilon}{(T-t)^2}=0$$
I have no idea how to solve this for $t$ to get my $t_\varepsilon$. Does anyone have an idea on how to go on with this? Thanks!
A:
First, you can assume without loss of generality that $(x_0,T)$ is a global maximum of $w$. To see this, note that $w(x,t)<w(x_0,T)$ in some compact neighbourhood $K$ of $(x_0,T)$ (except at that point itself), so there is some $m<w(x_0,T)$ so that $w<m$ on the boundary of $K$ (except the part where $t=T$). Now replace $w$ by $w\wedge m$ outside $K$, turning the local maximum into a global one.
Now for each $\delta>0$, put $K_\delta=\{(x,t)\in\mathbb{R}^n\times(0,T]\colon w(x,t)\ge w(x_0,T)-\delta\}$, and convince yourself that for small enough $\delta$, $K_\delta$ is compact, and this set shrinks to the single point $(x_0,T)$ as $\delta\to0$.
You should find that when $\delta>0$ is fixed and $\varepsilon$ is small enough, $\tilde w$ has a global maximum $(x_\varepsilon,t_\varepsilon)$ which happens to lie in $K_\delta$.
And that should pretty much finish the proof. I'll leave the mopping up of the details to you.
| {
"pile_set_name": "StackExchange"
} |
Q:
Select N Random Rows with Fluent NHibernate
How do I retrieve N random entities using Fluent NHibernate?
Desired query:
SELECT TOP 5 * FROM MyTable ORDER BY newid()
I'd like to be able to use the Linq repo's for this, but I'm not sure if the result will be optimal. I am not familiar with HQL.
A:
SQL Server-specific Solution
Where Word is the random entity:
IQuery q = _unitOfWork.CurrentSession
.CreateQuery("from Word order by newid()")
.SetMaxResults(5);
var randomWords = q.List<Word>();
| {
"pile_set_name": "StackExchange"
} |
Q:
Jquery UI Draggable Snapping with margin
I'm working on a project where users can customize their own dashboard page. This means they can drag components onto the page and position them as they like.
To get a nicely layout page I want the components to snap to each other. At this moment I'm using the snap: true property, which will place the components right next to each other. However, I'd like to have some space in between the components after they snapped. So instead of snapping to the exact position of the other component, it must snap to the other component with a 5 pixel gap.
Is there any way to do this?
A:
A few options to think about:
Wrap each component in an enclosing element (e.g. div) with a padding of 2.5 pixels and a transparent background and make these enclosing elements the draggable ones. Thus when the enclosing elements snap together, your current elements will appear to have snapped together but with a 5 pixel gap to each other
Subscribe to the 'stop' event on the draggable items and use it to manually reposition them to a 5 pixel gap after the snapping has finished
Set up 'droppable' elements to accept the 'draggable' components, laying them out to ensure that a 5 pixel gap is retained between each
| {
"pile_set_name": "StackExchange"
} |
Q:
Where can I ask how to change the storage place from owncloud to a hdd?
So I got a question about how to change the storage place from owncloud to a hdd. I am running the owncloud on Linux so I asked it at Linux, but I don't really feel like that's the right place to ask. Should I ask on Superuser? Or somewhere else? It's not really that the problem has very much to do with Linux but more the configuration of owncloud.
https://unix.stackexchange.com/questions/102045/owncloud-blank-page
A:
You can ask in Super User, there is a tag for owncloud https://superuser.com/questions/tagged/owncloud
something similar to your question Change owncloud data directory to an external drive
| {
"pile_set_name": "StackExchange"
} |
Q:
Django append for searching each words in a sentece using filter
I want to search each word in a sentence and put that in result['post'] dictionary
and of course this code only looks for last query
queries = querystring.split()
for query in queries:
results['posts'] = Post.objects.filter(text__icontains=query)
i tried append,extend and a lot of things but it didn't work as expected.
Edit Update:
I also tried
count = {}
results = {}
post_results = []
queries = querystring.split()
for query in queries:
post_results.append(Post.objects.filter(text__icontains=query))
results['posts'] = post_results
count['posts'] = results['posts'].count()
But this leads to another error count() takes exactly one argument (0 given)
Error Image
Also Post.objects.filter(text__icontains=query) this line returns a queryset value and Queryset type of django doesn't seem to have append. Is there it's own append like feature ? If so then that wouldn't change it's queryset type to list. Using temp variable like post_results = [] changes to list.
Can we change that list back to queryset? If we can then that would work.
A:
Thanks all of you I tried everything mentioned at first and finally got a solution
I did a crazy thing at first.
I wanted to define an empty queryset so for results['posts'] so I did a bad but a working way results['posts']=Post.objects.filter(text_icontains='sth_that_will_never_b_true')
and I used
Django Merge QuerySets
and solved the problem and then later studied genuine way to define empty QuerySet as
django.db.models.query.QuerySet.none
And gladly final code is
count = {}
results = {}
results['posts']=Post.objects.none() # empty QuerySet
queries = querystring.split()
for query in queries:
results['posts'] = results['posts'] | Post.objects.filter(
text__icontains=query)
count['posts'] = results['posts'].count()
Now everything works as expected.
| {
"pile_set_name": "StackExchange"
} |
Q:
Windows Server 2012 R2 and TCP slow start and Hyper-v hosts
I need to change default value of TCP InitialCongestionWindow
I read this document:
https://www.iispeed.com/blog/windows-server-2012-and-tcp-slow-start
I tryed it on our hyper-v hosted virtual server 2012 R2.
PS C:\>Set-NetTCPSetting -SettingName Custom -InitialCongestionWindow 10 -CongestionProvider CTCP
I got error:
Set-NetTCPSetting : No MSFT_NetTCPSetting objects found with property 'SettingName' equal to 'Custom'. Verify the valu
e of the property and retry.
At line:1 char:1
+ Set-NetTCPSetting -SettingName Custom -InitialCongestionWindow 10 -CongestionPro ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Custom:String) [Set-NetTCPSetting], CimJobException
+ FullyQualifiedErrorId : CmdletizationQuery_NotFound_SettingName,Set-NetTCPSetting
The question is how can I acomplish what that IISspeed document is telling about? If I Change this on Hyper-v machine Do i allso need change this on hypers-v host too to actualy make any difference?
Should I allso make the same change to SSL port 443 ?
I ran this command:
PS C:\Users\Administrator> Get-NetTCPSetting
SettingName : Automatic
MinRto(ms) :
InitialCongestionWindow(MSS) :
CongestionProvider :
CwndRestart :
DelayedAckTimeout(ms) :
DelayedAckFrequency :
MemoryPressureProtection :
AutoTuningLevelLocal :
AutoTuningLevelGroupPolicy :
AutoTuningLevelEffective :
EcnCapability :
Timestamps :
InitialRto(ms) :
ScalingHeuristics :
DynamicPortRangeStartPort :
DynamicPortRangeNumberOfPorts :
AutomaticUseCustom :
NonSackRttResiliency :
ForceWS :
MaxSynRetransmissions :
SettingName : InternetCustom
MinRto(ms) : 300
InitialCongestionWindow(MSS) : 4
CongestionProvider : CTCP
CwndRestart : False
DelayedAckTimeout(ms) : 50
DelayedAckFrequency : 2
MemoryPressureProtection : Enabled
AutoTuningLevelLocal : Normal
AutoTuningLevelGroupPolicy : NotConfigured
AutoTuningLevelEffective : Local
EcnCapability : Enabled
Timestamps : Disabled
InitialRto(ms) : 3000
ScalingHeuristics : Disabled
DynamicPortRangeStartPort : 49152
DynamicPortRangeNumberOfPorts : 16384
AutomaticUseCustom : Disabled
NonSackRttResiliency : Disabled
ForceWS : Disabled
MaxSynRetransmissions : 2
SettingName : DatacenterCustom
MinRto(ms) : 20
InitialCongestionWindow(MSS) : 4
CongestionProvider : DCTCP
CwndRestart : True
DelayedAckTimeout(ms) : 10
DelayedAckFrequency : 2
MemoryPressureProtection : Enabled
AutoTuningLevelLocal : Normal
AutoTuningLevelGroupPolicy : NotConfigured
AutoTuningLevelEffective : Local
EcnCapability : Enabled
Timestamps : Disabled
InitialRto(ms) : 3000
ScalingHeuristics : Disabled
DynamicPortRangeStartPort : 49152
DynamicPortRangeNumberOfPorts : 16384
AutomaticUseCustom : Disabled
NonSackRttResiliency : Disabled
ForceWS : Disabled
MaxSynRetransmissions : 2
SettingName : Compat
MinRto(ms) : 300
InitialCongestionWindow(MSS) : 2
CongestionProvider : Default
CwndRestart : False
DelayedAckTimeout(ms) : 200
DelayedAckFrequency : 2
MemoryPressureProtection : Enabled
AutoTuningLevelLocal : Normal
AutoTuningLevelGroupPolicy : NotConfigured
AutoTuningLevelEffective : Local
EcnCapability : Enabled
Timestamps : Disabled
InitialRto(ms) : 3000
ScalingHeuristics : Disabled
DynamicPortRangeStartPort : 49152
DynamicPortRangeNumberOfPorts : 16384
AutomaticUseCustom : Disabled
NonSackRttResiliency : Disabled
ForceWS : Disabled
MaxSynRetransmissions : 2
SettingName : Datacenter
MinRto(ms) : 20
InitialCongestionWindow(MSS) : 4
CongestionProvider : DCTCP
CwndRestart : True
DelayedAckTimeout(ms) : 10
DelayedAckFrequency : 2
MemoryPressureProtection : Enabled
AutoTuningLevelLocal : Normal
AutoTuningLevelGroupPolicy : NotConfigured
AutoTuningLevelEffective : Local
EcnCapability : Enabled
Timestamps : Disabled
InitialRto(ms) : 3000
ScalingHeuristics : Disabled
DynamicPortRangeStartPort : 49152
DynamicPortRangeNumberOfPorts : 16384
AutomaticUseCustom : Disabled
NonSackRttResiliency : Disabled
ForceWS : Disabled
MaxSynRetransmissions : 2
SettingName : Internet
MinRto(ms) : 300
InitialCongestionWindow(MSS) : 4
CongestionProvider : CTCP
CwndRestart : False
DelayedAckTimeout(ms) : 50
DelayedAckFrequency : 2
MemoryPressureProtection : Enabled
AutoTuningLevelLocal : Normal
AutoTuningLevelGroupPolicy : NotConfigured
AutoTuningLevelEffective : Local
EcnCapability : Enabled
Timestamps : Disabled
InitialRto(ms) : 3000
ScalingHeuristics : Disabled
DynamicPortRangeStartPort : 49152
DynamicPortRangeNumberOfPorts : 16384
AutomaticUseCustom : Disabled
NonSackRttResiliency : Disabled
ForceWS : Disabled
MaxSynRetransmissions : 2
A:
You need to create the transport filter first, which specifies the TCP settings as a NetTcpSetting object, like in the example below.
New-NetTransportFilter -SettingName Custom -LocalPortStart 80 -LocalPortEnd 80 -RemotePortStart 0 -RemotePortEnd 65535
The Set-NetTCPSetting commandlet is used when you want to modify a setting. Hence why you're receiving the error regarding the custom object not found. After creating the transport filter, your original command to modify the settings should work.
Set-NetTCPSetting -SettingName Custom -InitialCongestionWindow 10 -CongestionProvider CTCP
| {
"pile_set_name": "StackExchange"
} |
Q:
how to rename and move files according to directory names?
I have bunch of directories containing the file with the same name. I want to move these files to another directory and at the same time renaming them with the directory name so that they are distinguished and are not over-written.
EDIT:
All the directories are in the same directory. Destination is one directory on the system which could be anything. We read directory and read file form it and rename it exactly as the directory name and put it to the destination.
An important constraint is that the name of the file is given which will be in all of the directories. Directories might contain other files bit also the one which is given
Thanks a lot
A:
Assuming the filename of these files are thefilename, you've cded to the directory containing these directories, and you want to move them to /path/to/dest, the following shell loop should do the trick
for file in */thefilename; do
echo mv -iv "./$file" "/path/to/dest/${file%/*}"
done
You can run that directly in an interactive shell, or put it in a file and run it as a script.
I added an echo to make it only print the mv commands. If the output looks correct, remove the echo and run it again to have it actually do the moving.
| {
"pile_set_name": "StackExchange"
} |
Q:
In how many ways can a number be expressed as a sum of consecutive numbers?
All the positive numbers can be expressed as a sum of one, two or more consecutive positive integers. For example $9$ can be expressed in three such ways, $2+3+4$, $4+5$ or simply $9$. In how many ways can a number be expressed as a sum of consecutive numbers?
In how many ways can this work for $65$?
Here, for $9$ answer is $3$, for $10$ answer is $3$, for $11$ answer is $2$.
A:
Here's one more way to calculate this, from my answer to this question on codegolf.SE:*
An integer $n$ is expressible as the sum of $m$ consecutive positive integers if and only if either:
$m$ is odd and $\frac nm$ is an integer, or
$m$ is even and $\frac nm + \frac12$ is an integer,
and $\frac nm \ge \frac m2$ (or else some of the integers in the sum would be zero or negative).
These conditions follow from the fact that the sum of an arithmetically increasing sequence of $m$ numbers equals $m$ times the mean of the numbers.
The last condition can be rewritten as $m \le \sqrt{2n}$. Thus, it's sufficient to iterate over all integers $m$ from $1$ to $\lfloor \sqrt{2n} \rfloor$ and check whether $\frac nm + \frac m2 + \frac12$ is an integer.
*) The entire Q&A thread has since been deleted; here's an archive.org copy for anyone curious.
A:
A sum of consecutive numbers is a difference of triangular numbers. The paper below gives a solution for the case of nonconsecutive triangular numbers.
Nyblom, M. A.
On the representation of the integers as a difference of nonconsecutive triangular numbers.
Fibonacci Quart. 39 (2001), no. 3, 256–263.
The main result is that the number of distinct representations of a nonzero integer $m$ as a difference of nonconsecutive triangular numbers is given by $d−1$, where $d$ is the number of odd divisors of $m$.
A:
Fix $k$. Is there a way that a number $N$ can be written in more than one way as a sum of $k$ consecutive number? Certainly not because
$$
a+(a+1)+\cdots+(a+k-1)\neq
b+(b+1)+\cdots+(b+k-1)
$$
if $a\neq b$. On the other hand $N$ is the sum of $k$ consecutive number if and only if $N$ is the form
$$
N=\frac12\left[(n+k)(n+k+1)-n(n+1)\right]
$$
for some $n$. Does that help?
| {
"pile_set_name": "StackExchange"
} |
Q:
Create boundary area in Google Maps using coordinates
I want to show an area boundary in Google maps using API v3. I've got a list of postcodes for the area that the client covers, I've converted these to LatLng coordinates and can create a polygon with them but as you would expect, it's a mess of lines and not a solid shape area.
Anyone know if this is possible and if so, how to do this? Or a different way of doing this. Code I'm using below:
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 55.921772, lng: -3.383983},
scrollwheel: false,
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl: true
});
// Define the LatLng coordinates for the polygon's path.
var triangleCoords = [
new google.maps.LatLng(55.948969,-3.1927988),
new google.maps.LatLng(55.949292,-3.209399),
new google.maps.LatLng(55.957032,-3.1850223),
new google.maps.LatLng(55.929196,-3.2089489),
new google.maps.LatLng(55.934519,-3.2131166),
new google.maps.LatLng(55.924534,-3.2096679),
new google.maps.LatLng(55.901564,-3.2035307),
new google.maps.LatLng(55.940591,-3.2170048),
new google.maps.LatLng(55.943847,-3.2184679),
new google.maps.LatLng(55.932823,-3.2462462),
new google.maps.LatLng(55.924084,-3.2938003),
new google.maps.LatLng(55.948636,-3.3239403),
new google.maps.LatLng(55.94727,-3.2158532),
new google.maps.LatLng(55.946459,-3.2359557),
new google.maps.LatLng(55.942119,-3.2790791),
new google.maps.LatLng(55.943678,-3.2820926),
new google.maps.LatLng(55.933458,-3.2867013),
new google.maps.LatLng(55.907231,-3.2498242),
new google.maps.LatLng(55.914285,-3.2391396),
new google.maps.LatLng(55.929872,-3.2483283),
new google.maps.LatLng(55.919613,-3.272673),
new google.maps.LatLng(55.913635,-3.2773089),
new google.maps.LatLng(55.953223,-3.1155757),
new google.maps.LatLng(55.951535,-3.1124523),
new google.maps.LatLng(55.944854,-3.1050555),
new google.maps.LatLng(55.931274,-3.1456767),
new google.maps.LatLng(55.938277,-3.1758846),
new google.maps.LatLng(55.919988,-3.1677619),
new google.maps.LatLng(55.907921,-3.1339982),
new google.maps.LatLng(55.899518,-3.1649876),
new google.maps.LatLng(55.955011,-3.1932569),
new google.maps.LatLng(55.953699,-3.1905739),
new google.maps.LatLng(55.951683,-3.2010498),
new google.maps.LatLng(55.951121,-3.2034185),
new google.maps.LatLng(55.877027,-3.1487295),
new google.maps.LatLng(55.943146,-3.0559971),
new google.maps.LatLng(55.943718,-3.047895),
new google.maps.LatLng(55.939247,-3.0130501),
new google.maps.LatLng(55.892996,-3.0728633),
new google.maps.LatLng(55.89186,-3.0692661),
new google.maps.LatLng(55.892996,-3.0728633),
new google.maps.LatLng(55.956248,-3.4049741),
new google.maps.LatLng(55.958401,-3.204173),
new google.maps.LatLng(55.953391,-3.2083257),
new google.maps.LatLng(55.947542,-3.2146128),
new google.maps.LatLng(55.943346,-3.2109749),
new google.maps.LatLng(55.945203,-3.2049162),
new google.maps.LatLng(55.973614,-3.3522429),
new google.maps.LatLng(55.959293,-2.9831886),
new google.maps.LatLng(55.958761,-3.2259363),
new google.maps.LatLng(55.958258,-3.2509238),
new google.maps.LatLng(55.954508,-3.2162083),
new google.maps.LatLng(55.969754,-3.2567425),
new google.maps.LatLng(55.965345,-3.2713865),
new google.maps.LatLng(55.966799,-3.2759201),
new google.maps.LatLng(55.961259,-3.2624101),
new google.maps.LatLng(55.960523,-3.3189479),
new google.maps.LatLng(55.980282,-3.2222259),
new google.maps.LatLng(55.970837,-3.2150703),
new google.maps.LatLng(55.972055,-3.1971305),
new google.maps.LatLng(55.977169,-3.1812151),
new google.maps.LatLng(55.970188,-3.1726547),
new google.maps.LatLng(55.970989,-3.1715573),
new google.maps.LatLng(55.9706,-3.1709047),
new google.maps.LatLng(55.969318,-3.1629671),
new google.maps.LatLng(55.958457,-3.1835442),
new google.maps.LatLng(55.954315,-3.1853397),
new google.maps.LatLng(55.956023,-3.1607265),
new google.maps.LatLng(55.955162,-3.15005),
new google.maps.LatLng(55.950521,-3.1836543),
new google.maps.LatLng(55.94698,-3.1866047),
new google.maps.LatLng(55.934593,-3.1935895),
new google.maps.LatLng(55.934464,-3.1948181),
new google.maps.LatLng(55.930516,-3.1756174),
new google.maps.LatLng(55.97862,-3.2535203),
new google.maps.LatLng(55.951962,-3.1749222)
];
// Construct the polygon.
var areaCovered = new google.maps.Polygon({
paths: triangleCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.25
});
areaCovered.setMap(map);
}
</script>
A:
Okay here is that code example I promised. This will give you a square/rectangle polygon that contains all the points in triangleCoords.
// create new LatLngBounds
var bounds = new google.maps.LatLngBounds();
// extend bounds to contain each coordinate
for (var i = 0, i_end = triangleCoords.length; i < i_end; i++) {
bounds.extend(triangleCoords[i]);
}
// get the NSEW corners of the bounds
var NE = bounds.getNorthEast();
var SW = bounds.getSouthWest();
var SE = { lat: SW.lat(), lng: NE.lng() };
var NW = { lat: NE.lat(), lng: SW.lng() };
// Construct the polygon.
var areaCovered = new google.maps.Polygon({
paths: [NE, SE, SW, NW],
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.25
});
areaCovered.setMap(map);
I also wanted to clarify why your code was creating a mess of lines. A polygon will construct its boundary based on the order of the coordinates you supply it. To get an idea of what I'm talking about you can change the order in my example to this paths: [NE, SW, SE, NW].
To give you a visual, you can think of it like the game of connect the dots. If you didn't connect these dots in order you would end up with a mess of lines instead of a cute laughing Pikachu.
| {
"pile_set_name": "StackExchange"
} |
Q:
When does the 'Your turn begins' phase end?
Does a "when your turn begins" action trigger if the card is not in play during the "turn begins" phase but comes into play during the phase?
For example "the supplier" hosting a "drug dealer".
A:
The "turn begins" trigger happens only once (at step 1.2 of the corp/runners turn according to the timing structure chart). So a card installed when the triggers resolve would not itself trigger.
This is also separately clarified for The Supplier in the official FAQ (https://images-cdn.fantasyflightgames.com/ffg_content/android-netrunner/support/FAQ/Android-Netrunner%20FAQ.pdf) in the card clarification section.
56 The Supplier
The Runner cannot use any “when your turn begins”
abilities on cards that are installed by The Supplier until his next
turn
| {
"pile_set_name": "StackExchange"
} |
Q:
How to canonise a road network
I am working on geographical data which represents the road network of some city and I need to automatically fix inaccuracies in the data.
Data was manually produced by “drawing” the road network over some actual map overlay with a geographical system like qgis. As a result, many road portions which connect in reality are not connected in the data, that is, endpoints of connected roads might be off by a few centimeters or sometimes a few meters.
As a result, the road network is “wrongly” digitized as a graph or combinatorial object—that is, the simple algorithm assuming that roads are connected when they have a common endpoint is too optimistic and misses a lot of connections. How can I process and fix the geographic data to recover the correct combinatorial road network?
A:
I had to perform the treatment you describe on the road network of German city (about 200.000 inhabitants). I devised a procedure that produced great results: the road network has over 2000 road portions and about 200 connection failures and the procedure was able to fix automatically 95% of the failures and to mark the remaining ones as “requiring attention”. There were so few of them that manual editing was affordable.
Let me now go into the details.
Wishlist
We want to build a procedure which, given the set M of missing or faulty connections,
detects and fixes automatically a large subset A of M
detects problematic places P in the network that require manual treatment.
We want to conduct step 1. without producing any false positive i.e. without introducing non-existant connections, i.e. enforcing the condition “A is a subset of M”.
We want to conduct step 2. so that all of M is in the union of A and P. It is fine to have false positives here, as long as the ratio ”false positive / true positive” remains low.
Algorithm
The input is a road network R, i.e. a list of road portions (broken lines) represented by the list of their vertices. (This is what is stored in ESRI files.)
The output is an amended road network S together with a list P of places (points) requiring manual treatment.
Choose two thresholds α = 2.5m and β = 20m
Replace R by an equivalent network where road portions can only cross at a vertex and where if two road portions have points whose distance is smaller than α then they have two vertices whose distance is smaller than α. This is achieved by introducing supplementary vertices in the descriptions of road portions.
Go through all the vertices of all the road portions of the road network and create equivalence classes for the relation A “vertices are closer than α” and B ”vertices are closer than β”.
To each equivalence class of A associate a point (e.g. center of mass) and replace each member of the class by that point. The result is the final network S.
To each equivalence class of B not reduced to a point associate a point (e.g. center of mass), the list of points thus obtained is P.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there any way to use a member function of a class to run in a concurrent thread without passing *this in C++11?
I'm a novice in C++11 threading and trying use a member function of a class to run in concurrent threads.
In the answer to my earlier question I received the suggestion:
std::thread t1(&SomeClass::threadFunction, *this, arg1, arg2);
I implemented the above suggestion. It removed the compile error I was having but introduced a runtime error. In another question I received the suggestion to remove all copy mechanism. Actually, I don't want to copy the data, because the code is for Finite Element Analysis and require a lot of memory.
Is There any way I can do this?
The header is similar to the following.
SomeClass {
vector<int*> someVariable;
public:
~SomeClass();
void threadedMethod(bool, bool); // Inside this method the
// member vector 'someVariable' is used.
void someMethod(); // In this function the threadedMethod has
// been used twice to make 2 different thread
};
The someMethod implementation is,
void SomeClass::someMethod() {
thread t1(&SomeClass::threadedMethod, *this, arg1, arg2);
thread t2(&SomeClass::threadedMethod, *this, arg1, arg2);
t2.join();
t1.join();
}
The destructor is similar to the following,
SomeClass::~SomeClass() {
int count = someVariable.size();
for(int i=0; i < count; i++) {
delete someVariable[i];
}
}
The threadMethod accesses the variable. The operations are data parallel. As a result, no thread will write in the same memory block. Again, the read and write memory is different. There for I think I don't need any kind of locks.
As you can see, I am using *this and that is causing a lot of copy. I really need to avoid it. Can any one kindly suggest any other way which will let me avoid the copying?
If you need more explanation please let me know. If within my ability I'll try to elaborate as much as possible.
I am using an Intel Mac with OS X 10.8.3. I'm coding on Xcode 4.6.1. The compiler is Apple LLVM 4.2 (default compiler).
A:
Arguments are passed by value to the constructor of std::thread. Therefore, this statement:
std::thread t1(&SomeClass::threadFunction, *this, arg1, arg2);
// ^^^^^
Triggers a copy of *this, which is not what you want. However, std::thread can also accept a pointer to the object on which the member function shall be invoked, exactly like std::bind.
Therefore, by passing this (instead of *this) as an argument, it is the pointer - instead of the pointed object - that is going to be passed by value and eventually copied. This will trigger no copy construction of SomeClass, as you desire.
Thus, you should rewrite the above statement as follows:
std::thread t1(&SomeClass::threadFunction, this, arg1, arg2);
// ^^^^
| {
"pile_set_name": "StackExchange"
} |
Q:
how to create instance for a generic type in c#
I need to create an parameterless instance for a Generic Class in C#.
How to do this.
A:
You could add the : new() constraint:
void Foo<T>() where T : class, new() {
T newT = new T();
// do something shiny with newT
}
If you don't have the constraint, then Activator.CreateInstance<T> may help (minus the compile-time checking):
void Foo<T>() {
T newT = Activator.CreateInstance<T>();
// do something shiny with newT
}
If you mean you the type itself, then probably something like:
Type itemType = typeof(int);
IList list = (IList)Activator.CreateInstance(
typeof(List<>).MakeGenericType(itemType));
| {
"pile_set_name": "StackExchange"
} |
Q:
java.lang.NoClassDefFoundError in cmd
I am facing this problem while trying to run my java file by writing java filename ....
I have read on many pages the possible ways this could be corrected but unfortunately I have been unable to correct my problem...
First of all I looked at my environment variables and observed that there was no CLASSPATH set and I had pointed PATH correctly to my jre as well as jdk bin in C:\
Second I am able to run javac filename.java and observe that .class file gets built in the local directory.
While writing javac -classpath . filename works writing java -classpath . filename (without .class) results in the same error.
I just don't know how to run my program in command prompt!!!!
Please do not give me links to the pages which have given the same answers that I have mentioned above as they do not work in my case.....
Please help....
A:
Note that if your class resides in some package mypackage, you need to make sure the class file is inside mypackage/ and do
java -classpath . mypackage.YourClass
| {
"pile_set_name": "StackExchange"
} |
Q:
how to increment the iterator from inside for loop in python 3?
for i in range (0, 81):
output = send command
while True:
last_byte = last_byte - offset
if last_byte > offset:
output = send command
i+
else:
output = send command
i+
break
I want to increase the iterator every time the send command is executed. Right now it only increases by one when the for loop is executed. Please advise
for i in range(0,10):
print(i)
i +=2
print("increased i", i)
I ran this code and it produced out from 0 to 9. I was expecting it would increase the iterator by 2.
A:
Save a copy of the iterator as a named object. Then you can skip ahead if you want to.
>>> myiter = iter(range(0, 10))
>>> for i in myiter:
print(i)
next(myiter, None)
...
0
2
4
6
8
A:
You can't do that inside a for loop. Because every time that the loop gets restarted it reassign the variable i (even after you change it inside the loop) and every time you just increase the reassigned variable. If you want to do such thing you better to use a while loop and increase the throwaway variable manually.
>>> i=0
>>> while i< 10 :
... print(i)
... i +=2
... print("increased i", i)
...
0
('increased i', 2)
2
('increased i', 4)
4
('increased i', 6)
6
('increased i', 8)
8
('increased i', 10)
Beside that, if you want to increase the variable on a period rather than based some particular condition, you can use a proper slicers to slice the iterable in which you're looping over.
For instance if you have an iterator you can use itertools.islice() if you have a list you can simply use steps while indexing (my_list[start:end:step]).
| {
"pile_set_name": "StackExchange"
} |
Q:
Ant run command with pipes
I must to implement command : java -jar test.jar page.xml | mysql -u user -p base
in ant. So i Have tried with this task:
<java jar="test.jar" fork="true">
<arg line="page.xml | mysql -u user -p base"/>
</java>
But i have got en exception with pipe - "|" :
java.lang.IllegalArgumentException: Input already set; can't set to |
So, that's the problem:)
A:
The pipe (|) can only be used in a shell script. You're passing it as an argument to the java process.
So you need to execute a shell script. You can do this by executing (say) bash -c and passing the above as a shell statement (albeit inline - you could write a separate script file but it seems a bit of an overhead here)
<exec executable="bash">
<arg value="-c"/>
<arg line="java -jar test.jar page.xml | mysql -u user -p base"/>
</exec>
A:
I don't know if this was ever resolved, but I was having a similar problem which I solved by using the following:
<exec executable="bash">
<arg value="-c"/>
<arg line='"java -jar test.jar page.xml | mysql -u user -p base"'/>
</exec>
Just thought I would share.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to take consistent screenshots across multiple machines?
I have some OpenGL based software and I would like to set up some automated testing using image comparison, but one problem we always have is that the screenshots we take always have some small differences across machines, usually due to graphics driver difference or something else (?).
What strategies are there for getting consistent screenshots across machines with varying hardware and graphics drivers?
A:
Nicol Bolas explains why you can't expect pixel-accurate reproductions, but that doesn't mean you can't test with screenshots.
Don't compare the screenshots byte-for-byte. Instead, use a perceptual diff to quantify how different the renders are. You can then set a threshold in your test and have the test fail if the renders are too different. A harsh threshold will let you filter out the rounding differences between platforms, and the slight differences around object silhouettes, but still detect objects in the wrong place or inconsistent texturing. A more forgiving threshold will allow bigger differences in texturing (or even with different shader versions or extensions, if you have different rendering paths for different hardware), and only complain if you have gross differences such as missing lights or a completely different scene being rendered.
The pdiff tool is commonly used for this task, and I've set up test systems based on it before.
| {
"pile_set_name": "StackExchange"
} |
Q:
Connecting More than one device ussing gameKit framework
I am using GameKit framework for bluetooth connectivity between devices and then sending and receiving data.My problem is how to connect more than one device using Gamekit.I spend almost one week in searching on internet, but got nothing except questions posted with no answer.
Please suggest me that how can I connect more than one device or any link or tutorial which I can follow.
Any help would be highly appreciated!
A:
Try this Apple documentation its very helpful.
http://developer.apple.com/library/ios/#documentation/NetworkingInternet/Conceptual/GameKit_Guide/Introduction/Introduction.html
| {
"pile_set_name": "StackExchange"
} |
Q:
UIPopover Controller dismissal
I have a doubt.
When dismissing a Popover Controller does the initWithContentViewController object gets released? For Example:
UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:content];
Does the content gets released here?
A:
Yes. initWithContentsViewController increments the retain count by 1, ARC or non-ARC. Dismissing the popOver will decrement the retain count by 1.
| {
"pile_set_name": "StackExchange"
} |
Q:
return the array position where two strings are different
I am trying to check whether the position in the array where the two strings are different. For example if I have the String apple and the string appendix then the two string are different at the position where i = 3.
How can I check that with Java?
Code
//The first string is s.
char[] cArray = s.toCharArray();
// The seond string is root.edge.
char[] rootEdgeCharacter = root.edge.toCharArray();
for(int i=0; i<cArray.length; i++ ){
for(int j=0; j<rootEdgeCharacter.length; j++){
if(cArray[i]== rootEdgeCharacter[j]){
System.out.println("The String are different where i =" + i);
}
}
}
A:
Don't use .toCharArray(), it needlessly creates a new character array. Use .charAt() instead.
What is more, your code will not walk arrays "in parallel": you iterate at indices 0, 0 then 1, 0, then 3, 0 etc. This is not what you want.
Here is one solution; note that for string of inequal length it will return the smaller length, and it both strings are equal it returns -1:
public static int findDifferingIndex(final String s1, final String s2)
{
final int len1 = s1.length();
final int len2 = s2.length();
final int len = Math.min(len1, len2);
for (int index = 0; index < len; index++)
if (s1.charAt(index) != s2.charAt(index))
return index;
// Check the length of both strings; if they are equal, return -1.
// Otherwise return the length `len`.
return len1 == len2 ? -1 : len;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
UPDATE column using a result from SELECT subquery
This query returns an error : "Subquery returns more than one row":
UPDATE forums as f
SET f.f_last_pid = (SELECT pid FROM posts ORDER BY ptime DESC )
I know that i need to use ANY before the subquery but that won't get the proper result I want. I want to update every row in my forums table based on the result shown from the subquery.
A:
UPDATE forums as f
SET f.f_last_pid =
(SELECT pid FROM posts ORDER BY ptime DESC LIMIT 1 )
But (without really knowing your schema), you're not joining these tables on anything. Every last_pid in forums would be updated by the last post in posts
| {
"pile_set_name": "StackExchange"
} |
Q:
Select count paid order by user in the same table
If example I have this table
-----------------
|ID|user_no|paid|
|---------------|
|1 |1 |yes |
|2 |1 |yes |
|3 |1 |no |
|4 |2 |yes |
|5 |2 |no |
|---------------|
I want the result to be
-----------------------------
|ID|user_no|order_paid_count|
|---------------------------|
|1 |1 |2 |
|2 |1 |2 |
|3 |1 |2 |
|4 |2 |1 |
|5 |2 |1 |
|---------------------------|
I do the query like this, but it doesnt work.. it loading so long and didnt come out result, its like loop infinity
SELECT o1.*, (SELECT COUNT(*) FROM order AS o2 WHERE o1.user_no=o2.user_no AND o2.paid=yes) as order_paid_count
FROM order as o1
A:
Have a sub-query that counts each user_no's number of paid orders. LEFT JOIN with that result:
select o1.id, o1.user_no, o2.order_paid_count
from order as o1
left join (select user_no, count(*) as order_paid_count
from order
where paid = 'yes'
group by user_no) as o2
on o1.user_no = o2.user_no
(LEFT JOIN to include also user_no's with no paid orders at all.)
| {
"pile_set_name": "StackExchange"
} |
Q:
shell script if else loop not working
Given the following programme which reads in user input twice
function search_grep
{
if [ "$2" == "" ];then
for x in "${title[@]}"
do
value=$(echo $x | grep "$1")
if [ "$value" != "" ];then
echo "$value"
fi
done
elif [ "$1" == "" ];then
hello="123"
echo "$hello"
fi
}
echo -n "Enter title : "
read book_title
echo -n "Enter author : "
read author
title=(CatchMe HappyDay)
search_grep $book_title $author
it works as expected when i enter followed by HappyDay HOWEVER
When i enter foo followed by , I would expect console output to be
123
instead I am getting
Can someone explain to me , the programme is not executing the second elif loop though second input is
A:
In both of your cases cases, the following:
search_grep $book_title $author
expands to a call with a single argument. Hence, the "then" clause is activated. The reason is that an unquoted argument consisting of whitespace expands to nothing and disappears. That is the way of bash.
If you want to pass search_grep two arguments, then you need to quote the variables:
search_grep "$book_title" "$author"
| {
"pile_set_name": "StackExchange"
} |
Q:
AVD Creation of Android 4.0 (Ice Cream Sandwich) for windows
Android 4.0 is released now. Where can i get that ADT Plugin for android 4.0. And, also where can i get the Android 4.0's SDK.
I'm using Eclipse for developing the android. I just googling about this but i got answer for linux Where can i get these things for Eclipse using Windows OS. Anyone guid me? Thanks in advance.
A:
Yo are using the Eclipse so ,For 4.0 SDK trace Window>AndroidSdkManager > AvailablePackages >then Select the Platform 14 . it will update your Sdk .
After updating your Sdk you need to update the ADT Plugin .For that trace Help >CheckForUpdate . then select the ADT for platform 14.
| {
"pile_set_name": "StackExchange"
} |
Q:
Number elements in a list
I'm trying to learn more about list replacement without using Table. I have a list like this:
list = {{{"a", "b", "c"}, {"d", "e", "f"}, {"g", "h", "i"}}}
Now, I want to modify the list elements, i.e. add the position of the respective elements in front of it and replace every element in the list with that:
listMod = {{{1->"a", 2->"b",3->"c"}, {1->"d", 2->"e", 3->"f"}, {1->"g", 2->"h", 3->"i"}}}
A:
list = {{{"a", "b", "c"}, {"d", "e", "f"}, {"g", "h", "i"}}};
Map[MapIndexed[First@#2 -> #1 &], #, {2}] &@list
(* Out: {{{1 -> "a", 2 -> "b", 3 -> "c"}, {1 -> "d", 2 -> "e", 3 -> "f"},
{1 -> "g", 2 -> "h", 3 -> "i"}}} *)
A:
list = {{{"a", "b", "c"}, {"d", "e", "f"}, {"g", "h", "i"}}};
Apply[Rule, Map[Transpose[{Range@3, #}] &, list, {2}], {3}]
Or, more generally
num[v_] := Thread[Range@Length@v -> v]
num /@ Catenate@list
Or
Normal @ Map[PositionIndex, list, {2}] /. (a_ -> {b_}) :> b -> a
A:
MapIndexed[#2[[3]] -> #1 &, list, {3}]
{{{1 -> "a", 2 -> "b", 3 -> "c"}, {1 -> "d", 2 -> "e",
3 -> "f"}, {1 -> "g", 2 -> "h", 3 -> "i"}}}
Original answer
Map[Thread[Range@Length@# -> #] &, list, {2}]
MapIndexed[#2[[3]] -> #1 &, list, {3}] ==
Map[Thread[Range@Length@# -> #] &, list, {2}] == listMod
True
| {
"pile_set_name": "StackExchange"
} |
Q:
Application font size dosn't change
I'm working on an application that can change the device font size. When I change the font size from my application, the change applies to the whole device and other applications but not itself. I haven't set font sizes in dp. What causes this problem?
A:
Finally, I found the problem. I had used
implementation 'androidx.appcompat:appcompat:1.1.0'
changed its version to 1.0.2 and it solved.
I reported this issue to google: https://issuetracker.google.com/issues/144151376
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I build a tokenizing regex based iterator in python
I'm basing this question on an answer I gave to this other SO question, which was my specific attempt at a tokenizing regex based iterator using more_itertools's pairwise iterator recipe.
Following is my code taken from that answer:
from more_itertools import pairwise
import re
string = "dasdha hasud hasuid hsuia dhsuai dhasiu dhaui d"
# split according to the given delimiter including segments beginning at the beginning and ending at the end
for prev, curr in pairwise(re.finditer(r"^|[ ]+|$", string)):
print(string[prev.end(): curr.start()]) # originally I yield here
I then noticed that if the string starts or ends with delimiters (i.e. string = " dasdha hasud hasuid hsuia dhsuai dhasiu dhaui d ") then the tokenizer will print empty strings (these are actually extra matches to string start and string end) in the beginning and end of its list of token outputs so to remedy this I tried the following (quite ugly) attempts at other regexes:
"(?:^|[ ]|$)+" - this seems quite simple and like it should work but it doesn't (and also seems to behave wildly different on other regex engines) for some reason it wouldn't build a single match from the string's start and the delimiters following it, the string start somehow also consumes the character following it! (this is also where I see divergence from other engines, is this a BUG? or does it have something to do with special non corporeal characters and the or (|) operator in python that I'm not aware of?), this solution also did nothing for the double match containing the string's end, once it matched the delimiters and then gave another match for the string end ($) character itself.
"(?:[ ]|$|^)+" - Putting the delimiters first actually solves one of the problems, the split at the beginning doesn't contain string start (but I don't care too much about that anyway since I'm interested in the tokens themselves), it also matches string start when there are no delimiters at the beginning of the string but the string ending is still a problem.
"(^[ ]*)|([ ]*$)|([ ]+)" - This final attempt got the string start to be part of the first match (which wasn't really that much of a problem in the first place) but try as I might I couldn't get rid of the delimiter + end and then delimiter match problem (which yields an additional empty string), still, I'm showing you this example (with grouping) since it shows that the ending special character $ is matched twice, once with the preceding delimiters and once by itself (2 group 2 matches).
My questions are:
Why do I get such a strange behavior in attempt #1
How do I solve the end of string issue?
Am I being a tank, i.e. is there a simple way to solve this that I'm blindly missing?
remember that the solution can't change the string and must
produce an iterable generator which iterates on the spaces between the tokens and not the tokens themselves (This last part might seem to complicate the answer unnecessarily since otherwise I have a simple answer but if you must know (and if you don't read no further) it's part of a bigger framework I'm building where this yielding method is inherited by a pipeline which then constructs yielded sentences out of it in various patterns which are used to extract fields from semi structured classifier driven messages)
A:
The problems you're having are due to the trickiness and undocumented edge cases of zero-width matches. You can resolve them by using negative lookarounds to explicitly tell Python not to produce a match for ^ or $ if the string has delimiters at the start or end:
delimiter_re = r'[\n\- ]' # newline, hyphen, or space
search_regex = r'''^(?!{0}) # string start with no delimiter
| # or
{0}+ # sequence of delimiters (at least one)
| # or
(?<!{0})$ # string end with no delimiter
'''.format(delimiter_re)
search_pattern = re.compile(search_regex, re.VERBOSE)
Note that this will produce one match in an empty string, not zero, and not separate beginning and ending matches.
It may be simpler to iterate over non-delimiter sequences and use the resulting matches to locate the string components you want:
token = re.compile(r'[^\n\- ]+')
previous_end = 0
for match in token.finditer(string):
do_something_with(string[previous_end:match.start()])
previous_end = match.end()
do_something_with(string[previous_end:])
The extra matches you were getting at the end of the string were because after matching the sequence of delimiters at the end, the regex engine looks for matches at the end again, and finds a zero-width match for $.
The behavior you were getting at the beginning of the string for the ^|... pattern is trickier: the regex engine sees a zero-width match for ^ at the start of the string and emits it, without trying the other | alternatives. After the zero-width match, the engine needs to avoid producing that match again to avoid an infinite loop; this particular engine appears to do that by skipping a character, but the details are undocumented and the source is hard to navigate. (Here's part of the source, if you want to read it.)
The behavior you were getting at the start of the string for the (?:^|...)+ pattern is even trickier. Executing this straightforwardly, the engine would look for a match for (?:^|...) at the start of the string, find ^, then look for another match, find ^ again, then look for another match ad infinitum. There's some undocumented handling that stops it from going on forever, and this handling appears to produce a zero-width match, but I don't know what that handling is.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using xxdiff with svn diff command on Unix
I've tried using the command
svn diff --diff-cmd xxdiff some_file.cpp
But it gives me the error message "invalid option -- u"
After some googling, I tried using the "extensions", and setting it to blank, like this:
svn diff --extensions "" --diff-cmd xxdiff some_file.cpp
To get rid of the 'u', which worked, but then xxdiff complained about a "-L" option. How can I get this to work?
A:
To figure out exactly what was being passed to svn diff, I created a one line script in my local directory called 'svn-xxdiff' which only has one line: "echo $@", and then ran it as follows:
svn diff --diff-cmd ./svn-xxdiff some_file.cpp
This showed me that the arguments being passed to xxdiff were as follows:
-u -L some_file.cpp (revision 1234) -L some_file.cpp (working copy) .svn/text-base/some_file.cpp.svn-base some_file.cpp
Note: "some_file.cpp (revision 1234)" is considered a single argument, I imagine it's because it comes after "-L", please correct me if I'm wrong.
With this information, I created a really quick workaround. In my svn-xxdiff script, I just changed "echo $@" to:
xxdiff --title1 "$3" --title2 "$5" $6 $7
Pop that file into a $PATH directory (like /bin/) and you should be able to use xxdiff with svn, and the titles will reflect appropriately. I'm not sure how I'd modify this script for a 3-way diff, I have less experience with those, but if others would like to suggest a modification for that, please do.
| {
"pile_set_name": "StackExchange"
} |
Q:
What can I do if I require more memory than there is on the heap in Java?
I have a graph algorithm that generates intermediate results associated to different nodes. Currently, I have solved this by using a ConcurrentHashMap<Node, List<Result> (I am running multithreaded). So at first I add new results with map.get(node).add(result) and then I consume all results for a node at once with map.get(node).
However, I need to run on a pretty large graph where the number of intermediate results wan't fit into memory (good old OutOfMemory Exception). So I require some solution to write out the results on disk—because that's where there is still space.
Having looked at a lot of different "off-heap" maps and caches as well as MapDB I figured they are all not a fit for me. All of them don't seem to support Multimaps (which I guess you can call my map) or mutable values (which the list would be). Additionally, MapDB has been very slow for me when trying to create a new collection for every node (even with a custom serializer based on FST).
I can barely imagine, though, that I am the first and only to have such a problem. All I need is a mapping from a key to a list which I only need to extend or read as a whole. What would an elegant and simple solution look like? Or are there any existing libraries that I can use for this?
Thanks in advance for saving my week :).
EDIT
I have seen many good answers, however, I have two important constraints: I don't want to depend on an external database (e.g. Redis) and I can't influence the heap size.
A:
You can increase the size of heap. The size of heap can be
configured to larger than physical memory size of your server while
you make sure the condition is right:
the size of heap + the size of other applications < the size of physical memory + the size of swap space
For instance, if the physical memory is 4G and the swap space is 4G,
the heap size can be configured to 6G.
But the program will suffer from page swapping.
You can use some database like Redis. Redis is key-value
database and has List structure.
I think this is the simplest way to solve your problem.
You can compress the Result instance. First, you serialize the
instance and compress that. And define the class:
class CompressResult {
byte[] result;
//...
}
And replace the Result to CompressResult. But you should deserialize
the result when you want to use it.
It will work well if the class Result has many fields and is very
complicated.
| {
"pile_set_name": "StackExchange"
} |
Q:
Deleting a selected item on ListView in javafx
I have an ListView with items, and developed a delete function which deletes the item. The problem Im facing is when I delete an item, the item below gets deleted as well.
To give you a better understanding. ex:
If I have 5 items in a list and I select and delete "item 2", then item 2 & 3 gets deleted. And items 1, 4 & 5 remains on the list view. If I delete the last item on the list then the item gets deleted and I get a java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
Here is my code:
public void handleDeleteButton() {
btnDelete.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
final int selectedIdx = playerList.getSelectionModel().getSelectedIndex();
if (selectedIdx != -1) {
String itemToRemove = playerList.getSelectionModel().getSelectedItem();
final int newSelectedIdx =
(selectedIdx == playerList.getItems().size() - 1)
? selectedIdx - 1
: selectedIdx;
playerList.getItems().remove(selectedIdx);
playerList.getSelectionModel().select(newSelectedIdx);
//removes the player for the array
System.out.println("selectIdx: " + selectedIdx);
System.out.println("item: " + itemToRemove);
players.remove(selectedIdx);
}
}
});
}
I want only the selected item to be deleted. How do I do that? And how do you make the table multi selectable?
players is the list of players used in the ListView.
A:
You remove 2 items from the list using the following lines:
playerList.getItems().remove(selectedIdx);
// ^ this should return players
players.remove(selectedIdx);
Remove one of them.
To allow multiple selection, set MultipleSelectionModel.selectionMode to SelectionMode.MULTIPLE.
| {
"pile_set_name": "StackExchange"
} |
Q:
Having Multiple SetStates() in a Gesture Detector?
I can't get the set state to change in multiple areas from an onTap VoidCallback?
I have two AnimationController in different stateful widgets. What I would like to implement is that if controller1.value == 0.0 then it'll make sure that when onTap that the controller2.value == 1.0 and visa versa for if controller1.value == 1.0.
StatefulWidget bottom layer (passes the widget.onTapOpen/closed to the top layer)
onTap: () {
_toggleExpandingSheetPanelVisibility();
setState(() {
if (_controller1.value == 0.0){
widget.onTapOpen();
}
else if (_controller1.value == 1.0){
widget.onTapClosed();
}
});
},
StatefulWidget top layer
onTapOpen: _ensureVisible,
onTapClosed: _ensureInvisible,
void _ensureVisible() {
setState(() {
if (_controller2.value == 0.0) {
_toggleVisibility();
}
});
}
void _ensureInvisible() {
setState(() {
if (_controller2.value == 1.0) {
_toggleVisibility();
}
});
}
A:
It worked when if (_controller2.value > or < 0.5) then it would toggle the visibility.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to tell a user at the gym that it's not OK to use one machine and “reserve” another one?
The following situation has happened to me several times:
A user in the gym is using some machine or equipment (a bench, a row machine, a bar, etc.). When I'm going to use another machine or equipment that it's apparently free, this user comes quickly and says "Sorry, I'm also using this machine". It usually happens when the user is doing some kind of combined exercises (for instance, doing a bench press and then immediately afterwards, using the cable row machine to "finish" their chest).
To me, the user isn't really using both machines, but instead, they are using one machine and "reserving" the use of another one (sometimes the user "marks" this machine as reserved by putting a barbell or a small towel over it), and I have the impression that this is not a legit action with regards to the use of a gym's piece of equipment, because one person can only use one machine at a time, and preventing other users to use other machines just because they are happening to be doing a combined exercise is not fair for other users, which don't deserve to wait. So in these situations I think I would perfectly be entitled to refuse to leave the "reserved" machine, remove the item set by the other user to mark the machine and, at most, I could offer the user to share the machine with me.
How could I explain my point to the other user in the least confrontational way?
A:
It might be helpful for a future encounter with such a person to do a little digging ahead of time.
I would ask the gym for their terms of use and gym etiquette policy. Most gyms will have such a document, and it often does state that gym users are only allowed to use one machine at a time, kind of similar to a fair usage policy. Often there are posters placed around the gym as well.
If something like this happens again, and the gym does have a policy of no equipment reservations, you can simply refer the person to the gym policies. I might say something like:
This gym’s policy for equipment usage is no reservations. I would like to use this machine right now. I'm planning on spending x amount of time on it and then you can use it after me.
I tend to be a more direct person and I like to state my case simply, clearly, and directly. If the person has an issue with this you can direct them to the staff and the rules of the facility.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python: remove repeated values only if at end of list
I have a python list where order of responses is important. I would like to filter out nan values only if they occur at the end of the list. I was wondering if there is an efficient way to go from a list like the following:
nan = float("nan")
responses = [1.0, nan, 9.0, nan, nan, nan, nan, nan, nan, nan, nan]
To a list without any trailing nan values:
[1.0, nan, 9.0]
I know how to filter out all nan values using a list comprehension:
import pandas as pd
[r for r in responses if pd.notnull(r)]
>>> [1.0, 9.0]
But can't think of a straightforward way to filter out nan values at the end without converting everything to strings and using regular expressions. I could do that, but am concerned about performance, which is an issue because it will be performed several hundred thousand times.
A:
while responses and math.isnan(responses[-1]):
responses.pop()
Update: this isn't as fast as a straight up slice.
>>> timeit.timeit('responses = list(r)\nwhile responses and isnan(responses[-1]): responses.pop()', 'from math import isnan; nan = float("nan"); r = [1.0, nan, 9.0, nan, nan, nan, nan, nan, nan, nan, nan]')
1.3209394318982959
>>> timeit.timeit('responses = list(r)\nresponses = responses[:3]', 'from math import isnan; nan = float("nan"); r = [1.0, nan, 9.0, nan, nan, nan, nan, nan, nan, nan, nan]')
0.29652016144245863
| {
"pile_set_name": "StackExchange"
} |
Q:
Can't find strings that aren't words in Django Haystick/Elasticsearch
I'm using Django Haystack with Elasticsearch as the backend for a real-time flight mapping service.
I have all my search indexes set up correctly, however, I'm having trouble returning results for searches that aren't full words (such as aviation callsigns, some of which take the style N346IF, others include full words such as in Speedbird 500). The N346IF style of query doesn't yield any results, whereas I can easily return results for the latter example.
I make my query as below:
queryResults = SearchQuerySet().filter(content=q) # where q is the query in string format
(note that in the past I used the AutoQuery queryset, but the documentation lists that this only tracks words, so I'm passing a raw string now).
I have my search index fields setup as EdgeNgramField with search templates.
I have a custom backend with the following index settings (as well as both the snowball analyzer and the pattern analyzer):
ELASTICSEARCH_INDEX_SETTINGS = {
'settings': {
"analysis": {
"analyzer": {
"ngram_analyzer": {
"type": "custom",
"tokenizer": "lowercase",
"filter": ["haystack_ngram"]
},
"edgengram_analyzer": {
"type": "custom",
"tokenizer": "lowercase",
"filter": ["haystack_edgengram"]
}
},
"tokenizer": {
"haystack_ngram_tokenizer": {
"type": "nGram",
"min_gram": 4,
"max_gram": 15,
},
"haystack_edgengram_tokenizer": {
"type": "edgeNGram",
"min_gram": 4,
"max_gram": 15,
"side": "front"
}
},
"filter": {
"haystack_ngram": {
"type": "nGram",
"min_gram": 4,
"max_gram": 15
},
"haystack_edgengram": {
"type": "edgeNGram",
"min_gram": 4,
"max_gram": 15
}
}
}
}
}
ELASTICSEARCH_DEFAULT_ANALYZER = "pattern"
My backend is configured as:
class ConfigurableElasticBackend(ElasticsearchSearchBackend):
def __init__(self, connection_alias, **connection_options):
super(ConfigurableElasticBackend, self).__init__(
connection_alias, **connection_options)
user_settings = getattr(settings, 'ELASTICSEARCH_INDEX_SETTINGS')
if user_settings:
setattr(self, 'DEFAULT_SETTINGS', user_settings)
class ConfigurableElasticBackend(ElasticsearchSearchBackend):
DEFAULT_ANALYZER = "pattern"
def __init__(self, connection_alias, **connection_options):
super(ConfigurableElasticBackend, self).__init__(
connection_alias, **connection_options)
user_settings = getattr(settings, 'ELASTICSEARCH_INDEX_SETTINGS')
user_analyzer = getattr(settings, 'ELASTICSEARCH_DEFAULT_ANALYZER')
if user_settings:
setattr(self, 'DEFAULT_SETTINGS', user_settings)
if user_analyzer:
setattr(self, 'DEFAULT_ANALYZER', user_analyzer)
def build_schema(self, fields):
content_field_name, mapping = super(ConfigurableElasticBackend,
self).build_schema(fields)
for field_name, field_class in fields.items():
field_mapping = mapping[field_class.index_fieldname]
if field_mapping['type'] == 'string' and field_class.indexed:
if not hasattr(field_class, 'facet_for') and not \
field_class.field_type in('ngram', 'edge_ngram'):
field_mapping['analyzer'] = self.DEFAULT_ANALYZER
mapping.update({field_class.index_fieldname: field_mapping})
return (content_field_name, mapping)
class ConfigurableElasticSearchEngine(ElasticsearchSearchEngine):
backend = ConfigurableElasticBackend
What would be the correct setup in order to successfully yield results for search patterns that are both and/or N346IF-style strings?
Appreciate any input, apologies if this is similar to another question (could not find anything related to it).
edit: requested by solarissmoke, the schema for this model:
class FlightIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.EdgeNgramField(document=True, use_template=True)
flight = indexes.CharField(model_attr='flightID')
callsign = indexes.CharField(model_attr='callsign')
displayName = indexes.CharField(model_attr='displayName')
session = indexes.CharField(model_attr='session')
def prepare_session(self, obj):
return obj.session.serverId
def get_model(self):
return Flight
Text is indexed as:
flight___{{ object.callsign }}___{{ object.displayName }}
A:
Solving my own question - appreciate the input by solarissmoke as it has helped me track down what was causing this.
My answer is based on Greg Baker's answer on the question
ElasticSearch: EdgeNgrams and Numbers
The issue appears to be related to the use of numeric values within the search text (in my case, the N133TC pattern). Note that I was using the snowball analyzer at first, before switching to pattern - none of these worked.
I adjusted my analyzer setting in settings.py:
"edgengram_analyzer": {
"type": "custom",
"tokenizer": "standard",
"filter": ["haystack_edgengram"]
}
Thus changing the tokenizer value to standard from the original lowercase analyzer used.
I then set the default analyzer to be used in my backend to the edgengram_analyzer (also on settings.py):
ELASTICSEARCH_DEFAULT_ANALYZER = "edgengram_analyzer"
This does the trick! It still works as an EdgeNgram field should, but allows for my numeric values to be returned properly too.
I've also followed the advice in the answer by solarissmoke and removed all the underscores from my index files.
| {
"pile_set_name": "StackExchange"
} |
Q:
Android ConnectivityManager onAvailable sometime not returned
We use the Android ConnectivityManager to listen for internet connection changes inside our app as follows.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
...
ConnectionStateMonitor().enable(this)
}
class ConnectionStateMonitor : NetworkCallback() {
private val networkRequest: NetworkRequest = NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI).build()
fun enable(context: Context) {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
connectivityManager.registerNetworkCallback(networkRequest, this)
}
override fun onAvailable(network: Network) {
Log.i(TAG, "onAvailable ")
}
override fun onLost(network: Network?) {
super.onLost(network)
Log.i(TAG, "onLost ")
}
}
}
This implementation is working well except for two issues we've encountered
If we connect to the internet by using both wifi and mobile data and turn off wifi sometimes the onLost() callback is fired followed by onAvailable(), as expected, but in other instances only onLost() is fired which is incorrect.
If we don't have internet connection and open the app onLost() is not fired, however if we have internet connection and open the app onAvailable() is fired.
Any help, suggestions, workarounds or another approaches to detect internet connection changes reliably would really be appreciated.
Tested on Xioami A2 (Android 9), OnePlus (Android 9)
DEMO project
https://github.com/PhanVanLinh/AndroidNetworkChangeReceiver
A:
I have used your project and I added another method: onCapabilitiesChanged. I started with the flight mode ebabled and then I turned off and then on again. These are the logs:
onAvailable 632
onCapabilitiesChanged 632 [ Transports: CELLULAR ...]
onAvailable 632
onCapabilitiesChanged 632 [ Transports: CELLULAR ...]
onAvailable 632
onCapabilitiesChanged 632 [ Transports: CELLULAR ...]
onCapabilitiesChanged 632 [ Transports: CELLULAR ...]
onCapabilitiesChanged 632 [ Transports: CELLULAR ...]
onAvailable 633
onCapabilitiesChanged 633 [ Transports: WIFI ...] onAvailable 633
onCapabilitiesChanged 633 [ Transports: WIFI ...]
onAvailable 633
onCapabilitiesChanged 633 [ Transports: WIFI ...]
onCapabilitiesChanged 633 [ Transports: WIFI ...]
onCapabilitiesChanged 633 [ Transports: WIFI ...]
onCapabilitiesChanged 633 [ Transports: WIFI ...]
onCapabilitiesChanged 633 [ Transports: WIFI ...]
onCapabilitiesChanged 633 [ Transports: WIFI ...]
onLost 632
onLost 632
onLost 632
onLost 633
onLost 633
onLost 633
onAvailable 634
onCapabilitiesChanged 634 [ Transports: CELLULAR ...]
onAvailable 634
onCapabilitiesChanged 634 [ Transports: CELLULAR ...]
onAvailable 634
onCapabilitiesChanged 634 [ Transports: CELLULAR ...]
onCapabilitiesChanged 634 [ Transports: CELLULAR ...]
onCapabilitiesChanged 634 [ Transports: CELLULAR ...]
onCapabilitiesChanged 634 [ Transports: CELLULAR ...]
onAvailable 635
onCapabilitiesChanged 635 [ Transports: WIFI ...]
onAvailable 635
onCapabilitiesChanged 635 [ Transports: WIFI ...]
onAvailable 635
onCapabilitiesChanged 635 [ Transports: WIFI ...]
onCapabilitiesChanged 635 [ Transports: WIFI ...]
onCapabilitiesChanged 635 [ Transports: WIFI ...]
onCapabilitiesChanged 635 [ Transports: WIFI ...]
onLost 634
onLost 634
onLost 634
onCapabilitiesChanged 635 [ Transports: WIFI ...]
onCapabilitiesChanged 635 [ Transports: WIFI ...]
As you can see the LOST is for the cellular transport while the AVAILABLE is for the WiFi
Following your use case (enable wifi, enable mobiledata, disable wifi data, enable wifi, disable wifi) this is what I get.
onAvailable 640
onCapabilitiesChanged 640 [ Transports: WIFI ... ]
onAvailable 640
onCapabilitiesChanged 640 [ Transports: WIFI ... ]
onCapabilitiesChanged 640 [ Transports: WIFI ... ]
onCapabilitiesChanged 640 [ Transports: WIFI ... ]
onCapabilitiesChanged 640 [ Transports: WIFI ... ]
onCapabilitiesChanged 640 [ Transports: WIFI ... ]
onLost 640
onLost 640
onAvailable 641
onCapabilitiesChanged 641 [ Transports: CELLULAR ... ]
onAvailable 641
onCapabilitiesChanged 641 [ Transports: CELLULAR ... ]
onCapabilitiesChanged 641 [ Transports: CELLULAR ... ]
onCapabilitiesChanged 641 [ Transports: CELLULAR ... ]
onAvailable 642
onCapabilitiesChanged 642 [ Transports: WIFI ... ]
onAvailable 642
onCapabilitiesChanged 642 [ Transports: WIFI ... ]
onCapabilitiesChanged 642 [ Transports: WIFI ... ]
onCapabilitiesChanged 642 [ Transports: WIFI ... ]
onCapabilitiesChanged 642 [ Transports: WIFI ... ]
onCapabilitiesChanged 642 [ Transports: WIFI ... ]
onLost 641
onLost 641
onLost 642
onLost 642
onAvailable 643
onCapabilitiesChanged 643 [ Transports: CELLULAR ... ]
onAvailable 643
onCapabilitiesChanged 643 [ Transports: CELLULAR ... ]
onCapabilitiesChanged 643 [ Transports: CELLULAR ... ]
onCapabilitiesChanged 643 [ Transports: CELLULAR ... ]
| {
"pile_set_name": "StackExchange"
} |
Q:
In Splunk, streamstats function give cumulative data on weekly basis but displaying data "Thursday to Thursday" instead "Monday to Sunday"
In Splunk, I want to display data in cumulative way on weekly basis but below query is counting data from "Thursday to Thursday" instead "Monday to Sunday".
Please Help.
index=c sourcetype=c | timechart count(eval(State = "Closed" OR State= "Resolved")) as "Closed", count(eval(State = "Assigned" OR State= "Open")) as "Still Open", count(eval(State = "Pending")) as "Pending" span=1w | streamstats sum(*) as *
A:
You can explicitly "bin" the _time into weeks starting any particular day of the week by using the relative_time() function and time modifiers "w" or "w0" (for Sunday), "w1" (for Monday) through "w6" (for Saturday).
index=c sourcetype=c
| eval _time =relative_time(_time,"@w1")
| timechart count(eval(State = "Closed" OR State= "Resolved")) as "Closed", count(eval(State = "Assigned" OR State= "Open")) as "Still Open", count(eval(State = "Pending")) as "Pending" span=1w
| streamstats sum(*) as *
| {
"pile_set_name": "StackExchange"
} |
Q:
Time travel to the crucifixion of Jesus and changing the past
The story I'm looking for is not Let's Go to Golgotha!, although there are a few core similarities.
It's not Up the Line either.
In the mid 2000s, I read in a magazine a science fiction short story that I'm now trying to find. (Unfortunately, the magazine is not in circulation anymore and there aren't any archives that I can find.)
The Greek translation of the title was Τελευταίο Ταξίδι Μετά Χριστόν, which I would translate to English as Final Travel After Christ (alternatively: Final Travel in the Year of Our Lord), but I don't have the slightest idea how close that is to the original title. I vaguely recall the author having a male Latin American name, but I may be way off.
The story involved a commercial time travelling agency. The crucifixion of Jesus was a pretty popular destination with the customers. The protagonist joined a group that went to visit that event.
At some point, one or more people from the protagonist's group unexpectedly intervened and helped Jesus flee, saving him from crucifixion. (IIRC the group was organised ahead of time and they may have managed to illegally carry weapons through the agency's security.) Everyone present was shocked, but ultimately they returned to their time machines.
That whole day is narrated by the protagonist to a young woman he met at the bar. She finds it so unbelievable, she thinks it's just a made up story. He makes a passing note of the pendant she's wearing around her neck. It's a little sword, symbolising the death of John the Baptist, the central figure in the dominant religion of the world the protagonist returned to.
A:
Well, after I spent a couple of hours locating the stored boxes in the attic, unpacking them, and going through the individual issues one by one, I managed to find it (in full compliance with Murphy's law, the sought issues were near the end of my unordered stack)...
It is a Greek translation of a novelette by Spanish author Juan Miguel Aguilera, originally written in Spanish as Ultima Visita d.C. (according to the accompanying info in 9 magazine) or C.T.C (according to the ISFDb), but first published in French translation as Dernière visite avant le Christ in the December 2003 issue (#31) of the French SF magazine Galaxies. No wonder google searches went unfruitful, as it seems it has never been translated into English.
The Greek translation was titled Τελευταίο Ταξίδι μ.Χ., roughly translated in English as Last Voyage AD; it was published in two parts, in the issues #196-197 (7 & 14 April 2004) of 9, the SF & comics magazine that accompanied the (now defunct) Greek newspaper Eleftherotypia every Wednesday:
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there any way to return from JFileChooser.showOpenDialog() programmatically?
The context is here is unit testing: at the end of a test, at tearDown, if a JFileChooser is left "hanging" (i.e. displayed), I want to force it to return with a "Cancelled" value.
The problem is that, otherwise, the actionPerformed() where I've called showOpenDialog (a blocking method) continues to live on... I need to close down that Runnable.
NB the Runnable running actionPerformed is of course running in the EDT. But despite this, the framework is capable of starting another "event pump": my understanding is that this is the quite normal and correct behaviour when you do JFileChooser.showOpenDialog in the EDT: similar functioning to calling one of the JOptionPane.showXXX static methods in the EDT.
I also want to avoid a "testing-contrived" solution to this: in other words, the application code must be sufficient for itself, and not use tortuous or unnatural mechanisms in the knowledge that it is going to be run by testing code for which it needs to provide a "handle".
PS I am actually using Jython, rather than Java, and I am using the Python unittest module, rather than a Java-based unit testing framework. But this doesn't change the principles involved...
PPS (later) I have devised a method which I regard as rather "precarious": this involves digging down into the JFileChooser to identify a JButton with getText() == "Cancel". Sorry, it's written in Jython, but it should be pretty easy to grasp even to those who know no Python:
def close_main_frame():
self.main_frame.dispose()
self.cancel_button = None
def explore_descendant_comps( container, method, breadth_first = False, depth = 0 ):
for component in container.components:
if isinstance( component, java.awt.Container ):
if breadth_first:
method( component, depth )
explore_descendant_comps( component, method, breadth_first, depth + 1 )
if not breadth_first:
method( component, depth )
def identify_cancel_button( comp, depth ):
if isinstance( comp, javax.swing.JButton ) and comp.text == 'Cancel':
self.cancel_button = comp
explore_descendant_comps( self.main_frame.analysis_file_chooser, identify_cancel_button )
if self.cancel_button:
self.cancel_button.doClick()
else:
raise Exception()
self.edt_despatcher.run_in_edt( close_main_frame, False )
This is "precarious" not least because the "Cancel" text of the button may be replaced by something with another name in another language...
A:
JFileChooser chooser = new JFileChooser();
chooser.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if( e.getActionCommand().equals("CancelSelection") )
{
chooser.cancelSelection();
}
}
} );
public void forceCancel()
{
ActionEvent e = new ActionEvent(chooser, ActionEvent.ACTION_PERFORMED, "CancelSelection");
fireActionPerformed(e);
}
public void fireActionPerformed( ActionEvent e )
{
ActionListener[] listeners = chooser.getActionListeners();
for( ActionListener listener : listeners )
{
listener.actionPerformed( e );
}
}
Using this code, you can call forceCancel() which fires an action event to automatically cancel the JFileChooser. You can include forceCancel() in your unit test.
( OR )
if you have component in your Jython call component.cancelSelection() by making is instance of check on the component.
| {
"pile_set_name": "StackExchange"
} |
Q:
Вывести количество часов с правильным окончанием час(а/ов)
Сделал так :
import datetime
def showHours( hours ):
result = "{0} {1}."
lastdigits = hours % 20
s = ""
if lastdigits == 1:
s += "час"
elif lastdigits > 1 and lastdigits < 5:
s += "часа"
else:
s += "часов"
return result.format( hours, s )
print showHours(datetime.datetime.now().hour)
Какие ещё варианты возможны?
A:
Вот принимали бы вы участие в переводе интерфейса Хэшкода, и не пришлось бы задавать этот вопрос :-)
Правильный вариант такой (псевдокод):
def pluralRusVariant(x):
lastTwoDigits = x % 100
tens = latTwoDigits / 10
if tens == 1:
return 2
ones = latTwoDigits % 10
if ones == 1
return 0
if ones >= 2 && ones <= 4
return 1
return 2
def showHours(hours) :
suffix = [ "час", "часа", "часов" ] [pluralRusVariant(hours)]
return "{0} {1}".format(hours, suffix)
Ваш вариант выдаст неправильный ответ при hours == 32. Получится 32 часов, а надо 32 часа.
| {
"pile_set_name": "StackExchange"
} |
Q:
Make Radio Button Clickable Link
I have a link that holds a radio button, which I want to make a clickable link. I've tried:
<a href="/">
<input type="radio" style="pointer-events:none;">
</a>
This prevents anything from happening when I click the radio button. I would like it to follow the link. Any ideas?
http://css-tricks.com/almanac/properties/p/pointer-events/
A:
You can use JavaScript to turn elements like that into a link. E.g.:
<input type="radio" onclick="window.location='/';" />
If other elements should be combined on the link with the radio button, put the onclick attribute on the wrapping element.
| {
"pile_set_name": "StackExchange"
} |
Q:
Android and how to change a listview
I am getting a json file from server parsing into a list and I am trying to update a listview, i see that when I try this line of code
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ReadWebpageAsyncTask.this,R.layout.medialist, mediaList);
it works just fine but when I try this line "myListView.setAdapter(adapter);" everything goes wrong, can you guys see what I'm doinf wrong, any help will be greatly appreciated.
package de.vogella.android.asynctask;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;
import android.app.Activity;
import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ReadWebpageAsyncTask extends ListActivity {
private TextView textView;
public ListView myListView = null;
List<String> mediaList = new ArrayList();
ArrayAdapter<String> adapter;
String[] newArray;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };
//String[] myMediList = mediaList.toArray(mediaList);
newArray = new String[mediaList.size()];mediaList.toArray(newArray);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, newArray);
setListAdapter(adapter);
readWebpage(myListView);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String item = (String) getListAdapter().getItem(position);
Toast.makeText(this, item + " selected", Toast.LENGTH_LONG);
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String response = "";
String responseBuilder;
String responseString = "";
JSONArray jsonArray;
JSONObject jObject = new JSONObject();
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
try {
//JSONObject json = new JSONObject(response);
//JSONObject jObject = new JSONObject(response);
//jObject = response.t
jsonArray = new org.json.JSONArray(response);
jObject = jsonArray.toJSONObject(jsonArray);
for (int i=0;i<jObject.length();i++)
{
responseBuilder="\n";
responseBuilder+= "\n title: "+((JSONObject) jsonArray.getJSONObject(i).get("videoinfo")).get("title");
responseBuilder+= "\n subject: "+ ((JSONObject) jsonArray.getJSONObject(i).get("videoinfo")).get("subject");
responseBuilder+= "\n language: "+ ((JSONObject) jsonArray.getJSONObject(i).get("videoinfo")).get("language");
responseBuilder+= "\n date: "+ ((JSONObject) jsonArray.getJSONObject(i).get("videoinfo")).get("date");
mediaList.add(responseBuilder);
responseString += responseBuilder;
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
myListView = (ListView) findViewById (R.id.lv);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ReadWebpageAsyncTask.this,
R.layout.medialist,
mediaList);
myListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
return responseString;
//final ArrayAdapter <String> aa;
//aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mediaList);
// Bind the array adapter to the listview
//myListView.setAdapter(aa);
}
@Override
protected void onPostExecute(String result) {
textView.setText(result);
adapter.notifyDataSetChanged();
//textView.setText(myListView.toString());
//final ArrayAdapter <String> aa;
//aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mediaList);
//Bind the array adapter to the listview
//myListView.setAdapter(aa);
}
}
public void readWebpage(View view) {
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://hummedia.byu.edu/mediainfo/search/?title=Harry" });
}
}
here is my stack trace:
11-18 10:54:55.946: W/dalvikvm(790): threadid=11: thread exiting with uncaught exception (group=0x409951f8)
11-18 10:54:56.323: E/AndroidRuntime(790): FATAL EXCEPTION: AsyncTask #1
11-18 10:54:56.323: E/AndroidRuntime(790): java.lang.RuntimeException: An error occured while executing doInBackground()
11-18 10:54:56.323: E/AndroidRuntime(790): at android.os.AsyncTask$3.done(AsyncTask.java:278)
11-18 10:54:56.323: E/AndroidRuntime(790): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
11-18 10:54:56.323: E/AndroidRuntime(790): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
11-18 10:54:56.323: E/AndroidRuntime(790): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
11-18 10:54:56.323: E/AndroidRuntime(790): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-18 10:54:56.323: E/AndroidRuntime(790): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
11-18 10:54:56.323: E/AndroidRuntime(790): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
11-18 10:54:56.323: E/AndroidRuntime(790): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
11-18 10:54:56.323: E/AndroidRuntime(790): at java.lang.Thread.run(Thread.java:856)
11-18 10:54:56.323: E/AndroidRuntime(790): Caused by: java.lang.NullPointerException
11-18 10:54:56.323: E/AndroidRuntime(790): at de.vogella.android.asynctask.ReadWebpageAsyncTask$DownloadWebPageTask.doInBackground(ReadWebpageAsyncTask.java:122)
11-18 10:54:56.323: E/AndroidRuntime(790): at de.vogella.android.asynctask.ReadWebpageAsyncTask$DownloadWebPageTask.doInBackground(ReadWebpageAsyncTask.java:1)
11-18 10:54:56.323: E/AndroidRuntime(790): at android.os.AsyncTask$2.call(AsyncTask.java:264)
11-18 10:54:56.323: E/AndroidRuntime(790): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
11-18 10:54:56.323: E/AndroidRuntime(790): ... 5 more
A:
In activity onCreate() I see //setContentView(R.layout.main);. So there is no custom content view.
But AsyncTask tries to get the list view by myListView = (ListView) findViewById (R.id.lv);
I think myListView gets null at this point. You should change myListView = (ListView) findViewById (R.id.lv) to myListView = getListView();
| {
"pile_set_name": "StackExchange"
} |
Q:
Pass TextStyle from c++ to QML
I am having problems setting the TextStyle of a Label when using a c++ method, it always causes the app to crash.
I have a c++ getStyle() method. I want to be able to call it like so (parameters removed to simplify code example):
Label {
id: myLabel
text: "test with style"
textStyle.base: _App.getStyle();
}
The following does NOT work:
TextStyle ApplicationUI::getStyle() {
TextStyle *blueStyle = new TextStyle(bb::cascades::SystemDefaults::TextStyles::smallText());
blueStyle->setColor(Color::Blue);
return *blueStyle;
}
Currently the only way I have been able to get it working is to pass the entire Label object into a method and set the style with c++. This however makes the QML code more verbose leading to this:
Label {
id: myLabel
text: "test with style"
onCreationCompleted: {
_App.setStyle(myLabel);
}
}
C++ (Works)
void ApplicationUI::setStyle(AbstractTextControl* label) {
TextStyle *blueStyle = new TextStyle(bb::cascades::SystemDefaults::TextStyles::smallText());
blueStyle->setColor(Color::Blue);
label->textStyle()->setBase(*blueStyle);
}
Is there any way to pass the TextStyle directly to the QML Label without having to pass the Label object into the method?
A:
I managed to solve the problem after some browsing of the various .h files and experimenting.
QML:
Label {
id: myLabel
text: "test with style"
textStyle.base: _App.getStyle();
}
C++:
QVariant ApplicationUI::getStyle() {
TextStyleDefinition *textStyle = new TextStyleDefinition();
textStyle->setColor(Color::Blue);
QVariant style = textStyle->property("style");
return style;
}
The trick is that when setting a Label's Style.base property from c++ it requires a TextStyle object, however when you set it from QML it expects a QVariant. Using ->property("style") we can get the QVariant which QML expects.
| {
"pile_set_name": "StackExchange"
} |
Q:
GCM tmpClient.open(url) - "open" подсвечивает красным
Здравствуйте, подскажите пожалуйста, почему open не распознаётся?
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.atomic.AtomicInteger;
import okhttp3.OkHttpClient;
public class MainActivity extends AppCompatActivity {
EditText editText_user_name;
EditText editText_email;
Button button_login;
static final String TAG = "pavan";
TextView mDisplay;
GoogleCloudMessaging gcm;
AtomicInteger msgId = new AtomicInteger();
SharedPreferences prefs;
Context context;
String regid;
String msg;
String name;
String email;
private GoogleApiClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = getApplicationContext();
if (isUserRegistered(context)) {
startActivity(new Intent(MainActivity.this, ChatActivity.class));
finish();
} else {
editText_user_name = (EditText) findViewById(R.id.editText_user_name);
editText_email = (EditText) findViewById(R.id.editText_email);
button_login = (Button) findViewById(R.id.button_login);
button_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendRegistrationIdToBackend();
}
});
// Check device for Play Services APK. If check succeeds, proceed with
// GCM registration.
if (checkPlayServices()) {
gcm = GoogleCloudMessaging.getInstance(this);
regid = getRegistrationId(context);
if (regid.isEmpty()) {
registerInBackground();
}
} else {
Log.i("pavan", "No valid Google Play Services APK found.");
}
}
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
Util.PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.i(TAG, "This device is not supported.");
finish();
}
return false;
}
return true;
}
private String getRegistrationId(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
String registrationId = prefs.getString(Util.PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
Log.i(TAG, "Registration not found.");
return "";
}
// Check if app was updated; if so, it must clear the registration ID
// since the existing registration ID is not guaranteed to work with
// the new app version.
int registeredVersion = prefs.getInt(Util.PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
Log.i(TAG, "App version changed.");
return "";
}
return registrationId;
}
private boolean isUserRegistered(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
String User_name = prefs.getString(Util.USER_NAME, "");
if (User_name.isEmpty()) {
Log.i(TAG, "Registration not found.");
return false;
}
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Substitute you own sender ID here. This is the project number you got
* from the API Console, as described in "Getting Started."
*/
private void registerInBackground() {
new AsyncTask() {
@Override
protected String doInBackground(Object[] params) {
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(MainActivity.this);
}
regid = gcm.register(Util.SENDER_ID);
msg = "Device registered, registration ID=" + regid;
// You should send the registration ID to your server over HTTP,
//GoogleCloudMessaging gcm;/ so it can use GCM/HTTP or CCS to send messages to your app.
// The request to your server should be authenticated if your app
// is using accounts.
// sendRegistrationIdToBackend();
// For this demo: we don't need to send it because the device
// will send upstream messages to a server that echo back the
// message using the 'from' address in the message.
// Persist the registration ID - no need to register again.
storeRegistrationId(context, regid);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
// If there is an error, don't just keep trying to register.
// Require the user to click a button again, or perform
// exponential back-off.
}
return msg;
}
}.execute();
}
private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (PackageManager.NameNotFoundException e) {
// should never happen
throw new RuntimeException("Could not get package name: " + e);
}
}
private void storeRegistrationId(Context context, String regId) {
final SharedPreferences prefs = getGCMPreferences(context);
int appVersion = getAppVersion(context);
Log.i(TAG, "Saving regId on app version " + appVersion);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(Util.PROPERTY_REG_ID, regId);
editor.putInt(Util.PROPERTY_APP_VERSION, appVersion);
editor.commit();
}
private void storeUserDetails(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
int appVersion = getAppVersion(context);
Log.i(TAG, "Saving regId on app version " + appVersion);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(Util.EMAIL, editText_email.getText().toString());
editor.putString(Util.USER_NAME, editText_user_name.getText().toString());
editor.commit();
}
private SharedPreferences getGCMPreferences(Context context) {
// This sample app persists the registration ID in shared preferences, but
// how you store the registration ID in your app is up to you.
return getSharedPreferences(MainActivity.class.getSimpleName(),
Context.MODE_PRIVATE);
}
// private RequestQueue mRequestQueue;
private void sendRegistrationIdToBackend() {
// Your implementation here.
new SendGcmToServer().execute();
// AppController.getInstance().addToRequestQueue(jsObjRequest, "jsonRequest");
}
@Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.example.aseke.goo/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
@Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.example.aseke.goo/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
private class SendGcmToServer extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
name = editText_user_name.getText().toString();
email = editText_email.getText().toString();
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String url = Util.register_url + "?name=" + name + "&email=" + email + "®Id=" + regid;
Log.i("pavan", "url" + url);
OkHttpClient client_for_getMyFriends = new OkHttpClient();
String response = null;
// String response=Utility.callhttpRequest(url);
try {
url = url.replace(" ", "%20");
response = callOkHttpRequest(new URL(url),
client_for_getMyFriends);
for (String subString : response.split("<script", 2)) {
response = subString;
break;
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//Toast.makeText(context,"response "+result,Toast.LENGTH_LONG).show();
if (result != null) {
if (result.equals("success")) {
storeUserDetails(context);
startActivity(new Intent(MainActivity.this, ChatActivity.class));
finish();
} else {
Toast.makeText(context, "Try Again" + result, Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(context, "Check net connection ", Toast.LENGTH_LONG).show();
}
}
}
// Http request using OkHttpClient
String callOkHttpRequest(URL url, OkHttpClient tempClient)
throws IOException {
HttpURLConnection connection = tempClient.open(url); // open подсвечен красным
connection.setConnectTimeout(40000);
InputStream in = null;
try {
// Read the response.
in = connection.getInputStream();
byte[] response = readFully(in);
return new String(response, "UTF-8");
} finally {
if (in != null)
in.close();
}
}
byte[] readFully(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
for (int count; (count = in.read(buffer)) != -1; ) {
out.write(buffer, 0, count);
}
return out.toByteArray();
}
}
В принципе код okhttp аналогичен с этого тикета https://stackoverflow.com/questions/33854040/cannot-resolve-symbol-okhttp
в build.gradle произвёл компиляцию таким образом:
compile 'com.squareup.okhttp3:okhttp:3.2.0'
A:
Изменились вызовы
// OkHttp 1.x:
HttpURLConnection connection = client.open(url);
// OkHttp 2.x:
HttpURLConnection connection = new OkUrlFactory(client).open(url);
В версии 3 этот код вынесен в отдельную библиотеку:
Deprecated.
OkHttp will be dropping its ability to be used with HttpURLConnection
in an upcoming release. Applications that need this should either
downgrade to the system's built-in HttpURLConnection or upgrade to
OkHttp's Request/Response API
.
Рекомендуемый код в версии 3.0
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url( Util.register_url)
.addQueryParameter("name", name)
.addQueryParameter("email", email)
.addQueryParameter("regId", regid)
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
for (String subString : response.body().string().split("<script", 2)) {
newresponse = subString;
break;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to store a translation in a different table using Doctrine 2 + Gedmo Translatable
Using the instructions on https://github.com/l3pp4rd/DoctrineExtensions/blob/master/doc/translatable.md#advanced-examples a table can be split in order to store the translations in another table.
The resulting table structure is:
(example A)
Article ArticleTranslation
+--------------+ +----------------------+
| id | | id |
+--------------+ +----------------------+
| title | | locale |
+--------------+ +----------------------+
| content | | objectclass |
+--------------+ +----------------------+
| online | | foreign_key |
+--------------+ +----------------------+
| field |
+----------------------+
In my view there are two problems using this standard approach:
1. the translated entity is stored into multiple records (one per field) in the translation table
2. The original record should be in the translated table as well.
Is it possible with Doctrine+ Gedmo Translatable to store the translations like this:
(example B)
Article ArticleTranslation
+--------------+ +----------------------+
| id | | id |
+--------------+ +----------------------+
| online | | foreign_key |
+--------------+ +----------------------+
| locale |
+----------------------+
| title |
+----------------------+
| content |
+----------------------+
So untranslated fields should be in the Article table, translated fields in the ArticleTranslation table with one record per translated article.
How can this be achieved?
A:
using current architecture it stores a record per field in translation table. In general it was done this way in order to avoid synchronization issues if you add or remove translatable fields from your entities.
Implementation of your method would result in having additional schema migration command specifically for extension or having some magic mapping in background. To avoid confusion the only thing which is scheduled for update is original record translation storage as default locale fallback, without having record in translation table.
I understand that in advanced cases this bahavior is not what you would have done, but it is a behavior for most users which want it configurable as simple as possible.
And regarding collection translations you can use query hint This behavior will never cover 99% of use cases like SF2 does in order to maintain simplicity
| {
"pile_set_name": "StackExchange"
} |
Q:
Confusion with the predicate $Dem(x,z)$ in Godel's incompleteness theorem proof
I'm reading http://www.math.mcgill.ca/rags/JAC/124/GodelsProof.pdf
Near the final pages, they prove it.
Here's the proof as I understand it:
All symbols in the language of arithmetic are given a unique Godel number (which is a whole number)
All formulas in arithmetic are also given a unique Godel number by the method: $2^{a}3^{b}5^{c}7^{d}.....$, where 2,3,5,7... are the primes and $a,b,c,d$ are the Godel numbers of the symbols which appear in the formula in the order of their appearance.
Every proof in arithmetic is given a unique Godel number using the same method, except this time $a,b,c,d....$ are the Godel numbers of the formulas which appear in the proof in the order of appearance.
$Dem(x,z)$ is an arithmetic predicate which takes two Godel numbers $x$ and $z$. It is true if the proof corresponding to Godel number $x$ results in the formula (or proves the formula) corresponding to the Godel number $z$.
$sub(y,16,y)$ is an arithmetic function of $y$ (I don't know why two y's are used in the notation). It gives us the Godel number of the formula obtained by replacing all instances of the symbol corresponding to Godel number 16, in the formula corresponding to Godel number $y$, by $y$.
Now we start with the formula:
$$\forall(x), \neg Dem(x,sub(y,16,y))$$
Suppose this formula has Godel number $n$, and $y$ has been assigned Godel number $16$. We substitute $n$ for $y$ to get another formula:
$$\forall(x), \neg Dem(x,sub(n,16,n))$$
By definition of $sub(n,16,n)$, the above formula has Godel number $sub(n,16,n)$, as it has been obtained by replacing $y$ by $n$ in the formula of Godel number $n$
Also, this formula is saying "The formula of Godel number $sub(n,16,n)$ (i.e. the formula itself) is not demonstrable".
Now we prove that this formula is true. We assume that it is false. This means the formula is demonstrable. But that means its negation, which says "The formula is demonstrable", is also demonstrable. Since this is a contradiction, we arrive at the conclusion that the formula is true and undemonstrable. Have I understood this all correctly?
My problem
My problem is with the $Dem$ predicate. Given two Godel numbers $x$ and $z$, how do we calculate the truth value of $Dem(x,z)$?
To do that, we prime factorize $x$, and look at the power of the largest prime factor. If that power is equal to $z$, then that means the formula assigned to $z$ is the last formula (or the final result) in the proof assigned to Godel number $x$. So that means $x$ proves $z$, right?
But this method regards any sequence of formulas, ending in the formula corresponding to Godel number $z$, as a proof of the formula having Godel number $z$. This doesn't take into account any transformation rules of the axioms, whether the proof is logically valid or not. For example, $Dem(z,z)$ would be true by this method and hence every formula would be demonstrable.
A:
Here's the basic idea (as Mauro indicates)
To determine whether the relation Dem(m, n) holds, proceed as follows. First decode m (undo the Gödel numbering). That’s a mechanical exercise. Now ask: is the result a sequence of PA wffs? That’s algorithmically decidable (since it is decidable whether the Gödel number decodes into a string which is a sequence of wffs). If it does decode into a sequence of wffs, ask next: is this sequence a properly constructed PA proof? That’s decidable too (check whether each wff in the sequence is either an axiom or is an immediate consequence of previous wffs by one of the rules of inference of PA’s logical system). If the sequence is a proof, ask: does its final wff have the g.n. n? That’s again decidable. Dem(m, n) holds if the sequence coded by $m$ is a proof of the wff coded by $n$.
(So even if you choose a coding where a sequence of one wff gets the same code as the code for that wff, Dem(n, n) won't be true unless $n$ codes an instance of an axiom.)
Putting all that together, there is a computational procedure for telling whether Dem(m, n) holds. Moreover, at each and every stage, the computation involved is once more a straightforward, bounded procedure that can be done with ‘for’-loops. So Dem will be a primitive recursive relation, expessible in PA.
For more on this, see §39 of Gödel Without (too many) Tears, downloadable from https://www.logicmatters.net/igt/godel-without-tears/ Or even better of course the Gödel book of which those notes are the short version.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to create a certificate chain using keytool?
I want to create certificate chain in java as follows:
ca.mycompany.com
|--asia.mycompany.com
|--india.mycompany.com
where ca.mycompany.com is a root certificate (self signed).
I know this is possible with OpenSSL. But is it possible to to achieve this with keytool?
If not, can I achieve this with Mozilla NSS library?
A:
There is an example in the keytool documentation that shows how to do this:
keytool -genkeypair -keystore root.jks -alias root -ext bc:c
keytool -genkeypair -keystore ca.jks -alias ca -ext bc:c
keytool -genkeypair -keystore server.jks -alias server
keytool -keystore root.jks -alias root -exportcert -rfc > root.pem
keytool -storepass <storepass> -keystore ca.jks -certreq -alias ca | keytool -storepass <storepass> -keystore root.jks -gencert -alias root -ext BC=0 -rfc > ca.pem
cat root.pem ca.pem > cachain.pem
keytool -keystore ca.jks -importcert -alias ca -file cachain.pem
keytool -storepass <storepass> -keystore server.jks -certreq -alias server | keytool -storepass <storepass> -keystore ca.jks -gencert -alias ca -ext ku:c=dig,keyEncipherment -rfc > server.pem
cat root.pem ca.pem server.pem > serverchain.pem
keytool -keystore server.jks -importcert -alias server -file serverchain.pem
You can also generate certificate chains pretty easily with KeyStore Explorer:
Create a new key pair, which implies creating a self-signed certificate (the root CA).
Right click on root CA certificate and select "Sign New Key Pair", this creates the sub CA certificate and key pair.
Right click on sub CA certificate and select "Sign New Key Pair" again.
The resulting chain:
A:
This is a perfect tutorial which help you go though the process of creating certificate chain using keytool. Basically, the process is you need to sign the certificate with the keys from CA and then install the certificate to the keystore you create.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to put id inside the newUser using Typescript
i have a signUp form, i am giving email and password from frontend, and active, role_id field from the typescript.. I am getting active in the consoled output but not the role_id. i guess if i can get role_id inside consoled output of ts file then my error may solve. i am getting all the required fields in the apiservice section but not in my component file.. Can anyone help me to solve this.
A:
You need to take a loggedIn variable and should use it to toggle the alert popup,
Conponent Variable:
public loggedIn = false;
Login method:
login(email, password) {
this.localSt.store('boundValue', email);
var data = {
email: email,
password: password
};
this.ApiService
.login(data)
.subscribe(
user => {
this.signIn.hide();
this.loggedIn = true;
this.toasterService.pop('success', 'SignIn Successfull');
this.myFav = true;
}, error => {
this.myFav = false;
if (error.data && error.data.length > 0) {
this.toasterService.pop('error', error.data);
} else {
this.toasterService.pop('error', 'Something went wrong!');
}
})
}
Popup method:
openPopup(event) {
if (!this.loggedIn) {
event.preventDefault();
this.signIn.show();
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
A few questions about $\mathbb{Q}$-models of modular curves (curves given by congruence groups)
I'm just now beginning to learn about descending the curves $X(N)$ to $\mathbb{Q}$, and I have a few questions:
Does $X(N)$ have a $\mathbb{Q}$-point for every $N$?
What is $\operatorname{Aut}(X(N))$? I know that $\operatorname{PSL}_2(\mathbb{F}_p)\leq \operatorname{Aut}(X(p))$ for $p$ prime, but can we say more? (for example, is this an equality for $p$ prime; what can we say if $p$ isn't prime?)
Does the map $X(N)\rightarrow \mathbb{P}^1_{\mathbb{C}}$ together with the Galois action descend to $\mathbb{Q}$? How about without it?
Do the curves $X_0(N)$ (and curves given by congruence groups in general) also descend to $\mathbb{Q}$? If so, I ask the above questions for those as well.
A:
For $X(N)$, one can give a $\mathbb{Q}$-model, but there's a sense in which doing so is "cheating".
The moduli interpretation of $X(N)$ only makes sense over $\mathbb{Q}(\zeta_N)$; if $R$ is an algebra over this field, then $X(N)$ classifies triples $(E, P_1, P_2)$ where $E$ is an elliptic curve over $R$ and $P_1, P_2$ are $R$-points of $E$ order $N$ which pair to $\zeta_N$ under the Weil pairing.
You can choose a model for $X(N)$ over $\mathbb{Q}$ in various ways, but you lose the moduli interpretation above. The usual way of doing this is such that the rational functions defined over $\mathbb{Q}$ are those whose $q$-expansions at the cusp $\infty$ have coefficients in $\mathbb{Q}$. This is done in, for instance, Stevens' book "Arithmetic on modular curves". With this choice, it is essentially tautological that the cusp $\infty$ is a $\mathbb{Q}$-point, and that the $j$-invariant map $X(N) \to X(1) \cong \mathbf{P}^1$ is defined over $\mathbb{Q}$. But this $\mathbb{Q}$-structure is rather artificial, and doesn't interact well with the moduli interpretation; e.g. sometimes one encounters modular curves $X$ which are quotients of $X(N)$, and which have a natural $\mathbb{Q}$-structure which is compatible with the moduli space interpretation of $X$, but where the map $X(N) \to X$ isn't defined over $\mathbb{Q}$ when we give $X(N)$ the $\mathbb{Q}$-structure described above. (See e.g. Elkies' paper on mod 3 and mod 9 representations of elliptic curves.)
I hope this at least partially answers your questions (1) and (3). I don't know the answer to (2); but for $N < 6$ we have $X(N) \cong \mathbf{P}^1$, so the automorphism group of $X(N)$ is infinite in these cases (in particular it is much larger than $PSL_2(\mathbf{Z} / N)$).
For $X_0(N)$ and $X_1(N)$ life is much easier than $X(N)$: the moduli space interpretations of these curves make sense over $\mathbb{Q}$, and they have rational models compatible with this moduli space structure, and the cusp $\infty$ is always a $\mathbb{Q}$-point.
(EDIT: Actually the last sentence is wrong, sorry! This works for $X_0(N)$ but not for $X_1(N)$. The canonical $\mathbb{Q}$-structure on $X_1(N)$ is the one that makes $\mathbb{Q}$-expansions at the cusp 0, not the cusp $\infty$, rational.)
| {
"pile_set_name": "StackExchange"
} |
Q:
DLL import failure in using WinDivert
I am going to design a program using WinDivert to manipulate the network traffic.
The language I use is C++ and the program is designed under Visual Studio 2008.
Firstly I create a project in visual C++ CLR (Windows Forms Application) so I can implement the UI simply.
For importing the WinDirvert Library, I have done the following setting in project properties:
Configuaration Properties: General
Common Language Runtime support: Common Language Runtime Support(/ctr)
Configuaration Properties: Linker
Additional Dependencies: link of WinDivert.lib
Module Definition File: link of windivert.def
Within the project I have created, I also added the windivert.h in the header files.
Also, windivert.h is included in the main entry point of my project (ProjectG.cpp):
#include "stdafx.h"
#include "Form1.h"
#pragma managed(push, off)
#include "windivert.h"
#pragma managed(pop)
using namespace ProjectG;
[STAThreadAttribute]
int main(array<System::String ^> ^args)
{
// Enabling Windows XP visual effects before any controls are created
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
// Create the main window and run it
Application::Run(gcnew Form1());
HANDLE handle;
unsigned char packet[8192];
UINT packet_len;
WINDIVERT_ADDRESS addr;
handle = WinDivertOpen("udp", WINDIVERT_LAYER_NETWORK, 0,
WINDIVERT_FLAG_DROP);
if (handle == INVALID_HANDLE_VALUE)
{
Application::Exit();
}
while (TRUE)
{
// Read a matching packet.
if (!WinDivertRecv(handle, packet, sizeof(packet), &addr, &packet_len))
{
MessageBox::Show("Fail");
continue;
}
}
return 0;
}
Finally, I put the {WinDivert.dll, windivert.h, WinDivert.lib, WinDivert32.sys} under the project directory.
However, the following error is shown:
fatal error LNK1306: DLL entry point "int __clrcall main(cli::array<class
System::String ^ >^)" (?main@@$$HYMHP$01AP$AAVString@System@@@Z) cannot be managed;
compile to native ProjectG.obj ProjectG
Additional: (a warning)
warning LNK4070: /OUT:WinDivert.dll directive in .EXP differs from output filename
'C:\Users\David\Desktop\css\ProjectG\Debug\ProjectG.exe'; ignoring directive
ProjectG.exp ProjectG
Question:
How can I resolve this situation?
A:
a) your main source is .cpp, so you can delete [STAThreadAttribute] and change
int main(array<System::String ^> ^args) to int _tmain(int argc, _TCHAR* argv[])
b) exclude windivert.def from linker Module Definition File, this only when you are creating a DLL
c) the DLL/SYS files would need to be copied to the Debug and Release folders
| {
"pile_set_name": "StackExchange"
} |
Q:
OSX Apache Web Server El Capitan Upgrade 404 Error
I was receiving a 404 error after upgrading to El Capitan when trying to access pages in my local sites directory after they were already enabled at the user level when running OSX Yosemite. The issue was that Apache reset the httpd.conf file to its default which disables the user folders to load files from. So http://localhost loaded fine BUT http://localhost/~username/index.html would NOT load.
A:
Here's the fix:
back up the "new" config file that was created:
sudo cp /etc/apache2/httpd.conf /etc/apache2/httpd.conf_capitan
restore the "old" config file that was renamed:
sudo cp /etc/apache2/httpd.conf~previous /etc/apache2/httpd.conf
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I travel through the Schengen Zone on a type D student visa (for Spain) if I have already lived in the country of the vissa for more then 90 days?
I am currently living in Spain on a 5 month trip, I was granted a student visa for 180 days. This is a type D visa and I would like to travel in the month after my program is finished, will I have problems with this if I have already lived in the country of issue for 90 days? and as a bonus question, can I re-enter the Schengen Zone through a different country to return to Spain?
A:
Curious but the other related questions while answer the question whether you can travel on a D to other Schengen countries (yes) does not emphasize this fact: the 90/180 rule only applies to the countries you visit. The country where you reside with a D visa does not fall under the 90/180 rule as you are not a visitor there but a temporary resident.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I share apps and music purchased on one apple ID between 7 devices?
I have:
1 Macbook Pro for office use
1 Macbook Air for personal travel use
1 Mac Mini to run my home theater system
1 iMac that my wife and kids use
1 iPad v1 for the kids to play with
1 iPad v2 for myself
1 iPhone 3GS
I'm running into problems with iTunes telling me I've authorized too many devices. I have seen in some places people saying that I'm allowed to authorized up to 10 devices, 5 of which can be computers, but iTunes seems to be treating computers and other devices the same for me, limiting me to 5 no matter what.
Any ideas what might be wrong?
A:
Maybe you have authorized Macs you no longer have.
Go to your account in iTunes, under Apple ID Overview you can see how many computers you have authorized and (once a year) you can deauthorize all, after that you should be able to reauthorize your Macs. (This does not affect iOS devices, as they do not count towards your 5 devices limit)
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I Plan to Write a Scholarly Book in LuaTeX or ConTeXt
This is a general question only. By now I am only a graduate student, and you might laugh at me for this, but maybe some day I will publish a book. I am considering to use LuaTeX or ConTeXt, but I am afraid most (if not all) publishers cannot read them. Does the writer necessarily has to sent the publisher his or her work in the format publisher can open?
I know most journal publishers accpet LaTeX only for article submission. But what about books? Imagining the book is completed, reasonably proofed, and has accordingly compiled a PDF, and the writer sends the PDF to the publisher. I assume the book is of some value, of course. But the source is written in LuaTeX, or ConTeXt, or some rare format.
Will it still be unreasonable that the writer collaborate with the publisher in a format only the writer can open? Or even if he or she uses a format the publisher cannot read, is it possibly viable that he send a PDF file only, that the publisher suggest corrections and advices on format, and repeat the process, allowing the writer to make change?
If a certain format is almost universally rejected, I will think twice in what format should I write my miscellaneous notes, thoughts and sketches related to my field, since it is hard to tell whether in the distant future I will organize material into a book.
Supposing not, what formats do scholarly publishers approve in general? I suppose pdflatex-compilable LaTeX files is almost universally acknowledged, but are there other options? Some say that a small percentage of publishers also accept Microsoft Word, and I am aware that, but I hate Word, sorry.
A:
It's possible that you could find a small or specialized publisher that is happy with an unusual format, but I don't think most academic publishers would be able to work with LuaTeX or ConTeXt. It just won't be part of their standard workflow.
It's very unlikely that they will let you control the file and make all the changes yourself. Instead, publishers almost always edit the file themselves, since that's more efficient and gives them more control. If you care about doing all the edits yourself, you should mention it early and expect to be turned down by most publishers for this reason alone.
In practice, I don't think the editor will even think about the format issue if you don't bring it up. They'll assume you are using LaTeX, and they'll be surprised to learn otherwise when it's time to submit your manuscript for copyediting and formatting. At that point, they aren't likely to reject it for format reasons, but they'll probably do things that make you unhappy. They might try to convert it to LaTeX themselves, or even retype everything from scratch. Any fine details of formatting will have to be reconstructed, and the chances of getting everything exactly the way it was are slim. If you have strong opinions about formatting, you should try hard to avoid this outcome. (It's better to convert it to LaTeX yourself than to have them do it.)
| {
"pile_set_name": "StackExchange"
} |
Q:
What should I do about old cables that have been damaged?
I was replacing some drywall and noticed the wiring underneath has a couple of surface tears. House is from the sixties, but has been rewired with new Romex, except this circuit. Wire seems to be old type of Romex (cloth covered) and has the marking "HATFLEX NM 14/2". Only the cloth is partially teared-up.
Should I be worried about this? I was considering putting some electrical tape over the damaged sections. Is this ok? What other alternatives do I have?
A:
Repair
You can use a cable jacket repair tape, to repair the jacket. I would not use simple electrical tape to make the repair, since it has a tendency to dry out and fall off.
Scotch® Cable Jacket Repair Tape 2234
Repairing Damaged Cable Jacket When No Portion of Cable Jacket is Missing
Abrade the cable jacket 3" (75 mm) beyond each side of the damaged cable jacket section
Wrap one half-lapped layer of Scotch® Cable Jacket Repair Tape 2234 extending at least 2" (50 mm) on each side beyond the damaged cable jacket
Starting 1" (25 mm) past the Scotch® Cable Jacket Repair Tape 2234, apply 3 half-lapped layers of Scotch™ Super 33+™ Vinyl Electrical Tape to each end to temporarily secure the ends of the Scotch® 2234 tape to the cable jacket until the tape reaches full bond.
Instructions
NOTE: Other products do exist. The products listed above are for example purposes only. I do not recommend or endorse the above listed products.
Replace
If the section is accessible at both ends, you could simply replace the section of cable.
| {
"pile_set_name": "StackExchange"
} |
Q:
¿Existe algún hosting gratuito en ASP.net y C# para hospedar sitio Web personal?
¿Existe algún hosting gratuito en ASP.net, C# y SQL Server para hospedar sitio Web personal?
A:
Si, yo tengo tres sitios en azurewebsites:
http://twaincentral.azurewebsites.net/
http://bigsurgarrapata.azurewebsites.net/
http://usamaporama.azurewebsites.net/
Nunca he pagado por ellos.
Puedes mirar en How Azure pricing works
| {
"pile_set_name": "StackExchange"
} |
Q:
my android app keeps closing when i press a button
i am making a android app that connects to my chat server. When I start the app and press the Join button it stops I don't know what the problem is. If you can help me thank you in advance.
package com.example.marcus.chatclient1;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
public class chat extends AppCompatActivity {
public Socket s;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
final Button join = (Button)findViewById(R.id.joinButton);
join.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText nameText = (EditText)findViewById(R.id.editTextName);
String name = nameText.getText().toString();
join.setVisibility(View.INVISIBLE);
nameText.setVisibility(View.INVISIBLE);
TextView errorT = (TextView) findViewById(R.id.errorText);
try {
s = new Socket("192.168.0.15", 55555);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
A:
Basically there are answers here
The code Socket clientSocket = new Socket(); crashes in android app. Why?
https://ru.stackoverflow.com/questions/274551/%D0%9A%D0%BB%D0%B8%D0%B5%D0%BD%D1%82-android-%D1%81%D0%B5%D1%80%D0%B2%D0%B5%D1%80-java-app
You problem it that you are trying to create socket on a main thread.
| {
"pile_set_name": "StackExchange"
} |
Q:
System.import usage cause multiple errors in my console
I use System in my component.
export class LoginComponent {
constructor() {
System.import('app/login/login.js');
}
}
File loads fine, but TypeScript compiller says
Error:(10, 9) TS2304: Cannot find name 'System'.
And my browser console says
EXCEPTION: Error: Uncaught (in promise): Error: Error: http://localhost:3000/app/login/login.js detected as register but didn't execute.
at ZoneDelegate.invoke (http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:332:29)
at Object.NgZoneImpl.inner.inner.fork.onInvoke (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:2111:31)
at ZoneDelegate.invoke (http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:331:35)
at Zone.run (http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:227:44)
Error loading http://localhost:3000/app/login/login.js
Error: Uncaught (in promise): Error: Error: http://localhost:3000/app/login/login.js detected as register but didn't execute.(…)
How do I fix that?
A:
You have an error since you don't have typings for the SystemJS library.
Most of time we don't use explicitly System.import in TypeScript files since we can make it act under the hood. I mean when you use the following, the TypeScript compiler will convert import into something supported by SystemJS:
import {...} from 'app/login/login';
export class LoginComponent {
constructor() {
}
}
You can notice that I remove the js extension since SystemJS allows to configure the default extension to add when resolving modules:
<script>
System.config({
packages: {
app: {
format: 'register',
defaultExtension: 'js'
}
}
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Use RAM after GPU memory is not enough
Is there any way to use RAM after GPU memory(NVIDIA) is completely used up in CUDA?
What I have thought up to now is:
Find a way to check if all the thread blocks are used
Move the process to RAM
But obiviously this will need alot of syncronization things.
Thank you!
A:
If the memory on the GPU is not enough you can use the host memory quite easily. What you are looking for is zero-copy memory allocated with cudaHostAlloc. Here is the example from the best-practice guide:
float *a_h, *a_map;
...
cudaGetDeviceProperties(&prop, 0);
if (!prop.canMapHostMemory)
exit(0);
cudaSetDeviceFlags(cudaDeviceMapHost);
cudaHostAlloc(&a_h, nBytes, cudaHostAllocMapped);
cudaHostGetDevicePointer(&a_map, a_h, 0);
kernel<<<gridSize, blockSize>>>(a_map);
However, the performance will be limited by the PCIe bandwitdh (around 6GB/s).
Here is the documentation in the best-practice guide: Zero-Copy
| {
"pile_set_name": "StackExchange"
} |
Q:
batch file to delete folder with special name
I want to delete all the folders with only digit name.
So I write a batch file using regular expression:
@echo off
D:
cd D:\Install\Work
for /d %%i in (*|findstr "^[0-9]*$") do (
rd /s /q %%i
)
echo [all the folders under work are deleted!]
pause
but it doesnt work. Where is the error?
A:
@ECHO OFF
SETLOCAL
FOR /f %%x IN (
'dir /ad /b * ^|FINDSTR "^[0-9]*$" '
) DO ECHO %%x
FOR /F reads lines from a file/command output to the metavariable.
for /d simply applies dirnames to the metavariable.
| {
"pile_set_name": "StackExchange"
} |
Q:
Javascript blocks other javascript codes
I purchased a document on www.themeforest.com, which generated a function like:
<!-- Start Live Chat Code -->
<script type="text/javascript" src="http://dev.testsite.com/support/assets/js/jquery.min.js"></script>
<script type="text/javascript">
var jQuery5524f88f85aa4 = $.noConflict();
jQuery5524f88f85aa4(document).ready(function($) {
$.get("http://dev.testsite.com/support/", function(data) {
$("body").append(data);
});
});
</script>
<!-- End Live Chat Code -->
But this code is blocking the other Javascript functions in my document. Does anyone have a idea how i could i fix this?
For example navigation dropdown's wouldnt work anymore etc.
A:
Can you wrap this inside a try catch block like this
<script type="text/javascript">
try {
var jQuery5524f88f85aa4 = $.noConflict();
jQuery5524f88f85aa4(document).ready(function($) {
$.get("http://dev.testsite.com/support/", function(data) {
$("body").append(data);
});
});
} catch (e) {
console.log(e.stack);
}
</script>
If this JS snippet is causing an exception that is blocking other JS on the page then you will be able to catch that using this try..catch
| {
"pile_set_name": "StackExchange"
} |
Q:
How to make it this display in a new line
I am getting a response from backend this way
{
"toppings": [
{
"name": "Quantity1",
"value": [
"HoneywithChocolateSauce10ML",
"HoneywithCarmel20ML",
"HoneywithCarmel10ML"
]
}
]
}
and i am parsing it in the below manner and forming the HTML dynamically
else if(toppins.length >= 0)
{
var uitaghtml = '<ul>';
for (var d = 0; d < toppins.length; d++) {
var uitaghtml = '<ul>' +
'<li>' + toppins[d].value + '</li>' +
'</ul>';
itemcart ='<div class="order-listdetails-wrap">
<div class="orderTitle">'+itemname+'</div>
<div class="orderCont">
<div class="img"><img src="'+image+'"/></div>
<div class="orderPrice">
<p>Qty: <span>1</span></p>
' + uitaghtml + '</ul>
</div>
</div>
</div>';
divhtml.append(itemcart);
}
}
With the above the HTML is displaying this way
Instead of comma seperated values , how to make that display one after another ??
A:
You're printing out the value property of your data, but that property's an array. You should iterate over it instead. I've done it here using jQuery:
var uitaghtml = '<ul>';
$.each(toppins[d].value, function(i, text) {
uitaghtml += "<li>" + text + "</li>";
});
uitaghtml += "</ul>";
You may also like to consider using a JavaScript templating library like Underscore or Handlebars to help you get your HTML out of your source code.
| {
"pile_set_name": "StackExchange"
} |
Q:
Changing div background image on mouseover & click in a separate location
I am currently trying to hover over a background image and see a new image in a separate div. Which works (with the code below), however I cant seem to get it to change when the image is clicked. below are images representing what I am trying to accomplish.
1 http://pkg.madisonmottdev.com/images/1.png
when hovered or clicked(same for the 2nd floor)
2 http://pkg.madisonmottdev.com/images/2.png
Javascript code currently using for the hovering, which works properly. I just cannot figure out how to click (the first or second floor and have it change on the right). Any help is appreciated.
$(window).load(function(){
$(document).ready(function(){
// FIRST FLOOR
$('.floor1').mouseover(function(){
$('.floor1').css('background', 'url("images/phase-2/first-floor-hover.a.png") no-repeat');
$('#elevation').css('background', 'url("images/phase-2/first-floor-lg.a.png") no-repeat');
});
$('.floor1').mouseout(function(){
$('.floor1').css('background', 'url("images/phase-2/first-floor.a.png") no-repeat');
$('#elevation').css('background', 'url("images/phase-2/elevation.a.png") no-repeat');
});
// SECOND FLOOR
$('.floor2').mouseover(function(){
$('.floor2').css('background', 'url("images/phase-2/second-floor-hover.a.png") no-repeat');
$('#elevation').css('background', 'url("images/phase-2/second-floor-lg.a.png") no-repeat');
});
$('.floor2').mouseout(function(){
$('.floor2').css('background', 'url("images/phase-2/second-floor.a.png") no-repeat');
$('#elevation').css('background', 'url("images/phase-2/elevation.a.png") no-repeat');
});
});
});
HTML code (floor1, floor2 & elevation are set to background images with height/width):
<div id="building">
<div id="floor">
<div class="floor1"></div>
</div>
<div id="floor">
<div class="floor2"></div>
</div>
</div>
A:
Is something like this what you're after?
http://jsfiddle.net/98wuW/19/
The trick is that if you've clicked floor1, then the floor1.mouseout can't remove the floor1 image in #elevation.
As it stands, you have floor1.mouseout to change the background image of #elevation back to the default. So suppose that you hover over floor1. Then you move the mouse off floor1. The floor1.mouseout will then set the background image of #elevation back to the default.
The trick is that, when you click floor1 you've got to set a flag or something that says "keep the floor1 image in #elevation." Then in the mouseout, you can check that flag to see if you can remove the floor image in #elevation or not.
It gets a little tricky with your example, because you've got two floors, both of which could be clicked, so you've got to check two flags on each mouseout.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to design form in material style template getting alignment issues
Hi am trying to design a form in material design bootstrap template causing alignment issues. getting difficult to place two input fields on same line, if i place drop down and text input on same line that doesn't looking in same line.
i have added an image for the expected output and the below fiddle has full code
Fiddle https://jsfiddle.net/hktq7zxv/12/
<div class="row">
<div class="form-group">
<div class="col-md-3">
<input type="email" class="form-control" id="inputEmail" value="+1" readonly> </div>
</div>
<div class="form-group">
<div class="col-md-5">
<input type="email" class="form-control" id="inputEmail" placeholder="Company Phone"> </div>
</div>
<div class="form-group">
<div class="col-md-2">
<input type="email" class="form-control" id="inputEmail" placeholder="Extension"> </div>
</div>
<div class="col-md-1">
<a href="javascript:void(0)" class="btn btn-primary">Add</a></div>
</div>
A:
You are not using bootstrap classes properly.
Your row should contain two 6 level column class and form-group form-group col-md-6 element if you want the elements to appear in a single row. Here is an example of an input and dropdown in one row. Moreover, your dropdown has a class of btn-group having margin which makes it look a bit different than the input. Here a link to the fiddle where I have fixed the first row, and removed the margin from the btn-group class.
http://jsfiddle.net/qf87qb63/8/
<div class="row">
<div class="form-group col-md-6">
<label for="inputEmail" class="control-label">Company Name</label>
<input type="email" class="form-control" id="inputEmail" placeholder="Company Name">
</div>
<div class="form-group col-md-6">
<label for="select111" class=" control-label">Select</label>
<select id="select111" class="form-control selectpicker" data-dropup-auto="false">
<option>Company Type</option>
<option>Connection Design Engineering </option>
<option value="Design Assist">Design Assist</option>
<option value="Engineering & Consulting">Engineering & Consulting</option>
<option value="Fabricators">Fabricators</option>
<option value="GC">GC</option>
<option value="Erectors">Erectors</option>
<option value="Steel Detailing">Steel Detailing</option>
<option value="Structural Engineering">Structural Engineering</option>
</select>
</div>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
How to insert date and time in vim along with string literal?
I'm new to Vim and trying to solve what might just be a very basic thing.
When I type dd and press <space> in insert mode, I want it to be replaced with [10-Feb-2011 10:10]. (notice the square brackets around date).
So, far I've been able to achieve this - :iab <expr> dd strftime("%e-%b-%Y %H:%M") which inserts date, but I also want it to be surrounded by square brackets.
I'm using Maemo's implementation of Vim on Nokia N900.
http://maemo.org/downloads/product/Maemo5/vim/
I'd also like to know how to make this change persistent so that the dd abbreviation is always available in all sessions of vim. (writing this line in ~/.vim or something like this).
A:
In your ~/.vimrc file:
:iab <expr> dd strftime("[%e-%b-%Y %H:%M]")
Note however that Vim uses your platform's strftime so the string it takes and the format flags in particular are platform-dependent.
| {
"pile_set_name": "StackExchange"
} |
Q:
Ionic + Angular POST request return state 404
I just updated on the new version on the Angular + Ionic and method for processing remote request stopped working and returns always 404 response.
Request is following:
Request Method:POST
Status Code:404 Not Found (from cache)
Request Headersview source
Accept:application/json, text/plain, */*
Content-Type:text/plain
Origin:file://
User-Agent:Mozilla/5.0 (Linux; Android 4.4.2; Lenovo Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/30.0.0.0 Mobile Safari/537.36
Request Payloadview source
{,…}
Code of the method which is processing remote request is following:
// set transfer credentials
$http({
method : 'POST',
url : $scope.remoteUrl,
data: {img_base64: "/9j/4AAQSkZ"},
headers: 'application/json',
timeout: 10000
// success response
}).success(function(data, status, headers, config) {
//SUCESSS
} else {
//PROCESSING ERROR
}
// error response
}).error(function(data, status, headers, config) {
// ERROR
});
I tried to solve it using this topic:
AngularJs $http.post() does not send data
and
Angular + Ionic Post request getting 404 not found
But without luck.
Server side is processing request by this way:
$inputJSON = file_get_contents('php://input');
$input= json_decode( $inputJSON, TRUE ); //convert JSON into array
If i'm trying to send request using Postman or Curl everything seems to be working.
Ionic info:
Node Version: v0.12.2
Cordova CLI: 5.0.0
Ionic CLI Version: 1.3.22
Xcode version: Xcode 6.3.1 Build version 6D1002
ios-sim version: Not installed
ios-deploy version: Not installed
AngularJS version:
"version": "1.3.13",
How can i solve it please?
Many thanks for any advice
A:
Hum, I just ran into the same problem: the header suggests it has been fetched from cache... But actually, it seems it has to do with a new security policy in new versions of Cordova.
Here's how I solved it:
I installed Cordova's whitelist plugin :
cordova plugin add cordova-plugin-whitelist
Then, add your content policy in your index.html as a meta tag (using your own host or '*' for accepting all requests) :
<meta http-equiv="Content-Security-Policy" content="default-src 'self' yourhost.com ws://localhost:35729 data: gap: https://ssl.gstatic.com; style-src 'self' 'unsafe-inline'; media-src *;script-src 'self' localhost:35729 'unsafe-eval' 'unsafe-inline';">
default-src is used for general requests; the ws://localhost:35729 host is used for live-reload in ionic serve.
script-src is used for secure script execution
unsafe-inline and unsafe-eval are required in order for angular to work properly.
data: gap: https://ssl.gstatic.com is only used on iOS.
self means the current host of the index.html file.
You'll have to add your own in order for your requests to work. Don't forget to add the protocol and the port if they're non-standard
You can skip the meta tag if you don't want it, but you'll get a lot of warnings from the whitelist plugin.
More info on how to configure this in the plugin's readme.
Then rebuild your app, and it should work again.
A:
I also had this problem and searched a lot then finally...
i removed the whitelist plugin:
cordova plugin remove cordova-plugin-whitelist
then renstalled it
cordova plugin add cordova-plugin-whitelist
It helped me and hope it solve your problem
| {
"pile_set_name": "StackExchange"
} |
Q:
how to deal with multiple devise model for omniauth in ruby on rails
I have a 3types of users (student, teacher and admin). Students will record their study, Teachers will supervise students and admins will administer service. So I made all users with a devise gem. Actually my purpose was that every user can login with facebook or twitter but I couldn't do that because omniauthable in devise supports only one devise model...
how to deal with multiple devise model for omniauth like
<%= link_to 'student login with facebook', ........ %>
<%= link_to 'teacher login with facebook', ........ %>
A:
You can follow this Devise guide on how to get around setting up multiple models with Devise :omniauthable here.
If you can get around using multiple models you should consider using 1 User model with 3 roles (Student, Teacher, Admin). Check out the cancancan gem and that might fit in better what with you are looking to do.
| {
"pile_set_name": "StackExchange"
} |
Q:
Mudar a cor do label de acordo com estado da tela
Estou tendo problemas para mudar a cor do conteúdo de um label, de acordo com o estado da minha tela (habilitado/desabilitado).
Gostaria de saber como eu faço para poder fazer com que ele mude a cor.
Fiz um exemplo bem simples (sem me preocupar com as melhores práticas de organização e etc)
Exemplo simplificado do código:
package cor;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MudaCor extends JFrame implements ActionListener
{
public final int DESABILITADA = 0;
public final int HABILITADA = 1;
public int estadoTela = DESABILITADA;
public JPanel jpBotoes = new JPanel();
JTextField tx1 = new JTextField();
JTextField tx2 = new JTextField();
private JButton botao01 = new JButton("Habilita");
private JButton botao02 = new JButton("Desabilita");
private String conteudo = "Teste de cor";
public MudaCor()
{
setTitle("Tela de teste");
setSize(400, 300);
add(posicaoComponentes());
habilitaComp(false);
estilo(conteudo);//metodo estilo
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public String estilo(String estilo)
{
String x = "<html><font color=#4a2d56> <b> Teste de cor </b> </font></html>"; //roxo
String y = "<html><font color=#225218> <b> Teste de cor </b> </font></html>";//verde
if(estadoTela != DESABILITADA)
{
return conteudo = x;
}
else
{
return conteudo = y;
}
}
public JComponent posicaoComponentes()
{
JPanel painel = new JPanel();
painel.setLayout(null);
JLabel label = new JLabel(estilo(conteudo));
painel.add(label);
label.setBounds(170, 150, 100, 25);
painel.add(tx1);
tx1.setBounds(130, 30, 150, 22);
painel.add(tx2);
tx2.setBounds(130, 70, 150, 22);
getContentPane().add("South", jpBotoes);
jpBotoes.setLayout(new GridLayout(1, 2));
adicionaBotao(botao01);
adicionaBotao(botao02);
return painel;
}
private void adicionaBotao(JButton botao)
{
jpBotoes.add(botao);
botao.addActionListener(this);
}
public void habilitaComp(boolean status)
{
if(estadoTela == DESABILITADA)
{
tx1.setEnabled(status);
tx2.setEnabled(status);
}
else
{
tx1.setEnabled(status);
tx2.setEnabled(status);
}
}
@Override
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource() == botao01)
{
habilitaComp(true);
}
else if (ae.getSource() == botao02)
{
habilitaComp(false);
}
}
public static void main(String[] args)
{
MudaCor cor = new MudaCor();
cor.setVisible(true);
}
}
A:
Antes de tudo quero deixar dois alertas sobre seu código:
Sempre inicie a tela dentro da Event-Dispatch-Thread, pois a API do swing não é Thread-Safe, e toda a interface precisa iniciar dentro desta unica Thread. Nesta resposta explica melhor o motivo para isto e eventuais problemas que podem ocorrer. Esta outra resposta mostra algumas maneiras de como iniciar a aplicação dentro desta Thread.
Evite usar layout absoluto, a API do swing provê de vários Layouts Managers para facilitar a vida do programador na hora de criar telas, além de tornar a tela flexível a diferentes tamanhos de monitores e resoluções, sem que seja necessário isso ser tratado diretamente no código. Layout absoluto irá quebrar a aparência da sua aplicação, dependendo do monitor onde a aplicação for executada.
Para alterar cor da fonte de um JLabel, basta utilizar o método setForeground(), mas mesmo adicionando isso no seu código, ele jamais altera a variável estadoTela e o parâmetro status do método habilitaComp, que é o que você está usando para alterar o status do componente, jamais é usado.
Fiz algumas alterações no seu código, para que a cor seja alterada conforme o valor booleano passado no método habilitaComp, não há necessidade de criar constantes:
public void habilitaComp(boolean status)
{
tx1.setEnabled(status);
tx2.setEnabled(status);
label.setForeground(status ? new Color(74, 45, 86) : Color.GREEN);
}
Com essa mudança, o método estilo e as constantes que você criou para controlar o estado deixam de ser necessárias, já que cria complexidade desnecessária para algo que dá para fazer utilizando operação ternária.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is a default constructor responsible for initializing members to default values?
A default constructor initializes all instance and class members to its default value.
is above statement True or False?
A:
No. The default constructor does nothing other than call super().
Instance fields are always initialized to their default values before any constructors are run (it isn't the constructor that does it).
And, of course, static fields ("class members") are not initialized by a constructor. That'd be silly.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why PHP does not have a function to redirect page at any given instant?
I'm aware that you can use the header('Location: next.php') to accomplish that as well as other possible solutions, but that must be used before any output is sent to the client. My question is why PHP doesn't support a function to page redirection at any given time. I just want to know why, not interested in solutions or workarounds. Thanks.
A:
You have to remember that PHP is a server side language. Therefore, once the page is loaded on the client's browser, you no longer have control or access to it. It would not be possible to manipulate the loading, reloading, or relocation of the client's browser window after the content has left the server.
| {
"pile_set_name": "StackExchange"
} |
Q:
PCA in matlab selecting top n components
I want to select the top N=10,000 principal components from a matrix. After the pca is completed, MATLAB should return a pxp matrix, but it doesn't!
>> size(train_data)
ans =
400 153600
>> [coefs,scores,variances] = pca(train_data);
>> size(coefs)
ans =
153600 399
>> size(scores)
ans =
400 399
>> size(variances)
ans =
399 1
It should be coefs:153600 x 153600? and scores:400 X 153600?
When I use the below code it gives me an Out of Memory error::
>> [V D] = eig(cov(train_data));
Out of memory. Type HELP MEMORY for your options.
Error in cov (line 96)
xy = (xc' * xc) / (m-1);
I don't understand why MATLAB returns a lesser dimensional matrix. It
should return an error with pca: 153600*153600*8 bytes=188 GB
Error with eigs:
>> eigs(cov(train_data));
Out of memory. Type HELP MEMORY for your options.
Error in cov (line 96)
xy = (xc' * xc) / (m-1);
A:
Foreword
I think you are falling prey to the XY problem, since trying to find 153.600 dimensions in your data is completely non-physical, please ask about the problem (X) and not your proposed solution (Y) in order to get a meaningful answer. I will use this post only to tell you why PCA is not a good fit in this case. I cannot tell you what will solve your problem, since you have not told us what that is.
This is a mathematically unsound problem, as I will try to explain here.
PCA
PCA is, as user3149915 said, a way to reduce dimensions. This means that somewhere in your problem you have one-hundred-fifty-three-thousand-six-hundred dimensions floating around. That's a lot. A heck of a lot. Explaining a physical reason for the existence of all of them might be a bigger problem than trying to solve the mathematical problem.
Trying to fit that many dimensions to only 400 observations will not work, since even if all observations are linear independent vectors in your feature space, you can still extract only 399 dimensions, since the rest simply cannot be found since there are no observations. You can at most fit N-1 unique dimensions through N points, the other dimensions have an infinite number of possibilities of location. Like trying to fit a plane through two points: there's a line you can fit through those and the third dimension will be perpendicular to that line, but undefined in the rotational direction. Hence, you are left with an infinite number of possible planes that fit through those two points.
After the first 400 components, there's no more dimensions left. You are fitting a void after that. You used all your data to get the dimensions and cannot create more dimensions. Impossible. All you can do is get more observations, some 1.5M, and do the PCA again.
More observations than dimensions
Why do you need more observations than dimensions? you might ask. Easy, you cannot fit a unique line through a point, nor a unique plane through two points, nor a unique 153.600 dimensional hyperplane through 400 points.
So, if I get 153.600 observations I'm set?
Sadly, no. If you have two points and fit a line through it you get a 100% fit. No error, jay! Done for the day, let's go home and watch TV! Sadly, your boss will call you in the next morning since your fit is rubbish. Why? Well, if you'd have for instance 20 points scattered around, the fit would not be without errors, but at least closer to representing your actual data, since the first two could be outliers, see this very illustrative figure, where the red points would be your first two observations:
If you were to extract the first 10.000 components, that'd be 399 exact fits and 9601 zero dimensions. Might as well not even attempt to calculate beyond the 399th dimension, and stick that into a zero array with 10.000 entries.
TL;DR You cannot use PCA and we cannot help you solve your problem as long as you do not tell us what your problem is.
A:
PCA is a dimension reduction algorithm, as such it tries to reduce the number of features to principal components (PC) that each represents some linear combination of the total features. All of this is done in order to reduce the dimensions of the feature space, i.e. transform the large feature space to one that is more manageable but still retains most if not all of the information.
Now for your problem, you are trying to explain the variance across your 400 observations using 153600 features, however, we don't need that much information 399 PC's will explain 100% of the variance across your sample (I will be very surprised if that is not the case). The reason for that is basicly overfitting, your algorithm finds noise that explain every observation in your sample.
So what the rayryeng was telling you is correct, if you want to reduce your feature space to 10,000 PC's you will need 100,000 observations for the PC's to mean anything (that is a rule of thumb but a rather stable one).
And the reason that matlab was giving you 399 PC's because it was able to correctly extract 399 linear combinations that explained some #% of the variance across your sample.
If on the other hand what you are after are the most relevant features than you are not looking for dimensional reduction flows, but rather feature elimination processes. These will keep only the most relevant feature while nulling the irrelevant ones.
So just to make clear, if your feature space is rubbish and there isn't any information there just noise, the variance explained will be irrelevant and will indeed be less than 100% for example see the following
data = rand(400,401);
[coefs,scores,variances] = pca(data);
numel(variances)
disp('Var explained ' num2str(cumsum(variances)) '%'])
Again if you want to reduce your feature space there are ways to that even with a small m, but PCA is not one of them.
Good Luck
| {
"pile_set_name": "StackExchange"
} |
Q:
Grails json cells with enum
In my code I have a domain object with an Enum type in it. That enum type saves and retrieves fine from the database. I am converting a list of domain objects into json cells. All fields except the enum are either a string or a long. When the json gets picked up 'on the other side' it displays [Object object] for the column, instead of the enum name or enum value. Is there something on either the domain or json side that would help with this? Code/example below
Domain Class
class MyDomain {
long id
long otherValue
MyEnum enu //Nullable per constraints
//Mapping and constraints are not special.
}
Enum
enum MyEnum {
ENUM1("Value1"),ENUM2("Value2")
//constructor ommitted
String myValue
String toString() { myValue }
Json cell creation
def jsonCells = domainList.collect
{
[cell: [
it.id,
it.otherValue,
it.enu?.value
],
id: it.id]
}
it.enu?.value works. However, is there somehow a better way to do this where I don't have to call the value every time and can rely on the object? I would have assumed that overriding the toString method would have taken care of it, but apparently I was wrong. I know it seems like a minor issue, but its easier to forget ".value", especially as the same enum will be used in many domain objects. Ideas?
A:
Since you're simply putting it in a List when building the object, it will treat it as an Object unless you specifically do something else with it (like you're doing currently).
One alternative would be to use it.enu as String or something similar, but that still probably doesn't achieve what you're trying to achieve.
Another (maybe overengineered?) way would be to create a method on the domain itself that returns the value, and then use that method when building JSON:
class MyDomain {
MyEnum enu
def enuVal() {
enu?.value
}
}
with
def jsonCells = domainList.collect {
[cell: [
it.enuVal()
],
...]
As for me, I guess I'd just prefer to use it.enu?.val in the JSON. Write a test for your JSON-rendering methods and make sure the value is what you expect it to be, so that you don't forget.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to specify the target location for downloading the remote file using mget command?
I have a batch file to do the bulk copy the file from remote location. This is working fine. But here I want to specify the local system location (target location).
Sample:
cd test/test
mget sample_*.zip
quit
A:
Use the lcd /path to change the current local working directory:
cd /source_remote_path
lcd /destination_local_path
mget sample_*.zip
quit
See the ftp man page.
If you are running Windows locally, use Windows style path, of course:
lcd c:\destination_local_path
See the Windows ftp.exe lcd command help.
| {
"pile_set_name": "StackExchange"
} |
Q:
What scale degrees form the most-used chords in a minor tonality?
We know that for songs written in a major tonality, the I, IV, V chords are the most used. The II chord is used often, the III and VI chords a slightly less often, and you almost never see the VII chord.
Are there similar trends found in the chords used in songs having minor tonality?
I know that while the major songs tend to use the V chord heavily, minor songs tend to use the relative major chord (the III chord). So I thought the common chords might be different for major and minor tonalities. I couldn't find anything on the Internet that explains that.
A:
In minor keys, most of the time i, iv, and V (often V7) are used. As for other scale degrees, you often see VI, but the other scale degrees aren't seen as often. ii° and vii° are diminished and need special resolution to sound good, while III+ is augmented and hard to fit in anywhere.
Here is an image of triads built on the various scale degrees (remember that the harmonic minor is used most commonly):
| {
"pile_set_name": "StackExchange"
} |
Q:
Multiple instances of Javascript function with resize function
I created a quick library to help me position text absolutely over a background image. It works great with one instance. As soon as I add multiple instances, the resize function inside the library function only works on the last instance.
Here is my library code -
function overlay(params) {
function resizeOverlay(params) {
//get the overlay container
var layContainer = document.getElementsByClassName(params.element)[0];
//user sets height and width of bg image used so we can calculate ratio
var bgHeight = params.height;
var bgWidth = params.width;
var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
x = w.innerWidth || e.clientWidth || g.clientWidth,
y = w.innerHeight|| e.clientHeight|| g.clientHeight;
var newSize = getFinalMeasurements(x, y, bgWidth, bgHeight);
var newPos = getNewPosition(x, y, newSize);
function getFinalMeasurements(x, y, natWidth, natHeight) {
var finalSize = {};
var originalRatios = {
width: x / natWidth,
height: y / natHeight
};
var coverRatio = Math.max(originalRatios.width, originalRatios.height);
finalSize = {
height: natHeight * coverRatio,
width: natWidth * coverRatio
}
return finalSize;
}
function getNewPosition(x, y, finalSize) {
var left = finalSize.width - x;
var top = finalSize.height - y;
var leftPos;
var topPos;
var finalPos = {};
if(left > 0) {
leftPos = left/2;
} else {
leftPos = left;
}
if(top > 0) {
topPos = top/2;
} else {
topPos = top;
}
finalPos = {
left: leftPos,
top: topPos
}
return finalPos;
}
layContainer.setAttribute('style', 'height:' + newSize.height + 'px; width:' + newSize.width + 'px; left: -' + newPos.left + 'px; top:-' + newPos.top + 'px');
}
resizeOverlay(params);
window.onresize = function() {
resizeOverlay(params);
console.log('resizing');
}
}
And then my instances -
var compassTextContainer = new overlay({
width: 2364,
height: 1314,
element: 'compass-overlay'
});
var liveFeedContainer = new overlay({
width: 2364,
height: 1314,
element: 'livefeed-overlay'
});
var rocketContainer = new overlay({
width: 2364,
height: 1314,
element: 'rocket-overlay'
});
All of them work on initial load but when I resize the window, the rocket-overlay element is the only one working.
A:
It's because you're using onresize that overrides the previous event listener. So each time you set up an instance, that instance's resize event listener will override the previous one, hence only the last one works.
To fix that use addEventListener which adds the new event listener without removing the previous ones:
window.addEventListener("resize", function() {
resizeOverlay(params);
console.log('resizing');
});
Note: Since the logic is repeated among all the instances, you could refactor your code to use event delegation which only sets one event listener. Also, try not to redefine the functions resizeOverlay and getNewPosition each time you call overlay, an IIFE is ideal for this:
var overlay = (function() {
function resizeOverlay(params) {
// ...
}
function getNewPosition(x, y, finalSize) {
// ...
}
return function(params) {
resizeOverlay(params);
window.addEventListener("resize", function() {
resizeOverlay(params);
});
}
})();
| {
"pile_set_name": "StackExchange"
} |
Q:
Store UmbracoIdentity data in SQL Server
I have implemented Umbraco using UmbracoIdentity for membership and everything was going fine until I deployed my solution to an Azure Web App. On azure I am getting permission errors because UmbracoIdentity is using a SQL Server CE database stored in the App_Data folder.
For reference the error I am getting is:
Exception type: SqlCeException
There is a file sharing violation. A different process might be using the file. [ ...\wwwroot\App_Data\UmbracoIdentity.sdf ]
My Umbraco data is being stored in an SQL database and I would like to store my UmbracoIdentity membership data here as well. I would appreciate any help in how to setup SQL Server as the user store for membership data.
A:
You need to implement the IExternalLoginStore.cs interface and then configure the application to use it. It should be fairly simple to implement as you can use the SQL Server CE implementation as an example. I've done one for Azure Table Storage - you can check the Readme at https://github.com/alindgren/UmbracoIdentity.AzureLoginStore to get an idea of how to configure the app to use a custom external login store (which for me was the least obvious part).
| {
"pile_set_name": "StackExchange"
} |
Q:
What makes turbomachinery so special in CFD
As my experience with CFD grows, I start to gain the feeling that turbomacinery is kind of special in CFD: there are special tools tailor for it. For example, ANSYS has TurboGrid or Vista TF for turbomachinery design. And OpenFOAM has special working group for turbomachinery. I wish to know what makes turbomacinery so 'stand out' in CFD technology, I am sure there is something special about it, otherwise we would just use general solvers. So, can somebody shed some light on this mystery (to me)?
A:
1) Turbomachinery is ubiquitous, used for the vast majority of power generation in the world. Therefor, there is a huge amount of money and vested interest in it for practical reasons.
2) Turbomachines are inherently extremely hard to do any kind of detailed experiments on. Visualizing the flowfield or getting any detailed force measurements of an operating turbomachine in order to improve the design is impossible-to-difficult for experiments. This leaves you with CFD as the primary practical tool.
| {
"pile_set_name": "StackExchange"
} |
Q:
Geometry homework question - enough data?
I've been asked to help with the following school problem on geometry.
In the triangle $\Delta ABC$ one has $AB = 60$, $AC = 80$. Point $O$ is the centre of the circumscribed circle. Point $D$ belongs to the side $AC$. Additionally, one has $AO \perp BD$. One is asked to find $CD$.
(just in case, the answer is $35$)
I am really puzzled, since the information given clearly does not fix the triangle. I know how to solve the problem under the assumption that point $O$ belongs to $BD$. In this case, the solution goes as follows:
Denote $\alpha = \angle OAC$, $\beta = \angle OBC$.
$\angle ACB = \dfrac{1}{2}\angle AOB = 45^\circ$.
From the sum of angles of the triangle $\triangle ABC$, one has:
$$\alpha + \beta = 45^\circ$$
The law of sines for the triangle $\triangle ABC$ gives:
$$\dfrac{AC}{\sin(\beta + 45^\circ)}=\dfrac{AB}{\sin(45^\circ)}$$
From where one can find $\beta$:
$$\beta = \arccos\left( \dfrac{2\sqrt2}{3} \right) + 45^\circ$$
From the triangle $\triangle AOD$ one finds:
$$CD = AC - AD = AC - \dfrac{AO}{\cos(\alpha)}= AC - \dfrac{AO}{\cos(45^\circ - \beta)}$$
Substituting the value of $\beta$ indeed gives $CD = 35$.
Now, I have two questions:
Is it possible to get the answer without the assumption I have made (or any other one).
Can anyone present an easier solution? (just in case, this is one of $26$ problems in the $9$th grade quiz in Russian middle school — students are obviously limited in time and are not supposed to use Mathematica and even Stack Exchange)
A:
Let $G$ be the point of intersection of $AO$ and $BD.$
$AGB$ is a right triangle.
Drop altitudes $OE$ and $OF$ to sides $AB$ and $AC$ respectively
Since $AOB$ and $AOC$ are isosceles, these altitudes bisect their respective sides.
$AFO$ is similar to $AGB$
$AF:AO = AG: AB$
$AO\cdot AG = 1800$
$AEO$ is similar to $AGD$
$AE:AO = AG: AD$
$AE\cdot AD = 1800$
$AD = 45$
$CD = 35$
A:
Draw the line $AO$ and let $E$ be the second point of intersection of $AO$ with the circumcircle of triangle $ABC$ (the first point of intersection being $A$). Then $AE$ is the diameter of the circumcircle and therefore triangle $ABE$ is a right triangle ( $\angle \, ABE = 90^{\circ}$ ). Let $H$ be the itnersection point of $BD$ and $AO$.
Since by assumption $BD$ is orthogonal to $AO$, and therefore orthogonal to $AE$, segment $BD$ is an the altitude of $ABE$ through $B$. Hence triangles $AHB$ and $ABE$ are similar and thus
$$\frac{AH}{AB} = \frac{AB}{AE}$$ which is equivalent to $$AH \cdot AE = AB^2 = 60^{2}$$
Triangle $AEC$ is right triangle ( $\angle \, ACE = 90^{\circ}$ ) and so is $AHD$, which means they are similar and thus
$$\frac{AD}{AE}=\frac{AH}{AC} $$ which is equivalent to $$AD \cdot AC = AH \cdot AE = 60^2$$ and since $AD = AC - CD = 80 - CD$ and $AC = 80$ get the equation
$$(80-CD)\cdot 80 = 60^2$$ When you solve it you get $CD = 35$.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.