text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
How to solve Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous in laravel
I have a belongsToMany relationship between the students and departments. Now i want to fetch all the departments of students where subject_id of departments is null. I below code but it gives me the following error
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous (SQL: select * from departments where subject_id is null and exists (select * from students inner join department_student on students.id = department_student.student_id where departments.id = department_student.department_id and id = 16 and students.deleted_at is null))
$departments=Department::where('subject_id','=',null)
->whereHas('students',function($student){
$student->where('id',Auth::id());
})
->get();
dd($departments);
Any help will be appreciated
A:
You should specify the table name where you are referencing the id to avoid the ambiguity.
$departments=Department::where('subject_id','=',null)
->whereHas('students',function($student){
$student->where('student.id',Auth::id()); //Notice the student.id instead of id
})->get();
| {
"pile_set_name": "StackExchange"
} |
Q:
problem in comparing element of two array and if element matches then modifies another array value with some condition
I want to compare x and z and if element in x is present in z then push element of y in temp else push 0 in temp at the end length of z and temp should be equal.
below is my code ---
var x=[00,03,06,21]
var y=[79,11,18,14]
var temp=[]
var z=[00,01,02,03,04,05,06,07,08,09,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]
for(var i=0;i<z.length;i++){
for(j=0;j<x.length;j++){
if(z[i]==x[j]){
// alert("hello")
temp.push(y[j])
}
}
if(z[i]!=x[j]){
temp.push(0)
}
}
console.log(temp)
console.log(z)
i getting the output as -
//temp (29) [79, 0, 0, 0, 11, 0, 0, 0, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 0, 0, 0, 0]
//z (25) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
expected output --
//temp (25) [79, 0, 0, 11, 0, 0, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 0, 0, 0]
//z (25) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
24]
A:
Once you found a common value, you need to continue the outer loop. If not found, push after finishing the inner loop.
BTW, do not forget to declare all variables.
var x = [0, 3, 6, 21],
y = [79, 11, 18, 14],
temp = [],
z = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24];
outer: for (let i = 0; i < z.length; i++) {
for (let j = 0; j < x.length; j++) {
if (z[i] === x[j]) {
temp.push(y[j]);
continue outer;
}
}
temp.push(0);
}
console.log(temp);
console.log(z);
A version without a label.
var x = [0, 3, 6, 21],
y = [79, 11, 18, 14],
temp = [],
z = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24];
for (let i = 0; i < z.length; i++) {
let value = 0;
for (let j = 0; j < x.length; j++) {
if (z[i] === x[j]) {
value = y[j];
break;
}
}
temp.push(value);
}
console.log(temp);
console.log(z);
Finally, a shorter approach with an object for the replacement values.
var x = [0, 3, 6, 21],
y = [79, 11, 18, 14],
z = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24],
values = x.reduce((r, k, i) => (r[k] = y[i], r), {}),
temp = z.map(k => values[k] || 0);
console.log(temp);
console.log(z);
| {
"pile_set_name": "StackExchange"
} |
Q:
Showing a measure is countably additive if it's finitely additive
Let $\mu$ be a finitely additive nonnegative set function on some measurable space $(\Omega, \mathcal{F})$ with the continuity property $$B_n\in \mathcal{F},\, B_n\downarrow\emptyset, \, \mu(B_n)<\infty\Rightarrow \mu(B_n)\to 0 \tag{$*$} $$
is countably additive when $\mu(\Omega)<\infty$.
I am having difficulty using the property to show $\mu$ is countably additive. I would like to prove for any disjoint collection of sets $(A_i)$, $\lim \mu (\bigcup _{i=1} ^n A_n)=\mu(\bigcup _{i=1} ^\infty A_n)$. WLOG, (by rearranging indices) suppose $(A_n)$ is decreasing. Then $A_n\downarrow \emptyset$. By $(*)$ $\mu(A_n)\to 0$. I don't see how this helps or how this implies $\sum_i \mu (A_i)<\infty$.
How can I show $\mu$ is countably additive?
Doesn't the condition that $B_n\downarrow \emptyset$ automatically imply $\mu(B_n)\to 0$?
A:
Hint: note that
$$\cup_0^\infty A_n = \cup_0^N A_n \cup \left( \cup_{N+1}^\infty A_n\right) $$
is a finite union and that you can apply the assumption to the sequence $(\cup_{N+1}^\infty A_n)_N$
| {
"pile_set_name": "StackExchange"
} |
Q:
A generalization of strict convexity
Consider the following properties of a Banach space:
the intersection of any support hyperplane with the unit sphere is
(S) a singleton (this is the strict convexity);
(SF) finite-dimensional set;
(SC) compact in the norm topology.
It is easy to see that these properties are equivalent to the fact that any closed convex subset of a unit sphere is singleton/finite-dimensional/ compact.
Q1: Are (SF) and (SC) different?
Q2: Were these conditions considered in the literature? Do they have names?
Q3: Are there any necessary or sufficient conditions for them? In particular, are there any dual/predual conditions?
A:
I think that one can answer Question 1 in the positive by studying the following construction: consider $X=\ell_2\oplus \mathbb{R}$. Consider in $\ell_2$ an infinitely dimensional compact ellipsoid $E$ centered at $0$ with all axes of length $<1$. Denote the unit ball of $\ell_2$ by $B$. Consider in $X$ the norm whose unit ball is the closure of the convex hull of the union of three sets: $B\oplus \{0\}$, $E\oplus \{-1\}$, and $E\oplus \{1\}$. I would expect this to be (SC), but it is obviously not (SF).
As for literature, you can check references listed in the book by Day, Normed Linear Spaces, book Deville-Godefroy-Zizler, and the survey of Godefroy in the "Handbook of the Geometry of Banach spaces".
| {
"pile_set_name": "StackExchange"
} |
Q:
How should common references be passed around in an assembly?
I am trying to get rid off static classes, static helper methods and singleton classes in my code base. Currently, they are pretty much spread over the whole code, especially so for the utility classes and the logging library. This is mainly due to the need for mocking ability as well as object-oriented design and development concerns, e.g. extensibility. I might also need to introduce some form of dependency injection in the future and would like to leave an open door for that.
Basically, the problem I have encountered is about the method of passing the commonly used references around. These are objects that are used by almost every class in the code base, such as the logging interface, the utility (helper) class interface and maybe an instance of a class that holds an internal common state for the assembly which most classes relate to.
There are two options, as far as I'm aware. One is to define a class (or an interface) that stores the common references, a context if you will, and pass the context to each object that is created. The other option is to pass each common reference to almost every class as a separate parameter which would increase the number of parameters of the class constructors.
Which one of these methods is better, what are the pros and cons of each, and is there a better method for this task?
A:
I generally go with the context object approach, and pass the context object either to an object's constructor, or to a method -- depending on which one makes the most sense.
The context object pattern can take a few forms.
You can define an interface that has exactly the members you need, or you can generate a sort of container class. For example, when writing loosely-coupled components, I tend to have each component I implement have a matching interface, so that it can be reimplemented if desired. Then I register the objects on a "manager" object, something like this:
public interface IServiceManager
{
public T GetService<T>();
public T RequireService<T>();
public void RegisterService<T>(T service);
public void UnregisterService<T>(T service);
}
Behind the scenes there is a map from type to object, which allows me to extremely quickly assemble a large set of diverse components into a working whole. Each component asks for the others by interface, and the manager object is what glues them together. (If you correctly author your components, you can even swap out one service for another while the process is running!)
One would register a service something along these lines:
class FooService : IFooService { }
// During process start-up:
serviceManager.RegisterService<IFooService>(new FooService());
There is more overhead with this approach than with the flat-interface approach due to the dictionary lookup, but it has allowed me to build very sophisticated systems that can be easily redeployed with different service implementations. (And, as is usual, any bottlenecks I encounter are never in looking up a service object from a dictionary, but somewhere else such as the database.)
| {
"pile_set_name": "StackExchange"
} |
Q:
Getting NSPopUpButton from NSMenuItem
My application uses the -validateMenuItem: method for validating menu items.
But I need to validate different menu items depending on what popup's there in.
I was hoping for a way to get the tag of the popup, but after looking through the docs I can't seem to find a way... any ideas?
Edit:
I thought this needed some more context... my model object is a JDBCSyncer (syncs one database with another), my window is a settings one, and I need to validate my menu items based on wether their title is in an array of strings which represents the various fields within a table. The idea is that you select the field from a popup.
A:
I don't have a great answer off the top of my head, but how about something along these lines:
- (BOOL)validateMenuItem:(NSMenuItem *)menuItem
{
NSMenu *menu = [menuItem menu];
if (menu == [popUpButton1 menu]) {
return YES;
}
else if (menu == [popUpButton2 menu]) {
return NO;
}
else (menu == [popUpButton3 menu]) {
return YES;
}
else {
return NO;
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Weierstrass points and Osculating Hyperplanes
Let $X$ be an irreducible non-singular curve of genus $g$, embedded in $\mathbb{P}^n$ via the canonical embedding.
Let $j$ be an integer, and $P\in X$ a point on the curve. I would like to prove the following statement:
The integer $j+1$ is a Weierstrass gap for $P$ if and only if there
exists a hyperplane $H\subseteq\mathbb{P}^{n}$ such that $H$ intersects $X$
at $P$ with multiplicity exactly $j$.
Recall that an integer $s$ is called a Weierstrass gap for a point $P\in X$ if there does not exist any meromorphic function $f$ on $X$ such that $f$ is regular outside of $P$, and has pole of order $s$ at $P$.
This should apparently follow from Riemann-Roch Theorem. Which line bundles should I apply the Riemann-Roch theorem on? This seems to be an important characterization of Weierstrass points, so it might be helpful to have a canonical answer in this website.
A:
Let $s=j+1$. A meromorphic function with a pole of order $s$ at $P$ which is regular at all other points is exactly a section of $\mathcal{O}_X(sP)$ which is not a section of $\mathcal{O}_X((s-1)P)$. So $s$ is a Weierstrass gap at $P$ iff $$\ell(sP)=\ell((s-1)P).$$ By Riemann-Roch, this is equivalent to $$\ell(K-sP)=\ell(K-(s-1)P)-1$$ where $K$ is the canonical divisor. That is, $s$ is a Weierstrass gap at $P$ iff there is a section of $\mathcal{O}_X(K-(s-1)P)$ which is not a section of $\mathcal{O}_X(K-sP)$. This condition is equivalent to the existence of a divisor $D$ linearly equivalent to $K$ such that $D-(s-1)P$ is effective but $D-sP$ is not effective. But this just means $D$ is effective and $s-1$ is the coefficient of $P$ in $D$. The effective divisors which are linearly equivalent to $K$ are exactly the hyperplane sections of $X$ for its canonical embedding. So our condition is equivalent to the existence of a hyperplane section of the canonical embedding that contains $P$ with multiplicity $s-1=j$, as desired.
| {
"pile_set_name": "StackExchange"
} |
Q:
Finding all the maximal ideals of $C([0,1])$ and also prime ideals in it which are not maximal
Hope this isn't a duplicate.
I have been able to prove that the maximal ideals of $C([0,1])$ are of the form $M_c = \big\{ f \in C([0,1]) : f(c)=0 \text{ for some fixed c }\in [0,1]\big\}$
I was trying to find all the maximal ideals of $C([0,1])$ and also prime ideals in it which are not maximal.
No idea so far...
A:
To supplement egreg's answer, here is a proof of the result they mentioned:
If $X$ is a completely regular space, then there is a natural bijection between points of the Stone-Cech compactification $\beta X$ and maximal ideals in $C(X)$.
For $f\in C(X)$, we will write $V(f)$ for $f^{-1}(\{0\})$. Given a point $x\in \beta X$, define $$M_x=\{f\in C(X):x\in\overline{V(f)}\}.$$ (Here and below, the overline denotes closure in $\beta X$, not closure in $X$.) I claim that $x\mapsto M_x$ is our desired bijection.
First, $M_x$ is a maximal ideal. It is clear that it is closed under multiplication by elements of $C(X)$. If $f,g\in M_x$, observe $V(f)\cap V(g)\subseteq V(f+g)$. We will show $x\in\overline{V(f)\cap V(g)}$ and hence $f+g\in M_x$.
So, suppose $x\not\in\overline{V(f)\cap V(g)}$. We can then choose a closed neighborhood $A$ of $x$ which is disjoint from $\overline{V(f)\cap V(g)}$ and a function $h:\beta X\to [0,1]$ which vanishes on $A$ and is $1$ on $\overline{V(f)\cap V(g)}$. Now consider $F=(f^2+h,g^2+h)$ as a function $X\to\mathbb{R}^2$. Observe that $F$ never vanishes, since when $f$ and $g$ both vanish, $h$ is $1$. Choose a continuous function $s:\mathbb{R}^2\setminus\{(0,0)\}\to [0,1]$ such that $s(a,0)=0$ for all $a$ and $s(0,b)=1$ for all $b$. Then $s\circ F$ extends continuously to a map $k:\beta X\to [0,1]$. Observe that $k=1$ on $V(f)\cap A$ and $k=0$ on $V(g)\cap A$. But $A$ is a neighborhood of $x$, so $x\in\overline{V(f)\cap A}$ and also $x\in\overline{V(g)\cap A}$. Thus by continuity, $k(x)=1$ and $k(x)=0$, which is a contradiction.
We have therefore shown that $M_x$ is an ideal. For maximality, suppose $f\in C(X)\setminus M_x$. Then $x\not\in\overline{V(f)}$, so as above we can choose $h:\beta X\to [0,1]$ which vanishes on a neighborhood of $x$ and is $1$ on $\overline{V(f)}$. Then $h|_X\in M_x$ since it vanishes on an entire neighborhood of $x$, and $h|_X+f^2$ vanishes nowhere on $X$. Thus $h|_X+f^2$ is a unit in $C(X)$ and thus the ideal generated by $M_x$ and $f$ is not proper. Since $f\not\in M_x$ was arbitrary, this shows $M_x$ is maximal.
Now I claim that for $x\neq y$, $M_x\neq M_y$. To prove this, choose $h:\beta X\to [0,1]$ vanishing on a closed neighborhood of $x$ but not vanishing at $y$. Then $h|_X\in M_x$ and $h|_X\not\in M_y$.
Finally, I claim that any maximal ideal $M\subset C(X)$ is equal to $M_x$ for some $x\in \beta X$. To prove this, let $Z=\{\overline{V(f)}:f\in M\}$. Note that $V(f)$ is nonempty for all $f\in M$ since $M$ cannot contain a unit, and also that $V(f)\cap V(g)\supseteq V(f^2+g^2)$. It follows that $Z$ has the finite intersection property, and so by compactness of $\beta X$ there is some $x\in \beta X$ which is in every element of $Z$. But this just means that $M\subseteq M_x$, and so by maximality of $M$, $M=M_x$.
As for prime ideals that are not maximal, there are a lot more possibilities and it is much harder to describe all of them. As mentioned in Max's answer, you can construct some using ultrafilters. In fact, instead of considering functions which are $0$ along an ultrafilter as he does, you can instead consider functions which converge to $0$ at a certain rate, and in this way you can obtain large nested collections of prime ideals. You can find the details of such a construction at this answer of mine, which constructs a chain of prime ideals in $C(X)$ which is order-isomorphic to $[0,\infty)$ from any element of $C(X)$ that is not locally constant.
| {
"pile_set_name": "StackExchange"
} |
Q:
Bootstrap 3: Catch event when navbar is collapsed or expanded
Using Bootstrap 3:
Is it possible to catch when the navbar is collapsed/expanded?
I can't seam to find an event for this.
Edit:
I have a logo that is 90px heigh, so the navbar must be around 110px heigh.
To place the menu links close to the main content, I therefor have a margin-top at 60px. When it collapse, I want the three dashes (icon-bar) to have a margin-top of 60px also. When doing that, the menu suddently is 60px + 60px = 120px down - and that is 60px too much. So I want to catch when it's collapsed and then change margin-top of menu-links to 0px and when it's expanded I want to change it to 60px.
Here's a bootply sample:
http://www.bootply.com/120802
A:
Maybe this way:
$('.navbar-collapse').on('shown.bs.collapse', function() {
// do something
});
The navbar is using the collapse jQuery-Plugin. There you can look for the events: http://getbootstrap.com/javascript/#collapse
Edit:
I added an example of usage:
http://jsbin.com/tizanoti/4/edit
A:
Enable manually with:
$('.collapse').collapse()
Collapse Methods
.collapse("toggle") //Toggles the collapsible element
.collapse("show") //Shows the collapsible element
.collapse("hide") //Hides the collapsible element
Collapse Events
show.bs.collapse //Occurs when the collapsible element is about to be shown
shown.bs.collapse //Occurs when the collapsible element is fully shown (after CSS transitions have completed)
hide.bs.collapse //Occurs when the collapsible element is about to be hidden
hidden.bs.collapse //Occurs when the collapsible element is fully hidden (after CSS transitions have completed)
reference
| {
"pile_set_name": "StackExchange"
} |
Q:
How to prepare data for weka in word sense disambiguation
I want to use weka for word sense diasambiguation. I prepared some files containing a Persian sentence, a tab, a Persian word, a tab and then an English word. they are in notepad++ in txt format. Now how should I use these files for weka? How should I change them?
The sample file:
https://www.dropbox.com/s/o7wtvrvkiir80la/F.txt?dl=0
A:
I found it. The files should have the same number of columns. So I put the sentences in quotations, then a comma and the the English word in quotation. Above these, we should write proper relations and attributes.
| {
"pile_set_name": "StackExchange"
} |
Q:
Explanation on block needed
I have recently started learning magento and would appreciate if anyone could explain what this does, especially the method addItemRender.
<adminhtml_sales_order_view>
<block type="adminhtml/sales_order_view_items" name="order_items" template="sales/order/view/items.phtml">
<action method="addItemRender"><type>default</type><block>adminhtml/sales_order_view_items_renderer_default</block><template>sales/order/view/items/renderer/default.phtml</template></action>
</block>
</adminhtml_sales_order_view>
I do understand that it calls the method addItemRender with params $type, $block, $template on the block adminhtml/sales_order_view_items, but what I dont understand is what happens next and is it the same as below and calling getChildHtml() in the parent phtml ?
<adminhtml_sales_order_view>
<block type="adminhtml/sales_order_view_items" name="order_items" template="sales/order/view/items.phtml">
<block type="adminhtml/sales_order_view_items_renderer_default" name="order_items" template="sales/order/view/items/renderer/default.phtml"/>
</block>
</adminhtml_sales_order_view>
Any help would be really appreciated
A:
Each order idem has a product associated to it, because that's what you buy...products.
And each product can have a different type: simple, configurable, grouped, bundle, downloadable, virtual.
Each product type may behave differently in certain conditions. For example the price should be shown differently depending on the product type.
The method addItemRenderer provides a block and a template for different product types.
To show a line in an order for a product the method Mage_Adminhtml_Block_Sales_Items_Abstract::getItemHtml is called.
This method checks the product type and looks in the associated renderers for a block and template to use.
public function getItemHtml(Varien_Object $item)
{
if ($item->getOrderItem()) {
$type = $item->getOrderItem()->getProductType();
} else {
$type = $item->getProductType();
}
return $this->getItemRenderer($type)
->setItem($item)
->setCanEditQty($this->canEditQty())
->toHtml();
}
This method calls getItemRenderer that looks if there is a block and a template associated to the product type. If there is it uses them. If not it uses the block and template marked as default.
The method is somehow similar to adding a child block to a parent block, but it's some kind of conditional child block. You have have multiple renderers associated to the parent block, but only one is used depending on what you are printing. And the renderer can be used multiple times. Each time a product of the same tipe is shown, the associated renderer is used.
| {
"pile_set_name": "StackExchange"
} |
Q:
omnisharp with asp.net core 1.1 app
I'm trying to get code completion for a asp.net core 1.1 app in vi (neovim)
Here is the omnisharp server + vim plugin:
https://github.com/OmniSharp/Omnisharp-vim
In my .vimrc I added this:
Plug 'OmniSharp/omnisharp-vim'
let g:OmniSharp_server_type = 'roslyn'
(I think I need roslyn for .net core?)
I also cloned and compiled the omnisharp roslyn server without errors.
But when I start OmniSharp, I get this error:
/.local/share/nvim/plugged/omnisharp-vim/omnisharp-roslyn> ./artifacts/scripts/OmniSharp
OmniSharp:
System.DllNotFoundException: System.Native
at (wrapper managed-to-native) Interop+Sys:GetUnixNamePrivate ()
at Interop+Sys.GetUnixName () [0x00000] in <2c0705c248b844f597694acdb70b3a23>:0
at System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform (System.Runtime.InteropServices.OSPlatform osPlatform) [0x00009] in <2c0705c248b844f597694acdb70b3a23>:0
at Microsoft.Extensions.Logging.Console.ConsoleLogger..ctor (System.String name, System.Func`3[T1,T2,TResult] filter, System.Boolean includeScopes) [0x00051] in <e9a418d09ae748d6a3f11d651b9e1106>:0
at Microsoft.Extensions.Logging.Console.ConsoleLoggerProvider.CreateLoggerImplementation (System.String name) [0x00019] in <e9a418d09ae748d6a3f11d651b9e1106>:0
at System.Collections.Concurrent.ConcurrentDictionary`2[TKey,TValue].GetOrAdd (TKey key, System.Func`2[T,TResult] valueFactory) [0x00034] in <a33fd236349b4603bef9951b0ab37965>:0
at Microsoft.Extensions.Logging.Console.ConsoleLoggerProvider.CreateLogger (System.String name) [0x00000] in <e9a418d09ae748d6a3f11d651b9e1106>:0
at Microsoft.Extensions.Logging.Logger.AddProvider (Microsoft.Extensions.Logging.ILoggerProvider provider) [0x00000] in <6ac0afe55b53462283fd4e4f8f1658ac>:0
at Microsoft.Extensions.Logging.LoggerFactory.AddProvider (Microsoft.Extensions.Logging.ILoggerProvider provider) [0x00061] in <6ac0afe55b53462283fd4e4f8f1658ac>:0
at Microsoft.Extensions.Logging.ConsoleLoggerExtensions.AddConsole (Microsoft.Extensions.Logging.ILoggerFactory factory, System.Func`3[T1,T2,TResult] filter, System.Boolean includeScopes) [0x00008] in <e9a418d09ae748d6a3f11d651b9e1106>:0
at Microsoft.Extensions.Logging.ConsoleLoggerExtensions.AddConsole (Microsoft.Extensions.Logging.ILoggerFactory factory, System.Func`3[T1,T2,TResult] filter) [0x00000] in <e9a418d09ae748d6a3f11d651b9e1106>:0
at OmniSharp.Startup.Configure (Microsoft.AspNetCore.Builder.IApplicationBuilder app, System.IServiceProvider serviceProvider, Microsoft.Extensions.Logging.ILoggerFactory loggerFactory, OmniSharp.Stdio.Services.ISharedTextWriter writer, OmniSharp.Services.IAssemblyLoader loader, Microsoft.Extensions.Options.IOptionsMonitor`1[TOptions] options) [0x00032] in <8853ad029e4d47c0b478044425f4b3a3>:0
at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&)
at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00032] in <a33fd236349b4603bef9951b0ab37965>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <a33fd236349b4603bef9951b0ab37965>:0
at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure (Microsoft.AspNetCore.Builder.IApplicationBuilder app) [0x00027] in <24af31b64ae843689736582353a19b3a>:0
at Microsoft.AspNetCore.Hosting.Internal.AutoRequestServicesStartupFilter+<>c__DisplayClass0_0.<Configure>b__0 (Microsoft.AspNetCore.Builder.IApplicationBuilder builder) [0x0000d] in <24af31b64ae843689736582353a19b3a>:0
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication () [0x00080] in <24af31b64ae843689736582353a19b3a>:0
at Microsoft.AspNetCore.Hosting.Internal.WebHost.Initialize () [0x00008] in <24af31b64ae843689736582353a19b3a>:0
at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build () [0x0008a] in <24af31b64ae843689736582353a19b3a>:0
at OmniSharp.Program+<>c__DisplayClass1_0.<Run>b__1 () [0x00196] in <8853ad029e4d47c0b478044425f4b3a3>:0
at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute (System.String[] args) [0x0035b] in <e56ebbc3ed87488b8e26736bbadaa5d3>:0
at OmniSharp.Program.Run (System.String[] args) [0x001ae] in <8853ad029e4d47c0b478044425f4b3a3>:0
at OmniSharp.Program.Main (System.String[] args) [0x0001c] in <8853ad029e4d47c0b478044425f4b3a3>:0
Here is some version information:
~> dotnet --info
.NET Command Line Tools (1.0.4)
Product Information:
Version: 1.0.4
Commit SHA-1 hash: af1e6684fd
Runtime Environment:
OS Name: Mac OS X
OS Version: 10.12
OS Platform: Darwin
RID: osx.10.12-x64
Base Path: /usr/local/share/dotnet/sdk/1.0.4
~> mono --version
Mono JIT compiler version 5.2.0.209 (2017-04/3d531ba Mon Jul 3 12:16:03 EDT 2017)
Copyright (C) 2002-2014 Novell, Inc, Xamarin Inc and Contributors. www.mono-project.com
TLS: normal
SIGSEGV: altstack
Notification: kqueue
Architecture: amd64
Disabled: none
Misc: softdebug
LLVM: yes(3.6.0svn-mono-master/8b1520c)
GC: sgen (concurrent by default)
~>
Why do I even need Mono? Isn't dotnet core enough?
Does dotnet core only works with Roslyn?
What does vscode uses for c# completion? Roslyn?
What could be the problem here?
UPDATE:
I did a publish from the roslyn folder (~/.local/share/nvim/plugged/omnisharp-vim/omnisharp-roslyn) like this: 'dotnet publish -c Release -f netcoreapp1.1'
Then I copied the files from the publish folder (~/.local/share/nvim/plugged/omnisharp-vim/omnisharp-roslyn/artifacts/publish/OmniSharp/default/netcoreapp1.1) to the scripts folder (~/.local/share/nvim/plugged/omnisharp-vim/omnisharp-roslyn/artifacts/scripts).
Not sure if this is the correct solution, but it seems to work.
UPDATE 2:
In the end I just downloaded a release from here: https://github.com/OmniSharp/omnisharp-roslyn/releases
I then changed omnisharp-vim/omnisharp-roslyn/artifacts/scripts/OmniSharp to something like this:
#!/bin/bash
"/<path>/omnisharp-vim/omnisharp-osx-x64-netcoreapp1.1/Omnisharp" "$@"
Now it works
A:
Usually the System.DllNotFoundException: System.Native exception happens because you have just copied the compilation folder, that's wrong, you must publish the app and then use the files from that folder, there will be all the libraries the app needs to run.
| {
"pile_set_name": "StackExchange"
} |
Q:
ClickOnce custom prerequisite problem with installation
I have created custom prerequisite setup project for ClickOnce and it is among the other prerequisites in publish tab of the project. But when i try to install my app via ClickOnce(with setup button) it runs prerequisite setup, and asks if i want to install it. I click "install" and the following error appears:
The following package files could not
be found:
C:\Users\..\AppData\Local\Microsoft\Windows\Temporary
Internet
Files\Content.IE5\U2R49322\FontPrerequisite\setupfont.msi
When i launch the application-it installs it, but without prerequisite. What can cause the problem?
A:
This is a wild guess, but I would assume that you've specified that the user should download the prerequisite from the vendors site. Open the Prerequisites dialog and select your prerequisite. Click on the option that states Download prerequisite from the same location as my application. (See the screen shot below)
This should bundle your prereq with your application deployment. Hope that helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I display text on button click in React.js
Have this code (below) and am trying to display the text at the click of a button in React.js.
Heres the code:
class App extends Component{
render(){
alert=()=>{return(<h1>Hi</h1>)}
return(<div className="App">
<button onClick={this.alert}>Enter</button>
</div>);
}}
export default App;
Any ideas why it's not working...?
A:
If you want to display it in an alert window, you need to call a function to trigger the window.
class App extends Component{
onButtonClickHandler = () => {
window.alert('Hi')
};
render(){
return(<div className="App">
<button onClick={this.onButtonClickHandler}>Enter</button>
</div>);
}
}
However, if you need to show the message in your render, you can use a state to manage that.
class App extends Component{
state = {
showMessage: false
}
onButtonClickHandler = () => {
this.setState({showMessage: true});
};
render(){
return(<div className="App">
{this.state.showMessage && <p>Hi</p>}
<button onClick={this.onButtonClickHandler}>Enter</button>
</div>);
}
}
Source code:
If you need to toggle the text on button click, you just need to update the onButtonClickHandler function to this.setState({ showMessage: !this.state.showMessage });.
| {
"pile_set_name": "StackExchange"
} |
Q:
Error inserting into PostgreSQL time type using JDBC
I have a table with a "time without time zone" data type in a postgres database and I'm getting a syntax error when trying to insert using prepared statements. I've tried creating a new java.sql.Time object rather than using inputs from a web page and I am still getting the same error. What am I doing wrong?
Error:
org.postgresql.util.PSQLException: ERROR: invalid input syntax for type time: "1970-01-01 +01:00:00"
Table:
Table "public.reservation"
Column | Type | Modifiers
------------+------------------------+--------------------------------------------------------------
res_id | integer | not null default nextval('reservation_res_id_seq'::regclass)
cust_id | character varying(50) | not null
date | date | not null
time | time without time zone | not null
num_people | integer | not null
Indexes:
"reservation_pkey" PRIMARY KEY, btree (res_id)
Foreign-key constraints:
"reservation_cust_id_fkey" FOREIGN KEY (cust_id) REFERENCES customer(cust_id)
Referenced by:
TABLE "reservation_table" CONSTRAINT "reservation_table_res_id_fkey" FOREIGN KEY (res_id) REFERENCES reservation(res_id)
Reservation Java:
public static boolean createReservation(String custID, Date date, Time time, int numPeople) throws ServletException {
//TODO add checking
//TODO need to add determing table and if reservation time is free
boolean succeeded = false;
//checks if reservation is possible to be booked
if(checkReservationPossible()){
//convet date to correct format for database
//SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy/MM/dd");
//String formattedDate = dateFormatter.format(date);
//convert time to correct format for database
//SimpleDateFormat timeFormatter = new SimpleDateFormat("HH:mm");
//String formattedTime = timeFormatter.format(time);
DatabaseAccess db = new DatabaseAccess();
String sql = "INSERT INTO reservation (cust_id, date, time, num_people)"
+ "VALUES (?,?,?,?)";
LinkedList<Object> params = new LinkedList<Object>();
params.add(custID);
params.add(date);
params.add(time);
params.add(numPeople);
succeeded = db.runUpdateQuery(sql,params);
db.close();
}
return succeeded;
}
DB Access Java:
public boolean runUpdateQuery(String sql, LinkedList<Object> params) throws ServletException
{
// Using try {...} catch {...} for error control
try{
// Create a statement variable to be used for the sql query
//Statement statement = this.connection.createStatement();
// Perform the update
PreparedStatement pst = this.connection.prepareStatement(sql);
Iterator iter = params.iterator();
for(int i = 1;iter.hasNext(); i++){
Object curr = iter.next();
//TODO may need to add more for different types
if(curr instanceof String){
pst.setString(i, curr.toString());
}else if (curr instanceof Integer){
pst.setInt(i, (Integer)curr);
}else if (curr instanceof java.util.Date){
//convert to sql date
java.util.Date tempDate = (java.util.Date)curr;
java.sql.Date sqlDate = new java.sql.Date(tempDate.getTime());
pst.setDate(i, sqlDate);
}else if (curr instanceof Time){
pst.setTime(i, Time.valueOf("11:30:00"));
}
}
int numRows = pst.executeUpdate();
pst.close();
if(numRows > 0){
return true;
}else{
return false;
}
} catch (SQLException e){
// Deal with the error if it happens
throw new ServletException(String.format("Error: Problem running query... "), e);
}
}
A:
You don't need all that checking. I recommend you change you code to simply this:
for (int i = 1; iter.hasNext(); i++) {
Object curr = iter.next();
pst.setObject(i, curr);
}
JDBC knows what to do with all the various usual java types - no need to convert.
The only time you need to check the type is if you want to use some custom class and you want to get some JDBC compliant type from it. This is not the case here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Mongodb query to find element value type of nested array or object in a field
I have mongodb data model where I have some array fields that contain embedded objects or arrays. I have some inconsistencies in the field in question because I've tweaked my application logic. Initially, my model looked like this:
Initial Setup of Results collection
"competition" : "competition1",
"stats" : [
{
"stat1" : [],
"stat2" : []
}
]
However, I saw that this wasn't the best setup for my needs. So I changed it to the following:
New Setup of Results collection
"competition" : "competition1",
"stats" : [
{
"stat1" : 3,
"stat2" : 2
}
]
My problem now is that documents that have the initial setup cause an error. So what I want is to find all documents that have the initial setup and convert them to have the new setup.
How can I accomplish this in mongodb?
Here is what I've tried, but I'm stuck...
db.getCollection('results').find({"stats.0": { "$exists": true }})
But what I want is to be able to do something like
db.getCollection('results').find({"stats.0".stat1: { "$type": Array}})
Basically I want to get documents where the value of stats[0].stat1 is of type array and override the entire stats field to be an empty array.
This would fix the errors I'm getting.
A:
$type operator for arrays in older versions works little differently than what you might think than $type in 3.6.
This will work in 3.6
db.getCollection('results').find( { "stats.0.stat1" : { $type: "array" } } )
You can do it couple of ways for lower versions and It depends what you are looking for.
For empty arrays you can just check
{"stats.0.stat1":{$size:0}}
For non empty arrays
{"stats.0.stat1": {$elemMatch:{ "$exists": true }}}
Combine both using $or for finding both empty and non empty array.
For your use case you can use below update
db.getCollection('results').update({"stats.0.stat1":{$size:0}}, {$set:{"stats":[]}})
| {
"pile_set_name": "StackExchange"
} |
Q:
How to Create Multi Auth in Laravel 5.2
I have made multi auth but i have problem with final code. I have code like this
php artisan make:auth
it will generate basic login/register route, view and controller for user table.
Make a admin table as users table for simplicity.
Controller For Admin
app/Http/Controllers/AdminAuth/AuthController
app/Http/Controllers/AdminAuth/PasswordController
(note: I just copied these files from app/Http/Controllers/Auth/AuthController here)
config/auth.php
//Authenticating guards
'guards' => [
'user' =>[
'driver' => 'session',
'provider' => 'user',
],
'admin' => [
'driver' => 'session',
'provider' => 'admin',
],
],
//User Providers
'providers' => [
'user' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admin' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
]
],
//Resetting Password
'passwords' => [
'clients' => [
'provider' => 'client',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
'admins' => [
'provider' => 'admin',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
],
route.php
Route::group(['middleware' => ['web']], function () {
//Login Routes...
Route::get('/admin/login','AdminAuth\AuthController@showLoginForm');
Route::post('/admin/login','AdminAuth\AuthController@login');
Route::get('/admin/logout','AdminAuth\AuthController@logout');
// Registration Routes...
Route::get('admin/register', 'AdminAuth\AuthController@showRegistrationForm');
Route::post('admin/register', 'AdminAuth\AuthController@register');
Route::get('/admin', 'AdminController@index');
});
AdminAuth/AuthController.php
Add two methods and specify $redirectTo and $guard
protected $redirectTo = '/admin';
protected $guard = 'admin';
public function showLoginForm()
{
if (view()->exists('auth.authenticate')) {
return view('auth.authenticate');
}
return view('admin.auth.login');
}
public function showRegistrationForm()
{
return view('admin.auth.register');
}
it will help you to open another login form for admin
creating a middleware for admin
class RedirectIfNotAdmin
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = 'admin')
{
if (!Auth::guard($guard)->check()) {
return redirect('/');
}
return $next($request);
}
}
register middleware in kernel.php
protected $routeMiddleware = [
'admin' => \App\Http\Middleware\RedirectIfNotAdmin::class,
];
use this middleware in AdminController e.g.,
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
class AdminController extends Controller
{
public function __construct(){
$this->middleware('admin');
}
public function index(){
return view('admin.dashboard');
}
}
And what does this code mean Auth::guard('admin')->user() ? And where must i type that code?
A:
And what does this code mean Auth::guard('admin')->user() ?
In simple word, Auth::guard('admin')->user() is used when you need to get details of logged in user. But, in multi auth system, there can be two logged in users (admin/client). So you need to specify that which user you want to get. So by guard('admin'), you tell to get user from admin table.
Where must i type that code?
As from answer, you can understand that where must you use it. But still I can explain with example. Suppose there are multiple admins. Each can approve users request (like post/comments etc). So when an admin approve any request, then to insert id of that admin into approved_by column of post, you must use this line.
| {
"pile_set_name": "StackExchange"
} |
Q:
conditional list indexing in R
The output of strsplit() can be the following:
list( c("a","b") , character(0) , c("a","b") )
or, if assigning the expression to lst:
> lst
[[1]]
[1] "a" "b"
[[2]]
character(0)
[[3]]
[1] "a" "b"
What is the vectorized way to replace the character(0) entry? I'm trying to avoid the following:
for( i in seq(1,length(lst)) ){
if (length(lst[[i]]) == 0) {
lst[[i]] <- "nothing"
}
}
A:
How about:
lst[sapply(lst,identical,character(0))] <- 'nothing'
| {
"pile_set_name": "StackExchange"
} |
Q:
Why this code is not working - sass
This is working perfectly:
.navbar_ind {
background-color: blue;
}
.navbar_ind .nav-link:hover {
color: red;
}
but when I am doing like this it does not work, why?
.navbar_ind {
background-color: blue;
&__nav-link:hover {
color: red;
}
}
A:
You can use & with space ou not use it at all, like this:
.navbar_ind {
background-color: blue;
& .nav-link:hover {
color: red;
}
}
Or like this:
.navbar_ind {
background-color: blue;
.nav-link:hover {
color: red;
}
}
Both should work fine
A:
This:
.navbar_ind {
background-color: blue;
&__nav-link:hover {
color: red;
}
}
will compile to:
.navbar_ind {
background-color: blue;
}
.navbar_ind__nav-link:hover {
color: red;
}
What you need is:
.navbar_ind {
background-color: blue;
// The ampersand selector isn't even needed.
& .nav-link:hover {
color: red;
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Improving Numpy speed for Gauss-Seidel (Jacobi) Solver
This question is a follow-up to a recent question posted regarding MATLAB being twice as fast as Numpy.
I currently have a Gauss-Seidel solver implemented in both MATLAB and Numpy which acts on a 2D axisymmetric domain (cylindrical coordinates). The code was originally written in MATLAB and then transferred to Python. The Matlab code runs in ~20 s whereas the Numpy codes takes ~30 s. I would like to use Numpy, however, since this code is part of a larger program, the almost twice as long simulation time is a significant drawback.
The algorithm simply solves the discretized Laplace equation on a rectangular mesh (in cylindrical coordinates). It finishes when the maximum difference between updates on the mesh is less than the indicated tolerance.
The code in Numpy is:
import numpy as np
import time
T = np.transpose
# geometry
length = 0.008
width = 0.002
# mesh
nz = 256
nr = 64
# step sizes
dz = length/nz
dr = width/nr
# node position matrices
r = np.tile(np.linspace(0,width,nr+1), (nz+1, 1)).T
ri = r/dr
# equation coefficients
cr = dz**2 / (2*(dr**2 + dz**2))
cz = dr**2 / (2*(dr**2 + dz**2))
# initial/boundary conditions
v = np.zeros((nr+1,nz+1))
v[:,0] = 1100
v[:,-1] = 0
v[31:,29:40] = 1000
v[19:,54:65] = -200
# convergence parameters
tol = 1e-4
# Gauss-Seidel solver
tic = time.time()
max_v_diff = 1;
while (max_v_diff > tol):
v_old = v.copy()
# left boundary updates
v[0,1:nz] = cr*2*v[1,1:nz] + cz*(v[0,0:nz-1] + v[0,2:nz+2])
# internal updates
v[1:nr,1:nz] = cr*((1 - 1/(2*ri[1:nr,1:nz]))*v[0:nr-1,1:nz] + (1 + 1/(2*ri[1:nr,1:nz]))*v[2:nr+1,1:nz]) + cz*(v[1:nr,0:nz-1] + v[1:nr,2:nz+1])
# right boundary updates
v[nr,1:nz] = cr*2*v[nr-1,1:nz] + cz*(v[nr,0:nz-1] + v[nr,2:nz+1])
# reapply grid potentials
v[31:,29:40] = 1000
v[19:,54:65] = -200
# check for convergence
v_diff = v - v_old
max_v_diff = np.absolute(v_diff).max()
toc = time.time() - tic
print(toc)
This is actually not the full algorithm which I use. The full algorithm uses successive overrelaxation and a checkerboard iteration scheme to improve speed and remove solver directionality, but for purposes of simplicity I provided this easier to understand version. The speed drawbacks in Numpy are more pronounced for the full version (17s vs. 9s simulation times respectively in Numpy and MATLAB).
I tried the solution from the previous question, changing v to a column-major order array, but there was no performance increase.
Any suggestions?
Edit: The Matlab code for reference is:
% geometry
length = 0.008;
width = 0.002;
% mesh
nz = 256;
nr = 64;
% step sizes
dz = length/nz;
dr = width/nr;
% node position matrices
r = repmat(linspace(0,width,nr+1)', 1, nz+1);
ri = r./dr;
% equation coefficients
cr = dz^2/(2*(dr^2+dz^2));
cz = dr^2/(2*(dr^2+dz^2));
% initial/boundary conditions
v = zeros(nr+1,nz+1);
v(1:nr+1,1) = 1100;
v(1:nr+1,nz+1) = 0;
v(32:nr+1,30:40) = 1000;
v(20:nr+1,55:65) = -200;
% convergence parameters
tol = 1e-4;
max_v_diff = 1;
% Gauss-Seidel Solver
tic
while (max_v_diff > tol)
v_old = v;
% left boundary updates
v(1,2:nz) = cr.*2.*v(2,2:nz) + cz.*( v(1,1:nz-1) + v(1,3:nz+1) );
% internal updates
v(2:nr,2:nz) = cr.*( (1 - 1./(2.*ri(2:nr,2:nz))).*v(1:nr-1,2:nz) + (1 + 1./(2.*ri(2:nr,2:nz))).*v(3:nr+1,2:nz) ) + cz.*( v(2:nr,1:nz-1) + v(2:nr,3:nz+1) );
% right boundary updates
v(nr+1,2:nz) = cr.*2.*v(nr,2:nz) + cz.*( v(nr+1,1:nz-1) + v(nr+1,3:nz+1) );
% reapply grid potentials
v(32:nr+1,30:40) = 1000;
v(20:nr+1,55:65) = -200;
% check for convergence
max_v_diff = max(max(abs(v - v_old)));
end
toc
A:
I've been able to reduce the running time in my laptop from 66 to 21 seconds by following this process:
Find the bottleneck. I profiled the code using line_profiler from the IPython console to find the lines that took most time. It turned out that over 80% of the time was spent in the line that does "internal updates".
Choose a way to optimise it. There are several tools to speed code up in numpy (Cython, numexpr, weave...). In particular, scipy.weave.blitz is well suited to compile numpy expressions, like the offending line, into fast code. In theory, that line could be wrapped inside "..." and executed as weave.blitz("...") but the array that's being updated is used in the computation, so as stated by point #4 in the docs a temporary array must be used to keep the same result:
expr = "temp = cr*((1 - 1/(2*ri[1:nr,1:nz]))*v[0:nr-1,1:nz] + (1 + 1/(2*ri[1:nr,1:nz]))*v[2:nr+1,1:nz]) + cz*(v[1:nr,0:nz-1] + v[1:nr,2:nz+1]); v[1:nr,1:nz] = temp"
temp = np.empty((nr-1, nz-1))
...
while ...
# internal updates
weave.blitz(expr)
After checking that the results are correct, runtime checks are disabled by using weave.blitz(expr, check_size=0). The code now runs in 34 seconds.
Building up on Jaime's work, precompute the constant factors A and B in the expression. The code runs in 21 seconds (with minimal changes but it now needs a compiler).
This is the core of the code:
from scipy import weave
# [...] Set up code till "# Gauss-Seidel solver"
tic = time.time()
max_v_diff = 1;
A = cr * (1 - 1/(2*ri[1:nr,1:nz]))
B = cr * (1 + 1/(2*ri[1:nr,1:nz]))
expr = "temp = A*v[0:nr-1,1:nz] + B*v[2:nr+1,1:nz] + cz*(v[1:nr,0:nz-1] + v[1:nr,2:nz+1]); v[1:nr,1:nz] = temp"
temp = np.empty((nr-1, nz-1))
while (max_v_diff > tol):
v_old = v.copy()
# left boundary updates
v[0,1:nz] = cr*2*v[1,1:nz] + cz*(v[0,0:nz-1] + v[0,2:nz+2])
# internal updates
weave.blitz(expr, check_size=0)
# right boundary updates
v[nr,1:nz] = cr*2*v[nr-1,1:nz] + cz*(v[nr,0:nz-1] + v[nr,2:nz+1])
# reapply grid potentials
v[31:,29:40] = 1000
v[19:,54:65] = -200
# check for convergence
v_diff = v - v_old
max_v_diff = np.absolute(v_diff).max()
toc = time.time() - tic
| {
"pile_set_name": "StackExchange"
} |
Q:
CheckBox Tree Item hide borders
Does anybody know if it is possibile, and how to, hide or do not show CheckBoxTreeItem borders?
I mean the rectangle such as this picture.
A:
You can use the setStyle() method with the -fx-border-color property.
treeView.setStyle("-fx-border-color: white white white white;");
(null instead of white seems to work too)
| {
"pile_set_name": "StackExchange"
} |
Q:
Dynamic password in Inno Setup
I need that my program be protected with a dynamic password that includes the current date.
I need just the month or the day or the hour or the minute.
I tried this code to include the day into the password:
[Setup]
Password=Password!{code:DateTime|0}
[Code]
function DateTime (Param: string): string;
begin
Result := GetDateTimeString('dd', #0, #0);
end;
But it's not working.
Regards.
A:
The Password directive cannot contain any constants, let only scripted constants.
So your script makes the password be literally Password!{code:DateTime|0}.
Instead, use CheckPassword event function:
[Code]
function CheckPassword(Password: String): Boolean;
begin
Result := (Password = ('Password!' + GetDateTimeString('dd', #0, #0)));
end;
Though safer than comparing against a literal string (which can be seen in .exe binary) is comparing a checksum.
See How to do a dynamic password in Inno Setup?
| {
"pile_set_name": "StackExchange"
} |
Q:
Which is better SMS,TCP,UDP for communication purposes on mobile phones?
I am developing an client server application on mobile phone and I would really appreciate to get some comparisons between each of them ..
A:
UDP may be good for streaming audio/video, but I'd expect packet loss or reordering in the context of a mobile phone. In A/V applications you can often get away with this, but if you need data integrity and packet transmission confirmation, you'll have to use TCP or SMS.
TCP coordinates packet sequencing and ensures that all data are received in-order uncorrupted. If you can, use a higher-level protocol like HTTP (which usually runs over TCP) so that you can use existing libraries, and avoid the hassle of sockets programming. TCP is subject to higher latencies than UDP, as it requires the client to send back packet confirmations; however, since you're already working from a phone, I'd expect the increased reliability to be well-worth the cost in latency. TCP is the norm for client-server applications.
SMS is great for intrusive text alerts, but I don't believe it can even carry a binary payload reliably, packet length limitation is low, I'm not sure what kind of latency you can expect, and I don't know if any integration options are available if you were to ever want to port your application to anything but a cell phone. SMS was not designed for general-purpose internet communications; I'd avoid it unless you have good reason.
| {
"pile_set_name": "StackExchange"
} |
Q:
What am I doing wrong loading a .txt file?
try (BufferedReader br = new BufferedReader(new FileReader("Templates/format/test.txt")))
{
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine.toString().trim());
if(sCurrentLine.toString().trim().equalsIgnoreCase("Test2")){
System.out.println("HI: "+sCurrentLine.toString().trim());
}
}
} catch (IOException e) {
e.printStackTrace();
}
I'm trying the get the contents of a .txt but neither
if(sCurrentLine.toString().trim().equalsIgnoreCase("Test2")){
System.out.println("HI: "+sCurrentLine.toString().trim());
}
or
if(sCurrentLine.toString().trim().equals("Test2")){
System.out.println("HI: "+sCurrentLine.toString().trim());
}
works.
This is the content of the txt:
Text1
Text2
Text3
I also don't understand why this: System.out.println(sCurrentLine.toString().trim()); leads to the following output in the console. Why do I get breaks and the Symbol at the beginning?
þÿ T e s t 1
T e s t 2
T e s t 3
Thanks for helping me out here!
A:
Convert your .txt file to UTF-8 without BOM. You can do that with Notepad++ or any other advanced text editor.
| {
"pile_set_name": "StackExchange"
} |
Q:
Wifi connection slows down when bluetooth speaker is connected
I have a 20mb/s wifi connection and it works properly unless I connect my bluetooth speaker. when I do that the wifi connection slows down and poorly work. I've already tryed this solution and this other one
but none of that worked. I'm running a Ubuntu 16.04 on a Dell Inspiron 14300.
The outputs for lspci -knn | grep Net -A2 are:
06:00.0 Network controller [0280]: Qualcomm Atheros QCA9565 / AR9565 Wireless Network Adapter [168c:0036] (rev 01)
Subsystem: Dell QCA9565 / AR9565 Wireless Network Adapter [1028:020c]
Kernel driver in use: ath9k
Kernel modules: ath9k
And also, the outputs for lsusb are:
Bus 001 Device 006: ID 0bda:0129 Realtek Semiconductor Corp. RTS5129 Card Reader Controller
Bus 001 Device 007: ID 0cf3:0036 Atheros Communications, Inc.
Bus 001 Device 004: ID 0bda:5756 Realtek Semiconductor Corp.
Bus 001 Device 003: ID 062a:4102 Creative Labs
Bus 001 Device 002: ID 8087:8000 Intel Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 003 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
I don't know what else I can do to fix it.
A:
You can enable BT coexistence in the ath9k module.
Run in a terminal
sudo tee /etc/modprobe.d/ath9k.conf <<< "options ath9k btcoex_enable=1"
and reboot.
This helps in most cases. The ath9k BT coex algorithm is good. It is a shame that it isn't enabled by default yet.
| {
"pile_set_name": "StackExchange"
} |
Q:
Easy clarification for the question 'show that $x^3-2x^2+6x+6$ is irreducible in $\mathbb{Z}[x]$'
I successfully completed this question by showing it was irreducible in $\mathbb{Z}_5$. I showed this by putting each of the elements of $\mathbb{Z}_5$ into the polynomial.
My question is this: in the mark scheme, they checked $f(1)$,$f(2)$,$f(4)$ and $f(5)$, but didn't bother checking $f(3)$, (if we call the polynomial $f(x)$). Do you think this was a mistake or is there some reason that $f(3)$ doesn't need to be checked?
It's a minor confusion, but one that I would like to understand if there is anything to be understood about it. I hope I'm not overlooking something obvious.
Thanks
A:
It looks like a mistake and $f(3)$ should be checked. Thanks to Quasi
| {
"pile_set_name": "StackExchange"
} |
Q:
How can get a count with nested objects with a certain property?
Okay so I'm using angular to get a json saved to my computer to recreate a github gradebook.
I can get the data with my $http request but for the love of me all I want is to get a count of the number of issues with the label "Not Yet".
Here is the javascript:
$http.get('/api/github/repos/issues/all_issues/00All.json')
.then(function(response) {
console.log(response.data[0]);
var counter = 0;
for(var index = 0; index < response.data.length; index++) {
if(response.data[index].labels[0].name == "Not Yet") {
counter++;
};
};
console.log(counter);
});
That's the latest try, I also tried using lodash to get it earlier:
$http.get('/api/github/repos/issues/all_issues/00All.json')
.then(function(response) {
console.log(response);
mile.notYet.width = _.forEach(response.data, function(n){
var counter = 0;
if(_.result(_.find(n.labels[0], 'name')) == "Not Yet") {
counter++;
}
console.log(counter);
counter = ((counter/10) * 100) + '%';
});
});
This is a bit of the json data:
[
{
"url": "https://api.github.com/repos/TheIronYard--Orlando/2015--SUMMER--FEE/issues/11",
"labels_url": "https://api.github.com/repos/TheIronYard--Orlando/2015--SUMMER--FEE/issues/11/labels{/name}",
"comments_url": "https://api.github.com/repos/TheIronYard--Orlando/2015--SUMMER--FEE/issues/11/comments",
"events_url": "https://api.github.com/repos/TheIronYard--Orlando/2015--SUMMER--FEE/issues/11/events",
"html_url": "https://github.com/TheIronYard--Orlando/2015--SUMMER--FEE/issues/11",
"id": 73013825,
"number": 11,
"title": "00 -- Brace Yourself -- BEN GRIFFITH",
"user": {
"login": "Epicurean306",
"id": 11682684,
"avatar_url": "https://avatars.githubusercontent.com/u/11682684?v=3",
"gravatar_id": "",
"url": "https://api.github.com/users/Epicurean306",
"html_url": "https://github.com/Epicurean306",
"followers_url": "https://api.github.com/users/Epicurean306/followers",
"following_url": "https://api.github.com/users/Epicurean306/following{/other_user}",
"gists_url": "https://api.github.com/users/Epicurean306/gists{/gist_id}",
"starred_url": "https://api.github.com/users/Epicurean306/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/Epicurean306/subscriptions",
"organizations_url": "https://api.github.com/users/Epicurean306/orgs",
"repos_url": "https://api.github.com/users/Epicurean306/repos",
"events_url": "https://api.github.com/users/Epicurean306/events{/privacy}",
"received_events_url": "https://api.github.com/users/Epicurean306/received_events",
"type": "User",
"site_admin": false
},
"labels": [
{
"url": "https://api.github.com/repos/TheIronYard--Orlando/2015--SUMMER--FEE/labels/Not%20Yet",
"name": "Not Yet",
"color": "e11d21"
}
],
As you can see the labels property is an object, nested in an array, nested in an object, nested in an array, real lovely. Putting labels[0] results in an error for me each time and doesn't get me a count. Can anybody tell me where I'm messing up please? Thank you!
A:
If you need a solution that includes lodash, which is much more performant than the native high order functions then you can try this solution below:
var size = _(response.data)
.pluck('labels')
.flatten()
.where({ name: 'Not Yet' })
.size();
UPDATE:
If you want it to be more reusable, you can save a reference for a cloned chained sequence and simply supply another array for that cloned sequence.
var data1 = [/*array from data1*/];
var data2 = [/*array from data2*/];
var notYetSequence = _(data1)
.pluck('labels')
.flatten()
.where({ name: 'Not Yet' });
notYetSequence.size(); // returns data 1 count
notYetSequence.plant(data2).size(); // returns data 2 count
| {
"pile_set_name": "StackExchange"
} |
Q:
Frequency Response of 1st Order circuit
I am having a bit of trouble trying to figure this out. The equation I come up with keeps canceling Omega out.
$$Attempt$$
Converting the circuit to the frequency domain the capacitor becomes \$\frac{4}{j\omega}\$
I then used a current divider to find \$\underline y(j\omega)\$ = \$\underline u(j\omega)\$ 6 \$\frac{2+\frac{4}{j\omega}}{6+(2+\frac{4}{j\omega})}\$
Final Equation: \$\frac{12+\frac{24}{j\omega}}{8+\frac{4}{j\omega}}\$ = \$\frac{3x+6}{2x + 1}\$
Simplifying this I get the frequency response to be \$\frac{1}{2}\$. I am fairly certain that his is not correct.
A:
a)
Your start equation is missing a factor 6, which is the value of the resistor.
The frequency response would then be:
$$
G(S)=\frac{Y(S)}{U(S)}=\frac{3.(S+2)}{2.S+1}
$$
b)When the the frequency is zero the cap is an open circuit and the resulting gain should be 6, which is the value of the the resisor is parallel with the source.
When the frequency approaches infinity, the cap is a short circuit and the gain should be the parallel combination of the two resistor. That would be 12/8, you will reach the same value after calculating the limit with S-->infinity of the equation above.
| {
"pile_set_name": "StackExchange"
} |
Q:
Does $S_P \geq S_{NG}$ hold off-shell?
I know that, on-shell, the Polyakov action $S_\text{P}$ is equivalent to the Nambu-Goto action $S_\text{NG}$.
What about off-shell? In the literature, I saw that $S_\text{P} \geq S_\text{NG}$ holds off-shell. I want to prove this but have no clue. Any comments and references are welcome.
A:
The equations of motion are the Euler-Lagrange equations of the action functional. We have that
$$ S_\text{P}(X,h_c) = S_\text{NG}(X),$$
where $h_c$ is the solution to the equation of motion of the worldsheet metric, and we know that $S_\text{P}(X,h_c)$ is a stationary point of $S_\text{P}$ in the space of all possible $h$s since the E-L equations are just the equations for stationary points in field space.
If you now examine small perturbations around $h_c$ and you find that $S_\text{P}(X,h_c + \delta h) \geq S_\text{P}(X,h_c)$, then the stationary point is a minimum, and therefore
$$ S_\text{P}(X,h)\geq S_\text{P}(X,h_c) = S_\text{NG}(X).$$
| {
"pile_set_name": "StackExchange"
} |
Q:
What should I do with the 6-character minimum for edits?
I know quite a few posts with small mistakes involving less than 6 characters, but I can't correct them without some more changes in the post, because that "at least 6 characters changed" limit.
What to do with it? I can make some invisible changes in addition to the correction, but I'd be happy to know official Christianity.SE policy about this. Would something like this (click "edit" to read invisible text here) be OK? Is there any better option? Or can I consider it a "Christianity.SE low-ranking editor's marginal edit policy"?
A:
It's annoying and silly. Often, if you look, there'll be something else to fix. If there isn't, you could leave a comment to the post author pointing out the error and encouraging them to fix it. Mason Wheeler suggests flagging it for moderator attention, which wouldn't have occurred to me, but he's a moderator himself so he should know what he's talking about.
A:
Be creative. Find something else to fix while you have it open. I have rarely seen a post that couldn't use at least 6 characters of touch up. Maybe they didn't link a verse or format a quote. Maybe they took a grammar shortcut you can expand on for a cleaner read.
If you really can't think of anything or don't have the time, leave a comment for the original OP to fix. Not only will the OP get notified of the comment, but any 2k+ user who comes along afterwards will have the chance to fix the mistake as well since they don't have the 6 character edit limit. Note that whoever makes the fix should then flag the comment as obsolete so it gets removed and doesn't waste future readers' time.
A:
Moderators are able to make very minor edits. If you see a problem that's too small for you to edit, you can flag it as "Other" and explain the issue, and one of us can review it and make the edit.
| {
"pile_set_name": "StackExchange"
} |
Q:
Purifying a text string in python
This a continuation of this question. I have this string;
s = 'A ligeira raposa marrom ataca o cão preguiçoso Быстрая коричневая лиса прыгает через ленивую собаку +='
I would like to keep the Russian letters and remove the rest. Hence, I would like to get the all the possible letters in the Portuguese alphabet so that I could apply it for any line.
My question is it possible to get all possible letters of a certain language from a website? or directly from the computer itself. Whatever is easier.
Thanks & Best Regards
Michael
A:
Python's tools for dealing with Unicode feature the unicodedata module - which have some tools to deal with this.
Testing things on a "character by character" basis, and trying to check for all possible combinations of accented latin letters in an "if_esque" structure not only look and feels bad: it is a bad approach.
One of the most basic tools for dealing with unicode is getting the character names itself - all Latin letters do have "LATIN" in their name, and all cyrillic characters do have "CYRILLIC" in their name.
In [1]: import unicodedata
In [2]: unicodedata.name("ã")
Out[2]: 'LATIN SMALL LETTER A WITH TILDE'
In [3]: unicodedata.name("ы")
Out[3]: 'CYRILLIC SMALL LETTER YERU'
Your strategy will vary if you want to keep whitespace, digits, and so on - but basically, if you want to remove all non cyrillic characters:
In [7]: s = 'A ligeira raposa marrom ataca o cão preguiçoso Быстрая коричневая лиса прыгает через ленивую собаку +='
...:
In [8]: print(''.join(char for char in s if 'CYRILLIC' in unicodedata.name(char)))
Быстраякоричневаялисапрыгаетчерезленивуюсобаку
And conversely, if you want to keep everything and remove all latin characters:
In [9]: print(''.join(char for char in s if 'LATIN' not in unicodedata.name(char)))
Быстрая коричневая лиса прыгает через ленивую собаку +=
With that information alone, it is possible to achieve your objective - although there is more unicode metadata in characters than their name, like their "category". If you need to
refine your filters, unicodedata.category(...) will return a two-character code
for a character category. All letters (regardless of alphabet) will have "L" in
the first position of that code, for example:
In [10]: unicodedata.category("a")
Out[10]: 'Ll'
In [11]: unicodedata.category("ã")
Out[11]: 'Ll'
In [12]: unicodedata.category("л")
Out[12]: 'Ll'
In [13]: unicodedata.category("A")
Out[13]: 'Lu'
In [14]: unicodedata.category("2")
Out[14]: 'Nd'
| {
"pile_set_name": "StackExchange"
} |
Q:
Does the constant on an LFSR primitive polynomial hold any significance?
For the following internal feedback LFSR defined by the primitive polynomial: $$X^3 + X + 1$$ Does the constant at the end do anything to either its pseudo-random number generation sequence or to its structure? For example, if the constant at the end was a zero?
A:
Comments clarified. X to the power of 0 is always 1 - so for a primitive polynomial, there is always a +1 attached.
| {
"pile_set_name": "StackExchange"
} |
Q:
XPM Session Storage configuration for JNDI
I can use a JNDI name in my storage_conf.xml file for the standard content delivery database, but. This is great as we can create a single storage file that is used in all environments and remains part of the same deployment package.
We'd seen that this doesn't work when configuring a <storage> element within a <Wrapper> (the new nodes for session preview)
<Wrappers>
<Wrapper Name="SessionWrapper">
<storage />
</Wrapper>
</Wrappers>
we believe that SDL Tridion doesn't support a JNDI name at the moment for this format, which is something I will confirm with SDL Tridion support. In the event this is indeed not supported, I was wondering what work arounds the community has made in an attempt to create a single deployment package (war file) that can be used in all SDL Tridion environments.
A:
JNDI cannot currently be used for "storage wrappers" as you state, so the solution is not very easy - unless all your environments are using the same wrapper database - which is not such a crazy thing, after all this database only has temporary data in it.
The way I'm dealing with it right now is with post-deployment scripts that modify ##variables## in the cd_*_conf.xml files. Not elegant, but effective.
| {
"pile_set_name": "StackExchange"
} |
Q:
Как узнать ID формы из элемента находящегося в ней?
Всем привет.
Собственно, вопрос в заголовке.
Сейчас у меня так
$(elem).get(0).form.id;
В elem указано id Поля формы.
Но вот если туда подставляю ID не поля, а дива, то мне не находит id формы.
Каким образом можно получать id формы из любого ее элемента, если есть только его id?
У меня несколько форм, которые работают с одним и тем же JS скриптом.
Т.е. фактически там различия могут быть только в ID формы, а могут и быть разные поля, а может быть вообще все одинаковое.
Каждое поле формы, если было изменено, то срабатывает onclick, который отсылает ID поля в обработчик. И вот по этому ID нужно получать ID той формы в которой этот onclick сработал.
Но есть элементы, где мне нужно НЕ id поля, а ID дива отправить. И вот тут не могу понять как сделать.
Буду благодарен за помощь.
A:
Можно найти ближайший родительский элемент с помощью .closest() и получить его ID с помощью .attr():
var formId = $(elem).closest('form').attr('id');
| {
"pile_set_name": "StackExchange"
} |
Q:
Generating PDF file with Ionic framework
Is there any plugin for Ionic framework to generate a pdf file using html content?
Basically I need to create a html with values passed from an Ionic mobile application and some css styles, and then convert it into a pdf file which can be saved inside the local file system in a device (Android device and iOS device). I want to do this with a javascript like library so that it can be used in both Android and iOS devices.
A:
Alright, this is a more detailed answer that provides the example I mentioned in my first answer. I have a repo on github:
https://github.com/jeffleus/ionic-pdf
and an online github.io example:
https://jeffleus.github.io/ionic-pdf/www/#/.
First off, I created a ReportBuilderSvc that is used to generate the actual report declaration in the JSON format used by pdfMake.org. This process will be application specific, so I generated this as a separate service. You can view my example code and play around w/your own document definition on the pdfMake.org website. Once you have a report design, place your own document definition JSON in the _generateReport method.
Then, I wrapped the pdfMake.org library in a complimentary angular service, named ReportSvc. This calls the public generateReport() method of the ReportBuilderSvc to get the reportDefinition JSON. I broke the process of generating the report into $q promise-wrapped internal methods to allow the service to emit progress events that the client can consume for updating the UI. On older/slower iPhone 4 devices I saw the report process take as much as 30-45 sec. This ability to update the UI is really important, otherwise the app looks like it has frozen.
The wrapper breaks the process into:
generateReportDef --> in: ReportBuilderSvc out: JSON rpt object
generateReportDoc --> in: JSON doc def out: pdfDoc object
generateReportBuffer --> in: pdfDoc object out: buffer[]
generateReportBlob --> in: buffer[] out: Blob object
saveFile --> in: Blob object out: filePath of report
At each step the service broadcasts an event on the $rootScope using an internal utility function:
function showLoading(msg) {
$rootScope.$broadcast('ReportSvc::Progress', msg);
}
This allows clients to 'subscribe' in the controller or consuming code with:
$scope.$on('ReportSvc::Progress', function(event, msg) {
_showLoading(msg);
});
And finally, to display the pdf, I use an iframe and set the src w/ the generated dataURI for the online demo in the browser. And, I use the InAppBrowser and the local file created when run on the device or emulator. I plan to clean this up a little more so that it can be included as a library and injected as an angular service. This will leave the client free to attend to the report declaration w/ a safely wrapped angular/ionic service.
Any thoughts are appreciated as I am new to the node, angular, ionic world and can definitely use help too...
| {
"pile_set_name": "StackExchange"
} |
Q:
write a jpeg with libjpeg (seg fault)
Trying to write a jpeg file from some raw data using libjpeg.
It triggers a Segmentation Fault in jpeg_start_compress()
Here is the relevant part of the code :
void write_sub_image(char *filename, int start, int end)
{
struct jpeg_compress_struct cinfo;
unsigned char *stride;
JSAMPROW row_pointer[1];
unsigned long new_width = end-start;
int i;
FILE *fp;
stride = (unsigned char *)malloc( new_width * 3);
fp = fopen(filename, "w+");
jpeg_create_compress(&cinfo);
jpeg_stdio_dest(&cinfo, fp);
cinfo.image_width = new_width;
cinfo.image_height = height;
cinfo.input_components = 3;
cinfo.in_color_space = JCS_RGB;
jpeg_set_defaults(&cinfo);
jpeg_start_compress(&cinfo, FALSE);
for (i=0; i<height; i++) {
memcpy (stride, image + (start + i * width) * 3, new_width * 3);
row_pointer[0] = stride;
jpeg_write_scanlines(&cinfo, &stride, 1);
}
jpeg_finish_compress(&cinfo);
jpeg_destroy_compress(&cinfo);
fclose(fp);
}
The problem is not with the memcpy, it does not even get to the for loop... just crash at _start_compress.
In case that is relevant, the system is Ubuntu 10.10.
A:
You need to set an error manager:
struct jpeg_error_mgr jerr;
....
cinfo.err = jpeg_std_error(&jerr);
jpeg_set_defaults(&cinfo);
....
| {
"pile_set_name": "StackExchange"
} |
Q:
What does 'trout-shouldered' mean?
In an episode of the television show Archer one character refers to another as being "trout-shouldered."
“This pathetic, trout-shouldered excuse for a boom operator is Chet Manly."
What might this phrase mean?
A:
'Trout-shouldered' presumably means
having shoulders like a trout.
This probably means that the writer is implying that person so labeled doesn't have very strong shoulders and so is somewhat weak. This is implying not physical weakness but metaphorical weakness of character.
It is not a set-phrase or idiom meaning something outside of its implications.
| {
"pile_set_name": "StackExchange"
} |
Q:
Uploading an image to a file storing details in database but it overwrites the image already uploaded
I have been working on an image uploader to upload an image to a file saving the details in the database, the problem is after I upload one image the next time I upload an image it overwrites the current uploaded image. Also I was trying to store the new image with the new image name but it appears to just store it as '.jpg'. Here is my process code;
<?php
//Parser for Add Photo Form
if (isset($_POST["subject"], $_POST["content"], $_POST["imageName"])){
$subject = mysqli_real_escape_string ($con, ($_POST["subject"]));
$content = mysqli_real_escape_string ($con, ($_POST["content"]));
$imageName = mysqli_real_escape_string ($con, ($_POST["imageName"]));
$latitude = mysqli_real_escape_string ($con, ($_POST["latitude"]));
$longitude = mysqli_real_escape_string ($con, ($_POST["longitude"]));
//add photo to db
$sql = mysqli_query($con, "
INSERT INTO
Blog (
subject,
content,
imageName,
latitude,
longitude,
datetime
)VALUES(
'$subject',
'$content',
'$imageName',
'$latitude',
'$longitude',
NOW())")
or die(mysqli_error($con));
$pid = mysqli_insert_id();
$newName = "$pid.jpg";
move_uploaded_file($_FILES['fileField']['tmp_name'],"blogPhotos/$newName");
header("location: datauploadprocess.php");
exit();
}
?>
A:
use this . it works fine now.(I assume that your table has an auto-generated id field.)
$pid = mysqli_insert_id($con);
| {
"pile_set_name": "StackExchange"
} |
Q:
Spit out random line based on searching of a text file in Java
I'm making an IRC bot and I have a text file with a quote from each user on a new, separate line.
For example:
I like peas - user1
I like tomatoes - user2
I like peas inside of tomatoes - user1
I want a way to be able to make it so that if someone types in "!quote user" it will take a random quote from that user and send it to the channel. This is the code that I have so far:
if (messageIC.startsWith("!quote")) {
String user = message.substring(7);
java.io.FileInputStream fs = null;
try {
fs = new java.io.FileInputStream("C:/Users/Quibbles/Documents/ampersand/quotes.txt");
} catch (FileNotFoundException ex) {
Logger.getLogger(Ampersand.class.getName()).log(Level.SEVERE, null, ex);
}
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
ArrayList<String> array = new ArrayList<>();
String line;
try {
while((line = br.readLine()) != null)
array.add(br.readLine());
} catch (IOException ex) {
Logger.getLogger(Ampersand.class.getName()).log(Level.SEVERE, null, ex);
}
// variable so that it is not re-seeded every call.
Random rand = new Random();
// nextInt is exclusive. Should be good with output for array.
int randomIndex = rand.nextInt(array.size());
if ((array.get(randomIndex).contains(user))) {
sendMessage(channel, array.get(randomIndex));
}
}
However, this doesn't work. The bot doesn't spit out anything. What am I doing wrong?
A:
You can replace the first half of your code with:
List<String> array = Files.readAllLines(
Paths.get(System.getProperty("user.home"),
"Documents", "ampersand", "quotes.txt"),
Charset.defaultCharset());
Your exception handling needs improvement. It makes no sense to continue with the method if you can't read the file, right? So either add throws IOException to the containing method's signature, or do something like this:
try {
List<String> array = Files.readAllLines(
Paths.get(System.getProperty("user.home"),
"Documents", "ampersand", "quotes.txt"),
Charset.defaultCharset());
// Choose quote here
} catch (IOException e) {
// Can't continue if we can't read the quotes file.
throw new RuntimeException(e);
}
You want a random quote from a specific user, not just a random line in the file. So you should be applying your random value to only lines for the desired user:
try {
List<String> array = Files.readAllLines(
Paths.get(System.getProperty("user.home"),
"Documents", "ampersand", "quotes.txt"),
Charset.defaultCharset());
// Discard lines from other users
Iterator<String> i = array.iterator();
while (i.hasNext()) {
if (!i.next().endsWith(" - " + user)) {
i.remove();
}
}
// Important: Do not keep creating a new Random instance. Instead,
// create one instance and keep it in a field of your class.
int randomIndex = random.nextInt(array.size());
sendMessage(channel, array.get(randomIndex));
} catch (IOException e) {
// Can't continue if we can't read the quotes file.
throw new RuntimeException(e);
}
In Java 8, you can make things shorter with a Stream:
Path quotesFile = Paths.get(System.getProperty("user.home"),
"Documents", "ampersand", quotes.txt");
try (Stream<String> lines =
Files.lines(quotesFile, Charset.defaultCharset())) {
String[] array = lines.filter(line -> line.endsWith(" - " + user))
.toArray(String[]::new);
int randomIndex = random.nextInt(array.length);
sendMessage(channel, array[randomIndex]);
} catch (IOException e) {
// Can't continue if we can't read the quotes file.
throw new RuntimeException(e);
}
The Stream is in a try-with-resources statement because it is an I/O-backed Stream, meaning it supplies its values from an I/O operation (specifically, reading the file).
| {
"pile_set_name": "StackExchange"
} |
Q:
How to style GWT Editor errors
I am using the GWT 2.4 Editor framework. I have everything working with errors displaying, but I am not sure how to style the errors! It looks like the styles are part of a CssResource as they are obfuscated. Anyone know how to go about styling these?
The errors I am wanting to style are the ones automatically added by the ValueBoxEditorDecorator#showErrors.
A:
ValueBoxEditorDecorator is actually a bit "half-baked". You'd better copy/paste it to make your own.
| {
"pile_set_name": "StackExchange"
} |
Q:
Windows.Foundation.Uri supports Data URI Scheme?
Does Windows.Foundation.Uri supports data URI Scheme, if yes, can I use that in Windows.UI.StartScreen.SecondaryTile as logoReference parameter? Please help.
A:
Just tested this using the JavaScript Grid app template, and it does not work.
The constructor for Windows.Foundation.Uri will happily accept a data URI, but the constructor for Windows.UI.StartScreen.SecondaryTile throws an exception when attempting to initialize the tile with the data URI.
So you will probably need to find another way of solving this. Perhaps you can dynamically create the tile image and save it to your appdata folder, which can then be accessed via the ms-appdata:// URI scheme?
For more info on Windows Store app development, register for Generation App.
| {
"pile_set_name": "StackExchange"
} |
Q:
parse_str wrongly parsing integers to strings
Consider the following PHP code:
//JS
// var a = { category: [9] };
// var x = $.param(a);
// window.location.href = "test.com/?foo=" + x;
$x = $_GET["foo"];
$x = "category%5B%5D=9"; // this is what $_GET["foo"] looks like
$result = array();
parse_str($x, $result);
var_dump($result);
Now, that will output:
array(1) {
["category"]=>
array(1) {
[0]=>
string(1) "9"
}
}
Which is wrong. The element inside the category array should be an integer and not a string. Why is parse_str handling that input so badly? And how can I make it convert to string only the data that is between " or '? (pretty much how json_decode works)
A:
If you are using plain GET, how should parse_str() know about the desired data type? You, the programmer, need to:
verify input values (is it really numeric?)
cast values to the data type you wish. parse_str() will always deliver strings.
If you want to transfer strictly typed values between the client and the server, you need to go a more sophisticated way . Starting from json, over XMLRPC to SOAP.
Using json in the request might be the simplest way to start, however it does not fit well for GET requests since it is hard to type that in an url, sure you do that by code, however I still think json doesn't suite for GET requests.
| {
"pile_set_name": "StackExchange"
} |
Q:
php pchart pie chart problem with 0 value
I have a problem with my pie chart when I have 0 values
$MyData->addPoints(array(10,20,20,15,23),"Data");
This works fine and converts to percentages across a pie chart however if any of these values are 0 which could happen as I'm dealing with counts and these are really variables in my script) then everything screws up and the color of the legend don't correlate with the data values. Basically in the pie chart the color palette only assigns a value to non 0 points
10 $PieChart->setSliceColor(0,array("R"=>48,"G"=>199,"B"=>13));
20 $PieChart->setSliceColor(1,array("R"=>246,"G"=>2,"B"=>8));
20 $PieChart->setSliceColor(2,array("R"=>233,"G"=>215,"B"=>59));
15 $PieChart->setSliceColor(3,array("R"=>38,"G"=>42,"B"=>191));
23 $PieChart->setSliceColor(3,array("R"=>38,"G"=>42,"B"=>191));
10 $PieChart->setSliceColor(0,array("R"=>48,"G"=>199,"B"=>13));
0
20 $PieChart->setSliceColor(1,array("R"=>246,"G"=>2,"B"=>8));
15 $PieChart->setSliceColor(2,array("R"=>233,"G"=>215,"B"=>59));
23 $PieChart->setSliceColor(3,array("R"=>38,"G"=>42,"B"=>191));
$PieChart->setSliceColor(3,array("R"=>38,"G"=>42,"B"=>191));
Is this a common problem?
A:
I used a quick hack to bypass this bug, try to replace your zero values by -0.0001.
| {
"pile_set_name": "StackExchange"
} |
Q:
Cannot find proper JSON array syntax for Highcharts
Hope all is well. I am running into a little trouble with setting up a JSON array via PHP and pushing it into Highcharts.
At the moment I generate the array like this:
$stack[] = array($commname => $countit);
$stack = json_encode($stack);
When I print_r the array I get the following:
[{"Crude Oil":69},{"Natural Gas":554},{"Liquid Natural
Gas":152},{"Power":40},{"Coal":10},{"Weather":21},{"Macroeconomics":67},{"Miscellaneous":45},{"Prices":50},{"Freight":14},{"Forecasts":16}]
I then pass the array to javascript like this:
var stack = <?php echo json_encode( $stack ) ?>;
.. and then pass it into the following highcharts array like this:
var text = {
chart: {
plotBackgroundColor: null,
plotBorderWidth: 1,//null,
plotShadow: false
},
title: {
text: 'Browser market shares at a specific website, 2014'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
type: 'pie',
name: 'Browser share',
data: [
]
}]
};
text.series[0].data.push(stack);
... But this does not work. I think my array 'stack' is not prepared properly, because highcharts wants it to be in this format: [["Crude oil", 35],["Natural Gas", 45] etc...]
Any pointers as to what I am doing wrong? Thank you!
G.
A:
You have two ways
- form json to this form:
{name:"Crude Oil", y:69}
get JSON then use loop and push to new series data array and then refer to it in the highcharts option.
| {
"pile_set_name": "StackExchange"
} |
Q:
Jquery do nothing on aspx content page
I have this in my child/ContentPage but nothing happen .What am i missing?
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WFFHM.WebForm1" %>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
<asp:Button ID="Button2" runat="server" Text="Button" />
<script src="Scripts/jquery-1.7.1.js"></script>
<script type="text/javascript">
$("#Button2").click(function () {
alert("ASD");
}
);
</script>
</asp:Content>
A:
Your ID selector is wrong (missing the #, also, you need to set clientIdMode="static" for your button.
You could also do this which is uglier IMO.
$("#<%= Button2.ClientID %>")
| {
"pile_set_name": "StackExchange"
} |
Q:
Where do I post question about why git-scm.com is not accessible (down)?
The site git-scm.com currently times out. I'd like to know what's going on. Google chrome displays the following:
No data received
ERR_EMPTY_RESPONSE
Is there a Stack Exchange site can I ask about this? Or, are there other known sites on the Internet that can give hints about what may be causing it, the status of the problem, etc.?
I can't contact the site directly in this case as the home page is not accessible.
A:
There is no Stack Exchange site for this, because this type of question is not a good fit for the Stack Exchange model.
Sites can be down for any reason; often only the site maintainers know why (or are desperately trying to find out why...)
But this is a temporary issue. The site may be up a few hours later, in which case the question no longer has relevance. Or the site may have gone down for good, in which case the question is also largely irrelevant.
Answers on Stack Exchange must be useful for the future, and it must be possible for the community to judge them, so that they can upvote or downvote accordingly. Neither condition applies to "why is example.com down", so this is not a good fit for Stack Exchange.
However, current events can be discussed in the relevant Stack Exchange chat; if you find a chatroom that is open to this kind of question, you can ask your question there.
A:
The site git-scm.com currently times out. I'd like to know what's
going on
This site you've asked on is about managing all Stack sites in the network, so you cannot ask that question here, and all other sites in the Stack Exchange network are not for asking things like "why is this website down". How can someone other than the people who manage the site tell you what is wrong?
Contact the site in question and see what they say.
Also, try this:
http://downforeveryoneorjustme.com/http://git-scm.com/
It's not just you, so there's nothing anyone can do, or tell you really. The site is down. I'm sure the site admins are working on it.
| {
"pile_set_name": "StackExchange"
} |
Q:
N+1 query on bidirectional many to many for same entity type
I have an entity as below. I want to get an entity from DB with all of her/his friends with their primitive type fields (id, name). In this example, it is trying to return all friends and the friends of the friends so it is creating an infinite loop. I just want to get the first level friend objects with primitive fields. It seems like a N+1 query problem but I could not find a solution for it. Is there any solution for stopping this infinite recursion and returning the response as I mentioned?
@Builder
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "PERSON")
@ToString(exclude = "friends")
@EqualsAndHashCode(exclude = "friends")
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
@Column(name = "name",unique = true)
private String name;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "FRIENDSHIP",
joinColumns = @JoinColumn(name = "person_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "friend_id", referencedColumnName = "id"))
private Set<Person> friends;
I am creating the bidirectional friendship as below:
public Person makeFriendship(String personName, String friendName)
throws FriendshipExistsException, PersonNotFoundException {
Person person = retrieveWithName(personName);
Person friend = retrieveWithName(friendName);
if(!person.getFriends().contains(friend)){
person.getFriends().add(friend);
friend.getFriends().add(person);
return repository.save(person);
} else {
throw new FriendshipExistsException(personName, friendName);
}
It is giving the following error:
Could not write JSON: Infinite recursion (StackOverflowError);
But I think the root cause is N+1 query but neither @EntityGraph nor @JsonBackReference became a solution for my case. I am not sure how to implement them for same type entity relationships.
PS: I have a premise question about same code:
Many to many relationship for same type entity
A:
Try to use:
@JsonIgnoreProperties("friends")
private Set<Person> friends;
It should prevent friends from the displaying of their friends in recursion.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to display join result in view
I need to join three tables using inner join and i did as follows
@posts = SubCategory.joins(products: :posts)
Now I am trying to list the fields for posts table but it is throwing error as
undefined method `title' for #<ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_Post:0x9932f84>
i tried something like this i my view but it doen't help
<% @posts.each do |post| %>
<h4><%= post.posts.title %></h4>
<% end %>
Any suggestions
Edit 1
ActiveRecord::StatementInvalid in Posts#index
PG::UndefinedColumn: ERROR: column posts.sub_category_id does not exist
LINE 1: SELECT "posts".* FROM "posts" WHERE "posts"."sub_category_i...
It is true i don't have sub_category_id in my posts table. But i have product_id in my posts table.
A:
When I read your query it says to me "Give me all of the SubCategories that have a product with a post". And the call to .posts on your |post| (which really is a subcategory) shows that you have defined a collection posts. So there must be more than one Post per SubCategory.
Since post.posts is a collection then you probably need to iterate over it.
<% post.posts.each do |p| %>
<h4><%= p.title %></h4>
<% end %>
It would be useful to see the code for sub_category.rb
Another thought
In case you really just want to get every post even if sub_categories and products are repeated then just do this:
@posts = Post.includes(:product => :sub_category)
Then you'll always get Post instances and you can do this
<% @posts.each do |post| %>
<h4><%= post.title %></h4>
<% end %>
Rails may not always do a join here though. Either way it tries to pull product and sub_category in one shot.
If you just want Post data with no other fields but you want a join. Do this:
@posts = Post.joins(:product => :sub_category)
This should produce a query that looks like this:
SELECT "posts".* FROM "posts"
INNER JOIN "products" ON "products"."id" = "posts"."product_id"
INNER JOIN "sub_categories" ON "sub_categories"."id" = "products"."sub_category_id"
| {
"pile_set_name": "StackExchange"
} |
Q:
Completion handler for UINavigationController "pushViewController:animated"?
I'm about creating an app using a UINavigationController to present the next view controllers.
With iOS5 there´s a new method to presenting UIViewControllers:
presentViewController:animated:completion:
Now I ask me why isn´t there a completion handler for UINavigationController?
There are just
pushViewController:animated:
Is it possible to create my own completion handler like the new presentViewController:animated:completion: ?
A:
See par's answer for another and more up to date solution
UINavigationController animations are run with CoreAnimation, so it would make sense to encapsulate the code within CATransaction and thus set a completion block.
Swift:
For swift I suggest creating an extension as such
extension UINavigationController {
public func pushViewController(viewController: UIViewController,
animated: Bool,
completion: @escaping (() -> Void)?) {
CATransaction.begin()
CATransaction.setCompletionBlock(completion)
pushViewController(viewController, animated: animated)
CATransaction.commit()
}
}
Usage:
navigationController?.pushViewController(vc, animated: true) {
// Animation done
}
Objective-C
Header:
#import <UIKit/UIKit.h>
@interface UINavigationController (CompletionHandler)
- (void)completionhandler_pushViewController:(UIViewController *)viewController
animated:(BOOL)animated
completion:(void (^)(void))completion;
@end
Implementation:
#import "UINavigationController+CompletionHandler.h"
#import <QuartzCore/QuartzCore.h>
@implementation UINavigationController (CompletionHandler)
- (void)completionhandler_pushViewController:(UIViewController *)viewController
animated:(BOOL)animated
completion:(void (^)(void))completion
{
[CATransaction begin];
[CATransaction setCompletionBlock:completion];
[self pushViewController:viewController animated:animated];
[CATransaction commit];
}
@end
A:
iOS 7+ Swift
Swift 4:
// 2018.10.30 par:
// I've updated this answer with an asynchronous dispatch to the main queue
// when we're called without animation. This really should have been in the
// previous solutions I gave but I forgot to add it.
extension UINavigationController {
public func pushViewController(
_ viewController: UIViewController,
animated: Bool,
completion: @escaping () -> Void)
{
pushViewController(viewController, animated: animated)
guard animated, let coordinator = transitionCoordinator else {
DispatchQueue.main.async { completion() }
return
}
coordinator.animate(alongsideTransition: nil) { _ in completion() }
}
func popViewController(
animated: Bool,
completion: @escaping () -> Void)
{
popViewController(animated: animated)
guard animated, let coordinator = transitionCoordinator else {
DispatchQueue.main.async { completion() }
return
}
coordinator.animate(alongsideTransition: nil) { _ in completion() }
}
}
EDIT: I've added a Swift 3 version of my original answer. In this version I've removed the example co-animation shown in the Swift 2 version as it seems to have confused a lot of people.
Swift 3:
import UIKit
// Swift 3 version, no co-animation (alongsideTransition parameter is nil)
extension UINavigationController {
public func pushViewController(
_ viewController: UIViewController,
animated: Bool,
completion: @escaping (Void) -> Void)
{
pushViewController(viewController, animated: animated)
guard animated, let coordinator = transitionCoordinator else {
completion()
return
}
coordinator.animate(alongsideTransition: nil) { _ in completion() }
}
}
Swift 2:
import UIKit
// Swift 2 Version, shows example co-animation (status bar update)
extension UINavigationController {
public func pushViewController(
viewController: UIViewController,
animated: Bool,
completion: Void -> Void)
{
pushViewController(viewController, animated: animated)
guard animated, let coordinator = transitionCoordinator() else {
completion()
return
}
coordinator.animateAlongsideTransition(
// pass nil here or do something animated if you'd like, e.g.:
{ context in
viewController.setNeedsStatusBarAppearanceUpdate()
},
completion: { context in
completion()
}
)
}
}
A:
Based on par's answer (which was the only one that worked with iOS9), but simpler and with a missing else (which could have led to the completion never being called):
extension UINavigationController {
func pushViewController(_ viewController: UIViewController, animated: Bool, completion: @escaping () -> Void) {
pushViewController(viewController, animated: animated)
if animated, let coordinator = transitionCoordinator {
coordinator.animate(alongsideTransition: nil) { _ in
completion()
}
} else {
completion()
}
}
func popViewController(animated: Bool, completion: @escaping () -> Void) {
popViewController(animated: animated)
if animated, let coordinator = transitionCoordinator {
coordinator.animate(alongsideTransition: nil) { _ in
completion()
}
} else {
completion()
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Remove Request-Context from Response Header
Somehow in my request response header "Request-Context" coming and i tried to remove that using in web.config and Response.Headers.Remove("Request-Context"); in global.asax but that header is not getting removed.
In the value of that header I am getting some Appid and I am not sure from where that is coming.
Here is response header of my request.
Cache-Control:no-cache, no-store
Content-Encoding:gzip
Content-Length:140
Content-Type:application/json; charset=utf-8
Date:Tue, 20 Feb 2018 09:48:28 GMT
Pragma:no-cache
Request-Context:appId=cid-v1:b650ed48-297a-4ea2-af46-0a5a5d26a82b
Vary:Accept-Encoding
Any help appreciated. Thanks in Advance.
A:
Request-Context is used for cross-component correlation when 2 of your applications use different instrumentation keys.
In this case, knowing caller or callee appId (passed in the header) allows to build application map and trace correlated telemetry across instrumentation keys
You may set RequestTrackingTelemetryModule.SetComponentCorrelationHttpHeaders to false to prevent header to be added to the response.
You can do it in applicationInsights xml file, just find RequestTrackingTelemetryModule element and add false under it.
Refer link: https://github.com/Microsoft/ApplicationInsights-dotnet-server/issues/739#issuecomment-367774652
| {
"pile_set_name": "StackExchange"
} |
Q:
Oracle using Temp tables in stored procedure
I have a query that uses temp tables and I would like to add this to a stored procedure. However upon compiling I get "Error(10,1): PLS-00428: an INTO clause is expected in this SELECT statement"
as example
WITH T1 as
(
SELECT ID, CREATED_DATE, LOOKUP_ID
FROM TEST1
),T2 as
(
SELECT ID, CREATED_DATE, LOOKUP_ID
FROM TEST2
)
SELECT * from T1
minus
SELECT * from T2
RESULTS
ID CREATED_D LOOKUP_ID
---------- --------- ----------
217322 11-DEC-16 1
Adding as a Stored Procedure:
create or replace PROCEDURE "TEST"
(
T IN OUT SYS_REFCURSOR
) AS
BEGIN
WITH T1 as
(
SELECT ID, CREATED_DATE, LOOKUP_ID
FROM TEST1
), T2 as
(
SELECT ID, CREATED_DATE, LOOKUP_ID
FROM TEST2
)
SELECT * from T1
minus
SELECT * from T2
end;
END;
Error(7,1): PLS-00428: an INTO clause is expected in this SELECT statement
I did see PLS-00428: an INTO clause is expected in this SELECT statement BUT that is using INSERTS and I do not want to,. I would like to use temp tables only.
A:
We need to handle the output of the query in a PL/SQL variable.
create or replace PROCEDURE "TEST"
(
T IN OUT SYS_REFCURSOR
) AS
cursor c_cur is
WITH T1 as
(
SELECT ID, CREATED_DATE, LOOKUP_ID
FROM TEST1
), T2 as
(
SELECT ID, CREATED_DATE, LOOKUP_ID
FROM TEST2
)
SELECT * from T1
minus
SELECT * from T2;
BEGIN
for r_cur in c_cur
loop
dbms_output.put_line('ID: '||r_cur.id ||'CREATED_DATE: ' ||r_cur.CREATED_DATE ||' LOOKUP_ID: '||r_cur.lookup_id);
end loop;
end;
| {
"pile_set_name": "StackExchange"
} |
Q:
Break setInterval and variable undefined
I'm new to Javascript and tried doing this script. Onclick it should grab the price of the item and stop the price dropping. Onclick, it doesn't stop and it doesn't grab the price shown. Please advise.
The price should be:-
Start Price: 100
Lowest Max Price: 90
function updateValue(task) {
var amount = document.getElementById("amount").value + "00";
var maxamt = document.getElementById("maxamount").value + "00";
var amountgrabbed = document.getElementById("revese-amt").value;
var decimal_places = 2;
var decimal_factor = decimal_places === 0 ? 1 : Math.pow(10, decimal_places);
var floored_number = Math.floor(amount) / decimal_factor;
var floored_number_max = Math.floor(maxamt) / decimal_factor;
floored_number = floored_number.toFixed(decimal_places);
floored_number_max = floored_number_max.toFixed(decimal_places);
if (task == "stop") {
console.log(amountgrabbed);
check(refreshid, "stop", amountgrabbed);
} else {
var refreshid = setInterval(function() {
floored_number = floored_number - 1 / 100;
floored_number = floored_number.toFixed(decimal_places);
if (floored_number < floored_number_max) {
check(refreshid, "over");
} else {
$('#revese-amt').html(floored_number);
}
}, 100);
}
}
function check(refreshid, status, amt) {
if (status == "over") {
clearInterval(refreshid);
$('#revese-amt').html('Deal Gone!');
} else if (status == "stop") {
console.log(amt);
clearInterval(refreshid);
alert('Congratulations! You have grabbed the item @ price of RM ' + amt);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input
type="text"
name="amount"
id="amount"
value="Start Price"
onclick=""/>
<BR>
<BR>
<input
type="text"
name="maxamount"
id="maxamount"
value="Lowest Max Price"
onblur="updateValue()"
/>
<span id="maxa"></span>
<BR>
<BR>
<div
style="width:130px; height:50px; background-color:red;"
onclick="updateValue('stop')">
<center>MYR
<p id="revese-amt"></p>
</center>
</div>
A:
You can change your code about below:
first html p tag ,must use textContent method to get its text.
// change
var amountgrabbed = document.getElementById("revese-amt").value;
// to
var amountgrabbed = document.getElementById("revese-amt").textContent;
| {
"pile_set_name": "StackExchange"
} |
Q:
Single dash phone number - regex validation
I need a simple regex to validate a phone number of the form x-y, where x and y can represent any number of digits and the dash is optional, but if it does show up it most be within the string (the dash must have digits at its left and right)
A:
/^\d+(?:-\d+)?$/ should do the trick.
| {
"pile_set_name": "StackExchange"
} |
Q:
Parse huge json data to html with PHP is slow
I have one problem with HUGE JSON DATA. I get json data from backend with service and then I parse the data into HTML with PHP.
When I get raw JSON data it takes 2 second, but when I parse it into HTML, it takes too long, about 35 seconds.
How can I accelerate parse time?
Find my code bellow. I use recursive function and for loops inside that function.
$allstructure=$this->allStructure();
$str='<ul style="padding: 0px;padding-left: 5px;list-style: none">';
for ($x=0;$x<count($allstructure);$x++){
$str.='<li>'.$allstructure[$x]->name.'</li>';
$str.='<li>'.$this->iterator($allstructure[$x]->child).'</li>';
}
$str.='</ul>';
return $str;
}
public function iterator($data)
{
$str='<ul>';
for($i=0;$i<count($data);$i++) {
$str.='<li>'.$data[$i]->name;
$str.='<ul>';
$str.='<li style="display:flex"><input type="checkbox" class="rehbersecim"></li>';
for($z=0;$z<count($data[$i]->listPosNames);$z++){
$str.='<li style="display:flex"><input type="checkbox" class="checkqutu" name="vezife[]" value="'.$data[$i]->listPosNames[$z]->posNameId.'"><p style="width:230px;height:20px"><b>'.$data[$i]->listPosNames[$z]->posName.'</b></p> '.$this->createHtml($data[$i]->listPosNames[$z]->posNameId).'</li>';
}
$str.='</ul>';
if(isset($data[$i]->child)){
$str.=$this->iterator($data[$i]->child);
}
$str.='</li>';
}
$str.='</ul>';
return $str;
}
A:
Your biggest name problem in the code above is the use of for(...; count(...); ...). This forces PHP to do count() every time you go through the loop in question, and you have three of these. When dealing with large data, that will be murderously slow.
Instead of doing it that way, call count() one time for each loop, like so:
$structureCount = count($allstructure);
for ($x=0; $x<$structureCount; $x++){
$str .= '<li>' . $allstructure[$x]->name . '</li>';
$str .= '<li>' . $this->iterator($allstructure[$x]->child) . '</li>';
}
A good resource for this kind of thing is http://www.phpbench.com/. For this problem, it shows that calling count() each time through takes approximately 340% as long as calling it once, like I did above. Because you have 3 of these loops effectively nested, this one change means your app may be taking about 3.43 = 39 times as long as it should be.
Also, as TomTom101 pointed out in the comments, you probably don't want to show "HUGE" data to the user all at once. You should consider paging (i.e., showing only part of the data at one time).
| {
"pile_set_name": "StackExchange"
} |
Q:
Bootstrap columns pushing elements in other column down
Example code to illustrate my problem looks like:
<div class='body'>
<div class="container">
<div class="col-md-12">
<div class="col-md-6">
Col Left 1
</div>
<div class="col-md-6">
Col Right 1 ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
</div>
<div class="col-md-6">
Col Left 2
</div>
</div>
</div>
</div>
This is how this renders, and the markup on the screenshot is what I would like to fix:
Ultimately, on my application, I would like to have my forms and buttons on one side, and my data display on the other like so:
What this is doing is pushing everything on the left down and creating a large space between the elements as shown in the example. How do I overcome this and keep the two columns separated?
A:
Your code is incorrect. In Bootstrap grid layout, columns must be wrapped by rows. You can re-write your code as below:
<div class="container">
<div class="row">
<div class="col-md-6">
Col Left 1
</div>
<div class="col-md-6">
Col Right 1
</div>
<div class="col-md-6 border border-info">
Col Left 2
</div>
</div>
Your layout should now look like the picture below, without space between the columns:
bootstrap columns
| {
"pile_set_name": "StackExchange"
} |
Q:
Calculating the standard reduction potential for the oxidation of water
I was working with Latimer and Frost diagrams for oxygen when I came across what seems to me a contradiction.
From the Latimer diagram for oxygen below, we know the standard reduction potential for the reduction of $\ce{O2}$ to $\ce{H2O2}$ and the standard reduction potential for the reduction of $\ce{H2O2}$ to $\ce{H2O}$, as represented in the following chemical equations:
$$\ce{O2} \overset{+0.70}{\longrightarrow} \ce{H2O2} \overset{+1.76}{\longrightarrow} \ce{H2O}$$
$$\begin{align}
\ce{2H+ (aq) + 2e- + H2O2 (aq) &-> 2H2O (l)} & E^\circ &= \pu{+1.76 V} \\
\ce{O2 (g) + 2H+ (aq) + 2e- &-> H2O2 (aq)} & E^\circ &= \pu{+0.70 V} \\
\end{align}$$
If we add these two reduction chemical equations, we can find the standard reduction potential for the reduction of $\ce{O2}$ to $\ce{H2O2}$, which would be $\pu{+2.46 V}$ according to the aformentioned reduction potentials and chemical equations.
The reduction of $\ce{O2}$ to $\ce{H2O}$ is the reverse reaction of the oxidation of water:
$$\ce{2H2O(l) -> O2(g) + 4H+(aq) + 4e-}\qquad E^\circ = \pu{-1.23 V}$$
Why does the standard reduction potential for the oxidation of water calculated from the Latimer diagram differ from the value reported in the table of standard reduction potentials? More specifically, why is the value calculated from the Latimer diagram double of that reported in the table? I checked my work multiple times and do not understand why this occurs, but I might have still made a silly mistake.
References
Shriver, D. F., Weller, M. T., Overton, T., Rourke, J., & Armstrong, F. A. (2014). Inorganic chemistry 6th Edition.
A:
According to Hess’ law, we expect the Gibbs energy change $\Delta G$ of the two partial reactions to add up to the total Gibbs energy change:
$$\Delta G_1+\Delta G_2=\Delta G_3$$
For an electrochemical reaction, the change in Gibbs energy corresponds to an electrochemical potential $E$ according to
$$\Delta G = -zFE$$
where
$F$ is the Faraday constant and
$z$ is the number of electrons transferred.
Since for the two partial reactions the number of electrons is $z_1=z_2=2$, but for the total reaction $z_3=4$, we expect:
$$\begin{align}\Delta G_1+\Delta G_2&=\Delta G_3\\
z_1E_1+z_2E_2&=z_3E_3\\
2\times0.695\ \mathrm V+2\times1.763\ \mathrm V&=4\times1.229\ \mathrm V
\end{align}$$
| {
"pile_set_name": "StackExchange"
} |
Q:
JTable show all Records (Data), just in one column?
In the Code the JTable retrieves all Data from a Database with one Table and two Columns.
The program is just a minimal Example. Database (Javadb) "SOMETABLE" , Table "TESTTABLE" , Column one "DATA1" (char) , Column two "DATA2" (char) .
The program gets and shows the input and records from and to the command line. The rest is done on the Gui. First get the Inputs for DATA1 and DATA2, then click Save, then show the records by clicking Load.
And then click Del, to show the records on JTable. Just switching between GUI and CLI.
But when I execute the program, the JTable shows all Data just in one Column, instead of the two Columns ?
Sorry for misunderstandings.
public class DBtest {
JFrame f;
JPanel p1;
JPanel p2;
JPanel p3;
JButton b1;
JButton b2;
JButton b3;
JMenuItem delete;
JPopupMenu pm;
JTable t;
String[] c = {
"DATA1",
"DATA2"
};
Object[][] obj = null;
Object o1;
Object o2;
int n;
Scanner sc;
String s1;
String s2;
Object row2Delete;
Connection con;
PreparedStatement ps;
Connection con1;
PreparedStatement ps1;
Connection con2;
PreparedStatement ps2;
Connection con3;
PreparedStatement ps3;
ResultSet rs;
ResultSet rs2;
public static void main(String[] args) {
new DBtest().startApp();
}
public void startApp() {
p1 = new JPanel();
p2 = new JPanel();
p3 = new JPanel();
b1 = new JButton("Save");
b1.addActionListener(new SaveListener());
b2 = new JButton("Load");
b2.addActionListener(new LoadListener());
b3 = new JButton("Del");
b3.addActionListener(new DelListener());
t = new JTable(obj, c);
pm = new JPopupMenu();
delete = new JMenuItem("Delete ?");
delete.addActionListener(new DeleteListener());
pm.add(delete);
p1.setLayout(new BorderLayout());
p1.add(p2, BorderLayout.NORTH);
p2.setLayout(new FlowLayout());
p2.add(b1);
p2.add(b2);
p2.add(b3);
f = new JFrame();
f.getContentPane().add(p1);
f.setTitle("Database");
f.setSize(450, 550);
f.setResizable(false);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sc = new Scanner(System.in);
System.out.println("Type something");
s1 = sc.nextLine();
System.out.println("Type again");
s2 = sc.nextLine();
sc.close();
}
public class DelListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent ev) {
try {
tableView(); //filling the table
boolean DEBUG = false;
boolean ALLOW_COLUMN_SELECTION = false;
boolean ALLOW_ROW_SELECTION = true;
t.setPreferredScrollableViewportSize(new Dimension(500, 70));
t.setFillsViewportHeight(true);
t.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (ALLOW_ROW_SELECTION) {
ListSelectionModel rowSM = t.getSelectionModel();
rowSM.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting()) return;
ListSelectionModel lsm = (ListSelectionModel) e.getSource();
if (lsm.isSelectionEmpty()) {
System.out.println("No rows are selected");
} else {
int selectedRow = lsm.getMinSelectionIndex();
pm.show(t, 50, 50);
System.out.println("Row " + selectedRow + " is now selected");
}
}
});
}
JScrollPane scrollPane = new JScrollPane(t);
p1.add(scrollPane, BorderLayout.CENTER);
f.validate();
} catch (SQLException ex) {
Logger.getLogger(DBtest.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(DBtest.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public void tableView() throws SQLException, ClassNotFoundException {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
con1 = DriverManager.getConnection("jdbc:derby://localhost:1527/TESTTABLE", "me", "1234");
con1.commit();
String sql = "SELECT DATA1 FROM ME.SOMETABLE";
ps1 = con1.prepareStatement(sql);
rs = ps1.executeQuery();
con2 = DriverManager.getConnection("jdbc:derby://localhost:1527/TESTTABLE", "me", "1234");
con2.commit();
String sql2 = "SELECT DATA2 FROM ME.SOMETABLE";
ps2 = con2.prepareStatement(sql2);
rs2 = ps2.executeQuery();
//Create new table model
DefaultTableModel tableModel = new DefaultTableModel();
//Retrieve meta data from ResultSet
ResultSetMetaData metaData = rs.getMetaData();
ResultSetMetaData metaData2 = rs2.getMetaData();
//Get number of columns from meta data
int columnCount = metaData.getColumnCount();
int columnCount2 = metaData2.getColumnCount();
//Get all column names from meta data and add columns to table model
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
tableModel.addColumn(metaData.getColumnLabel(columnIndex));
}
for (int columnIndex = 1; columnIndex <= columnCount2; columnIndex++) {
tableModel.addColumn(metaData2.getColumnLabel(columnIndex));
}
//Create array of Objects with size of column count from meta data
Object[] row = new Object[columnCount];
Object[] row2 = new Object[columnCount2];
//Scroll through result set
while (rs.next() && rs2.next()) {
//Get object from column with specific index of result set to array of objects
for (int i = 0; i < columnCount; i++) {
row[i] = rs.getObject(i + 1);
for (int h = 0; h < columnCount2; h++) {
row2[h] = rs2.getObject(h + 1);
}
}
//Add row to table model with that array of objects as an argument
tableModel.addRow(row);
tableModel.addRow(row2);
}
//Now add that table model to your table
t.setModel(tableModel);
t.setAutoCreateRowSorter(true);
}
public class DeleteListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent ev) {
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
con3 = DriverManager.getConnection("jdbc:derby://localhost:1527/TESTTABLE", "me", "1234");
con3.commit();
String sql = "DELETE FROM ME.SOMETABLE WHERE DATA1=?";
int row = t.getSelectedRow();
int column = t.getColumnCount();
for (int i = 0; i < column; i++) {
row2Delete = t.getValueAt(row, i);
}
ps3 = con3.prepareStatement(sql);
ps3.setString(1, "+row2Delete+");
int rowsDeleted = ps3.executeUpdate();
System.out.println("Row deleted: " + " " + rowsDeleted);
if (rowsDeleted > 0) {
System.out.println(" delete successfully!");
}
ps3.clearParameters();
} catch (SQLException ex) {
Logger.getLogger(DBtest.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(DBtest.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
if (ps3 != null) con3.close();
if (con3 != null) con3.close();
} catch (SQLException ex) {
Logger.getLogger(DBtest.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public class SaveListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent ev) {
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
con = DriverManager.getConnection("jdbc:derby://localhost:1527/TESTTABLE", "me", "1234");
con.commit();
//System.out.println(textAreaText() + "\n");
String sql = "INSERT INTO SOMETABLE (DATA1, DATA2)" + "VALUES (?,?)";
ps = con.prepareStatement(sql);
ps.setString(1, s1);
ps.setString(2, s2);
ps.executeUpdate();
ps.clearParameters();
} catch (SQLException es) {
es.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (ps != null) con.close();
if (con != null) con.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
}
public class LoadListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent ev) {
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
con1 = DriverManager.getConnection("jdbc:derby://localhost:1527/TESTTABLE", "me", "1234");
con1.commit();
String sql = "SELECT DATA1 FROM ME.SOMETABLE";
ps1 = con1.prepareStatement(sql);
rs = ps1.executeQuery();
con2 = DriverManager.getConnection("jdbc:derby://localhost:1527/TESTTABLE", "me", "1234");
con2.commit();
String sql2 = "SELECT DATA2 FROM ME.SOMETABLE";
ps2 = con2.prepareStatement(sql2);
rs2 = ps2.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
while (rs.next() && rs2.next()) {
for (int z = 0; z < rsmd.getColumnCount(); z++) {
n = z + 1;
o1 = rs.getObject(z + 1);
o2 = rs2.getObject(z + 1);
System.out.println(rs.getObject(z + 1) + "\n");
System.out.println(rs2.getObject(z + 1) + "\n");
}
}
ps1.clearParameters();
ps2.clearParameters();
} catch (SQLException es) {
es.printStackTrace();
} catch (Exception ex) {} finally {
try {
if (ps2 != null) con2.close();
if (con2 != null) con2.close();
if (ps1 != null) con1.close();
if (con1 != null) con1.close();
} catch (SQLException ex) {
Logger.getLogger(DBtest.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
A:
Your tableView method makes no sense. Why are you opening two connections to the data, running two different queries on the same table and then trying to merge them?
You're also risking leaking your resources (leaving database connections open), which isn't going to be healthy in the long run.
The simple answer to the question is, use SQL properly. Query the database for the columns you want from the table you want in as few statements as possible. For example...
public void tableView() throws SQLException, ClassNotFoundException {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
//Create new table model
DefaultTableModel tableModel = new DefaultTableModel();
try (Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/TESTTABLE", "me", "1234")) {
String sql = "SELECT DATA1, DATA2 FROM ME.SOMETABLE";
try (PreparedStatement ps = con.prepareStatement(sql)) {
try (ResultSet rs = ps.executeQuery()) {
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
List<String> columnNames = new ArrayList<>(columnCount);
for (int column = 0; column < columnCount; column++) {
columnNames.add(rsmd.getColumnName(column + 1));
}
tableModel.setColumnIdentifiers(columnNames.toArray(new Object[columnNames.size()]));
while (rs.next()) {
Object row[] = new Object[columnCount];
for (int column = 0; column < columnCount; column++) {
row[column] = rs.getObject(column + 1);
}
tableModel.addRow(row);
}
}
} finally {
t.setModel(tableModel);
}
}
}
Also take a look at try-with-resources for a better way to manage your resources...
| {
"pile_set_name": "StackExchange"
} |
Q:
Best SQL 2005 Query to get Related Items?
I have a small video site where I want to get related videos on the basis of the most matched tags. What would be the best MSSQL 2005 query to get the related videos?
A LINQ query would be appreciated as well.
Schema:
CREATE TABLE Videos
(VideoID bigint not null ,
Title varchar(100) NULL,
isActive bit NULL )
CREATE TABLE Tags
(TagID bigint not null ,
Tag varchar(100) NULL )
CREATE TABLE VideoTags
(VideoID bigint not null ,
TagID bigint not null )
Each video can have multiple tags. Now I want to get related videos on basis of tags but only those videos which match most tags. The most matched videos should come on top and the less matched should be on the bottom, if no tags matched then it should not return any videos.
Also I want to know that above schema is ok if I have say more than a million videos and 10-20 tags for each video.
A:
Here's the sql
SELECT v.VideoID, v.Title, v.isActive
FROM Videos v
JOIN
(
SELECT vt.VideoID, Count(*) as MatchCount
FROM VideoTags vt
WHERE vt.TagID in
(
SELECT TagID
FROM Tags t
WHERE t.Tag in ('horror', 'scifi')
)
GROUP BY vt.VideoID
) as sub
ON v.VideoID = sub.VideoID
ORDER BY sub.MatchCount desc
And here's the Linq.
List<string> TagList = new List<string>() {"horror", "scifi"};
//find tag ids.
var tagQuery =
from t in db.Tags
where TagList.Contains(t.Tag))
select t.TagID
//find matching video ids, count matches for each
var videoTagQuery =
from vt in db.VideoTags
where tagQuery.Contains(vt.TagID)
group vt by vt.VideoID into g
select new { VideoID = g.Key, matchCount = g.Count;
//fetch videos where matches were found
//ordered by the number of matches
var videoQuery =
from v in db.Videos
join x in videoTagQuery on v.VideoID equals x.VideoID
orderby x.matchCount
select v
//hit the database and pull back the results
List<Video> result = videoQuery.ToList();
Oh wait - you don't have a taglist, you have a video and want videos with similiar tags. Ok:
SELECT v.VideoID, v.Title, v.isActive
FROM Videos v
JOIN
(
SELECT vt.VideoID, Count(*) as MatchCount
FROM VideoTags vt
WHERE vt.TagID in
(
SELECT TagID
FROM VideoTags vt2
WHERE vt2.VideoID = @VideoID
)
GROUP BY vt.VideoID
) as sub
ON v.VideoID = sub.VideoID
ORDER BY sub.MatchCount desc
And the Linq is the same except tag query changes
int myVideoID = 4
//find tag ids.
var tagQuery =
from t in db.VideoTags
where t.VideoID = myVideoID
select t.TagID
| {
"pile_set_name": "StackExchange"
} |
Q:
Get child controls on server control using javascript ASP.NET
I've create a basic composite server control that contains a button.
<Custom:Class1 ID="testClass" ClientInstanceName="test1" runat="server"></Custom:Class1>
I would like to be able to get to the child controls using javascript for example:
var myButton = testClass.FindControl('btnTest');
Is there anyway to do this?
A:
Create a client side object to represent your server side control (javascript class). Put a collection of references to the child controls on the client side object. Then on the server side OnPreRender event create or load a script to define your client side object and at the same time pass the collection of references to its constructor.
Example of how to embed a javascript file containing the clientside object definition (put this somwhere above the namespace declaration:
[assembly: WebResource("myNS.stuff.clientSideObj.js", "application/x-javascript")]
namespace myNS.stuff
{
Example of how to register the WebResouce (OnPreRender):
ClientScriptManager cs = this.Page.ClientScript;// Get a ClientScriptManager reference from the Page class.
Type csType = this.GetType();// Get the type from this class.
//Register an embedded JavaScript file. The JavaScript file needs to have a build action of "Embedded Resource".
String resourceName1 = "myNS.stuff.clientSideObj.js";
cs.RegisterClientScriptResource(csType, resourceName1);
Example of creating a script to declare an instance of your client side object (OnPreRender):
String childControlIDsList= getChildControlList();//I am not writing this one.. just look up javascript arrays.
String uniqueScriptKey = "myKey";
StringBuilder theScript = new StringBuilder();
theScript.AppendLine("var myObj = new clientSideObj(" + childControlIDsList + ");");
theScript.AppendLine("window['myClientControl'] = myObj;") //create a client side reference to your control.
cs.RegisterStartupScript(csType, uniqueScriptKey, theScript.ToString(), true);
I will leave the client side object definition up to you... Hope that helps!
| {
"pile_set_name": "StackExchange"
} |
Q:
how to write Rails3 routes exceptions?
Hello
I have an application where URI looks like http://mysite.com/post1 or http://mysite.com/post2 etc.
But with routing as this i can't get images because it stored at http://mysite.com/images/ folder in my server.
So how to overcome this problem?
A:
Take a look at Compass. It is a stylesheet authoring framework which allows you to use helpers such as image_url in scss stylesheets. image_url can be used in combination with a configuration variable asset_host, that prepends that path to images in your stylesheets.
Here is an example:
.content{
background: image_url("background.png") "no-repeat";
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Specifying seq as return type in F#
I want to make a function that takes a string and returns a sequence of numbers. It should return a sequence containing only 0 if it passed a empty string. I tried doing the following:
let mapToInt (s: string) :seq<int> =
if s.Length = 0 then
seq {0}
else
s.Split ' '
|> Seq.map int
This however gives the following error message:
This expression should have type 'unit', but has type 'int'. Use 'ignore' to discard the result of the expression, or 'let' to bind the result to a name.
What's wrong with my code?
A:
Your sequence expression needs to use yield to yield a value:
if s.Length = 0 then
seq { yield 0 }
| {
"pile_set_name": "StackExchange"
} |
Q:
Прогрессбар для загрузки фото
Добрый вечер пользователям портала. У меня есть форма для отправки фото на сервер.
<div class="progress-bar"><div class="progressing"></div></div>
<iframe id="support_upload_iframe" name="support_upload_iframe" width="200" height="300" style="border: none;"></iframe>
<form method="post" enctype="multipart/form-data" action="/system/modules/add_new_photo.php" target="support_upload_iframe">
<input id="support_add_img_file" type="file" name="file">
<input id="support_upload_iframe_submit" type="submit">
</form>
Где <div class="progress-bar"> - фон будущего прогрессбара, а <div class="progressing"> - полоска загрузки.
И есть банальный файл-обработчик add_new_photo.php. Как можно сделать, чтобы в <div class="progress-bar"> выводился прогрессбар загрузки изображения? "изображения будут HD качества"
A:
Самое простое и быстрое решение - использовать плагины для этого. Если будете писать свое решение, то столкнетесь с кучей проблем кроссбраузерности. Никто не мешает загрузить изображение через плагин и потом давать его обрабатывать.
Но, если сильно хочется, то можно... :)
Вот лучшее решение, которое я нашел: http://www.matlus.com/html5-file-upload-with-progress/. В конце весь код одним куском с очень хорошими комментариями. Это базовый код. Для его работы браузер должен поддерживать File API (can i use?). Если нужна кроссбраузерность, то нужно будет писать костыли (например, через iframe).
Вот 2 функции из ссылки выше:
Функция uploadFile получает файл для аплоада и вешает все обработчики. Конечно, в строке xhr.open("POST", "UploadMinimal.aspx"); имя файла нужно заменить на свое, в котором идет сохранение иозображения. Если это будет php, то получить нужный файл вы сможете как $_POST['fileToUpload'].
function uploadFile() {
var fd = new FormData();
fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", "UploadMinimal.aspx");
xhr.send(fd);
}
Функция uploadProgress рассчитывает сколько процентов уже загружено и отображает эту информацию.
function uploadProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
}
else {
document.getElementById('progressNumber').innerHTML = 'unable to compute';
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
django: How to make one form from multiple models containing foreignkeys
I am trying to make a form on one page that uses multiple models. The models reference each other. I am having trouble getting the form to validate because I cant figure out how to get the id of two of the models used in the form into the form to validate it. I used a hidden key in the template but I cant figure out how to make it work in the views
My code is below:
views:
def the_view(request, a_id,):
if request.method == 'POST':
b_form= BForm(request.POST)
c_form =CForm(request.POST)
print "post"
if b_form.is_valid() and c_form.is_valid():
print "valid"
b_form.save()
c_form.save()
return HttpResponseRedirect(reverse('myproj.pro.views.this_page'))
else:
b_form= BForm()
c_form = CForm()
b_ide = B.objects.get(pk=request.b_id)
id_of_a = A.objects.get(pk=a_id)
return render_to_response('myproj/a/c.html',
{'b_form':b_form,
'c_form':c_form,
'id_of_a':id_of_a,
'b_id':b_ide })
models
class A(models.Model):
name = models.CharField(max_length=256, null=True, blank=True)
classe = models.CharField(max_length=256, null=True, blank=True)
def __str__(self):
return self.name
class B(models.Model):
aid = models.ForeignKey(A, null=True, blank=True)
number = models.IntegerField(max_length=1000)
other_number = models.IntegerField(max_length=1000)
class C(models.Model):
bid = models.ForeignKey(B, null=False, blank=False)
field_name = models.CharField(max_length=15)
field_value = models.CharField(max_length=256, null=True, blank=True)
forms
from mappamundi.mappa.models import A, B, C
class BForm(forms.ModelForm):
class Meta:
model = B
exclude = ('aid',)
class CForm(forms.ModelForm):
class Meta:
model = C
exclude = ('bid',)
B has a foreign key reference to A, C has a foreign key reference to B. Since the models are related, I want to have the forms for them on one page, 1 submit button. Since I need to fill out fields for the forms for B and C & I dont want to select the id of B from a drop down list, I need to somehow get the id of the B form into the form so it will validate. I have a hidden field in the template, I just need to figure how to do it in the views
A:
The code you have is almost right. Just do:
if b_form.is_valid() and c_form.is_valid():
print "valid"
b = b_form.save()
c = c_form.save(commit=False)
c.b = b
c.save()
| {
"pile_set_name": "StackExchange"
} |
Q:
Eigenvectors in non-orthogonal coordinate system
I have a general ellipsoid in the matrix form of
$$X=\left[\begin{matrix}x_{11}&x_{12}&x_{13}\\x_{12}&x_{22}&x_{23}\\x_{13}&x_{23}&x_{33}\end{matrix}\right],$$
(symmetrical around the main diagonal)
and this ellipsoid is situated in a non-orthogonal coordinate system (angle between $x$ and $y = 120^{\circ},$ others $90^{\circ}$), see screenshot link. X is expressed relative to this coordinate system.
What is the proper way to calculate the eigenvectors and values from it?
A:
You go about finding eigenvalues and eigenvectors the same way regardless of the coordinate system you’re working in, but the results will be specific to that coordinate system: in general, eigenvalues in different coordinate systems will be different and eigenvectors will not be related to each other via the coordinate transformation. Therefore, if you want to know the principal axes in the standard coordinate system, you’ll have to transform the ellipsoid’s matrix first.
A simple two-dimensional example to illustrate: Consider the ellipse given by $x^2/25+y^2/9=1$ in the standard basis. The corresponding matrix is $$C=\begin{bmatrix}\frac1{25}&0\\0&\frac19\end{bmatrix}.$$ Its eigenvalues are of course $1/25$ and $1/9$, with the standard basis vectors for the corresponding eigenvectors. If we rotate the $y$-axis thirty degrees so that the angle between the positive axis directions is $120°$, the corresponding change-of-basis matrix is $$M=\begin{bmatrix}1&\frac1{\sqrt3}\\0&\frac2{\sqrt3}\end{bmatrix}$$ and the matrix of the ellipse relative to this new basis is $$C'=\begin{bmatrix}\frac1{25}&-\frac1{50}\\-\frac1{50}&\frac7{75}\end{bmatrix}.$$ Its eigenvalues are $1/10$ and $1/30$, with respective eigenvectors $(1,-3)^T$ and $(3,1)^T$, which, even if normalized, are clearly not the images under $M$ of the eigenvectors of $C$.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to “switch role” in aws-cli?
I'm contracting for a company that has multiple aws accounts. They gave me access to the Login account and I "Switch Role" in the web console to the Project account I work on. In the web gui it works.
How do I do the same with aws-cli?? I only have access keys for the Login account and I don’t have permissions to create a user and access keys in the Project account. Is it even possible?
A:
Of course it's possible!
Let's assume you've got your Login account credentials in ~/.aws/credentials, probably something like this:
~ $ cat ~/.aws/credentials
[customer-login]
aws_access_key_id = AKIABCDEFGHJKLMNOPQR
aws_secret_access_key = ZxCvBnMaSdFgHjKlQwErTyUiOp
All you need to do is to add another profile to ~/.aws/credentials that will use the above profile to switch account to your project account role. You will also need the Project account Role ARN - you can find that in the web console in IAM -> Roles after you switch to the Project account. Let's say the Project account number is 123456789012...
[customer-project]
role_arn = arn:aws:iam::123456789012:role/your-project-role-name # << Change this
source_profile = customer-login
With that in place you can test if it works:
~ $ aws --profile customer-project sts get-caller-identity
{
"Account": "123456789012",
"UserId": "AROA1B2C3D4E5F6G7H8I:botocore-session-1538120713",
"Arn": "arn:aws:sts::123456789012:assumed-role/your-project-role-name/botocore-session-1538120713"
}
As you can see you're now in the Project account as confirmed by the Account id 123456789012.
If you want to always use this profile with aws-cli you can do so:
~ $ export AWS_DEFAULT_PROFILE=customer-project
~ $ aws sts get-caller-identity
... will be the same output as above, even without specifying --profile ...
For more info check out this post: https://aws.nz/best-practice/cross-account-access-with-aws-cli/
Check also:
Assuming an IAM Role in the AWS CLI.
AWS CLI Configuration Variables.
| {
"pile_set_name": "StackExchange"
} |
Q:
IOS 5: How to return YES on contains: with 2 'identical' objects, but with different pointers
I'm quite new to StackOverflow, so apologies in advance if I forgot some
critical element in my question. It's a long one, so bear with me!
Iterating over JSON-webservice result:
For an IOS5 iPad app, I collect JSON information from a webservice and via:
NSData *data = [NSData dataWithContentsOfURL:url];
NSDictionary *json =
[NSJSONSerialization JSONObjectWithData:data options:kNilOptions
error:&error];
I'll iterate over the returned NSDictionary and store the returned objects and their properties as a custom class.
The custom class contains several properties, including an AmountInShoppingCart-value.
I use this custom class to represent items that we sell in our store, so an NSMutableArray is made of all the returned objects and shown to the user.
If the AmountInShoppingCart value > 0, then the object will be put in the ShoppingCart NSMutableArray (which is a singleton).
Checking for duplicates in ShoppingCart:
To make sure the ShoppingCart doesn't contain any duplicate entries, I've got a function like this in the ShoppingCartController (also borrowed from SO):
- (void)checkForDuplicates
{
NSMutableSet *seen = [NSMutableSet set];
NSUInteger i = 0;
NSLog(@"ShoppingCartArray count: %u",[ShoppingCartArray count]);
//Iterate over the Array to check for duplicates, and to sync the list with the
cart.
while (i < [ShoppingCartArray count]) {
id obj = [ShoppingCartArray objectAtIndex:i];
if ([seen containsObject:obj]) {
if ([obj isKindOfClass:[MyCust class]]){
MyCust *cust = [ShoppingCartArray objectAtIndex:i];
MyCust *seenCust = [seen member:obj];
seenCust.AmountInShoppingCart = cust.AmountInShoppingCart;
[ShoppingCartArray removeObjectAtIndex:i];
}} else {seen addObject:obj];
i++;}}}
Equality & Hashing
To accomplish this, I've overridden the isEqual:-function of the MyCust-class so that it'll look at the externalItemID-property, which is the only property that is definitely unique for each class object.
I picked this function up from StackOverflow:
- (BOOL)isEqual:(id)otherObject;
{
if ([otherObject isKindOfClass:[MyCust class]]) {
MyCust *otherCust= (MyCust *)otherObject;
if (externalItemId != [otherCust externalItemId]) return NO;
return YES;
}
return NO;
}
- (NSUInteger) hash;
{
return [[self externalItemId] hash];
}
Sync the two arrays:
It can happen that people request the same result from the JSON-webservice, since it uses the MyCust's size, height and diameter to return a set of objects that adhere to those sizes.
So I use the following function to check and 'sync' the two NSMutableArrays with the new results:
In: RESULTLISTCONTROLLER.M
- (void) syncWithCart
{
ShoppingCart *sc = [ShoppingCart sharedCart];
[sc checkForDuplicates];
NSMutableSet *listSet = [NSMutableSet setWithArray:resultList];
NSUInteger i = 0;
while (i < [sc.ShoppingCartArray count]) {
id ShopObject = [sc.ShoppingCartArray objectAtIndex:i];
if ([listSet containsObject:ShopObject])
{
MyCust *listCust = [listSet member:ShopObject];
MyCust *shopCust = ShopObject;
listCust.AmountInShoppingCart = shopCust.AmountInShoppingCart;
[listSet removeObject:ShopObject];
} else {i++;}}}
This all works pretty well until...
The 2nd webservice!
Now here comes the good part: There's a 2nd JSON-WebService the app uses to retrieve external supplier stock. It sometimes contains the same MyCust objects, but contains extra information that has to be parsed into the existing objects.
I basically get the first WebService's result into the getMyCustArray and the other in the getExternalCustArray. I then check if getMyCustArray contains an object in the getExternalCustArray and update the additional information on the objects and delete the similar object in getExternalCustArray. Any leftover objects only available from the supplier will be added using:
mergedCustArray = [NSMutableArray arrayWithArray:[getMyCustArray arrayByAddingObjectsFromArray:getExternalCustArray]];
Now the problem is, that when the user checks the same sizes twice, the App doesn't seem to consider the new results as the same.
When I do an NSLog of the ShoppingCartArray, the following shows:
(original item names obfuscated)
First Search:
MyCust: SideShowBobsEarWarmers
Hash: **2082010619**
AmountInShoppingCart: 4
**<MyCust: 0x81cee50>**",
"
MyCust: SolidSnakesCardBoardBox
Hash: **4174540990**
AmountInShoppingCart: 4
**<MyCust: 0x8190d10>**"
Second Search:
the ResultList doesn't retain the MyCust's AmountInShoppingCart values, so I add them to the ShoppingCart again from the ResultList.
MyCust: SideShowBobsEarWarmers
Hash: **2082010619**
AmountInShoppingCart: 4
**<MyCust: 0x81cee50>**",
MyCust: SolidSnakesCardBoardBox
Hash: **4174540990**
AmountInShoppingCart: 4
**<MyCust: 0x8190d10>**"
"
// Different Pointers, although they should be considered Equal.
MyCust: SideShowBobsEarWarmers
Hash: **2082010619**
AantalInWinkelWagen: 3
**<MyCust: 0x74bc570>**",
"
MyCust: SolidSnakesCardBoardBox
Hash: **4174540990**
AantalInWinkelWagen: 2
**<MyCust: 0x74bc7b0>**"
So somehow the compiler allocates those objects in a different memory address/pointer, and then breaks the isEqual: function, as far as I can tell.
My guts tell me there's something to do with NSCopy(able), but I'm not quite sure how I'd implement that. If anyone got some good tips for a Shopping Cart system, that's always welcome too. I've got half a mind converting all this to Core Data but would like to have the core functionality in place before doing that.
A:
In isEqual: method, the line "if (externalItemId != [otherCust externalItemId]) return NO;" is wrong.
I think it should be if (![externalItemId:isEqual:[otherCust externalItemId]]) return NO;
| {
"pile_set_name": "StackExchange"
} |
Q:
Python's tkinter smart entry password
I want to create a password entry.
One easy solution is:
password = Entry(root, font="Verdana 22")
password.config(show="*");
but the problem is that to avoid typos, I want to show the item clicked to be visible only for a few seconds, while everything else is hidden. After a few seconds everything is hidden.
A:
It's not easy to do exactly what you want with Tkinter, but here's something close: when you press a key it displays the whole contents of the Entry, but after one second the text is hidden again.
I developed this on Python 2; to use it on Python 3 change Tkinter to tkinter.
import Tkinter as tk
class PasswordTest(object):
''' Password Entry Demo '''
def __init__(self):
root = tk.Tk()
root.title("Password Entry Demo")
self.entry = e = tk.Entry(root)
e.pack()
e.bind("<Key>", self.entry_cb)
b = tk.Button(root, text="show", command=self.button_cb)
b.pack()
root.mainloop()
def entry_cb(self, event):
#print(`event.char`, event.keycode, event.keysym )
self.entry.config(show='')
#Hide text after 1000 milliseconds
self.entry.after(1000, lambda: self.entry.config(show='*'))
def button_cb(self):
print('Contents:', repr(self.entry.get()))
PasswordTest()
It would be tricky to only display the last char entered. You'd have to modify the displayed string manually while maintaining the real password string in a separate variable and that's a bit fiddly because the user can move the insertion point cursor at any time.
On a final note, I really don't recommend doing anything like this. Keep passwords hidden at all times! If you want to reduce the chance of typos in newly-chosen passwords, the usual practice is to make the user enter the password twice.
| {
"pile_set_name": "StackExchange"
} |
Q:
Sorting by columns in excel vba
I'm trying to sort by descending value in column h in vba.
The code i'm using is the following;
With .Range("a8:h" & Rowindex - 1)
.Sort Key1:=Range(.Cells(9, 8), .Cells(Rowindex, 8)), Order1:=xlDescending, Header:=xlNo
End With
Rowindex is my row count.
However when i run this, i get the following error;
"Method 'Range' of object '_Global' failed"
A:
.Sort Key1:=.Range("a8:h" & Rowindex - 1), Order1:=xlDescending, Header:=xlNo
| {
"pile_set_name": "StackExchange"
} |
Q:
Using MySQL aggregate functions and UNION operator together
This is the first time I'm trying UNION operator of MySQL but the following code is giving me an error of "undefined index: female".
$sql = "(SELECT COUNT(gender) AS male FROM members WHERE gender='m')
UNION
(SELECT COUNT(gender) AS female FROM members WHERE gender='f')
UNION
(SELECT COUNT(gender) AS no_gender FROM members WHERE gender='n')
";
$results = $con->query($sql);
if ($row = $results->fetch_assoc()) {
print $row["male"] . "<br>";
print $row["female"] . "<br>";
print $row["no_gender"] . "<br>";
}
So, based on the solution by fancyPants, the following worked:
print "<table>";
$sql = "SELECT gender, COUNT(1) AS no_of_genders
FROM members
WHERE user_id = $user_id
GROUP BY gender";
$results = $con->query($sql);
while ($row = $results->fetch_assoc()) {
print "<tr><td>" . $row["gender"] . "</td><td>" . $row["no_of_genders"] . "</td></tr>";
}
print "</table>";
A:
You should use the GROUP BY clause.
SELECT gender,
COUNT(1) AS no_of_members
FROM members
GROUP BY gender;
This produces as much rows as there are different genders in your table.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I render a PDF from HTML with working named anchors?
Is there a way for a bunch of named anchors in a large html to be clickable within a PhantomJs generated PDF file?
I.e. say I have a table of contents or a list of FAQ questions. When clicking on the question/title - I'm taken to its answer/content within the same HTML file which is great but when the same HTML is rendered into a PDF each named anchor becomes an absolute URL (i.e. http://example.com/render.html#anchor_1) so clicking on it opens a browser with that URL instead of jumping to its content within the PDF file.
So, basically, is it possible (and how?) for a markup like this - https://fiddle.jshell.net/jyjuaaog/ to work within the generated PDF?
BTW, this works great when "printing as a PDF file" in Google Chrome but links end up broken when rendered in PhantomJs so there must be something I'm missing that I can't seem to find in the docs.
Any ideas?
Thanks!
A:
Apparently there's a bug in PhantomJs preventing this. As suggested by PhantomJsCloud a quick-and-dirty workaround would be to replace the links with page links.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to stop parallel region of OpenMP 2.0
I look for a better way to cancel my threads.
In my approach, I use a shared variable and if this variable is set, I just throw a continue. This finishes my threads fast, but threads keep theoretically spawning and ending, which seems not elegant.
So, is there a better way to solve the issue (break is not supported by my OpenMP)?
I have to work with Visual, so my OpenMP Lib is outdated and there is no way around that. Consequently, I think #omp cancel will not work
int progress_state = RunExport;
#pragma omp parallel
{
#pragma omp for
for (int k = 0; k < foo.z; k++)
for (int j = 0; j < foo.y; j++)
for (int i = 0; i < foo.x; i++) {
if (progress_state == StopExport) {
continue;
}
// do some fancy shit
// yeah here is a condition for speed due to the critical
#pragma omp critical
if (condition) {
progress_state = StopExport;
}
}
}
A:
You should do it the simple way of "just continue in all remaining iterations if cancellation is requested". That can just be the first check in the outermost loop (and given that you have several nested loops, that will probably not have any measurable overhead).
std::atomic<int> progress_state = RunExport;
// You could just write #pragma omp parallel for instead of these two nested blocks.
#pragma omp parallel
{
#pragma omp for
for (int k = 0; k < foo.z; k++)
{
if (progress_state == StopExport)
continue;
for (int j = 0; j < foo.y; j++)
{
// You can add break statements in these inner loops.
// OMP only parallelizes the outermost loop (at least given the way you wrote this)
// so it won't care here.
for (int i = 0; i < foo.x; i++)
{
// ...
if (condition) {
progress_state = StopExport;
}
}
}
}
}
Generally speaking, OMP will not suddenly spawn new threads or end existing ones, especially not within one parallel region. This means there is little overhead associated with running a few more tiny iterations. This is even more true given that the default scheduling in your case is most likely static, meaning that each thread knows its start and end index right away. Other scheduling modes would have to call into the OMP runtime every iteration (or every few iterations) to request more work, but that won't happen here. The compiler will basically see this code for the threaded work:
// Not real omp functions.
int myStart = __omp_static_for_my_start();
int myEnd = __omp_static_for_my_end();
for (int k = myStart; k < myEnd; ++k)
{
if (progress_state == StopExport)
continue;
// etc.
}
You might try a non-atomic thread-local "should I cancel?" flag that starts as false and can only be changed to true (which the compiler may understand and fold into the loop condition). But I doubt you will see significant overhead either way, at least on x86 where int is atomic anyway.
which seems not elegant
OMP 2.0 does not exactly shine with respect to elegance. I mean, iterating over a std::vector requires at least one static_cast to silence signed -> unsigned conversion warnings. So unless you have specific evidence of this pattern causing a performance problem, there is little reason not to use it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Static, nonmember or static nonmember function?
Every time I have some functionality which is in the direction of "utility", I end up wondering which option is the best. For instance, printing message structs (own or external), some encoding/decoding code or simply a few useful conversion functions in the context I'm working.
The options I think about are:
1) Static function in helper class/struct.
struct helper
{
static bool doSomething(...);
};
2) Nonmember function.
namespace helper
{
bool doSomething(...);
}
3) Static nonmember function.
namespace helper
{
static bool doSomething(...);
}
In some cases there might be necessary to initialize or keep state in the "utility", so then I go for option 1 to avoid "global" state. However, if there is no state that needs to be kept, should I then option 2 or 3? What's the practical difference between option 2 and 3?
What is important to consider and is there a preferred way to approach this? Thanks!
A:
The difference between options 2 and 3 is that in the second case, the function will be internal to the translation unit. If the function is only defined in the cpp this should be the option (which is roughly equivalent to an unnamed namespace --which is a fourth option to consider, again roughly equivalent to 3).
If the function is to be used by different translation units then you should go with option 2. The function will be compiled once (unless you mark it as inline and provide the definition in the header), while with option 3 the compiler will create it's an internal copy in each translation unit.
As of option 1, I would avoid it. In Java or C# you are forced to use classes everywhere, and you end up with utility classes when operations do not nicely map to the object paradigm. In C++ on the other hand, you can provide those operations as free standing functions, and there is no need to add the extra layer. If you opt for the utility class, don't forget to disable the creation of the objects.
Whether the functions are at class or namespace level will affect the lookup, and that will impact on user code. Static member functions need to be qualified with the class name always, unless you are inside the class scope, while there are different ways of bringing namespace functions into scope. As an illustrative example, consider a bunch of math helper functions, and calling code:
double do_maths( double x ) {
using namespace math;
return my_sqrt( x ) * cube_root(x);
}
// alternatively with an utility class:
double do_maths( double x ) {
return math::my_sqrt(x) * math::cube_root(x);
}
Which one you find easier to read is a different story, but I prefer the former: within the function I can select the namespace and then just focus on the operations and ignore lookup issues.
A:
Don't use classes as namespaces. Using a free (ie. nonmember) function inside a namespace is the simplest thing.
Moreover, the function shouldn't be static if it has to be used across multiple translation units. Otherwise, it will be duplicated.
Using classes as namespace is stupid: why make a class which you won't instantiate ?
If some state is to be kept, then have a global state somewhere: static variable inside the function, utility global object (possibly in a "private" namespace, or as a static global variable in one of your translation units). Don't write classes you don't instantiate.
Alas, people with a C#/Java background are used to do this stupid thing, but it is because their language designers have decided unilaterally that free functions are evil. Whether they should be shot or not is a matter of religion.
As a last word of caution: global state should be rarely used. Indeed, it couples your code to the existence of the global state in a way you don't control when the code grows. You should always ask yourself why you don't make this coupling explicit.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python / Django: Get var from cookies
I tried to get distinct_id with request.COOKIES.get('distinct_id'). However Mixpanel saves the data in a not extractable way for me. Anyone knows why there are all these %22%3A%20%22 and how to extraxt distinct_id?
print(request.COOKIES):
{
'djdt': 'hide',
'cookie_bar': '1',
'mp_1384c4d0e46aaaaad007e3d8b5d6eda_mixpanel': '%7B%22distinct_id%22%3A%20%22165edf326870-00fc0e7eb72ed3-34677908-fa000-165e40c268947b%22%2C%22%24initial_referrer%22%3A%20%22%24direct%22%2C%22%24initial_referring_domain%22%3A%20%22%24direct%22%2C%22__alias%22%3A%20%22maz%2B1024%40gmail.com%22%7D',
'csrftoken': 'nvWzsrp3t6Sivkrsyu0gejjjjjiTfc36ZfkH7U7fgHaI40EF',
'sessionid': '7bkel6r27ebd55x262cv9lzv61gzoemw'
}
A:
Check this code. You can run it because use the example you shared. First you must unquote the data in the mixpanel value. I used the suffix of the cookie key to get it. Then after the unquote you must load the json to get back a dictionary.
The code here prints all the keys in the dictionary, but you can easily get the distinct_id using mixpanel_dict.get('distinct_id')
Try it.
from urllib import parse
import json
cookie = {'djdt': 'hide',
'cookie_bar': '1',
'mp_1384c4d0e46aaaaad007e3d8b5d6eda_mixpanel': '%7B%22distinct_id%22%3A%20%22165edf326870-00fc0e7eb72ed3-34677908-fa000-165e40c268947b%22%2C%22%24initial_referrer%22%3A%20%22%24direct%22%2C%22%24initial_referring_domain%22%3A%20%22%24direct%22%2C%22__alias%22%3A%20%22maz%2B1024%40gmail.com%22%7D',
'csrftoken': 'nvWzsrp3t6Sivkrsyu0gejjjjjiTfc36ZfkH7U7fgHaI40EF',
'sessionid': '7bkel6r27ebd55x262cv9lzv61gzoemw'
}
def get_value_for_mixpanel(cookie):
mixpanel_dict = {}
for key in cookie.keys():
if '_mixpanel' in key:
value = parse.unquote(cookie.get(key))
mixpanel_dict = json.loads(value)
return mixpanel_dict
if __name__ == "__main__":
mixpanel_dict = get_value_for_mixpanel(cookie) # type: dict
for key,value in mixpanel_dict.items():
print("%s:%s" %(key, value))
Result
distinct_id:165edf326870-00fc0e7eb72ed3-34677908-fa000-165e40c268947b
$initial_referrer:$direct
$initial_referring_domain:$direct
__alias:[email protected]
| {
"pile_set_name": "StackExchange"
} |
Q:
running a .sh file inside grails server
I am trying to run a bash file(.sh) to make some photos conversion in my grails server, my code is the following to make that task:
def folderTo = grailsAttributes.getApplicationContext().getResource("/files/").getFile()
def f = new File(folderFrom.toString())
def cmd = '/bin/bash /var/lib/tomcat6/webapps/malibueventapp-qa/uploads/convertPhoto.sh /var/lib/tomcat6/webapps/malibueventapp-qa/uploads /var/lib/tomcat6/webapps/malibueventapp-qa/files'
def process = runtime.exec(cmd, null, f);
the problem here is, when I am running it in the server, I am getting the follow error:
Cannot run program "/bin/bash" (in directory "/var/lib/tomcat6/webapps/malibueventapp-qa/uploads"): java.io.IOException: error=12, Cannot allocate memory
that is the only message error i am getting! so I have no ideas what to do!
some sugestions?!
thanks
A:
Sounds like you're not alone:
How to solve "java.io.IOException: error=12, Cannot allocate memory" calling Runtime#exec()?
Above SO thread provides a (possible) solution to your problem, give it a shot.
| {
"pile_set_name": "StackExchange"
} |
Q:
Does "raising awareness" have a meaningful impact?
People often talk about the indirect value of "raising awareness" or "consciousness raising".
For issues that most people already know about (like cancer), is there value to raising awareness?
A:
The paper BAKER, S. B., SWISHER, J. D., NADENICHEK, P. E. and POPOWICZ, C. L. (1984), Measured Effects of Primary Prevention Strategies conducted a meta-analysis on 40 primary prevention studies in the context of education.
For evaluating the effectiveness they defined the Effect Size to be:
where ES is the Effective Size - means the benchmark how well prevention helped, X_t the "posttest mean of the treatment condition", X_c the "posttest mean of control condition" and SD_c the posttest standard deviation of the control condition.
Their benchmark ist defined after Smith, Mary Lee, Gene V. Glass, and Thomas I. Miller. The benefits of psychotherapy. Baltimore: Johns Hopkins University Press, 1980:
Based on the interpretation format in Smith, Glass and Miller (1980),
the combined primary prevention ES (without outlayer) of .55 means
that a hypothetical person not having received a primary prevention
treatment but being at the mean of the control group on dependant
measures will improve on those dependant measures to a position .55
standard deviations above the mean after experiencing primary
prevention treatmeant. In terms of percentile ranks, this represents
an increase from the 50th to approximately the 73rd percentile. In
other words, persons not previously exposed to primary prevention
strategies similar to those listed in Table 1 should improve 23
percentile points after having received such a treatment. Different
figures are appropriate when making estimates for the the specific
subcategories of primary prevention strategies listed in Table 2 (e.g.
moral education, values clarification).
After explaining their benchmark, they define the performance indices:
Cohen (1996) suggested that the criteria for judging effect size
magnitude should be: .20 to .49 = small, .50 to .79 = medium, and
above .80 = large. Therefor, based on Cohen's (1969) criteria, the
overall primary prevention strategy effect size (.91; with outlayer)
and the effect size for career maturity enhancement (1.33),
communication skills training (3.90 and .93; with and without the
outlayer, repsectively), deliberate psychological education programs
(1.43), and deliberate psychological education and moral education
programs combined (.83) may be classified as large. Furthermore, the
overall effective siize for primary prevention programs (:55; without
outlayer) and those for values clarification programs (.69) and all
values clarification programs combined (.51) may be classified as
medium. Finally, the effective size for cognitive coping skills
training programs (.26), moral education programs (.42), substance
abuse preventions programs (.34) and programs blending values
clarification with other strategies (.37) are viewd as low according
to Cohen's (1969) standards. Readers should note that the number of
studies in several categories is relatively small, which suggests
caution in intepreting the comparison of strategies.
(Permanent link, in case imgur is down)
Disclaimer: I ain't no social science scholar, so take my interpretation with care.
Summary:
prevention helps on a general scale in the context of this meta-study.
it fails in moral education
it fails in "coping skills training founded on cognitive-behaviour modification principles"
it's excellent in "communication skills programs"
it fails in "moral education programs"
it also fails in "substance abuse programs"
You have to keep in mind that this meta-study is from 1984. Anecdotal evidence and personal expericen tell me that the "substance abuse programs" improved quite a lot in the last 30 years, and I bet that there are improvements in other areas as well.
P.S.: Needs copyediting, I had to manually type in all the quotes. Also, since I ain't no expert in that field it'd be helpful if someone familiar with the topic could review this posting.
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP File Upload
I'm looking to change my normal PHP file upload into a multiple file upload.
I have this as my single file input:
<input name="sliderfile" id="sliderfile" type="file" />
And this is the PHP I'm using to upload to my server/place in folder and register it into my databases:
if($_POST[sliderurl]){
$path= "uploads/".$HTTP_POST_FILES['sliderfile']['name'];
if($ufile !=none){
if(copy($HTTP_POST_FILES['sliderfile']['tmp_name'], $path)){
date_default_timezone_set('Europe/London');
$added = date("F j, Y");
$query = mysql_query("INSERT INTO `slider` (`imgurl`, `url`, `title`, `description`, `added`) VALUES ('$path', '$_POST[sliderurl]', '$_POST[slidertitle]', '$_POST[sliderdesc]', '$added')");
?>
<div id="fademessage" style="margin-top: 13px;">
<p class="message_greenadmin">Your slide has been successfully created and added to the homepage, Thank you.</p>
</div>
<?php
}else{
?>
<div id="fademessage" style="margin-top: 13px;">
<p class="message_redadmin">Something seems to have gone wrong. Try renaming the photos file name.</p>
</div>
<?php
}
}
}else{
}
?>
Any help would be appreciated,
Thanks!
A:
you need use move_uploaded_file() for save uploaded file. And
foreach ($_FILES['sliderfile'] as $example) {
UploadFile($example);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Offset Partition with only one remainder element
I would like to use a combination of options of Partition in a way that I can't seem to find in the documentation.
Given example input {a,b,c,d,e,f,g}, I would like output {a,b,c,d},{c,d,e,f},{e,f,g}, i.e. an offset partition where one final element is allowed to be smaller at the end of the list.
Partition[{a,b,c,d,e,f,g}, UpTo[4], 2]
comes close, but because it continues to run in steps of 2 it gives an extra {g} which I do not want. Using Upto without the offset gives what I want, but I need the offset. Various other combinations get me near but nothing quite fits. I'm aware I could fiddle with this and create some function that goes through and deletes lists that are too small, but Partition has so many nice options that I feel I must be missing something.
Edit: A few people have given answers that work for the given list, but in case I wasn't clear I need this to work for varying partition and offset size and on lists of unknown length, which I really think must be possible.
A:
Partition[{a, b, c, d, e, f, g}, 4, 2, {1, -2}, {}]
{{a, b, c, d}, {c, d, e, f}, {e, f, g}}
Partition[{a, b, c, d, e, f, g}, 5, 2, {1, -2}, {}]
{{a, b, c, d, e}, {c, d, e, f, g}}
In general, a function that works for varying partition and offset size and on lists of unknown length:
ClearAll[pF]
pF = Partition[##, {1, -#3}, {}] &;
Examples:
pF[{a, b, c, d, e, f, g}, 4, 2]
{{a, b, c, d}, {c, d, e, f}, {e, f, g}}
pF[{a, b, c, d, e, f, g}, 4, 3]
{{a, b, c, d}, {d, e, f, g}}
pF[{a, b, c, d, e, f, g}, 5, 2]
{{a, b, c, d, e}, {c, d, e, f, g}}
pF[{a, b, c, d, e, f, g}, 5, 3]
{{a, b, c, d, e}, {d, e, f, g}}
A:
Most@Partition[list, 4, 2, 1, {}]
{{a, b, c, d}, {c, d, e, f}, {e, f, g}}
| {
"pile_set_name": "StackExchange"
} |
Q:
Wordpress's loop
<?php if(have_posts()) : while(have_posts()) : the_post(); ?>
While it use while(have_posts()), I feel it's useless. Suppose it doesn't have the while condition, the first if(have_posts()) to check the block whether have a post. If there is no post, the programme goes out the loop. if there is a post, then execute the_post(). Any tips would be appreciated.
A:
First, it check if there are posts to display on that particular page using:
if(have_posts())
if there are any, it will loop through each post using:
while(have_posts())
Right after that, it extract post's data using:
the_post();
As for the syntax it self, it uses what is called ternary operation (CMIIW here).
For more detailed explanation, you can read about the loop on wordpress codex.
Here's a little explanation taken from that page:
Once WordPress has finished loading the blog header and is descending into the template, we arrive at our post Loop. The have_posts() simply calls into $wp_query->have_posts() which checks a loop counter to see if there are any posts left in the post array. And the_post() calls $wp_query->the_post() which advances the loop counter and sets up the global $post variable as well as all of the global post data. Once we have exhausted the loop, have_posts() will return false and we are done.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it OK to use "empty-handed" on an animal?
Can I write the following?
One of the seagulls spotted a fish and dove after it, but came up empty-handed
If not, what other word I can use to replace empty-handed?
A:
It is most definitely acceptable to use the phrase empty-handed to describe animals.
Even if the animal you're referring to has no hands, the phrase empty-handed is understood to mean "having acquired nothing."
A:
You can write simply came up empty to indicate that its attempt was unsuccessful. (see m-w.com's definition, below item 6.)
As pointed out in comments, "dropped itself into the water" sounds a bit off. I would suggest something more like this:
One of the seagulls spotted a fish and dove after it, but came up empty.
A:
Gulls have webbed feet with small talons. Empty-taloned or empty-clawed appears to be a reasonable description.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to filter ebay search results by shipping price
I live in quite a remote location. While it is reasonably simple to filter ebay search results so that I only see items that will ship to me, some of those will have a ludicrous shipping cost.
Is it possible to filter out items from a ebay search that have shipping price over a given value?
A:
No, there is no such possibility, you have to look out for it manually. You can filter the items in terms of their actual cost only and not the additional shipping charges.
Also I think that the Shipping Charges are only calculated once you add a particular item to your cart, select the seller from who you would like to purchase and give your shipping address - so there is no possibility to filter items based on shipping costs as they are not calculated at that time at all.
The same item has various shipping charges based on from which seller you choose to buy, whether you have a premium account (or whatever they call it).
A:
You can try auctionsensor ebay search tool. You can search items by total price (list price + shipping fee). For example, if your max price is $50, and the item's list price is $40 and shipping fee is $11, auctionsensor will filter it out. It is free and no sign up required. Highly recommended.
Some of the auction sniper software also have advanced search/filter feature, for example, JoyBidder eBay Auction Sniper, you can click Ctrl+F to bring up a filter bar to allow more granular filtering capability. But it is not free and could be over-kill, if you just buy or sell on eBay occasionally.
| {
"pile_set_name": "StackExchange"
} |
Q:
Show another button when using "commitEditingStyle" in a UITableView datasource
I want to show an "Edit" button below the default "Delete" button that shows up with a swipe gesture on a cell when you implement "commitEditingStyle" on the table's datasource.
Is this possible by only implementing "commitEditingStyle" or will i have to implement my own way of showing the buttons on the cells? And if it is, how would i handle the commit?
A:
Yes you have to implement your own way of showing buttons on UITableViewCells by customizing the UITableViewCells.
As far as your requirement is concerned, I dont think its a good idea to show the "edit" button below the "delete" button, as accommodating both buttons vertically one-by-one may disappoint the user to make desired touch actions.
I mean to say, user may want to touch edit, but due to successive placing of custom edit/delete buttons, delete button may get clicked which is dangerous & not acceptable too. Of course,it will cause user to take proper care every-time making any of the edits.
| {
"pile_set_name": "StackExchange"
} |
Q:
Leer/escribir arrays de char en ficheros binarios
Estoy intentando guardar binariamente strings a partir de arrays estáticos de caracteres para posteriormente imprimirlos. La cuestión es que, pese a a que les asigno el valor de manera estática (con lo que al crearlos, se deberían crear con el \0 al final, por lo que no debería ponerlo yo a mano). El mayor problema es que estos arrays forman parte de una estructura, por lo que les he dado un valor máximo en la declaración de la misma y posteriormente asignar valores. Dicha estructura parece guardarse correctamente, pero al leer los arrays, no se imprimen correctamente. He aquí el código:
La estructura:
typedef struct
{
char P [250];
char R1 [250] ;
char R2 [250] ;
char R3[250] ;
} t_p_r;
La asignación de valores a sus arrays y el intento de impresión de los mismos:
arrPreg =(t_p_r*)malloc(sizeof(t_p_r));
t_p_r preg;
strcpy(preg.P,"hola");
strcpy(preg.R1,"1");
strcpy(preg.R2, "2");
strcpy(preg.R3 ,"3");
arrPreg[0] = preg;
guardarPR(arrPreg,1);
pS = (t_p_r*)malloc(sizeof(t_p_r));
size = leerPR(pS);
for(int i=0; i<strlen(pS[0].P);i++)
{
printf("%c\n", pS[0].P[i] );
}
Los métodos para lectura/escritura:
void guardarPR(t_p_r P[], int numP)
{
FILE* fichero = fopen("PR.dat", "wb");
fputc(numP, fichero);
fwrite(&P, sizeof( t_p_r), numP, fichero);
fclose(fichero);
}
int leerPR(t_p_r* PL)
{
int numElem;
FILE* fichero = fopen("PR.dat", "rb");
numElem = fgetc(fichero);
PL= (t_p_r*) malloc((numElem) * sizeof(t_p_r));
fread(&PL, sizeof(t_p_r) , numElem, fichero);
fclose(fichero);
return numElem;
}
EDIT
Así mismo, he hecho otra prueba, esta vez guardando las estructuras individualmente. Aunque da un mejor resultado, sigue sin funcionar:
guardarSingular(preg);
t_p_r preg2;
leerSingular(&preg2);
printf(" %s\n", preg2.P);
printf(" %s\n", preg2.R1);
printf(" %s\n", preg2.R2);
printf(" %s\n", preg2.R3);
void guardarSingular(t_p_r PG)
{
FILE* fichero = fopen("PR.dat", "wb");
fputc(1, fichero);
fwrite(&PG, sizeof(t_p_r), 1, fichero);
fclose(fichero);
}
void leerSingular(t_p_r* PL)
{
FILE* fichero = fopen("PR.dat", "rb");
fread(PL, sizeof(t_p_r) , 1, fichero);
fclose(fichero);
}
Al parecer, en vistas al resultado, las estructuras parecen guardarse bien, pero a la hora de leerlas y querer mostrarlas, muestran caracteres extraños distintos a los introducidos al inicio. ¿Cómo puedo almacenar esta estructura en un fichero binario para poder recuperar sus strings tal y como los guardé?
A:
Dicha estructura parece guardarse correctamente
Pues yo diría que no:
void guardarPR(t_p_r P[], int numP)
// ^^^ P es un puntero
{
FILE* fichero = fopen("PR.dat", "wb");
fputc(numP, fichero);
fwrite(&P, sizeof( t_p_r), numP, fichero);
// ^^ En el fichero guardas la referencia al puntero
fclose(fichero);
}
fwrite te pide un puntero a la información a guardar... y tu le estás pasando la referencia a un puntero... es decir, un puntero doble...
Prueba a pasarle el puntero directamente:
void guardarPR(t_p_r P[], int numP)
{
FILE* fichero = fopen("PR.dat", "wb");
fputc(numP, fichero);
fwrite(P, sizeof( t_p_r), numP, fichero); // <<--- Linea modificada
fclose(fichero);
}
Aunque el código será más legible si cambias la firma de la función:
void guardarPR(t_p_r *P, int numP)
Y ahora vamos a revisar la lectura:
int leerPR(t_p_r* PL)
{
int numElem;
FILE* fichero = fopen("PR.dat", "rb");
numElem = fgetc(fichero);
PL= (t_p_r*) malloc((numElem) * sizeof(t_p_r)); // <<--- cambio local
fread(&PL, sizeof(t_p_r) , numElem, fichero);
fclose(fichero);
return numElem;
}
Si tu tienes un código tal que:
void func (int var)
{ var = 10; }
int main ()
{
int v;
func (v);
printf ("%d\n",v);
}
¿que valor imprime?
La respuesta correcta es un numero indeterminado y es facil ver que la asignación que se hace en func es local... con el valor de los punteros pasa exactamente lo mismo... los punteros se usan para modificar una memoria común... no para usar una memoria diferente... si quieres ese efecto debes usar punteros dobles:
int leerPR(t_p_r** PL)
{
int numElem;
FILE* fichero = fopen("PR.dat", "rb");
numElem = fgetc(fichero);
*PL= (t_p_r*) malloc((numElem) * sizeof(t_p_r));
fread(*PL, sizeof(t_p_r) , numElem, fichero);
fclose(fichero);
return numElem;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there an ideal height for a workbench?
Is there a universal standard height that people try to go for when building workbenches? Should DIY tabletops be tailor made to the height of the user and how does the ideal height of the tabletop correlate to the person?
A:
I don't think there is specific universal height as people aren't manufactured in a specific universal height.
Googling for "workbench height" returns many results asking the same thing: what is the best height for a workbench.
This page suggests the following method:
A good rule of thumb is to make the workbench table the same height as
the distance from the floor to your wrist when letting your arms hang
down. So if you stand next to your table, the height would be exactly
where your hands would be touching it if you put your palms on the
table.
The page goes on to say that you should consider the type of work you'll be doing. If you're doing lots of detail work, you may want to sit (so the bench shouldn't be too low or too high to accommodate a chair). If you're standing and decide to put those foam mats down to make it more comfortable, you might want to add a half inch or so. The final suggestion is if you have the space for it, have more than one workbench.
A:
There is a large body of information about what size furniture and tools should be. The field concerning sizing furniture to individuals and populations is called Anthropometrics and information about safety and ease of use is called Ergonomics.
If you are building your own workbench for your own use, then you should size it to yourself unless you expect others to use it. Why buy off the rack if you can get tailored for less?
Most furniture is optimized for the middle of the height distribution curve which is roughly 5'8". I got into woodworking in the first place because I am 6'4" tall and absolutely nothing fits. It's all literally 6" too short.
I used the "fall drop" rule to size my generic workshop surfaces. Just stand relaxed and let your hands fall down as if resting comfortably on a surface in front of you. It's the position you hands will just fall or drop to if you try to rest them on an imaginary surface. It gives a higher bench than the using the wrist line method above.
I suggest creating a mock-up first using whatever is available and easily resized. I used a chair, a sturdy box and books of various thicknesses. I swapped books and fiddled with the height of the mock-up until I found the most comfortable height. In my case, it was exactly 39".
You'll know it when you find your own ideal height because it just feels right.
However, shuffler is correct that different work requires different heights. The "fall drop" rule sizes a bench for use with modern power tools and precision hand tools but if you use other tools you might want a higher or lower bench e.g. heavy handsaws, chisels and planes usually require something like saw bench which is usually just under knee height.
I use a mini-bench on top of my main 39" surface if I have fiddling work like soldering.
Oh, and build yourself a custom stool and work supports at the same time. You'll be glad you did.
A:
There's no real answer to this - it depends on how tall you are, what you are using the bench for and if you are standing or sitting (and then, are you using a chair or stool?). The use for it might also play a role. Things like electrical soldering work require you to be a lot closer to the project then wood working.
The simple solution to this is to find a bench with adjustable legs. Mine is adjustable by about 16" - I started with it as high as it could go (I'm 6'), but eventually brought it down a couple inches; it's still pretty high which means I don't need to bend over to work on things. I find it comfortable like this, but you might hate it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Picard groups, ample cones, and proper birational maps
Let $f:Y\to X$ be a proper birational map of normal varieties over an algebraically closed field which is an isomorphism over the regular locus.
Q1: Is it the case that the pullback $f^*\operatorname{Pic}(X)\to\operatorname{Pic}(Y)$ is always injective?
(Update: this was answered in the affirmative by Jason Starr.)
Q2: Suppose that there exists a finite set $\{C_i \mid i\in I\}$ of projective curves in $Y$ such that a line bundle is ample (respectively nef) on $Y$ if and only if its restriction to each $C_i$ has positive (respectively non-negative) degree. Is it the case that a line bundle on $X$ (interpreted via pullback as a line bundle on $Y$) is ample (respectively nef) if and only if its restriction to each $C_i$ that isn't contracted by $f$ has positive (respectively non-negative) degree?
For example, suppose that $Y$ is a crepant resolution of a Kleinian singularity, with exceptional divisor $E\subset Y$ consisting of a finite union of projective lines. Suppose that $X$ is a partial resolution, obtained from $Y$ by contracting some (but not all) of the components of $E$. Then the Picard group of $X$ should be isomorphic to the subgroup of the Picard group of $Y$ consisting of line bundles whose restrictions to the contracted curves have degree zero, and its ample cone should be those line bundles whose restrictions to the un-contracted curves have positive degree.
A:
There is a relative version of the ample cone, discussed a bit in Section 1.6.2 of the draft http://www.math.utah.edu/~defernex/book.pdf . There is indeed a relative version of Kleiman's criterion telling you that the interior of the relative ample cone is the relative nef cone.
But just knowing the relative ample cone of $f$ and the ample cone of $X$ doesn't really tell you very much about the ample cone of $Y$, unless you are only looking for extremely coarse information. For example, take $X$ the blow-up of $\mathbb P^2$ at eight general points. The nef cone is a rational polyhedral cone, since this is a del Pezzo surface. Now let $Y$ be the blow-up of $X$ at a single general point. The relative nef cone is a cone in a 1-dimensional vector space, and just a single ray. But the nef cone of $Y$ is a wild thing with infinitely many extremal rays.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get Control Register (CR2) value?
Do we have a way to find the value of CR2 from core of x86-64 ?
Info registers doesn't show it.
(gdb) info registers all
rax 0x7fc9ca854000 140504662884352
rbx 0x119ad58 18459992
rcx 0xa0000 655360
rdx 0x7fca99045300 140508127318784
rsi 0x1 1
rdi 0x120 288
rbp 0x7fc9d0104e40 0x7fc9d0104e40
rsp 0x7fc9d0104c70 0x7fc9d0104c70
r8 0x0 0
r9 0xc0 192
r10 0x0 0
r11 0x7fca1432b2e0 140505898988256
r12 0x7fc9c95e5d80 140504643558784
r13 0x800a0003 2148139011
r14 0x0 0
r15 0x7fc94537d198 140502426440088
rip 0x666831 0x666831
eflags 0x10206 [ PF IF RF ]
cs 0x33 51
ss 0x2b 43
ds 0x0 0
es 0x0 0
fs 0x0 0
gs 0x0 0
st0 0 (raw 0x00000000000000000000)
st1 0 (raw 0x00000000000000000000)
st2 0 (raw 0x00000000000000000000)
st3 0 (raw 0x00000000000000000000)
st4 0 (raw 0x00000000000000000000)
st5 0 (raw 0x00000000000000000000)
st6 0 (raw 0x00000000000000000000)
st7 0 (raw 0x00000000000000000000)
fctrl 0x37f 895
fstat 0x0 0
ftag 0xffff 65535
fiseg 0x0 0
fioff 0x0 0
foseg 0x0 0
fooff 0x0 0
fop 0x0 0
xmm0 {
v4_float = {0x0, 0x0, 0x0, 0x0},
v2_double = {0x0, 0x0},
v16_int8 = {0x0 <repeats 16 times>},
v8_int16 = {0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
v4_int32 = {0x0, 0x0, 0x0, 0x0},
v2_int64 = {0x0, 0x0},
uint128 = 0x00000000000000000000000000000000
}
xmm1 {
v4_float = {0x0, 0x0, 0x0, 0x0},
v2_double = {0x0, 0x0},
v16_int8 = {0x0 <repeats 16 times>},
v8_int16 = {0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
v4_int32 = {0x0, 0x0, 0x0, 0x0},
v2_int64 = {0x0, 0x0},
uint128 = 0x00000000000000000000000000000000
}
xmm2 {
v4_float = {0x0, 0x0, 0x0, 0x0},
v2_double = {0x0, 0x0},
v16_int8 = {0x21, 0x80, 0x0 <repeats 14 times>},
v8_int16 = {0x8021, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
v4_int32 = {0x8021, 0x0, 0x0, 0x0},
v2_int64 = {0x8021, 0x0},
uint128 = 0x00000000000000000000000000008021
}
xmm3 {
v4_float = {0x0, 0x0, 0x0, 0x0},
v2_double = {0x0, 0x0},
v16_int8 = {0xa8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x58, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
v8_int16 = {0xa8, 0x0, 0x0, 0x0, 0x58, 0x0, 0x0, 0x0},
v4_int32 = {0xa8, 0x0, 0x58, 0x0},
v2_int64 = {0xa8, 0x58},
uint128 = 0x000000000000005800000000000000a8
}
xmm4 {
v4_float = {0x0, 0x0, 0x0, 0x0},
v2_double = {0x0, 0x0},
v16_int8 = {0x0 <repeats 16 times>},
v8_int16 = {0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
v4_int32 = {0x0, 0x0, 0x0, 0x0},
v2_int64 = {0x0, 0x0},
uint128 = 0x00000000000000000000000000000000
}
xmm5 {
v4_float = {0x0, 0x0, 0x0, 0x0},
v2_double = {0x0, 0x0},
v16_int8 = {0x92, 0xff, 0x0 <repeats 14 times>},
v8_int16 = {0xff92, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
v4_int32 = {0xff92, 0x0, 0x0, 0x0},
v2_int64 = {0xff92, 0x0},
uint128 = 0x0000000000000000000000000000ff92
}
xmm6 {
v4_float = {0x0, 0x0, 0x0, 0x0},
v2_double = {0x0, 0x0},
v16_int8 = {0xf8, 0x51, 0x0, 0x0, 0x33, 0xcc, 0x0, 0x0, 0xc9, 0x7f, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
v8_int16 = {0x51f8, 0x0, 0xcc33, 0x0, 0x7fc9, 0x0, 0x0, 0x0},
v4_int32 = {0x51f8, 0xcc33, 0x7fc9, 0x0},
v2_int64 = {0xcc33000051f8, 0x7fc9},
uint128 = 0x0000000000007fc90000cc33000051f8
}
xmm7 {
v4_float = {0x0, 0x0, 0x0, 0x0},
v2_double = {0x0, 0x0},
v16_int8 = {0x0 <repeats 16 times>},
v8_int16 = {0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
v4_int32 = {0x0, 0x0, 0x0, 0x0},
v2_int64 = {0x0, 0x0},
uint128 = 0x00000000000000000000000000000000
}
xmm8 {
v4_float = {0x0, 0x0, 0x0, 0x0},
v2_double = {0x0, 0x0},
v16_int8 = {0x0 <repeats 16 times>},
v8_int16 = {0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
v4_int32 = {0x0, 0x0, 0x0, 0x0},
v2_int64 = {0x0, 0x0},
uint128 = 0x00000000000000000000000000000000
}
xmm9 {
v4_float = {0x0, 0x0, 0x0, 0x0},
v2_double = {0x0, 0x0},
v16_int8 = {0xe8, 0x3b, 0x3, 0x0, 0xf8, 0x97, 0x2, 0x0, 0x92, 0xff, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
v8_int16 = {0x3be8, 0x3, 0x97f8, 0x2, 0xff92, 0x0, 0x0, 0x0},
v4_int32 = {0x33be8, 0x297f8, 0xff92, 0x0},
v2_int64 = {0x297f800033be8, 0xff92},
uint128 = 0x000000000000ff92000297f800033be8
}
xmm10 {
v4_float = {0x0, 0x0, 0x0, 0x0},
v2_double = {0x0, 0x0},
v16_int8 = {0x82, 0xa3, 0x1, 0x0, 0x66, 0x98, 0x1, 0x0, 0x92, 0xff, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
v8_int16 = {0xa382, 0x1, 0x9866, 0x1, 0xff92, 0x0, 0x0, 0x0},
v4_int32 = {0x1a382, 0x19866, 0xff92, 0x0},
v2_int64 = {0x198660001a382, 0xff92},
uint128 = 0x000000000000ff92000198660001a382
}
xmm11 {
v4_float = {0x0, 0x0, 0x0, 0x0},
v2_double = {0x0, 0x0},
v16_int8 = {0x92, 0xff, 0x0 <repeats 14 times>},
v8_int16 = {0xff92, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
v4_int32 = {0xff92, 0x0, 0x0, 0x0},
v2_int64 = {0xff92, 0x0},
uint128 = 0x0000000000000000000000000000ff92
}
xmm12 {
v4_float = {0x0, 0x0, 0x0, 0x0},
v2_double = {0x0, 0x0},
v16_int8 = {0xf8, 0x51, 0x0, 0x0, 0x33, 0xcc, 0x0, 0x0, 0xc9, 0x7f, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
v8_int16 = {0x51f8, 0x0, 0xcc33, 0x0, 0x7fc9, 0x0, 0x0, 0x0},
v4_int32 = {0x51f8, 0xcc33, 0x7fc9, 0x0},
v2_int64 = {0xcc33000051f8, 0x7fc9},
uint128 = 0x0000000000007fc90000cc33000051f8
}
xmm13 {
v4_float = {0x0, 0x0, 0x0, 0x0},
v2_double = {0x0, 0x0},
v16_int8 = {0x0 <repeats 16 times>},
v8_int16 = {0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
v4_int32 = {0x0, 0x0, 0x0, 0x0},
v2_int64 = {0x0, 0x0},
uint128 = 0x00000000000000000000000000000000
}
xmm14 {
v4_float = {0x0, 0x0, 0x0, 0x0},
v2_double = {0x0, 0x0},
v16_int8 = {0xe8, 0x3b, 0x3, 0x0, 0xf8, 0x97, 0x2, 0x0, 0x92, 0xff, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
v8_int16 = {0x3be8, 0x3, 0x97f8, 0x2, 0xff92, 0x0, 0x0, 0x0},
v4_int32 = {0x33be8, 0x297f8, 0xff92, 0x0},
v2_int64 = {0x297f800033be8, 0xff92},
uint128 = 0x000000000000ff92000297f800033be8
}
xmm15 {
v4_float = {0x0, 0x0, 0x0, 0x0},
v2_double = {0x0, 0x0},
v16_int8 = {0x82, 0xa3, 0x1, 0x0, 0x66, 0x98, 0x1, 0x0, 0x92, 0xff, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
v8_int16 = {0xa382, 0x1, 0x9866, 0x1, 0xff92, 0x0, 0x0, 0x0},
v4_int32 = {0x1a382, 0x19866, 0xff92, 0x0},
v2_int64 = {0x198660001a382, 0xff92},
uint128 = 0x000000000000ff92000198660001a382
}
mxcsr 0x1f80 [ IM DM ZM OM UM PM ]
A:
From Intel's instruction set manual page 3-514 "MOV — Move to/from Control Registers".
This instruction can be executed only when the current privilege level is 0.
As GDB is a ring 3 process, it can't read cr2 and any other control register.
Of course, process core dumps wouldn't have control registers because these registers are not part of task state.
| {
"pile_set_name": "StackExchange"
} |
Q:
sudo apt-get install php-redis stopped to work
in our CircleCI build, we have a few months this installation of PHP redis but it stopped to work today. The return message is below.
Please, do you know how to fix it? I am a little confused what to do. Thank you for your help.
sudo apt-get install php-redis Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created or
been moved out of Incoming. The following information may help to
resolve the situation:
The following packages have unmet dependencies:
php-redis: Depends: php-igbinary but it is not going to be installed
Dep
ends: phpapi-20160303 but it is not installable or
phpapi-20151012 but it is not installable or
phpapi-20131226 but it is not installable E: Unable to correct problems, you have held broken packages.
sudo apt-get install php-redis returned exit code 100
Action failed: sudo apt-get install php-redis
Our flow in CircleCi looks like this:
sudo apt-add-repository -y ppa:ondrej/php
sudo apt-get update
sudo apt-get install php-redis
echo 'extension=/usr/lib/php/20131226/redis.so' | sudo tee /opt/circleci/php/$(phpenv global)/etc/conf.d/redis.ini
echo 'extension=/usr/lib/php/20131226/igbinary.so' | sudo tee /opt/circleci/php/$(phpenv global)/etc/conf.d/igbinary.ini
SOLVED:
use sudo apt-get -f install php-redis
A:
It sounds as though there are other dependencies which are not installed by the main package. This usually happens to me when I install by dpkg (a downloaded Chrome deb package is the usual one).
When you run
sudo apt-get upgrade
It will usually tell you there has been some installation failure and suggests that you run
sudo apt-get -f install
These will usually resolve the dependencies and install any extra packages required.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to pull in changes from skeleton sub-repository into production super-repository
I am using the Aurelia skeleton which contains various project setups for different purposes, but it is more of a general question of how you would do something with git like discribed below.
I would like to be able to merge in the updates published in the GitHub skeleton repository to the project I am actually working on. How would you do that?
At the moment I just initialized a new local repository in the skeleton-typescript project (which I am using) and connected it to a private remote repo to push my changes. But with this setup, I am polluting the parent repository (remote pointing to aurelia-skeleton on Github) with my project-specific changes.
It would be perfect to have some kind of one-way tracking going as the aurelia-skeleton remote repository is normally only used to pull changes in.
As a second step, it would be interesting how you could create a pull request with such a setup. In this case, I would like to use the changes I made in the sub-repository to be merged into the fork of the aurelia remote...
A:
My usual workflow is to create a dedicated branch from which to track the upstream project. You can cherry pick what you want onto that branch and create a pull request without muddying the template with your project specifics.
First thing, go ahead and fork aurelia/skeleton-navigation so you can easily issue a pull request through Github's GUI.
Clone your fork of the project with remote named upstream in a new folder called skeleton-typescript
git clone -o upstream [email protected]:YOUR_GITHUB_USERNAME/skeleton-navigation.git skeleton-typescript
cd skeleton-typescript
Rename master branch.
git branch -m asmaster
Create a new repository for skeleton-typescript
Tip: You can do this right from the command line using Github's API with something like curl
curl --data '{"name":"skeleton-typescript"}' -u YOUR_GITHUB_USERNAME https://api.github.com/user/repos
Add the remote.
git remote add origin [email protected]:YOUR_GITHUB_USERNAME/skeleton-typescript.git
Split the repo into a subtree (see source code for man page) which will contain a new tree with all the commit history of files in the prefix directory.
git subtree split --prefix=skeleton-typescript
This will print out a single commit ID which is the HEAD of the subtree.
539d913a8cf9b34b644273b5cdb480359553247c
Create your master branch from that commit.
git checkout -b master 539d913a8cf9b34b644273b5cdb480359553247c
Push to and track your new repo.
git push -u origin master
Backporting
Commit some work on skeleton-typescript
echo "notable contribution" >> file.txt
git add .
git commit -m "backport test commit"
git push origin master
Checkout the upstream super-project branch, and cherry-pick the subtree commits.
git checkout asmaster
git cherry-pick -x --strategy=subtree master
git push upstream asmaster:master
Now you can issue a pull request from your upstream fork YOUR_GITHUB_USERNAME/skeleton-navigation:master branch to their aurelia/skeleton-navigation:master branch.
Updating
Now there's going to be updates no doubt to your upstream's upstream (aurelia/skeleton-navigation:master) which will include updates to your subtree's skeleton-typescript folder.
Add another remote to track the original project.
git remote add upupstream [email protected]:aurelia/skeleton-navigation.git
Note that you now have 3 remotes in your local repository.
git remote -v
origin [email protected]:YOUR_GITHUB_USERNAME/skeleton-typescript.git (fetch)
origin [email protected]:YOUR_GITHUB_USERNAME/skeleton-typescript.git (push)
upstream [email protected]:YOUR_GITHUB_USERNAME/skeleton-navigation.git (fetch)
upstream [email protected]:YOUR_GITHUB_USERNAME/skeleton-navigation.git (push)
upupstream [email protected]:aurelia/skeleton-navigation.git (fetch)
upupstream [email protected]:aurelia/skeleton-navigation.git (push)
Pull down updates.
git checkout asmaster
git pull upupstream master
Split off the subtree again and grab the HEAD commit.
git subtree split --prefix=skeleton-typescript
095c0c9f7ed06726e9413030eca4050a969ad0af
Switch back to subproject.
git checkout master
If you have never backported changes, then a notable attribute of git subtree split is that you'll have the exact same hash commit history, so you can fast forward merges without rewriting history. From the docs:
Repeated splits of exactly the same history are guaranteed to be identical (i.e. to produce the same commit ids). Because of this, if you add new commits and then re-split, the new commits will be attached as commits on top of the history you generated last time, so git merge and friends will work as expected.
git merge 095c0c9f7ed06726e9413030eca4050a969ad0af
However, if you have already backported cherry-picked updates, or any other changes to the subtree history, then you'll want to rebase changes, otherwise you'll have duplicate commits.
git rebase 095c0c9f7ed06726e9413030eca4050a969ad0af
| {
"pile_set_name": "StackExchange"
} |
Q:
Show div on Submit button
This question might have been asked many times, I have been having difficulty in applying approach which are given on different websites.
I have a JSP page which contains a search field
---------------------
| | Type a Character to Search from the Database
| |
---------------------
=============
| Submit |
=============
When the user types in a character and clicks on the Submit button, I am calling a different JSP "xyz.jsp" like
<div id="searchPage">
<%@include file="searchResult.jsp"%>
</div>
My requirement is When the page gets loaded, it should display only the search text box and a submit button. When he/she click on the submit button, the div which is including another jsp should get called and displayed.
Note
I need to retain the value entered by the user in the search text field on the click on submit button.
Code for search page
<div id="Search1">
<aui:form action="......" method="post" name="searchForm" id="searchFormId">
<aui:input id='name' name="name" label="Student Name" type="text" value="" size="50"/>
</aui:form>
</div>
A:
You can do something like this
<script type="text/javascript">
function showResult(){
var ele = document.getElementById("Search1");
if(ele.style.display == "block") {
ele.style.display = "block";
}
else {
ele.style.display = "none";
}
}
</script>
| {
"pile_set_name": "StackExchange"
} |
Q:
Using the dominated convergence theorem to show the following equality
I am trying to show the above using the Dominated convergence theorem. I have let the integrand be the limit point of a sequence of functions obtained by replacing the log by its expansion ($\log(\frac{1}{x})=\log((\frac{1}{x}-1)+1)$). I have reduced the problem to finding the integral:
$$\int_{0}^{1}{x^{\frac{1}{3}-k}(1-x)^{k-1}}dx$$
but I feel Cike this is the wrong approach. How can this be shown using The Dominated convergence Theorem, and more specifically how can we choose an appropriate sequence of functions?
A:
Let $x = e^{-t} \therefore dx=-e^{-t}dt$. The integral is,
$$I=\int_{0}^{\infty}\frac{te^{-t/3}}{1-e^{-t}}dt$$
$\because 0 < e^{-t} <1$ for $t \in (0,\infty)$, we can express the denominator as a geometric progression.
$$I=\int_{0}^{\infty}te^{-t/3}(1+e^{-t}+\cdots)dt$$
$\because \int_0^{\infty}te^{-at}dt=\frac{1}{a^2}$, we get,
$$I=3^2+\frac{3^2}{4^2}+\frac{3^2}{7^2}\cdots=9\sum_{n=1}^{\infty}\frac{1}{(3n+1)^2}$$
which is the desired result. Hope this helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
Android Thermal printer Font Family
I'm using this app to print from MTP-II APP and it's working fine. However, I need to print in a sans-serif font and it's printing in a serif font. is there a way I can add a font to it?
A:
After suffering for a long time. I finally found a way around that is to convert it into PDF file and then print it. it treats the whole file as an image.
True Solution: The manual has commands to change the font on the printer. there are two fonts available, you can switch between them programmatically and also by pressing a sequence of buttons on the printer.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I publish a book permanently free on Amazon
I have tried to publish a book permanently free on Amazon but I couldn't. I have seen many books on Kindle that seems to be permanently free. How do I publish a book on Kindle and keep it free forever?
If anyone knows how to set a book to free without subscribing to Kindle Select program it is also something I would like to know how to do and maybe it is linked to this question answer.
A:
Amazon does still do the price matching, and that is the only way to get your book listed as free on their site. The advantage of Smashwords is in distributing to Apple and Sony. If you go to your e-book's details page on Amazon, you will see a link that says "tell us about a lower price". You can click that link and provide them a link to the product page for your free book at one of the other sites, and eventually they will match it. Again, this seems to be more effective with Apple and Sony. The process may take a week or two, so if you can get others to click that link and share the news, it will help speed things up.
If you want to make your book free for a limited time or on a specific date, I would definitely NOT recommend this approach. There is no way to control how quickly or when Amazon will respond, so you won't be able to determine the specific date(s). Also, if you think you may want to raise the price back up after a while, I would not recommend doing this. I have one title that I published under a pseudonym that has been free for months, in spite of the fact that I have raised the price on all other sites and tried repeatedly to get Amazon to raise the price.
A:
You can have it permanently published for free at Smashwords. Amazon used to do price matching, and this used to be the way to publish your book for free at Amazon.
I am not sure if Amazon is still following this method, and no method could realistically be permanent in Amazon's ever changing business model. You will still need to check periodically.
If your goal is to stay on the "Kindle free list", you will need to check periodically. If your goal is to always have a place someone can get your book for free, Smashwords may be the better vehicle. Also Project Gutenberg has opened a new Self-Publishing Portal, which may be worth looking into.
A:
Amazon does not allow "permanently free" Kindle books. They want to make money. :D You may have seen what you think are permanently-free Kindle books, and though they were probably only running a free promotion via Kindle Select, who am I to say there aren't a few flukes out there? Perhaps you did — I have seen stranger things on Amazon.
But regardless, the point remains: you and I cannot.
This is why there are so many $0.99 books. And it's not a bad deal. Most people have no problem forking out a dollar, even on the risk of a bad book. In fact, many people don't even think twice about making a string of 99¢ purchases. Embrace it. You might even end up earning enough to pay for your subscription to Netflix.
| {
"pile_set_name": "StackExchange"
} |
Q:
PayPal sandbox for testing - is it safe?
I've been working with PayPal's Adaptive Payments API for a while and i'm ready to begin testing of my website.
My plan is to create a bunch of PayPal sandbox accounts and give them to family and friends to use on my site.
However, I've noticed that when I log in to a sandbox account (at sandbox.paypal.com), it says 'Logged in as [email protected]' where [email protected] is my actual PayPal account.
Does logging in to the fake sandbox accounts give the testers access to my real PayPal account?
A:
No, it doesn't. Your real PayPal email address shows up at the top of the page because that's what you used to sign into https://developer.paypal.com, and there's a cookie on your computer telling the Sandbox that you signed in with that email address. It won't show up for other users.
| {
"pile_set_name": "StackExchange"
} |
Q:
Irregularity in Python class variable assignment
I'm trying to create a class which has multiple class-level variables, some of which have calculated values which reference previously declared class-level variables. However, I'm having difficulty referencing the variables at certain points.
My first attempt:
#!/usr/bin/env python
from decimal import Decimal
import math
class Foo(object):
NUM_BUCKETS = 10
BUCKET_SIZE = Decimal(1.0 / NUM_BUCKETS)
BUCKET_LABELS = tuple("BUCKET_{}".format(int(BUCKET_SIZE * i * 100)) for i in xrange(1, NUM_BUCKETS + 1))
print Foo.BUCKET_LABELS
Result:
> python test.py
Traceback (most recent call last):
File "test.py", line 5, in <module>
class Foo(object):
File "test.py", line 8, in Foo
BUCKET_LABELS = tuple("BUCKET_{}".format(int(BUCKET_SIZE * i * 100)) for i in xrange(1, NUM_BUCKETS + 1))
File "test.py", line 8, in <genexpr>
BUCKET_LABELS = tuple("BUCKET_{}".format(int(BUCKET_SIZE * i * 100)) for i in xrange(1, NUM_BUCKETS + 1))
NameError: global name 'BUCKET_SIZE' is not defined
Trying to access the class variable via the class name doesn't work either:
#!/usr/bin/env python
from decimal import Decimal
import math
class Foo(object):
NUM_BUCKETS = 10
BUCKET_SIZE = Decimal(1.0 / NUM_BUCKETS)
BUCKET_LABELS = tuple("BUCKET_{}".format(int(Foo.BUCKET_SIZE * i * 100)) for i in xrange(1, NUM_BUCKETS + 1))
print Foo.BUCKET_LABELS
Result:
> python test2.py
Traceback (most recent call last):
File "test2.py", line 5, in <module>
class Foo(object):
File "test2.py", line 8, in Foo
BUCKET_LABELS = tuple("BUCKET_{}".format(int(Foo.BUCKET_SIZE * i * 100)) for i in xrange(1, NUM_BUCKETS + 1))
File "test2.py", line 8, in <genexpr>
BUCKET_LABELS = tuple("BUCKET_{}".format(int(Foo.BUCKET_SIZE * i * 100)) for i in xrange(1, NUM_BUCKETS + 1))
NameError: global name 'Foo' is not defined
Replacing the reference to BUCKET_SIZE with a hardcoded value fixes the problem; even though there's another class-level variable reference in the same line, it works just fine:
#!/usr/bin/env python
from decimal import Decimal
import math
class Foo(object):
NUM_BUCKETS = 10
BUCKET_SIZE = Decimal(1.0 / NUM_BUCKETS)
BUCKET_LABELS = tuple("BUCKET_{}".format(int(Decimal(0.1) * i * 100)) for i in xrange(1, NUM_BUCKETS + 1))
print Foo.BUCKET_LABELS
Result:
> python test3.py
('BUCKET_10', 'BUCKET_20', 'BUCKET_30', 'BUCKET_40', 'BUCKET_50', 'BUCKET_60', 'BUCKET_70', 'BUCKET_80', 'BUCKET_90', 'BUCKET_100')
Does anybody know the correct way of referencing BUCKET_SIZE in that spot? Is this a bug in Python itself? (I'm running Python 2.7.5, BTW.)
A:
First of all, a solution among others, by simply editing this one line (notice the brackets):
BUCKET_LABELS = tuple(["BUCKET_{}".format(int(BUCKET_SIZE * i * 100)) for i in xrange(1, NUM_BUCKETS + 1)])
Now, if you are curious as to why it works like that in Python, and why it is not a bug... Well, it is not an easy one :-) :
[i*2 for i in xrange(3)] is a list comprehension. It generates an actual list, which can be used like this for example:
>>> a = [i*2 for i in xrange(3)]
>>> a
[0, 2, 4]
(i*2 for i in xrange(3)) is a generator expression. It works in a rather similar way, but not exactly, since it does not generate a list or a tuple, but rather, a generator:
>>> a = (i*2 for i in xrange(3))
>>> a
<generator object <genexpr> at 0x02CEE058>
>>> a.next()
0
>>> a.next()
2
>>> a.next()
4
>>> a.next()
Traceback (most recent call last):
File "<input>", line 1, in <module>
StopIteration
>>> a = (i*2 for i in xrange(3))
>>> tuple(a)
(0, 2, 4)
>>> tuple(a)
()
You can find more information here if you are curious: generator expressions.
The tl;dr version is that a generator cannot be accessed directly (you must ask it to generate its content, using next() for example), and that each value can only be generated once (and then the generator moves on to the next one, hence the next() function name).
So, coming back at your problem. In the expression below, you actually ask to generate a tuple with a generator expression, which is fine in itself. Nonetheless, you do it by using Foo class variables, which in the case of a generator, can be problematic.
BUCKET_LABELS = tuple("BUCKET_{}".format(int(BUCKET_SIZE * i * 100)) for i in xrange(1, NUM_BUCKETS + 1))
In particular, the generator does not actually know about Foo.BUCKET_SIZE variable at all once you ask him to generate a tuple out of it (a generator works within in its scope, contrary to a list). This is why you get this error.
So, one solution is simply to rather use a list comprehension (which is more easy to handle/intuitive anyway).
PS: the Decimal() function probably does not do what you think it does:
>>> NUM_BUCKETS = 10
>>> print Decimal(1.0 / NUM_BUCKETS)
0.1000000000000000055511151231257827021181583404541015625
>>> print round(1.0 / NUM_BUCKETS, 2)
0.1
PPS: the reason why you do not get an error with the xrange(1, NUM_BUCKETS + 1) part, if you are curious about it, is because it is evaluated before the generator is built, so, that class variable is actually replaced by its value for the generator... which does not complain about it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Nodejs File Search from Array of Filenames
I am attempting to do a file search based off array of file names and root directory. I found some file search snips online that seem to work when I am finding just 1 single file, but it will not work when there is more than 1 file specified. Below is the snippet:
const fs = require('fs');
const path = require('path');
var dir = '<SOME ROOT DIRECTORY>';
var file = 'Hello_World.txt'
var fileArr = ['Hello_World.txt', 'Hello_World2.txt', 'Hello_World3.txt'];
const findFile = function (dir, pattern) {
var results = [];
fs.readdirSync(dir).forEach(function (dirInner) {
dirInner = path.resolve(dir, dirInner);
var stat = fs.statSync(dirInner);
if (stat.isDirectory()) {
results = results.concat(findFile(dirInner, pattern));
}
if (stat.isFile() && dirInner.endsWith(pattern)) {
results.push(dirInner);
}
});
return results;
};
console.log(findFile(dir, file));
Any thoughts on how I can get this working with an array rather than just a single file string?
Doing the following seems to be working, but didn't know if there were other ways to do this which may be simpler:
newFileArr = [];
fileArr.forEach((file => {
//findFile(dir, file).toString();
console.log(findFile(dir, file).toString());
}));
A:
The only thing that needs to change is the condition to determine if an individual filepath meets the search criteria. In the code you've posted, it looks like dirInner.endsWith(pattern), which says "does the filepath end with the given pattern?"
We want to change that to say "does the filepath end with any of the given patterns?" And closer to how the code will look, we can rephrase that as "Can we find a given pattern such that the filepath ends with that pattern?"
Let's rename pattern to patterns. Then we can simple replace dirInner.endsWith(patterns) with patterns.some(pattern => dirInner.endsWith(pattern))
| {
"pile_set_name": "StackExchange"
} |
Q:
format R package dependency strings
Goal: List all package names of a certain package - here: "ggplot2"
Desired Output:
c(digest, grDevices, grid, gtable, lazyeval, MASS, mgcv, reshape2, rlang, scales, stats, tibble, viridisLite, withr)
I get very Close with:
pack <- available.packages()
p <- pack["ggplot2", c("Imports")]
p
"digest, grDevices, grid, gtable (>= 0.1.1), lazyeval, MASS,\nmgcv, reshape2, rlang (>= 0.3.0), scales (>= 0.5.0), stats,\ntibble, viridisLite, withr (>= 2.0.0)"
See here: Listing R Package Dependencies Without Installing Packages.
Next i want to replace the Version number, e.g. "(>= 2.0.0)"
What i tried:
library(stringr)
res <- str_match_all(p, " ( (.*?) )")
res <- str_match_all(p, " [(] (.*?) [)]")
A:
Using stringr you could split the string and remove anything inside parentheses (inclusive), spaces, and newlines:
library(stringr)
str_remove_all(str_split(p, ",")[[1]], "\\(.*\\)|\\\n|\\s+")
[1] "digest" "grDevices" "grid" "gtable" "lazyeval" "MASS" "mgcv" "reshape2" "rlang"
[10] "scales" "stats" "tibble" "viridisLite" "withr"
Same logic with base R:
gsub("\\(.*\\)|\\\n|\\s+", "", strsplit(p, ",", fixed = T)[[1]])
| {
"pile_set_name": "StackExchange"
} |
Q:
How to generate Unique coupen code?
I am trying to generate coupen codes to provide discounts. I have tried with Math.Random() but I am not sure if it will assure an unique code each time ?.
Also I have tried with dbms_random.string utility of `Oracle' which is generating random numbers but it also does not guarantee the unique code.
Does anyone knows a good algorithm to do this ?
I am using java and oracle to develope the code.
EDIT: After looking few responses I would like to add that I have to store each and every generated code in the table. And the generated code should be Alphanumeric.
A:
You could use the Java UUID class. It generates random 128-bit alphanumeric strings. The possibility of repetition of a string is astronomically low.
Specifically:
import java.util.UUID
.
.
String uniqueString = UUID.randomUUID().toString()
.
.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to create an in instance using HyperlinkedModelSerializer by just providing the url of the nested HyperlinkedModelSerializer fields?
I am trying to create an instance of a model which has all its fields to be the related fields.
class LearnerQuestionAnswer(models.Model):
quiz_question = models.ForeignKey(Quiz_Question, on_delete=models.CASCADE)
learner = models.ForeignKey(Learner_Model, on_delete=models.CASCADE)
chosen_option = models.ForeignKey(Answer_Options, related_name="chosen_option", default=None, on_delete=models.CASCADE, blank=True, null=True)
For this model I have created the following serializer:-
class LearnerQuestionAnswerSerializer(serializers.HyperlinkedModelSerializer):
quiz_question = Quiz_QuestionSerializer()
learner = Learner_ModelSerializer()
chosen_option = Answer_OptionsSerializer()
class Meta:
model = LearnerQuestionAnswer
fields = ('quiz_question', 'learner', 'chosen_option')
All the nested serializer's are as well HyperlinkedModelSerializer.
I want to create an instance of this model by just providing the urls of the related fields like for example consider the following POST method:-
{
"quiz_question": "http://localhost:8080/api/registration_quiz_questions/83/",
"learner": "http://localhost:8080/api/registration_learners/3/",
"chosen_option": "http://localhost:8080/api/registration_answer_options/218/",
}
Is this possible an how?
A:
HyperlinkedModelSerializerusing for related fields HyperlinkedRelatedField by default, which can give you desired behavior. To represent data as nested objects you can override to_representation method:
class LearnerQuestionAnswerSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = LearnerQuestionAnswer
fields = ('quiz_question', 'learner', 'chosen_option')
def to_representation(self, instance):
self.fields['quiz_question'] = Quiz_QuestionSerializer()
self.fields['learner'] = Learner_ModelSerializer()
self.fields['chosen_option'] = Answer_OptionsSerializer()
return super(LearnerQuestionAnswerSerializer, self).to_representation(instance)
| {
"pile_set_name": "StackExchange"
} |
Q:
CSS How to put the headline infront of the border?
So I need this to happen in an article:
I already found a solution for this but I’d like one that does not abuse CSS.
The one I found was using a <legend> element. I’m looking for a solution that is completely standards compliant.
A:
You can use negative margins (and semantic html and relative units):
article {
margin-top: 1.5em;
border: .125em solid;
padding: 0 1em;
}
article h1 {
/* stretch to fit */
display: table;
/* set font size and line height */
font-size: 1em;
line-height: 1.5;
/* set margins wrt line height */
margin-top: -.75em;
margin-bottom: 1em;
background: #ccc;
}
<article>
<h1>AAAAAAAA</h1>
<p>ASDF</p>
</article>
<article>
<h1>AAAAAAAA</h1>
<p>ASDF</p>
</article>
| {
"pile_set_name": "StackExchange"
} |
Q:
How to only pass an optional parameter to a PHP function by keeping all other mandatory/optional parameters(if any) equal to their default values?
I'm using PHP 7.3.2 on my laptop that runs on Windows 10 Home Single Language 64-bit operating system.
I've installed the latest version of XAMPP installer on my laptop which has installed the Apache/2.4.38 (Win32) and PHP 7.3.2
Please do consider below prototype definition of the built-in PHP function htmlspecialchars() from the PHP Manual:
htmlspecialchars ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = ini_get("default_charset") [, bool $double_encode = TRUE ]]] ) : string
Now, I only want to set the last optional parameter i.e. $double_encode with a boolean value FALSE and keep all other optional parameters set to their default values.
For achieving this I tried below code :
<?php
echo htmlspecialchars('&', '', '', FALSE);
?>
After executing the above code I got following output in my web browser :
Warning: htmlspecialchars() expects parameter 2 to be int, string given in th67i.php on line 2
I'm not understanding where I'm going wrong. I took care of other parameters to be set to their default values by keeping blank spaces separated by commas and only assigning the optional parameter $double_encode to boolean value FALSE.
Then why I'm not able to get the output and getting some warning? Why? What mistake I'm making in my code?
A:
Passing '' does not mean falling back to default argument value. It means just that — trying to pass an empty string.
You would need to reproduce defaults if you want to achieve this:
htmlspecialchars('&', ENT_COMPAT | ENT_HTML401, ini_get('default_charset'), FALSE);
| {
"pile_set_name": "StackExchange"
} |
Q:
Escaping two dollar signs at once
I have an SQL statement which I am running in my Bash script. It contains instances of two dollar signs in a row, for example:
psql -U $username -h $DATABASE_HOST $DATABASE_NAME -c "DO $$ DECLARE myVar varchar; END$$"
How can both of these be escaped?
A:
Just put a backslash in front of each one:
psql -U "$username" -h "$DATABASE_HOST" "$DATABASE_NAME" -c \
"DO \$\$ DECLARE myVar varchar; END\$\$"
(Actually, since the second $ is followed by white space, the shell won't try to expand it, but the second backslash doesn't hurt).
Or, use single quotes around the string so that it is interpreted literally by the shell:
psql -U "$username" -h "$DATABASE_HOST" "$DATABASE_NAME" -c \
'DO $$ DECLARE myVar varchar; END$$'
Like Biffen said in the comments, it's a good habit to always quote your variables.
If you're finding that the $$ is still being expanded, then I guess that this code is being parsed twice. In that case, you will need to either double-escape (\\\$\\\$) inside double quotes, or use \$\$ inside single quotes (or better yet, avoid parsing it twice if you don't need to).
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.