text
stringlengths 64
89.7k
| meta
dict |
|---|---|
Q:
Audio cassette to MP3 or CD
I have plenty of old audio cassettes. I want the songs of the cassette in MP3 or some other computer playable format.
Is there any software available for converting audio cassettes to MP3 or CD?
A:
You could use Audacity.
Features:
Free, open-source and multiplatform software.
Includes processing options for removing noise, and normalising volume.
Can detect silence between tracks to help with conversion.
There is a tutorial for doing precisely what you want: http://manual.audacityteam.org/o/man/tutorial_copying_tapes_lps_or_minidiscs_to_cd.html
If you save as MP3 you need to download LAME encoder from here.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Potential Postdoc advisor giving exams (assignment) as part of hiring process
I will be graduating with a PhD from a US institution in computational sciences. I have published 10+ papers in peer reviewed journals in the field I am applying for jobs.
I have been interviewed by some PIs, and after interview, I have been asked to submit a few hours of tasks for further evaluation. I was wondering if it is normal these days in hiring process to assign some work/test to evaluate the candidates on top of interview presentation. Anyway, I found the assignment interesting and have decided to work on it.
A:
It is highly unusual. As you note, the PI has plenty of "standard" information (publications, recommendation letter, CV, etc.) that can be used to assess your potential as a collaborator and independent scientist. This is what most PIs will use in the hiring process. Some will ask you to give a seminar or do an interview by phone, video, or in person.
How the PI evaluates you as a candidate will reflect how the PI evaluates you once you are an advisee. This is especially true if they ask you to do something unusual, which is certainly the case here.
You are being told that the work you have done in the past, the good credit that you have earned with your previous advisor, your attendance and interaction at seminars... these are unimportant factors compared to whatever skills this "exam" is testing. It sounds like you do not agree with that attitude. That is reasonable, and if true, I suggest that you and this advisor may not be a good match.
A:
I find it a bit intriguing, actually. Though unusual. And, of course, if you object to it, move on now without another thought.
But perhaps she just wants to know how you will attack a new and fresh problem without the support you may have had in your studies. Or perhaps she and you are in a field in which a lot of opportunities pop up and there are threads of potential research that need a quick study and overview.
I don't find it offensive. Painful to comply with, perhaps, but that is up to you. Once she is paying you such things might become a requirement, not a request.
And I don't agree that she considers your accomplishments unimportant. But if the competition for the position is fierce, she will want every bit of information she can gather on candidates.
There is no reason to do this, unless you want the position, and no reason not to, but for the time it takes, if you do.
You choose.
Not everything that is weird is necessarily bad.
I'd love to hear from her why she does this. Maybe I'd be appalled.
A:
In the professional world there are plenty of interview processes that contain one or another way of skill assessment. That's pretty normal and not a way to devalue your general expertise but a matter of establishing whether your skills do fit the exact needs of the company and typically also if your way to apply them fits the company culture / type of person the company is looking for.
Whether an exam/report is the right and (e.g. wrt time investment) fair way to check how well you match for the given position is certainly debatable and definitely uncommon in the academic world.
However, note that this does not mean your other qualifications do not matter, they are the basis on which you get to the test level. Whether the job is worth the involved effort only you can decide.
On the other hand, isn't it a bit odd, that you want to complete the report while you don't want to take the position either way? That wastes your time and that of the potential advisor who will likely read it. Then again, if it is so motivating to do for you, maybe it is the perfect check whether you bring the right kind of motivation with you for the job. And it can also be valuable to you if you know the kind of stuff you would later deal with on a daily basis...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
MySQL for Oracle DBA
I am a newbie to MySQL, but understand Oracle databases well. I need a quick help to understand the architectural differences. Currently I am working on a Windows platform.
1) In Oracle we have to put the database in archive log mode, do we have to do this with MySQL to perform point in time recovery?
2) In Oracle, an instance starts with memory structure SGA. How does it work in MySQL?
3) RMAN is the online backup tool for oracle. MySQL backup for MySQL, is it capable to do point in time recovery?
4) I don't understand logging and database files layout in MySQL In Oracle if i create tablespace we see a file on the file system with name. How does this work in MySQL?
A:
Q) RMAN is the online backup tool for oracle. MySQL backup for MySQL, is it capable to do point in time recovery?
A) MySQL use mysqldump as online backup tool.
Q) In Oracle, an instance starts with memory structure SGA. How does it work in MySQL?
A) In MySQL, tuning of the caches similar to Oracle’s buffer cache is done on a per storage engine basis. For the MyISAM engine, the key_buffer can be used to cache index data only, and relies on the underlying operating system to cache data files unlike Oracle’s buffer cache. Because of this difference, while a dedicated Oracle database might allocate 80% of the system’s main memory to the buffer cache, often MySQL’s key buffer does not get set to much over 50% of the database system’s main memory for optimal tuning.
MySQL’s InnoDB storage engine has a more similar cache to Oracle’s buffer cache called innodb_buffer_pool_size and caches both index and data blocks. Like Oracle’s buffer pool, a dedicated MySQL system using only InnoDB tables would do well to set to up 80% of the systems main memory for use in this cache.
Q) I don't understand logging and database files layout in MySQL In Oracle if i create tablespace we see a file on the file system with name. How does this work in MySQL?
A) Each database managed by the MySQL server has its own database directory. This exists as a subdirectory of the data directory, with the same name as the database it represents. For example, a database mydb corresponds to the database directory DATADIR/mydb. This representation allows several database-level statements to be almost trivial in their implementation.
Q) In Oracle we have to put the database in archive log mode, do we have to do this with MySQL to perform point in time recovery?
A) I found something similar to this question in https://stackoverflow.com/questions/65093/best-way-to-archive-live-mysql-database
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Reading selected portion of line and soting it in array
How do I read every line of a string in Python and store seleted line as an element in an array?
I want to read the file line by line and each line is appended to the end of the array. I could not find how to do this anywhere and I couldn't find how to create an array of strings in Python.
For Example:
Line1=
abc def gef
lmn qrt was
lmh kjd lxm
skd fdj djk
ndz weg tdg
ndg has dbg
pef rah vdg
pas dgh ghr
bde ghx ore
My output should be:
line1[0]= abc def gef
lmn qrt was
lmh kjd lxm
line1[1]= skd fdj djk
ndz weg tdg
ndg has dbg
line1[2]= pef rah vdg
pas dgh ghr
bde ghx ore
A:
>>> line1 = """abc def gef
... lmn qrt was
... lmh kjd lxm
...
... skd fdj djk
... ndz weg tdg
... ndg has dbg
...
... pef rah vdg
... pas dgh ghr
... bde ghx ore"""
>>> line1.split("\n\n")
['abc def gef\nlmn qrt was\nlmh kjd lxm',
'skd fdj djk\nndz weg tdg\nndg has dbg',
'pef rah vdg\npas dgh ghr\nbde ghx ore']
>>> for number, item in enumerate(line1.split("\n\n")):
... print("Line number {0}".format(number))
... print(item)
...
Line number 0
abc def gef
lmn qrt was
lmh kjd lxm
Line number 1
skd fdj djk
ndz weg tdg
ndg has dbg
Line number 2
pef rah vdg
pas dgh ghr
bde ghx ore
>>>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Plot Pandas DataFrame as Bar and Line on the same one chart
I am trying to plot a chart with the 1st and 2nd columns of data as bars and then a line overlay for the 3rd column of data.
I have tried the following code but this creates 2 separate charts but I would like this all on one chart.
left_2013 = pd.DataFrame({'month': ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'],
'2013_val': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 6]})
right_2014 = pd.DataFrame({'month': ['jan', 'feb'], '2014_val': [4, 5]})
right_2014_target = pd.DataFrame({'month': ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'],
'2014_target_val': [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]})
df_13_14 = pd.merge(left_2013, right_2014, how='outer')
df_13_14_target = pd.merge(df_13_14, right_2014_target, how='outer')
df_13_14_target[['month','2013_val','2014_val','2014_target_val']].head(12)
plt.figure()
df_13_14_target[['month','2014_target_val']].plot(x='month',linestyle='-', marker='o')
df_13_14_target[['month','2013_val','2014_val']].plot(x='month', kind='bar')
This is what I currently get
A:
The DataFrame plotting methods return a matplotlib AxesSubplot or list of AxesSubplots. (See the docs for plot, or boxplot, for instance.)
You can then pass that same Axes to the next plotting method (using ax=ax) to draw on the same axes:
ax = df_13_14_target[['month','2014_target_val']].plot(x='month',linestyle='-', marker='o')
df_13_14_target[['month','2013_val','2014_val']].plot(x='month', kind='bar',
ax=ax)
import pandas as pd
import matplotlib.pyplot as plt
left_2013 = pd.DataFrame(
{'month': ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep',
'oct', 'nov', 'dec'],
'2013_val': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 6]})
right_2014 = pd.DataFrame({'month': ['jan', 'feb'], '2014_val': [4, 5]})
right_2014_target = pd.DataFrame(
{'month': ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep',
'oct', 'nov', 'dec'],
'2014_target_val': [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]})
df_13_14 = pd.merge(left_2013, right_2014, how='outer')
df_13_14_target = pd.merge(df_13_14, right_2014_target, how='outer')
ax = df_13_14_target[['month', '2014_target_val']].plot(
x='month', linestyle='-', marker='o')
df_13_14_target[['month', '2013_val', '2014_val']].plot(x='month', kind='bar',
ax=ax)
plt.show()
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Preventing methods from being inherited
I have a base class Foo that is concrete and contains 30 methods which are relevant to its subclasses.
Now I've come across a situation that is specific only to the base class,and I want to create a method that cannot be inherited, is this possible?
Class Foo
{
/* ... inheritable methods ... */
/* non-inheritable method */
public bool FooSpecificMethod()
{
return true;
}
}
Class Bar : Foo
{
/* Bar specific methods */
}
var bar = new Bar();
bar.FooSpecificMethod(); /* is there any way to get this to throw compiler error */
EDIT
I'm not sure if I was clear originally.
I do understand the principles of inheritance, and I understand the Liskov substitution principle. In this case there is a single exception that ONLY deals with the 'un-inherited' case, and so I did not want to create an 'uninheritedFoo' subclass.
I was asking if it is technically possible to create a situation where
foo.FooSpecificMethod() is a valid and publicly accessible method, but subclassoffoo.FooSpecificMethod() throws a compiler error.
Essentially I want a sealed method on an unsealed class.
A:
I would rethink the need for this.
If you are using inheritance, you are suggesting that "Bar" IS A "Foo". If "Bar" is always a "Foo", methods that work on "Foo" should also work on "Bar".
If this isn't the case, I would rework this as a private method. Publically, Bar should always be a Foo.
Just to take this one step further -
If you could do this, things would get very complicated. You could have situations where:
Foo myBar = new Bar(); // This is legal
myBar.FooSpecificMethod(); // What should this do?
// It's declared a Foo, but is acutally a Bar
You can actually force this behavior using reflection, though. I think it's a bad idea, but FooSpecificMethod() could check the type of this, and if it isn't typeof(Foo), throw an exception. This would be very confusing, and have a very bad smell.
Edit in response to question's edit:
There is no way for the compiler to enforce what you are asking. If you really want to force the compiler to check this, and prevent this, you really should consider making Foo a sealed class. You could use other extension methods than subclassing in this case.
For example, you might want to consider using events or delegates to extend the behavior instead of allowing the object to be subclasses.
Trying to do what you are accomplishing is basically trying to prevent the main goals of inheritance.
A:
Brian's right about Liskov Substitution (upmodded). And Reed's right about "is-a" (also upmodded); in fact they're both telling you the same thing.
Your public methods are a contract with users of your class Foo, saying that, "you can always" call those methods on Foo.
Subclassing Foo means that you're saying that a Subclass, e.g. Bar, is always acceptable to use where a Foo could be used. In particular, it means you inherit not (necessarily) Foo's implementation (you can override that, or Foo may be abstract and give no particular implementation for a method).
Inheritance of implementation (if any) is a detail; what you're really inheriting is the public interface, the contract, the promise to users that a Bar can be used like a Foo.
Indeed, they may never even know they have a Bar, not a Foo: if I make a FooFactory, and I write its Foo* getAFoo() to return a pointer to a Bar, they may never know, and sholdn't have to.
When you break that contract, you break Object Orientation. (And the Java Collection classes, by throwing NotSupported exceptions, entirely break OO -- users can no longer use so-called subclasses polymorphically. That's poor, poor design, which has caused major headaches for many many Java users, not something to emulate.)
If there's a public method that Foo subclasses can't use, then that method shouldn't be in Foo, it should be in a Foo subclass, and the other subclasses should derive from Foo.
Now, that does NOT mean that all methods in Foo should be callable on subclasses. No, I'm not contradicting myself. Non-public methods are not part of a class's public interface.
If you want a method in Foo that can't be called on Bar, and shouldn't be publicly callable in Foo, then make that method private or protected.
A:
No, this would violate the Liskov substitution principle.
Pragmatically, you can either have it "throw NotImplementedException()" in Bar, or remove the method from Foo and move it down to the subclasses to which it applies.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why is this easy comparison false?
Why does this simple statement evaluate to FALSE in R?
mean(c(7.18, 7.13)) == 7.155
Furthermore, what do I have to do in order to make this a TRUE statement? Thanks!
A:
It's probably due to small rounding error. Rounding to the third decimal place shows that they are equal:
round(mean(c(7.18, 7.13)), 3) == 7.155
Generally, don't rely on numerical comparisons to give expected logical outputs :)
A:
Floating point arithmetic is not exact. The answer to this question has more information.
You can actually see this:
> print(mean(c(7.18,7.13)), digits=16)
[1] 7.154999999999999
> print(7.155, digits=16)
[1] 7.155
In general, do not compare floating point numbers for equality (this applies to pretty much every programming language, not just R).
You can use all.equal to do an inexact comparison:
> all.equal(mean(c(7.18,7.13)), 7.155)
[1] TRUE
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Provide an easy way (or link) to browse to the tags page from the Ask a Question page
I joined a new site, and realized there's no easy way to "browse" the tags page from the Ask a Question page. The usual tag select box has its useful autocomplete, but it requires me to enter something before I can see anything. It's my first time on that site, and even a link to the tags page would help. (The links on the right panel were helpful.)
A:
It's easy! Just click the blue help icon at the bottom right:
and click on "Use existing popular tags". It'll take you straight to the Tag page.
Credit to @user289905: Alternatively, go here:
and click on "Tags".
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Need past 2 results from observable as input into a third
Is there a way to get the past 2 results from an observable sequence and use as input into a third.
Here is the code without any observables.
public login(...): Promise<any> {
const user: any = ctx.prisma.query.user({ where: { email } });
if (!user) {
throw new Error(`No such user found for email: ${email}`);
}
const valid = bcrypt.compare(password, user.password);
if (!valid) {
throw new Error("Invalid password");
}
return {
token: jwt.sign({ userId: user.id }, process.env.APP_SECRET),
user,
};
}
Here is my solution that does not work that brought me to ask this question. This doesn't work because i do not have the user result from the call to ctx.prisma.query.user(...) when i need to check valid and do my map.
public login(...): Promise<any> {
return from(ctx.prisma.query.user({ where: { email } })).pipe(
mergeMap(
(user: User) => {
if (!user) {
throw new Error(`No such user found for email: ${email}`);
}
return from(bcrypt.compare(password, user.password));
}
),
map(
(valid: boolean) => {
if (!valid) {
throw new Error("Invalid password");
}
return {
token: jwt.sign({ userId: user.id }, process.env.APP_SECRET),
user,
};
}
)
).toPromise();
}
Here is my attempt at this solution that works, but i was just wondering if this is correct or if there is a better way.
I need the user and the valid result in my map so that i can create the correct object.
My solution just feels weird, because if i needed to keep going with this sequence and previous results it would get really deep.
public login(...): Promise<any> {
return from(ctx.prisma.query.user({ where: { email } })).pipe(
switchMap(
(user: User) => {
if (!user) {
throw new Error(`No such user found for email: ${email}`);
}
return from(bcrypt.compare(password, user.password)).pipe(
map(
(valid: boolean) => {
if (!valid) {
throw new Error("Invalid password");
}
return {
token: jwt.sign({ userId: user.id }, process.env.APP_SECRET),
user,
};
}
)
);
}
)
).toPromise();
}
A:
With the help of @bryan60 and @Daniel Gimenez, we came to the conclusion that my provided solution in my question is the most accurate with version 6. Here is my final solution.
public login(
source: any,
{email, password},
ctx: IContext,
info: GraphQLResolveInfo): Promise<any> {
return from(ctx.prisma.query.user({ where: { email } })).pipe(
tap(
(user: User) => {
if (!user) {
throw new Error(`No such user found for email: ${email}`);
}
}
),
switchMap(
(user: User) => {
return from(bcrypt.compare(password, user.password)).pipe(
map(
(valid: boolean) => {
if (!valid) {
throw new Error("Invalid password");
}
return {
token: jwt.sign(
{ userId: user.id },
process.env.APP_SECRET
),
user,
};
}
)
);
}
)
).toPromise();
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Merging two consecutive lines into one (seeking a solution working for Windows files too)
I'd like to merge two consecutive lines in a Windows text file using external bash environment like the one that for instance Cygwin or MobaXTerm provide.
I know there are similar questions asked and already set to solved but for some reason they don't work with my environment. Is it perhaps cos Windows is adding some invisible characters unrecognized by bash tools?
Here are the solutions from other similar questions which I already tried:
awk 'NR%2{a=$0;next}{print a","$0}' test.txt
grep "line" test.txt |awk 'NR==0{prefix=$0;next} {print prefix, $0}'
sed '$!N;s/\n/,/' test.txt
Input I'm working with:
first line
second line
third line
fourth line
fifth line
sixth line
Expected result:
first line,second line
third line,fourth line
fifth line,sixth line
Actual result with any of the code I tried so far:
1)
➤ sed '$!N;s/\n/,/' test.txt
,second line
,fourth line
,sixth line
2)
➤ grep "line" test.txt |awk 'NR==0{prefix=$0;next} {print prefix, $0}'
first line
second line
third line
fourth line
fifth line
sixth line
Any help here will be greatly appreciated.
A:
$ cat -v file
first line^M
second line^M
third line^M
fourth line^M
fifth line^M
sixth line^M
With GNU awk for multi-char RS:
$ awk -v RS='\r?\n' -v OFS=',' 'NR%2{p=$0; next} {print p, $0}' file
first line,second line
third line,fourth line
fifth line,sixth line
With any awk:
$ awk -v OFS=',' '{sub(/\r$/,"")} NR%2{p=$0; next} {print p, $0}' file
first line,second line
third line,fourth line
fifth line,sixth line
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to eliminate alternator whine?
On my car's LW receiver, I have a severe case of alternator whine, especially when the headlights are on. It has become worse over time.
I have read that capacitors might help.
However, two things remain unclear to me:
Of what value should these capacitors be?
Where in the vehicle should these be installed? A schematic drawing would be very much appreciated.
A:
The most important and simplest thing you can do to eliminate alternator whine is run a separate set of power cables directly from the cars battery terminals to the radio. Making sure you include the proper rated fuses links on both leads immediately after the battery terminal connection. (the fuses are for safety and should be on both the positive and negative leads)
Doing that should solve a good portion of your issue.
You should also make sure the antenna is properly grounded to the vehicles body. If it is mounted on a trunk lid you will need to add a ground connection from the body to the lid. As the hinges don't offer a solid ground.
Lastly you can buy a noise filter to put in the power leads just before the connection to the radio. This can be purchase at your every day electronics shack or automotive store. make sure you purchase a filter that can handle the load your radio will put on it.
A:
Alternator whine is caused by a small amount of AC signal component on your DC power supply to the radio. The alternator generates this AC signal as a by-product of how it works. A diode pack on the alternator converts AC current from it's windings into DC to charge the battery. The battery "smooths" out the pulses of energy from the alternator. For more information on this bit, see here: http://auto.howstuffworks.com/alternator3.htm.
To eliminate the alternator whine, you need to remove this AC signal from your DC supply. You mention that the whine has gotten worse, which probably corresponds to the deterioration of your vehicle battery — i.e. it is not smoothing the pulses out quite as well. This is a side issue.
The approach I would use to eliminate the whine noise, and that has worked for me before, is to run wires from the radio directly to the battery, where the smoothing should occur. Adding a filter in the supply cable, specifically the positive cured the issue for me. I used a large DC choke from an old power inverter (used for a similar job inside that) — essentially a large inductor capable of handing the current your transceiver needs — in series with the supply, followed by a large-ish capacitor (25 V, 10 000 µF) on the radio side to dissipate any noise passing through the inductor.
This worked pretty well for me. YMMV.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
como puedo crear un bat para que haga un ping infinito
Hola estoy intentando hacer un simple lo que necesito haga ping infinito a mi router porque muchas veces pierdo la conexion con mi router y asi me va un poco mejor.
no se mucho sobre bat pero lo que necesito es poner este comando en un bat:
ping 192.168.1.1 -t
¿como podría hacerlo? y disculpar por mi ignorancia.
A:
Puedes copia lo siguiente:
@echo off
title Infinite ping
echo Ctrl+c para detener la ejecución...
ping 192.168.3.29 -t
pause
y luego lo guardas como ping_infinito.bat o el nombre que tu quieras, solo asegurate que la extensión sea .bat
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Requesting MathJax/Latex Support
Not sure if this is the right place to ask this, but can we get MathJax/Latex support in here for more serious questions?
NOTE: We have MathJax. Put away pitchforks.
Also: Thank you SE powers.
A:
Irrespective of the arguments, and the votes on the matter, in Area 51, SE activated the private Beta without MathJax. No comment.
Once again: "Economics" lives as a tag in math.SE already:
https://math.stackexchange.com/questions/tagged/economics
We don't need to show again that MathJax is vital for this site, but let's provide one example:
This is an ugly looking question
First Order Condition for Profit Maximization in Gambling Industry
and I cannot post the answer I wanted to.
And I cannot participate here, without MathJax. So, until things change, good luck.
A:
I'm starting a community wiki for questions that we think could really use MathJax.
First Order Condition for Profit Maximization in Gambling Industry
The relation between the Black-Scholes model and quantum mechanics
Is elasticity meaningful in my, or any, regression?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Colorbar - axis ticks in Matlab
I am using the code below
d3 = vals;
n = datesmonth;
figure
plot(n,d3);
colormap(jet(12));
hold on
plot(n, d3,'b-');
scatter(n, d3, [], RiskierInd, 'filled');
caxis([1 12]);
colorbar('YTick',[1:12],...
'YTickLabels',{'Non-Durables','Durables','Manufacturing','Oil, Gas and Coal ','Chemicals','Technology','Telephone & TV','Utilities','Wholesale and Retail','Health','Finance','Other'})
datetick('x','mm-yyyy')
to produce this figure
I have two quick questions:
Is it possible to center the color bar string entries for each color? For example, the entry "Non-Durables" should not be at the bottom of color bar, but in the middle of the darkest blue category.
Is it possible to manually choose the colors for each category?
A:
Ratbert pretty much answered the first question. However, for the sake of completeness, simply do this and replace your current caxis call:
caxis([0.5 12.5]);
To answer the second question, yes you can.
If you notice in your code, you produced a colour map of 12 components from the jet theme. This produces a 12 x 3 matrix where each row is a unique colour. As such, if you want to manually choose the colours, you simply have to rearrange what order the colours come in. If you look at the colour bar label in your plot, the first colour starts from the bottom, or blue, and it progresses to the top, or red.
As a reference, this is the matrix that gets produced by jet(12):
>> cmap = jet(12)
cmap =
0 0 0.6667
0 0 1.0000
0 0.3333 1.0000
0 0.6667 1.0000
0 1.0000 1.0000
0.3333 1.0000 0.6667
0.6667 1.0000 0.3333
1.0000 1.0000 0
1.0000 0.6667 0
1.0000 0.3333 0
1.0000 0 0
0.6667 0 0
Each row contains a unique RGB tuple, where the first column denotes the amount of red, second the amount of green and third the amount of blue. Therefore, the first couple of colours are purely blue, and then shades of green are incrementally added after that point to make it cyan and so on and so forth.
The matrix is arranged such that the first colour is the first row and the last colour is the last row. If you want to decide which colours you want for which label, you simply need to re-arrange the rows so that it matches whichever label you want.
Therefore, you have a set of labels:
labels = {'Non-Durables','Durables','Manufacturing','Oil, Gas and Coal ','Chemicals','Technology','Telephone & TV','Utilities','Wholesale and Retail','Health','Finance','Other'};
... and currently, you have an order of which colour appears in the colour map:
cmap = jet(12);
order = [1 2 3 4 5 6 7 8 9 10 11 12]; %// or order = 1:12;
cmap = cmap(order,:);
All you have to do is change order so that you get the right colour to appear in the right order. Therefore, consult the colour bar in your image, and make the positions of each colour be arranged so that it conforms to the same positions of order. For example, if you wanted to reverse the colour ordering, you would do this:
cmap = jet(12);
order = [12 11 10 9 8 7 6 5 4 3 2 1]; %// or order = 12:-1:1;
cmap = cmap(order,:);
Similarly, if you wanted the yellow and cyan colours to come first and the rest to come after, you would do:
cmap = jet(12);
order = [8 4 5 6 7 1 2 3 9 10 11 12];
cmap = cmap(order,:);
Once you do this, you call colormap on cmap and continue with your plot:
%// From before
cmap = jet(12);
order = [4 5 6 8 7 1 2 3 9 10 11 12];
cmap = cmap(order,:);
%// New
colormap(cmap);
hold on
plot(n, d3,'b-');
scatter(n, d3, [], RiskierInd, 'filled');
caxis([0.5 12.5]); %// Change
colorbar('YTick',[1:12],...
'YTickLabels',{'Non-Durables','Durables','Manufacturing','Oil, Gas and Coal ','Chemicals','Technology','Telephone & TV','Utilities','Wholesale and Retail','Health','Finance','Other'})
datetick('x','mm-yyyy')
However, if you want to manually choose the colours yourself, that'll be a bit more involved. You'd just need to know what colours you'd want then place them into the matrix. Remember, each colour is a RGB tuple and is placed in a single row. You'd have to look at a colour picker though to know what each component should be weighted as to get the right colour.
Go here: http://colorpicker.com - You can choose the exact colour you want and record the RGB values. After, divide each value by 255 and place this as an entry in your colour map matrix. Each colour is a row where the first column is the red, second column green and third column blue. This is if you truly want to control what colour goes with what category. You'll have to get right down to determining the right combination of red, green and blue values.
Good luck!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Wordpress - can't install plugins after server reboot
I'm running a CentOS server which I had to reboot.
However, after the reboot I found myself unable to install wordpress plugins via its admin control panel, as I'm getting a 'failed to connect' message:
This is strange since the the same configuration worked before the reboot.
Any ideas on what can be the problem?
A:
vsftpd 0:off 1:off 2:off 3:off 4:off 5:off 6:off
It means that vsftpd is not starting at boot. Execute the following commands as root:
/etc/init.d/vsftpd start
chkconfig vsftpd on
|
{
"pile_set_name": "StackExchange"
}
|
Q:
google v3 info bubble position doesn't center
When page loaded info bubble position can't get center.
But when i click the marker info bubble is get true position.
so this issue causes readable problem.
http://jsfiddle.net/onurodemis/QxvPR/1/
A:
In this cases I am used to postpone opening the balloon. One possible way is to use javascript setTimeout like here:
http://jsfiddle.net/PuxT7/5/
Using jquery $(document).ready() for instance will probably give the same result.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Compiling Error: Enabled Compilation before Running a Compile
I went to System > Tools > Compilation and "enabled" before anything was actually compiled and my site returned this error:
Fatal error: Class 'Mana_Filters_Resource_Setup' not found in /home/kokorugs/public_html/store/includes/src/Mage_Core_Model_Resource_Setup.php on line 234
I did some research and believe my answer is below:
Judging by the include warning, it seems like you have the compiler enabled but it cannot find the (flattened) file.
So either disable the compiler:
php shell/compiler.php disable
Or run a compilation so that it will generate the file for you:
php shell/compiler.php compile
My question is:
Where do I enter something like php shell/compiler.php compile?
A:
It is one of several Magento management scripts contained in shell/ and is to be run from the command line in an ssh session on hosting plans where ssh access has been allowed.
So you log in with a SSH client like putty, get a terminal window and cd to the Magento root directory.
Depending on how you installed Magento, this will be:
your web server document root (public_html, htdocs, or in rather unsophisticated and poorly setup hosting, your home directory)
a directory under your web server document root (for example, installed in a subdirectory called magento)
In the Magento root directory, you will see a subdirectory called shell
At the command prompt in the Magento root directory, enter your command string and press enter.
somebody@someserver$ php shell/compiler.php disable
A:
First off don't sweat it. Everyone makes this mistake at some point. In the future you never want to use "Enable" but rather always use "Run compilation process" to be safe.
From this blog post on how to disable the Magento compiler, here are 4 different ways you can get it disabled:
Login to your server using SSH and navigate into your root Magento directory (usually /home/{username}/public_html/ then type php shell/compiler.php disable. If you're not sure how to use shell you can do some googling or see step 4 below.
Edit the includes/config.php and comment out both lines at the end of the file by placing a # in front of them like this:
#define('COMPILER_INCLUDE_PATH', dirname(__FILE__).DIRECTORY_SEPARATOR.'src');
#define('COMPILER_COLLECT_PATH', dirname(__FILE__).DIRECTORY_SEPARATOR.'stat');
Login to the Magento admin and go to System > Tool > Compilation and click Disable
If you're not sure how to use SSH, you can create a simple PHP file to run the proper commands for you. Simply create a php file like disable_compilation.php in your web directory (usually /home/{username}/public_html/ or /var/www/) and paste the contents below. After you have the file saved simply navigate to the file in your browser and it'll disable the compiler for you like www.yoursite.com/disable_compilation.php
<?php
echo system('php shell/compiler.php disable');
?>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
sbt dependsOn, typesafe config merges application.conf
I have a project with two modules, A and B. Each has an application.conf and a local.conf that includes the former. My project's build.sbt file specifies:
B.dependsOn(A % "compile->compile")
It appears that the local.conf for module B is including application.conf for module A, because I am getting an UnresolvedSubstitution exception for substituted values in module A's application.conf when trying to run module B.
I think it is merging the application.conf files. Is there any way to stop it doing this? In particular, can I do it via the build.sbt file?
A:
When you do this:
B.dependsOn(A % "compile->compile")
what happens is that when B is compiled, it executes A compilation and makes it available to B. This means your configuration files in A will be available to B because Type-Safe configuration puts those configurations into the classpath.
The easiest solution is probably to namespace your properties so that module B is only using properties from it's own configuration and never As. (This is a best practice, to keep separation of concerns clear.) If the intent is for B's configuration to override A's 'default' configuration, and assuming A is essentially a library being used by B, following the best practice guideline here and place a resource.conf file in A and an application.conf file in B, since application.conf is higher-priority.
In your case, both A and B rely on common code. In order to preserve separation of concerns, it is best to refactor this common code into it's own library module and have both A and B reference that code. In this manner you can ensure that the properties they both rely on are in C and properties that are properly set by either A or B are in their domain alone.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Conexion internet IOS Xcode 7
Es posible deshabilitar la conexión a internet en el simulador de IOS de xcode 7?
A:
Existe una herramienta de xcode que simula entornos de conectividad buenos y malos. Quizás puedas simular una conexión mala malisima y/o practicamente nula o nula y asi no tener internet en el simulador. A ver si te sirve. (http://nshipster.com/network-link-conditioner/)
Otra opción que te podría servir sería simular un red lenta, este paquete de github te podría ayudar.
(https://github.com/AliSoftware/OHHTTPStubs)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Circular Reference in C++
i'm working on a Snake game and i'm having trouble with Circular Reference in C++.
This is the header of the class SnakeBody who represent anypart of the Snake that is not the head.
#ifndef SNAKEBODY_HPP_
#define SNAKEBODY_HPP_
class SnakeBody {
public:
SnakeBody(SnakeHead *origin, int left, int x, int y);
~SnakeBody() = default;
void move();
void grow(int size);
protected:
SnakeBody *next;
SnakeHead *head;
SnakeGame *game;
int x;
int y;
int growWait;
};
#endif /* !SNAKEBODY_HPP_ */
And there is the source code (the part containing the constructor).
#include "../include/SnakeHead.hpp"
#include "../include/SnakeGame.hpp"
#include "../include/SnakeBody.hpp"
SnakeBody::SnakeBody(SnakeHead *origin, int left, int x, int y)
{
this->head = origin;
this->game = this->head->getGame();
this->x = x;
this->y = y;
this->growWait = 0;
if (left > 0)
this->next = new SnakeBody(origin, left - 1, x + 1, y);
else
this->next = nullptr;
}
I have been carefull about make every include in source and not header to avoid unfinished reference and loop. But it still appear that SnakeHead has a undefined reference.
SnakeBody : Any part of the snake that is not the head.
SnakeHead : The head of the snake.
SnakeGame : Contain the state of the board, need a reference of SnakeHead and SnakeHead and SnakeBody need a reference of SnakeGame to get data about the state of the game (ie : wall, food, etc...).
The error message is : ./src/../include/SnakeBody.hpp:19:9: error: ‘SnakeHead’ does not name a type; did you mean ‘SnakeBody’?
SnakeHead *head;
A:
Add forward references. BTW, there's no reason to use three header files.
None of the classes is of any use without the others, so put them all into one header. And a namespace would be nice.
#ifndef SNAKEBODY_HPP_
#define SNAKEBODY_HPP_
class SnakeHead; // Here
class SnakeGame; // and here
class SnakeBody {
public:
SnakeBody(SnakeHead *origin, int left, int x, int y);
~SnakeBody() = default;
void move();
void grow(int size);
protected:
SnakeBody *next;
SnakeHead *head;
SnakeGame *game;
int x;
int y;
int growWait;
};
#endif /* !SNAKEBODY_HPP_ */
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Translate from English to first-order logic
Translate the following sentences to FOL:
1)Mary loves all fluffy cats
2)Anybody who trusts nobody deceives themself.
3)Tom's uncle does not like any of his own children.
From my understanding of First-order logic I have come to these answers:
1) ∀x[cat(x) ^ fluffy(x) loves(Mary,x)]
2) ∀x[Person(x) trusts(x, ¬ x) deceives(x, x)]
3)This third one has been bugging me for quite some time now. I have come to 4 answers and I am not sure wether one of these is correct or if there is a correct one at all:
a) ∃x∀y ¬[Uncle(x,Tom) Child(y) ^ likes(x,y)]
b) ∃x∀y [Uncle(x,Tom) Child(y) ^ ¬ likes(x,y)]
c) ∃x∀y ¬[Uncle(x,Tom) Child(y,x) ^ likes(x,y)]
d) ∃x∀y [Uncle(x, Tom) Child(y,x) ^ ¬ likes(x,y)]
On c) and d) I write "Uncle - Child" relation the same way as "Uncle - Tom" (not sure if it is correct)
If you could explain where I am wrong and right and why I would much appreciate it. Thank you!
A:
1) $∀x[\operatorname{cat}(x) \wedge \operatorname{fluffy}(x) \to \operatorname{loves}(\operatorname{Mary},x)]$
Yes.
2) $∀x[\operatorname{Person}(x)\wedge \operatorname{trusts}(x, ¬ x) \to \operatorname{deceives}(x, x)]$
No. $x$ is an entity and not a predicate; you can't negate it. Nobody is: $\neg\exists y~(\operatorname{Person}(y)\wedge\ldots)$
3)This third one has been bugging me for quite some time now. I have come to 4 answers and I am not sure wether one of these is correct or if there is a correct one at all:
a) $∃x∀y ¬[\operatorname{Uncle}(x,\operatorname{Tom}) \to \operatorname{Child}(y) \wedge \operatorname{likes}(x,y)]$
b) $∃x∀y [\operatorname{Uncle}(x,\operatorname{Tom}) \to \operatorname{Child}(y) \wedge ¬ \operatorname{likes}(x,y)]$
c) $∃x∀y ¬[\operatorname{Uncle}(x,\operatorname{Tom}) \to \operatorname{Child}(y,x) \wedge \operatorname{likes}(x,y)]$
d) $∃x∀y [\operatorname{Uncle}(x, \operatorname{Tom}) \to \operatorname{Child}(y,x) \wedge ¬ \operatorname{likes}(x,y)]$
None of them really. You want to say: "Some one is Tom's Uncle and any one who is that one's children will not be liked by that one."
Can you put that in symbols?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SQL join column
I have a set of table as following
customer(cus_id,cus_first_name,cus_last_name);
insert into customer values ('c001', 'tan', 'wah khang');
I want to create a select statement to display the first name join with the last name.
Example :
tan wah khang
is that possible?
A:
You can use the (this is not called "join" but) concatenation *|| (double pipe)* operator:
SELECT (cus_first_name || ' ' || cus_last_name) AS full_name
FROM customer
|
{
"pile_set_name": "StackExchange"
}
|
Q:
RRD wrong values
I'm playing with RRDTool, but it shows wrong values.
I have little python script:
import sys
import rrdtool
import time
i = 0
rrdtool.create(
'tempo.rrd',
'--step', '10',
'DS:temp:GAUGE:20:-40:100',
'RRA:LAST:0.5:1:1500'
)
while 1:
ret = rrdtool.update('tempo.rrd','N:' + `i`);
print "i %i" % i
rrdtool.graph(
'test.png',
'--imgformat', 'PNG',
'--width', '540',
'--height', '200',
'--start', "-%i" % 60,
'--end', "-1",
'--vertical-label', 'Temperatura',
'--title', 'Temperatura lauke',
'--lower-limit', '-1',
'DEF:actualtemp=tempo.rrd:temp:LAST',
'LINE1:actualtemp#ff0000:Actual',
'GPRINT:actualtemp:LAST:Actual %0.1lf C'
)
i += 1
time.sleep(10)
After inserting [0, 1, 2], I get graph with wrong values -
http://i.imgur.com/rfWWDMm.png (sorry, I can't post images).
As you see, after inserting 0, graph shows 0, after inserting 1, graph shows 0.8 and after inserting 2, graph shows 1.8. Sometimes after inserting 1, graph shows 0.6 and so on. Am I doing something wrong?
A:
This is how RRDtool works. RRDtool works with rates, exclusively. You can input gauge data (discrete values in time) but RRDtool will always treat them internally as rates.
When you created your RRD file (tempo.rrd), internally RRDtool created buckets with a starting timestamp at creation time and each subsequent bucket +10s from that timestamp. For example
bucket 1 - 1379713706
bucket 2 - 1379713716
bucket 3 - 1379713726
...
bucket 100 - 1379714706
bucket 101 - 1379714716
bucket 102 - 1379714726
If you were to insert your integer values at exactly the timestamps matching the buckets, you'd be ok but you're not. Your script is inserting values using the current timestamp which is almost certainly not going to be equal to a bucket value. Hypothetically, lets say current timestamp is 1379714708 and you want to insert a value of 2. When you insert your value, RRDtool needs to choose which bucket to put it in. In this case 1379714706 is the nearest so it will choose that one (there's a bit more logic here but that's the gist). You might think it would insert '2' into the bucket, but to RRDtool, that would be a lie. It might be 2 now, but it probably wasn't 2 a few seconds ago. Bearing in mind that it sees all these values as rates, it tries to figure out how much it should subtract from that value to make it right by looking at the rate of change of previous values That's why you see values such as 1.8 and 2.8 and not the integer values you expect. Things get more complicate if you insert multiple values between buckets or skip buckets.
There's an excellent tutorial at http://oss.oetiker.ch/rrdtool/tut/rrdtutorial.en.html that goes into more detail.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SQL Server database security
I have SQL Server 2008 installed on Windows 2008 Server.
I've disabled built-in administrator password and created sa with sysadmin privileges.
Question is: Is there any way to access to database, or back it up. or methods to reset (and / or) get password for sa?
I want to secure my database.
Thanks.
A:
I've disabled built-in administrator password...I want to secure my database.
If you think you can disable access to built-in administrators your are chasing a phantasm. Built-in administrators will always be able to access your database, the steps to gain access are clearly documented in Connect to SQL Server When System Administrators Are Locked Out. Your database must be deployed on a system on which you completely trust the system administrators, there is no work around for this basic requirement.
Most often this question is asked as some misguided attempt to protect the perceived IP in the database. The answer to that question is that what you want is called DRM and SQL Server does not offer DRM. If you are afraid of distributing the database to your users then use a service like SQL Azure.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to use a class without declaring object
I'm trying to develop a class in VB .NET in order to manage a language globalization stored in a database and editable by the user.
What I need is to know what kind of class I need to declare in order to use it without declaring a new object. For example, the way My.Settings is used.
One of the goals is that in some project the developer imports the reference and after that access directly to a property. For example: My.CustomLanguage.GetWord("Hello") without declaring objects.
Is this possible? And if it's what is the best way to aproach it?
Thank you.
A:
You can declare every property or method that you need to access as static, in VB, "Shared"
Shared Sub GetSomething()
MySharedClass.GetSomething()
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Vector direction for gravity in a circular orbit
I am currently working on a project in C# where i play around with planetary gravitation, which i know is a hardcore topic to graps to it's fullest but i like challenges. I've been reading up on Newtons laws and Keplers Laws, but one thing i cannot figure out is how to get the correct gravitational direction.
In my example i only have 2 bodies. A Satellite and a Planet. This is to make is simplify it, so i can grasp it - but my plan is to have multiple objects that dynamically effect each other, and hopefully end up with a somewhat realistic multi-body system.
When you have an orbit, then the satellite has a gravitational force, and that is ofcourse in the direction of the planet, but that direction isn't a constant. To explain my problem better i'll try using an example:
let's say we have a satellite moving at a speed of 50 m/s and accelerates towards the planet at a speed of 10 m/s/s, in a radius of 100 m. (all theoretical numbers) If we then say that the framerate is at 1, then after one second the object will be 50 units forward and 10 units down.
As the satellite moves multiple units in a frame and about 50% of the radius, the gravitational direcion have shifted alot, during this frame, but the applied force have only been "downwards". this creates a big margin of error, especially if the object is moving a big percentage of the radius.
In our example we'd probably needed our graviational direction to be based upon the average between our current position and the position at the end of this frame.
How would one go about calculating this?
I have a basis understanding of trigonometry, but mainly with focus on triangles. Assume i am stupid, because compared to any of you, i probably am.
(I made a previous question but ended up deleting it as it created some hostility and was basicly not that well phrased, and was ALL to general - it wasn't really a specific question. i hope this is better. if not, then please inform me, i am here to learn :) )
Just for reference, this is the function i have right now for movement:
foreach (ExtTerBody OtherObject in UniverseController.CurrentUniverse.ExterTerBodies.Where(x => x != this))
{
double massOther = OtherObject.Mass;
double R = Vector2Math.Distance(Position, OtherObject.Position);
double V = (massOther) / Math.Pow(R,2) * UniverseController.DeltaTime;
Vector2 NonNormTwo = (OtherObject.Position - Position).Normalized() * V;
Vector2 NonNormDir = Velocity + NonNormTwo;
Velocity = NonNormDir;
Position += Velocity * Time.DeltaTime;
}
If i have phrased myself badly, please ask me to rephrase parts - English isn't my native language, and specific subjects can be hard to phrase, when you don't know the correct technical terms. :)
I have a hunch that this is covered in keplers second law, but if it is, then i'm not sure how to use it, as i don't understand his laws to the fullest.
Thank you for your time - it means alot!
(also if anyone see multi mistakes in my function, then please point them out!)
A:
I am currently working on a project in C# where i play around with planetary gravitation
This is a fun way to learn simulation techniques, programming and physics at the same time.
One thing I cannot figure out is how to get the correct gravitational direction.
I assume that you are not trying to simulate relativistic gravitation. The Earth isn't in orbit around the Sun, the Earth is in orbit around where the sun was eight minutes ago. Correcting for the fact that gravitation is not instantaneous can be difficult. (UPDATE: According to commentary this is incorrect. What do I know; I stopped taking physics after second year Newtonian dynamics and have only the vaguest understanding of tensor calculus.)
You'll do best at this early stage to assume that the gravitational force is instantaneous and that planets are points with all their mass at the center. The gravitational force vector is a straight line from one point to another.
Let's say we have a satellite moving at a speed of 50 m/s ... If we then say that the framerate is one frame per second then after one second the object will be 50 units right and 10 units down.
Let's make that more clear. Force is equal to mass times acceleration. You work out the force between the bodies. You know their masses, so you now know the acceleration of each body. Each body has a position and a velocity. The acceleration changes the velocity. The velocity changes the position. So if the particle starts off having a velocity of 50 m/s to the left and 0 m/s down, and then you apply a force that accelerates it by 10 m/s/s down, then we can work out the change to the velocity, and then the change to the position. As you note, at the end of that second the position and the velocity will have both changed by a huge amount compared to their existing magnitudes.
As the satellite moves multiple units in a frame and about 50% of the radius, the gravitational direcion have shifted alot, during this frame, but the applied force have only been "downwards". this creates a big margin of error, especially if the object is moving a big percentage of the radius.
Correct. The problem is that the frame rate is enormously too low to correctly model the interaction you're describing. You need to be running the simulation so that you're looking at tenths, hundredths or thousanths of seconds if the objects are changing direction that rapidly. The size of the time step is usually called the "delta t" of the simulation, and yours is way too large.
For planetary bodies, what you're doing now is like trying to model the earth by simulating its position every few months and assuming it moves in a straight line in the meanwhile. You need to actually simulate its position every few minutes, not every few months.
In our example we'd probably needed our graviational direction to be based upon the average between our current position and the position at the end of this frame.
You could do that but it would be easier to simply decrease the "delta t" for the computation. Then the difference between the directions at the beginning and the end of the frame is much smaller.
Once you've got that sorted out then there are more techniques you can use. For example, you could detect when the position changes too much between frames and go back and redo the computations with a smaller time step. If the positions change hardly at all then increase the time step.
Once you've got that sorted, there are lots of more advanced techniques you can use in physics simulations, but I would start by getting basic time stepping really solid first. The more advanced techniques are essentially variations on your idea of "do a smarter interpolation of the change over the time step" -- you are on the right track here, but you should walk before you run.
A:
I'll start with a technique that is almost as simple as the Euler-Cromer integration you've been using but is markedly more accurate. This is the leapfrog technique. The idea is very simple: position and velocity are kept at half time steps from one another.
The initial state has position and velocity at time t0. To get that half step offset, you'll need a special case for the very first step, where velocity is advanced half a time step using the acceleration at the start of the interval and then position is advanced by a full step. After this first time special case, the code works just like your Euler-Cromer integrator.
In pseudo code, the algorithm looks like
void calculate_accel (orbiting_body_collection, central_body) {
foreach (orbiting_body : orbiting_body_collection) {
delta_pos = central_body.pos - orbiting_body.pos;
orbiting_body.acc =
(central_body.mu / pow(delta_pos.magnitude(),3)) * delta_pos;
}
}
void leapfrog_step (orbiting_body_collection, central_body, delta_t) {
static bool initialized = false;
calculate_accel (orbiting_body_collection, central_body);
if (! initialized) {
initialized = true;
foreach orbiting_body {
orbiting_body.vel += orbiting_body.acc*delta_t/2.0;
orbiting_body.pos += orbiting_body.vel*delta_t;
}
}
else {
foreach orbiting_body {
orbiting_body.vel += orbiting_body.acc*delta_t;
orbiting_body.pos += orbiting_body.vel*delta_t;
}
}
}
Note that I've added acceleration as a field of each orbiting body. This was a temporary step to keep the algorithm similar to yours. Note also that I moved the calculation of acceleration to it's own separate function. That is not a temporary step. It is the first essential step to advancing to even more advanced integration techniques.
The next essential step is to undo that temporary addition of the acceleration. The accelerations properly belong to the integrator, not the body. On the other hand, the calculation of accelerations belongs to the problem space, not the integrator. You might want to add relativistic corrections, or solar radiation pressure, or planet to planet gravitational interactions. The integrator should be unaware of what goes into those accelerations are calculated. The function calculate_accels is a black box called by the integrator.
Different integrators have very different concepts of when accelerations need to be calculated. Some store a history of recent accelerations, some need an additional workspace to compute an average acceleration of some sort. Some do the same with velocities (keep a history, have some velocity workspace). Some more advanced integration techniques use a number of techniques internally, switching from one to another to provide the best balance between accuracy and CPU usage. If you want to simulate the solar system, you need an extremely accurate integrator. (And you need to move far, far away from floats. Even doubles aren't good enough for a high precision solar system integration. With floats, there's not much point going past RK4, and maybe not even leapfrog.)
Properly separating what belongs to whom (the integrator versus the problem space) makes it possible to refine the problem domain (add relativity, etc.) and makes it possible to easily switch integration techniques so you can evaluate one technique versus another.
A:
So i found a solution, it might not be the smartest, but it works, and it's pretty came to mind after reading both Eric's answer and also reading the comment made by marcus, you could say that it's a combination of the two:
This is the new code:
foreach (ExtTerBody OtherObject in UniverseController.CurrentUniverse.ExterTerBodies.Where(x => x != this))
{
double massOther = OtherObject.Mass;
double R = Vector2Math.Distance(Position, OtherObject.Position);
double V = (massOther) / Math.Pow(R,2) * Time.DeltaTime;
float VRmod = (float)Math.Round(V/(R*0.001), 0, MidpointRounding.AwayFromZero);
if(V > R*0.01f)
{
for (int x = 0; x < VRmod; x++)
{
EulerMovement(OtherObject, Time.DeltaTime / VRmod);
}
}
else
EulerMovement(OtherObject, Time.DeltaTime);
}
public void EulerMovement(ExtTerBody OtherObject, float deltaTime)
{
double massOther = OtherObject.Mass;
double R = Vector2Math.Distance(Position, OtherObject.Position);
double V = (massOther) / Math.Pow(R, 2) * deltaTime;
Vector2 NonNormTwo = (OtherObject.Position - Position).Normalized() * V;
Vector2 NonNormDir = Velocity + NonNormTwo;
Velocity = NonNormDir;
//Debug.WriteLine("Velocity=" + Velocity);
Position += Velocity * deltaTime;
}
To explain it:
I came to the conclusion that if the problem was that the satellite had too much velocity in one frame, then why not seperate it into multiple frames? So this is what "it" does now.
When the velocity of the satellite is more than 1% of the current radius, it seperates the calculation into multiple bites, making it more precise.. This will ofcourse lower the framerate when working with high velocities, but it's okay with a project like this.
Different solutions are still very welcome. I might tweak the trigger-amounts, but the most important thing is that it works, then i can worry about making it more smooth!
Thank's everybody that took a look, and everyone who helped be find the conclusion myself! :) It's awesome that people can help like this!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Python Pandas Regex: Search for strings with a wildcard in a column and return matches
I have a search list in a column which may contain a key: 'keyword1*keyword2' to try to find the match in a separate dataframe column. How can I include the regex wildcard type 'keyword1.*keyword2' #using str.extract, extractall or findall?
Using .str.extract works great matching exact substrings but I need it to also match substrings with wildcards in between the keyword.
# dataframe column or series list as keys to search for:
dfKeys = pd.DataFrame()
dfKeys['SearchFor'] = ['this', 'Something', 'Second', 'Keyword1.*Keyword2', 'Stuff', 'One' ]
# col_next_to_SearchFor_col
dfKeys['AdjacentCol'] = ['this other string', 'SomeString Else', 'Second String Player', 'Keyword1 Keyword2', 'More String Stuff', 'One More String Example' ]
# dataframe column to search in:
df1['Description'] = ['Something Here','Second Item 7', 'Something There', 'strng KEYWORD1 moreJARGON 06/0 010 KEYWORD2 andMORE b4END', 'Second Item 7', 'Even More Stuff']]
# I've tried:
df1['Matched'] = df1['Description'].str.extract('(%s)' % '|'.join(key['searchFor']), flags=re.IGNORECASE, expand=False)
I've also tried substituting 'extract' from the code above with both 'extractall' and 'findall' but it still does not give me the results I need.
I expected 'Keyword1*Keyword2' to match "strng KEYWORD1 moreJARGON 06/0 010 KEYWORD2 andMORE b4END"
UPDATE: The '.*' worked!
I'm also trying to add the value from the cell next to the matched key in 'SearchFor' column i.e. dfKeys['AdjacentCol'].
I've tried:
df1['From_AdjacentCol'] = df1['Description'].str.extract('(%s)' % '|'.join(key['searchFor']), flags=re.IGNORECASE, expand=False).map(dfKeys.set_index('SearchFor')['AdjacentCol'].to_dict()).fillna('') which works for everything but the keys with the wildcards.
# expected:
Description Matched From_AdjacentCol
0 'Something Here' 'Something' 'this other string'
1 'Second Item 7' 'Second' 'Second String Player'
2 'Something There' 'Something' 'this other string'
3 'strng KEYWORD1 moreJARGON 06/0 010 KEYWORD2...' 'Keyword1*Keyword2' 'Keyword1 Keyword2'
4 'Second Item 7' 'Second' 'Second String Player'
5 'Even More Stuff' 'Stuff' 'More String Stuff'
Any help with this is much appreciated. thanks!
A:
Solution
You are close to the solution, just change * to .*. Reading the docs:
.
(Dot.) In the default mode, this matches any character except a newline. If the DOTALL flag has been specified, this matches any
character including a newline.
*
Causes the resulting RE to match 0 or more repetitions of the preceding RE, as many repetitions as are possible. ab* will match ‘a’,
‘ab’, or ‘a’ followed by any number of ‘b’s.
In Regular Expression star symbol * alone means nothing. It has a different meaning than the usual glob operator * in Unix/Windows file systems.
Star symbol is a quantifier (namely the gready quantifier), it must be associated to some pattern (here . to match any character) to mean something.
MCVE
Reshaping your MCVE:
import re
import pandas as pd
keys = ['this', 'Something', 'Second', 'Keyword1.*Keyword2', 'Stuff', 'One' ]
df1 = pd.DataFrame()
df1['Description'] = ['Something Here','Second Item 7', 'Something There',
'strng KEYWORD1 moreJARGON 06/0 010 KEYWORD2 andMORE b4END',
'Second Item 7', 'Even More Stuff']
regstr = '(%s)' % '|'.join(keys)
df1['Matched'] = df1['Description'].str.extract(regstr, flags=re.IGNORECASE, expand=False)
The regexp is now:
(this|Something|Second|Keyword1.*Keyword2|Stuff|One)
And matches the missing case:
Description Matched
0 Something Here Something
1 Second Item 7 Second
2 Something There Something
3 strng KEYWORD1 moreJARGON 06/0 010 KEYWORD2 an... KEYWORD1 moreJARGON 06/0 010 KEYWORD2
4 Second Item 7 Second
5 Even More Stuff Stuff
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to delete extra lines in WPF DataGrid?
Does somebody know how to delete these lines in the last non-existing column in the WPF DataGrid? And also how to remove the last extra row?
Here is my xaml:
<WindowChrome.WindowChrome>
<WindowChrome CaptionHeight="30" />
</WindowChrome.WindowChrome>
<Border BorderBrush="#FF333333" BorderThickness="1">
<DataGrid Name="ParametersConfigGrid"
AutoGenerateColumns="False"
Loaded="ParametersConfigGrid_OnLoaded">
<DataGrid.Columns>
<DataGridTextColumn Header="Order" Binding="{Binding Order}" />
<DataGridTextColumn Header="Parameter Name" Binding="{Binding ParameterName}" />
<DataGridTextColumn Header="Designation" Binding="{Binding Designation}" />
</DataGrid.Columns>
</DataGrid>
</Border>
Thanks!
A:
To get rid of the last row, in your DataGrid set the CanUserAddRows property to False:
<DataGrid Name="ParametersConfigGrid"
AutoGenerateColumns="False"
Loaded="ParametersConfigGrid_OnLoaded"
CanUserAddRows="False">
To get rid of the lines that extend past your columns, use a row style. You can just put the style into your Window Resources.
<Style TargetType="{x:Type DataGridRow}" BasedOn="{StaticResource {x:Type DataGridRow}}">
<Setter Property="BorderThickness" Value="0" />
</Style>
You may need to add a style for the cells if you want borders on cells. You would do it in a very similar way as for the row.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
In the Pound Rebka Experiment, how were the gamma rays generated?
Lest my question be dismissed as poorly-worded, let me first say that I do understand the concept of how a gamma ray is emitted when an electron in an excited (higher energy) state transitions to a lower state. Also, I'm aware that they used $^{57}\text{Fe}$ as its photon energy (and thus gamma ray frequency) were/are well-known to an accurate value.
I've read the Wikipedia page and this Physics SE question/answer, but I still can't figure out...
How did they get the $^{57}\text{Fe}$ electrons all excited to begin with?
Certainly the electrons in the iron samples don't maintain their excited state unless one keeps adding some external energy, correct?
Related side question: How difficult was it to get "enriched" $^{57}\text{Fe}$? And, just how well-enriched were the samples?
Facetious side-question: How loud could one hear the rumbling bass notes across the Harvard Campus while Dr. Pound and his student were running the experiment? :)
A:
The photons in question were not atomic photons derived from relaxing an excitation of the electronic states of the atom. They were nuclear photons derived relaxing an excited nuclear states. The excited state of Fe-57 is generated by the electron-capture decay of Cobalt-57
Colbalt-57 can be produced in quantities sufficient for use in this kind of experiment by putting a sample containing Cobalt-56 in a environment with high neutron flux such as near an operating nuclear reactor or a intense neutron source. Co-57 has a half life around nine months so it is well suited to this kind of application (long enough for the rate to be treated as constant over a few days, but short enough to get significant rate).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What does the maxJsonLength property refer to?
In a web forms project, I am loading a jqGrid using a SQL stored procedure where I return the data as json. During initial setup and testing, I was returning 85 rows of data. I then changed the parameters which caused 1,868 rows to be returned, except it was not displaying in the grid.
Upon debugging in Firebug, I saw the error "The length of the string exceeds the value set on the maxJsonLength property". I fixed it by setting the maxJsonLength="2147483647" in my webconfig as found in a popular Stackovrflow post.
So my question is what was the string that caused the error? Is it the length of the whole data record, or the length of the data in one of the columns returned?
I've seen examples of the jqGrid returning much more data. Thanks for any insight.
Update
I took Olegs advice and used Nuget to install Newtonsoft.Json in my project. I then made changes to my code to use it:
In the codebehind - .cs I have this:
using Newtonsoft.Json;
public partial class Default2 : System.Web.UI.Page
{
[WebMethod]
public static string GetDataFromDB()
{
DataSet ds = new DataSet();
string con = System.Configuration.ConfigurationManager.ConnectionStrings["SQLCon"].ToString();
SqlConnection SCon = new SqlConnection(con);
SCon.Open();
SqlCommand sqlCmd = new SqlCommand("dbo.usp_GetProjectDetails", SCon);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.Add("@ProjNum", SqlDbType.Int).Value = DBNull.Value;
sqlCmd.Parameters.Add("@TrakIt", SqlDbType.VarChar, 255).Value = DBNull.Value;
sqlCmd.Parameters.Add("@Title", SqlDbType.VarChar, 255).Value = DBNull.Value;
sqlCmd.Parameters.Add("@Status", SqlDbType.VarChar, 255).Value = DBNull.Value;
sqlCmd.Parameters.Add("@Dept", SqlDbType.Int).Value = DBNull.Value;
sqlCmd.Parameters.Add("@AssignTo", SqlDbType.Int).Value = DBNull.Value; //19;
sqlCmd.Parameters.Add("@RecDate", SqlDbType.DateTime).Value = DBNull.Value;
sqlCmd.Parameters.Add("@CmpDate", SqlDbType.DateTime).Value = DBNull.Value;
sqlCmd.Parameters.Add("@EndDate", SqlDbType.DateTime).Value = DBNull.Value;
sqlCmd.Parameters.Add("@ExComp", SqlDbType.Int).Value = DBNull.Value;
sqlCmd.Parameters.Add("@ExAcReq", SqlDbType.Int).Value = DBNull.Value;
SqlDataAdapter da = new SqlDataAdapter(sqlCmd);
da.Fill(ds);
SCon.Close();
return JsonConvert.SerializeObject(ds.Tables[0]);
}
The function in .aspx looks like this:
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json",
data: "{}",
url: "Default2.aspx/GetDataFromDB",
dataType: "json",
success: function (data) {
data = data.d;
$("#list1").jqGrid({
datatype: "local",
colNames: ["Project #", "Trak-It #", "Priority", "Title", "Status", "Department", "Assigned To", "Resource", "Requestor"],
colModel: [
{ name: 'Project Number', index: 'Project Number', width: 80, key: true, formatter: 'showlink', formatoptions: { baseLinkUrl: 'Details.aspx', target: '_new' } },
{ name: 'Trak-It #', index: 'Trak-It #', width: 80 },
{ name: 'Priority', index: 'Priority', width: 80 },
{ name: 'Title', index: 'Title', width: 200 },
{ name: 'Status', index: 'Status', width: 80 },
{ name: 'Department', index: 'Department', width: 180 },
{ name: 'Assigned To', index: 'Assigned To', width: 100 },
{ name: 'Resource', index: 'Resource', width: 160 },
{ name: 'Requestor', index: 'Requestor', width: 140 }
],
data: JSON.parse(data),
rowNum: 8,
rowList: [10, 20, 30],
pager: '#pager1',
caption: "Test Grid",
viewrecords: true,
ignoreCase: true,
async: true,
loadonce: true,
gridview: true,
width: 1000
});
}
});
});
</script>
And finally in Web.config, I commented out the maxjsonLength:
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="2147483647">
</jsonSerialization>
</webServices>
</scripting>
But I still get the error = "Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property."
If I uncomment the web.config settings, it works just fine. If I leave it commented out and bring back less data, it works fine. What am I missing?
A:
You mean probably System.Web.Script.Serialization.JavaScriptSerializer.MaxJsonLength property which need be increased globally if you use WebServices interface in the server code. The solution was described in the answer for example.
You ask about the background information of the problem. To tell the truth the main problem is that usage of very old WebService interface in ASP.NET applications. It was the first attempt by Microsoft, many years ago, to return XML or JSON data based on Content-Type header of HTTP request. It was implemented in .NET Framework 3.5. The web service should return object (not a string) which will be serialized by .NET framework to JSON string by usage of JavaScriptSerializer. Your code don't uses JavaScriptSerializer directly. Because you don't use JavaScriptSerializer directly, you can configure parameters of JavaScriptSerializer only in web.config.
In other words, you have to use MaxJsonLength settings of JavaScriptSerializer in web.config every time if the size of returned data could be larger as about 100k.
The restriction 100k for web method was relatively large 8 years ago (at 2007) at the time of publishing .NET Framework 3.5. Later Microsoft introduced WCF interface which made JSON serialization more quickly, and have not so small restriction. WCF is of case too old now too, but it allows still to make manual serialization using more performance version of JSON serializer (see the answer for example). After WCF Microsoft introduced ASP.NET MVC and then WebAPI. Now Microsoft works on ASP.NET 5 and MVC version 6, which combine MVC and WebAPI under one name MVC6. Starting with MVC2 (or MVC3) Microsoft stopped to develop own JSON serializer and suggested to use some other one. Microsoft use mostly Newtonsoft.Json (synonyme of Json.NET), which is not the most quick one, but relatively good and powefull.
I don't want to write too much too common things, but I would recommend you to go away from reto style of usage WebServices and go to some other interface which gives you more flefibility in choosing of JSON serializer. If you support some old code and can't use more modern technologies then I would recommend you to use ASHX handle, which are very old, but much more flexible as WebServices. I recommend you to look in the old answer, where I attached Visual Studio Project which used ASHX handle and return JSON data using Newtonsoft.Json (Json.NET). You can replace Newtonsoft.Json to any other JSON serializer class which you more like.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Adding elements of a matrix in R
I have two matrices as follows:
loweredge
[,1] [,2] [,3]
[1,] -32.5 87.5 207.5
SectorAzimuth
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 10.83 21.66 32.5 43.33 54.16 65
I wish to add all 6 values in SectorAzimuth to the first value of loweredge, then add all 6 values in SectorAzimuth to the second value of loweredge and similarly the same 6 values of SectorAzimuth to the 3rd value of loweredge.
Can anyone give me some pointers please?
A:
You can try
loweredge <- matrix(c(-32.5, 87.5, 207.5), nrow = 1)
SectorAzimuth <- matrix(c(10.83, 21.66, 32.5, 43.33, 54.16, 65), nrow = 1)
apply(loweredge, MARGIN = 2, FUN = `+`, y = SectorAzimuth)
[,1] [,2] [,3]
[1,] -21.67 98.33 218.33
[2,] -10.84 109.16 229.16
[3,] 0.00 120.00 240.00
[4,] 10.83 130.83 250.83
[5,] 21.66 141.66 261.66
[6,] 32.50 152.50 272.50
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Azure custom domain name
when I create a new custom domain for a site on Azure, does it check if the name is already been used.
The host name is in the form myhostName.azurewebsites.net.
Does Azure check if the myhostName name has been already used?
A:
Yes, you can't create website with name which has already been taken, you will see this:
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Two sections are on top of each other
The landing page and founders section are on top of each other. when I tried to add the founders section, it just messed up, here is the codepen URL you can check directly there.
https://codepen.io/anon/pen/BeMyRx
I tried to make position:absolute; and top:1500px; but nothing happened
*{
margin: 0;
padding: 0;
}
body,html{
font-family: sans-serif;
width: 100%;
height:100%;
flex-wrap:wrap;
position: center;
background-image:url(https://cdn.discordapp.com/attachments/508013798544769034/583722034157060096/Untitled-1.png);
background-repeat: no-repeat;
background-size: cover;
}
.section-top{
width: 100%;
height: 100%;
overflow: hidden;
position: relative;
box-sizing: border-box;
}
.content{
position: absolute;
top:50%;
left:50%;
transform: translate(-50% , -50%);
text-align: center;
}
.content h1{
color:#c0392b;
text-transform: uppercase;
}
.content h3{
color:white;
font-size:15px;
font-family: Arial;
}
.content a{
background:#e74c3c;
padding: 10px 24px;
color: white;
text-decoration: none;
font-size:18px;
border-radius:20px;
text-transform: uppercase;
}
.testimonial-section{
background: #3498db;
padding: 40px 0;
}
.inner-width{
max-width: 1200px;
margin: auto;
padding: 0 20px;
}
.testimonial-section h1{
text-align: center;
color: #333;
font-size: 24px;
}
.border{
width: 100px;
height: 3px;
background: #333;
margin: 40px auto;
}
.testimonial{
background: #f1f1f1;
padding: 40px;
overflow: hidden;
border-radius: 8px;
cursor: pointer;
}
.test-info{
display: flex;
height: 60px;
align-items: center;
}
.test-pic{
width: 50px !important;
border-radius: 50%;
margin-right: 15px;
}
.test-name{
font-size: 12px;
color: #333;
}
.test-name span{
display: block;
font-size: 14px;
font-weight: 700;
color: #3498db;
}
.testimonial p{
font-size: 12px;
line-height: 22px;
margin-top: 20px;
}
It's expected that the landing page should be on the top of the website, then the founders section should be next.
A:
in the HTML code, you wrote "secton-top" instead of "section-top" in your class property.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Kohana routing - subfolders
Hy.
I have 2 controllers, the first one application/classes/controller/welcome.php and the second one application/classes/controller/admin/welcome.php.
And I have the following routings, set in bootstrap.php
Route::set('admin', '(<directory>(/<controller>(/<action>(/<id>))))', array('directory' => '(admin)'))
->defaults(array(
'directory' => 'admin',
'controller' => 'welcome',
'action' => 'index',
));
Route::set('default', '(<controller>(/<action>(/<id>)))')
->defaults(array(
'controller' => 'welcome',
'action' => 'index',
));
If I access example.com/welcome it calls index action from the application/classes/controller/welcome.php controller (this is good),
if I access example.com/admin/welcome it calls index action from application/classes/controller/admin/welcome.php controller (this is good),
but if I access simply example.com, it calls the admin's welcome and not the other one, and I can't understand why.
I want this: if I access example.com, then call index action from application/classes/controller/admin/welcome.php controller.
How can I solve this?
A:
It looks like you've set the directory tag in the first route to be optional, and so it's matching when no directory is specified. Try:
Route::set('admin', '<directory>(/<controller>(/<action>(/<id>)))', array('directory' => '(admin)'))
->defaults(array(
'directory' => 'admin',
'controller' => 'welcome',
'action' => 'index',
));
This should make the tag mandatory, and so it won't match on /.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to group values over different columns
I have the following data frame:
df =
ID HOUR GROUP_1 GROUP_2 GROUP_3 DURATION
1 7 AAA AAA BBB 20
2 7 BBB AAA CCC 22
3 7 BBB BBB BBB 21
4 8 AAA AAA AAA 23
5 8 CCC AAA CCC 25
6 9 CCC CCC CCC 28
I can calculate average DURATION per HOUR as follows:
grouped = df.groupby("HOUR").DURATION.mean().reset_index()
Now I need to also group the entried by group values stored in GROUP_1, GROUP_2 and GROUP_3. I want to consider the occurance of a group only once per row, i.e. if AAA is repeated two times in the first row, it should be considered only once.
The result should be:
result =
GROUP HOUR MEAN_DURATION
AAA 7 21
AAA 8 24
BBB 7 21
...
I know how to count the occurance of each group per row, but don't know how to put everything together to get the expected result:
df.filter(regex="^GROUP").stack().reset_index(level=1, drop=True).reset_index().drop_duplicates()[0].value_counts()
A:
You can transform your group variables to one column, drop duplicated groups in each row and then group by hour and group to take the mean:
(pd.melt(df, id_vars=['ID', 'HOUR', 'DURATION'], value_name='GROUP')
.drop('variable', axis=1).drop_duplicates()
.groupby(['HOUR', 'GROUP']).DURATION.mean()
.reset_index())
|
{
"pile_set_name": "StackExchange"
}
|
Q:
RDLC footer and dynamic visibility
tldr; Hide the left UI component on the footer and the right component moves over to the center.
I have a .rdlc file that I'm modifying in Visual Studio 2010 (and, sometimes, in Notepad++, as well). This particular report has a footer with two text boxes. The left side textbox contains information that is only sometimes relevant. When it is not relevant, it gets hidden. The right side textbox contains a page number.
So long as the left textbox is visible, everything is fine. However, when I hide the left textbox, the resulting output has the right textbox shifted over to the middle.
I don't want my page number shifted to the middle. How do I prevent this? I tried handling it with a table stretched all across the footer, but the footer apparently won't allow a table to be contained.
A:
Apparently, nobody has any better ideas, so I'm going to say that my comment above is the answer:
"I ended up just creating a duplicate textbox to the one I was hiding and showing it when the original was hidden. This new one just contains a bunch of spaces rather than text. Kludgy, but it worked."
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Equivalent of fseek and ftell in main
I would like to know if there is an equivalent of fseek and ftell when I'm working in main.
For example, if I type the name of a file when asked, at end I hit enter. Next I'll ask the user another file name, but there's a '\n' in the buffer that was not read. The user won't be able to type the name of the second file because the program will read the '\n'. So I would like to move one position forward in the buffer. Normally in a file I would do:
fseek(file, ftell + 1, SEEK_SET);
I would like to do the same thing when I'm in main, not working with a file.
A:
Actually, it is possible to use fseek in main, you just have to set FILE * stream to stdin, so it would be:
fseek(stdin, ftell - 1, SEEK_SET);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using itextsharp to set ocg state of existing pdf
I have spent several hours researching this and can't seem to locate the answer.
I have downloaded and referenced itextsharp in my wpf .net application. (VB)
What I am doing is needing to turn off a specific layer (ocg object) in an exisiting .pdf that was created in Autocad that is defaulted on.
I have successfully opened and displayed the .pdf but i can't seem to use the setOCGstate control correctly
pdf name is "random.pdf"
layer name that i can see once i open the .pdf is "Option 1"
where im getting stuck is i know the layer names are stored in an array inside the .pdf. i know the name of the layer i am trying to turn off, so how do i reference that layer and turn it off using the setocgstate.
example code
dim doc1 as New PdfReader("random.pdf")
PdfAction.SetOCGstate ("confused", False)
A:
I've created an example that turns off the visibility of a specific layer. See ChangeOCG
The concept is really simple. You already have a PdfReader object and you want to apply a change to a file. As documented, you create a PdfStamper object. As you want to change an OCG layer, you use the getPdfLayers() method and you select the layer you want to change by name. (In my example, the layer I want to turn off is named "Nested layer 1"). You use the setOn() method to change its status, and you're done:
PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
Map<String, PdfLayer> layers = stamper.getPdfLayers();
PdfLayer layer = layers.get("Nested layer 1");
layer.setOn(false);
stamper.close();
reader.close();
This is Java code. Please read it as if it were pseudo-code and adapt it to your language of choice.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
personal cloud storage and microsoft teams
I am using Microsoft teams to share my files with my colleagues. I also have a personal could storage based on the Seafile application.
I would like to find a way to synchronize my files on Microsoft teams and my folder using my personal cloud.
Is it possible to do it without using a predefined cloud storage proposed by Microsoft teams (one drive, dropbox, google drive ...) and without creating an account on my server for my colleagues ?
A:
Currently this is not possible. Teams have predefined cloud storage which is supported.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
objective-c passing parameters to a view
I'm doing an app for study that from an introview go to another view throught 4 custom buttons.
to each button is bind an url that is èpassed as parameter to the segue that go to the other view, were there is a webview that displays the given url.
everything is working, but there is a strange bug:
the first time I touch each of the button in the first view a null value is passed to the other view
all the other times, everyting works fine...
this is the code:
///this is the action linked to the buttons
- (IBAction)go:(id)sender
{
[self performSegueWithIdentifier:@"MySegue" sender:sender];
if (sender==btnImg1){
linkz = linkUrl1;
}else if (sender==btnImg2){
linkz = linkUrl2;
}else if (sender==btnImg3){
linkz = linkUrl3;
}else if (sender==btnImg4){
linkz = linkUrl4;
}
NSLog(@"msg: %@", linkz);
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:@"MySegue"]) {
// Get the destination view
SecondView *og = [segue destinationViewController];
// Set the selected vaue in the new view
[og setNavigationUrl:linkz];
}
}
any ideas why this happens?
A:
You should set linkz before calling [self performSegueWithIdentifier:].
|
{
"pile_set_name": "StackExchange"
}
|
Q:
HTML5 Boilerplate Build Script - .htaccess doesn't exist
I thought I'd try out the Build Script for HTML5 Boilerplate - it's aimed at front-end designers and developers so this should be fairly straightforward right?
I'm running with a Mac so I should have all I need according to Paul.
Tried it on a blank project and immediately hit a brick wall.
I ran the cd build command, pointing it to my local folder
Then I ran ant build. It seemed to go OK, with a load of jibberish about how it was Building a Production environment but got stuck when looking for the htaccess file...
BUILD FAILED
/Users/jaygeorge/Dropbox/Websites/Clients/HTML-Sandbox/build/build.xml:137:
The following error occurred while
executing this line:
/Users/jaygeorge/Dropbox/Websites/Clients/HTML-Sandbox/build/build.xml:673:
Replace: source file
/Users/jaygeorge/Dropbox/Websites/Clients/HTML-Sandbox/publish/.htaccess
doesn't exist
Well of course the .htaccess file doesn't exist because it didn't come with the Boilerplate download. Do I need to download the htaccess file from my website so that it sits locally? I don't really understand this stuff - Was hoping Paul Irish would make his instructions more comprehensive :-(.
A:
There should be an .htaccess file in the root folder of the ZIP file you downloaded. Note that you may have to turn on 'view hidden files' or similar in your File Explorer to see it.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is it really necessary to close questions based on it being subjective and argumentative regarding parenting?
I was just amazed to see that a question got closed, on the grounds that it is subjective and argumentative. If this is really the case, you might just close the complete site. If anything in life is subjective and argumentative, it is parenting.
First of all I disagree with the closers of the subject. There are objective arguments for immunization, I haven't seen any argument against general immunization being backed up by data.
But more general, the closing of this question really made me pessimistic about the onset of this Stack Exchange site. If being argumentative and subjectivity is an issue, just close the site. Just another example. The question on when you should allow your children to drink wine, would lead to interesting contradicting answers. Is it argumentative or subjective, sure? But still it is a legit question. It just shows that there is no general answer to a parenting question.
You might change the name in American Parenting and create a single SE for every cultural background.
A:
I don't think that question is neither subjective nor argumentative.
It's possibly off-topic though. "What is the proof for scientific claim X" isn't really a parenting question, and indeed I saw a very similar question on skeptics.SE.
But I can see other questions being subjective and argumentative in a different way from parenting questions in general. Like "What is the best lullaby to get my kid to sleep", and "Why should you co-sleep? It's stupid!" being hypothetical examples of subjective and argumentative questions respectively. :)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Roaming profiles on OS X 10.7 Lion Server
Is there a way to store user data like documents folder deskstop folder pictures etc on the server? If not how can a user access their files from a different computer on the network?
A:
The Mac equivalent of roaming folders are Portable Home Folders, which are an extension of Network Home folders. You would need to use Workgroup Manager to configure them, as the required bits of GUI sit outside Server.app. The Snow Leopard documentation for this feature is pretty much still applicable.
Check out chapters 7 & 8 of the User Management guide (PDF)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Are questions about RPG design on topic?
Should questions that ask for help in designing an RPG game, or specific mechanics for an RPG game, be allowed?
A:
Yes; definitely. As long as they are well scoped questions given other site parameters.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is the mechanism for the reaction of acetyl chloride and aniline?
I want to devise the synthesis of 1,2-dinitrobenzene without producing a large amount of 1,3 or 1,4 products.
In my synthesis I have a step in which I obtain aniline. I would like to know the mechanism for protecting the amine using $\ce{CH3COCl}$ and triethylamine so I can keep it from reacting in the next step of my synthesis. I'm not really "fluent" with amine chemistry, and I have no good idea at the moment.
If you cannot make picture of mechanism, please explain it with words. I must understand!
A:
The mechanism is just a regular nucleophilic attack of an amine on a carbonyl, with the triethylamine just there to pick up any loose protons at the end of the reaction.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is known about the sum x^{n^2}/n?
It follows from a general theorem of Honda that the formal group with the logarithm
$$
x+x^{2^s}/2+x^{3^s}/3+x^{4^s}/4+\cdots
$$
has integer coefficients. I became interested in it because its $p$-typizations give the formal groups of the $s$th Morava K-theories (after reducing modulo $p$).
In particular I wonder whether the series
$$
\sum_{n\geqslant1}\frac{x^{n^2}}n
$$
which one obtains for $s=2$ is related in any way to modular forms and elliptic curves.
Does anybody know where to find information about this?
P.S. - Decided to add a picture: here is the color-coded modulus of the derivative of the above series as a function of a complex variable $x$ in the unit disk, where its ``modular-like'' behavior is especially apparent.
P.P.S. - ...and for some further suspense, here are the first few terms of the formal group itself. Notation: $s$ is the sum of the two variables and $p$ is their product. Note the reappearing factors.
\begin{align*}
s\\
-p&(2s^2-p)\\
+2s^3p&(2s^2-p)\\
-sp&(3s^6-9s^4p+10s^2p^2-3p^3)\\
-s^2p&(2s^2-p)(4s^4+6s^2p-3p^2)\\
+s^4p&(12s^6-21s^4p+20s^2p^2-6p^3)\\
+2sp&(2s^2-p)(4s^8+18s^6p-5s^4p^2-4s^2p^3+p^4)\\
-2s^3p&(18s^{10}+18s^8p-67s^6p^2+87s^4p^3-48s^2p^4+9p^5)\\
-s^2p&(36s^{12}+246s^{10}p+72s^8p^2-493s^6p^3+356s^4p^4-106s^2p^5+12p^6)\\
+3s^9p&(3s^6-9s^4p+10s^2p^2-3p^3)\\
+...
\end{align*}
A:
The following answer is not really satisfactory for me; however it seems to be the analog of current results on similar phenomena like partial, mock and quantum modular forms, so I decided to post it here in hope that somebody will contribute further improvements.
Using help from another question I posted later on, I can now claim this:
let $\tilde\theta(\tau):=\sum_{n\geqslant1}ne^{n^2\pi i\tau}$ be (up to a constant) the derivative wrt $\tau$ of the series in question with $x=e^{\pi i\tau}$; then in the upper half-plane,
$$
\tilde\theta(-1/\tau)=(i\tau)^\frac32\tilde\theta(\tau)-\frac{i\tau}\pi\int\limits_0^\infty t\coth(\sqrt{\pi i\tau}t)e^{-t^2}dt.
$$
The last term must be closely related to the Mordell integral; for large $z=i\tau/\pi$ its asymptotic behavior is given by the (divergent) series
$$
\sum_{n\ge0}\frac{B_{2n}}{2n!}z^{1-n}=\frac z2+\frac1{12}-\frac1{120z}+\frac1{504z^2}-\frac1{1440z^3}+\frac1{3168z^4}-\frac{691}{3931200z^5}+...
$$
which somehow explains the near-modular features of $\tilde\theta$. I think I will post a followup question to clarify relationship with some recent work mentioned by @rlo in a comment above.
Another thing I do not understand well: it seems that I cannot extend the first equality analytically simultaneously to both branches of the square root.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
taring vmdk files does not preserve thinness
we have NFS storage, where we store our backups.. we manipulate with them from linux machine where the nfs is also mounted..
So, for example thin provisioned thin.vmdk disk is on linux seen as thin.vmdk and thin-flat.vmdk. We want to archive and compress them with tar and gzip, however when issuing simple tar command on those two.. the thin just dissappears and everythnig is suddenly 10G.
Even when I try to tar the thin-flat.vmdk, which has 1.6G, separately (with "tar cf thin.tar thin-flat.vmdk") it makes 10G tar file. This also happened when the I tried to run tar cf /extfs/thin.tar to create the tar on ext fs.
What kind of sorcery is this? Does anybody have a clue?
Thanks a lot.
A:
GNU tar, which you should have if you're using Linux, supports handling sparse files with the -S (or --sparse) option. Try
tar cSf thin.tar thin-flat.vmdk
A:
From the GNU tar(1) man page:
-S, --sparse
handle sparse files efficiently
A:
You should tell tar to treat sparse files efficiently with the -S --sparse command line switch.
-S, --sparse
handle sparse files efficiently
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Declare variable of composite type in PostgreSQL using %TYPE
Question: How can I declare a variable of the same type a parameter in a stored function?
The simple answer is use %TYPE, this works:
CREATE OR REPLACE FUNCTION test_function_1(param1 text)
RETURNS integer AS
$BODY$
DECLARE
myVariable param1%TYPE;
BEGIN
return 1;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
But the problem is when param1 is a composite type:
CREATE TYPE comp_type as
(
field1 text
)
CREATE OR REPLACE FUNCTION test_function_2(param1 comp_type)
RETURNS integer AS
$BODY$
DECLARE
myVariable param1%TYPE;
BEGIN
return 1;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
This doesn't work:
ERROR: type comp_type does not exist [SQL State=42704]
So how can I do when param1 is a composite type?
(Note: Just myVariable comp_type is not a good option because my function is slightly more complex.)
Edited:
I had a mistake on copy&paste, the real error is:
ERROR: invalid type name "param1%TYPE"
Position: 130 [SQL State=42601]
And using param1%ROWTYPE the error is:
ERROR: relation "param1" does not exist
Where: compilation of PL/pgSQL function "test_function_2" near line 3 [SQL State=42P01]
A:
Use %ROWTYPE in that case.
Edit - simple case
Tests by A.H. and DavidEG have shown this won't work. Interesting problem!
You could try a workaround. As long as your definition is like the example you can simply resort to
CREATE FUNCTION test(param1 comp_type)
RETURNS integer AS
$BODY$
DECLARE
myvar comp_type;
BEGIN
return 1;
END;
$BODY$
LANGUAGE plpgsql VOLATILE;
But your real problem is probably not as simple as that?
Edit 2 - the real problem
As expected, the real problem is more complex: a polymorphic input type.
Workaround for that scenario was harder, but should work flawlessly:
CREATE FUNCTION test(param1 anyelement, OUT a integer, OUT myvar anyelement)
RETURNS record AS
$BODY$
BEGIN
myvar := $1; -- myvar has now the required type.
--- do stuff with myvar.
myvar := NULL; -- reset if you don't want to output ..
a := 1;
END;
$BODY$
LANGUAGE plpgsql VOLATILE;
Call:
SELECT a FROM test('("foo")'::comp_type); -- just retrieve a, ignore myvar
See full output:
SELECT * FROM test('("foo")'::comp_type);
Note for PostgreSQL 9.0+
There has been a crucial update in v9.0. I quote the release notes:
Allow input parameters to be assigned values within PL/pgSQL functions
(Steve Prentice)
Formerly, input parameters were treated as being declared CONST, so
the function's code could not change their values. This restriction
has been removed to simplify porting of functions from other DBMSes
that do not impose the equivalent restriction. An input parameter now
acts like a local variable initialized to the passed-in value.
Ergo, in addition to my workaround, you can utilize input variables directly.
Dynamic Filed names
How to clone a RECORD in PostgreSQL
How to set value of composite variable field using dynamic SQL
|
{
"pile_set_name": "StackExchange"
}
|
Q:
¿Cómo solucionó este error PHP: move_uploaded_file() failed to open stream: No such file or directory?
Estoy intentando subir un archivo a mi directorio por medio de html y lo manipulo desde el servidor con php de tal forma de que quede guardado en el directorio que yo le indique, pero no he podido, el archivo me llega y cuándo lo intento de la manera en que me lo indica la pagina, pero no funciona, me salta este error:
Warning: move_uploaded_file(/Jomar/induccion/documents/mision, vision/OBJETIVOS JOMAR INVERSIONES SAS 2019.pdf): failed to open stream: No such file or directory in C:\xampp\htdocs\Jomar\induccion\controllers\UploadFiles.php on line 9
Warning: move_uploaded_file(): Unable to move 'C:\xampp\tmp\php32BA.tmp' to '/Jomar/induccion/documents/mision, vision/OBJETIVOS JOMAR INVERSIONES SAS 2019.pdf' in C:\xampp\htdocs\Jomar\induccion\controllers\UploadFiles.php on line 9
Este es el código php:
<?php
require_once "../controllers/FilesController.php";
$dir = "/Jomar/induccion/documents/";
print_r($_FILES);
if($_FILES["mision_vision"] != null){
$fichero = "{$dir}mision, vision/".basename($_FILES["mision_vision"]["name"]);
FilesController::deleteFiles($dir."mision, vision/");
if(move_uploaded_file($_FILES["mision_vision"]["tmp_name"], $fichero)){
echo "Subido correctamente";
}else{
echo "Error al intentar subir";
}
}
?>
Captura de los directorios:
La respuesta al hacer var_dump y el [error]
array(1) {
["mision_vision"]=>
array(5) {
["name"]=>
string(40) "OBJETIVOS JOMAR INVERSIONES SAS 2019.pdf"
["type"]=>
string(15) "application/pdf"
["tmp_name"]=>
string(23) "C:\xampp\tmp\php303.tmp"
["error"]=>
int(0)
["size"]=>
int(207419)
}
}
Error al intentar subir: 0
ACTUALIZACIÓN
<?php
require_once "../controllers/FilesController.php";
define ('SITE_ROOT', realpath(dirname(__FILE__)));
$dir = "/Jomar/induccion/documents/";
print_r($_FILES);
if(isset($_FILES["mision_vision"]) && $_FILES["mision_vision"] != null){
$fichero = SITE_ROOT."{$dir}".basename($_FILES["mision_vision"]["name"]);
FilesController::deleteFiles($dir."mision, vision/");
if(move_uploaded_file($_FILES["mision_vision"]["tmp_name"], $fichero)){
echo "Subido correctamente";
}else{
echo "Error al intentar subir";
}
}
?>
A:
Resuelto, lo que hice para resolver el problema fue poner $_SERVER["DOCUMENT_ROOT"], después de buscar exhaustivamente llegué a la respuesta desde este foro (está en inglés) de igual manera muestro la forma en la que lo apliqué para solucionar mi problema.
$dir = "/Jomar/induccion/documents/";
if(isset($_FILES["mision_vision"]) && $_FILES["mision_vision"] != null){
$fichero = $_SERVER['DOCUMENT_ROOT']."{$dir}mision, vision/";
if(FilesController::deleteFiles($fichero)){
if(move_uploaded_file($_FILES["mision_vision"]["tmp_name"], $fichero.basename($_FILES["mision_vision"]["name"]))){
echo "Subido correctamente";
}else{
echo "Error al intentar subir";
}
}
}
Gracias a @A. Cedano por su ayuda, espero que a alguien también le sirva.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Css and JS image zoom on scroll top
I found this really cool app and it has a few features that I can't figure out.
One in particular is the image zoom on scroll up so that you don't see "behind" the app. I included a video demo here
I don't know if they have the image set to the background, or if the image is in another container. I am talking about the top picture of Batman.
I'm new to js and haven't been able to see any solutions that would point me in the right direction!
Thanks everyone!
A:
They are probably building into how far you've scrolled down the page. For example, you can get the distance the user has scrolled with:
var scrollTop = window.pageYOffset || (document.documentElement || document.body.parentNode || document.body).scrollTop;
If you bound this into the scroll event, like so:
window.addEventListener("scroll", function(){
var scrollTop = window.pageYOffset || (document.documentElement || document.body.parentNode || document.body).scrollTop;
console.log(scrollTop);
}, false)
Then you can alter the size of some image based on how far you've scrolled down. Here's an example of how this could be used to change the size of some image:
window.addEventListener("scroll", function(){
var scrollTop = window.pageYOffset || (document.documentElement || document.body.parentNode || document.body).scrollTop;
image = document.getElementById("theImage");
var dimension = 100 + 400 - Math.min(400,scrollTop) + "%";
image.style.backgroundSize = dimension+" "+dimension;
}, false)
#theImage {
width: 100%;
text-align: center;
background-image: url('http://lorempixel.com/1000/1000/sports/');
background-position: center;
height: 800px;
}
<div id="theImage">
</div>
<h1>Some text</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sed ante elementum, ornare nibh nec, finibus purus. Donec eu hendrerit orci. Vivamus fermentum, quam sed vulputate semper, est orci mollis leo, non pharetra nisi ante sit amet lorem. Nulla condimentum metus vitae nulla fringilla, dapibus dignissim lacus commodo. Etiam tincidunt urna sit amet odio mollis, eget vestibulum odio iaculis. Praesent vel est malesuada, efficitur eros ut, pellentesque metus. In sagittis tincidunt ligula. Donec sit amet ipsum libero. Donec quis dolor ut eros maximus finibus molestie a lorem.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sed ante elementum, ornare nibh nec, finibus purus. Donec eu hendrerit orci. Vivamus fermentum, quam sed vulputate semper, est orci mollis leo, non pharetra nisi ante sit amet lorem. Nulla condimentum metus vitae nulla fringilla, dapibus dignissim lacus commodo. Etiam tincidunt urna sit amet odio mollis, eget vestibulum odio iaculis. Praesent vel est malesuada, efficitur eros ut, pellentesque metus. In sagittis tincidunt ligula. Donec sit amet ipsum libero. Donec quis dolor ut eros maximus finibus molestie a lorem.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sed ante elementum, ornare nibh nec, finibus purus. Donec eu hendrerit orci. Vivamus fermentum, quam sed vulputate semper, est orci mollis leo, non pharetra nisi ante sit amet lorem. Nulla condimentum metus vitae nulla fringilla, dapibus dignissim lacus commodo. Etiam tincidunt urna sit amet odio mollis, eget vestibulum odio iaculis. Praesent vel est malesuada, efficitur eros ut, pellentesque metus. In sagittis tincidunt ligula. Donec sit amet ipsum libero. Donec quis dolor ut eros maximus finibus molestie a lorem.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sed ante elementum, ornare nibh nec, finibus purus. Donec eu hendrerit orci. Vivamus fermentum, quam sed vulputate semper, est orci mollis leo, non pharetra nisi ante sit amet lorem. Nulla condimentum metus vitae nulla fringilla, dapibus dignissim lacus commodo. Etiam tincidunt urna sit amet odio mollis, eget vestibulum odio iaculis. Praesent vel est malesuada, efficitur eros ut, pellentesque metus. In sagittis tincidunt ligula. Donec sit amet ipsum libero. Donec quis dolor ut eros maximus finibus molestie a lorem.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sed ante elementum, ornare nibh nec, finibus purus. Donec eu hendrerit orci. Vivamus fermentum, quam sed vulputate semper, est orci mollis leo, non pharetra nisi ante sit amet lorem. Nulla condimentum metus vitae nulla fringilla, dapibus dignissim lacus commodo. Etiam tincidunt urna sit amet odio mollis, eget vestibulum odio iaculis. Praesent vel est malesuada, efficitur eros ut, pellentesque metus. In sagittis tincidunt ligula. Donec sit amet ipsum libero. Donec quis dolor ut eros maximus finibus molestie a lorem.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sed ante elementum, ornare nibh nec, finibus purus. Donec eu hendrerit orci. Vivamus fermentum, quam sed vulputate semper, est orci mollis leo, non pharetra nisi ante sit amet lorem. Nulla condimentum metus vitae nulla fringilla, dapibus dignissim lacus commodo. Etiam tincidunt urna sit amet odio mollis, eget vestibulum odio iaculis. Praesent vel est malesuada, efficitur eros ut, pellentesque metus. In sagittis tincidunt ligula. Donec sit amet ipsum libero. Donec quis dolor ut eros maximus finibus molestie a lorem.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sed ante elementum, ornare nibh nec, finibus purus. Donec eu hendrerit orci. Vivamus fermentum, quam sed vulputate semper, est orci mollis leo, non pharetra nisi ante sit amet lorem. Nulla condimentum metus vitae nulla fringilla, dapibus dignissim lacus commodo. Etiam tincidunt urna sit amet odio mollis, eget vestibulum odio iaculis. Praesent vel est malesuada, efficitur eros ut, pellentesque metus. In sagittis tincidunt ligula. Donec sit amet ipsum libero. Donec quis dolor ut eros maximus finibus molestie a lorem.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sed ante elementum, ornare nibh nec, finibus purus. Donec eu hendrerit orci. Vivamus fermentum, quam sed vulputate semper, est orci mollis leo, non pharetra nisi ante sit amet lorem. Nulla condimentum metus vitae nulla fringilla, dapibus dignissim lacus commodo. Etiam tincidunt urna sit amet odio mollis, eget vestibulum odio iaculis. Praesent vel est malesuada, efficitur eros ut, pellentesque metus. In sagittis tincidunt ligula. Donec sit amet ipsum libero. Donec quis dolor ut eros maximus finibus molestie a lorem.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sed ante elementum, ornare nibh nec, finibus purus. Donec eu hendrerit orci. Vivamus fermentum, quam sed vulputate semper, est orci mollis leo, non pharetra nisi ante sit amet lorem. Nulla condimentum metus vitae nulla fringilla, dapibus dignissim lacus commodo. Etiam tincidunt urna sit amet odio mollis, eget vestibulum odio iaculis. Praesent vel est malesuada, efficitur eros ut, pellentesque metus. In sagittis tincidunt ligula. Donec sit amet ipsum libero. Donec quis dolor ut eros maximus finibus molestie a lorem.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sed ante elementum, ornare nibh nec, finibus purus. Donec eu hendrerit orci. Vivamus fermentum, quam sed vulputate semper, est orci mollis leo, non pharetra nisi ante sit amet lorem. Nulla condimentum metus vitae nulla fringilla, dapibus dignissim lacus commodo. Etiam tincidunt urna sit amet odio mollis, eget vestibulum odio iaculis. Praesent vel est malesuada, efficitur eros ut, pellentesque metus. In sagittis tincidunt ligula. Donec sit amet ipsum libero. Donec quis dolor ut eros maximus finibus molestie a lorem.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sed ante elementum, ornare nibh nec, finibus purus. Donec eu hendrerit orci. Vivamus fermentum, quam sed vulputate semper, est orci mollis leo, non pharetra nisi ante sit amet lorem. Nulla condimentum metus vitae nulla fringilla, dapibus dignissim lacus commodo. Etiam tincidunt urna sit amet odio mollis, eget vestibulum odio iaculis. Praesent vel est malesuada, efficitur eros ut, pellentesque metus. In sagittis tincidunt ligula. Donec sit amet ipsum libero. Donec quis dolor ut eros maximus finibus molestie a lorem.</p>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Webapp able to work offline !
I have to design an webapp that has the capability of working offline.
So there are many working points that in normal mode work online , connected to a central server.
Now there are moments when for different reasons , the central server might not be available.
(no internet ,server crash etc) so then is needed to enter in offline work mode.
Is not required to work fully just to do some work because clients should not wait , so invoicing should be possible (concrete case).
A custom solution I already have in mind but I am wondering if you know a framework or something that does such things already.
Thank you !
A:
We wrote a desktop app for hundreds of employees to use on their laptops. It used database replication to merge the data from the laptop copy of the database to the server copy of the database. The amount of data contained in the database was significant -- product information, customer contact information, and so on. That was all needed for the rep to be able to create sales orders and invoices and the like. It was crucial that the rep be able to use the software all the time, not just once in a while when they had connectivity. However, this approach does have its challenges -- if the local databases don't get synched up frequently, data at both ends becomes stale, plus you have to deal with conflicing updates.
If the amount of database information needed locally for working disconnected isn't huge, you definitely can take advantage of the new HTML5 offline storage and use a website.
I think that the critical factors here are how much data the user needs when they are working offline, how fresh the data needs to be, and what percentage of time they will be working online vs. offline.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Error with PHPMailer
Hello everyone i have been getting this error and dont know how to fix it.
{"response":"error","message":"You must provide at least one recipient
email address."}
This is the code.
<?php
require_once('phpmailer/class.phpmailer.php');
$mail = new PHPMailer();
//recipient data
$toemail = $_POST['[email protected]']; // Your Email Address
$toname = $_POST['Spadaweb, INC']; // Your Name
//sender data
$name = $_POST['contact-form-name'];
$email = $_POST['contact-form-email'];
$service = $_POST['contact-form-service'];
$subject = $_POST['contact-form-subject'];
$message = $_POST['contact-form-message'];
if( isset( $_POST['contact-form-submit'] ) ) {
if( $name != '' AND $email != '' AND $subject != '' AND $message != '' ) {
$body = "Name: $name <br><br>Email: $email <br><br>Service: $service <br> <br>Message: $message";
$mail->SetFrom( $email , $name );
$mail->AddReplyTo( $email , $name );
$mail->AddAddress( $toemail , $toname );
$mail->Subject = $subject;
$mail->MsgHTML( $body );
$sendEmail = $mail->Send();
if( $sendEmail == true ):
$arrResult = array ('response'=>'success');
else:
$arrResult = array ('response'=>'error','message'=>$mail->ErrorInfo);
endif;
} else {
$arrResult = array ('response'=>'empty');
}
} else {
$arrResult = array ('response'=>'unexpected');
}
echo json_encode($arrResult);
?>
I have changed the email etc to mine and i keep getting the above error? Currently hosted on a bluehost vps cent os server as well. DKIM is enabled on this particular account? Thanks for looking over the problem!
A:
$toemail = $_POST['[email protected]']; // Your Email Address
$toname = $_POST['Spadaweb, INC']; // Your Name
This needs to be changed since you are giving it the actual variables and not trying to get the posts.
$toemail = '[email protected]'; // Your Email Address
$toname = 'Spadaweb, INC'; // Your Name
Now it should be able to send.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Get the main where of query
I want to get the index of main where clause of database query in Java ?
How can I handle this with Regex?
For example in this query I want to get Second where clause:
select u.id, (select x.id from XEntity where x.id = 200)
from UserEntity u
**where** u.id in (select g.id from AnotherEntity g where g.id = 100)
I think the main where is which that number of "(" characters and ")" characters is equal after it.
but I don't know how can I get this with regex.
With Best Regards
A:
What Toote and David Brabant said is absolutely correct. Parsing SQL, especially complex SQL using only regex is a very hard problem.
In terms of parsing SQL in Java, which seems to be the thrust of your question, there's a very good (if apparently un-maintained) library called JSQLParser. A more up-to-date version of this library can be found on Github here (disclaimer: I made a very small contribution to this). The main page shows an example of visitor designed to consume the output of the AST here.
There is also a grammar for ANTLR available in it's grammar list. Or, if you're feeling adventurous, the H2 database supports a rather extensive range of SQL, including some proprietary features of, e.g., MySQL. You could modify it's Parser to generate an appropriate structure for extracting the information you need.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Maximal Subgroups and order of a group
I encountered the following exercise in Isaacs' Algebra:
"Suppose a group $G$ has only one maximal subgroup. Prove that the order of $G$ must be a power of a prime".
I think I've proven this for the case when $G$ is cyclic, based on the observation that in a cyclic group $G$ with a subgroup $H$, $H$ is maximal iff $\frac{|G|}{|H|}$ is prime. However if $G$ is not cyclic, I cannot use the property that there always exists a subgroup of order some divisor of $|G|$. I have run out of ideas in solving this problem, how can I proceed from here? Please do not post complete solutions.
A:
All such groups are cyclic. To see this let $H$ be the unique maximal subgroup of $G$ and $x\in G\setminus H.$ Then the subgroup generated by $x$ is contained in no maximal subgroup and hence is equal to $G.$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do you get cash without a debit card quickly?
I lost my debit card and need to get cash quickly. What are some good ways of doing this? There are no bank branches near me.
A:
Use Venmo, Paypal, Zelle, or similar to send money to a friend who can give you cash in exchange.
A:
Some credit cards allow ATM withdrawals as cash advances.
if you have access to your checkbook, you could also make a check out to CASH and take it to anywhere that offers check-cashing services
You could possibly send yourself money via something like Western Union
pawn something
borrow some from a friend
There are also, of course, illicit ways to get cash. I won’t attempt to enumerate them here.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Jabber ID (XMPP JID) on own domain
Instead of [email protected] or [email protected] I would like to use
[email protected].
can this be one when using app-engine xmpp service,
when own-domain is using google apps for mail service
This would be a great option if available.
We feel many getting worried to add when they find @appspot.com at end,
also when they see an app id which may not much same as our domain name.
A:
Unfortunately App Engine doesn't support this feature yet.
http://code.google.com/p/googleappengine/issues/detail?id=2145
|
{
"pile_set_name": "StackExchange"
}
|
Q:
No Results by Content Search Webpart
Why I get no results in my Content search Webpart in Office 365? The query Shows me results by testing, but not in the site.
A:
What license do you have?
If you do not meet the license requirements which is any of the Office 365 Enterprise plans, you will see the webpart, be able to add it to a page and create a query and get results while testing it in the dialog, but it simply won't work in the site.
Q: Which SharePoint Online plans include the search-driven publishing
features?
A: The Content Search Web Part and Cross-site Publishing are available
for Office 365 for Enterprise plans. Specifically, these plans are:
Office 365 Enterprise E3 and E4, Office 365 Education A3 and A4,
Office 365 government G3 and G4, and Office 365 Enterprise E3 for
Nonprofits.
Search innovations for site and portal design in SharePoint Online
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to render contents of a tag in unicode in BeautifulSoup?
This is a soup from a WordPress post detail page:
content = soup.body.find('div', id=re.compile('post'))
title = content.h2.extract()
item['title'] = unicode(title.string)
item['content'] = u''.join(map(unicode, content.contents))
I want to omit the enclosing div tag when assigning item['content']. Is there any way to render all the child tags of a tag in unicode? Something like:
item['content'] = content.contents.__unicode__()
that will give me a single unicode string instead of a list.
A:
Have you tried:
unicode(content)
It converts content's markup to a single Unicode string.
Edit: If you don't want the enclosing tag, try:
content.renderContents()
|
{
"pile_set_name": "StackExchange"
}
|
Q:
multiple column groupBy and get max value from each group (Java Spark)
I have a 'Dataset' in Java Spark related to cabs of a city, that among its several columns, it has :
day in the form 2016-04-02, which is the day that the cab picked up a customer.
vendor_id, which is for example 1.
hour in the form form of 2 or 16.
I want to get the hour that each vendor, each day had the maximum number of customers. So, I think I should GroupBy on these three columns. What I get after GroupBy is
first 2 rows after I groupBy on day, vendor_id, hour :
+----------+---------+----+-----+
|day |vendor_id|hour|count|
+----------+---------+----+-----+
|2016-01-01|1 |2 |116 |
|2016-01-01|1 |1 |110 |
+----------+---------+----+-----+
How can I get the hour of each day of each vendor (the groups created by GroupBy) with the maximum count?
I have already seen that this is solved with join, but this and other examples grouped only on one column where here I grouped on three.
If possible, I prefer Java code that uses Spark libraries, thank you for your time.
A:
I used Window class as @Salim suggested and it worked. Actually, I had already seen that it could be solved with Window but I thought I would be easier using join.
Dataset<Row> df_dhv_grouped = df.groupBy(
col("day"), col("vendor_id"), col("hour")).count();
Dataset<Row> df_max_hours =df_dhv_grouped.withColumn("max_drives_hour",max("count")
.over(Window.partitionBy("day","vendor_id")));
df_max_hours.filter(col("count").equalTo(col("max_drives_hour")))
.orderBy(col("day").asc(), col("vendor_id").asc()).show();
Thank you for your answers.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Linux - Run a daemon as 'nobody'
I have a daemon sitting in my root directory that currently is being run as root. However, since this program can read the file system, this is clearly a security problem. How can I run it as nobody so that I can resolve this problem?
Doing "su - nobody -c /root/myscript" doesn't work, returning a permission denied error. The only ways I can seem to get around this are:
Chmod -R 777 /root, which I don't want to do on my root dir and also messes up ssh.
Move the script to /opt or /var and then do (1)
Of course, there may be an easy solution that I'm missing. I can chown it to nobody but that doesn't fix the problem either. Any ideas?
A:
You don't want to do (1) -- Leave root's home directory alone. (2) is your best option - Create a new directory owned by the user the daemon will run as & have it do any disk I/O it needs to do in that directory.
Semi-related, please don't run things as "nobody" -- there's an old joke that nobody is usually the most privileged user on a *NIX system because all the daemons run as "nobody".
If you're really concerned about security you don't want to fall into that trap. It's worth taking the extra minute to create a dedicated user for your daemons with appropriate restrictions :-)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to 'union' 2 or more DataTables in C#?
How to 'union' 2 or more DataTables in C#?
Both table has same structure.
Is there any build-in function or should we do manually?
A:
You are looking most likely for the DataTable.Merge method.
Example:
private static void DemonstrateMergeTable()
{
DataTable table1 = new DataTable("Items");
// Add columns
DataColumn idColumn = new DataColumn("id", typeof(System.Int32));
DataColumn itemColumn = new DataColumn("item", typeof(System.Int32));
table1.Columns.Add(idColumn);
table1.Columns.Add(itemColumn);
// Set the primary key column.
table1.PrimaryKey = new DataColumn[] { idColumn };
// Add RowChanged event handler for the table.
table1.RowChanged += new
System.Data.DataRowChangeEventHandler(Row_Changed);
// Add ten rows.
DataRow row;
for (int i = 0; i <= 9; i++)
{
row = table1.NewRow();
row["id"] = i;
row["item"] = i;
table1.Rows.Add(row);
}
// Accept changes.
table1.AcceptChanges();
PrintValues(table1, "Original values");
// Create a second DataTable identical to the first.
DataTable table2 = table1.Clone();
// Add column to the second column, so that the
// schemas no longer match.
table2.Columns.Add("newColumn", typeof(System.String));
// Add three rows. Note that the id column can't be the
// same as existing rows in the original table.
row = table2.NewRow();
row["id"] = 14;
row["item"] = 774;
row["newColumn"] = "new column 1";
table2.Rows.Add(row);
row = table2.NewRow();
row["id"] = 12;
row["item"] = 555;
row["newColumn"] = "new column 2";
table2.Rows.Add(row);
row = table2.NewRow();
row["id"] = 13;
row["item"] = 665;
row["newColumn"] = "new column 3";
table2.Rows.Add(row);
// Merge table2 into the table1.
Console.WriteLine("Merging");
table1.Merge(table2, false, MissingSchemaAction.Add);
PrintValues(table1, "Merged With table1, schema added");
}
private static void Row_Changed(object sender,
DataRowChangeEventArgs e)
{
Console.WriteLine("Row changed {0}\t{1}", e.Action,
e.Row.ItemArray[0]);
}
private static void PrintValues(DataTable table, string label)
{
// Display the values in the supplied DataTable:
Console.WriteLine(label);
foreach (DataRow row in table.Rows)
{
foreach (DataColumn col in table.Columns)
{
Console.Write("\t " + row[col].ToString());
}
Console.WriteLine();
}
}
A:
You could try this:
public static DataTable Union (DataTable First, DataTable Second)
{
//Result table
DataTable table = new DataTable("Union");
//Build new columns
DataColumn[] newcolumns = new DataColumn[First.Columns.Count];
for(int i=0; i < First.Columns.Count; i++)
{
newcolumns[i] = new DataColumn(
First.Columns[i].ColumnName, First.Columns[i].DataType);
}
table.Columns.AddRange(newcolumns);
table.BeginLoadData();
foreach(DataRow row in First.Rows)
{
table.LoadDataRow(row.ItemArray,true);
}
foreach(DataRow row in Second.Rows)
{
table.LoadDataRow(row.ItemArray,true);
}
table.EndLoadData();
return table;
}
From here (not tested).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Simple PHP random array
I have a simple array like this:
$input = array('Line1', 'Line2', 'Line3');
And want to echo one of the values randomly. I've done this before but can't remember how I did it and all the examples of array_rand seem more complex that what I need.
Can any help? Thanks
A:
echo $input[array_rand($input)];
array_rand() returns the key, so we need to plug it back into $input to get the value.
A:
Complex? Are we on the same manual page?
$rand_key = array_rand($input, 1);
A:
You could use shuffle() and then just pick the first element.
shuffle($input);
echo $input[0];
But I would go with the array_rand() method.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Return only duplicate files from specified directory
I am trying to return a list of all duplicate files within a directory. I have managed to return all file names from within the directory and subdirectories. I think I have code that allows duplicatae files to be returned but I want to return a list of all duplicate files and their paths to the console. I have created a FileDetail class which contains the folder, filename and filesize.
Would I need to create another class for duplicate files?
What would be the best way to return the list of all duplicate files found?
Relatively new to C# and using this task as a learning experience on ways to work with directories
private static void ListAllDuplicateFiles()
{
string[] files = Directory.GetFiles(rootPath, "*.*", SearchOption.AllDirectories);
List<string> duplicates = new List<string>();
List<FileDetail> fileDetails = new List<FileDetail>();
foreach (string file in files)
{
FileInfo fileInfo = new FileInfo(file);
FileDetail fileDetail = new FileDetail(fileInfo);
fileDetails.Add(fileDetail);
if (fileDetails.Select(f => f.Filename).Contains(file))
{
duplicates.Add(file);
}
}
foreach (string duplicate in duplicates)
{
List<FileDetail> duplicateFileDetails = fileDetails.Where(f => f.Filename == duplicate).ToList();
}
foreach (FileDetail fileDetail in fileDetails)
{
Console.WriteLine(fileDetail.Filename);
}
Console.ReadLine();
}
A:
I think you're pretty close. But maybe you can achieve things a little easier.
So you're asking two questions.
First question: do i need to create a new class for duplicate files? In all fairness, it seems that even the first class is a little redundant as the class you're using: System.IO.FileInfo has all the properties you're interested in (or so it seems anyway). So, no i don't think you do. You can think of classes more in a way of structuring your data and possible determining behavior. If you don't need specific behavior nor need to add data to an already existing available class, might as well use it. :-)
The second question: What would be the best way to return the list of all duplicate files found? I guess the easiest way to do what you're doing, but I'd change the datatype of 'duplicates' from List<string> to List<FileInfo> and put 'm in there when you find them.
string[] files = Directory.GetFiles(rootPath, "*.*", SearchOption.AllDirectories);
var fileInfos = new List<FileInfo>();
foreach(var item in files)
{
var fileInfo = new FileInfo(item);
var doppelganger = fileInfos.FirstOrDefault(x => x.Name == fileInfo.Name);
if (doppelganger != null && duplicates.All(x => x.FullName != doppelganger.FullName))
duplicates.Add(doppelganger);
if(doppelganger != null)
duplicates.Add(fileInfo);
fileInfos.Add(fileInfo);
}
So, what i'm doing is re-using the FileInfo class in System.IO and putting them in the list where ever necessary. Just to clarify on the 'doppelganger', if you want all doubles, that would include the one you're comparing to, right? That's why i'm also adding that one. Maybe this could be done more elegantly, but hey, there ya go.
Hope this helps! Happy coding
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Export Lint report from Eclipse IDE
I am using lint tool in Eclipse while developing an Android project. I could see the lint warnings in the lint tool console, but i cannot find any option to export this result to either XML or html file.
I know that, report can be generated from command promt, but i need to confirm whether this is possible through Lint tool integrated with Eclipse IDE. If it is possible could any one suggest how to take the report, if not i wonder why eclipse has not provided such a simple feature to the lint tool.
A:
1.open command line (cmd in windows)
2.navigate to "tools" directory located in android installation directory
3.here you just have to type :
command -
lint --html < html_output_path > < your_android_project_path >
eg:
lint --html C:\report.html C:\yourAndroidProject\
4.go to html_path and open the html test report :)
A:
Hi As a part of RnD from my end I am closing this thread with the conclusion that we cannot export the lint report when we are running lint from the latest available Eclispe (bundled with ADT) plugin till date. If you are so required to get the report from this plugin, better enhance your own plugin for the same :).
As Kanwalijit answered, if we want to export the Lint report, we need to run the lint from command prompt.
Thanks
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Checking if a vector is a min heap using recursion
I'm trying to write a program that checks if a vector is a min heap. I've been looking at code from here. I understand why they use 2*i+2 to compare to n, since there's a tipping point with the index where values in the vector/array (mine uses a vector) become leaf nodes. What I don't understand is why they keep using 2*i + 1 and 2*i + 2 as the index when they call the function recursively. Shouldn't they be using i+1 to access the left node and i+2 to access the right? But I tried this and I get a segmentation fault.
bool checkMinHeap(int A[], int i, int n)
{
// if i is a leaf node, return true as every leaf node is a heap
if (2*i + 2 > n)
return true;
// if i is an internal node
// recursively check if left child is heap
bool left = (A[i] <= A[2*i + 1]) && checkMinHeap(A, 2*i + 1, n);
// recursively check if right child is heap (to avoid array out
// of bound, we first check if right child exists or not)
bool right = (2*i + 2 == n) ||
(A[i] <= A[2*i + 2] && checkMinHeap(A, 2*i + 2, n));
// return true if both left and right child are heap
return left && right;
}
Their test code:
int main()
{
int A[] = {1, 2, 3, 4, 5, 6};
int n = sizeof(A) / sizeof(int);
// start with index 0 (root of the heap)
int index = 0;
if (checkMinHeap(A, index, n))
cout << "Given array is a min heap";
else
cout << "Given array is not a min heap";
return 0;
}
My test code (returns 0, when it should return 1):
int main (void)
{
vector <int> test;
test.push_back(1);
test.push_back(2);
test.push_back(3);
test.push_back(4);
test.push_back(5);
test.push_back(9);
test.push_back(3);
test.push_back(19);
cout << isMinHeap(test,0) << endl;
}
A:
What I don't understand is why they keep using 2*i + 1 and 2*i + 2 as the index when they call the function recursively.
For instance, your heap data structure is following one.
These values are stored in an array, say A[i], i = 0, 1, …, 7.
In this picture, the blue circles i = 3 = 2*1+1 and i = 4 = 2*1+2 are the children of the green circle i = 1
Like this, in general, the left child of a parent i has an index 2*i+1 and the right one has index 2*i+2.
This is very general child-parent relationships in binary heap maps.
This is the reason why they keep using 2*i+1 and 2*i+2 as the index when they call the function recursively.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to process only new (unprocessed) files in linux
Given a directory with a large number of small files (>1 mio) what's a fast way to remember which files were already processed (for a database import).
The first solution I tried was a bash script:
#find all gz files
for f in $(find $rawdatapath -name '*.gz'); do
filename=`basename $f`
#check whether the filename is already contained in the process list
onlist=`grep $filename $processed_files`
if [[ -z $onlist ]]
then
echo "processing, new: $filename"
#unzip file and import into mongodb
#write filename into processed list
echo $filename #>> $processed_files
fi
done
For a smaller sample (160k files) this ran ~8 minutes (without any processing)
Next I tried a python script:
import os
path = "/home/b2blogin/webapps/mongodb/rawdata/segment_slideproof_testing"
processed_files_file = os.path.join(path,"processed_files.txt")
processed_files = [line.strip() for line in open(processed_files_file)]
with open(processed_files_file, "a") as pff:
for root, dirs, files in os.walk(path):
for file in files:
if file.endswith(".gz"):
if file not in processed_files:
pff.write("%s\n" % file)
This runs in less than 2 mins.
Is there a significantly faster way that I'm overlooking?
Other solutions:
Moving processed files to a different locations is not convenient since I use s3sync to download new files
since the files have a timestamp as part of their name I might consider to rely on processing them in order and only compare the name to a "last processed" date
alternatively I could keep track of the last time a processing ran, and only process files that have been modified since.
A:
Just use a set:
import os
path = "/home/b2blogin/webapps/mongodb/rawdata/segment_slideproof_testing"
processed_files_file = os.path.join(path,"processed_files.txt")
processed_files = set(line.strip() for line in open(processed_files_file))
with open(processed_files_file, "a") as pff:
for root, dirs, files in os.walk(path):
for file in files:
if file.endswith(".gz"):
if file not in processed_files:
pff.write("%s\n" % file)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Handle number followed by letters in Flex
In some Flex/Lex code we have,
DIGIT [0-9]
LETTER [A-Za-z]
ID {LETTER}{LETTER}|{DIGIT})*
NUM {DIGIT}+(\.{DIGIT}+)?
So, 123 matches NUM and abc123 matches ID. In case of
123abc, this matches NUM followed by and ID. However,
I want this to generate an error message instead of matching.
Is there a simple way to do this?
A:
You can just add an additional pattern to detect an error.
The following does not use macros, because I personally find them distracting. But the idea is the same.
[[:alpha:]][[:alnum:]]* { return IDENTIFIER; }
[[:digit:]]+"."([[:digit:]]+)? { return NUMBER; }
[[:digit:]]+"."([[:digit:]]+)?[[:alpha:]] { return BAD_NUMBER; }
The last pattern will only match if there is a letter immediately following a NUMBER, and will override the second pattern because of the longest-match rule.
By the way, a better pattern for a number is:
[[:digit:]]+("."[[:digit:]]*)?|"."[[:digit:]]+
That will match 23. and .56, which many people expect to be valid numbers.
You might also find this answer interesting, particularly the examples from other programming languages. Most languages (other than C & family) do allow 123abc to be scanned as two tokens, which usually leads to a syntax error anyway, and that is both the easiest and the most maintainable solution.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Assigning labels in R based on ID?
I have a data frame as follows:
DF<-data.frame(a=c(1,1,1,2,2,2,3,3,4,4),b=c(43,23,45,65,43,23,65,76,87,4))
a b
1 43
1 23
1 45
2 65
2 43
2 23
3 65
3 76
4 87
4 4
I want to set a flag like this:
a b flag
1 43 A
1 23 B
1 45 C
2 65 A
2 43 B
2 23 C
3 65 A
3 76 B
4 87 A
4 4 B
How can I get this done in R?
A:
Using dplyr
library(dplyr)
DF %>% group_by(a) %>% mutate(flag=LETTERS[row_number()])
Using data.table(HT to @David Arenberg)
library(data.table)
setDT(DF)[, flag := LETTERS[1:.N], a]
And a soon to be vintage solution (by @Roman Luštrik)
do.call("c", sapply(rle(DF$a)$lengths, FUN = function(x) LETTERS[1:x]))
Addendum
@akrun suggested following extension of the LETTERS to address the immediate question arose "What if there is more than 26 groups?" (by @James)
Let <- unlist(sapply(1:3, function(i) do.call(paste0,expand.grid(rep(list(LETTERS),i)))))
All above codes remain fully functional, when LETTERS replaced by Let.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Função de codigo script
Alguem poderia me explica o que significa nesse codigo a parte que diz:
document.cookie = 'useHTML5=; expires=Thu, 01 Jan 1970 00:00:01
Ela aparece mais de uma vez, gostaria de saber se é algo relacionado a uma data valida do script, e por que o ano de 1970
No script também tem alguns links encodados, eu desencodei alguns e em todos eles aparece a parte (expire)
https://redirector.googlevideo.com/videoplayback?requiressl=yes&shardbypass=yes&cmbypass=yes&id=a65e10712772b860&itag=37&source=picasa&cmo=secure_transport=yes&ip=0.0.0.0&ipbits=0&expire=1410146288&sparams=requiressl,shardbypass,cmbypass,id,itag,source,ip,ipbits,expire&signature=520E18C71BF843019359E7EB492F8CBD928385BD.35D96C19784732AC04B057DC838BC70B21E467D7&key=lh1
Já nesse outro link a parte que se refere expire é diferente
http://redirector.googlevideo.com/videoplayback?id=d4f4531d811f6fc8&itag=18&source=picasa&cmo=sensitive_content=yes&ip=0.0.0.0&ipbits=0&expire=1407845352&sparams=id,itag,source,ip,ipbits,expire&signature=CBB7533D638BE53685D14770144A4808C129B264.275AA97CABC08AB6AD4BC8780EC905DCA9989D9A&key=lh1
Esse script teria a função de mudar essa data ou algo parecido?
<script type="text/javascript">
$(document).ready(function () {
$("#divContentVideo").allofthelights({
'opacity': '0.95',
'clickable_bg': 'true',
'callback_turn_off': function() {
$('.allofthelights_bg').hide().show(0);
$('#switch').hide();
},
'callback_turn_on': function() {
$('#switch').show();
}
});
setTimeout('ReloadIfNeed()', 10000);
});
function ReloadIfNeed(){
if ($('#divFileName').html().indexOf("My Movie") > 0)
{
location.reload();
}
}
var isHTML5 = false;
if (document.cookie.indexOf("useHTML5") >= 0) {
isHTML5 = true;
$('#playerChoose').html('-> Switch to Flash Player (more stable & better quality)');
$('#qualityChoose').show();
}
var isHTML5HQ = false;
if (document.cookie.indexOf("isHTML5HQ") >= 0) {
isHTML5HQ = true;
$('#qualityChoose').html('-> Switch to HTML5 LOW quality');
}
$('#playerChoose').click(function () {
if (isHTML5)
{
document.cookie = 'useHTML5=; expires=Thu, 01 Jan 1970 00:00:01 GMT;path=/';
document.cookie = 'useFlash=true;path=/';
}
else
{
document.cookie = 'useHTML5=true;path=/';
document.cookie = 'useFlash=; expires=Thu, 01 Jan 1970 00:00:01 GMT;path=/';
}
document.location.reload(true);
});
$('#qualityChoose').click(function () {
if (isHTML5HQ)
{
document.cookie = 'isHTML5HQ=; expires=Thu, 01 Jan 1970 00:00:01 GMT;path=/';
document.cookie = 'isHTML5LQ=true;path=/';
}
else
{
document.cookie = 'isHTML5HQ=true;path=/';
document.cookie = 'isHTML5LQ=; expires=Thu, 01 Jan 1970 00:00:01 GMT;path=/';
}
document.location.reload(true);
});
var txha = 'fmt_list=37%2F1920x1080%2C22%2F1280x720%2C35%2F854x480%2C34%2F640x360%2C18%2F640x360&fmt_stream_map=37%7Chttps%3a%2f%2fredirector.googlevideo.com%2fvideoplayback%3frequiressl%3dyes%26shardbypass%3dyes%26cmbypass%3dyes%26id%3da65e10712772b860%26itag%3d37%26source%3dpicasa%26cmo%3dsecure_transport%3dyes%26ip%3d0.0.0.0%26ipbits%3d0%26expire%3d1410146288%26sparams%3drequiressl%252Cshardbypass%252Ccmbypass%252Cid%252Citag%252Csource%252Cip%252Cipbits%252Cexpire%26signature%3d520E18C71BF843019359E7EB492F8CBD928385BD.35D96C19784732AC04B057DC838BC70B21E467D7%26key%3dlh1%2C22%7Chttps%3a%2f%2fredirector.googlevideo.com%2fvideoplayback%3frequiressl%3dyes%26shardbypass%3dyes%26cmbypass%3dyes%26id%3da65e10712772b860%26itag%3d22%26source%3dpicasa%26cmo%3dsecure_transport%3dyes%26ip%3d0.0.0.0%26ipbits%3d0%26expire%3d1410146288%26sparams%3drequiressl%252Cshardbypass%252Ccmbypass%252Cid%252Citag%252Csource%252Cip%252Cipbits%252Cexpire%26signature%3d11DBC00A15B49979B0B9A23004174EF4FFF7A925.32E74A92AEE34FADEC0096642702584FD658DBBF%26key%3dlh1%2C35%7Chttps%3a%2f%2fredirector.googlevideo.com%2fvideoplayback%3frequiressl%3dyes%26shardbypass%3dyes%26cmbypass%3dyes%26id%3da65e10712772b860%26itag%3d35%26source%3dpicasa%26cmo%3dsecure_transport%3dyes%26ip%3d0.0.0.0%26ipbits%3d0%26expire%3d1410146288%26sparams%3drequiressl%252Cshardbypass%252Ccmbypass%252Cid%252Citag%252Csource%252Cip%252Cipbits%252Cexpire%26signature%3dABE28CFF2DF9768DDCBEBC525145903668D9A9F6.CC31D9AC79E0EF78E20C88DDCEC6D1B537E68268%26key%3dlh1%2C34%7Chttps%3a%2f%2fredirector.googlevideo.com%2fvideoplayback%3frequiressl%3dyes%26shardbypass%3dyes%26cmbypass%3dyes%26id%3da65e10712772b860%26itag%3d34%26source%3dpicasa%26cmo%3dsecure_transport%3dyes%26ip%3d0.0.0.0%26ipbits%3d0%26expire%3d1410146288%26sparams%3drequiressl%252Cshardbypass%252Ccmbypass%252Cid%252Citag%252Csource%252Cip%252Cipbits%252Cexpire%26signature%3d700BCAB38FAB60AD6AABC3549B9E7C74D3ED489C.57F7DC1FC5A065786DB4F2E6277D1546D54ACF2B%26key%3dlh1%2C18%7Chttps%3a%2f%2fredirector.googlevideo.com%2fvideoplayback%3frequiressl%3dyes%26shardbypass%3dyes%26cmbypass%3dyes%26id%3da65e10712772b860%26itag%3d18%26source%3dpicasa%26cmo%3dsecure_transport%3dyes%26ip%3d0.0.0.0%26ipbits%3d0%26expire%3d1410146288%26sparams%3drequiressl%252Cshardbypass%252Ccmbypass%252Cid%252Citag%252Csource%252Cip%252Cipbits%252Cexpire%26signature%3d270F5022125B383BF7365840657C61CB83505AA5.97F4F9604EEDEBE76CC22625C2F8AAE4761D0970%26key%3dlh1&video_id=picasacid&fs=1&hl=en&autoplay=1&ps=picasaweb&playerapiid=uniquePlayerId&t=1&vq=large&auth_timeout=86400000000';
$('#selectEpisode').change(function () {
location.href = 'http://kissanime.com/Anime/K-On-2-Dub/' + $(this).val();
});
$('#selectGroup').change(function () {
location.href = 'http://kissanime.com/Anime/' + $(this).val();
});
if (isHTML5) {
$('#divContentVideo').html('<video id="my_video_1" class="video-js vjs-default-skin" controls autoplay preload="auto" width="854px" height="552px" data-setup="{}"><source src="' + txha + '" type="video/mp4"></video>');
//$('#divContentVideo').html('<div style="position: relative;width:100%;height:100%"><div data-swf="//releases.flowplayer.org/5.4.3/flowplayer.swf" class="flowplayer play-button" style="position: absolute; bottom: 0;" data-embed="false"><video preload="auto" autoplay><source type="video/mp4" src="' + txha + '"/></video></div></div>');
$('#divTextQua').html('IF THE PLAYER DOES NOT WORK, PLEASE CLICK ON THE URLS BELOW TO WATCH VIDEO');
$('#switch').css('left', '860px');
$('#switch').css('top', '530px');
}
else
{
//$('#divContentVideo').show();
setTimeout('DoHideFake()', 2000);
}
function DoHideFake()
{
$('#divContentVideo').append('<embed id="embedVideo" height="552" src="//www.youtube.com/get_player?enablejsapi=1&modestbranding=1"type="application/x-shockwave-flash" width="854" allowfullscreen="true" allowscriptaccess="always" bgcolor="#fff" scale="noScale" wmode="opaque" flashvars="' + txha + '" style="width: 854px; height: 552px" />');
}
function NextEps() {
$('#divMsg').css('display', 'block');
}
</script>
A:
No seu código está removendo o cookie, a data é para forçar a remoção.
• useHTML5 = ''
• expires = Thu, 01 Jan 1970 00:00:01
Ou seja, useHTML5 sem um valor atribuido - nulo, e a data do cookie já vencida.
Neste caso o cookie simplesmente é apagado.
Por que definir a data em 1970?
A data Thu, 01 Jan 1970 00:00:01 garante que seja feita a remoção do cookie, mesmo que a data do computados do usuário não seja a data corrente. Caso o usuário altere a data do PC, 1970 garante a remoção sem conflito de data.
Um exemplo para a criação de cookie com validade até o final do ano.
document.cookie="username=John Doe; expires=Thu, 18 Dec 2014 12:00:00 GMT";
[referencia]
A URL do googlevideo provavelmente faz o load dos controles do player.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Java program keeps exiting program prematurely
I need to build a simple automaton for my Automata class. I am using Java and I cannot figure out for the life of me why my program keeps exiting prematurely. I've tried debugging it, having print statements everywhere to figure out where it's stopping, and although I know where it stops, I do not see anything that would make the program stop working. The stoppage happens on line 27 (Right where I SOP "Enter a string of digits...".
Knowing me it's probably something simple, but I cannot figure this one out.
import java.util.*;
public class hw1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please indicate the number of states");
int numState = input.nextInt();
int[] state = new int[numState];
boolean[] accept = new boolean[numState];
for (int i = 0; i < numState; i++) {
System.out.println("Is the state q" + (i + 1) + " a final state? (Answer 1 for yes; 0 for no)");
int finalState = input.nextInt();
if (finalState == 1)
accept[i] = true;
} // for
System.out.println("Enter the number of symbols s: ");
int numSym = input.nextInt();
int[][] next = new int[numState][numSym];
for (int i = 0; i < numState; i++) {
for (int j = 0; j < numSym; j++) {
System.out.println("What is the number for the next state for q" + i + " when it gets symbol " + j);
next[i][j] = input.nextInt();
}//nested for
}//for
String digits = input.nextLine();
System.out.print("Enter a string of digits (0-9) without spaces to test:");
int[] digitArray = new int[digits.length()];
for (int i = 0; i < digits.length(); i++) {
digitArray[i] = digits.charAt(i);
}
for (int i = 0; i < digits.length(); i++) {
System.out.print(digitArray[i] + " ,");
}
System.out.println("end of program");
}// main;
}// class
A:
Change your code to :
input.nextLine();
System.out.print("Enter a string of digits (0-9) without spaces to test:");
String digits = input.nextLine();
This will get and ignore the newline character left in the stream after call to nextInt()
|
{
"pile_set_name": "StackExchange"
}
|
Q:
3 dimensional matrix multiplication in matlab
I have a normal map of size mxnx3, where each pixel has a normal vector {Nx, Ny, Nz}.
I want to rotate each normal vector independently by a rotation matrix. Let R be the rotation matrix of size mxnx3x3, where each pixel has a rotation matrix of size 3x3.
I want to multiply rotation matrix at each pixel to the normal vector to get the rotated
normal vectors. I am looking for an optimized way to do the task, as looping over each pixel may not be the best way.
Please help!!
A:
I would try
res = sum( bsxfun(@times, map, R), 4 );
With map an m-by-n-by-3 normal vectors, and R an m-by-n-by-3-by-3 the rotation per vector.
Coming to think about it, you might need to use permute
res = sum( bsxfun(@times, map, permute(R, [1 2 4 3]) ), 4 ); % transposing the vectors
Or, as Harshit put it:
res = sum( permute( bsxfun(@times, map, R ), [1 2 4 3]), 4 ); % transposing the vectors
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Mark 2 points on parallel walls directly opposite each other
I am about to mount some steel pipe which spans from one wall of a room to the opposite wall. (Here's why: Mount Pull-up bar from wall to wall)
How do I accurately mark two points on facing parallel walls so that the points are directly opposite each other? By directly opposite, I mean that the line joining the points should be horizontal and should also be perpendicular to both walls.
Additionally, I have a hook suspended from my ceiling and it would be nice if I could accurately mark the points so that the line joining them passes directly below this hook in addition to being level and perpendicular to the walls.
A:
Why not buy the pipe, and make the marks based on that. That is, have a level, hold the pipe up and level it, then mark where it touches the wall. A friend would help, so might hanging or otherwise supporting the pipe from either above or below as you do this.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
scrapy CrawlSpider: crawl policy / queue questions
I started with scrapy some days ago, learned about scraping particular sites, ie the dmoz.org example; so far it's fine and i like it. As I want to learn about search engine development I aim to build a crawler (and storage, indexer etc) for large amount of websites of any "color" and content.
So far I also tried the depth-first-order and bredth-first-order crawling.
I use at the moment just one Rule, I set some path to skip and some domains.
Rule(SgmlLinkExtractor(deny=path_deny_base, deny_domains=deny_domains),
callback='save_page', follow=True),
I have one pipeline, a mysql storage to store url, body and headers of the downloaded pages, done via a PageItem with these fields.
My questions for now are:
Is it fine to use item for simple storing of pages ?
How does it work that the spider checks the database if a page is already crawled (in the last six months ie), it's builtin somehow?
Is there something like a blacklist for useless domains, ie. placeholder domains, link farms etc.?
There are many other issues like storage but I guess I stop here, just one more general search engine question
Is there a way to obtain crawl result data from other professional crawlers, of course it must be done by sending harddisks otherwise the data volume would be the same if I crawl them myself, (compressing left aside).
A:
I will try to answer only two of your questions:
Is it fine to use item for simple storing of pages ?
AFAIK, scrapy doesn't care what you put into an Item's Field. Only your pipeline will dealing be with them.
How does it work that the spider checks the database if a page is already crawled (in the last six months ie), it's builtin somehow?
Scrapy has duplicates middleware, but it filters duplicates only in current session. You have to manually prevent scrapy to not crawl sites you've crawled six months ago.
As for question 3 and 4 - you don't understand them.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
3d borders on a html row
My pen: http://codepen.io/helloworld/pen/gimoI
I want to have a gray and white border on a table row to achieve a 3d effect.
Why is only one border color visible?
<link href="http://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">
<table style="width:100%;">
<tr>
<td style="vertical-align:top;width:60px;">Alarm 1</td>
<td style="width:auto;">
<span style="font-weight:bold;">Brand LANG: </span>
<span>Helmenstraße 5</span>
<span>90000 Nürnbergxxxxxxxxx</span>
</td>
<td style="width:30px;text-align:center;"> <i class="icon-angle-down button"></i></td>
</tr>
<tr>
<td style="width:60px;vertical-align:top;">
<div style="border-radius:28px;border:black solid 1px;background:red;">Alarm 1</div>
</td>
<td style="width:auto;">
<span style="font-weight:bold;">Brand LANG: </span>
<span>Langenburgerwald allee 25/c</span>
<span>70000 Wurmlingen ob der Tauber</span>
</td>
<td style="width:30px;text-align:center;"> <i class="icon-angle-down button"></i></td>
</tr>
</table>
body,html{
padding:0;
margin:10px;
background:#fafafa;
}
table{
border-collapse:collapse;
border-spacing:0;
}
table td
{
padding: 5px;
}
td {
border-bottom: gray solid 2px;
border-top: white solid 2px;
background:green;
}
A:
Because the top border is white and is difficult to see the diference with the background.
I just updated it now:
body,html{
padding:0;
margin:10px;
background:#fcc;
}
table{
border-spacing:0px;
}
table td
{
padding: 5px;
border-bottom: gray solid 2px;
border-top: white solid 2px;
}
tr {
background:green;
}
You have to remove border-collapse:collapse;
Check this [http://codepen.io/anon/pen/vIHcf][1]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Help inserting Ruby script in HTML
In my HTML page, I simply have an input box and an output box.
The Ruby script I have simply extracts the value from the input box, calculates and needs to display the output in the output box.
How do I get this done in my HTML code?
A:
Try using Ruby as your CGI back-end. Here is a simple overview of what Ruby with CGI might be. You can also delve into the intro given by the Pragmatic Programmers here. So fo example:
if your HTML contains a form that has the field someVal,
then you can access it using Ruby's cgi as:
require 'cgi'
cgi = CGI.new
cgi['someVal'] » ["whatever they sent in someVal"]
To make it even more interesting, without using any special frameworks, you can use Ruby's eruby so that you directly embed your Ruby in HTML :-).
Something like:
This text is <% a = 100; puts "#{a}% Live!" %>
Gives something like:
This text is 100% Live!
Try it out, I know you'll love what you learn...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Problem installing phpMyAdmin on Ubuntu 19.10 (Eoan Ermine)
I just recently upgraded from Ubuntu 19.04 (Disco Dingo) to Ubuntu 19.10 (Eoan Ermine). My phpMyAdmin was removed while upgrading. Now I can't install it again.
I tried using:
sudo apt-get install phpmyadmin php-gettext
but it shows something like this:
Package phpmyadmin is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source
E: Package 'phpmyadmin' has no installation candidate
So I searched from phpMyAdmin, apt search phpmyadmin, but I didn't find any.
How can I install phpMyAdmin on this version?
A:
I am a member of the packaging team and we are doing our best to get back phpMyAdmin in the Debian buster repository ASAP (buster-backports), this will update Ubuntu afterwards.
You can use our PPA: https://bugs.launchpad.net/ubuntu/+source/phpmyadmin/+bug/1837775/comments/7
There is an open issue on our tracker for Ubuntu: https://github.com/phpmyadmin/phpmyadmin/issues/15515
And for Debian:
https://github.com/phpmyadmin/phpmyadmin/issues/15236
Hope the PPA or installing manually using our website will help someone
A:
To add the ppa mentioned by William Desportes and install phpmyadmin do the following:
sudo add-apt-repository ppa:phpmyadmin/ppa
sudo apt-get update
sudo apt-get install phpmyadmin
A:
Obviously it has been removed for security reasons.
It popped up first in Debian Community: #916310 - 4.6 should not be shipped in a stable release - Debian Bug report logs
Then in Launchpad
Ubuntu Forums thread here: phpmyadmin missing from repository
It seems like some Debians joined the phpMyAdmin project to fix the problem in future releases.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
read xml data in sql for each rows
This is my table
id paydetails
----------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1 <PayDetails><Column Name="NETPAY" DataType="VARCHAR(3000)" Value="40710.00" /><Column Name="EPFAMOUNT" DataType="VARCHAR(3000)" Value="4499.00" /><Column Name="FPFAMOUNT" DataType="VARCHAR(3000)" Value="541.00" /><Column Name="GROSS" DataType="VARCHAR(3000
2 <PayDetails><Column Name="NETPAY" DataType="VARCHAR(3000)" Value="49210.00" /><Column Name="EPFAMOUNT" DataType="VARCHAR(3000)" Value="5549.00" /><Column Name="FPFAMOUNT" DataType="VARCHAR(3000)" Value="541.00" /><Column Name="GROSS" DataType="VARCHAR(3000
required output:-
id NETPAY EPFAMOUNT FPFAMOUNT GROSS PTGROSS
1 40710.00 4499.00 541.00 47200.00 42000.00
2 49210.00 5549.00 541.00 58250.00 50750.00
I have tried following code, but problem is that by default it is returning only last row. Because I am passing xml as a parameter, I want result for each record.
declare @xml xml
select @xml = paydetails
from empPayDetails
declare @SQL nvarchar(max) = 'select '+
(
select ',T.X.value(''Column[@Name = "'+T.ColName+'"][1]/@Value'','''+T.DataType+''') as '+quotename(T.ColName)
from (
select T.X.value('@Name', 'nvarchar(128)') as ColName,
T.X.value('@DataType', 'nvarchar(128)') as DataType
from @XML.nodes('/PayDetails/Column') as T(X)) as T
for xml path(''), type
).value('substring(text()[1], 2)', 'nvarchar(max)')+' '+
'from @XML.nodes(''/PayDetails'') as T(X)';
print @sql
exec sp_executesql @SQL, N'@XML xml', @XML;
A:
The query should be:
declare @SQL nvarchar(max) = 'select '+
(
select ',T.X.value(''Column[@Name = "'+T.ColName+'"][1]/@Value'','''+T.DataType+''') as '+quotename(T.ColName)
from (
select distinct T.X.value('@Name', 'nvarchar(128)') as ColName,
T.X.value('@DataType', 'nvarchar(128)') as DataType
from empPayDetails
cross apply paydetails.nodes('/PayDetails/Column') as T(X)) as T
for xml path(''), type
).value('substring(text()[1], 2)', 'nvarchar(max)')+' '+
'from empPayDetails cross apply paydetails.nodes(''/PayDetails'') as T(X)';
print @sql
exec sp_executesql @SQL;
Note the use of cross apply to use an xml column of a table, the use of distinct (otherwise you'll have the same columns repeated), the fact that I removed the parameter of the exec.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Single table Inheritance name collisions
I've been using STI for a table called Journey. People will post journey requests/offers, so the Discriminator will be either: Driver or Passenger, meaning there will be journeys posted by someone who is willing to drive and take other passengers, or people who are just hitchhiking (passenger). So these two would share most of the attributes (such as the date of departure, source, destination etc.), but there will be some name collisions due to the type of the user who is posting.
For instance, if I am a passenger I may specify that I want to travel with my friend (thus having a PassengerCount = 2, i.e. we look for drivers who have at least 2 available seats). Or I may note that, I want to bring some luggage with me (thus having HaveLuggage = true, i.e. I'm looking for rides who can take my luggage)
On the other hand, if I am a driver, I should fill a form where I can specify the number of available seats (AvailableSeats) and I may note that I can't transport luggage (TakesLuggage=false).
As you can see the columns PassengerCount - AvailableSeats and HaveLuggage - TakesLuggage are the same, only their name differs from the posters perspective.
So the question is, what naming convention should I follow in order to minimize confusion? Also, is this a good idea to have one table like this (STI), if not, what alternative would you recommend?
A:
Not sure you need to worry so much about naming conventions... You've already got the distinguishing property (type). Labels can be added on data-out that would distinguish however you liked. Example:
Journey
Type (integer) -- 1 = provider, 2 = consumer
Passengers (integer)
Luggage (bit / bool) -- 1 = yes, 0 = no
so as for naming convention:
SELECT "Driver", passengers as "Avaliable Seats", luggage as "Takes Luggage" WHERE type=1
UNION
SELECT "Passenger", passengers as "Passenger Count", luggage as "Have Luggage" WHERE type=2
Or you could use control statements (IF/CASE/etc) in the SELECT itself.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
BeautifulSoup findAll not returning values on webpage
I want to webscrape individual game pages on yahoo sports.
This is an example of the type of webpage i would like to scrape: https://sports.yahoo.com/nfl/atlanta-falcons-philadelphia-eagles-20180906021/?section=teamcomparison
Underneath the initial Box Score, you will see a tab titled "Team Comparison". What I am trying to obtain are the statistics that are underneath "Offensive/Defensive Team Ranks" for each team.
# The URL i would like to scrape.
url = 'https://sports.yahoo.com/nfl/atlanta-falcons-philadelphia-eagles-
20180906021/?section=teamcomparison'
# Reading in the HTML code with BeautifulSoup
uClient = uReq(url)
page_html = uClient.read()
uClient.close()
page_soup = soup(page_html, "html.parser")
#page_soup
# Finding the segment of HTML code with my desired stats
stats = page_soup.findAll("div", {"class": "D(ib) Bxz(bb) W(100%)"})
print(stats)
### Result line -> In [743]: []
This is should be giving me the list of Offensive and Defensive ranks per team (e.g., Atlanta Passing Yards Per Game = 309.3 and Passing Yards Per Game Rank = 4), however it is only giving me "[]" and not returning any values. I believe this is because of the Javascript embedded in the webpage, however i am new to webscraping and not sure how to go about this.
A:
This data is actually downloaded from the API with AJAX, so you don't need to scrape it, you can ask API yourself if you know how to compose the URL. For example for the page that you gave in your post the URL is: https://sports.yahoo.com/site/api/resource/sports.game.team_stat_leaders;id=nfl.g.20180906021
So you only need to know the id part of the url for every game. The JSON you will get in response is a little bit obscure but after a while it is possible to understand what is going on :).
Example code to get the data:
import requests
response = requests.get("https://sports.yahoo.com/site/api/resource/sports.game.team_stat_leaders;id=nfl.g.20180906021")
data = response.json()
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is the right to keep and bear crypto protected by the Second Amendment?
Stumbled across an interesting comment in regards to the recent events about TorProject and a public library in Lebanon, New Hampshire, U. S. of A.:
http://www.dslreports.com/forum/r30291606-So-let-me-get-this-right
The Committee for State Security (Komitet gosudarstvennoy bezopasnosti/ ) has no issues with encouraging freedom fighters from using a service that is illegal in their countries, but sends an "advisory letter" to anyone in the United States that uses it where it is legal. Shady.
The government has already classified encryption technology as a weapons system. Wouldn't this mean that use of encryption technology by US citizens is protected under the 2nd Amendment? (This isn't a serious argument, but it does make you wonder)
I still remember when the Department of Homeland Security got its name. I laughed my ass off. My buddy who was a Russian linguist for the military laughed even harder because it DIRECTLY translates to KGB. The soviets had Committees for everything instead of departments, and they used "the state" instead of "the homeland" in colloquial conversation.
Goldir
(emphasis mine)
Indeed, it's been well known in the technical communities that crypto has long been classified as munition by the US government. Bernstein v. United States. http://export.cr.yp.to/
Doesn't it indeed make it protected under the 2nd Amendment?
A:
Not all weapons are protected by the Second Amendment. There is a "dangerous and unusual weapons" exclusionary clause established by the Supreme Court in District of Columbia v. Heller, which excludes pretty much anything that's incredibly dangerous (obviously we wouldn't want our people to have the right to keep bombs in their house) or not considered a normal weapon (encryption/cryptography would probably fall under this).
One case currently being considered under this exclusion is the stun gun, which is going to the Supreme Court to determine whether it qualifies as an unusual weapon and whether it is protected by the Second Amendment.
A:
When understanding jurisprudence and laws that implicate the second amendment I generally find it helpful to reference the old United States v. Miller case. Essentially, the Supreme Court decided to read the second amendment as prohibiting infringements on keeping or bearing arms with some reasonable relation to the preservation or efficiency of a militia. So, for example, at the time a short-barrelled shotgun was not considered a useful military weapon and therefore not covered by the second amendment. (It would be fascinating to see the analysis today, when not only the standing military but even police routinely use short-barreled weapons.)
I could see the argument today that cryptographic technology does have a direct bearing on the preservation and efficiency of a militia, and therefore laws restricting its possession by U.S. citizens would be unconstitutional under the second amendment.
A:
As discussed in the answer to another question, Is crypto legal in a weapon-free zone?, just because something is listed as a munition doesn't make it a weapon.
The definition of munition includes "weapons and ammunition" but not exclusively so.
The International Traffic in Arms Regulations (ITAR) defines what can and cannot be exported without a special license. The inclusion of cryptographic equipment and technology is related to regulations regarding the exporting of that technology.
There is no 2nd Amendment protection of exporting arms and the 2nd amendment does not apply.
There are other components regulated by ITAR, including a prohibition on the furnishing of training to a foreign person. This has been seen to mean that it is illegal to provide firearms-related training to a foreign person.
The prohibition on cryptographic software, training about cryptographic software and training for firearms is an issue that implicates the 1st amendment.
The National Rifle Association is challenging such regulations, as they relate to firearms information, under 1st amendment grounds. The Electronic Frontier Foundation has already successfully, so far, challenged ITAR on 1st amendment grounds as it relates to cryptography.
The bottom line is that the definition of cryptographic equipment and technology as a munition by ITAR does not make it a weapon.
ITAR regulates munitions. Munitions is a set that includes weapons and other items. One of those other items is cryptographic technology.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to print tweet from from specific profile in python using twitter api
I want to print the tweets from a profile but I can't. I guess that I'm not using the right commands or something. I'm new in coding so I don't uderstand to much about api's.
I can get info about the profile so the conection is right.
from tweepy import OAuthHandler
from tweepy import API
from tweepy import Cursor
from datetime import datetime, date, time, timedelta
from collections import Counter
import sys
import tweepy
#I don't put the secret token and all of that
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
auth_api = API(auth)
account_list = ["jufut390"]
if len(account_list) > 0:
for target in account_list:
print("Getting data for " + target)
item = auth_api.get_user(target)
print("screen_name: " + item.screen_name)
#Get info about tweets
end_date = datetime.utcnow() - timedelta(days=5)
for status in Cursor(auth_api.user_timeline, id=target, tweet_mode = "extended").items():
#print tweets
if status.created_at < end_date:
break
A:
In this line :
for status in Cursor(auth_api.user_timeline, id=target, tweet_mode = "extended").items():
The id parameter has no effect. It should be user_id and a valid user ID (numeric) See : https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline.html
In you case, you can use the screen_name.
Secondly, you say you want to print the tweets, so write a print. Try this :
#Get info about tweets
end_date = datetime.utcnow() - timedelta(days=5)
for status in Cursor(auth_api.user_timeline, screen_name=item.screen_name, tweet_mode = "extended").items():
print(status.full_text)
if status.created_at < end_date:
break
|
{
"pile_set_name": "StackExchange"
}
|
Q:
VertexList ordering of a simple graph
Given a simple graph like
g=Graph[{b -> c, a -> b}]
I would like to have f[g] resulting in {a,b,c} but for instance
VertexList[g] results {b,c,a} which's not wanted.
Is there any simple way to do this?
A:
If you have disordered graph
g = Graph[{b -> c, a -> b}]; VertexList[g]
{b, c, a}
Use sort to find the order
f[g_] := Graph[Sort[VertexList[g]], EdgeList[g]];
VertexList[f[g]]
{a, b, c}
If your graph is directed and acyclic, then you have a built in function to sort based on topological order:
TopologicalSort[g]
{a, b, c}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Update statement using case and or
UPDATE Productions
SET CountryCode = (CASE WHEN @SOffice='LA' OR @SOffice='GA' then 'USA' ELSE 'CAN' END)
Can anyone confirm if this is a correct update case statement. I seem to be running into an error of some sort. It seems correct to me.
I am working on an application and have this update statment:
SqlCommand cmd = new SqlCommand("UPDATE Productions SET CountryCode = (CASE WHEN @SOffice IN ('LA', 'GA') then 'USA' ELSE 'CAN' END), ProvinceCode = '" + user.GetProvinceCode() + "' WHERE ID = " + newProductionID, conn);
cmd.ExecuteNonQuery();
But when I build the application and run this functionality I get the following error:
Exception Message: Must declare the scalar variable "@SOffice".
Exception Triggered by Method: OnError
What does this mean??
A:
declare @Productions table(
ind int not null identity(1,1)primary key clustered
,CountryCode nchar(3) not null
,SOFFICE NCHAR(2) NULL
)
insert into @Productions (CountryCode, SOFFICE) VALUES ('ITA','LA')
insert into @Productions (CountryCode, SOFFICE) VALUES ('ITA','VE')
insert into @Productions (CountryCode, SOFFICE) VALUES ('ITA','LZ')
insert into @Productions (CountryCode, SOFFICE) VALUES ('FRA','GA')
insert into @Productions (CountryCode, SOFFICE) VALUES ('FRA','BF')
insert into @Productions (CountryCode, SOFFICE) VALUES ('ITA','VR')
insert into @Productions (CountryCode, SOFFICE) VALUES ('GER','LA')
insert into @Productions (CountryCode, SOFFICE) VALUES ('CAN','LA')
SELECT * FROM @Productions
UPDATE P
SET COUNTRYCODE = CASE P.SOFFICE WHEN 'LA' THEN 'USA'
WHEN 'GA' THEN 'USA'
ELSE 'CAN'
END -- CASE
FROM @PRODUCTIONS P
SELECT * FROM @Productions
copy and paste the code above on sql server 2008 and you see it works fine.
hope this helps
marcelo
A:
You need to put that parameter into the SqlCommand object you are using to execute the command, the @ symbol signifies a variable in Sql, if @SOffice isn't a variable you need to remove the @, if it is you need to add a SqlParameter to the command before executing it
cmd.Parameters.Add(new SqlParameter("SOffice",DbType.Char,2){Value = "LA"})
And you should also include the other options in as parameters not by building a sql statement dynamically, it is a lot safer to add the parameters through Parameters property of the command... You also need to be wrapping your command in a using statement, and conn should be wrapped in one too
using(var conn = new SqlConnection(ConfigurationMananger
.ConnectionStrings["conn"].ConnectionString)
using(cmd = conn.CreateCommand())
{
cmd.CommandText =
@"UPDATE Productios
SET CountryCode = (CASE
WHEN @SOffice IN('LA','GA')
THEN 'USA' ELSE 'CAN'
END),
ProvinceCode = @ProvinceCode
WHERE ID = @newProductionID";
cmd.Parameters.AddRange(new[]{
new SqlParameter("SOffice",DbType.Char,2)
{
Value = "LA"
},
new SqlParameter("ProvinceCode",DbType.Int)
{
Value = user.GetProvinceCode()
},
new SqlParameter("newProductionID",DbType.Int)
{
Value = newProductionID
}
});
if(!conn.State == ConnectionState.Open)
conn.Open();
var resultCount = cmd.ExecuteNonQuery();
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Username and Password not Matching Error Messages in Java
The below form , retrieves MySQL database username and password and check them with user's input.
Error messages on password or username incorrect is not showing. I tried many methods but not working as expected.
How can I code that functionality?
private void mysettingChangebtnActionPerformed(java.awt.event.ActionEvent evt) {
String val1 = usernametxt.getText();
String val2 = passwordtxt.getText();
if( val1.equals("") || val2.equals("")){
JOptionPane.showMessageDialog(null, "Fill all fields and try again .... ");
usernametxt.setText("");
passwordtxt.setText("");
}
try{
String sql1 = "SELECT username FROM logininfo WHERE username LIKE '"+val1+"'" ;
String sql2 = "SELECT password FROM logininfo WHERE password LIKE '"+val2+"'" ;
pst1 = conn.prepareStatement(sql1);
pst2 = conn.prepareStatement(sql2);
rs1 = pst1.executeQuery();
rs2 = pst2.executeQuery();
while(rs1.next()){
String uname=rs1.getString("username");
//System.out.println(uname);
while(rs2.next()){
String pwd=rs2.getString("password");
//System.out.println(pwd);
if(val1.equals(uname) && val2.equals(pwd)){
chg2.setVisible(true);
this.setVisible(false);
} else{
JOptionPane.showMessageDialog(null, "Login Information is Incorrect. Try Again.... ");
}
if(!(val1.equals(uname)) || !(val2.equals(pwd))){
JOptionPane.showMessageDialog(null, "Login Information is Incorrect. Try Again.... ");
}
}}
}catch(SQLException | HeadlessException e){
JOptionPane.showMessageDialog(null, "errrrrr"+e);
}
}
A:
You might need to look up the user by username AND password:
String username = usernametxt.getText();
String password = passwordtxt.getText();
// avoid SQL injection by setting query parameters with '?'
String sql = "SELECT * FROM logininfo WHERE username = ? AND password = ?";
PreparedStatement st = conn.prepareStatement(sql);
st.setString(1, username);
st.setString(2, password );
ResultSet rs = st.executeQuery();
if (!rs.next()) {
// no records found, login failed
JOptionPane.showMessageDialog(null, "Login Information is Incorrect.");
}
else {
// record found, login succeeded
// assuming here that there is a unique constraint in the database
// on (username, password), otherwise multiple records could be found
chg2.setVisible(true);
this.setVisible(false);
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Probability Concepts
Which of these numbers cannot be a probability?
a) $-0.00001$
b) $0.5$
c) $1.001$
d) $0$
e) $1$
f) $20\%$
Probability can either be expressed in percentages, decimals, proper fractions or numbers between 0 to 1, that is, not likely to happen or most likely to happen. Therefore a and c are not probability. What are the concepts behind this? Thanks in advance!
A:
(Thank you. I found the defining properties of probability which sums up your comments)
Probability has two defining properties:
1.The probability of any event is a number between 0 and 1, or 0 < P(E) < 1. A P followed by parentheses is the probability of (event E) occurring. Probabilities fall on a scale between 0, or 0%, (impossible) and 1, or 100%, (certain). There is no such thing as a negative probability (less than impossible) or a probability greater than 1 (more certain than certain).
2.The sum of all probabilities of all events equals 1, provided the events are both mutually exclusive and exhaustive. If events are not mutually exclusive, the probabilities would add up to a number greater than 1, and if they were not exhaustive, the sum of probabilities would be less than 1.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Subtraction operator work but Addition operator not working
I has been view some topic about Operator Not Working, but cannot solve my problem.
I have 2 JavaScript code.
<span id="number">this work</span>
<span id="miaonumber">this doesn't work</span>
<script>
setTimeout(start, 1000);
var hh = 9999.9999;
var num = document.getElementById('number');
function start() {
setInterval(increase, 1000);
}
function increase() {
if (hh > 0.0001) {
hh = (hh-0.0001).toFixed(15);
num.innerText = hh;
}
}
setTimeout(startmiao, 1000);
var zz = 8888.8888;
var nummiao = document.getElementById('miaonumber');
function startmiao() {
setInterval(increasemiao, 1000);
}
function increasemiao() {
if (zz > 0) {
zz = (zz+0.0001).toFixed(15);
nummiao.innerText = zz;
}
}
</script>
The <span id="number"></span> will work, but the <span id="miaonumber"></span> doesn't work, I open F12 to view, every second +1 error Uncaught TypeError: (zz + 0.0001).toFixed is not a function
A:
You're converting both hh and zz to strings when you use .toFixed(). If you keep them as numbers then they both work. Simply move the .toFixed() to where you set the element text.
setTimeout(start, 1000);
var hh = 9999.9999;
var num = document.getElementById('number');
function start() {
setInterval(increase, 1000);
}
function increase() {
if (hh > 0.0001) {
hh = hh - 0.0001;
num.innerText = hh.toFixed(15);
}
}
setTimeout(startmiao, 1000);
var zz = 8888.8888;
var nummiao = document.getElementById('miaonumber');
function startmiao() {
setInterval(increasemiao, 1000);
}
function increasemiao() {
if (zz > 0) {
zz = zz + 0.0001;
nummiao.innerText = zz.toFixed(15);
}
}
<span id="number">this work</span><br />
<span id="miaonumber">this doesn't work</span>
Javascript is sensible enough to know that when you subtract values it's most likely that you want them to be numbers, so "123" - 1 == 122, but when you try to add it assumes you want to append to an existing string, so "123" + 1 == "1231"
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Image not resizing correctly using GD library
I'm developing a custom script to import photos from an FTP folder into Wordpress. Since I do not include wp-load due to specific customer requests, I can not use the various classes like $ wpdb, etc ...
So I had to create the whole script, but I found a problem on resizing the photos with watermark applied...
This script picks up the photos in a folder, moves the original photo in high quality to a hidden folder to the public, then later, creates the copies in low resolution and applies the watermark above.
This is the primary function that cycle each photo contained in a folder:
function generate_resized_image($path_to, $path_from, $image, $sell_media_dir){
$upload_dir = wp_upload_dir();
$all_size = array(
'1' => array('width'=>150, 'height'=>150), //thumbnail
'2' => array('width'=>620, 'height'=>357), //medium
'3' => array('width'=>768, 'height'=>442), //medium_large
'4' => array('width'=>100, 'height'=>70), //very-small
'5' => array('width'=>300, 'height'=>200), //max-user-view
);
rename(str_replace(".jpg", ".JPG", $path_from), str_replace(".JPG", ".jpg", $path_to));
$newname = explode(".", $image);
foreach($all_size as $size){
//$path_to_save = $sell_media_dir."/".$newname[0]."-".$size['width']."x".$size['height'].".jpg";
$path_to_sell = $upload_dir['path']."/".$newname[0]."-".$size['width']."x".$size['height'].".jpg";
$img = resize_image( str_replace( ".JPG", ".jpg", $path_to ), $size['width'], $size['height'], $cut=($size['width'] == $size['height']) ? true : false);
imagejpeg($img, $path_to_sell, 10);
echo 'Immagine creata: ' . $newname[0]."-".$size['width']."x".$size['height'].".jpg ". PHP_EOL;
//rename($path_to_save, $path_to_sell);
}
$or_image = imagecreatefromjpeg( str_replace( ".JPG", ".jpg", $path_to ) );
imagejpeg($or_image, $upload_dir['path']."/".str_replace(".JPG",".jpg",$image), 10);
$img_size = getimagesize($upload_dir['path']."/".str_replace(".JPG",".jpg",$image));
return array(
'width' => $img_size[0],
'height' => $img_size[1]
);
}
This call a function resize_image that, in theory, resize the images by applying the watermark above.
function resize_image($file, $w, $h, $crop=FALSE) {
$stamp = imagecreatefrompng('./wp-content/uploads/2018/11/spanshot_watermark.png');
list($width, $height) = getimagesize($file);
$r = $width / $height;
if ($crop) {
if ($width > $height) {
$width = ceil($width-($width*abs($r-$w/$h)));
} else {
$height = ceil($height-($height*abs($r-$w/$h)));
}
$newwidth = $w;
$newheight = $h;
} else {
if ($w/$h > $r) {
$newwidth = $h*$r;
$newheight = $h;
} else {
$newheight = $w/$r;
$newwidth = $w;
}
}
$src = imagecreatefromjpeg($file);
$w = imagesx($src);
$h = imagesy($src);
$stamp = PNGResize($stamp, $w, $h);
$sx = imagesx($stamp);
$sy = imagesy($stamp);
// $par1 = (imagesx($src)/2)-($sx/2);
// $par2 = (imagesy($src)/2)-($sy/2);
imagecopy($src, $stamp, 0, 0, 0, 0, imagesx($stamp), imagesy($stamp));
echo "La lunghezza nuova è: " . $newwidth . PHP_EOL;
echo "L'altezza nuova è: " . $newheight . PHP_EOL;
$dst = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
return $src;
}
Finally, this function calls PNGResize a resizing of the watermark while maintaining the transparency, which adapts the latter to the size of the image to be resized.
function PNGResize($image, $w, $h)
{
$oldw = imagesx($image);
$oldh = imagesy($image);
$temp = imagecreatetruecolor($w, $h);
imagealphablending( $temp, false );
imagesavealpha( $temp, true );
imagecopyresampled($temp, $image, 0, 0, 0, 0, $w, $h, $oldw, $oldh);
return $temp;
}
All this works correctly, except for the resizing of moveable images, which keep the original dimensions indifferently from the parameters, lowering the quality.
These are the original images in the right folder:
And these are the images, correctly moved, but not properly resized.
I do not understand why the images are not resized according to the past dimensions, can someone help me?
A:
In you resize_image function you are returning the $src which should change with $dst which is resized image.
So in your function change return $src; line with return $dst; and it will work.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
apt-get duplicate sources.list entry for google-chrome (Ubuntu 11.10)
I am running Ubuntu 11.10.
This is the only line in my /etc/apt/sources.list with the text "google" or "chrome" in it:
deb http://dl.google.com/linux/chrome/deb/ stable main
Sometimes (not always) when I run apt-get update, I get these warnings at the end of the output:
Reading package lists... Done
W: Duplicate sources.list entry http://dl.google.com/linux/chrome/deb/ stable/main amd64 Packages (/var/lib/apt/lists/dl.google.com_linux_chrome_deb_dists_stable_main_binary-amd64_Packages)
W: Duplicate sources.list entry http://dl.google.com/linux/chrome/deb/ stable/main i386 Packages (/var/lib/apt/lists/dl.google.com_linux_chrome_deb_dists_stable_main_binary-i386_Packages)
W: You may want to run apt-get update to correct these problems
If I run apt-get update again immediately after receiving these warnings, they don't show up the second time (or third time, etc...). But then the warnings always come back eventually.
In any case, installing/updating google-chrome works fine, but those warnings are annoying (and since I skim over them now, I may inadvertently miss some more important warning if one ever comes up).
Any way to get rid of these warnings permanently?
A:
When you installed chrome it most likely added a file in /etc/apt/sources.list.d/ named google-chrome.list. You should remove the line you manually added, and just keep the file that is in there, which is what the chrome package uses.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to add codesigning to dmg file in mac
I have a dmg file in my portal.After downloading it,when i try to open it is showing a message indicating that opening package is insecure. i am able to add codesign through command line using codesign command and also able to check whether it is added or not. but still when i click to open my dmg file insecure message is coming
A:
As of macOS 10.11.5 you can now sign disk images, .dmg, files using the codesign tool:
codesign -s <identity> --keychain <full-path-to-keychain> <path-to-disk-image>
A:
There's 3 ways to do this. In the terminal on OS X 10.11.5 or newer. Note: you can code sign DMGs on earlier OS versions, however Sierra only likes them from 10.11.5 or newer.
codesign --force --sign "Developer ID Application: <identityIdentifier>" <pathToDMG>
Verification is done via (requires macOS Sierra).
spctl -a -t open --context context:primary-signature -v <pathToDMG>
Araelium have updated DMG Canvas (v2.3), so it will code sign DMGs when it builds.
DropDMG has been updated to code sign DMG image files too (v3.4).
There's also (a tool I developed) called App Wrapper (3.6), which can code sign DMG files.
A:
Earlier I struggle to code sign dmg on 10.11.5 even this command codesign -s <identity> <path-to-disk-image> is known to me.
What I am doing earlier is
Create the Read/Write DMG (created using Disk utility)
Copy App and other external resources
Code signed DMG using codesign command
Convert it to Read only DMG using Disk Utility
Verify it using spctl -a -t open --context context:primary-signature <path-to-disk-image>, which results in rejection.
Then few permutation and combination, I found it pretty easy straight forward solution:
Create the Read/Write DMG (created using Disk utility).
Copy App and other external resources
Convert it to Read only DMG using Disk Utility
Code signed DMG using codesign command (This time I did it on Sierra, most probably should work with 10.11.5)
Verify it using spctl -a -t open --context context:primary-signature <path-to-disk-image>, that results in success.
I hope this works for you. :)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Compute matrix inverse using biogo?
I'm working on a Kalman filter implementation in Go. After reading this thread, I decided to use biogo for matrix operations. However, it appears from the documentation that biogo doesn't provide a function to calculate the inverse of a matrix.
Does anyone know otherwise or know of an easy way to calculate the inverse using the functions that biogo does provide? Thanks!
A:
If you're willing to switch to the github.com/gonum/matrix package, then it provides an Inverse function that you can use. The interfaces of the two packages appear similar.
From posts on the gonum-dev mailing list, it appears that gonum/matrix is the way forward (and will eventually replace biogo.matrix).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Quando rolo minha listView perco os checkboxes marcados
Esse é um código do meu adapter, nele eu tenho um textview e 4 chekboxes. O problema é que eu acredito que tenho que salvar o status dos meus checkboxes, para não perder os dados dele, porque quando eu rolo minha list view meus checkboxes desmarcam sozinhos.
public class ListaFuncionarioAdapter extends BaseAdapter {
/*
private Activity activity;
private List<MeuItem> itens;
public ListaFuncionarioAdapter(Activity activity, List<MeuItem> itens){
this.activity = activity;
this.itens = itens;
}
*/
private List<MeuItem> itens;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
CheckBox chkSalManha, chkDoceManha, chkSalTarde, chkDoceTarde;
private Context context;
private List<QtdePaes> listQtdePaes = new ArrayList<QtdePaes>();
private ArrayAdapter<QtdePaes> arrayAdapterQtdePaes;
QtdePaes qtdePaesSelecionado;
private List<Funcionario> listFuncionario;
final QtdePaes qtdePaes = new QtdePaes();
int salmanha = 0;
int saltarde = 0;
int docemanha = 0;
int docetarde = 0;
public ListaFuncionarioAdapter(Context context, List<Funcionario> listFuncionario) {
this.context = context;
this.listFuncionario = listFuncionario;
}
private void inicializarFirebase() {
FirebaseApp.initializeApp(context);
firebaseDatabase = FirebaseDatabase.getInstance();
// firebaseDatabase.setPersistenceEnabled(true);
databaseReference = firebaseDatabase.getReference();
//DatabaseReference novaReference = firebaseDatabase.getReference();
// novaReference = databaseReference.child("minh");
}
@Override
public int getCount() {
return listFuncionario.size();
}
@Override
public Object getItem(int position) {
return listFuncionario.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v= View.inflate(context, R.layout.item_funcionario, null);
chkSalManha = (CheckBox)v.findViewById(R.id.chkSalManha);
chkDoceManha = (CheckBox)v.findViewById(R.id.chkDoceManha);
chkSalTarde = (CheckBox)v.findViewById(R.id.chkSalTarde);
chkDoceTarde = (CheckBox)v.findViewById(R.id.chkDoceTarde);
TextView txtNome = (TextView)v.findViewById(R.id.txtNome);
inicializarFirebase();
txtNome.setText(String.valueOf(listFuncionario.get(position).getNome()));
//MeuItem item = itens.get(position);
//chkSalManha.setTag(item);
//chkSalManha.setChecked(item.foiMarcado());
v.setTag(listFuncionario.get(position).getUid());
chkSalManha.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
salmanha += 1;
String estado = (String) chkSalManha.getTag();
// qtdePaes.setUid(UUID.randomUUID().toString());
qtdePaes.setQtdeSalManha(salmanha);
qtdePaes.setQtdeDoceManha(docemanha);
qtdePaes.setQtdeSalTarde(saltarde);
qtdePaes.setQtdeDoceTarde(docetarde);
//databaseReference.child("QtdePaes").child(qtdePaes.getUid()).setValue(qtdePaes);
databaseReference.child("QtdePaes").child("6fd2aede-e00f-48d8-b6cb-f1498e23e8e8").setValue(qtdePaes);
}
if(!isChecked)
{
salmanha -= 1;
//qtdePaes.setUid(qtdePaesSelecionado.getUid());
qtdePaes.setQtdeSalManha(salmanha);
qtdePaes.setQtdeDoceManha(docemanha);
qtdePaes.setQtdeSalTarde(saltarde);
qtdePaes.setQtdeDoceTarde(docetarde);
databaseReference.child("QtdePaes").child("6fd2aede-e00f-48d8-b6cb-f1498e23e8e8").setValue(qtdePaes);
}
}
});
chkSalTarde.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
saltarde += 1;
//qtdePaes.setUid(UUID.randomUUID().toString());
qtdePaes.setQtdeSalTarde(salmanha);
qtdePaes.setQtdeDoceManha(docemanha);
qtdePaes.setQtdeSalTarde(saltarde);
qtdePaes.setQtdeDoceTarde(docetarde);
//databaseReference.child("QtdePaes").child(qtdePaes.getUid()).setValue(qtdePaes);
databaseReference.child("QtdePaes").child("6fd2aede-e00f-48d8-b6cb-f1498e23e8e8").setValue(qtdePaes);
}
if(!isChecked)
{
saltarde -= 1;
//qtdePaes.setUid(qtdePaesSelecionado.getUid());
qtdePaes.setQtdeSalTarde(salmanha);
qtdePaes.setQtdeDoceManha(docemanha);
qtdePaes.setQtdeSalTarde(saltarde);
qtdePaes.setQtdeDoceTarde(docetarde);
databaseReference.child("QtdePaes").child("6fd2aede-e00f-48d8-b6cb-f1498e23e8e8").setValue(qtdePaes);
}
}
});
chkDoceManha.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
docemanha += 1;
//qtdePaes.setUid(UUID.randomUUID().toString());
qtdePaes.setQtdeSalTarde(salmanha);
qtdePaes.setQtdeDoceManha(docemanha);
qtdePaes.setQtdeSalTarde(saltarde);
qtdePaes.setQtdeDoceTarde(docetarde);
//databaseReference.child("QtdePaes").child(qtdePaes.getUid()).setValue(qtdePaes);
databaseReference.child("QtdePaes").child("6fd2aede-e00f-48d8-b6cb-f1498e23e8e8").setValue(qtdePaes);
}
if(!isChecked)
{
docemanha -= 1;
//qtdePaes.setUid(qtdePaesSelecionado.getUid());
qtdePaes.setQtdeSalTarde(salmanha);
qtdePaes.setQtdeDoceManha(docemanha);
qtdePaes.setQtdeSalTarde(saltarde);
qtdePaes.setQtdeDoceTarde(docetarde);
databaseReference.child("QtdePaes").child("6fd2aede-e00f-48d8-b6cb-f1498e23e8e8").setValue(qtdePaes);
}
}
});
chkDoceTarde.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
docetarde += 1;
// qtdePaes.setUid(UUID.randomUUID().toString());
qtdePaes.setQtdeSalTarde(salmanha);
qtdePaes.setQtdeDoceManha(docemanha);
qtdePaes.setQtdeSalTarde(saltarde);
qtdePaes.setQtdeDoceTarde(docetarde);
//databaseReference.child("QtdePaes").child(qtdePaes.getUid()).setValue(qtdePaes);
databaseReference.child("QtdePaes").child("6fd2aede-e00f-48d8-b6cb-f1498e23e8e8").setValue(qtdePaes);
}
if(!isChecked)
{
docetarde -= 1;
//qtdePaes.setUid(qtdePaesSelecionado.getUid());
qtdePaes.setQtdeSalTarde(salmanha);
qtdePaes.setQtdeDoceManha(docemanha);
qtdePaes.setQtdeSalTarde(saltarde);
qtdePaes.setQtdeDoceTarde(docetarde);
databaseReference.child("QtdePaes").child("6fd2aede-e00f-48d8-b6cb-f1498e23e8e8").setValue(qtdePaes);
}
}
});
return v;
}
}
A:
Cada vez que a ListView necessita de renderizar um item/linha chama o método getView() do adapter.
Na implementação desse método é feito o inflate de um novo layout e é atribuído às suas views os respectivos valores.
Este processo é repetido enquanto houver itens na lista ou a altura da ListView ficar preenchida.
Quando é feito scroll, novos layouts são "inflados" para as posições inferiores e os das posições superiores são descartados.
O processo é idêntico quando o scroll é feito em sentido contrário.
Se entretanto tiver marcado qualquer um dos CheckBox, essa marcação será perdida quando o respectivo layout/item/linha for descartado em consequência do scroll.
Assim, a solução passa por guardar o estado dos checbox's no objecto que é usado para preencher a ListView e atribuí-lo ao CheckBox da mesma forma que são atribuídos os valores às outra views. Veja aqui um exemplo.
Nota: Para tornar o processo de criação de novos layouts mais eficiente considere usar o padrão View holder ou uma RecyclerView.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
java.sql.SQLException: column id is not unique
I have a program written in Java which parses a set of files and places information about them inside a database using sqlite. The code seems to work fine for a while until one day I get this Exception:
Exception in thread "main" java.sql.SQLException: column id is not unique
at org.sqlite.DB.throwex(DB.java:370)
at org.sqlite.DB.executeBatch(DB.java:302)
at org.sqlite.PrepStmt.executeBatch(PrepStmt.java:93)
at DatabaseTest.main(DatabaseTest.java:43)
As it turned out, two of the files were somehow interfering with each other in my code. I have constructed a smaller program which still gives the same problem.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
public class DatabaseTest {
public static void main(String[] args) throws SQLException {
System.out.println(new org.sqlite.JDBC().toString());
Connection conn = DriverManager.getConnection("jdbc:sqlite:my_file.sqlite");
Statement stat = conn.createStatement();
try {
stat.executeUpdate("drop table if exists my_table;");
stat.executeUpdate("create table my_table (id STRING UNIQUE, content STRING);");
PreparedStatement prep = conn.prepareStatement("insert into my_table values (?, ?);");
prep.setString(1, "0325E498"); // I keep this value same for all tests
prep.setString(2, "test1");
prep.addBatch();
//prep.setString(1, "0336E810"); // Gives error
//prep.setString(1, "0336E8100"); // Gives error
//prep.setString(1, "0336E8100000"); // Gives error
//prep.setString(1, "0336E8111111"); // Gives error
//prep.setString(1, "1336E811"); // Gives error
//prep.setString(1, "9336E811"); // Gives error
//prep.setString(1, "A336E811"); // OK!
//prep.setString(1, "111111111E811"); // Gives error
prep.setString(1, "111111111E311"); // Gives error
//prep.setString(1, "111111111E211"); // OK!
prep.setString(2, "test2");
prep.addBatch();
conn.setAutoCommit(false);
prep.executeBatch(); // Exception thrown here
conn.setAutoCommit(true);
} finally {
stat.close();
conn.close();
}
}
My current maven dependency information.
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.7.2</version>
</dependency>
So am I doing something wrong and why does this work for most strings but not all? Is the uniqueness calculated in a non straightforward manner?
A:
It seems like the issue was related to using the wrong datatype, it should have been TEXT instead of STRING. From sqlite documentation:
Note that a declared type of "FLOATING POINT" would give INTEGER affinity, not REAL affinity, due to the "INT" at the end of "POINT". And the declared type of "STRING" has an affinity of NUMERIC, not TEXT.
So the string "111111111E311" will be considered an OK number but is too large and what's put in the entry is NaN. The string "111111111E211" is slightly smaller and can be stored as it is.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
IIS 7 URL rewrite module equivalent Apache mod_rewritte?
Currently we have an API serving in Apache with Mod Rewrite module with the following rules:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [L,NS]
As you can see it obtains the URI segments as they are and calls only index.php which is in charge of exploding all segments '/'.
We are just starting with this new URL Rewrite Module that we downloaded in the IIS official web page.
We have also seen that there are rules within the IIS like Frienly SEO urls and other stuff.
so the question is, How Can I achieve the rules above to work with this IIS module?
A:
Just import it on the IIS server. The IIS server will automatically convert the rewrite rule.
To do this just select your website or the Default Web Site then click on Features View > URL Rewrite > Import Rules (on Action Pane).
Here are some reference to start with:
Importing Apache mod_rewrite rules
Converting mod_rewrite rules to IIS7 URL rewrite rules
IIS7 URL rewrite importing IIS mod_rewrite rules from Apache
|
{
"pile_set_name": "StackExchange"
}
|
Q:
parse array and get a given child element in yaml python3
I have yaml as below
environments:
qa:
east:
appname:testapp
west:
appname:testapp2
prod:
east:
appname:testapp
west:
appname:testapp2
And i want to iterate environments and pick key for agiven environment value.
For instance:
environment='qa'
region='east'
now i would like to iterate environments and pick appname under qa & east values
A:
You mean something like this? (Note that you need to put a space after appname:, otherwise the yaml parser takes appname:testapp as a string, and not a key/value pair)
import yaml
config_yaml = """environments:
qa:
east:
appname: testapp
west:
appname: testapp2
prod:
east:
appname: testapp
west:
appname: testapp2"""
config = yaml.load(config_yaml)
def appname(env, area):
return config['environments'][env][area]['appname']
if __name__ == '__main__':
print(appname('qa', 'east'))
As @zwer correctly stated: What you are trying to do it not "iterate" over it, but "look up" the data. In python, config is a dict, which is a hashtable data structure. You can directly access values by a key. Whereas in an list (=array) in python you need to iterate (=traverse) the data structure in order to find an item.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Setting up the MMA8452 to trigger interrupt
I am working with the MMA8452q accelerometer by Freescale. I am trying to set it up to be in low power mode, to go to sleep when no motion has happened, and to wake up due to motion being detected and trigger the interrupt that corresponds to it. I am using Arduino.
I have verified the accelerometer works (i.e. can read off accelerometer data and communicate properly to it via I2C), and I have also verified that the interrupt and handler all work (by manually triggering the interrupt as compared to using the accelerometer). However, after initializing using the code below, my interrupt due to motion is not getting triggered.
-The datasheet can be found here: http://www.freescale.com/files/sensors/doc/data_sheet/MMA8452Q.pdf
-App note can be found here: http://cache.freescale.com/files/sensors/doc/app_note/AN4074.pdf
My code is as follows:
void MMA8452::initMMA8452(unsigned char fsr)
{
//CONFIGURE THE ACCELEROMETER
MMA8452Standby(); // Must be in standby to change registers
//Set up the full scale range to 2, 4, or 8g.
if ((fsr==2)||(fsr==4)||(fsr==8))
writeRegister(XYZ_DATA_CFG, fsr >> 2);
else
writeRegister(XYZ_DATA_CFG, 0);
writeRegister(CTRL_REG1, readRegister(CTRL_REG1) | bmRES1DOT56); //1.56Hz resolution in both wake and sleep mode (lowest power)
writeRegister(CTRL_REG2, readRegister(CTRL_REG2) | (LP << SMODS) | (LP << MODS) | (1 << SLPE)); //LOW POWER MODE IN SLEEP & ACTIVE STATES WITH LOWEST SAMPLING
writeRegister(CTRL_REG3, (1 << WAKE_FF_MT)); //ONLY WAKE UP FROM MOTION DETECTION
writeRegister(CTRL_REG4, (1 << INT_EN_ASLP) | (1 << INT_EN_FF_MT)); //ENABLE SLP/AWAKE INTERRUPT (INTERRUPT THROWN WHENEVER IT CHANGES) & MOTION INTERRUPT TO KEEP AWAKE
writeRegister(ASLP_COUNT, ASLP_TIMEOUT); //162s TIMEOUT BEFORE SLEEPING
writeRegister(CTRL_REG5, (1 << INT_CFG_FF_MT) | (1 << INT_CFG_ASLP)); //INTERRUPT SLEEP AND FREE FALL TO INT1 PIN OF MMA8452
//SETUP THE MOTION DETECTION
writeRegister(FF_MT_CFG, (1 << ELE) | (1 << OAE)); //MOTION DETECTION AND LATCH THE RESULT WHEN IT HAPPENS AS OPPOSED TO COMBINATIONAL REAL TIME
writeRegister(FF_MT_THS, MOTION_THRESHOLD); //MOTION DETECTION THRESHOLDS
writeRegister(FF_MT_COUNT, MOTION_DEBOUNCE_COUNT); //TIME MOTION NEEDS TO BE PRESENT ABOVE THE THRESHOLD BEFORE INTERRUPT CAN BE ASSERTED
MMA8452Active();
};
A:
I played around more with it, and this code works:
void MMA8452::initMMA8452(unsigned char fsr, unsigned char dr, unsigned char sr, unsigned char sc, unsigned char mt, unsigned char mdc)
{
MMA8452Standby();
//Set up the full scale range to 2, 4, or 8g.
if ((fsr==2)||(fsr==4)||(fsr==8))
writeRegister(XYZ_DATA_CFG, fsr >> 2);
else
writeRegister(XYZ_DATA_CFG, 0);
writeRegister(CTRL_REG1, readRegister(CTRL_REG1) & ~(0xF8));
if (dr<= 7)
writeRegister(CTRL_REG1, readRegister(CTRL_REG1) | (dr << DR0));
if (sr<=3)
writeRegister(CTRL_REG1, readRegister(CTRL_REG1) | (sr << ASLP_RATE0));
writeRegister(CTRL_REG2, readRegister(CTRL_REG2) | (LP << SMODS) | (LP << MODS) | (1 << SLPE)); //LOW POWER MODE IN SLEEP & ACTIVE STATES WITH LOWEST SAMPLING
writeRegister(ASLP_COUNT, sc);
// Set up interrupt 1 and 2: 1 = wake ups, 2 = data
writeRegister(CTRL_REG3, (1 << WAKE_FF_MT) | (1 << IPOL)); // Active high, push-pull interrupts, sleep wake up from motion detection
writeRegister(CTRL_REG4, (1 << INT_EN_ASLP) | (1 << INT_EN_FF_MT) | (1 << INT_EN_DRDY)); // DRDY ENABLE SLP/AWAKE INTERRUPT (INTERRUPT THROWN WHENEVER IT CHANGES) & MOTION INTERRUPT TO KEEP AWAKE
writeRegister(CTRL_REG5, (1 << INT_CFG_ASLP) | (1 << INT_CFG_FF_MT)); // DRDY on INT1, ASLP_WAKE INT2, FF INT2
writeRegister(CTRL_REG5, readRegister(CTRL_REG5));
//SETUP THE MOTION DETECTION
writeRegister(FF_MT_CFG, 0xF8); /*MOTION DETECTION AND LATCH THE
//RESULT WHEN IT HAPPENS AS OPPOSED
//TO COMBINATIONAL REAL TIME*/
writeRegister(FF_MT_THS, mt); //MOTION DETECTION THRESHOLDS
writeRegister(FF_MT_COUNT, mdc); //TIME MOTION NEEDS TO BE
//PRESENT ABOVE THE THRESHOLD BEFORE INTERRUPT CAN BE ASSERTED
MMA8452Active();
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
A specified Include path is not valid. The EntityType 'SpiceShop.Models.Product' does not declare a navigation property with the name 'Products'
I Have Database that contains 2 tables
TABLE Categories (CategoriesId, Name, Description)
TABLE Products (ProductId, CategoriesId, Title, ProductImageUrl)
Categories is linked to Products by CategoriesId.
I am trying to use LINQ to get all of a particular Title.
public ActionResult Browse(string categories)
{
var spices = spiceDB.Products.Include("Products").Single(p => p.Title == categories);
return View(spices);
}
Product Model
namespace SpiceShop.Models
{
public class Product
{
[Key]
public int ProductId { get; set; }
public int CategoriesId { get; set; }
public string Title { get; set; }
public string ProductImageUrl { get; set; }
public List <Categorie> Name { get; set; }
}
}
Categorie Model
namespace SpiceShop.Models
{
public class Categorie
{
[Key]
public int CategoriesId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
//public List<Product> ProductId { get; set; }
public List<Product> Products { get; set; }
}
}
A:
Just remove the .Include("Products"), that's not how it's used.
The error is clear, there is no "Products" property at your "Product" model.
A:
Edit:
It looks like your View requires a Model that is a single object of type "Product".
Also, I have tried to give each of my identifiers/variables a name that best conveys their meaning and intent.
Edit 2:
Please note that changing any input parameter names on a method will require a corresponding change in your View code that calls the method.
In MVC, Action-Method parameters are automatically mapped.
Your debug shows a URL of Browse?categories=Sauces, which is automatically mapped to the method "Browse" with input parameter categories set to "Sauces". But (my version of) the Browse method is expecting a categoryName parameter, not categories. So you will need to make sure that URL Attribute and the Method Parameter have exactly the same name.
So if you really need to pass the selected Category's Name as the input parameter:
public ActionResult Browse(string categoryName)
{
// Gets the CategoryId for the given categoryName, or zero if not found.
var categoryId = spiceDB.Categories
.Where(c => c.Name == categoryName)
.Select(c => c.CategoriesId)
.FirstOrDefault();
// Gets the first Product (only) for the specified categoryId.
var firstProduct = category.Products
.FirstOrDefault(p => p.CategoriesId == categoryId);
return View(firstProduct);
}
However, a much more common usage scenario for supporting this type of "parent-child" relationship would be:
Your Category List invokes a query by ID when clicked, not a query by Name (i.e. 3, not "Pickles")
Your View supports all the related Products, not just the first one (i.e. a model of type List<Product>, not just Product)
e.g.
public ActionResult Browse(int categoryId)
{
var products = spiceDB.Products
.Where(p => p.CategoriesId == categoryId)
.ToList();
return View(products);
}
i.e. making your Product List more comprehensive, and your data access code simpler and more efficient.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
importance of link identifier in mysql_real_escape_string()
Why is it necessary to have a link identifier as an input when using mysql_real_escape_string(). I know that the function should be used with MySQL queries, but the function is really just a string manipulation.
A:
From the PHP manual:
Escapes special characters in the unescaped_string , taking into account the current character set of the connection so that it is safe to place it in a mysql_query(). If binary data is to be inserted, this function must be used.
and:
If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
A connection is needed to determine the character set.
A:
Have a read of http://ilia.ws/archives/103-mysql_real_escape_string-versus-Prepared-Statements.html
For example, if GBK character set is being used, it will not convert an invalid multibyte sequence 0xbf27 (¿’) into 0xbf5c27 (¿\’ or in GBK a single valid multibyte character followed by a single quote). To determine the proper escaping methodology mysql_real_escape_string() needs to know the character set used, which is normally retrieved from the database connection cursor.
Maybe as a consequence of this article but clearly after it the function mysql_set_charset() has been added to the mysql extension. The charset is a property of the mysql connection (resource).
If you have multiple connections you really should pass them to mysql_real_escape_string() (and always use mysql_set_charset() instead of SET NAMES).
If you don't pass the connection resource the function will use the last connection established by your script. If the charset of the two (or more connections) differ the result of real_escape_string() may be misinterpreted by the server (expecting another encoding and therefore different escaping rules).
And since it doesn't hurt to do so even if you have only one connection (can you say with absolute certainty that this will be so until the end of time?) just pass it always.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I check if one element in an array satisfies a pattern, while the rest don't?
I'm using Ruby 2.4. I know how to check if a string is all capitalized by doing
str == str.upcase
but if I have an array of strings, what is a quick way to check that only the last element of the array is capitalized while, for the other elements, str != str.upcase . I'm assuming there is at least one element in the array and if there is only one element and it is capitalized, I would want my condition to evaluate to true.
A:
def only_last_upcase?(arr)
arr.find_index { |w| w == w.upcase } == arr.size - 1
end
only_last_upcase? ["word", "wOrD", "WORD"] #=> true
only_last_upcase? ["WORD", "wOrD", "WORD"] #=> false
only_last_upcase? ["word", "wOrD", "word"] #=> false
only_last_upcase? ["word"] #=> false
only_last_upcase? ["Word"] #=> false
only_last_upcase? ["WORD"] #=> true
only_last_upcase? [] #=> false
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Select several checkboxes in the same group
So I have a set of checkboxes, where I can only check one box per group, how do I change so I can check multiple boxes per group?
Codepen: http://codepen.io/anon/pen/dNwqzx
$(document).ready(function() {
$(".filterGenius input").each(function() {
if (window.location.href.indexOf($(this).val()) >= 0) {
$(this).attr("checked", "checked")
}
});
$(".filterGenius select option").each(function() {
if (window.location.href.indexOf($(this).val()) >= 0) {
$(this).attr('selected', true);
}
});
$(".filterGenius input").change(function() {
var s = encodeURI(unescape(jQuery.query.set("fss", getFSS())));
var o = window.location.href.split("?")[0];
$(".filterGenius input").attr("disabled", true);
window.location.href = o + s
});
});
$('input[type="checkbox"]').on('change', function() {
$('input[name="' + this.name + '"]').not(this).prop('checked', false);
});
<div class="filterGenius">
<div class="col">
<b>Manufacturer</b>
<br>
<input type="checkbox" name="Manufacturer" value="HP" /> <span class "filtertext">HP</span>
<br>
<input type="checkbox" name="Manufacturer" value="Dell" /> <span class "filtertext">Dell</span>
<br>
<input type="checkbox" name="Manufacturer" value="Lenovo" /> <span class "filtertext">Lenovo</span>
<br>
<input type="checkbox" name="Manufacturer" value="Apple" /> <span class "filtertext"> Apple</span>
<br>
<input type="checkbox" name="Manufacturer" value="Acer" /> <span class "filtertext">Acer</span>
<br>
<input type="checkbox" name="Manufacturer" value="Asus" /> <span class "filtertext"> Asus</span>
<br>
</div>
<div class="col">
<b>OS</b>
<br>
<input type="checkbox" name="OS" value="W7H" /> <span class "filtertext">W7H</span>
<br>
<input type="checkbox" name="OS" value="Bing" /> <span class "filtertext">Bing</span>
<br>
<input type="checkbox" name="OS" value="W7P" /> <span class "filtertext">W7P</span>
<br>
<input type="checkbox" name="OS" value="W8P" /> <span class "filtertext">W8P</span>
<br>
<input type="checkbox" name="OS" value="W8.1P" /> <span class "filtertext">W8.1P</span>
<br>
<input type="checkbox" name="OS" value="Freedos" /> <span class "filtertext">Freedos</span>
<br>
<input type="checkbox" name="OS" value="CMAR" /><span class "filtertext"> CMAR</span>
<br>
<input type="checkbox" name="OS" value="COA" /><span class "filtertext"> COA</span>
<br>
</div>
</div>
A:
The last jquery function prevents you from checking multiple boxes. From what I can tell that's all it does. Remove it and you should be able to check as many boxes as you like!
$(document).ready(function () {
$(".filterGenius input").each(function () {
if (window.location.href.indexOf($(this).val()) >= 0) {
$(this).attr("checked", "checked")
}
});
$(".filterGenius select option").each(function () {
if (window.location.href.indexOf($(this).val()) >= 0) {
$(this).attr('selected', true);
}
});
$(".filterGenius input").change(function () {
var s = encodeURI(unescape(jQuery.query.set("fss", getFSS())));
var o = window.location.href.split("?")[0];
$(".filterGenius input").attr("disabled", true);
window.location.href = o + s
});
});
//$('input[type="checkbox"]').on('change', function() {
//$('input[name="' + this.name + '"]').not(this).prop('checked', //false);
//});
<div class="filterGenius">
<div class="col">
<b>Manufacturer</b><br>
<input type="checkbox" name="Manufacturer_1" value="HP" /> <span class"filtertext">HP</span><br>
<input type="checkbox" name="Manufacturer_2" value="Dell" /> <span class"filtertext">Dell</span><br>
<input type="checkbox" name="Manufacturer_3" value="Lenovo" /> <span class"filtertext">Lenovo</span><br>
<input type="checkbox" name="Manufacturer_4" value="Apple" /> <span class"filtertext"> Apple</span><br>
<input type="checkbox" name="Manufacturer_5" value="Acer" /> <span class"filtertext">Acer</span><br>
<input type="checkbox" name="Manufacturer_6" value="Asus" /> <span class"filtertext"> Asus</span><br>
</div>
<div class="col">
<b>OS</b><br>
<input type="checkbox" name="OS_1" value="W7H" /> <span class"filtertext">W7H</span><br>
<input type="checkbox" name="OS_2" value="Bing" /> <span class"filtertext">Bing</span><br>
<input type="checkbox" name="OS_3" value="W7P" /> <span class"filtertext">W7P</span><br>
<input type="checkbox" name="OS_4" value="W8P" /> <span class"filtertext">W8P</span><br>
<input type="checkbox" name="OS_5" value="W8.1P" /> <span class"filtertext">W8.1P</span><br>
<input type="checkbox" name="OS_6" value="Freedos" /> <span class"filtertext">Freedos</span><br>
<input type="checkbox" name="OS_7" value="CMAR" /><span class"filtertext"> CMAR</span><br>
<input type="checkbox" name="OS_8" value="COA" /><span class"filtertext"> COA</span><br>
</div>
</div>
This should (hopefully) achieve what you are setting out to do - as @Yunus Saha pointed out
|
{
"pile_set_name": "StackExchange"
}
|
Q:
angular 2 two-way data binding vs one-way
I have a question about the difference between Angular 2 two-way and one-way data binding. As I understand, one-way data binding is used for data that flows from parent to child. However, if the source of the binding is a reference to an object, the modifications made by the child are reflected on the parent (through the reference). So how is this different from two-way data binding? Or do I misuse one-way binding, and should use two-way when the child modifies the data?
Thanks
A:
Two way Data binding is Between View and Controller ...
In Simple Words
Two Way
Changes made in view will reflect in Controller
Changes made in Controller will reflect in View
One Way
Once you set the value it will not affect the View or Controller for further changes
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.