text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Popular ClientDataSet com JSON trunca os dados em 255 caracteres
Estou tentando passar um JSON para um TClientDataSet utilizando a seguinte função:
procedure JsonToDataset(aDataset : TDataSet; aJSON : string);
var
JObj: TJSONObject;
JArr: TJSONArray;
vConv : TCustomJSONDataSetAdapter;
i: Integer;
begin
if (aJSON = EmptyStr) then
begin
Exit;
end;
JArr := nil;
JObj := nil;
try
JArr := TJSONObject.ParseJSONValue(aJSON) as TJSONArray;
except
JObj := TJSONObject.ParseJSONValue(aJSON) as TJSONObject;
end;
vConv := TCustomJSONDataSetAdapter.Create(Nil);
try
vConv.Dataset := aDataset;
if JObj <> nil then
vConv.UpdateDataSet(JObj)
else
vConv.UpdateDataSet(JArr);
finally
vConv.Free;
JObj.Free;
end;
end;
Porém, quando tenho um campo grande, a função trunca minha string em 255 caracteres. Exemplo de JSON:
{
"string": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur rhoncus convallis risus, nec posuere nisl gravida vitae. Duis elementum augue nec condimentum rutrum. Aliquam sodales, dolor at laoreet pharetra, tortor eros efficitur eros, vel euismod sem nulla quis erat. Aliquam erat volutpat. Ut vitae congue lectus, et sodales velit. Cras suscipit pulvinar dolor ut consequat. Praesent eget pellentesque justo. In at maximus lectus, posuere mattis felis."
}
Tem alguma forma de contornar este problema?
A:
A Classe TCustomJSONDataSetAdapter identifica e cria por padrão o Tipo dos campos.
No caso de conteúdo string será criado por padrão um campo do tipo WideStrig de 255 caracteres.
O Ideal é você criar o campo antes da conversão com um tamanho maior que o criado no processo de conversão.
Utilize um Blob se não sabe o tamanho que será enviado.
Edit:
Ao invés de usar o TDataSet, utilize uma TClientDataSet pois, a facilidade de criar os campos será muito maior:
var
i : Integer;
JObj : TJSONObject;
begin
if (aJSON <> EmptyStr) then
begin
JObj := TJSONObject.ParseJSONValue(aJSON) as TJSONObject;
aDataset.Close;
aDataset.FieldDefs.Clear; //Limpa os Campos Existentes
for i := 0 to Pred(JObj.Size) do
begin
//Chave: JObj.Get(i).JsonString.Value
if (Length(JObj.Get(i).JsonValue.Value) > 250) then
begin
aDataset.FieldDefs.Add(JObj.Get(i).JsonString.Value, ftBlob);
end
else
begin
aDataset.FieldDefs.Add(JObj.Get(i).JsonString.Value, ftString, 255);
end;
end;
aDataset.CreateDataSet;
for i := 0 to Pred(JObj.Size) do
begin
//Valor: JObj.Get(i).JsonValue.Value
aDataset.Insert;
aDataset.FieldByName(JObj.Get(i).JsonString.Value).AsString := JObj.Get(i).JsonValue.Value;
aDataset.Post;
end;
JObj.Free;
end;
Esta é uma alternativa para que não seja necessário usar a classe TCustomJSONDataSetAdapter que possui um padrão a ser seguido, claro, é possível modificar esta classe, mas ai é a nível de IDE e não vale a pena, pois perderia este progresso em uma próxima atualização!
| {
"pile_set_name": "StackExchange"
} |
Q:
How to work with AWS Cognito in production environment?
I am working on an application in which I am using AWS Cognito to store users data. I am working on understanding how to manage the back-up and disaster recovery scenarios for Cognito!
Following are the main queries I have:
I wanted to know what is the availability of this stored user data?
What are the possible scenarios with Cognito, which I need to take
care before we go in production?
A:
AWS does not have any published SLA for AWS Cognito. So, there is no official guarantee for your data stored in Cognito. As to how secure your data is, AWS Cognito uses other AWS services (for example, Dynamodb, I think). Data in these services are replicated across Availability Zones.
I guess you are asking for Disaster Recovery scenarios. There is not much you can do on your end. If you use Userpools, there is no feature to export user data, as of now. Although you can do so by writing a custom script, a built-in backup feature would be much more efficient & reliable. If you use Federated Identities, there is no way to export & re-use Identities. If you use Datasets provided by Cognito Sync, you can use Cognito Streams to capture dataset changes. Not exactly a stellar way to backup your data.
In short, there is no official word on availability, no official backup or DR feature. I have heard that there are feature requests for the same but who knows when they would be released. And there is not much you can do by writing custom code or follow any best practices. The only thing I can think of is that periodically backup your Userpool's user data by writing a custom script using AdminGetUser API. But again, there are rate limits on how many times you can call this API. So, backup using this method can take a long time.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to determine if a div has a specific element with specific class?
How can I determine if my div.class has a specific child element e.g table? with a specific class? Is there a javascript/Jquery function for this?
In my case, I want to know if there's already a <table class="mytable"></table> inside my <div class="anotherdiv"></div>
any suggestions, answers, and comments would really be appreciated, Thank you and have a good day!
A:
you can use
if($('.anotherdiv .mytable').length){
//exists
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I align date and values to gridlines in Google Chart?
I'm using Google Chart in my application with the following code (JSFiddle):
google.load('visualization', '1', {packages: ['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'date');
data.addColumn('number', 'view');
data.addRows([
[new Date('2015-08-01'), 5],
[new Date('2015-08-02'), 7],
[new Date('2015-08-03'), 2],
[new Date('2015-08-04'), 16],
[new Date('2015-08-05'), 3],
[new Date('2015-08-06'), 6],
[new Date('2015-08-07'), 1]
]);
var options = {
title: 'view count',
width: 900,
height: 500,
hAxis: {
format: 'MM-dd',
gridlines: {count: 90}
},
vAxis: {
minValue: 0,
gridlines: {
color: '#f3f3f3',
count: 6
}
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
However, the chart does not match between date and gridlines:
How can I match (synchronize) grid and date?
A:
Changing the date format (mm/dd/yyyy vs. yyyy-mm-dd) seems to get it to align...
google.load('visualization', '1', {
packages: ['corechart']
});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'date');
data.addColumn('number', 'view');
data.addRows([
[new Date('08/01/2015'), 5],
[new Date('08/02/2015'), 7],
[new Date('08/03/2015'), 2],
[new Date('08/04/2015'), 16],
[new Date('08/05/2015'), 3],
[new Date('08/06/2015'), 6],
[new Date('08/07/2015'), 1]
]);
var options = {
title: 'view count',
width: 900,
height: 500,
hAxis: {
format: 'MM-dd',
gridlines: {
count: 90
}
},
vAxis: {
minValue: 0,
gridlines: {
color: '#f3f3f3',
count: 6
}
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script src="https://www.google.com/jsapi"></script>
<div id="chart_div"></div>
| {
"pile_set_name": "StackExchange"
} |
Q:
It's possible to temporary store file in ASP.NET ViewState as byte[]?
I've seen this:
How can I store a byte[] list in viewstate?
and I'm trying to do the same with byte[] from a FileUpload:
<asp:FileUpload ID="Documento" runat="server" />
<asp:ImageButton ID="BtnUpload" runat="server" OnClick="BtnUpload_Click" CausesValidation="false" />
<asp:Panel ID="DocumentoAllegato" runat="server" Visible="false">
<asp:ImageButton ID="BtnDownloadDocumento" runat="server" OnClick="BtnDownloadDocumento_Click" CausesValidation="false" />
<asp:ImageButton ID="BtnEliminaDocumento" runat="server" OnClick="BtnEliminaDocumento_Click" />
</asp:Panel>
protected void BtnUpload_Click(object sender, ImageClickEventArgs e)
{
if (Documento.HasFile)
{
ViewState["myDoc"] = Documento.FileBytes;
Documento.Visible = false;
BtnUpload.Visible = false;
DocumentoAllegato.Visible = true;
}
}
protected void BtnDownloadDocumento_Click(object sender, ImageClickEventArgs e)
{
byte[] file = null;
if (ViewState["myDoc"] != null)
{
file = (byte[])ViewState["myDoc"];
}
MemoryStream ms = new MemoryStream(file);
Response.Clear();
Response.Buffer = false;
Response.ContentType = "application/pdf";
Response.AddHeader("Content-disposition", string.Format("attachment; filename={0};", "Allegato.pdf"));
ms.WriteTo(Response.OutputStream);
}
protected void BtnEliminaDocumento_Click(object sender, ImageClickEventArgs e)
{
ViewState["myDoc"] = null;
FuDocumento.Visible = true;
BtnUpload.Visible = true;
DocumentoAllegato.Visible = false;
}
But when I upload a file and I try to download it from the ImageButton it comes with more size and if I try to open it says it's dameged and cannot be open.. What I'm doing wrong?
UPDATE:
Tried doing:
ViewState["myDoc"] = Convert.ToBase64String(FuDocumento.FileBytes);
and
file = Convert.FromBase64String((string)ViewState["myDoc"]);
But still same problem. So I've tried to edit the PDF with Notepad++ and over the %%EOF line there's the entire asp page code!! Deleting that part and saving the PDF it turn OK, why It's doing that? That's something wrong in
ms.WriteTo(Response.OutputStream);
?
UPDATE 2:
Changed the ViewState with an hiddenfield:
<asp:HiddenField ID="myDoc" runat="server" />
myDoc.Value = Convert.ToBase64String(FuDocumento.FileBytes);
file = Convert.FromBase64String(myDoc.Value);
And adding in the download part:
Response.End();
It's now working!
A:
The problem was I miss the Response.End() in the download part, so it was adding the entire asp page code inside the pdf file..
Good suggestions are to use Convert.ToBase64String from Gavin and HiddenField instead of ViewState from Arindam Nayak.
| {
"pile_set_name": "StackExchange"
} |
Q:
Invalid appsecret_proof provided in the API argument
i have created an app in my facebook account and done post to my friend using my access token (php).
But another user cannot post to their friend using my app id and secret and getting the error
Invalid appsecret_proof provided in the API argument
i have disabled
Required app secret proof in my app settings
any solution please?
public function facebookUsershare() {
require '../facebook/src/facebook.php'; $facebook = new Facebook(array( 'appId' => 'app id', 'secret' => 'secret_key', ));
$privacy = array( 'description' => 'Vladimir Sergeevich', 'value' => 'CUSTOM', 'friends' =>'friend id' 'allow' => 'loged in user' );
try {
$result = $facebook->api('/me/feed', 'POST', array( "access_token" => 'access_token', 'picture' => "path to image", 'link' => "gmail.com";, 'name' => "Go wi6 7", 'caption' => "capn", 'privacy' => json_encode($privacy) ));
echo 'Successfully posted to Facebook Personal Profile'; //return $facebookfrndids; } catch(Exception $e) {
echo $e->getMessage();
return false; }
A:
finally i got the answer....
disable Required app secret proof in the advanced settings of app, and comment the following code in base_facebook.php sdk
if (isset($params['access_token'])) {
$params['appsecret_proof'] = $this->getAppSecretProof($params['access_token']);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Excel worksheet maximum of calculated value
Is there a worksheet function that enables you to find the maximum value of a series of calculations. I'm trying to find the highest difference between two columns without creating a new column with the difference in. I could use =max(l1-m1,l2-m2,l3-m3) etc. but there are hundreds of rows. Max(l1-m1:l100-m100) doesn't work
A:
Try this:
=MAX(IF(ISNUMBER(L1:L100)*ISNUMBER(M1:M100),ABS(L1:L100-M1:M100),""))
Its an array formula, so commit the formula by pressing Ctrl + Shift + Enter
If your data is consistent you can even use:
=MAX(ABS(L1:L100-M1:M100))
Again this is an array formula.
Got this from here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Arduino digitalWrite affected by Serial.begin
I used following code to write to digital pin with Serial.begin. Using Serial.begin affected my digital write. The correct timing will not happen.
#define led 0
void setup() {
// put your setup code here, to run once:
pinMode(led,OUTPUT);
Serial.begin (115200);
}
void loop() {
// put your main code here, to run repeatedly:
delay(500);
digitalWrite(led,LOW);
delay(500);
digitalWrite(led,HIGH);
}
A:
I discovered that I cannot using digital pin 0 and 1 as input or output when using serial. Serial transmit(tx) and Receive (Rx) is on 1 and 0 respectively. It is shown in the Arduino Uno board. Solution was to use a different digital pin (2-13).
| {
"pile_set_name": "StackExchange"
} |
Q:
C# & CLIPS. Using .clp in more than in one Form
I want to use a .clp file in my C# project. This project contain several Forms.
Can I load *.clp once and use it in all forms (create/delete facts, etc.)?
(I am using CLIPSNet.dll.)
UPD. There is a Form1. On close it I save the facts. In second form (Form2) I want to do same thing but if I load a .clp file in block of Form2 I've lost the facts entered at first form.
How I can avoid this situaton? So I need opened CLIPS file through all C# solution. So I want ask you - Is it really to do or not?
UPD1. I use MVS Community 2013.
A:
Dude, just create another class working with CLIPS project!
That's it.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to check form validation inside directive applied to itself?
With AngularJS, I'm trying to check validity of a form within a custom directive.
In the template:
<form name="formName" custom-directive="someController.function()">
...
</form>
In JavaScript:
angular.module("myApp")
.directive("customDirective", function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var callbackFn = attrs.customDirective;
// Check form validation, then call callbackFn
scope.$eval(callbackFn);
}
};
}
);
Usually, we can see form validation with scope.formName.$valid, but the form's name can be different, so I need a generic way to access it.
A:
You need to add require: 'form' directive:
.directive("customDirective", function () {
return {
require: 'form',
restrict: 'A',
link: function (scope, element, attrs, formController) {
var callbackFn = attrs.customDirective;
// Check form validation, then call callbackFn
if (formController.$valid) {
scope.$eval(callbackFn);
}
}
};
}
After that form controller will be injected as fourth argument into link function, and you would be able to check form validity with formController.$valid property.
| {
"pile_set_name": "StackExchange"
} |
Q:
issue exporting path to spark home on ubuntu
I’m installing spark, and pyspark on my ubuntu server. I’m trying to set my SPARK_HOME path on ubuntu server and I’m getting the error below. Does anyone see what the issue might be?
code:
export SPARK_HOME='/home/username/spark-2.4.3-bin-hadoop2.7'
export PATH$SPARK_HOME:$PATH
output:
-bash: export: `PATH/home/username/spark-2.4.3-bin-hadoop2.7:/home/username/anaconda3/condabin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin': not a valid identifier
A:
export PATH=$SPARK_HOME:$PATH
Missing equalTo..
| {
"pile_set_name": "StackExchange"
} |
Q:
How Can I Tell Eclipse to Compile and Build a Project with a Different JRE Version than it Normally Does?
I'm not sure if this question has been answered in full or if my title is descriptive enough given my situation, but I've been asked to convert a project from being built with Ant to Maven. That part isn't too bad, but I've been told that this application was designed specifically for the JRE version 1.5 rather than the JRE 6 everything else I've been dealing with uses. Now, I'm incredibly new to Eclipse and Java themselves, so I was a bit confused when I was asked to tell either Eclipse or Maven to build this particular project using the JRE 1.5 instead. I have it installed, I believe, and I've tried to follow the steps outlined here: ( Eclipse: Build and conform to different JRE versions ), but I've run into a snag.
I've managed to change the Run Configuration to use the Alternate JRE jre1.5.0_11. When I then tried to build it, the console spat out the following:
[ERROR] Unable to locate the Javac Compiler in:
[ERROR] C:\Program Files (x86)\Java\jre1.5.0_11\..\lib\tools.jar
[ERROR] Please ensure you are using JDK 1.4 or above and
[ERROR] not a JRE (the com.sun.tools.javac.Main class is required).
[ERROR] In most cases you can change the location of your Java
[ERROR] installation by setting the JAVA_HOME environment variable.
I assume this means that I need to be using the JDK 1.5 in order to use the JRE 1.5, since I'm currently working with JDK 1.6. Now, is there a way to install the JDK 1.5 so that this project can use it? My JAVA_HOME variable currently points to the JDK 1.6, and I would like it to stay that way... Is there a way to be able to use both and simply tell the project (or Eclipse or Maven... however it works) to use a specific version of the JDK?
A:
Yes, this is possible. You can install as many different versions of Java — JREs and JDKs — as you like, and tell Eclipse which one to use for each project.
First step is to install the JDK 1.5 on your machine (JDK is short for 'Java [SE] Development Kit', look for that on the Oracle download site). The JDK includes a JRE, so to make life easier you can usually just install the JDK and not worry about the JRE/JDK distinction.
Second step is to tell Eclipse about the new JDK. Go to Preferences... then Java > Installed JREs. Click the Search... button and Eclipse should find your newly installed JDK 1.5 and add it to the list.
Final step is to allocate that JDK 1.5 to your project. Bring up the Properties menu for your project (right-click it). Then set these values:
Java Compiler tab
Tick Enable project specific settings
Set Compiler Compliance level to 1.5
Java Build Path tab, Libraries subtab
Find the JRE System Library item, click Edit...
Set Alternate JRE to your newly installed JDK 1.5
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use string parameters in an URL?
I'm using Rest api, so I send a Request with URLs, my problem is when the user nome a folder with a name containing a space or special characters, it sends nothing. I used the following conversion, but it does not work:
string url = "http://localhost:8080/alfresco/service/set/folder/permission/?folderName="
+ folder
+ "&permi="
+ acces
+ "&username="
+ user
+ "&alf_ticket="
+ GetToken();
Uri url2 = new Uri(url);
Response.Write(url2);
A:
You have to URL encode the variables in order to make them safe. Use HttpUtility.UrlEncode.
string urlSafeFolder = HttpUtility.UrlEncode(folder);
Use that variable in your URL and you will be fine. (You will have to do this for every parameter you pass in!)
| {
"pile_set_name": "StackExchange"
} |
Q:
Where can I find people to collaborate on software projects?
I mean not on open source, but software to build and sell.
They don't have to be programmers, they can be also people who have ideas or with a marketing background.
Is there any good internet platform for this?
A:
Try FairSoftware or more specifically FairSoftware/TeamUp.
A:
builditwith.me
bettercodes.org
A:
Professional social network LinkedIn is a good place to start out with. You can get involved in groups with same interests and find people to start out a project, find employers and so on.
| {
"pile_set_name": "StackExchange"
} |
Q:
Avoid O(n^2) when matching persons in databases - parallel person matching
I have millions of "people" records - say the customers for client one and customers for client two. We want to match the people in client one and client two together - for example finding that "Mr Joel Spolsky" is in client one database and matching him to "J Spolsky" in client two, creating a totally new record in "master database".
THe exact algorthim to match two candidates is not important, what is important is that the most obvious solution is to take every record in client one and compare to every record in client two.
This quickly becomes an enormous task, especially with clients three four five etc.
Does anyone have any interesting approaches to improve performance?
A:
The most obvious way is to create a common sort algorithm for all databases. Sort your databases into lists, compare the "top" items in each sorted list, then keep discarding the "earliest" item until you find two items that match. Record the match, discard the matches, and continue.
This works very well if you have, say, two sets of book ISBN numbers to compare to find duplicates between two libraries, but not so well with people's names where names may not be identical (J Smith vs John Smith, eg). You can improve things somewhat by using a sort of KWIC scheme where you make several entries in your sorted list for each DB entry -- eg, one entry for name, one entry for address, one entry for social security number -- whatever criteria you might decide to match on. A Soundex-type translation of the names may also be beneficial.
| {
"pile_set_name": "StackExchange"
} |
Q:
Mutual fund wants to get 1% upfront fee (US). Is that within acceptable ranges for a managed bonds fund?
Mutual fund wants to get 1% upfront fee (US) plus an annual fixed fee. Is that within acceptable ranges for a managed bonds fund?
A:
"Front loaded" (and the inverse "back loaded") Mutual funds used to be very common. They were mostly replaced in the 1980s by no-load mutual funds from places like Vanguard.
I've got a managed no-load bond fund through Vanguard, and it's management fee is 0.09%. According to its web site, the average management fee for similar funds is 0.74%.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can this Rails action be refactored?
How can this simple new action be refactored?
def new
@payment = Payment.new(:invoice_id => params[:invoice_id])
if @payment.invoice.present?
@payment.amount = @payment.invoice.balance.abs
end
@title = "New payment"
end
It feels a bit clumsy to me.
Thanks for any help!
A:
To simplify your controller, you should move the business logic to your model.
Here's three suggestion:
If invoice_id will not change over the live of your Payment instance, and you don't need caching:
def amount
invoice.balance.abs
end
If invoice_id will not change over the live of your Payment instance, but you use the amount value multiple times in your controller/view. (use caching):
def amount
@_amount ||= invoice.balance.abs
end
If invoice_id may change over the live of your Payment instance, and you need caching:
def amount
@_amount ||= {}
@_amount[invoice_id] ||= invoice.balance.abs
end
end
| {
"pile_set_name": "StackExchange"
} |
Q:
Javascript - Codepen trying to change order of my html content using an array my function is working but not so well i don't understand why
https://codepen.io/thibault-cabanes/pen/xmvYqr
Hi! if someone can help me, I don't know if it's the logic of my code that is wrong or if I made some mistakes , so please just take a look on it!
I create an Array named "dominos" with 13 entries;
I link each entries of dominos with each div class= domino of my html with my "lien" function;
I shuffle the dominos array with the "shuffle" function;
I send back the new order of my div in the document;
`
const reload = (array) => {
let len = array.length-1 ;
for (var i = 0; i <= len; i++) {
let n = i+1,
//
par = document.getElementById('pioche'),
son = array[i],
old = document.getElementById("d"+n);
par.replaceChild(son, old);
//another way to do the same thing
/*document.getElementById("pioche").replaceChild(array[i],
document.getElementById('d'+ n));*/
}}
lien(dominos);
shuffle(dominos);
reload(dominos)
console.log(dominos); `
In this last opération, i'm loosin some html dominos, while at the end of the opérations my array is full and shuffle, some of my html's domino's are missing, and as you refresh, there is not the same number of domino's that are missing in the DOM...
A:
First off all your shuffle function makes some random array but not shuffled array of origin elements. Here is how you can fix it:
const shuffle = (array) => {
let len = array.length - 1;
let dominos = array.slice(0); //make a copy of your original array
for ( var i = len; i >= 0 ; i--){
//select random index from 0 to array length
var j = Math.floor(Math.random() * (dominos.length - 1));
/*delete element at selected index from copy of the original array,
so it can't be randomly chosen again*/
temp = dominos.splice(j, 1);
//replace the element in the origin array with the randomly selected one
array[i] = temp[0];
}
}
The second problem is using getElementById for selecting elements in your reload function. When you make replacement, there is some possibility that you'll add element that has the the same id that is already in DOM tree. After that your ids are not unique anymore, and according to documentation: the id attribute specifies a unique id for an HTML element (the value must be unique within the HTML document). Since ids are not unique, the behaviour of getElementById is unpredictable. But you can always address children with childNodes from the parent element, that's how you can fix it:
const reload = (array) => {
let len = array.length-1 ;
for (var i = 0; i <= len; i++) {
let n = i+1,
par = document.getElementById('pioche'),
son = array[i],
//old = document.getElementById("d"+n); this line makes it all wrong
old = par.childNodes[i]; //this way you are always addressing the correct child
par.replaceChild(son, old);
}}
lien(dominos);
shuffle(dominos);
reload(dominos)
console.log(dominos);
now it should all work fine.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to retrieve value of a specific field from a MongoDB collection in Java
I have a MongoDB database and I need to retrieve the list of values in a field. I have tried with:
FindIterable<Document> findIterable = collection.find(eq("data", data)).projection(and(Projections.include("servizio"), Projections.excludeId()));
ArrayList<Document> docs = new ArrayList();
findIterable.into(docs);
for (Document doc : docs) {
nomeServizioAltro += doc.toString();
}
but it prints
Document{{servizio=Antoniano}}Document{{servizio=Rapp}}Document{{servizio=Ree}}
While I want an array with these strings:
Antoniano,Rapp,Ree
Is there a way to do it?
A:
You can try java 8 stream to output a list of servizio values.
List<String> res = docs.stream().
map(doc-> doc.getString("servizio")).
collect(Collectors.toList());
Using for loop
List<String> res = new ArrayList();
for(Document doc: docs) {
res.add(doc.getString("servizio"));
}
| {
"pile_set_name": "StackExchange"
} |
Q:
What was Newton's idea of absolute space and time?
When one says that Newton believed in the concept of "absolute space" and "absolute time" does it simply mean that the length interval between two points in space and time interval between two events is independent of the state of motion of the observer? If there is something more to it or if I am incorrect please disabuse my misconception.
A:
Newton does not reference intervals in his work. Quoting from the Scholium (appendix) to Philosophiae Naturalis:
...And thence arise certain prejudices, for the removing of which it will be convenient to distinguish them into absolute and relative, true and apparent, mathematical and common.
Absolute, true, and mathematical time, of itself and from its own nature, flows equably without relation to anything external, and by another name is called duration; relative, apparent, and common time is some sensible and external ... measure of duration by the means of motion, which is commonly used instead of true time, such as an hour, a day, a month, a year.
Absolute space, in its own nature, without relation to anything external, remains always similar and immovable. Relative space is some movable dimension or measure of the absolute spaces, which our senses determine by its position to bodies and which is commonly taken for immovable space; such is the dimension of a subterraneous, an aerial, or celestial space, determined by its position in respect of the earth. Absolute and relative space are the same in figure and magnitude, but they do not remain always numerically the same...
I've edited out some bits to avoid burdening the quote, but the key points are that absolute time refers to time measured by some imaginary ideal "absolute" clock, whereas absolute space refers to some position measured by some imaginary ideal "absolute" coordinate system, which are postulated as ipso facto existing on their own, without relation to anything external.
It is Galilei who discussed what we now called invariants of the state of motion, in the "Second Day" of his Dialogue Concerting the Two Chief World Systems, between Savatius and Sagredius.
Source: The translation of Newton's is by Andrew Motte (1729) as revised by Florian Cajori (Berkeley: University of California Press, 1934).]
| {
"pile_set_name": "StackExchange"
} |
Q:
getimagesize / fopen connection refused
I am trying to get the size from an remote image with the native php function getimagesize from an absolute URL.
I am using PHP 7.3, here is the code:
$fichier = 'http://mydomain/images/image.jpg';
$size = getimagesize($fichier);
var_dump($size);
And the code return :
PHP Warning: getimagesize(http://mydomain/images/image.jpg): failed to open stream: Connection refused in ...
And with fopen, same problem:
PHP Warning: fopen(http://mydomain/images/image.jpg): failed to open stream: Connection refused
And when I am trying the same URL from an other server, it is working.
Also, if I am trying to get infos from an other image and from an other domain but on the same server, it is not working also.
allow_url_fopen is enabled.
I think that it should come from Apache conf, but not sure... Anybody has an idea ?
Thanks !
A:
Finally, the problem is coming from the network.
Apache could not resolve his own public domain name.
So to correct the problem, I just had " 127.0.0.1 mydomain" in the hosts file, and the problem was solved.
Hope it can help !
| {
"pile_set_name": "StackExchange"
} |
Q:
How to group by column with hibernate, and retrieve all columns
I've inherited an application that retrieves some data from an Oracle DB and then transforms it into XML for another application to import. The reasoning behind why it needs to be done in this manner is a bit long winded, but in short we have a database that looks something like this:
ID | CHILD_ID | IRRELEVANT_COLUMN
1 | 100 | A
2 | 200 | E
2 | 200 | B
3 | 300 | G
3 | 300 | ZZ
3 | 300 | WHO_KNOWS_WHAT_MIGHT_END_UP_HERE
We only use the values ID & CHILD_ID - previously there was no IRRELEVANT_COLUMN, so each ID would be unique and the following code was used to retrieve the data from the DB:
public static List<RecordInfo> getRecordInfo() {
List<RecordInfo> recordInfo = null;
Session session = HibernateUtils.getSessionFactory().openSession();
try {
recordInfo = session.createCriteria(RecordInfo.class)
.list();
}
catch (Exception e) {
logger.error("Error reading database", e);
}
return recordInfo;
}
RecordInfo.java:
public class RecordInfo {
private Long id;
private Event event;
private Integer childId;
//Snip - Public Getters and Setters below.
}
RecordInfo.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.hewhowas.model.RecordInfo" table="NIGHTMARE_TABLE" lazy="false">
<id name="id" type="long" column="ID">
<generator class="native"/>
</id>
<property name="childId">
<column name="CHILD_ID"/>
</property>
<many-to-one name="event" class="com.hewhowas.model.Event" column="CHILD_ID" fetch="join"/>
</class>
I've attempted to use Projections to group the data by ID - but then it only retrieves the column ID and nothing else - and I get Cast Exceptions when trying to cast retrieve a RecordInfo object.
Is there any way that I could use Criteria and Projections to return a result set similar to:
ID | CHILD_ID | IRRELEVANT_COLUMN
1 | 100 | A
2 | 200 | B
3 | 300 | WHO_KNOWS_WHAT_MIGHT_END_UP_HERE
The information in "IRRELEVANT_COLUMN" is not used in any manner - so the exact records that are retrieved don't impact the application in any way, I just need to make sure that ONLY one record with id of 1 is returned, and only one record with the id of 2 is returned, so on, etc.
Hope there's enough info. Thanks in advance guys :)
A:
I'm not sure what exactly you tried when you tried the Projections. With that in mind I would like to recommend you to try:
query.add(Projections.property(Id)).add(Projections.property(Child_id)).add(Projections.property(Irrelevant_Column)).add(Projections.groupProperty(Id))
I would like to state that there are multiple ways to write this. Basically this one is equivalent to :
select id, child_id, irrelevant_column
from RecordInfo
group by id
| {
"pile_set_name": "StackExchange"
} |
Q:
have problem with axios on two sequential request
I Have problem when two sequential request send and the second request get error --> Error: "Network Error"
for example :
OPTION : /meal/get 200 success
GET: /meal/get 200 success
OPTION: /message/get 200 get
dont send GET :/message/get
and show error
I check the header response of OPTIONS : the response part of first option is true but the second is wrong
I use php for my backend and All of the part work truly
global config file:
axios.defaults.headers.get['Accept'] = 'application/json'
axios.defaults.headers.common['Content-Type'] = 'application/json'
this is my code
axios({
method: 'get',
url: '/message/index',
data: {},
params: {
page: page
}
}).then(res => {
header of response:
Access-Control-Allow-Credentials true
Access-Control-Allow-Headers Origin, Accept, Content-Type, …, X-GR- Token, Accept-Language
Access-Control-Allow-Methods GET,POST,OPTIONS
Access-Control-Allow-Origin *
Access-Control-Expose-Headers X-Access-Token, X-Refresh-Toke…nation-Total-Count, X-Payload
Connection Keep-Alive
Content-Length 0
Content-Type text/html; charset=UTF-8
Date Mon, 11 Mar 2019 16:00:22 GMT
Keep-Alive timeout=5, max=100
Server Apache/2.4.27 (Win64) PHP/7.1.9
Status 200 OK
X-Powered-By PHP/7.1.9
each request in different component
axios({
method: 'get',
url: '/meal/suggest',
data: {},
params: {}
}).then( res => {
console.log(res)
// this.rightSideData = res.data
}).catch(err => {
console.log(err)
console.log(err.response.data)
})
header response of this request:
Connection Keep-Alive
Content-Length 876
Content-Type text/html; charset=UTF-8
Date Mon, 11 Mar 2019 16:00:23 GMT
Keep-Alive timeout=5, max=100
Server Apache/2.4.27 (Win64) PHP/7.1.9
X-Powered-By PHP/7.1.9
A:
I found the solution
I set header in my php phalcon and It's response to first request but if I send two request in the same time It's answer just one of them and second borken
I search alot and understand I put header in .htaccess too
this is my code:
#Header set Content-Security-Policy "default-src 'self';"
Header always set Access-Control-Allow-Origin "http://localhost:8080"
Header always set Access-Control-Allow-Headers "Content-Type, Accept-Language, X-Access-Token, X-Client-Id, X-Secret-Id, X-GR-Token"
Header always set Access-Control-Allow-Methods "GET,POST,OPTIONS"
Header always set Access-Control-Expose-Headers "X-Access-Token, X-Refresh-Token,X-Access-Token-Expire, X-Pagination-Current-Page, X-Pagination-Page-Count,X-Pagination-Per-Page, X-Pagination-Total-Count, X-Payload"
Header always set Access-Control-Allow-Credentials "true"
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get Database-table entries where a certain column is not linked to a certain value by another table?
I have a database with the following tables: Students, Classes, link_student_class. Where Students contains the information about the registered students and classes contains the information about the classes. As every student can attend multiple classes and every class can be attended by multiple students, I added a linking-table, for the mapping between students and classes.
Linking-Table
id | student_id | class_id
1 1 1
2 1 2
3 2 1
4 3 3
In this table both student_id as well as class_id will appear multiple times!
What I am looking for, is a SQL-Query that returns the information about all students (like in 'SELECT * FROM students') that are not attending a certain class (given by its id).
I tried the following SQL-query
SELECT * FROM `students`
LEFT JOIN(
SELECT * FROM link_student_class
WHERE class_id = $class_id
)
link_student_class ON link_student_class.student_id = students.student_id
Where $class_id is the id of the class which students i want to exclude.
In the returned object the students i want to include and those i want to exclude are different in the value of the column 'class_id'.
Those to be included have the value 'NULL' whereas those I want to exclude have a numerical value.
A:
you should check for NULL link_student_class.student_id
SELECT *
FROM `students`
LEFT JOIN(
SELECT *
FROM link_student_class
WHERE class_id = $class_id
) link_student_class ON link_student_class.student_id = students.student_id
where link_student_class.student_id is null
| {
"pile_set_name": "StackExchange"
} |
Q:
Merging and Counting of attributes uisng Pandas
I have grouped 2 columns of a CSV file
(r3 = df.groupby(['Predicted_Label', 'Actual_Label']).size().unstack(fill_value=0)
print (r3))
to get the following result:
Column 5 and 6 of Actual Labels should be merged into Row 1 of Predicted Labels.
Output should be in the following form:
How to create the above new columns using Pandas?
A:
Use assign for new columns created by numpy.diagonal and subtracted sums per rows and per columns, reindex is used for same indices of columns like index values:
#strip traling whitespaces
df['Predicted_Label'] = df['Predicted_Label'].str.strip()
r3 = df.groupby(['Predicted_Label', 'Actual_Label']).size().unstack(fill_value=0)
a = np.diagonal(r3.reindex(columns=r3.index))
b = r3.sum(axis=1) - a
c = r3.sum().reindex(r3.index) - a
out = r3.assign(T1=a,T2=b,T3=c)
print (out)
0 1 2 3 5 6 T1 T2 T3
0 14 0 3 22 0 0 14 25 14
1 5 56 14 157 19 11 56 206 8
2 2 0 37 26 0 0 37 28 17
3 7 8 0 1805 0 1 1805 16 205
| {
"pile_set_name": "StackExchange"
} |
Q:
Can the root user change the owner of a file that he doesn't own?
My web server uses the user www-data to access/change files. This causes permission issues for php file upload etc. for files owned by root (or by any other user).
I'd like to use the 755/644 permissions for my folders/files (rather than 775/664), so I'd like to actually change the owner of the files to www-data, rather than just the group.
I don't want to run in to the situation where the root user can't access/modify the files though.
I'm sure this is basic knowledge for most people, but I just wanted to double-check it. If I change the owner:group of a file to www-data:www-data, will the root user still be able to edit/access the files? Would the root user be able to change it back to root:root if desired?
A:
In most situations (read default installations), root can do anything a regular user can and much more. If you think root cannot do something, remember it can become a user who can :)
You'll be fine.
| {
"pile_set_name": "StackExchange"
} |
Q:
Json4s ignoring None fields during seriallization (instead of using 'null')
I am having a generic json serialization method that uses json4s. Unfortunately, it is ignoring fields if the value is None. My goal is to have None fields be represented with a null value. I tried by adding custom serializer for None, but still it is not working.
object test extends App {
class NoneSerializer extends CustomSerializer[Option[_]](format => (
{
case JNull => None
},
{
case None => JNull
}))
implicit val f = DefaultFormats + new NoneSerializer
case class JsonTest(x: String, y: Option[String], z: Option[Int], a: Option[Double], b: Option[Boolean], c:Option[Date], d: Option[Any])
val v = JsonTest("test", None, None,None,None,None,None);
println(Serialization.write(v))
}
Result from the above code :
{"x":"test"}
I tried this link and some others, but is is not solving the issue for case classes
A:
I assume that you would like to have Nones serialized to null within your JSON. In this case it is sufficient to use DefaultFormats.preservingEmptyValues:
import java.util.Date
import org.json4s._
import org.json4s.jackson.Serialization
object test extends App {
implicit val f = DefaultFormats.preservingEmptyValues // requires version>=3.2.11
case class JsonTest(x: String, y: Option[String], z: Option[Int], a: Option[Double], b: Option[Boolean], c:Option[Date], d: Option[Any])
val v = JsonTest("test", None, None, None, None, None, None);
// prints {"x":"test","y":null,"z":null,"a":null,"b":null,"c":null,"d":null}
println(Serialization.write(v))
}
| {
"pile_set_name": "StackExchange"
} |
Q:
A special type of transitivity
Let $M$ be a smooth orientable manifold with volume form $\Omega$. Fix two pints $x,y \in M$. Put $A$=all volume preserving diffeomorphism of M which maps $x$ to $y$.
Define $B$=All linear volume preserving maps from $T_{x}M$ to $T_{y} M$, with respect to $\Omega_{x}$ and $\Omega_{y}$, respectively. We assume that $A\neq \text{The empty set}.$
My question:$\;$ Is the following map surjective? :
$$\phi:A\rightarrow B\\\phi(f)=Df_{x}$$
We can consider the same question by replacing the volume form by a riemanian metric (or some other structures) and revise $A$ and $B$ to isometries and linear isometries, respectively.
The motivation for the second part is "the spheres". However these are not reliable example because they are homogenous, isometrically.
A:
Let $M$ be an $n$-manifold endowed with a nonvanishing $n$-form $\Omega$, let $\mathrm{Diff}(M,\Omega)$ denote the group of $\Omega$-preserving diffeomorphisms of $M$, and, for $x\in M$, let $\mathrm{Diff}(M,\Omega,x)$ denote the subgroup that fixes $x$.
Your question, then, reduces to "Is the homomorphism $D:\mathrm{Diff}(M,\Omega,x)\to \mathrm{SL}(T_xM)$ defined by $D(f) = f'(x):T_xM\to T_xM$ surjective?"
The answer is 'yes'. The reason is that the image of $D$ has to be a Lie subgroup of $\mathrm{SL}(T_xM)$, and a simple local construction (see the remark at the end) shows that it must be all of $\mathrm{SL}(T_xM)$.
As for your more general question, this has been considered at length in the literature, beginning with the work of Élie Cartan on what are now called 'pseudo-groups' and continuing with a very extensive development in the 1950s and 1960s by Chern, Kuranishi, Singer, Sternberg, Guillemin, and many others. The basic question is this: "If an $n$-manifold is endowed with a $G$-structure $B\subset \mathcal{F}(M)$ (where $G\subset\mathrm{GL}(n,\mathbb{R})$ is a subgroup and $\mathcal{F}(M)$ is the (co-)frame bundle of $M$, when does $\mathrm{Diff}(M,B)$, the group of diffeomorphisms of $M$ that preserve $B$, act transitively on $M$ and when does it act transitively on $B$?" This latter transitivity is a very strict condition, and it can hold 'locally' without holding globally.
For example, when the $G$-structure is a Riemannian metric, $\mathrm{Diff}(M,B)$ acts transitively on $M$ iff $M$ is homogeneous as a Riemannian manifold, but $\mathrm{Diff}(M,B)$ acts transitively on $B$ iff $M$ has constant sectional curvature and is globally symmetric.
On the other hand, if the $G$-structure is a complex structure on $M$, all of these $G$-structures are locally equivalent, so they are locally homogeneous to all orders. Now, when $M=\mathbb{CP}^2$, the biholomorphisms act transitively on the complex frame bundle, but when $M=\mathbb{CP}^1\times \mathbb{CP}^1$, the biholomorphisms act transitively on $M$ but not on its complex frame bundle.
As a final example, when the $G$-structure is a symplectic structure on $M$ (and $M$ is connected), the symplectomorphisms do act transitively on both $M$ and $B$.
Thus, the answer to your question depends very much on which $G$-structure you want to study.
Remark added at the request of the OP: Showing that the image of the homomorphism $D$ contains a neighborhood of the identity in $\mathrm{SL}(T_xM)$ can be done in a number of ways, but here is one that is relatively 'low-tech': Note that the result is obvious when $n=1$, so assume that $n>1$ from now on. Then, one can choose coordinates $u=(u^i)$ centered on $x\in M$ and defined on a neighborhood $U$ of $x$ in which
$$
\Omega = \mathrm{d}u^1\wedge\mathrm{d}u^2\wedge\cdots\wedge\mathrm{d}u^n = \mathrm{d}u
$$
There is an $r>0$, so that $u(U)\subset\mathbb{R}^n$ contains the open ball $B_r(0)$ of radius $r$ about $0\in\mathbb{R}^n$. Let $G_0 = \mathrm{Diff}_0\bigl(B_r(0),\mathrm{d}u,0\bigr)$ denote the group of diffeomorphisms $\phi:B_r(0)\to B_r(0)$ that satisfy $\phi(0)=0$, $\phi^*(\mathrm{d}u) = \mathrm{d}u$, and for which there exists a compact set $K_\phi\subset B_r(0)$ such that $\phi$ is the identity outside the compact set $K_\phi$. Clearly, it will be enough to show that the homomorphism $D:G_0\to \mathrm{SL}\bigl(T_0B_r(0)\bigr) = \mathrm{SL}(\mathbb{R}^n)$ is surjective.
To do this, consider the subset $C\subset \mathrm{Hom}_0(\mathbb{R}^n,\mathbb{R}^n)={\frak{sl}}(n,\mathbb{R})$ consisting of the operators that are skew-symmetric with respect to some positive definite inner product on $\mathbb{R}^n$. Let $L\in C$ be such an operator, and let $\langle,\rangle$ on $\mathbb{R}^n$ be a positive definite inner product with respect to which $L$ is skew-symmetric. In particular, the $1$-parameter subgroup $\mathrm{e}^{tL}$ preserves $\langle,\rangle$ and hence the volume form $\mathrm{d}u$. Now, let $\epsilon>0$ be so small that the set of vectors $y\in\mathbb{R}^n$ that satisfy $\langle y,y\rangle \le \epsilon$ is a compact subset of $B_r(0)$. Let $h:\mathbb{R}\to\mathbb{R}$ be a smooth function that is identically $1$ when $0\le t \le \epsilon/2$ and vanishes identically for $t\ge\epsilon$. Now consider the $1$-parameter family of smooth maps
$$
f_t(y) = \mathrm{e}^{t\ h(\langle y,y\rangle) L}\ y.
$$
This family preserves the level sets of $Q(y) = \langle y,y\rangle$, which are spheres, and isometrically rotates each one, so it preserves the volume form $\mathrm{d}u$. It clearly lies in $G_0$. When $Q(y)\ge\epsilon$, $f_t(y) = y$, and, when $Q(y)\le \epsilon/2$, one has $f_t(y) = \mathrm{e}^{tL}y$. Note that $f_t$ lies in $G_0$. Since
$$
D(f_t) = \mathrm{e}^{tL},
$$
it follows that the image of $D$ contains the subset $\mathrm{e}^{C}\subset \mathrm{SL}(n,\mathbb{R})$. In particular, the image of $D$, which is a subgroup of $\mathrm{SL}(n,\mathbb{R})$, contains all of the compact subgroups of $\mathrm{SL}(n,\mathbb{R})$. Thus, it follows that the image of $D$ is all of $\mathrm{SL}(n,\mathbb{R})$, which is what needed to be proved.
| {
"pile_set_name": "StackExchange"
} |
Q:
Conditionally use a custom UITableViewCell class or a regular UITableViewCell?
I have subclassed UITableViewCell so that I can customize some of its layout. I didn't create a XIB for it. I have been using custom class by simply defining each static cell's class in Interface Builder. Because they're static cells I didn't need to implement cellForRowAtIndexPath.
But now I would like to use that custom cell class only if a certain condition is true, otherwise I want that cell's class to be the default UITableViewCell class.
I have reverted the static cell's classes to remove the custom class in Interface Builder. So now I need some way to change each cell's class in code. I believe this will need to be done in cellForRowAtIndexPath but I don't know how to dynamically create a custom cell class and use that cell, otherwise use the default.
A:
You can use two different reuse identifiers for cells of different type. Set up your condition like this:
UITableViewCell *cell;
if (needCustomCell) {
cell = [tableView dequeueReusableCellWithIdentifier:@"CustomIdentifier"];
if (!cell) {
cell = [[MyCustomTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"CustomIdentifier"];
}
... // Do configuration specific to your custom cell
} else {
cell = [tableView dequeueReusableCellWithIdentifier:@"PlainIdentifier"];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"PlainIdentifier"];
}
... // Do configuration specific to your regular cell
}
... // Do configuration common to both kinds of cell
return cell;
| {
"pile_set_name": "StackExchange"
} |
Q:
Confused at regular expressions-Python
import re
caps = "bottle caps/ soda caps/ pop caps"
regex = re.findall(r"\w[1-6]", caps)
print(regex)
output is:
[]
however if I do this
import re
caps = "bottle caps/ soda caps/ pop caps"
regex = re.findall(r"\w[1-6]*", caps)
ouput is:
['b', 'o', 't', 't', 'l', 'e', 'c', 'a', 'p', 's', 's', 'o', 'd', 'a', 'c', 'a', 'p', 's', 'p', 'o', 'p', 'c', 'a', 'p', 's']
how do I make it output:
["bottle caps", "soda caps, "pop caps"]
I know you guys would recommend using the .split but I wanna understand regular expressions more
I've tried this as well:
import re
caps = "bottle caps/ soda caps/ pop caps"
regex = re.findall(r"\w[1-6]?\s*\w[1-3]*", caps)
print(regex)
output:
['bo', 'tt', 'le', 'ca', 'ps', 'so', 'da', 'ca', 'ps', 'po', 'p c', 'ap']
whats happening?
A:
You appear to be confusing {1,6}, which means "the previous pattern repeated 1 to 6 times", with [1-6], which means "any of the characters in the range 1 to 6".
So, what you have:
\w[1-6]
Debuggex Demo
… will match a word character, followed by a digit from 1-6.
Putting the * on the end just means 0 or more of that digit pattern, which means any word character followed by zero or more digits from 1-6.
But if you use the right syntax, you get what you want:
\w{1,6}
Debuggex Demo
| {
"pile_set_name": "StackExchange"
} |
Q:
Some line beginnings are a different color in Aptana
I've spent like an hour tying to find a way to fix this, but I just can't do it. Some lines/characters will show up a different color in Aptana (all semicolons, some tabs, and some whole). I just installed it today, so I don't know my way around the software very well.
Here's a picture to help you get the idea:
I would like get rid of the way some sections are lighter (the line saying some text is the line the caret's on, which is not the problem)
P.S. If this is the wrong place to ask this, I'm sorry, but I'm getting frustrated searching through Google and the Aptana preferences.
A:
I too spent way too much time on this issue.
The answer by phazei is correct:
Aptana 3, php code background highlighting
But my main problem was I didn't know where to look. So to give some insight into how I found the answer:
It turns out you can see what markup the editor is using and how it classifies any block of text, by just right-clicking on the text you are interested in and pick Show in -> Properties.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to distinguish Korean "ㅔ" /e/ and "ㅐ" /ɛ/?
I've always had trouble with the distinction between the "e"-like vowels in European languages: /e/ vs /ɛ/. But pronouncing them the same has never caused me any problems.
In fact I don't even know whether my English "short e" is /e/ vs /ɛ/. I seem to recall it varies by English variety, even for IPA use (I always use /e/ for English IPA). In my idiolect there may even be some kind of merger. "Head" is /hEd/ and "haired" is /hEːd/ where E could be either e or ɛ - I'm not sure.
So now I'm in Korea trying to improve my Korean. Up until now I had always pronounced "ㅐ" as /æ/ and "ㅔ" as whatever my English "short e" is.
But lately people have been correcting me and telling me "ㅐ" should be what to me sounds like "short e".
Having done some reading I find Korean doesn't have /æ/ as I'd thought, but has two contrasting vowels that would both fall into the "short e" category for my idiolect:
"ㅐ" is /ɛ/ and "ㅔ" is /e/.
How can I learn to distinguish these sounds correctly, both for listening and speaking?
If I learn it for Korean it will also help for my linguistics generally.
Are there some minimal pairs in Korean I can practice with with my native Korean speaking friends here? (It's not easy trying to explain to non-linguists with imperfect English what minimal pairs are.)
A:
There's a book called The Sounds of Korean [1] with an accompanying CD which is invaluable for getting the phonetic distinctions right.
Mechanical snail is right in that the distinction is being lost, particular among the young. However, in speakers who maintain the distinction, it sounds like a lowered [e]. I had a little look on Forvo for examples of speakers who maintain the distinction, but all the ones I checked were from people who merged the distinction.
As for basic minimal pairs, explain to your friends that you're interested in the difference between 새 (new) and 세 (combining form of 셋), and they should be able to come up with more.
EDIT: I have a few more minimal pairs for you.
게 crab vs 개 dog
세 집 three houses vs 새 집 new house
The book also observes that while the distinction is not reliably made by many speakers', there is consistency when transcribing English words: English [æ] is reliably mapped to ㅐ while [eI] and [E] are mapped to ㅔ.
[1] Choo and O'Grady. The Sounds of Korean. University of Hawaii Press.
A:
Here are the minimal pairs of more than one syllable that I could find in the English Wiktionary using a custom application I wrote in JavaScript:
모레 (more)
the day after tomorrow
모래 (morae)
sand
새로 (saero)
anew, newly, for the first time
세로 (sero)
height, length, vertical
I also found twenty minimal pairs of just a single syllable that I'll include if requested.
I tried the "crab v dog" test mentioned by jogloran with some Koreans here in Seoul.
Two guys in their 20s who I think are from Seoul both insisted they sound the same.
Another friend who is about 40 and not from Seoul insisted they sound different. He pronounced "crab" with a short sound like in English "bet" and "dog" with a long sound like in non-rhotic English "bear".
Apparently both the vowel length distinction and the ㅔ vㅐ distinction are in the process of disappearing and it's happening in Seoul before elsewhere. This is pretty much just what Wikipedia says.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to deserialize an array containig strings and objects in JSON.NET
I am trying to deserialize a special array to an object in Visual Basic.
The following json data is delivered by the webservice I use; the part interesting to me is the "data" property; basically it is an array of string arrays, with each array representing an object:
{"timestamp":1385984969075,
"data":
[
[1590,null,null,null,0],
[1020,"data a",null,null,0],
[1025,"data b",null,null,0],
...
[2756,"data c",null,
[
{"id":2,"name":"Tom","mail":"[email protected]","f_id":6,"md":1},
{"id":3,"name":"Carl","mail":"[email protected]","f_id":6,"md":1}
]
,3],
[1277,"data d",null,null,0],
...
]}
In this example, data item 4 of each array may be either null or contain an array of objects.
I would like to deserialize the array into a list of objects, but I can't get it to work. I have searched through a lot of similar posts, but I could not find anything helpful so far.
(I am writing in Visual Basic.net , but C# examples are welcome.)
Can someone help please?
A:
Updated:
Here is another example that uses object arrays to map that the array of arrays you have. I have then extracted each piece of data within the arrays.
Again hopefully this will help you:
var list = new People
{
PersonList = new object[]
{
new object[]
{
"Test1", "Test2", "Test3", null, new object[]{new Person{Name="John", Age=21}}, 1
},
new object[]
{
"Test4", "Test5", "Test6", null, null, 2
},
new object[]
{
"Test17", "Test8", "Test9", null, new object[]{new Person{Name="Sara", Age=31}}, 3
},
new object[]
{
"Test10", "Test11", "Test12", null, null, 4
},
new object[]
{
"Test13", "Test14", "Test15", null, new object[]{new Person{Name="John", Age=31}}, 5
}
}
};
string output = JsonConvert.SerializeObject(list);
var objList = JsonConvert.DeserializeObject<People>(output);
objectList = objList.PersonList;
foreach(JArray objectItem in objectList)
{
var stringOne = (string)objectItem[0];
var stringTwo = (string)objectItem[1];
var stringthree = (string)objectItem[2];
var nullObj = objectItem[3];
foreach(var individual in objectItem[4])
{
JObject obj = (JObject)JToken.FromObject(individual);
var person = obj.ToObject<Person>();
string name = person.Name;
int age = person.Age;
}
var num = (int)objectItem[5];
}
JSON:
{
"PersonList": [
[
"Test1",
"Test2",
"Test3",
null,
[
{
"Name": "John",
"Age": 21
},
{
"Name": "Pete",
"Age": 44
}
],
1
],
[
"Test4",
"Test5",
"Test6",
null,
null,
2
],
[
"Test17",
"Test8",
"Test9",
null,
[
{
"Name": "Sara",
"Age": 31
}
],
3
],
[
"Test10",
"Test11",
"Test12",
null,
null,
4
],
[
"Test13",
"Test14",
"Test15",
null,
[
{
"Name": "John",
"Age": 31
}
],
5
]
]
}
Person Class:
public class Person
{
public string Name { set; get; }
public int Age { set; get; }
}
PeopleList class:
public class People
{
public object[] PersonList { set; get; }
}
| {
"pile_set_name": "StackExchange"
} |
Q:
JSP get the value of input tag inside dynamically generated rows of a table
I am trying to get the value of the input tag which has the id b_quantity field but I am getting only the first row b_quantity value when the data is generated in the table. Every row has a different record and a button when the button has clicked the value of b_quantity inside this row should be targeted and not the first row the same goes for all other rows. If there is any JQuery or JS code I am willing to add it to my JSP page.
Expected Output:
When clicking the Order button the value of b_quantity in the same row should be sent to the servlet post method.
Observed Output:
When clicking the Order button the value of b_quantity in the first row is sent to the servlet post method.
<tbody>
<%
List<Beverage> beverages = (List<Beverage>) request.getAttribute("beverageList");
for(Beverage b: beverages) {
%>
<tr>
<td class="pt-3-half"><%= b.getName() %></td>
<td class="pt-3-half"><%= b.getManufacturer() %></td>
<td class="pt-3-half"><%= b.getQuantity() %></td>
<td class="pt-3-half"><%= b.getPrice() %></td>
<% if (b.getIncentiveDTO() != null){ %>
<td class="pt-3-half"><%= b.getIncentiveDTO().getName() %> </td>
<%}else { %>
<td></td>
<%}%>
<td>
<input id="b_quantity" type="number" class="b_quantity" min="0" max="<%=b.getQuantity()%>" value="0">
</td>
<td>
<input type="hidden" name="b_id" value="<%= b.getId() %>">
<!-- <input id="q_val" type="hidden" type="number" name="q_val" value="0"> -->
<a id="<%= b.getId() %>" href="" type="button" class="order btn btn-primary btn-lg">Order</a>
</td>
</tr>
<% } %>
</tbody>
I am using AJAX to invoke the Servlet doPost method.
<script type="text/javascript">
$(document).ready(function() {
$(".order").click(function() {
event.preventDefault();
$.ajax({
url: '/frontend/new?b_id=' + event.target.id ,
type: 'Post',
data: {
b_quantity: $('#b_quantity').val()
},
success: function(response) {
location.href = "/frontend/beverages";
}
});
});
});
</script>
A:
The ID b_quantity is not unique because you are generating rows in a table, each each row contains an input with the id b_quantity. Since the input also has the class 'b_quantity', you can use that to find the input. Try this in your click handler:
<script type="text/javascript">
$(document).ready(function() {
$(".order").click(function() {
event.preventDefault();
var myRow = $(this).parents('tr');
var quantity = $('.b_quantity',myRow).val();
$.ajax({
url: '/frontend/new?b_id=' + event.target.id ,
type: 'Post',
data: {
b_quantity: quantity
},
success: function(response) {
location.href = "/frontend/beverages";
}
});
});
});
</script>
| {
"pile_set_name": "StackExchange"
} |
Q:
wpf Databinding using XAML not working
I am developing a small application for learning purpose. I find that when I bind ItemControl's ItemSource to a ViewModel property in XAML, it doesn't work in an expected way. i.e. It loads the underlying collection with values at the loading time, but any changes to it are not reflected.
However, if I set Itemsource in Codebehind, it works.
When the form is loaded, it shows 2 note objects. Clicking on button should show the 3rd one. I don't understand why setting DataContext using XAML doesn't update to changes in collection. I am sharing snippet of the code here. Any help greatly appreciated.
Cut-down version of XAML -
<Window x:Class="NotesApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:NotesApp"
xmlns:vm="clr-namespace:NotesApp.ViewModel"
Title="MainWindow" Height="480" Width="640">
<Window.DataContext >
<vm:MainViewModel/>
</Window.DataContext>
<DockPanel >
<ScrollViewer VerticalScrollBarVisibility="Auto">
<ItemsControl Name="NoteItemControl" ItemsSource="{Binding notes}" Background="Beige" >
<ItemsControl.LayoutTransform>
<ScaleTransform ScaleX="{Binding Value, ElementName=zoomSlider}" ScaleY="{Binding Value, ElementName=zoomSlider}" />
</ItemsControl.LayoutTransform>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Name="NoteBorder" Background="Green" CornerRadius="3" Margin="5,3,5,3">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock Text="{Binding noteText}" Margin="5,3,5,3"/>
<StackPanel Grid.Row="1" Orientation="Vertical" >
<Line X1="0" Y1="0" X2="{Binding ActualWidth,ElementName=NoteBorder}" Y2="0" Stroke="Black" StrokeThickness="1"/>
<TextBlock Text="{Binding Category}" Margin="5,3,5,3"/>
</StackPanel>
</Grid>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</DockPanel>
</Window>
View Code behind-
namespace NotesApp
{
public partial class MainWindow : Window
{
MainViewModel ViewModel { get; set; }
public MainWindow()
{
InitializeComponent();
ViewModel = new MainViewModel();
// IT WORKS IF I BRING IN THIS STATEMENT
//NoteItemControl.ItemsSource = ViewModel.notes;
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
ViewModel.AddNote(new Note("note3", "Category 3"));
}
}
}
ViewModel -
namespace NotesApp.ViewModel
{
public class MainViewModel: INotifyPropertyChanged
{
ObservableCollection<Note> _notes;
public ObservableCollection<Note> notes
{
get
{ return _notes; }
set
{
_notes = value;
OnPropertyChanged("notes");
}
}
public void AddNote(Note note)
{
_notes.Add(note);
OnPropertyChanged("notes");
}
public MainViewModel ()
{
notes = new ObservableCollection<Note>();
notes.Add(new Note("note1", "Category 1"));
notes.Add(new Note("note2", "Category 2"));
}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
protected virtual void OnPropertyChanged(string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs( propertyName));
}
}
}
A:
You create a MainViewModel instance and assign it to the MainWindow's DataContext in XAML
<Window.DataContext >
<vm:MainViewModel/>
</Window.DataContext>
The bindings in your XAML use this instance as their source object, as long as you do not explicitly specify some other source. So there is no need (and it's an error) to create another instance in code behind.
Change the MainWindow's constructor like this:
public MainWindow()
{
InitializeComponent();
ViewModel = (MainViewModel)DataContext;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
HTTrack Empty Mirror Error
I'm trying to download the following site: http://www.interneto-parduotuve.lt/
However, no matter what I try to do (get rid of the www, try other options than the "download website" one, etc) I keep getting a "HTTrack has detected that the current mirror is empty." error. Does anyone know how to resolve this?
A:
I was apparently using an older version of Mozilla as the browser within HTTrack. I changed the version to 4.0 and it worked fine.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to create an arrayList using Costum objects on C#
I want to add objects on a dynamic list for use it after on other cases, I'm new on C# .net and I tried this piece of code:
class DashboardClass
{
private int prix;
private string name;
private int quantity;
public void SetInfo(string name, int prix, int quantity)
{
this.prix = prix;
this.quantity = quantity;
this.name = name;
}
public int getprix()
{
return prix;
}
public string getname()
{
return name;
}
public int getquantity()
{
return quantity;
}
}
and on my main form :
DashboardClass Object = new DashboardClass();
List<object> ProductList = new List<object>();
DashboardClass item = Object.SetInfo("ala", 152, 1);
ProductList.Add(item);
please how to modify my code for making a list of Productlist.
A:
Make your setinfo to constructor.
class DashboardClass
{
private int prix;
private string name;
private int quantity;
public DashboardClass(string name, int prix, int quantity)
{
this.prix = prix;
this.quantity = quantity;
this.name = name;
}
public int getprix()
{
return prix;
}
public string getname()
{
return name;
}
public int getquantity()
{
return quantity;
}
}
This way you can use object to access prix,name and quantity through get methods.
List<DashboardClass> cls = new List<DashboardClass>();
cls.Add(new DashboardClass("example", 1, 1));
Console.WriteLine(cls[0].getprix());
Console.Read();
cls[0] here is accessing the first object in the generic list.
When you have more objects in the list just iterate using foreach loop
| {
"pile_set_name": "StackExchange"
} |
Q:
How to insert a GeoJSON polygon into a PostGIS table?
I need to insert a polygon from GeoJSON to my PostGIS table. This is how the SQL query looks like.
INSERT INTO tablename (name, polygon)
VALUES (
'Name',
ST_GeomFromGeoJSON(
'{
"type": "Polygon",
"coordinates": [
[7.734375,51.835777520452],
[3.8671875,48.341646172375],
[7.20703125,43.580390855608],
[18.6328125,43.834526782237],
[17.9296875,50.289339253292],
[13.7109375,54.059387886624],
[7.734375,51.835777520452]
]
}'
)
)
Unfortunately, I get an error message.
ERROR: Geometry SRID (0) does not match column SRID (3857)
The GeoJSON is already in the right reference system. But this isn't specified. How do I specify the SRID in the GeoJSON? What does the GeoJSON need to look like?
Update: When I wrap the geometry created by ST_GeomFromGeoJSON with ST_SetSRID(..., 3857) it throws another error. In my view it doesn't seem that the geometry has a Z dimension.
ERROR: Geometry has Z dimension but column does not
A:
Taking a look at the source code of PostGIS I found out how it parses SRIDs. Here is the correct way to specify the SRID in GeoJSON.
The GeoJSON specification says that the coordinates of a polygon are an array of line strings. Therefore I had to wrap them with additional brackets.
{
"type":"Polygon",
"coordinates":
[
[
[-91.23046875,45.460130637921],
[-79.8046875,49.837982453085],
[-69.08203125,43.452918893555],
[-88.2421875,32.694865977875],
[-91.23046875,45.460130637921]
]
],
"crs":{"type":"name","properties":{"name":"EPSG:3857"}}
}
A:
There are a couple of problems with your JSON.
Firstly, the coordinates should be an array of arrays.
Secondly, looking at the coordinates, it looks like the values are Latlong in a Geographic coordinate system, most probably EPSG:4326. That then needs to be transformed to EPSG:3857.
Once you correct these two things, you can insert the row, using the following SQL Query:
INSERT INTO "Parcels"("Name", the_geom)
VALUES ('Corrected_Shape',
ST_TRANSFORM(ST_GeomFromGeoJSON('{
"type":"Polygon",
"coordinates":[[
[-91.23046875,45.460130637921],
[-79.8046875,49.837982453085],
[-69.08203125,43.452918893555],
[-88.2421875,32.694865977875],
[-91.23046875,45.460130637921]
]],
"crs":{"type":"name","properties":{"name":"EPSG:4326"}}
}'),3857));
If this does not work, (i.e. you are still getting the error with Z diemsnion), please update the question with the PostGis version, and the Create Statement of your table.
A:
your geojson must have UTM values instead, you could transform that with Proj or other online tools, but you can do it easily and directly with postgis before inserting it into your table, try this (untested):
SELECT ST_AsText(ST_Transform(ST_GeomFromGeoJSON
(
{
"type":"Polygon",
"coordinates":[
[7.734375,51.835777520452],
[3.8671875,48.341646172375],
[7.20703125,43.580390855608],
[18.6328125,43.834526782237],
[17.9296875,50.289339253292],
[13.7109375,54.059387886624],
[7.734375,51.835777520452]
]
}
),4326),3857));
| {
"pile_set_name": "StackExchange"
} |
Q:
Monit to watch over God?
We're using God to monitor our server processes, and were wondering if we should use something like Monit to make sure God gets up if something unexpected happens.
A quis custodiet ipsos custodes? conundrum :)
Googling for it didn't bring any mentions of this being done, which makes me think it's probably pretty rare.
Has anybody here seen a need for it?
A:
I would put the responsibility of keeping god running on something more core to the OS. On Ubuntu maybe you could use upstart to launch and monitor god. I haven't done this myself however.
The only other benefit of using monit for this seems to be that it might be possible to monitor god's memory usage, which in the past has had some leaks.
| {
"pile_set_name": "StackExchange"
} |
Q:
JSS Rendering DataSource item Workflow States
In JSS datasource items, we can see "JSS Development Workflow" added.
In that workflow, there are "Development Mode", "Content Mode" and "Published" states.
In which state of the JSS development lifecycle these different stages are assigned/changed ?
A:
You can find information on the workflow states in the JSS docs: https://jss.sitecore.com/docs/fundamentals/dev-workflows/code-first#content-workflow-and-developer-overwrite
The JSS import process is designed to gracefully skip items to which the configured import user does not have write permission. This allows you to utilize Sitecore Security to prevent the import from overwriting content which should no longer be "developer-owned."
To further facilitate this, JSS includes a content workflow which is automatically applied to all generated templates. This workflow defines Development Mode and Content Mode states to designate the current "owership" of a content item.
Development Mode - Import can overwrite field values and route item layout.
Content Mode - Import user is denied item write access. Import will skip writes on the item. For route items, this means that any rendering changes or updates to datasource items are also skipped.
| {
"pile_set_name": "StackExchange"
} |
Q:
I am a former model
A long time ago, I used to be a model,
Even though I was a bit thick boned,
I'd dress in casual clothes like everyone else,
I could have been a thousand different things, I was way ahead of my time,
It pains me to think I should have been a singer instead,
Nowadays, I'm not as mobile as I used to be,
People treat me like I'm a dinosaur,
And my bills are really adding up,
I'm not fooling myself, I don't want your pity,
At least my immune system hasn't failed me yet,
Who / what am I?
A:
You could be
the letter T
A long time ago, I used to be a model,
Ford Model T
Even though I was a bit thick boned,
T-bone steak
I'd dress in casual clothes like everyone else,
T-shirt
I could have been a thousand different things, I was way ahead of my time,
T-1000, from the Terminator series (from OP)
It pains me to think I should have been a singer instead,
T-Pain
Nowadays, I'm not as mobile as I used to be,
T-Mobile
People treat me like I'm a dinosaur,
T-Rex
And my bills are really adding up,
T-bill i.e. Treasury bill
I'm not fooling myself, I don't want your pity,
Mr. T’s “I pity the fool” (from OP)
At least my immune system hasn't failed me yet,
T cell
| {
"pile_set_name": "StackExchange"
} |
Q:
Only finitely many primes dividing the values of an integer polynomial
For a given $P\in \mathbb{Z}[x]$ call a positive prime $p$ good if there exists $n\in \mathbb{Z}$ such that $p$ divides $P(n)$. Does there exist a non-constant $P$ such that the set of good primes is finite?
A:
The answer is no. Given any finite set of primes $S$, the number of positive integers up to $x$ divisible only by primes in $S$ grows like a constant times $(\log x)^{\#S}$. Since the number of values, up to $x$, of a degree-$d$ polynomial grows like a constant times $x^{1/d}$, those values must inevitably include integers with prime factors outside of $S$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Bundle install/update not working
Taking a rails tutorial, and I've run into the following problem that I'm having trouble figuring out. I'm creating a sample app that's supposed to use the following gemfile:
source 'https://rubygems.org'
gem 'rails', '3.2.5'
group :development, :test do
gem 'sqlite3', '1.3.5'
gem 'rspec-rails', '2.10.0'
end
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'sass-rails', '~> 3.2.4'
gem 'coffee-rails', '~> 3.2.2'
gem 'uglifier', '1.2.3'
end
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', :platform => :ruby
gem 'jquery-rails', '2.0.0'
group :test do
gem 'capybara', '1.1.2'
end
group :production do
gem 'pg', '0.12.2'
end
When I tried to "bundle install --without production" per instructions, though, I get this
Bundler could not find compatible versions for gem "activesupport":
In snapshot (Gemfile.lock):
activesupport (3.2.3)
In Gemfile:
rails (= 3.2.5) ruby depends on
activesupport (= 3.2.5) ruby
Running bundle update will rebuild your snapshot from scratch, using only
the gems in your Gemfile, which may resolve the conflict.
So I tried updating, but I was told that:
Bundler could not find compatible versions for gem "railties":
In Gemfile:
rails (= 3.2.5) ruby depends on
railties (= 3.2.5) ruby
jquery-rails (= 2.0.0) ruby depends on
railties (3.2.6)
So I tried to update my gems via rvm, figuring that was the problem. (Did "rvm rubygems current"). But that didn't seem to fix anything.
Help? Thanks!
A:
Try changing this line:
gem 'rails', '3.2.5'
to
gem 'rails', '3.2.6'
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL Server 2005 IsNumeric Not catching '0310D45'
I've got this value '0310D45'
I'm using isnumeric to check if values are numeric prior to casting to a bigint. Unfortunately this value is passing the isnumeric check. So my query is failing saying:
Msg 8114, Level 16, State 5, Line 3
Error converting data type varchar to bigint.
What is the simplest way to handle this. I was thinking of using charindex but I would have to check all 26 letters.
Is there a simple solution that I'm not seeing? I really don't want to create a user defined function.
Thanks
A:
Take a look at this article named What is wrong with IsNumeric()? which contains the following abstract:
Abstract: T-SQL's ISNUMERIC() function has a problem. It can falsely interpret
non-numeric letters and symbols (such as D, E, and £), and even tabs
(CHAR(9)) as numeric.
Unfortunately it looks like IsNumeric is just plain weird and you will have to write a few lines of T-SQL to get around it. (By weird I mean that IF the data evaluated can be converted into ANY numeric type at all, the it will get converted.)
A:
I recently faced this problem, and was looking for solution. I think I found two, and wanted to post them here so that its easier for others to find.
First solution is to use regular expression and SQLServer function PATINDEX()
IF PATINDEX('%[^0-9]%', @testString) = 0
Second solution is to concatenate a string 'e0' to your test string and still use SQLServer function ISNUMERIC() with the concatenated string. ISNUMERIC fails to detect presence of characters such as d, e, x because of different notations used in the numeric formats, but it still allows only a single character. Thus concatenating 'e0' prevents the function from giving you a false true, when ever required.
IF (ISNUMERIC (@testString + 'e0') = 1)
Hope this helps
| {
"pile_set_name": "StackExchange"
} |
Q:
How do i capture a variable from a text file with a batch script?
Hi I'm trying to write a batch script that reads a long text file, finds a line that says:
Location: xxxxxxxx
And saves xxxxxxxx (only) as a variable that i can use later in the script.
xxxxxxxx is an ID and there is nothing else on that line.
Can someone help?
A:
This works, too.
for /f "tokens=2" %a in ('type longtextfile.txt ^|findstr /b "Location"') do set location=%a
echo %location%
EDIT: Adding Aacini's more efficient way of doing this:
for /f "tokens=2" %a in ('findstr /b "Location" longtextfile.txt') do set location=%a
echo %location%
| {
"pile_set_name": "StackExchange"
} |
Q:
AFNetworking (AFHttpClient) offline mode not working with NSURLRequestReturnCacheDataDontLoad policy
I am using AFNetworking in my app and try to make it work in the offline mode by use the cached data if available.
I expected after I set the request cache policy to NSURLRequestReturnCacheDataDontLoad, getPath:parameters:success:failure: will success with the cached data while offline. However, even if there are data in the cache (I verified by check the cache with the code), getPath will simply fail in airplane mode.
There was a thread in AFNetworking github: https://github.com/AFNetworking/AFNetworking/issues/378 But seemed the issue is not addressed at all. The author of AFNetworking simply point to Apple's document, and it said:
NSURLRequestReturnCacheDataDontLoad
Specifies that the existing cache
data should be used to satisfy a request, regardless of its age or
expiration date. If there is no existing data in the cache
corresponding to a URL load request, no attempt is made to load the
data from the originating source, and the load is considered to have
failed. This constant specifies a behavior that is similar to an
“offline” mode.
As Apple said, NSURLRequestReturnCacheDataDontLoad is exactly designed for offline mode.
I am testing in iOS6, I tested with both NSURLCache and SDURLCache, all have the same result.
The request failed, the error message:
2012-12-22 03:11:18.988 Testapp[43692:907] error: Error
Domain=NSURLErrorDomain Code=-1009 "The Internet connection appears to
be offline." UserInfo=0x211b87c0
{NSErrorFailingURLStringKey=http://Testapp.com/api/v1/photo/latest/,
NSErrorFailingURLKey=http://Testapp.com/api/v1/photo/latest/,
NSLocalizedDescription=The Internet connection appears to be offline.,
NSUnderlyingError=0x211b9720 "The Internet connection appears to be
offline."}
A:
Turned out, it's a bug in iOS 6.
There is a discussion thread in AFNetworking exactly for this problem: https://github.com/AFNetworking/AFNetworking/issues/566
Thanks for guykogus' tips and experiments on this issue. I spent a night on this issue!
A summarized work around is read the response from cache, instead of use NSURLRequestReturnCacheDataDontLoad policy:
NSCachedURLResponse *cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request];
if (cachedResponse != nil &&
[[cachedResponse data] length] > 0)
{
// Get cached data
....
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Is the orientation of an expansion tank with respect to the pipe important?
Does it matter whether a thermal expansion tank (for water heaters) is installed above the pipe it tees from (tank's threaded port pointing downwards) or if it's installed below so that it hangs from it (tank's threaded port pointing upwards)?
A:
In general, the tank can be installed vertically above or below the plumbing, or horizontally. Typically, the tank is only required to be supported when installed in the horizontal position. Most smaller tanks are designed to be supported by the plumbing, when installed in the vertical orientation. The most common recommendation seems to be, to install the tank vertically below the plumbing.
You'll want to check the manufacturer's installation instructions, to determine how to properly install the specific tank you're using.
Here's example installation instructions, from a Watts® Potable Hot Water Expansion Tank.
5. Install the expansion tank in the system (refer to Figure 1).
a. The weight of the expansion tank filled with water is supported by
the system piping. Therefore, it is important that, where appropriate,
the piping has suitable bracing (strapping, hanger, brackets).
b. The expansion tank may be installed vertically (preferred method)
or horizontally. Caution: The tank must be properly supported
in horizontal applications.
c. This expansion tank, as all expansion tanks, may eventually leak.
Do not install without adequate drainage provisions.
| {
"pile_set_name": "StackExchange"
} |
Q:
Strange, garbled formatting on question #154133 'Boot from ISO'
I just encountered the answer to this question and curiously enough my browser, for the first time, shows comments entangled with the bottom of the response paragraphs, like this:
I even can't access any of the edit, share (...) buttons. Is there something that can be done?
FYI my browser is Seamonkey 2.49.5.2 on (Gentoo) Linux and it's the only browser I have on my system so I can't really check anything right now (I'd need another hour or two to compile and check Firefox).
Note: I've just emptied my browser's cache, no change.
A:
My browser shows comments entangled with the bottom of the answer
my browser is Seamonkey 2.49.5.2 on (Gentoo) Linux
Unfortunately you are using an unsupported browser:
We support the last two versions of the browsers that we see the vast
majority of our visitors actually use. This does not include beta/dev
releases, which are not supported.
The supported browsers, in practice, based on the above guideline:
Standard View
Internet Explorer (current version status from Wikipedia)
Compatibility mode should be disabled
Exception: Internet Explorer on Mac OS X
Firefox (current version status from Wikipedia)
Chrome (current version status from Wikipedia)
Opera (current version status from Wikipedia)
Safari (current version status from Wikipedia)
Edge (current version status from Wikipedia)
Mobile View
Android browser
Supported: 4.0 and up (source)
Mobile Safari (iPhone browser)
Supported: the versions that come with iOS 9 and up.
| {
"pile_set_name": "StackExchange"
} |
Q:
node.js generic function execution using function.prototype.apply
I have a bunch of action methods such as:
function doA(x, y, callback){
.. some additional logic here ...
do_something_async(x, y, function(result) {
callback(result);
});
}
function doB(x, y, z, callback){
.. some additional logic here ...
do_something_async2(x, y, z, function(result) {
callback(result);
});
}
And I'd like to create a generic execution function such as:
function doCommand(fn) {
// Execute the fn function here with the arguments
// Do something with the result to the callback from the action function
// (which may require running the action function again...)
}
The function doCommand will receive as a first argument the name of the action command and the rest of the arguments will be as required by the action command. In other words:
doCommand(doA, 5, 10, cbfn); will call doA with the relevant arguments. And doCommand(doB, 1, 2, 3, cbfn) will call doB with the relevant arguments.
So far, my doCommand function looks like this:
function doCommand(fn) {
fn.apply(null, arguments);
}
However, I have no idea how to capture inside doCommand the value of result after the async function execution because based on this value I may need to do something in addition, for example, run the action function again.
Plus, this will require a change the signature of every action command to disregard the first null argument created by the apply function.
I'm pretty sure there is a smarter way to do this. Would appreciate your help in finding out how.
Thanks!
EDIT:
A typical action function would look like this:
function doA(arg1, arg2, cb) {
... some logic using arguments ...
asyncmodule.once('event', function(event) {
... do something ...
callback(event.result);
});
asyncmodule.send('A command', [list of specific arguments]);
}
The caller to the action function needs to do something with the result, however for specified failure results, there needs to be either a repeat or changing of arguments and retry.
A:
There's a pretty strong convention of the callback being the final argument to a function, so I'll assume you're using that. We'll start by fixing up the arguments and injecting our own callback, and then we can call the function and be on our way.
function doCommand(fn) {
var args = Array.prototype.slice.call(arguments); // We want a real array
args = args.slice(1); // Otherwise it contains fn, which isn't right
var finalCallback = args[args.length - 1]; // We'll need this at the end
args = args.slice(0, -1); // But we don't need it now
fn.apply(null, args.concat( function() { // This looks weird, but it allows us
// to keep the callback inline with
// the function call
// Here you can operate on the results
}));
}
Note that concat is non-destructive, so you can call fn like that as many times as you like with different callbacks. Don't forget to eventually call finalCallback!
As Bergi points out, you can combine all of the slices - I just pulled them apart so I could comment them better:
var args = Array.prototype.slice.call(arguments, 1, -1)
And you'd have to pull the finalCallback out of arguments instead of args, of course.
| {
"pile_set_name": "StackExchange"
} |
Q:
Uploading UImage to facebook
My following code for posting the UIImage to user's facebook wall is not working .I've looked into the sample code that comes along with the facebook sdk and its working fine. I am unable to find whats going wrong with my code.
-(void) shareOnFacebook
{
facebook = [[Facebook alloc] initWithAppId:@"MYAPPID" andDelegate:(id)self];
NSArray * neededPermissions = [[NSArray alloc] initWithObjects:@"offline_access",@"user_about_me", @"publish_stream", @"user_photos", nil] ;
[facebook authorize:neededPermissions ];
if (![facebook isSessionValid])
{
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
img, @"picture",
nil];
[facebook requestWithGraphPath:@"me/photos"
andParams:params
andHttpMethod:@"POST"
andDelegate:(id)self];
}
}
please tell me that what can be the problems?
thanks in advance..
A:
you need to call the upload function after the delegate method - (void)fbDidLogin is being called .. try to do it like this and it should work
- (void)fbDidLogin {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[fb accessToken] forKey:@"FBAccessTokenKey"];
[defaults setObject:[fb expirationDate] forKey:@"FBExpirationDateKey"];
[defaults synchronize];
[self uploadImageWithName:yourImageName];
}
- (void) uploadImageWithName : (NSString*)name
{
NSString *img = [NSString stringWithFormat:@"%@.PNG",name];
UIImage *uploadImage = [UIImage imageNamed:img];
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
[fb accessToken],
@"access_token",nil];
[params setObject:uploadImage forKey:@"source"];
[fb requestWithGraphPath:@"me/photos"
andParams: params
andHttpMethod: @"POST"
andDelegate:self];
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Shisha Vachamishim Umeya - mi yodeya?
Who knows one hundred fifty-six?
Please cite/link your sources, if possible. At some point at least twenty-four hours from now, I will:
Upvote all interesting answers.
Accept the best answer.
Go on to the next number.
A:
Terach as 156 when Yishmael was born.
[Terach was 70 when he begat Avraham.
Avraham was 86 when he begat Yishmael.]
A:
The Gematria of "Yosef" is 156 (also noted by Gershon Gold). Accordingly, in the book Kol HaTor on the Redemption, by Rabbi Hillel Rivlin of Shklov, a disciple of the Vilna Gaon, there are 156 teachings about Mashiach ben Yosef.
A:
יוסף & אהב אביהם מכל = 156
| {
"pile_set_name": "StackExchange"
} |
Q:
In Kafka Connector, how do I get the bootstrap-server address My Kafka Connect is currently using?
I'm developing a Kafka Sink connector on my own. My deserializer is JSONConverter. However, when someone send a wrong JSON data into my connector's topic, I want to omit this record and send this record to a specific topic of my company.
My confuse is: I can't find any API for me to get my Connect's bootstrap.servers.(I know it's in the confluent's etc directory but it's not a good idea to write hard code of the directory of "connect-distributed.properties" to get the bootstrap.servers)
So question, is there another way for me to get the value of bootstrap.servers conveniently in my connector program?
A:
Instead of trying to send the "bad" records from a SinkTask to Kafka, you should instead try to use the dead letter queue feature that was added in Kafka Connect 2.0.
You can configure the Connect runtime to automatically dump records that failed to be processed to a configured topic acting as a DLQ.
For more details, see the KIP that added this feature.
| {
"pile_set_name": "StackExchange"
} |
Q:
Any idea to delete item in system.keychain in command or AppleScript?
Currently I am developing a small application that I wanna to remove the airport settings.
Firstly, I use shell command networksetup to delete the preferred networks, and then delete the recorded-password in keychain by AppleScript. But I found that the airports' passwords recorded in both system.keychain and login.keychain. I write the AppleScript such as:
tell application "Keychain Scripting"
set keychainName to "Login.keychain" -- "system.keychain"
set gkeyCount to count generic key of keychain keychainName
repeat with keyIndex from 1 to gkeyCount
log keyIndex
if (account of generic key keyIndex of keychain keychainName is "ABCD") then
delete generic key keyIndex of keychain keychainName
log "find the key"
end if
end repeat
end tell
For keychain "login.keychain", it's no problem, but for keychain "System.keychain", it failed with a popup show me "Keychain Scripting got an error: File not open with write permission."
Any idea?
A:
Edit: This doesn't work. Ah well, it was just a guess anyway. I'm leaving the answer up for posterity.
My guess is that the problem is that the system keychain is locked. I can't really test this, since I don't want to delete things from my keychain, but I did confirm that my system keychain defaults to being locked, and this seems like the sort of thing which would cause the error you see. Thus, I'd do something like this:
tell application "Keychain Scripting"
set keychainName to "Login.keychain" -- "system.keychain"
set doRelock to false
set kc to keychain keychainName
if locked of kc then
unlock kc
set doRelock to true
end if
try
set gkeyCount to count generic key of kc
repeat with keyIndex from 1 to gkeyCount
log keyIndex
if (account of generic key keyIndex of kc is "ABCD") then
delete generic key keyIndex of keychain keychainName
log "find the key"
end if
end repeat
if doRelock then
lock kc
set doRelock to false
end if
on error
if doRelock then lock kc
end try
end tell
The idea is to first unlocked the keychain if you need to, and then make sure you relock it when you're done. Let me know if this does or doesn't work—like I said, I had nothing I wanted to test this on.
| {
"pile_set_name": "StackExchange"
} |
Q:
R: independence test: access the p-value
I've read about getting the p-value from chisq.test using $p.value and from the binomial test using a similar call. However, that doesn't work for the independence_test from the coin package.
> i1 = independence_test(Response ~ Type)
> i1
Asymptotic General Independence Test
data: Response by Type (A, B, C)
maxT = 0.95091, p-value = 0.9265
alternative hypothesis: two.sided
> i1$p.value
Error in i1$p.value : $ operator not defined for this S4 class
> names(i1)
NULL
Can't index it either:
> i1[1]
Error in i1[1] : object of type 'S4' is not subsettable
> i1[[1]]
Error in i1[[1]] : this S4 class is not subsettable
How can I access the p-value?
A:
It appears that coin provides a special function to retrieve the p-value from the object returned by the test function:
> result <- independence_test(c(1,2,3) ~ c(4,5,6))
> pvalue(result)
[1] 0.1572992
>
| {
"pile_set_name": "StackExchange"
} |
Q:
Share drawables between applications
I have implemented plugin system in my applications. Plugins exist as the standalone applications.
What is the best way to access drawables from plugins in main application ?
A:
You have few options:
ContentProvider - not definitely need to be based over SQLite database.
manifest attribute android:sharedUserId
From docs:
The name of a Linux user ID that will be shared with other
applications. By default, Android assigns each application its own
unique user ID. However, if this attribute is set to the same value
for two or more applications, they will all share the same ID —
provided that they are also signed by the same certificate.
Application with the same user ID can access each other's data and, if
desired, run in the same process.
See http://developer.android.com/guide/topics/manifest/manifest-element.html#uid
PackageManager.getResourcesForApplication() to retrieve the resources associated with an application.
Usage:
PackageManager pm = getPackageManager();
try {
Resources resources = pm.getResourcesForApplication("com.example.app");
int id = resources.getIdentifier("ic_launcher", "drawable", "com.example.app");
Drawable d = resources.getDrawable(id)
} catch (NameNotFoundException e) {
e.printStackTrace();
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it safe to delete a lost+found folder?
I have an empty seperate partition used for my vhd/virtualbox. mounted at /mount/win7.
I've deleted everything now and there's a lost+found folder left over. It takes up about 5gigs
Is it safe to remove a lost and found folder?
A:
fsck will recreate the lost+found directory if it is missing.
On startup most distributions run fsck if the filesystem is detected as not being unmounted cleanly.
As fsck creates the lost+found directory if it is missing, it will create it then and place anything that it finds into that directory.
So you can remove it without any problem.
A:
So far I was under the impression that deleting lost+found was perfectly safe, as it would be recreated by fsck whenever it is needed. But after the Ubuntu 12.10 upgrade I got this mail from cron:
/etc/cron.daily/standard:
Some local file systems lack a lost+found directory. This means if the
file system is damaged and needs to be repaired, fsck will not have
anywhere to put stray files for recovery. You should consider creating
a lost+found directory with mklost+found(8).
The following lost+found directories were not available:
/home/lost+found
The man-page of mklost+found says:
mklost+found pre-allocates disk blocks to the lost+found directory
so that when e2fsck(8) is being run to recover a filesystem, it does
not need to allocate blocks in the filesystem to store a large number
of unlinked files. This ensures that e2fsck will not have to allocate
data blocks in the filesystem during recovery.
I am not sure what exactly that means, but it seems to indicate that not having lost+found might cause trouble on recovery. Furthermore it indicates that lost+found different from a regular directory in that it has preallocated blocks associated with it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Mock controller in Symfony2 unit test
I am writing unit tests for an API Service in a Symfony2 project. One service method takes a controller instance as an argument, and handles the requested JSON.
public function getJSONContent(Controller $controller) {
$version = $this->getAPIVersion();
//Read in request content
$content = $controller->get("request")->getContent();
if (empty($content)) {
throw new HttpException(400, 'Empty request payload');
}
//Parse and Detect invalid JSON
$jsonContent = json_decode($content, true);
if($jsonContent === null) {
throw new HttpException(400, 'Malformed JSON content received');
}
return $jsonContent;
}
The following is my test:
class ApiTest extends \PHPUnit_Framework_TestCase {
public function testGetJSONContent() {
// Create a stub for the OrgController Object
$stub = $this->getMock('OrganizationController');
// Create the test JSON Content
$post = 'Testy Test';
$request = $post;
$version = "VersionTest";
$APIService = new APIService();
// Configure the Stub to respond to the get and getContent methods
$stub->expects($this->any())
->method('get')
->will($this->returnValue($post));
$stub->expects($this->any())
->method('getContent')
->will($this->returnValue($request));
$stub->expects($this->any())
->method('getAPIVersion')
->will($this->returnValue($version));
$this->assertEquals('Testy Test', $APIService->getJSONContent($stub));
}
}
My test throws the following error:
Argument 1 passed to Main\EntityBundle\Service\APIService::getJSONContent() must be an instance of Symfony\Bundle\FrameworkBundle\Controller\Controller, instance of Mock_OrganizationController_767eac0e given.
My stub is obviously not fooling anyone, is there any way to fix this?
A:
Use the namespace to specify the controller you are mocking. I.e.
// Create a stub for the OrgController Object
$stub = $this->getMock('Acme\AcmeBundle\Controller\OrganizationController');
| {
"pile_set_name": "StackExchange"
} |
Q:
Show the build duration time in Makefile
within in Make file, i can printed the time before the build start and finished.
myitem:
printf 'start time is %s\n' "$$(date --iso-seconds)"
#other build command, i.e. g++ xxxx.cpp
printf 'end time is %s\n' "$$(data --iso-seconds)"
Is there any other way that implemented like below in Make file?
myitem:
starttime = $$(date)
#start my build
printf "The build took time:" NowTime - startTime
A:
If this is just for informational purposes, the absolutely easiest way is to run your build under the time command.
To answer your question in full, though, read on.
By default, each line of a recipe runs in a separate shell instance. To use a variable from an earlier command, use a single shell. Perhaps like this:
myitem:
d=$$(date +%s)\
; build \
&& echo "Build took $$(($$(date +%s)-d)) seconds"
The backslashes escape the newlines so that this is seen as a single long logical line by make. The semicolons and && are statement separators - I find it helpful (because it's so ugly!) to put them at the beginning of the next line just to remind myself that this is a single compound command. If the build fails, the stuff after && will not execute; this is slightly inelegant, but better than thinking that your build succeeded when it didn't.
I switched to date +%s (seconds since epoch) because that is so much easier to work with programmatically.
In GNU Make, you could also use .ONESHELL.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python, remove all html tags from string
I am trying to access the article content from a website, using beautifulsoup with the below code:
site= 'www.example.com'
page = urllib2.urlopen(req)
soup = BeautifulSoup(page)
content = soup.find_all('p')
content=str(content)
the content object contains all of the main text from the page that is within the 'p' tag, however there are still other tags present within the output as can be seen in the image below. I would like to remove all characters that are enclosed in matching pairs of < > tags and the tags themselves. so that only the text remains.
I have tried the following method, but it does not seem to work.
' '.join(item for item in content.split() if not (item.startswith('<') and item.endswith('>')))
What is the best way to remove substrings in a sting? that begin and end with a certain pattern such as < >
A:
Using regEx:
re.sub('<[^<]+?>', '', text)
Using BeautifulSoup:(Solution from here)
import urllib
from bs4 import BeautifulSoup
url = "http://news.bbc.co.uk/2/hi/health/2284783.stm"
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)
# kill all script and style elements
for script in soup(["script", "style"]):
script.extract() # rip it out
# get text
text = soup.get_text()
# break into lines and remove leading and trailing space on each
lines = (line.strip() for line in text.splitlines())
# break multi-headlines into a line each
chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
# drop blank lines
text = '\n'.join(chunk for chunk in chunks if chunk)
print(text)
Using NLTK:
import nltk
from urllib import urlopen
url = "https://stackoverflow.com/questions/tagged/python"
html = urlopen(url).read()
raw = nltk.clean_html(html)
print(raw)
A:
You could use get_text()
for i in content:
print i.get_text()
Example below is from the docs:
>>> markup = '<a href="http://example.com/">\nI linked to <i>example.com</i>\n</a>'
>>> soup = BeautifulSoup(markup)
>>> soup.get_text()
u'\nI linked to example.com\n'
| {
"pile_set_name": "StackExchange"
} |
Q:
In XSLT, what is the difference between true() and true?
I wanted to understand the difference between true() and true and the usage of both.
For example:
I am declaring a variable var1 as follows:
<xsl:variable name="var1"
select="/root/name ='' and exists(/root/name[@as:firstname])"></xsl:variable>
<!--and now I wan to use it as a condition, say:-->
<xsl:if test="$var1=true() "> <!-- Now would I use true() or true here ?-->
<xsl:text>Hello World</xsl:text>
</xsl:if>
A:
Since you have defined the variable using a boolean expression, both:
<xsl:if test="$var1=true()">
and:
<xsl:if test="$var1">
will work the same way. Not sure what you mean by true; it could be a node or it could be a string "true". In the latter case, the test:
<xsl:if test="$var1='true'">
would work in XSLT 1.0 (and it would work just as well with any non-empty string), but not in XSLT 2.0.
Note also that:
string(var1)
will return either "true" or "false", so the test:
<xsl:if test="string($var1)='true'">
will work the way you would expect, in both XSLT 1.0 and 2.0
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP - Criar um array associativo do banco
Eu tenho as informações abaixo num banco:
E quero o resultado em um array assim:
['CLARO' => "IPHONE 8", "VIVO" => "MOTO ONE", "TIM" => "ZENFONE 6", "CLARO" => "IPHONE 8", "CLARO" => GALAXY S9", "TIM" => "MOTO ONE Z", "TIM" => "MOTO ONE Z", "VIVO" => "MOTO ONE" e "VIVO" => "GALAXY S10"]
Até agora não deu muito certo (kkkkkkk) e estou com o seguinte código:
$t_op = array();
$t_mod = array();
$t_result = mysqli_query($conn, "SELECT operadora, modelo FROM sdc_tm_aparelhos WHERE id <> 1");
while ($t_row = mysqli_fetch_assoc($t_result)) {
$t_op[] = $t_row['operadora'];
$t_mod[] = $t_row['modelo'];
}
foreach ($t_op as $um) {
foreach ($t_mod as $dois) {
$novo = array($um=>$dois);
}
}
print_r($novo);
Esse código me apresenta o seguinte na tela:
Procurei solução aqui no site mas não encontrei exatamente o que eu precisa, se alguém souber responder ou indicar algum outro tópico bem próximo a isso que preciso agradeço!
A:
Não tem como criar array associativo com valores de chaves duplicadas, elas são únicas.
O que você pode fazer é criar uma array associativo multidimensional onde os valores das chaves ficariam nessa estrutura:
Veja que a estrutura é uma array da operadora com os modelos, e nos modelos outra array com os id's (que você pode substituir por outro dado do banco).
O código ficaria assim:
$novo = array();
$t_result = mysqli_query($conn, "SELECT id, operadora, modelo FROM sdc_tm_aparelhos WHERE id <> 1");
while ($t_row = mysqli_fetch_assoc($t_result)) {
$novo[$t_row['item']][$t_row['nivel']][] = $t_row['id'];
}
print_r($novo);
| {
"pile_set_name": "StackExchange"
} |
Q:
View Added Items in Visual Studio
I just began using Visual Studio to work on a practice .NET project. I have added a stylesheet that I made outside of VS. I went to Project/Add Existing Item... My question is, how can I view all the items I have added to a project.
A:
You should be able to see all of your files in Solution Explorer, or are you asking about showing just the ones "added" to the project, not those "created" in the project? I don't think there is a way to differentiate between the two once they are in the project.
| {
"pile_set_name": "StackExchange"
} |
Q:
Scene not changing in SpriteKit
I've created a game and now I want to add a start screen in which I want to run a video and after that there will be a screen with start button, I've searched over internet but couldn't find out the way to do it, have tried many things, the latest code is:
#import "FirstScreen.h"
#import "GameScene.h"
#import <MediaPlayer/MediaPlayer.h>
@implementation FirstScreen
-(id)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
NSURL *url =[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Intro" ofType:@"mp4"]];
_player = [[MPMoviePlayerController alloc] initWithContentURL:url];
_player.view.frame = CGRectMake(0,0, 1024, 768);
[self.view addSubview:_player.view];
_player.shouldAutoplay = YES;
[_player prepareToPlay];
NSString *nextSceneButton;
nextSceneButton = @"Start";
SKLabelNode *myLabel = [SKLabelNode labelNodeWithFontNamed:@"Chalkduster"];
myLabel.text = nextSceneButton;
myLabel.fontSize = 30;
myLabel.fontColor = [SKColor blackColor];
myLabel.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
myLabel.name = @"Start";
[self addChild:myLabel];
}
return self;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
/* Called when a touch begins */
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
SKNode *node = [self nodeAtPoint:location];
if ([node.name isEqualToString:@"Start"]) {
SKTransition *reveal = [SKTransition fadeWithDuration:3];
GameScene *scene = [GameScene sceneWithSize:self.view.bounds.size];
scene.scaleMode = SKSceneScaleModeAspectFill;
[self.view presentScene:scene transition:reveal];
}
}
@end
App just starts and give the SIGABRT error. Can you tell me how to do it?
A:
You should check few things to make sure is everything okay there:
Check if everything is okay with file name, look for spaces or typos etc...
See what pathForResource returns (println it)
See what fileURLWithPath returns
Go to : Target -> Build Phases -> Copy Bundle Resources and add Intro.mp4 file there. If that file is already added , delete it, clean your project Project->Clean, and add it again. Build project and run it.
| {
"pile_set_name": "StackExchange"
} |
Q:
complexity of minmax_element
How is minmax_element typically implemented?
I can see the time complexity is at most max(floor(3/2(N−1)), 0) applications of the predicate, where N = std::distance(first, last).
Where minmax_element allows me to find the smallest and largest elements in a range of elements that can be iterated over (read: containers).
For example:
#include <algorithm>
#include <vector>
using namespace std;
void Algorithm_minmax_element()
{
double x = 2, y = 1, z = 0;
vector<double> v = { 2, 1, 0, -1 };
auto result1 = minmax(x, y);
// result1 == pair(1, 2)
auto result2 = minmax({ x, y, z });
// result2 == pair(0, 2)
auto result3 = minmax_element(v.begin(), v.end());
// result3 == pair(&v[3] = -1, &v[0] = 2)
}
A:
A reference implementation is given in cppreference.com.
Using std::min and std::max for each element would require two comparisons per element, or 2n comparisons in total. Same goes for std::min_element and std::max_element.
The reference implementation requires only about 3n/2 comparisons in total. The principle is simple: at each step, we process 2 elements. We need one comparison to decide which one is smaller, one comparison to compare the smaller to the minimum, and one comparison to compare the larger to the maximum. Total of 3 comparisons for each 2 elements.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get Runtime Web Application path?
In my web application, I'm using property file inside web folder and I need to refer the property file from java file in the same application to get the value of the property. How can I provide the path? I need the path name and not the URI. My code is as follows:
Properties prop = new Properties();
FileInputStream propertiesStream = null;
try {
propertiesStream = new FileInputStream("..\Files\Prop.properties");
prop = new Properties();
prop.load(propertiesStream);
prop.getProperty("id");
propertiesStream.close();
} catch (IOException ioException) {
System.out.println("PropertiesLoader IOException message:" + ioException.getMessage());
}
A:
Considering that it is a properties file I would suggest that you fetch it as a ResourceBundle from your classpath.
E.g. say you put your properties file here:
/WEB-INF/classes/MyProperties.properties
You could fetch it with the following code:
ResourceBundle props = ResourceBundle.getBundle("MyProperties");
Or as a Properties object:
Properties props = new Properties();
InputStream is = getClass().getResourceAsStream("MyProperties");
props.load(is);
is.close();
| {
"pile_set_name": "StackExchange"
} |
Q:
plotting color codded graph in matlab
I need to plot a color codded 2d graph using a .dat file. data in the file is arranged as
48.000000 0.000184 0.400000
48.500000 0.000185 0.400000
49.000000 0.000186 0.400000
49.500000 0.000187 0.400000
50.000000 0.000187 0.400000
50.500000 0.000186 0.400000
51.000000 0.000186 0.400000
51.500000 0.000186 0.400000
52.000000 0.000185 0.400000
52.500000 0.000184 0.400000
53.000000 0.000184 0.400000
53.500000 0.000182 0.400000
54.000000 0.000180 0.400000
54.500000 0.000179 0.400000
55.000000 0.000177 0.400000
55.500000 0.000174 0.400000
56.000000 0.000172 0.400000
here 3rd column is also changing. There are almost 3000 lines. I need to plot a color codded 2d graph between 1st and 2nd variable and color has to put as height of 3rd variable.
Can someone help me ?
A:
If you want the colors of your data to go from dark to light based on the value in column 3, then you might be best off just using the scatter function. According to the documentation
scatter(X,Y,S,C) displays colored circles at the locations specified by the vectors X and Y (which must be the same size).
S determines the area of each marker ...
C determines the color of each marker. When C is a vector the same length as X and Y, the values in C are linearly mapped to the colors in the current colormap.
This means that you can explicitly chose the colormap that you want your data to use. Assuming col1, col2, col3 contain the values in each of the three columns of your data, the following code will draw a scatter plot with col1 and col2 defining the x and y positions (respectively) and col3 defining the color of each point.
scatter(col1, col2, 25, col3, '.');
colormap(gray);
After drawing the scatter plot, I explicitly set the colormap to gray so that points in col3 with a small value will be dark and those with a large value will be light. Note that in this example the marker area is 25 and the marker type is a dot ('.'), as specified by the 3rd and 5th parameters of the scatter function.
There are many other colormaps that you could use besides gray. For example, hot or copper might be more aesthetically pleasing. The doc for the colormap function gives more info on your other options.
| {
"pile_set_name": "StackExchange"
} |
Q:
Ubuntu Software Center / Update Manager not working - Could not open file
I'm having trouble with my Software Center, I'm running Natty Narwale and receive the following error when I try to open Update Manager.
Could not initialize the package information
An unresolvable problem occurred while initializing the package
information.
Please report this bug against the 'update-manager' package and
include the following error message:
'E:Could not open file
/var/lib/apt/lists/Ubuntu%2011.04%20%5fNatty%20Narwhal%5f%20-%20Release%20i386%20(20110427.1)_dists_natty_Release
- open (2: No such file or directory), E:The package lists or status file could not be parsed or opened.'
As I get similar issues in the Software Center I've tried removing it via the terminal but I get the same problem:
Reading package lists... Error!
E: Could not open file /var/lib/apt/lists/Ubuntu%2011.04%20%5fNatty%20Narwhal%5f%20-%20Release%20i386%20(20110427.1)_dists_natty_Release - open (2: No such file or directory)
E: The package lists or status file could not be parsed or opened.
Does anyone have any thoughts how I can resolve this?
A:
It is a bug. its caused by the status file parser not being able to open up the proper format that the status file is in. please report the bug.
| {
"pile_set_name": "StackExchange"
} |
Q:
dynamic directive: templateUrl
I really need help by solving the following problem:
I try to realize some settings for an application, therefore I want to use the UI-Bootstrap accordion.
I have the following HTML-Code:
<accordion close-others="oneAtATime">
<accordion-group ng-repeat="group in groups" heading="{{group.groupTitle}}">
<accordion-content></accordion-content>
</accordion-group>
</accordion>
The DOM of the "accordion" is a div where ng-controller="AccordionController". In this Controller I have a variable groups which looks like this:
$scope.groups = [{
groupTitle: "title1",
templateUrl: "file1.html"
}, {
groupTitle: "title2",
templateUrl: "file2.html"
}]; // ... and so on
accordionContent is my directive which should give different templateURLs depending on the $index or groupTitle (doesn't matter).
The accordionContent-directive looks like this:
settings.directive("accordionContent", function () {
return {
restrict: "E",
templateUrl: //**here is my problem**
};
});
The content also has some angular-stuff implemented, I read that this need to get considered. (or not ?)
A:
I don't believe you can do that like that. I tried myself once, didn't work if I remember correctly.
What you can do is have a static HTML page in the directive, and in that HTML page you'll have:
<div>
<div class="slide-animate" ng-include="templateUrl"></div>
</div>
Where templateUrl is the variable on your isolated scope (or not isolated..) in the accordion-content directive.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to check if a Choice field option is selected
In our PowerApps form we have the DisplayMode of our submit button determined by a formula that checks all the mandatory fields have been completed.
If (
And(
Or(DPIAForm.Mode=FormMode.Edit,DPIAForm.Mode=FormMode.New),
Not IsBlank(TitleField.Text),
Not IsBlank(DescOfInitiativeField.Text),
DateRaisedField.SelectedDate <> Date(
1900,
01,
01
),
Not IsEmpty(PersonalDataChoiceField.SelectedItems.Value),
Not IsEmpty(SpecialCatChoiceField.SelectedItems.Value),
Not IsEmpty(ChildrensDataChoiceField.SelectedItems.Value),
Not IsEmpty(CriminalChoiceDataField.SelectedItems.Value),
Not IsEmpty(SourcesOfDataChoiceField.SelectedItems.Value),
Not IsEmpty(NumberOfIndividualDataSubjectsChoiceField.SelectedItems.Value),
Not IsEmpty(LawfulBasisChoiceField.SelectedItems.Value),
Not IsBlank(ProviderField.Text),
Not IsEmpty(NewTechnologyChoiceField.SelectedItems.Value),
Not IsEmpty(DataEvaluatedOrScoredChoiceField.SelectedItems.Value),
Not IsEmpty(DecisionsMadeAutomaticallyChoiceField.SelectedItems.Value),
//Not IsBlank(KindofDecisionsMadeAutomaticallyField.Text),
If(DecisionsMadeAutomaticallyChoiceField.SelectedItems.Value ="Yes", Not IsBlank(KindofDecisionsMadeAutomaticallyField.Text), "" ),
Not IsEmpty(IndividualNotAwareOfPersonalDataCaptureChoiceField.SelectedItems.Value),
Not IsEmpty(DataTransferredOutsideEEAChoiceField.SelectedItems.Value),
Not IsBlank(WhoWillHaveAccessToDataField.Text),
Not IsEmpty(MonitoringIndividualsChoiceField.SelectedItems.Value),
Not IsEmpty(CriminalChoiceDataField.SelectedItems.Value),
Not IsEmpty(MonitoringIndividualsChoiceField.SelectedItems.Value),
Not IsEmpty(DataRetentionPlanChoiceField.SelectedItems.Value),
Not IsBlank(RetentionPlanForPersonalDataField.Text),
Not IsBlank(RetentionPlanForSensitiveDataField.Text),
Not IsBlank(RetentionPlanForChildrensDataField.Text),
Not IsBlank(RetentionPlanForCriminalConvictionDataField.Text),
Not IsEmpty(SupplierDueDiligenceDoneChoiceField.SelectedItems.Value),
Not IsEmpty(GDPRCompliantContractWithAll3rdPartiesChoiceField.SelectedItems.Value),
StatusDataField.Text = "Draft"
),
DisplayMode.Edit,
DisplayMode.Disabled)
the part we are having trouble with is the formula in the middle:
If(DecisionsMadeAutomaticallyChoiceField.SelectedItems.Value ="Yes", Not IsBlank(KindofDecisionsMadeAutomaticallyField.Text), "" ),
here I want to test that if the user has selected "Yes" in the drop-down/choice field ecisionsMadeAutomaticallyChoiceField and if so, then the field KindofDecisionsMadeAutomaticallyField must not be blank/empty in order for the Submit button to be enabled...
But I am getting an error Invalid argument type on If(DecisionsMadeAutomaticallyChoiceField.SelectedItems.Value ="Yes"
I have also tried:
If(DecisionsMadeAutomaticallyChoiceField.SelectedItems(1)
so what's the correct way to do this in our formula?
A:
I found the answer is to check that Yes is selected in the following way:
if("Value" in ComboBox.SelectedItems.Value,
Not IsBlank(TextDataField.Text), IsBlank(TextDataField.Text) ),
so in my case the correct formula is:
if("Yes" in DecisionsMadeAutomaticallyChoiceField.SelectedItems.Value,
Not IsBlank(KindofDecisionsMadeAutomaticallyField.Text),
IsBlank(KindofDecisionsMadeAutomaticallyField.Text) ),
| {
"pile_set_name": "StackExchange"
} |
Q:
Vectorizing a for-loop operation
I have an SDE I'm approximating by a numerical scheme using this code:
mu = 1.5;
Sigma = 0.5;
TimeStep = 0.001;
Time = 0:TimeStep:5;
random1 = normrnd(2,0.05,[1,500]);
random2 = randn(1,length(Time));
X = zeros(500, length(Time));
for j = 1:500
X(j,1)= random1(j);
for i = 1:length(Time)
X(j,i+1) = X(j,i) - mu*X(j,i)*TimeStep + Sigma*sqrt(2*mu)*sqrt(TimeStep)*random2(i);
end
end
How would it be possible to remove the outer for-loop and vectorize, so that at each time step, the first value is calculated for all 500 plots?
A:
That's pretty simple, especially since j is only used for row indexing here:
X(:,1)= random1;
for i = 1:length(Time)
X(:,i+1) = X(:,i) - mu*X(:,i)*TimeStep + Sigma*sqrt(2*mu)*sqrt(TimeStep)*random2(i);
end
I tested both versions (Octave 5.1.0), and get identical results. Speed-up is about 400x on my machine.
General remark: Never use i and/or j as loop variables, since they are also used as imaginary units, cf. i and j.
Hope that helps!
| {
"pile_set_name": "StackExchange"
} |
Q:
Why would one of my accounts not show up anywhere in my account listing?
Possible Duplicate:
How can I have my English SE account show up on my list of SE accounts?
It's not quite the same as this question because even on the site of the missing account, all my other SE accounts are shown, but not that one. It's not some kind of joke to do with being an IT Security site, is it?
My account on IT Security is https://security.stackexchange.com/users/3677/bryan-agee.
A:
Alrighty--so apparently clearing all associations and then re-linking them was the answer.
| {
"pile_set_name": "StackExchange"
} |
Q:
Start Application Before Windows Shell Starts Up?
I have a C# WPF application that I'd like to startup/display before the Windows explorer shell comes up. I basically want my application to be the first thing to load after login.
A:
Winlogon is the program that shows you the login credential dialog, it is responsible for logging you in, and eventually starts the shell.
You can configure many aspect of it from the registry. Specifically, you can tell it to spawn a different program as a shell. You do it at:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon
Shell (REG_SZ)
Just change the value to whatever program you want to start, either a full path or a partial path. You can also change it per user in a equivalent HKCU hive.
[side note: Your tags are misleading. Your question has nothing to do with c# or WPF]
| {
"pile_set_name": "StackExchange"
} |
Q:
Sitecore GlassMapper MVC add standard fields to model
I need the sort order of my item in a specific model.
I have tried it like this but no luck:
[SitecoreField("__Sortorder")]
public string SortOrder { get; set; }
Any idea how I can include standard fields in my model?
If this is not possible, actually I am working with a Checklist in that case, The AutoMapping from GlassMapper does return it in alphabetical order.
Here is the Definition of the Checklist Field:
IEnumerable<Guid> Filter_Tags_To_Shows {get; set;}
And like mentioned before, the list is returned in alphabetical order but I have no change to sort afterwards since missing the sortOrder field.
Thanks in Advance.
A:
Your Filter_Tags_To_Shows property is returning a list of Guids which, I presume, you are then doing something to get the linked Item from Sitecore. This is not the most efficient way and Glass allows you to specify the linked Item type which it will them automap.
IEnumerable<FilterTagClass> Filter_Tags_To_Shows {get; set;}
Assuming that the FilterTagClass has the sort order specified like in your question:
[SitecoreType(TemplateId={GUID})]
public class FilterTagClass : GlassBase
{
[SitecoreField("__Sortorder")]
public virtual int SortOrder { get; set; }
}
You can sort using Linq:
@foreach (var tag in Filter_Tags_To_Shows.OrderBy(i => i.SortOrder))
{
// do stuff
}
This is a re-hash of the answer from @DougCouto but note it is not necessary to convert IDs to object if you set up the properties and mapping correctly.
As an alternative to using the Checklist field you can use the Multilist field, which will allow you select tags and re-order them as required. Glass should return them in the same order you have set then.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to pass an expression as list elements for a Mathematica command
I'm trying to build a generic function that will calculate sums on different iterators.
To simplify let consider:
Sum[x1 + x2 + x3, {x2, 2}, {x3, 2}];
MySum := Function[ Sum[x1 + x2 + x3, ##]];
(* I can call this function like this *)
MySum[{x2, 2}, {x3, 2}];
(*Now let's try an expression*)
xpr = {{x2, 2}, {x3, 2}};
(*Below still works*)
MySum [xpr[[1]], xpr[[2]] ]
(*How to make it generic for an arbitary number of elements?*)
imax = 2;
MySum [For[ i = 1, i <= imax, i++, xpr[[i]] ] ]
I would like to be able to call the function for 1 or 2 elements of the list generically.
A:
This should work for any length of the xpr list:
MySum @@ xpr
Call just with the first element of xpr:
MySum @@ xpr[[{1}]]
Call just with the first, third, and fifth element of xpr:
MySum @@ xpr[[{1,3,5}]]
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use a string to get the respective image drawable
private int imageres[] = {
R.drawable.desk,
R.drawable.bed,
R.drawable.chair,
};
private String typeofplace[] = {
"Desk", //0
"Bed", //1
"Desk", //2
"Chair", //3
"Bed", //4
"Chair", //5
};
for (int i = 0; i < typeofplace.length; i++) {
//how do I get the image (int) based on the `typeofplace`:
// MyFunction(imageres[R.drawable.{typeofplace}]);
}
Dow do I get the image (int) based on the typeofplace:
MyFunction(imageres[R.drawable.{typeofplace}]);
A:
I think that there is a better approach to do that, you don't need a HashMap or a string array with the typeofplace. If you know the name of your drawable, simply use:
int imageId = getResources().getIdentifier("desk", "drawable", getPackageName());
| {
"pile_set_name": "StackExchange"
} |
Q:
What IP MTU sizes are seen in real networks
I am writing an application which will be deployed in third party networks. It will receive IP packets and I want to know what the maximum size in reality they are likely to be is. I'm not asking what the Maximum theoretical size is but rather what in practice is generally seen. I've heard that there may be an MTU of 1576 used but have not been able to ratify this?
Regards
A:
The biggest I've seen on Ethernet is 9000 plus headers, but unless you want to become famous through posts on Security Focus, I suggest you not use a static buffer and instead determine how much space you need to allocate and use that instead.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to check whether an input is integer, string or float in C++
What I want to know is, If I ask a user to input something, how will I output if the input is a Integer or String or a Float Value. I want some method to check the data type of the input in C++14.
For eg.
If the input is "Hello world"
Output should be : "The input is String"
If the input is "134"
Output should be : "The input is integer"
If the input is "133.23"
Output should be : "The input is float"
A:
Read string.
In <string>, the standard library provides a set of functions for extracting numeric values from their character representation in a string or wstring.
Use x=stoi(s,p). Check p - if whole string was read - it is integer.
Do the same with x=stof(s,p) or x=stod(s,p), x=stold(s,p) to check for float/double/long double.
If everything fails - it is string.
A:
The user will always input a string, what you can do is try to convert it to a float, if it succeeds then it probably is a float or an int.
If the float conversion doesnt succeed then its probably not a number.
A:
#include <iostream>
#include <string>
#include <boost/variant.hpp>
#include <sstream>
using myvariant = boost::variant<int, float, std::string>;
struct emit : boost::static_visitor<void>
{
void operator()(int i) const {
std::cout << "It's an int: " << i << '\n';
}
void operator()(float f) const {
std::cout << "It's a float: " << f << '\n';
}
void operator()(std::string const& s) const {
std::cout << "It's a string: " << s << '\n';
}
};
auto parse(const std::string& s) -> myvariant
{
char* p = nullptr;
auto i = std::strtol(s.data(), &p, 10);
if (p == s.data() + s.size())
return int(i);
auto f = std::strtof(s.data(), &p);
if (p == s.data() + s.size())
return f;
return s;
}
void test(const std::string& s)
{
auto val = parse(s);
boost::apply_visitor(emit(), val);
}
int main()
{
test("Hello world");
test("134");
test("133.23");
}
expected output:
It's a string: Hello world
It's an int: 134
It's a float: 133.23
| {
"pile_set_name": "StackExchange"
} |
Q:
Python Indentation with For, While and Try
I've written a small program to simulate a paper, scissor, rock game.
I'm using a for-loop to control the round-of-3 behaviour and am using while and try to control user input.
I don't believe python is running the code within the game evaluation logic, but I'm not too sure why. I think it might have to do with scope / indentation, but I'm not sure? Have run out of ideas!
If anyone could point me in the direction of a previous answer, resource or help clarify the issue in my code I'd be very thankful.
# module packages
import random
def rockpaperscissor():
# data structures and primary variables
state = ["Rock", "Paper", "Scissor"]
user_points = []
computer_points = []
round_counter = 1
# game loop (best of three rounds)
for i in range(3):
print("Round " + str(round_counter) + ":")
computer_choice = random.choice(state)
# user input
while True:
try:
print("You: ", end='')
user_input = input().strip()
if user_input not in {"Rock", "rock", "Paper", "paper", "Scissor", "scissor"}:
raise Exception
except Exception:
print("You have not entered a valid choice. Please re-enter.")
else:
break
print("Computer: ", end='')
print(computer_choice + "\n")
# game evaluation logic
if user_input in {"Rock" or "rock"}:
if computer_choice == "Paper":
computer_points.append(1)
elif computer_choice == "Scissor":
user_points.append(1)
elif computer_choice == user_input:
computer_points.append(0)
user_points.append(0)
elif user_input in {"Paper" or "paper"}:
if computer_choice == "Rock":
print('test')
user_points.append(1)
elif computer_choice == "Scissor":
computer_points.append(1)
print('test')
elif computer_choice == user_input:
computer_points.append(0)
user_points.append(0)
print('test')
elif user_input in {"Scissor" or "scissor"}:
if computer_choice == "Paper":
user_points.append(1)
elif computer_choice == "Rock":
computer_points.append(1)
elif computer_choice == user_input:
computer_points.append(0)
user_points.append(0)
round_counter = round_counter + 1
print(user_points)
print(computer_points)
print("Your final score: ", end='')
print(sum(user_points))
print("The Computer's final score: ", end='')
print(sum(computer_points))
# outcome logic
if user_points < computer_points:
print("\nSorry, you lost! Better luck next time!")
elif user_points > computer_points:
print("\nCongratulations, you won!")
else:
print("\nYou drew with the computer!")
# repeat logic
print("\nDo you want to play again? Yes or No?")
play_again = input().strip()
print("\n")
if play_again in {"Yes", "yes"}:
rockpaperscissor()
elif play_again in {"No", "no"}:
print("Not a problem. Thanks for playing. Catch you next time!")
rockpaperscissor()
# end of code
A:
In addition to fixing your code, I've made some relatively minor changes to condense it, or tidy it up here and there:
# module packages
import random
state = ("rock", "paper", "scissors")
def get_input():
while True:
user_input = input("You: ").strip().lower()
if user_input not in state:
print("You have not entered a valid choice. Please re-enter.")
continue
break
return user_input
def compare(move1, move2):
"""
If draw, return 0
If move1 beats move2, return 1
If move2 beats move1, return -1
"""
if move1 == move2:
return 0
if move2 == state[(state.index(move1) + 1) % 3]:
return -1
return 1
def rockpaperscissor():
# data structures and primary variables
user_points = 0
computer_points = 0
# game loop (best of three rounds)
for round_counter in range(1, 4):
print("\nRound {}".format(round_counter))
computer_choice = random.choice(state)
# user input
user_input = get_input()
print("Computer: {}".format(computer_choice))
# game evaluation logic
result = compare(user_input, computer_choice)
if result == 1:
user_points += 1
elif result == -1:
computer_points += 1
print("Round {} standings:".format(round_counter))
print("User: {}".format(user_points))
print("Computer: {}".format(computer_points))
print("Your final score: {}".format(user_points))
print("The Computer's final score: {}".format(computer_points))
# outcome logic
if user_points < computer_points:
print("\nSorry, you lost! Better luck next time!")
elif user_points > computer_points:
print("\nCongratulations, you won!")
else:
print("\nYou drew with the computer!")
# repeat logic
print("\nDo you want to play again? Yes or No?")
play_again = input().strip()
print("\n")
if "y" in play_again.lower():
rockpaperscissor()
else:
print("Not a problem. Thanks for playing. Catch you next time!")
rockpaperscissor()
# end of code
I'm working on some explanations now.
The biggest problem in your code was trying to test user_input in {"Rock" or "rock"}. This is a pretty direct translation from spoken language to code - it would probably seem natural to ask "is the input a Rock or a rock?". However, in Python, or is actually a special word used to operate on booleans (True or False values). For example, False or True is True, 1 == 4 or 6 < 7 is True, and so on. When Python tries to do "Rock" or "rock", it tries to treat both of the strings like booleans. Because they aren't empty, they act like True, so they reduce to True, except because one of them is True, it reduces to one of them, roughly. This is a little confusing to those not too familiar with the idea of truthiness, and where it can be used, but the important thing is that the fix was to separate them with a comma ,, not or.
However, there's an even better way to test this - using the .lower() method. Then you can directly do user_input.lower() == "rock". Note that this does mean "ROck" etc are also valid, but presumably that's fine as in that case the user probably did mean rock. Now we can actually use this trick together with the previous explanation of the use of in, to combine the entire validation into user_input.lower() in state, as state is actually exactly the three things it can be (given that I've modified state to be lowercase).
I've also moved some of the stuff you're doing into functions to improve clarity a bit.
get_input is now a function, using that validation logic. It also uses some simpler control flow than try/except - it uses the continue statement, which skips the rest of the body of the loop, and goes back to the start, so skips the break, and begins the whole cycle anew. If it is missed, the loops breaks and the function returns.
I've also written a function compare, which does the logic for comparing two moves. It uses a touch of voodoo - if move2 is to the right of move1 in state, move2 beats move1 so it returns -1, is what the longest condition does. It uses the modulo operator % so it "wraps" back around.
Using this compare function, the code can find out which score to increment without having to enumerate each case.
Aside from that, there are some smaller changes:
round_counter is drawn from the for loop, so it no longer has to be incremented.
I'm using .format a lot for string interpolation. It has relatively straightforward, concise syntax and is very powerful. I'd recommend using it in cases like this.
user_points and computer_points are just integers, as for the purposes of your code, being able to add 1 to them each time seems enough.
I'm verifying if the user wants to play again with 'y' in play_again.lower(), and actually have removed the elif condition, as it just needs to exit if the user gives no affirmation.
Also I've changed some statements of the form a = a + 1 to a += 1, which does the same thing but is slightly shorter.
As a comment mentioned, I've moved the import to the start of the file.
There is actually something stil very minorly sloppy about this code - rockpaperscissor is recursive. This isn't inherently a problem, but as it could end up calling itself infinitely many times - if you find a very enthusiastic user - it will eventually actually crash. This is because when you go "deeper" into a function in Python, has to store the state of the whole "stack" of functions somewhere. This is a "stack frame" and Python only has a limited number of stack frames it can allocate before they overflow. Note that sometimes a new stack frame isn't actually needed - your function is a case of that, as the information from any "parent" rockpaperscissor does not need to be preserved. This is called a "tail recursive" function, and many languages will actually optimise away the tail call, so this isn't a problem. Unfortunately we in Python don't have that luxury. So, if you like, you can try and change this code to use a while loop instead, so your hypothetical fan never has to stop playing.
This is what would end up happening:
Traceback (most recent call last):
File "code.py", line 71, in <module>
rockpaperscissor()
File "code.py", line 29, in rockpaperscissor
rockpaperscissor()
File "code.py", line 29, in rockpaperscissor
rockpaperscissor()
File "code.py", line 29, in rockpaperscissor
rockpaperscissor()
[Previous line repeated 995 more times]
RecursionError: maximum recursion depth exceeded
You also mentioned being interested in practicing try/except statements. If you like, you could try adding code so that instead of crashing when a user from the command line hits Ctrl-C or Ctrl-D it exits gracefully, maybe saying goodbye.
They raise
Round 1
You: ^CTraceback (most recent call last):
File "code.py", line 70, in <module>
rockpaperscissor()
File "code.py", line 38, in rockpaperscissor
user_input = get_input()
File "code.py", line 8, in get_input
user_input = input("You: ").strip().lower()
KeyboardInterrupt
and
Round 1
You: Traceback (most recent call last):
File "code.py", line 70, in <module>
rockpaperscissor()
File "code.py", line 38, in rockpaperscissor
user_input = get_input()
File "code.py", line 8, in get_input
user_input = input("You: ").strip().lower()
EOFError
respectively.
| {
"pile_set_name": "StackExchange"
} |
Q:
Insert icon in a tabbed page(Android) on xamarin form
I'm new to StackOverflow community!
I need help with one problem with android in Xamarin Forms. To be precise... I tried with some friends to build our first app. We choose(with the help of our University professor) Xamarin for the cross-platform development of Android and iOS for both systems using the Xamarin Forms. I created the interface part of the app and now I am stuck in a fort with big walls. When I try to add a Tabbed Page the icon for the functional bar, the app crashes(Android) but in iOS, the problem doesn't appear...
I'd try with some solution... like :
-Render in the NameApp.Droid adds different renderer only for the android part but no result...
-Try another way to insert the icon in the .xaml file directly but no result...
-Try to follow another way to modify the .axam file for the "Theme" part
but no result...
I want to integrate all the stuff on time only in the "Main Project". I don't want for now touch the "nameProject.Droid" or "nameProject.iOS" part, But try to make in one shoot both(Andriod & iOS). I've found a different bug in Android (è.é) but for this, I am going crazy...
But I need to modify the ".Droid" no problem I accept the challenge!
This is the result I aspire to create.
"https://storage.googleapis.com/material-design/publish/material_v_12/assets/0B6Okdz75tqQsbHJuWi04N0ZIc0E/components-tabs-usage-mobile7.png"
This is the way I add the Icon in the Tabbed Page. An assumption I add all the stuff in the "Resource" in ".Droid" and ".iOS :
var MainPageTabbed = new MPageTabbed();
var Profile = new Profile();
var ListChat = new ListChat();
if (Device.RuntimePlatform == Device.Android)
{
MainPageTabbed.Icon = "ldpi.png";
Profile.Icon = "ldpi2.png";
Chat.Icon = "ldpi1.png";
}
if (Device.RuntimePlatform == Device.iOS)
{
MainPageTabbed.Icon = "ldpi.png";
Profile.Icon = "ldpi2.png";
ListChat.Icon = "ldpi1.png";
}
NavigationPage.SetHasNavigationBar(this, false);
Children.Add(MainPageTabbed);
Children.Add(Profile);
Children.Add(ListChat);
Someone can help me please to find a solution?
A:
Here you have an example of how to use the TabbedPage in xamarin forms:
https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/navigation/tabbed-page/
... Xamarin.forms renders Android tabbed-pages as something called a viewpager combined with a TabPagerStrib, and it looks like the example in the link above.
You might read about BottomNavigationBar for Android instead, or look at this link for a TabPagerStrip with an image:
https://forums.xamarin.com/discussion/39937/adding-icons-to-a-pagertabstrip-instead-of-text
A:
If anyone is interested in a FontAwesome custom icon implementation I followed this tutorial to begin with: FontAwesome with Xamarin Forms
Unfortunately he doesn't give an example of integrating with tabbed pages but after some experimenting I finally figured out a simplified Xaml way to render it without a custom tabbed renderer:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:IBMobile.Views"
xmlns:local2="clr-namespace:FontAwesome"
x:Class="IBMobile.Views.HomePage"
Visual="Material">
<ContentPage.IconImageSource>
<FontImageSource FontFamily="{StaticResource FontAwesomeSolid}" Glyph="{x:Static local2:IconFont.Home}" />
</ContentPage.IconImageSource>
| {
"pile_set_name": "StackExchange"
} |
Q:
How to set the GaussianBlurEffect's object source to bitmap image
I'm using Win2D and i want to make a blur effect to an image, however i can't set the source of the blur effect to an image.
GaussianBlurEffect blur = new GaussianBlurEffect();
blur.Source = // cants accept a bitmap image
blur.BlurAmount = 10.0f;
args.DrawingSession.DrawImage(blur);
A:
As the doc provided by @IInspectable, the source of GaussianBlurEffect should be ICanvasImage type instead of a BitmapImage.
There are several methods to load a CanvasImage, for example directly load from a file:
var image = await CanvasBitmap.LoadAsync(sender, "Assets/miao4.jpg");
GaussianBlurEffect blur = new GaussianBlurEffect();
blur.Source = image;
blur.BlurAmount = 10.0f;
args.DrawingSession.DrawImage(blur, 400, 200);
For other methods, you can refer to CanvasBitmap Class.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to improve this python vectorial function
I have a function A whose input is a numpy vector (numpy.ndarray) called x. This function calculates, for each element of x, the sum of that element itself with other elements of x given by a list of those elements.
The following example should illustrate this better:
x = [[2,3], [3,4], [1,2], [1,3], [1,4]] # my input
n = [[1,2,3], [0,4,2], [3,0,1], [0,1,4], [3,1,2]] # list with lists of element to be added for each element in x
So for the first element of x, which is x[0] = [2,3] I have to add the values given by n[0], so those are 1, 2 and 3. I obtain them by x[n[0][0]],x[n[0][1]] and x[n[0][2]].
The expected output for the example should be:
l = [[11, 18], [13, 21], [9, 16], [9, 20], [8, 21]]
The final sum for a element x[i] should be
(x[i] + x[n[i][0]] + x[i] + x[n[i][1]] + x[i] + x[n[i][2]])
The return of the function is the list with each calculated sum.
As this is iterative I move through both lists x and n. The following code achieve this but goes element by element in both lists x and n.
def A(x):
a = []
for i, x_i in enumerate(x):
mysum = np.zeros(2)
for j, n_j in enumerate(n[i]):
mysum = mysum + x_i + x[n_j]
a.append(mysum)
return np.array(a)
I want to make this code more vectorial, but this is my best since some days ago.
Edit: If it is helpful, I always sum 3 values per element, so the sublists of n are always of lenght 3.
A:
(Please see the UPDATE at the end for simpler and faster solution)
This can be done without the for loop, by the technique of broadcasting
def C(x,n):
y = x[n.ravel()-1]
z = y.reshape((-1,3,2))
xx = x[:,np.newaxis,:]
ans = z+xx
ans = ans.sum(axis=1)
return ans
It is atleast 5-6x faster compared to the solution with for loop.
In [98]: np.all(A(x,n)==C(x,n))
Out[98]: True
In [95]: %timeit ans=A(x,n)
10000 loops, best of 3: 153 us per loop
In [96]: %timeit ans=C(x,n)
10000 loops, best of 3: 27 us per loop
UPDATE
Jaime has reduced my 6 lines of code into a simple 1-line code (check comments below), and it is 20% faster too.
ans = 3*x + x[n-1].sum(axis=1)
A:
You can at least remove the inner loop as follows:
def A(x, n):
a = 3 * x
for i in range(len(x)):
a[i] += np.sum(x[np.ix_(n[i]-1)], axis=0)
return a
| {
"pile_set_name": "StackExchange"
} |
Q:
How to sum nodes with XSL?
Hi, I found this, but isn't what I want. I want this output
Driver B 27
Driver A 18
This is the XML:
<grid>
<driver>
<name>Driver B</name>
<points>
<imola>10</imola>
<monza>9</monza>
<silverstone>8</silverstone>
</points>
</driver>
<driver>
<name>Driver A</name>
<points>
<imola>7</imola>
<monza>6</monza>
<silverstone>5</silverstone>
</points>
</driver>
</grid>
And this is the XSLT:
<xsl:template match="/grid">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Championship</title>
</head>
<body>
<h1>Classification</h1>
<xsl:apply-templates select="driver" />
</body>
</html>
</xsl:template>
<xsl:template match="driver">
<xsl:for-each select=".">
<p>
<xsl:value-of select="name" />
<xsl:value-of select="sum(???)" /> <!-- Here, I don't know the code to sum the points of the races-->
</xsl:for-each>
</xsl:template>
I'm sure the solution is easy, but I can't find it. Thanks.
A:
You can do so like this:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://www.w3.org/1999/xhtml">
<xsl:output method="html" indent="yes" omit-xml-declaration="yes"/>
<xsl:template match="/grid">
<html>
<head>
<title>Championship</title>
</head>
<body>
<h1>Classification</h1>
<xsl:apply-templates select="driver" />
</body>
</html>
</xsl:template>
<xsl:template match="driver">
<p>
<xsl:value-of select="concat(name, ' ', sum(points/*))" />
</p>
</xsl:template>
</xsl:stylesheet>
Here, * means "match any child element".
This produces the output:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Championship</title>
</head>
<body>
<h1>Classification</h1>
<p>Driver B 27</p>
<p>Driver A 18</p>
</body>
</html>
| {
"pile_set_name": "StackExchange"
} |
Q:
What is `change` event in Angular 2
What is change event in Angular 2? When is it dispatched and how can I use it?
I. e. what have I subscribed in following code via (change)="update()"?
http://plnkr.co/edit/mfoToOSLU6IU2zr0A8OB?p=preview
import {Component, View, Input, Output, EventEmitter, OnChanges} from '@angular/core'
@Component({
selector: 'inner-component',
template: `
<label><input type="checkbox" [(ngModel)]="data.isSelected"> Selected</label>
`
})
export class InnerComponent {
data = { isSelected: false };
}
@Component({
selector: 'my-app',
template: `
<p><inner-component (change)="update()"></inner-component></p>
<p>The component was updated {{count}} times</p>
`,
directives: [InnerComponent]
})
export class AppComponent {
count = 0;
update() {
++this.count;
}
}
PS: Same question in Russian.
A:
That's event bubbling: change occures on input, then bubbles by dom tree and gets handled on inner-component element. It can be checked by logging an event:
http://plnkr.co/edit/J8pRg3ow41PAqdMteKwg?p=preview
@Component({
selector: 'my-app',
template: `
<p><inner-component (change)="update($event)"></inner-component></p>
<p>The component was updated {{count}} times</p>
`,
directives: [InnerComponent]
})
export class AppComponent {
count = 0;
update($event) {
console.log($event, $event.target, $event.currentTarget);
++this.count;
}
}
A:
The change event notifies you about a change happening in an input field. Since your inner component is not a native Angular component, you have to specifiy the event emitter yourself:
@Component({
selector: 'inner-component',
template: `
<label><input type="checkbox" (change)="inputChange.emit($event)" [(ngModel)]="data.isSelected"> Selected</label>
`
})
export class InnerComponent {
@Output('change') inputChange = new EventEmitter();
data = { isSelected: false };
}
And in your AppComponent you're now receiving the events:
@Component({
selector: 'my-app',
template: `
<p><inner-component (change)="update($event)"></inner-component></p>
<p>The component was updated {{count}} times</p>
`,
directives: [InnerComponent]
})
export class AppComponent {
count = 0;
update(event: any) {
++this.count;
console.log(event);
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Should I edit a picture in a link?
I have been noticing some people upload pictures and embed them in SO and others post a link to the picture in their posts.
What is the preferred way? Should you embed your pictures in SO or create links to your pictures?
If one way is preferred, should we edit posts and fix them to the preferred way of posting pictures?
A:
It's hard to see how making people go to another site to see part of a question or answer would be better, so I always prefer inline images. I'd say edit posts that have links to images to either
put the image inline if it matters to the post, or
remove the link if it doesn't.
A:
If you do inline the picture, be sure to give it a meaningful description. This not only helps people who use screen readers, it also helps everyone if the picture is for some reason not loading (some firewalls block it).
That being said, edits that only change a link to a picture are minor enough that it's wasteful to suggest edits that just do that. In many cases, I would rather add the one character myself (2k+ users can edit without review), especially there are usually other errors that need to be fixed.
To put this bluntly, the queue has been atypically large because you are only changing the picture to be inline. I am going to reject as many of these edits as I can because you are failing to fix the other issues present in each post.
| {
"pile_set_name": "StackExchange"
} |
Q:
Parsing large file with MPI in C++
I have a C++ program in which I want to parse a huge file, looking for some regex that I've implemented. The program was working ok when executed sequentially but then I wanted to run it using MPI.
I started the adaptation to MPI by differentiating the master (the one who coordinates the execution) from the workers (the ones that parse the file in parallel) in the main function. Something like this:
MPI::Init(argc, argv);
...
if(rank == 0) {
...
// Master sends initial and ending byte to every worker
for(int i = 1; i < total_workers; i++) {
array[0] = (i-1) * first_worker_file_part;
array[1] = i * first_worker_file_part;
MPI::COMM_WORLD.Send(array, 2, MPI::INT, i, 1);
}
}
if(rank != 0)
readDocument();
...
MPI::Finalize();
The master will send to every worker an array with 2 position that contains the byte where it will start the reading of the file in position 0 and the byte where it needs to stop reading in position 1.
The readDocument() function looks like this by now (not parsing, just each worker reading his part of the file):
void readDocument()
{
array = new int[2];
MPI::COMM_WORLD.Recv(array, 10, MPI::INT, 0, 1, status);
int read_length = array[1] - array[0];
char* buffer = new char [read_length];
if (infile)
{
infile.seekg(array[0]); // Start reading in supposed byte
infile.read(buffer, read_length);
}
}
I've tried different examples, from writing to a file the output of the reading to running it with different number of processes. What happens is that when I run the program with 20 processes instead of 10, for example, it lasts twice the time to read the file. I expected it to be nearly half the time and I can't figure why this is happening.
Also, in a different matter, I want to make the master wait for all the workers to complete their execution and then print the final time. Is there any way to "block" him while the workers are processing? Like a cond_wait in C pthreads?
A:
In my experience people working on computer systems with parallel file systems tend to know about those parallel file systems so your question marks you out, initially, as someone not working on such a system.
Without specific hardware support reading from a single file boils down to the system positioning a single read head and reading a sequence of bytes from the disk to memory. This situation is not materially altered by the complex realities of many modern file systems, such as RAID, which may in fact store a file across multiple disks. When multiple processes ask the operating system for access to files at the same time the o/s parcels out disk access according to some notion, possibly of fairness, so that no process gets starved. At worst the o/s spends so much time switching disk access from process to process that the rate of reading drops significantly. The most efficient, in terms of throughput, approach is for a single process to read an entire file in one go while other processes do other things.
This situation, multiple processes contending for scarce disk i/o resources, applies whether or not those processes are part of a parallel, MPI (or similar) program or entirely separate programs running concurrently.
The impact is what you observe -- instead of 10 processes each waiting to get their own 1/10th share of the file you have 20 processes each waiting for their 1/20th share. Oh, you cry, but each process is only reading half as much data so the whole gang should take the same amount of time to get the file. No, I respond, you've forgotten to add the time it takes the o/s to position and reposition the read/write heads between accesses. Read time comprises latency (how long does it take reading to start once the request has been made) and throughput (how fast can the i/o system pass the bytes to and fro).
It should be easy to come up with some reasonable estimates of latency and bandwidth that explains the twice as long reading by 20 processes as by 10.
How can you solve this ? You can't, not without a parallel file system. But you might find that having the master process read the whole file and then parcel it out to be faster than your current approach. You might not, you might just find that the current approach is the fastest for your whole computation. If read time is, say, 10% of total computation time you might decide it's a reasonable overhead to live with.
| {
"pile_set_name": "StackExchange"
} |
Q:
json confusion
I have created and Android app that has to communicate with my website using JSON. JSON (on client, Android side) looks like this:
private static String JSONSend(Context ctx, JSONObject obj, String ObjName, String address) {
IHttpDispatcher disp = new HttpDispatcher();
Vector<String> ss = new Vector<String>();
String link = address;
String locale = uzmiLocale(ctx);
if(locale=="")
return "";
try {
obj.put("Lokal", locale);
ss.add(ObjName + obj.toString());
String ID = disp.getHttpResponse_POST(link, ss);
return ID;
} catch (Exception e) {
return "";
}
}
Above method is called from here:
public static String sendReq(Context ctx, String txt, String number) {
JSONObject jsn = new JSONObject();
try {
jsn.put("TextPoruke", txt);
jsn.put("BrTel", number);
return JSONSend(ctx, jsn, "JSNSend=", "www.mysite.com");
} catch (JSONException e1) {
return "";
}
}
Everything works fine on my Wamp server, but after moving my php code to webserver, nightmare started! Apparently, everything is sent the way it should be,but on serverside this php code is creating problems:
if(isset ($_POST['JSNSend']))
{
$argument = $_POST['JSNSend'];
$json = json_decode($argument,true);
$broj = $json['BrTel'];
$jsnLocale = $json['Lokal'];
it seems that result of "json_decode" is NULL, but $argument equals
{"\TextPoruke\": \"sometext\", \"BrTel\":\"111\"}
So passed JSON string seems ok, but for some reason it can't be decoded on webserver. Can anyone help me with this? Why it's not working?
A:
Seems like your JSON got escaped prematurely which triggers a bad syntax error.
If $argument is in the format you state, then the following procedure would work:
<?php
$s = '{"\TextPoruke\": \"sometext\", \"BrTel\":\"111\"}';
echo 'Without stripslashes:' . PHP_EOL;
var_dump( json_decode( $s ) );
echo 'With stripslashes:' . PHP_EOL;
var_dump( json_decode( stripslashes($s) ) );
?>
Result:
Without stripslashes:
NULL
With stripslashes:
object(stdClass)#1 (2) {
["TextPoruke"]=>
string(8) "sometext"
["BrTel"]=>
string(3) "111"
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How should one properly comment and license a set of code files before uploading to the public?
I've written a decent chunk of code over the past few days and I'm ready to git init it and push it to github. But before I do so, I want to do this the "correct" way in case anyone else wants to use my code. So I guess I need to pick a license (probably MIT) and implement it, and write some sort of comment at the top of every file.
What is a good style comment to put at the top of the file? What info should it include, what should it look like? And do I put the license in a LICENSE folder in the root directory, or at the top of every source file or something? And are there any other steps I'm missing before throwing this up to github?
A:
Short 2-line disclaimer should be enough, e.g.
// (c) 2011 Ricket
// This code is licensed under MIT license (see LICENSE.txt for details)
Don't forget that there is not much sense in publishing code if people can't found it, so write good description and readme (who knows when someone would need your code even if nobody comes on project page).
| {
"pile_set_name": "StackExchange"
} |
Q:
Test Android PackageManager.getInstaller()
Maybe I am missing something very obvious here:
I wanted to test the PackageManager.getInstallerPackageName(). When I test my app through eclipse, or even as a standalone apk, the above method returns null as expected. But for users who install through Google Play or Amazon AppStore, the returned value will not be null.
My question is how do I test this before putting my app into production?
(Eg. Is something like this possible: upload a draft in Android Developer Console, and without moving it to production, somehow access it through Google Play, maybe by using a device which is setup with the same account as my Developer Console account; and then install and test it on my test device?)
A:
Updated Answer:
If what you want is to be able to test an actual install from google play then use their Alpha and Beta programs. See here for a description of the program.
Original Answer:
If what you want is to just test your handling of this case, then you can use the BuildConfig.DEBUG flag to give you a dummy value when you are in DEBUG mode.
String installer;
if (BuildConfig.DEBUG) {
installer = "com.android.vending";
} else {
installer = pm.getInstallerPackageNamge(myPackage);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
DDD/CQRS: Combining read models for UI requirements
Let's use the classic example of blog context. In our domain we have the following scenarios: Users can write Posts. Posts must be cataloged at least in one Category. Posts can be described using Tags. Users can comment on Posts.
The four entities (Post, Category, Tag, Comment) are implemented as different aggregates because of I have not detected any rule for that an entity data should interfere in another. So, for each aggregate I will have one repository that represent it. Too, each aggregate reference others by his id.
Following CQRS, from this scenario I have deducted typical use cases that result on commands such as WriteNewPostCommand, PublishPostCommand, DeletePostCommand etc... along with their respective queries to get data from repositories. FindPostByIdQuery, FindTagByTagNameQuery, FindPostsByAuthorIdQuery etc...
Depending on which site of the app we are (backend or fronted) we will have queries more or less complex. So, if we are on the front page maybe we need build some widgets to get last comments, latest post of a category, etc... Queries that involve a simple Query object (few search criterias) and a QueryHandler very simple (a single repository as dependency on the handler class)
But in other places this queries can be more complex. In an admin panel we require to show in a table a relation that satisfy a complex search criteria. Might be interesting search posts by: author name (no id), categories names, tags name, publish date... Criterias that belongs to different aggregates and different repositories.
In addition, in our table of post we dont want to show the post along with author ID, or categories ID. We need to show all information (name user, avatar, category name, category icon etc).
My questions are:
At infrastructure layer, when we design repositories, the search methods (findAll, findById, findByCriterias...), should have return the corresponding entity referencing to all associations id's? I mean, If a have a method findPostById(uuid) or findPostByCustomFilter(filter), should return a post instance with a reference to all categories id it has, all tags id, and author id that it has? Or should my repo have some kind of method that populates a given post instance with the associations I want?
If I want to search posts created from 12/12/2014, written by John, and categorised on "News" and "Videos" categories and tags "sci-fi" and "adventure", and get the full details of each aggregate, how should create my Query and QueryHandler?
a) Create a Query with all my parameters (authorName, categoriesNames, TagsNames, if a want retrive User, Category, Tag association full detailed) and then his QueryHandler ensamble the different read models in a only one. Or...
b) Create different Queries (FindCategoryByName, FindTagByName, FindUserByName) and then my web controller calls them for later
call to FindPostQuery but now passing him the authorid, categoryid, tagid returned from the other queries?
The b) solution appear more clean but it seems me more expensive.
A:
On the query side, there are no entities. You are free to populate your read models in any way suits your requirements best. Whatever data you need to display on (a part of) the screen, you put it in the read model. It's not the command side repositories that return these read models but specialized query side data access objects.
You mentioned "complex search criteria" -- I recommend you model it with a corresponding SearchCriteria object. This object would be technnology agnostic, but it would be passed to your Query side data access object that would know how to combine the criteria to build a lower level query for the specific data store it's targeted at.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I customize dropdown menu in CSS?
http://jsfiddle.net/zcfqu/
Been playing around with this piece of code for a while and am confused a bit.
How do I:
Change the color of the each submenu?
Make the submenu the same width as the main button?
HTML
<ul id="menu">
<li><a href="#">This is the button</a>
<ul class="submenu">
<li><a href="#">Button one</a>
</li>
<li><a href="#">Button two</a>
</li>
<li><a href="#">Button three</a>
</li>
</ul>
</li>
</ul>
A:
Remove all floats and position:absolute
Check this demo
I just removed all floats (which was causing funny jumping of li and really not needed) and position:absolute (which was causing menu to shift sideways)
Also, I didn't read through all your CSS to find which background property is overriding which one, but I just removed them all and added new ones at bottom.
#menu > li { background-color: red; }
#menu > li:hover { background-color: green; }
.submenu li { background-color: blue; }
.submenu li:hover { background-color: yellow; }
EDIT 1
Its a good idea to use CSS shorthands and reduce CSS size and also make it more readable. Also, remove all incorrect CSS and you can also write border-radius: 2px 2px 2px 2px as border-radius: 2px (and save 12 bytes :O)
EDIT 2
CSS shorthands - MDN
font shorthand - W3C
background shorthand - W3C (scroll to the very bottomo of the page)
| {
"pile_set_name": "StackExchange"
} |
Q:
PowerBuilder DSN Creation
I am new to PowerBuilder.
I want to retrieve the data from MSAccess tables and update it to corresponding SQL tables. I am not able to create a permanent DSN for MSAccess because I have to select different MSAccess files with same table information. I can create a permanent DSN for SQL server.
Please help me to create DSN dynamically when selecting the MSAccess file and push all the tables data to SQL using PowerBuilder.
Also give the full PowerBuilder code to complete the problem if its possible.
A:
In Access we strongly suggest not using DSNs at all as it is one less thing for someone to have to configure and one less thing for the users to screw up. Using DSN-Less Connections You should see if PowerBuilder has a similar option.
| {
"pile_set_name": "StackExchange"
} |
Q:
WIX installing files, override
Hi I am installing files into a directory using WIX with the code below.
<Directory Id="CMSICONSDIR" Name="CMSIcons">
<Component Id="CMSICONSDIR_C" Guid="B0328FBF-D9F7-4278-B16C-28650016FF86" SharedDllRefCount="no" KeyPath="no" NeverOverwrite="no" Permanent="no" Transitive="no" Location="either">
<CreateFolder/>
<File Id="AddCamera.png" Name="AddCamera.png" DiskId="1" Source="..\..\OrionVEWorld\bin\Release\CMSICons\AddCamera.png" KeyPath="no" />
<File Id="aldownloadsmall.png" Name="al-download-small.png" DiskId="1" Source="..\..\OrionVEWorld\bin\Release\CMSICons\al-download-small.png" KeyPath="no" />
They way my application works is that a user can copy their own files in that directory overriding with what they prefer.
The problem is when I do my next install for an update, its overrides those files with the files stipulated in the install.
How do I ensure that when I run my install it does not override the existing files that are there and only adds new ones.
Unfortunately in other case I do need files that override what is there.
I do have an upgrade script section which can affect this as below
<Upgrade Id="$(var.UpgradeCode)">
<UpgradeVersion Minimum="$(var.ProductVersion)" OnlyDetect="no" Property="NEWERVERSIONDETECTED"/>
<UpgradeVersion Minimum="1.0.0.0"
IncludeMinimum="yes"
OnlyDetect="no"
Maximum="$(var.ProductVersion)"
IncludeMaximum="no"
Property="PREVIOUSVERSIONSINSTALLED" />
</Upgrade>
Any suggestions is appreciated.
A:
You could try changing the upgrade order by modifing the sequence of RemoveExistingProducts action. You could place it after InstallFinalize (no 4 option in the link article).
Also this article explains how windows installer handles the whole file overwrite logic.
EDIT: Also add the "Never overwrite" attribute to the components.
| {
"pile_set_name": "StackExchange"
} |
Q:
Symfony 5 controller won't validate errors
I am trying to migrate a some parts of a project made with Typescript + Express + Firebase to Symfony 5 and MySQL. But I don't get why the ValidatorInterface isn't working.
When I submit the form with unexpected characters (i.e.: a password with 3 charactesrs) it creates the user despites the validation constraints assigned in the User entity. The only constraint validation that actually works despites it does not show any form errors, is the UniqueEntity.
This is how my controller looks like:
/**
* GET: Display form
* POST: Creates a user
*
* @Route("/users/crear", name="create_user", methods={"GET", "POST"})
*/
public function create_user(Request $request, EntityManagerInterface $entityManager, ValidatorInterface $validator)
{
$user = new User();
// Form
if ($request->isMethod('GET')) {
$form = $this->createForm(CrearUserType::class, $user);
return $this->render('user/create.html.twig', [
'form' => $form->createView(),
'errors' => []
]);
}
// Form submit
$data = $request->request->get('create_user');
$errors = [];
$user->setName($data['name']);
$user->setEmail($data['email']);
$user->setPassword($data['password']);
$user->setCreatedAt(new \DateTime());
$user->setUpdatedAt(new \DateTime());
$form = $this->createForm(CrearUserType::class, $user);
// Entity validation
$errors = $validator->validate($user);
if (count($errors) > 0) { // This is always 0
$user->setPassword('');
return $this->render('user/create.html.twig', [
'form' => $form->createView(),
'user' => $user,
'errors' => $errors
]);
}
try {
$user->setPassword(password_hash($user->getPassword(), PASSWORD_BCRYPT));
$entityManager->persist($user);
$entityManager->flush();
$this->addFlash(
'success',
'User '.$user->getName().' has been saved.'
);
return $this->redirectToRoute('users');
} catch(\Exception $exception) {
$user->setPassword('');
$this->addFlash(
'error',
'Server error: ' . $exception->getMessage()
);
return $this->render('user/create.html.twig', [
'form' => $form->createView(),
'user' => $user,
'errors' => $errors
]);
}
}
And this is my entity:
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* @ORM\Entity(repositoryClass="App\Repository\UserRepository")
* @UniqueEntity("email")
*/
class User
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
* @Assert\NotBlank(message="Name is mandatory")
*/
private $name;
/**
* @ORM\Column(type="string", length=255, unique=true)
* @Assert\NotBlank(message="Email is mandatory")
* @Assert\Email(
* message="Invalid email address"
* )
*/
private $email;
/**
* @ORM\Column(type="string", length=60)
* @Assert\NotBlank(message="Password is mandatory")
* @Assert\GreaterThanOrEqual(
* value=6,
* message="The password has to be at least 6 chars long"
* )
*/
private $password;
/**
* @ORM\Column(type="date")
*/
private $createdAt;
/**
* @ORM\Column(type="date")
*/
private $updatedAt;
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
public function getPassword(): ?string
{
return $this->password;
}
public function setPassword(?string $password): self
{
$this->password = $password;
return $this;
}
public function getCreatedAt(): ?\DateTimeInterface
{
return $this->createdAt;
}
public function setCreatedAt(\DateTimeInterface $createdAt): self
{
$this->createdAt = $createdAt;
return $this;
}
public function getUpdatedAt(): ?\DateTimeInterface
{
return $this->updatedAt;
}
public function setUpdatedAt(\DateTimeInterface $updatedAt): self
{
$this->updatedAt = $updatedAt;
return $this;
}
}
So, any clues on what is wrong here?
A:
I'm not sure of my response, because I never handle request with a ValidatorInterface. I use the handlerequest method provided by controller.
You created the form
$form = $this->createForm(CrearUserType::class, $user);
But you forgot to handle request
$form->handleRequest($request);
So your form does not validate data forwarded by request. Try to add this line just after the $form creation. Then, you can test that the user entity is valid with
if ($form->isValid()) {
//no errors
}
//error exists
| {
"pile_set_name": "StackExchange"
} |
Q:
Sync android map with a SQLite database on a server
I created an SQLite database for my android map application that keeps user's favorite markers using this tutorial,
now I want to create another same database that allows users to share some markers with others who uses this app, so I need to upload my database on a server and sync it with my app and restore shared markers.
which server can I use that keeps my database in SQL not in JSON.
how can I sync my app with my uploaded database?
A:
I would not recommend to talk directly to your remote database, because you have to store the authentication credentials inside the app and its pretty easy to reverse engineer your app and get this credentials.
I would recommend you to write a small service/API with 2 endpoints. One endpoint to get all the markers available and the other one to store the markers.
The communication with your API you can handle with e.g. Retrofit. You store the markers via your POST call. With the GET call you get all the markers available in the database. Then you can store the response got from the call inside the users local database.
UPDATE:
REST API with NodeJS and MongoDB
Retrofit Tutorial
| {
"pile_set_name": "StackExchange"
} |
Q:
RoR ActiveRecord save method
Im new to Rails, im trying to execute the save method within an ActionController's Create method multiple times to insert multiple values
def create
@pin = Pin.new(params[:pin])
i = 1
while i < 10
if @pin.save
end
end
redirect_to @pin
end
This works but only inserts one record
there's no Contraints that enforces uniqueness of Records in my Database.
Please how do i correct this?
A:
One AR objects maps to one row. You need to create new object for each row you want added.
Something like that:
10.times do
pin = Pin.new(params[:pin])
pin.save
end
or
10.times do
Pin.create(params[:pin]
end
create method creates an AR object and saves it in the database.
However, you cannot redirect to 10 objects.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to close a RadWindow from a RadButton
The close button on the RadWindow works fine!!!
But I'd like to add a custom RadButton with "Close" that does the same thing....close the RadWindow in .NET (VB or C#)
Is this possible?
Thanks all.....
A:
I am assuming that the technology you are talking is ASP.NET.
With that assumption i want to point you to this demo we have on our RadControls for ASP.NET Ajax control suite. This demo showcases the scenario you are looking out for. The rad window contains a button inside the window, which when clicked will close the rad window. here is the link to the demo:
http://demos.telerik.com/aspnet-ajax/window/examples/clientsideevents/defaultcs.aspx?product=window
Same scenario in ASP.NET MVC is having the following demo:
http://demos.telerik.com/aspnet-mvc/window/clientsideapi
Hope this answers your quesiton. Do let me know if this solved your problem
Lohith (Tech Evangelist, Telerik India)
| {
"pile_set_name": "StackExchange"
} |
Q:
VBA unique values count along with sheet name
Hello I am trying to go through each sheet in my workbook and print the name of the sheet along with each of the unique items and a count of them. But I am getting an error, please help.
This is a broad example of the result I am trying to achieve, right now I have the commented out.
"Sheet1" Dan 2
"Sheet1" Bob 23
"Sheet1" Mark 1
"Sheet2" Ban 3
"Sheet2" Dan 2
I get an error with this line:
Sheets("Summary").Range(NextRowB).Resize(dict.Count - 1, 1).Value = ActiveSheet.Name
Sub summaryReport()
Dim dict As Object
Set dict = CreateObject("scripting.dictionary")
Dim varray As Variant, element As Variant
For Each ws In ThisWorkbook.Worksheets
varray = ActiveSheet.Range("B:B").Value
'Generate unique list and count
For Each element In varray
If dict.exists(element) Then
dict.Item(element) = dict.Item(element) + 1
Else
dict.Add element, 1
End If
Next
NextRowB = Range("B" & Rows.Count).End(xlUp).Row + 1
NextRowC = Range("C" & Rows.Count).End(xlUp).Row + 1
Sheets("Summary").Range(NextRowB).Resize(dict.Count - 1, 1).Value=ActiveSheet.Name
Sheets("Summary").Range(NextRowC).Resize(dict.Count, 1).Value = _WorksheetFunction.Transpose(dict.keys)
'Sheets("Summary").Range("D3").Resize(dict.Count, 1).Value = _
WorksheetFunction.Transpose(dict.items)
Next ws
End Sub
A:
Rather than using a dictionary this code uses a temporary sheet and formula.
The names are copied from each sheet, the duplicates removed and then a COUNTIF formula is applied to make the count.
The final figures are then copied and the values pasted into column A of the temporary sheet.
Sub Test()
Dim wrkSht As Worksheet
Dim tmpSht As Worksheet
Dim rLastCell As Range
Dim rTmpLastCell As Range
Dim rLastCalculatedCell As Range
'Add a temporary sheet to do calculations and store the list to be printed.
Set tmpSht = ThisWorkbook.Worksheets.Add
'''''''''''''''''''''''''''''''''''''''
'Comment out the line above, and uncomment the next two lines
'to print exclusively to the "Summary" sheet.
'''''''''''''''''''''''''''''''''''''''
'Set tmpSht = ThisWorkbook.Worksheets("Summary")
'tmpSht.Cells.ClearContents
For Each wrkSht In ThisWorkbook.Worksheets
With wrkSht
'Decide what to do with the sheet based on its name.
Select Case .Name
Case tmpSht.Name
'Do nothing
Case Else 'Process sheet.
Set rLastCell = .Cells(.Rows.Count, 2).End(xlUp)
'tmpSht.Columns(4).Resize(, 3).ClearContents
'Copy names to temp sheet and remove duplicates.
.Range(.Cells(1, 2), rLastCell).Copy Destination:=tmpSht.Cells(1, 5)
tmpSht.Columns(5).RemoveDuplicates Columns:=1, Header:=xlNo
'Calculate how many names appear on the sheet and place sheet name
'to left of people names.
Set rTmpLastCell = tmpSht.Cells(Rows.Count, 5).End(xlUp)
tmpSht.Range(tmpSht.Cells(1, 5), rTmpLastCell).Offset(, 1).FormulaR1C1 = _
"=COUNTIF('" & wrkSht.Name & "'!R1C2:R" & rLastCell.Row & "C2,RC[-1])"
tmpSht.Range(tmpSht.Cells(1, 5), rTmpLastCell).Offset(, -1) = wrkSht.Name
'Find end of list to be printed.
Set rLastCalculatedCell = tmpSht.Cells(Rows.Count, 1).End(xlUp).Offset(1)
'Copy columns D:F which contain the sheet name, person name and count.
'Paste at the end of column A:C
tmpSht.Range(tmpSht.Cells(1, 4), rTmpLastCell).Resize(, 3).Copy
rLastCalculatedCell.PasteSpecial xlPasteValues
'Clear columns D:F
tmpSht.Columns(4).Resize(, 3).ClearContents
End Select
End With
Next wrkSht
End Sub
| {
"pile_set_name": "StackExchange"
} |
Q:
Android: Install ADT locally
I have already had the necessary ADT plugins for Android programming in Eclipse.
(Eclipse Java EE IDE for Web Developers.
Version: Kepler Service Release 1
Build id: 20130919-0819)
I know the common way to install them is this link
(to download and install them), but i am curious about installing them when they are exist in my local machine?
Thanks
A:
You should download from Android developer site http://developer.android.com/sdk/installing/installing-adt.html#Troubleshooting,
e.g. ADT-22.2.1
| {
"pile_set_name": "StackExchange"
} |
Q:
Do while error control for Excel VBA Import
I'm using the following code to import all CSV files from D:\Report into Excel with each file on a new Sheet with the name of the file as the sheet name.
I'm looking to include some error control to allow the code to be run a second time if a file was not in the Report directory. The current problem is that the code will run again but bombs out as you cannot have the same name for two sheets and I dont want the same files imported again.
Sub ImportAllReportData()
'
' Import All Report Data
' All files in D:\Report will be imported and added to seperate sheets using the file names in UPPERCASE
'
Dim strPath As String
Dim strFile As String
'
strPath = "D:\New\"
strFile = Dir(strPath & "*.csv")
Do While strFile <> ""
With ActiveWorkbook.Worksheets.Add
With .QueryTables.Add(Connection:="TEXT;" & strPath & strFile, _
Destination:=.Range("A1"))
.Parent.Name = Replace(UCase(strFile), ".CSV", "")
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End With
strFile = Dir
Loop
End Sub
Any help would be greatly appreciated
A:
Use the following function to test if a WS already exists:
Function SheetExists(strShtName As String) As Boolean
Dim ws As Worksheet
SheetExists = False 'initialise
On Error Resume Next
Set ws = Sheets(strShtName)
If Not ws Is Nothing Then SheetExists = True
Set ws = Nothing 'release memory
On Error GoTo 0
End Function
Use it in your code like this:
....
strPath = "D:\New\"
strFile = Dir(strPath & "*.csv")
Do While strFile <> ""
If Not SheetExists(Replace(UCase(strFile), ".CSV", "")) Then
With ActiveWorkbook.Worksheets.Add
With .QueryTables.Add(Connection:="TEXT;" & strPath & strFile, _
.....
End If
| {
"pile_set_name": "StackExchange"
} |
Q:
How to initialize 2D list of custom class objects - Java
I am trying to create a 2D array of objects but getting this error:
array required, but List<List<TransitionObject>> found
----
This is my TransitionObject Class:
public class TransitionObject {
public char character;
public int state;
TransitionObject(char character, int state)
{
this.character=character;
this.state=state;
}
}
and this is my main class code:
List<List<TransitionObject>> liist = new ArrayList<List<TransitionObject>>();
liist.add(new ArrayList<TransitionObject>());
liist[0].add(new TransitionObject('a',1));
liist[0].add(new TransitionObject('b',3));
I am getting this error when I try to add an object to my list. Solution with a short example would be nice. Thanks !
A:
liist[0].add(new TransitionObject('a',1));
is wrong. liist is no array.
if you need the first element from a List use get()
liist.get(0).add(new TransitionObject('a',1));
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.