text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Center programmatically View inside another view that is inside GridLayout (that is inside RelativeLayout)
I would like to center an ImageView to a Button (that is inside a GridLayout (that is inside a RelativeLayout that contains all)).
I tried different option but none worked.
ImageView image = new ImageView(getApplicationContext());
image.setImageResource(R.drawable.heart);
int lastSelectedID = currentIds.get(currentIds.size()-1);
View lastButton = findViewById(lastSelectedID); //Is inside the GridLayout
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(100, 100);
// lp.addRule(RelativeLayout.CENTER_IN_PARENT);
// lp.addRule(RelativeLayout.CENTER_IN_PARENT, lastSelectedID);
// lp.addRule(RelativeLayout.ABOVE, lastSelectedID);
lp.addRule(RelativeLayout.ALIGN_LEFT, lastSelectedID);
lp.addRule(RelativeLayout.ALIGN_RIGHT, lastSelectedID);
image.setLayoutParams(lp);
Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.spark);
image.startAnimation(animation);
final ViewGroup mainLayout = (ViewGroup) findViewById(R.id.layout_main); //relative layout that contains all
mainLayout.addView(image);
I put the new ImageView inside the RelativeLayoute instead its inner GridLayout. This because the ImageView animation can move outside the GridLayout.
A:
I solved in this way:
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(100, 100);
lp.addRule(RelativeLayout.ALIGN_LEFT, gridLayout.getId());
lp.addRule(RelativeLayout.ALIGN_TOP, gridLayout.getId());
lp.setMargins(lastButtonPositionX, lastButtonPositionY, 0, 0);
| {
"pile_set_name": "StackExchange"
} |
Q:
error after close the application
i have a glsurfaceview renderer with some code that allows me resume after press home button and enter again on the game, and that works fine, but if i close the game with the return button, and i try enter again to the game, it crashes and close.
i've tried writing finish() on OnDestroy but not work.
i already checked that onDestroy() execute it when i press return button.
in onSurfaceCreated i have functions that load textures and set vertices for draw those textures, but, i dont understand what could be happening
edit:
this is the log after i launch the game the second time, having closed it before
05-08 20:30:41.069: I/GLThread(6272): noticed surfaceView surface lost tid=12
05-08 20:30:41.069: I/GLThread(6272): onResume tid=12
05-08 20:30:41.169: I/GLThread(6272): noticed surfaceView surface acquired tid=12
05-08 20:30:41.169: W/EglHelper(6272): start() tid=12
05-08 20:30:41.219: W/EglHelper(6272): createContext com.google.android.gles_jni.EGLContextImpl@4056d398 tid=12
05-08 20:30:41.219: I/GLThread(6272): noticing that we want render notification tid=12
05-08 20:30:41.219: W/GLThread(6272): egl createSurface
05-08 20:30:41.219: W/EglHelper(6272): createSurface() tid=12
05-08 20:30:41.219: W/GLThread(6272): onSurfaceCreated
05-08 20:30:41.219: W/GLThread(6272): onSurfaceChanged(480, 320)
05-08 20:30:41.379: W/EglHelper(6272): destroySurface() tid=12
05-08 20:30:41.389: W/EglHelper(6272): finish() tid=12
05-08 20:30:41.389: W/dalvikvm(6272): threadid=9: thread exiting with uncaught exception (group=0x40018578)
05-08 20:30:41.389: E/AndroidRuntime(6272): FATAL EXCEPTION: GLThread 12
05-08 20:30:41.389: E/AndroidRuntime(6272): java.lang.NullPointerException
05-08 20:30:41.389: E/AndroidRuntime(6272): at glfg.gl.render.setverticesSquare(render.java:180)
05-08 20:30:41.389: E/AndroidRuntime(6272): at glfg.gl.render.onSurfaceChanged(render.java:475)
05-08 20:30:41.389: E/AndroidRuntime(6272): at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1381)
05-08 20:30:41.389: E/AndroidRuntime(6272): at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1138)
05-08 20:30:41.399: I/GLThread(6272): onPause tid=12
if i kill the process, i can enter again without problems, but if i exit with return button, it crashes when i try to launch it again, it's supposed that the app would be closed totally but seems that not
A:
Your error is here:
05-08 20:30:41.389: E/AndroidRuntime(6272): java.lang.NullPointerException
05-08 20:30:41.389: E/AndroidRuntime(6272): at glfg.gl.render.setverticesSquare(render.java:180)
In glfg.gl.render.setverticesSquare at line 180. Is this part of your code? I'd look at that line and see what objects could be null, or preferably use breakpoints to inspect it.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to append into table using jquery?
I want to add row if user press button add.
I using jsp and jquery .append(), but it's doesnt work
I tired to try this append for <form:input path=""> into table.
HTML code
<table class="table" id="fileMappingTable">
<thead>
<tr>
<th><fmt:message key='fileMapping.parameter.sequence' /></th>
<th style="text-align:right;" colspan=2><a href="#" id="addSequence" class="button tiny" style="margin: 0;">Add sequence</a></th>
</tr>
</thead>
<tbody>
<tr>
<td style="vertical-align: top;">
<form:input path="sequence" id="sequence"
cssClass="validate[required]"
cssErrorClass="error validate[required]" />
<form:errors path="sequence" cssClass="error" />
</td>
<td>
<form:radiobutton path="value" id="default" value=""/><label for="default">Default</label> <br>
<form:radiobutton path="value" id="startCharacter" value=""/><label for="startCharacter">Start character</label>
<form:input path="firstCharacterPosition" id="firstCharacterPosition"
cssClass="validate[required]"
cssErrorClass="error validate[required]"/>
<label for="length">Length</label>
<form:input path="length" id="length"
cssClass="validate[required]"
cssErrorClass="error validate[required]"/><br>
<form:radiobutton path="value" id="dateTime" value=""/><label for="dateTime">Date & Time</label>
<form:select path="">
<form:option value="">DATE</form:option>
<form:option value="">DATE AND TIME</form:option>
</form:select><br>
</td>
<td style="vertical-align: top;">
<a href="#">remove</a>
</td>
</tr>
</tbody>
</table>
Javascript code
$("#addSequence").click(function(){
$("#fileMappingTable:last").append(
"<tr>" +
"<td style='vertical-align: top;'>" +
"<form:\input path='sequence' id='sequence' cssClass='validate' cssErrorClass='error validate' />" +
"<form:\errors path='sequence' cssClass='error' />" +
"</td>" +
"<td>" +
"<form:radiobutton path='value' id='default' value=''/><label for='default'>Default</label><br>" +
"<form:radiobutton path='value' id='startCharacter' value=''/><label for='startCharacter'>Start character</label>" +
"<form:input path='firstCharacterPosition' id='firstCharacterPosition' cssClass='validate[required]' cssErrorClass='error validate[required]'/>" +
"<label for='length'>Length</label>" +
"<form:input path='length' id='length' cssClass='validate[required]' cssErrorClass='error validate[required]'/><br>" +
"<form:radiobutton path='value' id='dateTime' value=''/><label for='dateTime'>Date & Time</label>" +
"<form:select path=''>" +
"<form:option value=''>DATE</form:option>" +
"<form:option value=''>DATE AND TIME</form:option>" +
"</form:select><br>" +
"</td>" +
"<td style='vertical-align: top;'>" +
"<a href='#'>remove</a>" +
"</td>" +
"</tr>"
);
});
if i click the button with id="addSequence" it will be add row with <form:input path=""/> like on javascript code
thanks before
A:
The JSTL or your Spring MVC form tag will execute first and create the normal tag or html. Then after that you will manipulate the html using Jquery, not the other way around. Create first spring tags before manipulate it with jquery
| {
"pile_set_name": "StackExchange"
} |
Q:
IIS Hosted file is finished downloading at 66%
I have an android application that is downloading a file from a server that is hosting the file with IIS. I have a progress bar that is shown to the user while the file is being downloaded. If I host my file on dropbox and grab it from there instead of my IIS server the progress bar works correctly. However when I grab the file from the IIS server the last update that the progress bar gets bumps it to 66% then the file is done downloading. I checked the file size after download and it is definitely getting the whole file. It is an mp4 file that I am working with, I have the MIME type for '.mp4' set to: 'video/mpeg' though I have also tried 'video/mp4', and 'file/mpeg' none of which corrected the problem. I thought maybe it had something to do with the Compression setting in IIS so I disabled both static and dynamic compression, this made the progress bar go all the way to 100%, but made the download take WAY longer. Is there some other setting in IIS that could be causing this behavior?
A:
I had Dynmaic Compression enabled on the IIS server and that was causing the response to the HTTP request to contain a file size that was larger than the actual file. The size that I was getting in that response is how I was figuring out how far to set the progress bar. It was smart enough to realize that the file was finished when it was, but the progress bar was basing its progress on an inflated file size. I am not sure why dynamic compression would make it report a size that is larger than it is in reality. I would've thought if anything it would give a smaller size. But anyhow, I turned off dynamic compression and all is well now.
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL - Update Multiple Tables, Where Inner Join Value is from Third Table
In a MySQL Database I have tables labeled as the following:
Table:catalog_product_entity
|-------------------------|
|entity_id | sku |
|-------------------------|
|5 | 094922562333 |
|6 | 087454664234 |
|7 | 054545789548 |
---------------------------
Table:catalog_product_entity_decimal
|-------------------------|
|entity_id | price |
|-------------------------|
|5 | 39.99 |
|6 | 37.92 |
|7 | 5.99 |
---------------------------
Table: cataloginventory_stock_item
|-------------------------|
|entity_id | qty |
|-------------------------|
|5 | 0 |
|6 | 5 |
|7 | 8 |
---------------------------
I'm connecting to another database that can only provide me the SKU. I'm wanting to use the SKU as a INNER JOIN to update the tables using the entity_id with one query.
Here is the query I have so far (getting syntax error):
UPDATE catalog_product_entity_decimal, cataloginventory_stock_item
SET catalog_product_entity_decimal.value ='37.95',
cataloginventory_stock_item.qty ='4'
INNER JOIN catalog_product_entity
ON catalog_product_entity.entity_id = catalog_product_entity_decimal.entity_id
WHERE catalog_product_entity.sku = '094922562333';
A:
The JOIN is part of the UPDATE statement, not after the SET. So you might try:
UPDATE catalog_product_entity_decimal cped JOIN
catalog_product_entity cpe
ON cpe.entity_id = cped.entity_id JOIN
cataloginventory_stock_item csi
ON csi.entity_id = cpe.entity_id
SET cped.value = 37.95,
csi.qty = 4
WHERE cpe.sku = '094922562333';
Notes:
The JOINs are in the UPDATE clause.
Table aliases make the query easier to write and to read.
You need a JOIN for cataloginventory_stock_item.
Single quotes are not required around numbers.
| {
"pile_set_name": "StackExchange"
} |
Q:
Force exerted by pressure on projectile
Imagine a free cylindrical body around a pipe that is pressurized with air. How does one find the force exerted on the cylindrical free body at the moment this body becomes a projectile?
*air resistance and friction is neglible.
The current way that I find the force exerted is by measuring the distance traveled and the mass of the cylindrical projectile.
Using the Kinematics:
*Δy = 0
Δy = .5at^2+VisinƟt
Δx = 0 + VicosƟt
Collapsing above equations with simultaneous equation to solve for time. Then I solve for the initial velocity.
This initial velocity is the final velocity of when the cylindrical mass leaves the pipe.
(Vf^2 - Vi^2)/2Δx = acceleration, where Δx here is the length of the pipe.
Finally Fnet = mass * acceleration.
I am trying to figure out if it is possible to figure out the force exerted on the projectile just by being given the unit of pressure like 20psi etc. My method was to covert to psi to N per in^2, then multiply that value by the area of the pipe (with set diameter and height of rocket * 2, assuming rocket is pushed in all the way).
A:
Just remember that $1 Pa = 1\dfrac{N}{m^2}$, so you just multiply by square area to obtain force. Remember that only the pressure on the end matters because the other pressure cancels out.
| {
"pile_set_name": "StackExchange"
} |
Q:
iphone html css tutorials
I am trying to find some good introductory short tutorials that show how to build web site suitable for iphone brwoser. I am not having any success. Google is not turning up useful sites. please let me know if you are aware of any.
thanks
A:
You should have a look at:
Building iPhone Apps with HTML, CSS, and JavaScript
iPhone Development: 12 Tips To Get You Started
| {
"pile_set_name": "StackExchange"
} |
Q:
Change pagination based on user type with django rest framework
I try to set the pagination of my WebAPI based on the status of a User. If the user is_anonymous he should not be able to set the page size with a query parameter. I try to do this with one view class. I could do it with two different view classes and limit the access to one of them, but I think this is not a good solution.
View Class:
class WeathermList(generics.ListAPIView):
queryset = WeatherMeasurements.objects.all()
serializer_class = WeatherMeasurementsSer
filter_backends = (filters.DjangoFilterBackend, filters.OrderingFilter,)
filter_class = WeatherMeasurementsFilter
ordering_fields = ('measure_datetime',)
ordering = ('measure_datetime',)
@property
def paginator(self):
"""
The paginator instance associated with the view, or `None`.
"""
if not hasattr(self, '_paginator'):
# import ipdb
# ipdb.set_trace()
if self.request.user.is_anonymous:
self._paginator = AnonymousPaginator
else:
self._paginator = RegisteredPaginator
return self._paginator
Pagination classes:
class RegisteredPaginator(PageNumberPagination):
page_size = 288
page_size_query_param = 'page_size'
max_page_size = 10000
class AnonymousPaginator(PageNumberPagination):
page_size = 288
Error message:
File ".../env/lib/python3.5/site-packages/rest_framework/generics.py", line 172, in paginate_queryset
return self.paginator.paginate_queryset(queryset, self.request, view=self)
TypeError: paginate_queryset() missing 1 required positional argument: 'request'
The property paginator is originally declared in class GenericAPIView. I am not sure if I reimplement it correctly. Both Custom pagination classes of mine are working when I set them using pagination_class
Any help to get this working is greatly appreciated.
A:
The problem is: self._paginator needs a paginator class instance, not a class itself
It should be AnonymousPaginator()and RegisteredPaginator(), not AnonymousPaginator, RegisteredPaginator.
if self.request.user.is_anonymous:
self._paginator = AnonymousPaginator()
else:
self._paginator = RegisteredPaginator()
| {
"pile_set_name": "StackExchange"
} |
Q:
Opposite to capitalize for Python strings
If I want to make a string start with a capital letter, I do
"hello world".capitalize() # produces 'Hello world'
However, I would need the exact opposite: I need to make a string start with a lowercase letter, therefore something like this:
"Hello world".decapitalize() # produces 'hello world'
"HELLO WORLD".decapitalize() # produces 'hELLO WORLD'
Do we have such a function/method in Python, or it needs to be coded from scratch?
A:
There is no such function in both python2 and python3, so you have to add code it by yourself:
def decapitalize(s):
if not s: # check that s is not empty string
return s
return s[0].lower() + s[1:]
| {
"pile_set_name": "StackExchange"
} |
Q:
conditional loop in jquery selector
How can I select the first 3 div elements in the following example using jquery?
I want to select the div elements with status = 0 until I encounter any other value.
<div status='0'></div>
<div status='0'></div>
<div status='0'></div>
<div status='1'></div>
<div status='0'></div>
The following example I would only need the first 2 elements
<div status='0'></div>
<div status='0'></div>
<div status='1'></div>
<div status='1'></div>
<div status='0'></div>
A:
var divs = [];
$('div[status]').each(function() {
if ($(this).attr('status') === '0') {
divs.push(this);
} else {
return false;
}
});
| {
"pile_set_name": "StackExchange"
} |
Q:
UWP project referencing the wrong sqlite dll
somewhere along the line I was playing around and renamed a sqlite3.dll to sqlite3.copydll. Now my UWP project is referencing that dll. I have since changed it back to Sqlite3.dll what it should be but I keep getting the below when I build my project
Could not copy the file "C:\Users[username].nuget\packages\SQLite\3.13.0\runtimes\win10-x86\nativeassets\uap10.0\sqlite3.copydll" because it was not found.
I cant find where in my project it is still referencing this dll name.
Can anybody help
A:
Open your .csproj as text and search for it there. Or remove reference to SQLite in VS and add it back.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the difference between a slice and an array?
Why are both &[u8] and &[u8; 3] ok in this example?
fn main() {
let x: &[u8] = &[1u8, 2, 3];
println!("{:?}", x);
let y: &[u8; 3] = &[1u8, 2, 3];
println!("{:?}", y);
}
The fact that &[T; n] can coerce to &[T] is the aspect that makes them tolerable. — Chris Morgan
Why can &[T; n] coerce to &[T]? In what other conditions does this coercion happen?
A:
[T; n] is an array of length n, represented as n adjacent T instances.
&[T; n] is purely a reference to that array, represented as a thin pointer to the data.
[T] is a slice, an unsized type; it can only be used through some form of indirection.
&[T], called a slice, is a sized type. It's a fat pointer, represented as a pointer to the first item and the length of the slice.
Arrays thus have their length known at compile time while slice lengths are a runtime matter. Arrays are second class citizens at present in Rust, as it is not possible to form array generics. There are manual implementations of the various traits for [T; 0], [T; 1], &c., typically up to 32; because of this limitation, slices are much more generally useful. The fact that &[T; n] can coerce to &[T] is the aspect that makes them tolerable.
There is an implementation of fmt::Debug for [T; 3] where T implements Debug, and another for &T where T implements fmt::Debug, and so as u8 implements Debug, &[u8; 3] also does.
Why can &[T; n] coerce to &[T]? In Rust, when does coercion happen?
It will coerce when it needs to and at no other times. I can think of two cases:
where something expects a &[T] and you give it a &[T; n] it will coerce silently;
when you call x.starts_with(…) on a [T; n] it will observe that there is no such method on [T; n], and so autoref comes into play and it tries &[T; n], which doesn’t help, and then coercion come into play and it tries &[T], which has a method called starts_with.
The snippet [1, 2, 3].starts_with(&[1, 2]) demonstrates both.
A:
Why can &[T; n] coerce to &[T]?
The other answer explains why &[T; n] should coerce to &[T], here I'll explain how the compiler works out that &[T; n] can coerce to &[T].
There are four possible coercions in Rust:
Transitivity.
If T coerces to U and U coerces to V, then T coerces to V.
Pointer weakening:
removing mutability: &mut T → &T and *mut T → *const T
converting to raw pointer: &mut T → *mut T and &T → *const T
Deref trait:
If T: Deref<Target = U>, then &T coerces to &U via the deref() method
(Similarly, if T: DerefMut, then &mut T coerces to &mut U via deref_mut())
Unsize trait:
If Ptr is a "pointer type" (e.g. &T, *mut T, Box, Rc etc), and T: Unsize<U>, then Ptr<T> coerces to Ptr<U>.
The Unsize trait is automatically implemented for:
[T; n]: Unsize<[T]>
T: Unsize<Trait> where T: Trait
struct Foo<…> { …, field: T }: Unsize< struct Foo<…> { …, field: U }>, provided that T: Unsize<U> (and some more conditions to make the job easier for the compiler)
(Rust recognizes Ptr<X> as a "pointer type" if it implements CoerceUnsized. The actual rule is stated as, “if T: CoerceUnsized<U> then T coerces to U”.)
The reason &[T; n] coerces to &[T] is rule 4: (a) the compiler generates the implementation impl Unsize<[T]> for [T; n] for every [T; n], and (b) the reference &X is a pointer type. Using these, &[T; n] can coerce to &[T].
| {
"pile_set_name": "StackExchange"
} |
Q:
Check Network Status
I want to check the network status if network is down, I mean if my network is down then I want to find out by programmatically using C#/VB.net, to find out which router, or server etc is down due to which the network is also down,
Hope I have explain my question, if you want more explanation Please tell me.
I want to check if there is router down in the network connection or some other problem, As there are lot of techniques to check the up or down of the network, but which due to which device on the network the net work down, that is my problem.
A:
Why not use the .Net networking classes?
http://msdn.microsoft.com/en-us/library/system.net.networkinformation.aspx
| {
"pile_set_name": "StackExchange"
} |
Q:
If, $x+y=1, x^2+y^2=2$ Find $x^7+y^7=??$
If, $x+y=1, x^2+y^2=2$ Find $$x^7+y^7=??$$
any help guys please?
A:
Hint: $x^{n+1}+y^{n+1}=(x+y)(x^n+y^n)-xy(x^{n-1}+y^{n-1})$
A:
Mark Bennet gave the very good trick.
Since $$x^{n+1}+y^{n+1}=(x+y)(x^n+y^n)-xy(x^{n-1}+y^{n-1})$$ let us define $u_n=x^n+y^n$. So $$u_{n+1}=(x+y)\,u_n-x\,y\,u_{n-1}$$ and you know that $x+y=1$; on the other side $$(x+y)^2=x^2+y^2+2xy$$ means that $1=2+2xy$ so $xy=-\frac12$. This makes the recurrence equation $$u_{n+1}=u_n+\frac12 u_{n-1}$$ The characteristic equation is then $r^2=r+\frac12$ the roots of which being $$r_{1,2}=\frac{1}{2} \left(1\pm\sqrt{3}\right)$$ which gives $$u_n=c_1 r_1^n+c_2 r_2^n$$ Using the conditions $u_1=1$, $u_2=2$, this finally gives $$u_n=\left(\frac{1}{2}-\frac{\sqrt{3}}{2}\right)^n+\left(\frac{1}{2}+\frac{\sqrt{3}}{2}\right)^n=\frac{\left(1-\sqrt{3}\right)^n+\left(1+\sqrt{3}\right)^n}{2^n}$$ Now use the binomial expansion (all $\sqrt 3$ will disappear) to get $u_3=\frac{5}{2}$, $u_4=\frac{7}{2}$, $u_5=\frac{19}{4}$, $u_6=\frac{13}{2}$, $u_7=\frac{71}{8}$, $u_8=\frac{97}{8}$, $u_9=\frac{265}{16}$, $\cdots$.
Just to mimic Dietrich Burde (this is a joke) $$u_{125}=\frac{394645107381876211072765516988567419}{4611686018427387904}$$
A:
If $x+y=1$ and $x^2+y^2=2$, then $xy=\frac{(x+y)^2-(x^2+y^2)}{2}=-\frac{1}{2}$, so $x$ and $y$ are roots of the polynomial $p(z)=z^2-z-\frac{1}{2}$, or eigenvalues of the (companion) matrix:
$$ M=\left(\begin{array}{cc}0 & \frac{1}{2}\\ 1 & 1\end{array}\right)$$
so that:
$$ x^7 + y^7 = \text{Tr}(M^7)=\text{Tr}\left(
\begin{array}{cc}
\frac{15}{8} & \frac{41}{16} \\
\frac{41}{8} & 7 \\
\end{array}
\right)=7+\frac{15}{8}=\color{red}{\frac{71}{8}}. $$
In order to compute $M^7$, you may just apply repeated squaring three times, then multiply $M^8$ by $M^{-1}$, or notice that, by setting $s_n=x^n+y^n$, we have:
$$ s_{2n} = s_n^2 - 2(xy)^n = s_n^2-\frac{(-1)^n}{2^{n-1}}, $$
$$ s_{2n+1} = s_n s_{n+1} - (xy)^n(x+y) = s_n s_{n+1}-\frac{(-1)^n}{2^n},$$
so you may compute $(s_{2n},s_{2n+1})$ from $(s_n,s_{n+1})$. We may use this technique for the fast computation of Fibonacci or Lucas numbers.
| {
"pile_set_name": "StackExchange"
} |
Q:
Value for PRIMARY KEY recognized as NULL (EF6 Code First)
Well, I have rather odd exception when I try to insert new value. Please, see attached files for further investigation.
So, I use:
SQL Server 2012
VS 2012 Update 2
EF6 Alpha 3 Code First
The problem is I'm trying to insert new value into simple table called dbo.Worker2 (see "Worker2 Table" image file) which consists of 2 columns: TableNumber and Name. The TableNumber column is primary key of integer data type (see "Primary Key column properties" image file). I have installed the latest EF6 alpha3 and trying to insert new value (see "VB.NET Code" image file). However, exception is thrown: "Cannot insert NULL the value NULL into column 'TableNumber', table Bonus.dbo.Worker2'; column does not allow nulls. INSERT fails." (see "VS Exception" image file).
Then I have decided to see what T-SQL query EF sends to SQL Server with SQL Server Profiler and was surprised that no TableNumber was sent by EF (see "Profiler Queries" image file).
Is it bug or I have missed something?
A:
By the looks of it you need to set your Worker2 Primary Key property as non-database generated.
something like:
<Key, DatabaseGenerated(DatabaseGeneratedOption.None)>
Public Property TableNumber As Integer
| {
"pile_set_name": "StackExchange"
} |
Q:
Create data on Package Installation
We are developing a managed package and I would like to know how can I load/create large amount of data in customer org after package is successfully installed. I understand there is a Post Install Script that I can use, but I would like to know the best strategy to achieve this. We have approx. 10,000 records that we would like to load/create in the org after installation of the application is successful.
A:
There are different strategies that you can leverage and it entirely depends how well the adopted approach fits your need. These are some approaches that we have used before along with the considerations for their usage.
Approach 1 - Using Post Install Scripts
Salesforce provides the InstallHandler interface which can be implemented to execute automation or Apex scripts before the package installation is complete. It can be leveraged by implementing the onInstall() method of the InstallHandler interface.
global class CustomPostInstallClass implements InstallHandler {
global void onInstall(InstallContext context){
if(context.previousVersion() == null) {
//Execute context specific logic when a fresh install
}
else{
if(context.previousVersion().compareTo(new Version(1,0)) == 0) {
//Execute context specific logic on specific version upgrades
}
}
if(context.isUpgrade()) {
//Execute context specific logic if this a Package Upgrade due to a new release version of the Managed Package
}
if(context.isPush()) {
//Execute context specific logic if this a forceed Push to the customer org
}
}
}
Usage Considerations
Post Install scripts provide installation context variables that help determine and differentiate a fresh installation versus a package upgrade versus adding package version specific branching logic. This is useful in your case since you may only want to load records during a fresh installation and refrain from creating them during an upgrade or when patches are pushed over to client orgs.
Since this script executes before the package installation completes, you can check for pre-requisites that your managed package requires for e.g. certain Salesforce features that need to be enabled on the org for the package to work as expected. If those are not met, you have the flexibility to abort the installation process by raising a custom Exception. This avoids installation nightmares and enforces that the setup adheres to the pre-requisite mandates. If you intend to enforce the record creation before the package is used then this is the option for you.
A deterrent that the post install approach brings, is the increased installation time while the 10K records are being created. Moreover, you could run into DML Exceptions while loading these records which could abort the installation process and lead to a poor installation experience.
Approach 2 - Using a Product Setup Page
Another approach to reduce installation times and improve the installation experience is introducing a Product Setup Page and the User explicitly initiating the setup through a user interaction. The records to load can be stored as a Json String in a file within the Static Resource of the managed package and can be read when the setup is initiated.
Usage Considerations
This approach requires an additional screen to be implemented and business logic to mandate the setup page which means that additional development effort. If you do not mandate this screen to show up first within the product, chances are your user could miss out on record creation leading to installation woes and poor installation experience.
Since the InstallContext variables are unavailable the check to determine a fresh install versus a package upgrade versus a package version specific check will need to be done via custom code.
Couple of advantages that this approach brings is reduced installation times since the record creation process is decoupled. This also makes the package installation independent of the record load thus reducing installation failure points.
In situations where you need to upgrade the records, you could provide your package users with a new Static Resource (provided it is packaged as UnProtected ) giving the package provider an added flexibility and avoiding the overhead of going through a repeated installation effort for the customer.
Approach 3 - Using a Installation Batch or Scheduler
This approach leverages using a Post Install script except that the records to be read from a Json file stored within the package's statis resource and created via a scheduled Batch Apex Job to improve the installation experience.
Based on my experience, I would recommend going for Approach 2 or 1 as explained above.
| {
"pile_set_name": "StackExchange"
} |
Q:
Display better error messages for the user
private boolean relatedCommand(String input) {
// make sure the split afterwards has at least size one
if (input.matches(" .*")) {
return false;
}
final String command = input.split(" ".toString())[0];
return COMMAND_PACKAGE
.keySet()
.stream()
.map(Pattern::toString)
.anyMatch(patternText -> patternText.startsWith(command + " "));
}
public Command getCommand(final String input) throws InvalidInputException {
if (relatedCommand(input)) {
Terminal.printError("test");
throw new InvalidInputException("invalid arguments");
} else {
throw new InvalidInputException("unknown command");
}
...
}
I am having trouble with giving the user a more specific error message. For example I have the commands add track <argument1> and add switch <argument1>. If the user just types in "add" he shouldn't get the error message "invalid arguments". Instead it should be "invalid command: either use add track or add switch). Since relatedCommand() is a boolean. How do I implement this efficiently?
A:
As you mentioned, currently the method returns a boolean, which is a two-state outcome. At the same time you are seeking for three-state outcome:
command is known
command is unknown
there are several commands known for the prefix.
For the question given in regards to the way of returning the proper result, one option would be to return the collection of possible commands, which can represent the required three states:
the collection consists of one element
the collection is empty
the collection consists of more than one element.
The changes to your original code can be like these:
private Collection<String> relatedCommand(String input) {
// make sure the split afterwards has at least size one
if (input.matches(" .*")) {
return Collections.emptyList();
}
final String command = input.split(" ".toString())[0];
return COMMAND_PACKAGE
.keySet()
.stream()
.map(Pattern::toString)
.filter(patternText -> patternText.startsWith(comman))
.collect(Collectors.toList());
}
public Command getCommand(final String input) throws InvalidInputException {
Collection<String> commands = relatedCommand(input)
if (commands.size() == 1) {
Terminal.printError("test");
throw new InvalidInputException("invalid arguments");
} else if (commands.isEmpty()) {
throw new InvalidInputException("unknown command");
} else {
...
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
If Else inside jQuery each not working
If is not blocking the execution of else statement. Help plase!
function checarZero() {
$(".ps-form-entry--progressbar").each(function() {
var valorPerc = $(this).val();
if (parseFloat(valorPerc) === 0) {
psLib.NotifyShowHide(
'alert:Você não distribuiu a renda vitalícia.');
event.preventDefault();
} else {
$("#btn-continuar").fadeIn("fast");
}
});
}
A:
That's because event is undefined.
Given the snippet you provided is your code, you should see an error in your JS console.
The event variable should be passed into checarZero function, for it to be cancelled.
From the snippet, it's hard to say what event you're looking for, if you just want to stop the execution of .each loop you must return false;
| {
"pile_set_name": "StackExchange"
} |
Q:
for loop on files that don't exist
I want to process a set of files (*.ui) in the current directory. The following script works as expected if some *.ui files are found. But if no .ui file exist the current directory, the for loop is entered all the same. Why is that ?
for f in *.ui
do
echo "Processing $f..."
done
It prints :
Processing *.ui...
A:
Use:
shopt -s nullglob
From man bash:
nullglob
If set, bash allows patterns which match no files (see Pathname Expansion
above) to expand to a null string, rather than themselves.
| {
"pile_set_name": "StackExchange"
} |
Q:
Conversion of big-endian long in C++?
I need a C++ function that returns the value of four consecutive bytes interpreted as a bigendian long. A pointer to the first byte should be updated to point after the last. I have tried the following code:
inline int32_t bigendianlong(unsigned char * &p)
{
return (((int32_t)*p++ << 8 | *p++) << 8 | *p++) << 8 | *p++;
}
For instance, if p points to 00 00 00 A0 I would expect the result to be 160, but it is 0. How come?
A:
The issue is explained clearly by this warning (emitted by the compiler):
./endian.cpp:23:25: warning: multiple unsequenced modifications to 'p' [-Wunsequenced]
return (((int32_t)*p++ << 8 | *p++) << 8 | *p++) << 8 | *p++;
Breaking down the logic in the function in order to explicitly specify sequence points...
inline int32_t bigendianlong(unsigned char * &p)
{
int32_t result = *p++;
result = (result << 8) + *p++;
result = (result << 8) + *p++;
result = (result << 8) + *p++;
return result;
}
... will solve it
| {
"pile_set_name": "StackExchange"
} |
Q:
Google Analytics Data Import API for Campaigns - can it overwrite historic hits?
May I ask if anyone has used the Data Import API for campaigns? Could they explain how the historic data overwrite works?
I can't get the historic campaignCodes to be overwritten with my new data - it works after the csv is uploaded, but its a lot more useful if it can work retrospectively since we have campaign codes that are generated at the time of the campaign usually (CRM). Adobe Analytics you can upload at any time and overwrite historic stuff, so I'm surprised GA can't do the same.
Also, it seems to say it can do this when looking at the documentation:
https://support.google.com/analytics/answer/6014980?hl=en&utm_id=adOverwrite
"For Campaign, Content, Custom, Product and User Data Set types, you can choose whether duplicate data overwrites previously collected or imported hits, or is discarded in favor of the existing data."
In my example I did the following:
session to example.com?utm_id=A123
Uploaded definition of:
campaignCode = A123, medium=test_m, source=test_s, campaign=camp_t1
campaignCode = B123, medium=test_m, source=test_s, campaign=camp_t2
session to example.com?utm_id=A123
session to example.com?utm_id=B123
After 24 hours the reports show only one session to campaign camp_t1 and camp_t2.
The hit from before the upload is recorded as campaignCode=A123, source/medium = (not set) / (not set) and campaign (not set)
Also I can see that the post hits don't have campaignCode recorded anymore, instead registering as source / medium = test_s / test_m. Ideally it would be nice if the campaignCode would be kept for future overwrites (say if there was a mistake).
I'm basically asking if the above all expected behaviour, or is it a bug/will change in the future?
Hope someone can help!
A:
Answered via Simo on G+
Linking historic data to an upload is only possible with Google Analytics Premium, as explained in the Query Time import docs
| {
"pile_set_name": "StackExchange"
} |
Q:
ASP .NET - Quartz Scheduler only Executes jobs on user visit
I need my emails to be sent automatically from my .NET application. However, when scheduling jobs for the future, the jobs are only executing when a user visits the site.
Global.asax.cs
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
JobScheduler.Start();
}
Job Scheduler (ScheduledTasks.cs)
public class EmailJob : IJob
{
public void Execute(IJobExecutionContext context)
{
BDL.Utilities.sendEmailNotification(to, subject, body);
}
}
public static void start()
{
foreach (AspNetUser user in users)
{
IJobDetail job = JobBuilder.Create<EmailJob>().WithIdentity((jobidentity))
.UsingJobData("to", user.Email)
.UsingJobData("subject", subject)
.UsingJobData("body", bodyholder).Build();
ITrigger trigger = TriggerBuilder.Create()
// schedule for 1 day in the future
.StartAt(expdate.AddDays(1)))
.WithIdentity(triggerid)
.Build();
scheduler.ScheduleJob(job, trigger);
}
}
I have scheduled a trigger for 1 day in the future. This trigger should cause my job to execute 1 day in the future. However, for some reason this job will only execute if a user visits my site on the day the job is scheduled to fire. How can I make these Jobs be executed automatically by Quartz???
EDIT: My goal is to accomplish this without messing with the Application Pool threads. The accepted answer shows that this question is about merely replacing the user interaction with automated scripts. Whereas the duplicate asks for a way to maintain the application pool threads, and in Java I might add!
A:
I was able to come up with a more elegant solution. Using the tool Zapix I was able to schedule my website to be quality checked every 20 minutes. Zapix simply visited the site and received and http response. By using Zapix, it mimicked the functionality of manually visiting the website to trigger the emails.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a way to share a wi-fi connection over wi-fi?
The problem is that here is a router (at a cottage), which only allows 2 connections. but we need wi-fi for 8 devices. so the plan is to create another wi-fi spot to share our connection. is there a tool or tutorial for that?
A:
In order for a Mac to create a local Wi-Fi network, it needs to have a wired Internet source. So what you need to do is:
Connect an Ethernet cable from the router (the wired source) to a Mac.
On that Mac, choose System Preferences > Sharing.
Select Internet Sharing.
Choose Ethernet from the “Share your connection from” pop-up menu.
Select AirPort in the “To computers using” list, then click AirPort Options and give your network a name and password.
Connect the other computers to the new Wi-Fi network you just created.
If needed, there are more details on this Apple help page: Sharing your Internet connection.
| {
"pile_set_name": "StackExchange"
} |
Q:
Securely embedded Power BI reporting has no option for fullscreen
When I publish my Power BI reporting to the web and embed it into my website with allowFullScreen="true", I can see an icon on the bottom right which enables me to see it in fullscreen mode.
However, when I "Securely embed this report in a website or portal", Power BI gives me the iframe code with allowFullScreen="true" but this time I'm not able to see the icon.
Anyone knows what I'm doing wrong here?
A:
The "Enter into fullscreen" button is part of the Power BI Publish To Web - unfortunately it is not available within the option Securely embed this report in a website or portal.
The allowFullScreen="true" has nothing to do with that and is an attribute of the html iframe tag.
| {
"pile_set_name": "StackExchange"
} |
Q:
CRM 2011 (rollup 12) shows the mobile view instead of the normal view in non IE browsers
I recently went to do a demo of some a CRM solution I had been developing but when I tried displaying it on my MAC in firefox and chrome it comes up with the mobile interface. The instance will never be used on mobile devices so I want to disable this functionality for the whole site...How do I do this?
A:
I had the same issue when I opened crm on firefox (on explorer and chrome it was ok), I assume you are using roll up 12 since only from this rollup you have other browsers besides internet explorer integration.
The issue with me was that for some reason, it opened the "default.aspx" page, which opened this url:
https://mydomain:444/m/default.aspx
When the correct address should be:
https://mydomain:444/main.aspx#
I'm also guessing that you have set up ADFS..
A:
I had the same problem and what helped for me was to add the site to the Compatibility View in Internet Explorer.
| {
"pile_set_name": "StackExchange"
} |
Q:
Problem retrieving results from an index in an embedded RavenDB
I have an index that works great when I query it using the .Net client API with a server based RavenDb.
However, if I change the RavenDb to an embedded type then I cannot query the index directly unless I first query the document that the index uses.
For instance if I have the following document objects which reside as separate collections in the RavenDb:
private class TestParentDocument
{
public string Id { get { return GetType().Name + "/" + AggregateRootId; } }
public Guid AggregateRootId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
private class TestChildProductFlagDocument
{
public string TestParentDocumentId { get; set; }
public short ProductFlagTypeId { get; set; }
}
Then I have the following object which represents the output document that the index maps to:
private class TestJoinIndexOutput
{
public string TestParentDocumentId { get; set; }
public string Name { get; set; }
public short ProductFlagTypeId { get; set; }
}
Here is the index definition:
private class TestJoinIndex : AbstractIndexCreationTask<TestChildProductFlagDocument, TestJoinIndexOutput>
{
public TestJoinIndex()
{
Map = docs => from doc in docs
select new
{
TestParentDocumentId = doc.TestParentDocumentId,
ProductFlagTypeId = doc.ProductFlagTypeId
};
TransformResults = (database, results) =>
from result in results
let parentDoc = database.Load<TestParentDocument>(result.TestParentDocumentId)
select new
{
TestParentDocumentId = result.TestParentDocumentId,
ProductFlagTypeId = result.ProductFlagTypeId,
Name = parentDoc.Name
};
}
My code to call the index looks like so:
var theJoinIndexes = ravenSession.Query<TestJoinIndexOutput, TestJoinIndex>().ToList();
This returns almost immediately and fails unless I do the following:
var theParentDocuments = ravenSession.Query<TestParentDocument>().ToList();
var theJoinIndexes = ravenSession.Query<TestJoinIndexOutput, TestJoinIndex>().ToList();
My Ravendb embedded definition looks like so:
docStore = new EmbeddableDocumentStore
{
UseEmbeddedHttpServer = false,
RunInMemory = true
};
docStore.Configuration.Port = 7777;
docStore.Initialize();
IndexCreation.CreateIndexes(typeof(TestJoinIndex).Assembly, docstore);
A:
You aren't waiting for indexing to complete, call WaitForNonStaleResultsAsOfNow
| {
"pile_set_name": "StackExchange"
} |
Q:
Suppose $X$ has a standard normal distribution and $Y=e^X$. What is the $k^{\text{th}}$ moment of $Y$?
My attempt
$$F_Y(y) = P(Y<y) = \int\limits_{-\infty}^{\ln y}\frac{1}{\sqrt{2\pi}}e^{-\frac{1}{2}x^2}dx $$
from $f_Y(y)=\frac{d}{dy}F_Y(y)$,
$$ f_Y(y) = \frac{1}{y\sqrt{2\pi}}e^{-\frac{1}{2}(\ln y)^2}~~~(0<y<\infty) $$
so
$$ M_Y(t)=\int_0^{\infty}e^{ty}\frac{1}{y\sqrt{2\pi}}e^{-\frac{1}{2}(\ln y)^2}dy$$
I'm not sure how to solve this integral?
A:
$$E(Y^k) = E(e^{kX}) = M_{X}(k) = e^{\mu k + \frac{\sigma^2k^2}{2}}$$
Put $\mu = 0$ and $\sigma = 1$ if $X$ follows standard normal distribution.
| {
"pile_set_name": "StackExchange"
} |
Q:
Print a score counter with HTML/Javascript
I am having the following logic in my code. When someone clicks a button on a button, I increment a score counter by one. I want to print this value in the html side, at the very next second. What are my optios? I have tried the following(score is a div in the html side and score the global counter) with no result:
document.getElementById("score").innerHTML+=score;
var tmpscore = document.getElementById("score");
tmpscore.appendChild(score);
Any ideas?
A:
var score_elem = document.getElementById("score");
score_elem.innerHTML = parseInt(score_elem.innerHTML)++;
| {
"pile_set_name": "StackExchange"
} |
Q:
React w/ Redux - Best way to find matching path in history
I have a React/Redux project that consists of a navigation, lists of items and a details pane (showing one single item).
The "Pop hits 2" album can be opened by navigating to path "/list/all" or "/list/pop" and then selecting the "Pop hits 2" row. When the "Pop hits 2" opens the path changes to "/album/1234567890". For correct rendering of the UI I need to know where I opened the "Pop hits 2" from ("/list/all" or "/list/pop") when closing the details pane. The album can also be opened from a shared link. I do not wish to use history.go(-1) - this will not work when pasting a shared link.
I need to be able to find the actual path in the history that matches the last opened list.
Is there a recommended way to achieve this in React?
Kind regards /K
A:
I turns out the best way to see where the application has been been is to simply use the state property in the React Router Link.
This article on how to pass state from Link to components really helped explain how to use the Link state.
Basically the Link can pass the state property to the rendered component.
<Link to={{ pathname: "/courses", state: { fromDashboard: true } }} />
The rendered component then access the state via props.location.state
This in conjunction with passing props to components generating the links solved my problem! (^__^)
| {
"pile_set_name": "StackExchange"
} |
Q:
Passing data from a parent visualforce page to a child visualforce page
I have successfully created a visualforce page (parent VF page) that injects another visualforce page (child VF page) into a jquery modal window.
The problem I am running into is passing some data from the parent VF page to the child VF page. The way I currently have it setup is using the apex:composition tag. However, I am not sure if that is the best approach. Here is the code...
Parent VF page
<apex:page controller="ChooseContactController">
JS/Stylesheets
<apex:form >
<apex:pageBlock title="Choose a contact" mode="edit">
<apex:pageBlockButtons >
<input type="button" class="btn show-modal" value="New Contact"/>
<apex:commandButton action="{!save}" value="Save" rerender="chooseContactPageMessagesWrapper"/>
</apex:pageBlockButtons>
<apex:outputPanel id="chooseContactPageMessagesWrapper">
<apex:pageMessages />
</apex:outputPanel>
Data Display
</apex:pageBlock>
<apex:inputHidden value="{!primaryContactId}" id="primaryContactId" />
</apex:form>
<div id="modal-div" title="Create Contact" style="display:none;">
<apex:composition template="CreateContact">
<apex:define name="accountId">
<apex:inputHidden value="{!accountId}" id="accountId" />
</apex:define>
</apex:composition>
</div>
In the apex:define tag, I am successfully passing the accountId to the child page...
Child VF page
<apex:page standardController="Contact" extensions="CreateContactExtensions">
<apex:form >
<apex:pageBlock title="Create a new contact">
<apex:outputPanel id="createContactPageMessagesWrapper">
<apex:pageMessages />
</apex:outputPanel>
<apex:pageBlockButtons >
<apex:commandButton action="{!save}" value="Save" rerender="createContactPageMessagesWrapper" />
</apex:pageBlockButtons>
<apex:pageBlockSection >
<apex:inputField value="{!contact.firstName}"/><br />
<apex:inputField value="{!contact.lastName}"/>
</apex:pageBlockSection>
</apex:pageBlock>
<apex:insert name="accountId"/>
</apex:form>
When I inspect the html on the child VF page, the accountId is successfully being passed over. However, the CreateContactExtensions controller class does not recognize the accountId.
CreateContactExtensions controller
public class CreateContactExtensions
{
public String accountId { get; set; }
public Contact contact { get; set; }
ApexPages.StandardController standardController;
public CreateContactExtensions(ApexPages.StandardController standardControllerParam)
{
accountId = 'test';
standardController = standardControllerParam;
contact = (Contact)standardController.getRecord();
}
public String getAccountId()
{
return accountId;
}
public PageReference save()
{
System.debug(accountId);
contact.AccountId = accountId;
standardController.save();
return null;
}
}
When I try to save the contact, the accountId is always set to 'test'. I am assuming that is because the child VF page extension controller class does not recognize accountId as a property.
Is there a way to get the extension controller class to recognize accountId as a property the way I have it setup? Should I be taking a different approach... maybe using apex:components? Is there a way to leverage a standard controller within a custom component?
Should I try one large custom visualforce page/controller? Although, I am not sure how viable this solution is because my child VF page is optional. To do this, I would have to move the child VF page markup into the form tag on the parent VF page. Then, when I post back to the parent VF custom controller, validation rules will run on all the properties. The contact property will need to have certain fields, i.e. last name, filled in for the validation rules to pass. Being that this piece is optional, sometimes those fields will not be filled in, the validation rules will fail, and I will never reach my method on the custom controller.
Am I simply missing something with my current architecture?
A:
I would suggest the pattern of using a custom component that receives data from the parent page. As long as you are only needing the value within the component, it is a straightforward process. If, however, you are wanting to modify the value in the component and return that to the parent page, it gets more complicated.
In the simplest form (just passing the value to the component):
<apex:component controller="YourComponentControllerClass" selfClosing="true" allowDML="true">
<apex:attribute name="accountId" description="" type="Id" assignTo="{!theAccountId}" />
<!-- do your stuff here -->
</apex:component>
public with sharing class YourComponentControllerClass {
public Id theAccountId {get; set;}
public YourComponentControllerClass() {}
// do your stuff here
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Oracle - all_tables is not complete?
How come all_tables does not show actually contain a list of all the tables?
I can do select * from blah; and desc blah.
But doing select * from all_tables where lower(table_name) = 'blah'; returns 0 rows.
blah is not a synonym or view but a table.
Is there a specific stats command that needs to be run so that all the tables that my user can query appear in all_tables?
A:
You might try the following statement to see what's going on.
select owner, object_name, object_type
from all_objects
where object_name = 'BLAH'
union
select o.owner, o.object_name, o.object_type
from all_synonyms s, all_objects o
where synonym_name like 'BLAH'
and o.owner = s.table_owner
and o.object_name = s.table_name;
I ran it on my system this output (names changed to protect the indigent).
OWNER OBJECT_NAME OBJECT_TYPE
------- -------------- -----------
PROD T_BLAH TABLE
PUBLIC BLAH SYNONYM
HTH.
| {
"pile_set_name": "StackExchange"
} |
Q:
C# list of class objects changing to match last object?
I am trying to make an 'archive' of all past versions of a class (or struct, for that matter). But as a class is created to be added to the list, it seems the sum total of listed classes alter themselves to match.
My code goes along something like this:
public class State
{
public int i;
public State(int newI)
{
i = newI;
}
}
List<State> list = new List<State>;
public void NewEntry(int x)
{
State state = new State(x); //this is the line in question
list.Add(state)
}
By the time the State constructor has executed, all states in list have been changed to match their i to the fresh value of x.
What am I missing, besides basic knowledge and understanding? :P
A:
Uhm... Is not very clear from your example, but let me guess what the problem is.
When you add the class to the list, you may be adding a reference.
When you use:
State x = new State();
State b = x;
box "x" and "b" points to same object, x.i and b.i are the same memory.
IF and if State is a struct, then it's different
public **struct** State
{
public int i;
public State(int newI)
{
i = newI;
}
}
Then
State x = new State();
State b = x;
will make a copy of every value field (like ints and doubles) and x.i will be in a different memory location than b.i
Is this related to your issue?
| {
"pile_set_name": "StackExchange"
} |
Q:
Red Hat shell: less command is always executing .tcshrc
I have a small issue with less command (this is happening only on Red Hat). Any time I use it is executing the .tcshrc. There is no alias defined for less. I have one machine running Red Hat and one SUSE, in SUSE everything is fine but not in Red Hat.
# which less
/usr/bin/less
# less abc
Executing .tcshrc
Late edit based on crw comments:
env variable is set as: LESSOPEN=|/usr/bin/lesspipe.sh %s
and running less -L abc is working without problem,.
A:
Is the LESSOPEN env variable defined?
LESSOPEN contains the path or piped-command and a filename placeholder for utilising an "input preprocessor" (filter) before displaying a file in less.
What happens when running less -L abc ?
The -L and --no-lessopen switches disable the input preprocessor.
| {
"pile_set_name": "StackExchange"
} |
Q:
PostgreSQL: Drop Database but DB is still there
I am new to PostgreSQL and I try to get my head around it. I am familiar to db's and MySQL.
I am trying to delete database, which I created since psql seems to ignore the changes I try to push through Django.
When I execute \l I get the following response:
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
------------------+--------+----------+-------------+-------------+-------------------
postgres | neurix | UTF8 | en_AU.UTF-8 | en_AU.UTF-8 |
test_db | neurix | UTF8 | en_AU.UTF-8 | en_AU.UTF-8 |
template0 | neurix | UTF8 | en_AU.UTF-8 | en_AU.UTF-8 | =c/neurix +
| | | | | neurix=CTc/neurix
template1 | neurix | UTF8 | en_AU.UTF-8 | en_AU.UTF-8 | =c/neurix +
| | | | | neurix=CTc/neurix
template_postgis | neurix | UTF8 | en_AU.UTF-8 | en_AU.UTF-8 |
(5 rows)
Now I wan to drop the database "test_db" with
DROP DATABASE test_db
but when I execute \l afterwards, the table is still there and the overview looks like about.
A:
Did you type a ; after the DROP DATABASE test_db? Did PostgreSQL print a response to your command?
| {
"pile_set_name": "StackExchange"
} |
Q:
Azure AD B2C Link to Sign Up Page (Not Sign In)
I'm using Azure AD B2C with msal.js in my React app.
Currently, when the user tries to enter the protected area of my app, msal.js redirects the user to the login in page which provides a link to the sign up page.
Is there a way for me to send users directly to the sign up page? There are cases when I know the user has not yet signed up so it's bad user experience to send the user first to the sign in page then let them click and go to the sign up page. It would be nicer to just send them directly to sign up instead.
A:
As well as the sign-up or sign-in policy, you can create a sign-up only policy, which allows a new user to sign up with a local account and/or a social account.
| {
"pile_set_name": "StackExchange"
} |
Q:
Chipmunk Physics or Box2D for C++ 2D GameEngine?
I'm developing what it's turning into a "cross-platform" 2D Game Engine, my initial platform target is iPhone OS, but could move on to Android or even some console like the PSP, or Nintendo DS, I want to keep my options open.
My engine is developed in C++, and have been reading a lot about Box2D and Chipmunk but still I can't decide which one to use as my Physics Middleware.
Chipmunk appears to have been made to be embedded easily, and Box2D seems to be widely used.
Chipmunk is C , and Box2D is C++, but I've heard the API's of Box2D are much worse than chipmunk's API's.
For now I will be using the engine shape creation and collision detection features for irregular polygons (not concave).
I value:
1) Good API's
2) Easy to integrate.
3) Portability.
And of course if you notice anything else, I would love to hear it.
Which one do you think that would fit my needs better ?
EDIT: I ended up writing an article about my particular choice, you can find it here
A:
I use both, but when I can choose, I go for chipmunk, it has much better API, and was much easier to learn...
But that was because I learned it without need for a community, the manual is completly fine.
UPDATE: My current game is using Box2D, and I wish I used Chipmunk with it... Mostly because Box2D has two serious issues, that are exacerbated on my game: First, it has a REALLY OLD bug where objects "snag" on corners, my game is a breakout game, so when the ball is "rolling" along a wall, sometimes it snag and is flung away from the wall, lots of people asked why my game physics looks "random".
The other issues that Box2D have, is how it store objects, Chipmunk use a spatial hash, and Box2D use a binary tree, my game was having MASSIVE slowdowns in levels with lots of objects, I asked Erin (author of Box2D) the reason, and he explained that because Box2D uses binary tree, if you place objects in a grid (like I said, my game is a breakout clone! everything is in a grid!) the tree gets unbalanced, and Box2D slows down. The solution for my game was make some levels into a "checkerboard" pattern to avoid this problem.
So, for all tile-based games, I will just use Chipmunk, Box2D REALLY is unsuitable for those (because the "snag" on tile corner bug, and the slowdown bug with tile grid)
A:
You are right, chipmunk has been developed improving a lot of the places where Box2D falls down.
However, Box2D is definitely the more established platform and from my personal experience when making the decision of which engine to use, I found that Box2D had a much larger community following, so was easier to learn by example.
A:
Chipmunk is straight C, while Box2D is C++. There is also a new set of Objective-C bindings for Chipmunk, but they are not free to use commercially.
As I understand it, Chipmunk does not support Continuous Collision Detection, but Box2D does. This is important to prevent "tunneling" (objects passing slightly through eachother when moving at high speeds)
At the end of the day, from what I hear, they're both great. If you prefer C++ to C or need continuous collision detection, you should probably choose Box2D.
If you'd rather use a pure C library, go with Chipmunk.
I personally use Box2D and my experience has been fantastic so far.
Also, I think Box2D has a different (possibly larger) set of joint types, so that could be something to consider...
| {
"pile_set_name": "StackExchange"
} |
Q:
Como listar apenas o nome das pastas existentes em um determinado diretório
Como posso fazer para listar apenas o nome de uma pasta que está dentro de uma pasta raiz?
Exemplo:
Pasta raiz C:/Downloads
SubPastas: Teste/ Teste 2
Na minha DLL eu consigo listar as pastas porém com seu caminho completo, gostaria apenas de listar o nome das subpastas:
No caso apenas Teste e Teste 2
Segue código:
private void carregarFolders()
{
try
{
string caminho = @"C:/Downloads";
ddlFolders.DataSource = Directory.GetDirectories(caminho);
ddlFolders.DataValueField = "";
ddlFolders.DataTextField = "";
ddlFolders.DataBind();
ddlFolders.Items.Insert(0, new ListItem(string.Empty, string.Empty));
}
catch (Exception ex)
{
throw ex;
}
}
A:
A forma que lhe dará melhor performance:
try {
var dirs = new List<string();
foreach (var dir in Directory.EnumerateDirectories(caminho)) dirs.Add(dir.Substring(dir.LastIndexOf("\\") + 1));
} catch (UnauthorizedAccessException ex) {
//faça algo útil aqui ou retire esse catch
} catch (PathTooLongException ex) {
//faça algo útil aqui ou retire esse catch
}
ddlFolders.DataSource = dirs;
Coloquei no GitHub para referência futura.
Nunca capture uma exceção para fazer nada, especialmente para lançá-la novamente.
A:
É possível, usando LINQ, mapear cada caminho completo para uma instância de DirectoryInfo e, a partir desta instância, obter apenas o "nome final" do diretório usando a propriedade Name.
var source = Directory.GetDirectories(caminho)
.Select(c => new DirectoryInfo(c).Name)
.ToList();
ddlFolders.DataSource = source;
| {
"pile_set_name": "StackExchange"
} |
Q:
Clearance stops rails server from running
I installed clearance and followed the last steps which were "rails generate clearance:install". However rails server does not start up for me when I try to open in terminal.
/Users/lexi87/areyoutaken/config/initializers/clearance.rb:4:in `block in <top (required)>': uninitialized constant Clearance::PasswordStrategies::BCrypt (NameError)
from /Users/lexi87/.rvm/gems/ruby-1.9.3-p374/gems/clearance-0.16.3/lib/clearance/configuration.rb:36:in `configure'
from /Users/lexi87/areyoutaken/config/initializers/clearance.rb:1:in `<top (required)>'
from /Users/lexi87/.rvm/gems/ruby-1.9.3-p374/gems/railties-3.2.12/lib/rails/engine.rb:588:in `block (2 levels) in <class:Engine>'
Here's my Gemfile and I have bcrypt gem inside.
source 'https://rubygems.org'
gem 'rails', '3.2.12'
gem 'bootstrap-sass', '2.1'
gem 'bcrypt-ruby', '3.0.1'
gem 'faker', '1.0.1'
gem 'will_paginate', '3.0.3'
gem 'bootstrap-will_paginate', '0.0.6'
gem 'jquery-rails', '2.0.2'
gem 'annotate', '2.5.0'
gem 'clearance'
group :development, :test do
gem 'sqlite3', '1.3.5'
gem 'rspec-rails', '2.11.0'
gem 'guard-rspec', '1.2.1'
gem 'guard-spork', '1.4.2'
gem 'spork', '0.9.2'
gem 'rb-fsevent', '~> 0.9.1'
end
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'sass-rails', '3.2.5'
gem 'coffee-rails', '3.2.2'
gem 'uglifier', '1.2.3'
end
group :test do
gem 'capybara', '1.1.2'
gem 'factory_girl_rails', '4.1.0'
gem 'cucumber-rails', '1.2.1', :require => false
gem 'database_cleaner', '0.7.0'
# gem 'launchy', '2.1.0'
# gem 'rb-fsevent', '0.9.1', :require => false
gem 'growl', '1.0.3'
end
group :production do
gem 'pg', '0.12.2'
end
Any help would be greatly appreciated.
A:
You appear to be running gem version 0.16.3 of clearance, which doesn't support the Clearance::PasswordStrategies::BCrypt password strategy. If you upgrade to v1.0.0.rc1 or higher than that should work.
The only supported password strategies in 0.16.3 are Clearance::PasswordStrategies::Blowfish and Clearance::PasswordStrategies::SHA1.
If you want to try a version that supports BCrypt, you can update your Gemfile to say:
gem 'clearance', :git => "git://github.com/thoughtbot/clearance.git", :tag => "v1.0.0.rc4"
That will pull a specific tag of that repository. You can leave off the :tag to grab the latest version from GitHub. Keep in mind, that it may not be as stable as 0.16.3.
| {
"pile_set_name": "StackExchange"
} |
Q:
Thymeleaf: Accessing externaized strings from Java code
I'm currently using Thymeleaf in a classic Maven project (no Spring) and I can't find in the documentation a simple way to acces externalized internationalisation string from Java code like, e.g Rails' t() function.
I found the following tutorial but it really seems overengineered for what I'm trying to do.
A:
I finally adopted a raw solution, by just reading property files and extracting them into a Properties class.
This is not ideal as this obliges me to deal myself with the template name and locale to find the correct property but since this is a little project, this is no big deal. I hoped that Thymeleaf provided itself the correct set of locales but I've unhopefully no time to search.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do you get RequestMapping request in AOP advice from a Spring controller?
Given some kind of controller with a request mapping
@RequestMapping(value="/some/path", method=RequestMethod.POST)
How would you retrieve the method value (RequestMethod.POST) in the aspect class?
I want to keep track of all the controller methods that perform a POST request.
Thanks
A:
@AL13N: Your own answer is correct, but you do not need to use reflection if you just bind the annotation to a parameter. Here is an example in POJO + AspectJ. In Spring AOP it should be the same, though:
Sample controller with main method:
package de.scrum_master.app;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class MyController {
@RequestMapping(value="/some/path", method=RequestMethod.POST)
public void foo() {
System.out.println("foo");
}
public void bar() {
System.out.println("bar");
}
public static void main(String[] args) {
MyController controller = new MyController();
controller.foo();
controller.bar();
}
}
Aspect:
package de.scrum_master.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.web.bind.annotation.RequestMapping;
public aspect RequestMappingInterceptor {
@Pointcut(
"within(@org.springframework.stereotype.Controller *) && " +
"@annotation(requestMapping) && " +
"execution(* *(..))"
)
public void controller(RequestMapping requestMapping) {}
@Before("controller(requestMapping)")
public void advice(JoinPoint thisJoinPoint, RequestMapping requestMapping) {
System.out.println(thisJoinPoint);
System.out.println(" " + requestMapping);
System.out.println(" " + requestMapping.method()[0]);
}
}
BTW, the && execution(* *(..)) part of the pointcut is probably not necessary in Spring AOP because it just knows execution pointcuts anyway. In AspectJ you need to exclude call() and other types of pointcuts because AspectJ is more powerful. It does not hurt though and is safer and more explicit.
Console output:
execution(void de.scrum_master.app.MyController.foo())
@org.springframework.web.bind.annotation.RequestMapping(headers=[], name=, value=[/some/path], produces=[], method=[POST], params=[], consumes=[])
POST
foo
bar
Edit: Swapped parameters so as to make the joinpoint the first advice method parameter, because Spring AOP seems to insist on this order while AspectJ does not.
A:
Found the solution.
import org.aspectj.lang.reflect.MethodSignature;
import java.lang.reflect.Method;
@Pointcut("within(@org.springframework.stereotype.Controller *)")
public void controller() {}
// In advice
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
Method method = methodSignature .getMethod();
RequestMethod[] requestMethods = method.getAnnotation(RequestMapping.class).method();
Be careful of which class you import.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using Fermat's little theorem
I have this question:
$a \equiv 12^{772} \pmod{71}$, when $0 \leq a < 71$
and I am having troubles getting it started.
$\frac{772}{71}$ is $10$ with a remainder of $62$;
How do I do this question?
A:
$12^{772}=12^{71\cdot 10+62}\equiv 12^{10+62}=12^{71+1}\equiv 12\cdot 12=144\equiv 2$ mod $71$. So $a=2$.
Alternately,
$12^{772}=12^{70\cdot 11+2}\equiv 12^2=144\equiv 2$ mod $71$.
The first one uses the form $a^p\equiv a$ mod $p$ and the second uses the form $a^{p-1}\equiv 1$ mod $p$ if $gcd(a,p)=1$ where $p$ is prime.
A:
Hint $\rm\ \ X^N \equiv X\ \ \Rightarrow\ \ X^{A + B\ N + C\ N^{\Large 2} + \cdots} \equiv\ X^{A + B + C + \cdots}\ (mod\ N)$
Note $\, $ This is simply "casting out orders" - a cyclic group analog of casting out nines. Namely, $\rm\ X^{N-1} = 1\ \Rightarrow\ X^N = X\ $ thus we can map $\rm\ N\to 1$ when calculating integral powers of $\rm\:X\:$.
When $\rm\:X\:$ has order dividing $\:9\:,\:$ then it amounts precisely to casting out nines from its exponents.
For example, $\rm\ mod\ 27:\ (-2)^9 \equiv 1\ \Rightarrow\ (-2)^{721} \equiv -2\ \ $ since $\rm\ \ 721\equiv 7+2+1\equiv 1\ \:(mod\ 9)$
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get UserId from localStorage
I'm trying to build a blog, on a certain end point I want to list all the blogs created by specific user only, so i have stored the user info in Local Storage and I'm trying to get the username of the same, so that i can send the username to backend to get the blogs posted by that specific username.
set cookie
import cookie from 'js-cookie';
export const setCookie = (key, value) => {
if (process.browser) {
cookie.set(key, value, {
expires: 1
});
}
};
get cookie
// get cookie
export const getCookie = key => {
if (process.browser) {
return cookie.get(key);
}
};
set LocalStorage
export const setLocalStorage = (key, value) => {
if (process.browser) {
localStorage.setItem(key, JSON.stringify(value));
}
};
isAuth action
export const isAuth = () => {
if(process.browser ) {
const cookieChecked = getCookie('token')
if(cookieChecked){
if(localStorage.getItem('user')){
return JSON.parse(localStorage.getItem('user'))
}else{
return false;
}
}
}
}
This is the Info that I have stored in the Local Storage
{_id: "5ece659149421c1f18c0c756", username: "2asjvwxkq", name: "test3", email: "[email protected]", role: 0}
email: "[email protected]"
name: "test3"
role: 0
username: "2asjvwxkq"
_id: "5ece659149421c1f18c0c756"
I tried doing const username = isAuth() && isAuth().username
But it is returning undefined
I want to send the username as a props to a component but the variable username is getting me undefined value.
Update :
JSON.stringify(username) gives me the username but i am unable to send the same to backend
A:
Try doing
Suggestion 1 :
const username = isAuth() ? isAuth().username : ''
or use useEffect() wherever necessary .
Suggestion 2 :
Instead of sending the props , directly call the function
isAuth() inside the component you wanted to send in the first place ( if doing so won't affect anything ) and just to debug try doing JSON.stringify(user)
| {
"pile_set_name": "StackExchange"
} |
Q:
What suggests Edmund might be gay?
While I was doing some research, looking for an answer for Are Frog and Toad more than just friends?, I found this article listing 15 fictional characters the author thinks are probably gay. Some of them are widely joked about (Bert and Ernie, Peter Pan), but two characters on the list were deeply mystifying: Old Yeller, and Edmund Pevensie from the Chronicles of Narnia series.
Granted, it's been a long time since I read the Narnia books, but I did read them again as an adult, and I can't remember a single thing that would suggest Edmund is gay, particularly if we confine ourselves the The Lion, The Witch, and The Wardrobe as the list does. I can't recall any of the four Pevensie children having any kind of sexuality at all, except for some intimations about Susan in The Horse and His Boy and The Last Battle, so it seems to me we could as well say that Peter was gay and Lucy was a lesbian.
I very much doubt Lewis, as a Christian philosopher in the 1950's, would have written a gay character intentionally, but is there any way to interpret the text that would suggest Edmund is gay? Conversely, is there a way to interpret the text that suggests he's not gay?
A:
As someone who rather likes the totally non-canonical idea of gay Edmund, there is really no textual evidence to support this idea and you are right to point out that it is extremely unlikely that Lewis intended the character to be gay. There's not even much of what most people would consider obvious gay subtext. We don't see Edmund longingly describe the appearance or other attributes of other male characters, for example. We don't see him form the kind of extremely close male friendship that seems to border on romantic that you sometimes see in other works. We don't really see other characters describe him in ways that are coded gay.
All that being said, the person in the linked article isn't the first to come up with the idea of gay Edmund. A quick look at Narnia's M/M category over on the popular fan fiction site, An Archive Of Our Own reveals that Edmund is the character most listed in male/male pairings section despite the fact that both Peter and Caspian are played by older, arguably more attractive actors in the movies. Caspian/Edmund is the most popular male/male romantic pairing.
So why do many fans see Edmund, in particular, as gay but not, say, Peter or Lucy? What you have to realize about the way that many LGBT people read or view fiction is that they sometimes connect aspects of a particular character's journey or arc to their own journey or struggles with queerness.
One rather prominent example of this is the character Elsa from the Disney movie Frozen. A lot of LGBT people read Elsa as gay, not because she pines after women, explicitly or otherwise, but because her character arc shares much in common with the type of struggles that LGBT people face. Elsa is forced by her parents to keep her powers hidden, "conceal, don't feel." This causes her to feel alienated from her community and family, even from her sister who loves her no matter what. Elsa eventually chooses to live alone in a literal ice fortress because this is the only place where she can be herself. This parallels the issues that many young gay people face with lack of family acceptance, feelings of alienation and isolation, feeling somehow dangerous to others, suppression of a major part of themselves, and choosing to be apart from the community that they were born into because they don't feel they can be themselves there. But someone could, of course, correctly point out that there is nothing in the movie itself that suggests Elsa is gay and her sexuality goes entirely unaddressed in the movie.
And I do think there are elements of Edmund's character that LGBT people might identify with in this way. Edmund starts out the series feeling alienated from his siblings for reasons that aren't entirely clear. Edmund started being a jerk the first time he came back from boarding school which perhaps indicates that he was experiencing some form of bullying (interestingly, the same boarding school doesn't seem to have had a similar effect on Peter -- and though I believe Peter suggests that Edmund himself has become a bully, it wouldn't be unusual for someone who is bullied to, in turn, bully others). Edmund seems to harbor a certain amount of resentment toward his more explicitly masculine older brother (this isn't to say that Edmund is feminine, just that Peter is usually given the more explicitly masculine tasks of physically protecting the girls or generally waving his sword around, for example). In his resentment, Edmund screws up big time and betrays his siblings. Edmund is forgiven, but aspects of this forgiveness are kept "secret" -- the books explicitly point out that the all the conversation between Edmund and Aslan was never revealed to others, but that it was a conversation that Edmund never forgot. Edmund ends up doing something heroic in a way that suits his personality (using his smarts to come up with the idea of breaking the witch's wand -- something that no one else thought of).
I'm not saying that all gay people identify with these experiences or that no straight people can identify with them, but I think there is a certain overlap between Edmund's experiences and the experiences of many LGBT people that isn't really true of the other Pevensie siblings. The feelings of alienation and isolation followed by eventual acceptance and affirmation of Edmund's particular qualities as a person is a journey that would feel familiar and comforting to many LGBT people. Actually, now that I think of it, Edmund and Elsa share quite a bit in common -- the feelings of alienation from family, the somewhat closed-off personality, the much more open, optimistic, sweet younger sister, even the association with cold and winter (Edmund goes to the White Witch's castle to ally with her, Elsa has ice powers and goes off on her own to create her own ice castle).
And to answer this question: Conversely, is there a way to interpret the text that suggests he's not gay? No. There is nothing in the text itself that suggests he is heterosexual. We see more of adult Edmund in The Horse and His Boy than we do the other Pevensie siblings, but we don't see anything that would point to a possible sexuality. This certainly doesn't mean that he's gay -- but it is one less obstacle to people viewing him in that way.
A:
It is worth noting in this conversation that Lewis had very level-headed opinions about homosexuality and did write directly about the subject outside of his children's fiction; in his private life, he was great friends with a gay man, also a devout Christian, who expressed his theory of homosexuality to Lewis and whose view Lewis seemed to accept as authortitative.
This friend was Arthur Greeves, a familiar name to anyone who has read Lewis. In Greeves' assessment, homosexuality was a divinely-ordained burden, an opportunity to grow in holiness through lifelong celibacy. Although this might seem distasteful to many of us, it's worth noting that Greeves doesn't condemn himself as inherently flawed or sinful - if Lewis did accept this view, that's significant.
Lewis also wrote about the issue of homosexual relations in English public schools with clarity. He accuses the English public of reacting with disgust for neither moral nor Christian reasons but rather squeamishness.
All of this is to say that 1. Lewis has written about homosexuality and 2. Lewis' views were comparatively broad-minded. Although I doubt that any Narnian character is gay, it isn't impossible, and should be thought about through the lens of Lewis' actual writings on the subject.
References:
You can read about his "pious homosexual friend" in Vol. II of his letters, where a footnote identifies the friend as Greeves.
Read about Lewis and public school homosexuality here.
A:
No, there's absolutely no textual evidence for this. There's really not anything in the text that would come even vaguely close to supporting this. I suppose that you could say that, strictly speaking, the text doesn't say he's not either, though, but the fact remains that this simply can't be answered on the basis of textual analysis - it's simply not in the text.
Correct me if I'm wrong, but C. S. Lewis doesn't really explicitly discuss LGBT issues in any of his major works (Narnia or otherwise). You are also correct in stating that it would be highly anachronistic for him to intentionally make a character gay given the time he was writing in.
Keep in mind that that wasn't really a major public issue at the time (certainly not like it is today), and C. S. Lewis tended tended to shy away from controversial theological issues (and it certainly would have been controversial at the time - people's ideas on LGBT issues have evolved a lot since the 1950's) to some extent (at least in his major works), preferring to discuss "common ground" that all Christians could agree on - in fact, he's pretty explicit about that in, for example, Mere Christianity. (He does discuss some of those types of issues in his letters and essays, though).
| {
"pile_set_name": "StackExchange"
} |
Q:
How to discretize a signal?
If I have a function like below:
G(s)= C/(s-p) where s=jw, c and p are constant number.
Also, the available frequency is wa= 100000 rad/s. How can I discretize the signal at ∆w = 0.0001wa in Python?
A:
Use numpy.arange to accomplish this:
import numpy as np
wa = 100000
# np.arange will generate every discrete value given the start, end and the step value
discrete_wa = np.arange(0, wa, 0.0001*wa)
# lets say you have previously defined your function
g_s = [your_function(value) for value in discrete_wa]
| {
"pile_set_name": "StackExchange"
} |
Q:
Encode/decode certain text sequences in Qt
I have a QTextEdit where the user can insert arbitrary text. In this text, there may be some special sequences of characters which I wish to translate automatically. And from the translated version, I wish I could go back to the sequences.
Take for instance this:
QMessageBox::information(0, "Foo", MAGIC_TRANSLATE(myTextEdit->text()));
If the user wrote, inside myTextEdit's text, the sequence \n, I would like that MAGIC_TRANSLATE converted the string \n to an actual new line character.
In the same way, if I give a text with a new line inside it, a MAGIC_UNTRANSLATE will convert the newline with a \n string.
Now, of course I can implement these two functions by myself, but what I am asking is if there is something already made, easy to use, in Qt, which allows me to specify a dictionary and it does the rest for me.
Note that sequences with common prefix can create some conflicts, for example converting:
\foo -> FOO
\foobar -> FOOBAR
can give rise to issues when translating the text asd \foobar lol, because if \foo is searched and replaced before \foobar, then the resulting text will be asd FOObar lol instead of the (more natural) asd FOOBAR lol.
I hope to have made clear my needs. I believe that this may be a common task, so I hope there is a Qt solution which takes into account this kind of issues when having conflicting prefixes.
I am sorry if this is a trivial topic (as I think it may be), but I am not familiar at all with encoding techniques and issues, and my knowledge of Qt encoding cover only very simple Unicode-related issues.
EDIT:
Btw, in my case a data-oriented approach, based on resources or external files or anything that does not requires a recompilation would be great.
A:
It is always a bit ugly to self-answer questions, but... Maybe this solution is useful to someone.
As suggested by Nicholas in his answer, a good strategy is to use replacement. It is simple and effective in most cases, for example in the plain C/C++ escaping:
\n \r \t etc
This works because they are all different. It will always work with a replacement if the sequences are all different and, in particular, if no sequence is a prefix to another sequence.
For example, if your sequences are the one aboves plus some greek letters, you will not like the \nu sequence, which should be translated to ν.
Instead, if the replacing function tests for \n before \nu, the result is wrong.
Assuming that both sequences will be translated in two completely different entities, there are two solutions: place a close-sequence character, for example \nu;, or just replace by longest to shorter strings. This ensure that any sequence which is prefix of another one is not replaced before it.
For various reasons, I tried another way: using a trie, which is a tree of all the prefixes of a dictionary of words. Long story short: it works fairly well and probably works faster than (most) regexes and replacements.
Regex are state machines and it is not rare to re-process the input, with a trie, you avoid to re-match characters twice, so you go pretty fast.
Code for tries is pretty easy to find on the internet, and the modifications to do efficient matching are trivial, so I will not write the code here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Displaying notifications from a CLI app
I'm new to the Apple development ecosystem. I thought I'd start with writing CLI apps in Swift (and work my way towards OS X and iOS).
Although there is no GUI involved, I want to display notifications using the native notifications API. Is this possible with CLI apps written in Swift? Are there examples?
A:
You need a proper Cocoa app bundle to display notifications in the app. However, you can use AppleScript to accomplish this:
display notification "foo"
So with Swift, you can use NSTask:
NSTask.launchedTaskWithLaunchPath("/usr/bin/osascript", arguments: ["-e", "display notification \"Hello\""])
| {
"pile_set_name": "StackExchange"
} |
Q:
Google Charts - "Missing Query for request id: 0"
This error only appears if I try to put two charts on the same page. Both charts work perfectly if they are the only one on the page. The minute I add the second only the first one loads and I get the "Missing Query for request id: 0" error.
Here is my js file for the chart:
function drawChart(title, queryPage, divToFill) {
var dataTab = null;
var query = new google.visualization.Query(queryPage);
var strSQL = "SELECT *";
query.setQuery(strSQL);
query.send(processInitalCall);
function processInitalCall(res) {
if(res.isError()) {
alert(res.getDetailedMessage());
} else {
dataTab = res.getDataTable();
// Draw chart with my DataTab
drawChart(dataTab);
}
}
function drawChart(dataTable) {
// Draw the chart
var options = {};
options['title'] = title;
options['backgroundColor'] = "#8D662F";
var colors = Array();
var x = 0;
if(currentCampaignId >= 0) {
while(x < dataTab.getNumberOfColumns() - 2) {
colors[x] = '#c3c1b1';
x++;
}
colors[x] = '#d2bc01';
}
else {
colors[0] = '#c3c1b1';
}
options['colors'] = colors;
options['hAxis'] = {title: "Week", titleColor: "white", textColor: "white"};
options['vAxis'] = {title: "Flow", titleColor: "white", textColor: "white", baselineColor: "#937d5f", gridColor: "#937d5f"};
options['titleColor'] = "white";
options['legend'] = "none";
options['lineWidth'] = 1;
options['pointSize'] = 3;
options['width'] = 600;
options['height'] = 300;
var line = new google.visualization.LineChart(document.getElementById(divToFill));
line.draw(dataTab, options);
}
}
Here is a snip from the index.php file:
<body>
<script type="text/javascript">
google.load('visualization', '1', {'packages': ['table', 'corechart']});
google.setOnLoadCallback(function(){
drawChart("Water", "waterData.php", "water");
drawChart("Air", "airData.php", "air");
});
</script>
<div id="water" style="text-align: center;"></div>
<div id="air" style="text-align: center;"></div>
</body>
It throws the error right at the query.send(processInitalCall); line, only on the second time it's called. Both the waterData.php and airData.php are identical except for the sig field. I did notice there was a field called reqId and it's set to 0.
Do I need to somehow change this reqId in these classes?
A:
Probably too late, but for anyone interested...
When loading data from the data source, there will be a GET parameter in the request - tqx - with a value like: "reqId:0". You must return the same reqId in your response.
From the docs:
reqId - [Required in request; Data source must handle] A numeric
identifier for this request. This is used so that if a client sends
multiple requests before receiving a response, the data source can
identify the response with the proper request. Send this value back in
the response.
| {
"pile_set_name": "StackExchange"
} |
Q:
How does MVC3 picks which ViewEngine to use if I have multiple engines in ViewEngines collection?
I have a custom view engine developed internally. In the same project, I would like to use Razor for some pages and my custom engine for some pages. How does MVC framework choose which engine to use? BTW, my custom engine does not require any templates, it renders pages based on meta-data from database. For my custom engine I don't want to setup any template files.
What I am expecting is there should be a way to drive framework to use certain engine based on the controller name and action name.
Is this flexibility exists in MVC3?
A:
Your view engine should implement the IViewEngine interface. After you registered your view engine with the ViewEngines.Engines.Add() method, the MVC framework will call FindView and FindPartialView whenever it needs a view engine to render a view.
It's absolutely possible for multiple view engines to operate side by side. If you don't want your view engine to be used in a specific situation you return new ViewEngineResult(new string[0]); from FindView or FindPartialView and MVC will choose another view engine. If you do want your view engine to be used you return a valid ViewEngineResult pointing to the view class (that is implementing IView) that you want to Render the result.
There are some specifics with the useCache parameter. If you want to know more, there was an excellent presentation on building your own view engine at TechEd 2011 by Louis DeJardin. You can find the video of Writing an ASP.NET MVC View Engine at Channel9.
| {
"pile_set_name": "StackExchange"
} |
Q:
Building new species. How deep and how complex?
In my latest project i developed new species not far different from humanoids. I am making whole history, gender interaction, abilities, their psychology and trying to discribe their life and development from birth to adult person.
I even made patology report and developed special character, who made experiments from them.
My question is: "How far is good to go to discribe species its abilities and complexity for reader to be still interested in it?"
A:
Treat fantastic, made-up facts the same as you would treat facts about our own world.
Do you describe the physiology of human beings when you write a book about people like you and me? No. Neither should you go into medical detail when you write about aliens – unless your protagonist is a scientist studying them. In that case, give us the same amount of detail as you would if you were writing an episode of Medical Detectives, that is, do go into detail, but keep it limited to what is relevant to your plot. Do not stifle the dynamic of your story.
But if you write about normal people habitually interacting with the normal aliens they live with, mention their physical characteristics only when they become relevant to the story, in the same way you would describe the color of the eyes of a person your protagonist is in love with, but won't usually report the whole spectrum of possible eye colors that men and women might have.
By treating fantasy the same as facts are conventionally treated in fiction, you make the fantasy more believable.
I assume you are writing narrative fiction. If, on the other hand, you are writing a Bestiarium Imaginarium, don't hesitate to give us the full Atlas of Alien Anatomy.
The above answers your question about how far your in-text descriptions should go. For yourself, as a writer, you should of course be clear even about details that don't make it into the text. If you don't know that humans have differing eye colors, you will miss the importance of eye color for a person staring into the eyes of their loved one. But this does not mean that you have to define all possible details of your alien anatomy before you start writing. Just invent the most important aspects, and make up some of the minor details as you go along. You will have to rewrite anyway, and will have ample opportunity to correct small mistakes.
A:
Whatever point you choose on that spectrum you will have some readers who won't like the place that you have chosen. You will never get the balance exactly right for everyone.
I am sure some people would enjoy a purely anthropological study of another species, if it was well written and contained interesting insights - myself included. Equally, that would bore others to death.
Personally, I would aim to keep the details subtlety conveyed. I prefer to infer characteristics than to be told them directly. I like to have some gaps that make me wonder.
It also depends on the type of story you are telling, for example it would be difficult to naturally talk about the gender interactions of humans as a human. Whereas you could make a more naturally flowing story if you were talking about human gender interactions as seen from a non-human perspective.
It ultimately depends on what your goal for the story is, if you want a vehicle to convey the complexities you have created in this species then choose a story that helps to exhibit that. If you want the species characteristics to be incidental to the story you want to tell then work out how best to tell that story.
Decide on the story that you want to tell. The story that you would want to read. Write the story that you are passionate about, that you are excited to tell. Help the reader to understand what is so special about this species and they will enjoy the journey you take them on.
| {
"pile_set_name": "StackExchange"
} |
Q:
CertGetCertificateChain - Invalid memory access
Cross-posting for visibility: https://groups.google.com/forum/#!topic/jna-users/qfkoxPwA-r8
I am working on creating a wrapper for the CertGetCertificateChain method in the Crypt32 lib and I would like to get help in resolving an 'Invalid Memory Access' issue that results in a crash.
The signature for the wrapper is:
boolean CertGetCertificateChain(Pointer hChainEngine, PCERT_CONTEXT pCertContext, Pointer pTime,
Pointer hAdditionalStore, CERT_CHAIN_PARA.ByReference pChainPara, int dwFlags, Pointer pvReserved,
PointerByReference ppChainContext);
The structures i am using are:
public static class CERT_CHAIN_PARA extends Structure {
public int cbSize;
public CERT_USAGE_MATCH RequestedUsage;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("cbSize", "RequestedUsage");
}
public static class ByReference extends CERT_CHAIN_PARA implements Structure.ByReference {}
}
public static class CERT_USAGE_MATCH extends Structure {
public int dwType;
public CERT_ENHKEY_USAGE Usage;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("dwType", "Usage");
}
public static class ByReference extends CERT_USAGE_MATCH implements Structure.ByReference {}
}
public static class CERT_ENHKEY_USAGE extends Structure {
public int cUsageIdentifier;
public LPSTR.ByReference rgpszUsageIdentifier;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("cUsageIdentifier", "rgpszUsageIdentifier");
}
public static class ByReference extends CERT_ENHKEY_USAGE implements Structure.ByReference {}
}
There are copies of the ones in the Wincrypt.h header. CERT_CHAIN_PARA has additional members that become active only when a flag is enabled and I have not enabled it in the native code. So, i avoided adding them here.
The calling code is:
CERT_CHAIN_PARA.ByReference pChainPara = new CERT_CHAIN_PARA.ByReference();
PointerByReference p = new PointerByReference();
pChainPara.cbSize = pChainPara.size();
pChainPara.RequestedUsage.dwType = WinCrypt.USAGE_MATCH_TYPE_AND;
pChainPara.RequestedUsage.Usage.cUsageIdentifier = 0;
pChainPara.RequestedUsage.Usage.rgpszUsageIdentifier = null;
CertGetCertificateChain(null, pCertContext, null, null, pChainPara, 0, null, p);
The crash happens on the call to CertGetCertificateChain. One thing i've noticed it that setting pChainPara to null stops it from throwing the memory access exception and crashing. But i am not sure if this is because the pChainPara structure is corrupt or if setting null forces it to fail early and masks an issue somewhere else. I've checked the sizes of the structure passed in and they match with the sizes in the native code.
Please let me know if i need to provide more information. Once implemented and tested, i'll clean this up and contribute the certificate workflow's wrappers and structures to JNA.
Edit:
I tried adding the additional members in CERT_CHAIN_PARA as given below:
public static class CERT_CHAIN_PARA extends Structure {
public int cbSize;
public CERT_USAGE_MATCH RequestedUsage;
public CERT_USAGE_MATCH RequestedIssuancePolicy;
public int dwUrlRetrievalTimeout;
public boolean fCheckRevocationFreshnessTime;
public int dwRevocationFreshnessTime;
public FILETIME pftCacheResync;
public CERT_STRONG_SIGN_PARA.ByReference pStrongSignPara;
public int dwStrongSignFlags;
@Override
protected List<String> getFieldOrder() {
// return Arrays.asList("cbSize", "RequestedUsage");
return Arrays.asList("cbSize", "RequestedUsage","RequestedIssuancePolicy","dwUrlRetrievalTimeout","fCheckRevocationFreshnessTime",
"dwRevocationFreshnessTime","pftCacheResync","pStrongSignPara","dwStrongSignFlags");
}
public static class ByReference extends CERT_CHAIN_PARA implements Structure.ByReference {
}
}
public static class CERT_STRONG_SIGN_SERIALIZED_INFO extends Structure {
DWORD dwFlags;
LPWSTR pwszCNGSignHashAlgids;
LPWSTR pwszCNGPubKeyMinBitLengths;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("dwFlags", "pwszCNGSignHashAlgids", "pwszCNGPubKeyMinBitLengths");
}
public static class ByReference extends CERT_STRONG_SIGN_SERIALIZED_INFO implements Structure.ByReference {
}
}
public static class DUMMYUNIONNAME extends Union {
Pointer pvInfo;
CERT_STRONG_SIGN_SERIALIZED_INFO.ByReference pSerializedInfo;
LPSTR pszOID;
}
public static class CERT_STRONG_SIGN_PARA extends Structure {
public int cbSize;
public int dwInfoChoice;
public DUMMYUNIONNAME union;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("cbSize", "dwInfoChoice", "union");
}
public static class ByReference extends CERT_STRONG_SIGN_PARA implements Structure.ByReference {
}
}
public static class FILETIME extends Structure {
public int dwLowDateTime;
public int dwHighDateTime;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("dwLowDateTime", "dwHighDateTime");
}
public static class ByReference extends FILETIME implements Structure.ByReference {
}
public static class ByValue extends FILETIME implements Structure.ByValue {
}
}
}
And the calling code was modified to set the rest of the members:
pChainPara.RequestedIssuancePolicy.Usage.cUsageIdentifier = 0;
pChainPara.RequestedIssuancePolicy.Usage.rgpszUsageIdentifier = null;
pChainPara.dwUrlRetrievalTimeout = 0;
pChainPara.fCheckRevocationFreshnessTime = false;
pChainPara.dwRevocationFreshnessTime = 0;
pChainPara.pftCacheResync.dwHighDateTime = 0;
pChainPara.pftCacheResync.dwLowDateTime = 0;
pChainPara.pStrongSignPara = null;
But I still get the failure as mentioned above.
Edit2:
PCERT_CONTEXT context = CryptUIDlgSelectCertificateFromStore(store, hwnd,
"", "", 2, 0, null);
public static class CERT_CONTEXT extends Structure {
public int dwCertEncodingType;
public Pointer pbCertEncoded;
public int cbCertEncoded;
public Pointer pCertInfo;
public Pointer hCertStore;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("dwCertEncodingType", "pbCertEncoded", "cbCertEncoded", "pCertInfo", "hCertStore");
}
public static class ByReference extends CERT_CONTEXT implements Structure.ByReference {
}
}
public static class PCERT_CONTEXT extends Structure {
public CERT_CONTEXT.ByReference certContext;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("certContext");
}
public static class ByReference extends PCERT_CONTEXT implements Structure.ByReference {
}
public static class ByValue extends PCERT_CONTEXT implements Structure.ByValue {
}
}
A:
It's quite possible that you need to define the remainder of the CERT_CHAIN_PARA structure, since its expected size depends on a compile-time variable (independent of what you might supply in cbSize).
Note This member can be used only if CERT_CHAIN_PARA_HAS_EXTRA_FIELDS
is defined by using the #define directive before including Wincrypt.h.
If this value is defined, the application must zero all unused fields.
UPDATE
PCERT_CONTEXT is a typedef to CERT_CONTEXT *. Your Java definition will in effect make it CERT_CONTEXT **, at least w/r/t passing it as a parameter. If you need native CERT_CONTEXT *, use Java CERT_CONTEXT as the parameter type. Embedding a pointer field within a struct effectively gives the callee the address of the value you wish to pass, rather than the pointer value you really want to pass.
In general you should omit the <Structure>.ByReference notation unless you are defining a structure field that needs to be of type struct *.
| {
"pile_set_name": "StackExchange"
} |
Q:
Strange outlet behavior
I am going to be updating electrical outlets in my house, so today I checked them all with the 3 lamp tester. Only a few are properly grounded and others not. One outlet is showing strange behavior.
If washer is connected to the lower outlet, the upper shows proper grounding (lamps 2 & 3 are ON). But if I disconnect the washer and check again, only 2nd lamp is ON indicating no proper grounding. Is connecting the washer doing something funny with both receptacles?
Update:
When the washer is connected to a GFCI outlet, it runs uninterrupted without tripping that outlet. I have tested that the GFCI outlet is working as expected (the reset test).
I tested the original non-GFCI outlet in my question with a second 3 prong equipment (a grain mill) and now the receptacle tester illuminates only the middle lamp (i.e. no grounding) as expected.
So it looks like there is definitely some grounding fault with the washer but that doesn't stop it from working either on GFCI or non-GFCI outlets.
Update 2:
It looks like my GFCI receptacle may be wired incorrectly. I can't get it to trip with gfci receptacle tester. In stead, when I press the tester switch, it lights up first and last lamps indicating that neutral and hot are reversed. I will post another update when I open up the outlet to check.
A:
This feels like the washing machine has a ground fault, where there's a connection between neutral and earth somewhere. See Why does my laundry machine trip the GFCI when I plug it in?
If so, this is something you need to deal with, as it makes using your washing machine unsafe.
(In that case, when the tester checks for ground, power goes into the earth pin, up the earth pin on the washer, out the neutral pin on the washer, and back into the panel, which looks a lot like a real ground.)
You can also test with a different three-pin device connected, and see if you still get a fake earth reading.
EDIT: since you tested with a GFCI, and it works, I'll take another look with the new information.
When you plug in the washer, the 3rd light comes on. The usual meaning for the third light is that there's a voltage difference between hot to ground, which means the ground is going somewhere. While it's possible there's a grounding wire somewhere that you missed, another interesting possibility is that the surface the washing machine rests on is acting as a ground. This is somewhat dependent on the surface and the actual construction of the washing machine, but if the washer feet are metal, and it's resting on concrete, there might be enough conductivity to give a ground reading. In that case, your tester is giving a correct result. (But you should still run a real earth wire.)
| {
"pile_set_name": "StackExchange"
} |
Q:
Compare last row range of values to a set of rows in VBA
I am basically inputting data from a cell and copying it to another set of cells as seen on the table below as an example. Now I need to check if the input data is the same as the previous ones. If it is the same, I will clear that row and remove it form the table.
DATA1 DATA2 DATA3
cat 1 white
dog 2 white
dog 1 brown
cat 1 white (should be compared and removed from table - similar with 1st row)
I have tried using a For loop function. However, Range value cannot accept Range("S" & Lastrow & ":" & "X" & Lastrow). Could you please advise what should be the correct format for this? Thank you!
Sub RowCompare()
Dim ary1() As Variant
Dim Range1 As Range, Range2 As Range, rr1 As Range, rr2 As Range
Set xWs = ThisWorkbook.Sheets("Summary")
LastRow = xWs.Range("T" & Rows.Count).End(xlUp).Row + 1
'Check last row with previous rows
Set Range1 = Range("S5:X" & LastRow)
For i = LastRow - 1 To 2 Step -1
Set Range2 = Range("S")
Set rr1 = Range1.Rows(1)
Set rr2 = Range2.Rows(1)
ary1 = Application.Transpose(Application.Transpose(rr1))
ary2 = Application.Transpose(Application.Transpose(rr2))
st1 = Join(ary1, ",")
st2 = Join(ary2, ",")
If st1 = st2 Then
MsgBox "UPH already plotted"
Exit Sub
End If
Next
End Sub
A:
For example the formula
=COUNTIFS(A:A,A:A,B:B,B:B,C:C,C:C)
results in >1 if the current row is a duplicate:
You could also use this in VBA
Option Explicit
Public Sub TestIfLastRowIsDuplicate()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet1")
Dim LastRow As Long 'find last used row
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
Dim Cnt As Long 'count how many duplicates of last row exist
Cnt = WorksheetFunction.CountIfs(ws.Range("A:A"), ws.Range("A" & LastRow), _
ws.Range("B:B"), ws.Range("B" & LastRow), _
ws.Range("C:C"), ws.Range("C" & LastRow))
If Cnt > 1 Then
MsgBox "Last row is duplicate"
Else
MsgBox "Last row is unique"
End If
End Sub
| {
"pile_set_name": "StackExchange"
} |
Q:
Unable to add Selenium library in Pycharm
So I installed Python, Pycharm and Selenium
Pycharm still unable to show selenium even though Selenium is installed.
from selenium.webdriver import Edge
Look at the screenshot.
It had happened before, but then I was able to click "install/ad selenium" etc and then it worked. But I dont see any more option.
What are the other options to add this?
A:
Found the problem.
At the time of creating project, I was not checking the box to "inherit global site-package", as shown in the screenshot.
| {
"pile_set_name": "StackExchange"
} |
Q:
Logic to hide opened sub menu on click elsewhere?
Suppose user goes to a ecommerce site and clicks on products, there is a submenu which drops down. What logic to write to ensure that when user clicks on any other blank space(or elements) that submenu is hidden back?
A:
Check this js fiddle:-
http://jsfiddle.net/H3Vnw/3/
Here is the java script code:-
$(document).mouseup(function (e)
{
var container = $('.dropdown-menu');
if (container.has(e.target).length === 0)
{
container.hide();
}
});
$('.comment').click(function(){
$('.dropdown-menu').css({'display': 'block'});
});
If we click on the comment we can get drop menu if we click else where the drop menu will be hidden!
Hope this helps!
| {
"pile_set_name": "StackExchange"
} |
Q:
Security changes between Windows 2008 (Windows 7) and 2008 R2?
Coming from the questions, for ex., Sharepoint 2010 - “We did not find any results for” keyword which identified the problem (but not solution) with the help of Mike Hacker's blog Crawler Issue with SharePoint 2010 and Windows Server 2008 R2
The latter tells:
"The one that was working was built on Windows Server 2008 and the problem farm was built on Windows Server 2008 R2.
Since Windows Server 2008 R2 and Windows 7 are built on the same core code"
"After several conversations with Microsoft it appears that the issue is related to security changes made in Windows Server 2008 R2 and Windows 7"
What are the security changes in Windows Server 2008 R2 (and Windows 7) in comparison with Windows Server 2008?
How is it that "Windows Server 2008 R2 and Windows 7 are built on the same core code" but Windows Server 2008 is built on a different one?
that is, workstation and server share the same core code but the different releases of the same Windows Server 2008 - not?
A:
Windows Server 2008 R2 is not "a different release of Windows Server 2008": it's the server release of Windows 7; this becomes immediately obvious if you simply compare the taskbar of Vista, 2008, 7 and 2008 R2. It also results from the version numbers, as Vista/2008 are NT 6.0, while 7/2008 R2 are NT 6.1.
Yes, I know the name is quite misleading; moreso as Windows Server 2003 R2 actually was only an interim release of Windows Server 2003, i.e. exactly the same O.S., but with some additional features.
| {
"pile_set_name": "StackExchange"
} |
Q:
Did the Elves do mathematics?
The Elves had quite a lot of time to do what interested them. They liked the stars, which is (among mortals) a good starting point for geometry. It is also said about the Noldor, that they always searched more suitable names for things they encountered or imagined, so I can imagine them playing with abstract concepts.
Is there any evidence that the Eldar developed mathematics? (Other than simple integer counting.)
Edit: The answers so far covered the everyday math, they had to have to accomplish their other works, quite well. So my second question is:
Is it possible, that they studied more advanced mathematics not for purpose, but for challenge and intellectual exercise, and for its beauty?
(It is said in the Silmarillion, that: "(the Noldor) delighted in building of tall towers." They didn't do it for watchtower, fortification, display of power, lighthouse, or any other purpose, for which towers are normally built on Middle-earth, but they enjoyed their beauty, and loved to challenge their powers, and to create things, which weren't before. Just like they cut gems, and scattered them on the shores.)
A:
Little
There's evidence for some elementary algebra in devising the Elvish calendar; in particular, they were aware that they couldn't quite fit the right number of days into a year, and devised leap days to compensate, and then compensated again for the deficiencies in that system:
Between yávië and quellë1 were inserted three enderi or 'middle-days'. This provided a year of 365 days which was supplemented by doubling the enderi (adding 3 days) in every twelfth year.
How any resulting inaccuracy was dealt with is uncertain. If the year was then of the same length as now, the yén2 would have been more than a day too long. That there was an inaccuracy is shown by a note in the Calendars of the Red Book to the effect that in the 'Reckoning of Rivendell' the last year of every third yén was shortened by three days: the doubling of the three enderi due in that year was omitted; 'but that has not happened in our time'.
Return of the King Appendix D: "The Calendars"
There's also some (limited) evidence for abstract mathematical thought, in that the Elves prefer a duodecimal number system; Tolkien remarks in Letter 344 that this is based on a simple mathematical observation:
The English use duodecimals and have special words for them, namely dozen and gross. The Babylonians used duodecimals. This is due to the elementary mathematical discovery, as soon as people stop counting on their fingers and toes, that 12 is a much more convenient number than 10.
The Letters of J.R.R. Tolkien 344: From a letter to Edmund Meskys. November 1972
As VBartilucci points out in a comment on the question, the advanced engineering seen among the Elves may hint at some practical mathematics, though I wouldn't want to come down on this definitively; based on Tolkien's intended themes, I would suggest that the Elves tend to prefer a more intuitionist approach to their craft, and of course one can't discount the presence of magic.
In any case, there's no evidence given of theoretical mathematics among the Elves.
1 Two of the seasons as reckoned in Rivendell; the words respectively translate to "autumn" and "fading", and between them basically correspond to what we would call autumn (possibly with some overlap with early winter)
2 "Long year", equivalent to 52,596 solar days
A:
There's no geometry proofs in the text of Lord of the Rings, but there are lots of activities that the Elves participated in that require mathematics of greater complexity than integer counting.
The elves we see in the movies and books live high in the trees in beautiful constructions. Now, Ewoks also lived in trees, but there's a huge difference in construction style: everything Ewok is over-engineered and over built, because they are NOT concerned with their city looking beautiful, and they aren't doing any computation during construction. It's possible to build a relatively safe construction intuitively using ropes and the like in trees, or big thick walls surrounded by buttresses using instinct alone... but it's hard to do so beautifully. Elven cities are beautiful constructions with graceful arches, flying buttresses, and artistic flourishes. This would require at least basic geometry to calculate dimensions and the ability to calculate load. It's easy to slam a thick buttress into the ground; to have a graceful load bearing pillar requires either a TON of wasteful experimentation or some form of calculation.
Elves understood metalworking. Celebrimbor and Gondolin crafted the Rings as well as Orcrist and Glamdring. Basic smithing can be done on an ad-hoc basis; a few general "recipes" can be used to combine metals. Swords and armor for regular troops would be nothing special; good enough quality to fight, but not pieces of art. However, advanced alloys require mathematics to calculate time, temperature, and ingredients to produce specific properties in the materials being forged. In the books, armor is "Early Middle" mail and scale shirts and the like; basic simple repeating shapes or thick slabs of metal. In the movies, plate armor appears in the "High and Middle Late" period style. Plate armor requires basic geometry to fabricate, as well as computation to build armor properly for the wearer. Hand-forging being slow, you wouldn't want to "seat of the pants" design a complete suit of plate armor, especially if you need to repeat that pattern over an entire group of soldiers.
Finally, Elves understood the concept of sailing. Any sailing beyond sight of shore requires navigation, and even dead reckoning needs mathematics to compute speed and time. Celestial navigation brings in angles as well. Basic geometry is required to navigate by map using the data collected to compute heading and current location.
| {
"pile_set_name": "StackExchange"
} |
Q:
Unable to query SQL view
I'm working on an old classic ASP site and have run into a problem. I can query database tables but not views.
This query on a table returns the correct number of rows:
Set rs = Server.CreateObject("ADODB.Recordset")
sqlQuery = "SELECT * FROM tblContent;"
rs.Open sqlQuery, conn, 1, 2
response.write "q1 cnt = " & rs.RecordCount
The same query on a view returns -1:
Set rs = Server.CreateObject("ADODB.Recordset")
sqlQuery = "SELECT * FROM myView;"
rs.Open sqlQuery, conn, 1, 2
response.write "q2 cnt = " & rs.RecordCount
Both queries return the correct number of rows if run from SQL Server Management Studio but only one works when called from a .asp web page. The same seems to apply for all tables and views in the DB (I've tested half a dozen of so of each).
Can anyone offer any clues as to what is going on here?
A:
OK, here's my comment as an answer
This is a workaround, it doesn't explain why the recordcount property doesn't work with views, but you can use an SQL query to count your rows, eg
Set rs = Server.CreateObject("ADODB.Recordset")
sqlQuery = "SELECT COUNT(*) as myrecordcount FROM myView;"
rs.Open sqlQuery, conn, 1, 2
response.write "q2 cnt = " & rs("myrecordcount")
| {
"pile_set_name": "StackExchange"
} |
Q:
How can we not say an after bracha on Kiddush wine during the seder
The Shulchan Aruch (OC 473:2) rules that after the first cup at the seder, one doesn't make an after bracha. The Mishnah Berurah (s.k. 11) explains that we rely on benching after the meal to cover it, or the bracha achronah after the last cup.
I've heard that the poskim ask how can we rely on this, when (usually speaking) Maggid can take over an hour to complete, usually meaning that the shiur ikkul has passed (a person is as thirsty now as they were before they drank), making them lose their after bracha.
What are the answers to this question? I'm looking for as many as possible.
A:
I've heard two. Rav Yitzchak Berkowitz brings that Rav Shlomo Zalman Aueurbach would drink liquids throughout the Haggadah (not being concerned with the opinion of the Ramban that forbids drinking during the Haggadah) so that he never became thirsty to avoid this issue. Rav Shternbuch (Teshuvos VeHanhagos 1:305) answers with a big innovation: the shiur ikkul is only when eating/drinking for pleasure, not for a mitzvah.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is "side of the hill" the same as "shoulder of the hill"?
From The Hobbit,
The tunnel wound on and on, going fairly but not quite straight into the side of the hill—The Hill, as all the people for many miles round called it—and many little round doors opened out of it, first on one side and then on another.
As I understand, we can refer to any part of a hill below the top but above the foot of the hill as side of the hill. Another word for this is hillside.
I just started reading a translated version of The Hobbit, the one I got several years ago (around the time the LOTR Trilogy was still in theaters), and to my dismay, one of every two or three sentences was mistranslated one way or another in my opinion. But that is not my question here.
My question is about the term shoulder of the hill.
Tolkien's the side of the hill was translated into the shoulder of the hill. Considering other difficulties that arose because the translator's choice (she chose the word "เนินเขา" in Thai for hill--meaning small mountain, but could also mean hillside too), I think it is fair in this case to translate side of the hill as shoulder of the hill. But I still think that side of the hill and shoulder of the hill are not quite the same thing anyway.
But maybe I might be wrong. Maybe, to native speakers, "side of the hill" refers to exactly the same part or the same area of a hill as "shoulder of the hill". I am interested in the meaning and usage of both terms in English. (Please do not mind about the translation, I provide it as background information of my curiosity only.)
Do they refer to the same area? Or do they have subtle differences in meaning?
A:
NOAD lists three definitions for shoulder (I've omitted Definition #1, as that is the classic anatomical shoulder):
2 a part of something resembling a shoulder in shape, position, or function : the shoulder of a pulley.
• a point at which a steep slope descends from a plateau or highland area : the shoulder of the hill sloped down.
3 a paved strip alongside a road for stopping on in an emergency.
With those definitions in mind (particularly the subdefinition under Def. 2), it seems like shoulder tells a bit more about the hill than side might; specifically, it implies the top of the hill is relatively flat, with a relatively steep slope downward from the top. Depending on their shapes, some hills might not have shoulders.
In regards to the sentence, I think the shoulder of the hill is a more precise area than the side of the hill. Looking at the image below, I there are several hobbit holes in the side of the hill, but only the ones boxed in orange are ones that I would place on the shoulder of the hill, that is, in the area where the slope descends downward from the highland area:
Unless Mr. Baggins lived in one of the lower holes, I wouldn't really call this a "mistranslation" – just a word that is perhaps more detailed than it needs to be.
| {
"pile_set_name": "StackExchange"
} |
Q:
Speeding SQL queries for a large(?) WordPress database?
I am using a WordPress plugin called feedwordpress in order to run a planet like website (it takes content from other websites, with their permission) on WordPress (See it here).
The plugin is great except for one thing - it hogs down my (VPS) server into submission once every week or so.
In a recent e-mail exchange with the webadmin he wrote the following:
It does look like the increased mysql
resource usage is being caused by slow
queries being run by r-bloggers.com.
Here is a copy of some of the logs
that are being produced. You would
need to optimize this site and
database further to have it running as
efficiently as possible. If these
changes have already been made, your
best option would be to look into a
large upgrade for your VPS due to the
high level or resources and traffic
that your site needs and sees.
Here are the logs:
# Time: 110614 16:11:35
# User@Host: rblogger_rblogr[rblogger_rblogr] @ localhost []
# Query_time: 104 Lock_time: 0 Rows_sent: 0 Rows_examined: 54616
SELECT SQL_CALC_FOUND_ROWS wp_rb_posts.*
FROM wp_rb_posts
WHERE 1=1 AND (
(guid = '235cbefa4424d0cdb7b6213f15a95ded') OR
(guid = 'http://www.r-bloggers.com/?guid=235cbefa4424d0cdb7b6213f15a95ded') OR
(guid = 'http://www.r-bloggers.com/?guid=235cbefa4424d0cdb7b6213f15a95ded') OR
(MD5(guid) = '235cbefa4424d0cdb7b6213f15a95ded') ) AND
wp_rb_posts.post_type IN
('post', 'page', 'attachment', 'revision', 'nav_menu_item') AND
(wp_rb_posts.post_status = 'publish' OR
wp_rb_posts.post_status = 'future' OR
wp_rb_posts.post_status = 'draft' OR
wp_rb_posts.post_status = 'pending' OR
wp_rb_posts.post_status = 'trash' OR
wp_rb_posts.post_status = 'auto-draft' OR
wp_rb_posts.post_status = 'inherit' OR
wp_rb_posts.post_status = 'private'
)
ORDER BY wp_rb_posts.post_date DESC LIMIT 1570, 10;
# User@Host: rblogger_rblogr[rblogger_rblogr] @ localhost []
# Query_time: 237 Lock_time: 0 Rows_sent: 0 Rows_examined: 54616
SELECT SQL_CALC_FOUND_ROWS wp_rb_posts.* FROM wp_rb_posts WHERE 1=1 AND ((guid = '235cbefa4424d0cdb7b6213f15a95ded') OR (guid = 'http://www.r-bloggers.com/?guid=235cbefa4424d0cdb7b6213f15a95ded') OR (guid = 'http://www.r-bloggers.com/?guid=235cbefa4424d0cdb7b6213f15a95ded') OR (MD5(guid) = '235cbefa4424d0cdb7b6213f15a95ded')) AND wp_rb_posts.post_type IN ('post', 'page', 'attachment', 'revision', 'nav_menu_item') AND (wp_rb_posts.post_status = 'publish' OR wp_rb_posts.post_status = 'future' OR wp_rb_posts.post_status = 'draft' OR wp_rb_posts.post_status = 'pending' OR wp_rb_posts.post_status = 'trash' OR wp_rb_posts.post_status = 'auto-draft' OR wp_rb_posts.post_status = 'inherit' OR wp_rb_posts.post_status = 'private') ORDER BY wp_rb_posts.post_date DESC LIMIT 570, 10;
# Time: 110614 16:18:13
# User@Host: rblogger_rblogr[rblogger_rblogr] @ localhost []
# Query_time: 257 Lock_time: 0 Rows_sent: 0 Rows_examined: 54616
SELECT SQL_CALC_FOUND_ROWS wp_rb_posts.* FROM wp_rb_posts WHERE 1=1 AND ((guid = '956e208f101562f6654e88e9711276e4') OR (guid = 'http://www.r-bloggers.com/?guid=956e208f101562f6654e88e9711276e4') OR (guid = 'http://www.r-bloggers.com/?guid=956e208f101562f6654e88e9711276e4') OR (MD5(guid) = '956e208f101562f6654e88e9711276e4')) AND wp_rb_posts.post_type IN ('post', 'page', 'attachment', 'revision', 'nav_menu_item') AND (wp_rb_posts.post_status = 'publish' OR wp_rb_posts.post_status = 'future' OR wp_rb_posts.post_status = 'draft' OR wp_rb_posts.post_status = 'pending' OR wp_rb_posts.post_status = 'trash' OR wp_rb_posts.post_status = 'auto-draft' OR wp_rb_posts.post_status = 'inherit' OR wp_rb_posts.post_status = 'private') ORDER BY wp_rb_posts.post_date DESC LIMIT 570, 10;
# Time: 110614 16:19:02
# User@Host: rblogger_rblogr[rblogger_rblogr] @ localhost []
# Query_time: 83 Lock_time: 0 Rows_sent: 0 Rows_examined: 54616
SELECT SQL_CALC_FOUND_ROWS wp_rb_posts.* FROM wp_rb_posts WHERE 1=1 AND ((guid = '6c589e661f03a67b0529fab2f080bfd3') OR (guid = 'http://www.r-bloggers.com/?guid=6c589e661f03a67b0529fab2f080bfd3') OR (guid = 'http://www.r-bloggers.com/?guid=6c589e661f03a67b0529fab2f080bfd3') OR (MD5(guid) = '6c589e661f03a67b0529fab2f080bfd3')) AND wp_rb_posts.post_type IN ('post', 'page', 'attachment', 'revision', 'nav_menu_item') AND (wp_rb_posts.post_status = 'publish' OR wp_rb_posts.post_status = 'future' OR wp_rb_posts.post_status = 'draft' OR wp_rb_posts.post_status = 'pending' OR wp_rb_posts.post_status = 'trash' OR wp_rb_posts.post_status = 'auto-draft' OR wp_rb_posts.post_status = 'inherit' OR wp_rb_posts.post_status = 'private') ORDER BY wp_rb_posts.post_date DESC LIMIT 1440, 10;
Which leads me to my question - what in this logs might indicate to me what is happening (why should such queries take so long?)? is it possible to optimize these? If so, how?
Thanks,
Tal
A:
The first thing I see is the MD5(guid) = '235cbefa4424d0cdb7b6213f15a95ded' in the WHERE clause. That might trigger a bypass of the MySQL Query Optimizer and issue a full table scan to accomplish locating the row.
Also, try to find out if the guid column is indexed in the wp_rb_posts table.
Also, what jumps out at me when I see 'WordPress' is this question: Is all your data MyISAM or InnoDB ??? If all your data is MyISAM (in this case, the wp_rb_posts table), ALWAYS expect full table locks upon each INSERT, UPDATE, or DELETE on a MyISAM table. You may want to consider converting all your WordPress data into InnoDB. This will alleviate table locking.
The reason I switched gears into converting MyISAM to InnoDB ? When there are a lot of INSERTs, UPDATES, or DELETEs against wp_rb_posts (if it currently MyISAM), each will create a full table lock on a first-come, first-server basis. Any SELECT query, regardless of being a good or bad performing query, simply waits its turn until all queries accessing wp_rb_posts see the wp_rb_posts table unlock and access is granted.
While such SELECT queries wait, you may realize that the running time is climbing, not because the query is necessarily bad, but because it spent most of its lifetime waiting. Thus, the running time of the query may be deceptive because of external factors such as number of DB Connections running the same query, number of DB connections running different queries involving wp_rb_posts, overall server load, and so forth. Also worth noting is the number of rows in wp_rb_posts. You need to find out if the running time of this query is bad in a standalone test environment.
On the other hand, if wp_rb_posts is already InnoDB, now you can explore the query's EXPLAIN plan and look for indexes being selected or ignored.
Here is how you can convert all MyISAM tables to InnoDB
As a MySQL DBA, I trust MySQL to do the conversion by having MySQL write the script for me.
Form the Linux command run this query
mysql -h... -u... -p... -A --skip-column-names -e"SELECT db,tb FROM (SELECT A.db,A.tb,A.tbsize FROM (SELECT table_schema db,table_name tb,(data_length+index_length) tbsize FROM information_schema.tables WHERE engine='MyISAM' AND table_schema NOT IN ('information_schema','mysql')) A LEFT JOIN (SELECT table_schema db,table_name tb FROM information_schema.statistics WHERE index_type='FULLTEXT') B USING (db,tb) WHERE B.db IS NULL) AA ORDER BY tbsize" > /root/ConvertMyISAM2InnoDB.sql
The script will convert the smallest tables first. This script was also bypass any MyISAM tables that have FULLTEXT indexes.
Ater looking over the script, you can simply run it in MySQL as follows:
mysql -h... -u... -p... -A < /root/ConvertMyISAM2InnoDB.sql
or if you want to see the timing of each conversion, login to mysql and run this:
mysql> source /root/ConvertMyISAM2InnoDB.sql
This should not get messed up because a full table lock happens when the conversion is being executed.
Once all tables are converted you need to tune the MySQL settings for InnoDB usage and scale down the key_buffer.
Please read this for setting the InnoDB Buffer Pool : What are the main differences between InnoDB and MyISAM?
Give it a Try !!!
| {
"pile_set_name": "StackExchange"
} |
Q:
Generate random variable between 1 and 100 according to specific distribution using Node.js
Using Node.js we are trying to come up with a way of generating a random number that falls between 1 and 100. However instead of using a standard linear distribution like the typical RAND() function might we want to instead use a Weibull (or some such) distribution that will give a long tail and weigh the answers more heavily toward the larger values - for example a value of 75 to 100 might be generated 80% of the time, a value of 50 to 74 would be generated 15% of the time, and the remainder (< 20) generated 5% of the time.
We have found a Weibul random variable function using the following formula
alpha*(-ln(1-X))^(1/beta). Assuming X is a standard linear random from 0 to 1, using alpha = 1, and a beta <= 1 seems to give us a good distribution, however we are stumped as to how to generate a single value that will always fall between 1 and 100.
Any ideas or recommendations are appreciated.
A:
Ok - just in case anyone is interested in my version of an answer. Using the following reference got me to my goal of constraining the Weibull result set:
https://stats.stackexchange.com/questions/30303/how-to-simulate-data-that-satisfy-specific-constraints-such-as-having-specific-m
The following links were also handy:
http://en.wikipedia.org/wiki/Weibull_distribution
http://mathworld.wolfram.com/WeibullDistribution.html
In the end my roughed in node,js code looks like this:
var desiredMin = 1; //the desired minimum random result
var desiredMax = 50; //the desired maximum random result
var scale = 1; //Weibul scale parameter (1 provides an inverse result set)
var shape = 10; //Weibul shape parameter (how skewed the result set is)
//given an possible random range of {0,1} value calculate the minimum and maximum Weibull distribution values given current shape and scale parameters
var weibullMin = Math.pow((shape*scale), (-1*shape)) * Math.pow(.000001, shape -1) * Math.exp(Math.pow((.000001/scale), shape));
var weibullMax = Math.pow((shape*scale), (-1*shape)) * Math.pow(.999999, shape -1) * Math.exp(Math.pow((.999999/scale), shape));
//simulate 1000 random weibull values and write results to file
fileStream.once('open', function(fd) {
for(var i = 1; i <= 1000; i++) {
var r = Math.random();
var weibullRandom = Math.pow((shape*scale), (-1*shape)) * Math.pow(r, shape-1) * Math.exp(Math.pow((r/scale), shape)); //generate Weibull random value
var weibullRandomAdjusted = desiredMin + (desiredMax - desiredMin)*((weibullRandom-weibullMin) / (weibullMax - weibullMin)); //adjust Weibull random value so that it constrained into the desired min/max range
fileStream.write(weibullRandomAdjusted + "\n");
};
fileStream.end();
});
I've run the code for varying 'shape' values and it is providing me exactly the results I need.
| {
"pile_set_name": "StackExchange"
} |
Q:
Force failover a Cisco ASA
I have two ASA in a lan state primary\secondary configuration. None of them have "failover active" or "no failover active" in their configuration. Would it be proper to failover in a manner such as:
Log into console of primary unit and issue "failover lan state secondary", log into the console of the original secondary unit and issue "failover lan state primary". To fail back simply reverse the process
or
Log into the console of the primary unit and issue "no failover active", log into the console of the original secondary unit and issue "failover active". To fail back issue "failover active" on the original primary (now secondary) unit, and "no failover active" on the now primary unit.
I do not like the second method because it adds configuration directives that were not in place before. Will the first method work?
A:
Your first option wont work because the command failover lan state primary/secondary is used only to designate which ASA will be the primary/secondary in the event that they both boot at the same time. Your second option will work though, all you should need to do it log onto the secondary device and issue:
failover active
and you should failover.
When your maintenance is complete run the same command on the other (now primary) unit and it should fail back. Hope this helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
Probability theory - request for proof-verification f(further properties of characterisitc functions)
By the courtesy of the user @uniquesolution, I presumably managed to understand proof related to certain further property of characteristic function. I completed too big for me shortcuts in reasoning. However, I am not confident whether current form of proof with my edition is correct.
There is the following lemma and its proof of some interesting lemma for me regarding further propeties of characteristic functions in probability theory.
Lemma: Let $X$ be a random variable. Assume: $\exists$ $a\in\mathbb{R}$: $P(X=a)>\frac{1}{2}$. Prove that characteristic function of $X$ cannot take the value of 0.
Proof: Let $\gamma$ - characteristic function of $X$.
If: $a=0$: Since $\exists p \in (\frac{1}{2},1]$: $P(X=0)=p$, then there exists a probabilistic measure $\mu$ such that $P_{X}=p\delta_{0}+(1-p)\mu$. Hence: $(1-p)\mu = P_{X}-p\delta_{0}$ $\implies$ $\sum(1-p)e^{itx}\mu=\sum e^{itx}P_{X} - \sum e^{itx}p\delta_{0}$ $\implies$ $(1-p)\sum e^{itx}\mu = \gamma(t)-p$ $\implies$ $(1-p)\hat{\mu}(t)=\gamma(t)-p$ $\implies$ $|\gamma(t)-p|=(1-p)|\hat{\mu}(t)|\leq(1-p)\times 1 =1-p$ $\implies$ $-(1-p)\leq \gamma(t)-p \leq 1-p $. Therefore: the smallest distance of $\gamma$ to $X$-axis is equal to $p-(1-p)=2p-1>0$.
If $a \in \mathbb{R}\setminus
\{0\}$, then analogically to the case of $a=0$ : $|\gamma(t)-pe^{ita}|=|\gamma(t)e^{-ita}-p|\leq 1-p$. This implies that we do not have a change of distance of $\gamma$ with respect to $X$-axis. This implies that in the case of $a=0$ $\gamma$ is not uniformly continous, which must be satisfied by every characteristic function $\blacksquare$
Problem: I read this proof 9 times. Current version of the proof contains bridges of potential too big shortcuts in reasoning. However, I am not sure whether now I am completely correct.
I would be extremely thankful for feedback!
A:
$\hat{\mu}$ stands for the Fourier transform of $\mu$. In order to understand the solution the problem, you should know that the characteristic function of a random variable is the Fourier transform of its probability density function.
| {
"pile_set_name": "StackExchange"
} |
Q:
Angularjs unit test resolve promise inside custom directive with external template
I have a custom directive that uses an external template and is passed data from a service. I decided to ensure that the promise was resolved before modifying the data, which was fine in the actual code but broke my unit tests, which is annoying. I have tried a number of variations but am now stuck. I am using 'ng-html2js' preprocessor.
Here is the unit test
describe('ccAccordion', function () {
var elm, scope, deferred, promise, things;
beforeEach(module('ccAccordion'));
// load the templates
beforeEach(module('components/accordion/accordion.html'));
beforeEach(inject(function ($rootScope, $compile, $q) {
elm = angular.element(
'<cc-accordion items="genres"></cc-accordion>'
);
scope = $rootScope;
things = [{
title: 'Scifi',
description: 'Scifi description'
}, {
title: 'Comedy',
description: 'Comedy description'
}];
deferred = $q.defer();
promise = deferred.promise;
promise.then(function (things) {
scope.items = things;
});
// Simulate resolving of promise
deferred.resolve(things);
// Propagate promise resolution to 'then' functions using $apply().
scope.$apply();
// compile the template?
$compile(elm)(scope);
scope.$digest();
}));
it('should create clickable titles', function () {
var titles = elm.find('.cc-accord h2');
expect(titles.length).toBe(2);
expect(titles.eq(0).text().trim()).toBe('Scifi');
expect(titles.eq(1).text().trim()).toBe('Comedy');
});
I have left out the custom addMatchers and the rest of the tests. The error I get is
TypeError: 'undefined' is not an object (evaluating 'scope.items.$promise')
Here is the directive
var ccAccordion = angular.module("ccAccordion", []);
ccAccordion.directive("ccAccordion", function () {
return {
restrict: "AE",
templateUrl: "components/accordion/accordion.html",
scope: {
items: "="
},
link: function (scope) {
scope.items.$promise.then(function (items) {
angular.forEach(scope.items, function (item) {
item.selected = false;
});
items[0].selected = true;
});
scope.select = function (desiredItem) {
(desiredItem.selected === true) ? desiredItem.selected = false : desiredItem.selected = true;
angular.forEach(scope.items, function (item) {
if (item !== desiredItem) {
item.selected = false;
}
});
};
}
};
});
This is where the directive is used in main.html
<cc-accordion items="genres"></cc-accordion>
In the main controller the genres service is passed in ie
angular.module('magicApp')
.controller('GenresCtrl', ['$scope', 'BREAKPOINTS', 'Genre',
function ($scope, BREAKPOINTS, Genre) {
$scope.bp = BREAKPOINTS;
$scope.genres = Genre.query();
}]);
A:
Okay, I would move that code you put in link into the controller. The data processing should probably happen in a service. I know you've been told big controllers are bad, but big linking functions are generally worse, and should never do that kind of data processing.
.controller('GenresCtrl', ['$scope', 'BREAKPOINTS', 'Genre',
function ($scope, BREAKPOINTS, Genre) {
$scope.bp = BREAKPOINTS;
$scope.genres = Genre.query().then(function (items) {
angular.forEach(scope.items, function (item) {
item.selected = false;
});
items[0].selected = true;
});
scope.select = function (desiredItem) {
(desiredItem.selected === true) ? desiredItem.selected = false : desiredItem.selected = true;
angular.forEach(scope.items, function (item) {
if (item !== desiredItem) {
item.selected = false;
}
});
};
});
Your link function is now empty. Define items on the rootScope instead, this ensures that the isolateScope and your directive interface are working correctly.
beforeEach(inject(function ($rootScope, $compile, $q) {
elm = angular.element(
'<cc-accordion items="genres"></cc-accordion>'
);
scope = $rootScope;
things = [{
title: 'Scifi',
description: 'Scifi description'
}, {
title: 'Comedy',
description: 'Comedy description'
}];
scope.items = things; // Tests your directive interface
// compile the template?
$compile(elm)(scope);
scope.$digest();
}));
The behavior of the promise should be tested in a controller test, by mocking the return value of the service. Your problem with the $promise test has been solved.
The actual issue was that you were assuming that $q.defer() gave you the same kind of promise as the angular $http, but that is solved by design instead.
| {
"pile_set_name": "StackExchange"
} |
Q:
(Android Studio 3.2 Beta) - Navigation Architecture Component Configuration
I want to try out the new Navigation Architecture Component feature, so I followed this Tutorial: https://www.youtube.com/watch?v=GOpeBbfyb6s.
I am using Android Studio 3.2 Beta 1. I installed the necessary dependencies, but when I try to create the Navigation Android Resource File in the project just like in the video above, the Navigation option does not appear in the selection menu.
My Issue:
There is no Navigation option to select while trying to create the Navigation Android Resource File. Am I missing any steps in the installation?
Expected Result:
My Situation:
My build.gradle
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
// Navigation Architecture Component Configuration install HERE!!
def nav_version = "1.0.0-alpha02"
implementation "android.arch.navigation:navigation-fragment-ktx:$nav_version" // use -ktx for Kotlin
implementation "android.arch.navigation:navigation-ui-ktx:$nav_version" // use -ktx for Kotlin
}
A:
Per this currently open issue:
As per the Help > What's New in Android Studio screen that popped up when you upgraded:
"The Navigation Editor is an experimental feature, so you must first enable it by opening the IDE 'Settings/Preferences' dialog, selecting 'Experiemental' in the left pane, and checking the box next to the 'Enable Navigation Editor'."
We'll update the Navigation documentation to specifically call this out. It will also be enabled by default on future canary builds (of Android Studio 3.3) when available.
So you need to manually enable the Navigation Editor on Beta builds of Android Studio 3.2
| {
"pile_set_name": "StackExchange"
} |
Q:
Htaccess rewrite rules?
so my url is currently:
http://www.mywebsite.com/search.php?keyword=stack+overflow
I'm wanting to have it accessible as:
http://www.mywebsite.com/?s=stack+overflow
Now I've also implemented rewrites for .php files as below
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php
I'm a little confused now because the search.php is being rewritten to just search but is still accessable with search.php, so when I create my rewrite rule do I rewrite search.php or just search?.. either way I've tried and failed to accomplish it lol.
What should I add to have my desired url? Help is much appreciated :)
A:
It's impossible to change parameter name with mod_rewrite. The easiest way to achieve what you want is to add these lines to .htaccess:
RewriteCond %{QUERY_STRING} ^s=
RewriteRule .? search.php [L]
and modify search.php to react to s get parameter the same as it reacts to keyword.
An alternative is to keep .htaccess intact and add these at the top of index.php:
if (!empty($_GET['s'])) {
$_GET['keyword'] = $_GET['s'];
require __DIR__ . '/search.php';
exit;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
JavaFX bulk edit images
I'm trying to edit five images I have in a folder at once (using javafx motion blur), rather than select them one after the other. This is my code, I'm not exactly sure what I'm doing wrong but when I run it, only the last image in the folder gets edited. The others remain as they are.
public class IterateThrough extends Application {
private Desktop desktop = Desktop.getDesktop();
@Override
public void start(Stage primaryStage) throws IOException {
File dir = new File("filepath");
File [] directoryListing = dir.listFiles();
if (directoryListing != null) {
for (File file : directoryListing) {
if(file.getName().toLowerCase().endsWith(".jpeg")){
//desktop.open(file);
Image image = new Image(new FileInputStream(file));
//Setting the image view
ImageView imageView = new ImageView(image);
//setting the fit height and width of the image view
imageView.setFitHeight(600);
imageView.setFitWidth(500);
//Setting the preserve ratio of the image view
imageView.setPreserveRatio(true);
// instantiate Motion Blur class
MotionBlur motionBlur = new MotionBlur();
// set blur radius and blur angle
motionBlur.setRadius(15.0);
motionBlur.setAngle(110.0);
//set imageView effect
imageView.setEffect(motionBlur);
//Creating a Group object
Group root = new Group(imageView);
//Creating a scene object
Scene scene = new Scene(root, 600, 500);
//Setting title to the Stage
primaryStage.setTitle("Loading an image");
//Adding scene to the stage
primaryStage.setScene(scene);
//Displaying the contents of the stage
primaryStage.show();
}
}
}
}
public static void main(String[] args) {
launch(args);
}
}
A:
first, you shouldn't just let the primaryStage show() in the for-each loop, because when the primaryStage first show(), the fx thread pause on that instruction, the remaining pictures will not be read and when you close the window, the loop won't continue to go on for remaining, it represents the end of the application.
so it's better to let the primaryStage show() outside the each-loop after all image has been read.
second, you shouldn't use the "Group" container to contains all images, better use VBox/HBox/FlowPane, make sure above image won't covers below's.
here's modified code for reference.
public class IterateThrough2 extends Application{
private Desktop desktop = Desktop.getDesktop();
@Override
public void start(Stage primaryStage) throws IOException{
File dir = new File("filepath");
File[] directoryListing = dir.listFiles();
FlowPane root = new FlowPane();
if(directoryListing != null){
for(File file : directoryListing){
if(file.getName().toLowerCase().endsWith(".jpeg")){
Image image = new Image(new FileInputStream(file));
ImageView imageView = new ImageView(image);
imageView.setFitHeight(600);
imageView.setFitWidth(500);
imageView.setPreserveRatio(true);
MotionBlur motionBlur = new MotionBlur();
motionBlur.setRadius(15.0);
motionBlur.setAngle(110.0);
imageView.setEffect(motionBlur);
root.getChildren().add(imageView);
}
}
}
Scene scene = new Scene(root, 600, 500);
primaryStage.setTitle("Loading an image");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args){
launch(args);
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Django redirect to a view with GET arguments set
I'm having a hard time understanding the Django System of views and templates. All I want to do is inform the user of the status of his request- he pushes a button and gets an infobox with a message. The button in the Dashboard is at the root of the URL and sends a POST request to the Django Web App at book/.
In the view bound to this URL, I check if the booking is valid and want to inform the user (without the use of javascript) about the result. I wanted to send back a HTTP redirect to /?response=success or /?response=failed.
I've tried to give the view of the dashboard arguments and changed the URL regex but this did not lead where I want it to go. Currently, it's just
return redirect('dashboard')
and the URL conf is:
...
url(r'^$', app.views.dashboard, name='dashboard'),
url(r'^book/$', app.views.book, name='book'),
...
I really like Django - it's really easy to use. But in simple cases like this, it just drives me crazy. I would appreciate any kind of help.
Kind regards
Eric
A:
You could just use the messages framework - that's what it's for.
Oh and yes: if that's just for displaying informations (no side effect on the server), you should use a GET request - POST is for submitting data for processing by the server.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I redirect a copy of all output of a shell script?
I want to redirect a copy of all output of a shell script, there's some mount command and some echo in the script.
If I use >> 2>&1, I can't see the output from the command line.
If I use | tee -a the_log_file 2>&1, I can get all output in command line, but in the_log_file, there's no mount error output such as mount.nfs: /mnt/folder is busy or already mounted which I also want in the_log_file
How can I fix this?
A:
You need to use
command 2>&1 | tee -a the_log_file
instead of
command | tee -a the_log_file 2>&1
(If you ask me, it's pretty unintuitive that you need to not put the 2>&1 in an unintuitive place in the pipe case! ;) )
For the details, take a look at the Illustrated Redirection Tutorial in Bash Hackers Wiki. The illustration in section Duplicating File Descriptor 2>&1 shows our case:
ls /tmp/ doesnotexist 2>&1 | less
--- +--------------+ --- +--------------+
( 0 ) ---->| /dev/pts/5 | ------> ( 0 ) ---->|from the pipe |
--- +--------------+ / ---> --- +--------------+
/ /
--- +--------------+ / / --- +--------------+
( 1 ) ---->| to the pipe | / / ( 1 ) ---->| /dev/pts |
--- +--------------+ / --- +--------------+
/
--- +--------------+ / --- +--------------+
( 2 ) ---->| to the pipe | / ( 2 ) ---->| /dev/pts/ |
--- +--------------+ --- +--------------+
| {
"pile_set_name": "StackExchange"
} |
Q:
Are multiple versions of the same question constructive?
Closely related:
How close can two questions be without being duplicates?
Can simply adding “ACCORDING TO X” salvage any question?
This is something I worried about way back when we started requiring questions to be scoped to a denomination. Don't get me wrong, I agree with the fact that questions need to be properly scoped if they're to be answerable with anything other than opinion. However, I saw the potential for a user to abuse the system and essentially flood the system with the same exact question over and over, from different perspectives.
From a Baptist perspective, is baptism necessary for salvation?
from a Catholic perspective, is baptism necessary for salvation?
etc...
Now it seems to be happening, and it's time to ask the community:
Is this pattern desirable, and if not, what course of action should be taken?
A:
I prefer this sort of multiple questions over the alternative of overview questions. Defining an "overview question" is exceedingly difficult, as there is often not a defined border between "overview question" and "what is everyone's opinion on X?"
Having said that, every 'Explain X according to Y tradition?' question still needs to be held to high standards. Simply doing a search-and-replace to change "Catholics" to "Baptists" is not enough. A question like this ought to be closed for lack of research effort.
An honest seeker of truth on matters of Baptism will spend at least 5 minutes on Google before asking what Baptists believe about baptism. They should spend another 5 minutes before asking what Catholics believe, etc.
If askers will actually do this level of minimal research, it should be apparent in their question, and their questions won't be search-and-replace duplicates.
A:
It really depends on what the issue is. For an issue like baptism it is well known that Catholics, Reformed Protestants and Baptists have very different beliefs. I don't know the Orthodox churches well enough to know if they are essentially the same as the Catholics or if they're different again, but they're probably different. And of course the non-Trinitarian churches will probably have very different answers on almost everything. For an issue like baptism it is appropriate to have many different questions, or alternatively, an overview question. But when you're getting to the stage of having to cover four or five different positions it might be too broad for a good overview question...
Other issues are more uniform. We don't need different distinct Catholic and Anglican and Baptist questions about the Trinity.
Finally it's okay to not know whether the question you're asking will have an ecumenical answer or not. It's okay to ask whether Trinitarian Christians teach that baptism is essential, it will just be quickly closed as too broad.
| {
"pile_set_name": "StackExchange"
} |
Q:
assign to another object with retain and autorelease
I have the following code, expecting that once obj2 is released obj1 is still retained, will it work?
obj1 = [[Class1 alloc] init];
obj2 = [[obj1 retain] autorelease];
A:
I have the following code, expecting that once obj2 is released obj1 is still retained, will it work?
obj1 and obj2 are both pointers to the same object. That object gets a retain count of 1 when you create it. The object's retain count increases to 2 when you retain it again on the second line. The object (and any pointers to it) will therefore remain valid until it's released twice. One of those releases will eventually come from the autorelease on the second line; another should be supplied by your code somewhere.
| {
"pile_set_name": "StackExchange"
} |
Q:
Angular http.post nested json
I'm working with Angular5 and Symfony 3.4 with FOSUserBundle.
I have something like :
register(username: string, email: string, first: string, second: string)
{
return this.appHttp.post('register', {username, email, first, second}).subscribe(
data => {
this.appHttp.logRequest(data);
}
);
}
And what i need to send to API is a formated json like :
{
"email": "[email protected]",
"username" : "userTest",
"plainPassword" : {
"first" : "123",
"second": "123"
}
}
Currently, my json looks like :
{
"email": "[email protected]",
"username" : "userTest",
"first": "123",
"second": "123",
}
How can i post the required json ?
Thanks!
A:
Just Change :
{username, email, first, second}
To
{username, email, plainPassword : {first, second} }
| {
"pile_set_name": "StackExchange"
} |
Q:
Remove file extensions from my Php files
How can I remove .php extension from php files
htacess file
RewriteEngine On
RewriteCond
%{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php [NC,L]
any help is much appriciated, Thanks
A:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/?$ $1.php [NC,L]
If you go to example.com/test/ it will load example.com/test.php
| {
"pile_set_name": "StackExchange"
} |
Q:
Reference type in an array
Look at the following code snippet
// Prepare some data to insert into the template.
type Recipient struct {
Name, Gift string
Attended bool
}
var recipients = []Recipient{
{"Aunt Mildred", "bone china tea set", true},
{"Uncle John", "moleskin pants", false},
{"Cousin Rodney", "", false},
}
I create a struct with some properties. After create a slice with Recipient type. Does slice recipients keeps value or reference type inside?
It seems to be value type.
A:
A slice is in fact a (kind of) pointer to a portion of an array (see slice usage and internals), so as for arrays, items are values of the specified type.
| {
"pile_set_name": "StackExchange"
} |
Q:
Making Storyboards into resources that can be used by multiple controls in WPF
I have a working animation, now I am placing it in Apps.xaml under application.Resources, with all necessary bindings but it doesn't work. Am I missing something in the binding process? What is the proper way to bind the Storyboard.Targetname?
<Storyboard x:Key="RotateIn">
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)" Storyboard.TargetName="button2">
<EasingDoubleKeyFrame KeyTime="0" Value="-100"/>
<EasingDoubleKeyFrame KeyTime="0:0:0.5" Value="0"/>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)" Storyboard.TargetName="button2">
<EasingDoubleKeyFrame KeyTime="0" Value="50"/>
<EasingDoubleKeyFrame KeyTime="0:0:0.5" Value="0"/>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="Opacity" Storyboard.TargetName="button2">
<EasingDoubleKeyFrame KeyTime="0" Value="0"/>
<EasingDoubleKeyFrame KeyTime="0:0:0.8" Value="1"/>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimation Storyboard.TargetName="AnimatedRotateTransform"
Storyboard.TargetProperty="Angle"
By="10"
To="360"
Duration="0:0:0.7"
FillBehavior="Stop" />
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)" Storyboard.TargetName="textBlock">
<EasingDoubleKeyFrame KeyTime="0" Value="90"/>
<EasingDoubleKeyFrame KeyTime="0:0:0.7" Value="0"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
<Button Grid.Column="1" Name="btn2" Width="150" Height="150" Background="gray">
<StackPanel >
<Image Source="{StaticResource img2}" x:Name="button2" RenderTransformOrigin=".5,.5">
<Image.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform Angle="0" x:Name="AnimatedRotateTransform"/>
<TranslateTransform/>
</TransformGroup>
</Image.RenderTransform>
</Image>
<TextBlock x:Name="textBlock" HorizontalAlignment="Center" RenderTransformOrigin="0.5,0.5">
<TextBlock.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform/>
<TranslateTransform/>
</TransformGroup>
</TextBlock.RenderTransform>Rotate In</TextBlock>
</StackPanel>
</Button>
Above is my working animation created for a single Control. However, when I tried to make it into a resource where it can be reused like
here , (H.B.)'s answer :
<Application.Resources>
<ResourceDictionary>
<Storyboard x:Key="BindingRotate" x:Shared="False">
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)" Storyboard.TargetName="{DynamicResource AnimationTarget}">
<EasingDoubleKeyFrame KeyTime="0" Value="-100"/>
<EasingDoubleKeyFrame KeyTime="0:0:0.5" Value="0"/>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)" Storyboard.TargetName="{DynamicResource AnimationTarget}">
<EasingDoubleKeyFrame KeyTime="0" Value="50"/>
<EasingDoubleKeyFrame KeyTime="0:0:0.5" Value="0"/>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="Opacity" Storyboard.TargetName="{DynamicResource AnimationTarget}">
<EasingDoubleKeyFrame KeyTime="0" Value="0"/>
<EasingDoubleKeyFrame KeyTime="0:0:0.8" Value="1"/>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimation Storyboard.TargetName="{DynamicResource AnimationTarget1}"
Storyboard.TargetProperty="Angle"
By="10"
To="360"
Duration="0:0:0.7"
FillBehavior="Stop" />
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)" Storyboard.TargetName="{DynamicResource AnimationTarget2}">
<EasingDoubleKeyFrame KeyTime="0" Value="90"/>
<EasingDoubleKeyFrame KeyTime="0:0:0.7" Value="0"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</ResourceDictionary>
</Application.Resources>
<Button Grid.Column="1" Name="btn2" Width="150" Height="150" Background="gray">
<StackPanel >
<Image Source="{StaticResource img2}" x:Name="button2" RenderTransformOrigin=".5,.5">
<Image.Resources>
<sys:String x:Key="AnimationTarget">button</sys:String>
</Image.Resources>
<Image.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform Angle="0" x:Name="AnimationTarget1">
</RotateTransform>
<TranslateTransform/>
</TransformGroup>
</Image.RenderTransform>
</Image>
<TextBlock x:Name="textBlock" HorizontalAlignment="Center" RenderTransformOrigin="0.5,0.5" Text="Rotate In">
<TextBlock HorizontalAlignment="Center" Text="Expand In">
<TextBlock.Resources>
<sys:String x:Key="AnimationTarget2">button</sys:String>
</TextBlock.Resources>
</TextBlock>
</TextBlock>
</StackPanel>
<Button.Triggers>
<EventTrigger RoutedEvent="ButtonBase.MouseEnter">
<BeginStoryboard Storyboard="{StaticResource BindingRotate}"/>
</EventTrigger>
</Button.Triggers>
</Button>
''[Unknown]' property does not point to a DependencyObject in path '(0).(1)[3].(2)'.'
Exception is all I get. I followed exactly what was stated in the answer. Please let me know what is missing in my binding as I could not find related topic.
Another question, is there any way for me to set
<sys:String x:Key="AnimationTarget1">button</sys:String>
into
<RotateTransform.Resources>
as I did to other controls? Thank you for your time. I am still quite new to WPF.
A:
Define the resources that you are referring to in your Storyboard, i.e. AnimationTarget, AnimationTarget1 and AnimationTarget2, in the Resources property of the Button where the EventTrigger is defined. This works for me:
<Button Grid.Column="1" Name="btn2" Width="150" Height="150" Background="gray">
<Button.Resources>
<sys:String x:Key="AnimationTarget">button2</sys:String>
<sys:String x:Key="AnimationTarget1">AnimatedRotateTransform</sys:String>
<sys:String x:Key="AnimationTarget2">button2</sys:String>
</Button.Resources>
<StackPanel >
<Image Source="{StaticResource img2}" x:Name="button2" RenderTransformOrigin=".5,.5">
<Image.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform x:Name="AnimatedRotateTransform" Angle="0" />
<TranslateTransform/>
</TransformGroup>
</Image.RenderTransform>
</Image>
<TextBlock x:Name="textBlock" HorizontalAlignment="Center" RenderTransformOrigin="0.5,0.5" Text="Rotate In">
<TextBlock HorizontalAlignment="Center" Text="Expand In" />
</TextBlock>
</StackPanel>
<Button.Triggers>
<EventTrigger RoutedEvent="ButtonBase.MouseEnter">
<BeginStoryboard Storyboard="{StaticResource BindingRotate}"/>
</EventTrigger>
</Button.Triggers>
</Button>
| {
"pile_set_name": "StackExchange"
} |
Q:
Endomorphisms of bundles associated to codimension 2 subvarieties
Preamble
I initially decided to post this question on math.stackexchange a few days ago, as I consider it to be much less of a research question and much more of "I'm learning" question. But there weren't any takers, and since then it's naturally slipped farther down the "Questions" list over there. So I'm trying my luck here instead.$^*$
Question
Does anyone know of a nice way to think about endomorphisms of vector bundles arising from the Serre construction/correspondence---that is, the vector bundles on projective varieties associated to codimension 2 subvarieties? I am interested in particular in the case of such bundles on $\mathbb{CP}^2$, where these bundles have sections vanishing on prescribed sets of points. Is there anything concrete we can say about elements of $\Gamma(\mathbb{CP}^2,\mbox{End} E)$ when E is one of these bundles?
General Motivation
I'm learning about vector bundle constructions, and I'm trying to compute the cohomologies of these constructions, namely $H^i(E)$ and $H^i(\mbox{End}(E))$.
$^*$ In order to maintain tidiness, I will remove the duplicate question from math.stackexchange if it seems to generate more activity here.
A:
The bundle constructed from the subvariety $Z \subset X$ comes in exact triple
$$
0 \to L \to E \to J_Z \to 0,
$$
where $L$ is a line bundle on $X$ extending $\det N_{Z/X}$. (In case $X = P^2$ and $Z$ is a set of points, $L$ can be chosen to be arbitrary (since each line bundle on $Z$ is trivial)). So, you can use this triple to compute any cohomological invariant of $E$. For example, if you are interested in $\Gamma(P^2,End E)$ you can use the spectral sequence
with the first term having the following form
$$
\begin{array}{ccccc}
Hom(L,J_Z) & \to & Ext^1(J_Z,J_Z) \oplus Ext^1(L,L) & \to & Ext^2(J_Z,L) \cr
& & Hom(J_Z,J_Z) \oplus Hom(L,L) & \to & Ext^1(J_Z,L) \cr
& & & & Hom(J_Z,L)
\end{array}
$$
and converging to $Ext^i(E,E) = H^i(P^2,End E)$. So, you see that the contributions to $\Gamma(P^2,End E)$ come
1) from $Hom(J_Z,L)$;
2) from $Ker(Hom(J_Z,J_Z) \oplus Hom(L,L) \to Ext^1(J_Z,L))$; and
3) from $Ker(Hom(L,J_Z) \to Ext^1(J_Z,J_Z) \oplus Ext^1(L,L))$ (here one should also take into account the $d_2$ differential).
So, everything can be computed.
| {
"pile_set_name": "StackExchange"
} |
Q:
Set environment variable for unity application launcher
I've created a .desktop file to launch our application. Our application requires, that a certain environment variable is configured correctly. Where can I configure this environment variable on a per-user base (the usual candidates I know, like ~/.bashrc and ~/.profile don't work).
Maybe there is a work-around, so I can configure it in the Exec= line of the .desktop file before launching the application?
A:
In the desktop file itself, you can execute the program through env:
Exec=/usr/bin/env VAR=value /usr/bin/yourprogram
Alternatively, use a wrapper script (e.g. /usr/bin/yourprogram.env):
#!/bin/sh
VAR=value
export VAR
exec /usr/bin/yourprogram.real "$@"
However, both are poor solutions, since Unity will not be able to correctly track the program if it is started through a wrapper.
It would be much better to get ~/.profile working – make sure you're using the correct syntax and all that:
export VAR=value
or
VAR=value
export VAR
Also remember that ~/.profile is only read when you log in, so you must log out after changing it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Somehow physically colliding with Collision Triggers
With a whole bunch of copy-pasting from all over the web, I managed to hack together a piece of C# code which spawns a random object from an array when the player enters a large, spherical collision trigger. When the player leaves the trigger, the object is deleted. It's working almost as intended, only problem is that six out of ten times when the player passes through the collider, for a split second it feels like a physical collider. Meaning that although the player is trying to move straight forward, he or she will move left or right along the trigger collider for about half a second, before the object spawns and the player can move freely again.
I was under the impression that checking the "Is Trigger" box would remove all physical properties of that specific collider? Am I missing something?
I'm using the standard FPS Character Controller in Unity 5 if that might have something to do with it.
All help is greatly appreciated.
A:
Realized my solution didn't get posted as I thought it had. Yoyo's solution was correct. The object containing the code was also the trigger. Switched so that the player was the trigger and now all is well.
| {
"pile_set_name": "StackExchange"
} |
Q:
Will GCIH help me in my career path?
I am into non-functional (performance) testing for 12 years. I am planning to move to pen testing with GCIH certification. Can I get a fresh start in pen testing after this?
A:
TLDR: No. Start reading and go for a OSCP or SANS 560.
If you are moving into pen-testing it would be best for you to have more than just a GCIH. If you already have your GCIH it means that you are at least above beginner. I recommend taking the follow steps.
1.http://overthewire.org/ | This site is great for practice in understanding all things that might be done at a high level. I recommend at least finishing all the bandit levels.
2.https://www.vulnhub.com/resources/ | This should be your home for a little while. read it love it.
Sign up for OSCP.
I would imagine that it should take at least 3 months before your ready to signup for OSCP and probably 1 or 2 months before you are able to pass.
Cheers, CND
| {
"pile_set_name": "StackExchange"
} |
Q:
Determining original codevector assuming BEC given hamming code
I have the parity matrix for the Extended Hamming Code [16, 11, 4] :
\begin{bmatrix}
0 & 1 & 0 & 1 & 0 & 1 & 0 & 1 & 0 & 1 & 0 & 1 & 0 & 1 & 0 & 1 \\
0 & 0 & 1 & 1 & 0 & 0 & 1 & 1 & 0 & 0 & 1 & 1 & 0 & 0 & 1 & 1 \\
0 & 0 & 0 & 0 & 1 & 1 & 1 & 1 & 0 & 0 & 0 & 0 & 1 & 1 & 1 & 1 \\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 \\
1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 \\
\end{bmatrix}
The received code I have is:
$r=10?1$ $1001$ $?001$ $1001$
How would I go about finding the most likely code vector that was sent? Normally, if it wasn't the Binary Erasure Channel, I'd just multiply the received code by the parity check matrix transposed, and then find the error position, thus allowing me to figure out the original code-vector. But I'm having a hard time finding information for this related to the BEC.
A:
The erased positions must have been $0$ or $1$. So, you can construct $4$
possible received vectors without any erasures in them from the one given
to you. Compute the syndrome for all four of them. The one with zero
syndrome is the transmitted codeword.
Faster way: if the syndrome of your first hypothesized received vector is zero, you are done. If the syndrome is non-zero, attempt to complete
the decoding process. It will either give you the transmitted codeword
(and you are done) or it will tell you that a detectable but uncorrectable error has occurred. In the latter case, just flip
the two bits that you put into the erased positions and you are done.
| {
"pile_set_name": "StackExchange"
} |
Q:
openlayers + mapserver: controlling tiles
I have a mapserver serving the following mapfile:
MAP
NAME "GLOBCOVER MAP"
# Map image size
SIZE 1000 1000
UNITS meters
EXTENT -30.001389 -30.106069 80.998611 80.108847
PROJECTION
'proj=longlat'
'ellps=WGS84'
'towgs84=0,0,0,0,0,0,0'
'no_defs'
END
# Background color for the map canvas -- change as desired
IMAGECOLOR 255 255 255
IMAGEQUALITY 95
IMAGETYPE agg
OUTPUTFORMAT
NAME agg
DRIVER AGG/PNG
IMAGEMODE RGB
END
# Legend
LEGEND
IMAGECOLOR 255 255 255
STATUS ON
KEYSIZE 18 12
LABEL
TYPE BITMAP
SIZE MEDIUM
COLOR 0 0 89
END
END
# Web interface definition. Only the template parameter
# is required to display a map. See MapServer documentation
WEB
# Set IMAGEPATH to the path where MapServer should
# write its output.
IMAGEPATH '/tmp/'
# Set IMAGEURL to the url that points to IMAGEPATH
# as defined in your web server configuration
IMAGEURL '/tmp/'
# WMS server settings
METADATA
'ows_title' 'QGIS-MAP'
'ows_onlineresource' 'http://localhost/cgi-bin/mapserv?map=/opt/local/apache2/htdocs/eth_luc.map'
'ows_srs' 'EPSG:4326'
END
#Scale range at which web interface will operate
# Template and header/footer settings
# Only the template parameter is required to display a map. See MapServer documentation
TEMPLATE 'fooOnlyForWMSGetFeatureInfo'
END
LAYER
NAME 'GLOBCOVER_L4_200901_200912_V2.3'
TYPE RASTER
DUMP true
TEMPLATE fooOnlyForWMSGetFeatureInfo
EXTENT -30.001389 -30.106069 80.998611 80.108847
DATA '/Users/calvin/work/luc/proj_public/media/GLOBCOVER_L4_200901_200912_V2.3.tif'
METADATA
'ows_title' 'GLOBCOVER_L4_200901_200912_V2.3'
END
STATUS OFF
TRANSPARENCY 100
PROJECTION
'proj=longlat'
'ellps=WGS84'
'towgs84=0,0,0,0,0,0,0'
'no_defs'
END
END
END
A png is dynamically generated by mapserver and shown on the web browser as expected from what is specified in my mapfile's EXTENT. The url can be seen in the screenshot here:-
However, when I attempt to make use of openlayers to do the same using the same mapfile, by means of this openlayers code snippet:
<script type="text/javascript">
$(document).ready(function() {
var lon = 5;
var lat = 40;
var zoom = 5;
var map, layer;
var defaultProjection = new OpenLayers.Projection("EPSG:4326")
map = new OpenLayers.Map({
div: 'map',
displayProjection: defaultProjection
});
layer = new OpenLayers.Layer.MapServer(
"GLOBCOVER_L4_200901_200912_V2.3",
"http://localhost/cgi-bin/mapserv",
{
map: '/opt/local/apache2/htdocs/eth_luc.map',
srs: 'EPSG:4326',
isBaseLayer: true
});
console.log(layer);
map.addLayer(layer);
map.setCenter(new OpenLayers.LonLat(lon, lat), zoom);
map.addControl( new OpenLayers.Control.LayerSwitcher() );
console.log(map)
});
</script>
all I am getting are 36 instances of white PNGs tiled and displayed on the browser, as seen here:-
What am I missing in order to serve my dynamically generated mapserver tiles (PNGs) on openlayers? (with the same visual result as what was done by the pure mapserver solution)
A:
In your code the first parameter to the OpenLayers.Layer.MapServer constructor is the name of the layer in OpenLayers rather than MapServer - so it can be set to anything.
Try adding a layers parameter to the options instead.
layer = new OpenLayers.Layer.MapServer(
"MyLayerName",
"http://localhost/cgi-bin/mapserv",
{
layers: 'GLOBCOVER_L4_200901_200912_V2.3',
map: '/opt/local/apache2/htdocs/eth_luc.map',
srs: 'EPSG:4326'
}, {isBaseLayer: true}
);
Also you may want to use the WMS layers instead http://trac.osgeo.org/openlayers/wiki/Layer/WMS as it is less application specific, and is a good way of testing that your layers could be read by any WMS client.
| {
"pile_set_name": "StackExchange"
} |
Q:
Extract date, time and GPS position linked to road crossing
I am using QGIS. I have a large dataset of approx a hundred animals and I want to determine the number of successful road crossings and extract the date, the time and the two GPS coordinates before and after the road crossing. Please see screenshot attached that shows the example for one animal.
I have intersected the vector line layer from the road network (in red) with the vector line of the animal movements that links its GPS locations and obtained a layer of points where the animal likely crossed the road (round white coloured dot in the screenshot).
When I create a buffer around the intersected points to include the GPS locations linked to each road crossing, I end up including points where the animal did not cross the road because they are included within the distance of the buffer.
How can I include only the GPS points linked to the data crossing? It would be one GPS location at each side of the road (in red).
A:
Reuben, good day to you. I have solved problems like yours with the QGIS tool PointstoPaths (note the plural Paths). This is an extraordinarily useful tool. Sadly, it is only available at QGIS v. 2.X. If you don't have v. 2.X installed, download the latest version at:
https://qgis.org/downloads/
For my Windows 10 machine, I use the install file QGIS-OSGeo4W-2.18.28-2-Setup-x86_64.exe
Once installed, add the PointstoPaths plugin.
You will need two layers, your road layer and your GPS points. As with all GIS analysis procedures, please make sure that they have been projected to the same Coordinate Reference System, and that they contain no geometry errors.
Run PointstoPaths, using the GPS point layer. The Point Group Field will identify each unique animal. In my screenshot below, that field is animal_no.
The Point Order field will be your GPS date/time field. I have had best success setting that field to text, 19-characters long. Within that field, the values look like 2020-05-02 18:56:25 That date/time format is entered in Date Format as %Y-%m-%d %H:%M:%S. Note the blank between date and time.
Important: You must check the Line per Vertex checkbox! It is this option that gives PointstoPaths its unique capability.
PointstoPaths will now output a line shapefile. Each segment in this shapefile will have two fields, begin and end. Not surprisingly, begin and end contain the beginning and ending GPS date/time values that sequentially comprise each segment. These two fields are what make PointstoPaths so special, because each segment can now be related back to the two points that created it.
Now, use the QGIS Select by Location tool to select which output line segments intersect with the roads. Voila! The resulting selection will detail which animals crossed a road, along with the beginning and ending time of each crossing.
I only wish that PointstoPaths were upgraded to 3.x!
Note that the output field names begin and end are reserved ESRI words. To avoid downstream problems, I rename them to something else.
A:
Yet another approach using the Field Calculator... this will work only if your GPS attribute table is sorted according to the recorded date/time.
A dummy GPS point data crossing Road (I've got road 'fid' = only '1').
Now please ope the GPS layer's attribute table and start the Field Calculator.
Give this expression:
CASE
WHEN intersects(make_line($geometry, geometry(get_feature_by_id('GPS', $id +1))), geometry(get_feature('Road', 'fid', '1'))) = 1 THEN 'Pre'
WHEN intersects(make_line($geometry, geometry(get_feature_by_id('GPS', $id -1))), geometry(get_feature('Road', 'fid', '1'))) = 1 THEN 'Post'
ELSE NULL
END
It will add a new field with Pre (point before crossing), Post (point after crossing), and NULL (otherwise).
Delete the rows with NULL value.
| {
"pile_set_name": "StackExchange"
} |
Q:
(java.lang.IllegalArgumentException) Error with gui
I am making a simple gui program in java. When i click run it gives me an error that looks like this:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: adding a window to a container
at java.awt.Container.checkNotAWindow(Unknown Source)
at java.awt.Container.addImpl(Unknown Source)
at javax.swing.JLayeredPane.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at javax.swing.JRootPane.setContentPane(Unknown Source)
at javax.swing.JFrame.setContentPane(Unknown Source)
at main.cool(main.java:31)
at main$1.run(main.java:43)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
and here is my code:
import javax.swing.*;
import java.awt.Container;
import java.awt.event.*;
public class main extends JFrame implements ActionListener {
protected JButton click, fun;
public main()
{
click = new JButton("Click");
click.setActionCommand("click");
click.addActionListener(this);
add(click);
click.setSize(16, 16);
fun = new JButton("wow");
fun.setActionCommand("wow");
fun.addActionListener(this);
add(fun);
}
public static void cool()
{
JFrame frame = new JFrame("TEST!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main main = new main();
frame.setContentPane(main);
frame.setSize(128, 128);
frame.setVisible(true);
frame.setResizable(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run()
{
cool();
}
});
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if("click".equals(e.getActionCommand()))
{
System.out.println("oh right");
} else if ("wow".equals(e.getActionCommand()))
{
System.out.println("hi");
}
}
}
I believe the bug may be in the cool() method; with the setContentPane line. but not sure. Can anyone please help me.
A:
Yes; the bug is triggered in the frame.setContentPanel() in your cool() method in your main class. Your main class should extend JPanel instead of extend JFrame.
Aside: avoid declaring local variables which match class names; and, avoid declaring class names which are the same as standard method names...so, rename your main class as Main (if you must, but try to be more descriptive...perhaps Application), and make your local variable name something other than main...perhaps m or application.
| {
"pile_set_name": "StackExchange"
} |
Q:
"Connect" UiTableView with NavigationController
I am rather new to ios programming and i tried to create a tabbar application with 4 tabs
tab 1 and tab 2 are navigationcontrollers holding a UIView ... now i have a navigationbar, which i can access from my UIView classes.
I put a UITableView in the UIView-Class (with IB) and added a editbutton to the navigation bar:
self.navigationItem.leftBarButtonItem = self.editButtonItem;
Ok, this seems easy and okay, but how can i connect the "edit button" with the uitableview in my UIView Class. The Table is filled with data but when i push the edit button nothing happens ... i do not want to change the UIView class to UITableView because ther are some other UI Elements on the View.
A:
I recommend having a read of the Table View Programming Guide for iOS (specifically the "Inserting and Deleting Rows in Editing Mode" section), as it covers everything you need and you'll learn a lot that'll stand you in good stead going forward.
| {
"pile_set_name": "StackExchange"
} |
Q:
Calculate average rating of 5 ratings
How can calculate this array:
$ratings = [
1 => 220,
2 => 31,
3 => 44,
4 => 175,
5 => 3188
];
To a number (the average vote) like:
4
or
3.5
A:
The basic way to calculate the average is simply to add everything up, and divide it by the total number of values, so:
$total = array_sum($ratings);
$avg = $total/count($ratings);
printf('The average is %.2f', $avg);
The same logic applies to your values, only you need the average rating, so let's get the total number "rating points" that were given, and divide them by the total number of votes:
$totalStars = 0;
$voters = array_sum($ratings);
foreach ($ratings as $stars => $votes)
{//This is the trick, get the number of starts in total, then
//divide them equally over the total nr of voters to get the average
$totalStars += $stars * $votes;
}
printf(
'%d voters awarded a total of %d stars to X, giving an average rating of %.1f',
$voters,
$totalStars,
$totalStars/$voters
);
As you can see here, the output is:
3658 voters awarded a total of 17054 stars to X, giving an average rating of 4.7
| {
"pile_set_name": "StackExchange"
} |
Q:
How to format time in a dynamically generated php description?
I am currently using:
<? JFactory::getDocument()->setDescription($event->title . " am " . $event->start, 'end' -> $event->end) ?>
this generates following:
<meta name="description" content="event title am 2017-12-12 15:30:00">
but I need the time to be in this format:
12.12.2017 um 15:30 Uhr
how can I archive this?
I know that the Dates for the Event are rendered with this code:
helper('date.from_till', array('start' => $event->start, 'end' => $event->end, 'format' => $params->date_format))
I would really appreciate your help :)
A:
This Question got answered with another Question:
https://stackoverflow.com/a/47752218/8207054
$doc->setDescription($event->title . " am " . date('d.m.Y', strtotime($event->start)) . ", " . date('H:i', strtotime($event->end)) . " Uhr");
| {
"pile_set_name": "StackExchange"
} |
Q:
iOS transitions become instantaneous
I'm developing a basic iOS app that doesn't use any fancy animations except for the built in transitions between views. After testing the app on both the simulator and an iPhone 4S for a while, the animations suddenly become instantaneous. For example, clicking the back button makes the previous view appear instantly instead of sliding back in.
I don't get any errors, and I don't call setAnimationsEnabled at any point. The app remains fully functional except for the lack of animations.
EDIT: Occasionally, the tab bar items also disappear. This doesn't always happen, but the disappearing only happens when the animations stop working so I'm guessing they're somehow related.
Any ideas what the problem might be?
A:
Another possibility is incorrect use of threads. Are you using multi-threading of Grand Central Dispatch? If so and you attempt to perform UI animations from threads other than the main thread, all sorts of nasty UI thing happen. Animations and related UI manipulation should only happen on the main thread.
| {
"pile_set_name": "StackExchange"
} |
Q:
PDO Error when trying to retrieve table for database
So I keep getting an error when trying to get my table from my database, here is the error:
object(PDOStatement)#3 (1) { ["queryString"]=> string(18) "SELECT * FROM cars" }
I'm using a function within in a class to conned to the database and then to select from the database which looks like this:
CarsDb.class.php (login information comes from __construct function.)
public function connect($db = "daryl") {
try {
$this->db = new PDO("mysql:host=$this->host;dbname=$db", $this->user, $this->pass);
} catch (PDOException $error) {
echo $error->getMessage();
}
}
public function select($array) {
try {
$result ="SELECT * FROM cars";
$array = $this->db->query($result);
var_dump($array);
} catch (PDOException $e) {
echo $e->getMessage();
}
}
and my table to put this information looks like this:
<?php
include ('CarsDb.class.php');
$db = new CarsDb();
$db->connect();
$db->select($array);
var_dump($array);
?>
<h1 align="center">Database of Cars.</h1>
<form method="POST" >
<table class="sortable">
<thead>
<tr>
<th id="makehead">Make </th>
<th id="modelhead">Model </th>
<th id="idhead">Delete </th>
</tr>
</thead>
<tbody>
<?php
$i = 0;
while ($row = mysql_fetch_array($db->select())) {
$i++;
echo '<tr>';
if ($i % 2) {
echo '<td class="make">' . $row['make'] . '</td>';
echo '<td class="model">' . $row['model'] . '</td>';
echo '<td class="id"><input type="checkbox" name="id" value="' . $row['id'] . '">' . $row['id'] . '</td>';
} else {
echo '<td class="makelight">' . $row['make'] . '</td>';
echo '<td class="modellight">' . $row['model'] . '</td>';
echo '<td class="idlight"><input type="checkbox" name="id" value="' . $row['id'] . '">' . $row['id'] . '</td>';
}
echo '</tr>';
}
?>
</tbody>
<td>
<input Onclick="return ConfirmDelete();" name="delete" type="submit" id="delete" value="Delete"></input>
</td>
</table></form>
<a href= 'CarsWebpage.html'><br>Go back to the beginning.</a>
<?php
mysql_close($con);
?>
</body>
</html>
I've only put the relevant bit of code above to shorten it, you will notice some javascript in there which is working fine accept I can't get it to print due to error at the top, apologies for bad coding or bad practices as I have only been doing this for about a month so I'm very new to this, thanks to anyone who helps.
A:
You not requesting anything from the database, you are only creating a statement. Add this to your select() function.
$stmt = $this->db->query($result);
$array = $stmt->fetchAll();
var_dump($array);
| {
"pile_set_name": "StackExchange"
} |
Q:
Get sender on NotificationCenter keyboard will show
I am currently working on an app with multiple text fields and 2 text views in one scroll view. On appearance of keyboard, I have been able to change the content inset of the scroll view in order to allow the fields to not be hidden. The problem I am having is I can only get this to work on one hardcoded field. I have to choose one and animate to it. Is there anyway to get the sender field or text view on keyboardWillShow? Currently, I am using this and everything works except as mentioned I had to choose one field detailsTxtView and animate to it. Any help?
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(notification:)),name: NSNotification.Name.UIKeyboardWillShow, object: nil)
func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
let contentInsets: UIEdgeInsets? = UIEdgeInsetsMake(0.0, 0.0, keyboardSize.height, 0.0)
scrollView.contentInset = contentInsets!
scrollView.scrollIndicatorInsets = contentInsets!
let goto = CGPoint(x: CGFloat(0.0), y: CGFloat(detailsTxtView.frame.origin.y + (keyboardSize.height + 40)))
scrollView.setContentOffset(goto, animated: true)
}
}
A:
In iOS you can figure out who has the keyboard focus with UIResponder.isFirstResponder (note all UIViews inherit from UIResponder, so its a property on every view). Just check which field has isFirstResponder = true and scroll to that one. Its useful to put all of your fields into an outlet collection if you have a lot of them so you can just iterate through them and figure out which one isFirstResponder.
| {
"pile_set_name": "StackExchange"
} |
Q:
How does as work in ocaml?
I was writing a function that inserts a integer at the nth spot in a list and I initially wrote
let rec insert x n l =
match l with
|[] -> [x]
| h:: t -> if n = 0 then x :: l else h :: insert x (n-1) t
this would throw an error when I tried to add an integer at the end of the list.
let rec insert x n l =
match l with
|[] -> [x]
|h :: t as l -> if n = 0 then x :: l else h :: insert x (n-1) t
_
Adding as fixed the problem but I am not sure I fully understand what as is doing and was wondering how else as could be used.
A:
These two bits of code have the same meaning.
I can't see any problem with either one.
To answer your question, as is used to give a name to a subpart of a pattern. The pattern h :: t as l matches a non-empty list by binding h to the head of the list t to the tail of the list and l to the whole list.
In your example, the new binding for l is the same as the original binding (the function parameter). So there's no difference in the meaning of the code.
Here's a session with the first version:
OCaml version 4.03.0
# let rec insert x n l =
match l with
| [] -> [x]
| h :: t -> if n = 0 then x :: l else h :: insert x (n-1) t;;
val insert : 'a -> int -> 'a list -> 'a list = <fun>
# insert 'r' 3 ['o'; 'e'];;
- : char list = ['o'; 'e'; 'r']
# insert 'r' 2 ['o'; 'e'];;
- : char list = ['o'; 'e'; 'r']
# insert 'r' 1 ['o'; 'e'];;
- : char list = ['o'; 'r'; 'e']
# insert 'r' 0 ['o'; 'e'];;
- : char list = ['r'; 'o'; 'e']
I don't see any problem adding a value to the end of the list.
| {
"pile_set_name": "StackExchange"
} |
Q:
Calling function inside a loop but the loop stops - c#
for (int i = 0; i < dt.Rows.Count; i++)
{
function(dt.Rows[i][0].ToString());
}
I tried to loop the selected values from the gridview and put it inside a
datatable. Now, my problem is that when I tried the code above to pass the
value from datatable to my function. It works, but just once and the loop
stops. Can somebody help me please?
The function is for downloading pdf file.
A:
If the function is sending a binary pdf file to the response stream, it may be calling Response.End which would halt the thread.
If you want to send multiple files the client needs to make multiple requests or the server needs to package them up, like in a zip file.
| {
"pile_set_name": "StackExchange"
} |
Q:
Segmentation fault in matrix in C
I've tried to create a matrix in C and have some input value, but I don't know why it throws me a "segmentation error". This is my code:
#include <stdio.h>
#include <stdlib.h>
int main() {
int i;
int j;
int **a;
a = malloc(5 * sizeof(int));
for (i = 0; i < 5; i++) {
a[i] = malloc(4 * sizeof(int));
}
for (i = 0; i < 5; i++) {
for (j = 0; j < 4; j++) {
scanf("%d", (a[i][j]));
}
}
return 0;
}
A:
Your allocation for a should be
a=malloc(5*sizeof(int*));
Note well the pointer type in the sizof. On some systems (Windows desktops in the early 2000s) an int just happened to be the same size as an int*, but you must not assume that.
scanf takes a pointer as the parameter: the clearest way to write this is scanf("%d", &a[i][j]);
Don't forget to free the memory once you're all done.
Finally, I die a little inside every time I see a matrix modelled like this. Granted, it allows you to use the [][] notation, but normally it's better to model it as a contiguous memory block and use the idiom i * columns + j to access the element at (i, j).
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I make it so that select button will only appear if the column value is the same as the User ID?
How do I make it so that select button will only appear if the Doctor column value is the same as the User ID? For example, the current User ID is Dr.One. So i want it so that only rows that is entered by that Dr will show the select button, but hide it from rows with other Doctor's names.
<tr>
<td>No</td>
<td>Description</td>
<td>Doctor</td>
<td><button>Select</button></td>
</tr>
<tr> // This is the row that is entered by the current User ID
<td>1</td>
<td>Anything</td>
<td>Dr.One</td>
<td>Select</td>
</tr>
<tr>
<td>2</td>
<td>Anything</td>
<td>Dr.Two</td>
<td></td>
</tr>
Currently i'm using AJAX to load the table, i tried to put if-else in between the <td>, but it gives syntax error.
$.ajax({
url: '/Consultation/GetMyList',
type: 'GET',
data: $('#frmMyList').serialize(), // it will serialize the form data
dataType: 'json',
success: function (data) {
var rowNum = 0;
for (var i = 0; i < data.length; i++) {
rowNum += 1;
$("#LoadMyListTable tbody").append("<tr Class='odd gradeX subsequentmyList '>" +
"<td>" + rowNum + "</td>" +
"<td>" + data[i].Description + "</td>" +
"<td>" + data[i].UserID + "</td>" +
"<td style='text-align: center; vertical-align: middle;'><button type='button' class='select btn btn-default' data-refid='" + data[i].RefID + "'>Select</button></td>" +
"</tr>");
}
},
error: function () {
alert('Ajax Submit Failed ...');
}
}); // end ajax
GetMyList method
public List<Consultation> GetMyList(String paid, string UserID)
{
using (DbContext dbb = new DbContext())
{
var query = from p in dbb.patient
join pv in dbb.patient_visit on p.paid equals pv.paid
join d in dbb.diagnosis on pv.pvid equals d.pvid
join u in dbb.users on d.enteredby equals u.UserID
where p.paid.Equals(paid)
orderby d.entereddt descending
select new { d.RefID, d.Description, u.UserID, d.enteredby };
foreach (var item in query)
{
Consultation List = new Consultation();
List.RefID = item.RefID;
List.UserID = item.UserID;
List.Description = item.Description;
List.enteredby = item.enteredby;
LoadMyList.Add(List);
}
return LoadMyList;
}
}
A:
Include a bool SbowButton property in your Consultation view model (or just pass back a collection of anonymous objects.
var query = from p in dbb.patient
.....
var data = query.Select(x => new
{
RefID = x.RefID,
UserID = x.UserID,
Description = x.Description,
ShowButton = x.UserID == yourCurrentUserID // not sure of your logic here
});
return Json(data, JsonRequestBehavior.AllowGet);
Then in the ajax success call back, build your html conditionally
var table = $('#LoadMyListTable tbody'); // cache it
$.ajax({
....
success: function (data) {
$.each(data, function(index, item) {
var row = $('<tr></tr>').addClass('odd gradeX subsequentmyList');
row.append($('<td></td>').text(item.RefID));
row.append($('<td></td>').text(item.Description));
row.append($('<td></td>').text(item.UserID));
var buttonCell = $('<td></td>');
if (item.ShowButton) {
var button = $('<button></button>').attr('type', 'button').addClass('select btn btn-default').data('refid', item.RefID).html('Select');
buttonCell.append(button);
}
row.append(buttonCell);
table.apend(row);
});
}
....
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Battlefield 3 PC boxed, DRM constraints and Origin?
Is the boxed version of Battlefield 3 free from other clients, "services", and DRM? For instance, the intrusive "always online" DRM, "3-install" limits, Origin, and so on.
A:
No. Origin is required for any PC copy (boxed and digital) of Battlefield 3.
A:
Origin is required to play at all times (you can use the offline mode though).
You must also pass a one time release date check the first time you use Battlefield 3, which requires the internet. After that you're free to play offline (but still through Origin).
| {
"pile_set_name": "StackExchange"
} |
Q:
powershell / runspace in a thread
I'm running the following code :
RunspaceConfiguration config = RunspaceConfiguration.Create();
PSSnapInException warning;
config.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out warning);
if (warning != null) throw warning;
Runspace thisRunspace = RunspaceFactory.CreateRunspace(config);
thisRunspace.Open();
string alias = usr.AD.CN.Replace(' ', '.');
string letter = usr.AD.CN.Substring(0, 1);
string email = alias + "@" + (!usr.Mdph ? Constantes.AD_DOMAIN : Constantes.MDPH_DOMAIN) + "." + Constantes.AD_LANG;
string db = "CN=IS-" + letter + ",CN=SG-" + letter + ",CN=InformationStore,CN=" + ((char)letter.ToCharArray()[0] < 'K' ? Constantes.EXC_SRVC : Constantes.EXC_SRVD) + Constantes.EXC_DBMEL;
string cmd = "Enable-Mailbox -Identity \"" + usr.AD.CN + "\" -Alias " + alias + " -PrimarySmtpAddress " + email + " -DisplayName \"" + usr.AD.CN + "\" -Database \"" + db + "\"";
Pipeline thisPipeline = thisRunspace.CreatePipeline(cmd);
thisPipeline.Invoke();
The code is running in a thread created that way :
t.WorkThread = new Thread(cu.CreerUser);
t.WorkThread.Start();
If I run the code directly (not through a thread), it's working.
When in a thread it throws the following exception : ObjectDisposedException "The safe handle has been closed." (Translated from french)
I then replaced "Open" wirh "OpenAsync" which helped not getting the previous exception.
But when on Invoke I get the following exception : InvalidRunspaceStateException "Unable to call the pipeline because its state of execution is not Opened. Its current state is Opening." (Also translated from french)
I'm clueless...
Any help welcome !!!
Thanks !!!
With Open:
à Microsoft.Win32.Win32Native.GetTokenInformation(SafeTokenHandle TokenHandle, UInt32 TokenInformationClass, SafeLocalAllocHandle TokenInformation, UInt32 TokenInformationLength, UInt32& ReturnLength)
à System.Security.Principal.WindowsIdentity.GetTokenInformation(SafeTokenHandle tokenHandle, TokenInformationClass tokenInformationClass, UInt32& dwLength)
à System.Security.Principal.WindowsIdentity.get_User()
à System.Security.Principal.WindowsIdentity.GetName()
à System.Security.Principal.WindowsIdentity.get_Name()
à System.Management.Automation.MshLog.GetLogContext(ExecutionContext executionContext, InvocationInfo invocationInfo, Severity severity)
à System.Management.Automation.MshLog.GetLogContext(ExecutionContext executionContext, InvocationInfo invocationInfo)
à System.Management.Automation.MshLog.LogEngineLifecycleEvent(ExecutionContext executionContext, EngineState engineState, InvocationInfo invocationInfo)
à System.Management.Automation.MshLog.LogEngineLifecycleEvent(ExecutionContext executionContext, EngineState engineState)
à System.Management.Automation.Runspaces.LocalRunspace.OpenHelper()
à System.Management.Automation.Runspaces.RunspaceBase.CoreOpen(Boolean syncCall)
à System.Management.Automation.Runspaces.RunspaceBase.Open()
à Cg62.ComposantsCommuns.ActiveDirectory.Exchange.BoitesAuxLettres.CreationBAL(User usr, IList`1 log) dans D:\Applications\Commun\Sources .Net\COMIAD\COMIAD\Exchange.cs:ligne 141
à Cg62.ComposantsCommuns.ActiveDirectory.ComptesUtilisateurs.CreationUser.CreerUser() dans D:\Applications\Commun\Sources .Net\COMIAD\COMIAD\ComptesUtilisateurs.cs:ligne 199
à System.Threading.ThreadHelper.ThreadStart_Context(Object state)
à System.Threading.ExecutionContext.runTryCode(Object userData)
à System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
à System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
à System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
à System.Threading.ThreadHelper.ThreadStart()
With OpenAsync:
à System.Management.Automation.Runspaces.RunspaceBase.AddToRunningPipelineList(PipelineBase pipeline)
à System.Management.Automation.Runspaces.RunspaceBase.DoConcurrentCheckAndAddToRunningPipelines(PipelineBase pipeline, Boolean syncCall)
à System.Management.Automation.Runspaces.PipelineBase.CoreInvoke(IEnumerable input, Boolean syncCall)
à System.Management.Automation.Runspaces.PipelineBase.Invoke(IEnumerable input)
à System.Management.Automation.Runspaces.Pipeline.Invoke()
à Cg62.ComposantsCommuns.ActiveDirectory.Exchange.BoitesAuxLettres.CreationBAL(User usr, IList`1 log) dans D:\Applications\Commun\Sources .Net\COMIAD\COMIAD\Exchange.cs:ligne 149
à Cg62.ComposantsCommuns.ActiveDirectory.ComptesUtilisateurs.CreationUser.CreerUser() dans D:\Applications\Commun\Sources .Net\COMIAD\COMIAD\ComptesUtilisateurs.cs:ligne 199
à System.Threading.ThreadHelper.ThreadStart_Context(Object state)
à System.Threading.ExecutionContext.runTryCode(Object userData)
à System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
à System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
à System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
à System.Threading.ThreadHelper.ThreadStart()
Sorry for the late reply... I had a lot going on
Upgraded to Powershell 2.0 and I got past the Open error
but now I have the following on the Invoke.
I changed my command to :
Enable-Mailbox -Identity "Aagtest Abe" -Alias Aagtest.Abe -PrimarySmtpAddress [email protected] -DisplayName "Aagtest Abe" -Database "myDb" -DomainController adc.domain.int
The command works fine from powershell.
I get the following exception CmdletInvocationException :
"Une exception a été levée par l'initialiseur de type pour '<Module>'."
No idea on how to translate that...
StackTrace :
à Microsoft.Exchange.Data.Directory.DSAccessTopologyProvider..ctor(String machineName)
à Microsoft.Exchange.Data.Directory.DSAccessTopologyProvider..ctor()
à Microsoft.Exchange.Data.Directory.DirectoryServicesTopologyProvider.DiscoverConfigDC()
à Microsoft.Exchange.Data.Directory.DirectoryServicesTopologyProvider..ctor()
à Microsoft.Exchange.Data.Directory.TopologyProvider.InitializeInstance()
à Microsoft.Exchange.Data.Directory.TopologyProvider.GetInstance()
à Microsoft.Exchange.Data.Directory.ADSession.GetConnection(String preferredServer, Boolean isWriteOperation, Boolean isNotifyOperation, ADObjectId& rootId)
à Microsoft.Exchange.Data.Directory.ADSession.GetReadConnection(String preferredServer, ADObjectId& rootId)
à Microsoft.Exchange.Data.Directory.ADSession.IsReadConnectionAvailable()
à Microsoft.Exchange.Configuration.Tasks.RecipientObjectActionTask`2.InternalBeginProcessing()
à Microsoft.Exchange.Management.RecipientTasks.EnableMailbox.InternalBeginProcessing()
à Microsoft.Exchange.Configuration.Tasks.Task.BeginProcessing()
à System.Management.Automation.Cmdlet.DoBeginProcessing()
à System.Management.Automation.CommandProcessorBase.DoBegin()
A:
So the final answer to that problem is you can't execute remote Exchange powershell commands if you impersonate through advapi32 LogonUser.
Wether the commands are executed in a thread or not don't matter at all as far as I tested.
What seem to be the correct way - well the one that works for me - is to authenticate right after you connect to the Runspace.
As to why this happens... feel free to tell me !!
This code must not be executed while impersonating.
IContexteRemotePowerShell crp:
crp.ConfigurationName = "Microsoft.Exchange";
crp.RemoteUri = "http://exhangeserver/powershell";
crp.User = "account who has rights to do stuff on the exchange server";
crp.Password = "its password";
crp.Domaine = "Domain";
private static void Connect(IContexteRemotePowerShell contexte)
{
try
{
Espace = RunspaceFactory.CreateRunspace();
Espace.Open();
}
catch (InvalidRunspaceStateException ex)
{
throw new TechniqueException(MethodBase.GetCurrentMethod(), "Error while creating runspace.", ex);
}
// Create secure password
SecureString password = new SecureString();
foreach (char c in contexte.Password)
{
password.AppendChar(c);
}
// Create credential
PSCredential psc = new PSCredential(contexte.User, password);
PSCommand command = new PSCommand();
command.AddCommand("New-PSSession");
command.AddParameter("Credential", psc);
if (!String.IsNullOrEmpty(contexte.Serveur))
command.AddParameter("computername", contexte.Serveur);
if (!String.IsNullOrEmpty(contexte.RemoteUri))
command.AddParameter("ConnectionUri", new Uri(contexte.RemoteUri));
if (!string.IsNullOrEmpty(contexte.ConfigurationName))
command.AddParameter("ConfigurationName", contexte.ConfigurationName);
//// Create the session
PowerShell powershell = PowerShell.Create();
powershell.Commands = command;
powershell.Runspace = Espace;
Collection<PSObject> result = ExecuterCommande(command);
if (result.Count != 1)
throw new TechniqueException(MethodBase.GetCurrentMethod(),
"Error while connecting.");
// Create session variable
command = new PSCommand();
command.AddCommand("Set-Variable");
command.AddParameter("Name", "ra");
command.AddParameter("Value", result[0]);
ExecuterCommande(command);
}
private const string InvokeCommand = "Invoke-Command -ScriptBlock {{ {0} }} -Session $ra";
private static string ExecuteRemoteScript(string cmd)
{
PSCommand command = new PSCommand();
command.AddScript(string.Format(InvokeCommand, cmd));
Collection<PSObject> result = ExecuterCommande(command);
StringBuilder sb = new StringBuilder();
foreach (PSObject obj in result)
{
sb.AppendLine(obj.ToString());
}
return sb.ToString().Trim();
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How much money should a "fully-funded" 529 account contain to pay for a student's education?
What is the maximum, reasonable amount one might put into a 529 college savings account for the benefit of a single future student?
529 accounts have maximum allowed balances between $235k and $400k depending on which state's plan is being used. Given that the most expensive college in the country only costs $61k per year, the former would fully cover four years, and the latter would cover it almost twice over. Unless you expect the student to pursue a master's or doctorate, funding up until the allowed max would be too much.
My question is about how much the account would need to be considered fully funded, so for instance you could make a ratio of what percent of fully funded you've got so far. There are already other questions on this site about whether a 529 is a good idea at all, how to prioritize it against retirement accounts, etc.
Of course the answer is going to depend on a lot of assumptions. If you're trying to fund the account as early as possible, so that the tax-free gains are maximized, you're just going to have to make some guesses. Of course you can't predict if your child will go to grad school before they've even entered kindergarten.
Here are some assumptions one might make, but they're just suggestions; feel free to contradict them.
Four years of tuition, fees, books and supplies, room and board at an out of state public university.
Only about 1/3rd of the US population have a Bachelor's degree or better. Of those, only about 1/3rd have a Master's degree or better.
Covering all the costs of attending college.
Out of state public school costs are a mid-point between community, in-state public, out of state public, and private colleges.
According to http://trends.collegeboard.org/college-pricing/figures-tables/average-published-undergraduate-charges-sector-2015-16 the annual cost of a four-year out of state college is $34k
College cost inflation and investment returns will both be the same over the next 18-20 years as they were over the last 18-20 years
A simplifying assumption could be that future investment returns and college cost inflation will be equal. I haven't yet researched to know if this is a reasonable assumption or not.
"Between 2005-06 and 2015-16, published in-state tuition and fees at public four-year institutions increased at an average rate of 3.4% per year beyond inflation, compared to average annual rates of increase of 4.2% between 1985-86 and 1995-96 and 4.3% between 1995-96 and 2005-06." Source: http://trends.collegeboard.org/content/average-rates-growth-published-charges-decade-0 "Tuition and fees and room and board" grew slower, at 3.4% and 2.8% for the past two decades.
Schwab estimates that large cap stocks will return 6.3%, bonds will return 3.3%, and inflation will be 1.8% in the long-term future.
The after-inflation return of a 60/40 stock/bond portfolio is 3.30%, just 0.17% less per year than the historical college costs for the last two decades.
Therefore, I conclude that it's not unreasonable to assume investment returns will about equal increases in costs.
A:
OK, maximum reasonable amount (sort of an oxymoron the costs are not reasonable) is going to be end game more around $180K (2016 dollars) with the parameters you listed. My son is going to college next year so we did a little looking around the last couple of years.
Consider higher growth rates the first 10 years, then you would pull back on the aggressive portfolio as the child neared college.
First, (IMO only) costs in most public schools will not track up as fast over the next 25 years due to market pressures. A bubble now exists with a disconnect between value and cost of higher educations and Internet learning and reorganization of Universities may push this down over 10 years. Private schools can be another world though... it's like trying to reason out why someone would pay $1000 for a baby stroller. That perceived incremental value beyond the $200 stroller is there and folks that can are shelling out the dough. So private schools could continue to rise in cost. Wouldn't be surprising to see a further stratification of private higher ed 20 years from now.
Given that, if you don't want to over fund the account, shoot for $100K then re-adjust about 6 years out.
Federal Rules for reference: https://www.irs.gov/pub/irs-pdf/p970.pdf
529 plans have additional state rules so check with plan admin for help on these.
Remember: In addition to tuition, books,fees, room&board,... now computer equipment and Internet services (2015 statute change) needed/used for college and be paid by plan dollars in most cases.
Over funding risk is reduced when you consider the 529 plan as part of estate planning. Extra funds can be inherited (simple POD account declaration in most states). It's possible for child to inherit 529 assets then use them for his children, and down the line by creating new accounts and transferring within the rules. The advantage of 20-40 years of tax free growth may be available (well if the laws don't change).
| {
"pile_set_name": "StackExchange"
} |
Q:
Python - Assigning Multiple Keys for a Single Value
I'd like to be able to assign the following keys to these values in Python:
Numbers 01 - 10 : 5.01
Numbers 11 - 20 : 7.02
Numbers 21 - 30 : 9.03
Numbers 31 - 40 : 11.04
Numbers 41 - 50 : 15.00
Numbers 51 - 60 : 17.08
Numbers 61 - 70 : 19.15
I know that this is possible:
rates = dict.fromkeys(range(1, 11), 5.01)
rates.update(dict.fromkeys(range(11, 21), 7.02)
# ...etc
and that's okay. However, is there a way to do this in one line or one initializer list in Python?
A:
Use a dictionary comprehension and an initial mapping:
numbers = {1: 5.01, 11: 7.02, 21: 9.03, 31: 11.04, 41: 15.0, 51: 71.08, 61: 19.15}
numbers = {k: v for start, v in numbers.items() for k in range(start, start + 10)}
Demo:
>>> from pprint import pprint
>>> numbers = {1: 5.01, 11: 7.02, 21: 9.03, 31: 11.04, 41: 15.0, 51: 71.08, 61: 19.15}
>>> numbers = {k: v for start, v in numbers.items() for k in range(start, start + 10)}
>>> pprint(numbers)
{1: 5.01,
2: 5.01,
3: 5.01,
4: 5.01,
5: 5.01,
6: 5.01,
7: 5.01,
8: 5.01,
9: 5.01,
10: 5.01,
11: 7.02,
12: 7.02,
13: 7.02,
14: 7.02,
15: 7.02,
16: 7.02,
17: 7.02,
18: 7.02,
19: 7.02,
20: 7.02,
21: 9.03,
22: 9.03,
23: 9.03,
24: 9.03,
25: 9.03,
26: 9.03,
27: 9.03,
28: 9.03,
29: 9.03,
30: 9.03,
31: 11.04,
32: 11.04,
33: 11.04,
34: 11.04,
35: 11.04,
36: 11.04,
37: 11.04,
38: 11.04,
39: 11.04,
40: 11.04,
41: 15.0,
42: 15.0,
43: 15.0,
44: 15.0,
45: 15.0,
46: 15.0,
47: 15.0,
48: 15.0,
49: 15.0,
50: 15.0,
51: 71.08,
52: 71.08,
53: 71.08,
54: 71.08,
55: 71.08,
56: 71.08,
57: 71.08,
58: 71.08,
59: 71.08,
60: 71.08,
61: 19.15,
62: 19.15,
63: 19.15,
64: 19.15,
65: 19.15,
66: 19.15,
67: 19.15,
68: 19.15,
69: 19.15,
70: 19.15}
The dictionary expression produces both a key and a value for each iteration of the loops. There are two loops in that expression, and you need to read them from left to right as nested in that order. Written out as a non-comprehension set of loops, you'd get:
numbers = {1: 5.01, 11: 7.02, 21: 9.03, 31: 11.04, 41: 15.0, 51: 71.08, 61: 19.15}
output = {}
# loop over the (key, value) pairs in the numbers dictionary
for start, v in numbers.items():
for k in range(start, start + 10):
output[k] = v
numbers = output
Essentially the keys in the original numbers dictionary are turned into ranges to form 10 new keys in the output dictionary, all with the same value.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get the size range for fonts
What I want to do is have the user select a font from third party font selection combo box and select the font size. How do I go about having the correct range of sizes for that font?
A:
Fonts (generally) are vector-based and can be displayed at any reasonable point size. I say "reasonable" becase on a typical display, fonts below 8pts are not terribly useful.
Most Microsoft products give a range starting with 8, 9, 10, 11, 12 and then jump by ever-increasing point values up to 72. Depending on your application, you may want to allow a variety of smaller values (like 8-12) and then a few larger values.. a "correct" range really is dependent on how you want to use the fonts.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to fix 'Expression: vector subscript out of range' error
I'm in the process of making a simple game via SFML and have encountered the following error:
Debug assertation failed!
Expression: vector subscript out of range
This error only appears when the 'rocket' makes contact with the first 'enemy' whilst there are 3 enemies on screen at the same time.
for (int i = 0; i < rockets.size(); i++) //This is where the error points to
{
for (int j = 0; j < enemies.size(); j++)
{
Rocket *rocket = rockets[i];
Enemy *enemy = enemies[j];
if (checkCollision(rocket->getSprite(), enemy->getSprite()))
{
//hitSound.play();
score++;
std::string finalScore = "Score: " + std::to_string(score);
scoreText.setString(finalScore);
sf::FloatRect scoreBounds = scoreText.getGlobalBounds();
scoreText.setOrigin(scoreBounds.width / 2, scoreBounds.height / 2);
scoreText.setPosition(viewSize.x * 0.5f, viewSize.y * 0.10f);
rockets.erase(rockets.begin() + i);
enemies.erase(enemies.begin() + j);
delete(rocket);
delete(enemy);
if (score % 5 == 0) levelUp();
printf("rocket intersects with enemy \n");
}
}
}
I have stored the enemy and rocket objects in vectors:
std::vector <Enemy*> enemies;
std::vector <Rocket*> rockets;
Here's my entire update function if that helps:
void update(float dt)
{
hero.update(dt);
currentTime += dt;
if (currentTime >= prevTime + 1.125f)
{
spawnEnemy();
prevTime = currentTime;
}
for (int i = 0; i < enemies.size(); i++)
{
Enemy *enemy = enemies[i];
enemy->update(dt);
if (enemy->getSprite().getPosition().x < 0)
{
enemies.erase(enemies.begin() + i);
delete(enemy);
gameOver = true;
gameOverSound.play();
}
}
for (int i = 0; i < rockets.size(); i++)
{
Rocket *rocket = rockets[i];
rocket->update(dt);
if (rocket->getSprite().getPosition().x > viewSize.x)
{
rockets.erase(rockets.begin() + i);
delete(rocket);
}
}
for (int i = 0; i < rockets.size(); i++)
{
for (int j = 0; j < enemies.size(); j++)
{
Rocket *rocket = rockets[i];
Enemy *enemy = enemies[j];
if (checkCollision(rocket->getSprite(), enemy->getSprite()))
{
//hitSound.play();
score++;
std::string finalScore = "Score: " + std::to_string(score);
scoreText.setString(finalScore);
sf::FloatRect scoreBounds = scoreText.getGlobalBounds();
scoreText.setOrigin(scoreBounds.width / 2, scoreBounds.height / 2);
scoreText.setPosition(viewSize.x * 0.5f, viewSize.y * 0.10f);
rockets.erase(rockets.begin() + i);
enemies.erase(enemies.begin() + j);
delete(rocket);
delete(enemy);
if (score % 5 == 0) levelUp();
printf("rocket intersects with enemy \n");
}
}
}
for (int i = 0; i < enemies.size(); i++)
{
Enemy *enemy = enemies[i];
if (checkCollision(enemy->getSprite(), hero.getSprite()))
{
gameOver = true;
gameOverSound.play();
}
}
}
A:
You can't remove elements from a vector as you iterate over it. You're removing elements but not properly adjusting i and j so you end up out of bounds with your indices.
| {
"pile_set_name": "StackExchange"
} |
Q:
Linearizing 3 differential equations to make 6 linear equations
Hello I am having trouble trying to find the correct model for this coupled spring system. The scenario is the following we have: Ceiling - Spring - Mass(1) - Spring(2) - Mass(2) - Spring (3) - Mass(3) End.
I came up with the following system of differential equations in the 2nd order to model this problem.
$x_1^{''}=[-k_1x_1-k_2(x_2-x_1)]/m_1$
$x_2^{''}=[k_2(x_2-x_1)-k_3(x_3-x_2)]/m_2$
$x_3^{''}=-k_3(x_5-x_3)/m_3$
Is this the correct model? Afterwards I am trying to linearize these equations into 6 differential equations that I can input in matlab and plot the position of each spring.
So I linearized them and obtained the following:
$y_1^{'}=y_2$
$y_2^{'}=(-k_1y_1-k_2(y_3-y_1)-k_3(y_5-y_3)/m_1$
$y_3^{'}=y_4$
$y_4^{'}=(k_2(y_3-y_1)+k_3(y_5-y_3)/m_2$
$y_5^{'}=y_6$
$y_6^{'}=(-k_3(y_5-y_3))/m_3$
I am not sure if this is correct or not. When I plot them in matlab I get something very strange that doesn't make sense. Does anyone know how the spring mass problems work in Diff EQ?
A:
I think your model is off. The force on mass 1 should depend only on the lengths of springs 1 and 2, no? Consider that if you hold mass 2 in place and pull on mass 3, there is no force transferred to mass 1.
Also, in the equation for $x_2''$, I think there is a sign error. The two terms should have opposite signs since they're pulling the mass in opposite directions.
Here's my code in Python. I'm not sure it's right. It's largely ripped off from here: http://wiki.scipy.org/Cookbook/CoupledSpringMassSystem
The main/only difference from your problem is that here we include the springs' natural lengths L1, L2, and L3.
from scipy.integrate import odeint
import matplotlib.pyplot as plt
def vectorfield(w,t,p):
y1, y2, y3, y4, y5, y6 = w
m1, m2, m3, k1, k2, k3, L1, L2, L3 = p
# Create y' (the vector)
f = [y2,
( -k1 * (y1 - L1) + k2 * (y3 - y1 - L2)) / m1,
y4,
( -k2 * (y3 - y1 - L2) + k3 * (y5 - y3 - L3) ) / m2,
y6,
( -k3 *(y5 - y3 - L3) )/m3 ]
return f
# Parameter values
# Masses:
m1 = 10.0
m2 = 15.5
m3 = 12.2
# Spring constants
k1 = 4.0
k2 = 2.0
k3 = 1.0
# Natural lengths
L1 = 0.1
L2 = 2.0
L3 = 3.7
# Initial conditions
y1 = 0.2
y2 = 0.0
y3 = 5.25
y4 = 0.0
y5 = 8.0
y6 = 0.0
# ODE solver parameters
abserr = 1.0e-8
relerr = 1.0e-6
stoptime = 100.0
numpoints = 2500
# Create the time samples for the output of the ODE solver.
# I use a large number of points, only because I want to make
# a plot of the solution that looks nice.
t = [stoptime * float(i) / (numpoints - 1) for i in range(numpoints)]
# Pack up the parameters and initial conditions:
p = [m1, m2, m3, k1, k2, k3, L1, L2, L3]
w0 = [y1, y2, y3, y4, y5, y6]
# Call the ODE solver.
wsol = odeint(vectorfield, w0, t, args=(p,),
atol=abserr, rtol=relerr)
plt.xlabel('t')
plt.grid(True)
plt.hold(True)
lw = 1
plt.plot(t, wsol[:,0], 'b', linewidth=lw)
plt.plot(t, wsol[:,2], 'g', linewidth=lw)
plt.plot(t, wsol[:,4], 'r', linewidth=lw)
plt.legend((r'$y_1$', r'$y_3$', r'$y_5$'))
plt.title('Mass Displacements for the\nCoupled Spring-Mass System')
plt.show()
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.