text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Selenium: Can I combine several commands into one command to be referenced by other tests without coding
I'm currently evaluating Selenium and it seems I'll have to perform certain steps in my tests over and over again. Is there any way to wrap several steps from a selenium test into one single step which can be referenced by other tests?
It seems that this can be done with with custom coding as mentioned at in the UI-Element documentation, but I'd prefer to use the IDE if possible.
Thanks,
Adrian
A:
Actually there is a way. I added it to my blog article comparing Selenium to Coded UI
| {
"pile_set_name": "StackExchange"
} |
Q:
New model field showing in database query but not in django admin
I just added time_inserted = models.DateTimeField(auto_now_add=True) to my Shift model and when I query an object in the database it shows 'time_inserted': datetime.datetime(2018, 9, 5, 15, 26, 20, 226797) great! But I don't see it as a field in admin, how can I get it to appear there?
A:
Yes, when you set auto_now_add you implicitly set the readonly property, which means it won't by default show up in Django's model admin.
However, if you would just like to see the value of it; without changing it, you can do it with a custom ModelAdmin class:
class RatingAdmin(admin.ModelAdmin):
readonly_fields = ('time_inserted',)
admin.site.register(Rating,RatingAdmin)
| {
"pile_set_name": "StackExchange"
} |
Q:
Java: Split an int into separate variables
I need to split an int into separate variables.
For instance x=356 a=3|| b=5 || c=6
I have already solved it for 3 digit numbers only, but my program does not work for 2 digit or 4 digit numbers etc.
P.S.
I am a beginner.
A:
ArrayList<Integer> digits = new ArrayList<Integer>();
while (number > 0){
digit = number %10;
number/=10;
digits.add(digit);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
ような (you na) vs ように (you ni) grammar question
I have learnt that ように (you ni) can modify a verb. And ような (you na) modifies a noun. (I am not sure that is quite correct or not). Today I came across this sentence in "NHK easy Japanese" :
物を売る仕事になかなか人が集まらないため、店で働く人が集まるように、休みを多くしました
Firstly I don't know what it actually means.
Does it mean:
Because not a lot of people selling goods, many people took holidays by working inside the shops (!?).
休み【やすみ】 (yasumi) is a noun, so why is ように used instead of ような?
Thank you very much
A:
It means: Because the job of selling goods does not attract people, (we) increased holidays to attract more people to work in the shops.
店で働く人が集まるように (to attract more people to work in the shops) does not modify 休み, but the verb 多くしました, or the sentence 休みを多くしました. So this does not contradict the rule.
| {
"pile_set_name": "StackExchange"
} |
Q:
getClass().getResourceAsStream() in maven project
The pom.xml of my maven project looks as follows:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>groupId</groupId>
<artifactId>artifactId</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
</build>
</project>
In the src/main/resources directory I have a file called test.
In the src/main/java directory I have a class that contains the following line:
System.out.println(this.getClass().getResourceAsStream("test"));
When the line of code is run within Eclipse, I get as output
java.io.BufferedInputStream@1cd2e5f
When I export the project as .jar and run it I get as output
null
Did I configure anything wrong?
A:
Under <build><resources> make sure to have the <include> as below
This will explicitly tell maven to fetch these files and include it in the build.
<build>
<resources>
<resource>
<directory>${basedir}/src/main/resources</directory>
<includes>
<include>**/*</include>
</includes>
</resource>
</resources>
...
</build>
A:
I was facing this same problem.
When you are trying to get the resource like this:
getClass().getResourceAsStream("test")
You are trying to find the resource relative to that package.
To get the resource from the src/main/resources directory, you have to put a slash before the resource name.
getClass().getResourceAsStream("/test")
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I invoke an unknown Rust function with some arguments using reflection?
I'm having a lot of fun playing around with Rust having been a C# programmer for a long time but I have a question around reflection. Maybe I don't need reflection in this case but given that Rust is strongly typed I suspect I do (I would definitely need it in good ol' C#, bless its cotton socks).
I have this situation:
use std::collections::HashMap;
fn invoke_an_unknown_function(
hashmap: HashMap<String, String>,
// Something to denote a function I know nothing about goes here
) {
// For each key in the hash map, assign the value
// to the parameter argument whose name is the key
// and then invoke the function
}
How would I do that? I'm guessing I need to pass in some sort of MethodInfo as the second argument to the function and then poke around with that to get the arguments whose name is the key in the hash map and assign the values but I had a look around for the reflection API and found the following pre-Rust 1.0 documentation:
Module std::reflect
Module std::repr
[rust-dev] Reflection system
None of these give me enough to go on to get started. How would I implement the function I describe above?
A:
Traits are the expected way to implement a fair amount of what reflection is (ab)used for elsewhere.
trait SomeInterface {
fn exposed1(&self, a: &str) -> bool;
fn exposed2(&self, b: i32) -> i32;
}
struct Implementation1 {
value: i32,
has_foo: bool,
}
impl SomeInterface for Implementation1 {
fn exposed1(&self, _a: &str) -> bool {
self.has_foo
}
fn exposed2(&self, b: i32) -> i32 {
self.value * b
}
}
fn test_interface(obj: &dyn SomeInterface) {
println!("{}", obj.exposed2(3));
}
fn main() {
let impl1 = Implementation1 {
value: 1,
has_foo: false,
};
test_interface(&impl1);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
React + Typescript object props to component error
Simple case; I'm rendering a list of 'Reviews'. These are provided using the following Proptype:
export interface Props {
title: string;
name: string;
reviewdesc: string;
rating: number;
}
Mapping through the results in the parent component:
{reviews.map((review: Props) => {
return <Review data={review} />;
})}
And using the same Proptypes in the child component:
const Review = (data: Props) => { ...
It is giving me this error:
Type '{ data: Props; }' is not assignable to type 'IntrinsicAttributes & Props'.
Property 'data' does not exist on type 'IntrinsicAttributes & Props'.
It feels like I'm forgetting a little thing. I thought I should catch the Props like {data} in the child component, but it gives:
Property 'data' does not exist on type 'Props'.
A:
You are passing props incorrectly. Use,
<Review { ...review } />
... is called the spread operator and it "spreads" the properties of your object into props for that element.
| {
"pile_set_name": "StackExchange"
} |
Q:
Multirow vertical aligment issue
I am having issues with creating my table with multirow. Vertical aligment is not centered properly (letters are more at "top"). I think that is caused by "hline". When I use "toprule, midrule,.." aligment is good, but these commands have has issues with broken vertical borders. Please help me.
\documentclass[a4paper,12pt]{report}
\usepackage{array}
\usepackage{multirow}
\newcolumntype{M}[1]{>{\centering\arraybackslash}m{#1}}
\usepackage{tabularx}
\usepackage[none]{hyphenat}
\begin{document}
\begin{table}[htbf]
\center
\begin{tabular}{|M{1.7cm}|M{1.8cm}|}
\hline
bla &bla\\
\hline
\multirow{4}{*}{bla}
&bla\\ \cline{2-2}
&bla\\ \cline{2-2}
&bla\\ \cline{2-2}
&bla\\ \cline{2-2}
\hline
\end{tabular}
\end{table}
\end{document}
A:
Use \extrarowheight or, better, don't use vertical lines and load booktabs. Here is a demo of both solutions:
\documentclass[a4paper,12pt]{report}
\usepackage{array, booktabs}
\usepackage{multirow}
\newcolumntype{M}[1]{>{\centering\arraybackslash}m{#1}}
\usepackage{makecell}
\setcellgapes[t]{4pt}
\begin{document}
\begin{table}[!htbp] \centering%
\setlength\extrarowheight{2pt}
\begin{tabular}{|M{1.7cm}|M{1.8cm}|}
\hline
bla & bla \\
\hline
\multirow{4}{*}{bla} & bla \\
\cline{2-2} & bla \\
\cline{2-2} & bla \\
\cline{2-2} & bla \\
\hline
\end{tabular}
\end{table}
\begin{table}[!htbp] \centering%
\begin{tabular}{M{1.7cm} M{1.8cm}}
\toprule
bla & bla \\
\midrule
\multirow{4}{*}{bla} & bla \\[2pt]
& bla \\[2pt]
& bla \\[2pt]
& bla \\
\bottomrule
\end{tabular}
\end{table}
\end{document}
| {
"pile_set_name": "StackExchange"
} |
Q:
Inline text change not updating on ajax request (but changes on DB)
I'm using a script I found for changing a line of text on the go (you click on it and an input shows). It works fine without doing anything to the database but when I add my code for an update, it will update the DB but won't refresh the text after it submits. I'm totally lost now since I've been at it for hours, maybe I'm missing something very basic.
My JS:
$.ajaxSetup({
url: '/ajax/nombreruta.php',
type: 'POST',
async: false,
timeout: 500
});
$('.editable').inlineEdit({
value: $.ajax({ data: { 'action': 'get' } }).responseText,
buttons: '',
cancelOnBlur: true,
save: function(event, data) {
var html = $.ajax({
data: { 'action': 'save', 'value': data.value }
}).responseText;
//alert("id: " + this.id );
return html === 'OK' ? true : false;
}
});
nombreruta.php:
<?php session_start();
$action = isset($_POST) && $_POST['action'] ? $_POST['action'] : 'get';
$value = isset($_POST) && $_POST['value'] ? $_POST['value'] : '';
include $_SERVER['DOCUMENT_ROOT'] ."/util-funciones.php";//for my db functions
$cnx=conectar();
$sel="select * from ruta where id_ruta='".$_SESSION['ruta']."'";
$field=mysql_query($sel, $cnx);
if($row=mysql_fetch_object($field)){
$data = $row->nombre;
}
switch ($action) {
// retrieve data
case 'get':
echo $data;
break;
// save data
case 'save':
if ($value != '') {
$sel="update ruta set nombre='".$value."' where id_ruta=".$_SESSION['ruta'];
mysql_query($sel,$cnx) or die(mysql_error());
$_SESSION['data'] = $value;
echo "OK";
} else {
echo "ERROR: no se han recibido valores.";
}
break;
// no action
default:
echo "ERROR: no se ha especificado accion.";
break;
}
Firebug shows me that after I update my text it returns OK and after I refresh the site it will show the updated text but not before. I started thinking this approach is too much hassle but after so much hours I feel like I'm one step from my solution...
EDIT:
I'm using this plugin: http://yelotofu.com/2009/08/jquery-inline-edit-tutorial/
And my html is just
<span class="editable">Text</span>
A:
Your code works fine for me....
Here's the demo app I put together (asp.net, but basically the same minus the database).
Just to be clear: Press Enter to save. Click off to cancel (since you removed the buttons).
HTML
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" ></script>
<script type="text/javascript" src="https://raw.github.com/caphun/jquery.inlineedit/master/jquery.inlineedit.js"></script>
<script type="text/javascript">
$(function(){
$.ajaxSetup({
url: 'Test.ashx?' + window.location.search.substring(1),
type: 'POST',
async: false,
timeout: 500
});
$('.editable').inlineEdit({
value: $.ajax({ data: { 'action': 'get'} }).responseText,
buttons: '',
cancelOnBlur: true,
save: function (event, data) {
var html = $.ajax({
data: { 'action': 'save', 'value': data.value }
}).responseText;
return html === 'OK' ? true : false;
}
});
});
</script>
</head>
<body>
<span class="editable">Test 1</span>
</body>
</html>
C#
public void ProcessRequest(HttpContext context)
{
//Custom Object to Get and Format my Connection String from the URL
QueryStringObjects QSO = new QueryStringObjects(context.Request, "InlineAjaxTest");
//Look for any GET or POST params named 'action'
switch (context.Request.Params["action"])
{
//If 'action' = 'save' then....
case "save":
//Open a connection to my database (This is a custom Database object)
using (DataBrokerSql SQL = GetDataBroker(QSO.Connstring))
{
//Create a SQL parameter for the value of the text box
DbParameter[] Params = {
new SqlParameter("@val", context.Request.Params["value"])
};
//Execute an Insert or Update
SQL.ExecSQL(@"UPDATE
Test_InlineAJAX
SET
Value = @val
IF @@ROWCOUNT=0
INSERT INTO
Test_InlineAJAX
VALUES
(@val)", Params);
}
//Return OK to the browser
context.Response.Write("OK");
break;
default:
//Open a connection to my database
using (DataBrokerSql SQL = GetDataBroker(QSO.Connstring))
{
//Get Value from my table (there's only one row so no need to filter)
object obj = SQL.GetScalar("Select Value From Test_InlineAJAX");
//If my value is null return "" if not return the value of the object
context.Response.Write(obj != null ? obj.ToString() : "");
}
break;
}
}
SQL
CREATE TABLE [dbo].[Test_InlineAJAX](
[Value] [varchar](255) NULL
) ON [PRIMARY]
Not sure what else to tell you, but maybe something here will give you an idea...
| {
"pile_set_name": "StackExchange"
} |
Q:
Lexicographic ordering of triplets of integers in Matlab
I have the following problem: I have an array of N integer triplets (i.e. an Nx3 matrix) and I would like to order it lexicographically in Matlab. In order to do so I thought of using the built-in sort algorithm of Matlab, but I wanted to ask if the way I thought of doing it is right or if there exists a simpler way (preferably using Matlab routines).
I thought of converting every triplet into a single number and then sort these numbers with sort(). If my integers were between 0 and 9, I could just convert them into decimal. However, they are bigger. If their maximum absolute value is M, I thought of converting them into the (M+1)-ary system like this: if (a,b,c) the triplet, the corresponding integer is a*(M+1)^2+b*(M+1)+c. Would sorting these transformed integers solve the problem, or am I making a logical mistake in my reasoning?
Thank you!
PS: I know that sort() in Matlab does have a lexicographic option for strings, but my integers do not have the same digit length. Maybe padding them with leading zeros and concatenating them would do the trick?
A:
Have you considered using sortrows?
Should enable you to straight-forward sort your 3-columns of data lexicographically.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there any Javascript TCP Soket Library for PHP like SignalR with .NET?
I found SignalR library for ASP.NET developers that simplifies the process of adding real-time web functionality to applications.
Is there any similar library for php that also do the same job like signalR??
A:
Yes please find information at:
(1) http://php.net/manual/en/sockets.examples.php
(2) As well as can Creating Real Time Applications with PHP and WebSockets
PHPWebSockets is a WebSockets server written in PHP (https://github.com/ghedipunk/PHP-WebSockets).
The WebSocket server itself is a class that can be extended to write the rest of the application. The WebSockets.php is the base class and we need to extend that class to write our own simple WebSocket server application. The WebSockets.php base class does the socket management and WebSocket handshake.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it good practice to use the xor operator for boolean checks?
I personally like the exclusive or, ^, operator when it makes sense in the context of boolean checks because of its conciseness. I much prefer to write
if (boolean1 ^ boolean2)
{
//do it
}
than
if((boolean1 && !boolean2) || (boolean2 && !boolean1))
{
//do it
}
but I often get confused looks from other experienced Java developers (not just the newbies), and sometimes comments about how it should only be used for bitwise operations.
I'm curious as to the best practices regarding the usage of the ^ operator.
A:
You can simply use != instead.
A:
I think you've answered your own question - if you get strange looks from people, it's probably safer to go with the more explicit option.
If you need to comment it, then you're probably better off replacing it with the more verbose version and not making people ask the question in the first place.
A:
I find that I have similar conversations a lot. On the one hand, you have a compact, efficient method of achieving your goal. On the other hand, you have something that the rest of your team might not understand, making it hard to maintain in the future.
My general rule is to ask if the technique being used is something that it is reasonable to expect programmers in general to know. In this case, I think that it is reasonable to expect programmers to know how to use boolean operators, so using xor in an if statement is okay.
As an example of something that wouldn't be okay, take the trick of using xor to swap two variables without using a temporary variable. That is a trick that I wouldn't expect everybody to be familiar with, so it wouldn't pass code review.
| {
"pile_set_name": "StackExchange"
} |
Q:
Reduce/do.call to bind_rows in list of lists of data.frames
It has been hard for me expressing this in plain English, so if anyone can edit the language, that would be greatly appreciated.
I have a list object, where every element is a list of data.frame structures.
Some of these elements in the top level list might be empty, while the others have different numbers of data.frames (always an even number though).
My question (which seems suspiciously like the opposite of this one, is this:
How can I bind the rows of the data.frames in these lists so every element of the top-level list contains two data frames? These data.frames follow the same structure every time (I want to bind the rows of the data.frame number 1,3,5,7... and the data.frames number 2,4,6,8...
MRE as follows:
set.seed(1234)
listy <- list(`1` = list(),
`2` = list(a = data.frame(a1 = runif(1:3), a2 = runif(1:3)),
b = data.frame(a3 = runif(1:3), a4 = runif(1:3)),
c = data.frame(a1 = runif(1:3), a2 = runif(1:3)),
d = data.frame(a3 = runif(1:3), a4 = runif(1:3))))
listy is a list of 2 elements (1,2). Where 1 is empty. 2 is a list of data.frames (each with an even number of data.frames). I want to bind the rows of 2 so every element of the top level list has 2 data.frames (if they had data.frames in the first place).
My expected output is the following:
listb <- list(`1` = list(),
`2` = list(structure(list(a1 = c(0.113703411305323, 0.622299404814839, 0.609274732880294, 0.282733583590016, 0.923433484276757, 0.292315840255469), a2 = c(0.623379441676661, 0.860915383556858, 0.640310605289415, 0.837295628152788, 0.286223284667358, 0.266820780001581)), .Names = c("a1", "a2"), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame")), structure(list(a3 = c(0.0094957563560456, 0.232550506014377, 0.666083758231252, 0.186722789658234, 0.232225910527632, 0.316612454829738), a3.1 = c(0.514251141343266, 0.693591291783378, 0.544974835589528, 0.302693370729685, 0.159046002896503, 0.0399959180504084)), .Names = c("a3", "a3.1"), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"))))
Ideally, I would like to preserve listy, and its structure (the first element empty), the second one just with the bound rows. That is why I have tried the following, with no avail:
library(dplyr)
lapply(length(listy), function(i) {
#skip empty lists
if(length(listy[[i]]) < 1) {
next
} else {
#make two lists
#pairs list. even numbers
listy[[i]][[1]] <- do.call(bind_rows, listy[[i]][seq(1,length(listy[[i]]), by = 1) %% 2 == 0])
#pairs list. odd numbers
listy[[i]][[2]] <- do.call(bind_rows, listy[[i]][seq(1,length(listy[[i]]), by = 1) %% 2 == 1])
}
})
#another try, no positive result
lapply(length(listy), function(i) {
#skip empty lists
if(length(listy[[i]]) < 1) {
next
} else {
#make two lists
#pairs list. even numbers
listy[[i]][[1]] <- Reduce(bind_rows, listy[[i]][seq(1,length(listy[[i]]), by = 1) %% 2 == 0])
#pairs list. odd numbers
listy[[i]][[2]] <- Reduce(bind_rows, listy[[i]][seq(1,length(listy[[i]]), by = 1) %% 2 == 1])
}
})
A:
[Assuming that column names match]. It's often easier to lapply over the list itself because it gets easier to manipulate, instead of indices. Here you go:
listy2 <- lapply(listy, function(x){
#get length
current_length=length(x)
if(current_length==0){
res = x
} else{
res <- list(even=do.call(rbind,x[seq(2,current_length,by=2)]),
odd=do.call(rbind,x[seq(1,current_length,by=2)])
)
return(res)
}
}
)
> listy2
$`1`
list()
$`2`
$`2`$even
a3 a4
b.1 0.009495756 0.51425114
b.2 0.232550506 0.69359129
b.3 0.666083758 0.54497484
d.1 0.186722790 0.30269337
d.2 0.232225911 0.15904600
d.3 0.316612455 0.03999592
$`2`$odd
a1 a2
a.1 0.1137034 0.6233794
a.2 0.6222994 0.8609154
a.3 0.6092747 0.6403106
c.1 0.2827336 0.8372956
c.2 0.9234335 0.2862233
c.3 0.2923158 0.2668208
Edit with very much the same structure, but bind_rows to deal with more types inside the dataframe.
listy3 <- lapply(listy, function(x){
#get length
current_length=length(x)
if(current_length==0){
res = x
} else{
res <- list(even=bind_rows(x[seq(2,current_length,by=2)]),
odd=bind_rows(x[seq(1,current_length,by=2)])
# odd=do.call(bind_rows,x[seq(1,current_length,by=2)])
)
return(res)
}
}
)
| {
"pile_set_name": "StackExchange"
} |
Q:
Error (1093):You cant update target table for update in FROM Clause
This is the select statement which i have got the correct answer:
select s_billing_cycle.Billing_cycle from s_billing_cycle
join o_daily_lcsgeneration_copy on o_daily_lcsgeneration_copy.Location=s_billing_cycle.Location where o_daily_lcsgeneration_copy.Date between s_billing_cycle.From_Date and s_billing_cycle.To_Date
while updating the same query into another table i couldnt do that using update query getting :
You cant update target table "o_daily_lcsgeneration_copy" for update in FROM Clause
the query i have used is :
update o_daily_lcsgeneration_copy set o_daily_lcsgeneration_copy.Billing_cycle = (select s_billing_cycle.Billing_cycle from s_billing_cycle join o_daily_lcsgeneration_copy on o_daily_lcsgeneration_copy.Location=s_billing_cycle.Location where o_daily_lcsgeneration_copy.Date between s_billing_cycle.From_Date and s_billing_cycle.To_Date)
Help me !!!
A:
wrap it in a subquery (thus creating temporary table)
UPDATE o_daily_lcsgeneration_copy
SET o_daily_lcsgeneration_copy.Billing_cycle =
(
SELECT Billing_cycle
FROM
(
SELECT s_billing_cycle.Billing_cycle
FROM s_billing_cycle
INNER JOIN o_daily_lcsgeneration_copy
ON o_daily_lcsgeneration_copy.Location = s_billing_cycle.Location
WHERE o_daily_lcsgeneration_copy.DATE BETWEEN s_billing_cycle.From_Date
AND s_billing_cycle.To_Date
) s
)
or JOIN the tables
UPDATE o_daily_lcsgeneration_copy a
INNER JOIN s_billing_cycle b
ON a.Location = b.Location
SET a.Billing_cycle = b.Billing_cycle
WHERE a.DATE BETWEEN b.From_Date AND b.To_Date
| {
"pile_set_name": "StackExchange"
} |
Q:
Android R.anim,shake not found
I have followed the tutorial at:
http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/Animation1.html
The code is fine until I get to:
Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
It would appear that R.anim does not exist, eclipse suggests creating a field in in type R or creating a constant in type R. Correct me if I'm wrong but I don't believe either are the solution.
I am running Google APIs, platform 2.2, API 8 - I have tried higher levels but it didn't make a difference. All that I am trying to accomplish is a button shake on click...
Any feedback is appreciated,
Thanks
A:
You need to create the shake animation xml file. It will reside in
/res/anim/shake.xml
and it would look like this:
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="0" android:toXDelta="10" android:duration="1000"
android:interpolator="@anim/cycle_7" />
You then also need the interpolator (cycle_7.xml):
<cycleInterpolator xmlns:android="http://schemas.android.com/apk/res/android"
android:cycles="7" />
These files can both be found in
/path/to/android_sdk/samples/android-15/ApiDemos/res/anim
| {
"pile_set_name": "StackExchange"
} |
Q:
Troubleshooting some Exchange 2010 + iPhone email authentication problems
We have an Exchange Server 2010 that seems to be running fine.
Currently, we have most people able to connect to Exchange via various means and have a rich exchange email experience. Two of our users can't connect, though -> and I'm hoping someone can help explain some steps I can take to troubleshoot the server problems (assuming it's a server configuration issue).
Firstly, the following people can connect fine to Exchange 2010
Dad: iPhone (3Gs) + Mac Air (using Mail)
Mum: iPad (wifi) + iPhone (3G)
Sister: iMac (using Mail)
Wife: iMac (using Mail) and iPhone (3G) and iPad(wifi)
Everyone: OWA (any web browser)
Now, when I and my sister use our iPhone's (3Gs and 4G respectively) it keeps failing to connect.
It starts out saying:
Exchange Account. Unable to verify account information.
I'm assuming that i've entered our username/passwords correctly. I've also checked this by logging onto OWA with my username/password .. to confirm my credentials.
Now -> there's only ONE similarity between all these devices.
The ones that work -> our exchange account is the ONLY mail account on those devices.
For myself, I have another exchange account already in my phone. For my sister, she has an existing GMail account setup on her phone. So we're both trying to add a SECOND email account to our phones. Sounds weird, but that's the only pattern I can see.
So - i'm assuming this is some weird Exchange Server configuration issue. I'm not sure how I can see what is happening on the server.
Can someone suggest some things I can tick on/turn to verbose to get some info about what is happening, please - so I can troubleshoot any mobile user connection attempts?
A:
My first question is are the affected users members of (or have ever been a member of) a privileged group (such as Domain Admins or Enterprise Admins)? If so, ActiveSync has issues with administrative accounts.
You can turn up the diagnostic logging for ActiveSync to hopefully give you some pointers to the problem. Open up the Exchange Management Console and go to Server Configuration => Mailbox and chose Manage Diagnostic Logging Properties from the action pane.
Turn the MSExchange-ActiveSync options up to High and try to sync your iPhone and see if you get anything useful. Be sure to change the logging back down to Lowest when you've done - your server will love you for it.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to make JSLint tolerate a leading semi-colon?
The continuous integration software I am using runs JavaScript files through JSLint and complains if they fail (using default JSLint settings it appears).
I've always prepended a ; to the start of my jQuery plugins, so concatenating them doesn't lead to something like this...
common.js
I don't have access to this file, and can't enforce a semi colon at the end.
var abc = function() {
alert(arguments[0]);
}
plugin.js
This is my file that is concatenated with common.js. It is appended straight to the end of common.js.
(function($) {
$.fn.somePlugin = function() {}
})(jQuery);
jsFiddle of the problem this can cause.
jsFiddle of the solution (leading semi-colon of my plugin).
However, JSLint complains with...
Error:
Problem at line 1 character 1: Unexpected space between
'(begin)' and ';'.
;(function($) {
Problem at line 1 character 1: Expected ';' at column 5, not column 1.
;(function($) {
Problem at line 1 character 2: Missing space between ';' and '('.
...
I tried using a bang operator (!) instead, and a few other alternatives, but JSLint still complained.
What can I do to get this safety net and pass JSLint?
A:
Patch JSLint to not mind. Everyone will benefit.
| {
"pile_set_name": "StackExchange"
} |
Q:
Create memory index with Elasticsearch.net
I try to create memory index with following code but it creates regular index.
Any idea?
var node = new Uri("http://localhost:9200");
var settings = new ConnectionSettings(node);
var client = new Elasticsearch.Net.ElasticsearchClient(settings);
var js = JsonConvert.SerializeObject("{settings: { index.store.type: memory}");
var index = client.IndicesCreate("sampleIndex", js);
A:
Your second argument to the IndicesCreate method call is not correct. See the code below for a better way to achieve it. The first three lines are the same. In the fourth one, we properly create the settings for the index.
_body = new {
settings = new {
index = new {
store = new {
type = "memory"
}
}
}
};
var index = client.IndicesCreate("sampleIndex", _body);
| {
"pile_set_name": "StackExchange"
} |
Q:
Adding an Owin Startup Class in my project gives a SQL Server not found error
I have added the following startup code for Owin in my Startup.cs file -
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof(Biosimilia.Startup))]
namespace Biosimilia
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}
I have added a key in the Web.config file as -
<add key="owin:appStartup" value="Biosimilia.Startup" />
When I run the application with the startup file in place, I get the error -
Unable to connect to SQL Server Database.
If I remove the key and the startup file from the project, I get the following error -
The following errors occurred while attempting to load the app.
- No assembly found containing an OwinStartupAttribute.
- No assembly found containing a Startup or [AssemblyName].Startup class.
To disable OWIN startup discovery, add the appSetting owin:AutomaticAppStartup with a value of "false" in your web.config.
To specify the OWIN startup Assembly, Class, or Method, add the appSetting owin:AppStartup with the fully qualified startup class or configuration method name in your web.config.
If I add a key to my web.config to disable to startup discovery as following -
<add key="owin:AutomaticAppStartup" value="false"/>
I get the following error -
`No owin.Environment item was found in the context.`
I have looked at a lot of posts on the topic here already with no luck. Please help.
A:
I had the following line in my web.config >
This was resulting in a SQL Server connection timed out error. Removed this line from the web.config. The OWIN startup.cs class now runs correctly and the issue is resolved.
It appears that when using Identity, we do not need to have the roleManager explicitly enabled in the web.config.
| {
"pile_set_name": "StackExchange"
} |
Q:
querySelectorAll with forEach function not working for toggle button on carousel slides
I've created a template part in PHP that copies a button to each slide in a carousel using fullpage.js. The template part has a hidden div that should open up navigation for each slide. Trying the code below, I can only get this button to work on the first slide. I'm thinking an iterated class name might help, but not sure why querySelectorAll wouldn't do it. Any advice appreciated...
http://www.pulsecreative-clients.com/staging/hogshead/#golf
const clickOnMe = document.querySelectorAll(".course-button");
let clickOnMe = document.querySelectorAll(".course-button");
Array.from(clickOnMe).forEach(el => {
el.addEventListener("click", e => {
let showBox = e.currentTarget.nextElementSibling;
showBox.classList.toggle("open-nav");
});
});
.subnav-content {
position: fixed;
bottom: 15%;
z-index: 1;
box-sizing: border-box;
padding: 10px;
background-color: #000;
display: none;
}
.golfcoursebutton {
box-sizing: content-box;
min-width: 30px;
height: 30px;
padding: 4px;
margin: 4px;
background-color: #fff;
color: #000;
text-align: center;
}
.open-nav {
display: block;
}
<div id="jump-button" class="jumpbuttons-container">
<div class="subnav">
<button class="course-button">
JUMP TO <i class="fa fa-angle-up"></i>
</button>
<div class="subnav-content">
<div style="display: flex;">
<div class="golfcoursebutton"><a href="#golf/1">1</a></div>
<div class="golfcoursebutton"><a href="#golf/2">2</a></div>
<div class="golfcoursebutton"><a href="#golf/3">3</a></div>
<div class="golfcoursebutton"><a href="#golf/4">4</a></div>
<div class="golfcoursebutton"><a href="#golf/5">5</a></div>
<div class="golfcoursebutton"><a href="#golf/6">6</a></div>
</div>
<div style="display: flex;">
<div class="golfcoursebutton"><a href="#golf/7">7</a></div>
<div class="golfcoursebutton"><a href="#golf/8">8</a></div>
<div class="golfcoursebutton"><a href="#golf/9">9</a></div>
<div class="golfcoursebutton"><a href="#golf/10">10</a></div>
<div class="golfcoursebutton"><a href="#golf/11">11</a></div>
<div class="golfcoursebutton"><a href="#golf/12">12</a></div>
</div>
<div style="display: flex;">
<div class="golfcoursebutton"><a href="#golf/13">13</a></div>
<div class="golfcoursebutton"><a href="#golf/14">14</a></div>
<div class="golfcoursebutton"><a href="#golf/15">15</a></div>
<div class="golfcoursebutton"><a href="#golf/16">16</a></div>
<div class="golfcoursebutton"><a href="#golf/17">17</a></div>
<div class="golfcoursebutton"><a href="#golf/18">18</a></div>
</div>
</div>
</div>
</div>
EDIT
UPDATED WITH SOLUTION
A:
I've created a template part in PHP that copies a button to each slide in a carousel using fullpage.js.
Unfortunately, your code re-use is throwing an error. If we look at your source, we see:
div.jump-button
button.course-button
div.subnav-content
<script>
const clickOnMe = ...
</script>
This is repeated ~20 times.
The issue is that const can only be declared once. After that, JS will throw an error. In fact, if we view the console, we see just that:
Basically, after the first declaration of const clickOnMe, an error is thrown after. That's why only the first one works. I would look into moving (and consolidating) the <script> where you define clickOnMe to the bottom and invoke that once all the HTML is loaded.
Edit:
Regarding your comment, I see what you're referring to. You're now querying all the elements correctly by moving the event binding to the bottom (awesome!), but your event listener will need to be updated as well. The change is actually answered here (by @jeyko-caicedo) by referring to the event object when toggling the classList.
A more complete answer would be that you need to reference the event object (to reference the clicked element) and then query the sibling subnav-content. One way is what jeyko suggested (via closure of the forEach). The other is in the event handler with either: 1 walking up the DOM tree (using e.currentTarget.parentNode) or 2: just reference the element directly like e.currentTarget.nextElementSibling.
let clickOnMe = document.querySelectorAll(".course-button");
Array.from(clickOnMe).forEach(function(el) { // updated `e` to `el`
el.addEventListener("click", (e) => {
let showBox = e.currentTarget.nextElementSibling;
showBox.classList.toggle("open-nav");
});
});
| {
"pile_set_name": "StackExchange"
} |
Q:
C++ dynamic arrays. Why does this one work?
I was looking at this algorithm, the second one: Dynamic Programming Solution
http://www.geeksforgeeks.org/dynamic-programming-set-24-optimal-binary-search-tree/
It creates a dynamic array: int cost[n][n];
How does this work? I can run the code on GeeksForGeeks C++ emulator, but locally in Visual Studio I get the error "Expression must have a constant value".
What am I misunderstanding here? Doesn't C++ need to know the size of the array before compiling?
A:
The code is not standard.
type name[runtime_size]
Is what is called a variable length array. This is not standard in C++ and will only compile in compilers that have an extension for this like g++ or clang. The reason this extension exists is it is valid in C99.
You are completely correct that the size of the array must be known at compile time. If you need an array and the size will not be know until run time I suggest you use a std::vector or a std::unique_ptr<type[]>.
| {
"pile_set_name": "StackExchange"
} |
Q:
Apache Mesos - Zookeeper failing on load, cannot access marathon/attach slaves.
I am setting up a Mesos cluster. Our setup is:
3 Primary boxes (8gb RAM, 4 cpu)
3 Worker boxes (1gb RAM, 1 cpu)
The configuration files I have are all matching and proper from what I can see. In /etc/mesos/zk I have:
zk://106.133.117.128:2181,zk://153.213.95.171:2181,zk://106.121.34.29:2181/mesos
(I changed the IP addresses from the actual ones, but will use them with these same numbers when referenced throughout)
I am not quite sure where to go from here. I have stepped through each piece of configuration.
The ID's are located at /etc/zookeeper/conf/myid on each machine and properly set up. In the config on each machine for zookeeper conf they are set to the matching IP and id as well.
My Quorum size is 2.
IP and hostname are set to the IP of each machine respectively.
The configuration for marathon in /etc/marathon/conf/master reads:
zk://106.133.117.128:2181,zk://153.213.95.171:2181,zk://106.121.34.29:2181/marathon
The exact error from the logs is:
Log file created at: 2015/10/01 13:56:32
Running on machine: mesos-primary-1
Log line format: [IWEF]mmdd hh:mm:ss.uuuuuu threadid file:line] msg
I1001 13:56:32.595760 6618 logging.cpp:172] INFO level logging started!
I1001 13:56:32.596060 6618 main.cpp:229] Build: 2015-09-25 19:13:24 by root
I1001 13:56:32.596082 6618 main.cpp:231] Version: 0.24.1
I1001 13:56:32.596094 6618 main.cpp:234] Git tag: 0.24.1
I1001 13:56:32.596106 6618 main.cpp:238] Git SHA: 44873806c2bb55da37e9adbece938274d8cd7c48
I1001 13:56:32.596161 6618 main.cpp:252] Using 'HierarchicalDRF' allocator
I1001 13:56:32.602738 6618 leveldb.cpp:176] Opened db in 6.456045ms
I1001 13:56:32.611217 6618 leveldb.cpp:183] Compacted db in 8.423531ms
I1001 13:56:32.611312 6618 leveldb.cpp:198] Created db iterator in 22068ns
I1001 13:56:32.611348 6618 leveldb.cpp:204] Seeked to beginning of db in 1287ns
I1001 13:56:32.611372 6618 leveldb.cpp:273] Iterated through 0 keys in the db in 376ns
I1001 13:56:32.611448 6618 replica.cpp:744] Replica recovered with log positions 0 -> 0 with 1 holes and 0 unlearned
I1001 13:56:32.647243 6648 log.cpp:238] Attempting to join replica to ZooKeeper group
I1001 13:56:32.689388 6651 recover.cpp:449] Starting replica recovery
I1001 13:56:32.690028 6651 recover.cpp:475] Replica is in EMPTY status
W1001 13:56:32.690147 6649 zookeeper.cpp:101] zookeeper_init failed: Invalid argument ; retrying in 1 second
W1001 13:56:32.690726 6644 zookeeper.cpp:101] zookeeper_init failed: Invalid argument ; retrying in 1 second
W1001 13:56:32.690768 6647 zookeeper.cpp:101] zookeeper_init failed: Invalid argument ; retrying in 1 second
W1001 13:56:32.690821 6645 zookeeper.cpp:101] zookeeper_init failed: Invalid argument ; retrying in 1 second
I1001 13:56:32.690891 6618 main.cpp:465] Starting Mesos master
I1001 13:56:32.691463 6618 master.cpp:378] Master 20151001-135632-2088076136-5050-6618 (104.131.117.124) started on 106.133.117.128:5050
I1001 13:56:32.691494 6618 master.cpp:380] Flags at startup: --allocation_interval="1secs" --allocator="HierarchicalDRF" --authenticate="false" --authenticate_slaves="false" --authenticators="crammd5" --authorizers="local" --framework_sorter="drf" --help="false" --hostname="106.133.117.128" --initialize_driver_logging="true" --ip="106.133.117.128" --log_auto_initialize="true" --log_dir="/var/log/mesos" --logbufsecs="0" --logging_level="INFO" --max_slave_ping_timeouts="5" --port="5050" --quiet="false" --quorum="2" --recovery_slave_removal_limit="100%" --registry="replicated_log" --registry_fetch_timeout="1mins" --registry_store_timeout="5secs" --registry_strict="false" --root_submissions="true" --slave_ping_timeout="15secs" --slave_reregister_timeout="10mins" --user_sorter="drf" --version="false" --webui_dir="/usr/share/mesos/webui" --work_dir="/var/lib/mesos" --zk="zk://106.133.117.128:2181,zk://153.213.95.171:2181,zk://106.121.34.29:2181/mesoss" --zk_session_timeout="10secs"
I1001 13:56:32.691671 6618 master.cpp:427] Master allowing unauthenticated frameworks to register
I1001 13:56:32.691700 6618 master.cpp:432] Master allowing unauthenticated slaves to register
I1001 13:56:32.691725 6618 master.cpp:469] Using default 'crammd5' authenticator
W1001 13:56:32.691756 6618 authenticator.cpp:505] No credentials provided, authentication requests will be refused.
I1001 13:56:32.691790 6618 authenticator.cpp:512] Initializing server SASL
I1001 13:56:32.695333 6646 master.cpp:1464] Successfully attached file '/var/log/mesos/mesos-master.INFO'
I1001 13:56:32.695377 6646 contender.cpp:149] Joining the ZK group
W1001 13:56:33.690989 6649 zookeeper.cpp:101] zookeeper_init failed: Invalid argument ; retrying in 1 second
W1001 13:56:33.691220 6644 zookeeper.cpp:101] zookeeper_init failed: Invalid argument ; retrying in 1 second
Any input is much appreciated.
A:
You mesos zookeeper string is malformatted. It should be of the form
zk://host1:port1,host2:port2,host3:port3/path
That should fix your issue (barring any other configuration problems).
Answered on #mesos on freenode as well.
| {
"pile_set_name": "StackExchange"
} |
Q:
Dynamic event to handle download file async completed, and download async progress changed
im trying to create a tumblr image downloader,
my problem is when i need to download 100 image in one time.
i'm searching in google that i cant download 100 image in one time with one object webclient
so i will create new webclient every downloading.
the problem is eventhandler for downloadasyncCompleted and download progresschanged is always same.
how can i resolve this?
maybe my question is wrong
but what i need is :
1. download multiple file in one time
2. control the progresschanged event with dynamically created progressbar (progressbar total is same with how much the picture will download)
A:
I would make 30 threads each with their own web client and then use a ConcurrentQueue of string. Then push all the uri's only the queue then start all the threads they can have a while(trydequque()) and then each thread can dl. 30 threads works pretty good and a quad core pc. You can use download no need to use async this way.
ConcurrentQueue<string> queue = new ConcurrentQueue<string>();
queue.Enqueue("http://link.jpg");
for (var x = 0; x < 30; x++)
{
new Thread(new ThreadStart(() =>
{
//create webclient here
string uri;
while(queue.TryDequeue(out uri))
{
//download here
}
})).Start();
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Xcode: invalid variables view while debugging selected view
I have a subclass of UIButton, I'm using it in a storyboard. I'm adding some sublayers to its layer in the layoutSubviews() function. It shows up live fine in the storyboard.
In the storyboard, I'm doing Editor->Debug Selected Views. The breakpoint I've set is hit, but I can't inspect variables like "self" or "layer"
Why is that?
(lldb) po self
error: :1:1: error: use of unresolved identifier 'self'
self
^
(lldb) po layer
error: :1:1: error: use of unresolved identifier 'layer'
layer
^
Xcode Version 6.3 (6D570)
A:
From the Xcode 6.3 release notes:
Debugger
When using the debugger, the variables view may omit values for the current frame if the current function comes from a Swift framework.
Add -Xfrontend -serialize-debugging-options to the Other Swift Flags build setting for the framework. (20380047)
https://developer.apple.com/library/ios/releasenotes/DeveloperTools/RN-Xcode/Chapters/xc6_release_notes.html
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there any difference between 'document.getElementById()' and 'document.getElementById',can Round brackets make any difference?
given a piece of the code:
init: function () {
var tablebody;
if (!document.getElementById() || !document.createTextNode) return;
var ts = document.getElementsByTagName('table');
but it doesn't work.
A:
Yes!
document.getElementById()
This will call the function.
document.getElementById
This will check if the getElementById is defined on document and return it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can int variables be transferred from host to device in PyCUDA?
import pycuda.driver as cuda
import pycuda.autoinit
from pycuda.compiler import SourceModule
import numpy as np
dims=img_in.shape
rows=dims[0]
columns=dims[1]
channels=dims[2]
#To be used in CUDA Device
N=columns
#create output image matrix
img_out=np.zeros([rows,cols,channels])
#Convert img_in pixels to 8-bit int
img_in=img_in.astype(np.int8)
img_out=img_out.astype(np.int8)
#Allocate memory for input image,output image and N
img_in_gpu = cuda.mem_alloc(img_in.size * img_in.dtype.itemsize)
img_out_gpu= cuda.mem_alloc(img_out.size * img_out.dtype.itemsize)
N=cuda.mem_alloc(N.size*N.dtype.itemsize)
#Transfer both input and now empty(output) image matrices from host to device
cuda.memcpy_htod(img_in_gpu, img_in)
cuda.memcpy_htod(img_out_gpu, img_out)
cuda.memcpy_htod(N_out_gpu, N)
#CUDA Device
mod=SourceModule("""
__global__ void ArCatMap(int *img_in,int *img_out,int *N)
{
int col = threadIdx.x + blockIdx.x * blockDim.x;
int row = threadIdx.y + blockIdx.y * blockDim.y;
int img_out_index=col + row * N;
int i=(row+col)%N;
int j=(row+2*col)%N;
img_out[img_out_index]=img_in[]
}""")
func = mod.get_function("ArCatMap")
#for i in range(1,385):
func(out_gpu, block=(4,4,1))
cuda_memcpy_dtoh(img_out,img_in)
cv2_imshow(img_out)
What I have here is a 512 X 512 image. I am trying to convert all the elements of the input image img_in to 8 bit int using numpy.astype. The same is being done for the output image matrix img_out. When I try to use cuda.mem_alloc(), I get an error saying that 'type int has no attribute called size' and 'type int has no attribute called dtype'. Also, I get an error called 'int has no attribute called astype'. Could you state any possible causes ?
A:
You are getting a python error. You defined N as N=dims[1] so its just a single value integer. You can not call the function size on integers, as well, they are of size 1. Similarly, you can not check which type an int is, because well, its an int. You are doing that in the call to cuda.mem_alloc.
You dont need to allocate memory for a single int, you can just pass it by value. Define the kernel as __global__ void ArCatMap(int *img_in,int *img_out,int N) instead of passing a pointer.
| {
"pile_set_name": "StackExchange"
} |
Q:
Determinant of an $n \times n$-matrix
Can you help me with this $n\times n$ determinant? Can't find what from what i have to substract.. Spent hours of trying...
\begin{vmatrix}
1&\cdots& 1& 1& 4\\
1 &\cdots&1 & 9& 1 \\
1 & \cdots &16& 1 &1\\
\vdots & \dots& \vdots&\vdots&\vdots\\
(n+1)^2 &\cdots& 1& 1& 1
\end{vmatrix}
A:
We can rewrite this matrix as
$$
\pmatrix{0& \cdots & 0 & 0 & 2^2 - 1\\
0 & \cdots & 0 & 3^2 - 1 & 0\\
0 & \cdots & 4^2 - 1 & 0 & 0\\
\vdots & \ddots & \vdots & \vdots & \vdots\\
(n+1)^2 - 1 & \cdots & 0 & 0 & 0} + xx^T
$$
where $x = (1,1,\dots,1)^T$. From there, it suffices to apply the matrix determinant lemma.
| {
"pile_set_name": "StackExchange"
} |
Q:
d3.js: Transition the colours in an SVG linear gradient?
Just as the title says: with D3.js, is it possible to transition the colour of a linear gradient?
For example, if I have this gradient:
var gradient = svg.append("svg:defs")
.append("svg:linearGradient")
.attr("id", "gradient")
.attr("x1", "0%")
.attr("y1", "0%")
.attr("x2", "100%")
.attr("y2", "0%")
.attr("spreadMethod", "pad");
gradient.append("svg:stop")
.attr("offset", "0%")
.attr("stop-color", "yellow")
.attr("stop-opacity", 0.6);
gradient.append("svg:stop")
.attr("offset", "100%")
.attr("stop-color", "red")
.attr("stop-opacity", 0.6);
svg.append("svg:rect")
.attr("width", width)
.attr("height", 8)
.style("fill", "url(#gradient)");
Could I then transition it to become a gradient going from blue to red, rather than yellow to red?
A:
Yes -- changing the definition of a gradient is no different to changing the position of a circle or something like that as far as D3 is concerned. You could do what you want for example with the following code.
gradient.select("stop")
.transition()
.attr("stop-color", "blue");
| {
"pile_set_name": "StackExchange"
} |
Q:
Angular 8 - How to use pipes in an input with 2-way data-binding?
I'm a relative newbie when it comes to Angular and I'm building an Angular app and am looking to format an input field where a user inputs their income and it needs to be formatted so that it both has a GBP symbol before it and with commas separating out the value into thousands.
So, for example, a user adds their income as 34000 and it will be displayed as £34,000
I'm trying to use pipes to help me achieve this and I've tried using the CurrencyPipe and regular Pipes and I get the same issues with both. So, for example, with the number pipe I'll have:
<input type="number" (change)="getApp1income()" (keyup)="getApp1income()" [(ngModel)]="app1income | number" [ngModelOptions]="{standalone: true}" min="0" step="500" data-number-to-fixed="2" data-number-stepfactor="500" />
However, this gives me the following error:
Uncaught Error: Template parse errors:
Parser Error: Cannot have a pipe in an action expression at column 14 in [app1income | number=$event]
I'll get the same error when using CurrencyPipe as well. I think this has to do with the fact with the fact that ngModel is using 2-way data-binding as I'm using the value entered elsewhere. But I can't seem to find a solution at all and I've looked at various similar issues both on here and elsewhere.
Any help would be appreciated.
A:
If you're willing to use a third-party library for this, you can use ng2-currency-mask
npm install ng2-currency-mask --save
Add CurrencyMaskModule to the imports Array of the Module that you want to use this in.
Use it like this: <input currencyMask [(ngModel)]="value" [options]="{ prefix: '£ ', thousands: ',', precision: 0 }"/>
Here's a Working Sample StackBlitz for your ref.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to make my 6- and 8-year-old's stop using the f-word?
My kindergartener and 2nd grader have learned the f-word and a lot of other words in school and they say them at home. I never react too stubbornly with them or stop them to use those words. I gently talk to them that it is not good to say those kinds of words and we should not say them etc. I am of the opinion that if I am too stern about anything, they will start lying or hiding things/matters from me, which is worse. I want to keep them as open and transparent to me as possible.
Now the interesting thing is when I said they cannot use those words, they started creating their own secret language, and they have all kinds of corresponding words in that language which I don't want them to say in English.
What is the best way to stop them using those words in any language and make them truly realize that those words are bad? Again I don't want to be too strict or too threatening with them.
A:
I am of opinion that if i am too stern about anything, they will start lying or hiding things/matters from me which is worse
I see what you mean, but it seems to me that you're retreating before it's even come to a battle, because you're afraid of possible consequences. Generally speaking, I think that in parenting, this is unwise. Deal with the consequences when you actually have proof that they manifest themselves; don't retreat prematurely.
and they speak them at home. I never [...] stop them using those words.
In my opinion, you should. This is your home. As a parent, you have a say in how people speak in your home. Make it clear to them that using these words at home is unacceptable to you.
started creating their own secret language, and they have all kinds of corresponding words in that language which i don't want them to speak in English.
Okay, I think this is seriously cool. I'm sorry, but if my kids invented their own secret language with secret cuss words, I'd be impressed and amused. Ask yourself why you find invented cuss words so problematic. They're invented words which only make sense to your two children. Why is this a problem?
What is the best way to stop them using those words in any language and make them truly realize those words are bad?
I don't agree with your premise. I don't think any words are bad. Words are a means to an end; we use them to communicate. Words can be disrespectful, or inappropriate, or hurtful, but I don't think they're bad.
It's totally okay if you don't want certain words used in your presence, and it's important to teach your children that if they use certain words in certain contexts, they will tell other people something about themselves, their upbringing and their social standing. You can discuss this with them. Requiring your kids not to use certain words at home because they're inappropriate teaches them that there are contexts in which they have to watch their language. They will carry this skill over to other contexts later on.
But if I were you, I wouldn't try to make words "bad". I speak differently in different social settings, and I use words in some settings that I won't use in other settings. I don't speak the same way to my wife and kids that I speak with my male friends, and I use yet another language when I speak with students. When I was in the army, my language was much rougher than in all the other social settings. It's true that I use some cuss words very sparingly because I think they're inappropriate in pretty much every situation I find myself in, but I never thought of them as "bad" words. If you tell your kids that certain words are never to be spoken, you tell them that these different social situations don't exist, and IMO that's a bad idea because your kids will notice the world works differently all by themselves, and trust you a little less after that.
| {
"pile_set_name": "StackExchange"
} |
Q:
Could you simplify this sentence?
Could you simplify this sentencd. I can't get the meaning :
" ...every one of them fell ill because he had lost that which the living religions of every age have given to their followers, and none of them has been really healed who did not regain his religious outlook."
I have problem with that which ... in the first part of the sentence. And in the second part with ... heald who did not ...
Thanks.
A:
According to the writer, religions have always given their followers something, but s/he doesn't tells us what it is. (Perhaps it is explained earlier in the book.) The word "that" is used to mean 'that thing'.
They all fell ill because they had lost that thing which was given to them by religion. And only those people who regained their religious outlook have been really healed.
To heal means to make well again, or to make healthy.
Notice that "Everyone of them fell ill" is in the past tense but "none of them has been really healed" is in the present perfect tense. It means "people who did not regain their religious outlook have still (even today) not been healed."
| {
"pile_set_name": "StackExchange"
} |
Q:
Remove all bracketed text except for percentages
I'm trying to write a regex for removing text within brackets () or []. But, only places where it's not numbers with a percent symbol. Also, to remove the farthest bracket.
2.1.1. Berlin (/bɜːrˈlɪn/; German: [bɛʁˈliːn] (About this soundlisten)) is the capital and largest city of Germany by both area and population.[5][6] Its 3,769,495 (2019)[2] inhabitants make it the most populous city proper of the European Union. The two cities are at the center of the Berlin-Brandenburg capital region, which is, with about six million inhabitants. By 1700, approximately 30 percent (30%) of Berlin's residents were French, because of the Huguenot immigration.[40] Many other immigrants came from Bohemia, Poland, and Salzburg.
What I have now is removing everything between the brackets. But not considering the far end of the bracket.
re.sub("[\(\[].*?[\)\]]", "", sentence).strip()
A:
You may remove all substrings between nested square brackets and remove all substrings inside parentheses except those with a number and a percentage symbol inside with
import re
def remove_text_nested(text, pattern):
n = 1 # run at least once
while n:
text, n = re.subn(pattern, '', text) # remove non-nested/flat balanced parts
return text
text = "Berlin (/bɜːrˈlɪn/; German: [bɛʁˈliːn] (About this soundlisten)) is the capital and largest city of Germany by both area and population.[5][6] Its 3,769,495 (2019)[2] inhabitants make it the most populous city proper of the European Union. The two cities are at the center of the Berlin-Brandenburg capital region, which is, with about six million inhabitants. By 1700, approximately 30 percent (30%) of Berlin's residents were French, because of the Huguenot immigration.[40] Many other immigrants came from Bohemia, Poland, and Salzburg."
text = remove_text_nested(text, r'\((?!\d+%\))[^()]*\)')
text = remove_text_nested(text, r'\[[^][]*]')
print(text)
Output:
Berlin is the capital and largest city of Germany by both area and population. Its 3,769,495 inhabitants make it the most populous city proper of the European Union. The two cities are at the center of the Berlin-Brandenburg capital region, which is, with about six million inhabitants. By 1700, approximately 30 percent (30%) of Berlin's residents were French, because of the Huguenot immigration. Many other immigrants came from Bohemia, Poland, and Salzburg.
See the Python demo
Basically, the remove_text_nested method removes all matches in a loop until no replacement occurs.
The \((?!\d+%\))[^()]*\) pattern matches (, then fails the match if there are 1+ digits, %) to the right of the current location, then matches 0+ chars other than ( and ) and then matches ). See this regex demo.
The \[[^][]*] pattern simply matches [, then 0 or more chars other than [ and ] and then a ]. See the regex demo.
| {
"pile_set_name": "StackExchange"
} |
Q:
What encoding I should use in editor (NetBeans), if I were intend to print non-english character
I try to set the encoding of my editor to UTF-16. (Java String store the data in UTF-16 internally, right?)
alt text http://sites.google.com/site/yanchengcheok/Home/helloworld.png
And I type the following code
package helloworld;
/**
*
* @author yan-cheng.cheok
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
System.out.println("我爱你");
System.out.println("\u6587\u4EF6\u79CD\u7C7B");
}
}
However, the output is not what I expected :
alt text http://sites.google.com/site/yanchengcheok/Home/helloworld1.png
我爱你�
文件种类�
I try to change the editor encoding format to UTF-8, it works this time!
我爱你
文件种类
May I know why I need to change the editor encoding format to UTF-8 but not UTF-16? Isn't Java String store the data in UTF-16 internally?
A:
The best way is to store those string in a properties file.
Those string will be stored in unicode format, you can type them in your native language (japanese for example) and after that run the native2ascii command to convert them to unicode...
The advantage with that is that everyone will be able to open the .java and .jsp files... if they want to work with the phrases, then they open the properties file...
A:
Looks like a limitation of the underlaying platform ( Windows in this case ) which doesn't fully support UTF-16
Try investigating around this:
http://wiki.netbeans.org/TextEncodingFOW
http://bugs.sun.com/view_bug.do?bug_id=4163515
They're not definitive answers but may lead you.
| {
"pile_set_name": "StackExchange"
} |
Q:
Search for multiple column names in every table, and return table names
I'm trying to write a single query, for returning table names for every table in my database, that has 3 column names: gps time, shape, id.
I was looking for an answer, but everything works only for one column name.
SELECT table_name
FROM information_schema.COLUMNS
WHERE
TABLE_SCHEMA = 'db_name'
AND COLUMN_NAME = 'column_name'
When I add another "AND COLUMN_NAME = 'column_name2'" it returns 0.
Thank you in advance for any help.
A:
SELECT table_name
FROM information_schema.COLUMNS
WHERE
TABLE_SCHEMA = 'db_name'
AND COLUMN_NAME IN ('column_name', 'column_name2', 'column_name3')
GROUP BY table_name
HAVING COUNT(*) = 3
| {
"pile_set_name": "StackExchange"
} |
Q:
select tag in form not working
I have a form and a drop-down list inside it...
<form method="post" action="rew1.php" id="inputform">
<select form="inputform" name="some1">
<option value="" disabled="disabled" selected="selected">Select Travel Mode</option>
<option value="Train">Train</option>
<option value="Flight">Flight</option>
</select>
</form>
But when i post using this form the value Train Or Flight is not posted in to the database....
Here's The Server Side Code...
<?php
$con=mysqli_connect("127.0.0.1","root","plsdonthack","cab");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO cabs (NAME,IDNO,HOSTEL,MODE,DATE,TIME,TFNO,CONTACT)
VALUES
('$_POST[name]','$_POST[idno]','$_POST[hostel]','$_POST[mode]','$_POST[date]','$_POST[time]','$_POST[tfno]','$_POST[contact]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
header("location:http://localhost\overflow\index.html");
?>
What is the mistake i am making....?
A:
you should set name attribute for select like this:
<select name="something">
| {
"pile_set_name": "StackExchange"
} |
Q:
got error TypeError: urlretrieve() got an unexpected keyword argument 'CablingFilename' python
i am trying to make a list from a txt file that is online, this is part of the code
import urllib
def Dict(Filename,var1,var2):
FileDict = open(Filename,'r')
List = []
for l in FileDict:
if D in l:
pattern = re.split('W',l)
List.append(pattern[4])
more code...
return (thing1,thing2,List)
in1=raw_input("name of file \n >")
url='https.page_address'
in2=raw_input("other instructions")
in3=raw_input("other instructions2")
urllib.urlretrieve(url+in1, Filename = in1)
MyDict = Dict(in1,in2,in3)
But when i execute the script and type in1 (name of file), i get the error "TypeError: urlretrieve() got an unexpected keyword argument 'Filename' and i checked over and over but i do not know the error
hope somebody help, i am new at python so please dont be so hard
"
A:
The keyword is lowercase f, 'filename' not Filename.
filename = uri
Wrong way:
In [56]: import urllib
In [57]: in1 = "foo"
In [58]: urllib.urlretrieve("http://goo.gl/xymu6o",Filename=uri)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-58-e89982cacc95> in <module>()
----> 1 urllib.urlretrieve("http://goo.gl/xymu6o",Filename=in1)
TypeError: urlretrieve() got an unexpected keyword argument 'Filename'
Correct way:
In [59]: import urllib
In [60]:
In [60]: in1 = "foo"
In [61]: urllib.urlretrieve("http://goo.gl/xymu6o",filename=in1 )
Out[61]: ('foo', <httplib.HTTPMessage instance at 0x7fb580d57680>)
Just change to urllib.urlretrieve(url+in1, filename = in1)
or urllib.urlretrieve(url+in1, in1)
As you can see from the docs description:
urllib.urlretrieve(url[, filename[, reporthook[, data]]])
You pass url which is required and optional, filename not Filename
filename is a keyword arg, you cannot use Filename as it is simply not a valid keyword argument.
| {
"pile_set_name": "StackExchange"
} |
Q:
Alternative behaviour of && operator
I've faced such situation. I've used to program in C#, and such code:
if (condition1 && condition2){
//some actions
}
was asking both, condition1 and condition2 to be true (the case when they both are giving false and the end-result is true, could be achieved in other way).
In Flex, same code would perform "some actions" if the both conditions are false. I just was wondering if is there any chance to make it break after finding first false in a queue, or I have no choice and should write nested if's?
Thanks in advance :)
A:
ActionScript stops checking whenever it needs to.
if( false && true ){
}
This stops after the first false.
if( true && false ){
}
This stops after the second false.
if( true || false ){
}
This stops after the first true.
if( false || true ){
}
This stops after the second true.
Hope this helps...
A:
In Flex (actually AS3 to be exact), if condition1 is false, condition2 is not checked.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I make SMPTE colour bars using batch
I want to make this image
using Batch, but I'm not sure how- I know how to echo in batch, but I don't know what to echo, how to get the right colours and what the size of the windows should be. Should the size be:
mode con:cols=37 lines=22
A:
Using cecho.exe can do what you need.
mode con:cols=70 lines=20
for /l %%G in (1,1,10) do (
cecho.exe {07}aaaaaaaaa{#}{06}aaaaaaaaaa{#}{0B}aaaaaaaaaa{#}{0A}aaaaaaaaaaa{0D}aaaaaaaaaa{#}{04}aaaaaaaaaa{#}{01}aaaaaaaaa{#}{\n}
)
for /l %%G in (1,1,2) do (
cecho.exe {01}aaaaaaaaa{#} {0D}aaaaaaaaaa{#} {0B}aaaaaaaaaa{#} {07}aaaaaaaaa{#}{\n}
)
for /l %%G in (1,1,3) do (
cecho.exe {01}aaaaaaaaa{#}{0F}aaaaaaaaaa{#}{05}aaaaaaaaaa{#} {\n}
)
You can change the a's to whatever character you like - just note the codepage issue. You may want to change codepage(chcp) to 65000/65001 for Unicode in UTF-7 and UTF-8. Codepage 437(OEM is also a good option)
mode command changes the console size
The first for /l loop runs the command in the brackets 10 times
The second for /l loop runs the command in the brackets 2 times
The third for /l loop runs the command in the brackets 3 times
cecho echoes out colored text.
{nn} is the color code, followed by the text
{#} resets to the original console color
{\n} creates a new line
When you want to cecho a {, make sure you write {{.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is this case handled by distribution theory?
I want to express a distribution, $f(x)$, that has the following properties:
$$\int_{-\infty}^x f(x') \operatorname{d}x' = \left\{\begin{array}{cc}
0 & x \le 0 \\
\frac{1}{x} & x > 0.
\end{array}\right. = \frac{\Theta(x)}{x},$$
where $\Theta(x)$ is a unit step function. Formally, I would guess that I could just take the derivative using the standard rules to get:
$$f(x) = -\frac{\Theta(x)}{x^2} + \frac{\delta(x)}{x}.$$
The problem I have is that integrating the second equation above to recover the required property runs into an apparent $\infty - \infty$ ambiguity. Is this ambiguity handled in distribution theory in some particular way? Is this, perhaps, related in some way to the Cauchy principle value, for example?
Right now, my best guess for how to write $f$ to make it unambiguously have the needed property is to write it as:
$$f(x) = \lim_{s\rightarrow 0}\left(-\frac{1}{x^2} + \left[\frac{1}{x}\right] \frac{\partial}{\partial x} \right) \sigma(x,s), $$
where $\sigma(x,s)$ is a signmoid that satisfies $\lim_{x\rightarrow 0^+} \frac{\sigma(x,s)}{x^2} = 0$, $\sigma(x,s)=0$ if $x \le 0$, $\lim_{x\rightarrow \infty} \sigma(x,s) = 1$, $\lim_{s\rightarrow 0^+} \sigma(x,s) = \Theta(x)$, and the limit is understood, formally, to be delayed until after an integral is taken, the same way many think about the delta function. For example:
$$\sigma(x,s) = \frac{1}{2}\operatorname{erfc}\left(-\frac{\ln(x/s)}{s\sqrt{2}}\right) \Theta(x),$$
where $\mathrm{erfc}$ is the the standard complimentary error function.
A:
Let
$$\ln_+(x) = \begin{cases}\ln x, & x>0 \\ 0, & x\leq 0\end{cases}$$
This is in $L^1(\mathbb R)$ and thus a distribution. The derivative of it obviously satisfies
$$\ln_+'(x) = \begin{cases}\frac1x, & x>0 \\ 0, & x\leq 0\end{cases}$$
so you can take
$$f = \ln_+''.$$
I understand that you want it expressed in a more explicit form, but that's not always possible.
| {
"pile_set_name": "StackExchange"
} |
Q:
TypeError: __init__() got an unexpected keyword argument 'shape'
I am new to Tensorflow and I met an error while trying to run some sample codes.
import tensorflow as tf
g1 = tf.Graph()
with g1.as_default():
v = tf.get_variable("v", initializer=tf.zeros_initializer(shape=[1]))
Running the code above gives the error:
TypeError: __init__() got an unexpected keyword argument 'shape'.
The comment below says that tf.zeros_initializer does not accept 'shape' argument according to the documentation. I tried
v = tf.get_variable("v", initializer=tf.zeros_initializer())
and it says ValueError: Shape of a new variable (v) must be fully defined, but instead was .
So, what kind of argument/expression should I use to define the shape without causing a type error?
I cannot find how to solve it online. Please help. Thank you
A:
It appears that the book I'm using is a bit out of date. The following code appears to work so far.
v = tf.get_variable("v", shape=[1], initializer=tf.zeros_initializer)
I will check if it actually works with more code added later.
| {
"pile_set_name": "StackExchange"
} |
Q:
Double Pointer and Char
I have a problem with the set_ccs function. I cannot take elements from user. How can i fix that?
int main(){
char *ccs;
*ccs =(char*)malloc(sizeof(char) * 80);//i have to use dynamic memory allocation
printf("Enter CCS: ");
set_ccs(&ccs);
free(ccs);
return 0;
}
int set_ccs(char **ccs){
int i = 0;
scanf("%s",*ccs);//Is it better to use fgets? Because scanf seems to count 'enter'
while(*ccs!='\0'){
ccs++;
i++;
}
printf("Length of sequence : %d\n",i);//It always return 3
printf("%s",ccs); //with weird elements
return i;
}
Thanks already.
A:
In addition to unwinds answer that you should just use
char *ccs;
ccs = malloc(80);
You should make the function set_ccs() accept a pointer:
int set_ccs(char *ccs)
And call it like this from your main:
set_ccs(css);
Then in your function you can use scanf() like so:
scanf("%s", css);
Now you if you want to check for '\0', it is good practice to initialize your "string" to 0 before you use it. You can do that with calloc(80) instead of malloc(80).
If you need to have the pointer to pointer (char **ccs), you have to make a double pointer in your main, check this code:
int main(){
char *ccs;
char **ccs2; //a pointer to a pointer
ccs = calloc(80); //i have to use dynamic memory allocation
ccs2 = &ccs; //pass the address of the pointer to the double pointer
printf("Enter CCS: ");
set_ccs(ccs2); //pass the double pointer
free(ccs);
return 0;
}
int set_ccs(char **ccs){
int i = 0;
scanf("%s", *ccs);
char *c = *ccs; //copy to make increments
while(*c != '\0'){
c++;
i++;
}
printf("Length of sequence : %d\n", i);
printf("%s", *ccs);
return i;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to check if someone tries to share your program
I made a program (.jar) which I want to let others use, but not share with others without my permission. I thought about encryption, but I know they will just let the other people know the encryption password.
Is there any way in Java or Javascript Offline to check if someone attempts to share my program? or better yet a way to stop people from sharing, but allowing me to share (one time share or password to share)
Edit: prefer offline as i know how to do a online database solution
A:
you can ask their IP address and use that as a key then build a Jar file based on that. I hope this will help you.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to measure the sum of the areas of each class in QGIS?
The project has a layer with several groups of polygons with different weights. Each group is associated to a weight. How can I get the sum of the area of each group?
A:
You can use the GroupStats plugin to achieve your goals. Just make sure to add the area column to your data table. Here's a link to a tutorial for the plugin GroupStats
| {
"pile_set_name": "StackExchange"
} |
Q:
Can't access a session variable
I'm using a session variable to keep track of the current site language, three values are possible, 1. EN, 2. RU, 3. ES.
the session variable is set initially in the config file:
$_SESSION['lang'] = 'RU';
but inside my db class I cannot access the variable. My basic understanding is that variables stored in the $_SESSION array are accessible throughout the site.
so what's the problem?
A:
Be sure to call session_start(); before using a session variables.
| {
"pile_set_name": "StackExchange"
} |
Q:
sql update statement with from clause for validation?
I have an update operation that I perform on multiple users at once (the value stays the same). Is it possible to join tables to an update statement for reasons of validation?
For instance, here is my statement at the moment :
$user_set = array(1, 5, 10, 15, .....)
//update 'changed' status for ALL selected users at once
$stmt = $db->prepare("
UPDATE users
SET changed = ?
WHERE user_id IN(". implode(', ', array_fill(1,count($user_set),'?')) .")
");
array_unshift($user_set, 1);
$stmt->execute($user_set);
In a perfect scenario I would like to join one table (computers) to the users table to validate account ownership and if this update is 'valid' and should occur or not.
I found out earlier I can do EXACTLY that with DELETE, but can it be done with UPDATE as well? Example delete using validation I want :
$selected = array(1, 5, 10, 15, .....)
$stmt = $db->prepare("
DELETE del_table.*
FROM some_table as del_table
LEFT JOIN
users
on users.user_id = del_table.user_id
LEFT JOIN
computers
on computers.computer_id = users.computer_id
WHERE computers.account_id = ? AND del_table.activity_id IN(". implode(', ', array_fill(1,count($selected),'?')) .")
");
// use selected array and prepend other data into the array so binding and execute work in order
array_unshift($selected, $_SESSION['user']['account_id']);
$stmt->execute($selected);
EDIT (SOLUTION) :
Thanks Alex... it works!
$selected = array(5,10,12,13);
$stmt = $db->prepare("
UPDATE users
INNER JOIN computers
on computers.computer_id = users.computer_id
SET changed = ?
WHERE computers.account_id = ? AND users.user_id IN(". implode(', ', array_fill(1,count($selected),'?')) .")
");
array_unshift($selected, 1, $_SESSION['user']['account_id']);
$stmt->execute($selected);
A:
Yes, you can, as documented here under the multi-table syntax section.
UPDATE [LOW_PRIORITY] [IGNORE] table_references
SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
[WHERE where_condition]
You just need to make sure you order the statements correctly.
UPDATE my_table
INNER JOIN other_table
ON my_table.col2 = othertable.col2
SET my_table.col = 'foo'
WHERE other_table.col = 'bar'
| {
"pile_set_name": "StackExchange"
} |
Q:
How to format code like C# style for Java in Intellij?
I am using Intellij for Java development, but I prefer C# like coding style. How to format like C# code style? For example:
if()
{
/// do something
}
else
{
//// do something
}
A:
Go to
File -> Settings -> Editor -> Code Style -> Java
Go to Wrapping and Braces tab.
under Braces placement, there's a drop-down called Others, change it to Next Line. (by default it is End of line). This will change bracer placement for all the places other than class and method declaration.
If you want class and method declarations also to appear in that style, change 2 previous drop-downs in Braces placement section(In class declaration, In method declaration) to Next Line also.
| {
"pile_set_name": "StackExchange"
} |
Q:
JavaFX table update threading architecture mismatch
I have a JavaFX table which is ultimately with data received on a network thread.
Using Platform.runLater() to update the view-model is simple, but it does not fit into our architecture.
The current architecture separates applications into "view" and "network/comms" parts.
View listens to models and updates corresponding components. No knowledge of network.
Network listens to network updates and writes data into models accordingly. No knowledge of JavaFX.
So I'm in a dilemma.
To be true to the architecture and "separation of concerns" - the network reader class should not be calling Platform.runLater()
To keep it simple and have the network reader class call Platform.runLater() - just works - no additional code.
I've attempted to illustrate this in code
The simple approach
Just call Platform.runLater() from network reader
public class SimpleUpdate extends Application {
private int clock;
public class Item {
private IntegerProperty x = new SimpleIntegerProperty(0);
public final IntegerProperty xProperty() {
return this.x;
}
public final int getX() {
return this.xProperty().get();
}
public final void setX(final int x) {
this.xProperty().set(x);
}
}
@Override
public void start(Stage primaryStage) throws Exception {
ObservableList<Item> viewModel = FXCollections.observableArrayList();
TableView<Item> table = new TableView<Item>(viewModel);
TableColumn<Item, Integer> colX = new TableColumn<>();
colX.setCellValueFactory(new PropertyValueFactory<Item, Integer>("x"));
table.getColumns().add(colX);
primaryStage.setScene(new Scene(table));
primaryStage.show();
new Thread(() -> {
while (true) {
Platform.runLater(() -> { // update on JavaFX thread
if (clock % 2 == 0) {
viewModel.add(new Item());
viewModel.add(new Item());
} else {
viewModel.remove(1);
}
for (Item each : viewModel) {
each.setX(each.getX() + 1);
}
clock++;
});
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "Network update").start();
}
public static void main(String[] args) {
launch(args);
}
}
Pure approach
Network reader thread writes into its own model
View listener listens to network model and syncs its own view model using JavaFX thread
A lot more complicated
Code
public class PureUpdate extends Application {
private int clock;
public class Item {
private IntegerProperty x = new SimpleIntegerProperty(0);
public final IntegerProperty xProperty() {
return this.x;
}
public final int getX() {
return this.xProperty().get();
}
public final void setX(final int x) {
this.xProperty().set(x);
}
}
public class ViewItem extends Item {
private Item original;
public ViewItem(Item original) {
super();
this.original = original;
sync();
}
public void sync() {
setX(original.getX());
}
public Item getOriginal() {
return original;
}
}
@Override
public void start(Stage primaryStage) throws Exception {
ObservableList<ViewItem> viewModel = FXCollections.observableArrayList();
TableView<ViewItem> table = new TableView<ViewItem>(viewModel);
TableColumn<ViewItem, Integer> colX = new TableColumn<>();
colX.setCellValueFactory(new PropertyValueFactory<ViewItem, Integer>("x"));
table.getColumns().add(colX);
primaryStage.setScene(new Scene(table));
primaryStage.show();
ObservableList<Item> networkModel = FXCollections
.synchronizedObservableList(FXCollections.observableArrayList());
networkModel.addListener((Observable obs) -> {
Platform.runLater(() -> {
List<Item> alreadyKnown = new ArrayList<>();
for (Iterator<ViewItem> it = viewModel.iterator(); it.hasNext();) {
ViewItem each = it.next();
alreadyKnown.add(each.getOriginal());
if (networkModel.contains(each.getOriginal())) {
each.sync();
} else {
it.remove();
}
}
for (Item each : networkModel.toArray(new Item[0])) {
if (!alreadyKnown.contains(each)) {
viewModel.add(new ViewItem(each));
}
}
});
});
new Thread(() -> {
while (true) {
if (clock % 2 == 0) {
networkModel.add(new Item());
networkModel.add(new Item());
} else {
networkModel.remove(1);
}
for (Item each : networkModel) {
each.setX(each.getX() + 1);
}
clock++;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "Network update").start();
}
public static void main(String[] args) {
launch(args);
}
}
Question. Can I achieve the pure approach without writing additional code?
A:
Have the processor post notifications to a Runnable. or a Consumer<T>, or define a custom @FunctionalInterface.
This will make testing easier to as you design out threading and the dependency on JavaFX or any other framework needing synchronization on a specific thread.
Example using consumer:
public class NetworkReader {
private final Consumer<? super Data> consumer;
public NetworkReader(Consumer<? super Data> consumer) {
this.consumer = Objects.requireNonNull(consumer);
}
public void readStuff() {
while (...) {
Data data = ...;
consumer.accept(data);
}
}
}
The NetworkReader would be constructed with e.g. new NetworkReader(d -> Platform.runLater(() -> updateModel(d)));
When you want to test you could pass do as follows:
NetworkReader reader = new NetworkReader(d -> this.actuals = d);
reader.readStuff();
assertEquals(expecteds, actuals);
A smart consumer could coelesc updates until it has actually been processed.
| {
"pile_set_name": "StackExchange"
} |
Q:
PostrgreSQL 8.4: Summation by account numbers
I am doing some report on financial accounts, and I need to sum values at levels depending on the initial numbers...
For example sum all values for account starting with 0 (01, 011, 012..), or starting with 1 (1, 10, 111...), or starting with 111 (111,1112,1113...) etc.
Here is simplified sample table:
CREATE TABLE account(id, acctNo, credit) AS (
VALUES
(1, '01', 100)
,(2, '011', 200)
,(3, '0112', 300)
,(4, '014', 400)
,(5, '0144', 500)
,(6, '0148', 600)
,(7, '01120', 100)
,(8, '01121', 100)
,(9, '0140', 50)
,(10,'02', 50)
,(11,'021', 50)
,(12,'1', 50)
,(13,'10', 100)
,(15,'100', 50)
,(14,'1021', 50)
,(16,'202', 50)
,(17,'221', 50)
,(18,'4480', 50)
,(19,'447', 50)
,(20,'5880', 50)
)
I managed to do it but it is kinda robust SQL, is there some better solution?
Here is code:
WITH
a AS (SELECT SUBSTRING(acctNo,1,1) AS LEVEL,
SUM(credit) AS sum1 FROM account GROUP BY LEVEL
ORDER BY LEVEL),
b AS
(SELECT SUBSTRING(acctNo,1,2) AS level2,
SUM(credit) FROM account GROUP BY level2
ORDER BY level2),
c AS
(SELECT SUBSTRING(acctNo,1,3) AS level3,
SUM(credit) FROM account GROUP BY level3
ORDER BY level3),
d AS (SELECT SUBSTRING(acctNo,1,4) AS level4,
SUM(credit) FROM account GROUP BY level4
ORDER BY level4),
e AS (SELECT SUBSTRING(acctNo,1,5) AS level5,
SUM(credit) FROM account GROUP BY level5
ORDER BY level5)
SELECT * FROM
(SELECT a.* FROM a
UNION (SELECT b.* FROM b WHERE char_length(level2)>=2)
UNION (SELECT c.* FROM c WHERE char_length(level3)>=3)
UNION (SELECT d.* FROM d WHERE char_length(level4)>=4)
UNION (SELECT e.* FROM e WHERE char_length(level5)>=5)) a
ORDER BY LEVEL
This is only for 5 levels(five-digit numbers)...Is there some generic solution? What if tomorrow I'll need for 6 levels, etc...
Here is SQL Fiddle
Thanks.
A:
Yay generate_series!
SELECT substring(a.acctNo from 1 for g.g) as level, sum(a.credit)
FROM account a, generate_series(1,5) g
where length(a.acctNo) >= g.g
group by 1
order by 1
| {
"pile_set_name": "StackExchange"
} |
Q:
Configuring multiple upload repositories in Gradle build
I want to upload my artifacts to a remote Nexus repo. Therefore I have configured a snaphot and a release repo in Nexus. Deployment to both works.
Now I want to configure my build so I can decide in which repo I want to deploy:
gradle uploadArchives should deploy to my snapshots repo
gradle release uploadArchives should deploy to my release repo
This was my try:
apply plugin: 'war'
apply plugin: 'maven'
group = 'testgroup'
version = '2.0.0'
def release = false
repositories {
mavenCentral()
mavenLocal()
}
dependencies{ providedCompile 'javax:javaee-api:6.0' }
task release <<{
release = true;
println 'releasing!'
}
uploadArchives {
repositories {
mavenDeployer {
repository(url: "http://.../nexus/content/repositories/releases"){
authentication(userName: "admin", password: "admin123")
}
addFilter('lala'){ x, y -> release }
}
mavenDeployer {
repository(url: "http://.../nexus/content/repositories/snapshots"){
authentication(userName: "admin", password: "admin123")
}
addFilter('lala'){ x, y ->!release}
pom.version = version + '-SNAPSHOT'
}
}
}
The build works if I comment out one of the two mavenDeployer configs, but not as a whole.
Any ideas how to configure two target archives in one build file?
A:
One solution is to add an if-else statement that adds exactly one of the two deployers depending on the circumstances. For example:
// should defer decision until end of configuration phase
gradle.projectsEvaluated {
uploadArchives {
repositories {
mavenDeployer {
if (version.endsWith("-SNAPSHOT")) { ... } else { ... }
}
}
}
}
If you do need to vary the configuration based on whether some task is "present", you can either make an eager decision based on gradle.startParameter.taskNames (but then you'll only catch tasks that are specified as part of the Gradle invocation), or use the gradle.taskGraph.whenReady callback (instead of gradle.projectsEvaluated) and check whether the task is scheduled for execution.
A:
Correct me if I'm wrong, but shouldn't you use the separate snapshotRepository in this case (as opposed to an if statement)? For example,
mavenDeployer {
repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2/") {
authentication(userName: sonatypeUsername, password: sonatypePassword)
}
snapshotRepository(url: "https://oss.sonatype.org/content/repositories/snapshots/") {
authentication(userName: sonatypeUsername, password: sonatypePassword)
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Set Post Format if find a string in title or post content
I'm working with ITFFF in order to create posts, but I have a problem with the "Post Format". I need to change the Post Format to image if there are some specifics strings in the title or post content.. I was reading the forum and collecting some codes to create a this.. but it isn't working. This is my code:
add_action( 'save_post', 'CambiarPostFormat' );
function CambiarPostFormat( $postID ) {
$a = get_the_title( $post_id );
if ( has_post_format( 'image', $postID ) || srtpos($a, 'imagenes') !== false)
return;
set_post_format( $postID, 'image' );
}
A:
You are using $post_id, but you have passed the post ID as $postID. As a result $a is always empty.
Even if it weren't empty, there is no PHP function srtpos. It's strpos and you could have more straightforward logic to execute set_post_format.
Wrapping it up:
function CambiarPostFormat( $postID ) {
$a = get_the_title( $postID );
if ( !has_post_format( 'image', $postID ) && strpos($a, 'imagenes') !== false)
set_post_format( $postID, 'image' );
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Reusing an 8 bit microprocessor? (86CH09NG)
I salvaged some parts from a microwave and I am wondering if it is possible/ feasible to reuse the 8 bit microprocessor on it? I am also not sure if I found the proper datasheet for it? (link to datasheet)
A:
ROM (MaskROM)
Nope.
Well, yes, but only for what it was already used for. Mask ROM means that the programming is directly part of the silicon and cannot be changed.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to tear down testbed resources in Tasty conditionally?
I use Haskell's Tasty framework for testing. When I acquire and clear resources, I do it with withResource Tasty's function:
withResource :: IO a -> (a -> IO ()) -> (IO a -> TestTree) -> TestTree
where a is type of resource. But I want to keep resources if tests fail and to clear them only if tests passed. How is it possible?
A:
Test failures (at least in tasty-hunit) are implemented as exceptions. The purpose of withResource and bracket is to free resources even when there is an exception. If you write straight-line code like this, the resource will be freed if and only if the assertions pass:
testCase "resource management" $ do
a <- allocate
assertBool =<< runTest
cleanUp a
| {
"pile_set_name": "StackExchange"
} |
Q:
Does Android Studio emulator affect Firestore login?
My app is not automatically logging in when I restart the Android emulator. I believe previously it was doing so - though this might have been a bug caused by some bad code I have since ironed out. So to troubleshoot this problem I first need to discover whether or not this is simply a feature of the emulator.
Here is my code. I've confirmed that it successfully logs into FirebaseAuth and creates a user. According to documentation, automatically logging in on reboot should be as easy as this:
@Override
public void onStart() {
super.onStart();
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
// Check if user is signed in (non-null)
firebaseUser = auth.getCurrentUser();
}
A:
The emulator has no bearing on the way Firebase Auth actually works. The problem is almost certainly that you're asking the SDK if the user is signed in before the SDK is certain about that. Instead of calling auth.getCurrentUser() you should use an auth state listener to get a callback when the final authentication state of the user is known. It might not be known immediately at launch, as the user's token might have expired and need to be refreshed at the server. This takes time.
Your app should wait until this auth state listener indicates that the user is actually signed. This means that your listener will actually be the thing to move your UI along to do things like make queries and present data to the user.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to utilize code analysis with no default branch
I'm currently trying to setup some code analysis for my team however I found our release process does not mesh well with the tools I have looked into (CodeClimate and SonarQube). Both tools require a default branch to track the state or "grade" of your repository over time. They watch the default branch and analyze pull requests to that branch. However, our current release process involves a new branch for each release which we merge into master after the branch is released. We could use master as our default branch but we would not see the analysis until after the code is out which is not ideal. As I am not in a position to change our process, I am tasked with finding a tool or work around to get an analysis tool to work with our process. The only work around I could think of is two pull requests. One to the release branch as usual, and another to master just to trigger the analysis. The master PR would then be closed once the issues found in the analysis are fixed. This is far from ideal and I come to my favorite forum looking for help and experience.
Code is in Github.
Primary language to analyze is PHP, bonus languages are CSS, JS, and Java.
A:
It looks like Codacy could be a good alternative.
You can enable the analysis on all the branches of your project. All the pull requests to an analysed branch will be analysed, even if it's not the default branch.
It supports all the required languages: PHP, JS, CSS, Java and more. It also has a nice auto-comment integration with Github to help you save more time in code reviews.
| {
"pile_set_name": "StackExchange"
} |
Q:
What table is affected by delete when form based on query?
In MS Access 2003 I have a form whose record source is equal to a query that involves an INNER JOIN. The join is between a location table and a container table. Containers are objects that are stored in specific locations each location and container are specified by ID values.
SELECT DISTINCTROW Container.Container_ID, Location.Location_ID
FROM Location INNER JOIN Container
ON Location.[Location_ID] = Container.[Location_ID]
What I am trying to figure out is this …. When I delete a record (using the form navigation controls) in the form based on the above query which tables are affected? Are records in the Container and Location tables deleted or is it just in the location table?
A:
Without a relationship defined, you will delete the current row from Container and leave Location unchanged.
However, I think you should add a relationship and enforce referential integrity to assure you can't delete a location which still has a container stored there. Otherwise you could wind up with a Container record which refers to a Location_ID which no longer exists. The relationship may not help with this form and query, but it can safeguard against mistakes in other situations.
There are other ways to design your form which would make it easier to understand which record will be deleted from where. You could base a main form on Location and include a subform based on Container. In the properties set Location_ID as the link master/child field. Then for the Location_ID displayed in the main form, all the containers stored at that location will be displayed in the subform. Use the subform to delete whichever container you want.
| {
"pile_set_name": "StackExchange"
} |
Q:
Modify a JavaScript Object while iterating its properties
Can javascript implement pass-by-reference techniques on function call? You see, I have the JSON below and I need to traverse all its node. While traversing, if the current item is an Object and contains key nodes, I must add another property isParent: true to that exact same item. But I'm having difficulty on creating a traversal function with such feature, and I tried to search for traversal functions, but all I found only returns a new JSON object instead of changing the exact JSON that is being processed.
var default_tree = [
{
text: "Applications",
nodes: [
{
text: "Reports Data Entry",
nodes: [
{ text: "Other Banks Remittance Report" },
{ text: "Statement of Payroll Deduction" },
...
]
},
{
text: "Suspense File Maintenance",
nodes: [
{ text: "Banks with Individual Remittances" },
{ text: "Employers / Banks with Employers" },
...
]
}
]
},
{
text: "Unposted Transactions",
nodes: [
{ text: "Unposted Borrower Payments"},
{ text: "Unposted CMP Payments"}
]
},
{ text: "Maintenance" },
{
text: "Reports",
nodes: [
{
text: "Daily Reports",
nodes: [
{
text: "List of Remittance Reports",
nodes: [
{ text: "Banks" },
...
{
text: "Employers-LBP",
nodes: [
{ text: "Employers-Zonal" }
]
},
]
},
...
]
},
...
]
}
]
Considering we have this traversal function:
function traverse(json_object) {
// perform traversal here
}
traverse(default_tree)
After it runs the traverse function, the default_tree's value will remain the same unless we do something like:
default_tree = traverse(default_tree)
Can someone help me create an iterator will really alter the Object being processed while iterating, instead of returning a new Object?
A:
Please check this one
var default_tree = [....] //Array
function traverse(arrDefaultTree){
arrDefaultTree.forEach(function(val,key){
if(val.hasOwnProperty("nodes")){
val.isParent = true;
traverse(val.nodes);
}
})
}
traverse(default_tree);
console.log(default_tree);
Hope this helpful.
| {
"pile_set_name": "StackExchange"
} |
Q:
Become Anonymous over the internet
As the title suggests, How can I become anonymous over the internet, i.e disallow the websites from tracking my public as well as private IP address.
Please help!
A:
You have many many options to varying degrees of anonymity. One of the best options is to use TOR browser and connect to TOR network and follow all the guidelines provided by the TOR community.
Simpler steps include, using the incognito or private browsing mode in modern browsers and using anonymous proxy servers
| {
"pile_set_name": "StackExchange"
} |
Q:
Logic app expression for path to File not working
I tried to find documentation in the subject but fell short until now.
I am trying to use Logic Apps in order to update a table when a trigger occurs.
Adding some context:
In many separate excel online file that are located in different area of Sharepoint, I have one Table in each of those files. Anytime the SQL table is updated, I get the following elements:
Name
Age
path_to_doc
doc_id
Name and Age are element I wish to add in those Excel file.
path_to_doc is the path to the Excel file that needs to be updated.
doc_id is the id of the Excel file that needs to be updated.
In the "Add row to a table" action, those are the elements that need to be filled:
Site (Manual no problem, this doesn't change) Document Library
(Manual no problem, this doesn't change)
File (this is where I have a first problem: when I do not click
manually, and try to put either the "path_to_doc" or the "doc_id"
instead, it doesn't work.
Table (It seems that I can force it to be Table1), which is fine
because all my Excel files have the table called Table1
Arguments (that is Azure understands the Table and is componnents and
asks you to fill the ones you need to fill, those elements disappear
when you change from a manual input to an input "path_to_doc" or
"doc_id").
It throws me an error:
ERROR 400
NOTE: When I do it manually, it works.
Anyone has experienced this and found a solution?
Thank you
A:
Finally found the answer.
I needed to go to the code view and add my dynamic details there for the body.
Thank you for your help.
Here is the solution. I hope it helps others :)
In the designer view, create an action "Add a row into a table" and use the dynamic path that brings you to the excel file that you need to update. It will show an error and you will not be able to add the body arguments.
In the code view, now you can manually add the body of the request to include the element you wish to update in the Table of the excel file.
That's it!
| {
"pile_set_name": "StackExchange"
} |
Q:
Apt-get update through Tor
I'm trying to update my apt-get list. In my country a lot of sites are blocked or have been blocked from companies.
When I use a proxy for the whole system I get errors,
Tor works perfectly when browsing.
Can I update apt-get through a connection from Tor?
I mean I want to unblock the blocked sites using Tor connection, so I can perform apt-get update without errors.
Edit: I'm using Ubuntu 13.10 and Tor 0.2.21
$ sudo apt-get update
[sudo] password for alexander:
Ign http://extras.ubuntu.com saucy InRelease
Ign http://security.ubuntu.com saucy-security InRelease
Ign http://us.archive.ubuntu.com saucy InRelease
Hit http://extras.ubuntu.com saucy Release.gpg
Get:1 http://dl.google.com stable InRelease [1,540 B]
100% [1 InRelease gpgv 1,540 B] [Waiting for headers] [Waiting for headers]
[WaSplitting up/var/lib/apt/lists/partial/dl.google.com_linux_chrome_deb_dists_stabIgn
http://dl.google.com stable InRelease
E: GPG error: http://dl.google.com stable InRelease: Clearsigned file isn't valid,
got 'NODATA' (does the network require authentication?
A:
Install the apt-transport-tor package and then:
Edit /etc/apt/sources.list to add the prefix tor+ to your repositories.
deb tor+http://deb.debian.org/debian unstable main
deb-src tor+http://deb.debian.org/debian unstable main
This will allow apt to run over tor.
Note: Substitute http://deb.debian.org/debian unstable main with the appropriate sources for your distribution.
A:
You can use torsocks, It's shell wrapper to torify applications, to simplify the use of the Tor socks.
torsocks apt-get update
| {
"pile_set_name": "StackExchange"
} |
Q:
Is creating a new object recursively slower than creating a reference?
Say I have the following code:
public static ArrayList<Integer> doSomething(int n) {
ArrayList<Integer> list = new ArrayList<Integer>();
if (n <= 0)
return list ;
list = ListMethods.doSomething(n - 1);
list.add(n);
return list;
Is this any slower than this code:
public static ArrayList<Integer> doSomething(int n) {
ArrayList<Integer> list = null;
if (n <= 0)
return list = new ArrayList<Integer>();
list = ListMethods.doSomething(n - 1);
list.add(n);
return list;
I ask because one of my lecturers uses the latter code in his notes, whereas I've seen other guides online use the former. Is it just personal preference, or is there a speed difference? Additionally, if there is a speed difference, is it too small to be concerned with?
A:
Yes, the first code is slower. For every value of n greater than 0, you end up with the first part equivalent to:
ArrayList<Integer> list = new ArrayList<Integer>();
list = ListMethods.doSomething(n - 1);
There's no point in creating a new ArrayList object and immediately assigning a different value to the same variable.
The second code is better, but could still be improved significantly in terms of readability:
public static ArrayList<Integer> doSomething(int n) {
if (n <= 0) {
return new ArrayList<Integer>();
}
ArrayList<Integer> list = doSomething(n - 1);
list.add(n);
return list;
}
This only uses a list variable if it actually needs to. It's pointless to even declare it for the n <= 0 case, where you're just going to return a new ArrayList<Integer>.
| {
"pile_set_name": "StackExchange"
} |
Q:
Stretch isolated cells or to max width of table
I was trying to achieve the following table,
using php as follows
<?php
while($rowcustomer = mysql_fetch_array($querycustomer)){
echo '<tr><td bgcolor="#FFFFFF" style="color: #CC3300;"><h2>'.$rowcustomer['cusname'].'</h2></td></tr>';
echo '<tr><td bgcolor="#FFFFFF" style="color: #CC3300;"><h2>'.$rowcustomer['cusname'].'</h2></td></tr>';
echo '<tr height="20">
<td width="120" height="20" bgcolor="#FFFFFF"><h3>Invoice Date</h3></td>
<td width="120" bgcolor="#FFFFFF"><h3 align="center">Invoice Number</h3></td>
<td width="120" bgcolor="#FFFFFF"><h3 align="center">Invoice Amount</h3></td>
<td width="120" bgcolor="#FFFFFF"><h3 align="center">Payed Amount</h3></td></tr>';
}
?>
But I get the following
instead of what I need, how can I achieve it?
A:
Quick answer, add colspan="4" to the td that spans all the columns:
HTML
<td bgcolor="#FFFFFF" style="color: #CC3300;" colspan="4">
Longer answer :) - Let's clean up some HTML:
Example fiddle - Fiddle Link!
HTML
<table>
<thead>
<tr>
<th colspan="4">Header</th>
</tr>
<tr>
<th colspan="4">Header2</th>
</tr>
</thead>
<tbody>
<tr>
<td>aaaaa</td>
<td>aaaaa</td>
<td>aaaaa</td>
<td>aaaaa</td>
</tr>
<tr>
<td>aaaa</td>
<td>aaaaa</td>
<td>aaaaa</td>
<td>aaaaa</td>
</tr>
<tr>
<th>Invoice Date</th>
<th>Invoice Number</th>
<th>Invoice Amount</th>
<th>Payed Amount</th>
</tr>
</tbody>
</table>
CSS - add extra styles and ditch the width="120" bgcolor="#FFFFFF"
table {
border-collapse: collapse;
}
td, th {
border: solid 1px #CCC;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to build a graph of resolved instances with Autofac?
After all registrations, I am doing ContainerBuilder.RegisterCallback and subscribing to all IComponentRegistration.Preparing and IComponentRegistration.Activating events to be able to handle all activations. With this two events I am able to build a tree, the order of events looks like this:
Preparing: Root
Preparing: FirstLevel_A
Activating: FirstLevel_A
Preparing: FirstLevel_B
Preparing: SecondLevel_C
Activating: SecondLevel_C
Activating: FirstLevel_B
Activating: Root
But what if some registrations are not Per Dependency and I will have a graph instead of a tree. Is it possible to handle this case?
A:
According to this answer there's another way of handling these events:
If you want to get fancier, you can set up some event handlers on the
container ChildLifetimeScopeBeginning, ResolveOperationBeginning,
ResolveOperationEnding, and CurrentScopeEnding events.
During ChildLifetimeScopeBeginning you'd need to set up something to
automatically attach to any child lifetime ResolveOperationBeginning
events.
During ResolveOperationBeginning you'd log what is going to be
resolved.
During ResolveOperationEnding you'd log any exceptions
coming out.
During CurrentScopeEnding you'd need to unsubscribe from
any events on that scope so the garbage collector can clean up the
lifetime scope with all of its instances.
It's harder, but should do the job.
| {
"pile_set_name": "StackExchange"
} |
Q:
Which HTML elements can't have an id or class?
According to the HTML4 spec,
Almost every HTML element may be assigned identifier and class information.
What it doesn't say is which elements can't have an id or class. Which elements can't?
A:
Your question specifically mentions the HTML 4.01 standard. If you look at the bottom of the documentation for id and class at MDN, you'll see a table of which specifications these attributes are present in. The table shows:
The current version of HTML is HTML 5.x, which has been standardized for several years now and formally introduced "global attributes". In that standard, global attributes, can be used anywhere according to the documentation and the actual HTML specification, but may not have any impact depending on where you use them:
Global attributes are attributes common to all HTML elements; they can
be used on all elements, though the attributes may have no effect on
some elements.
For all practical purposes, everything in the body (including body) can have an id and/or a class, head can have an id, but given that there is only one head in a document (and only one body for that matter), that is never really needed. Nothing outside of the body would ever need a class.
| {
"pile_set_name": "StackExchange"
} |
Q:
when take photo get - java.lang.Throwable: file:// Uri exposed through ClipData.Item.getUri()
The Exception is:
file:// Uri exposed through ClipData.Item.getUri()
java.lang.Throwable: file:// Uri exposed through ClipData.Item.getUri()
at android.os.StrictMode.onFileUriExposed(StrictMode.java:1618)
at android.net.Uri.checkFileUriExposed(Uri.java:2341)
at android.content.ClipData.prepareToLeaveProcess(ClipData.java:808)
at android.content.Intent.prepareToLeaveProcess(Intent.java:7926)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1506)
at android.app.Activity.startActivityForResult(Activity.java:3832)
at android.app.Activity.startActivityForResult(Activity.java:3783)
at android.support.v4.app.FragmentActivity.startActivityFromFragment(Unknown Source)
at android.support.v4.app.Fragment.startActivityForResult(Unknown Source)
at me.chunyu.ChunyuDoctor.Utility.w.takePhoto(Unknown Source)
at me.chunyu.ChunyuDoctor.Dialog.ChoosePhotoDialogFragment.takePhoto(Unknown Source)
at me.chunyu.ChunyuDoctor.Dialog.ChoosePhotoDialogFragment.access$000(Unknown Source)
at me.chunyu.ChunyuDoctor.Dialog.b.onClick(Unknown Source)
at me.chunyu.ChunyuDoctor.Dialog.ChoiceDialogFragment.onClick(Unknown Source)
at android.view.View.performClick(View.java:4848)
at android.view.View$PerformClick.run(View.java:20270)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5643)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
My code is here:
public static void takePhoto(Fragment fragment, int token, Uri uri) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (uri != null) {
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
}
fragment.startActivityForResult(intent, token);
}
I searched the similar problems and solutions.
And modify the code as follow:
public static void takePhoto(Fragment fragment, int token, Uri uri) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
| Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
if (uri != null) {
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
}
fragment.startActivityForResult(intent, token);
}
But it is also not work.
It happend on Android 5.1 While work well on Android 4.3.
Is there anyone meet the same problem?
Ask for some advance.
Waiting online...
A:
I have already resolved this problem.
First, this problem occurred because StrictMode prevents passing URIs with a file:// scheme.
So there are two solutions:
Change StrictMode. See similar problem and its code.
But for our apps, it is not realistic to modify the Android source code.
Use another URI scheme, instead of file://. For example, content:// related to MediaStore.
So I chose the second method:
private void doTakePhoto() {
try {
ContentValues values = new ContentValues(1);
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg");
mCameraTempUri = getActivity().getContentResolver()
.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
takePhoto(this, RequestCode.REQCODE_TAKE_PHOTO, mCameraTempUri);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void takePhoto(Fragment fragment, int token, Uri uri) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
| Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
if (uri != null) {
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
}
fragment.startActivityForResult(intent, token);
}
Also, there is another solution.
A:
So, I was actually reading about this, and it seems the correct solution to handle this is the following:
String mCurrentPhotoPath;
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
static final int REQUEST_TAKE_PHOTO = 1;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
...
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
Notice there is a note that google says to create a "content://" file instead of a "file://" based resource.
This is from google:
Note: We are using getUriForFile(Context, String, File) which returns a content:// URI. For more recent apps targeting Android N and higher, passing a file:// URI across a package boundary causes a FileUriExposedException. Therefore, we now present a more generic way of storing images using a FileProvider.
Also, you will need to setup the following:
Now, you need to configure the FileProvider. In your app's manifest, add a provider to your application:
<application>
...
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.android.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"></meta-data>
</provider>
...
</application>
Note: (Taken from google's site) Make sure that the authorities string matches the second argument to getUriForFile(Context, String, File). In the meta-data section of the provider definition, you can see that the provider expects eligible paths to be configured in a dedicated resource file, res/xml/file_paths.xml. Here is the content required for this particular example:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="Android/data/com.example.package.name/files/Pictures" />
</paths>
If you would like more information: read up here
https://developer.android.com/training/camera/photobasics.html
A:
Besides the solution using the FileProvider, there is another way to work around this. Simply put in Application.onCreate() method. In this way the VM ignores the file URI exposure.
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
| {
"pile_set_name": "StackExchange"
} |
Q:
ASP.NET File upload - Validation
In our application , we are using asp.net FileUpload control to upload files.
Requirement is , user should be able to upload only ".doc, .xls , .pdf" files.
System should not allow him to upload other files. To achieve this we are validating the extension of the uploaded file. If it is not valid then throwing error message.. this works fine..
But if i change the any exe file as .doc file , then system is allowing to upload. this should not happen.
Is there any way to validate the file with its content instead of its extension ..?
A:
Check out this question/answer on stackoverflow. I belive this is a duplicate question.
Also, look into reading a file's magic number especially if you are just trying to determine if the file is one of a few acceptable types. Magic number Wikipedia
| {
"pile_set_name": "StackExchange"
} |
Q:
Running Multiple functions in python Maya
Is there a way you can pass multiple functions through one button for eg:
def test1(*args)
print Hi
def test2(*args)
print Hello
cmds.button('greetings',label = 'Menu',command = test1 & test2)...?
I want to run both the functions through one button command is that possible in python maya..???
A:
The easy way to do it would be to define a new function
def test1_test2(*args):
test1(*args)
test2(*args)
cmds.button('greetings', label='Menu', command=test1_test2)
| {
"pile_set_name": "StackExchange"
} |
Q:
Copy geometry from one scene into another
I'm playing around with SceneKit and Swift (but answers in Objective-C are fine).
I know how to load a collada file into a scene. (Can you load it into a node?)
This is the Swift code I'm using:
let url = NSBundle.mainBundle().URLForResource("weasel", withExtension: "dae")
var error: NSErrorPointer? = nil
let weasel = SCNScene.sceneWithURL(url, options: nil, error: error!)
(I'm not sure how idiomatic the way I've declared error is. Feel free to enlighten me.)
This seems to work fine, but I now want to insert something in this scene (or the whole scene, it doesn't matter) into another scene. I've gotten something like this to compile and run, but it does not appear to work.
let weaselNode = SCNNode()
weaselNode.geometry = SCNNode(geometry: weasel.rootNode.geometry)
scene.rootNode.addChildNode(weaselNode)
A:
Here, you are just retrieving the root node's geometry (which is probably nil). What you need to do is to get the node(s) you are interested in (not just a geometry) from scene A and add them to scene B.
Pseudo code should be:
SCNNode *weaselNodeTree = [sceneA.rootNode childNodeWithName:
@"theObjectNameImLookingFor" recursively:YES];
(then optional if you don't want to modify scene A: weaselNodeTree = [weaselNodeTree clone];)
[sceneB.rootNode addChildNode:weaselNodeTree];
| {
"pile_set_name": "StackExchange"
} |
Q:
Linq-To-SQL attribute mapping string property containing DbGenerated primary key
I'm using Linq-To-SQL with Attribute mapping, and have a class with the following properties:
private long item_Id;
[Column(Storage="item_Id", IsDbGenerated = true, IsPrimaryKey = true)]
public long Item_Id;
private string description;
[Column(Storage="description")]
public string Description
{
get { return description; }
set { description = value; }
}
private string lookup_Id;
[Column(Storage="lookup_Id")]
public string Lookup_Id
{
get { return lookup_Id.ToString() + "|" + Description; }
}
The Lookup_Id field actually contains significantly more data, but I've narrowed the scope for this question.
As it is, this setup allows me to use the database generated primary key as a portion of the object's Lookup_Id property.
My problem is that I need to import items into this database from a different source, and the Lookup_Id of those items needs to be set by a defined string; not generated by gathering values of other properties.
I can change my Lookup_Id property to one with a regular getter/setter and add an extension method that populated the Lookup_Id. However, this would require me to save all my objects to the database first to get their database-generated primary key values assigned, then call the extension method to populate the Lookup_Id property, then save the items again.
Is there some way I can accomplish this without the need to save my objects twice? I need to be able to generate the Lookup_Id with the primary key value populated for items my system creates, but I also need to be able to assign the Lookup_Id with values I might import from a CSV file, for example.
A:
Why don't you create a new class derived from the existing one? mark your Lookup_Id as virtual and override it in the new class... Would it help achieving your goal?
| {
"pile_set_name": "StackExchange"
} |
Q:
Create single animation from programme
This programme fills a figure with square patches. The y axis limit is set so that it will be seen that there is only one patch in one position. It plots this filling process. I want to record the filling as an animation and am trying to do so with 'matplotlib.animation'. I turn the plotting part of the programme into a function (def filler(b):) so that I can pass this function to the animation lines at the bottom. When I run the programme I get an error right at the end of the plotting saying Python has stopped working. Please could somebody explain why. Thanks.
Note that I don't know what the b in the function argument is meant to represent. I include it because without it the programme doesn't run, asking for a positional argument.
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.animation as animation
import numpy as np
startx = 0
endx = 10
blocks = 100
points = np.random.randint(startx,endx,size=blocks)
y = [-1]*int(endx-startx)
fig = plt.figure(figsize=(5,6))
ax = fig.add_subplot(111,aspect='equal')
ax.set_xlim(startx,endx)
ax.set_ylim(0,5)
def filler(b):
for i in range(blocks):
z = 5
a = patches.Rectangle((points[i],z),1,1,ec='k',fc=(1-i/blocks,i/(2*blocks),i/blocks))
ax.add_patch(a)
while z>y[int(points[i])]+1:
z=z-1
plt.pause(0.001)
a.set_y(z)
y[int(points[i])]=z
filler_ani = animation.FuncAnimation(fig, filler,interval=50, repeat=False, blit=True)
filler_ani.save('filler.mp4')
A:
The code in the question mixes two different types of animations. Using a loop and plt.draw(), and a FuncAnimation. This will lead to chaos, as essentially the complete animation on screen is done during the first frame of the FuncAnimation, at the end of that first frame the animation fails.
So, one has to decide. Since it seems you want to do a FuncAnimation here, in order to be able to save it, one needs to get rid of the plt.draw. Then the problem is that there is a for loop and a while loop. This makes it hard to use a framenumber based animation.
Instead one may use a generator based animation.
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.animation as animation
import numpy as np
startx = 0
endx = 10
blocks = 101
points = np.random.randint(startx,endx,size=blocks)
y = [-1]*int(endx-startx)
fig = plt.figure(figsize=(5,6))
ax = fig.add_subplot(111,aspect='equal')
ax.set_xlim(startx,endx)
ax.set_ylim(0,5)
def filler():
yield None
for i in range(blocks):
z = 5
a = patches.Rectangle((points[i],z),1,1,ec='k',fc="r")
ax.add_patch(a)
while z>y[int(points[i])]+1:
z=z-1
a.set_y(z)
yield a
y[int(points[i])]=z
filler_ani = animation.FuncAnimation(fig, lambda x: None, frames=filler,
interval=50, blit=False, repeat=False)
plt.show()
This is kind of hacky, but stays most closely to your initial code.
| {
"pile_set_name": "StackExchange"
} |
Q:
Scheme keyword is unbound
When I type the following lambda expression in to a scheme terminal ((lambda(x) (modulo x 4)) 4) why do i get an error stating that the symbol modulo is unbound when it's a keyword ?
A:
Probably because you're using a restricted sublanguage that offers only limited functionality. What Scheme implementation are you using, and are you in some kind of restricted module that doesn't import the standard Scheme procedures?
modulo is indeed a standard part of Scheme and is included in any standard Scheme system. (It is, however, not a "keyword", in either the "reserved word" sense (Scheme has no reserved words), nor the named parameters sense (where keywords look like #:this).)
| {
"pile_set_name": "StackExchange"
} |
Q:
Compile Qt for Beaglebone Black
I want to compile Qt for Beaglebone Black from source.
I have the following:
cross compiler: gcc-linaro-arm-linux-gnueabihf-4.9-2014.06_linux
qt-everywhere-opensource-src-5.3.1.
My host OS is Scientific Linux 6.3 32-bit.
My problem is I have no idea what parameters I need to pass to ./confiure tool.
I have following clues:
-xplatform = qtbase/mkspecs/linux-arm-gnueabi-g++
-device = qtbase/mkspecs/devices/linux-beagleboard-g++
-device-option CROSS_COMPILE=/home/anjanu/Downloads/gcc-linaro-arm-linux-gnueabihf-4.9-2014.06_linux/bin/arm-linux-gnueabihf-g++
Is this correct and what all is need to pass to ./configure and also what is sysroot option for?
A:
Basically, this should be enough on its own:
-xplatform = qtbase/mkspecs/linux-arm-gnueabi-g++
All the rest is almost red-herring...
Even though the toolchain binaries are properly named with their long names, e.g. arm-linux-gnueabi-g++, the include and library paths may clash with the system include and library paths. That is exactly what sysroot is meant to handle.
You can set it to the PATH of your cross-toolchain installation. No, this is not the Qt installation. It is the SDK that you got from possibly Linaro, including the whole SDK for cross-platform development. That is, the compiler, linker, stripper, include files, libraries and so on.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is AirAsia's "embargo period" they mention but seldom actually define?
I was just looking at a list of deals on AirAsia's site and one of its "travel notes" says
Fares are not available during embargo period
So I'm assuming this is a specific date range. But they don't seem to tell us what that date range is.
When I google for it, I find they've been mentioning this embargo period for at least a few years, and I can find some people asking what it means, but I can't find an official definition.
I can find some sporadic bits and pieces, not official, mentioning festive times and other stuff. This makes it seem like it's not just one date range, even though they always use "embargo period" in the singular.
Where can I find a straight and detailed answer, preferably on AirAsia's site somewhere telling us exactly what this period, or periods, is?
A:
It's a convoluted way of saying "these fares may not be available during dates that we decide". For example, one of the fares is listed as being valid "6 August 2018 - 31 January 2019", but if you click through to December you'll see that prices double around Christmas. This is because the discounted fares are either no longer available or (more likely) were never available in the first place, hence "embargo".
And no, you can't find the periods anywhere, because Air Asia reserves the right to change them without notice.
| {
"pile_set_name": "StackExchange"
} |
Q:
Google API returning different results than website
When I do a site-specific search on google.com:
site:http://one-month-of-chat-logs.github.io security
I get 12 results. I signed up for a custom search engine (cx: 015271449006306103053:mz6wkimeenc) and API key, and I get only 3 results when I run the same search:
$ curl 'https://www.googleapis.com/customsearch/v1?key=$MY_API_KEY&cx=015271449006306103053%3Amz6wkimeenc&q=security'
Why do the results differ? Is my API request actually querying something different than the search I performed on google.com?
A:
This google page has what you are looking for https://support.google.com/customsearch/answer/70392?hl=en
your results are unlikely to match those returned by Google Web Search, for several reasons:
Even if a custom search engine is configured to search the entire web,
it’s designed to emphasize results from your own sites.
Your custom search engine doesn’t include Google Web Search features such as
Oneboxes, real-time results, universal search, social feaures, or
personalized results.
If your custom search engine includes more than
ten sites, the results may be from a subset of our index and may
differ from the results of a 'site:' search on Google.com.
| {
"pile_set_name": "StackExchange"
} |
Q:
Template syntax help
Two questions for an assignment, first is the first set of errors for my template in a the CharComparator.h file, I don't see why it is complaining. The second question is why that I added include "CharComparator.h" to my main.cpp file, I get a bunch more of compiler errors. Here are my files:
CharComparator.h
#ifndef CHARCOMPARATOR_H
#define CHARCOMPARATOR_H
template <>
int my_comp<const char*>(const char *a, const char *b) {
return std::strcmp(a, b) < 0;
}
#endif
main.cpp
// Reduce Template Assignment
#include <iostream>
#include <algorithm>
using namespace std;
#include "CharComparator.h"
// definition of global varible
const int MAX = 10;
// declaration of template functions
template <class T>
int reduce(T array[], int size);
template <class T>
void show(const T array[], int size);
// Main program for testing
int main() {
// test using long instantiation
long nonUniqueArray[MAX] = {12, 12 ,5, 6, 11, 5, 6, 77, 11, 12};
// show non-unique array
cout << "old array with non-unique elements: " << endl;
show(nonUniqueArray, MAX);
int newsize = reduce(nonUniqueArray, MAX);
// now non-unique array becomes unique
cout << "new array has only unique elements: " << endl;
show(nonUniqueArray, newsize);
cout << "size reduced to " << newsize << endl;
cout << endl;
// test using string instantiation
const char* strArray[MAX] = {"aa", "bb", "bc", "ca", "bc", "aa", "cc", "cd", "ca", "bb"};
//aa bb bc ca cc cd
// show non-unique array
cout << "string array with non-unique elements: " << endl;
show(strArray, MAX);
newsize = reduce(strArray, MAX);
// now non-unique array becomes unique
cout << "string array has only unique elements: " << endl;
show(strArray, newsize);
cout << "size reduced to " << newsize << endl;
return (0);
}
// reduce the non-unique array to unique array, return new size
template <class T>
int reduce(T array[], int size) {
// CODE UP A REDUCE TEMPLATE HERE
T *begin = array;
T *end = array + size;
sort(begin, end);
T *end_new = unique(begin, end);
return end_new - array;
}
// show the array element
template <class T>
void show(const T array[], int size) {
for (int i = 0; i < size; i++) {
cout << array[i] << ' ';
}
cout << endl;
}
And of course, compiler errors:
08\projects\c4\c4_1b_jwong\c4_1b_jwong\charcomparator.h(5) : error C2143: syntax error : missing ';' before '<'
1>c:\users\jon\documents\visual studio 2008\projects\c4\c4_1b_jwong\c4_1b_jwong\charcomparator.h(5) : error C2988: unrecognizable template declaration/definition
1>c:\users\jon\documents\visual studio 2008\projects\c4\c4_1b_jwong\c4_1b_jwong\charcomparator.h(5) : error C2059: syntax error : '<'
1>c:\users\jon\documents\visual studio 2008\projects\c4\c4_1b_jwong\c4_1b_jwong\main.cpp(22) : error C2065: 'MAX' : undeclared identifier
1>c:\users\jon\documents\visual studio 2008\projects\c4\c4_1b_jwong\c4_1b_jwong\main.cpp(22) : error C2078: too many initializers
1>c:\users\jon\documents\visual studio 2008\projects\c4\c4_1b_jwong\c4_1b_jwong\main.cpp(26) : error C2065: 'MAX' : undeclared identifier
1>c:\users\jon\documents\visual studio 2008\projects\c4\c4_1b_jwong\c4_1b_jwong\main.cpp(28) : error C2065: 'MAX' : undeclared identifier
1>c:\users\jon\documents\visual studio 2008\projects\c4\c4_1b_jwong\c4_1b_jwong\main.cpp(37) : error C2065: 'MAX' : undeclared identifier
1>c:\users\jon\documents\visual studio 2008\projects\c4\c4_1b_jwong\c4_1b_jwong\main.cpp(37) : error C2078: too many initializers
1>c:\users\jon\documents\visual studio 2008\projects\c4\c4_1b_jwong\c4_1b_jwong\main.cpp(41) : error C2065: 'MAX' : undeclared identifier
1>c:\users\jon\documents\visual studio 2008\projects\c4\c4_1b_jwong\c4_1b_jwong\main.cpp(43) : error C2065: 'MAX' : undeclared identifier
1>Build log was saved at "file://c:\Users\jon\Documents\Visual Studio 2008\Projects\C4\C4_1b_JWong\C4_1b_JWong\Debug\BuildLog.htm"
1>C4_1b_JWong - 11 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Any thoughts? Thanks, and sorry for such noob quesitons.
A:
If you want to specialize a template function, you need to have at least declared the original template first, i.e.:
template<class T> int my_comp<T>(T a, T b);
// ... now you can specialize my_comp()
Specializations are for providing implementations for "special cases" of a generic template, see e.g. C++ FAQ lite 35.7. As James points out there are some intricacies to template specialization to be aware of that Sutter described in this article.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to calculate change between conditional elements in panda dataframe
I have a data frame of Open, High, Low, Close prices for 30 securities every five minutes in a dataframe. Here is a sample:
Close High Low Open Symbol
2015-03-18 14:05:00 75.99 75.99 75.73 75.76 DD
2015-03-18 14:05:00 82.82 82.85 82.55 82.55 WMT
2015-03-18 14:05:00 25.72 25.72 25.62 25.64 GE
2015-03-18 14:05:00 61.94 61.95 61.62 61.62 JPM
2015-03-18 14:10:00 26.72 26.72 26.62 26.64 GE
2015-03-18 14:10:00 62.94 62.95 62.62 62.62 JPM
2015-03-18 14:10:00 83.82 83.85 83.55 83.55 WMT
2015-03-18 14:10:00 73.99 73.99 73.73 73.76 DD
I want to take the Open values for each symbol at each timestamp, and subtract them from the Close at the previous timestamp for that symbol so to measure the gap. For example, I would take the 14:10 timestamped Open value for DD and subtract it from the 14:05 timestamped Close value for DD.
I have found solutions for data which is uniform, i.e. if this dataframe was for only one symbol, but given that I have 30 symbols in this dataframe, what would be the best way to calculate this 'Gap' value?
Thank you,
CJ
A:
You can groupby on 'Symbol' and then call apply passing a lambda and use shift:
In [147]:
df.groupby('Symbol').apply(lambda x: x['Open'] - x['Close'].shift())
Out[147]:
index 2015-03-18 14:05:00 2015-03-18 14:10:00
Symbol
DD NaN -2.23
GE NaN 0.92
JPM NaN 0.68
WMT NaN 0.73
EDIT
To add this as a new column, you can groupby as above and call transform on the 2 columns of interest and index the 'Close' column. tranform returns a Series aligned to the original df:
In [19]:
df['New_col'] = df.groupby('Symbol')[['Open','Close']].transform(lambda x: x['Open'] - x['Close'].shift())['Close']
df
Out[19]:
Close High Low Open Symbol New_col
index
2015-03-18 14:05:00 75.99 75.99 75.73 75.76 DD -2.23
2015-03-18 14:05:00 82.82 82.85 82.55 82.55 WMT 0.73
2015-03-18 14:05:00 25.72 25.72 25.62 25.64 GE 0.92
2015-03-18 14:05:00 61.94 61.95 61.62 61.62 JPM 0.68
2015-03-18 14:10:00 26.72 26.72 26.62 26.64 GE 0.92
2015-03-18 14:10:00 62.94 62.95 62.62 62.62 JPM 0.68
2015-03-18 14:10:00 83.82 83.85 83.55 83.55 WMT 0.73
2015-03-18 14:10:00 73.99 73.99 73.73 73.76 DD -2.23
| {
"pile_set_name": "StackExchange"
} |
Q:
Is an empty conjunction in propositional logic true?
Consider an illustratory formula
$\psi \equiv \bigwedge_{i \in \emptyset} false$, does $\psi$ valuate to $true$?
Is such a formula ill-formed?
If not, is there a symbol for an empty formula?
The reason why I ask is that I have a definition where I can have a conjunction over a set of constraints, and it would be really helpful if I could interpret an empty set of constraints as true.
A:
It makes a lot of sense anyway. Truth is usually denoted by $\top$. Consider, that $a\wedge \top \equiv \top \wedge a \equiv a$, so $\top$ acts like an identity of $\wedge$. We define empty sums to be $0$, because then certain recursive formulas still work in some "borderline cases". Similarly we should define empty conjunctions to be $\top$.
Another reason, why that makes sense, is the universal property of a product with some index set $I$ known from category theory . If $I$ is empty, then the product turns out to be a terminal object. The terminal object of a category of propositions, where an arrow $a \to b$ exists, if and only if $a \vdash b$, is $\top$. In lattice theory terminal objects are known as "maximal elements" and products as "infima".
A:
With Stefan, I think empty conjunction is equivalent to $\top$ for the following reason within classical propositional logic:
$\Gamma\vDash\Delta\qquad$ iff $\qquad\vDash\bigwedge\Gamma\supset\bigvee\Delta$
Now for the special case $\Delta = \emptyset$,
$\Gamma\vDash\emptyset\qquad$ iff $\qquad\Gamma\vDash\bot\qquad$ iff $\qquad\vDash\bigwedge\Gamma\supset\bot$
and similarly, for the special case $\Gamma = \emptyset$,
$\emptyset\vDash\Delta\qquad$ iff $\qquad\top\vDash\Delta\qquad$ iff $\qquad\vDash\top\supset\Delta$
| {
"pile_set_name": "StackExchange"
} |
Q:
System.Runtime.CompilerServices in .NET Standard library
Currently I am in the process of converting a .NET 4.5 class library to a .NET Core class library, referencing .NETStandard v1.6.
In part of my code (relying heavily on reflection) I need to determine whether an object is of type Closure, which is located in the System.Runtime.CompilerServices namespace. This namespace and type is not available in .NETStandard v1.6.
Did this type move, or is it no longer accessible?
Since my code relied on it, what is an alternative in case it is not available in .NETStandard?
The specific code relying on Closure determines the parameter types of a delegate, skipping the compiler generated Closure ones.
Delegate toWrap;
MethodInfo toWrapInfo = toWrap.GetMethodInfo();
var toWrapArguments = toWrapInfo.GetParameters()
// Closure argument isn't an actual argument, but added by the compiler.
.SkipWhile( p => p.ParameterType == typeof( Closure ) )
.Select( p => p.ParameterType );
A:
In .Net Core 1.0, Closure exists in the System.Linq.Expressions assembly in the System.Linq.Expressions package, but it's not exposed in a reference assembly. This means it's just an implementation detail in Core (and could for example vanish or move in a future version). It also means you can't reference it at compile time (like you did in .Net Framework), but you can retrieve it using reflection at runtime (don't forget using System.Reflection; for GetTypeInfo()):
Type closureType = typeof(Expression).GetTypeInfo().Assembly
.GetType("System.Runtime.CompilerServices.Closure");
In .Net Framework, Closure is in a different assembly (namely, System.Core), but so is Expression, so this code should work on both.
| {
"pile_set_name": "StackExchange"
} |
Q:
Core Data multiple instances of same Entity - entities that share attributes
I am trying to wrap my head around how to have multiple instances of the same Core Data entity. It does not seem possible, so I must be approaching this wrong.
Basically, say I have a shopping cart that can be full of multiple balloons. But each balloon can have a different color. If I edit the template for the balloon, all the balloons will update to reflect the change. So say I change the template's name to 'bacon', all the balloon's names will change to 'bacon' as well.
How would I go about achieving this with Core Data?
EDIT
As requested I will try to clarify what I am trying to do.
Maybe this example will be more clear.
Say you are creating a model for exercises. So you have Ab Roller, Shoulder Press, etc.
In a workout, you may have multiple instances of each. So in one workout you will have, say
Ab Roller
Shoulder Press
Ab Roller
And each instance of Ab Roller would have its own relationship to Sets which would be different for each of course.
Maybe not the best example but should give a clearer understanding of repeating instances.
I was thinking of having a template entity, and then an instance entity, and a relationship between them - when template entity name is updated, all instance entity's name update through KVO. Or I place all the shared attributes (i.e. name) in the relationship (so the instance entity's name attribute returns its template's name attribute) so that they reflect the changes to the template. What is the best way to go about it?
A:
I'm going to answer this from a database design point of view, given the agreement in the comments that this is more a generic database design question. If that doesn't clear up all of your questions then hopefully someone who knows the ins and outs of Core Data can clear that side of things up for you.
You're looking at holding some configuration data for your system, and then also holding data for the various instances of entities which use that configuration data. The general pattern you've come up with of having a template entity (I've also seen this called a definition or configuration entity) and an instance entity is certainly one I've come across before, and I don't see a problem with that.
The rules of database normalization tell you to avoid data replication in your database. So if your template entity has a name field, and every single instance entity should have the same name, then you should just leave the name in the template entity and have a reference to that entity via a foreign key. Otherwise, when the name changes you'd have to update every single row in your instance table to match - and that's going to be an expensive operation. Or worse, it doesn't get updated and you end up with mismatched data in your system - this is known as an update anomaly.
So working on the idea of a shopping cart and stock for some sort of e-commerce solution (so like your first example), you might have a BasketItem entity, and an ItemTemplate entity:
ItemTemplate:
* ItemTemplateId
* Name
BasketItem:
* BasketItemId
* ItemTemplateId
* Color
Then your balloon template data and the data for your balloon instances would look like this in the database:
ItemTemplate:
| ItemTemplateId | Name |
| 7 | Balloon |
BasketItem:
| BasketItemId | ItemTemplateId | Color |
| 582 | 7 | Blue |
| 583 | 7 | Green |
(This is obviously massively simplified, only looking at that one specific example and ignoring all of the mechanics of the basket and item, so don't take that as an actual design suggestion.)
Also, you might want to hold more configuration data, and this could drastically change the design: for instance, you might want to hold configuration data about the available colors for different products. The same concepts used above apply elsewhere - if you realise you're holding "Blue" over and over and realise you might in future want to change that to "Dark blue" because you now stock multiple shades of blue balloon, then it makes sense to have the color stored only once, and then have a foreign key pointed to wherever it is stored, so that you're not carrying out a massive update to your entire BasketItem table to update every instance of "Blue" to "Dark blue."
I would highly recommend doing some reading on database design and database normalization. It will help answer any questions you have along these lines. You might find that in some situations you need to break the rules of normalization - perhaps so that an ORM tool works elegantly, or for performance reasons - but it's far better to make those decisions in an informed manner, knowing what problems you might cause and taking further steps to prevent them from happening.
| {
"pile_set_name": "StackExchange"
} |
Q:
Number Formatting in Thousands
How, for example, do I turn the number 10562.3093 into 10,562 in C#?
Also, how do I ensure that same formatter will apply correctly to all other numbers?....
...For example 2500.32 into 2,500
Help greatly appreciated.
A:
string formatted = value.ToString("N0");
This divides your number in the manner specified by the current culture (in the case of "en-US," it's a comma per multiple of 1000) and includes no decimal places.
The best place to look for any question regarding formatting numbers in .NET would have to be here:
Standard Numeric Format Strings (MSDN)
And here:
Custom Numeric Format Strings (MSDN)
| {
"pile_set_name": "StackExchange"
} |
Q:
'System.OutOfMemoryException' was thrown in ZipArchive for large file from URL
I have an URL which contains a zip file. The files need to be unzipped from the URL. The URL is Opened and Read using webclient and then added to a Stream. It is then used in the ZipArchive object which will unzip the files and store them in the D:\ drive. When a file is around 400Mb I get the 'System.OutOfMemoryException'.
Stream has to be used since the webClient.OpenRead(Uri Address) returns a Stream. As well as the use ZipArchive(Stream stream).
How can I stop from getting this message?
string zipFileUrl = "https://www.dropbox.com/s/clersbjdcshpdy6/oversize_zip_test_0.zip?dl=0"
string output_path = @"D:\";
using (WebClient webClient = new WebClient())
{
using (Stream streamFile = webClient.OpenRead(zipFileUrl))
{
using (ZipArchive archive = new ZipArchive(streamFile))//ERROR HERE
{
var entries = archive.Entries;
//Loops thru each file in Zip and adds it to directory
foreach (var entry in entries)
{
if (entry.FullName != "/" && entry.Name != "")
{
string completeFileName = Path.Combine(output_path, entry.FullName);
string directory = Path.GetDirectoryName(completeFileName);
//If directory does not exist then we create it.
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
//Extracts zip from URL to extract path, and overwrites if file exists.
entry.ExtractToFile(completeFileName, true);
}
}
}
}
A:
I think here might be your problem, from the ZipArchive.Init method
private void Init(Stream stream, ZipArchiveMode mode, Boolean leaveOpen)
{
Stream extraTempStream = null;
try
{
_backingStream = null;
//check stream against mode
switch (mode)
{
case ZipArchiveMode.Create:
// (SNIP)
case ZipArchiveMode.Read:
if (!stream.CanRead)
throw new ArgumentException(SR.ReadModeCapabilities);
if (!stream.CanSeek)
{
_backingStream = stream;
extraTempStream = stream = new MemoryStream();
_backingStream.CopyTo(stream);
stream.Seek(0, SeekOrigin.Begin);
}
break;
case ZipArchiveMode.Update:
// (SNIP)
default:
// (SNIP)
}
// (SNIP)
}
if streamFile.CanSeek is false (which from a WebClient it will be) it copies the entire file in to memory then works on the file. This is what is using up all the memory.
Try to find a 3rd party library that handles Zip files and does not need a stream that supports seeking. If you can't, copy the file to disk first to the temp folder with a FileStream with the FileOptions.DeleteOnClose option passed in, then use that stream in your zip before you close the stream.
string zipFileUrl = "https://www.dropbox.com/s/clersbjdcshpdy6/oversize_zip_test_0.zip?dl=0";
string output_path = @"D:\";
using (var tempFileStream = new FileStream(Path.GetTempFileName(), FileMode.Create,
FileAccess.ReadWrite, FileShare.None,
4096, FileOptions.DeleteOnClose))
{
using (WebClient webClient = new WebClient())
{
using (Stream streamFile = webClient.OpenRead(zipFileUrl))
{
streamFile.CopyTo(tempFileStream);
}
}
tempFileStream.Position = 0;
using (ZipArchive archive = new ZipArchive(tempFileStream))
{
var entries = archive.Entries;
//Loops thru each file in Zip and adds it to directory
foreach (var entry in entries)
{
if (entry.FullName != "/" && entry.Name != "")
{
string completeFileName = Path.Combine(output_path, entry.FullName);
string directory = Path.GetDirectoryName(completeFileName);
//If directory does not exist then we create it.
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
//Extracts zip from URL to extract path, and overwrites if file exists.
entry.ExtractToFile(completeFileName, true);
}
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
why exposing with 18% gray card does not give IRE near 40?
I am trying to understand how to get perfect exposure using gray card.
With my Sony a6500 using ITU709 gamma, I locked exposure by doing spot metering on the gray card.
When importing in final cut pro the waveform monitor show IRE value near 25 for the gray card.
Shouldn't it show between 40 and 43 for 18% reflectance mid gray?
A:
18% reflectivity means it should reflect 18% of whatever linear light is actually on it. Gamma should compute 117 at 46%, but your picture shows the card to be in some shadows, so then it can't be 18% of the brightest 255 (expecting gamma to 46%). But the histogram won't be the exact computation, because the camera is busy doing other things too, like your contrast setting, and white balance, and your color profile like Vivid, etc. The purpose of those settings are to shift the histogram. Mild settings in the bright normal light should be near ballpark, but probably not exact as planned. It is not an adequate calibration solution.
| {
"pile_set_name": "StackExchange"
} |
Q:
jquery-lazyload images in jquery-databables
With the datatables javascript plugin I want to display 10k little images in a table with pagination.
Because I load too much of them, I get errors.
I would like to load those images only when they appear so I found the lazyload plugin.
However, the images don't appear at all at first.
I have to manually enter
$("img.lazy").lazyload();
in the browser console.
Then only it loads the images that are on screen
(i.e. when I scroll down, I see all other images unloaded).
This proves at least that the plugin is somewhat working.
Is there something particular to do with the use of datatables?
Do I have to scriptually trigger lazyload every second?
Thank you !
A:
I found another method here without the lazyload plugin.
Use the option
"fnRowCallback": customFnRowCallback
and then this function will replace the first column with an image tag.
function customFnRowCallback( nRow, aData, iDisplayIndex )
{
$('td:eq(0)', nRow).html( '<img class="" src="http://aaaaa/'+ aData.attribute+'" alt="" />' );
return nRow;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
having problems setting this div width to 1px?
I've created the following UI component:
http://codepen.io/ac123/pen/xqYzxR
<div id="MapKeys">
<div id="RegionalSupply">
<div class="header">Regional supply</div>
<div class="circle"></div>
<div class="detail">Circles sized by the amount of change from the previous period</div>
</div>
<div id="CorridorNetFlowDirection">
<div class="header">Corridor net flow direction</div>
<div class="dottedLine">
<div class="part1"></div>
<div class="part2"></div>
<div class="part3"></div>
</div>
<div class="detail">Lines sized by the amount of change in net flow from the previous period</div>
</div>
</div>
#MapKeys
{
.header{
font-size:16px;
}
#RegionalSupply{
height:100px;
width:240px;
border:solid purple 1px;
display:inline-block;
padding:10px;
& > .circle {
width: 14px;
height: 14px;
background: lightgrey;
-moz-border-radius: 7px;
-webkit-border-radius: 7px;
border-radius: 7px;
display:inline-block;
}
& > .detail{
display:inline-block;
width:150px;
font-size:12px;
}
}
#CorridorNetFlowDirection{
height:100px;
width:240px;
border:solid red 1px;
display:inline-block;
padding:10px;
& > .dottedLine
{
& > .part1{
width: 12px;
height: 10px;
background: lightgrey;
display:inline-block;
}
& > .part2{
width: 1px;
height: 10px;
background: none;
display:inline-block;
}
& > .part3{
width: 12px;
height: 10px;
background: lightgrey;
display:inline-block;
}
}
& > .detail{
display:inline-block;
width:150px;
font-size:12px;
}
}
}
The "Corridor net flow direction" component displays a grey icon which represents a dotted line. I've defined this dotted line as 3 adjacent divs with the middle div having wdith:1px and background:none.
However, the appearance of the rendered middle div width looks more like 6px or 7px. What do I need to adjust in my css or html in order for this dotted line to display a width of 1px between the 1st and 3rd divs?
Also, how can I specify the shared css attrs for part1, part2, part3 in this scenario? For example, I would expect the following shared styling to work but it doesn't:
& > .dottedLine
{
height: 10px;
display:inline-block;
& > .part1{
width: 12px;
background: lightgrey;
}
& > .part2{
width: 1px;
background: none;
}
& > .part3{
width: 12px;
background: lightgrey;
}
}
A:
Simply add font-size: 0px; to the parent container named .dottedLine
.dottedLine{
font-size:0px;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
"This is actually true" vs. [sic]
I often find myself in need of a short expression, to emphasize that what I just wrote (not quoted) is actually true. In cases of paradoxes or illogical truths for instance, like The Monty Hall Problem.
It is not always possible to explain that something is actually true, nor does it look pretty to constantly add "(This is actually the truth, despite it seeming to be incorrect)" at the end of what might just be a 2-digit number in a small table-cell.
Apart from adding an asterix, or footnote, with an explanation at the bottom of the page, is there a [sic]-like alternative? An abbreviation that simply says "This is actually true/the correct value despite looking incorrect/seeming illogical"?
Assuming none exist, the only way to get a new phrase or abbreviation into the language/dictionary is to start using it... With that in mind, just for laughs, what would you prefer as a new expression?:
cbt - "counterintuitive but true"
sya - "surprising yet accurate"
tis - "this is so" (I think we'd best avoid "this is true"...)
Or perhaps cor for "correct"? Could create some confusion as it is already used as an expression in british, but I kinda like that idea.
A:
When I see "[sic]" after a word or phrase, I expect the sicced word to be obviously wrong, as in the M-W Online definition's example: Definition of SIC
"intentionally so written —used after a printed word or passage to indicate that it is intended exactly as printed or to indicate that it exactly reproduces an original (said he seed [sic] it all)"
Seeing a lot of "[sic]"s in a paper isn't pleasant. If you're talking about something like the Monty Hall problem, it's probably best to include a footnote or an explanation rather than a "[sic]". If there are a lot of paradoxical or incorrect statements in quoted material, then I'd use a superscript * to indicate that. If you're paraphrasing someone else and want to indicate errors, I'd also use some kind of footnote and superscript symbol if there are more than two.
I don't know of any abbreviation that meets your criteria, but you might try abbreviating verbatim as "(vbt)" if you really want an abbreviation instead of a superscript symbol + footnote combo.
| {
"pile_set_name": "StackExchange"
} |
Q:
Tutorial to create phone book contact in Android SDK
Although there are sites out there to help me create a contact, I am still not able to understand how to do it, Can someone give me a pointer/link/suggestion, that teaches me from scratch how to create a phone contact that will eventually show up in phone contacts list. Thank you.
A:
While I don't know of any tutorials to show step by step. These links may help:
Using the Contacts API
ContactManager - Contact Manager
| {
"pile_set_name": "StackExchange"
} |
Q:
Unable to install software-properties-common for Docker
To install Docker I need to run:
sudo add-apt-repository \
"deb [arch=amd64] https://download.docker.com/linux/ubuntu \
$(lsb_release -cs) \
stable"
which requires software-properties-common.
When I try to install software-properties-common with sudo apt-get install, the following error occurs:
The following packages have unmet dependencies:
software-properties-common : Depends: python3-software-properties (= 0.96.20.9) but it is not going to be installed
E: Unable to correct problems, you have held broken packages.
So then I try to install python3-software-properties and this shows:
The following packages have unmet dependencies:
python3-software-properties : Depends: python3-pycurl but it is not going to be installed
E: Unable to correct problems, you have held broken packages.
And if I try to install python3-pycurl:
The following packages have unmet dependencies:
python3-pycurl : Depends: python3 (< 3.6) but 3.6.7-1~18.04 is to be installed
E: Unable to correct problems, you have held broken packages.
So does this mean my Python version has to be <3.6 ? This seems to be really weird. Thanks in advance for any help.
A:
Turns out the sources in my sources.list were broken. Previously I was using Aliyun's sources (since I'm located in China) which caused the errors above. Switching to Tsinghua's sources fixed the issue.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I extend the d3.js selection whit a custom filter function?
I've many use of this filter function that just skips null data:
selection
.data(array).enter()
.filter(function(d) { return d === null ? null : this })
.append("something")
So I decided to simplify code extending the selection with a notnull function:
d3.selection.enter.prototype.notnull = function() {
return this.filter(function(d) {
return d === null ? null : this
})
}
So I can simply the code this way:
selection
.data(array).enter()
.notnull()
.append("something")
And it seems to work, but evidently I've some problem with the return value, because I get this error:
TypeError: selection.data(...).enter(...).notnull(...).append is not a function
And now I'm really struggling to realize why. Any suggestion?
EDIT
The question was uncorrect, the first example had to be:
selection
.data(array).enter()
.append("something")
.filter(function(d) { return d === null ? null : this })
but this leaves a lot of empty svg entities, so the way to go, as Ruben has pointed out, is to use the Array.filter on the data array.
A:
I created a snippet for your original filter code - without a custom function - and found that it does two things. Firstly, it throws an error: Uncaught TypeError: selection.data(...).enter(...).filter(...).append is not a function and secondly, it logs the argument filter is called with.
var array = [1, 2, 3, 4, null, 5, 6, 7];
var selection = d3.select('body').selectAll('span');
selection
.data(array).enter()
.filter(function(d) {
console.log(d);
return d === null ? null : this;
})
.append("span")
.text(function(d) {
return d;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
<body>
</body>
Here, we see that d is actually an array of values, so .filter() is called on an array of arrays, not just on an array itself. To fix this, you can do two things: you can decide to filter your data before passing it to d3js as follows .data(array.filter(function(d) { return return d !== null; }));or you can filter the values after you've added span tags for all of them. The snippet below shows your code in a functioning way:
var array = [1, 2, 3, 4, null, 5, 6, 7];
var selection = d3.select('body').selectAll('span');
d3.selection.prototype.notnull = function() {
return this.filter(function(d) {
return d === null ? null : this
})
}
selection
.data(array).enter()
.append("span")
.notnull()
.text(function(d) {
return d;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
| {
"pile_set_name": "StackExchange"
} |
Q:
how to change textbox textmode using jquery
i have a login component and within it the password field has a textmode of singlline
what i am trying to do is on focus the textmode will change to password
i tried this :
$(function () {
$(".PassTextBox").focus(function (pas) {
$(".PassTextBox").attr("TextMode", "Password");
});
});
but it didn't work
using asp.net 3.5 , thanks
A:
Why not display it as a password field from the start ?
If you have to, take a look at How display text in password field
It is not as simple as it seems because IE (before v9) does not allow to dynamically change the type of the textbox, so you will have to actually replace it with another one.
A:
You'll need to change the "type" attribute to password. "TextMode" is an asp.net control attribute, but on the client side it gets turned into an HTML input, which has a type attribute: http://htmlhelp.com/reference/html40/forms/input.html
$(function () {
$(".PassTextBox").focus(function (pas) {
$(".PassTextBox").attr("Type", "Password");
});
});
UPDATE:
After testing this to confirm it works, it appears changing the type may not be supported on all browsers or by jQuery. This answer will give you some more insight. My suggestion is to put two fields on the form and dynamically show/hide them to give the same effect.
| {
"pile_set_name": "StackExchange"
} |
Q:
Unable to use libcurl to access a site requiring client authentication
I’m using the below snipped for setting the certificate and key for client authentication.
curl_easy_setopt(curl,CURLOPT_SSLCERT,"clientCert.pem");
curl_easy_setopt(curl,CURLOPT_SSLCERTPASSWD,"changeit");
curl_easy_setopt(curl,CURLOPT_SSLCERTTYPE,"PEM");
curl_easy_setopt(curl,CURLOPT_SSLKEY,"privateKey.pem");
curl_easy_setopt(curl,CURLOPT_SSLKEYPASSWD,"changeit");
curl_easy_setopt(curl,CURLOPT_SSLKEYTYPE,"PEM");
The certificate doesn’t have a password, I don’t know why on earth the option SSLCERTPASSWD exists, I just provided a dummy value.
When I run the program on Linux I get an error code of 58 and an error message
unable to set private key file: 'privateKey.pem' type PEM
On Windows however I get
unable to use client certificate (no key found or wrong pass phrase?)
It seems to suggest the certificate and the key don’t match but I don’t know how. I have extracted both the cert and the key from a p12 file using openssl commands.
The command I used to extract the key is
openssl.exe pkcs12 -in client.p12 -nocerts -out privateKey.pem
and the command used to extract the cert is
openssl.exe pkcs12 -in client.p12 -nokeys -out clientCert.pem
The p12 file has been successfully used in a browser to access the client authentication url.
Please help before I shoot myself.
Edit:
Here is proof that the private key and the certificate correspond to each other:
[debugbld@nagara ~/curlm]$ openssl x509 -noout -modulus -in clientCert.pem | openssl md5
d7207cf82b771251471672dd54c59927
[debugbld@nagara ~/curlm]$ openssl rsa -noout -modulus -in privateKey.pem | openssl md5
Enter pass phrase for privateKey.pem:
d7207cf82b771251471672dd54c59927
So why can’t it work?
A:
Using the command line curl, I've got the same error using a .pem file that was also obtained with openssl from a p12 file, The p12 was also able to working properly doing client authentication when imported in a browser. Just like you described, I think.
My problem was caused because the .pem file was not listing the certificates in the proper order: seems that each certificate in the file has to be followed by its issuer certificate. I edited the file and changed the order of the sections and curl was happy.
For the record, my original .p12 file was obtained by backing up a certificate from Firefox.
Also note that in my case, I was not getting prompted for the password and was getting the
curl: (58) unable to set private key file: 'alice.pem' type PEM
before the password prompt
| {
"pile_set_name": "StackExchange"
} |
Q:
Why we can backup postgresql database backup without password?
I want to backup my PostgreSQL database with pg_dump command that takes a lot of parameters.
One of them is --no-password.
Why this parameter is provided?
I mean if anyone can backup database, so what about security?
A:
Read documentation on this: "If the server requires password authentication and a password is not available by other means such as a .pgpass file, the connection attempt will fail." This parameter doesn't mean that you can connect (and dump) without knowing password, it is just help for (backup) scripts where entering passwords isn't possible by hand.
| {
"pile_set_name": "StackExchange"
} |
Q:
Git статус сборки приложения с базой
Дали тестовое задание написать простой сервис для вывода данных из базы. Сделал с помощью Spring boot. Также нужно залить проект на гит и отобразить статус сборки (Travis CI) но как туда подвязать базу(что бы тесты крутились)? И как отдать это тестовое компании? отдать им скрипты создания базы и таблицы? или есть какие то продвинутые решения?
A:
Список поддерживаемых Travis CI баз данных и способы их подключения смотрите в документации.
Отдавать нужно в таком виде, чтобы проверяющая сторона смогла а) легко поднять ваше приложение и б) почитать код. Т.е. отдаете все исходники, плюс пишете краткую инструкцию как все поднять, либо создаете батник. Что касается БД — да, канонический вариант — это набор скриптов для поднятия/заполнения базы. Их выполнение опять же можно спрятать в батник.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to unit-test a class in a web application?
I have a very large web application and have created a class that calculates dates, yesterday, last week etc.
The problem I have is I have to build and run the web application each time I want to test the class. I want to be able to run the class on its own and test the outputs, rather than building the entire app each time.
I think unit testing is the correct way to do it.
A:
It was quite simple really. I right clicked on the Solution in Solution Explorer added a new unit test project from the Test options. It installed and I set up my first test and it worked.
As ever, thanks for all your guidance.
| {
"pile_set_name": "StackExchange"
} |
Q:
Filter a NumPy array by the final dimension, collapsing only the second to last dimension
I am so incredibly confused battling this problem, even though it's super simple:
I have a numpy array a where a.shape == (16,4,1000,60)
I really dislike it when a[:,:,:,5] == x
I want to remove all of the above, to produce b where b.shape == (16,4,k,60), where k is an unknown but constant number.
The indexes where a[0,0,:,5] == x are not necessarily the same as the indexes where a[0,1,:,5] == x, but there are always k of them.
Any ideas? Thanks!
EDIT:
I've just discovered that if I do:
b = a[a[:,:,:,5] == x]
k = b.size / (16*4*60)
b = b.reshape([16,4,k,60])
b.shape # e.g. (16,4,3,60)
It works, but this doesn't seem like a very nice solution. Is there a way to explicitly keep dimensions?
A:
Instead of b = b.reshape([16,4,k,60]) just do a b = b.reshape((16,4,-1,60)). numpy will figure out the implicit dimension for you.
One and only one shape dimension can be -1. In this case, the value is inferred from the total size of the array and the other dimensions.
| {
"pile_set_name": "StackExchange"
} |
Q:
Geting error when installing custome module in joomla 2.5.8
I am trying to learn creating module for joomla 2.5.8 as per joomla 2.5's documentation but not able to install it properly. while i am installing the module.. it is displaying me error
error
Jfolder::Create:could not create directory
Warning: Failed to move File.
the source i am using to learn creating module is
http://docs.joomla.org/Creating_a_Module_for_Joomla_2.5
and i had not make any changes from my side... i had just follow as per site instruction. even i put whole code as it is in respected file and also give name to file as in site instruction. Please help me to solve this issue.
A:
Seems that you have incorrect permissions set on folders. Log in to admin panel, then choose Site -> System infromation -> Directory Permissions and check them.
| {
"pile_set_name": "StackExchange"
} |
Q:
ASP vs Inc behavior difference with html.encode
For my current project i work with include files (.inc) inside visual studio.
What i did is changed some inc files to asp.
But when i consult my page i have a strange behavior with special characters.
Examples
André for André
Priv� for privé
When i use html.encode i do not get any good result.
In versioncontrol i noticed the only thing that's changed are the extentions for the include files.
Is this normal behavior ?
What did i mis or do wrong ?
A:
I found the cuase of my problem.
In visual studio each file i create is in UTF-8 encoding.
What i need to do is change the encoding from UTF-8 to ANSI.
Problem solved.
| {
"pile_set_name": "StackExchange"
} |
Q:
Rolling Covariance on DF
I have following df:
Close_x Close_y
key_0
2017-10-23 NaN NaN
2017-10-24 -0.147631 0.161791
2017-10-25 0.044194 -0.466305
2017-10-26 -0.069876 0.127095
2017-10-27 0.142261 0.807302
2017-10-30 -0.178176 -0.319247
2017-10-31 0.108544 0.094446
2017-11-01 -0.136536 0.159211
2017-11-02 -0.204280 0.018997
2017-11-03 0.324777 0.309708
2017-11-06 0.049001 0.127125
2017-11-07 0.108391 -0.018910
2017-11-08 0.167624 0.144365
2017-11-09 -0.183357 -0.376189
2017-11-10 0.126741 -0.089764
2017-11-13 0.523946 0.098363
2017-11-14 -0.481367 -0.230961
2017-11-15 -0.148953 -0.552568
2017-11-16 -0.320806 0.819606
2017-11-17 0.172988 -0.262596
2017-11-20 -0.242568 0.127568
2017-11-21 -0.220614 0.654114
2017-11-22 -0.287271 -0.075026
2017-11-24 0.483940 0.205610
2017-11-27 0.177181 -0.038426
2017-11-28 -0.005628 0.984851
2017-11-29 0.537868 -0.036923
2017-11-30 0.112756 0.819095
2017-12-01 0.018372 -0.202453
2017-12-04 -0.362582 -0.105216
... ... ...
2018-09-07 -0.176824 -0.221334
2018-09-10 -0.106907 0.189783
2018-09-11 -0.553854 0.373984
2018-09-12 -0.410831 0.035667
2018-09-13 -0.566335 0.528225
2018-09-14 -0.157859 0.027548
2018-09-17 -0.111232 -0.556972
2018-09-18 0.163057 0.536901
2018-09-19 -0.170732 0.125327
2018-09-20 0.241025 0.784059
2018-09-21 0.065865 -0.036853
2018-09-24 -0.321969 -0.351569
2018-09-25 0.489287 -0.130510
2018-09-26 0.197137 -0.328928
2018-09-27 0.535727 0.276329
2018-09-28 -0.151688 -0.000687
2018-10-01 -0.350278 0.364111
2018-10-02 -0.148503 -0.039669
2018-10-03 -0.252355 0.071152
2018-10-04 -0.104687 -0.816948
2018-10-05 -0.022230 -0.552798
2018-10-08 -0.123084 -0.039512
2018-10-09 -0.425363 -0.141790
2018-10-10 0.408815 -3.286423
2018-10-11 -0.629016 -2.057301
2018-10-12 -0.717824 1.420620
2018-10-15 -0.461052 -0.590498
2018-10-16 -0.385450 2.149560
2018-10-17 -1.040515 -0.025266
2018-10-18 -0.496977 -0.524702
I'm trying to run a rolling(21).cov(close_x,close_y) but keep getting errors. I also want to run a rolling(21).var(close_x) which I have succeeded in getting. The ultimate goal is to create a df (Beta) that equals cov(close_x,close_y)/var(close_x) over a rolling 21-period window. Little help?
A:
To obtain the covariance between the columns you can do:
df.rolling(21).cov()
Close_x Close_y
key_0
2017-10-23 Close_x NaN NaN
Close_y NaN NaN
2017-10-24 Close_x NaN NaN
Close_y NaN NaN
2017-10-25 Close_x NaN NaN
Close_y NaN NaN
2017-10-26 Close_x NaN NaN
Close_y NaN NaN
2017-10-27 Close_x NaN NaN
Close_y NaN NaN
2017-10-30 Close_x NaN NaN
Close_y NaN NaN
2017-10-31 Close_x NaN NaN
Close_y NaN NaN
2017-11-01 Close_x NaN NaN
Close_y NaN NaN
2017-11-02 Close_x NaN NaN
Close_y NaN NaN
2017-11-03 Close_x NaN NaN
Close_y NaN NaN
2017-11-06 Close_x NaN NaN
Close_y NaN NaN
2017-11-07 Close_x NaN NaN
Close_y NaN NaN
2017-11-08 Close_x NaN NaN
Close_y NaN NaN
2017-11-09 Close_x NaN NaN
Close_y NaN NaN
2017-11-10 Close_x NaN NaN
Close_y NaN NaN
2017-11-13 Close_x NaN NaN
Close_y NaN NaN
2017-11-14 Close_x NaN NaN
Close_y NaN NaN
2017-11-15 Close_x NaN NaN
Close_y NaN NaN
2017-11-16 Close_x NaN NaN
Close_y NaN NaN
2017-11-17 Close_x NaN NaN
Close_y NaN NaN
2017-11-20 Close_x NaN NaN
Close_y NaN NaN
2017-11-21 Close_x 0.055186 0.004344
Close_y 0.004344 0.139974
2017-11-22 Close_x 0.057800 0.006661
Close_y 0.006661 0.140316
2017-11-24 Close_x 0.070428 0.011944
Close_y 0.011944 0.126975
To extract the rolling covariance betweem Close_x and Close_y just do:
df.rolling(21).cov().unstack()['Close_x']['Close_y']
key_0
2017-10-23 NaN
2017-10-24 NaN
2017-10-25 NaN
2017-10-26 NaN
2017-10-27 NaN
2017-10-30 NaN
2017-10-31 NaN
2017-11-01 NaN
2017-11-02 NaN
2017-11-03 NaN
2017-11-06 NaN
2017-11-07 NaN
2017-11-08 NaN
2017-11-09 NaN
2017-11-10 NaN
2017-11-13 NaN
2017-11-14 NaN
2017-11-15 NaN
2017-11-16 NaN
2017-11-17 NaN
2017-11-20 NaN
2017-11-21 0.004344
2017-11-22 0.006661
2017-11-24 0.011944
2017-11-27 0.011000
2017-11-28 0.005615
2017-11-29 -0.001627
2017-11-30 0.001503
2017-12-01 0.001986
2017-12-04 0.005164
Name: Close_y, dtype: float64
The variance of Close_x can be obtained by:
df['Close_x'].to_frame().rolling(21).var()
Close_x
key_0
2017-10-23 NaN
2017-10-24 NaN
2017-10-25 NaN
2017-10-26 NaN
2017-10-27 NaN
2017-10-30 NaN
2017-10-31 NaN
2017-11-01 NaN
2017-11-02 NaN
2017-11-03 NaN
2017-11-06 NaN
2017-11-07 NaN
2017-11-08 NaN
2017-11-09 NaN
2017-11-10 NaN
2017-11-13 NaN
2017-11-14 NaN
2017-11-15 NaN
2017-11-16 NaN
2017-11-17 NaN
2017-11-20 NaN
2017-11-21 0.055186
2017-11-22 0.057800
2017-11-24 0.070428
2017-11-27 0.071921
2017-11-28 0.070846
2017-11-29 0.083070
2017-11-30 0.083106
2017-12-01 0.081725
2017-12-04 0.086686
Then the result you want can be achieved by:
df_cov = df.rolling(21).cov().unstack()['Close_x']['Close_y']
df_var = df['Close_x'].to_frame().rolling(21).var()
(df_cov/(df_var.T)).T
Close_x
key_0
2017-10-23 NaN
2017-10-24 NaN
2017-10-25 NaN
2017-10-26 NaN
2017-10-27 NaN
2017-10-30 NaN
2017-10-31 NaN
2017-11-01 NaN
2017-11-02 NaN
2017-11-03 NaN
2017-11-06 NaN
2017-11-07 NaN
2017-11-08 NaN
2017-11-09 NaN
2017-11-10 NaN
2017-11-13 NaN
2017-11-14 NaN
2017-11-15 NaN
2017-11-16 NaN
2017-11-17 NaN
2017-11-20 NaN
2017-11-21 0.078712
2017-11-22 0.115246
2017-11-24 0.169587
2017-11-27 0.152945
2017-11-28 0.079259
2017-11-29 -0.019581
2017-11-30 0.018079
2017-12-01 0.024298
2017-12-04 0.059574
| {
"pile_set_name": "StackExchange"
} |
Q:
GUI Freezing with QThreading and QProcess
I'm attempting to write some software that will process large amounts of images collected from some crystallography experiments. The data process involves the following steps:
User Input to determine the number of images to batch together.
A directory containing the images is selected, and the total number of images is calculated.
A nested for loop is used to batch images together, and construct a command and arguments for each batch which is processed using a batch file.
The following code can be used to simulate the process described using QThread and QProcess:
# This Python file uses the following encoding: utf-8
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import test
import time
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.ui=test.Ui_test()
self.ui.setupUi(self)
self.ui.pushButton_startThread.clicked.connect(self.startTestThread)
def startTestThread(self):
self.xValue = self.ui.lineEdit_x.text() #Represents number of batches
self.yValue = self.ui.lineEdit_y.text() #Represents number of images per batch
runTest = testThread(self.xValue, self.yValue) #Creates an instance of testThread
runTest.start() #Starts the instance of testThread
class testThread(QThread):
def __init__(self, xValue, yValue):
super().__init__()
self.xValue = xValue
self.yValue = yValue
def __del__(self):
self.wait()
def run(self):
for x in range(int(self.xValue)): #For loop to iterate througeach batch
print(str(x) + "\n")
for y in range(int(self.yValue)): #For loop to iterate through each image in each batch
print(str(y) + "\n")
print(y)
process = QProcess(self) #Creates an instance of Qprocess
process.startDetached("test.bat") #Runs test.bat
def stop(self):
self.terminate()
if __name__ == "__main__":
app = QApplication(sys.argv)
app.setStyle("Fusion")
window = MainWindow()
window.show()
sys.exit(app.exec_())
test.bat contents:
@ECHO OFF
ECHO this is a test
The GUI contains two user inputs for xValue and yValue and a button to start a thread. For example, one experiment yields 150,000 images that need to be processed in batches of 500. This will require 300 images per batch to be processed. You can enter 500 for xValue and 300 for yValue. There are two problems:
The GUI freezes, so I can't stop the process if I need to. I thought running a thread was supposed to prevent this.
I receive the following error:
QObject: Cannot create children for a parent that is in a different thread.
(Parent is testThread(0x1a413f3c690), parent's thread is QThread(0x1a4116cb7a0), current thread is testThread(0x1a413f3c690)
I believe this error is a result of the multiple QProcesses being generated through the nested for loop, but I'm not entirely sure.
Is there anyway to stop the GUI from freezing and avoid the generated error?
A:
Explanation
To understand the cause of the problem then the following concepts must be clear:
A QThread is not a Qt thread, that is to say it is not a thread created by Qt but it is a QObject handler of the native threads of each OS.
Only what is inside QThread's run() method is executed in another thread.
If a QThread is destroyed then the run() method will not be executed on a secondary thread but on the thread to which the QThread belongs.
A QObject belongs to the same thread as the parent, and if it has no parent then it belongs to the thread where it was created.
Considering the above, both errors can be explained:
"runTest" is an object with local scope that will be destroyed an instant after the startTestThread method is finished executing, so according to (3) the run method will be executed in the thread to which the QThread belongs, and according to (4) this will be the the GUI.
Considering (4) clearly the QProcess belongs to the main thread (since its parent is QThread and it belongs to the main thread), but you are creating it in a secondary thread (2) that can cause problems so Qt warns you of this.
Solution
For the first problem, simply extend its life cycle, for example by passing it a parent (or make it an attribute of the class). For the second problem it is not necessary to create an instance of QProcess since you can use the static method(QProcess::startDetached()). Considering this, the solution is:
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.ui=test.Ui_test()
self.ui.setupUi(self)
self.ui.pushButton_startThread.clicked.connect(self.startTestThread)
def startTestThread(self):
self.xValue = self.ui.lineEdit_x.text() #Represents number of batches
self.yValue = self.ui.lineEdit_y.text() #Represents number of images per batch
runTest = testThread(
self.xValue, self.yValue, self
) # Creates an instance of testThread
runTest.start() # Starts the instance of testThread
class testThread(QThread):
def __init__(self, xValue, yValue, parent=None):
super().__init__(parent)
self.xValue = xValue
self.yValue = yValue
def __del__(self):
self.wait()
def run(self):
for x in range(int(self.xValue)): # For loop to iterate througeach batch
print(str(x) + "\n")
for y in range(
int(self.yValue)
): # For loop to iterate through each image in each batch
print(str(y) + "\n")
print(y)
QProcess.startDetached("test.bat") # Runs test.bat
def stop(self):
self.terminate()
| {
"pile_set_name": "StackExchange"
} |
Q:
How can you do a simple inline test for an enumeration's case that has associated values you don't care about?
Given this code:
class Item{}
func foo(item:Item){}
enum SelectionType{
case single(resultsHandler:(Item)->Void)
case multi(resultsHandler:([Item])->Void)
}
var selectionType:SelectionType = .single(resultsHandler:foo)
// This line won't compile
let title = (selectionType == .single)
? "Choose an item"
: "Choose items"
How can you update the part that won't compile?
A:
A ternary operator cannot work for enums with associated values, because the classic equality operator does not work with them. You have to use pattern matching, or if case syntax:
let title: String
if case .single = selectionType {
title = "Choose an item"
} else {
title = "Choose items"
}
| {
"pile_set_name": "StackExchange"
} |
Q:
AWS Lambda times out connecting to RedShift
My Redshift cluster is in a private VPC. I've written the following AWS Lamba in Node.js which should connect to Redshift (dressed down for this question):
'use strict';
console.log('Loading function');
const pg = require('pg');
exports.handler = (event, context, callback) => {
var client = new pg.Client({
user: 'myuser',
database: 'mydatabase',
password: 'mypassword',
port: 5439,
host: 'myhost.eu-west-1.redshift.amazonaws.com'
});
// connect to our database
console.log('Connecting...');
client.connect(function (err) {
if (err) throw err;
console.log('CONNECTED!!!');
});
};
I keep getting Task timed out after 60.00 seconds unfortunately. I see in the logs "Connecting...", but never "CONNECTED!!!".
Steps I've taken so far to get this to work:
As per Connect Lambda to Redshift in Different Availability Zones I have the Redshift cluster and the Lamba function in the same VPC
Also Redshift cluster and the Lamba function are on the same subnet
The Redshift cluster and the Lamba function share the same security group
Added an inbound rule at the security group of the Redshift cluster as per the suggestion here (https://github.com/awslabs/aws-lambda-redshift-loader/issues/86)
The IAM role associated with the Lamba Function has the following policies: AmazonDMSRedshiftS3Role, AmazonRedshiftFullAccess, AWSLambdaBasicExecutionRole, AWSLambdaVPCAccessExecutionRole, AWSLambdaENIManagementAccess scrambled together from this source: http://docs.aws.amazon.com/lambda/latest/dg/vpc.html (I realize I have some overlap here, but figured that it shouldn't matter)
Added Elastic IP to the Inbound rules of the Security Group as per an answer from a question listed prior (even if I don't even have a NAT gateway configured in the subnet)
I don't have Enhanced VPC Routing enabled because I figured that I don't need it.
Even tried it by adding the Inbound rule 0.0.0.0/0 ALL types, ALL protocols, ALL ports in the Security Group (following this question: Accessing Redshift from Lambda - Avoiding the 0.0.0.0/0 Security Group). But same issue!
So, does anyone have any suggestions as to what I should check?
*I should add that I am not a network expert, so perhaps I've made a mistake somewhere.
A:
The timeout is probably because your lambda in VPC cannot access Internet in order to connect to your cluster(you seem to be using the public hostname to connect). Your connection options depend on your cluster configuration. Since both your lambda function and cluster are in the same VPC, you should use the private IP of your cluster to connect to it. In your case, I think simply using the private IP should solve your problem.
Depending on whether your cluster is publicly accessible, there are some points to keep in mind.
If your cluster is configured to NOT be publicly accessible, you can use the private IP to connect to the cluster from your lambda running in a VPC and it should work.
If you have a publicly accessible cluster in a VPC, and you want to
connect to it by using the private IP address from within the VPC, make sure the following VPC parameters to true/yes:
DNS resolution
DNS hostnames
The steps to verify/change these settings are given here.
If you do not set these parameters to true, connections from within VPC will resolve to the EIP instead of the private IP and your lambda won't be able to connect without having Internet access(which will need a NAT gateway or a NAT instance).
Also, an important note from the documentation here.
If you have an existing publicly accessible cluster in a VPC,
connections from within the VPC will continue to use the EIP to
connect to the cluster even with those parameters set until you resize
the cluster. Any new clusters will follow the new behavior of using
the private IP address when connecting to the publicly accessible
cluster from within the same VPC.
| {
"pile_set_name": "StackExchange"
} |
Q:
Url Rewrite in IIS 7.5 causes Internal server error
I have a web application runs @ Windows 2008 R2, ASP.NET v4.0.
I installed the Url Rewrite Module, and started to use it as shown in the official examples.
My problem starts when the <rewrite> tag is added to the web.config under <system.webServer> - actually when I try to browse to any page under this current application, I get 500 - Internal server error.
This is the <rewrite> block I've been adding:
<system.webServer>
<rewrite>
<rules>
<rule name="test1">
<match url="^default/([0-9]+)/([_0-9a-z-]+)" />
<action type="Rewrite" url="default.aspx?id={R:1}&title={R:2}" />
</rule>
</rules>
</rewrite>
</system.webServer>
A:
Just had same error and found a fix. You need to install the module for IIS for URL rewrite. you can dowload it here: http://www.iis.net/download/URLRewrite
Cheers,
A:
I had the Url Rewrite Module 2.0 installed as well. However, at some point I had also uninstalled and re-installed iis7, so I believe the rewrite module wasn't registered properly within iis. I was getting the same error as above, even if I just added an empty set of tags to the web.config.
My solution was to uninstall the Url Rewrite Module (through Programs and Features) and reinstall it using the Web Platform Installer. I stopped iis7 during the install (not sure if it mattered). I did not need to reboot.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.