text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Where does android.hardware.camera2.full come from?
I am trying to implement a camera app. and checking examples. Some examples contain following manifest feature: uses-feature android:name="android.hardware.camera2.full.
I have checked official documents and google examples and none of them mentioning existing this feature. (or I am missing some).
What is the source of this feature and what is the difference between android.hardware.camera?
Edit:
What confuses me was those examples on googlesamples:
https://github.com/googlesamples/android-Camera2Basic/blob/master/kotlinApp/Application/src/main/AndroidManifest.xml
and this
https://github.com/googlesamples/android-Camera2Basic/blob/master/Application/src/main/AndroidManifest.xml
and this
https://github.com/googlesamples/android-Camera2Raw/blob/master/Application/src/main/AndroidManifest.xml
They are using new Camera2 API and old manifest features. I don't know how both fits together.
A:
The feature flags and the names of the camera APIs aren't actually related, even though they look the same.
The feature "android.hardware.camera" (PackageManager.FEATURE_CAMERA) means that the device has a back-facing camera. That's all; any app that wants to avoid being installed on a device with no back-facing camera needs to list that one.
It's not related to the Java android.hardware.Camera class.
The feature "android.hardware.camera.level.full" (PackageManager.FEATURE_CAMERA_LEVEL_FULL) says that at least one camera on the device supports the FULL hardware level when used via the android.hardware.camera2 API package.
So a device with a back-facing camera always lists "android.hardware.camera". If it's got a good camera, it'll also list "android.hardware.camera.level.full".
Since the sample apps for camera2 are meant to run on any quality of camera, they only require there to be a camera device, not that it has any particular level of capability.
I've seen some developers try to require a feature like "android.hardware.camera2"; there's no such feature defined in the Android SDK, so trying to require it means your app can't be installed on any device. The camera2 API is always available starting from Android 5.0 (Lollipop); it's just a question of what hardware level each camera device supports (LEGACY, LIMITED, FULL, or LEVEL_3).
A:
As always, it's best to look in Android source code itself:
* A given camera device may provide support at one of two levels: limited or
* full. If a device only supports the limited level, then Camera2 exposes a
* feature set that is roughly equivalent to the older
* {@link android.hardware.Camera Camera} API, although with a cleaner and more
* efficient interface. Devices that implement the full level of support
* provide substantially improved capabilities over the older camera
* API. Applications that target the limited level devices will run unchanged on
* the full-level devices; if your application requires a full-level device for
* proper operation, declare the "android.hardware.camera2.full" feature in your
* manifest.</p>
I hope that clarifies the nature of the feature you mentioned.
As for the camera2 apis - those were introduced in Android 5 (api level 21) as an attempt to create cleaner apis for interaction with the camera as opposed to the old camera api.
A:
Android introduced Camera2 api since Android API 21, this new Camera api makes it more usable and easy to change parameters. The previous version was more limited in its capabilities.
Android Camera2 has 4 levels of implementations that depends on the manufacturer:
Legacy: Its just a conversion between Camera2 and Camera. Just used for compatibility. Just some things of Camera2 work properly.
Limited: Has Camera2 implementation, but not all the methods that are available. (Not all manufacturers implement the same methods so not everything will work on every device)
Full: All methods of Camera2 are implemented. Usually manufacturers implement this on their flagship devices.
Level 3: Additionally support YUV reprocessing and RAW image capture. (BEST CASE)
source here and personal experience.
| {
"pile_set_name": "StackExchange"
} |
Q:
Trecho de código em Try
Estava fazendo correções numa classe e me deparei com o seguinte código, não sabia que isso era possível e nunca parei para pensar, mas por que isto é válido? Me refiro a primeira linha do Try. Para mim try/catch sempre foi no formato:
try{
...
}catch(Exception e){
...
}
O seguinte código é a mesma coisa que escrever na "sintaxe" acima?
try (FileInputStream fs = new FileInputStream(templateFile)) {
Workbook wb = write(validation, WorkbookFactory.create(fs), planilha);
File file = relatorioPlanilhaDAO.exportSheet(planilha.getNomeHash());
FileOutputStream fout = new FileOutputStream(file);
if (wb != null) {
wb.write(fout);
} else {
Log.error(this, "Erro ao escrever no arquivo.");
throw new InternalServerErrorException("Erro ao exportar relatório.");
}
fout.flush();
fout.close();
return file;
} catch (IOException e) {
Log.info(this, "Erro ao obter planilha.", e);
throw new NotFoundException("Erro ao exportar planilha.", e);
} catch (InvalidFormatException | IllegalArgumentException e) {
Log.error(this, "Formato de planilha inválido.", e);
throw new InternalServerErrorException("Formato de planilha inválido.", e);
}
A:
Não é a mesma coisa.
O segundo se trata de um try with resources, introduzido no Java 7, que resumidamente é um try que declara um objeto AutoCloseable, no seu caso um FileInputStream. Isso quer dizer que havendo falha ou não, a FileInputStream será fechada automaticamente.
Seria semelhante se o primeiro código fosse assim:
try{
...
FileInputStream fs = new FileInputStream(templateFile);
}catch(Exception e){
...
}
finally {
fs.close();
}
Você mesma pode criar seu objeto AutoCloseable, bastando implementar esta classe ou a Closeable.
Um bom artigo em português para entender melhor pode ser visto aqui: http://blog.globalcode.com.br/2011/10/o-novo-try-no-java-7-por-uma-linguagem.html
| {
"pile_set_name": "StackExchange"
} |
Q:
how to install curl in latest python?
When I'm googling everywhere it is pointed to http://pycurl.sourceforge.net/
but when I try to install this package I get :
d:\pycurl>setup.py -install d:\curl\
File "d:\pycurl\setup.py", line 58
print "FATAL: bad directory %s in environment variable %s" % (dir, envvar)
^
SyntaxError: invalid syntax
A:
The package is not compatible with Python 3; you'll have to request the author ports it. There is an existing patch you could try out.
In the meantime, look into other libraries instead, the requests library does support Python 3 and has a far superior API to pycurl.
| {
"pile_set_name": "StackExchange"
} |
Q:
Selecting a property from JSON
I have a JSON similar to this one:
{"request":
{"Target":"Affiliate_Offer","Format":"json","Service":"HasOffers","Version":"2","NetworkId":"adattract","Method":"getPayoutDetails","api_key":"bd2e82f029c50b582db85868b7c0b8ab99d095886ab079f87b464bb68486c891","offer_id":"9463"},"response":
{"status":1,"httpStatus":200,"data":{"offer_payout":
{"payout":"0.820"}},"errors":[],"errorMessage":null}}
And I want to select only value of payout which is 0.820.
Here what I try
<?php
include 'db.php';
$result = mysql_query("SELECT * FROM ada WHERE require_approval='0' ORDER BY i2 ASC LIMIT 0,10") or die(mysql_error());
// keeps getting the next row until there are no more to get
while ($row = mysql_fetch_array($result)) {
echo "<div>";
$r = $row['id'];
$ri = $row['i2'];
// $ri contains no. 1 2 3 4 5..//
$json = '';
}
$mydata = json_decode($json, true);
$data = $mydata["response"]["data"];
$pay = $data[$ri]["offer_payout"][payout];
echo "</div>";
mysql_query("INSERT INTO thumb(img,id) VALUES('$nth','$oid')");
echo $pay; //output of 0.8200 but not work plz here i need help//
}
?>
A:
In the vain of 'Give a man a fish and he will feed his family for a day. Teach a man to fish and he will feed his family forever' here is how you find out what a json object looks like.
$json = '{"request":
{"Target":"Affiliate_Offer","Format":"json","Service":"HasOffers","Version":"2","NetworkId":"adattract","Method":"getPayoutDetails","api_key":"bd2e82f029c50b582db85868b7c0b8ab99d095886ab079f87b464bb68486c891","offer_id":"9463"},"response":
{"status":1,"httpStatus":200,"data":{"offer_payout":
{"payout":"0.82000"}},"errors":[],"errorMessage":null}}';
$mydata = json_decode($json,true);
print_r($mydata);
Will output this :-
Array
(
[request] => Array
(
[Target] => Affiliate_Offer
[Format] => json
[Service] => HasOffers
[Version] => 2
[NetworkId] => adattract
[Method] => getPayoutDetails
[api_key] => bd2e82f029c50b582db85868b7c0b8ab99d095886ab079f87b464bb68486c891
[offer_id] => 9463
)
[response] => Array
(
[status] => 1
[httpStatus] => 200
[data] => Array
(
[offer_payout] => Array
(
[payout] => 0.82000
)
)
[errors] => Array
(
)
[errorMessage] =>
)
)
And now you know how to address any and all fields
So the field you want will be
$pay = $mydata["response"]["data"]["offer_payout"]["payout"];
Now you decided to convert a JSON Object to an array, there is no need to do that, and in some ways an object is even easier to address and uses less key strokes than an array.
So leave the ,true out of the json_decode and you get this
$json = '{"request":
{"Target":"Affiliate_Offer","Format":"json","Service":"HasOffers","Version":"2","NetworkId":"adattract","Method":"getPayoutDetails","api_key":"bd2e82f029c50b582db85868b7c0b8ab99d095886ab079f87b464bb68486c891","offer_id":"9463"},"response":
{"status":1,"httpStatus":200,"data":{"offer_payout":
{"payout":"0.82000"}},"errors":[],"errorMessage":null}}';
$mydata = json_decode($json);
print_r($mydata);
Which outputs :-
stdClass Object
(
[request] => stdClass Object
(
[Target] => Affiliate_Offer
[Format] => json
[Service] => HasOffers
[Version] => 2
[NetworkId] => adattract
[Method] => getPayoutDetails
[api_key] => bd2e82f029c50b582db85868b7c0b8ab99d095886ab079f87b464bb68486c891
[offer_id] => 9463
)
[response] => stdClass Object
(
[status] => 1
[httpStatus] => 200
[data] => stdClass Object
(
[offer_payout] => stdClass Object
(
[payout] => 0.82000
)
)
[errors] => Array
(
)
[errorMessage] =>
)
)
Now the field you want to address is :-
$pay = $mydata->response->data->offer_payout->payout;
A:
You can get values from the json as like that:
// your json
$json = '{"request":
{"Target":"Affiliate_Offer","Format":"json","Service":"HasOffers","Version":"2","NetworkId":"adattract","Method":"getPayoutDetails","api_key":"bd2e82f029c50b582db85868b7c0b8ab99d095886ab079f87b464bb68486c891","offer_id":"9463"},"response":
{"status":1,"httpStatus":200,"data":{"offer_payout":
{"payout":"0.82000"}},"errors":[],"errorMessage":null}}';
// json_decode() function with second param true for array format
$json_decoded = json_decode($json,true);
echo $json_decoded['response']['data']['offer_payout']['payout']; //0.82000
How can you get this in your code?
You just need to change these two lines in your code:
$data = $mydata["response"]["data"];
$pay = $data["offer_payout"]['payout']; //0.82000
| {
"pile_set_name": "StackExchange"
} |
Q:
Oracle database schema
How to get an Oracle database schema? How to get all table names and columns in those tables and any foreign keys?
A:
How to get all table names
There is a lot you are asking here but this will work for tables from schema:
SELECT *
FROM DBA_OBJECTS
WHERE OBJECT_TYPE = 'TABLE'
AND OWNER = 'SCHEMA_NAME'
This will also work:
SELECT *
FROM DBA_OBJECTS
WHERE OBJECT_TYPE = 'TABLE';
but it will return a lot of sys and system owned table names you do not want to see I think... or do you ? Your question is not so clear...
In the column called OBJECT_NAME are the names of the tables:
SELECT OBJECT_NAME
FROM DBA_OBJECTS
WHERE OBJECT_TYPE = 'TABLE';
and any foreign keys?
I have found this great query here:
List of foreign keys and the tables they reference
SELECT a.table_name, a.column_name, a.constraint_name, c.owner,
-- referenced pk
c.r_owner, c_pk.table_name r_table_name, c_pk.constraint_name r_pk
FROM all_cons_columns a
JOIN all_constraints c ON a.owner = c.owner
AND a.constraint_name = c.constraint_name
JOIN all_constraints c_pk ON c.r_owner = c_pk.owner
AND c.r_constraint_name = c_pk.constraint_name
WHERE c.constraint_type = 'R'
AND a.table_name = 'YOUR_TABLE_NAME';
I believe you now know what is the deal and how to find other things you need. Do go to the link I have mentioned here and research other answers here also...
Note
If you by any chance are not getting any results from your query's first make sure you have entered your table/schema/.../object names in capital letters like this:
AND a.table_name = 'YOUR_TABLE_NAME';
AND OWNER = 'SCHEMA_NAME'
Or if you do not want to think about it you can TURN THEM ALL TO CAPITAL LETTER STRINGS WITH UPPER:
AND UPPER(OWNER) = UPPER('SCHEMA_NAME')
| {
"pile_set_name": "StackExchange"
} |
Q:
An awful factorisation question.
If $a+b+c = 0$ show that $$(2a-b)^3 + (2b-c)^3 + (2c-a)^3 = 3 (2a-b)(2b-c)(2c-a)$$
I have tried substituting the values but it gets too complicated.
Can anyone please help with the method? I have been trying for 30 minutes.
Thanks!
A:
Let $x=2a-b$, $y=2b-c$, and $z=2c-a$. Then $x+y+z=0$, so $LHS=x^3+y^3+z^3=x^3+y^3+(-x-y)^3=3xy(-x-y)=3xyz=RHS$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python SyntaxError: invalid syntax end=''
I am studying the book "Head First Python" and I'm having trouble this code:
data = open('sketch.txt')
for each_line in data:
(role, line_spoken) = each_line.split(':')
print(role, end='')
print(' said: ', end='')
print(line_spoken, end='')
data.close()
Error:
File "Aula 3.py", line 12
print(role, end='')
^
SyntaxError: invalid syntax
sketch.txt:
Man: Is this the right room for an argument?
Other Man: I've told you once.
Man: No you haven't!
Other Man: Yes I have.
Man: When?
Other Man: Just now.
Man: No you didn't!
Other Man: Yes I did!
Man: You didn't!
Other Man: I'm telling you, I did!
Man: You did not!
Other Man: Oh I'm sorry, is this a five minute argument, or the full half hour?
Man: Ah! (taking out his wallet and paying) Just the five minutes.
Other Man: Just the five minutes. Thank you.
Other Man: Anyway, I did.
Man: You most certainly did not!
Other Man: Now let's get one thing quite clear: I most definitely told you!
Man: Oh no you didn't!
Other Man: Oh yes I did!
Man: Oh no you didn't!
Other Man: Oh yes I did!
Man: Oh look, this isn't an argument!
(pause)
Other Man: Yes it is!
Man: No it isn't!
I'm two days trying to figure out why the code is not working. The error is always shown in "end =''".
A:
It seems like you're using Python 2.x, not Python 3.x.
Check your python version:
>>> import sys
>>> sys.version
'2.7.5 (default, May 15 2013, 22:44:16) [MSC v.1500 64 bit (AMD64)]'
>>> print(1, end='')
File "<stdin>", line 1
print(1, end='')
^
SyntaxError: invalid syntax
In Python 3.x, it should not raise Syntax Error:
>>> import sys
>>> sys.version
'3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:06:53) [MSC v.1600 64 bit (AMD64)]'
>>> print(1, end='')
1>>>
A:
>>> import sys
>>> print(sys.version)
2.7.8 (default, Jun 30 2014, 16:08:48) [MSC v.1500 64 bit (AMD64)]
>>> from __future__ import print_function
>>> print(1, end=',')
1,
A:
If you're running it from the command line you may also just need to use the python3 command instead of just python command such as:
python3 MyFile.py
| {
"pile_set_name": "StackExchange"
} |
Q:
Mysteriously fails to compile when I comment a line
I set up a github repo with a not-so minimal working environment (sorry for that).
As the README at github says, uncommenting the following stupid line solves the problem and makes the diplomadolgozat.tex file compilable.
%\begin{figure}[h]\end{figure}
There are other lines which when deleted make the compiler happy, but it's all unpredictable. Until now everything was fine, but this error made my whole writing process unstable: I no longer know when will it break again and when it breaks, why.
If you have some time for it, clone the github repo, see it for yourself.
A:
Nearly any modification which change page breaks will make the error go away, so it seems to me that there is a problem if a page break occurs inside a listing, and there is a pending floating environment. (I was able to strip down your document to a far smaller example document which still shows the error, see below.)
But the main reason for the trouble seems to be the version 1.5b of magyar.ldf inside your document folder. When using the version v1.4j provided by TeXlive 2011 instead, the error will go away, too, and I was not able to get the error back by changing content of the document.
So it seems that the version 1.5b of magyar.ldf is having at least one bug. Here is an example document still showing the error when using v1.5b of magyar.ldf:
\begin{filecontents}{compiler.clj}
;;{antIfStar}
(defn ant-if* [kond true-branch false-branch]
{:pre [(every? node? [kond true-branch false-branch])
(binary-node? kond)]
:post [(node? %)]}
(let [[t-node f-node] (mark-branches true-branch
false-branch)
ztrue (to-ztree t-node)
zkond (to-ztree kond)]
(->> f-node
(insert-at-the-bottom ztrue ,,,)
(insert-under-a-jump-to-true-label zkond ,,,))))
;;{end}
\end{filecontents}
\documentclass[12pt,a4paper,oneside]{report}
\usepackage[utf8]{inputenc}
\def\magyarOptions{defaults=hu-min}
\usepackage[magyar]{babel}
\usepackage{anysize}
\marginsize{2.5cm}{2cm}{1.5cm}{1.5cm}
\usepackage[demo]{graphicx}
\linespread{1.3}
\usepackage{listings}
\begin{document}
\begin{verbatim}
(ant-if (sense :ahead :foe) ; feltétel
(turn :left) ; igaz ág
(turn :right)) ; hamis ág
\end{verbatim}
\begin{figure}
\centering
\includegraphics[bb=0 0 227 345,scale=0.85]{a.png}
\caption{\texttt{(turn :right)}}
\label{antSenseAFoe}
\end{figure}
A \verb|Sense Ahead| csúcsnak két \verb|"jump" UnaryNode| gyermeke van. Ha a \verb|Sense Ahead| feltétele igaz, tehát ha előttem egy ellenséges hangya áll, akkor a baloldali \verb|"jump" :next| értelmében a következő utasításon kell folytatnom, ami a [T1] címkével jelölt \emph{Turn Left}. Ha a feltétel nem igaz, tehát ha nincs előttem ellenség, akkor jobboldali \verb|"jump" F1| -- aminek a \verb|:target| mezőjében F1 szerepel -- az [F1] címkéjű \emph{Turn Right} utasításra irányít.
A \verb|Sense Ahead| csúcsnak két \verb|"jump" UnaryNode| gyermeke van. Ha a \verb|Sense Ahead| feltétele igaz, tehát ha előttem egy ellenséges hangya áll, akkor a baloldali \verb|"jump" :next| értelmében a következő utasításon kell folytatnom, ami a [T1] címkével jelölt \emph{Turn Left}. Ha a feltétel nem igaz, tehát ha nincs előttem ellenség, akkor jobboldali \verb|"jump" F1| -- aminek a \verb|:target| mezőjében F1 szerepel -- az [F1] címkéjű \emph{Turn Right} utasításra irányít.
A \verb|Sense Ahead| csúcsnak két \verb|"jump" UnaryNode| gyermeke van. Ha a \verb|Sense Ahead| feltétele igaz, tehát ha előttem egy ellenséges hangya áll, akkor a baloldali \verb|"jump" :next| értelmében a következő utasításon kell folytatnom, ami a [T1] címkével jelölt \emph{Turn Left}. Ha a feltétel nem igaz, tehát ha nincs előttem ellenség, akkor jobboldali \verb|"jump" F1| -- aminek a \verb|:target| mezőjében F1 szerepel -- az [F1] címkéjű \emph{Turn Right} utasításra irányít.
A \verb|Sense Ahead| csúcsnak két \verb|"jump" UnaryNode| gyermeke van. Ha a \verb|Sense Ahead| feltétele igaz, tehát ha előttem egy ellenséges hangya áll, akkor a baloldali \verb|"jump" :next| értelmében a következő utasításon kell folytatnom, ami a [T1] címkével jelölt \emph{Turn Left}. Ha a feltétel nem igaz, tehát ha nincs előttem ellenség, akkor jobboldali \verb|"jump" F1| -- aminek a \verb|:target| mezőjében F1 szerepel -- az [F1] címkéjű \emph{Turn Right} utasításra irányít.
Az \verb|ant-if| csak annyit csinál, hogy
\lstinputlisting[linerange=antIfStar-end]{compiler.clj}
\end{document}
A:
Jake and Andrey, you are totally right.
After getting some sleep and a somehow cleaner head, I tried to minify my master document. Commenting out the \def\magyarOptions{defaults=hu-min} line solved the problem.
I hope that was the real problem, and I hope I solved it permanently. If not, I just continue minifying it until I arrive to a MWE.
| {
"pile_set_name": "StackExchange"
} |
Q:
NHibernate with or without Repository
There are several similar questions on this matter, by I still haven't found enough reasons to decide which way to go.
The real question is, is it reasonable to abstract the NHibernate using a Repository pattern, or not?
It seems that the only reason behind abstracting it is to leave yourself an option to replace NHibernate with a different ORM if needed. But creating repositories and abstracting queries seems like adding yet another layer, and doing much of the plumbing by hand.
One option is to use expose IQueryable<T> to the business layer and use LINQ, but from my experience LINQ support is still not fully implemented in NHibernate (queries simply don't always work as expected, and I hate spending time on debugging a framework).
Although referencing NHibernate in my business layer hurts my eyes, it is supposed to be an abstraction of data access by itself, right?
What are you opinions on this?
A:
Good quiestions. I was also thinking about them a few days ago.
Actually, try out NHibernate 3.0 alpha (or the current trunk), its new LINQ provider is much greater than the previous ones. (So far I only found one method which is not working, but it is possible to hook in your own mechanism if you run into something it doesn't support by default.)
I had no problems (yet?) with using the current trunk. You can find a "nightly" build on the http://www.hornget.net/packages/ site, along with a FluentNHibernate build against it. Fluent really increases your productivity if you know how to use it. The SO community really helped me with that, too.
If you are okay with your business layer having a direct dependency on NHibernate, or you are writing a smaller application which remains maintainable without this kind of abstraction, you're good to go without the repository pattern. However, if you do it right, it can save you a lot of redundant coding.
The reason for abstracting it isn't only useful because then you can replace NHibernate later with another ORM, but it is a good practice because of a concept called Separation of Concerns. Your business logic layer shouldn't care or know anything about how to access the data it works with. This makes maintaining the application or its different layers easier, which also makes teamwork easier: If X creates the data access layer, and Y writes the business logic, they don't have to know each others' work in detail.
Exposing an IQueryable<T> is a very good idea, and that is exactly what many repository implementations are doing right now. (And me too, although I preferred to write it in a static class.)
And of course you'll have to expose some methods to insert or update an entity, or methods for beginning and commiting transactions, if you want to. (The BeginTransaction should just return an IDisposable to avoid leaking out an NHibernate interface, and that'll be fine.)
I can give you some directions: check out SharpArchitecture's or FubuMVC Contrib's implementations to get some ideas about how do do it right, and this is how I solved it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Ajax file uploading with java back end?
I don't want to use flash. I've found multiple jquery libraries that do this. Right now I'm using this one: http://demo.webdeveloperplus.com/ajax-file-upload/
The problem is they all use PHP. I tried just pointing it at my servlet instead of the PHP file, but it never gets called.
A:
I did it with this jquery plugin. It pretty much mimics standard jquery ajax functionality, but also allows you to send data using iframe. No flash involved, pure javascript.
http://malsup.com/jquery/form/
Here is a file upload example
http://malsup.com/jquery/form/#file-upload
| {
"pile_set_name": "StackExchange"
} |
Q:
Email with Inbox / Outbox single app using ember js
I've recently (2 days ago) come across a simple email system built in ember js, but I can't seem to find it anymore!
it was just a single page app written in ember js (i think!!)
A:
Scroll down a bit (to Routing) on http://emberjs.com/, I think that's the one you meant.
| {
"pile_set_name": "StackExchange"
} |
Q:
Split string issues with null position
I have a string of the days of the week. I parse it in C# and store each day in a separate variable. For example:
string weekdayName = "Mon,Tue,Wed,Thu,Fri,Sat,Sun";
And the I split them using ',' as a delimiter:
var weekDayName = weekDay.Split(',');
var firstDay = weekDayName[0];
var secondDay = weekDayName[1];
var thirdDay = weekDayName[2];
var fourthDay = weekDayName[3];
var fifthDay = weekDayName[4];
var sixDay = weekDayName[5];
var seventhDay = weekDayName[6];
Everything works. However, the string dynamically changes. A user assigns the days of the week. For example a string weekDayName could only contain "Mon,Tue". But the problem i'm running into is if not all the position contains value it will fail.
Index was outside the bounds of the array.
I have tried:
if (weekDayName[5].Length >0)
{
var sixDay = weekDayName[5];
}
But it still fails...
How can I check and grab the value of the existing data, if some of the position are missing I just ignore them?
What I'm trying to achieve is:
DateTime currentDay = new DateTime();
currentDay = DateTime.Now;
if (currentDay.ToString("ddd") == firstDay || currentDay.ToString("ddd") == seconday)
{
// I will check the currentDay against every day of the week
//do something
}
A:
Your index out of range is not coming from where you think. I am of course assuming this since you tried to check length on an element that was never set if the user enters Mon,Tue.
var enteredDays = weekDay.Split(',');
for(var i = 0; i < enteredDays.Length; i++)
{
var day = enteredDays[i];
if(i == 0)
first = day;
else if(i == 1)
second = day;
... etc....
}
Now you can check String.IsNullOrEmpty(..yourDay..) when you need to use the values you pulled from the array. You can't use .Length on them because they are null and will blow up unless you default them all to string.Empty.
| {
"pile_set_name": "StackExchange"
} |
Q:
Numeric node property is rounded when querying with Cypher
I am running the following query using Cypher on Neo4j 2.0.1
MATCH (n) WHERE n.value = -4810333952080461631 OR n.value = -163182636343344959
RETURN n.value
Results:
-4810333952080462000
-163182636343344960
It seems that the values are getting rounded. I tried it through their web ui, and the node js neo4j client.
When I browse to the node through their web ui, I can see that it holds the correct value.
A:
This was opened in an issue: https://github.com/neo4j/neo4j/issues/2009. The JSON returned is correct. If it's not correct coming from the client you're using (you don't mention which), there is possibly a bug in the client, where a value is converted to a double and losing precision.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to draw Line chart in monoandroid(xamarin) with shinobi chart library
I am using "shinobicontrols" (link given bellow) for my mono android application(xamarin).so, now i want to draw line chart for two data field one for "ask" price and one for "bid" price. so, any one can help me?
thanks in advance ....
http://www.shinobicontrols.com/android/shinobicharts/price-plans
A:
The best place to ask for help relating to Shinobi Charts is their forums, there you will get help from people who are familiar with the libraries and the devs themselves.
It seems like you are just getting started, so the best place to begin would be the user guide, available here:
http://www.shinobicontrols.com/docs/ShinobiControls/ShinobiChartsAndroid/1.3.5/Premium/Normal/user-guide/index.html
This will take you through the steps needed to create and render a chart, there are also more detailed API documentation for the Xamarin bindings, for example for a Line Series (which is what it sounds like you are wanting to use):
http://www.shinobicontrols.com/docs/ShinobiControls/ShinobiChartsAndroid/1.3.5/Premium/MonoTouch/Com.ShinobiControls.Charts/LineSeries.html
Finally if you are still having problems feel free to post on the forums:
http://www.shinobicontrols.com/forum/shinobicontrols
Hope this helps, if you are still struggling just let us know what we can do to help.
Craig.
(Full disclosure: I work for ShinobiControls)
| {
"pile_set_name": "StackExchange"
} |
Q:
Multiple TextView on a Listview
I'm trying to create a ListView with 2 TextView. I'm not very good in Java so I usually follow many tutorials and combine them to create what I need.
But I've tried to combine 2 guides together without much success...
Here is the tutorial I'm trying to follow to add the second TextView :
https://www.youtube.com/watch?annotation_id=annotation_3104328239&feature=iv&src_vid=8K-6gdTlGEA&v=E6vE8fqQPTE
But this doesn't really help me since I have difficulty understanding how I can implement what he is doing.
So far what I have understood is that I need to add my item like this :
countryList.add(new EntryItem("Électron","1/6"));
To do so I'll have to modify EntryItem and my class that extends BaseAdapter
But I haven't been successful with that.
What is the best way to add my second TextView?
Fragment Activity
public class Tab1Fragment extends Fragment {
ListView lvCountry;
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main,container,false);
lvCountry = (ListView) view.findViewById(R.id.lvCountry);
ArrayList<Item> countryList = new ArrayList<Tab1Fragment.Item>();
// Header
countryList.add(new SectionItem("Atomes")); // 0
// State Name
countryList.add(new EntryItem("Électron")); // 1
countryList.add(new EntryItem("Monstre")); // 2
countryList.add(new EntryItem("Neutron")); //3
countryList.add(new EntryItem("Proton")); //4
countryList.add(new EntryItem("Stigmate")); //5
// Header
countryList.add(new SectionItem("Chaos")); //6
// State Name
countryList.add(new EntryItem("Casbah")); //7
countryList.add(new EntryItem("Chaos")); //8
countryList.add(new EntryItem("Gaufrette"));//9
countryList.add(new EntryItem("Lorenz")); //10
// Header
countryList.add(new SectionItem("Monolith")); //11
// State Name
countryList.add(new EntryItem("Chanceux")); //12
countryList.add(new EntryItem("Monolith")); //13
countryList.add(new EntryItem("Ubik")); //14
// Header
countryList.add(new SectionItem("Autres")); //15
// State Name
countryList.add(new EntryItem("Beau")); //16
countryList.add(new EntryItem("Enclume")); //17
countryList.add(new EntryItem("Huitre")); //18
// set adapter
final CountryAdapter adapter = new CountryAdapter(getActivity(), countryList);
lvCountry.setAdapter(adapter);
com.melnykov.fab.FloatingActionButton fab = (com.melnykov.fab.FloatingActionButton) view.findViewById(R.id.fab);
fab.attachToListView(lvCountry);
lvCountry.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int i = 0;
for (i= 0; i < 16 ; i++) {
if(position== 0||position==6||position==11||position==15){
}
else {
Intent myintent = new Intent(view.getContext(), MainActivity.class);
startActivityForResult(myintent, i);
}
}
}
});
lvCountry.setTextFilterEnabled(true);
// filter on text change
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
return view;
}
/**
* row item
*/
public interface Item {
public boolean isSection();
public String getTitle();
}
/**
* Section Item
*/
public class SectionItem implements Item {
private final String title;
public SectionItem(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
@Override
public boolean isSection() {
return true;
}
}
/**
* Entry Item
*/
public class EntryItem implements Item {
public final String title;
public EntryItem(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
@Override
public boolean isSection() {
return false;
}
}
/**
* Adapter
*/
public class CountryAdapter extends BaseAdapter {
private Context context;
private ArrayList<Item> item;
private ArrayList<Item> originalItem;
public CountryAdapter(Tab1Fragment tab1Fragment, ArrayList<Item> countryList) {
super();
}
public CountryAdapter(Context context, ArrayList<Item> item) {
this.context = context;
this.item = item;
//this.originalItem = item;
}
@Override
public int getCount() {
return item.size();
}
@Override
public Object getItem(int position) {
return item.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (item.get(position).isSection()) {
// if section header
convertView = inflater.inflate(R.layout.layout_section, parent, false);
TextView tvSectionTitle = (TextView) convertView.findViewById(R.id.tvSectionTitle);
tvSectionTitle.setText(((SectionItem) item.get(position)).getTitle());
}
else
{
// if item
convertView = inflater.inflate(R.layout.layout_item, parent, false);
TextView tvItemTitle = (TextView) convertView.findViewById(R.id.tvItemTitle);
tvItemTitle.setText(((EntryItem) item.get(position)).getTitle());
}
return convertView;
}
/**
* Filter
*/
public Filter getFilter()
{
Filter filter = new Filter() {
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
item = (ArrayList<Item>) results.values;
notifyDataSetChanged();
}
@SuppressWarnings("null")
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
ArrayList<Item> filteredArrayList = new ArrayList<Item>();
if(originalItem == null || originalItem.size() == 0)
{
originalItem = new ArrayList<Item>(item);
}
/*
* if constraint is null then return original value
* else return filtered value
*/
if(constraint == null && constraint.length() == 0)
{
results.count = originalItem.size();
results.values = originalItem;
}
else
{
constraint = constraint.toString().toLowerCase(Locale.ENGLISH);
for (int i = 0; i < originalItem.size(); i++)
{
String title = originalItem.get(i).getTitle().toLowerCase(Locale.ENGLISH);
if(title.startsWith(constraint.toString()))
{
filteredArrayList.add(originalItem.get(i));
}
}
results.count = filteredArrayList.size();
results.values = filteredArrayList;
}
return results;
}
};
return filter;
}
}
}
Layout_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="100">
<TextView
android:id="@+id/tvItemTitle"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_weight="20"
android:gravity="center_vertical"
android:paddingLeft="20dp"
android:text="TextView1"
android:textAppearance="@style/TextAppearance.AppCompat"
android:textSize="18sp" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="80">
<TextView
android:gravity="center"
android:text="1/6"
android:layout_width="match_parent"
android:layout_height="50dp"
android:id="@+id/textView2"/>
</LinearLayout>
</LinearLayout>
This is what the App looks like for now
Any help would be appreciated!
You found a grammar mistake? Don't keep it to yourself ! English isn't my mother tongue. Share it, so I can correct myself !
A:
First, you have to modify your EntryItem by adding a field to indicate the value, like this:
public class EntryItem implements Item {
public final String title;
public final String value;
public EntryItem(String title, String value) {
this.title = title;
this.value = value;
}
public String getTitle() {
return title;
}
public String getValue() {
return value;
}
@Override
public boolean isSection() {
return false;
}
}
Then, you have to get the TextView reference of your TextView of id textView2 and setText() inside getView(int, View, ViewGroup) of your Adapter.
if (item.get(position).isSection()) {
//your code...
} else {
//your code...
TextView tvItemTitle = (TextView) convertView.findViewById(R.id.textView2);
tvItemTitle.setText(((EntryItem) item.get(position)).getValue());
}
Finally, update your EntryItem data:
countryList.add(new SectionItem("Atomes")); // 0
// State Name
countryList.add(new EntryItem("Électron", "1/6")); // 1
countryList.add(new EntryItem("Monstre", "1/6")); // 2
countryList.add(new EntryItem("Neutron", "1/6")); //3
countryList.add(new EntryItem("Proton", "1/6")); //4
countryList.add(new EntryItem("Stigmate", "1/6")); //5
// Header
countryList.add(new SectionItem("Chaos")); //6
// State Name
countryList.add(new EntryItem("Casbah", "1/6")); //7
countryList.add(new EntryItem("Chaos", "1/6")); //8
countryList.add(new EntryItem("Gaufrette", "1/6"));//9
countryList.add(new EntryItem("Lorenz", "1/6")); //10
// Header
countryList.add(new SectionItem("Monolith")); //11
// State Name
countryList.add(new EntryItem("Chanceux", "1/6")); //12
countryList.add(new EntryItem("Monolith", "1/6")); //13
countryList.add(new EntryItem("Ubik", "1/6")); //14
// Header
countryList.add(new SectionItem("Autres")); //15
// State Name
countryList.add(new EntryItem("Beau", "1/6")); //16
countryList.add(new EntryItem("Enclume", "1/6")); //17
countryList.add(new EntryItem("Huitre", "1/6")); //18
| {
"pile_set_name": "StackExchange"
} |
Q:
Does the brightness/power of each individual bulb change when you add more bulbs in a parallel circuit?
I have asked this question on different sites and have received contradictory answers. Assume that there is an ideal voltage source and the resistance of each bulb is the same.
I believe that the brightness/power remains the same because the voltage across each bulb is constant and the current across each bulb is therefore constant. I don't see how adding more bulbs could change this. However, others have said that adding more bulbs will decrease the current by a small amount, and therefore the brightness of each bulb decreases. Have they made the assumption that an ideal voltage source is not used?
A mathematical proof or just a good explanation to clear this up would be much appreciated
A:
Assume that there is an ideal voltage source
The problem is that such a voltage source does not exist. Every real-life voltage source has an internal resistance. Because of that (and possibly for other reasons as well), as you draw more current, its output voltage will drop. When that voltage drops, the current through the bulbs will also drop.
When you add an additional light bulb (in parallel to the others), you are reducing the total resistance of the load. Hence there will be an increase in the current drawn from the supply. However, that will make its voltage drop, and as a result the current will not increase as much as you would expect.
Sure, if you did have an ideal voltage source (no internal resistance, able to supply infinite current) then neither the voltage nor the current would change and you could keep adding additional bulbs forever.
| {
"pile_set_name": "StackExchange"
} |
Q:
PyQT5 show label before sleep
I'm trying to create a GUI for my python code.
I ran into a problem, where i'd like to show a label with text "Please wait" and paralel with this i'd like to sleep my code for 1.25s.
However, it is going into sleep without showing the label. It seems to me it somehow "skips" the .show()
Here is the snippet from the code:
def status_check(self):
self.varakozas.setText("Please wait...")
self.varakozas.show()
time.sleep(1.25)
sudoPassword = self.sudopassword.text()
command = "some command"
passtmeg = "echo '"+sudoPassword+"' | sudo -S "+command
line = subprocess.Popen(["bash", "-c", passtmeg],stdout=subprocess.PIPE,shell=True)
status_of = str(line.communicate()[0])
status_of_to_log = status_of.translate({ord(translate_table): "" for translate_table in "'b"})
logging.info('Status: '+ status_of_to_log[:-2])
if ("xy" in status_of) or ("Starting" in status_of):
self._status.setText("xy is running")
self.varakozas.hide()
else:
self._status.setText("xy is stopped")
self.varakozas.hide()
A:
As you said self.varakozas is QLabel so i predict it is child of your window.
If you call show() Qt will only schedule paint event for this widget and paint event is called by event loop. Event loop is executed once the execution of this method is done. So the sleep is called first because it is before the end of scope. This is standard behaviour of Qt event loop environments.
But there is a workaround. You can call paint event manually by repaint() method.
Try this:
def status_check(self):
self.varakozas.setText("Please wait...")
self.varakozas.show()
self.repaint()
time.sleep(1.25)
| {
"pile_set_name": "StackExchange"
} |
Q:
Error while cross compiling an openssl C cpplication
I write a simple encryption program with C for Raspberry Pi. It successfully compiled for my X86 CPU with gcc encoder.c -lcrypto -o encoder (I'd installed libssl-dev), but when I want to cross compile it (with arm-linux-gnueabihf-gcc), this error occur:
$ arm-linux-gnueabihf-gcc encoder.c -lcrypto -o encoder
In file included from ./encoder.c:4:0:
/usr/include/openssl/aes.h:55:33: fatal error: openssl/opensslconf.h: No such file or directory
#include <openssl/opensslconf.h>
^
compilation terminated.
How to cross compile an openssl C application for Raspberry Pi?
A:
Your biggest problem is that your cross-compiler tries to use builds (as in your x86 machine) headers and it will also happily try to use wrong libraries if and when it comes to linking (and fail to link, of course). For a long time there is --sysroot option that solves exactly this problem, you just need to have properly set up sysroot for your target machine, and if you already have a cross-compiler chances are you do have some sysroot already. You just need to know proper paths (based on where and how you cross-compiler is installed), compile and install openssl itself (cross-compiling openssl in not fun, BTW) and then you'll be able to cross-compile something using openssl for your Pi.
As was already noted in the comments, building on the device is way easier, but Pi is slow, so there is a choice — easy setup and slow builds on Pi or relatively hard cross-compilation setup and fast builds on x86 machine.
As an alternative, you can try to use specialized cross-compiling build environments like OpenEmbedded, BuildRoot or OpenWRT, but that's also probably an overkill for one simple program.
| {
"pile_set_name": "StackExchange"
} |
Q:
A “puck” of frozen food
I found a recipe that calls for 5 “pucks” of frozen spinach. I cannot find a definition of the term. I need to know how many ounces are in a puck?
A:
The term "puck" is not in general use for food, but it seems to refer to a hockey puck-like volume of frozen spinach. (Spinach is commonly found frozen into blocks.) Presumably the author of the recipe had a particular brand - and therefore size standard - of spinach in mind. The spinach "pucks" in my freezer are about 4 oz each, but other sizes are also common.
Find a better recipe, or ask the author for clarification.
| {
"pile_set_name": "StackExchange"
} |
Q:
Segfault when assigning to char* in struct
So I have a struct "sequence" that has a char* in it. When I try and create a sequence, whenever I try and change the char* it segfaults. Here is the related code. The struct:
typedef struct _sequence {
unsigned int length;
unsigned char* bytes;
} Sequence;
The constructor:
Sequence* newSequence(unsigned char firstByte) { //Creates new sequence, allocates memory
printf("Creating new Sequence\n");
Sequence* seq = (Sequence*)malloc(sizeof(Sequence));
printf("Have new sequence\n");
seq->length = 1;
printf("Set length\n");
seq->bytes[0] = firstByte;
printf("Set variables\n");
return seq;
}
Now I have a main function here just for testing purposes, this file will in the end not have a main function. But here is what i used to testing:
int main() {
char test[] = "ab";
printf("Testing sequences!\n");
Sequence* newSeq = newSequence(test[0]);
printf("Made new sequence!\n");
outputSequence(newSeq, stdout);
printf(" <-- new Sequence created\n");
return 0;
}
The printfs are again for testing purposes. It always prints out all the way up to "Set length\n" in the constructor, then segfaults. What am I doing wrong? Thank you!
A:
You allocated apace for the structure correctly, but you didn't allocate any space for the buffer pointed to by the bytes element.
This line invokes undefined behavior because bytes is uninitialized:
seq->bytes[0] = firstByte;
You need to also allocate a buffer and point seq->bytes to it.
A:
Sequence* seq = malloc (sizeof(Sequence));
Here you allocate memory space for one char * , and one int, but you need to allocate space for what you want to store on what is pointed at by your char *, this way :
seq->bytes = malloc (my_string_size);
Only then can you start storing characters in your allocated chunk of memory.
Edit : for instance, to store one single character, you could do :
seq->bytes = malloc(1);
seq->bytes[0] = firstByte;
to use it as a single character. But the good habit in C to manipulate string is to always leave one char more, in that fashion :
seq->bytes = malloc(2);
seq->bytes[0] = firstByte;
seq->bytes[1] = '\0';
The 2nd method looks more like a real 'string' in C.
| {
"pile_set_name": "StackExchange"
} |
Q:
MBP Late 2011 freezes under yosemite
I have an MacBook Pro Late 2011 and it freezes (So the Beachball is turning arround), not completely randomly but when I use the disks, (writing or reading data) over 1/2 Mb/s so if I copy a big file from a DMG it freezes often but randomly during the copy process, or if I download something over internet it freeze randomly during the download.
I can't do anything except of moving the mouse, if i wait a few seconds all comes back and I can continue use my Mac. I first thought it was totally random but it happens more often when I copy data or download anything. I think it's Yosemite's fault but I can not certify that.
Useful pasts:
EtreCheck: https://paste.ee/r/UvuNe
Full console log: https://paste.ee/r/kxZgs
I already reinstalled OSX Yosemite, and after that it continued with the same issue, but before i reinstalled a fresh version, it hung up always randomly, after I reinstalled OSX on my Home made Fusion Drive it only hung up when i started copying files or other things like that
I have read similar topics on internet about Yosemite and Freezing bug that was always different causes and different freezes like total freeze (no mouse) or freeze for infinite time and does not continue after a few secs.
When it freeze ALL stops even iTunes stop playing music. and after the freeze stops, everywhere i clicked clicks in a accelerated mode.
So if during the freeze i click on two apps and open a few menus, it does nothing but after a few secs all opens.
Anyone got the same issue or an idea to solve/troubleshoot this ?
Sorry for my English.
Edit: (my answer to Buscar웃SD)
I already looked at the system monitor, i forget to say it i'll add it.
When the freeze happens the CPU is at 30% and disks are not at 100% when ii download but when I copy anything they are at 100% So it's weird, the amount of RAM used changes nothing, and the console writes nothing suspect
Edit2: I add a few images from the console and activity monitor during a freeze:
During the Freeze
Another during the freeze
And this is after the freeze
I have another screenshot who is important and it's the lines during the FREEZE, theses lines are these after the blue selected line
On the screenshot we can see that the freeze during from 20:20:58 and the next line appears on 20:21:07 so the crash is during 9 seconds:
A:
So, I installed OS X EL Capitan, (10.11) and i started to transfer a 9Gigs app (xCode) to install it, and I had NO freeze, so it is Yosemite, and fixed in OS X El Capitan :) It was only a quick test but On Yosemite doing this froze the system every minute.
If I get one freeze during the next days I'l Edit this post. If not I resolve it.
Anyway, thank you for your help :)
Okay it wasn't OS X but Hardware, The second SSD was installed in the Optical Super Drive bay, and on Late 2011 Mac Book Pro there is an issue on the controller so I installed OS X on the Hard Drive without using the SSD, NO freeze, so I decided to swap SSD and Hard Drive but I don't have the right Screwdriver
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I make my code in compliance with MISRA 2012 RULE10.4
if(fn1()) //Line 1
{
a++;
}
Here the return type of function fn1 is uint8_t. The function returns only values 0 or 1.
PC Lint throws error for line 1 says "Mismatched essential type categories for binary operator" [RULE 10.4 required]
Rule 10.4 says "Both operands of an operator in which the usual arithmetic conversions are performed shall have the same essential type category"
A:
MISRA-C doesn't allow implicit checks against zero - all inputs to conditional statements must be "essentially boolean", which is what you get if you explicitly use logical operators like ==.
In addition, MISRA-C has various rules blocking you from mixing "essenitally signed" and "essentially unsigned" in the same expression, and thereby relying on implicit type promotions. So you can't write if (fn1() == 1) for that reason, since 1 is a signed type and there's also a rule requiring all integer constants to have u suffix.
So one possible fix is if (fn1() == 1u). However, since the function only returns 0 or 1, you can also cast its result to boolean type and that would be fine too: if ((bool)fn()). The best solution is however to rewrite the function to return bool, after which you can use if(fn1()).
| {
"pile_set_name": "StackExchange"
} |
Q:
Restrict certain users from adding new tags , django-taggit?
i'm quite new to django framework, i'm creating a blog application from scratch , and i am integrating django-taggit, to tag the articles. What im trying to accomplish is that , i want only certain users to be able to add new tags and the rest of them can only use the existing ones. It something like what stackoverflow implements, it allows users with certain amount of reputations to add new tags.
How do i achieve this ?
A:
You could do a couple things. First I would definitely implement a UserProfile model of some kind, i.e. that has a reputation attribute, and then you have a bunch of options to accomplish your task, i.e.
Use the @user_passes_test decorator, where you create your own function to pass to the decorator.
def at_least_fifty_rep(user):
my_profile = ... # get the user profile
return my_profile.reputation > 50
@user_passes_test(at_least_fifty_rep)
def my_custom_view(request):
...
Alternatively, you could implement controls in the template as well.
| {
"pile_set_name": "StackExchange"
} |
Q:
Does getting an unaccept change the "accept don't count towards the max" calculation?
Today (2/5/15) I am currently being capped at 200 rep (several upvotes have not counted). Since I have one accepted answer, I would normally expect to max out at 215, not 200, as reputation from accepts doesn't count against the cap.
However, for some reason, an asker unaccepted a previous day's answer today, leaving me at 1 accept and 1 unaccept for the day (though the unaccept wasn't accepted today)
Is this causing my cap to not be what I expect? Is this expected behavior, or a bug?
A:
Just like accepts, unaccepts do not count towards the cap either. You just lose the 15 points, the cap calculation is unchanged and unaffected.
So you got 200 points from upvotes (capped), 15 points from the accept, and -15 points from the unaccept. Your net reputation change is then 200 (200 + 15 - 15).
Now, if someone undid a normal upvote vote, you'd lose 10 points from the capped reputation, after which subsequent normal upvote would then count again until you once again hit that cap. The same would apply to a downvote on one of your posts, or if you downvoted someone else's answer. You'd lose some reputation, and the next upvote would count until you are at the maximum 200 points for the again.
| {
"pile_set_name": "StackExchange"
} |
Q:
Visual Studio error when ITK and VTK is used
I am doing a project in visual studio 2015When i included ITK and compiled everything ,some errors are occurring
Error C3861 '_beginthreadex': identifier not found
Error C2039 '_time64': is not a member of '`global namespace''
Error C3861 '_time64': identifier not found
Error C3861 '_mktime64': identifier not found
Error C3861 '_mktime64': identifier not found
Error C3861 '_gmtime64_s': identifier not found
Error C3861 '_localtime64_s': identifier not found
Error C3861 '_mktime64': identifier not found
Error C3861 '_localtime64_s': identifier not found
Error C3861 '_gmtime64_s': identifier not found
Error C2039 '_time64': is not a member of '`global namespace''
Error C3861 '_time64': identifier not found
Error C3646 'm_nLastAnimTime': unknown override specifier
Error C4430 missing type specifier - int assumed. Note: C++ does not
support default-int
Error C3646 'm_ActiveTime': unknown override specifier
Error C4430 missing type specifier - int assumed. Note: C++ does not
support default-int
Error C3646 'm_clkLastTime': unknown override specifier
But i tried including Visual studio/VC/Include and Visual Studio/VC/bin to the Additional Include Directories,still it is showing the same errors.
I also tried changing the Use of MFC and c++ ->code generation ->Runtime Library in configuration properties as well.
I referred this link also,but my problem is not solved.
So i thought may be because of vs2015 instalation problems and tried to build a new project using VTK and ITK in Visualstudio 2017,In there also the same errors are occurring.I have been stuck for weeks ,Can anyone give a solution for my problem?
A:
Are you using this procedure to build ITK and VTK? Are you following this guide to build your own application? Using CMake is the only supported way of using ITK and/or VTK.
If you cannot use CMake, a workaround is to build a hello world example using CMake and then copy include paths and list of libraries to your main Visual Studio application.
| {
"pile_set_name": "StackExchange"
} |
Q:
What default libraries are taken while compiling C project with GCC
I have simple application:
#include <stdio.h>
int main( int argc, char ** argv )
{
printf( "hello");
exit( 0 );
}
When I compile it with command
gcc -c count_words.c
I have warning:
warning: incompatible implicit declaration of built-in function ‘exit’ [enabled by default]
exit( 0 );
I was trying to find where exit() function is defined. And found that it is defined in stdlib.h. But it is not included in my project and no additional libs defined in compile command.
Correct me if I'm wrong, but looks like gcc takes some libs as default. What are these libs and is it possible to tell gcc not include them?
Why compiler is not happy regarding exit(0) assuming that it somehow includes stdlib.h as default?
A:
Let's take your example:
#include <stdio.h>
int main( int argc, char ** argv )
{
printf("hello\n");
exit(56);
}
Although we get a warning on compilation:
~$ gcc test.c -o test
test.c: In function ‘main’:
test.c:6:5: warning: implicit declaration of function ‘exit’ [-Wimplicit-function-declaration]
exit(56);
^
test.c:6:5: warning: incompatible implicit declaration of built-in function ‘exit’
test.c:6:5: note: include ‘<stdlib.h>’ or provide a declaration of ‘exit’
Anyway, I think you have tried to run it and make sure it works:
~$ ./test
hello
~$ echo $?
56
@Mat was right when he said that:
You're mixing up including headers and linking to libraries. Those are
two completely different things
The C compiler and linker are totally separate tools. Let's look on this. Actually, this program depends on the standard C library (as all programs if you didn't pass -nostdlib to compiler) and a couple of system libraries (like loader and vdso). You may see it with:
~$ ldd test
linux-vdso.so.1 (0x00007fff1b128000)
libc.so.6 => /lib64/libc.so.6 (0x00007f804389f000)
/lib64/ld-linux-x86-64.so.2 (0x0000557744537000)
These three library is a minimal set for any program. The exit function is defined in the standard library or libc.so.6 in our case. Now let's look on the compilation process in verbose mode. You can achieve this by the passing -v or --verbose option to compiler:
gcc test.c -o test --verbose
If you will execute this, you will find lines like these:
#include <...> search starts here:
/usr/lib/gcc/x86_64-redhat-linux/5.3.1/include
/usr/local/include
/usr/include
So, compile knows where to search header files for stdlib and it starts to search it to find declaration for non-local functions. Note that it searches only in header files which are included in your source code file. It can find printf declaration in thestdio.h, but can't locate declaration of the exit.
After this step, the compile starts to link your program with libraries:
/usr/libexec/gcc/x86_64-redhat-linux/5.3.1/collect2 ... -lc ...
Where collect2 is gcc util which tries to link your program with lc which is standard C library. Note that the process consists from two steps: compilation and linking. That's why your program works.
Additionally, gcc supports -M option which will tell you about dependencies of the main file. So, if you will execute it, you will see the set of header files including stdio.h, but not stdlib.h:
$ gcc -M test.c
test.o: test.c /usr/include/stdc-predef.h /usr/include/stdio.h \
/usr/include/features.h /usr/include/sys/cdefs.h \
/usr/include/bits/wordsize.h /usr/include/gnu/stubs.h \
/usr/include/gnu/stubs-64.h \
/usr/lib/gcc/x86_64-redhat-linux/5.3.1/include/stddef.h \
/usr/include/bits/types.h /usr/include/bits/typesizes.h \
/usr/include/libio.h /usr/include/_G_config.h /usr/include/wchar.h \
/usr/lib/gcc/x86_64-redhat-linux/5.3.1/include/stdarg.h \
/usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h
Or even better, try to pass -E option to gcc:
$ gcc -E test.c
and you will see result right after the first stage - preprocessing stage. I think it is the easiest way to understand why you are getting this warning.
| {
"pile_set_name": "StackExchange"
} |
Q:
get cross tabulated report according to data available - pivot
I want to pivot and turn an existing table and generate a report(cross tabulated). You see vals column is determined by unique combination of date_a and date_e columns. I don't know how to do this.
A:
Something like this:
Test data
CREATE TABLE #tbl(date_a DATE,date_e DATE, vals FLOAT)
INSERT INTO #tbl
VALUES
('2/29/2012','1/1/2013',28.47),
('2/29/2012','2/1/2013',27.42),
('2/29/2012','3/1/2013',24.36),
('3/1/2012','1/1/2013',28.5),
('3/1/2012','2/1/2013',27.35),
('3/1/2012','3/1/2013',24.39),
('3/6/2012','1/1/2013',27.75),
('3/6/2012','2/1/2013',26.63),
('3/6/2012','3/1/2013',23.66)
Query
SELECT
*
FROM
(
SELECT
tbl.date_a,
tbl.date_e,
vals
FROM
#tbl AS tbl
) AS SourceTable
PIVOT
(
SUM(vals)
FOR date_e IN ([1/1/2013],[2/1/2013],[3/1/2013])
) AS pvt
DROP TABLE #tbl
EDIT
If you do not know how many columns there is then you need to do a dynamic pivot. Like this:
The unique columns
DECLARE @cols VARCHAR(MAX)
;WITH CTE
AS
(
SELECT
ROW_NUMBER() OVER(PARTITION BY date_e ORDER BY date_e) AS RowNbr,
tbl.*
FROM
#tbl AS tbl
)
SELECT @cols=STUFF
(
(
SELECT
',' +QUOTENAME(date_e)
FROM
CTE
WHERE
CTE.RowNbr=1
FOR XML PATH('')
)
,1,1,'')
Dynamic pivot
DECLARE @query NVARCHAR(4000)=
N'SELECT
*
FROM
(
SELECT
tbl.date_a,
tbl.date_e,
vals
FROM
#tbl AS tbl
) AS SourceTable
PIVOT
(
SUM(vals)
FOR date_e IN ('+@cols+')
) AS pvt'
EXECUTE(@query)
| {
"pile_set_name": "StackExchange"
} |
Q:
Pipe superagent response to express response
I'm trying to "proxy" some file with an express app. Why the code below doesn't work?
var app = require('express')()
var request = require('superagent')
app.get('/image', function(req, res, next) {
request('http://s3.amazonaws.com/thumbnails.illustrationsource.com/huge.104.520060.JPG')
.then(function(_res) {
_res.pipe(res)
})
})
app.listen(3001, function() {
console.log('listen')
})
When I "wget" a file directly it works:
$ wget http://s3.amazonaws.com/thumbnails.illustrationsource.com/huge.104.520060.JPG
--2016-07-20 11:44:33-- http://s3.amazonaws.com/thumbnails.illustrationsource.com/huge.104.520060.JPG
Resolving s3.amazonaws.com... 54.231.120.106
Connecting to s3.amazonaws.com|54.231.120.106|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 21026 (21K) [image/jpeg]
Saving to: 'huge.104.520060.JPG'
huge.104.520060.JPG 100%[==============================================================================================>] 20.53K --.-KB/s in 0.1s
2016-07-20 11:44:34 (203 KB/s) - 'huge.104.520060.JPG' saved [21026/21026]
when I call my enpdpoint it never finishes:
$ wget localhost:3001/image
--2016-07-20 11:45:00-- http://localhost:3001/image
Resolving localhost... 127.0.0.1, ::1
Connecting to localhost|127.0.0.1|:3001... connected.
HTTP request sent, awaiting response...
Some details:
$ npm -v
3.9.5
$ npm list --depth=0
express-superagent-pipe-file
├── [email protected]
└── [email protected]
A:
A superagent's response object should not be treated as a stream, because it may already be the result of automatic serialization (e.g. from JSON to a JavaScript object). Rather than using the response object, the documentation on piping data states that you can directly pipe the superagent request to a stream:
var app = require('express')()
var request = require('superagent')
app.get('/image', function(req, res, next) {
request('http://s3.amazonaws.com/thumbnails.illustrationsource.com/huge.104.520060.JPG')
.pipe(res)
})
app.listen(3001, function() {
console.log('listen')
})
| {
"pile_set_name": "StackExchange"
} |
Q:
Go cli cant find my tests
When i try to run my tests in golang i get the following error
testing: warning: no tests to run
I also tried to create a test project to see if it behaves the same in other projects these are my 2 files.
package test
func test() string {
return "test"
}
And here is my test.
package test
import (
"testing"
"github.com/stretchr/testify/assert"
)
func testTest(t *testing.T) {
assert.Equal(t, "test", test(), "String was not test")
}
I tried running it with:
go test
go test -v
Also i tested the behaviour in git bash and the cmd.
Im using Windows 10 with Go 1.7.1.
I hope somebody can help me.
A:
Test functions must begin with Test. Try renaming your function to TestTest. That should fix it. Full info here: https://golang.org/pkg/testing
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I move bower libraries in ASP.NET Core?
In my wwwroot folder I have two subfolders called lib and lib_bower. My lib_bower folder is setup in my .bowerrc file like so:
{
"directory": "wwwroot/lib_bower"
}
When I restore bower packages I'm left with this:
I'd like to move the entire dist folder from bootstrap into my lib folder when I build if the files are not found. How can I do this?
A:
You can use gulp task runner to move bootstrap folder into lib folder.
Configuration code(gulpfile.js):
var gulp = require('gulp');
gulp.task('default', function () {
// place code for your default task here
});
var paths = {};
paths.webroot = "wwwroot/";
paths.bowerSrc = "./wwwroot/lib_bower/";
paths.lib = paths.webroot + "lib/";
gulp.task("copy-bootstrap", function () {
return gulp.src(paths.bowerSrc + '/bootstrap/dist/**/*.*', { base: paths.bowerSrc + '/bootstrap/dist/' })
.pipe(gulp.dest(paths.lib + '/bootstrap/'));
});
Then right click gulpfile.js, select Task Runner Explorer, run the copy-bootstrap task or set Bindings to Before Build .
| {
"pile_set_name": "StackExchange"
} |
Q:
Issues reading appsettings.json file C# .NET Core
I'm coming from regular .NET Web API and I have found the experience around configuration in .NET Core 2 absolutely maddening.
I have read the official documentation and a few tutorials such as this one, but they all see to error.
I have a Database helper class that is supposed to establish a MongoDB connection.
My configuration is rather simple
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "mongodb://localhost:27017"
}
}
I started with the .NET Core official Angular (ngx) boilerplate template
I add the configuration as a service singleton in Startup.CS under the ConfigureServices section like so services.AddSingleton(Configuration);
I attempt to inject the configuration into my class like so
public class DatabaseHelper
{
public static string connstring { get; private set; }
public DatabaseHelper(IConfiguration Configuration)
{
connstring = Configuration["ConnectionStrings:DefaultConnectionString"];
}
public static IMongoDatabase QuizDB { get; } = GetDatabase("QuizEngine");
public static IMongoCollection<Quiz> QuizCol { get; } = GetQuizCollection();
public static MongoClient GetConnection() {
return new MongoClient(connstring);
}
public static IMongoDatabase GetDatabase(string database) {
MongoClient conn = DatabaseHelper.GetConnection();
return conn.GetDatabase(database);
}
public static IMongoCollection<Quiz> GetQuizCollection() {
return DatabaseHelper.QuizDB.GetCollection<Quiz>("Quizzes");
}
}
This compiles and builds fine with no Intellesense errors - But when I step through it in the debugger, the connstring is null. I have tried playing around with the configuration names etc, but I always seem to come up empty.
I have also tried the POCO way using the example code in the below answer, but I seem to run into static field initializer issues.
Getting value from appsettings.json in .net core
if it helps here is the the startup class part where it sets the public value of Configuration
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
A:
You don't need to add the configuration as a service singleton in Startup.CS under the ConfigureServices section like services.AddSingleton(Configuration);
If you separate your solution into multiple projects with use of class libraries, Microsoft.Extensions.Options.ConfigurationExtensions package comes in handy for reading the values from appsettings files and injecting them into your configuration classes within projects.
It has 2 extensions you can use:
public static T Get<T>(this IConfiguration configuration);
public static IServiceCollection Configure<TOptions>(this IServiceCollection services,
IConfiguration config) where TOptions : class;
your configuration file appsetting.json
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"MongoDBConnection": "mongodb://localhost:27017"
}
}
add code for ConfigureServices method in startup.cs file
services.Configure<MongoDBconfig>(Configuration.GetSection("ConnectionStrings"));
services.AddSingleton<DatabaseHelper>();
your DBhelper.cs
public class MongoDBconfig
{
public string MongoDBConnection { get; set; }
}
public class DatabaseHelper
{
public static string connstring { get; private set; }
public DatabaseHelper(IOptions<MongoDBconfig> Configuration)
{
connstring = Configuration.Value.MongoDBConnection;
}
public static IMongoDatabase QuizDB { get; } = GetDatabase("QuizEngine");
public static IMongoCollection<Quiz> QuizCol { get; } = GetQuizCollection();
public static MongoClient GetConnection()
{
return new MongoClient(connstring);
}
public static IMongoDatabase GetDatabase(string database)
{
MongoClient conn = DatabaseHelper.GetConnection();
return conn.GetDatabase(database);
}
public static IMongoCollection<Quiz> GetQuizCollection()
{
return DatabaseHelper.QuizDB.GetCollection<Quiz>("Quizzes");
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to dynamically create bootstrap modals as Angular2 components?
Original title: Can't initialize dynamically appended (HTML) component in Angular 2
I've created a directive that appends a modal to the body on initialization. When a button (with the directive injected into it) is clicked this modal fires up. But I want the contents of this modal to be another component (In fact I want the modal to be the component). It seems that I can't initialize the component.
Here is a plunker of what I've done:
http://plnkr.co/edit/vEFCnVjGvMiJqb2Meprr?p=preview
I'm trying to make my-comp the template of my component
'<div class="modal-body" #theBody>'
+ '<my-comp></my-comp>' +
'</div>
A:
update for 2.0.0 final
Plunker example >= 2.0.0
@NgModule({
imports: [ BrowserModule ],
declarations: [ App, ModalComponent, CompComponent],
providers: [SharedService],
entryComponents: [CompComponent],
bootstrap: [ App, ModalComponent ]
})
export class AppModule{}
export class ModalComponent {
@ViewChild('theBody', {read: ViewContainerRef}) theBody;
cmp:ComponentRef;
constructor(
sharedService:SharedService,
private componentFactoryResolver: ComponentFactoryResolver,
injector: Injector) {
sharedService.showModal.subscribe(type => {
if(this.cmp) {
this.cmp.destroy();
}
let factory = this.componentFactoryResolver.resolveComponentFactory(type);
this.cmpRef = this.theBody.createComponent(factory)
$('#theModal').modal('show');
});
}
close() {
if(this.cmp) {
this.cmp.destroy();
}
this.cmp = null;
}
}
Hint
If one application change the state in SharedService or calls a method that causes an Observable to emit a value and the subscriber is in a different application then the emitter, the code in the subscriber is executed in the NgZone of the emitter.
Therefore when subscribing to an observable in SharedService use
class MyComponent {
constructor(private zone:NgZone, private sharedService:SharedService) {
private sharedService.subscribe(data => this.zone.run() => {
// event handler code here
});
}
}
For more details how to trigger change detection see Triggering Angular2 change detection manually
original
Dynamically added HTML is not processed by Angular and doesn't result in components or directives to be instantiated or added.
You can't add components outside Angulars root component (AppComponent) using DynamicComponentLoader (deprecated) ViewContainerRef.createComponent() (Angular 2 dynamic tabs with user-click chosen components).
I guess the best approach is to create a 2nd component outside Angulars root component is to call bootstrap() on each and use a shared service to communicate:
var sharedService = new SharedService();
bootstrap(AppComponent, [provide(SharedService, {useValue: sharedService})]);
bootstrap(ModalComponent, [provide(SharedService, {useValue: sharedService})]);
Plunker example beta.17
Plunker example beta.14
@Injectable()
export class SharedService {
showModal:Subject = new Subject();
}
@Component({
selector: 'comp-comp',
template: `MyComponent`
})
export class CompComponent { }
@Component({
selector: 'modal-comp',
template: `
<div class="modal fade" id="theModal" tabindex="-1" role="dialog" aria-labelledby="theModalLabel">
<div class="modal-dialog largeWidth" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="theModalLabel">The Label</h4></div>
<div class="modal-body" #theBody>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" (close)="close()">Close</button>
</div></div></div></div>
`
})
export class ModalComponent {
cmp:ComponentRef;
constructor(sharedService:SharedService, dcl: DynamicComponentLoader, injector: Injector, elementRef: ElementRef) {
sharedService.showModal.subscribe(type => {
if(this.cmp) {
this.cmp.dispose();
}
dcl.loadIntoLocation(type, elementRef, 'theBody')
.then(cmp => {
this.cmp = cmp;
$('#theModal').modal('show');
});
});
}
close() {
if(this.cmp) {
this.cmp.dispose();
}
this.cmp = null;
}
}
@Component({
selector: 'my-app',
template: `
<h1>My First Attribute Directive</h1>
<button (click)="showDialog()">show modal</button>
<br>
<br>`,
})
export class AppComponent {
constructor(private sharedService:SharedService) {}
showDialog() {
this.sharedService.showModal.next(CompComponent);
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to give name to array values in PHP
I have data like:
array:3 [▼
"jne" => "Jalur Nugraha Ekakurir (JNE)"
"pos" => "POS Indonesia (POS)"
"tiki" => "Citra Van Titipan Kilat (TIKI)"
]
I only need jne, pos, tiki part of this array but i can't get them. I tried to map them like:
$couriers = collect($results)->map(function ($item) {
return ['title' => $item];
})->toArray();
it returns:
array:3 [▼
"jne" => array:1 [▼
"title" => "Jalur Nugraha Ekakurir (JNE)"
]
"pos" => array:1 [▼
"title" => "POS Indonesia (POS)"
]
"tiki" => array:1 [▼
"title" => "Citra Van Titipan Kilat (TIKI)"
]
]
How can I get those data 3 titles in 1 array so I can loop it in my view?
Code
$rajaongkir = new Raja\Domestic($key);
$results = $rajaongkir->courier('all');
$couriers = collect($results)->map(function ($item) {
return ['title' => $item];
})->toArray();
dd($couriers);
A:
You can use array_keys() to get all keys of an array.
$arr = [
'jne' => 'Jalur Nugraha Ekakurir (JNE)',
'pos' => 'POS Indonesia (POS)',
'tiki' => 'Citra Van Titipan Kilat (TIKI)',
];
$keys = array_keys($arr);
print_r($keys);
| {
"pile_set_name": "StackExchange"
} |
Q:
Using Binary Search on Variant Array Created From an ADO Recordset
I'm using VB6 (yeah I know) to pull get an ADO recordset (over 650,000 records) and load that recordset into a variant array. Then I'm trying search the array to see if a specified string value exists in it using a Binary Search function I found online. I'm getting the error message "Subscript Out Of Range" when I call the Binary Search function. Any idea what I'm doing wrong here?
Dim arrItems() As Variant
'gXRst and gXCon are global variables declared elsewhere. They are not the problem here.
With gXRst
.CursorLocation = adUseClient
.CursorType = adOpenKeyset
.LockType = adLockReadOnly
.Open "SELECT item_cd FROM xmsalinv ORDER BY item_cd ASC", gXCon
End With
arrItems = gXRst.GetRows(gXRst.RecordCount)
gXRst.Close
MsgBox BinarySearch(arrItems(), "491588S")
Function BinarySearch(arr As Variant, search As String, _
Optional lastEl As Variant) As Long
Dim index As Long
Dim first As Long
Dim last As Long
Dim middle As Long
Dim inverseOrder As Boolean
' account for optional arguments
If IsMissing(lastEl) Then lastEl = UBound(arr)
first = LBound(arr)
last = lastEl
'Error message occurring on next line. Error 9, subscript out of range.
' deduct direction of sorting
inverseOrder = (arr(first) > arr(last))
' assume searches failed
BinarySearch = first - 1
Do
middle = (first + last) \ 2
If arr(middle) = search Then
BinarySearch = middle
Exit Do
ElseIf ((arr(middle) < search) Xor inverseOrder) Then
first = middle + 1
Else
last = middle - 1
End If
Loop Until first > last
End Function
A:
GetRows returns a 2D array but the binary search routine wants a 1D array.
Why not just use the built-in Find in the recordset object? Its quicker than a hand-rolled binary search, and much easier.
gXRst.MoveFirst
gXRst.Find("item_cd='491588S'")
MsgBox gXRst.Fields("item_cd").Value
| {
"pile_set_name": "StackExchange"
} |
Q:
Why do some web page URLs have no suffix?
For example the web page I'm on now is:
https://superuser.com/questions/ask
not:
https://superuser.com/questions/ask.html
https://superuser.com/questions/ask.php
I've noticed this for all kinds of sites. Do the developers just not bother putting suffixes on the files?
A:
It's important to remember that a URL is a way to specify a resource. This resource can be of any type. In simpler sites, the resource is requesting a file located in a given folder on the server. But it is become much more common for the URL to be less of a direct 'give me this file', and instead be parsed by a web engine.
In these more advanced sites (or at least more driven by custom software), the URL is more a directive to the software rather than a specifier for a particular file, and so has no reason to include an extension (which is merely a way for operating systems to conveniently tell what kind of file something is).
You are not requesting a file on a site like superuser; you are making a query against a API (so to speak). So it has no need for a file extension.
| {
"pile_set_name": "StackExchange"
} |
Q:
\leqslant causes "Undefined control sequence"
I have the following line: $0 \leqslant b \leqslant 1$
I want to display 0 <= b <= 1, but I get Undefined control sequence
thanks
A:
do you want it like this way? $0 \le b \le 1$.
Otherwise load \usepackage{amssymb}
A:
You should use the amssymb package.
\documentclass{minimal}
\usepackage{amssymb}
\begin{document}
$0 \leqslant b \leqslant 1$
\end{document}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to convert comma separated values to rows in oracle?
Here is the DDL --
create table tbl1 (
id number,
value varchar2(50)
);
insert into tbl1 values (1, 'AA, UT, BT, SK, SX');
insert into tbl1 values (2, 'AA, UT, SX');
insert into tbl1 values (3, 'UT, SK, SX, ZF');
Notice, here value is comma separated string.
But, we need result like following-
ID VALUE
-------------
1 AA
1 UT
1 BT
1 SK
1 SX
2 AA
2 UT
2 SX
3 UT
3 SK
3 SX
3 ZF
How do we write SQL for this?
A:
I agree that this is a really bad design.
Try this if you can't change that design:
select distinct id, trim(regexp_substr(value,'[^,]+', 1, level) ) value, level
from tbl1
connect by regexp_substr(value, '[^,]+', 1, level) is not null
order by id, level;
OUPUT
id value level
1 AA 1
1 UT 2
1 BT 3
1 SK 4
1 SX 5
2 AA 1
2 UT 2
2 SX 3
3 UT 1
3 SK 2
3 SX 3
3 ZF 4
Credits to this
To remove duplicates in a more elegant and efficient way (credits to @mathguy)
select id, trim(regexp_substr(value,'[^,]+', 1, level) ) value, level
from tbl1
connect by regexp_substr(value, '[^,]+', 1, level) is not null
and PRIOR id = id
and PRIOR SYS_GUID() is not null
order by id, level;
If you want an "ANSIer" approach go with a CTE:
with t (id,res,val,lev) as (
select id, trim(regexp_substr(value,'[^,]+', 1, 1 )) res, value as val, 1 as lev
from tbl1
where regexp_substr(value, '[^,]+', 1, 1) is not null
union all
select id, trim(regexp_substr(val,'[^,]+', 1, lev+1) ) res, val, lev+1 as lev
from t
where regexp_substr(val, '[^,]+', 1, lev+1) is not null
)
select id, res,lev
from t
order by id, lev;
OUTPUT
id val lev
1 AA 1
1 UT 2
1 BT 3
1 SK 4
1 SX 5
2 AA 1
2 UT 2
2 SX 3
3 UT 1
3 SK 2
3 SX 3
3 ZF 4
Another recursive approach by MT0 but without regex:
WITH t ( id, value, start_pos, end_pos ) AS
( SELECT id, value, 1, INSTR( value, ',' ) FROM tbl1
UNION ALL
SELECT id,
value,
end_pos + 1,
INSTR( value, ',', end_pos + 1 )
FROM t
WHERE end_pos > 0
)
SELECT id,
SUBSTR( value, start_pos, DECODE( end_pos, 0, LENGTH( value ) + 1, end_pos ) - start_pos ) AS value
FROM t
ORDER BY id,
start_pos;
I've tried 3 approaches with a 30000 rows dataset and 118104 rows returned and got the following average results:
My recursive approach: 5 seconds
MT0 approach: 4 seconds
Mathguy approach: 16 seconds
MT0 recursive approach no-regex: 3.45 seconds
@Mathguy has also tested with a bigger dataset:
In all cases the recursive query (I only tested the one with regular
substr and instr) does better, by a factor of 2 to 5. Here are the
combinations of # of strings / tokens per string and CTAS execution
times for hierarchical vs. recursive, hierarchical first. All times in
seconds
30,000 x 4: 5 / 1.
30,000 x 10: 15 / 3.
30,000 x 25: 56 / 37.
5,000 x 50: 33 / 14.
5,000 x 100: 160 / 81.
10,000 x 200: 1,924 / 772
A:
This will get the values without requiring you to remove duplicates or having to use a hack of including SYS_GUID() or DBMS_RANDOM.VALUE() in the CONNECT BY:
SELECT t.id,
v.COLUMN_VALUE AS value
FROM TBL1 t,
TABLE(
CAST(
MULTISET(
SELECT TRIM( REGEXP_SUBSTR( t.value, '[^,]+', 1, LEVEL ) )
FROM DUAL
CONNECT BY LEVEL <= REGEXP_COUNT( t.value, '[^,]+' )
)
AS SYS.ODCIVARCHAR2LIST
)
) v
Update:
Returning the index of the element in the list:
Option 1 - Return a UDT:
CREATE TYPE string_pair IS OBJECT( lvl INT, value VARCHAR2(4000) );
/
CREATE TYPE string_pair_table IS TABLE OF string_pair;
/
SELECT t.id,
v.*
FROM TBL1 t,
TABLE(
CAST(
MULTISET(
SELECT string_pair( level, TRIM( REGEXP_SUBSTR( t.value, '[^,]+', 1, LEVEL ) ) )
FROM DUAL
CONNECT BY LEVEL <= REGEXP_COUNT( t.value, '[^,]+' )
)
AS string_pair_table
)
) v;
Option 2 - Use ROW_NUMBER():
SELECT t.id,
v.COLUMN_VALUE AS value,
ROW_NUMBER() OVER ( PARTITION BY id ORDER BY ROWNUM ) AS lvl
FROM TBL1 t,
TABLE(
CAST(
MULTISET(
SELECT TRIM( REGEXP_SUBSTR( t.value, '[^,]+', 1, LEVEL ) )
FROM DUAL
CONNECT BY LEVEL <= REGEXP_COUNT( t.value, '[^,]+' )
)
AS SYS.ODCIVARCHAR2LIST
)
) v;
A:
Vercelli posted a correct answer. However, with more than one string to split, connect by will generate an exponentially-growing number of rows, with many, many duplicates. (Just try the query without distinct.) This will destroy performance on data of non-trivial size.
One common way to overcome this problem is to use a prior condition and an additional check to avoid cycles in the hierarchy. Like so:
select id, trim(regexp_substr(value,'[^,]+', 1, level) ) value, level
from tbl1
connect by regexp_substr(value, '[^,]+', 1, level) is not null
and prior id = id
and prior sys_guid() is not null
order by id, level;
See, for example, this discussion on OTN: https://community.oracle.com/thread/2526535
| {
"pile_set_name": "StackExchange"
} |
Q:
Google Client API v3 - update a file on drive using Python
I'm trying to update the content of a file from a python script using the google client api. The problem is that I keep receiving error 403:
An error occurred: <HttpError 403 when requesting https://www.googleapis.com /upload/drive/v3/files/...?alt=json&uploadType=resumable returned "The resource body includes fields which are not directly writable.
I have tried to remove metadata fields, but didn't help.
The function to update the file is the following:
# File: utilities.py
from googleapiclient import errors
from googleapiclient.http import MediaFileUpload
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
def update_file(service, file_id, new_name, new_description, new_mime_type,
new_filename):
"""Update an existing file's metadata and content.
Args:
service: Drive API service instance.
file_id: ID of the file to update.
new_name: New name for the file.
new_description: New description for the file.
new_mime_type: New MIME type for the file.
new_filename: Filename of the new content to upload.
new_revision: Whether or not to create a new revision for this file.
Returns:
Updated file metadata if successful, None otherwise.
"""
try:
# First retrieve the file from the API.
file = service.files().get(fileId=file_id).execute()
# File's new metadata.
file['name'] = new_name
file['description'] = new_description
file['mimeType'] = new_mime_type
file['trashed'] = True
# File's new content.
media_body = MediaFileUpload(
new_filename, mimetype=new_mime_type, resumable=True)
# Send the request to the API.
updated_file = service.files().update(
fileId=file_id,
body=file,
media_body=media_body).execute()
return updated_file
except errors.HttpError as error:
print('An error occurred: %s' % error)
return None
And here there is the whole script to reproduce the problem.
The goal is to substitute a file, retrieving its id by name.
If the file does not exist yet, the script will create it by calling insert_file (this function works as expected).
The problem is update_file, posted above.
from __future__ import print_function
from utilities import *
from googleapiclient import errors
from googleapiclient.http import MediaFileUpload
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
def get_authenticated(SCOPES, credential_file='credentials.json',
token_file='token.json', service_name='drive',
api_version='v3'):
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
store = file.Storage(token_file)
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets(credential_file, SCOPES)
creds = tools.run_flow(flow, store)
service = build(service_name, api_version, http=creds.authorize(Http()))
return service
def retrieve_all_files(service):
"""Retrieve a list of File resources.
Args:
service: Drive API service instance.
Returns:
List of File resources.
"""
result = []
page_token = None
while True:
try:
param = {}
if page_token:
param['pageToken'] = page_token
files = service.files().list(**param).execute()
result.extend(files['files'])
page_token = files.get('nextPageToken')
if not page_token:
break
except errors.HttpError as error:
print('An error occurred: %s' % error)
break
return result
def insert_file(service, name, description, parent_id, mime_type, filename):
"""Insert new file.
Args:
service: Drive API service instance.
name: Name of the file to insert, including the extension.
description: Description of the file to insert.
parent_id: Parent folder's ID.
mime_type: MIME type of the file to insert.
filename: Filename of the file to insert.
Returns:
Inserted file metadata if successful, None otherwise.
"""
media_body = MediaFileUpload(filename, mimetype=mime_type, resumable=True)
body = {
'name': name,
'description': description,
'mimeType': mime_type
}
# Set the parent folder.
if parent_id:
body['parents'] = [{'id': parent_id}]
try:
file = service.files().create(
body=body,
media_body=media_body).execute()
# Uncomment the following line to print the File ID
# print 'File ID: %s' % file['id']
return file
except errors.HttpError as error:
print('An error occurred: %s' % error)
return None
# If modifying these scopes, delete the file token.json.
SCOPES = 'https://www.googleapis.com/auth/drive'
def main():
service = get_authenticated(SCOPES)
# Call the Drive v3 API
results = retrieve_all_files(service)
target_file_descr = 'Description of deploy.py'
target_file = 'deploy.py'
target_file_name = target_file
target_file_id = [file['id'] for file in results if file['name'] == target_file_name]
if len(target_file_id) == 0:
print('No file called %s found in root. Create it:' % target_file_name)
file_uploaded = insert_file(service, target_file_name, target_file_descr, None,
'text/x-script.phyton', target_file_name)
else:
print('File called %s found. Update it:' % target_file_name)
file_uploaded = update_file(service, target_file_id[0], target_file_name, target_file_descr,
'text/x-script.phyton', target_file_name)
print(str(file_uploaded))
if __name__ == '__main__':
main()
In order to try the example, is necessary to create a Google Drive API from https://console.developers.google.com/apis/dashboard,
then save the file credentials.js and pass its path to get_authenticated(). The file token.json will be created after the first
authentication and API authorization.
A:
The problem is that the metadata 'id' can not be changed when updating a file, so it should not be in the body. Just delete it from the dict:
# File's new metadata.
del file['id'] # 'id' has to be deleted
file['name'] = new_name
file['description'] = new_description
file['mimeType'] = new_mime_type
file['trashed'] = True
I tried your code with this modification and it works
| {
"pile_set_name": "StackExchange"
} |
Q:
Tic tac toe in JavaScript with minimax algorithm giving error maximum call stack size exceed
I am doing an assignment tic tac toe game. My minimax algorithm works fine on its own with an array and two players provided but when working with html collections of divs it gives an error of maximum call stack size exceed. I don't understand why it is happening. By searching google I know that my function somewhere calling itself over and over again but can't figure it out what to do solve this issue. I tried converting the .cells div collection into an array but still the same error occurred. Anybody please help me with this.
Thank you.
var humanPlayer, aiPlayer;
humanPlayer = 'x';
aiPlayer = 'o';
var cells = document.querySelectorAll(".cell");
/** Tic Tac Toe game object **/
var TicTacToe = {
checkWinner : function(arr, player){
if(
(arr[0] === player && arr[1] === player && arr[2] === player)||
(arr[3] === player && arr[4] === player && arr[5] === player)||
(arr[6] === player && arr[7] === player && arr[8] === player)||
(arr[0] === player && arr[3] === player && arr[6] === player)||
(arr[1] === player && arr[4] === player && arr[7] === player)||
(arr[2] === player && arr[5] === player && arr[8] === player)||
(arr[0] === player && arr[4] === player && arr[8] === player)||
(arr[2] === player && arr[4] === player && arr[6] === player)
){
return true;
}
else{
return false;
}
},//checkWinner function.
getAvailableSpots : function(arr){
var spots = [];
for(var i = 0; i < arr.length; i++){
if(arr[i].textContent !== "x" && arr[i].textContent !== "o"){
spots.push(i);
}
}
return spots;
},// getAvailableSpots function.
minimax : function(newBoard, player){
newBoard = Array.from(newBoard);
var availSpots = this.getAvailableSpots(newBoard);
if(this.checkWinner(newBoard, aiPlayer)){
return {score: 10};
}
else if(this.checkWinner(newBoard, humanPlayer)){
return {score: -10};
}
else if(availSpots.length === 0){
return {score: 0};
}
var moves = [];
for(var j = 0; j < availSpots.length; j++){
var move = {};
move.index = availSpots[j];
newBoard[availSpots[j]] = player;
if(player === aiPlayer){
var result1 = this.minimax(newBoard, humanPlayer);
move.score = result1.score;
}
else{
var result2 = this.minimax(newBoard, aiPlayer);
move.score = result2.score;
}
newBoard[availSpots[j]] = move.index;
moves.push(move);
}
var bestMove;
if(player === aiPlayer){
var bestScore1 = -100000;
for(var k = 0; k < moves.length; k++){
if(moves[k].score > bestScore1){
bestScore1 = moves[k].score;
bestMove = k;
}
}
}
else{
var bestScore2 = 100000;
for(var l = 0; l < moves.length; l++){
if(moves[l].score < bestScore2){
bestScore2 = moves[l].score;
bestMove = l;
}
}
}
return moves[bestMove];
}// minimax function.
};//TicTacToe object literal.
function move(e){
if(e.target.className === "cell" && e.target.textContent === ""){
e.target.textContent = humanPlayer;
var result = TicTacToe.minimax(cells, aiPlayer);
cells[result.index].textContent = aiPlayer;
}
}
document.querySelector('.cells').addEventListener('click', move);
.*{
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.cells {
width: 390px;
height: 390px;
margin: 50px auto;
}
.cell {
width:128px;
height: 128px;
border: 1px solid #dedede;
float: left;
text-align: center;
line-height: 128px;
font-size: 80px;
font-weight: bold;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="cells">
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
</div>
</body>
</html>
A:
It's because your minmax function is recursive, meaning it tries every possible combination chain. To not repeat the same chain over and over, it creates a clone of the board on every recursion (via Array.from(newBoard)).
Now, back when you were testing it with primitve arrays, that copying of the board worked fine. However, now your board array is actually containing DOM objects, which will not be cloned by Array.from(). So your AI is basically altering the cells for every attempt which causes a stack overflow.
My suggestion would be to convert the current board to a primitive array before passing it to the minmax function.
var humanPlayer, aiPlayer;
humanPlayer = 'x';
aiPlayer = 'o';
var cells = document.querySelectorAll(".cell");
/** Tic Tac Toe game object **/
var TicTacToe = {
checkWinner : function(arr, player){
if(
(arr[0] === player && arr[1] === player && arr[2] === player)||
(arr[3] === player && arr[4] === player && arr[5] === player)||
(arr[6] === player && arr[7] === player && arr[8] === player)||
(arr[0] === player && arr[3] === player && arr[6] === player)||
(arr[1] === player && arr[4] === player && arr[7] === player)||
(arr[2] === player && arr[5] === player && arr[8] === player)||
(arr[0] === player && arr[4] === player && arr[8] === player)||
(arr[2] === player && arr[4] === player && arr[6] === player)
){
return true;
}
else{
return false;
}
},//checkWinner function.
getAvailableSpots : function(arr){
var spots = [];
for(var i = 0; i < arr.length; i++){
if(arr[i] !== "x" && arr[i] !== "o"){
spots.push(i);
}
}
return spots;
},// getAvailableSpots function.
minimax : function(newBoard, player){
newBoard = Array.from(newBoard);
var availSpots = this.getAvailableSpots(newBoard);
if(this.checkWinner(newBoard, aiPlayer)){
return {score: 10};
}
else if(this.checkWinner(newBoard, humanPlayer)){
return {score: -10};
}
else if(availSpots.length === 0){
return {score: 0};
}
var moves = [];
for(var j = 0; j < availSpots.length; j++){
var move = {};
move.index = availSpots[j];
newBoard[availSpots[j]] = player;
if(player === aiPlayer){
var result1 = this.minimax(newBoard, humanPlayer);
move.score = result1.score;
}
else{
var result2 = this.minimax(newBoard, aiPlayer);
move.score = result2.score;
}
newBoard[availSpots[j]] = move.index;
moves.push(move);
}
var bestMove;
if(player === aiPlayer){
var bestScore1 = -100000;
for(var k = 0; k < moves.length; k++){
if(moves[k].score > bestScore1){
bestScore1 = moves[k].score;
bestMove = k;
}
}
}
else{
var bestScore2 = 100000;
for(var l = 0; l < moves.length; l++){
if(moves[l].score < bestScore2){
bestScore2 = moves[l].score;
bestMove = l;
}
}
}
return moves[bestMove];
}// minimax function.
};//TicTacToe object literal.
function move(e){
if(e.target.className === "cell" && e.target.textContent === ""){
e.target.textContent = humanPlayer;
var result = TicTacToe.minimax(domBoardToArray(cells), aiPlayer);
cells[result.index].textContent = aiPlayer;
}
}
function domBoardToArray(cells){
return Array.prototype.slice.call(cells).map(function (cell){
return cell.textContent
})
}
document.querySelector('.cells').addEventListener('click', move);
.*{
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.cells {
width: 390px;
height: 390px;
margin: 50px auto;
}
.cell {
width:128px;
height: 128px;
border: 1px solid #dedede;
float: left;
text-align: center;
line-height: 128px;
font-size: 80px;
font-weight: bold;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="cells">
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
</div>
</body>
</html>
| {
"pile_set_name": "StackExchange"
} |
Q:
Maven: Fatal error compiling: invalid target release: 1.8
We just upgraded the project from jdk 1.6 to jdk 1.8. While building the project in my machine, i'm getting following error.
[ERROR] Failed to execute goal
org.apache.maven.plugins:maven-compiler-plugin:3.3:compile
(default-compile) on project exception: Fatal error compiling: invalid
target release: 1.8 -> [Help 1]
Here is the maven compiler plugin which is been used
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
I looked at the many post and most of them were related with not having the correct version configured for java_home. I verified all of these aspects and couldn't find any of them alarming.
Java version -
qadeersmsiphone:main pdubey$ java -version
java version "1.8.0_51"
Java(TM) SE Runtime Environment (build 1.8.0_51-b16)
Java HotSpot(TM) 64-Bit Server VM (build 25.51-b03, mixed mode)
Maven Version -
qadeersmsiphone:main pdubey$ mvn -version
Apache Maven 3.1.1 (0728685237757ffbf44136acec0402957f723d9a; 2013-09-17 08:22:22-0700)
Maven home: /usr/share/maven
Java version: 1.8.0_51, vendor: Oracle Corporation
Java home: /Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk/Contents/Home/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "mac os x", version: "10.8.5", arch: "x86_64", family: "mac"
and I checked that while building the project maven uses jdk 1.8
qadeersmsiphone:main pdubey$ mvn install -debug
Apache Maven 3.1.1 (0728685237757ffbf44136acec0402957f723d9a; 2013-09-17 08:22:22-0700)
Maven home: /usr/share/maven
Java version: 1.8.0_51, vendor: Oracle Corporation
Java home: /Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk/Contents/Home/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "mac os x", version: "10.8.5", arch: "x86_64", family: "mac"
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from /usr/share/maven/conf/settings.xml
[DEBUG] Reading user settings from /Users/pdubey/.m2/settings.xml
[DEBUG] Using local repository at /Users/pdubey/.m2/repository
[DEBUG] Using manager EnhancedLocalRepositoryManager with priority 10.0 for /Users/pdubey/.m2/repository
[INFO] Scanning for projects...
UPDATE: I could get it working by removing the
maven-compiler-plugin in pom file (Ideally, i don't want to do this). And i also observed that even if i
remove this plugin, maven by default downloads the 3.3 version of
compiler plugin in my local repo. I'm not sure what's wrong in this
plugin although source and target appears to be correct.
A:
Check the java and Javac version - My Java version was 1.8.0_51
$ java -version
java version "1.8.0_51"
But javac version was pointing to old jdk 1.7.0_67
$ javac -version
javac 1.7.0_67
There are couple of thing which we should try -
Ensure that symbolic link is pointing to correct jdk. If not, remove existing link and create new one for your jdk
cd /System/Library/Frameworks/JavaVM.framework/Versions/
rm CurrentJDK
ln -s /Library/Java/JavaVirtualMachines/<jdk version>.jdk/Contents/ CurrentJDK
In /Library/Java/Extension, i had a tools.jar. I believe, this was from old jdk.
cd /Library/Java/Extensions
-rw-r--r-- 1 root admin 15286304 Jan 14 2015 tools.jar
Remove this
sudo rm -rf /Library/Java/Extensions
point 2 did the trick for me :)
A:
Sometimes this problem is related to a JAVA_HOME used by maven.
In my particular case I tried to start an install target and had an exact the subj message.
Then I just tried an mvn -version command and I realized that it uses jdk7
Then I run in a console set JAVA_HOME=C:\Java\jdk8 (my jdk path, so your own could be different)
Then typed mvn clean install test and it worked just fine at last
Good luck!
| {
"pile_set_name": "StackExchange"
} |
Q:
Context menu on Intellj IDEA
I have installed Intellij IDEA 10 on Linux (Ubuntu 8.04) and the way the context menu works is annoying me.
The context menu is visible as long as I keep the right button pressed (if I release the button, the menu disappears). To click on a menu item, I have to position the cursor upon the item with the right button pressed and then release it. I've also figured out two alternative ways to keep the menu visible with the right button released:
To right-click, drag, and release the button outside the context menu.
Ctrl + Right-click or Shift + Right-click
But I would expect the "normal" behavior: that when I right-click and release, the menu keeps visible until the next click (on an item or outside the menu). Is there a way to change this behavior?
Thanks in advance.
A:
This issue seems to be caused by the Eclipse Keymap in IDEA, it doesn't happen if you choose another keymap. Please see http://youtrack.jetbrains.net/issue/IDEA-66182.
I've also found a workaround for this problem which is very simple:
Open Settings | Keymap, press Copy button to create an editable copy of the Eclipse keymap, in the copy find "Show Context Menu" action in the Other group, it has multiple shortcuts defined, delete "Button3 Click" from the list of shortcuts, press Apply. Context menu will no longer disappear after right click.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to compile a github project in Android Studio?
I wanted to download and compile a Github Android App. I am a web developer with little to no experience with Android Studio. So far I have installed the Android Studio and added the files as in the repo in the studio. But I do not know how to compile these files into an apk file.
A:
You can follow below steps
Step1:
Clone or download github project
Step2
Extract it.
Step 3
Open it in Android Studio. File >> Open...
Step 4
After successful build. From toolbar
Build >> Build Apk(s)
Where to find that apk?
you can find that apk in your project folder inside
~\app\build\outputs\apk\debug\app-debug.apk
| {
"pile_set_name": "StackExchange"
} |
Q:
Which math discipline should i learn to become familiar with rewriting equations?
In my self study of calculus, I've found that there are examples in the books i read where the author rewrites an equation or expression either as part of a logical step in a proof, or to simplify it so that he can perform other desired operations on it.
But when it comes time for me to try practice questions, i look at the expression/equation and have no intuition or idea as to how to meaningfully simplify or rewrite it to suit my purpose. I also have a tendency of looking at expressions and initially getting intimidated by their complexity
Thus I'm interested in studying a field which will help me become comfortable with working with, manipulating and rewriting expressions/equations including basic operators, exponents, log and trig functions.
From my limited understanding basic algebra would be a good starting place, but which more advanced fields should i study to get an even stronger/more advanced ability to be comfortable with/manipulate expressions and equations?
A:
In my opinion one learns those kind of manipulation by experience and i don't think that there is any area which do not uses such things. Consider for example that you need to prove $|x-y|\leq |x-z|+|z-y|\ \forall\ x,y,z\in \mathbb{R}$. The standard trick is to write $x-y=x-z+z-y$ in LHS and then proceed using the properties of modulus. Now a person who sees it for the first time may wonder that how one manipulates such thing but slowly while doing similar kind of operations one gets accustomed to it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Two divs float left, one float right in row
I'm trying to have 3 divs in one row. I've the code below and the biggest problem is, that second div doesn't end where third starts. The line also should be aligned vertically to center of texts. Result should look like this https://www.linksketch.com/XOfi
Texts in the first div may vary by length. So I can't specify it's width (or width of second one).
.activityType {
color: #007b87;
font-size: 20px;
float: left;
margin: 0 5px 0 0;
}
.lineActivities {
height: 1px;
margin-bottom: 10px;
margin-left: 10px;
background-color: #afbc16;
opacity: .4;
margin: 10px 10px 2px 0;
overflow: hidden;
}
.activityDate {
color: #007b87;
font-size: 15px;
float: right;
margin-right: 25px;
width: 140px;
}
<!-- First div with text aligned to left. -->
<div class="activityType">
User created tiket
</div>
<!-- Second div with colored line going from 1. to 3. div (filling the gap). -->
<div class="lineActivities">
</div>
<!-- Third div with text. -->
<div class="activityDate">
23. 02. 2015 01:31:33
</div>
A:
You can do this without an intervening third div if you wrap them items into one div...then use a pseudo-element..like so:
* {
box-sizing: border-box;
}
.activity {
width: 80%;
margin: auto;
overflow: hidden;
}
.activity:after {
content: '';
border-bottom: dotted 2px tomato;
display: block;
overflow: hidden;
height: 1.5em; /* controls position of line vertically */
}
.activityType {
color: #007b87;
float: left;
margin-right: 1em;
}
.activityDate {
color: #007b87;
float: right;
margin-left: 1em;
}
<div class="activity">
<p class="activityType">User created ticket</p>
<p class="activityDate">23. 02. 2015 01:31:33</p>
</div>
<div class="activity">
<p class="activityType">Lorem ipsum dolor sit amet.</p>
<p class="activityDate">23. 02. 2015 01:31:33</p>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
Do 2 different Availability Zones in EC2 act as a WAN or a LAN?
I am trying to establish a RabbitMQ Cluster on EC2 over 2 availability zones.
In its docs, RabbitMQ mentions to avoid network partition on the cluster nodes.
Do 2 different Availability Zones in EC2 act as a WAN or a LAN?
Can anyone direct me to a link?
Thank you.
A:
RabbitMQ cluster is not recommended in case of WAN network (say 2 Regions) . But the connection between availability zones can be viewed as a LAN.
We running RabbitMQ cluster in differnt AZ's with no issues.
AWS doesn't tells you how far away each AZ from each other, but you can assume it's close enough to be viewed as a LAN. One of the characteristics of a LAN is Coverage area is generally a few kilometers.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can't invoke function in a same-domain iframe in Firefox
I write code for Greasemonkey and I have an iframe without a src in which I add code like this:
var appendToHead = function(iframe, content) {
var doc = iframe[0].contentWindow.document;
var element = doc.createElement('script');
element.type = 'text/javascript';
element.text = content;
doc.head.appendChild(element);
};
I see in Firebug that the function is added in the iframe. But when I try to get them, EG
frames[0].contentWindow.functionName I get undefined and still see them in debugger.
Before I used Greasemonkey this approach worked well. How can invoke these functions?
A:
See How do I access an iframe's javascript from a userscript.
You would invoke the function like: frames[0].functionName();, but it must be from injected code, not the Greasemonkey script scope. (Except that @grant none might work in some cases.)
You may also need a delay, depending. Post a full working example of what you are doing.
| {
"pile_set_name": "StackExchange"
} |
Q:
React setting and clearing state through functions
React newbie here (talk about a steep learning curve!).
Building a simple component with a keyword input, and a clear button - but struggling to understand why my state value keeps getting recorded as an object?
Any advice would be awesome - thank you!
` class FacetsFilter extends React.Component {
constructor(props) {
super(props);
this.state = {
facetsKeyword: ''
};
}
handleOnChange(e) {
this.setState({
facetsKeyword: e
});
console.log('This is it : ' + e);
}
handleClearClick(e) {
e.preventDefault();
this.setState({
facetsKeyword: ''
});
}
render() {
return (
<div className="facetsFilter">
<h3 className="facetsTitle title is-5">Refine results</h3>
<div className="facetsKeywordFilter columns is-gapless">
<div className="column">
<TextField
id="facetsKeywordInput"
className="facetsKeywordInput"
hintText="Keyword filter"
onChange={this.handleOnChange.bind(this)}
value={this.state.facetsKeyword}
/>
</div>
<div className="column is-narrow">
<IconButton
className="facetsClearButton"
tooltip="Clear filter"
onClick={this.handleClearClick.bind(this)} >
<NavigationClose />
</IconButton>
</div>
</div>
<div className="facetsList body-2">
{facetsList.map((item, index) => (
<div>
<h3 key={index} className="facetsCategoryTitle">{item.category}</h3>
<div className="facetListItems">
{item.facets.map((subitem) => (
<div>{subitem}</div>
))}
</div>
</div>
))}
</div>
</div>
);
}
}
export default FacetsFilter;`
Im simply usure why when I console.log the onChange function that it returns as [Object Object].
Thank you for any advice.
A:
passed parameter e is not text but javascript event object. So if you want to get changed text, use e.target.value.
handleOnChange(e) {
const {value} = e.target;
this.setState({
facetsKeyword: value
});
console.log('This is it : ' + value);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
"I feel like such a fool" Possible?
I was thinking, is it grammatically correct to say, "I feel like such a fool"?
In my opinion it can be either "I feel like a fool" or "I feel such a fool".
A:
There appears to be a difference in usage between British vs. American English for this sense of feel. British English uses "feel such a" and American English (the dialect I speak) uses "feel like such a". And both dialects use "feel like a".
This is backed up by the data I found using the British National Corpus (BNC) and the Corpus of Contemporary American English (COCA):
BNC:
"feel like such a": no relevant results
"feel such a": 8 relevant results
"feel like a": 224 results, but not all are relevant (and I don't feel like getting an exact number)
COCA:
"feel like such a": 31 relevant results
"feel such a": 1 relevant result
"feel like a": 2791 results, but not all are relevant (and I really don't feel like getting an exact number as this is even larger than the BNC results)
Note: When I say "relevant results", this means I have excluded irrelevant results from the totals, such as "I feel such a connection".
| {
"pile_set_name": "StackExchange"
} |
Q:
Nested Observable/Promise (trying to block/wait flow in mapper function)
I have the following code in an Angular app:
services$
.pipe(
map(serviceModels => {
serviceModels
.forEach((srv, srvIdx) => {
// Resolve images in services
srv.images.forEach(async (img, imgIdx) => {
serviceModels[srvIdx].images[imgIdx] = await this.imageSrv.resolveImage(img).toPromise();
});
});
return serviceModels;
});
[...]
Result is a single emition with one value change afterwards.
emit -> service.image[0] // 'unrendered-url' -> (wait) -> service.image[0] // correct-url/image-path
I'm trying to resolve the image from a service (this.imageSrv) that takes a string and returns a observable/promise with a rendered string. All I want is the code to block (or map() to hold the emition until the images are resolved) because I get two values in Angular for the services[0].images[0].
The easy way out is to put promises in the service[0].images array and img | async in the template engine, but I'd like to avoid that and maybe learn something new.
A:
You're currently trying to run new observables inside a map - which is for synchronously transforming the result of an observable into a different structure. I will ignore the attempt to await the promise, as that will be addressed by using the underlying observables directly.
The approach I'm going to take:
Use switchMap to chain an inner observable to the outer observable
Flatten the nested image arrays
Create an array of observables from the flattened image array
Run the observable array in a forkJoin
Update the resolved images in the serviceModels when the forkJoin completes
Return the serviceModels in a mapTo
services$.pipe(
switchMap(serviceModels => {
// flatten images
const images = serviceModels.reduce((acc, srv) => acc.concat(srv.images), []);
// map to array of observables
const observables = images.map(img => this.resolveImage(img));
// run observables in parallel
return forkJoin(observables).pipe(
tap(images => {
// loop over original nested arrays
// extract image from flattened images result
let flatIdx = 0;
serviceModels.forEach(srv => {
srv.images.forEach((img, imgIdx) => {
srv.images[imgIdx] = images[flatIdx++];
});
});
}),
// return serviceModels from the outer observable
mapTo(serviceModels)
)
})
)
[...]
By the way, I would recommend not overwriting the original images with the resolved images. While this is valid Javascript, you'll run into issues with Typescript if you're using types (and I don't see any reason not to).
DEMO: https://stackblitz.com/edit/angular-a6fblk
| {
"pile_set_name": "StackExchange"
} |
Q:
Aligning Bootstrap Radio Buttons with text
I am trying to get my radio buttons to align but I am having difficulty doing this. What I am trying to do is have the buttons align with an indentation because I am going to display a caret if the option has been selected. I also want the text to come up just a bit because it's not inline with the actual radio button.
input[type=radio] {
z-index: 3;
width: 26px;
height: 26px;
-moz-appearance: none;
}
label {
font-weight: normal;
font-size: 1.5em;
cursor: pointer;
}
.question-label {
margin-left: 15px;
}
<div class="radio">
<label>
<span class="button"><input type="radio" name="optionsRadios" value="20"></span>
<span class="question-label">True</span>
</label>
</div>
<div class="radio">
<label>
<span><i class="fa fa-caret-right fa-2x correct-answer" aria-hidden="true"></i></span>
<span class="button"><input type="radio" name="optionsRadios" value="20"></span>
<span class="question-label">False</span>
</label>
</div>
Here is what it looks like right now.
A:
So I did a few things to your code:
Align the items inside the label using inline-blocks:
.radio label > span {
display: inline-block;
vertical-align: middle;
}
This is better than positioning using px.
Now add the caret icon to both radio so that the horizontal alignment will be automatically done (and you can contextually show the green caret). To make that work apply these:
.correct-answer {
color: green;
}
.wrong-answer {
opacity: 0;
}
Let me know your feedback. Thanks!
input[type=radio] {
z-index: 3;
width: 26px;
height: 26px;
-moz-appearance: none;
}
label {
font-weight: normal;
font-size: 1.5em;
cursor: pointer;
}
.question-label {
margin-left: 15px;
}
.radio label > span {
display: inline-block;
vertical-align: middle;
}
.correct-answer {
color: green;
}
.wrong-answer {
opacity: 0;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet">
<div class="radio">
<label>
<span><i class="fa fa-caret-right fa-2x wrong-answer" aria-hidden="true"></i></span>
<span class="button"><input type="radio" name="optionsRadios" value="20"></span>
<span class="question-label">True</span>
</label>
</div>
<div class="radio">
<label>
<span><i class="fa fa-caret-right fa-2x correct-answer" aria-hidden="true"></i></span>
<span class="button"><input type="radio" name="optionsRadios" value="20"></span>
<span class="question-label">False</span>
</label>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
tableless CSS problem
In general I know how to use css but not advanced css
So I need some help in order to start. Unfortunately I can't find any good and decent guide for tables without css and the part I want to do is very tricky. So here is what I want and what I've done so far.
The height is not fixed by the way so I want it flexible because the main text might be very long or very small
Here is what I've done so far
http://jsfiddle.net/VmnDj/1/
This doesn't seem to work properly though because the minimum height is where the main text is and it never includes the whole picture. Some part of the picture is out of the container. Please can you contribute on this and explain me why do you have to take each step? My purpose is to learn from this and not just the solution. If you need something more please let me know.
Thank you very much in advance
A:
Try this:
JSFIDDLE: http://jsfiddle.net/86FMw/
Notice that there is no fixed height and the box will grow when the main text is longer.
HTML
<div class="cartitem">
<div class="left">
<img src="http://images.pictureshunt.com/pics/p/pear-5428.jpg" width="60" height="60" alt=""/>
</div>
<div class="toptext">
top text top text top text
</div>
<p>
text text text text<br/>
text text text text text text text text text text text text <br/>
text text text text text text text text <br/>
</p>
<div class="buttonbar">
<button>click me</button>
</div>
</div>
CSS
.cartitem {
position: relative;
padding-left: 80px;
border: 1px solid #333;
}
.left {
position: absolute;
top: 0;
left: 0;
bottom: 0;
width: 80px;
}
.toptext {
background: silver;
}
.buttonbar {
text-align: right;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
how to add maxlength for TextAreaFor in View using razor engine
I have a TextArea() control in my View implemented using Razor Engine.
@Html.TextArea("EventNature",new { style = "width: 200px; height: 100px;" })
How can i set the Maxlength attribute for this control?
is there any built in Attribute in RazorEngine or do i have to use scripts?
A:
You can do it like:
@Html.TextArea("EventNature",new { maxlength=50, // or other value
style = "width: 200px; height: 100px;" })
Just be aware it's an HTML5 attribute
maxlength HTML5
The maximum number of characters (Unicode code points) that the user can enter. If it is not specified, the user can enter an unlimited number of characters.
MDN
Javascript(using jQuery) validation for HTML <5:
$('#EventNature').keypress(function(){
if (this.value.length >= 10) // allowing you to enter only 10 chars.
return false;
});
DEMO
A:
This also works for the TextAreaFor helper with more than one anonymous type in new
Confirmed to work fine in Visual Studio 2015 with MVC 5
@Html.TextAreaFor(model => model.Comments, 5, 500, new {maxlength=4000, @class = "form-control" })
| {
"pile_set_name": "StackExchange"
} |
Q:
would you use AOP to track points?
would you use springs AOP (aspects) if you had to track user points throughout your application?
it seems like a potential fit, since points are awarded etc. throughout the application, kind of like security checks.
(just reading on AOP, trying to grasp its potential and usage other than say security or logging).
when you wire up your joinpoints, are they "setup" on the fly or once? I'm just concerned as to how this effects performance, or is it a non-issue really?
A:
Yes, this sounds like a good use of AOP.
As to the specifics of how it works, that depends which AOP framework you're using. Some do the aspect weaving at compile time (e.g. AspectJ CTW), some do it when the lasses are loaded (e.g. AspectJ LTW), some do it dynamically at runtime (e.g. Spring AOP).
There is an inevitable performance impact, but don't let that stop you from giving it a go.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why didn't Jack O'Neill retire?
Stargate SG-1 starts with O'Neill being pulled, reluctantly, out of retirement. At the time, he's one of very few people to have been through the Stargate, and his experience is direly needed.
As of Stargate Universe, SG-1 is scattered to the winds, the Stargate project is quite mature and filled with knowledgeable experienced people, and while O'Neill's knowledge and expertise is certainly helpful, it doesn't seem like there's the vital need for him that there once was.
So why did he take up a position in the military hierarchy instead of retiring again?
A:
Well, before the season one there had been completely nothing military could offer Jack that he would have liked. So he retired to spend lonely nights on the roof with the telescope looking at the stars. And as for Stargate Universe we have completely another case. For eight years he had seen things the majority of people have never ever dreamed about; he made friends anobody could only wish to have and "Let's save this world once again" thing never gets old. Yes, the original SG-1 no longer exists, but from what we saw in the end of SGU season 1 Sam is under Jack's direct command (sort of) and Daniel is always around. So why retire? He would just become a lonely old man with a telescope and hurting knees and a lake without fish while his friends and colleagues are busy saving the universe. And when as a general he has practically everything an older man (no offence, Jack!) could dream of, and just in case something happens to his friends he is the first to be informed (let's face it: everybody knows how many Earth's ships have been destroyed and how many of their captains are dead know) and that's much more better than to be retired and with comletely no information. (Although Sam/Jack shippers would tell you a completely another story, but right now we aren't talking about them)
A:
Before SG1, there was no reason for him to stick around. He has done his job and nuked Ra. Mission Accomplished. Nothing comparable to do in the future.
Whereas in SG series universe:
He always has more stuff to do
He has unique expertise which makes him effective, needed (even if not vital as the question notes) and, for that matter, leads to promotion.
He feels responsible for the rest of his team/friends/etc... as any true leader, he can't abdicate that responsibility even if the alternative is unlimited fishing he so richly deserves and wants.
A:
I believe it was in large part related to his sense of responsibility. He's in charge of Earth's Stargate project (and, I believe, almost all of Earth's off-planet operations), because he is, in effect, a war hero, for his service on SG-1.
What I often forget, though is that he also has that job because all he's done in SG-1, the reputation he's built and the contacts and allies he's made, to say nothing of his massive experience with SG-related missions, make him actually one of the absolute best choices for the job. His sense of responsibility just doesn't allow him to pass it off to someone who wouldn't be as qualified, thus risking Earth's security, as well as the safety of all the SG-teams.
| {
"pile_set_name": "StackExchange"
} |
Q:
array_merge before json encode in PHP
$myArray = array();
for($i=0;i<2;$i++){
..
.. //get the content logic here
assign it to array
$myArray["item"]["content"] = $item_content;
}
echo json_encode($myArray);
The above code produced this result:
Which has an error because I didn't merge them.
I tried to merge like this:
$finalJson = array_merge($finalJson, $myArray);
but the output of echo $finalJson is one object instead of 3.
A:
Update:
Your real problem is down to your use of array_merge on an associative array. The behaviour of array_merge is to reassign duplicate keys if they are associative (cf the docs):
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
And because $myArray is clearly using strings as keys, the values in $finalJson are being reassigned. What you need to do is either create unique keys on each iteration, or simply push the values of $myArray onto a numerically indexed $finalJson array (like I showed in my original answer below)
The problem is simply this:
$myArray["item"]["content"] = $item_content;
it's inside the loop, each time reassigning the value of $myArray["item"]["content"], and not adding it to the array. I suspect that what you wanted to do is add this at the bottom of your loop (for each new value of $myArray):
$finalJson[] = $myArray;
Then, on the next iteration, $myArray will be reassigned, and its new value will be appended to the $finalJson variable.
| {
"pile_set_name": "StackExchange"
} |
Q:
Oracle ArrayBound Stored Procedure fails only with specific field
I have a stored procedure that works and has been working for months for inserting data.
Here's the "short" version:
procedure saveApplication( in_confirmation_number varchar2 := null
,in_nonstandard_address varchar2 := null
,in_absentee_type varchar2 := null) AS
BEGIN
insert into vr_application (
confirmation_number
,nonstandard_address
,absentee_type )
values ( in_confirmation_number
,in_nonstandard_address
,in_absentee_type
);
END;
I'm working in bulk so I stuff the data in as arrays after pulling the value from a datatable.
Again, below is the "shortened" version.
private static void loadFiles(DataTable dt, string connString, ErrorLogger log)
{
OracleConnection orclconn = null;
OracleCommand cmd = null;
using (orclconn = new OracleConnection(connString))
{
orclconn.Open();
using (cmd = BuildCommand(dt))
{
cmd.Connection = orclconn;
cmd.ExecuteNonQuery();
}
}
}
private static OracleCommand BuildCommand(DataTable dt)
{
OracleCommand cmd = new OracleCommand();
cmd.CommandText = "Applications.saveApplication";
cmd.CommandType = CommandType.StoredProcedure;
cmd.ArrayBindCount = dt.Rows.Count;
cmd.BindByName = true;
string[] CONFIRMATION_NUMBER = dt
.AsEnumerable()
.Select(row => row.Field<string>("CONFIRMATION_NUMBER"))
.ToArray();
OracleParameter in_confirmation_number = new OracleParameter();
in_confirmation_number.OracleDbType = OracleDbType.Varchar2;
in_confirmation_number.Value = CONFIRMATION_NUMBER;
in_confirmation_number.ParameterName = "in_confirmation_number";
cmd.Parameters.Add(in_confirmation_number);
string[] ABSENTEE_TYPE = dt
.AsEnumerable()
.Select(row => row.Field<string>("ABSENTEE_TYPE"))
.ToArray();
OracleParameter in_absentee_type = new OracleParameter();
in_absentee_type.OracleDbType = OracleDbType.Varchar2;
in_absentee_type.Value = ABSENTEE_TYPE;
in_absentee_type.ParameterName = "in_absentee_type";
cmd.Parameters.Add(in_absentee_type);
string[] NONSTANDARD_ADDRESS = dt
.AsEnumerable()
.Select(row => row.Field<string>("NONSTANDARD_ADDRESS"))
.ToArray();
OracleParameter in_nonstandard_address = new OracleParameter();
in_absentee_type.OracleDbType = OracleDbType.Varchar2;
in_absentee_type.Value = NONSTANDARD_ADDRESS;
in_absentee_type.ParameterName = "in_nonstandard_address";
cmd.Parameters.Add(in_nonstandard_address);
return cmd;
}
Scenario 1:
nonstandard_address code is commented out. Everything works.
Scenario 2:
nonstandard_address code is not commented out. But instead of passing values into the original datatable, I hardcode the value "null". Everything works. This is where it has been for months.
Scenario 3:
the datatable for nonstandard address has a single row which has a value in nonstandard address. All other rows contain null for this column. I get an Oracle.DataAccess.Client.OracleException, #ORA-06550, with the message "Encountered the symbol ">" when expecting one of the following...."
To attempt to identify the problem, I simply looped through the values in the array. I get the same error on the last loop iteration, which is always one more than the number of records in the data table (100). But if I loop without attempting to create an Oracle Parameter for nonstandard, I get no error and only 100 loop iterations.
If I do Scenario 2 and successfully fill the table with everything except nonstandard_address, I can then run the following in Oracle, and successfully update the table.
update vr_application a
set nonstandard_address = (select nonstandard_address from unprocessed_apps b where b.confirmation_number = a.confirmation_number)
where exists (select 1 from unprocessed_apps where confirmation_number = a.confirmation_number)
Can anyone see a mistake here? Anyone seen this before? I'm baffled.
A:
Well, it was one of those "duh" moments and a good argument for having coworkers who can be an extra set of eyes.
Look at my code - I fed the address into the absentee field. This is what I had:
string[] NONSTANDARD_ADDRESS = dt
.AsEnumerable()
.Select(row => row.Field<string>("NONSTANDARD_ADDRESS"))
.ToArray();
OracleParameter in_nonstandard_address = new OracleParameter();
**in_absentee_type**.OracleDbType = OracleDbType.Varchar2;
**in_absentee_type**.Value = NONSTANDARD_ADDRESS;
**in_absentee_type**.ParameterName = "in_nonstandard_address";
cmd.Parameters.Add(in_nonstandard_address);
This is what I SHOULD have had:
string[] NONSTANDARD_ADDRESS = dt
.AsEnumerable()
.Select(row => row.Field<string>("NONSTANDARD_ADDRESS"))
.ToArray();
OracleParameter in_nonstandard_address = new OracleParameter();
**in_nonstandard_address**.OracleDbType = OracleDbType.Varchar2;
**in_nonstandard_address**.Value = NONSTANDARD_ADDRESS;
**in_nonstandard_address**.ParameterName = "in_nonstandard_address";
cmd.Parameters.Add(in_nonstandard_address);
After staring at 72 arrays like the above, my eyes just totally missed it. Thanks to Bob Jarvis for suggesting something that made the syntax problem pop out at me.
| {
"pile_set_name": "StackExchange"
} |
Q:
C++ Seconds in Date
I'm trying to write a class in which I would like to give as input a Date in the format "03.02.2019" and an integer like 4 and what I would like the code to do is the give me as a result: "07.02.2019". I think the problem that I have here is that I am not assigning the pointers correctly because I can see that the code is doing something right. It does calculate "07.02.2019" but I can't make it to give me back the result ;-). Please find the code below:
#include <iostream>
#include "Calendar.h"
#include <ctime>
using namespace std;
int main()
{
Calendar MyDate("03.02.2019");
Calendar NewDate;
NewDate = MyDate + 4;
cout << endl << NewDate.print() << endl;
cin.get();
getchar();
return 0;
}
Calender.h:
#pragma once
#include <iostream>
#include <vector>
#include <ctime>
#include <string>
using namespace std;
class Calendar
{
public:
Calendar();
Calendar(string thedate);
/*
Calendar operator-(const Calendar &TheDate);
Calendar operator-(const int &numberOfDays);
*/
Calendar operator+(const int &numberOfDays);
string print(void);
void set_Date(string dertag);
void set_Seconds();
~Calendar();
private:
vector<string>AllTheDates;
string TheDate;
int TheYear;
int TheMonth;
int TheDay;
unsigned int YearSeconds;
unsigned int MonthSeconds;
unsigned int DaySeconds;
unsigned int TotalSeconds;
string *theNewDate2print_ptr=new string;
//string theNewDate2print;
bool isdate;
};
Calendar.cpp:
#include "Calendar.h"
#include <ctime>
#include <string>
#include <sstream>
using namespace std;
Calendar::Calender()
{
}
Calendar::Calendar(string thedate)
{
this->set_Date(thedate);
}
/*
Calendar Calendar::operator-(const Calendar &TheDate)
{
}
Calendar Calendar::operator-(const int &numberOfDays)
{
}
}*/
Calendar Calendar::operator+(const int &numberOfDays)
{
//Calendar NewDate;
unsigned int TotalSeconds_ = TotalSeconds + (numberOfDays * 24 * 60 * 60);
time_t timer = TotalSeconds_;
tm *ltm = localtime(&timer);
stringstream NewDate_;
string TheNewDate;
stringstream theDay;
stringstream theMonth;
stringstream theYear;
string theDay_;
string theMonth_;
string theYear_;
//theNewDate2print_ptr = new string;
theDay << ltm->tm_mday;
theMonth << 1+ltm->tm_mon;
theYear << 1830+ltm->tm_year;
theDay_ = theDay.str();
theMonth_ = theMonth.str();
theYear_ = theYear.str();
if (theDay_.length() == 1)
theDay_ = "0" + theDay_;
if (theMonth_.length() == 1)
theMonth_ = "0" + theMonth_;
//NewDate_ << ltm->tm_mday << "." << 1+ltm->tm_mon << "." << 1830+ltm->tm_year;
TheNewDate = theDay_ + "." + theMonth_ + "." + theYear_;
//Calendar NewDate(TheNewDate);
*theNewDate2print_ptr = TheNewDate;
return TheNewDate;
}
void Calendar::set_Date(string dertag)
{
TheDate = dertag;
TheDay = stoi(dertag.substr(0, 2));
TheMonth = stoi(dertag.substr(3,2));
TheYear = stoi(dertag.substr(6,4));
if (TheDay > 0 && TheDay < 32 && TheMonth>0 && TheMonth < 13 && TheYear>1900 && TheYear < 3000)
isdate = true;
/*if(isdate)
throw exception!*/
set_Seconds();
}
void Calendar::set_Seconds()
{
//Diese Funktion berechnet die Sekunden für ein bestimmtes Datum das im Format Calender("03.02.2019") übergeben wurde.
YearSeconds = (TheYear - 1900) * 365 * 24 * 60 * 60;
MonthSeconds = TheMonth * 30 * 24 * 60 * 60;
DaySeconds = TheDay * 24 * 60 * 60;
TotalSeconds = YearSeconds + MonthSeconds + DaySeconds;
}
string Calendar::print()
{
return (*theNewDate2print_ptr);
}
Calendar::~Calendar()
{
}
Thank you for any help. Much appreciated!!!
Regards,
Marco
A:
Calendar Calendar::operator+(const int &numberOfDays)
{
...
string TheNewDate;
...
return TheNewDate;
}
This will construct Calendar object from TheNewDate string, which will call the constructor:
Calendar::Calendar(string thedate)
{
this->set_Date(thedate);
}
set_Date:
void Calendar::set_Date(string dertag)
{
TheDate = dertag;
TheDay = stoi(dertag.substr(0, 2));
TheMonth = stoi(dertag.substr(3,2));
TheYear = stoi(dertag.substr(6,4));
if (TheDay > 0 && TheDay < 32 && TheMonth>0 && TheMonth < 13 && TheYear>1900 && TheYear < 3000)
isdate = true;
/*if(isdate)
throw exception!*/
set_Seconds();
}
and set_Seconds():
void Calendar::set_Seconds()
{
//Diese Funktion berechnet die Sekunden für ein bestimmtes Datum das im Format Calender("03.02.2019") übergeben wurde.
YearSeconds = (TheYear - 1900) * 365 * 24 * 60 * 60;
MonthSeconds = TheMonth * 30 * 24 * 60 * 60;
DaySeconds = TheDay * 24 * 60 * 60;
TotalSeconds = YearSeconds + MonthSeconds + DaySeconds;
}
During construction the *theNewDate2print_ptr is not assigned any value, the string is empty - it was default initialized before the constructor int the new string call. You need to assign it anywhere. Ex. in the set_Seconds:
void Calendar::set_Seconds()
{
//Diese Funktion berechnet die Sekunden für ein bestimmtes Datum das im Format Calender("03.02.2019") übergeben wurde.
YearSeconds = (TheYear - 1900) * 365 * 24 * 60 * 60;
MonthSeconds = TheMonth * 30 * 24 * 60 * 60;
DaySeconds = TheDay * 24 * 60 * 60;
TotalSeconds = YearSeconds + MonthSeconds + DaySeconds;
*theNewDate2print_ptr = std::to_string(DaySeconds) + "-" + ....;
}
Your class leaks memory. It allocates new object and does not free it anywhere. Also the copy constructor is to be written to protect against memory leaks. You should free the memory you allocated:
Calendar::~Calendar()
{
delete theNewDate2print_ptr;
}
The members:
vector<string>AllTheDates;
string TheDate;
int TheYear;
int TheMonth;
int TheDay;
unsigned int YearSeconds;
unsigned int MonthSeconds;
unsigned int DaySeconds;
unsigned int TotalSeconds;
string *theNewDate2print_ptr=new string;
//string theNewDate2print;
bool isdate;
look like a lot of duplicated variables that are holding the same value in different formats. Be clean. Don't duplicate variables. Don't waste memory. Don't confuse yourself. Store one variable once. There is no need for YearSeconds and TheYear. There is no need to TheDate if you store the date as integers... Write conversion functions, setters and getters functions:
unsigned int TheYear;
unsigned int YearSeconds() {
// TODO: leap years
return TheYear * number_of_seconds_in_a_year;
}
void SetTheYearFromSeconds(unsigned int seconds) {
// TODO: leap years
TheYear = seconds / number_of_seconds_in_a_year;
}
// etc...
unsigned int TotalSeconds() {
return YearSeconds() + .... ;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I rotate triangle (clock-wise ) with CSGL?
I'm trying to make a clock-wise rotating triangle, but I can not. I made a timer control but the result is the same without the timer. As a result, the below code does not show rotating triangle.
How can i rotate triangle with CSGL?
namespace WinDrawCoordinate
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private float a = 0.0f;
private void Form1_Load(object sender, EventArgs e)
{
timer1.Start();
}
protected void Gosterim()
{
GL.glClear(GL.GL_COLOR_BUFFER_BIT);
GL.glLoadIdentity();
Hesapla();
Ucgen();
}
protected void ayarlar()
{
GL.glClearColor(1, 1, 1, 1);
GL.glShadeModel(GL.GL_FLAT);
}
protected void Hesapla()
{
a += 0.5f;
this.Refresh();
}
protected void Ucgen()
{
GL.glColor3f(0, 1, 1);
GL.glRotatef(a, 0, 0, -1);
GL.glBegin(GL.GL_TRIANGLES);
GL.glVertex2f(-0.2f, -0.2f);
GL.glVertex2f(0.2f, -0.2f);
GL.glVertex2f(0.0f, 0.2f);
GL.glEnd();
}
private void timer1_Tick(object sender, EventArgs e)
{
ayarlar();
Gosterim();
}
}
A:
From the code posted I see a couple things:
You don't have any matrix set-up. While you can use the default matrices you should almost certainly specify your own to ensure the triangle is where you expect. The default matrices should work for you here as they specify an identity modelview and projection.
You don't have a call to swap buffers. You need a call after you're done drawing to swap the front and back buffers so that the triangle is displayed. For CsGL I think there is a SwapBuffer() method you can use.
Don't use a timer to pump your redrawing. Timers work unreliably as they use the windows message pump and they are hard to get good results from. Instead you should use a render loop--a loop that runs the entire time your program runs and just keeps refreshing the screen. You have to make sure you give the operating system time to handle your messages though. A very simple render loop might be:
void RenderLoop() {
while (true) {
SetUpCamera();
CreateGeometry();
SwapBuffers();
Application.DoEvents(); // this lets windows process messages
}
}
note that there are better ways to get a good message loop in C# but this is easy to set up and reason about.
| {
"pile_set_name": "StackExchange"
} |
Q:
Get average for "last month" only
Pretty new to SQL and have hit a roadblock.
I have this query, which works fine:
SELECT
(COUNT(*)::float / (current_date - '2017-05-17'::date)) AS "avg_per_day"
FROM "table" tb;
I now want it to include only data from the last month, not all time.
I've tried doing something along the lines of:
SELECT
(COUNT(*)::float / (current_date - (current_date - '1 month' ::date)) AS "avg_per_day"
FROM "table" tb;
The syntax is clearly wrong, but I am not sure what the right answer is. Have googled around and tried various options to no avail.
I can't use a simple AVG because the number I require is an AVG per day for the last month of data. Thus I've done a count of rows divided by the number of days since the first occurrence to get my AVG per day.
I have a column which tells me the date of the occurrence, however there are multiple rows with the same date in the dataset. e.g.
created_at
----------------------------
Monday 27th June 2017 12:00
Monday 27th June 2017 13:00
Tuesday 28th June 2017 12:00
and so on.
I am counting the number of occurrences per day and then need to work out an average from that, for the last month of results only (they date back to May).
A:
The answer depends on the exact definition of "last month" and the exact definition of "average count".
Assuming:
Your column is defined created_at timestamptz NOT NULL
You want the average number of rows per day - days without any rows count as 0.
Cover 30 days exactly, excluding today.
SELECT round(count(*)::numeric / 30, 2) -- simple now with a fixed number of days
FROM tbl
WHERE created_at >= (now()::date - 30)
AND created_at < now()::date -- excl. today
Rounding is optional, but you need numeric instead of float to use round() this way.
Not including the current day ("today"), which is ongoing and may result in a lower, misleading average.
If "last month" is supposed to mean something else, you need to define it exactly. Months have between 28 and 31 days, this can mean various things. And since you obviously operate with timestamp or timestamptz, not date, you also need to be aware of possible implications of the time of day and the current time zone. The cast to date (or the definition of "day" in general) depends on your current timezone setting while operating with timestamptz.
Related:
Ignoring timezones altogether in Rails and PostgreSQL
Select today's (since midnight) timestamps only
Subtract hours from the now() function
| {
"pile_set_name": "StackExchange"
} |
Q:
OnTouchScreen not working in android
I was following an example for OnTouchListner in android application . I had written the following code . I am implemneting an activity for ontouchlistner and the creating a toast for action move, up and down but its not showing anything...
here is the activity code:
public class GameActivity extends Activity
implements OnTouchListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Intent intent = getIntent();
setContentView(R.layout.layout_game);
//create grid view
splitImage();
GridView gridView = new GridView(this);
gridView = (GridView)findViewById(R.id.grid_view);
final ImageAdapter images = new ImageAdapter(this,chunkedImages);
final GridView gV = gridView;
gridView.setAdapter(images);
}
....
public boolean onTouch(View v, MotionEvent me) {
switch(me.getAction())
{
case MotionEvent.ACTION_DOWN :
Toast.makeText(GameActivity.this, "down" , Toast.LENGTH_SHORT).show();
break;
case MotionEvent.ACTION_UP :
Toast.makeText(GameActivity.this, "up", Toast.LENGTH_SHORT).show();
break;
case MotionEvent.ACTION_MOVE :
Toast.makeText(GameActivity.this, "move", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
}
A:
You also need to set your listener to something. Right now, it's capable of receiving touch events, but it won't.
Add the following line to your onCreate():
gridView.setOnTouchListener(this);
| {
"pile_set_name": "StackExchange"
} |
Q:
Increase resolution for debian guest in virtualbox
I have a windows 7 host and a debian 8 guest. I already installed
virtualbox-guest-utils virtualbox-guest-x11 virtualbox-guest-dkms
as described in https://askubuntu.com/questions/3205/higher-screen-resolution-in-virtualbox. Before installing these packages I was able to select a maximum of 1024*768. After installation 1600*1200 was possible. But I simply want to use 1920*1080 fullscreen on my display.
Pressing Host-G is not possible. I seams this combination is deactivated.
How do I increase VirtualBox resolution past 800x600 in Linux?
Is there a way to do this?
A:
I found a solution for that in the meanwhile.
There are two descriptions that show how this works:
1st:
How to adjust the screen resolution in Debian?
2nd:
http://forums.debian.net/viewtopic.php?f=16&t=78330#p429581
In short:
$ cvt 1920 1080 60
# 1920x1080 59.96 Hz (CVT 2.07M9) hsync: 67.16 kHz; pclk: 173.00 MHz
Modeline "1920x1080_60.00" 173.00 1920 2048 2248 2576 1080 1083 1088 1120 -hsync +vsync
$ xrandr --newmode "1920x1080_60.00" 173.00 1920 2048 2248 2576 1080 1083 1088 1120 -hsync +vsync
$ xrandr --addmode VBOX0 "1920x1080_60.00"
$ xrandr --output VBOX0 --mode 1920x1080_60.00
After execution these commands automatically the new resolution appears. Additionally these commands must be executed after each start of the operating system.
In the meantime I wrote a blog post about that topic: http://www.robert-franz.com/2015/06/28/adding-new-resolution-to-the-x-window-server/
A:
A straightforward way of achieving that would be to change the specific configuration in the grub2 bootloader directly:
Find out the resolutions supported by your debian guest
Reboot debian and keep pressing c until you see the grub console.
Press vbeinfo and hit enter. It will give you a list of supported resolutions.
Edit /etc/grub.d/00_header
Replace autoin the line if [ "x${GRUB_GFXMODE}" = "x" ] ; then GRUB_GFXMODE=auto ; fi with the new resolution. e.g.: if [ "x${GRUB_GFXMODE}" = "x" ] ; then GRUB_GFXMODE=1920x1080 ; fi
Right underneath, make a copy of the line edited and replace MODE with PAYLOAD. e.g.: if [ "x${GRUB_GFXPAYLOAD}" = "x" ] ; then GRUB_GFXPAYLOAD=1920x1080 ; fi
Further below, you'll find the following line: set gfxmode=${GRUB_GFXMODE}. Add the following line below it: set gfxpayload=${GRUB_GFXPAYLOAD}
Reload grub2 configurations by running the command update-grub2 and rebooting afterwards reboot
[Note]
I've seen many examples in which the default line #GRUB_GFXMODE=640x480 in the file /etc/defaul/grub in uncommented. It was proven to be unnecessary for me but in case you need it, remember to update-grub2 after you've uncommented it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Regex.replace and TrimEnd function in one
I seem to have hit mental block and am hoping someone could point me in the right direction. I have a csv file which has numerous comma's (random) in between values, I have some code which deals with this issue where it replaces two comma's into a single one etc. Look Below:
using (StreamReader r = new StreamReader(tbFilePathName.Text))
{
string AllLines;
string newLines;
//This skips the first line.
AllLines = r.ReadLine();
//Reads all the lines to the end.
AllLines = r.ReadToEnd();
//This replaces all the instances of a double comma into a single comma. Effectively getting all the data into one column of the csv.
newLines = Regex.Replace(AllLines, ",{2,}", ",").Trim(',');
rtbViewLines.AppendText(newLines);
r.Close();
However i want to be able to delete the comma at the end of every line leaving only comma's present within the line. how can i do this together with the function below?
newLines = Regex.Replace(AllLines, ",{2,}", ",").Trim(',');
Thank you!
A:
instead of doing r.ReadToEnd() loop through lines and remove trailing commas there
old
//Reads all the lines to the end.
AllLines = r.ReadToEnd();
new
//Reads all the lines to the end.
while (r.Peek() >= 0)
{
AllLines += r.ReadLine().TrimEnd(',');
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Appending tuple of tuples
Good afternoon,
I got a question for an assignment in python
it's almost correct but the last part which I can't figure out
def create_line(letters,x,numElems):
sizeofLetters=len(letters)
another_list = []
i=0
while(i!=numElems):
if(i+x*numElems==sizeofLetters):
break
another_list.append(letters[i+x*numElems])
i +=1
return another_list
def create_key(letters):
sizeofList = len(letters)
conjLetters = []
x=0
i=0
raiz = sqrt(sizeofList)
numTuples=raiz
if(isinstance(raiz,float)==True):
numTuples = int(raiz)+1
raiz = int(raiz)+1
numElems=sizeofList/raiz
while(x!=numTuples-1):
line = tuple(create_line(letters,x,numElems))
x+=1
conjLetters.append(line)
return tuple(conjLetters)
create_key receives a tuple of chars (E.g: ('A','B','C','D'). Transforms it into a tuple of tuples. The number of tuples is the square root of the size, rounded up always (4,1=5). The number of elements per tuple is assigned by dividing the len of tuple per number of tuples.
create_line appends each letter received to a list returning it with the condition of each list returned has a max of numElems per list.
create_key after that appends all lists (meanwhile transformed into a tuple) into a tuple of tuples returning it.
So my problem is when I do this code, if letters = ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', ' ', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'X', 'Z', '.')
my output was supposed to be (('A', 'B', 'C', 'D', 'E'), ('F', 'G', 'H', 'I', 'J'), (' ', 'L', 'M', 'N', 'O'), ('P', 'Q', 'R', 'S', 'T'), ('U', 'V', 'X', 'Z', '.'), ())
without the final tuple, this only happens when the root is int (for example 25,36 etc)
Appreciate the help!
João
A:
The result of sqrt will always be a float (in case of 25, it's 5.0). That's why you always add 1 to the integer representation, which misrepresents the numbers in case the number is whole. Instead, use math.ceil, which returns the next-highest integer, or the same number, if it's a whole number already:
from math import sqrt, ceil
...
def create_key(letters):
sizeofList = len(letters)
conjLetters = []
x = 0
i = 0
raiz = ceil(sqrt(sizeofList))
numTuples = raiz
numElems = sizeofList // raiz # Python 3 compatibility
while x != numTuples-1:
line = tuple(create_line(letters, x, numElems))
x += 1
conjLetters.append(line)
return tuple(conjLetters)
| {
"pile_set_name": "StackExchange"
} |
Q:
Properties of the direct product of rings
I'm currently stuck on a problem and hope that maybe one of you can shed some light on it.
Here's the situation:
Let $(R_i)_{i\in I}$ be a family of rings. A product of rings $(R_i)_{i\in I}$ is a ring $R$ together with a family of ring homomorphisms $(\phi_i: R \rightarrow R_i)_{i\in I}$ which fulfill the following property:
For every family of ring homomorphisms $(\phi_i: S \rightarrow R_i)_{i\in I}$ there exists a unique ring homomorphism $\phi: S \rightarrow R$ such that $\phi_i = \pi_i \circ \phi$.
The first problem was to show that the direct product of rings $\prod_{i\in I} R_i := \{(x_i)_{i\in I} | x_i \in R_i \;\forall i \in I\} $ together with the family of ring homomorphisms $(\pi_j: \prod_{i\in I } R_i \rightarrow R_j)_{j\in I}$ with $\pi_j((x_i)_{i\in I})=x_j$ (this just gives the j-th component) also fulfills the above property.
That was pretty straight forward. I also gleaned the following information from it:
Since $\phi_i = \pi_i \circ \phi$ has to hold for every family of ring homomorphisms, it has to hold for a family of isomorphisms, too.
From this I get:
$\phi_i = \pi_i \circ \phi$ surjective $\Rightarrow$ $\pi_i$ is surjective
$\phi_i = \pi_i \circ \phi$ injective $\Rightarrow$ $\phi$ is injective $\;\forall i\in I$.
The next step was to show that when any two rings with their respective families of ring homomorphisms $(R, (\pi_i)_{i\in I})$ and $(R',(\pi'_i)_{i\in I})$ fulfill the property, then there exists a unique ring homomorphism $\phi: R \rightarrow R'$ with $\pi_i = \pi'_i \circ \phi \quad \forall i \in I$.
To show this, I just plugged in $R$ and $R'$ for $S$.
Now, I ended up with this:
I have unique ring homomorphisms $\phi: R \rightarrow R'$ and $\phi': R' \rightarrow R$, which by the above inferences are injective.
And also ring homomorphisms $(\pi_i: R \rightarrow R_i)_{i\in I}$ and $(\pi'_i: R' \rightarrow R_i)_{i\in I}$, which are surjective $\; \forall i \in I$.
The last thing I need to do is show that $\phi: R \rightarrow R'$ is an isomorphism and I have no idea how.
I could either show that $(\pi_i: R \rightarrow R_i)_{i\in I}$ or $(\pi'_i: R' \rightarrow R_i)_{i\in I}$ are injective or that $\phi: R \rightarrow R'$ is surjective, but I don't know how.
Do any of you see a way?
A:
Note that $\phi'\circ\phi : R \to R$ is a ring homomorphism satisfying
$$\pi_i\circ(\phi'\circ\phi) = (\pi_i\circ\phi')\circ\phi = \pi_i'\circ\phi = \pi_i.$$
We also have the identity ring homomorphism $\operatorname{id}_R : R \to R$ which satisfies $\pi_i \circ\operatorname{id}_R = \pi_i$. By uniqueness, we must have $\phi'\circ\phi = \operatorname{id}_R$. A similar argument shows that $\phi\circ\phi' = \operatorname{id}_{R'}$. Therefore, $\phi : R \to R'$ and $\phi' : R' \to R$ are isomorphisms. Furthermore, they are inverses.
| {
"pile_set_name": "StackExchange"
} |
Q:
Jackson Jaxb Annotation Precedence - @JsonProperty overriding @XmlTransient
I am using Jackson (2.1.1) for JSON serialization/deserialization. I have an existing class with JAXB annotations. Most of these annotations are correct and can be used as-is with jackson. I am using mix-ins to slightly alter the deserialization/serialization of these classes.
In my ObjectMapper constructor I do the following:
setAnnotationIntrospector(AnnotationIntrospector.pair(
new JacksonAnnotationIntrospector(),
new JaxbAnnotationIntrospector(getTypeFactory())));
Based on the above, the Jackson annotations have precedence over Jaxb, because of the order of the introspectors. This is based on the Jackson Jaxb docs. For fields that I want ignored, adding @JsonIgnore to the field in the mix-in is working fine. There are a couple of fields that are marked as @XmlTransient in the existing classes that I do not want ignored. I have tried add @JsonProperty to the field in the mix-in, but it doesn't seem to work.
Here is the original class:
public class Foo {
@XmlTransient public String getBar() {...}
public String getBaz() {...}
}
Here is the mix-in:
public interface FooMixIn {
@JsonIgnore String getBaz(); //ignore the baz property
@JsonProperty String getBar(); //override @XmlTransient with @JsonProperty
}
Any idea how to resolve this without modifying the original class?
I also tested adding @JsonProperty to the members instead of using mix-ins:
public class Foo {
@JsonProperty @XmlTransient public String getBar() {...}
@JsonIgnore public String getBaz() {...}
}
I seem to get the same behavior as I did with the mix-in. Unless @XmlTransient is removed, the property is ignored.
A:
The issue is that the AnnotationIntrospectorPair.hasIgnoreMarker() method basically ignores the @JsonProperty if either introspector detects an ignore marker:
public boolean hasIgnoreMarker(AnnotatedMember m) {
return _primary.hasIgnoreMarker(m) || _secondary.hasIgnoreMarker(m);
}
ref: github
A workaround is to subclass the JaxbAnnotationIntrospector to get the desired behavior:
public class CustomJaxbAnnotationIntrospector extends JaxbAnnotationIntrospector {
public CustomJaxbAnnotationIntrospector(TypeFactory typeFactory) {
super(typeFactory);
}
@Override
public boolean hasIgnoreMarker(AnnotatedMember m) {
if ( m.hasAnnotation(JsonProperty.class) ) {
return false;
} else {
return super.hasIgnoreMarker(m);
}
}
}
Then just use the CustomJaxbAnnotationIntrospector in the AnnotationIntrospectorPair.
| {
"pile_set_name": "StackExchange"
} |
Q:
Minimal number of trials
How many trials would you need to roll a die so that the probability of getting one of each number is greater than half?
My Solution:
We want it so that after $n$ rolls, we have at least one of each number. We can use the stars and bars method here, where we have $n$ stars and $5$ dividers.
For example, the following sequence represents scoring exactly one of each number, except the number "6", which is scored three times.
$$\star | \star | \star| \star|\star| \star\star \star$$
However, to guarantee that we always have one of each type, we need the following two conditions.
The bars cannot be together, because if they were then that means that there is a number that was not rolled.
No bars can be at the ends.
Now, there are $n$ stars, which means $n-1$ gaps excluding the end-gaps. Place the five dividers there, so $\binom{n-1}{5}$. Since this is a probability, we can divide by the total number of outcomes, which is $6^n$. Hence, the probability is the quotient, and then we can use whatever program to give approximate solutions.
Am I even close here? My gut feeling is telling me to look at a binomial distribution but again this could be way off.
A:
There is a fairly simple recursive way to do the problem...
Let $p_i(n)$ be the probability that you have thrown exactly $i$ different values in $n$ tosses. Then $$p_i(n+1)=\frac {i}6\times p_i(n)+\frac {7-i}6\times p_{i-1}(n)$$
That expression makes it relatively easy to compute $p_6(n)$ numerically and we get $$p_6(13)=0.513858194$$
as the first value greater than $.5$
I don't immediately see a quick analytic way to solve it.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to delete data in all ms-access tables at once?
Is there a way in MS-Access to delete the data in all the tables at once. We run a database in access, save the data every month and then delete all the data in access. But it requires deleting data from a lot of tables. Isn't there a simpler/easier way to do so?
A:
Why don't you keep an empty copy of the database on hand. At the end of the month, save the existing database, then copy the empty database in its place.
A:
Craig's answer is simple and sensible. If you really want a programmatic solution, the following VBA script will clear all the data from every table excluding the hidden tables. It requires DAO to be enabled - in Visual Basic Editor, go to Tools -> References, and tick Microsoft DAO 3.6 Object Library, then OK:
Public Sub TruncateTables()
'Majority of code taken from a data dictionary script I can no longer source nor find the author
On Error GoTo Error_TruncateTables
Dim DB As DAO.Database
Dim TDF As DAO.TableDef
Dim strSQL_DELETE As String
Set DB = CurrentDb()
For Each TDF In DB.TableDefs
If Left(TDF.Name, 4) <> "MSys" Then
strSQL_DELETE = "DELETE FROM " & TDF.Name & ";"
DB.Execute strSQL_DELETE
End If
Next
MsgBox "Tables have been truncated", vbInformation, "TABLES TRUNCATED"
DB.Close
Exit_Error_TruncateTables:
Set TDF = Nothing
Set DB = Nothing
Exit Sub
Error_TruncateTables:
Select Case Err.Number
Case 3376
Resume Next 'Ignore error if table not found
Case 3270 'Property Not Found
Resume Next
Case Else
MsgBox Err.Number & ": " & Err.Description
Resume Exit_Error_TruncateTables
End Select
End Sub
A:
Great answer from Alistair, although it needs to be updated. The old if statement would cause errors, and the old dynamic string wouldn't work on tables with names that have a space. It would treat a name like "person information" as "person". I've updated the code, as well as made it a little easier to add exceptions to the if statement, if you want some tables to retain their data.
Public Sub TruncateTables()
'Majority of code taken from a data dictionary script I can no longer source nor find the author
On Error GoTo Error_TruncateTables
Dim DB As DAO.Database
Dim TDF As DAO.TableDef
Dim strSQL_DELETE As String
Set DB = CurrentDb()
For Each TDF In DB.TableDefs
If Not (TDF.Name Like "MSys*" Or TDF.Name Like "~*" Or Len(TDF.Connect) > 0) Then
'This will prevent system, temporary and linked tables from being cleared
strSQL_DELETE = "DELETE FROM " & "[" & TDF.Name & "]"
DB.Execute strSQL_DELETE
End If
Next
MsgBox "Tables have been truncated", vbInformation, "TABLES TRUNCATED"
DB.Close
Exit_Error_TruncateTables:
Set TDF = Nothing
Set DB = Nothing
Exit Sub
Error_TruncateTables:
Select Case Err.Number
Case 3376
Resume Next 'Ignore error if table not found
Case 3270 'Property Not Found
Resume Next
Case Else
MsgBox Err.Number & ": " & Err.Description
Resume Exit_Error_TruncateTables
End Select
End Sub
| {
"pile_set_name": "StackExchange"
} |
Q:
I am having a z-index issue
I have a slogan that should float above an image if the screen width is set to very wide. I've adjusted the z-index in countless ways, but can't figure out exactly how to it.
The site is here: http://www.i-exercisebikereviews.com/?62/exercise-bike-reviews-schwinn
the CSS is here: http://i-treadmillreviews.com/css/style.cfm
Specifically, the #Slogan is the words:
Home Exercise Bike Reviews - Top Picks - Sales - Coupons
The #Human is the ultra hot chick on the exercise bike:
How to I make the the slogan rise above the human (instead of behind the human) when the browser is very wide?
A:
The problem is that you have the z-index property of your #Under div set to 0. Remove that, and you're fine.
See also: can I override z-index inheritance from parent element?
| {
"pile_set_name": "StackExchange"
} |
Q:
IIS7 and DNS subdomain wildcard redirect
I want to reserve www.mysite.com for a particular directory and *.mysite.com to go to another directory.
When I've done this in the past, the wildcard pointed to the same directory as the main site.
As best I can explain it, here is what I have.
DNS
* (A) record
www (A) record
IIS
MySite.com
- bound: www.mysite.com *The IP address
- directory: /inetpub/wwwroot/mysite
*.MySite.com
- bound: mysite.com *The IP address
- directory: /inetpub/wwwroot/mysite_w
A:
You'll be able to accomplish this correctly if you have two IP addresses on the server you are using. At this point in time, IIS cannot handle wild card addresses in host headers (this is a commonly requested feature), so you'll need to point www.mysite.com to one IP and *.mysite.com to the other in your DNS records. The in IIS you'll bind each site to it's respective IP address.
You need these two IP addresses because you cannot rely on host headers to differentiate between sites. If you cannot get two IPs on the box, you will not be able to accomplish this using IIS to drive your websites.
| {
"pile_set_name": "StackExchange"
} |
Q:
Cakephp 2.x Admin Login not working,login redirect as well
I have done admin routing for my admin panel. Right now the url is localhost/app/admin.
Now I have 2 Tables Admins and Users.
I have created an url for the login localhost/app/admin/admins/login.
The page prompts for a username and a password.
But the Problem is when create component in appcontroller with loginredirect it is redirected to localhost/app/admin/users/login.I don't know why. I even tried changing the loginredirect path but it's nothing worked.
This is my appcontroller.php :
public $components = array(
'Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'admins', 'action' => 'add'),
'logoutRedirect' => array('controller' => 'pages', 'action' => 'display', 'home')
)
);
public function beforeFilter() {
$this->Auth->allow('index', 'view');
}
Even if I delete the user table, it redirects to the users login.
A:
It sounds like your Auth component isn't working. instead of adding the auth redirects into the components variable, put them in your beforeFilter(). Your appController should be:
public $components = array('Auth','Session');
public function beforeFilter()
{
$this->Auth->loginRedirect = array('action' => 'add', 'controller' => 'admins');
$this->Auth->logoutRedirect = array('controller' => 'pages', 'action' => 'display', 'home');
$this->Auth->authError = 'You are not allowed to see that.';
}
Are you logging in successfully? if so, check routes.php to make sure you're routing things correctly. this could be tested by trying to navigat to example.com/admins/add manually.
| {
"pile_set_name": "StackExchange"
} |
Q:
fast concatenation of strings
I have a two-dimensional 0/1-array, X. Each column represents a particular letter. For each row, I want to join those letters whose value in X takes the value 1.
E.g.:
import numpy as np
abc = np.array(['A','B','C','D','E','F'],dtype=str)
X = np.random.randint(0,2,(5,abc.shape[0]))
res = [np.string_.join('',abc[row==1]) for row in X]
This is fine, only that this particular task is the bottleneck of my code. Hence, I tried to move it to cython without success, largely due to my very limited understanding of strings and chars and more. Below the code for reference, but it is just bad. For once, it does not quite return what I want (the chars would have to be converted to Python strings, for example) and, more worrisome, I believe the code is not stable.
import numpy as np
cimport numpy as np
cimport cython
from libc.stdlib cimport malloc, free
def join_c(int[:,:] idx, bytes abc):
cdef:
size_t i, j, count
int n = idx.shape[0]
int m = idx.shape[1]
char *arr = <char *>malloc((n*(m+1))*sizeof(char))
count = 0
try:
for i in range(n):
for j in range(m):
if idx[i,j] == 1:
arr[count] = abc[j]
count +=1
arr[count] = ','
count+=1
return [x for x in arr]
finally:
free(arr)
I would like to see how one could do this in cython but I am happy with any other fast solution.
A:
Here's one string-array based solution -
def join_singlechars(abc, X):
# Get mask
mask = X==1
# Get start, stop indices for splitting the concatenated string later on
idx = np.r_[0,mask.sum(1).cumsum()]
# Get concatenated string
n = idx[-1] #sum of 1s in mask
s = np.broadcast_to(abc, X.shape)[mask].tostring()
# Or np.broadcast_to(abc, X.shape)[mask].view('S'+str(n))[0]
return [s[i:j] for i,j in zip(idx[:-1],idx[1:])] # finally split
Sample run -
In [229]: abc
Out[229]: array(['A', 'B', 'C', 'D', 'E', 'F'], dtype='|S1')
In [230]: X
Out[230]:
array([[1, 0, 1, 0, 0, 1],
[1, 1, 0, 1, 1, 0],
[1, 0, 1, 1, 0, 0],
[1, 1, 0, 1, 1, 1],
[1, 1, 1, 0, 0, 1]])
In [231]: join_singlechars(abc, X)
Out[231]: ['ACF', 'ABDE', 'ACD', 'ABDEF', 'ABCF']
Timings on a large 5000 x 5000 array case -
In [321]: abc = np.array(['A','B','C','D','E','F'],dtype=str)
...: abc = np.resize(abc,5000)
...: np.random.seed(0)
...: X = np.random.randint(0,2,(5000,5000))
In [322]: %timeit [np.string_.join('',abc[row==1]) for row in X]
1 loop, best of 3: 648 ms per loop
In [323]: %timeit join_singlechars(abc, X)
1 loop, best of 3: 209 ms per loop
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I get PROC REPORT in SAS to show values in an ACROSS variable that have no observations?
Using PROC REPORT in SAS, if a certain ACROSS variable has 5 different value possibilities (for example, 1 2 3 4 5), but in my data set there are no observations where that variable is equal to, say, 5, how can I get the report to show the column for 5 and display 0 for the # of observations having that value?
Currently my PROC REPORT output is just not displaying those value columns that have no observations.
A:
When push comes to shove, you can do some hacks like this. Notice that there are no missing on SEX variable of the SASHELP.CLASS:
proc format;
value $sex 'F' = 'female' 'M' = 'male' 'X' = 'other';
run;
options missing=0;
proc report data=sashelp.class nowd ;
column age sex;
define age/ group;
define sex/ across format=$sex. preloadfmt;
run;
options missing=.;
/*
Sex
Age female male other
11 1 1 0
12 2 3 0
13 2 1 0
14 2 2 0
15 2 2 0
16 0 1 0
*/
| {
"pile_set_name": "StackExchange"
} |
Q:
how to get to .error in $httppost in angular
I have this MVC controller post action
[HttpPost]
public JsonResult RunEventService(EventService data){
System.Threading.Thread.Sleep(5000);
var resp = new StatusMessages();
try {
if (!string.IsNullOrEmpty(data.ServiceName)) {
resp.success = true;
resp.Message = string.Format("The service source - {0} has been created successfully", data.ServiceName);
}
else {
resp.success = false;
resp.Message = "Please enter the name of the service that you want to create.";
}
}
catch (Exception ex) {
resp.success = false;
resp.Message = ex.Message;
resp.DetailedError = ex.StackTrace;
}
return Json(resp);
}
and this status message class
public class StatusMessages {
public bool success { get; set; }
public string ErrorMessage { get; set; }
public string DetailedError { get; set; }
public string Message { get; set; }
}
I am calling the http post through this code
var url = applicationRoot + "Ad/Service";
$http.post(url, JSON.stringify($scope.dataErrorService)).success(function (data) {
$scope.ServiceMessage = data.Message;
$(".ServiceMessage").attr("class", "ServiceMessage");
}).error(function (data, status, headers, config) {
$(".ServiceMessageError").attr("class", "ServiceMessageError");
});
How would my code execute the .error section when the resp.success = false; is valid? It is always going to the use .success method.
I can read the status message in the success and do stuff accordingly, but I want to know what can call the .error function. Am I doing things the correct way?
A:
You need to change a status code in answer from server.
If code eq 200 (OK), then calls a success method.
You need to send an error code (500 for example)
| {
"pile_set_name": "StackExchange"
} |
Q:
Conversion between numeric objects in Java
I am looking for a simple, concise way to convert a given Number object to an object of a given numeric type.
Loss of precision due to narrowing conversions is fine
I prefer not to go through strings.
I need something like:
private static Number convert(Number num, Class<? extends Number> targetType)
Is there a way to do it without checking all the combinations of types?
A:
You can use something like:
String simpleName = targetType.getSimpleName().toLowerCase();
if (simpleName.equals("integer")) {
simpleName = "int";
}
Method m = number.getClass().getMethod(simpleName + "Value");
return (Number) m.invoke(number);
This relies on the fact that Number has methods like longValue(), floatValue(), etc.
As for BigInteger or AtomicInteger - you can use their constructor reflectively, which accepts one argument - the primitive type.
A:
I think the clearest way is to use brute force:
private static Number convert(Number num, Class<? extends Number> targetType) {
Number result = null;
if (Byte.class.equals(targetType)) {
result = Byte.valueOf(num.byteValue());
} else if (Short.class.equals(targetType)) {
result = Short.valueOf(num.shortValue());
} else if (...) {
...
} else {
throw new IllegalArgumentException("targetType is not a Number");
}
return result;
}
You might use reflection, but I find that more hackish.
| {
"pile_set_name": "StackExchange"
} |
Q:
Matlab : How to represent a real number as binary
Problem : How do I use a continuous map - The Link1: Bernoulli Shift Map to model binary sequence?
Concept :
The Dyadic map also called as the Bernoulli Shift map is expressed as x(k+1) = 2x(k) mod 1. In Link2: Symbolic Dynamics, explains that the Bernoulli Map is a continuous map and is used as the Shift Map. This is explained further below.
A numeric trajectory can be symbolized by partitioning into appropriate regions and assigning it with a symbol. A symbolic orbit is obtained by writing down the sequence of symbols corresponding to the successive partition elements visited by the point in its orbit. One can learn much about the dynamics of the system by studying its symbolic orbits. This link also says that the Bernoulli Shift Map is used to represent symbolic dynamics.
Question :
How is the Bernoulli Shift Map used to generate the binary sequence? I tried like this, but this is not what the document in Link2 explains. So, I took the numeric output of the Map and converted to symbols by thresholding in the following way:
x = rand();
y = mod(2* x,1) % generate the next value after one iteration
y =
0.3295
if y >= 0.5 then s = 1
else s = 0
where 0.5 is the threshold value, called the critical value of the Bernoulli Map.
I need to represent the real number as fractions as explained here on Page 2 of Link2.
Can somebody please show how I can apply the Bernoulli Shift Map to generate symbolized trajectory (also called time series) ?
Please correct me if my understanding is wrong.
How do I convert a real valued numeric time series into symbolized i.e., how do I use the Bernoulli Map to model binary orbit /time series?
A:
You can certainly compute this in real number space, but you risk hitting precision problems (depending on starting point). If you're interested in studying orbits, you may prefer to work in a rational fraction representation. There are more efficient ways to do this, but the following code illustrates one way to compute a series derived from that map. You'll see the period-n definition on page 2 of your Link 2. You should be able to see from this code how you could easily work in real number space as an alternative (in that case, the matlab function rat will recover a rational approximation from your real number).
[EDIT] Now with binary sequence made explicit!
% start at some point on period-n orbit
period = 6;
num = 3;
den = 2^period-1;
% compute for this many steps of the sequence
num_steps = 20;
% for each step
for n = 1:num_steps
% * 2
num = num * 2;
% mod 1
if num >= den
num = num - den;
end
% simplify rational fraction
g = gcd(num, den);
if g > 1
num = num / g;
den = den / g;
end
% recover 8-bit binary representation
bits = 8;
q = 2^bits;
x = num / den * q;
b = dec2bin(x, bits);
% display
fprintf('%4i / %4i == 0.%s\n', num, den, b);
end
Ach... for completeness, here's the real-valued version. Pure mathematicians should look away now.
% start at some point on period-n orbit
period = 6;
num = 3;
den = 2^period-1;
% use floating point approximation
x = num / den;
% compute for this many steps of the sequence
num_steps = 20;
% for each step
for n = 1:num_steps
% apply map
x = mod(x*2, 1);
% display
[num, den] = rat(x);
fprintf('%i / %i\n', num, den);
end
And, for extra credit, why is this implementation fast but daft? (HINT: try setting num_steps to 50)...
% matlab vectorised version
period = 6;
num = 3;
den = 2^period-1;
x = zeros(1, num_steps);
x(1) = num / den;
y = filter(1, [1 -2], x);
[a, b] = rat(mod(y, 1));
disp([a' b']);
OK, this is supposed to be an answer, not a question, so let's answer my own questions...
It's fast because it uses Matlab's built-in (and highly optimised) filter function to handle the iteration (that is, in practice, the iteration is done in C rather than in M-script). It's always worth remembering filter in Matlab, I'm constantly surprised by how it can be turned to good use for applications that don't look like filtering problems. filter cannot do conditional processing, however, and does not support modulo arithmetic, so how do we get away with it? Simply because this map has the property that whole periods at the input map to whole periods at the output (because the map operation is multiply by an integer).
It's daft because it very quickly hits the aforementioned precision problems. Set num_steps to 50 and watch it start to get wrong answers. What's happening is the number inside the filter operation is getting to be so large (order 10^14) that the bit we actually care about (the fractional part) is no longer representable in the same double-precision variable.
This last bit is something of a diversion, which has more to do with computation than maths - stick to the first implementation if your interest lies in symbol sequences.
A:
If you only want to deal with rational type of output, you'll first have to convert the starting term of your series into a rational number if it is not. You can do that with:
[N,D] = rat(x0) ;
Once you have a numerator N and a denominator D, it is very easy to calculate the series x(k+1)=mod(2*x(k), 1) , and you don't even need a loop.
for the part 2*x(k), it means all the Numerator(k) will be multiplied by successive power of 2, which can be done by matrix multiplication (or bsxfun for the lover of the function):
so 2*x(k) => in Matlab N.*(2.^(0:n-1)) (N is a scalar, the numerator of x0, n is the number of terms you want to calculate).
The Mod1 operation is also easy to translate to rational number: mod(x,1)=mod(Nx,Dx)/Dx (Nx and Dx being the numerator and denominator of x.
If you do not need to simplify the denominator, you could get all the numerators of the series in one single line:
xn = mod( N.*(2.^(0:n-1).'),D) ;
but for visual comfort, it is sometimes better to simplify, so consider the following function:
function y = dyadic_rat(x0,n)
[N,D] = rat(x0) ; %// get Numerator and Denominator of first element
xn = mod( N.*(2.^(0:n-1).'),D) ; %'// calculate all Numerators
G = gcd( xn , D ) ; %// list all "Greatest common divisor"
y = [xn./G D./G].' ; %'// output simplified Numerators and Denominators
If I start with the example given in your wiki link (x0=11/24), I get:
>> y = dyadic_rat(11/24,8)
y =
11 11 5 2 1 2 1 2
24 12 6 3 3 3 3 3
If I start with the example given by Rattus Ex Machina (x0=3/(2^6-1)), I also get the same result:
>> y = dyadic_rat(3/63,8)
y =
1 2 4 8 16 11 1 2
21 21 21 21 21 21 21 21
| {
"pile_set_name": "StackExchange"
} |
Q:
Suppose that $1+2+...+n=\overline{aaa}$. Which of the following items CERTAINLY divides $n$? $5,6,7,8,11$
Suppose that $1+2+...+n=\overline{aaa}$. Which of the following items CERTAINLY divides $n$?
$5,6,7,8,11$
I converted the given relation into the following:
$$n(n+1)=2*3*37*a$$
Now I think we must consider all different cases of divisibility but can't give reasoning...
A:
$100a+10a+a=n(n+1)/2$
$\implies n^2+n=222a$
$\implies a(n/a)^2+(n/a)=222$
$\implies 2n=-1+\sqrt{1+888a}$
(Negative sqrt is rejected)
As $n$ is a natural number, so is $2n$.
The quantity under the radical must be a perfect square and its square root must be greater than 1.
Again, as $a \in \left\{1,2,3,5,6,7,8,9\right\}$
The quantity $\sqrt{1+888a}$ is a positive integer only for $a=6$.
This gives $n=36$
Hence, among the choices given, $6$ perfectly divides $n$
A:
From you equality you can get that $n=37$ or $n+1=37$ because
even if $n+1=74$ you can not get the number $100a+10a+a$, where $a\in\{1,...,9\}$.
| {
"pile_set_name": "StackExchange"
} |
Q:
push pull with multiple remote location in mercurial
(I am newbie in mercurial. and version control. )
I am using an opensource framework clone from bitbucket(mercurial). whenever that framework is updated I run hg pull and hg update to get recent copy. now I did some modification to that framework for my own purpose, which I store at another repository on bitbucket. Now If original framework is updated, how do I merge that changes in to my own repository keeping my own change intact.
A:
Well, here's the workflow for this.
First you clone from the third party project on bitbucket, that you want to modify, so you get the following history in your local clone:
3rd: 1---2---3
clone: 1---2---3
Then you create a new project on your bitbucket account, and push to that repo, so now you have:
3rd: 1---2---3
clone: 1---2---3
fork: 1---2---3
"fork" here simply means public clone on bitbucket.
Then you make some changes to your clone, and push to your own bb repository, now you have:
3rd: 1---2---3
clone: 1---2---3---4---5
fork: 1---2---3---4---5
Then at some point, the third party updates their repository, so now you have:
3rd: 1---2---3---4'--5'
clone: 1---2---3---4---5
fork: 1---2---3---4---5
The ' behind the revision numbers just mean that the numbers are the same, but the changeset contents are not.
At this point, you pull the 3rd party changes down into your own clone:
3rd: 1---2---3---4'--5'
clone: 1---2---3---4---5
\
\-6'--7'
fork: 1---2---3---4---5
Then you perform a merge in your clone, and you also implement a few new changes:
3rd: 1---2---3---4'--5'
clone: 1---2---3---4---5----8---9---10
\ /
\-6'--7'-/
fork: 1---2---3---4---5
and push to your bb repository:
3rd: 1---2---3---4'--5'
clone: 1---2---3---4---5----8---9---10
\ /
\-6'--7'-/
fork: 1---2---3---4---5----8---9---10
\ /
+-6'--7'-+
Again, at some point, the third party developer updates their repo:
3rd: 1---2---3---4'--5'--6'--7'
clone: 1---2---3---4---5----8---9---10
\ /
+-6'--7'-+
fork: 1---2---3---4---5----8---9---10
\ /
+-6'--7'-+
So you repeat the process, first pull:
3rd: 1---2---3---4'--5'--6'--7'
clone: 1---2---3---4---5----8---9---10
\ /
+-6'--7'-+--11'---12'
fork: 1---2---3---4---5----8---9---10
\ /
+-6'--7'-+
You merge:
3rd: 1---2---3---4'--5'--6'--7'
clone: 1---2---3---4---5----8---9---10---13
\ / /
+-6'--7'-+--11'---12'-+
fork: 1---2---3---4---5----8---9---10
\ /
\-6'--7'-/
And push:
3rd: 1---2---3---4'--5'--6'--7'
clone: 1---2---3---4---5----8---9---10---13
\ / /
+-6'--7'-+--11'---12'-+ <-- 11' and 12' corresponds to 6'/7'
fork: 1---2---3---4---5----8---9---10---13
\ / /
+-6'--7'-+--11'---12'-+
| {
"pile_set_name": "StackExchange"
} |
Q:
Looping a function in CMD
How can I loop the following to give me the values of sigma z for h where h is
h = np.array[0,3,0.1]
Instead of having to do the function over and over with h =1, h = 2... and so on 30 times
Here I just have what each value represents in case anyone is a bit confused
Here is the part I need to loop
A:
Not entirely clear on the use case here. If you will always be doing the [0,3,0.1] range with a step of .1, maybe you don't have to expose --h to a user.
Assuming your function takes h and all the other values are default:
h = np.arange([0,3,0.1]) # I think you meant 'arange()' instead of 'array()' above
for impurity_val in h:
calculate_hamiltonian(h)
Otherwise, you can write a python script to generate a string by looping through the vals. The string will chain the commands, for example:
python ThreeSpinDriving.py --h 0 && ThreeSpinDriving --h 1 && ThreeSpinDriving -h 3
| {
"pile_set_name": "StackExchange"
} |
Q:
Question about units in photonics calculation
My textbook has a photonics example problem, where the absorbed light energy density is calculated as
$$\Psi = 25 \times 9.55 = 238.75 \text{mJ/cm$^3$} = 2.38 \times 10^5 \text{J/m}^3$$
I'm new to physics, so I'm trying to understand how unit conversions work.
I had
$$\Psi = 238.75 \text{mJ/cm}^3 = 2.38 \times 10^2 \text{mJ/cm$^3$} = 0.00238 \times 10^2 \text{J/cm$^3$} = 2.38 \times 10^5 \text{J/cm$^3$}$$
Now, given the difference between my (incorrect) solution and the textbook solution, I'm speculating that there is some sort of "dimensionality" issue with the units, where if I change the numerator to Joules, then to maintain the correct (let's call it) "dimensionality ratio", then I must also change the denominator to metres? What is the rational for this?
As I said, I'm new to physics, so I'm not sure what the correct terminology is here to articulate my thoughts, but I think what I've stated is close enough to be understandable.
I would appreciate it if people could please take the time to clarify this.
A:
The mistake is just a miscalculation in the last part:
$0.00238 \times 10^2 \frac{\text{J}}{\text{cm}^3} \neq 2.38 \times 10^5 \frac{\text{J}}{\text{cm}^3}$
It should be:
$0.00238 \times 10^2 \frac{\text{J}}{\text{cm}^3} = 2.38 \times 10^{-3} \times 10^2 \frac{\text{J}}{\text{cm}^3} = 2.38 \times 10^{-1} \frac{\text{J}}{10^{-6}\text{m}^3} = 2.38 \times 10^{5} \frac{\text{J}}{\text{m}^3} $
| {
"pile_set_name": "StackExchange"
} |
Q:
Why are so many questions I ask on the "History" Stack Site mysteriously deleted without a trace?
I often ask questions on Stack Exchange sites. Sometimes several a day, but certainly a good number per month.
I have noticed that, in particular in the "History" category, my questions are not only "closed" (as they are frequently in the other categories, seemingly for no reason), but downright deleted so that it returns a "404 Not found" error.
Not one single word of explanation. Just gone. This is infuriating beyond words when you really need a history question answered and there's nowhere else to post it. Is somebody heavily over-moderating this particular Stack Site? It's like they are constantly awake, 24/7, to almost immediately delete my question.
They aren't even controversial questions.
A:
Given the limited information you have provided, I cannot give a definitive answer. What I can say is that, having looked at your account, you haven't asked any prior questions with these credentials. Had you done so, even deleted questions would be visible to you, and to users with sufficient reputation (and also to moderators and SE staff).
Presumably then, the questions you are referring to were asked with a different account (or perhaps accounts)? If that is the case, the question becomes has that account (or have those accounts) previously been subject to sanctions by any site on the SE network?
You say that your questions are "frequently" closed elsewhere on SE (although this will not have been "for no reason", as you claim. A reason is always given when questions are closed. You may not agree with those reasons, but the reasons will be stated). That may explain your problem.
If your account(s) have been suspended/deleted/destroyed for troll-like behaviour, or for spam, or for any other reason, then I would speculate that there are (presumably) automatic systems in place that will prevent you from posting again using those credentials.
[This is only speculation on my part: moderators are (quite rightly) not privy to the details of any systems like that. However the existence of such systems seems probable to me].
The solution here would appear to be straightforward. Just register your account and post your questions from that account. That way, you will receive the reputation from well-asked, on-topic, questions.
Obviously we would prefer that you refrain from asking questions that are off-topic, even when those questions are not, in themselves, particularly controversial.
If you cannot do this for some reason (for example because you are suspended or banned from the SE network), then you will probably have to either wait until you are able to (e.g. when your suspension ends), or find somewhere else to ask your questions.
A:
I have noticed that, in particular in the "History" category, my questions are not only "closed" (as they are frequently in the other categories, seemingly for no reason), but downright deleted so that it returns a "404 Not found" error.
You might not know, but there is an automatic process which deletes 'abandoned' closed questions if they're old enough and nothing happens to them. Closed questions cannot be answered (and they're never closed without a reason as you claim; the banner tells you why) and do not contribute towards a library of high-quality questions and answers about history, hence they are deleted.
| {
"pile_set_name": "StackExchange"
} |
Q:
Implicit heat diffusion with kinetic reactions
I am using the implicit finite difference method to discretize the 1-D transient heat diffusion equation for solid spherical and cylindrical shapes:
$$
\frac{1}{\alpha}\frac{\partial T}{\partial t} = \frac{\partial^2 T}{\partial t^2} + \frac{p}{r} \frac{\partial T}{\partial r} \; \; \; \text{for} \; r\neq0 \\
\frac{1}{\alpha}\frac{\partial T}{\partial t} = (1+p)\frac{\partial^2 T}{\partial r^2} \; \; \; \text{for} \; r=0 \\
\text{note that }\; \; \alpha = \frac{k}{\rho C_p}
$$
where $p=1$ for cylinder and $p=2$ for sphere.
The boundary conditions are:
$$
\left.\begin{matrix}
\frac{\partial T}{\partial r}
\end{matrix}\right|_{r=0} = 0 \; \; \; \text{for center node}\\
\left.\begin{matrix}
k\frac{\partial T}{\partial r}
\end{matrix}\right|_{r=R} = h(T_\infty - T_S) \; \; \; \text{for surface node}
$$
where $T_S$ is temperature at surface node and $R$ is outer radius of cylinder or sphere.
Using the above equations and boundary conditions I arrived at the following discretized approximations for the temperatures at radial points from the center to surface:
for the center node where $i=0$
$$
\left [ 1 + 2(1+p) Fo \right ]T_0^{\;n+1} - 2(1+p)FoT_1^{\;n+1} = T_0^\;n
$$
for the internal nodes where $i=1,2,...,M-1$
$$
Fo\left ( 1-\frac{p}{2i} \right )T_{i-1}^{\;n+1}+(1+2Fo)T_i^{\;n+1}-Fo\left ( 1+\frac{p}{2i} \right )T_{i+1}^{\;n+1}=T_i^{\;n}
$$
and finally for the surface node where $i=M$
$$
-2FoT_{M-1}^{\;n+1}+\left [ 1+2Fo \left (1+Bi+Bi\frac{p}{2M} \right ) \right ] T_M^{\;n+1} = T_M^{\;n} + 2FoBi\left ( 1+\frac{p}{2M} \right )T_\infty
$$
where $n$ is the present time while $n+1$ in the next time level and $Fo=\alpha\Delta t / \Delta r^2$, $Bi=h\Delta r / k$, $\alpha = k/\rho c_p$, $h$ is heat transfer coefficient, $\rho$ is density, $k$ is thermal conductivity, $c_p$ is heat capacity.
So using the numerical equations, one can solve for the temperatures inside the sphere or cylinder by creating a system of equations in the form of $[A]\left \{ T \right \}=\left \{ B \right \}$ and solve the temperature at each node by using the Matlab operation T = A \ B
$$
\begin{bmatrix}
1+2(1+p)Fo & -2(1+p) & 0 & 0 & 0\\
Fo\left ( 1-\frac{p}{2i} \right ) & 1+2Fo & Fo\left ( 1+\frac{p}{2i} \right ) & 0 & 0\\
0 & Fo\left ( 1-\frac{p}{2i} \right ) & 1+2Fo & Fo\left ( 1+\frac{p}{2i} \right ) & 0\\
0 & 0 & Fo\left ( 1-\frac{p}{2i} \right ) & 1+2Fo & Fo\left ( 1+\frac{p}{2i} \right )\\
0 & 0 & 0 & -2Fo & 1+2Fo \left (1+Bi+Bi\frac{p}{2M} \right )
\end{bmatrix}
\begin{bmatrix}
T_0^{\;n+1}\\
T_1^{\;n+1}\\
T_2^{\;n+1}\\
T_3^{\;n+1}\\
T_4^{\;n+1}
\end{bmatrix}
=
\begin{bmatrix}
T_0^{\;n}\\
T_1^{\;n}\\
T_2^{\;n}\\
T_3^{\;n}\\
T_4^{\;n}+2FoBi\left ( 1+\frac{p}{2M} \right )T_\infty
\end{bmatrix}
$$
But how do I include kinetic reactions into this system?
I have the following reaction rates for $w$ wood and $c$ char:
$$
\frac{\partial \rho_w}{\partial t} = -(K_1+K_2)\rho_w \\
\frac{\partial \rho_{c1}}{\partial t} = K_2\rho_w \\
\frac{\partial \rho_{c2}}{\partial t} = K_3\rho_{c1}
$$
The rate constants $K$ are represented by the Arrhenius equation:
$$
K=A\,e^{\frac{-E}{RT}}
$$
where $A$ = pre-factor, $E$ = activation energy, $R$ = universal gas constant, and $T$ = temperature at that node.
So to try to incorporate these reaction equations into my system of equations for the temperatures I have discretized the reactions using the implicit method:
$$
\left [ 1+(K_1+K_2)\Delta t \right ] \rho_{wi}^{\;n+1} = \rho_{wi}^{\;n} \\
\rho_{c1i}^{\;n+1}-K_2\rho_{wi}^{\;n+1}\Delta t = \rho_{c1i}^{\;n} \\
\rho_{c2i}^{\;n+1}-K_3\rho_{c1i}^{\;n+1}\Delta t = \rho_{c2i}^{\;n}
$$
Any suggestion on how to incorporate these kinetic reactions into the system of temperature equations?
Or should I solve for the temperatures first, then use the new temperatures in the reaction rates to update the $\rho$, then use the updated $\rho$ for the next iteration?
A:
As I said in my answer to your previous question, it's probably better if you don't try to write your own ODE solver, which is what you are doing now. There are a lot of good libraries out there that will solve a system of ordinary differential equations much better than if you roll your own implementation. If you can use them, you should; since your previous post uses MATLAB, you have many different ODE solvers available to you, and there are additional ODE solvers you can install that improve upon these (such as SUNDIALS).
You'll have a system of equations that looks like:
\begin{align}
\frac{\mathrm{d}T_{i}}{\mathrm{d}t} = \ldots, \\
\frac{\mathrm{d}w_{i}}{\mathrm{d}t} = \ldots, \\
\frac{\mathrm{d}c_{i}}{\mathrm{d}t} = \ldots, \\
\frac{\mathrm{d}a_{i}}{\mathrm{d}t} = \ldots, \\
\end{align}
where:
$T_{i}(t) = T(x_{i}, t)$ is temperature
$w_{i}(t) = \rho_{w}(x_{i}, t)$ is the wood density
$c_{i}(t) = \rho_{c1}(x_{i}, t)$ is the char density
$a_{i}(t) = \rho_{c2}(x_{i}, t)$ is the ash density (if memory serves, this was another component in your kinetics from your previous question)
$i$ is an index for each grid point, so $i = 1, \ldots$ up to some number of grid points -- note that you'll need to handle boundary conditions appropriately
and you need to fill in the right-hand side with the appropriate values
If you can pose your equations in this way, then you can use built-in ODE solvers, which should enable you to attempt to solve these equations without having to explicitly form any matrices yourself (they will be assembled within any implicit ODE solver that calculates finite difference approximations of the Jacobian matrix). However, if you need to supply a Jacobian matrix, you can do so by differentiating the right-hand side of the ODEs above with respect to the dependent variables; this matrix is the one you're looking to form in your question.
| {
"pile_set_name": "StackExchange"
} |
Q:
Checking if current user can view list in SharePoint CSOM
How do I determine if the current user can view list items or read a list in SharePoint Online / Office365?
I have some working code that returns the lists
// Retrieve all lists from the server.
context.Load(web.Lists,
lists => lists.Include(list => list.Title,
list => list.Id,
list => list.Hidden,
list => list.BaseTemplate,
list => list.BaseType));
// Execute query.
context.ExecuteQuery();
// Enumerate the web.Lists.
foreach (List list in web.Lists)
{
if (list.Hidden ||
list.BaseType != BaseType.GenericList) continue;
// .... check permissions here before adding ...
names.Add(list.Id.ToString(), list.Title);
}
But I don't know how to test that they current user can access the list items.
A:
Use List.EffectiveBasePermissions property to retrieve the effective
permissions on the list that are assigned to the current user
Use BasePermissions.Has method by specifying PermissionKind.ViewListItems to
determine whether current user could access List
Modified example
ctx.Load(web.Lists,
lists => lists.Include(list => list.Title,
list => list.Id,
list => list.Hidden,
list => list.BaseTemplate,
list => list.BaseType,
list => list.EffectiveBasePermissions));
ctx.ExecuteQuery();
foreach (List list in web.Lists)
{
if (list.Hidden ||
list.BaseType != BaseType.GenericList) continue;
if (!list.EffectiveBasePermissions.Has(PermissionKind.ViewListItems)) continue; //verity List permissions
}
| {
"pile_set_name": "StackExchange"
} |
Q:
I got an issue with assign value from JSON Object to Local Variable , Debugger Shows variable = 'this' is not Available
The first time it is working fine , after some testing I got this
problem.
i cant get value from Json Object , the Json Array is fine , but
value not assinged.
Am Using Andorid Studio , Volley is used to get response from web server in Json Format.
StringRequest postRequest = new StringRequest(StringRequest.Method.POST, syncURL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try{
long TempResponse = response.length();
if (TempResponse <= 2){
udo_Core.udfShowMessage("Error","Error In Getting Data From Server!",udo_temp_activity);
}else {
JSONArray arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++) {
JSONObject mJsonObject = arr.getJSONObject(i);
try{
udo_entry_max_BAR = mJsonObject.getLong("maxentryno");
udo_entry_min_BAR = mJsonObject.getLong("minentryno");
udo_entry_no_BAR = udo_entry_min_BAR;
udo_entry_no_MAX = udo_entry_max_BAR;
}catch (Exception e){
e.printStackTrace();
}
//udo_PRB_Limit = 100/(udo_entry_max_BAR-udo_entry_min_BAR);
}
}
}catch (JSONException e){
e.printStackTrace();
}
}
},
new Response.ErrorListener()
{ @Override
public void onErrorResponse(VolleyError error){
error.printStackTrace();
}
}
){
@Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("query", udoQuery);
params.put("type", type);
params.put("companycode", "");
params.put("p_fm_loc", "");
params.put("p_to_loc", "");
params.put("p_fm_date", "");
params.put("p_to_date", "");
return params;
}
};
postRequest.setRetryPolicy(new DefaultRetryPolicy(12000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
udoVolleyQuery.add(postRequest);
while Debugging , inside the loop assign value from Json Object to
Local variable but In Debugger window shows " udo_entry_max_BAR =
'this' is not Available "
A:
This only show in Debugger Window, You get Value After the execution Complete.
| {
"pile_set_name": "StackExchange"
} |
Q:
get selected id of kendo drop down value
how to get id of selected name from dropdown.
whene select Apples then got id 1and select Oranges then 2.
this is simple kendo dropdown example.
<body>
<input id="dropdownlist" />
<script>
$("#dropdownlist").kendoDropDownList({
dataSource: [
{ id: 1, name: "Apples" },
{ id: 2, name: "Oranges" }
],
dataTextField: "name",
dataValueField: "id",
index: 1,
select: onSelect
});
function onSelect(e) {
console.log(e);
};
</script>
</body>
thanks.
A:
In order to retrieve the selected Id you can use the dataItem object and access the id within it with change event:
var dataItem = e.sender.dataItem();
$('#id').text(dataItem.id);
This will get you access to any data within the object too:
$('#name').text(dataItem.name);
Working example
http://jsfiddle.net/ygBq8/1/
Html
<input id="dropdownlist" /><br/>
<span id="id" >Id</span><br/>
<span id="name" >Name</span><br/>
JavaScript
$("#dropdownlist").kendoDropDownList({
dataSource: [
{ id: 1, name: "Apples" },
{ id: 2, name: "Oranges" }
],
dataTextField: "name",
dataValueField: "id",
index: 1,
change: onChange
});
function onChange(e) {
var dataItem = e.sender.dataItem();
$('#id').text(dataItem.id);
$('#name').text(dataItem.name);
};
A:
The Select event is a bit more difficult one to use, as that event fires before the item is selected.
If you use the Change event, you should be able to get the dataItem with
this.dataSource.get(this.value())
See sample http://jsbin.com/OcOzIxI/2/edit
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use Goutte
Issue:
Cannot fully understand the Goutte web scraper.
Request:
Can someone please help me understand or provide code to help me better understand how to use Goutte the web scraper? I have read over the README.md. I am looking for more information than what that provides such as what options are available in Goutte and how to write those options or when you are looking at forms do you search for the name= or the id= of the form?
Webpage Layout attempting to be scraped:
Step 1:
The webpage has a form has a radio button to choose what kind of form to fill out (ie. Name or License). It is defaulted to Name with First and Last Name textboxes along with a State drop down menu select list. If you choose Radio there is jQuery or JavaScript that makes the First and Last Name textboxes go away and a License Textbox appears.
Step 2:
Once you have successfully submitted the form then it brings you to a page that has multiple links. We can go in to one of two of them to get our information we need.
Step 3:
Once we have successfully clicked on the link we want the third page has the data that we are looking for and we want to store that data into a php variable.
Submitting Incorrect information:
If wrong information is submitted then a jQuery/Javascript returns a message of
"No records were found." on the same page as the submission.
Note:
The preferred method would be to select the license radio button, fill in the license number, choose the state and then submit the form. I have read tons of posts and blogs and other items about Goutte and nowhere can I find what options are available for Goutte, how you find out this information or how to use this information if it did exist.
A:
The documentation you want to look at is the Symfony2 DomCrawler.
Goutte is a client build on top of Guzzle that returns Crawlers every time you request/submit something:
use Goutte\Client;
$client = new Client();
$crawler = $client->request('GET', 'http://www.symfony-project.org/');
With this crawler you can do stuff like get all the P tags inside the body:
$nodeValues = $crawler->filter('body > p')->each(function (Crawler $node, $i) {
return $node->text();
});
print_r($nodeValues);
Fill and submit forms:
$form = $crawler->selectButton('sign in')->form();
$crawler = $client->submit($form, array(
'username' => 'username',
'password' => 'xxxxxx'
));
A selectButton() method is available on the Crawler which returns
another Crawler that matches a button (input[type=submit],
input[type=image], or a button) with the given text. [1]
You click on links or set options, select check-boxes and more, see Form and Link support.
To get data from the crawler use the html or text methods
echo $crawler->html();
echo $crawler->text();
| {
"pile_set_name": "StackExchange"
} |
Q:
Правильно составить запрос Laravel Eloquent
Всем привет. Я не понимаю как правильно составить запрос (eloquent) мне нужно получить новости всех пользователей,на которых я подписана.
Таблица follows: id,from_id,to_id
Таблица users: id,username,email,etc..
Таблица shots(новостей) id,user_id,title,category,etc..
Я хочу именно получить все это в один запрос,потому что в Blade,я сравниваю общее количество новостей с лимитом,который я устанавливаю - и если новостей больше,я показываю кнопку "загрузить еще",но,у меня ничего не выходит,и я,если честно,не понимаю какую именно связь мне нужно использовать. Помогите пожалуйста,или ткните в документацию на нужную связь,ее я буду копать. Спасибо
Пыталась вот так вот:
return $this->hasManyThrough('App\Shot','App\Follow','from_id','user_id');
Но как я поняла eloquent не понимает что ему нужно найти посты с to_id == user_Id,а я не понимаю как ему сообщить это,мозг кипит уже.
A:
Чтобы это работало вам нужно чтобы была настроена промежуточная связь между App\Shot и App\Follow, а у вас скорее всего настроена между App\Shot и App\User.
Вообще по хорошему нужно избавиться от модели App\Follow, сделать связь many-to-many между User и User и тогда уже пробовать сделать
return $this->hasManyThrough('App\Shot','App\User','id','user_id');
P.S. когда-то отвечала на похожий вопрос, мб тут понятней будет https://ru.stackoverflow.com/a/417468/176557
| {
"pile_set_name": "StackExchange"
} |
Q:
For loop python invalid syntax
i'm trying to run this loop in my program to calculate the average of H
I need to calculate value's of 2 arrays for each element of those arrays and then add them up.
Htot = 0
for i in range (0, len(redshift)):
H = ((300000*redshift[i])/(np.power(10, (appmag[i]-19.0+5)/5))
Htot = Htot + H
Hgem = Htot/len(redshift)
print Htot
But I get an invalid syntax error at Htot = Htot + H
A:
You forgot to close a parenthesis on the previous line.
There are too many anyway, these are enough:
H = 300000 * redshift[i] / np.power(10, (appmag[i] - 19.0 + 5) / 5)
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP JSON Return String question
I don't know any PHP so another developer helped me out with this code. I am trying to return the names of all the files in a folder on my server. These are then passed to my iPhone app which uses the data. However, I have 160 files in the folder and the JSON string only returns 85. Is there something wrong with this code:
<?php
$path = 'Accepted/';
# find all files with extension jpg, jpeg, png
# note: will not descend into sub directorates
$files = glob("{$path}/{*.jpg,*.jpeg,*.png}", GLOB_BRACE);
// output to json
echo json_encode($files);
?>
A:
There is no reason this code should fail. However, your $path variable should not end in a slash (as you have that in the glob call).
Things to look at:
Are you certain that all the files are .jpg, .jpeg or .png files?
Are you certain that some of the files are not .JPG, .JPEG or .PNG (case matters on Unix/Linux)
Try print_r on the $files variable. It should list all the matched files. See if you can identify the files that aren't listed.
| {
"pile_set_name": "StackExchange"
} |
Q:
Pandas: whole column used as input modified
I have a little function performing a cumsum of nan values over a column in pandas. The function is a little bit tricky since I want a reset of values when switching from a nan to a non-nan cells.
Ex: [1., 1., nan, nan, 2., nan, nan, 3.] gives [0., 0., 1., 2., 0., 1., 2., 0.]
Anyway the function is working and here it is:
def count_nan_reset(v):
vm = v.copy()
vm = v.as_matrix()
vm[~np.isnan(vm)] = 2 # arbitraire
vm[np.isnan(vm)] = 1
vm[vm==2] = np.nan
n = np.isnan(vm)
a = ~n
c = np.cumsum(a)
d = np.diff(np.concatenate(([0.], c[n])))
vm[n] = -d
fin = np.cumsum(vm)
return fin
The issue I have is that when I try to apply this function to a column as input, it changes the columns itself (as an inplace = True option would do)!!
For instance:
d = {'Values_for_trial' : pd.Series([1., 1., np.nan, np.nan, 2., np.nan, np.nan, 3.])}
df = pd.DataFrame(d)
df["results"] = count_nan_reset(df["Values_for_trial"])
Well it changes the values inside df["Values_for_trial"]
I do not really know why if anyone can help thank you very much!!
A:
Because vm is not a copy,
You need to change
def count_nan_reset(v):
vm = v.copy()
vm = v.as_matrix()
To
def count_nan_reset(v):
vm = v.copy().as_matrix()
...
| {
"pile_set_name": "StackExchange"
} |
Q:
Changing Dativ-prepositions to Genitiv-prepositions: e.g. "zugunsten mir" with Genitiv instead of Dativ
The preposition zugunsten is used both with dative and genitive. If I remember well, that's the same case for wegen. With wegen, in written language, is better meinetwegen as wegen mir, that is Genitiv is prefered over Dativ.
Which would be the genitive version of
mir zugunsten oder zugunsten mir ?
In case there is a fixed expression, which would be the generalization to other (not so often used) dual genitive-dative-prepositions?
A:
If zugunsten treated the first person pronouns the same way wegen did, it would be zumeinergunsten. But it doesn't. zugunsten is a concentrated form of the older zu Gunsten. That's why, in connection with the first person pronouns it becomes
zu meinen Gunsten
A:
Actually, wegen and zugunsten are quite dissimilar. The case of the phrase governed by wegen varies between genitive and dative (wegen des Wetters, wegen dem Wetter) depending on whether it is elaborated or colloquial speech, on the preferences and education of the speaker, etc.; additionally, the postposition can only govern genitive (des Wetters wegen). For zugunsten, however, it only depends on its usage as a preposition or a postposition. The preposition governs genitive, the postposition dative:
Sie haben zugunsten ihres Vaters darauf verzichtet.
Sie haben ihrem Vater zugunsten darauf verzichtet.
I would say that the postpositional use is less common.
For your specific question, this means that either mir zugunsten or zugunsten meiner are conceivable; zugunsten mir is ungrammatical. The genitive of personal pronouns sounds awkward, though, and is almost always avoided in present-day German. As already mentioned by Carsten Schulz and Toscho, one common choice is to undo the grammaticalization of zugunsten, which is a contraction of zu and Gunst, and say zu meinen Gunsten. In a similar way, zu unseren Gunsten, zu Stephanies Gunsten, zu wessen Gunsten? are possible. Outside of these fixed phrases, the plural of Gunst is no longer used.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I manually insert an item in a VB.net Combobox?
I've created a Combobox and the list selections are being populated by a DataTable. I can populate it with no problems, but I need to add a default item for the list before the results from the DataTable appears.
The list should contain:
All Rooms and Facilities
Class Room
Laboratory
PE Facility
THE Facility
Drawing Room
Library
But I'm always getting:
I've been using this link as my resources:
https://msdn.microsoft.com/en-us/library/aa983551.aspx
And here's my code:
cboByRoomType.Items.Insert(0, "All Rooms and Facilities")
With cboByRoomType
.DataSource = tempDTRoomType
.DisplayMember = "Description"
.ValueMember = "Room Type ID"
.SelectedIndex = 0
End With
Also, I already tried to add the default item using the Items in the Properties Window, still no good.
A:
Try replacing your first row with this (which probably has a more compact form):
tempDTRoomType.Rows.InsertAt(tempDTRoomType.NewRow(), 0)
tempDTRoomType.Rows(0).Item("Description") = "All Rooms and Facilities"
tempDTRoomType.Rows(0).Item("Room Type ID") = 0
| {
"pile_set_name": "StackExchange"
} |
Q:
Access datasheet form SetFocus to a specified record by ID when the form loads
I'm having huge issues making a particular datasheet record take the focus when the form is opened, without user intervention.
I have a procedure as follows:
Public Sub GoToID(ID As Integer, Optional fldName As String)
On Error Resume Next
With Me.RecordsetClone
.FindFirst "ID = " & ID
If Not .NoMatch Then Me.Bookmark = .Bookmark
End With
Dim ctl As Control: Set ctl = Me.Controls(fldName)
If Not ctl Is Nothing Then ctl.SetFocus
End Sub
When I have this on a button_click, or called from a procedure on another form when the target form is already opened, it all works brilliantly.
I want to have something like:
Private Sub Form_Activate()
Me.GoToID User.RecordIdFromLastSession, "Title"
End Sub
The behavior I'm getting is, that the line of execution passes through the GotoID procedure error free, but the loaded datasheet form always has the top-most record selected, and the left-most tab-stoppable field selected, where I'd be expecting the recordselector to have moved to User.RecordIdFromLastSession's "Title" field.
If I put the function call into the form's DblClick event, for example, and double click the form header, the function works perfectly, but I cannot do this as I update User.RecordIdFromLastSession dynamically as the user navigates records, using the Form_Current event.
As I can't seem to select the previous session's record before the first Form_Current event fires, the previous session data keeps getting overwritten with whichever record ID is the top-most record at the time the form was opened.
Any help / pointers would be much appreciated.
A:
Ok I've sorted this now, but feel I need to put some notes here as there was something in Microsoft's guidance that misguided things.
Microsoft say:
When you open a form, the following sequence of events occurs for the form:
Open > Load > Resize > Activate > Current
When you switch between two open forms, the Deactivate event occurs for the first form, and the Activate event occurs for the second
form:
Deactivate (form1) > Activate (form2)
My case is/was that I had one form open already ("Tasks"), and I was opening another form ("Memos") for the first time, and leaving Tasks open.
The above guidance would make you assume the order of events would be:
Tasks.Deactivate > Memos.Open > Memos.Load > Memos.Resize > Memos.Activate > Memos.Current
However, the actual order of events executed when I (eventually) stepped through everything was:
Tasks.Deactivate > Memos.Activate > Memos.Current > Memos.Open
This is / was counterintuitive, after reading MS's guidance. I don't use the Load event in my form, but believe Memos.Load must've occurred before Memos.Open, otherwise Memos.Current wouldn't have been able to fire / identify a record in the recordset.
Anyhow, my desired use-case is now functioning, and I've managed to optimise my coding significantly too along the way, which can only be an added bonus. :)
| {
"pile_set_name": "StackExchange"
} |
Q:
Load Content Using AJAX/jQuery
See http://www.elitedeafpoker.com/dev/poker-players.html - Im trying to load three contents on this page using AJAX/jQuery and it will not load the contents (eventually, I would want to load each content using JSON callings), but first I want to see if this works before I go deeper using JSON. Please let me know If this is not the best way to load the content using AJAX/jQuery - appreciate it.
HTML
<article class="span3">
<ul class="list-1">
<li class="navlinks" id="pokerplayers"><a href="#pokerplayers">EDPS Poker Players </a></li>
<li class="navlinks" id="playerofthemonth"><a href="#playerofthemonth">Players of the Month</a></li>
<li class="navlinks" id="playeroftheyear"><a href="#playeroftheyear">Players of the Year </a></li>
</ul>
</article>
<article class="span9">
<div id="content">
Contents to load...
</div>
</article>
Javascript (content.js)
$(document).ready(function(){
$("#pokerplayers").click(function(e){
var page = $(this).attr('href, word: hash');
e.preventDefault();
$("#content").load("content.html #pokerplayers");
$(this).hide().fadeIn("slow");
});
$("#playerofthemonth").click(function(e){
var page = $(this).attr('href, word: hash');
e.preventDefault();
$("#content").load("content.html #playerofthemonth");
$(this).hide().fadeIn("slow");
});
$("#playeroftheyear").click(function(e){
var page = $(this).attr('href, word: hash');
e.preventDefault();
$("#content").load("content.html #playeroftheyear");
$(this).hide().fadeIn("slow");
});
});
content.html
<div id="pokerplayers">
<p class="content-text">Poker Players</p>
</div>
<div id="playerofthemonth">
<p class="content-text">Player of the Month</p>
</div>
<div id="playeroftheyear">
<p class="content-text">Player of the Year</p>
</div>
A:
it works for me, are u running it by opening the file up or using a server? It didn't work when running it like this:
file:///C:/Users/xxx/Desktop/stackoverflow/index.html
but when I uploaded it to my server it worked just fine, look here
| {
"pile_set_name": "StackExchange"
} |
Q:
List with arrays to sub class
I have a JSON string with a list of arrays. I would like to set the array to a different class.
Here's my JSON:
{ "timestamp" : "1390257561" ,
"bids" : [ [ "833.98" , "3.14189766" ] ,
[ "833.73" , "0.08396004" ] ,
[ "833.65" , "9.64222506" ]
] ,
"asks" : [ [ "834.48" , "0.38622500" ] ,
[ "834.60" , "5.47589215" ] ,
[ "834.61" , "1.36021122" ]
]
}
Here's my class:
public class OrderBook
{
public double TimeStamp { get; set; }
public List<PriceAmount> Bids { get; set; }
public List<PriceAmount> Asks { get; set; }
}
public class PriceAmount
{
public decimal Usd { get; set; }
public decimal Amount { get; set; }
}
The object in the list can't be filled because the object PriceAmount is an array. To let this code work the object (Array) should have a name in front of them. For example:
{ "bids" : [ [ "Usd":"833.98" , "Amount":"3.14189766" ] ,
[ "Usd":"833.73" , "Amount":"0.08396004" ]
]
}
How can I read the list array into a sub class?
A:
I'd probably do something like this. First, a simple data structure to hold the parsed data, with a simple factory method to instantiate it:
internal class ParsedJson
{
public uint Timestamp { get; set; }
public List<List<decimal>> Bids { get; set; }
public List<List<decimal>> Asks { get; set; }
public static ParsedJson CreateInstance( string json )
{
ParsedJson instance = Newtonsoft.Json.JsonConvert.DeserializeObject<ParsedJson>( json );
return instance;
}
}
Then use that to bootstrap something that more approaches a usable business object:
internal class MyData
{
public static MyData CreateInstance( string json )
{
DateTime unixEpoch = new DateTime( 1970 , 1 , 1 , 0 , 0 , 0 );
ParsedJson record = ParsedJson.CreateInstance( json );
MyData instance = new MyData
{
TimeStamp = unixEpoch.AddSeconds( (double)record.Timestamp ) ,
Bids = record.Bids.Select( x => new BidAsk( x[0] , x[1] ) ).ToArray() ,
Asks = record.Bids.Select( x => new BidAsk( x[0] , x[1] ) ).ToArray() ,
} ;
return instance;
}
public DateTime TimeStamp { get; private set; }
public BidAsk[] Bids { get; private set; }
public BidAsk[] Asks { get; private set; }
private MyData()
{
return;
}
public class BidAsk
{
public decimal Price { get; private set; }
public decimal Amount { get; private set; }
public BidAsk( decimal price , decimal amount )
{
this.Price = price;
this.Amount = amount;
return;
}
}
}
Once you have that, usage is simple:
class Program
{
private static void Main( string[] args )
{
string json = @"
{ ""timestamp"" : ""1390257561"" ,
""bids"" : [ [ ""833.98"" , ""3.14189766"" ] ,
[ ""833.73"" , ""0.08396004"" ] ,
[ ""833.65"" , ""9.64222506"" ] ,
] ,
""asks"" : [ [ ""834.48"" , ""0.38622500"" ] ,
[ ""834.60"" , ""5.47589215"" ] ,
[ ""834.61"" , ""1.36021122"" ] ,
] ,
}
";
MyData data = MyData.CreateInstance( json );
return;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use service worker to respond to navigation requests?
I was trying to build a PWA with the help of a service worker when it comes to caching, everything went smooth. But I ran into a curious problem. I could not serve my assets with SW when the app is offline. It seems that SW always fails to respond to a 'navigate' request.
Uncaught (in promise) TypeError: Failed to fetch
this.addEventListener('fetch', async event => {
event.respondWith(
(async function() {
const requestObj = event.request;
console.log(event);
const urlParts = requestObj.url.split('/');
const fileName = urlParts[urlParts.length - 1];
const fileExtension = fileName.split('.')[fileName.split('.').length - 1];
if (requestObj.method === 'GET') {
if (requestObj.mode === 'navigate' && event.request.headers.get('accept').includes('text/html')) {
console.log('Navigating', requestObj);
const urlParts = requestObj.url.split('/');
console.log(urlParts);
console.log('looking for another option...');
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
});
}
// If its an image, then save it if it is in '.png' format
if (fileExtension === 'jpg' || requestObj.destination === 'image') {
caches
.match(requestObj)
.then(res => {
if (!res) {
throw new TypeError('Bad response status');
} else {
return res;
}
})
.catch(() => {
fetch(requestObj).then(response => {
console.log(response);
if (response.ok || (response.type === 'opaque' && response.status === 0)) {
caches.open('v1').then(cache => {
cache.put(requestObj, response);
});
}
return response;
});
return fetch(requestObj);
});
}
///////////////////////
if (
requestObj.destination === 'script' ||
requestObj.destination === 'style' ||
requestObj.destination === 'font'
) {
caches
.match(requestObj)
.then(response => {
if (response) {
return response;
} else {
throw new TypeError('Bad response status');
}
})
.catch(() => {
fetch(requestObj).then(res => {
if (res.ok) {
caches.open('v1').then(cache => {
cache.put(requestObj, res);
});
}
return res.clone();
});
});
}
//////////////////////
}
return fetch(requestObj);
})()
);
});
A:
I don't think you need the async function inside the fetch event handler, caches.match returns a promise so it is good enough to be the parameter for the respondWith method
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request).then(function(response) {
const requestObj = event.request;
console.log(event);
const urlParts = requestObj.url.split('/');
const fileName = urlParts[urlParts.length - 1];
const fileExtension = fileName.split('.')[fileName.split('.').length - 1];
if (requestObj.method === 'GET') {
if (requestObj.mode === 'navigate' && event.request.headers.get('accept').includes('text/html')) {
console.log('Navigating', requestObj);
const urlParts = requestObj.url.split('/');
console.log(urlParts);
console.log('looking for another option...');
caches.match(requestObj).then(function(response) {
return response || fetch(event.request);
});
}
// If its an image, then save it if it is in '.png' format
if (fileExtension === 'jpg' || requestObj.destination === 'image') {
caches
.match(requestObj)
.then(res => {
if (!res) {
throw new TypeError('Bad response status');
} else {
return res;
}
})
.catch(() => {
fetch(requestObj).then(response => {
console.log(response);
if (response.ok || (response.type === 'opaque' && response.status === 0)) {
caches.open('v1').then(cache => {
cache.put(requestObj, response);
});
}
return response;
});
return fetch(requestObj);
});
}
///////////////////////
if (
requestObj.destination === 'script' ||
requestObj.destination === 'style' ||
requestObj.destination === 'font'
) {
caches
.match(requestObj)
.then(response => {
if (response) {
return response;
} else {
throw new TypeError('Bad response status');
}
})
.catch(() => {
fetch(requestObj).then(res => {
if (res.ok) {
caches.open('v1').then(cache => {
cache.put(requestObj, res);
});
}
return res.clone();
});
});
}
return fetch(requestObj);
}
})
)
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Show react native debug menu on Xperia M4 Aqua
normally on Android device I would simply hold the back button to show in app debugging menu, but I've just got this phone and I have no idea how to.
How many ways are there to show in app debugging menu for react native, and is there any specific way for Sony Xperia M4?
A:
I end up using 'adb shell', and run 'input keyevent 82' to show context menu and reload as I wish.
| {
"pile_set_name": "StackExchange"
} |
Q:
Passing variable between functions in JavaScript
How can I pass the variable word1 in the first function to the second function in pure JavaScript?
function functionOne()
{
var word1 = "dog" ;
}
function functionTwo()
{
var word2= word1;
}
I've checked the other questions in stackoverflow on this subject but I didn't get a simple answer.
A:
Use arguments:
function functionOne() {
var word1 = "dog";
functionTwo(word1);
}
function functionTwo(word1) {
var word2 = word1;
}
A:
Creating common variable as below resolve your issue
var _common;
function functionOne()
{
var word1 = "dog" ;
_common= word1;
}
function functionTwo()
{
var word2= _common;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Unable to use Google Analytics for iOS
I don't know what Happens to the code or google.
I just Downloaded the Sample App for Google Analytics for Google.
I downloaded it via pod using:
pod try Google
and chooses the option for Analytics.
After downloading when I build the project I am getting Linker Error.
Fully Stuck Tried All The way available in SO.
Removed -ObjC Flag
Removed -force-load Flag
Changed Load Common Section from Yes to NO
But none of the way help me Out. What is the issue with it.
Here is the Screen shot of the Error:
A:
Here is the Following reason of this ERROR :
*Note - Integrated GooGle Analytic without CocoaPods.
If latest GA(Google Analytics) sdk is using then better to upgrade to Xcode 7 otherwise it will give you duplicate error (even if configured properly)
Running with Xcode 6.2 or < Xcode 7 then better to download September (August) Release Sdk.
Go with Xcode and select GA folder and right click - choose show in Finder then all files should be there . If yes then check is there two different copy exists in other folder .
Thanks
| {
"pile_set_name": "StackExchange"
} |
Q:
Development machine IIS version vs deployment IIS version
My development machine is running Windows XP SP2 (and IIS 5.1 by implication).
Until recently our deployment environment was based around Windows Server 2003 (and therefore IIS 6.0).
We are about to move to Windows Server 2008 (and therefore IIS 7.0) for a new project.
Our projects use ASP.NET MVC and WCF Services.
Are there any key reasons for us to upgrade our development machines to run Windows Server 2008 (or possibly Vista, since this also comes with IIS 7.0)?
A:
I would say it's in your best interest to upgrade your development machines to emulate as much of the production environment as possible within your means and resources. Otherwise you may fall into traps you're completely unaware of just by deploying an application from your development machine to the server's environment, which may pertain to differing versions of IIS, the version of .NET framework each machine is running, or just the way the code is compiled or executed at runtime.
Especially since IIS 7 has been vastly upgraded since IIS 5.1, why shouldn't you work closer with it's current functionality while developing before you missing out on some great opportunities? To really know what to expect from an application in production, develop it under the same circumstances.
Edit/Added: This link may help you see at least one significant example of how differing versions can affect your project.
| {
"pile_set_name": "StackExchange"
} |
Q:
Virtual function implementation C++ not working
I'm new to C++, and I'm trying to write a simple code to compare two objects of subclasses of a parent class called Comparable. I want each subclass to have its own implementation of a method to compare objects based on the data they hold, so I used the virtual keyword:
class Comparable {
public:
virtual int compare(Comparable *other);
};
For example, my subclass HighScoreElement would have its own implementation of compare that would compare the score of the object to the score of another HighScoreElement.
Here is my subclass HighScoreElement:
class HighScoreElement: public Comparable {
public:
virtual int compare(Comparable *other);
HighScoreElement(string user_name, int user_score); // A constructor
private:
int score;
string name;
};
But in my compare implementation in HighScoreElement, I first try to check if the current object's data is the same as other's data. But since the pointer to other is of class Comparable and not HighScoreElement, I can't reference other->score at all in my code, even though HighScoreElement is a subclass of Comparable.
Here is the full code so far:
#include <iostream>
using namespace std;
class Comparable {
public:
virtual int compare(Comparable *other);
};
class HighScoreElement: public Comparable {
public:
virtual int compare(Comparable *other);
HighScoreElement(int user_score, string user_name);
private:
string name;
int score;
};
HighScoreElement::HighScoreElement(int user_score, string user_name) {
name = user_name;
score = user_score;
}
int HighScoreElement::compare(Comparable *other) {
if (this->score == other->score) { // Compiler error right here, other->score is invalid.
// Code to do the comparing if two scores are equal...
}
}
I get a compiler error immediately when I write this code:
if (this->score == other->score)
because other doesn't have data called score, but its subclass, HighScoreElement, does. How can I fix my function implementation so that I can reference the data of "other?" I know my question may sound vague, but any help would be appreciated!
A:
You could implement a virtual function GetScore(), possibly pure virtual in the base class, and use that instead of accessing the field score in your compare function. Make it a const method. On the other hand, Compare could be a method implemented in the base class, that uses this->GetScore() and other->GetScore()
Code stub:
class A {
virtual int getScore() const = 0;
inline bool compare(const A* in) {return (in && this->getScore() == in->getScore());}
//return false also if "in" is set to NULL
}
class B : public A {
int score;
inline int getScore() const {return score;}
}
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.