text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Google Maps Android API v2 - for ARM only?
Google Maps Android API v2
I'm getting error while trying to install sucessfully compiled maps demo app (%android-sdk%\extras\google\google_play_services\samples\maps\) on android-x86 device (Intel Mint):
Failure [INSTALL_FAILED_CPU_ABI_INCOMPATIBLE]
The same APK can be installed on ARM devices and works successfully.
A:
Yes. It is an official Google app and does not come in source code form to be recompiled for x86/MIPS.
Use the Genymotion Android emulator, see this other question: How do you install Google frameworks (Play, Accounts, etc.) on a Genymotion virtual device?
| {
"pile_set_name": "StackExchange"
} |
Q:
How do airline pilots maintain night currency?
Does flying as an airline pilot under 14 CFR 121 provide different ways to maintain night currency? Suppose a pilot were to bid only day trips and end up flying only during the day for over 90 days. Under the recency of flight experience requirements in 14 CFR 61 that would mean a pilot might not be night current anymore but do 121 operator's op specs have some way around this?
A:
The night currency requirements are in 14 CFR 61.57, which does provide exceptions for pilots flying for an air carrier:
Except as provided in paragraph (e) of this section, no person may act
as pilot in command of an aircraft carrying passengers [at night]
61.57(e)(2) has this exception for part 121:
(2) This section does not apply to a pilot in command who is employed
by a part 119 certificate holder authorized to conduct operations
under part 121 when the pilot is engaged in a flight operation under
part 91 or 121 for that certificate holder if the pilot in command
complies with §§121.436 and 121.439 of this chapter.
121.436 has general PIC requirements for part 121, and 121.439 has recency requirements, which are 3 takeoffs and landings in the last 90 days in the same aircraft type, or an equivalent simulator.
So part 121 pilots need three takeoffs and landings in type in the last 90 days, with no specific requirement for them to be at night. That's all based on just reading the regulations, someone who's actually been there and done that could probably add some more information.
| {
"pile_set_name": "StackExchange"
} |
Q:
Making urls.py file for Flask like in Django
Maybe someone can help/explain me, how to create urls.py file for Flask like in Django?
main.py - main project file. It includes only app runner (app.run()).
urls.py is situated in the same directory and need to provide views
from views.py.
A:
You can do this as is described in the Flask documentation, basically by calling app.add_url_rule to set your routes rather than using the decorator.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to validate a text box (total) based on two other textboxes with numeric values
I am working on a Telerik RadGrid and within the grid there are multiple radtextboxes like A, B, C and D. I have used radtextbox with regular expression validation to validate A, B and C textboxes with numbers. However, textbox D is A+B+C. My question is if customvalidator is used, how do I validate it within the grid, to alert the user that the total is inaccurate?
Here's a piece of code, I came up with for radD:
> <telerik:RadTextbox ID="radD" runat="server" Autopostback="true"
> Type="Number" text=<%# Bind("TotalD") </telerik:Radtextbox>
>
> <asp:customvalidator ID =CV1 controltovalidate=radD
> errormessage="Inaccuratetotal"
> clientvalidationfunction="total_validate"/>
My question is: How do I code the clientvalidationfunction for textbox D based on A, B and C. Can anyone point me in the right direction?
Thanks in advance.
Dimpy
A:
You don't include what's in the total_validate function, so I'll write some pseudo code for you.
function total_validate(sender, args){
var control = $find(sender.controltovalidate);
var textBoxA = $find(//textBoxA ID).value;
var textBoxB = $find(//textBoxB ID).value;
var textBoxC = $find(//textBoxC ID).value;
if (//textbox a plus b plus c is NOT what you want)
{
arguments.IsValid = false;
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I force a throw to be a statement and not an expression (in a lambda expression)?
Starting from C# 7.0 the throw keyword can be used both as an expression and as a statement, which is nice.
Though, consider these overloads
public static void M(Action doIt) { /*use doIt*/ }
public static void M(Func<int> doIt) { /*use doIt*/ }
When invoking like this
M(() => throw new Exception());
or even like this (with a statement lambda)
M(() => { throw new Exception(); });
the M(Func<>) overload is selected by the compiler indicating that the throw is here considered as an expression.
How can I elegantly and intent-clear force the compiler to select the M(Action) overload?
One way to do it is this
M(() => { throw new Exception(); return; });
but the reason for the return statement seems non-obvious, and runs the risk of being changed by the next developer especially since Resharper warns about the unreachable code.
(Of course I can change the method naming to avoid overloading, but that is not the question. :-)
A:
You could add a cast to for Action, although it does get a bit LISP'y with all the parentheses:
M((Action)(() => throw new Exception()));
Not ideal, but if you want maximum clarity:
Action thrw = () => throw new Exception();
M(thrw);
A:
This has nothing to do with whether the lambda is a statement lambda or an expression lambda (as is most succinctly shown by you changing the lambda from an expression lambda to a statement lambda and the behavior not changing).
There are numerous ways you can make a lambda match multiple possible overloads. This one is specific to newer versions, but other methods have applied since C# 1.0 (and the specific handling of anonymous methods and the resulting overload resolution disambiguation has needed to exist since the introduction of anonymous methods).
The rules for determining which overload is called are spelled out in section 7.5.3.3 of the C# specs. Specifically, when the parameter is an anonymous method, it will always prefer the overload who's delegate (or expression) has a return value over one that has no return value. This will be true whether it's a statement lambda or expression lambda; it applies to any form of anonymous function.
Thus you either need to prevent both overload from matching by making the anonymous method not valid for a Func<int>, or explicitly force the type to be an Action so the compiler is not disambiguating it itself.
A:
One possible approach is to use named parameters:
public static void M(Action action) { /* do stuff */ }
public static void M(Func<int> func) { /* do stuff */ }
public static void Main()
{
M(action: () => throw new Exception());
}
This should probably be documented in the code so as not to surprise the next developer to come along, and as noted in the comments write an appropriate automated test to verify the correct overload is called.
| {
"pile_set_name": "StackExchange"
} |
Q:
Difference between a 'figure' and 'figurine'?
I am writing a product description for an Easter bunny decorative figure/figurine and I am stuck at which term to use for my copy as both these terms have been used interchangeably on different sites.
A:
Figure and figurine can be used interchangeably to describe a small statue or statuette.
figure a representation of a human or animal form in drawing or sculpture (Oxford)
figurine a statuette, especially one of a human form (Oxford)
That said, figure is a more general term. In the statue sense alone, figure connotes no size, whereas figurine connotes a smaller size. Furthermore, figure has a plethora of other senses, evinced by the dictionary entry linked above.
If you're writing a product description, you should probably go with the more specific term, figurine.
| {
"pile_set_name": "StackExchange"
} |
Q:
Allow PHP application access only for slack
I have implemented slack -Jenkins Integration;
Triggering Jenkins build with parameters job by using PHP application hosted in a server.
Slash command to call PHP application ;
PHP application will take the input by REQUEST method and then call the Jenkins job .
If any one knows the file name(www.myserver.com/filename.php) and cracked the run time arguments(paramters), then they can do the deployments . By calling the it in the URL.
Slack doesn't have static IP . So IP restriction is not possible .
Tried :
RewriteCond %{REQUEST_METHOD} !^POST$
RewriteRule ^/check.php$ - [NC,R=404,L]
in the .htaccess.
But Fails the testcase.
Simply , need to allow the PHP application only from slack
A:
You'll want to process the verification token that comes with every slack request.
Verification tokens
Slash commands, Events API deliveries, and interactive messages all have one thing in common:
Slack dispatches a request that lands on your server. You need a way to identify that it really came from Slack. So every Slack app has a verification token that acts as a shared secret between your app and Slack. This verification token has nothing to do with any other kind of token on Slack. It's never needed for any API operations your app sends to Slack. It's only use case is to securely identify traffic coming from Slack.
Don't confuse verification tokens with an OAuth token, user token (xoxp), bot user token (xoxb), gossip girl token (xoxo), or workspace token (xoxa). The only relation is that token word "token."
| {
"pile_set_name": "StackExchange"
} |
Q:
Captioning two side by side figures outside float environment
I want to put two figures in the footnote of my document. I need to write a caption without a label for each figure. The problem is that the figures are located vertically when I add the \captionof*{} command. Does anybody have any idea to put the figures side by side?
I am using the following code
\documentclass{article}
\usepackage{graphicx}
\usepackage{caption}
\begin{document}
\footnote{text text text text text text text
\begin{center}
\includegraphics[width=0.3\textwidth]{Fig.png}
\captionof*{figure}{first figure}
\includegraphics[width=0.3\textwidth]{Fig.png}
\captionof*{figure}{second figure}
\end{center}
}
\end{document}
and the result is as the following
A:
As @leandriis said in the comments, I put each figure in a minipage environment. In this way, the figures are located side by side.
The modified code with minipage environment is as
\documentclass{article}
\usepackage{graphicx}
\usepackage{caption}
\begin{document}
\footnote{text text text text text text text
\begin{minipage}{0.5\textwidth}\vspace{15pt}
\centering
\includegraphics[width=0.3\textwidth]{Fig.png}
\captionof*{figure}{first figure}
\end{minipage}
\begin{minipage}{0.5\textwidth}\vspace{15pt}
\centering
\includegraphics[width=0.3\textwidth]{Fig.png}
\captionof*{figure}{second figure}
\end{minipage}
}
\end{document}
and the result of the above code is as
| {
"pile_set_name": "StackExchange"
} |
Q:
Matplotlib Scatter plot change color based on value on list
I'm quite new to matplotlib and i would like to know how we can change color of points on a scatter plot based on the value in a list.
In fact, I have a 2-D array that I want to plot and a list with the same number of rows containing, for each point, the color we want to use.
#Example
data = np.array([4.29488806,-5.34487081],
[3.63116248,-2.48616998],
[-0.56023222,-5.89586997],
[-0.51538502,-2.62569576],
[-4.08561754,-4.2870525 ],
[-0.80869722,10.12529582])
colors = ['red','red','red','blue','red','blue']
ax1.plot(data[:,0],data[:,1],'o',picker=True)
How to set the color parameter to fit my list of colors ?
A:
Using a line plot plt.plot()
plt.plot() does only allow for a single color. So you may simply loop over the data and colors and plot each point individually.
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
data = np.array([[4.29488806,-5.34487081],
[3.63116248,-2.48616998],
[-0.56023222,-5.89586997],
[-0.51538502,-2.62569576],
[-4.08561754,-4.2870525 ],
[-0.80869722,10.12529582]])
colors = ['red','red','red','blue','red','blue']
for xy, color in zip(data, colors):
ax.plot(xy[0],xy[1],'o',color=color, picker=True)
plt.show()
Using scatter plot plt.scatter()
In order to produce a scatter plot, use scatter. This has an argument c, which allows numerous ways of setting the colors of the scatter points.
(a) One easy way is to supply a list of colors.
colors = ['red','red','red','blue','red','blue']
ax.scatter(data[:,0],data[:,1],c=colors,marker="o", picker=True)
(b) Another option is to supply a list of data and map the data to color using a colormap
colors = [0,0,0,1,0,1] #red is 0, blue is 1
ax.scatter(data[:,0],data[:,1],c=colors,marker="o", cmap="bwr_r")
A:
You have to set argument c of plt.scatter with a list of desired colors:
import matplotlib.pylab as plt
import numpy as np
data = np.array([[4.29488806,-5.34487081],
[3.63116248,-2.48616998],
[-0.56023222,-5.89586997],
[-0.51538502,-2.62569576],
[-4.08561754,-4.2870525 ],
[-0.80869722,10.12529582]])
colors = ['red','red','red','blue','red','blue']
plt.scatter(data[:,0],data[:,1],marker='o',c = colors)
plt.show()
| {
"pile_set_name": "StackExchange"
} |
Q:
in spite of everyone playing or in spite of playing
1.In spite of everyone playing well, we lost the game.
2.In spite of playing well, we lost the game.
Which is better? I prefer 2#. I think "everyone" and "we" are the same in this sentence.
A:
Your understanding of your two sentences is correct.
"Everyone" is implied in the second sentence due to "we".
Your second sentence is shorter and would probably be preferred by a native speaker. It could be further shortened to
Despite playing well, we lost the game.
| {
"pile_set_name": "StackExchange"
} |
Q:
Regex for Alphanumeric, spaces and symbols, Doesn't match like i need
I want to make a regular expression that matches :
-alphanumeric with spaces
-these symbols and letters
á é í ó ú ñ Ñ ,.( ) ! - + % $
I tried with this, but it didn't match like i need:
[\w áéíóúñÑ,.\(\)\!\-\+\%\$]
What's wrong in this regex??
I'm using knockoutjs with knockout validation
.extend({pattern:{message:"No valid.",params:"[\w áéíóúñÑ,.\(\)\!\-\+\%\$]"}});
tested on chrome, firefox, IE10 and Safari browser.
A:
You need to escape the special \ escape character to place an actual \ in the string. Also, you do not need to escape all these characters, just the ones that have a special meaning within the brackets.
Try with:
"[\\w áéíóúñÑ,.()!\\-+%$]"
this pass ----> "||°°dafsasdf" but this didnt pass the valid --->
"||°°"
Oh, it's because right now as long as a single character in the string matches the regex, it will pass. You have to create a whole pattern match with a defined start and end.
"^[\\w áéíóúñÑ,.()!\\-+%$]*$"
| {
"pile_set_name": "StackExchange"
} |
Q:
How do you use list properties in Google App Engine datastore in Java?
An object to be placed in the datastore will have a set of tags.
public class Model
{
List<String> tagList
...
}
In Python, the Google App Engine has the notion of list properties. What is the equivalent notion in Java (if it exists) and how would you use list properties in Java, in JPA and/or in JDO?
A:
See my blog post exactly on this: Efficient Keyword Search with Relation Index Entities and Objectify for Google Datastore. It talks about implementing search with list properties using Relation Index Entities and Objectify.
To summarize:
Query<DocumentKeywords> query = ofy.query(DocumentKeywords.class);
for (String keyword : keywords) {
query = query.filter("keywords", keyword);
}
Set<Key<Document>> keys = query.<Document>fetchParentKeys();
Collection<Document> documents = ofy.get(keys).values();
where DocumentKeywords contains a list property (collection) of all keywords for its Document entity, and Document entity is a parent for DocumentKeywords.
A:
In JDO use
@Persistent
private List<ContactInfo> contactInfoSets;
| {
"pile_set_name": "StackExchange"
} |
Q:
My rails stylesheets are not loading/working
It's been a while since I've developed in Rails and I'm having trouble getting any scss stylesheet to work on my freshly created rails app.
layouts/application.html.erb has the default <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %> at the top.
For testing purposes, I created a main.scss file in assets/stylesheets/ that looks like this:
* {
border: 1px solid black;
}
I thought the application.scss file is supposed to grab all the stylesheets in it's folder and child folders but it's not. (Oddly, the .js files load just fine.)
I've tried RAILS_ENV=production rake assets:precompile but it didn't do anything. Could someone explain what it even does?
I've tried adding *= require main and *= require main.scss to application.scss. I even changed the file ext to css for both files. The only way I've gotten any css to render is by directly adding the code to application.scss, which I don't want to do.
Please help me with this.
EDIT 1
I'm going to add some more info since I'm getting generic answers. I mentioned that it's a fresh rails app so the basic things are already pre-generated. This is how my application.scss looks:
/*
* This is a manifest file that'll be compiled into application.css, which will include all the files
* listed below.
*
* Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
* or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.
*
* You're free to add application-wide styles to this file and they'll appear at the bottom of the
* compiled file so the styles you add here take precedence over styles defined in any styles
* defined in the other CSS/SCSS files in this directory. It is generally better to create a new
* file per style scope.
*
*= require_tree .
*= require main
*= require_self
*/
Still, nothing works
A:
/*
*= require_tree .
*= require_self
*/
Add the above to your application.scss or application.css.scss file
A:
Looks like the only way I can get it to work is by adding @import main; to application.scss. It seems like the styles end up being used on every page (is this the default in rails?).
This is not my ideal solution but it's the only thing I've been able to do to get any styles to work via requiring methods.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to throttle file copy
I need to duplicate a 3TB disk by copying from one to another. They're housed in separate docks (no fan). It will take at least 8hrs to copy this much data through USB 2.0 and im concerned about disks overheating.
Is there any utils to throttle the rate of files or MB/second copied?
A:
Software called UltraCopier allows you to limit the speed of the copy.
| {
"pile_set_name": "StackExchange"
} |
Q:
Need a hint evaluating $ \lim\limits_{x\to 0}\frac{x\ln{(\frac{\sin (x)}{x})}}{\sin (x) - x} $
I'm stuck with this. I've tried substituting $t$ for $\frac{\sin (x)}{x}$ and $\sin (x) - x$ but it doesn't work at all.
A small hint would be greatly appreciated.
A:
$$\lim_{x\to 0}\frac{x\ln{(\frac{\sin (x)}{x})}}{\sin (x) - x} = \lim_{x\to 0}\frac{\ln{(1+\frac{\sin (x)-x}{x})}}{\frac{\sin (x) - x}{x}} =1 $$ Because $$\lim_{x\to0}\frac{\sin x-x}{x}=\lim_{x\to0}\frac{\sin x}{x}-1=1-1=0$$ and $$\lim_{t\to0}\frac{\ln(1+t)}{t}=1.$$
| {
"pile_set_name": "StackExchange"
} |
Q:
If we use a sinusoidal signal as an input signal to a linear transmission path, then we always get out a sine wave of the same period/frequency
An Introduction to Information Theory: Symbols, Signals and Noise, by John R. Pierce, says the following:
With the very surprising property of linearity in mind, let us return to the transmission of signals over electrical circuits. We have noted that the output signal corresponding to most input signals has a different shape or variation with time from the input signal. Figures II-1 and II-2 illustrate this. However, it can be shown mathematically (but not here) that, if we use a sinusoidal signal, such as that of Figure II-4, as an input signal to a linear transmission path, we always get out a sine wave of the same period, or frequency. The amplitude of the output sine wave may be less than that of the input sine wave; we call this attenuation of the sinusoidal signal. The output sine wave, may rise to a peak later than the input sine wave; we call this phase shift, or delay of the sinusoidal signal.
I'm trying to find the aforementioned proof that, if we use a sinusoidal signal as an input signal to a linear transmission path, then we always get out a sine wave of the same period, or frequency.
During my research, the closest thing to this that I have come across is slide 30 of this presentation:
I would greatly appreciate it if people could please take the time to either prove this or redirect me somewhere that has the proof.
A:
$y=G(x)$ is translation invariant, $G\Bigl(T_sx\Bigr)(t)=(T_sy)(t)=y(t+s)$ Together with the linearity this has the consequence that also differential operators are preserved,
$$\dot y(t)=\lim_{s\to 0}\frac{(T_sy)(t)-y(t)}s=\lim_{s\to 0}\frac{G\bigl(T_sx\bigr)(t)-G\bigl(x\bigr)(t)}{s}=G\left(\lim_{s\to 0}\frac{T_sx-x}s\right)(t)=G\bigl(\dot x\bigr)(t).$$
Now you can also apply this to the oscillator equation, $G(\ddot x+\omega^2x)=\ddot y+ω^2y$ and if $x$ is sinusoid with frequency $ω$, then so is $y$.
With $$G(\cos(ω\,\cdot\,))(t)=a\cos(ωt)+b\sin(ωt)$$ you also get the shifted
$$
G(\sin(ω\,\cdot\,))=G(\cos(ω\,\cdot\,-\tfrac\pi2))(t)=a\sin(ωt)-b\cos(ωt)
$$
so that indeed there are only two free parameters per frequency. To get the attenuation and phase, you only need to compute the polar coordinates $(A,\varphi)$ of the point $(a,-b)$.
| {
"pile_set_name": "StackExchange"
} |
Q:
How was Bifrost Bridge shattered in Ragnarok?
In the Ragnarok events (Marvel Comics), Bifrost Bridge is shattered. How did this happen?
Also, providing Bifrost isn't used to travel across realms in comics, what's the significance of this?
A:
In the comic universe, the Bifrost is what anchors Asgard and Midgard together. It's the primary means of travelling between those two worlds. There are other portals in Asgard to various other realms, including places like Olympus that are not part of the Nine Realms. The Bridge was the only permanent one, and allowed free passage in both directions (assuming you could get past Heimdall.)
It should be noted that, in the comics, it's explicit that Asgard is a different dimensional plane than Midgard; some of the Nine Realms are on the same plane as Asgard, and thus can be reached via normal travel. Others, like Midgard and Jontunheim, are on their own planes, and need portals to reach them. In the MCU, there are strong indications that all Nine Realms exist in the same dimension, just different regions of the universe.
In keeping with the mythological meaning of Ragnarok, meaning the end of the world, the shattering of the Bifrost was part of the total desctruction of the Asgardian realm, sending all of the Asgardians into eternal sleep. Some, like Thor, are eventually reawakened, but the believe that Midgard is the only one of the Nine Realms left. I suspect that's not literally true, since Ragnarok is a cycle, not an event, though it's been claimed that Thor "broke" the cycle this last time. At the very least, though, Asgard as we knew it is unreachable from the Earth side.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to capture the prints of a python script being executed from another python script?
I have 2 scripts script1.py and script2.py in the same folder ,script1.py calls script2.py using Popen(See code below for details),issue is that the prints coming from script2.py is not being captured in script1.py,print output and print error doesn't print a thing in the code below? what am I missing here? how do I capture the prints from script2.py?
script1.py
import subprocess
from subprocess import Popen, PIPE, STDOUT
def func1 ():
cmd = "python script2.py"
proc = Popen(cmd.split(' '), stdout=PIPE, stderr=PIPE)
(output, error) = proc.communicate()
print output
print error
func1()
print "Done.."
script2.py
import sys
print "ERROR:port not detected"
sys.exit(29)
OUTPUT:-
C:\Dropbox>python script1.py
ERROR:port not detected
Done..
A:
Edited answer based on comments
Looks like after the edits you made to the original question, Your code is working correctly.
I just put output= in front of print statement to check that.
import subprocess
from subprocess import Popen, PIPE, STDOUT
def func1 ():
cmd = "python script2.py"
proc = Popen(cmd.split(' '), stdout=PIPE, stderr=PIPE)
(output, error) = proc.communicate()
print "output=",output
print error
func1()
print "Done.."
** OUTPUT: **
Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
output= ERROR:port not detected
Done..
>>>
| {
"pile_set_name": "StackExchange"
} |
Q:
Extremely slow model load with keras
I have a set of Keras models (30) that I trained and saved using:
model.save('model{0}.h5'.format(n_model))
When I try to load them, using load_model, the time required for each model is quite large and incremental. The loading is done as:
models = {}
for i in range(30):
start = time.time()
models[i] = load_model('model{0}.h5'.format(ix))
end = time.time()
print "Model {0}: seconds {1}".format(ix, end - start)
And the output is:
...
Model 9: seconds 7.38966012001
Model 10: seconds 9.99283003807
Model 11: seconds 9.7262301445
Model 12: seconds 9.17000102997
Model 13: seconds 10.1657290459
Model 14: seconds 12.5914049149
Model 15: seconds 11.652477026
Model 16: seconds 12.0126030445
Model 17: seconds 14.3402299881
Model 18: seconds 14.3761711121
...
Each model is really simple: 2 hidden layers with 10 neurons each (size ~50Kb). Why is the loading taking so much and why is the time increasing? Am I missing something (e.g. close function for the model?)
SOLUTION
I found out that to speed up the loading of the model is better to store the structure of the networks and the weights into two distinct files:
The saving part:
model.save_weights('model.h5')
model_json = model.to_json()
with open('model.json', "w") as json_file:
json_file.write(model_json)
json_file.close()
The loading part:
from keras.models import model_from_json
json_file = open("model.json", 'r')
loaded_model_json = json_file.read()
json_file.close()
model = model_from_json(loaded_model_json)
model.load_weights("model.h5")
A:
I solved the problem by clearing the keras session before each load
from keras import backend as K
for i in range(...):
K.clear_session()
model = load_model(...)
A:
I tried with K.clear_session(), and it does boost the loading time each time.
However, my models loaded in this way are not able to use model.predict function due to the following error:
ValueError: Tensor Tensor("Sigmoid_2:0", shape=(?, 17), dtype=float32) is not an element of this graph.
Github #2397 provide a detailed discussion for this. The best solution for now is to predict the data right after loading the model, instead of loading a dozens of models at the same time. After predicting each time you can use K.clear_session() to release the GPU, so that next loading won't take more time.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to return a non-editable PDF as a response?
I have a URL:
http://www.irs.gov/pub/irs-pdf/fw4.pdf
It contains an editable PDF. I have make it non-editable. I did so and kept it in the temp directory of a folder. Now i want to send the non-editable PDF as a response, when the user clicks this url, he must get the non-editable pdf. This is what I have done till now:
String strDirectoy ="C:\\Temp";
boolean success = (
new File(strDirectoy)).mkdir();
if (success) {
System.out.println("Directory: "
+ strDirectoy + " created");
}
PdfReader reader = new PdfReader("http://www.irs.gov/pub/irs-pdf/fw4.pdf");//C:\\fw4.pdf
PdfStamper stamp2 = new PdfStamper(reader, new FileOutputStream("C:\\Temp\\Flattened.pdf"));
AcroFields form2 = stamp2.getAcroFields();
stamp2.setFormFlattening(true);
stamp2.close();
Now i need to delete the temp folder as if it never existed and return the non-editable PDF as the response for the above specified URL.
How can i do this?
A:
Write a Servlet.
Flatten your pdf in a temporary file (using the
createTempFile() and deleteOnExit() methods of java.io.File).
Use the setContentType of the HttpServletResponse to set the MIME type
of the pdf.
Write the contents of the temporary pdf file to the
outputstream of the http response
| {
"pile_set_name": "StackExchange"
} |
Q:
Large form crashing on second opening
I have this problem where I have a very large form (winforms) that is loaded through the Activation.CreateInstance(Type) method, because the loading container is used for different forms. It opens fine the first time, but if I close it and then reopen it, it will always crash halfway through the InitializeComponent() method, where it 'jumps' to the Dispose() method, crashing on a NullReferenceException.
My current theory is that the Dispose() call is from the previous instance of the form that did not have the time to finish and is now trying to dispose of the current form. (does that make any sense?) On the other hand, I think that maybe it's the Activation.CreateInstance() that is causing the problem, but it's the first time I see that class so I'm not so sure about that either.
I did a test earlier today while debugging, and if I waited a few seconds on each line in the crashing InitializeComponent(), I got through without error.
A:
Finally I found the origin of the bug : the loading form has hundreds of grids with little toolbars each having 5-6 icons on them. And, the resource manager being a little daft, instead of reusing the same icon each time (the toolbars are instances of the same usercontrol), it instantiates a new bitmap each time, running out-of-memory. But, instead of failing with an obvious error, it squirrels it away and starts disposing of the calling objects, therefore disposing incompletely created objects. So the solution here is to make sure to load images only once when using the resource manager. Not only will it resolve the crash, it also loads faster.
| {
"pile_set_name": "StackExchange"
} |
Q:
Not able to find element by partial link text using Java and Selenium
Using geckodriver 0.23.0, firefox 64.0.2, selenium 3.12, java 8 I'm not able to find the element by partial link text. A frame is not used. Link text is "Accounts (1)". There is only one other instance of the same text on the page "View All Accounts"
html:
<li>
<a href="/accounting/view_all_accounts?_t=039f18daf35b4a00f0093dd17aa70730be385f6f&to_render=account" class="first accounting_page_menu ">Accounts (1)</a>
<ul>
<li>
<a href="/accounting/details?_t=e3d4ea94f5ed862d95196a620f1147be13b02979&to_render=account" class="first accounting_page_menu ">Primary</a>
</li>
<li>
<a onclick="javascript: ModalUtil.loadEditableModal('/accounting/details_new_account', false, false, true);" class="add-accounts">Add New Account...</a>
</li>
<li>
<a href="/accounting/view_all_accounts?_t=039f18daf35b4a00f0093dd17aa70730be385f6f&to_render=account" class="first accounting_page_menu ">View All Accounts</a>
</li>
</ul>
</li>
The code I'm using to find the element: "Accounts (n)" where n = 1, 2, 3 ...
driver.findElement(By.partialLinkText("Accounts (")).click();
I tried with "Accounts " and with "Accounts (" and they both return the same 404 not found - no such element error
Console log:
1547499923019 webdriver::server DEBUG -> POST /session/bed7e7d2-d849-4bd0-ab17-fdca3fb080f9/element {
"value": "Accounts ",
"using": "partial link text"
}
1547499923020 Marionette TRACE 0 -> [0,315,"WebDriver:FindElement",{"using":"partial link text","value":"Accounts "}]
1547499923241 Marionette TRACE 0 <- [1,315,{"error":"no such element","message":"Unable to locate element: Accounts ","stacktrace":"WebDriverError@chrome://mario ... entError@chrome://marionette/content/error.js:388:5\nelement.find/</<@chrome://marionette/content/element.js:339:16\n"},null]
1547499923240 webdriver::server DEBUG <- 404 Not Found {"value":{"error":"no such element","message":"Unable to locate element: Accounts ","stacktrace":"WebDriverError@chrome://marionette/content/error.js:178:5\nNoSuchElementError@chrome://marionette/content/error.js:388:5\nelement.find/</<@chrome://marionette/content/element.js:339:16\n"}}
A:
As you mentioned you are trying to find the element with text as Accounts (n) where n = 1, 2, 3 ... and a couple of more elements with linkText as Add New Account and View All Accounts exists, instead of using partialLinkText it would be better to use XPath and you can use the following solution:
XPath:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//li/a[@class='first accounting_page_menu' and starts-with(@href,'/accounting/view_all_accounts?')][starts-with(.,'Accounts')]"))).click();
Update
As per the discussion Official locator strategies for the webdriver Partial link text selector is preferred than XPath selector. However as per this usecase due to presence of similar link texts it would be easier to construct a XPath.
| {
"pile_set_name": "StackExchange"
} |
Q:
div toggle show/hide for parent and child relation ship in angular 6
I have list of values in div with parent and child relation ship. When I toggle any specific parent record, all the child records associated with other parents also gets opened. I bind this div from service (API)
Please find the sample code used for the above function
<div class="table rts-table-parentChild" *ngFor="let userRole of userRoleActions; let i = index">
<div class="table-row table-header">
<div class="table-cell">
<span *ngIf="userRole.userRoleSubActions.length" id="section{{userRole.actionName}}"
class="margin-right-5 fa fa-plus-circle" role="button"
tabindex="0" [ngClass]="[clickPlus === false ? 'fa fa-plus-circle' : 'fa fa-minus-circle']" (click)="clickPlus=!clickPlus"></span>
{{userRole.actionName}}
</div>
<div class="table-cell">
<input type="checkbox" [ngModelOptions]="{standalone: true}" class="setup-checkbox" id="ChekCreate{{userRole.actionName}}" [(ngModel)]="userRole.isCreateChecked"
(click)="selectParentRole(i,'create')">
</div>
<div class="table-cell">
<input type="checkbox"[ngModelOptions]="{standalone: true}" class="setup-checkbox" id="ChekDelete{{userRole.actionName}}" [(ngModel)]="userRole.isDeleteChecked"
(click)="selectParentRole(i,'delete')">
</div>
</div>
<ng-container *ngIf="clickPlus">
<div style="display:table-row-group;" *ngFor="let item of userRole.userRoleSubActions; let j = index">
<div class="table-row ">
<div class="table-cell" class="subj"> {{item.actionName}}</div>
<div class="table-cell">
<input type="checkbox" [ngModelOptions]="{standalone: true}" class="setup-checkbox"
[(ngModel)]="item.isCreateChecked" (change)="isCreateChecked(i,'create')">
</div>
<div class="table-cell">
<input type="checkbox" [ngModelOptions]="{standalone: true}" class="setup-checkbox"
[(ngModel)]="item.isDeleteChecked" (change)="isCreateChecked(i,'delete')">
</div>
</div>
</div>
</ng-container>
A:
Hi because are toggle on variable clickPlus That's why specific parent record, all parent record is togged. So you have to add
show:boolen
in model of userRoleActions and in click event you can toggle like
(click)="userRole.show=!userRole.show"
Hope you understand my point may this will help you.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I use a datepicker to set a reminder on a specific date?
I have a datepicker which can be used to pick a date and set it to a edittext. how can i set a reminder on the date ?.
The program for setting a edittext from the date picker is given below:
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
Calendar myCalendar= Calendar.getInstance();
private EditText et;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et =(EditText)findViewById(R.id.editText3);
}
DatePickerDialog.OnDateSetListener date =new
DatePickerDialog.OnDateSetListener(){
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel();
}
};
public void onClick(View v) {
// TODO Auto-generated method stub
new DatePickerDialog(MainActivity.this, date, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
private void updateLabel() {
String myFormat = "MM/dd/yy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
et.setText(sdf.format(myCalendar.getTime()));
}
}
A:
Try this:
private void setAlarm(Calendar target){
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), 1, intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, target.getTimeInMillis(), pendingIntent);
}
Let me know if it helped you.
UPDATE:
And alarmReciever must be something like this:
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,
"AlarmReceiver.onReceive()",
Toast.LENGTH_LONG).show();
}
}
And add it to your manifest.xml inside the application tag:
<receiver android:name=".AlarmReceiver" android:process=":remote" />
| {
"pile_set_name": "StackExchange"
} |
Q:
What's wrong with using sudo?
In a comment here I've been told that unnecessarily using sudo should be avoided. While it wasn't needed in that particular case, I don't see any harm in using it.
I think that when executing trivial programs like cat as root using sudo, the overall risk of hitting a bug that would somehow compromise system security is very low.
So can someone please point out the possible implications, besides typing 4 more characters and a space?
A:
The risk of a typo is more than the risk of a bug.
The risk of gaining a habit of "it doesn't work, stick sudo on it!" is much higher than the risk of a bug.
As a sysadmin who's seen people execute all sorts of random commands with sudo that didn't need them, I always caution against superfluous usage of sudo.
While cat isn't harmful, the habit that this encourages is.
A:
I think there is another issue not yet mentioned: sudo status is cached for the shell with a default of 15 minutes. This means you don't have to provide your password in the next 15 minutes in order to execute a potentially dangerous command.
I think we all can think of more or less likely security issues that could result from that: Unknown software bugs that exploit this or forgetting to lock the screen with random people or co-workers around come to mind.
This is indeed my primary reason for not using sudo when I don't have to and even if I have to, for frequently closing shells after I'm done with sudo work.
A:
Using sudo excessively is the Linux equivalent of the old Windows habit of running everything under the Administrator account. That one has been discussed and criticized to hell and back, so you can read everything that talks about why a person should not be running their Windows computer as an Administrator, and every single point will apply to habitual use of sudo on Linux.
| {
"pile_set_name": "StackExchange"
} |
Q:
optimize tween() transition in d3.js
I have a set of items:
[
{ label: 'item1', color: 'yellow' },
{ label: 'item2', color: 'red' },
{ label: 'item3', color: 'blue' },
{ label: 'item4', color: 'green' }
]
There's a main transition which moves all items from left to right.
Inside this main transition, I want to apply individual transitions to each item (this transition goes up and down).
This last transition is a bit special because each item is composed of a text and a circle and these two parts move independently from each other.
Here's a jsfiddle showing you an example: http://jsbin.com/juyoyuzuta/1/edit?js,output
(sorry if the example is a bit ugly, but you can get the idea)
When I profile this code in my browser it's seems like the browser is doing a lot of painting/rendering.
I'm wondering if there's some optimizations I can do to do less paintings/rendering. And more generally if there's a better way to do it.
A:
I think you're going to be getting into micro-optimization land after this point. You're doing it the way I would tackle the problem, here are some things you could try:
You could attempt to modify the position of the circles / labels directly rather than applying a transform. My gut feeling is if you're getting any hardware acceleration that you're probably going to lose it doing this (CSS transforms are a pretty standard thing, modify cx of a circle is not).
You could reduce the amount of movement, those circles look like they're just buzzing with energy, maybe slow the thing down and move the circles up/down a bit less frequently. Aim for a smoother transition and I don't think you'd lose anything.
But in essence, you're doing a very paint heavy operation and not a lot else. So it's fully expected that profiling the code is going to point to a lot of rendering and DOM manipulation. You're basically doing this over a fairly tight loop.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I respond to Mod question?
I flagged an answer as abusive because of the derogatory language the author used to reference another user (the answer has since been edited but you can see the original text in the edit history). I was using this post as my guide for what constitutes 'abuse'.
The flag reviewer responded with a question to me:
I don't want the reviewer to think I'm an idiot and I want them to know why I flagged it as I did (I don't want to argue that it was declined, that's within their right).
How do I respond and answer the question?
A:
Basically flags are for things where the normal tools cannot fix the issue. In this case, an edit handled it which is why the flag was declined.
Keep in mind, when we review flags we see the current post and not the original. The behavior was both rude and offensive so I've suspended the account in question temporarily.
| {
"pile_set_name": "StackExchange"
} |
Q:
String com lixo de memória
Estou com alguns problemas ao trabalhar com arquivos e funções, o código que estou fazendo deveria imprimir uma string no arquivo, porém essa string está com lixo, e não imprime o que deve apesar de ser usada normalmente.
http://pastebin.com/JtGTDSeL
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#define MAIOR_ID 0
int top_IDS(int ID_DNA, char *linhas[])
{
FILE *arquivo;
arquivo=fopen("MEL_PIOR.txt","a");
fflush(stdin);
fputs(linhas,arquivo);
fprintf(arquivo,"\t%i\n",ID_DNA);
fclose(arquivo);
return 0;
}
int calcular_peso(char lin_1[],int *qtd_g, int *qtd_c)
{
int i=0;
int soma_pesos=0,I_D=0;
int qt,qt2;
gets(lin_1);
for(i=0; i<10; i++)
{ if(lin_1[i]=='A' || lin_1[i]=='T')
soma_pesos+=3;
else
soma_pesos+=7;
}
qt = *qtd_g;
qt2 = *qtd_c;
I_D=(soma_pesos+qt+qt2);
printf("\tI_D: %i\n",I_D);
if(I_D<50)
printf("\tTem propencao a doencas cardiacas\n");
else if(I_D>50)
printf("\tTem propencao a doencas respiratorias\n");
else
printf("\tNada se pode afirmar sobre suas propencao as doencas \n");
top_IDS(I_D,&lin_1);
return 0;
}
int habilidades(int soma_guanina,int soma_adenina)
{
if(soma_adenina>10)
printf("\tTem propensäo a atividades esportivas\n");
else if(soma_guanina>10)
printf("\tTem propensäo a atividades artisticas\n");
else
printf("\tNada se pode afirmar sobre suas habilidades\n");
return 0;
}
int cria_complementar(char ler_linha[],char complementar[])
{
int contador=0;
int qtd_A=0,qtd_T=0,qtd_C=0,qtd_G=0;
int soma_AT=0,soma_CG=0;
for(contador=0; contador<10; contador++)
{
if(ler_linha[contador]=='A')
{
complementar[contador]='T';
qtd_A++;
}
else if(ler_linha[contador]=='T')
{
complementar[contador]='A';
qtd_T++;
}
else if(ler_linha[contador]=='C')
{
complementar[contador]='G';
qtd_C++;
}
else
{
complementar[contador]='C';
qtd_G++;
}
}
printf("\t");
soma_AT=(qtd_A+qtd_T);
soma_CG=(qtd_C+qtd_G);
for(contador=0; contador<10; contador++)
{
printf("%c",complementar[contador]);
}
printf("\n\tA:%i T:%i C:%i G:%i",soma_AT,soma_AT,soma_CG,soma_CG);
printf("\n\tA:%i%% T:%i%% C:%i%% G:%i%%\n\n",(soma_AT*100)/20,(soma_AT*100)/20,(soma_CG*100)/20,(soma_CG*100)/20);
habilidades(soma_CG,soma_AT);
calcular_peso(ler_linha,&qtd_G,&qtd_C);
return 0;
}
int main()
{
char bases[11],base_2[11];
FILE *arquivo;
arquivo = fopen("DNAS.txt","r");
if(arquivo==NULL)
{
printf("O arquivo nao pode ser lido\n");
system("pause");
return 0;
}
while(fgets(bases,11,arquivo)!=NULL)
{
printf("\n");
fgetc(arquivo);
printf("\t%s\n",bases);
cria_complementar(bases,base_2);
system("pause");
system("cls");
}
fclose(arquivo);
return 0;
}
A leitura do arquivo é na seguinte formatação:
CGATGCATGC
Várias linhas usando apenas ATCG e a impressão no arquivo é a mesma linha seguido de um número.
A:
Primeira coisa que eu reparei
int top_IDS(int ID_DNA, char *linhas[])
{
FILE *arquivo;
arquivo=fopen("MEL_PIOR.txt","a");
fflush(stdin);
fputs(linhas,arquivo);
...
0) Não verificas se o fopen() funcionou correctamente
0) o fflush(stdin); não parece ter ligação com o resto do código desta função
1) fputs() aceita uma string e um FILE*, mas linhas não é uma string
Sem ler o resto do código não sei como solucionar.
Liga o máximo de warnings que o teu compilador permite. Em princípio ele devia avisar que a chamada ao fputs() é incorrecta.
Ou chamas fputs() com cada um dos elementos de linhas
for (k = 0; k < nlinhas; k++) fputs(linhas[k], arquivo);
Ou re-defines a função para aceitar uma string em vez dum array de strings
int top_IDS(int ID_DNA, char *linhas)
| {
"pile_set_name": "StackExchange"
} |
Q:
Is false considered to be nil in rspec?
There is field name active in customer table. It validates as below in customer.rb:
validates :active, :presence => true
Here is the rspec code to test a field short_name:
it "should be OK with duplicate short_name in different active status" do
customer = Factory(:customer, :active => false, :short_name => "test user")
customer1 = Factory.build(:customer, :active => true, :short_name => "Test user")
customer1.should be_valid
end
Validation for short_name is:
validates :short_name, :presence => true, :uniqueness => { :scope => :active }
The above code causes the error:
1) Customer data integrity should be OK with duplicate short_name in different active status
Failure/Error: customer = Factory(:customer, :active => false, :short_name => "test user")
ActiveRecord::RecordInvalid:
Validation failed: Active can't be blank
# ./spec/models/customer_spec.rb:62:in `block (3 levels) in <top (required)>'
It seems that the false value assigned to field active was considered to be blank or nil by rspec and failed the data validation check. Tried to use 0 for false and it causes the same error. The rspec case passes if removing the validation for field active.
A:
This is not a rspec issue, it's related to Rails' validation. I suppose your active field is a boolean and, to quote the validates_presence_of documentation:
If you want to validate the presence of a boolean field (where the real values are true and false), you will want to use validates_inclusion_of :field_name, :in => [true, false] This is due to the way Object#blank? handles boolean values. false.blank? # => true
So simply change your validator to something like the following (assuming you want the "sexy" syntax) and it should work:
validates :active, :inclusion => [true, false]
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the size of codomain of a function $G(x) = F^A(x) \oplus F^B(x)$, where $F(x) = \text{Keccak-}f[1600](x)$?
Assuming that $m$ is a multiset of bitstrings where all bitstrings have the same length, let $D(m)$ denote the number of distinct elements in $m$. That is, $D(m)$ is equal to the dimension of $m$. For example, if $$m = \{00, 10, 11, 10, 11\},$$ then $D(m)=3$.
Let $F(x) = \text{Keccak-}f[1600](x)$, the block permutation function of SHA-3 (for $64$-bit words). We can define the following notation: $$\begin{array}{l}
{F^0(x)} = x,\\
{F^1(x)} = F(x),\\
{F^2(x)} = F(F(x)),\\
{F^3(x)} = F(F(F(x))),\\
\ldots
\end{array}$$
Assuming that $A$ and $B$ are two different natural numbers greater than or equal to $0$, let $G_{A, B}(x)$ denote a function defined as $$G_{A, B}(x) = F^A(x) \oplus F^B(x),$$
where $x$ denotes a $1600$-bit input and $\oplus$ denotes an XOR operation.
Assuming that $L = 2^{1600}$, let $S_i$ denote an $i$-th bitstring from a set of all possible $1600$-bit inputs:
$$\begin{array}{l}
S_1 = 0^{1600},\\
S_2 = 0^{1599}1,\\
\ldots,\\
S_{L-1} = 1^{1599}0,\\
S_L = 1^{1600}.\\
\end{array}$$
Let $A$ and $B$ denote two arbitrarily large, but different natural numbers (one of them is allowed to be equal to $0$). For example, $$A = 0, B = 1$$ or $$A = 2^{3456789}, B = 9^{876543210}$$ are valid pairs.
Then
$$\begin{array}{l}
S_{A, B}[i] = G_{A, B}(S_i),\\
C_{A, B} = \{S_{A, B}[1], S_{A, B}[2], \ldots, S_{A, B}[L-1], S_{A, B}[L]\}.\\
\end{array}$$
The question: can we assume that $D(C_{A, B})$ is expected to be approximately equal to $$(1-1/e) \times 2^{1600} = 10^{481} \times 2,810560755\ldots$$ for all (or almost all) pairs of $A$ and $B$?
A:
Let $\pi$ and $\sigma$ be two independent uniform random permutations, and $f$ a uniform random function. The best advantage of any $q$-query algorithm to distinguish $\pi + \sigma$ from $f$ is bounded by $(q/2^n)^{1.5}$[1]. In this case, the expected fraction of distinct outputs of $\pi + \sigma$ can't be too far from the expected fraction of distinct outputs from $f$, which is $1 - e^{-1} \approx 63\%$.
What about $\sigma = \pi^2$, or $\sigma = \pi^k$ for $k > 2$? Then $\pi$ and $\sigma$ are not independent. Nevertheless, it would be rather surprising if this situation were substantially different.
What about $\pi^{2^{3456789}} + \pi^{2^{987654321}}$ instead of $\pi + \pi^2$? This is the same as $\pi + \pi^{2^{987654321 - 3456789}}$. It's not clear why you would be worried about uncomputably large exponents like this unless you were flailing around without principle trying to make a design that looks complicated.
| {
"pile_set_name": "StackExchange"
} |
Q:
Sum of probability differential is zero
I keep seeing:
$$
\sum_i [ln(p_i) + 1]dp_i = \sum_i ln(p_i)dp_i
$$
where $p_i$ is the probability of the $i^{th}$ state and where
$ \sum_i p_i = 1 $
cropping up in my statistical mechanics course. I'm a bit unsure of how one comes to this?
EDIT: A similar result which confuses me is:
$$
\sum_i [ln(Z)] dp_i = 0
$$
where $Z$ is the partition function.
A:
Presumably because we always have $ \sum_i p_i = 1$: if we differentiate this condition,
$$ \sum_i dp_i = 0 $$
so that the total probability remains $1$. It's like $\dot{x} \cdot x = 0 $ when $x$ is forced to lie on a sphere $x \cdot x = R^2$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Move specific items to the end of a list
I have an ArrayList in Java:
{"deleteItem", "createitem", "exportitem", "deleteItems", "createItems"}
I want to move all string which contains delete to the end of the list, so I would get the next:
{"createitem", "exportitem", "createItems", "deleteItem", "deleteItems"}`
I can create two sublists - one for the words which contain the 'delete' word, and one for the others, and then merge them, but I search for a more efficient way.
A:
Use custom Comparator:
List<String> strings = Arrays.asList(
"deleteItem", "createitem", "exportitem", "deleteItems", "createItems"
);
Comparator<String> comparator = new Comparator<String>() {
@Override
public int compare(final String o1, final String o2) {
if (o1.contains("delete") && !o2.contains("delete")) {
return 1;
}else if (!o1.contains("delete") && o2.contains("delete")) {
return -1;
}
return 0;
}
};
Collections.sort(strings, comparator);
System.out.println(strings);
A:
If you want something efficient and need to remove elements in the beginning and middle of a List I would suggest using a LinkedList instead of a array list. That would avoid rewriting the underlying array for each remove operation.
Then, you simply iterate on the list, calling remove and addLast for any string that contains delete.
Of course, this is only OK if there is nothing preventing you from replacing your ArrayList with a LinkedList.
| {
"pile_set_name": "StackExchange"
} |
Q:
Redefine obeyspaces to newline
I want to typeset code snippets from different programming languages. I couldn't get listings to do what I want (one complete height of an empty line takes up too much space for my liking) and neither did I manage to define everything I want myself.
I'd like to define a new environment where return calls \newline, and where an empty line calls \par (this one is already present in normal text mode) so that I can differentiate between them. In addition, every space inserted should be printed, but that is taken care of by \obeyspaces.
MWE:
\documentclass{article}
\newenvironment{code}{
\ttfamily
\parindent=0pt\parskip=5pt
\obeyspaces\obeylines
}{}
\begin{document}
\begin{code}
text 1space 2spaces
new line
empty line before this line
\end{code}
\end{document}
I found
\def\obeypar{\catcode`\^^M\active \let ^^M\par }`
and tried to define \obeylines (LaTeX tells me it's undefined) but since these are TeX primitives (?) they give an error.
Can I tell LaTeX that this part should be treated as TeX?
What am I missing or where I can read about these things?
A:
If I understand the question, you need to distinguish the empty and non-empty lines in code environment. You can try the following:
\def\emptyline{\hbox to\hsize{\dotfill empty line\dotfill}}
%\def\emptyline{\vskip.7\baselineskip} % ... another alternative ...
\def\printemptyline#1{\def\par{\ifvmode\emptyline\fi\endgraf}\obeylines}
\begin{code}\printemptyline
text 1space 2spaces
new line
empty line before this line
\end{code}
This gives the result:
| {
"pile_set_name": "StackExchange"
} |
Q:
On CentOS Linux 7.4, cannot install the R package "httpuv"
I am currently using CentOS Linux 7.4.1708 (Core). I have tried to install the package httpuv in R through various methods to no avail. It always ends with the error:
CC src/unix/libuv_la-procfs-exepath.lo
CC src/unix/libuv_la-proctitle.lo
CC src/unix/libuv_la-sysinfo-loadavg.lo
CC src/unix/libuv_la-sysinfo-memory.lo
CCLD libuv.la
libtool: error: require no space between '-L' and '-L/n/helmod/apps/centos7/Core/pcre/8.37-fasrc02/lib'
make[1]: *** [libuv.la] Error 1
make[1]: Leaving directory `/tmp/Rtmp5Dj7hL/R.INSTALL5c046d96dc92/httpuv/src/libuv'
make: *** [libuv/.libs/libuv.a] Error 2
ERROR: compilation failed for package ‘httpuv’
Does anyone have any thought as to what is going on here? Thanks.
A:
The previous answer is partially correct in that it identifies libuv as the missing dependency.
In CentOS 7 you can add this with yum install libuv-devel, then attempt to install the package again with install.packages("httpuv") and provided that was your only issue, it should compile correctly.
| {
"pile_set_name": "StackExchange"
} |
Q:
Ajax in MVC @Ajax. Helpers and in JQuery.Ajax
I know a bit of Ajax. And now I am learning MVC + JQuery. I want to know if the 2 Ajaxs in MVC Ajax.Helper and JQuery.Ajax are using the same base? Are they the same as the normal Ajax I learned using XMLHttpRequest xhr? If not, what is the preferred way of doing it? I am new to this, and a bit confused, so please don't mind if my question doesn't make sense to you.
Thank you, Tom
(edited) I wrote some mvc3 Razor:
<div id="MyAjaxDiv">@DateTime.Now.ToString("hh:mm:ss tt")</div>
@Ajax.ActionLink("Update", "GetTime", new AjaxOptions { UpdateTargetId = "MyAjaxDiv", InsertionMode = InsertionMode.Replace, HttpMethod = "GET" })
When I open up the source code in notepad, I get:
<div id="MyAjaxDiv">06:21:10 PM</div>
<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#MyAjaxDiv" href="/Home/GetTime">Update</a>
So, because I have only included ~/Scripts/jquery.unobtrusive-ajax.min.js, the MVC helpers must be using the JQuery to work. I had the impression that they might need the MicrosoftAjax.js, MicrosoftMVCAjax.js ....etc, doesn't look like it now. Are they for MVC2 and aspx pages?
A:
Here's an excerpt from an MVC book,
MVC version 3 introduced support for jQuery Validation, whereas
earlier versions relied on JavaScript libraries that Microsoft
produced. These were not highly regarded, and although they are still
included in the MVC Framework, there is no reason to use them.
JQuery has really become the standard for ajax based requests. You may still use your "XMLHttpRequest xhr" way but Jquery has made it easier to perform the same thing.
| {
"pile_set_name": "StackExchange"
} |
Q:
CSS attribute selector not working when the attribute is applied using javascript?
.variations_button[style*="display: none;"] + div
This is my CSS selector which works fine if the style attribute is already in the DOM on page load:
http://jsfiddle.net/xn3y3hu0/
However, if i hide the .variations_button div using javascript, the selector is not working anymore:
$(document).click(function(){
$('.variations_button').hide();
});
http://jsfiddle.net/55seee1r/
Any idea whats wrong? Looks like the CSS is not refreshing, because if i edit another property using the inspector, the color changes red instantly.
A:
Because the selector you use, [style*="display: none;"], is looking for the presence of the exact string of "display: none;" in the style attribute, it requires the browser's JavaScript engine inserts that precise string, including the white-space character (incidentally in Chrome 39/Windows 8.1 it does). For your particular browser you may need to remove the space, and to target most1 browsers, use both versions of the attribute-value string, giving:
.variations_button[style*="display: none;"] + div,
.variations_button[style*="display:none;"] + div
.variations_button[style*="display: none;"]+div,
.variations_button[style*="display:none;"]+div {
color: red;
}
<div class="variations_button" style="display: none;">asd</div>
<div>test</div>
Of course, it remains much simpler to use classes to hide an element, toggling that class with JavaScript, and using the class as part of the CSS selector, for example:
$('.variations_button + div').on('click', function() {
$('.variations_button').toggleClass('hidden');
});
.hidden {
display: none;
}
.hidden + div {
color: red;
}
.variations_button + div {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="variations_button">asd</div>
<div>test</div>
As I understand it, the problem of the above not working once jQuery is involved, is because jQuery's hide(),show() and toggle() methods seem to update the display property of the element's style property, rather than setting the attribute directly. The updated attribute-value (as represented in the style attribute) seems to be a representation of the style property (derived, presumably, from its cssText). Because the attribute is unchanged, and merely serves as a representation of a property, the CSS attribute-selectors don't, or perhaps can't, match.
That said, a somewhat clunky workaround is to directly set the attribute; in the following demo this uses jQuery's attr() method (though the native DOM node.setAttribute() would work equally well):
$(document).click(function() {
// setting the style attribute of the selected element(s),
// using the attr() method, and the available anonymous function:
$('.variations_button').attr('style', function(i, style) {
// i: the index of the current element from the collection,
// style: the current value (before manipulation) of the attribute.
// caching the cssText of the node's style object:
var css = this.style.cssText;
// if the string 'display' is not found in the cssText:
if (css.indexOf('display') === -1) {
// we return the current text plus the appended 'display: none;' string:
return css + 'display: none;';
// otherwise:
} else {
// we replace the string starting with 'display:', followed by an
// optional white-space ('\s?'), followed by a matching string of
// one or more alphabetic characters (grouping that last string,
// parentheses):
return css.replace(/display:\s?([a-z]+)/i, function(a, b) {
// using the anonymous function available to 'replace()',
// a: the complete match, b: the grouped match (a-z),
// if b is equal to none we return 'display: block', otherwise
// we return 'display: none':
return 'display: ' + (b === 'none' ? 'block' : 'none');
});
}
});
});
jQuery(document).ready(function($) {
$(document).click(function() {
$('.variations_button').attr('style', function(i, style) {
var css = this.style.cssText;
if (css.indexOf('display') === -1) {
return css + 'display: none;';
} else {
return css.replace(/display:\s?([a-z]+)/i, function(a, b) {
return 'display: ' + (b === 'none' ? 'block' : 'none');
});
}
});
});
});
.variations_button[style*="display: none;"]+div {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="variations_button">asd</div>
<div>test</div>
References:
CSS:
Substring Matching Attribute-selectors.
JavaScript:
HTMLElement.style.
JavaScript Regular Expressions.
String.prototype.indexOf().
String.prototype.replace().
jQuery:
attr().
hide().
show().
toggle().
| {
"pile_set_name": "StackExchange"
} |
Q:
Question about positive recurrence of a Markov chain
Q) Let $\{X_n\}$ be an irreducible Markov chain on a countable set $S$. Suppose that for some $x_0$ and a non-negative function $f:S\to(0,\infty)$, there is a constant $0<\alpha<1$ s.t.
$$\mathbb{E}_xf(X_1)\leq \alpha f(x)\text{ for all }x\neq x_0$$
Suppose also that $f(x_0)\leq f(x)$ for all $x$. Show that $\{X_n\}$ is positive recurrent.
Let $Y_n = f(X_n)/\alpha^n$ and I can show that $Y_n$ is a supermartingale using the hypothesis. But to show $X_n$ is positive recurrent, since $x_0$ is mentioned, I was thinking of the stopping time
$$\tau = \inf\{n\geq 0:X_n = x_0\}$$
Then $Y_{n\wedge \tau}$ is also a supermartingale, $\mathbb{E}_xY_{n\wedge \tau}\leq f(x)$.
1) How can I show that $\mathbb{E}_x\tau < \infty$ which shows that $x_0$ is positive recurrent?
2) How does that show the chain is positive recurrent?
A:
You need to make use of the following theorem.
Theorem. If $X_n$ is a nonnegative supermartingale and $N \le \infty$ is a stopping time, then $EX_0 \ge EX_N$ where $X_\infty = \lim X_n$ (which exists by the martingale convergence theorem).
I will continue from where you left off. You've already proven that $E_xY_n$ is a nonnegative supermartingale, and $\tau$ is a stopping time. Hence
$$ f(x) = E_xY_0 \ge E_xY_\tau = E_x(Y_\tau;\tau=\infty) + E_x(Y_\tau;\tau<\infty)$$
$$\ge E_x(Y_\infty; \tau = \infty) = E_x(\lim_{n \rightarrow \infty}f(X_n)/\alpha^n; \tau=\infty) $$
$$ \ge E_x(\lim_{n \rightarrow \infty} f(x_0)/\alpha^n; \tau=\infty) . $$
Since $f(x_0) > 0, 0 < \alpha < 1$ and the term $f(x_0)/\alpha^n \rightarrow \infty$, it follows that $P_x(\tau = \infty) = 0$, and $P_x(\tau < \infty) = 1$ for all $x \in S$. Hence $P_x(X_n=x_0\; i.o.) =1$, and $x_0$ is recurrent.
Recall the chain is irreducible and $x_0$ is recurrent, hence all states $x \in S$ are recurrent (irreducibility $ \Rightarrow \rho_{x_0x} > 0$, additionally $x_0$ is recurrent $\Rightarrow \rho_{xx} = 1$ where $\rho_{xy}\equiv P_x(T_y < \infty)$).
| {
"pile_set_name": "StackExchange"
} |
Q:
How to type String content:encoded = "Hello"; in java?
How to type String content:encoded = "Hello"; in java ?
Eclipse keep telling me syntax error on tokens delete these tokens ?
setDescription(String content:encoded) {
_description = content:encoded;
}
A:
Because content:encoded is a syntax error. Name in java only accept letters numbers $ and "_". The rule might allow some other characters but it should be pretty much it. Also a variable cannot start with a number.
To be clear, remove the : from the variable name because : is illegal in a name and might have an other meaning in the language.
Quote from the article below:
Variable names are case-sensitive. A variable's name can be any legal identifier — an unlimited-length sequence of Unicode letters and
digits, beginning with a letter, the dollar sign $, or the
underscore character _. The convention, however, is to always begin
your variable names with a letter, not $ or _. Additionally, the
dollar sign character, by convention, is never used at all. You may
find some situations where auto-generated names will contain the
dollar sign, but your variable names should always avoid using it. A
similar convention exists for the underscore character; while it's
technically legal to begin your variable's name with _, this
practice is discouraged. White space is not permitted.
Subsequent characters may be letters, digits, dollar signs, or underscore characters.
Here read more about it: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html
A:
if you are creating method setDescription then it whould be:
public void setDescription(String content_encoded) {
_description = content_encoded;
}
Here
public is modifier
void is return type
setDescription is method name
String is parameter type
content_encoded is Variable that is holding string value.
| {
"pile_set_name": "StackExchange"
} |
Q:
Handling worker death in multiprocessing Pool
I have a simple server:
from multiprocessing import Pool, TimeoutError
import time
import os
if __name__ == '__main__':
# start worker processes
pool = Pool(processes=1)
while True:
# evaluate "os.getpid()" asynchronously
res = pool.apply_async(os.getpid, ()) # runs in *only* one process
try:
print(res.get(timeout=1)) # prints the PID of that process
except TimeoutError:
print('worker timed out')
time.sleep(5)
pool.close()
print("Now the pool is closed and no longer available")
pool.join()
print("Done")
If I run this I get something like:
47292
47292
Then I kill 47292 while the server is running. A new worker process is started but the output of the server is:
47292
47292
worker timed out
worker timed out
worker timed out
The pool is still trying to send requests to the old worker process.
I've done some work with catching signals in both server and workers and I can get slightly better behaviour but the server still seems to be waiting for dead children on shutdown (ie. pool.join() never ends) after a worker is killed.
What is the proper way to handle workers dying?
Graceful shutdown of workers from a server process only seems to work if none of the workers has died.
(On Python 3.4.4 but happy to upgrade if that would help.)
UPDATE:
Interestingly, this worker timeout problem does NOT happen if the pool is created with processes=2 and you kill one worker process, wait a few seconds and kill the other one. However, if you kill both worker processes in rapid succession then the "worker timed out" problem manifests itself again.
Perhaps related is that when the problem occurs, killing the server process will leave the worker processes running.
A:
This behavior comes from the design of the multiprocessing.Pool. When you kill a worker, you might kill the one holding the call_queue.rlock. When this process is killed while holding the lock, no other process will ever be able to read in the call_queue anymore, breaking the Pool as it cannot communicate with its worker anymore.
So there is actually no way to kill a worker and be sure that your Pool will still be okay after, because you might end up in a deadlock.
multiprocessing.Pool does not handle the worker dying. You can try using concurrent.futures.ProcessPoolExecutor instead (with a slightly different API) which handles the failure of a process by default. When a process dies in ProcessPoolExecutor, the entire executor is shutdown and you get back a BrokenProcessPool error.
Note that there are other deadlocks in this implementation, that should be fixed in loky. (DISCLAIMER: I am a maintainer of this library). Also, loky let you resize an existing executor using a ReusablePoolExecutor and the method _resize. Let me know if you are interested, I can provide you some help starting with this package. (I realized we still need a bit of work on the documentation... 0_0)
| {
"pile_set_name": "StackExchange"
} |
Q:
Restrict Action in ASP.Net MVC
I am trying to restrict the action to not to be called if it has the required parameter available in the url. for example I have a Login Action ut it only be access with it hit on an other web application and it redirect with query string parameter. but it can also be accessible with out parameter I want to restrict this.
Ristrict it
https://localhost:44300/account/login
Right Url
https://localhost:44300/Account/Login?returnUrl=https%3A%2F%2Fdevatea.portal.azure-api.net%2F%2F
A:
Based on your requirements, I think the easiest way would be to just add a check to the login action and return a 404 Not Found if the returnUrl is empty or null.
public ActionResult Login(string returnUrl)
{
if (string.IsNullOrEmpty(returnUrl)) return HttpNotFound();
//remaining code for login
//...
}
| {
"pile_set_name": "StackExchange"
} |
Q:
MySQL Command Line Client: Selecting records from a table which links two other tables
I have three tables. Two of them are separate irrelevant tables (students and subjects), the third (entries) is one which links them both with foreign keys (student_id and subject_id).
Here are all the tables with the records:
students:
+------------+------------+-----------+---------------------+----------------------+
| student_id | first_name | surname | email | reg_date |
+------------+------------+-----------+---------------------+----------------------+
| 1 | Emma | Harvey | emmah@gmail.com | 2012-10-14 11:14:13 |
| 2 | Daniel | ALexander | daniela@hotmail.com | 2014-08-19 08:08:23 |
| 3 | Sarah | Bell | sbell@gmail.com | 1998-07-04 13:16:32 |
+------------+------------+-----------+---------------------+--------------- ------+
subjects:
+------------+--------------+------------+----------------+
| subject_id | subject_name | exam_board | level_of_entry |
+------------+--------------+------------+----------------+
| 1 | Art | CCEA | AS |
| 2 | Biology | CCEA | A |
| 3 | Computing | OCR | GCSE |
| 4 | French | CCEA | GCSE |
| 5 | Maths | OCR | AS |
| 6 | Chemistry | CCEA | GCSE |
| 7 | Physics | OCR | AS |
| 8 | RS | CCEA | GCSE |
+------------+--------------+------------+----------------+
entries:
+----------+---------------+---------------+------------+
| entry_id | student_id_fk | subject_id_fk | entry_date |
+----------+---------------+---------------+------------+
| 1 | 1 | 1 | 2012-10-15 |
| 2 | 1 | 4 | 2011-09-21 |
| 3 | 1 | 3 | 2015-08-10 |
| 4 | 2 | 6 | 1992-07-13 |
| 5 | 3 | 7 | 2013-02-12 |
| 6 | 3 | 8 | 2016-01-14 |
+----------+---------------+---------------+------------+
I want to know how to select all the first_names of the students in the students table, who have entries with a with the OCR exam_board from the subjects table, using the entries table.
I'm sure it has to do with joins, but which one to use and the general syntax of it, I don't know.
I'm generally awful at explaining things, so sorry if these doesn't make a ton of sense and if I've missed out something important. I'll gladly go into more specifics if necessary.
I've got an answer, but what I was looking for as the output was this:
+------------+
| first_name |
+------------+
| Emma |
| Sarah |
+------------+
A:
You should use INNER JOINS in your query, like:
SELECT students.first_name
FROM students
INNER JOIN entries
ON entries.student_id_fk = students.student_id
INNER JOIN subjects
ON subjects.subject_id = entries.subject_id_fk
WHERE subjects.exam_board = 'OCR';
This query will join the tables on the matching key values, select the ones with exam_board OCR and return the student first_name.
| {
"pile_set_name": "StackExchange"
} |
Q:
Tank Tread Mathematical Model
I am struggiling with tank tread behaviour. The tank treads moving indivually if I move only the left tread the tank will go to the right direction for sure it depends on tread’s speed value subatraction , if ı am not wrong.
İf the left track moves 50 km and right track moves with 40km tank will go to the right direction but if i decrease the right track speed around 30 tank has to turn right again but Which Angle ?
When I drive a tank 90 degree forward with remote control I want to turn left 5 degree how much speed difference should be realize to turn 5 degree or 45 degree or 275 degree ?
I tried to put 2 force on a stick which is show the lenght of 2 tread distance. The net force should be locate somewhere on this lenght. It is easy to find if i know the force value.
By the way I tried to imagine with tread’s speed. Tank treads must have angular speed respectively. How can i associate with turning angle between angular speed or do you have another view!
A:
Calling
$$
\cases{
r = \text{Tread's wheel radius}\\
d = \text{mid tread's front distance}\\
\vec v_i = \text{Wheels center velocities}
}
$$
assuming the whole set as a rigid body, we can apply the Poisson kinematics law.
$$
\vec v_1 \times(p_1-O) = \vec v_2 \times(p_2-O)
$$
where $p_i$ are application points and $O$ is the rotation instantaneous center. Calling $G$ the arrangement geometrical center, $\vec V = V(\cos\theta,\sin\theta)$ and $p_G = (x_G,y_G)$ we have the equivalent kinematics
$$
\left(
\begin{array}{c}
\dot x_G\\
\dot y_G\\
\dot\theta
\end{array}
\right) = \left(
\begin{array}{cc}
\cos\theta & 0\\
\sin\theta & 0\\
0 & 1
\end{array}
\right) \left(
\begin{array}{c}
V\\
\omega
\end{array}
\right)
$$
and also
$$
\left(
\begin{array}{c}
V\\
\omega
\end{array}
\right) = \left(
\begin{array}{cc}
\frac r2 & \frac r2\\
\frac{r}{2d} &-\frac{r}{2d}\
\end{array}
\right) \left(
\begin{array}{c}
\omega_1\\
\omega_2
\end{array}
\right)
$$
Here $\omega$ is the rigid body angular rotation velocity, $\omega_i$ is the wheels angular rotation velocity. Assuming that the wheels do not skid laterally, should be considered the following restriction of movement:
$$
\dot x_G\sin\theta +\dot y_G\cos\theta = d_0\dot\theta
$$
where $d_0$ is the distance between $p_G$ and the tread center. This is a rough qualitative approximation. The real tank kinematics are a lot more complex.
NOTE
Attached a MATHEMATICA script simulating the movement kinematics.
parms = {r -> 0.5, d -> 2, d0 -> 0.1, wr -> UnitStep[t] - UnitStep[t - 30], wl -> UnitStep[t - 10] - 2 UnitStep[t - 50]};
M = {{Cos[theta[t]], 0}, {Sin[theta[t]], 0}, {0, 1}};
D0 = {{r/2, r/2}, {r/(2 d), -r/(2 d)}};
equs = Thread[D[{x[t], y[t], theta[t]}, t] == M.D0.{wr, wl}];
equstot = equs /. parms;
cinits = {x[0] == 0, y[0] == 0, theta[0] == 0};
tmax = 100;
solmov = NDSolve[Join[equstot, cinits], {x, y, theta}, {t, 0,tmax}][[1]];
gr0 = ParametricPlot[Evaluate[{x[t], y[t]} /. solmov], {t, 0,tmax}];
car[x_, y_, theta_, e_] := Module[{p1, p2, p3, bc, M, p1r, p2r, p3r},
p1 = {0, e};
p2 = {2 e, 0};
p3 = {0, -e};
bc = (p1 + p2 + p3)/3;
M = RotationMatrix[theta];
p1r = M.(p1 - bc) + {x, y};
p2r = M.(p2 - bc) + {x, y};
p3r = M.(p3 - bc) + {x, y};
Return[{p1r, p2r, p3r, p1r}]
]
nshots = 100;
dt = Floor[tmax/nshots];
path0 = Evaluate[{x[t], y[t], theta[t]} /. solmov];
path = Table[path0 /. {t -> k dt}, {k, 0, Floor[tmax/dt]}];
grpath = Table[ListLinePlot[car[path[[k, 1]], path[[k, 2]],path[[k, 3]], 0.2], PlotStyle -> Red, PlotRange -> All], {k, 1, Length[path]}];
Show[gr0, grpath, PlotRange -> All]
| {
"pile_set_name": "StackExchange"
} |
Q:
Passing custom flags to "open" in a device driver
I need to pass some custom flags to the open() call of my device driver.
I found this example in LDD3:
int dev_open(struct inode *inode, struct file *filp)
{
if ((filp->f_flags & O_ACCMODE) == O_WRONLY) {
...
}
}
My question is: is it possibile to define other flags (like O_ACCMODE and O_WRONLY) without conflicts with any others?
A:
Yes, it's possible. Take a look at include/uapi/asm-generic/fcntl.h. Pay attention to next comment:
/*
* When introducing new O_* bits, please check its uniqueness in fcntl_init().
*/
Now look into fcntl_init() function (defined at fs/fcntl.c):
/*
* Please add new bits here to ensure allocation uniqueness.
* Exceptions: O_NONBLOCK is a two bit define on parisc; O_NDELAY
* is defined as O_NONBLOCK on some platforms and not on others.
*/
BUILD_BUG_ON(20 - 1 /* for O_RDONLY being 0 */ != HWEIGHT32(
O_RDONLY | O_WRONLY | O_RDWR |
O_CREAT | O_EXCL | O_NOCTTY |
O_TRUNC | O_APPEND | /* O_NONBLOCK | */
__O_SYNC | O_DSYNC | FASYNC |
O_DIRECT | O_LARGEFILE | O_DIRECTORY |
O_NOFOLLOW | O_NOATIME | O_CLOEXEC |
__FMODE_EXEC | O_PATH | __O_TMPFILE
));
So first you need to find unique value for your new definition, so it can be bitwise-or'd with flags listed in fcntl_init(). Next you need to add your new definition to include/uapi/asm-generic/fcntl.h. And finally add your new define to fcntl_init(), so it will be checked at compile time.
In the end it boils down to finding the value that doesn't conflict with existing definitions. E.g. as I can see all 10, 100, 1000, 10000, 100000, 1000000 and 10000000 are used. So for your new flags you can use 100000000, 200000000, 400000000 and 800000000 values.
UPDATE: As SailorCaire correctly mentioned, you also need to increment first number in BUILD_BUG_ON() macro. For example, if it originally was BUILD_BUG_ON(20 - 1, and you are to add one element to this list, you should make it BUILD_BUG_ON(21 - 1.
UPDATE 2: Another valuable addition from SailorCaire:
By the way, you'll need to do make install_headers, copy the new headers, and it looks like you'll need to recompile glibc so it becomes aware of the API change.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using "plot for" in gnuplot to vary parameters
I want to use the plot for feature in gnuplot to plot functions with varying parameters. Here an example
par = "1 2" #two values for the parameter
f(x,a) = sin(a*x)
g(x,a) = cos(a*x)
plot for [i=1:words(par)] g(x, word(par,i)), f(x, word(par,i))
What I expect is the plotting of the four functions g(x,1), g(x,2, f(x,1), and f(x,2).
But for whatever reason only three functions are plotted, namely: g(x,1), g(x,2, and f(x,2).
This seems completely arbitrary to me.
Can someone help me out?
A:
You have to repeat the for condition:
plot for [i=1:words(par)] g(x, word(par,i)), for [i=1:words(par)] f(x, word(par,i))
| {
"pile_set_name": "StackExchange"
} |
Q:
Getting list of Variables of map in BPM Metastorm
I'm trying to get list of variables in some map OUTSIDE program automatically. I know I can find them in .process file, with has xml structure.
I also figured out that "x:object" with variable contains "x:Type" ending with "MboField}".
But unfortunately I need to narrow searching criterias more, because I still can't find the main patern to separate variables from other objects.
This is my current code in c#:
var xdoc = XDocument.Load(patches.ProcessFilePatch);
var xmlns = XNamespace.Get("http://schema.metastorm.com/Metastorm.Common.Markup");
IEnumerable<string> values = from x in xdoc.Descendants(xmlns+"Object")
where x.Attribute(xmlns+"Type").Value.ToString().EndsWith("MboField}")
select x.Attribute(xmlns+"Name").Value.ToString();
VariablesInProcessFile = values.ToList();
Any other ways to find Variables among others?
A:
private void getVariablesInProcessFile()
{
var xdoc = XDocument.Load(patches.ProcessFilePatch);
var xmlns = XNamespace.Get("http://schema.metastorm.com/Metastorm.Common.Markup");
var dane = xdoc.Descendants(xmlns + "Object").Where(x => CheckAttributes(x, xmlns)).ToArray();
IEnumerable<string> valuesE = from x in dane.Descendants(xmlns + "Object")
where x.Attribute(xmlns + "Type").Value.ToString().EndsWith("MboField}")
select x.Attribute(xmlns + "Name").Value.ToString();
VariablesInProcessFile = valuesE.ToList();
}
private bool CheckAttributes(XElement x, XNamespace xmlns)
{
var wynik = x.Attribute(xmlns + "Name");
return wynik != null && (wynik.Value == patches.MapName + "Data" || wynik.Value == patches.altMapName + "Data");
}
Where "patches" is my own class containing patch to .process file and possible names of group of Variables, usually related to name of the map.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to know the probability that a trade is successful?
I'm trying to model the distribution of different outcomes of day trading every day for a year. I'm starting with $350 dollars. I'm only doing options trading on Apple stock with a 5% stop loss and a 15% stop gain. And if it doesn't hit one of those stops, I sell before the market closes.
I'm not trying to find a way to control whether I win or lose on the given day, I'm just gonna do my best. But at least in the long run is there a way to use the law of large numbers so that after a year, my average is close to the probability of winning on a given day?
If I flip a coin every day for a year, I can get all heads, yeah, but it's way more likely that I get within 3 or 4 from half heads.
Is there a way to set up my option trade for the day so that it has a specific probability? Or at least on certain days that have certain conditions, will there be a pretty specific probability?
I've tried to learn "the secret to making money on the stock market", but I think for an average joe like me, I'm better off just trying to treat it as much like a coin flip as possible.
And by having certain limits on my orders, I get the impression that a probability can be calculated.
A:
If you had a trading system, and by trading system I mean the criteria setup that you will take a trade on, then once a setup comes up at what price will you open the trade and at what price you will close the trade.
As an example, if you want to buy once price breaks through resistance at $10.00 you might place your buy order at $10.05.
So once you have a written trading system you could do backtesting on this system to get a percentage of win trades to loosing trades, your average win size to average lose size, then from this you could work out your expectancy for each trade that you follow your trading system on.
| {
"pile_set_name": "StackExchange"
} |
Q:
highcharts redraw and reflow not working
I am trying to build a dynamic page that has any number between 1-4 graphs on it that can be added or removed as needed but I have run into a huge problem and I can't seem to get the graph to resize after resizing the containing div. for example if I add a graph on the page it will be width 800, then click a button to add another graph it should resize to be 400 a piece but I cannot make it happen. As a very simplistic model I have the following
$(function () {
$('#container').highcharts({
chart: {
type: 'line',
width: 300
},
title: {
text: 'Width is set to 300px'
},
xAxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
},
series: [{
data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
}]
});
$('#resize').click(function() {
$('#container').attr('style', 'width: 800px');
$("#container").highcharts().reflow();
console.log($('#container').width());
});
});
now when that is run it will log 800 to the dev tools window in chrome but the graph will not resize. I have tried both redraw() and reflow() as suggested in the documentation for highcharts. I even setup a really quick demo on jsfiddle here, http://jsfiddle.net/7cbsV/
can anyone please help me. It is kind of important. Thank you in advance for the help.
A:
How about using simple chart.setSize(w,h)? See docs.
$("#container").highcharts().setSize(800, height);
| {
"pile_set_name": "StackExchange"
} |
Q:
How dangerous is it to translate IPs directly via hosts in Windows
Sorry for the inconvenience, as English is not my native.
I use hosts to access some websites as DNS is polluted.
My question is, take www.google.com as an example.
If I am successfully social engineered by an attacker, and changes the translation in hosts into a phishing website.
If I use http, then I am completely screwed, right?
If I use https, then the browser will give a warning, if my PC is not compromised.
For the https case, is it possible that the phishing website just pass a certificate from www.google.com to me to prove it is genuine?
A:
Consider the following statements:
All certificate authorities trusted by your web browser refuse to issue a certificate for examplebank.com to the attacker without proof of domain ownership.
The signing keys of all authorities are securely stored and an unauthorized person cannot issue a certificate to themselves. (See recent Comodo break-in.)
Your web browser correctly checks if the server's SSL certificate is issued by a valid CA, not revoked, valid for use by servers, and issued for the examplebank.com domain.
There is no active malware or a browser bug that causes such checks to be bypassed.
You always open https://examplebank.com, requesting SSL explicitly instead of relying for the website to redirect you.
You actually read the SSL error messages instead of blindly clicking Ignore when you open the website.
If all of the above are true, HTTPS will warn you that you tried to connect to a fake website. However, HTTPS cannot bypass lower-level redirections (such as spoofing examplebank.com by DNS or /etc/hosts), so if you ignore the warnings, your data will be going to the attacker, not to the real bank.
To conclude, yes, it's dangerous.
In response to the edited question:
If you use plain HTTP, you're screwed.
If you use HTTPS, you will receive a big red warning (see first part of the answer).
Every "certificate" has a RSA (sometimes DSA, ECDSA) key pair. The public key of the pair is part of the certificate, while the private key is locked away in the webserver and never sent over the network. Both keys are needed to successfully complete the TLS/SSL handshake.
If the attacker presents a certificate, but does not have the associated private key, they will not be able to decrypt any traffic that goes over TLS. Wikipedia has a description of the TLS handshake.
A:
SSL (HTTPS) will only protect you as long as your client is not compromised.
If someone manages to modify /etc/hosts, he can also manage to modify your browser to not perform the SSL validation of the server you're connecting to, or he can add his fraud server's fake certificate into your system's database of trusted certificates.
If however your client is not compromised and someone manages to redirect your browser to a different IP address (e.g. some kind of DNS-related hack, or cheating you to modify /etc/hosts without anything else), the browser will warn you that something's wrong with the server's certificate, and, provided you don't ignore the warning and proceed, you are safe.
On your second question:
For the https case, is it possible that the phishing website just pass
a certificate from www.google.com to me to prove it is genuine?
No, that is not possible, unless the attacker managed to obtain the server's private key (e.g. by hacking the server itself). Even if a fraud server "passed on" the server's certificate, he will not be able to prove its identity to the client if it does not possess that private key. If he attempted to do that, he will fail and the browser will show a warning.
| {
"pile_set_name": "StackExchange"
} |
Q:
JavaScript runtime error: Unable to add dynamic content
I'm making a javascript metro app and have some code like this:
<script>
document.writeln(foo());//this line is trouble
</script>
and when I tried to run, it gave me a rather long error:
Unhandled exception at line 20, column 9 in ms-appx://a375ffac-3b69-475a-bd53-ee3c1ccf4c4e/default.html
0x800c001c - JavaScript runtime error: Unable to add dynamic content.
A script attempted to inject dynamic content, or elements previously
modified dynamically, that might be unsafe. For example, using the
innerHTML property to add script or malformed HTML will generate this
exception. Use the toStaticHTML method to filter dynamic content, or
explicitly create elements and attributes with a method such as
createElement. For more information, see
http://go.microsoft.com/fwlink/?LinkID=247104.
How can I get around this?
A:
Windows 8 restricts the content you can set through innerHTML and Writeln, because it's considered unsafe...
The correct way to add content is:
// The untrusted data contains unsafe dynamic content
var unTrustedData = "<img src='http://www.contoso.com/logo.jpg' on-click='calltoUnsafeCode();'/>";
// Safe dynamic content can be added to the DOM without introducing errors
var safeData = window.toStaticHTML(unTrustedData);
// The content of the data is now
// "<img src='http://www.contoso.com/logo.jpg'/>"
// and is safe to add because it was filtered
document.write(safeData);
If your code has some javascript, you can use this function (But microsoft dont recomend it):
MSApp.execUnsafeLocalFunction(function() {
var body = document.getElementsByTagName('body')[0];
body.innerHTML = '<div style="color:' + textColor + '">example</div>';
});
See at:
http://msdn.microsoft.com/en-us/library/windows/apps/Hh767331.aspx
For your case:
MSApp.execUnsafeLocalFunction(function() {
document.writeln(foo());
});
Note that you should only do this if you understand your content is safe; if you don't, I would recommend using the toStaticHTML method.
A:
regarding to the docs I would try :
document.writeln(window.toStaticHTML(foo()));
| {
"pile_set_name": "StackExchange"
} |
Q:
Apple rejected an app that for use on non public api where there aren't any non pulic apis
This is the message I got from Apple for rejecting my app:
Your app uses or references the following non-public APIs:
didDetermineState:forRegion:
didEnterRegion:
didExitRegion:
The use of non-public APIs is not permitted on the App Store because it can lead to a poor user experience should these APIs change.
I really don't know what to do as there api are clearly public. Anyone got some advise? It would really help.
A:
I think the public apis you are mentioning about are those in CLLocationManagerDelegate. If it is the case, take didEnterRegion:, for example, the api is actually locationManager:didEnterRegion:. However, Apple mentions didEnterRegion: only. That probably means somewhere in your app, you have declared a method with that exact signature, and it happens to have the same signature with a private api method.
My suggestion is to do a search on your whole project for such methods and rename them.
| {
"pile_set_name": "StackExchange"
} |
Q:
Multiplication error in php
I'm building a site where people can exchange coins (site currency) into Bitcoin. The problem I'm having is that for some reason when I multiply the $btcprice with 3 or less the echo is really weird... for your sake this is the code that matters:
<?php
// get 0,01 usd in bitcoins into a variable
$btcprice = file_get_contents('https://blockchain.info/tobtc?currency=USD&value=0.01');
$valueInBTC = 4 * $btcprice;
echo $valueInBTC;
?>
Anything that's 4 or higher will work, but if you try to multiply this with 3 or less it gets weird. For example this:
<?php
// get 0,01 usd in bitcoins into a variable
$btcprice = file_get_contents('https://blockchain.info/tobtc?currency=USD&value=0.01');
$valueInBTC = 3 * $btcprice;
echo $valueInBTC;
?>
Will echo 7.959E-5
I just don't understand what the problem is...
A:
The result you are getting is not an error. It is simply in a formatting you don't expect / know yet. 7.959E-5is exactly the same as 0.00007959 it is just a different way of writing it down. Think of it as 7.959E-5 = 7.959 × (10 ^ (-5)) = 0.00007959. It is called Scientific notation (E notation). In cumputation / science this notation is used, because you can show very large or very small (as in your case) numbers with less digits (it is just shorter to write).
To get the number in other formattings use the php function sprintf().
As you are handling bitcoin values, you shouldn't be formatiing the numbers until just for output. With bitcoins you always deal with very small numbers and you will soon meet precision problems if you try and calculate with formatted floating point numbers.
| {
"pile_set_name": "StackExchange"
} |
Q:
Removal of special characters, a comma separated text, PHP
I got my text variable which is user-specified, normally, user should enter the tags which has to look following:
"food, community, relationship"
but if user type for example
"food;;[]'.'.;@$#community,,,-;,,,relationship"
the script should change it into:
"food, community, relationship".
How can I get this done?
A:
how about:
$str = "-----music,,,,,,,,games;'235@#%@#%media";
$arr = preg_split("/\W+/", $str, -1, PREG_SPLIT_NO_EMPTY);
$str = implode(', ', $arr);
echo $str,"\n";
output:
music, games, 235, media
You could adapt the \W to which characters you need to keep.
| {
"pile_set_name": "StackExchange"
} |
Q:
CSS minify and rename with gulp
I've a variable like
var files = {
'foo.css': 'foo.min.css',
'bar.css': 'bar.min.css',
};
What I want the gulp to do for me is to minify the files and then rename for me.
But the tasks is currently written as (for one file)
gulp.task('minify', function () {
gulp.src('foo.css')
.pipe(minify({keepBreaks: true}))
.pipe(concat('foo.min.css'))
.pipe(gulp.dest('./'))
});
How to rewrite so it work with my variable files defined above?
A:
You should be able to select any files you need for your src with a Glob rather than defining them in an object, which should simplify your task. Also, if you want the css files minified into separate files you shouldn't need to concat them.
var gulp = require('gulp');
var minify = require('gulp-minify-css');
var rename = require('gulp-rename');
gulp.task('minify', function () {
gulp.src('./*.css')
.pipe(minify({keepBreaks: true}))
.pipe(rename({
suffix: '.min'
}))
.pipe(gulp.dest('./'))
;
});
gulp.task('default', ['minify'], function() {
});
A:
I tried the earlier answers, but I got a never ending loop because I wasn't ignoring the files that were already minified.
First use this code which is similar to other answers:
//setup minify task
var cssMinifyLocation = ['css/build/*.css', '!css/build/*.min.css'];
gulp.task('minify-css', function() {
return gulp.src(cssMinifyLocation)
.pipe(minifyCss({compatibility: 'ie8', keepBreaks:false}))
.pipe(rename({ suffix: '.min' }))
.pipe(gulp.dest(stylesDestination));
});
Notice the '!css/build/*.min.css' in the src (i.e. var cssMinifyLocation)
//Watch task
gulp.task('default',function() {
gulp.watch(stylesLocation,['styles']);
gulp.watch(cssMinifyLocation,['minify-css']);
});
You have to ignore minified files in both the watch and the task.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to install Visual Studio on Ubuntu 20.04?
Can anyone tell how to install Visual Studio and .NET Framework on Ubuntu 20.04?
Is there any way to Install .NET and Visual Studio in Ubuntu 20.04?
A:
Unfortunately Visual Studio does not available for Linux. But you really want' exactly VS - you should try Wine or any Windows VM.
But I recommend for you one of the following options:
Rider (Cross platform IDE from JetBrains)
Visual Studio Code (Very popular solution for developer on any technology)
Mono Develop
Eclipse
| {
"pile_set_name": "StackExchange"
} |
Q:
can't select all elements with classList API
I'm having a problem selecting all the LI tags when converting jQuery code to HTML5 javascript
code. I have applied the click event to the parent UL, and the click event is being applied to the correct clicked target LI. The class "selected" is also being applied. The problem is that I need all classes to be cleared from the LI tags before the "selected" class is applied, as I only want it applied to the current event target. In jQuery it is simply a matter of removing classes from the LI's, but I am having problems targeting all the LI tags and removing the class in javascript. I suspect the problem is how I am iterating over the node list returned from QuerySelectorAll. I have also tried amongst other things, document.GetElementsByTagName, and iterating over these.
I am getting an "Uncaught TypeError: Cannot read property 'contains' of undefined" on the myFunc function.
I would be very happy if someone could point out my error.
<div id='button'></div>
<ul id='swatches'>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
The jQuery code
$('li').on('click', function(){
$('li').removeClass('selected');
$(this).toggleClass('selected');
});
Using the classList API
var swatch = document.getElementById('swatches'),
$li = document.querySelectorAll('#swatches li');
swatch.addEventListener('click', myFunc, false);
function myFunc(e){
var target = e.target;
for(var i=0; i<$li.length; i++){
if($li.classList.contains('selected')){
$li.classList.remove('selected');
}
}
if(target.nodeName.toLowerCase() === 'li'){
e.target.classList.toggle('selected');
}
}
A:
I suspect the problem is how I am iterating over the node list returned from QuerySelectorAll.
Yes. You forget the indices. It should be
for (var i=0; i<$li.length; i++)
if ($li[i].classList.contains('selected'))
// ^^^
$li[i].classList.remove('selected');
// ^^^
However, two points:
You don't need to test for contains() before calling remove() unless you need the information explicitly. Trying to remove a class that doesn't exist just does nothing.
You might not need to iterate the whole $li collection on every click. Since there is only one <li> with the .selected class at a time, you might simply store a reference to the currently-selected element, or use
var cur = swatch.querySelector("li.selected");
if (cur) cur.classList.remove('selected');
(which could work with an id as well).
| {
"pile_set_name": "StackExchange"
} |
Q:
Retrieve List of picklist values in a Set
I got the following variables(Custom Labels referring to picklist values), and a get method to retrieve List of picklist values of a field.
I need to retrieve those List of picklist values in a Set. How can I do this ?
public String dailyValue {
get { return System.Label.Daily.toLowerCase().trim(); }
private set;
}
public String weeklyValue {
get { return System.Label.Weekly.toLowerCase().trim(); }
private set;
}
public String monthlyValue {
get { return System.Label.Monthly.toLowerCase().trim(); }
private set;
}
public String quarterlyValue {
get { return System.Label.Quarterly.toLowerCase().trim(); }
private set;
}
public String biannuallyValue {
get { return System.Label.Bi_Annually.toLowerCase().trim(); }
private set;
}
public String annuallyValue {
get { return System.Label.Annually.toLowerCase().trim(); }
private set;
}
//values from the frequency picklist
public List<SelectOption> getMonitoringFrequency(){
List<SelectOption> frequencyTypes = new List<SelectOption>();
Schema.DescribeFieldResult fieldResult = Metric__c.Monitoring_Frequency__c.getDescribe();
List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
for( Schema.PicklistEntry f : ple){
frequencyTypes.add(new SelectOption(
f.getValue().toLowerCase(),f.getLabel().toLowerCase()
));
}
return frequencyTypes;
}
A:
Depending on whether you want the label or the value in your set, create a set:
set<String> picklistValues = new set<String>();
set<String> picklistLabels = new set<String>():
and then in your for-loop, add the value or label, as appropriate:
for( Schema.PicklistEntry f : ple){
frequencyTypes.add(new
SelectOption(f.getValue().toLowerCase(),f.getLabel().toLowerCase()));
picklistValues.add(f.getValue());
picklistLabels.add(f.getLabel());
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I move JQuery draggable element without mouse
Is there a different way of JQuery draggable element moving?
Think yourself as a spammer.
A:
it should not be such a big deal, only calling the correct sequence of: .mousedown(), .mousemove() and .mouseup()
as the official documentation says (http://api.jquery.com/mousedown/):
Bind an event handler to the "mousedown" JavaScript event, or trigger that event on an element.
the same is true for the other two jquery function descriptions
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there any way to break on the next line of code executed in Visual Studio?
I'm trying to track down a bug that occurs when I click a particular element on an aspx page...
In the past I've had to track down the class that handles that particular event and put a break point on the line that I think should be hit. Often it takes me several tries before I finally find the correct class....especially if the class is a user control buried somewhere...
So it's left me wondering if there is any way to get Visual Studio to break at the next line of code executed after I click an element (say a button) on an aspx page. I know there is a way to break on any exception that is thrown so I'm thinking maybe there is something similar that could help me.
If this sort of feature isn't a possibility, perhaps someone could suggest a better way for me to quickly find the class I want to debug...
A:
Have you tried the Debug > Break All ("pause") button? (Ctrl+Break)
It'll usually break somewhere pretty low on the stack, like at Show() for your main form in a WinForms app, but if you then Step Into to get past that, it'll often work pretty well for this sort of thing.
A:
Are you looking for the Step Into (F11) or Step Over (F10) ?
-- Edit
Do you also know about the Call Stack window? It can help you determine your location, and what is happening.
| {
"pile_set_name": "StackExchange"
} |
Q:
Parse php associative array to javascript object
I want to have a javascript array of "country" objects which at this stage will have only two attributes: name, and geonameId.
I get these countries from a database like so:
$sql = "SELECT name, geonameId FROM countryinfo";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$rows = array ();
while($row = $result->fetch_assoc()) {
$country["geonameId"]);
$rows[$row['geonameId']] = $row['name'];
}
}
$conn->close();
?>
I then have this javascript script which turns the php array into a javascript one:
<script type="text/javascript">
var allCountries = <? echo json_encode($rows); ?>;
console.log(allCountries);
</script>
I just want to turn that array of key/value pairs into an array of objects so I have easier access to new attributes that I may add in the future. At the moment the javascript array logs to the console like this:
Object {0: "Netherlands Antilles", 49518: "Rwanda", 51537: "Somalia", 69543: "Yemen", 99237: "Iraq", 102358: "Saudi Arabia", 130758: "Iran", 146669: "Cyprus", 149590: "Tanzania", 163843: "Syria", 174982: "Armenia", 192950: "Kenya", 203312:...
How do I convert that array of key/value pairs to an array from javascript objects (with refactoring, I will be adding a Country class and the array will contain Country objects).
A:
My relevant code was changed to this to get it to work:
$sql = "SELECT name, geonameId FROM countryinfo";
$result = $conn->query($sql);
$allCountries = [];
if ($result->num_rows > 0) {
$rows = array ();
while($row = $result->fetch_assoc()) {
$country = array(
"name" => $row['name'],
"geonameId" => $row['geonameId']
);
$allCountries[] = $country;
}
}
$conn->close();
?>
<script type="text/javascript">
var allCountries = <?php echo json_encode($allCountries, JSON_PRETTY_PRINT) ?>;
console.log(allCountries)
</script>
| {
"pile_set_name": "StackExchange"
} |
Q:
Automatically add an Order column into tablix in Local Report?
I can populate my own Order column in the DataSource and pass this DataSource to Tablix. But if there is a way to automatically an Order column right in Tablix at design time (such as using some variable or expression), it would be better. Here is what I want:
Order | Column 1 | Column 2
1
2
3
...
The Order column can be added at design time easily, but how to populate it with ordinal numbers when refreshing report (of course, I don't want to populate it from data source). I want some way to populate it via expression or something like that right in Local Report designer.
Your help would be highly appreciated!
Thank you very much in advance!
A:
Yes,
Put expression =RowNumber(nothing) in Order column.
and if you want to show row number differently for group try =RowNumber("GroupName1")
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I get vim omnicompletion to support php class methods using ::
Using vim + php + ctags I can get fairly good php auto-completion. But one part really eludes me: getting vim to auto-complete class methods. Here's an example:
The full method is
CVarDumper::dumpAsString
And I want it to complete if I type this:
CVarDumper::d<tab>
The double-colon does not work. However, if I replace the :: with a . then it does autocomplete:
CVarDumper.d<tab>
I see the c++ omnifunc function has an option to allow for :: completion:
let OmniCpp_MayCompleteScope = 1 " autocomplete after ::
Is there an equivalent for the ft-php-omni function, or a way to hack this feature in?
Update:
Turns out the problem was the supertab plugin, specifically this option in my .vimrc
" SuperTab option for context aware completion
let g:SuperTabDefaultCompletionType = "context"
After removing that option supertab + phpcomplete allows for completion of php class methods.
A:
Try this alternative phpcomplete script. It is better than the default one in every possible ways, including the fact that it supports static completion.
| {
"pile_set_name": "StackExchange"
} |
Q:
Qual é a definição de delete JavaScript
Me deparei com uma instrução onde o delete representa um tipo em JavaScript. Pelo menos foi o que eu entendi.
Gostaria da ajuda de vocês pois não encontrei nenhuma referencia na internet.
if (MvL.object.hasValue(domain.cpf) || MvL.object.hasValue(domain.cnpj)) {
delete domain.nome_cliente;
delete domain.cod_cgl;
delete domain.uf;
}
A:
delete não é um tipo, mas sim um operador remove uma propriedade de um objeto. No entanto, só irá funcionar em propriedades que possuam o atributo de propriedade [[Configurable]] definido como true. Veja:
const obj = {};
obj.name = 'Luiz';
Object.defineProperty(obj, 'lastName', {
enumerable: true,
configurable: false // Não irá permitir que deletemos a propriedade `name`.
});
console.log(obj);
delete obj.name;
delete obj.lastName;
console.log(obj);
No modo normal do JavaScript, se você tentar deletar uma propriedade não configurável, false será retornado. No entanto, se você estiver no modo estrito, um erro será lançado:
'use strict';
const obj = {};
Object.defineProperty(obj, 'lastName', {
enumerable: true,
configurable: false
});
delete obj.lastName; // Uncaught TypeError: Cannot delete property 'lastName'
Esse operador irá retornar true em todos os casos, exceto quando você tentar remover uma propriedade não configurável sem estar no modo estrito – já vimos que nesse último caso, um erro é lançado.
Se, mesmo no modo estrito, você quiser receber um booleano false se não tiver conseguido deletar a propriedade, você pode usar o método Reflect.deleteProperty:
'use strict';
const obj = {};
obj.name = 'Luiz';
Object.defineProperty(obj, 'lastName', {
enumerable: true,
configurable: false
});
console.log(obj);
console.log(Reflect.deleteProperty(obj, 'name')); // true
console.log(Reflect.deleteProperty(obj, 'lastName')); // false
console.log(obj);
Vale dizer que tanto delete quanto Reflect.deleteProperty retornarão true mesmo se a propriedade que você tentar deletar não existir.
| {
"pile_set_name": "StackExchange"
} |
Q:
Add Password Requirements to Membership Provider
Do I need to make a Custom Membership Provider or is there another way?
I have a project using ASP.NET Forms Authentication and the Microsoft SQL Membership Provider. The website is DONE. I use this provider everywhere. (Register, Login, Forgot Password, etc...)
Until now, my website users have not needed complex passwords. The users' passwords were really just pins. The user could select anything for a password in the past. I had almost no restrictions for this website because none of the data is private or personal.
However I have received new requirements.
Here are the new password requirements:
Passwords must be at least 8 characters in length.
Passwords must be created using 3 of the following 4 character types:
Uppercase
Lowercase
Numeric
Punctuation
Do not use your name or User ID in the password.
Do not use old passwords again later.
Passwords must be changed at least every 60 days.
Passwords may not contain your User ID or any part of your full name.
Password history retention will prohibit use of the last 24 passwords.
Passwords may be changed by users only once in any 6-day period.
I realize I am going to have to modify all of the following pages: Register, Login, Forgot Password, etc... fortunately I stopped using the default controls a long time ago.
I appreciate your thoughts.
My first thought was that I need to write a Custom Membership Provider.
I don't know how to make the standard provider to do most of this. I could write code to do.
Do I modify the aspnet_membership table?
Should I add my own table aspnet_something?
Can the user profile table be used for this problem?
Do I need my own MembershipUser class?
Thanks.
A:
You need to listen to the ValidatingPassword event.
See ASP.NET Membership ChangePassword control - Need to check for previous password for sample code of how to do this.
| {
"pile_set_name": "StackExchange"
} |
Q:
How does MS Entity Framework map from the conceptual model to CLR types?
Given an Entity Data Model (EDMX) with "Code Generation Strategy" set to "None", how does EF determine which CLR types to map the conceptual model to?
I think I read somewhere that it just probes the assembly for types that match the conceptual model, but that was in reference to a CTP edition of EF. Is this still the case?
Can I control this process somehow?
In particular, I am in a scenario where I am moving a substantial codebase from using Linq2SQL to using POCO with EF 4.0. Thus, I have the Linq2SQL classes as well as my POCO classes, for now residing in the same assembly, but in different namespaces. I'm trying to have a smooth migration from L2S to EF so I would like to have the two frameworks run in parallel for a while. However, I get a runtime-error saying
The mapping of CLR type to EDM type is
ambiguous because multiple CLR types
match the EDM type 'SomeType'.
Previously found CLR type
'SomeNamespace.SomeType', newly found
CLR type 'SomeNamespace.POCO.SomeType'
where SomeNamespace is the namespace of the L2S entities. This error makes sense if EF is just probing for all types matching the conceptual model. Can I confine EF to only probe the SomeNamespace.POCO namespace? Or should I put my POCO objects in another assembly? Or should I take a third approach?
Thank you.
A:
Notice this comment from the ADO.NET team blog:
Jeff 25 Feb 2010 9:10 AM @Derek
This is intentional. You can put your
POCO classes in whatever namespace
you'd like. The Entity Framework's by
convention mechanism for detecting
which properties on the entity match
the properties of entities in your
model does not use Namespace. What
matters is that the type name (without
namespace) matches the EntityType name
in your model (edmx/csdl file).
One area to watch out for is if you
have multiple types with the same name
but in different namespaces. Because
we don't account for namespace, we
detect that we've found multiple types
and we throw an exception.
Jeff
See this article:
link text
| {
"pile_set_name": "StackExchange"
} |
Q:
How do baby animals that primarily subsist on cellulose get their initial gut flora?
In the case of mammals like giraffes and koalas, is that bacteria common on the plants they eat so when a baby starts to try to stick something besides its mother's milk in its mouth, it can't digest the cellulose at all the first time, but along with the cellulose, into its mouth went some cellulose-digesting flora that then begins a lifelong colony in the animal's gut? Is that about how it happens?
A:
I would not expect this to be any different than other animals - they get the flora from the environment. Key components of the environment for newborns are:
Birth canal
Den / living quarters
Skin / fur of mother, especially near the teats
Diet
Feces of family members (animals sniff this and aren't so clean)
A:
I don't know about ruminants, but baby rabbits (and presumably other lagomorphs) apparently acquire the necessary intestinal flora by consuming their mother's cecotropes.[1]
[1] Johnson-Delaney, C.A. (2006), "Anatomy and Physiology of the Rabbit and Rodent
Gastrointestinal System" (PDF)
| {
"pile_set_name": "StackExchange"
} |
Q:
Anyone know whether there is a 5-star rating component on iPhone?
In Google groups and some other web sites, there is a 5-star rating component which is pretty neat, such as in this url:
http://groups.google.com/group/Google-Picasa-Data-API/browse_thread/thread/b5a346e6429a70a7?hl=en
I am wondering whether there is an existing 5-star rating component in the iPhone environment. Or if there is not, if anyone has clue where to start?
Thanks
A:
Here's another open source solution: https://github.com/dlinsin/DLStarRating
A:
UIView that allows you to build Rating components to provide the same kind of experience AppStore or Youtube applications on iPhone do.
http://code.google.com/p/s7ratingview/
A:
I'd go simpler. Subclass UIControl and implement the touchesBegan: touchesMoved: and touchesEnded: methods. You can determine which star the user pressed/dragged/let up on with the X coordinate of the touch. For example:
CGFloat relativeTouchLocation = [event locationInView:self] / self.bounds.size.width;
Then it's just up to you to determine which stars are illuminated based on that value. Oh, and to send a UIControlEventValueChanged event.
Obviously, you also override drawRect: to draw the stars in the view.
Although Jason's solution above will work, your user won't be able to slide her finger across the control to fine-tune her rating. This would also give you the option of doing half-stars or other fine adjustments.
| {
"pile_set_name": "StackExchange"
} |
Q:
Put the correct image in the box according to the ID
I have a function that loads certain image data from the database. This data is later loaded into html through * ngFor.
In order to load the image referring to this data I need to get the ID of the function that carries the image information, and then perform the function to get image with that same ID.
I can get the ID and receive all the images, however at the time of preview all the different images are loaded into the boxes but they all have the same image. (If it has 10 images, it will show the 10 to load and will stop at the last) Only the last one is visible in all boxes.
The goal is in each box to fill the image with its ID.
Can anyone help me solve?
My HTML
<div class="row tab-pane Galeria">
<div *ngFor="let product of products" class="col-xl-2 col-lg-3 col-md-4 col-sm-6">
<div class="image-item" (click)="fillModal($event, product)">
<a class="d-block image-block h-100">
<homeImage>
<img *ngIf="Images && Images[product.id] && inView" [src]="Images" class="Images img-fluid" alt="">
</homeImage>
</a>
<div class="ImageText">{{product.name}}</div>
</div>
</div>
</div>
Component.ts
GetProducts() {
let self = this;
this.Global.refreshToken()
.subscribe(function (result) {
self.homeService.getProducts()
.then(function (resultado) {
if (resultado) {
self.products = resultado;
}
})
.then(() => {
if (self.products) {
return Promise.all(self.products.map((product) => self.ImageInfo(product.id)));
}
})
.catch((err) => console.error(err));
});
}
ImageInfo(id) {
var self = this;
this.Global.refreshToken().subscribe(function (result) {
self.homeService.getImage(id).then(function (resultado) {
if (resultado) {
self.Images=resultado;
}
}).catch();
});
}
A:
Obviously your last image will display as "Images: any " has been assigned values in each iteration of products. So the last product image will be the value of Images after iteration will get completed.
Image and product id as map
imagMap: Map<string, string> = new Map<string, string>();
and use them in [src]="imagMap.get(product.id)"
and in the service of image :-
ImageInfo(id) {
var self = this;
this.Global.refreshToken().subscribe(function (result) {
self.homeService.getImage(id).then(function (resultado) {
if (resultado) {
self.Images=resultado;
self.imagMap.set(id,resultado);
}
}).catch();
});
}
and this way it will keep track of every individual image being stored
| {
"pile_set_name": "StackExchange"
} |
Q:
You don't need to take an algebraic closure twice in model theory
This is an exercise (1.4.11) from Marker. Fix a language $\mathcal L$ and $\mathcal L$-structure $\mathcal M$. For a subset $A \subseteq M$, an element of $M$ is algebraic over $A$ if it is a member of a finite $A$-definable subset of $M$. Let $\bar A$ denote the set of algebraic elements over $A$. We would like to show that $\bar {\bar A} = \bar A$.
Here's a failed attempt to solve the problem. Let a formula $\psi(x, b)$ defines a finite set with a parameter $b$ from $\bar A$ and $\phi (y, a)$ defines a finite set with a parameter $a$ from $A$ (for simplicity we assume the number of parameters is one). Then, naively, the formula $\exists z (\psi(x, z) \wedge \phi(z, a))$ will do the job. However, this formula is not known to define a finite set a priori.
I'd be grateful if you could help me in this problem.
A:
Let $b\in\textrm{acl}\big(\textrm{acl}(A)\big)$. Then there is an $a\in\textrm{acl}(A)$ and formula $\psi(x,y)\in L(A)$ such that $\exists^n x\,\psi(x,a)\wedge\psi(b,a)$ for some $n$
As $a\in\textrm{acl}(A)$, there is a formula $\varphi(y)\in L(A)$ such that $\exists^m y\,\varphi(y)\wedge\varphi(a)$ for some $m$.
The following is a formula over $A$ that has at most $n\cdot m$ solutions and among these $b$:
$$\exists y \Big[\psi(x,y)\wedge\varphi(y)\wedge\exists^n x\,\psi(x,y)\Big]$$
| {
"pile_set_name": "StackExchange"
} |
Q:
setting wallpaper through code
I was trying to make an app which also had the facility to let user select wallpaper he would like to set. I have managed this by calling the Gallery Intent. Once the user selects a specific image, the data path of the image is returned to me which then i preview to the user by setting the image onto an imageview.
The problem crops up when the image size (and/or resolution) is greater than what android expects. This results in failure of my module.
And as if this was not enough, wen the user tries to select some other wallpaper(and in my test case the "other" wallpaper was also of size >700kb) then the app crashes with the "OutOfMemoryException"...
Helppp me here guys!!!
For Gallery Intent i use:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),SELECT_IMAGE);
For setting the wallpaper i use:
InputStream is = getContentResolver().openInputStream(Uri.parse(uri_returned_from_intent));
Bitmap bgImage = BitmapFactory.decodeStream(is);//OutOfMemory error thrown here
setWallpaper(bgImage);
So i have 2 problems to deal with:
How to crop the image before setting it as wallpaper...
Cant understand y OutOfMemoryException is thrown, coz none of my image sizes exceed even 1mb... and i guess the VM budget in case Of N1 is 24Mb if m not mistaken...
A:
You should decode with inSampleSize option to reduce memory consumption.
Android: Strange out of memory issue while loading an image to a Bitmap object (stackoverflow)
Another option inJustDecodeBounds can help you to find correct inSampleSize value
How to get bitmap infomation before decode an image file? (Google Groups)
| {
"pile_set_name": "StackExchange"
} |
Q:
Geometric Operations in GIS Systems
I have worked with 2D geometry for CAD - My questions are general and relate to understanding operations on geometric entities (lines).
Should geometric operations such as line-line intersection be done in the projected spaces (such as EPSG 3857) ?
I've had a brief look at the geos library, but it is unclear whether the inputs should be in a linear projected space.
If operations are done in projected space - does this introduce significant error in the result when the output is un-projected?
A:
Possible error of your geometric operation depends on:
overall size of the objects - bigger size increase errors,
projection that you use,
datum that you use (each datum suits some parts of the Earth more than the others)
quality of your data.
Generally you don't want to work with unprojected data at all unless there is some specific reasons like finding an orthodrome on a global scale (there is a Gnomonic projection for a regional scale) or you are working with global data in general (in this case you store data unprojected but project it for specific operations you need to perform: distance calculation, etc.). Note that there is no universal projection and for each task and the region of the world an appropriate projection (more precisely - CRS) have to be used for achieving the best results.
If your project demands to work with more than one projection you should pay a lot of attention to your data quality and integrity. Here a question: will a parallel and a meridian cross in any projection? The picture below is an unprojected image of the countries and a parallel and a meridian.
'Yes' would you say - they will cross in any projection. But I say - 'Nope if your data sucks ass'. Lets project our data into the Bonne projection:
Both parallel and meridian were defined only by 2 points each (start and end). That leaded to a disaster in specific projection. But if we know that we will use our lines in specific projection we can adapt our data to it. Lets add some nodes to our lines an project them again: much better result.
So when you are working with GIS, especially if you are going to modify your data - you have to understand the pros and cons of CRS. Don't be afraid to use projections - be afraid to use wrong one.
| {
"pile_set_name": "StackExchange"
} |
Q:
Nested List and For Loop
Consider this:
list = 2*[2*[0]]
for y in range(0,2):
for x in range(0,2):
if x ==0:
list[x][y]=1
else:
list[x][y]=2
print list
Result:
[[2,2],[2,2]]
Why doesn't the result be [[1,1],[2,2]]?
A:
Because you are creating a list that is two references to the same sublist
>>> L = 2*[2*[0]]
>>> id(L[0])
3078300332L
>>> id(L[1])
3078300332L
so changes to L[0] will affect L[1] because they are the same list
The usual way to do what you want would be
>>> L = [[0]*2 for x in range(2)]
>>> id(L[0])
3078302124L
>>> id(L[1])
3078302220L
notice that L[0] and L[1] are now distinct
| {
"pile_set_name": "StackExchange"
} |
Q:
Scene Graph as Object Container?
Scene graph contains game nodes representing game objects. At a first glance, it might seem practical to use Scene Graph as physical container for in game objects, instead of std::vector<> for example.
My question is, is it practical to use Scene Graph to contain the game objects, or should it be used only to define scene objects/nodes linkages, while keepig the objects stored in separate container, such as std::vector<>?
A:
Deciding on what type of scene management to use depends very heavily on what type of logic you are trying to run. Consider the different consumers of your scene:
Rendering Consumer
The renderer probably just wants to know what is currently visible to the user at any given point. It wants a bounding volume hierarchy for fast culling (BVH wiki article)
so that it can figure out that a chair inside a boat doesn't need to be drawn because the boat's bounds are outside the view frustum. This might be embedded into an octree.
It also might want to have an idea that the chair is on its back inside the boat, and that the boat is rolling up and down on some waves when it finally comes into view. That way to find the final world coordinates of the chair's vertices it can concatenate the chair and boat transforms and be done with it (this also makes your job as a programmer easier).
Yet another way of looking at this problem is that the renderer is probably running a good card, and ultimately just wants a pile of triangles sorted so as to minimize texture, shader, material, lighting, and transform state changes. This last will probably help you more than a BVH, preformance-wise.
Game Logic Consumer
The game logic probably just wants a flat list of things that can talk to each other by a messaging system, so a std::vector is probably fine.
The game might also want a way of keeping track of who is closest to what, so some sort of [nearest-neighbor][3] information might be helpful in that case. This can be provided by a BVH also, but having to up and down the graph might be annoying.
The game might even just want to know that when it moves A, A's item B should move too... in which case we are back to a sort of transform hierarchy.
Physics Consumer
Your game physics might want to have a [special representation][4] of indoor spaces for very fast collision detection. Alternately it might use some sort of octree or [spatial hashing][5] to efficiently find things that might collide.
None of the above physics data structure really looks like a "scene graph" in the Java3D sense.
Audio Consumer
An audio engine just wants geometry, perhaps a potentially visible (audible) set, or some sort of bounding volume hierarchy to calculate sound attenuation and propogation. Again, not really a normal sort of scene graph, though it may well be a graph of geometry in your scene.
Ultimately...
...it really just depends on the exact needs of your application. I'd suggest using a flat list to start with, and seeing where your issues arise. You might even try a flat list with a transform hierarchy, because that is perhaps the one sort of scenegraph useful for reasons other than efficiency.
Good luck!
A:
There's one good reason not to use the scene graph as the container for game objects, and that's instancing. If you want to reuse some resources, it makes much more sense to just refer to the resource from your scene graph several times than to have several actual copies.
| {
"pile_set_name": "StackExchange"
} |
Q:
natural language query processing
I have a NLP (natural language processing application) running that gives me a tree of the parsed sentence, the questions is then how should I proceed with that.
What is the time
\-SBAR - Suborginate clause
|-WHNP - Wh-noun phrase
| \-WP - Wh-pronoun
| \-What
\-S - Simple declarative clause
\-VP - Verb phrase
|-VBZ - Verb, 3rd person singular present
| \-is
\-NP - Noun phrase
|-DT - Determiner
| \-the
\-NN - Noun, singular or mass
\-time
the application has a build in javascript interpreter, and was trying to make the phrase in to a simple function such as
function getReply() {
return Resource.Time();
}
in basic terms, what = request = create function, is would be the returned object, and the time would reference the time, now it would be easy just to make a simple parser for that but then we also have what is the time now, or do you know what time it is. I need it to be able to be further developed based on the english language as the project will grow.
the source is C# .Net 4.5
thanks in advance.
A:
As far as I can see, using dependency parse trees will be more helpful. Often, the number of ways a question is asked is limited (I mean statistically significant variations are limited ... there will probably be corner cases that people ordinarily do not use), and are expressed through words like who, what, when, where, why and how.
Dependency parsing will enable you to extract the nominal subject and the direct as well as indirect objects in a query. Typically, these will express the basic intent of the query. Consider the example of tow equivalent queries:
What is the time?
Do you know what the time is?
Their dependency parse structures are as follows:
root(ROOT-0, What-1)
cop(What-1, is-2)
det(time-4, the-3)
nsubj(What-1, time-4)
and
aux(know-3, Do-1)
nsubj(know-3, you-2)
root(ROOT-0, know-3)
dobj(is-7, what-4)
det(time-6, the-5)
nsubj(is-7, time-6)
ccomp(know-3, is-7)
Both are what-queries, and both contain "time" as a nominal subject. The latter also contains "you" as a nominal subject, but I think expressions like "do you know", "can you please tell me", etc. can be removed based on heuristics.
You will find the Stanford Parser helpful for this approach. They also have this online demo, if you want to see some more examples at work.
| {
"pile_set_name": "StackExchange"
} |
Q:
Natural vs surrogate keys on support tables
I have read many articles about the battle between natural versus surrogate primary keys.
I agree in the use of surrogate keys to identify records of tables whose contents are created by the user.
But in the case of supporting tables what should I use?
For example, in a hypothetical table "orderStates".
The valuse in this table are not editable (the user can't insert, modify or delete this values).
If you use a natural key would have the following data:
TABLE ORDERSTATES
{ID: "NEW", NAME: "New"}
{ID: "MANAGEMENT" NAME: "Management"}
{ID: "SHIPPED" NAME: "Shipped"}
If I use a surrogate key would have the following data:
TABLE ORDERSTATES
{ID: 1 CODE: "NEW", NAME: "New"}
{ID: 2 CODE: "MANAGEMENT" NAME: "Management"}
{ID: 3 CODE: "SHIPPED" NAME: "Shipped"}
Now let's take an example: a user enters a new order.
In the case in which use natural keys, in the code I can write this:
newOrder.StateOrderId = "NEW";
With the surrogate keys instead every time I have an additional step.
stateOrderId_NEW = .... I retrieve the id corresponding to the recod code "NEW"
newOrder.StateOrderId = stateOrderId_NEW;
The same will happen every time I have to move the order in a new status.
So, in this case, what are the reason to chose one key type vs the other one?
A:
The answer is: it depends.
In your example of changing the order state inside your code, ask yourself how likely it is that you would create constants for those states (to avoid making typos for instance). If so, both will accomplish the same.
In the case that a new order state gets submitted via a form, you would build the drop down (for example) of possible values using either the natural or surrogate key, no difference there.
There's a difference when you're doing a query on the order table and wish to print the state for each order. Having a natural key would avoid the need to make another join, which helps (albeit a little).
In terms of storage and query performance, the surrogate key is respectively smaller and faster (depending on the table size) in most cases.
But having said all that, it just takes careful consideration. Personally I feel that surrogate keys have become something like a dogma; many developers will use them in all their tables and modeling software will automatically add them upon table creation. Therefore you might get mixed reactions about your choice, but there's no hard rule forbidding you to use them; choose wisely :)
| {
"pile_set_name": "StackExchange"
} |
Q:
What's the semantically accurate position for the ampersand in C++ references
It's pretty common knowledge that the semantically accurate way to declare pointers is
int *x;
instead of
int* x;
This is because C sees *x as an int, not x as an int pointer.
This can be easily demonstrated by
int* a, b;
where a is an int pointer, while b is an int.
There are at least 5 duplicate questions on stackoverflow.com that discuss this issue for pointers. But what about references?
A:
Bjarne Stroustrup says:
A typical C programmer writes int *p; and explains it *p is what is the int emphasizing syntax, and may point to the C (and C++) declaration grammar to argue for the correctness of the style. Indeed, the * binds to the name p in the grammar.
A typical C++ programmer writes int* p; and explains it p is a pointer to an int emphasizing type. Indeed the type of p is int*. I clearly prefer that emphasis and see it as important for using the more advanced parts of C++ well.
When declaring a pointer variable or argument, you may place the asterisk (or ampersand) adjacent to either the type or to the variable name.
The most important thing is to do this consistently within a single file.
// These are fine, space preceding.
char *c;
const int &i;
// These are fine, space following.
char* c;
const int& i;
A:
While researching for this question, I already found the answer:
The & needs to be written just like the *.
The demonstration code is similar to the pointer demonstration code:
int main() {
int a = 0;
int b = 1;
int& ar = a, br = b;
br = 2;
return b;
}
This returns 1, which means that ar is an int reference, while br is just an integer.
A:
Thanks to "template typedefs", you can declare multiple references in an (arguably) nicer way:
template<typename T> using ref = T&;
int a, b;
ref<int> ar = a, br = b;
| {
"pile_set_name": "StackExchange"
} |
Q:
Tomcat & Eclipse integration
I'm developing on a Ubuntu 8.04 machine using Eclipse Ganymede. I installed Tomcat 5.5 using sudo apt-get install tomcat5.5 tomcat5.5-admin and using an Ant script I deploy my WAR file by copying it to $CATALINA_HOME/webapps.
I then created an Eclipse project and I have it output compiled source in a similar but separate directory structure under $PROJECT_ROOT/target/. I still deploy the WAR file by right clicking on the build.xml and choosing my deploy-war task.
As Tomcat is running as a deamon, automatically started up on booting, I'm not instructing it when to start or exit.
My problems with this setup are:
Using this approach I do not get any output to the Eclipse console, as Tomcat is running under the tomcat55 user and I have a different login and no access to Stdout of tomcat55.
The logging which occurs is also directed to Stdout at the moment, which I find pretty nice during development. But it's not nice when I can't see it. :-)
I don't have any servers under the Server tab and no Run configurations. This makes it impossible for me to use the Debug mode of Eclipse, which otherwise is quite convenient.
What do you think I should do to integrate them and in turn make my development environment much better?
A:
I'd say forget the pre-packaged Tomcat. Grab the apache-tomcat-x.y.z.zip from the site, unzip it somewhere in your $HOME and add a Server to your eclipse workspace, pointing to your local installation of tomcat. Of course you need the j2ee/wtp Eclipse bundle. Works fine on Windows, can't see a reason for it not working on Linux.
Edit: You may have to fiddle with server ports if you have two tomcat installs.
A:
Add Tomcat to the list of Eclipse servers and run your web-app on the server. If you need more details click here.
| {
"pile_set_name": "StackExchange"
} |
Q:
"Linear isomorphism" in definition of vector bundle
I'm reading out of Broecker & Jaenich's differential topology text, and in the definition of vector bundle I'm having trouble understanding what they're talking about. This trouble is worsened by the fact that other sources define the structure similarly, and also don't address my problem.
The definition is as follows:
"A ($n$-dimensional real topological) vector bundle is a trouble $(E, \pi X)$, where $\pi : E \to X$ is a continuous surjective map, every $E_x = \pi^{-1}(x)$ has the structure of an $n$-dimensional real vector space such that:
Axiom of local triviality. Every point of $X$ has a neighborhood $U$, for which there exists a homeomorphism
$$f : \pi^{-1} (U) \to U \times \mathbb{R}^{n}$$
such that for every $x \in U$
$$f_{x} |E_{x} \to \{ x \} \times \mathbb{R}^{n}$$
is a vector space isomorphism." [Bold added for emphasis]
My trouble here is that we don't seem to have imposed any sort of vector space structure on $E_{x}$. Though the authors don't address exactly what kind of structures we've imposed on $E$ and $X$, other sources suggest only a topological space is needed, though others go on to imagine that $X$ is a topological or smooth manifold. None of these make reference to the assumption that any of the sets in question should have any kind of vector space structure. So I have no clue how I'm supposed to parse out what it means to have an isomorphism of vector spaces without a vector space. Is it supposed to be with reference to a chart on $X$? Someone please explain this.
Thanks.
A:
Part of the structure of a vector bundle $(E,\pi,X)$ is, as your definition says, a vector space structure on the set $E_x$ for each $x\in X$. That is, to have a vector bundle, you have to specify a vector space structure on each $E_x$. So the maps $f_x$ are supposed to be vector space isomorphisms with respect to this specified vector space structure on $E_x$ (and the obvious vector space structure on $\{x\}\times \mathbb{R}^n$).
(For a topological vector bundle, as in the definition you quoted, you also need topologies on $E$ and $X$, in order to say that $\pi$ is continuous and $f$ is a homeomorphism. For smooth vector bundles, you require $E$ and $X$ to be smooth manifolds and require all the maps to also be smooth.)
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the basis for anointing of physical objects and who practices this?
It's been a tradition of my family and friends to anoint a home with oil when a family moves in. I understand the significance of praying and dedicating the space as God's, used for His purposes and will - and my interpretation of anointing has mostly been along the lines of prayer in this manor.
However is there a biblical reason or basis for the practice of anointing a physical object? Were does this originate and what Christian traditions practice it?
A:
Anointing an object certainly appears in the Bible, and is part of ancient Jewish practice:
Then the Lord said to Moses, ‘Take the following fine spices: 500 shekels of liquid myrrh, half as much (that is, 250 shekels) of fragrant cinnamon, 250 shekels of fragrant calamus, 500 shekels of cassia – all according to the sanctuary shekel – and a hin of olive oil. Make these into a sacred anointing oil, a fragrant blend, the work of a perfumer. It will be the sacred anointing oil. Then use it to anoint the tent of meeting, the ark of the covenant law, the table and all its articles, the lampstand and its accessories, the altar of incense, the altar of burnt offering and all its utensils, and the basin with its stand. You shall consecrate them so they will be most holy, and whatever touches them will be holy.
Exodus 30:22–29 [NIV]
It's also part of the Catholic liturgy for consecrating an altar Reference. The oil of chrism which is used is a fragrant oil rather like that described in Exodus.
However this use of oil is part of the consecration, the setting-apart, of the object to God's use. The objects would not be put to any other use whatsoever. Whether a house is set apart in quite the same way may be open to question, and most house-blessings (such as the one I was involved with recently) would involve sprinkling1 holy water.
1 Sprinkling is a technical term, which refers to splashing water around with a brush or some sort of shaker. It's not usually a delicate operation!
| {
"pile_set_name": "StackExchange"
} |
Q:
FiwareLab Cygnus always get error to install
According to this manual, I've try to install Cygnus on my Centos instance of FiwareLab but always I get the following error "Permission denied".
I have used the default user "centos" but I don't get any result.
Anyone can help me?
Thanks a lot!!
Here's a supplementary screen shot:
A:
The error you were facing was because the user has no permission to perform that operation on the specified directory.
The solution, in this case, is use sudo:
sudo cat > /etc/yum.repos.d/fiware.repo <<EOL (continue the lines)
I hope it had helped you.
| {
"pile_set_name": "StackExchange"
} |
Q:
C++ Issue with median function using arrays
I am having trouble getting this function to work. I am trying to write a median function that takes a user entered array and size, validates that it is correct and then sorts it and displays the median and sorted array. I have tried several different things and no matter what I try I am unable to get this program to work. Any help would be appreciated. Thank you very much.
#include <iostream>
#include <iomanip>
using namespace std;
double median(int n[], int size);
int main(int argc, char** argv) {
cout << "Calculate The Median of an Array" << endl;
cout << "---------------------------------" << endl;
int size, n;
cout << "Array Size (Maximum is Ten)? ";
cin >> size;
if (size > 10 || size < 0) {
cout << "Invalid size. Please Re-enter." << endl;
};
cout << "Array Contents? ";
cin >> n;
if ([n] != size) {
cout << "Invalid Array. Please Re-enter. " << endl;
};
median(n, size);
return 0;
};
double median(int n[], int size) {
// Allocate an array of the same size and sort it.
double* dpSorted = new double[size];
for (int i = 0; i < size; ++i) {
dpSorted[i] = n[i];
};
for (int i = size - 1; i > 0; --i) {
for (int j = 0; j < i; ++j) {
if (dpSorted[j] > dpSorted[j+1]) {
double dTemp = dpSorted[j];
dpSorted[j] = dpSorted[j+1];
dpSorted[j+1] = dTemp;
};
};
};
// Middle or average of middle values in the sorted array.
int median = 0;
if ((size % 2) == 0) {
median = (dpSorted[size/2] + dpSorted[(size/2) - 1])/2.0;
}
else {
median = dpSorted[size/2];
};
cout << "Median of the array " << dpSorted << "is " << median << endl;
};
I am getting the following errors and I cant figure out how to fix them.
34 16 C:\Users\ryanw\Desktop\C++\Labs\Lab 6\main.cpp [Error] invalid
conversion from 'int' to 'int*' [-fpermissive]
and
18 8 C:\Users\ryanw\Desktop\C++\Labs\Lab 6\main.cpp [Note] initializing
argument 1 of 'double median(int*, int)'
A:
I'm inlining the explanations as comments in the code. Here is the array version. I'm keeping it as close to OP's source as possible.
#include <iostream>
#include <iomanip>
using namespace std;
double median(int n[], int size);
int main() { // the parameters asre not being used. You can safely leave them out.
cout << "Calculate The Median of an Array" << endl;
cout << "---------------------------------" << endl;
unsigned int size; // unsigned disallows negative numbers. Lest testing required
int n[10]; // n is an array of 10 elements
cout << "Array Size (Maximum is Ten)? ";
cin >> size;
while (size > 10) { // repeat until user provides a valid size
cout << "Invalid size. Please Re-enter." << endl;
cin >> size;
};
// the above loop will be an infinite loop if the user types in a value
// that cannot be converted into an integer.
cout << "Array Contents? ";
for (unsigned int index = 0; index < size; index++)
{
cin >> n[index];
}
// don't need to test the size. This is ensured by the for loop. Mostly
// for now we are ignoring the simple problem: "what if the user inputs
// a value that is not an integer?
median(n, size);
return 0;
}// don't need ; after function.
double median(int n[], int size) {
// Don't need an array of doubles. Ignoring it.
// assuming the logic here is correct. If it isn't, that's a different
// topic and another question.
for (int i = size - 1; i > 0; --i) {
for (int j = 0; j < i; ++j) {
if (n[j] > n[j+1]) {
int dTemp = n[j];
n[j] = n[j+1];
n[j+1] = dTemp;
};
};
};
// Middle or average of middle values in the sorted array.
double result = 0; //reusing an identifier is a dangerous business. Avoid it.
if ((size % 2) == 0) {
result = (n[size/2] + n[(size/2) - 1])/2.0;
}
else {
result = n[size/2];
};
cout << "Median of the array is " << result << endl;
// it's harder to print out an array than I think it should be.
// Leaving it out for now
// Other than main, a function with a return type must ALWAYS return.
return result;
}
And with std::vector and other library wizardry:
#include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
// using namespace std; generally should avoid this
// moving median up here so forward declaration isn't needed
double median(std::vector<int> &n) { //don't need size. Vector knows how big it is
std::sort(n.begin(), n.end()); // use built-in sort function
double result = 0;
auto size = n.size();
if ((size % 2) == 0) {
result = (n[size/2] + n[(size/2) - 1])/2.0;
}
else {
result = n[size/2];
};
// since this function calculates and returns the result, it shouldn't
// also print. A function should only do one thing. It make them easier
// to debug and more re-usable
return result;
}
int main() {
// can chain couts into one
// endl is more than just a line feed and very expensive. Only use it
// when you need the message to get out immediately
std::cout << "Calculate The Median of an Array\n" <<
"---------------------------------\n" <<
"Array Size (Maximum is Ten)? " << std::endl;
unsigned int size;
std::cin >> size;
while (size > 10) {
// here we use endle because we want he user to see the message right away
std::cout << "Invalid size. Please Re-enter:" << std::endl;
std::cin >> size;
};
std::vector<int> n(size);
std::cout << "Array Contents? " << std::endl;
for (int & val: n) // for all elements in n
{
std::cin >> val;
}
std::cout << "Median of the array is " << median(n) << std::endl;
return 0;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
regex regarding symbols in urls
I want to replace consecutive symbols just one such as;
this is a dog???
to
this is a dog?
I'm using
str = re.sub("([^\s\w])(\s*\1)+", "\\1",str)
however I notice that this might replace symbols in urls that might happen in my text.
like http://example.com/this--is-a-page.html
Can someone give me some advice how to alter my regex?
A:
So you want to unleash the power of regular expressions on an irregular language like HTML. First of all, search SO for "parse HTML with regex" to find out why that might not be such a good idea.
Then consider the following: You want to replace duplicate symbols in (probably user-entered) text. You don't want to replace them inside a URL. How can you tell what a URL is? They don't always start with http – let's say ars.userfriendly.org might be a URL that is followed by a longer path that contains duplicate symbols.
Furthermore, you'll find lots of duplicate symbols that you definitely don't want to replace (think of nested parentheses (like this)), some of them maybe inside a <script> on the page you're working on (||, && etc. come to mind.
So you might come up with something like
(?<!\b(?:ftp|http|mailto)\S+)([^\\|&/=()"'\w\s])(?:\s*\1)+
which happens to work on the source code of this very page but will surely fail in other cases (for example if URLs don't start with ftp, http or mailto). Plus, it won't work in Python since it uses variable repetition inside lookbehind.
All in all, you probably won't get around parsing your HTML with a real parser, locating the body text, applying a regex to it and writing it back.
EDIT:
OK, you're already working on the parsed text, but it still might contain URLs.
Then try the following:
result = re.sub(
r"""(?ix) # case-insensitive, verbose regex
# Either match a URL
# (protocol optional (if so, URL needs to start with www or ftp))
(?P<URL>\b(?:(?:https?|ftp|file)://|www\.|ftp\.)[-A-Z0-9+&@#/%=~_|$?!:,.]*[A-Z0-9+&@#/%=~_|$])
# or
|
# match repeated non-word characters
(?P<rpt>[^\s\w])(?:\s{0,100}(?P=rpt))+""",
# and replace with both captured groups (one will always be empty)
r"\g<URL>\g<rpt>", subject)
Re-EDIT: Hm, Python chokes on the (?:\s*(?P=rpt))+ part, saying the + has nothing to repeat. Looks like a bug in Python (reproducible with (.)(\s*\1)+ whereas (.)(\s?\1)+ works)...
Re-Re-EDIT: If I replace the * with {0,100}, then the regex compiles. But now Python complains about an unmatched group. Obviously you can't reference a group in a replacement if it hasn't participated in the match. I give up... :(
| {
"pile_set_name": "StackExchange"
} |
Q:
Output of awk is not shown when used after a grep command
I want to get CPU % of a process using pid from top command in Mac OS. When I use top | awk '{print $3}' I get the CPU % for all the processes. However, using top | grep 11568 | awk '{print $3}' returns nothing. The output of top | grep 11568 is
11568 java 0.0 09:48.45 663 2 1533+ 521M+ 0B 741M+ 11560 11560 sleeping *0[64+] 0.00000 0.00000 501 1335625+ 803+ 12376+ 4146+ 37032037+ 28783+ 3748122+ 514+ 112576 0.0 0 0 amar N/A N/A N/A N/A N/A N/A
A:
Haven't tested this command since I don't have mac os, could you please try following.
your_command | awk -F' +' '/11568/{print $3}'
| {
"pile_set_name": "StackExchange"
} |
Q:
irrationality of $\sqrt{2}^{\sqrt{2}}$.
The fact that there exists irrational number $a,b$ such that $a^b$ is rational is proved by the law of excluded middle, but I read somewhere that irrationality of $\sqrt{2}^{\sqrt{2}}$ is proved constructively. Do you know the proof?
A:
Since this is a well-established result, this is a community wiki post.
Relevant question: Deciding whether $2^{\sqrt2}$ is irrational/transcendental
Kuzmin proved the following claim in 1930:
Theorem: If $\alpha\neq 0,1$ is algebraic, $\beta$ is positive and rational, not a perfect square, then $\alpha^{\sqrt{\beta}}$ is transcendental.
Unfortunately the paper is in Russian and I failed to find an English translation. A corollary of this is that $2^{\sqrt{2}}$ is transcendental, and so is its square root $\sqrt{2}^{\sqrt{2}}$.
The outlines of both Gelfond and Kuzmin's constructive proof can be found here.
As David Mitra pointed out the comments, Niven's book had a section dedicated to this. I love Niven's book so much. The technique is similar to the adapted proof I posted here, proof by contradiction.
Rough idea about the construction: First assuming $\alpha^{\sqrt{\beta}}$ is algebraic. Then using sufficient large degree Lagrange interpolation polynomial to approximate $e^{(\ln \alpha)x}$ at points $\{a+ b\sqrt{2}\}$ for $a,b\in \mathbb{Z}$. Let the number of points go to infinity the error will go to zero, this shows a transcendental function $\alpha^x$ can be interpolate using countably many algebraic points. Contradiction.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to Enumerate variable XML Document in .NET using Linq to XML
I'm submitting a command to a ssh session and getting an XML response back which is variable depending on the type of query I'm running. I get the following type of XML returned...
<CLIOutput>
<Results>
<ReturnCode>0</ReturnCode>
<EventCode>23000</EventCode>
<EventSummary>CLI command completed successfully.</EventSummary>
</Results>
<Data>
<Row>
<Client>kcllaptop</Client>
<Domain>/Top/Top</Domain>
</Row>
<Row>
<Client>testclient</Client>
<Domain>/Top/Top</Domain>
</Row>
</Data>
</CLIOutput>
I then parse into an XDocument, and what I want to do is Enumerate through the different <Row> attributes in the <Data> section, given they change. They're always in DATA section, but the attribute names and numbers of them change. I can get the specific one in the example above, but I'm after a more generic method.
I can get to the specifcs by
_xDoc.Elements().<Data>.<Rows>(0).<Client>.ToValue
but the <Client> name changes.
What's the best way to enumerate through the rows returned in the element.
Complete LInq newbie sorry.
Thanks and Cheers, Al
A:
The answer by SLaks works. However, in VB.NET you don't need the .Elements() method.
This will do the same thing:
For Each row in _xDoc.<Data>.<Row>
Console.WriteLine(row.<Client>.Value)
Next
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the Java equivalent of JavaScript's resource folder?
My Wicket web application contains a Flash (*.swf) FLV player. The following code:
final String script = "var swfVersionStr = '10.0.0';"
+ "var xiSwfUrlStr = 'playerProductInstall.swf';"
+ "var flashvars = {file:'/proj/resources/video.flv'};"
+ "var params = {};"
+ "params.wmode = 'transparent';"
+ "params.quality = 'high';"
+ "params.allowscriptaccess = 'sameDomain';"
+ "params.allowfullscreen = 'true';"
+ "var attributes = {};"
+ "attributes.id = 'test';"
+ "attributes.name = 'test';"
+ "attributes.align = 'left';"
+ "swfobject.embedSWF('/proj/resources/mediaplayer.swf', 'movieDiv', '640', '480', swfVersionStr, xiSwfUrlStr, flashvars, params, attributes);"
+ "swfobject.createCSS('#flashContent', 'display:block;text-align:left;');";
add(new AbstractBehavior() {
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
response.renderOnLoadJavascript(script);
}
});
plays the FLV. The swfobject.js file is placed in the resource folder of my server. As I am testing it on localhost, the absolute path of resource folder is: /home/tapas/Desktop/proj/work/Jetty_0_0_0_0_80_proj.war__proj__qk44r3/webapp. Now, how can I save a file in the resource folder of my server by using Java? JavaScript identifies the resource folder path as /proj/resources/; what is the equivalent expression of this path in Java? I have tried:
try{
File file=new File("/proj/resources/joymaa.txt");
if(file.exists()){
System.out.println("File exists");
}else{
System.out.println("File does not exists");
}
}catch(Exception exception){
System.out.println(exception.getMessage());
}
This is not displaying any error message, but it shows "File does not exists."
A:
try to find out what is your actual working directory of java... this might help: example
I dont think that java could understand your relative path because it runs from different directory than javascript. Just my opinion, but give it a try.
| {
"pile_set_name": "StackExchange"
} |
Q:
Create RSS feed in asp.net core 1.0
I am working in Asp.net Core 1.0 MVC 6
I am trying to write a component to provide RSS feeds from my websites.
I found this post that suggests that System.ServiceModel.Syndication has yet to be ported to ASP.NET CORE.
I am unable to target the full .NET framework.
The suggestion is to write as an xml parser. I am however struggling to get my head around everything that might be required.
I have built the functionality to get my data into XML but now need to better understand how to allow this to be called from an IActionResult (or indeed how to generate a link that may be placed on my page).
I can provide samples of my code but am not sure it'll be helpful.
Is anyone able to point me in the right direction of examples achieving this?
I also found an answer on this post which points towards some ideas but I think is pre MVC6/Asp.net Core: RSS Feeds in ASP.NET MVC
A:
// action to return the feed
[Route("site/GetRssFeed/{type}")]
public IActionResult GetRssFeed(ArticleStatusTypes type)
{
var feed = _rss.BuildXmlFeed(type);
return Content(feed, "text/xml");
}
public string BuildXmlFeed(ArticleStatusTypes type)
{
var key = $"RssFeed{Convert.ToInt32(type)}{_appInfo.ApplicationId}";
var articles =
_cache.GetCachedData(key) ??
_cache.SetCache(key, _service.GetItems(Convert.ToInt32(type), _appInfo.CacheCount));
StringWriter parent = new StringWriter();
using (XmlTextWriter writer = new XmlTextWriter(parent))
{
writer.WriteProcessingInstruction("xml-stylesheet", "title=\"XSL_formatting\" type=\"text/xsl\" href=\"/skins/default/controls/rss.xsl\"");
writer.WriteStartElement("rss");
writer.WriteAttributeString("version", "2.0");
writer.WriteAttributeString("xmlns:atom", "http://www.w3.org/2005/Atom");
// write out
writer.WriteStartElement("channel");
// write out -level elements
writer.WriteElementString("title", $"{_appInfo.ApplicationName} {type}" );
writer.WriteElementString("link", _appInfo.WebsiteUrl);
//writer.WriteElementString("description", Description);
writer.WriteElementString("ttl", "60");
writer.WriteStartElement("atom:link");
//writer.WriteAttributeString("href", Link + Request.RawUrl.ToString());
writer.WriteAttributeString("rel", "self");
writer.WriteAttributeString("type", "application/rss+xml");
writer.WriteEndElement();
if (articles != null)
{
foreach (var article in articles)
{
writer.WriteStartElement("item");
writer.WriteElementString("title", article.Title);
writer.WriteElementString("link", _appInfo.WebsiteUrl); // todo build article path
writer.WriteElementString("description", article.Summary);
writer.WriteEndElement();
}
}
// write out
writer.WriteEndElement();
// write out
writer.WriteEndElement();
}
return parent.ToString();
}
A:
They've released a preview NuGet package for Microsoft.SyndicationFeed. On the dotnet/wcf repo, they've provided an example to get you up and running.
EDIT: I've posted a Repo and a NuGet package that serves as a Middleware around this.
| {
"pile_set_name": "StackExchange"
} |
Q:
Raw Socket Help: Why UDP packets created by raw sockets are not being received by kernel UDP?
I am studying raw sockets. I used the IP_HDRINCL option to build my own IP headers. After the IP header, I am building a UDP header. Then I am sending the packet to my system's loopback address. I have another program running which will catch the UDP packets as they come. To check whether the packets are being correctly formed and received, I have another process running which is reading raw IP datagrams. My problem is that although the second process(reading raw datagrams) is working well(all the IP and UDP fields seem to be okay), but the first process(receiving UDP) is not receiving any of the packets that I created. The protocol field in the IP header is okay and the port also matches...
I am using Linux 2.6.35-22.
I want to know whether this is normal in new kernels? Please check the code below for any bugs. The UDP process which should receive the packets is listening on a socket bound to port 50000 on the same machine...
unsigned short in_cksum(unsigned short *addr, int len)
{
int nleft = len;
int sum = 0;
unsigned short *w = addr;
unsigned short answer = 0;
while (nleft > 1) {
sum += *w++;
nleft -= 2;
}
if (nleft == 1) {
*(unsigned char *) (&answer) = *(unsigned char *) w;
sum += answer;
}
sum = (sum >> 16) + (sum & 0xFFFF);
sum += (sum >> 16);
answer = ~sum;
return (answer);
}
main()
{
int fd=socket(AF_INET,SOCK_RAW,IPPROTO_UDP);
int val=1;
int ret=setsockopt(fd,IPPROTO_IP,IP_HDRINCL,&val,sizeof(val));
char buf[8192];
/* create a IP header */
struct iphdr* ip=(struct iphdr*)buf;//(struct iphdr*) malloc(sizeof(struct iphdr));
ip->version=4;
ip->ihl=5;
ip->tos=0;
ip->id=0;
ip->frag_off=0;
ip->ttl=255;
ip->protocol=IPPROTO_UDP;
ip->check=0;
ip->saddr=inet_addr("1.2.3.4");
ip->daddr=inet_addr("127.0.0.1");
struct udphdr* udp=(struct udphdr*)(buf+sizeof(struct iphdr));//(struct udphdr*) malloc(sizeof(struct udphdr));
udp->source=htons(40000);
udp->dest=htons(50000);
udp->check=0;
char* data=(char*)buf+sizeof(struct iphdr)+sizeof(struct udphdr);strcpy(data,"Harry Potter and the Philosopher's Stone");
udp->len=htons(sizeof(struct udphdr)+strlen(data));
udp->check=in_cksum((unsigned short*) udp,8+strlen(data));
ip->tot_len=htons(sizeof(struct iphdr)+sizeof(struct udphdr)+strlen(data));
struct sockaddr_in d;
bzero(&d,sizeof(d));
d.sin_family=AF_INET;
d.sin_port=htons(50000);
inet_pton(AF_INET,"localhost",&d.sin_addr.s_addr);
while(1)
sendto(fd,buf,sizeof(struct iphdr)+sizeof(struct udphdr)+strlen(data),0,(struct sockaddr*) &d,sizeof(d));
}
A:
There seems to be a problem with the calculation of the UDP check-sum.
udp->check=in_cksum((unsigned short*) udp,8+strlen(data));
UDP check-sum must include something called the "Pseudo-Header" before the UDP header. The code calculates checksum over only the UDP header and the payload. The UDP receiving process might not be receiving the packets because of the wrong check-sums.
Enable check-sum validation in Wireshark and check whether the check-sum fields of the UDP packets are correct or not.
See the following:
UDP: Checksum Computation
IETF: RFC 768
| {
"pile_set_name": "StackExchange"
} |
Q:
Inequality between 2p-norm and p-norm for random variables
Recently I was studying something about random matrix theory, and class of sub-guassian / sub-exponential random variables is of interest. In the literature it gave an inequality as following:
$\sup_{p\geq 1} \frac{\|X^2\|_p}{p} \leq 2\sup_{p\geq 1} (\frac{\|X\|_p}{\sqrt{p}})^2$
which gives a sufficient condition such that:
$\|X\|_{2p} \leq \sqrt{2}\|X\|_p$
The proof of this inequality is not provided in the literature. Suppose the random variable $X\in\mathbb{L}^\infty(\mathbb{R})$ therefore the previous defined sub-gaussian norm and sub-exponential norm both exist, then how do we proof the sufficient condition?
Any comment is greatly appreciated :)
A:
This is a direct consequence of the general fact that $\|X^2\|_p=E[|X|^{2p}]^{1/p}=\left(\|X\|_{2p}\right)^2$ for every $p\gt0$ and every random variable $X$ in $L^{2p}$. Hence,
$$
\sup_{p\geqslant 1} \frac{\|X^2\|_p}{p}=2\,\sup_{p\geqslant 2} \left(\frac{\|X\|_p}{\sqrt{p}}\right)^2\leqslant 2\,\sup_{p\geqslant 1} \left(\frac{\|X\|_p}{\sqrt{p}}\right)^2.
$$
The rôle of the (not always true) inequality $\|X\|_{2p} \leqslant \sqrt{2}\,\|X\|_p$ is not clear.
| {
"pile_set_name": "StackExchange"
} |
Q:
Pascal to C converter
I'm writing program which translate Pascal to C and need some help. I started with scanner generator Flex. I defined some rules and created scanner which is working more or less ok. It breaks Pascal syntax into tokens, for now it's only printing what it found. But I have no idea what should I do next. Are there any articles or books covering this subject? What is the next step?
A:
You might want to take a look at "Translating Between Programming Languages Using A Canonical Representation And Attribute Grammar Inversion" and references therein.
A:
Why do you want to do such a Pascal to C converter?
If you just want to run some Pascal programs, it is simpler to use (or improve) existing compilers like gpc, or Pascal to C translators, like e.g. p2c
If you want to convert hand-written Pascal code to humanly-readable (and improvable) C code, the task is much more difficult; in particular, you probably want to convert the indentation, the comments, keep the same names as much as possible -but avoiding clashes with system names- etc!
You always want to parse some abstract syntax tree, but the precise nature of these trees is different. Perhaps flex + bison or even ANTLR may or not be adequate (you can always write a hand-written parser). Also, error recovery may or not be important to you (aborting on the first syntax error is very easy; trying to make sense of an ill-written syntactically-incorrect Pascal source is quite hard).
If you want to build a toy Pascal compiler, consider using LLVM (or perhaps even GCC middle-end and back-ends)
| {
"pile_set_name": "StackExchange"
} |
Q:
how can I change month only in java date object?
I have java date object.
How can I change its month without changing the year.
e.g.
12/1/14
I want to change it to
12/3/14 and to 12/10/14
I basically want to change the month by +/- x month without changing the year.
Can it be done?
A:
Calendar cal = Calendar.getInstance();
cal.setTime(date); // your date (java.util.Date)
cal.add(Calendar.MONTH, x); // You can -/+ x months here to go back in history or move forward.
return cal.getTime(); // New date
ref : Java Calendar
A:
You can use the set method of the Calendar class to change the specific month you want
sample:
Calendar c = Calendar.getInstance();
System.out.println(c.getTime());
c.set(Calendar.MONTH, Calendar.JANUARY); //will change the month to JANUARY
System.out.println(c.getTime());
result:
Sun Aug 17 03:17:35 EDT 2014
Fri Jan 17 03:17:35 EST 2014
A:
java.time
LocalDate localDate = LocalDate.of ( 2017, Month.JANUARY, 23 );
LocalDate localDateFeb = localDate.withMonth ( 2 );
…or…
LocalDate localDateFeb = localDate.withMonth ( Month.FEBRUARY.getValue ( ) );
localDate.toString(): 2017-01-23
localDateFeb.toString(): 2017-02-23
The other Answers use the troublesome old date-time classes, now supplanted by the java.time classes.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Joda-Time
Update: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.
The Joda-Time library has a LocalDate class to represent a date-only without a time-of-day nor time zone.
You can arbitrarily set the month value. But beware of the issue that not all months have the same number of days, so having day-of-month values of 29, 30, and 31 are a problem.
LocalDate localDate = new LocalDate( 2014 , 12 , 31 ); // December.
LocalDate localDate_Feb = localDate.withMonthOfYear( 2 ); // February.
Dump to console.
System.out.println( "localDate: " + localDate );
System.out.println( "localDate_Feb: " + localDate_Feb );
When run.
localDate: 2014-12-31
localDate_Feb: 2014-02-28
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get values from query string and pass it to new page using .htaccess file
currently I m using following code in my site in .htaccess file :
RewriteRule ^([^/\.]+).php?$ comman.php?cat=$1 [L]
This redirects user to comman.php page say, user requests
http://www.mysite.com/myfolder/page1.php
will redirects to
http://www.mysite.com/myfolder/comman.php?cat=page1
This works fine. My question is how can I achieve following
http://www.mysite.com/myfolder/page1.php?var1=123
to redirect
http://www.mysite.com/myfolder/comman.php?cat=page1¶m=123
i.e. whatever value passed to url using get method to add in my new url.
Thanks in Advance.....
A:
You should add the QSA flag:
RewriteRule ^([^/\.]+).php?$ comman.php?cat=$1 [L,QSA]
QSA stands for Query String Append. Anything after the ? in the original URL will be appended to the rewritten URL.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is this SML function returning a syntax error?
fun first_answer(my_f:('a -> 'b option)) : 'a list -> 'b =
let
fun help(_a:'a list) : 'a =
(((List.map valOf)o(List.filter isSome)o(List.map my_f)) _a)
in
help
end;
Error: syntax error: replacing WILD with SEMICOLON
Something with that _a is messing it up..... The error is linked to the last usage of _a
I am not getting very far, and I've rearranged the logic many ways already. As you can see the first_answer returns takes a function and returns a function. This is what I am doing here and I am following the types as far as I know. There is probably something simple that I am not seeing.
A:
It's simple indeed: an identifier cannot start with an underscore. So _a is parsed as if you had written _ a, in accordance with the usual maximal munch rule for lexical syntax.
Edit: Extra tip: Your function does not have the type 'a list -> 'b, because help returns a list of 'bs, not a single value of type 'b. Moreover, as written, it can be implemented more easily as
fun first_answer f xs = List.mapPartial f xs
or, in fact,
val first_answer = List.mapPartial
| {
"pile_set_name": "StackExchange"
} |
Q:
FFMPEG error with avformat_open_input returning -135
I have a DLL one of my applications uses to receive video from RTSP cameras. Under the hood, the DLL uses FFMPEG libs from this release zip :
ffmpeg-20141022-git-6dc99fd-win64-shared.7z
We have a wide variety of cameras in house and most of them work just fine. However, on one particular Pelco Model Number: IXE20DN-OCP, I am unable to connect. I tested the camera and rtsp connection string on VLC and it connects to the camera just fine.
I found the connection string here : http://www.ispyconnect.com/man.aspx?n=Pelco
rtsp://IPADDRESS:554/1/stream1
Oddly, even if I leave the port off of VLC, it connects, so I'm guessing its the default RTSP port or that VLC tries a variety of things based on your input.
In any case, when I attempt to connect, I get an error from av_format_open_input. It returns a code of -135. When I looked in the error code list I didn't see that listed. For good measure, I printed out all the errors in error.h just to see what their values were.
DumpErrorCodes - Error Code : AVERROR_BSF_NOT_FOUND = -1179861752
DumpErrorCodes - Error Code : AVERROR_BUG = -558323010
DumpErrorCodes - Error Code : AVERROR_BUFFER_TOO_SMALL = -1397118274
DumpErrorCodes - Error Code : AVERROR_DECODER_NOT_FOUND = -1128613112
DumpErrorCodes - Error Code : AVERROR_DEMUXER_NOT_FOUND = -1296385272
DumpErrorCodes - Error Code : AVERROR_ENCODER_NOT_FOUND = -1129203192
DumpErrorCodes - Error Code : AVERROR_EOF = -541478725
DumpErrorCodes - Error Code : AVERROR_EXIT = -1414092869
DumpErrorCodes - Error Code : AVERROR_EXTERNAL = -542398533
DumpErrorCodes - Error Code : AVERROR_FILTER_NOT_FOUND = -1279870712
DumpErrorCodes - Error Code : AVERROR_INVALIDDATA = -1094995529
DumpErrorCodes - Error Code : AVERROR_MUXER_NOT_FOUND = -1481985528
DumpErrorCodes - Error Code : AVERROR_OPTION_NOT_FOUND = -1414549496
DumpErrorCodes - Error Code : AVERROR_PATCHWELCOME = -1163346256
DumpErrorCodes - Error Code : AVERROR_PROTOCOL_NOT_FOUND = -1330794744
DumpErrorCodes - Error Code : AVERROR_STREAM_NOT_FOUND = -1381258232
DumpErrorCodes - Error Code : AVERROR_BUG2 = -541545794
DumpErrorCodes - Error Code : AVERROR_UNKNOWN = -1313558101
DumpErrorCodes - Error Code : AVERROR_EXPERIMENTAL = -733130664
DumpErrorCodes - Error Code : AVERROR_INPUT_CHANGED = -1668179713
DumpErrorCodes - Error Code : AVERROR_OUTPUT_CHANGED = -1668179714
DumpErrorCodes - Error Code : AVERROR_HTTP_BAD_REQUEST = -808465656
DumpErrorCodes - Error Code : AVERROR_HTTP_UNAUTHORIZED = -825242872
DumpErrorCodes - Error Code : AVERROR_HTTP_FORBIDDEN = -858797304
DumpErrorCodes - Error Code : AVERROR_HTTP_NOT_FOUND = -875574520
DumpErrorCodes - Error Code : AVERROR_HTTP_OTHER_4XX = -1482175736
DumpErrorCodes - Error Code : AVERROR_HTTP_SERVER_ERROR = -1482175992
Nothing even close to -135. I did find this error, sort of on stack overflow, here runtime error when linking ffmpeg libraries in qt creator where the author claims it is a DLL loading problem error. I'm not sure what led him to think that, but I followed the advice and used the dependency walker (http://www.dependencywalker.com/) to checkout what dependencies it thought my DLL needed. It listed a few, but they were already provided in my install package.
To make sure it was picking them up, I manually removed them from the install and observed a radical change in program behavior(that being my DLL didn't load and start to run at all).
So, I've got a bit of init code :
void FfmpegInitialize()
{
av_lockmgr_register(&LockManagerCb);
av_register_all();
LOG_DEBUG0("av_register_all returned\n");
}
Then I've got my main open connection routine ...
int RTSPConnect(const char *URL, int width, int height, frameReceived callbackFunction)
{
int errCode =0;
if ((errCode = avformat_network_init()) != 0)
{
LOG_ERROR1("avformat_network_init returned error code %d\n", errCode);
}
LOG_DEBUG0("avformat_network_init returned\n");
//Allocate space and setup the the object to be used for storing all info needed for this connection
fContextReadFrame = avformat_alloc_context(); // free'd in the Close method
if (fContextReadFrame == 0)
{
LOG_ERROR1("Unable to set rtsp_transport options. Error code = %d\n", errCode);
return FFMPEG_OPTION_SET_FAILURE;
}
LOG_DEBUG1("avformat_alloc_context returned %p\n", fContextReadFrame);
AVDictionary *opts = 0;
if ((errCode = av_dict_set(&opts, "rtsp_transport", "tcp", 0)) < 0)
{
LOG_ERROR1("Unable to set rtsp_transport options. Error code = %d\n", errCode);
return FFMPEG_OPTION_SET_FAILURE;
}
LOG_DEBUG1("av_dict_set returned %d\n", errCode);
//open rtsp
DumpErrorCodes();
if ((errCode = avformat_open_input(&fContextReadFrame, URL, NULL, &opts)) < 0)
{
LOG_ERROR2("Unable to open avFormat RF inputs. URL = %s, and Error code = %d\n", URL, errCode);
LOG_ERROR2("Error Code %d = %s\n", errCode, errMsg(errCode));
// NOTE context is free'd on failure.
return FFMPEG_FORMAT_OPEN_FAILURE;
}
...
To be sure I didn't misunderstand the error code I printed the error message from ffmpeg but the error isn't found and my canned error message is returned instead.
My next step was going to be hooking up wireshark on my connection attempt and on the VLC connection attempt and trying to figure out what differences(if any) are causing the problem and what I can do to ffmpeg to make it work. As I said, I've got a dozen other cameras in house that use RTSP and they work with my DLL. Some utilize usernames/passwords/etc as well(so I know that isn't the problem).
Also, my run logs :
FfmpegInitialize - av_register_all returned
Open - Open called. Pointers valid, passing control.
Rtsp::RtspInterface::Open - Rtsp::RtspInterface::Open called
Rtsp::RtspInterface::Open - VideoSourceString(35) = rtsp://192.168.14.60:554/1/stream1
Rtsp::RtspInterface::Open - Base URL = (192.168.14.60:554/1/stream1)
Rtsp::RtspInterface::Open - Attempting to open (rtsp://192.168.14.60:554/1/stream1) for WxH(320x240) video
RTSPSetFormatH264 - RTSPSetFormatH264
RTSPConnect - Called
LockManagerCb - LockManagerCb invoked for op 1
LockManagerCb - LockManagerCb invoked for op 2
RTSPConnect - avformat_network_init returned
RTSPConnect - avformat_alloc_context returned 019E6000
RTSPConnect - av_dict_set returned 0
DumpErrorCodes - Error Code : AVERROR_BSF_NOT_FOUND = -1179861752
...
DumpErrorCodes - Error Code : AVERROR_HTTP_SERVER_ERROR = -1482175992
RTSPConnect - Unable to open avFormat RF inputs. URL = rtsp://192.168.14.60:554/1/stream1, and Error code = -135
RTSPConnect - Error Code -135 = No Error Message Available
I'm going to move forward with wireshark but would like to know the origin of the -135 error code from ffmpeg. When I look at the code if 'ret' is getting set to -135, it must be happening as a result of the return code from a helper method and not directly in the avformat_open_input method.
https://www.ffmpeg.org/doxygen/2.5/libavformat_2utils_8c_source.html#l00398
After upgrading to the latest daily ffmpeg build, I get data on wireshark. Real Time Streaming Protocol :
Request: SETUP rtsp://192.168.14.60/stream1/track1 RTSP/1.0\r\n
Method: SETUP
URL: rtsp://192.168.14.60/stream1/track1
Transport: RTP/AVP/TCP;unicast;interleaved=0-1
CSeq: 3\r\n
User-Agent: Lavf56.31.100\r\n
\r\n
The response to that is the first 'error' that I can detect in the initiation.
Response: RTSP/1.0 461 Unsupported Transport\r\n
Status: 461
CSeq: 3\r\n
Date: Sun, Jan 04 1970 16:03:05 GMT\r\n
\r\n
I'm going to guess that... it means the transport we selected was unsupported. I quick check of the code reveals I picked 'tcp'. Looking through the reply to the DESCRIBE command, it appears :
Media Protocol: RTP/AVP
Further, when SETUP is issued by ffmpeg, it specifies :
Transport: RTP/AVP/TCP;unicast;interleaved=0-1
I'm going to try, on failure here to pick another transport type and see how that works. Still don't know where the -135 comes from.
A:
The solution turned out to be that this particular camera didn't support RTSP over TCP transport. It wanted UDP.
I updated to code to try TCP and if that failed, to use an alternate set of options for UDP and another call to try an open things up.
if ((errCode = av_dict_set(&opts, "rtsp_transport", "udp", 0)) < 0)
Works like a charm. Still concerned about the origin of the -135 and -22 error codes which don't appear in the error.h file. Maybe an ffmpeg bug where a stray error code is allowed through.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a way to state changes that will be applied to method parameters within Javadoc?
Imagine a method that applies changes to the parameterized objects. For example a map oder list passed.
If the developer decides not to create and return a copy of the parameter I guess it would be best to have a notice in the Javadoc of this method and the parameter which indicates these changes.
I could think of an alternate @param tag like @varparam or @refparam (Regarding pass-by-reference keywords of other programming languages).
The question is: Is there a common way to do those hints in Javadoc? How common is it to apply changes to parameters? I guess this could be a problem that appears often.
A:
There is no special tag that denotes this; the accepted practice is to clearly state that the method modifies the parameter object in the description section.
Although some don't like this style of code, there are some common methods in java core that do this. java.util.Arrays.sort (and a similar method in Collections) come to mind.
| {
"pile_set_name": "StackExchange"
} |
Q:
Affected rows for stored procedure with node mssql object
I can't seem to get this working. I have an update procedure in Azure SQL.
CREATE PROCEDURE foobar
@a int
AS
update foo set bar=@a;
RETURN 0
I was returning the @@rowcount and trying to work with that but it means two resultsets and sloppy code on the client side. The client being a node.js Azure Custom API.
exports.post = function(request, response) {
var mssql = request.service.mssql;
var sqlParams = [request.body.a];
var sql = "foobar ?";
mssql.query(sql, sqlParams, {
success: function(results) {
response.send(statusCodes.OK, results); //return affected rows
}
})
};
I've tried using results.affectedRows. I've tried using additional parameters in the function to get a return value. I've queried the database directly and receive '1 Records Affected' as a response. Even when I returned the @@rowcount I had problems specifying it in the javascript. As in I was returning for results:
[{"affected":1}]
and attempting to access it with results[0].affected/results[0]["affected"] and various other permutations. I tried JSON.parse(results) and tried to access its properties then but still no go. It takes the Azure portal so long to update each time I'm just blindly trying different things at the minute.
Stephen
A:
Of course after all that I found the correct documentation that suggests using queryRaw instead of query and wouldn't you know it, that returns a RowCount.
Stephen
| {
"pile_set_name": "StackExchange"
} |
Q:
no default constructor exists
I'm having some trouble with a class that was working fine and now doesn't seem to want to work at all.
The error is "No appropriate default constructor available"
I am using the class in two places I'm making a list of them and initializing then adding them to the list.
Vertice3f.h
#pragma once
#include "Vector3f.h"
// Vertice3f hold 3 floats for an xyz position and 3 Vector3f's
// (which each contain 3 floats) for uv, normal and color
class Vertice3f{
private:
float x,y,z;
Vector3f uv, normal, color;
public:
// If you don't want to use a UV, Normal or Color
// just pass in a Verctor3f with 0,0,0 values
Vertice3f(float _x, float _y, float _z, Vector3f _uv,
Vector3f _normal, Vector3f _color);
~Vertice3f();
};
Vertice3f.cpp
#include "Vertice3f.h"
Vertice3f::Vertice3f(float _x, float _y, float _z,
Vector3f _uv, Vector3f _normal, Vector3f _color){
x = _x;
y = _y;
z = _z;
uv = _uv;
normal = _normal;
color = _color;
}
It is being using in my OBJModelLoader class as follows:
list<Vertice3f> vert3fList;
Vertice3f tvert = Vertice3f(
x = (float)atof(
vertList[i].substr(
vertList[i].find("v") + 1,
vertList[i].find(" ", vertList[i].find("v") + 2, 10)
).c_str()
),
y = (float)atof(
vertList[i].substr(
vertList[i].find(" ", vertList[i].find("v") + 4, 10) + 1,
vertList[i].find(" ", vertList[i].find("v") + 13, 10)
).c_str()
),
z = (float)atof(
vertList[i].substr(
vertList[i].find(" ", vertList[i].find("v") + 13, 10) + 1,
vertList[i].find(" ", vertList[i].find("v") + 23, 10)
).c_str()
),
::Vector3f(0.0f,0.0f,0.0f),::Vector3f(0.0f,0.0f,0.0f),::Vector3f(0.0f,0.0f,0.0f)
);
vert3fList.push_back(
tvert
);
I have tried defining a default constructor myself so in the .h I put
Vertice3f();
and in the cpp
Vertice3f::Vertice3f(){
x = 0.0f;
y = 0.0f;
z = 0.0f;
uv = Vector3f(0.0f,0.0f,0.0f);
normal = Vector3f(0.0f,0.0f,0.0f);
color = Vector3f(0.0f,0.0f,0.0f);
}
So, I'm not sure why it can't find a default constructor or how to appease the compiler. I'm sure it's user error because the compiler probably knows what it's doing.
Any help is greatly appreciated, I will answer any other questions you have, just ask.
A:
I'd guess that the missing default constructor is the default constructor of Vector3f class, not of Vertice3f class. Your constructor of Vertice3f attempts to default-construct its Vector3f members, which leads to the error.
This is why your attempts to provide default constructor for Vertice3f don't change anything. The problem lies, again, with Vector3f.
To fix it either provide all necessary default constructors (assuming it agrees with your design), or rewrite the constructor of Vertice3f by using initializer list instead of in-body assignment
Vertice3f::Vertice3f(float _x, float _y, float _z,
Vector3f _uv, Vector3f _normal, Vector3f _color) :
x(_x), y(_y), z(_z), uv(_uv), normal(_normal), color(_color)
{}
This version no longer attempts to default-construct anything. And using initializer list instead of in-body assignment is a good idea in any case.
| {
"pile_set_name": "StackExchange"
} |
Q:
printing a report in a navigation subform
I have built a database using MS Access 2010, everything is done except for one button that is not working.
I have a main navigation form, that has different tabs, one tab opens another navigation form (secondary nav. form - SNF) inside the main navigation form (MNF). in the SNF there are tabs which open reports that get their data from queries.
the reports, when opened separately, have a print button which works fine when the report are opened directly and not using the forms.
when the reports are opened through the SNF and the print button pressed the printed page has the SNF and the MNF headers and footers which isn't needed and the supposedly 1 page report would be divided to 4 pages. each containing a quarter of the view.
what I am trying to do is have the printing function using the button print only the report inside the SNF without anything outside that reports borders just as it does when the report is opened directly without using the forms.
NOTE:
* The printing button uses the defaut access print function which is implemented using the button wizard.
** Attached is a screenshot of what I get in both cases.
A:
I was having the same issues, where the entire form was being printed instead of the reports that were navigation subforms. I worked around it this way:
VBA:
DoCmd.OpenReport "MY REPORT", acViewPreview
DoCmd.RunCommand acCmdPrint
DoCmd.Close acReport, "MY REPORT"
It's clumsy, but it allows the user to use the print dialogue instead of just using
DoCmd.OpenReport, "MY REPORT", acPrint
and not being given the option choosing a printer, double sided etc.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a new Midi API for Windows Vista/7/8?
I know the midiXxx API, but I saw it is currently listed under 'legacy' in msdn.
http://msdn.microsoft.com/en-us/library/windows/desktop/dd743619(v=vs.85).aspx
Is there some other API i should use to target the newer Windows versions?
Will the old API still work on Windows 7 and 8?
Thanx,
Marc
A:
For dektop applications (non metro) you can still use the legacy API safely.
Sadly for WinRT/Metro, there is no midi support at all (see this discussion on msdn).
Hope they will change that.
A:
Last Friday Microsoft released a preview Windows Runtime API for MIDI. Check out the //build/ session here:
http://channel9.msdn.com/Events/Build/2014/3-548
MSDN: http://msdn.microsoft.com/en-us/library/windows/apps/dn643522.aspx
Although a preview, apps can go live and be deployed to the Windows Store. Please let us know what you like or don't like. Happy app building!
| {
"pile_set_name": "StackExchange"
} |
Q:
MongoDB find in array
I have a mongodb JSON array and I am having issues locating categories, eg.
{ name:"hoyts"}
I have tried {categories.name:"hoyts"} and a few others but nothing seems to work.
This is my JSON:
{
"_id": ObjectId("4f67da1538fc5d7347000000"),
"categories": {
"id": 1,
"name": "hoyts",
"product-logo": "http: \/\/www.incard.com.au\/newsite\/template\/images\/movieticket\/4cinemas\/hoytstop.png",
"products"▼: {
"0": {
"barcode": "25001",
"name": "GoldClass",
"Price": "12.00",
"CashBack": "2.00"
},
"1": {
"barcode": "25002",
"name": "Weekday",
"Price": "12.00",
"CashBack": "2.00"
},
"2": {
"barcode": "25003",
"name": "Weekend",
"Price": "24.00",
"CashBack": "4.00"
}
}
},
"store_name": "movies",
"1": {
"id": 2,
"name": "village",
"logo": "village.png",
"products": {
"0": {
"barcode": "26001",
"name": "GoldClass",
"Price": "12.00",
"CashBack": "2.00"
},
"1": {
"barcode": "26002",
"name": "Weekday",
"Price": "12.00",
"CashBack": "2.00"
},
"2": {
"barcode": "26003",
"name": "Weekend",
"Price": "24.00",
"CashBack": "4.00"
}
}
}
}
A:
In the JSON you posted categories is not an array, but object. If we assume that you have categories as array (inside []), you should use {"categories.name":"hoyts"} (with quotes for categories.name) for your criteria. The same thing will work if "categories" is not an array, but object (but I think that you wanted to have more categories, since name of the "property" is plural.
| {
"pile_set_name": "StackExchange"
} |
Q:
GLEW 1.9.0 builds a 64-bit .so even with m32 argument?
I've been trying to compile a 32-bit shared library of GLEW-1.9.0 under a 64-bit RedHat 4 machine, but it seems no matter what I try, the shared library it produces is 64-bit (this is determined using "file libGLEW*" in the output directory).
It seems GLEW has its own system for detecting the architecture. Ultimately, this comes down to "shell uname -m", which I've attempted to change using "setarch i386". The output of "uname -m" after that call is "i686", which isn't i386, but should still be 32-bit.
I've been setting CFLAGS.EXTRA before my 32-bit build to "-m32 -Wl,-rpath,$(APPDIR32)/lib -fPIC", where $(APPDIR32) is the directory I'm outputting to, as well as where I'm linking libraries from. This worked just fine for my 64-bit build (except with the '32's in the string replaced with '64's).
I've been using GLEW's Makefile as follows (after setting the variables mentioned above, among other less relevant ones): "make -f Makefile all"
Setting LDFLAGS to -m32 or melf_i386 has no effect on the format of the output file, which always ends up in ELF_64 (not ELF_32). The libraries being linked are all 32-bit, and that's one of the reasons it complains, as a describe below.
During the build I get repeated warnings like the following...
/usr/bin/ld: warning: i386 architecture of input file `tmp/linux/default/shared/glew.o' is incompatible with i386:x86-64 output
One question: Is i686 a 32-bit architecture? The wikipedia page is unclear on this. I found a point in that page where it says some i686 processors have support for 64-bit instruction sets.
Another question: I haven't been able to find any useful information on building 32-bit shared libraries for GLEW in a 64-bit environment. Can you give me any pointers?
And the ultimate question: Can you see where I'm going wrong, or do you know about an additional action I need to take to get this building a 32-bit shared library?
In response to request for information about the exact command line and its output for the warning mentioned above, it is as follows...
cc -shared -Wl,-soname=libGLEW.so.1.9 -o lib/libGLEW.so.1.9.0 tmp/linux/default/shared/glew.o -L/usr/X11R6/lib -L/usr/lib -lXmu -lXi -lGL -lXext -lX11
/usr/bin/ld: skipping incompatible /usr/lib/libXmu.so when searching for -lXmu
/usr/bin/ld: skipping incompatible /usr/lib/libXi.so when searching for -lXi
/usr/bin/ld: skipping incompatible /usr/lib/libGL.so when searching for -lGL
/usr/bin/ld: skipping incompatible /usr/lib/libXext.so when searching for -lXext
/usr/bin/ld: skipping incompatible /usr/lib/libX11.so when searching for -lX11
/usr/bin/ld: skipping incompatible /usr/lib/libc.so when searching for -lc
/usr/bin/ld: skipping incompatible /usr/lib/libc.a when searching for -lc
/usr/bin/ld: warning: i386 architecture of input file `tmp/linux/default/shared/glew.o' is incompatible with i386:x86-64 output
Here's my makefile, in case you get really excited and want more material. This makefile will work just fine if you put it in the same directory as GLEW-1.9.0's Makefile (that is until you try configure32). Just make sure to set TOPDIR. Use 'make -f clean', 'make -f configure32', 'make -f all', 'make -f install'.
APPLICATION = glew
VERSION = 1.9.0
FULLAPPLICATION = $(APPLICATION)-$(VERSION)
TOPDIR = /home/<username>/dev/project/third-party
APPDIRROOT = $(TOPDIR)/apps-miles
ARCH=$(shell uname | sed -e 's/-//g')
SHELL = /bin/csh
MACHTYPE32= i386
APPDIR32 = $(APPDIRROOT)/$(ARCH)_$(MACHTYPE32)
MACHTYPE64= x86_64
APPDIR64 = $(APPDIRROOT)/$(ARCH)_$(MACHTYPE64)
#
# Linux
#
ifeq ($(ARCH), Linux)
CC = gcc
CXX = g++
CFLAGS.EXTRA32 += -m32 -Wl,-rpath,$(APPDIR32)/lib -fPIC
CFLAGS.EXTRA64 += -m64 -Wl,-rpath,$(APPDIR64)/lib -fPIC
PATH = /sbin:/usr/sbin:/bin:/usr/bin:/usr/X11R6/bin
endif
#
# Darwin
#
ifeq ($(ARCH), Darwin)
CC = gcc
CXX = g++
CFLAGS.EXTRA32 += -m32 -mmacosx-version-min=10.5 -fPIC
CFLAGS.EXTRA64 += -m64 -mmacosx-version-min=10.5 -fPIC
PATH = /usr/bin:/bin:/usr/sbin:/sbin
endif
V_M_EXIST = $(shell test -e CONFIG.mk && echo 1)
ifeq ($(V_M_EXIST), 1)
include CONFIG.mk
endif
ECHO = echo
all::
make -f Makefile all
configure32::
@-/bin/rm CONFIG.mk; touch CONFIG.mk
@echo "GLEW_DEST = $(APPDIR32)" >> CONFIG.mk
@echo "export GLEW_DEST" >> CONFIG.mk
@echo "LIBDIR = $(APPDIR32)/lib" >> CONFIG.mk
@echo "export LIBDIR" >> CONFIG.mk
@echo "CFLAGS.EXTRA = $(CFLAGS.EXTRA32)" >> CONFIG.mk
@echo "export CFLAGS.EXTRA" >> CONFIG.mk
configure64::
@-/bin/rm VAPOR.mk; touch CONFIG.mk
@echo "GLEW_DEST = $(APPDIR64)" >> CONFIG.mk
@echo "export GLEW_DEST" >> CONFIG.mk
@echo "LIBDIR = $(APPDIR64)/lib" >> CONFIG.mk
@echo "export LIBDIR" >> CONFIG.mk
@echo "CFLAGS.EXTRA = $(CFLAGS.EXTRA64)" >> CONFIG.mk
@echo "export CFLAGS.EXTRA" >> CONFIG.mk
install::
make -f Makefile install
clean::
make -f Makefile clean
frog::
@$(ECHO) APPDIR = $(APPDIR32)
A:
EDIT: updated to reflect seemingly working workaround
First approach
As linking 32-bit code with 64-bit libs will not work on first sight the only problem seemed to be the following snippet of config/Makefile.linux starting on line 5:
M_ARCH ?= $(shell uname -m)
ifeq (x86_64,${M_ARCH})
LDFLAGS.EXTRA = -L/usr/X11R6/lib64 -L/usr/lib64
LIBDIR = $(GLEW_DEST)/lib64
else
LDFLAGS.EXTRA = -L/usr/X11R6/lib -L/usr/lib
LIBDIR = $(GLEW_DEST)/lib
endif
hardcoding the library search path to 64-bit libraries.
Second sight
As a first attempt trying something like:
make LDFLAGS=-m32 M_ARCH=anything_but_not_x86_64
still failed it turned out that in addition disregarding common conventions LDFLAGS will not be passed to the linker in the Makefile going with rules like the one on line 108:
lib/$(LIB.SHARED): $(LIB.SOBJS)
$(LD) $(LDFLAGS.SO) -o $@ $^ $(LIB.LDFLAGS) $(LIB.LIBS)
With LDFLAGS.whatever hardcoded to required switches.
Suggested workaround
While any of the workarounds like:
make LDFLAGS.SO="-L/usr/lib -L/usr/X11R6/lib -m32"
should work the most easy one to type seems to be the following one:
make LD="gcc -m32"
smuggling the -m32 switch into the LD macro.
| {
"pile_set_name": "StackExchange"
} |