text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Self inspection of a bris milah
Is it possible for an adult to inspect his own milah to determine if the milah was done in a halachically proper manner? Are there any picture guides or some other type of resources that would help someone who is completely ignorant in the details of what a bris milah entails, to educate himself to the actual practical details of the laws and in turn allow him to inspect his own milah?
A:
When inspection is helpful, self inspection is good enough. For negayim, a man cannot check his own negayim, but for most isurim a man can check himself for shechita, Kashrut and all isurim.
There are a lot of question around a circumcision as other users have said.
We will try to answer a few of them.
If residues of foreskin remain, have we to cut them? The Shulchan Aruch says in Yore Dea siman 264, se'if 5, that if in some place a residue of foreskin covers the majority of the length of the glans, even in a small area, he still needs to circumcise as if he was not circumcised. The Baer Heytev (in name of an opinion reported in Bet Yosef and Shach) adds that if the majority of the circumference of the corona glandis is covered, he is not regarded as circumcised. This part of the inspection may be a self inspection.
Is it important to know who was the Mohel? The Shulchan Aruch in 264, 1, said that even a child or a woman can circumcise, bediavad even a NJ makes a valuable circumcision. But Rama requires brit bloodshed.
The time of the Brit. Rama at the same place explains that a child who was circumcised before his 8th day of life needs also brit bloodshed.
For 2 and 3, I am not convinced that a Jew needs to investigate to ensure that the conditions was fulfilled.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to reverse last N elements of list in python
Suppose I have a list:
>>> numbers = list(range(1, 15))
>>> numbers
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
I need reverse last 10 element only using slice notation
At first, I try just slice w/o reverse
>>> numbers[-10:]
[5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Then:
>>> numbers[-10::-1]
I expected [14, 13, 12, 11, 10, 9, 8, 7, 6, 5]
but got [5, 4, 3, 2, 1].
I can solve the problem like this:
numbers[-10:][::-1]
and everything OK
[14, 13, 12, 11, 10, 9, 8, 7, 6, 5]
But I wondering why numbers[-10::-1] doesn't work as expected in my case and if there a way to get the right result by one slice?
A:
Is there a way to get the right result by one slice?
Well, you can easily get right result by one slicing with code below:
numbers[:-11:-1]
# [14, 13, 12, 11, 10, 9, 8, 7, 6, 5]
Why numbers[-10::-1] doesn't work as expected?
Well it's work as expected, see enumerating of all slicing possibilities in that answer of Explain Python's slice notation question. See quoting ( from answer i've pointed above) of expected behaviour for your use case below:
seq[low::stride] =>>> # [seq[low], seq[low+stride], ..., seq[-1]]
A:
is that what you are looking for?
numbers = list(range(1, 15))
numbers[:-11:-1]
# [14, 13, 12, 11, 10, 9, 8, 7, 6, 5]
slice.indices 'explains':
print(slice(None, -11, -1).indices(len(numbers)))
# (13, 3, -1)
meaning that
numbers[:-11:-1] == numbers[13:3:-1]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How many cows are there?
In a field, the grass increases in a constant rate. $17$ cows can eat all the grass in the field in $30$ days. $19$ cows can eat all the grass in $24$ days. Suppose, a group of cows started eating grass for $6$ days. Then $4$ cows are sold. The rest cows took $2$ more days to eat the remaining grass. What is the number of cows in the group?
My trying:
A cow eats a certain amount of grass in one day, call it $c$.
The field grows by a certain amount each day, call it $g$.
The field has some initial amount of grass: $i$
\begin{equation}
\begin{aligned}
i + 30g - 17\cdot30c &= 0\\
i+24g-19\cdot24c&=0
\end{aligned}
\end{equation}
Solving these two equations we get , $g = 9c$ . That means It takes 9 cows to eat one day's growth in one day.
A:
I'm going to set up some variables first.
Number of Cows: $C$
Amount of Grass on Day $n$: $G_n$
The rate of growth of grass: $x$ per day
The rate of consumption of grass: $y$ per day
So we have
$$G_{n+1}=G_n+x-Cy$$
which give
$$G_n=G_0+nx-nCy$$
The first two equations can be easily converted to
$$G_{30}=0=G_0+30x-30\cdot17\cdot y\tag{1}$$
$$G_{24}=0=G_0+24x-24\cdot19\cdot y\tag{2}$$
This gives
$$x=9y\tag{*}$$
For the last one, the recurrence relation no longer holds but the idea is the same, so we have
$$0=G_0+(6+2)x-6Cy-2(C-4)y$$
which simplifies to
$$0=G_0+8x-(8C-8)y\tag{3}$$
The rest is algebraic work. Using $(1)$ and $(*)$, you will get $C=40$.
A:
$$\begin{aligned}
V+30x&=30\times 17\times y\\
V+24x&=24\times 19\times y\\
V+8x&=6\times k\times y+2(k-4)\times y\\
V&=510y-30x\\
x&=9y\\
510y-22x&=(8k-8)y\\
510y-198y&=(8k-8)y\\
k&=40
\end{aligned}$$
where $V$ - value of grass on the field,
$x$ - speed of growth grass for a day,
$y$ - speed of 1 cow for a day,
$k$ - number of cows.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Express $A \cup B$ in set buildier notation when $A=\{2n+1 \mid n \in \mathbb{Z}\}$ and $B=\{3n+2 \mid n \in \mathbb{Z}\}$
Express $A \cup B$ in set buildier notation when $A=\{2n+1 \mid n \in \mathbb{Z}\}$ and $B=\{3n+2 |n \in \mathbb{Z}\}$
We know that the rooster notation version of the union set is $A \cup B = \{1,2,3,5,7,8,9,11,13,14,15,17,19,20,21,\ldots\}$
It is a combination of every odd integer and every multiple of $6$ added with $2$. The even values in $A \cup B$ will be produced by the even inputs to the set $B$.
I haven't been able to find a sequence definition in terms of $n$ for the set builder notation version of $A \cup B$
NOTE: the mod operator is not allowed in the computation of the sequence, I come from a CS background, that was my first idea, but it's not valid for the rules of the game, sadly.
A:
Write the elements of $A$ as $a_n$, the elements of $B$ as $b_n$, and the elements of $C\equiv A\cup B$ as $c_n$. In other words, $a_n = 2n+1$, $b_n=3n+2$, and you want a formula for $c_n$ (there is, of course, not a unique answer since the elements are not ordered, and may be repeated without changing $C$).
I suggest you use (say) even integers to index the $a_n$ and odd integers to index the $b_n$. Then you can alternate between them, using the fact that
$$f_n\equiv \frac{1+(-1)^n}2$$ is $1$ for even $n$ and $0$ for odd $n$, while
$$g_n\equiv \frac{1-(-1)^n}2$$ is $0$ for even $n$ and $1$ for odd $n$. This means you can put
$$c_n = f_na_{\lfloor n/2\rfloor} + g_nb_{\lfloor(n-1)/2 \rfloor}
$$(here, "$\lfloor\cdot\rfloor$" denotes the "floor" or "greatest integer" function).
Let's test a few values:
$c_0 = f_0a_0+g_0b_{-1} = 1\cdot a_0 + 0\cdot b_{-1} = a_0$
$c_1 = f_1a_0+g_0b_0 = 0\cdot a_0 + 1\cdot b_0 = b_0$
$c_2 = f_2a_1+g_2b_0 = 1\cdot a_1 + 0\cdot b_0 = a_1$
$c_3 = f_3a_1+g_3b_1 = 0\cdot a_1 + 1\cdot b_1 = b_1$
$c_4 = f_4a_2+g_4b_1 = 1\cdot a_2 + 0\cdot b_1 = a_2$
$c_5 = f_5a_2+g_5b_2 = 0\cdot a_2 + 1\cdot b_2 = b_2$
and so on. The explicit formula, using your definitions of $a_n$ and $b_n$, would be
$$\boxed{c_n = \left( \frac{1+(-1)^n}2 \right)\left(2\lfloor n/2\rfloor + 1\right) + \left( \frac{1-(-1)^n}2 \right)\left(3\lfloor(n-1)/2 \rfloor+2\right)}
$$
and your set in set-builder notation would be
$$\boxed{C=\left\{ \left( \frac{1+(-1)^n}2 \right)\left(2\lfloor n/2\rfloor + 1\right) + \left( \frac{1-(-1)^n}2 \right)\left(3\lfloor(n-1)/2 \rfloor+2\right):n\in\mathbb Z\right\}}$$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Dataset vs table adapter?
what is difference between dataset and table adapter can someone explain with interesting example please.
How does table adapter gets data from sql server ?
A:
You use the DataAdapter to fill the DataSet with the data from SqlServer.
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand("SELECT * FROM tbl_tblname", conn);
try
{
conn.Open();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd; // Set the select command for the DataAdapter
da.Fill(ds); // Fill the DataSet with the DataAdapter
DataGridView1.DataSource = ds.Tables[0]; // I just displayed the results in a grid view for simplicity. If Asp.Net you will have to call a DataBind of course.
catch (Exception ex)
{
conn.Close();
conn.Dispose();
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Getting all MotionEvents with WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
My question refers directly to this question. The answer to that question shows how one can create a ViewGroup, embed it inside a WindowManager, and allow the WindowManager to catch MotionEvents through onTouchEvent(MotionEvent event). WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH is the flag that allows this this ViewGroup to receive MotionEvents. However, according to documentation, this flag
...will not receive the full down/move/up gesture
I want to know if there's a work-around or a way so that I can get all touch events including down, move, and up. A proof of concept is in the app Wave Launcher which uses the same concept but is able to receive more than just a single ACTION_OUTSIDE event.
A:
No you can not, and that is very much by design.
Wave Launcher doesn't do this, it has a UI element where you start your touch gesture and then as with standard even dispatching all touch events are delivered to the window of the first down point until the final up.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
can anyone explain this I am aware of functionality of decorators but still not getting the output
def c(f):
def inner(*args, **kargs):
inner.co += 1
return f(*args, **kargs)
inner.co = 0
return inner
@c
def fnc():
pass
if __name__ == '__main__':
fnc()
fnc()
fnc()
print(fnc.co)
please explain the final output: 3
I am aware of the functionality of decorators but I'm still not getting the output.
A:
First, let's unpack what the decorator syntax does. When you write this:
@c
def fnc():
pass
… it's equivalent to this:
def fnc():
pass
fnc = c(fnc)
Now look at what c does: It creates a new function, named inner, and sets inner.co to 0, and returns inner to be used in place of fnc. So, now your code is equivalent to this:
def fnc():
pass
def inner(*args, **kargs):
inner.co += 1
return fnc(*args, **kargs)
inner.co = 0
fnc = inner
So, when you call fnc() three times, you're calling inner each time. So it increments inner.co three times. And since inner and fnc are the same thing, inner.co and fnc.co are the same thing. So print(fnc.co) prints 3.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
error occurs when updating a table in sqlite
String updateQuery = "UPDATE Bookdetails SET lastchapter = " + test + " WHERE bookpath=" +sentFilename;
db.execSQL(updateQuery);
Error:
03-04 13:36:23.997: I/System.out(9722): android.database.sqlite.SQLiteException:
near "/": syntax error: , while compiling: UPDATE Bookdetails SET lastchapter =
mukund WHERE bookpath=/mnt/sdcard/Download/What's so great about the doctrine of
grace.epub errors happens
the error is posted above
My table contains the field id, bookpath and lastchapter, book path contains the values
/mnt/sdcard/Download/What's so great about the doctrine of grace.epub
/mnt/sdcard/Download/1b4fdaac-f31d-41e8-9d15-26c9078d891f.epub
/mnt/sdcard/Download/Commentary on Romans.epub
and lastchapter contains the values nothing nothing nothing
id contains 1 2 3
why is the error occurring at "/" there is no hash in my update query it is only there at string which stores bookpath? Is this an error?
A:
String literals in SQL need to be in '' quotes.
However, it's better to use ? placeholders for literals like this:
String updateQuery = "UPDATE Bookdetails SET lastchapter=? WHERE bookpath=?";
db.execSQL(updateQuery, new String[] { test, sentFilename });
|
{
"pile_set_name": "StackExchange"
}
|
Q:
airflow v1.10.1 - SSHOperator does not log the ssh command
Since we upgraded airflow from v1.8.1 to v1.10.1 the ssh command that is executed by the SSHOperator is not showing in the logs anymore. now you have the log;
Subtask: Output:
<the output of your ssh command>
before you got the command + the output of the executed command.
Before you had the log;
Subtask: Running command: <your ssh command>
Subtask: Output:
<the output of your ssh command>
any help on making the SSHOperator log the command again? it's good to have the command in the logs to debug your task.
A:
The command parameter of the SSHOperator is templated, so its value is saved by Airflow on every task run for debugging purposes.
When you are viewing the task-instance's log in the Airflow UI, there is a button "Rendered Template". Click on it and you will see the value of the command parameter for this task instance.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Exception thrown when I set isFocusable on a blackberry manager
In my blackberry app I have a manager that controls the layout of the fields for my screen. This is the standard way of doing things when you want a custom layout.
Now, one of the "fields" that I'm using is itself a Manager that lays out a series of controls nicely. Call this "field" the "summaryField" as it summarizes data for me. This all renders out nicely.
However, when I override the isFocusable() member of "summaryField", I start getting a null pointer exception.
Anyone have an idea of why this exception is being thrown?
public class SummaryField extends Manager
{
protected void drawFocus(Graphics graphics, boolean on) {
super.drawFocus(graphics, on);
}
protected void onFocus(int direction) {
super.onFocus(direction);
}
protected void onUnfocus() {
super.onUnfocus();
}
public boolean isFocusable() {
return true;
}
}
A:
If I had to guess, I'd say that your Manager probably doesn't contain any focusable fields in it, and therefore your hardcoded "true" return value for isFocusable() is lying about the true state of the SummaryField. Remember that Managers themselves can't have "focus", just the fields within it.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Comments with votes and "best answers"
I would like to make something like question and answers sites. I need votes and best answer on the comments. I've already done from scratch something but I don't like the appearence and I am looking for a ready template.
I found this one here but it is on facebook. I just like the template and the way it show the best answer.
I don't want to use something like disqus. I want to store comments on my own database.
Do you know any html&js template for this?
A:
For ASP.NET, here is an open source project called Stacked:
https://code.google.com/p/stacked/
There is an example of building a star rating system in ASP.NET MVC
and jQuery which you might use for inspiration or code ideas -
http://dotnet.dzone.com/news/building-star-rating-system
For C# there is an open source project on GitHub (which may no
longer be active) : https://github.com/ripper234/Stack-Underflow/
It may not be supported any longer
Here is a stackoverflow clone that someone built in ASP.NET MVC for
practice and documented his steps:
http://ripper234.com/p/open-source-stackoverflow-clone-by-a-n00b-webdev/
Here is one for PHP called Question2Answer:
http://www.question2answer.org/
Another for PHP called Qwench :
http://anantgarg.com/2009/12/09/php-stackoverflow-clone/
And here is one for PHP ZendFramework:
http://sourceforge.net/projects/phpancake/
If using wordpress, there is a plugin called Q&A:
http://premium.wpmudev.org/project/qa-wordpress-questions-and-answers-plugin/
For Drupal, following this tutorial called 'building a stack
overflow clone with Drupal' :
http://engineeredweb.com/blog/09/11/building-stack-overflow-clone-drupal-part-1/
Drupal also has an answers module: http://drupal.org/project/answers
For Java there is AnswerHub: http://answerhub.com/
And for Javascript: https://github.com/fuadmuhammad/kerjakelompok/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can't control a css element that shares a css class with another element with JavaScript
[FYI: Doing a Udemy tutorial challenge]
Here is the html. It displays 2 dice. As you can see, they share the class 'dice.' Then each die also has its own class for controlling individual items, 'dice1' and 'dice2' respectively.
<img src="dice-5.png" alt="Dice 1" class="dice dice1">
<img src="dice-5.png" alt="Dice 2" class="dice dice2">
Here is the css for all three of these classes, 'dice', 'dice1', 'dice2.' As you can see, the 'dice1' and 'dice2' classes merely control the vertical position on screen.
.dice {
position: absolute;
left: 50%;
transform: translateX(-50%);
height: 100px;
box-shadow: 0px 10px 60px rgba(0, 0, 0, 0.10);
}
.dice1 {
top: 260px;
}
.dice2 {
top: 150px;
}
At the beginning of this dice game, neither dice should be visible. For this I am using Javascript to control the display with the following code.
document.querySelector('.dice').style.display = 'none';
For some reason this ONLY works on dice1. It does not work on dice2. If I add an additional line of code specifying class 'dice2', dice2 will also disappear. However, selecting the class 'dice' SHOULD select them BOTH. Why is this not working?
A:
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
The Document method querySelector() returns the first Element within
the document
use querySelectorAll:
document.querySelectorAll('.dice').forEach( dice_Item=>dice_Item.style.display = 'none' );
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to keep showing number of notifications on small screens
Let me explain what I mean. On medium screens, the top navigation bar would look like this:
=========================================================
Logo 10 Settings Account Home
=========================================================
Where "10" is the number of notifications and is a bascially a dropdown menu that shows recent notifications when clicked on.
On small screens, I want the menu to be like this:
==============
Logo 10 |||
==============
in which "|||" is the collapse button which shows
Settings Account Home
when clicked on, and "10" has the same role as before.
As far as I have learned from bootstrap examples, ALL of "10 Settings Account Home" will go inside the collapse button. One solution I can think of is having two separate notification buttons and show/hide them using the media queries. But in this case, I should also have two separate menus (containing recent notifications) which doesn't seem smart to me.
I appreciate it if you can give me any ideas to achieve what I'm looking for.
A:
One way to achieve this is to remove the piece of nav that you DO NOT WANT to be collapsed from navbar-collapse and put it right below the navbar brand and use the navbar-link class. See code below:
<div class="navbar navbar-default" role="navigation">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Project name</a>
<p class="navbar-text navbar-left"><a href="#" class="navbar-link">10</a></p>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Settings</a></li>
<li><a href="#">Accounts</a></li>
<li><a href="#">Home</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
See non-nav links: http://getbootstrap.com/components/#navbar-links.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to make a transaction in asp.net-core 2.0?
I want to update some values but in case one fails I need to rollback. How can I do this in asp.net-core-2.0?
I have not found any answers yet. Is this because it is not yet supported? In that case what are some alternatives?
A:
Yes man, using System.Transactions.TransactionScope, available since .Net Core 2.0 and above. check this:
Using System.Transactions in ASP.NET:
https://msdn.microsoft.com/en-us/ms229977
Implementing an Implicit Transaction using Transaction Scope:
https://msdn.microsoft.com/en-us/ms172152
|
{
"pile_set_name": "StackExchange"
}
|
Q:
copying from one char pointer to another char pointer
I am trying to copy contents of one char array pointer to another array.Inside the for loop, it displays all elements. But outside the for loop it displays only last element in entire array. Following is code snippet
char *outhex[81] = {'\0'};
char *temp[81] = {'\0'};
int a, i, k=0, j=0;
uint8_t quotient[81] ;
uint8_t outdec[81];
quotient[81] = {65,00,01,134,160,00,00,01,194,00,00,00,00,00,00,00,01,00,00,01,32,00,00,00,01,00,00,00,00,00,00,00,15,00,00,00,100,00,00,00,00,00,00,00,06,00,00,8,00,00,00,21,124,00,00,58,152,00,00,03,32,00,00,00,25,00,00,00,00,00,00,00,01,00,00,00,00,00,00,01,244};
for(i = 0; i < 81; i++)
{
char remainder;
j = 0;
char hexadecimalnum[3] = {'0'};
while (quotient[i] != 0)
{
remainder = quotient[i] % 16;
if (remainder < 10)
hexadecimalnum[j++] = 48 + remainder;
else
hexadecimalnum[j++] = 55 + remainder;
quotient[i] = quotient[i] / 16;
}
printf("%s", hexadecimalnum);
int p =strlen(hexadecimalnum)-1,q=0;
char ch;
while(p > q)
{
ch = hexadecimalnum[p];
hexadecimalnum[p] = hexadecimalnum[q];
hexadecimalnum[q] = ch;
p--;
q++;
}
printf("\t%s", hexadecimalnum);
outhex[i] = (&hexadecimalnum);
printf(" = %d ", i);
temp[i] = outhex[i];
printf("\t outhex[%d] = %s \t %s \t %d \t %d\n", i, outhex[i], temp[i], &outhex[i], &temp[i]);
}
for(a = 0; a< 81; a++)
{
printf("temp = %s %d \n", temp[a], &temp[a]);
}
output is :
14 41 = 0 outhex[0] = 41 41 6299904 6300576
0 0 = 1 outhex[1] = 0 0 6299912 6300584
1 1 = 2 outhex[2] = 1 1 6299920 6300592
68 86 = 3 outhex[3] = 86 86 6299928 6300600
0A A0 = 4 outhex[4] = A0 A0 6299936 6300608
0 0 = 5 outhex[5] = 0 0 6299944 6300616
0 0 = 6 outhex[6] = 0 0 6299952 6300624
1 1 = 7 outhex[7] = 1 1 6299960 6300632
2C C2 = 8 outhex[8] = C2 C2 6299968 6300640
0 0 = 9 outhex[9] = 0 0 6299976 6300648
0 0 = 10 outhex[10] = 0 0 6299984 6300656
0 0 = 11 outhex[11] = 0 0 6299992 6300664
0 0 = 12 outhex[12] = 0 0 6300000 6300672
0 0 = 13 outhex[13] = 0 0 6300008 6300680
0 0 = 14 outhex[14] = 0 0 6300016 6300688
0 0 = 15 outhex[15] = 0 0 6300024 6300696
0 0 = 16 outhex[16] = 0 0 6300032 6300704
0 0 = 17 outhex[17] = 0 0 6300040 6300712
0 0 = 18 outhex[18] = 0 0 6300048 6300720
1 1 = 19 outhex[19] = 1 1 6300056 6300728
02 20 = 20 outhex[20] = 20 20 6300064 6300736
0 0 = 21 outhex[21] = 0 0 6300072 6300744
0 0 = 22 outhex[22] = 0 0 6300080 6300752
0 0 = 23 outhex[23] = 0 0 6300088 6300760
1 1 = 24 outhex[24] = 1 1 6300096 6300768
0 0 = 25 outhex[25] = 0 0 6300104 6300776
0 0 = 26 outhex[26] = 0 0 6300112 6300784
0 0 = 27 outhex[27] = 0 0 6300120 6300792
0 0 = 28 outhex[28] = 0 0 6300128 6300800
0 0 = 29 outhex[29] = 0 0 6300136 6300808
0 0 = 30 outhex[30] = 0 0 6300144 6300816
0 0 = 31 outhex[31] = 0 0 6300152 6300824
F F = 32 outhex[32] = F F 6300160 6300832
0 0 = 33 outhex[33] = 0 0 6300168 6300840
0 0 = 34 outhex[34] = 0 0 6300176 6300848
0 0 = 35 outhex[35] = 0 0 6300184 6300856
46 64 = 36 outhex[36] = 64 64 6300192 6300864
0 0 = 37 outhex[37] = 0 0 6300200 6300872
0 0 = 38 outhex[38] = 0 0 6300208 6300880
0 0 = 39 outhex[39] = 0 0 6300216 6300888
0 0 = 40 outhex[40] = 0 0 6300224 6300896
0 0 = 41 outhex[41] = 0 0 6300232 6300904
0 0 = 42 outhex[42] = 0 0 6300240 6300912
0 0 = 43 outhex[43] = 0 0 6300248 6300920
6 6 = 44 outhex[44] = 6 6 6300256 6300928
0 0 = 45 outhex[45] = 0 0 6300264 6300936
0 0 = 46 outhex[46] = 0 0 6300272 6300944
8 8 = 47 outhex[47] = 8 8 6300280 6300952
0 0 = 48 outhex[48] = 0 0 6300288 6300960
0 0 = 49 outhex[49] = 0 0 6300296 6300968
0 0 = 50 outhex[50] = 0 0 6300304 6300976
51 15 = 51 outhex[51] = 15 15 6300312 6300984
C7 7C = 52 outhex[52] = 7C 7C 6300320 6300992
0 0 = 53 outhex[53] = 0 0 6300328 6301000
0 0 = 54 outhex[54] = 0 0 6300336 6301008
A3 3A = 55 outhex[55] = 3A 3A 6300344 6301016
89 98 = 56 outhex[56] = 98 98 6300352 6301024
0 0 = 57 outhex[57] = 0 0 6300360 6301032
0 0 = 58 outhex[58] = 0 0 6300368 6301040
3 3 = 59 outhex[59] = 3 3 6300376 6301048
02 20 = 60 outhex[60] = 20 20 6300384 6301056
0 0 = 61 outhex[61] = 0 0 6300392 6301064
0 0 = 62 outhex[62] = 0 0 6300400 6301072
0 0 = 63 outhex[63] = 0 0 6300408 6301080
91 19 = 64 outhex[64] = 19 19 6300416 6301088
0 0 = 65 outhex[65] = 0 0 6300424 6301096
0 0 = 66 outhex[66] = 0 0 6300432 6301104
0 0 = 67 outhex[67] = 0 0 6300440 6301112
0 0 = 68 outhex[68] = 0 0 6300448 6301120
0 0 = 69 outhex[69] = 0 0 6300456 6301128
0 0 = 70 outhex[70] = 0 0 6300464 6301136
0 0 = 71 outhex[71] = 0 0 6300472 6301144
1 1 = 72 outhex[72] = 1 1 6300480 6301152
0 0 = 73 outhex[73] = 0 0 6300488 6301160
0 0 = 74 outhex[74] = 0 0 6300496 6301168
0 0 = 75 outhex[75] = 0 0 6300504 6301176
0 0 = 76 outhex[76] = 0 0 6300512 6301184
0 0 = 77 outhex[77] = 0 0 6300520 6301192
0 0 = 78 outhex[78] = 0 0 6300528 6301200
1 1 = 79 outhex[79] = 1 1 6300536 6301208
4F F4 = 80 outhex[80] = F4 F4 6300544 6301216
temp = F4 6300576
temp = F4 6300584
temp = F4 6300592
temp = F4 6300600
temp = F4 6300608
temp = F4 6300616
temp = F4 6300624
temp = F4 6300632
temp = F4 6300640
temp = F4 6300648
temp = F4 6300656
temp = F4 6300664
temp = F4 6300672
temp = F4 6300680
temp = F4 6300688
temp = F4 6300696
temp = F4 6300704
temp = F4 6300712
temp = F4 6300720
temp = F4 6300728
temp = F4 6300736
temp = F4 6300744
temp = F4 6300752
temp = F4 6300760
temp = F4 6300768
temp = F4 6300776
temp = F4 6300784
temp = F4 6300792
temp = F4 6300800
temp = F4 6300808
temp = F4 6300816
temp = F4 6300824
temp = F4 6300832
temp = F4 6300840
temp = F4 6300848
temp = F4 6300856
temp = F4 6300864
temp = F4 6300872
temp = F4 6300880
temp = F4 6300888
temp = F4 6300896
temp = F4 6300904
temp = F4 6300912
temp = F4 6300920
temp = F4 6300928
temp = F4 6300936
temp = F4 6300944
temp = F4 6300952
temp = F4 6300960
temp = F4 6300968
temp = F4 6300976
temp = F4 6300984
temp = F4 6300992
temp = F4 6301000
temp = F4 6301008
temp = F4 6301016
temp = F4 6301024
temp = F4 6301032
temp = F4 6301040
temp = F4 6301048
temp = F4 6301056
temp = F4 6301064
temp = F4 6301072
temp = F4 6301080
temp = F4 6301088
temp = F4 6301096
temp = F4 6301104
temp = F4 6301112
temp = F4 6301120
temp = F4 6301128
temp = F4 6301136
temp = F4 6301144
temp = F4 6301152
temp = F4 6301160
temp = F4 6301168
temp = F4 6301176
temp = F4 6301184
temp = F4 6301192
temp = F4 6301200
temp = F4 6301208
temp = F4 6301216
Outside for loop, all elements of temp array is containing only last data. Initial elements are overwritten by last element. What is the reason for this? Is there any solution to get all contents array outside 'for loop'.
A:
This line is the problem.
outhex[i] = (&hexadecimalnum);
For any value of i, it's pointing to the same variable. So outhex[0] will be the same as outhex[1] for example.
You're also assigning the wrong value to it as well as &hexadecimalnum is a char ** and outhex[i] will be char *. Your compiler should have flagged this up as an warning.
The correct way to do this is to make a new copy of the string and store it into outhex[i]. Like this, for example...
outhex[i] = malloc(strlen(hexadecimalnum)+1);
strcpy(outhex[i],hexadecimalnum);
or you can use strdup which does the allocation and copying in one function call.
outhex[i] = strdup(hexadecimalnum);
I can't see any difference in temp and outhex so there probably isn't any call to make a new copy, so temp[i]=outhex[i] probably isn't an issue...at least not in the code as provided.
There also a typo on this line
char hexadecimalnum[3] = {'0'};
which should be so that your string is NUL terminated and will work with the previous fixes.
char hexadecimalnum[3] = {'\0'};
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Does Enlarge/Reduce also reduce a monster’s max hit points?
From the Monster Manual intro, on p. 7, under "Hit Points":
A monster's size determines the die used to calculate its hit points, as shown in the Hit Dice by Size table.
Enlarge/Reduce gives an option to reduce the target's creature size by one level.
Reduce. The target's size is halved in all dimensions, and its weight is reduced to one-eighth of normal. This reduction decreases its size by one category - from Medium to Small, for example.
When a creature's Constitution modifier decreases, its maximum hit points decrease as well.
Following this logic, does using Reduce on a monster also reduce its maximum hit points?
A:
No, it won't reduce its max HP.
This spell details exactly every change effected by the spell. Changing hit points is not listed, so it doesn't happen.
While creature size is used for initially calculating the max hit points of a new custom monster, no rule states that a creature's hit dice change when a creature changes size during play. The guidelines given in that section have no effect outside of it.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is category equivalence unique up to isomorphism?
Let $\mathbf C$, $\mathbf D$ be categories and $F, F':\mathbf C \to \mathbf D$ and $G, G':\mathbf D \to \mathbf C$ be functors of the shown direction. Is it the case that, if each of $(F,G)$ and $(F',G')$ is an equivalence, then $F\cong F'$ (isomorphic in $\mathbf D^\mathbf C$)?
Initially I thought (without thinking) that there couldn't be more than "one" equivalence (up to isomorphism) between two categories. But, once I tried to prove this, I couldn't find any reason whay it should be so. Was I wrong? Any help will be appreciated.
A:
No; for instance, let $C = D = 2$, the discrete category with two objects, and let $F = G = \mathrm{id}_C$ while $F' = G'$ is the functor exchanging the objects.
Edit to add some more simple examples:
If we think of the poset $(\mathbb Z, <)$ as a category, then the two equivalences $\mathrm{id}_{\mathbb Z}: \mathbb Z \to \mathbb Z$ and $S: \mathbb Z \to \mathbb Z$ are not isomorphic.
If we think of a group as a one-object category (so that functors correspond to group homomorphisms), then for any non-trivial group $G$ the mapping $G \times G \to G \times G$ which swaps the elements is not isomorphic to the identity on $G \times G$. More generally, two group homomorphisms are isomorphic if and only if they are conjugate, so in particular any non-identity automorphism of an abelian group (e.g. negation for most abelian groups) is not isomorphic to the identity on that group.
A:
To get some more intuition on this, note that analogous statements aren't true for other mathematical objects. For example if $G$ and $H$ are isomorphic groups then the set of isomorphisms between them is in bijection with the set of automorphisms of either of them. A group can have more than one distinct automorphism.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Spring-boot @Value properties not overridden by command line arguments
I have a Maven/SpringBootApplication that takes its properties from a Spring config Server. I need to override the values of these properties using command line arguments. unfortunately, the properties keep the values provided by the config server and are not overridden by the command line arguments.
I have confirmed that the parameters are properly passed to the App as I can see being passed to SpringApplication.run.
I can see in the function ConfigurableApplicationContext of Spring Framework the environment carrying the arguments in environment.propertysources.propertySourceList.SimpleCommandLinePropertySource.source.optionArgs
If I try to set a Spring-defined value (e.g. --logging.level.org.springframework.web=TRACE) it works, meaning Spring logs traces
I read all possible threads on the subject but none seem to apply to my problem.
This is my Spring boot app (args are beeing passed to the SpringApplication)
@SpringBootApplication
@ComponentScan("com.mycompany")
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
Here is the component and the property
@Component
public class TaskProcessor implements com.mycompnay.fwk.task.engine.TaskProcessor {
private RestTemplate restTemplate = new RestTemplate();
@Value("${mycompany.converter.converter-uri.office}")
private String converterUriOffice;
}
The parameter being passed is received by the app (extracted from debugger):
0:"--debug=true"
1:"--logging.level.org.springframework.web=TRACE"
2:"--mycompany.converter.converter-uri.office=foo"
hash:0
value:char[44]@25
I expect the property converterUriOffice to have the value foo
Instead it gets its value from the config server (http://localhost:3000/convert/office)
A:
found following in the documentation https://cloud.spring.io/spring-cloud-static/Edgware.SR2/single/spring-cloud.html#overriding-bootstrap-properties
Overriding the Values of Remote Properties The property sources that
are added to you application by the bootstrap context are often
"remote" (e.g. from a Config Server), and by default they cannot be
overridden locally, except on the command line. If you want to allow
your applications to override the remote properties with their own
System properties or config files, the remote property source has to
grant it permission by setting spring.cloud.config.allowOverride=true
(it doesn’t work to set this locally). Once that flag is set there are
some finer grained settings to control the location of the remote
properties in relation to System properties and the application’s
local configuration: spring.cloud.config.overrideNone=true to override
with any local property source, and
spring.cloud.config.overrideSystemProperties=false if only System
properties and env vars should override the remote settings, but not
the local config files.
same problem here with the solution https://github.com/spring-cloud/spring-cloud-config/issues/907
The documentation is not very clear cause it says that command line
arguments always take precedence over remote configuration.
The property sources that are added to you application by the
bootstrap context are often "remote" (e.g. from a Config Server), and
by default they cannot be overridden locally, except on the command
line.
To achieve that, you have to activate the
spring.cloud.config.override-system-properties=false configuration
(the documentation only talk about System properties but it seems to
be applicable to command line arguments too).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I add a design-time description to a property implemented through an extender provider?
I know that I can add a design-time Designer description to a custom control's property by doing this:
<Category("Data"), Description("This describes this awesome property")>
Public Property Foo As Boolean
...
End Property
What I want to do is the exact same thing, but to properties that my extender provider component is providing other controls on my form with, so that when I click on the property's value field, for example, I would see the description I wrote for it. Searched a lot for an answer but had no success so far. Would I have to add something to my getter and setter methods for the property?
Thank you.
A:
Would I have to add something to my getter and setter methods for the property?
Yes. Add the DescriptionAttribute to the Get[PropertyName] method. The same goes for any other Attributes (they dont seem to work on the Set... counterpart).
<Category("ListContolExtender"), DisplayName("DisplayMode"),
Description("My very clever description")>
Public Function GetDisplayMode(ctl As Control) As ItemDisplays
If extData.ContainsKey(ctl) Then
Return extData(ctl).DispMode
Else
Return ItemDisplays.Enabled
End If
End Function
Public Sub SetDisplayMode(ctl As Control, v As ItemDisplays)
If extData.ContainsKey(ctl) Then
extData(ctl).DispMode = v
Else
Dim e As New ExtenderData
e.DispMode = v
extData.Add(ctl, e)
End If
End Sub
The DisplayNameattribute hides all the DisplayMode on ListBoxExtender verbiage
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Memory Management issues with LIExposeController in iOS
I am using "LIExposeController" to create new UIViewControllers. This brings up some memory warnings that I am not able to fix.
- (UIViewController *)newViewControllerForExposeController:(LIExposeController *)exposeController {
UIViewController *viewcontroller = [[[MyViewController alloc] init] autorelease];
return viewcontroller; // warning here saying object with a + 0 retain count returned to caller where a + 1 (owning) retain count is expected
}
- (void)shouldAddViewControllerForExposeController:(LIExposeController *)exposeController {
[exposeController addNewViewController:[self newViewControllerForExposeController:exposeController]
animated:YES];
} // warning here saying potential leak of an object
LIExposeController *exposeController = [[[LIExposeController alloc] init] autorelease];
exposeController.viewControllers = [NSMutableArray arrayWithObjects:
[self newViewControllerForExposeController:exposeController],
nil]; // warning here saying potential leak of an object
A:
A method starting with new is expected to produce an object with retain count +1 and not an autoreleased/retain count +0 object. ARC and the Static Analyzer both follow these conventions as rules, and you should fix your code to meet them or rename your method to not clash with the conventions.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What exercises should I perform to reduce fat on a specific area of my body?
I have had a couple of lower back surgeries in the past but I'm okay to do any activity. During the last 10 years I have gained a little more weight around the mid section but have been actively trying to lose the weight but with little success.
I'm currently doing hot yoga to increase my flexibility.
Currently I hit the gym 2 to 3 times a week and yoga every other week, I would like to do more of both but being a dad of four, time is limited. I have been working out in the morning for about an hour (usually cardio) and one day of the weekend for about 2 hours (Full body, upper/lower).
I've also changed my diet, the time of the day that I've been eating and the amount I eat to a healthier diet with smaller amounts about 5 times a day. I heard this would increase my metabolism. The total intake of calories for the day has stayed the same.
I'm about 6'3", 230 pounds, but would like to be around 190.
Summary:
For weight loss I'm doing cardio with some weight lifting but not seeing the results I would like to see. What exercises can I perform to reduce my belly fat?
A:
There is no "best" exercise to lose belly fat. In fact, there is no exercise that will specifically target weight loss in any part of your body. The only way to lose fat in your belly is to lose fat overall.
The number one thing you can do to lose weight is look at your diet. Losing weight is as simple as burning more calories than you consume. The easiest way to reduce your caloric intake is to eat healthier foods. Alternatively, you could eat the same foods and just eat less of them.
Food you buy at the grocery store and cook yourself are often healthier than what you would get at a fast food joint because they haven't been processed as much. For many people, cutting out most of the sugar in their diet (obviously not sugar from fruit and other healthy sources) is an excellent way to lose the weight. You can split your 3 big meals into 5 smaller ones, but make sure your 5-meal calorie count total is really less than your 3-meal plan total.
Once you get your diet squared away, then you will really start to see the benefits of your exercising. I would suggest doing a lot of different exercises in the beginning and there are many to try. Figure out what you like to do and works best for you. Is there anybody you could work out with? A partner is always a big plus to exercise.
Remember, it took you 10 years to gain the little extra weight you have right now. A healthy weight loss routine would have you losing a maximum of 2 pounds per week on average. If you want to get down to 190 again, you're looking at around a year or more of a dedicated lifestyle change in order to accomplish that.
A:
Start with cardio and progress to weights
Start by targeting a 'moderate' heart rate to burn the fat you already have. By moderate I mean Aerobic on the chart below.
Note: Image taken from [Wikipedia][4] and falls under CC-SA license.
Ignore the 'Weight Control' region for a minute and bear with me. What you're targeting here is the Aerobic Zone. Why, you may ask? While the weight burning zone is good for burning fat while you work out, it isn't really optimal for weight loss because as soon as you stop your body will go back to it's normal resting heart rate.
When you do an Aerobic workout, not only will the workout burn a lot of energy itself but it will continue to burn energy for the rest of the day. Try taking your heart rate a few hours after you finish running, you'll find that it's still chugging along burning energy.
So that takes care of initially burning off the excess energy (fat) but how do you keep it off in the long term without having to go to the gym 3 times a week (for your 30-60 minute cardio run)? Build muscle mass.
I'm not talking about the Type 1 muscles that you build from doing long distance running. I'm talking about the Type 2 fast twitch muscles that use tons of energy just to maintain themselves. These are what you build with exercises like weight lifting, (some) team sports (basketball, soccer, hockey), sprinting, etc...
There are 3 ways to check your heart rate while working out:
Count your pulse
This method is a PITA and it's nearly impossible to do while running.
Get a heart rate monitor
I highly recommend using one of these if you have the money to burn because not only does it let you see a real time measurement but having constant feedback over a long period of time gives you a sense of how hard you should be pushing yourself while you work out
Listen to what your body tells you
This is the best method when you first start out. The problem with the generic chart above is it assumes that you're in good health and average everything when in fact you're not (especially when you're out of shape).
The key terms you need to remember are 'aerobic' and 'anaerobic'. What these two terms mean are 'with oxygen' and 'without oxygen'. When you hit your aerobic range you start breathing harder because your body requires more oxygen to meet the performance needs of your workout. This is about the equivalent to a moderate-fast jog for somebody in good shape. The anaerobic range is when your body loses its ability to break down lactate at a fast enough rate and it starts to accumulate in your blood stream. Lactic acid is a byproduct of anaerobic metabolism and one of the reasons you feel sore the day after a hard workout. This is the stage when you find yourself gasping for air and feel your muscles burning. It's also the state you'll find yourself in when you start doing strenuous workouts.
The reason I say to feel it out when you first start is, your body is most likely in poor working shape. Because it's not used to the strain of exercise, it won't be adapted to the high demand of oxygen. You'll find yourself gasping for oxygen even on easy workouts and everything in the chart gets shifted because your VO2 max is much lower.
It takes some time for your body to adjust to exercise. It has to produce more red blood cells to carry oxygen. Drinking enough water is important for this or you'll get the workout hangover feeling. Your body also needs to cleanse itself of toxins like crap in your lungs and vascular system. It takes time for your body to fully adjust (don't rush the progression).
Listen to what your body tells you. Start out with the aerobic stuff and wait until it starts to feel easy until you introduce the harder workouts. Eventually, when you're ready you can shift over completely.
I usually start with 30-60 minute runs and after a week or two introduce a sprint. The sprint involves a mile to warm up (and to gradually get up to speed) a mile on full speed, and a mile to cool down (and gradually reduce the speed). When I say gradually increase/decrease the speed I'm talking some small increment that you use (like .5mph per 10th of a mile). Even if you're gasping after the mile at full speed force yourself to follow the gradual decreases in speed (unless you physically can't). What this does is push your anaerobic threshold even higher. A higher anaerobic threshold means you'll feel less sore and you'll be able to work out harder without feeling fatigued in the future.
At that point the workout doesn't need to get any longer (the sprints only get more difficult if you choose to push yourself). The sprint takes about 15-20 minutes to accomplish (less if I the warm-up cool-down phases are shortened) and you don't really need to do it that often for maintenance (max 2 times a week).
The benefits are, your body will naturally burn more energy because of the increase in muscle mass and if you quit for a while you still won't get chubby.
My general rule for muscle mass is, it takes 3 times longer to lose it than it took to build it (that's what I find at least). Meaning that if you work out and continue to improve over a 3 month period it'll take 9 months until you fall back into bad shape (a really bad diet can make this worse).
You may replace sprinting with lifting weights if you want but take note that it will take more time/work to maintain. Running builds muscle all throughout your body whereas lifting weights only targets individual regions. My 15-20min routine may take 1hr of lifting weights to effectively match.
As for diet, increase lean protein sources and decrease carbohydrates and fatty meats (like beef). By lean protein I'm referring to eggs, tuna, edamame, beans, chicken (if it's cooked right). Be sure not go on a protein-only diet though, a diverse diet is still important.
Another thing to make sure of is, always do cardio on an empty stomach (don't eat within 3 hours of a workout). If you're exercising in the morning, make sure you get a good meal the night before. You shouldn't need a whole lot of energy if you're not exercising for an extended period and this will force your body to burn the energy it has readily stored (fat). Save the meal for right after the workout, within 45 minutes after a workout is the period when nutrient uptake is at its greatest (and if feels the most satisfying).
As for lifting weights, if you plan to do it for an extended period of time you may need to eat before. Watch out for a feint light headed feeling (if you feel like this don't keep lifting). Light headedness is an indicator of low blood sugar so adjust your routine to eat before.
Update:
I have just realized a glaring mistake in the heart rate chart. The 'Maximum Effort' zone is not your V02 MAX. Your VO2 MAX is the point where your body's oxygen uptake reaches it's maximum so it has to fire up your anaerobic metabolism to compensate. This 'correct' classification of this would be the borderline between your aerobic and anaerobic zones.
@ldx Also had a very interesting link with a lot of good info about studies that determine the differences (results obtained) between aerobic/anaerobic exercises that should help your further optimize your workouts (I'm definitely going to try making some adjustments).
A:
I agree with Sparafusile that "targeted fat reduction" is not possible. When your body stores fat you have no control over where it happens. The only solution is to convince your body to stop storing so much fat. Because fat storage is regulated by hormonal signals that are influenced by WHAT you eat, I have some different recommendations. Try eating less often. Skipping breakfast is a form of intermittent fasting, and makes your body burn fat throughout the morning. Eliminate processed carbohydrates from your diet and you will probably find that your energy levels are more steady and missing a meal will not bother you. Instead of hours of cardio that can just end up making you eat more the next day, do some high intensity interval exercise, with or without weights. Crossfit.com or P90X are good examples. I have had good success with these methods and the most important factor for me is the short duration of the workouts.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Запустить анимацию при прокрутке страницы
Есть следующий код:
function startAnimation() {
var box = document.querySelector('.box');
var boxPosition = box.getBoundingClientRect().top;
var screenPosition = window.innerHeight / 1.2;
if(boxPosition < screenPosition) {
box.classList.add('animation');
}
}
window.addEventListener('scroll', startAnimation);
@keyframes rotate {
100% {
transform: rotate(180deg);
}
}
.box.animation {
animation: rotate 1s ease-in 0.1s;
animation-fill-mode: forwards;
}
.container {
background-color: #03A9F4;
height: 2000px;
}
.box-wrapper {
display: flex;
justify-content: center;
align-items: center;
height: 490px;
border: 5px solid #FFEB3B;
}
.box {
width: 100px;
height: 100px;
background-color: #8BC34A;
border: 5px solid #4CAF50;
}
<div class="container">
<div class="box-wrapper">
</div>
<div class="box-wrapper">
<div class="box"></div>
</div>
<div class="box-wrapper">
<div class="box"></div>
</div>
<div class="box-wrapper">
<div class="box"></div>
</div>
</div>
Подскажите пожалуйста, как сделать так, что бы каждый .box поворачивался когда он появляется на экране?
Я понимаю, что все .box нужно положить в массив, но что делать дальше с массивом я не представляю...
A:
Решение оказалось проще, чем я думал)
querySelector находит только первый указанный элемент на странице. Чтобы найти все, нужно использовать querySelectorAll(). А он и так уже возвращает "почти" массив
(демо):
var test = document.querySelectorAll('.box');
console.log( test[0] );
console.log( test[1] );
console.log( test[2] );
console.log( test[3] );
console.log( test );
<div class="box">0000</div>
<div class="box">1111</div>
<div class="box">2222</div>
<div class="box">3333</div>
А в вашем случае, элементы box как созданы - так и остаются на месте. Поэтому можно каждый раз не пересоздавать переменную внутри функции, а вынести её за её пределы.
var box = document.querySelectorAll('.box');
function startAnimation() {
var pos = window.innerHeight / 1.2;
var i, boxtop;
for(i = 0; i < box.length; i++){
boxtop = box[i].getBoundingClientRect().top;
if(boxtop < pos ) {
box[i].classList.add('animation');
}
}
}
window.addEventListener('scroll', startAnimation);
@keyframes rotate {
100% {
transform: rotate(180deg);
}
}
.box.animation {
animation: rotate 1s ease-in 0.1s;
animation-fill-mode: forwards;
}
.container {
background-color: #03A9F4;
height: 2000px;
}
.box-wrapper {
display: flex;
justify-content: center;
align-items: center;
height: 490px;
border: 5px solid #FFEB3B;
}
.box {
width: 100px;
height: 100px;
background-color: #8BC34A;
border: 5px solid #4CAF50;
}
<div class="container">
<div class="box-wrapper"></div>
<div class="box-wrapper">
<div class="box"></div>
</div>
<div class="box-wrapper">
<div class="box"></div>
</div>
<div class="box-wrapper">
<div class="box"></div>
</div>
</div>
Демо работы for()
var i;
for( i = 5; i < 10; i++ ){
console.log( 'На этом круге [i] равен - ' + i );
}
/*Это то же самое, что и
console.log( 5 );
console.log( 6 );
console.log( 7 );
console.log( 8 );
console.log( 9 );
for просто сильно сокращает код. Вместо i < 10 в вашем случае используется
количество элементов box. А i++ просто частный случай. То же, что и i = i + 1.
Там может быть вообще всё что угодно.
*/
P.s. хорошо бы отключить функцию после выполнения всех анимаций... чтобы оно не продолжало проверять столько всего при каждом скролле. Но пока не знаю как)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Implement a semantic web search engine using Arabic wordnet
I want to develop a web application that will use the current AWN, and provide the user to obtain semantic results. What I require are the things that I need to know before going into implementation of the system. My purpose is to do semantic search in the Holy Quran. Any help will be appreciated in this regard.
A:
You should do some workouts to achieve it
Step 1 :
Create a Table which has all possible words
Step 2 :
Create a php file and get your input
Step 3 :
Pass your input to the server page or another page which will compare your input with the matches
Step 4 :
Find atlest 2 matches and show the output
Ajax Call :
if(searchid!='')
{
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
cache: false,
success: function(html)
{
$("#result").html(html).show();
}
});
}return false;
});
Query to be processed
"select * from quote where word like '%$q%' order by id LIMIT 2"
Here $q is the input you give
I have created a demo for you which have the possible words like
Alhamdh, Bayan, Allah, Sunnah, Khalifa
Here is the Demo for you
The image which comes near dropdown is just for style and you can change it later on :)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Mobile Safari multi select bug
If found a really annoying bug on the current (iOS 9.2) mobile safari (first appearing since iOS 7!)
If you using multi select fields on mobile safari - like this:
<select multiple>
<option value="test1">Test 1</option>
<option value="test2">Test 2</option>
<option value="test3">Test 3</option>
</select>
You will have problems with automatically selection!
iOS is automatically selecting the first option after you opened the select (without any user interaction) - but it will not show it to you with the blue select "check".
So if you now select the second option, the select will tell you that two options are selected (but only highlighting one as selected)...
If you now close and open the select again, iOS will automatically deselect the first value - if you repeat, it will be selected again without any user interaction.
Thats a really annoying system bug, which is breaking the user experience!
A:
Solution for safari multi select bug and Empty and Disabled option tick related issue:
<select multiple>
<optgroup disabled hidden></optgroup>
<option value="0">All</option>
<option value="1">Test 1</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
<option value="4">Test 4</option>
</select>
Add a disabled and hidden optgroup before the real options.
A:
After a long research I found the following (not most beautiful) but working solution:
The trick is to add a empty and disabled select option at the fist position:
<select multiple>
<option disabled></option>
<option value="test1">Test 1</option>
<option value="test2">Test 2</option>
<option value="test3">Test 3</option>
</select>
This will prevent iOS from automatically selecting the first option and keep the selection values right and clean!
The empty option is not visible and the count of the selections is correct.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
plotting smooth line for data of very small magnitude
The command you suggested serves the purpose to some extent But I am still looking for a command/function to give smoother curves. I am giving a reproducible code below which is drawing rather sharp edges or more crudely: the line joining the points is too sharp especially at the moment it starts from one point to another. Sorry for non-technical language as I am still unfamiliar with the field. Thanks for the help provided on this issue. Please suggest the modifications in the code below to get smoother curves.
xdata1<-c(6:11)
ydata1<-c(-0.75132894, -1.71909555, -0.62653171, 0.49512191, 0.29201836, 0.31094460)
plot(NULL,NULL,xlim=xlims,ylim=ylims,axes=FALSE, ann=FALSE)
axis(1,cex.axis=0.7,mgp=c(3, .3, 0))
axis(2, las=1,cex.axis=0.7,at=c(-2,-1,0,1,2), mgp=c(3, .7, 0))
mtext(side = 1, text =expression('Year'), line = 1,font=15)
mtext(side = 2, text = expression('Variable'), line = 1.5,font=15)
lines(smooth.spline(xdata1,ydata1, df=5), col='red',type="l", pch=22, lty=1, lwd=1)
#######Updated Query Finishes Here
I have to plot very small magnitude data against time steps of 1. Please see the sample data below:
xdata<-c(1:48)
ydata<- c(0.325563413,0.401913414,0.221939845,0.19881055,
-0.05918293,-1.108143815,-0.220563332,-0.148715078,
-0.14998762,0.131610695,0.249923598,0.246891873,
0.656812019,0.524436114,0.23875397,0.200695075,
-0.015974087,-0.611863249,0.121994831,-0.143103421,
-0.142109609,0.101451935,0.160242421,0.232404601,
0.348305745,0.231109382,0.334988321,0.263046902,-0.058154333,
-1.032276818,-0.352068888,-0.13082767,-0.134611511,0.116967421,
0.268706409,0.232776855,0.39515544,0.540317537,0.424281195,
0.3061158,-0.210735495,0.023705618,0.473338271,0.270527033,
-0.165394174,0.268773501,0.202437269,0.305577906)
Please help me in plotting a smooth line without highlighting individual points for the data.
Thanks in advance,
A:
Not sure what "without highlighting individual points" means, but here's one way to get a smooth line:
plot(xdata,ydata)
lines(smooth.spline(xdata,ydata, df=10), col = "red")
See also: ?loess.smooth, apropos("smooth"). Searching for "[r] smooth plot" finds How to fit a smooth curve to my data in R? ...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Unix: How to clear the serial port I/O buffer?
I am working on a "high level" C++ interface for the standard PC serial port. When I open the port, I would like to clear the input and output buffers in order not to receive or send data from previous usage of the port. To do that, I use the tcflush function. However, it does not work. How can that be? My "port opening" code can be seen below. Yes I use C++ exceptions but none are getting thrown. That indicates that tcflush returns 0 but it does not clear the buffer.
The only way I can clear the input buffer is to read bytes from it until there is none left. This usually takes a couple of seconds and I do not think of it as a solution.
Thanks in advance :-)
fd = ::open(port.c_str(), O_RDWR | O_NOCTTY);
if (fd < 0)
{
throw OpenPortException(port);
return;
}
// Get options
tcgetattr(fd, &options);
// Set default baud rate 9600, 1 stop bit, 8 bit data length, no parity
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
// Default timeout (1000 ms)
options.c_cc[VMIN] = 0;
options.c_cc[VTIME] = 10;
// Additional options
options.c_cflag |= (CLOCAL | CREAD);
this->port = port;
// Apply the settings now
if (tcsetattr(fd, TCSANOW, &options) != 0)
{
throw PortSettingsException();
}
// Flush the port
if (tcflush(fd, TCIOFLUSH) != 0)
{
throw IOException();
}
A:
Try
ioctl(fd, TCFLUSH, dir)
with dir equal to 0 for receive, 1 for transmit, 2 for both.
A:
This is the correct way (as below):
usleep(1000);
ioctl(fd, TCFLSH, 0); // flush receive
ioctl(fd, TCFLSH, 1); // flush transmit
ioctl(fd, TCFLSH, 2); // flush both
User can choose both of the first 2 lines OR last line alone based on requirement. Please check if sleep may be required.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Getting PATH of running *.exe
I am currently developing a customized CafeSuite system for my Internet Cafe.
And I'm using Java and JNI (Java Native Interface) to get through the Windows Registry.
But I have this module I can't get or see if it is possible to work on Windows XP.
When I commanded on the Command-line, tasklist or tlist it would return me all of the running *.exe in the system. But with all of the parameters that could be added to the line, I can't see a parameter that would return the directory or path where an *.exe was executed.
Unfortunately, I am not using any Windows Server OS and am not to rely on any firewall of UAC or User Account Control feature of the OS.
With the given means, is it possible to pursue such concept?
A:
In XP and above you can use the “System Information” tool,
which shows the path.
You can run this from the menu at “Start” →
“All Programs” → “Accessories” → “System Tools”,
or from the command line as msinfo32
(or “Start” → “Run…” → msinfo32 ENTER).
Click on “Software Environment” → “Running Tasks”, and the path is shown.
http://www.raymond.cc/blog/determine-program-path-from-task-manager-for-each-program-in-windows-xp-windows-server-2003/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Magento2 Inventory Listing per store view?
I have a multisite magento 2.2.5 and trying to list out each sku that has less then a specific inventory but trying to list them out per store view.
Below is my sql
SELECT catalog_product_entity.entity_id, catalog_product_entity.sku, cataloginventory_stock_item.qty FROM catalog_product_entity, cataloginventory_stock_item
where catalog_product_entity.entity_id = cataloginventory_stock_item.product_id AND qty < 250"
how do I edit it to look at a specific store view?
A:
If you use only the Default stock and one website in your setup you will not be able to make a difference for the a product's stock in different store views.
That's because Magento keeps the stock per website. So if you have multiple stores and/or storeviews for the same website they will usually share the stock for a common prodcut by default.
If you use different websites with their own stock you can use the stock_id attribute in cataloginventory_stock_item to filter your selection.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
WCF service with msmq binding and closeTimeout?
I am working to speed up a large number of integration tests in our environment.
The problem I am facing right now is that during teardown between tests one WCF service using msmq binding takes about 1 minute to close down.
I the teardown process we loop over our servicehosts calling the Close() method with a very short timeout, overriding the closeTimeout value in the WCF configuration. This works well for net.tcp bindings but the one service that uses msmq still takes 1 minute to close down. The closeTimeout doesn't seem to have any effect.
The config look like this for the test service:
<netMsmqBinding>
<binding name="NoMSMQSecurity" closeTimeout="00:00:01" timeToLive="00:00:05"
receiveErrorHandling="Drop" maxRetryCycles="2" retryCycleDelay="00:00:01" receiveRetryCount="2">
<security mode="None" />
</binding>
</netMsmqBinding>
And the closing call I use is straight forward like this:
service.Close(new TimeSpan(0, 0, 0, 0, 10));
Is there another approach I can take to close down the servicehost faster?
As this is an automated test that at this point has succeded or failed I don't want to wait for any other unprocessed messages or similar.
Best regards,
Per Salmi
A:
I found the cause of the delayed closing down of the service host using Msmq.
The reason for the long close times seems to be that the service uses another net.tcp based service which has reliableSession activated and the servicehost. The reliableSession settings had an inactivity timeout set to 5 minutes which causes it to send keep-alive infrastructure messages, they should be sent every 2.5 minutes. This keep-alive messaging interval seems to cause the msmq based service to hang around for 1-2 minutes probably waiting for some of the keep-alive messages to arrive.
When I set the inactivityTimeout down to 5 seconds the shutdown of the msmq service completes in about 2.5 seconds. This makes the automatic integration tests pass a lot faster!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
PureData and Mobile Phone Games Sound
I have recently, as in this week, been approached by a games software company who mainly make games for mobile phones, with the request for some foley sounds and sound design. I also found, during my research, reference to the software called PureData.
How relevant is PureData to gaming sound design and production? Is it a case of having to learn a programming language? How else could one deliver sound to the programmers?
A:
You wanna read some of the stuff done by this guy: http://www.videogameaudio.com/
He's done a few papers on using Pd in conjunction with game engines.
Also if you do some googling, a modified version of Puredata was used to create the music in EA's "Spore".
Here are some other cool links to check out:
http://videogameaudio.com/AES-Feb2011/AES41-04Feb11-GranulationOfSoundInVideoGames-LeonardJPaul.pdf
and
http://vimeo.com/7122167
Regarding the actual delivery of sounds on mobile games, it depends on the development environment... are they just asking you to create sounds and they'll take care of implementation on their end?
There are people far more experience on this topic than me, so hopefully someone else will chime in here. Please correct me if I've made any mistakes people!
Joe
A:
Hi In my opinion experimenting with PD and delivering "some foley sounds and sound design" for a mobile app are two separate things entirely. Client deliverables and PD aren't really part of the same stream. They can be parallel thought read below ..
PD isn't a common way to hook sounds into a game. I've never hear of anyone using PD within the context of a basic mobile app and its really VERY rare for PD to be used at runtime for commercial games. Obviously there are a few exceptions. You don't need to learn PD or programming to work on sound for games.
What you do need to know is how to communicate and understand the client expectations regarding how sounds would work within the context of the game so you can clearly define what A) you need to deliver and B) what the programmers need to do to get it working as intended.
The most common way for sounds to get hooked into a game is by a programmer simply calling sounds in a VERY basic manner IE : when "x" happens play sounds OR play sound looped then stop loop once "X" happens. Advanced audio features and middleware are not common in games until you get to large scale game development for PC and console. Most small developers particularly mobile developers are writing their own game engines anyway and they certainly won't have more than the most basic audio features.
If you took the time to learn PD (months) you could build demo's to show clients and programmers how the audio interactivity could work. This helps communicate ideas faster and gives everyone the chance to give feedback on sounds as they might work in game. I wish I had a quick audio prototyping tool like PD it would solve a lot of problems early on in pre-production.
A:
I actually think that PureData/MaxMSP/SuperCollider/CSound or whichever audio programming language is really handy to know for game sound designers. And here is 2 practicle examples why :) ---
My weapon of choice is SuperCollider - currently we are looking at our weapon sounds and how they playback in game. In SuperCollider I can mock up a system to imitate what I want the weapon to do in the game, chuck in the sounds I want and see what it sounds like. The whole prototype takes about 2 hours. I can then fine tune and change the code and the sounds to taiste. I then can tell the 'real' programmers what I want. It's a damn sight quicker than bugging the programmers for prototype code. This approach is much the same as what LeonardJPaul point is.
Another example of great use of Max/MSP is EA's Sims. (If someone knows this story better than me please elaborate) - Basically from what I understand is that their entire VO recording process is pretty much automated using Max/MSP. From recording to editing and file naming. How that came to be is that one of the sound designers there could script in MAX.
So even though I agree it's pretty useless for actual sound creation or implementation in games, it can be really handy for testing or creating pipelines.
-- my 2cents -- :)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Get H.264 frame from UDP stream using jCodec
I am wondering how to get and decode a H.264 frame from a UDP live stream using jCodec. I see examples of how to get it from a file, but I need to get it from a live stream. I have the application receiving the live stream packets, but I need to know how to decode the packets and display the live stream.
Also, if there us a better way to do this than using jCodec please let me know. I looked for a while and that was the best I could find that is still actively maintained.
A:
I ended up using vlcj instead of jCodec. More information about vlcj can be found here:
http://www.capricasoftware.co.uk/projects/vlcj/index.html
And a tutorial to get started can be found here:
http://www.capricasoftware.co.uk/projects/vlcj/tutorial1.html
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Shared code logical address in process address space
In "Operating Systems Concepts" book of Silberchatz , it says
"Shared code must appear in same location in the logical address space of all processes" ,
Why does it have to appear in same location ? I thought that for each process we have a separate Page table , which makes it possible to have share code address in different logical addresses !
A:
Machine code is rarely fully position-independent. If you have some code that's been compiled to work when located at address 0x10000 (logical/virtual) and you move it to address 0x70000 (logical/virtual), it won't work at the new location.
Page tables can't help with this. What can is code/data addressing modes relative to the instruction pointer (AKA program counter). Some CPUs have it, some don't have it, yet some others have it half-baked (e.g. they can have it only for instructions that transfer control (e.g. jump/call) to other places in code, but nothing for data (e.g. move)).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
process a large file via multithreading
There is a quite large file (>10G) on the disk, each line inside the fie is composed of a line-number and a person's name, like this:
1 Jane
2 Perk
3 Sime
4 Perk
.. ..
I have to read this large file, and find the frequency of each name, finally output the results in descending order of each name's frequency, like this:
Perk 2
Jane 1
Sime 1
As the interviewer requested, the above job should be done as efficiently as possible, and multithreading is allowed. And my solution is something like this:
Because the file is too large, I partition the file into several small files, each small file is about 100M, via lseek I can locate the begin and the end of each small file (beg, end);
For these small files, there is a shared hash-map using person's name as key and how many times it shows so far as value;
For each small file, there is a single thread go through it, every time the thread encounters a person's name, it will increment its corresponding value in the shared hash-map;
When all threads finish, I think it's time to sort the hash-map according to the value field.
But because there might be too many names in that file, so the sorting would be slow. I didn't come up with a good idea about how to output the names in descending order.
Hope anyone can help me with the above problem, give me a better solution on how to do the job via multithreading and the sorting stuff.
A:
Using a map-reduce approach could be a good idea for your problem. That approach would consist of two steps:
Map: read chunks of data from the file and create a thread to process that data
Reduce: the main thread waits for all other threads to finish and then it combines the results from each individual thread.
The advantage of this solution is that you would not need locking between the threads, since each one of them would operate on a different chunk of data. Using a shared data structure, as you are proposing, could be a solution too, but you may have some overhead due to contention for locking.
You need to do the sorting part at the reduce step, when the data from all the threads is available. But you might want to do some work during the map step, so that it is easier (quicker) to finish the complete sort at the reduce step.
If you prefer to avoid the sequential sorting at the end, you could use some custom data structure. I would use a map (something like a red-black tree or a hash table) for quickly finding a name. Moreover, I would use a heap in order to keep the order of frequencies among names. Of course, you would need to have parallel versions of those data structures. Depending on how coarse the parallelization is, you may have locking contention problems or not.
A:
If I asked that as an interview question using the word "efficiently" I would expect an answer something like "cut -f 2 -d ' ' < file | sort | uniq -c" because efficiency is most often about not wasting time solving an already solved problem. Actually, this is a good idea, I'll add something like this to our interview questions.
Your bottleneck will be the disk so all kinds of multithreading is overdesigning the solution (which would also count against "efficiency"). Splitting your reads like this will either make things slower if there are rotating disks or at least make the buffer cache more confused and less likely to kick in a drop-behind algorithm. Bad idea, don't do it.
A:
I don't think multithreading is a good idea. The "slow" part of the program is reading from disk, and multithreading the read from disk won't make it faster. It will only make it much more complex (for each chunk you have to find the first "full" line, for example, and you have to coordinate the various threads, and you have to lock the shared hash map each time you access it). You could work with "local" hash map and then merge them at the end (when all the threads finish (at the end of the 10gb) the partial hash maps are merged). Now you don't need to sync the access to the shared map.
I think that sorting the resulting hash map will be the easiest part, if the full hash map can be kept in memory :-) You simply copy it in a malloc(ed) block of memory and qsort it by its counter.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Probability of superimposed states vs probability of separate states
Suppose there is an infinite square well where $\psi_1$ and $\psi_2$ are the ground state ($n=1$) and the first excited state ($n=2$), and each satisfies the time-independent Schrodinger equation. (ie, $H\psi_1=E_1\psi_1$ and $H\psi_2=E_2\psi_2$)
Now suppose we have the following two ensembles of systems in a quantum mechanical infinite square well at time $t=0$:
Half of the systems are in state $\psi_1$ and half of the systems are in state $\psi_2$
all of the systems are in a state $(\psi_1+\psi_2)/\sqrt{2}$.
At $t=0$ would the probability of finding a particle on the left half of the well in a randomly selected system from ensemble (1) be greater than, less than, or equal to the probability of finding a particle on the left half of the well in a randomly selected system from ensemble (2)? Would your answer change as time evolves?
A:
Note that I wrote this quickly, so try to find mistakes and correct them:
Okay so I'm assuming this is a 1D square well, since there was no ambiguity stated as to which degenerate state the n=2 wave function is in. Let's use the convention that the potential is zero from 0 to $\pi$ without a loss of generality (our answer will be generally invariant to rescaling).
At t=0 we can immediately say that the probability of finding a particle int he left half of ensemble (1) is 1/2. That's because $|\psi_1|^2$ and $|\psi_2|^2$ are both even about the point $\pi/2$ so the mod-square of the wave function of every particle integrates to 1/2 over the left part of the region.
For ensemble (2) (at t=0) we have a different result:
$$\frac{1}{\pi}\int_0^{\pi/2} dx \left|c_1 \sin x + c_2 \sin(2 x) \right|^2
$$
where $c_1$ and $c_2$ are just complex numbers of magnitude 1 (which are legitimate degrees of freedom for the respective wave functions).
Actually, since the answer is clearly invariant under global U(1) rotation, the only phase degree of freedom we care about in the brackets is the phase difference, so we can rotate to a phase where $c_1 = 1$ and $c_2 = e^{i \theta}; \, \theta \in [0,2 \pi)$. We can then expand it as such:
$$\frac{1}{\pi}\int_0^{\pi/2} dx \left( \sin^2x + 2 \cos\theta\sin x \sin 2x + \sin^22x \right)
$$
That's easy to do. The answer is
$$\frac{3 \pi + 8 \cos\theta}{6 \pi}
$$
Notice that the answer would simply be 1/2 if $\psi_1$ and $\psi_2$ were in phase. Alas, you didn't include that restraint in your question, so there's the general answer. Thus if $\psi_2$ shifted from $\psi_1$ by some phase in $(-\pi/2,\pi/2)$ then we're more likely to find the particle in the left half. And you can work out the consequence of different values of $\theta.$ So the answer to the question ("which is more likely?") depends on the relative phase of $\psi_1$ and $\psi_2$.
Now let's look at situation (2):
As time evolves, we have the following:
$$\psi \rightarrow e^{-i H t} \psi
$$
you'll forgive me for using units of $\hbar = 1$ here.
For the first ensemble, it's easy to see that this should have no effect. Half of the systems are just in state $e^{-i E_1 t} \psi_1$ and the other half are in state $e^{-i E_2 t} \psi_2$. In both cases, their wave function is just multiplied by an overall phase factor that gets cancelled out when you mod-square it, so the integral over the left half of the box won't change.
For system 2 we get:
$$(\psi_1 + \psi_2)/\sqrt{2} \rightarrow (e^{-i E_1 t} \psi_1 + e^{-i E_2 t} \psi_2)/\sqrt{2},
$$
which is easy to show by simply acting the unitary time operator on the whole thing. So assuming (like we did before) that $\psi_2$ was offset by phase $\theta$ from $\psi_1$ at $t=0$, we now have $\psi_2$ offset by phase $\theta - (E_2 - E_1) t.$
But this just makes our lives simple, since we already did most of the work before. This is just the same problem with a different phase factor. For ensemble 2 at time t, the probability, when taking a random system from the ensemble, of finding the particle in the left side of the box is simply
$$p = \frac{3 \pi + 8 \cos \left[\theta - (E_2 - E_1)t\right]}{6 \pi}.
$$
So now you have an answer that changes in time. Similar to the analysis I did for $\theta$ at time 0, you can figure out at which times you're more likely to find the particle in the left side for ensemble 1, and at which times it's more likely for ensemble 2. (Remember ensemble 1 is still always $1/2$; ensemble 2 oscillates between $(3 \pi- 8)/6 \pi$ and $(3 \pi + 8)/6 \pi.$)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to know current working directory in sftp from python
I had connected to sftp with some details to fetch some files with paramiko from python
and code is below
import paramiko
import os
import ftplib
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy( paramiko.AutoAddPolicy() )
ssh.connect('sftp.example.com', username='user', password='pass')
ftp = ssh.open_sftp()
files = ftp.listdir()
print files,"----< Total files"
print ftp.cwd(),"---< Current working diectory"
for feedFile in files:
if feedFile == 'LifeBridge':
ftp.chdir(feedFile)
Result
['Emerson', 'Lehighvalley', 'LifeBridge', 'stmaryct'] ----< Total files
File "test_sftp.py", line 11, in <module>
print ftp.cwd() ---< Current working diectory
AttributeError: 'SFTPClient' object has no attribute 'cwd'
here what i am doing is
Trying to find the current working directory of sftp
There is a list of files above which i got as a result for printing files, i am trying to check whether they are folders or files,
If they are folders i want to enter in to LifeBridge folder
Finally can anyone let me know the following
how to check the current working directory of sftp
how to check whether result from the above list is a file or a folder
A:
You are looking for the .getcwd() method instead:
Return the "current working directory" for this SFTP session, as emulated by paramiko. If no directory has been set with chdir, this method will return None.
So at the start of your session, if you need the current working dir, try a .chdir('.') (change to current directory) first.
The .listdir() method only returns names of items in the directory. If you need more information about those files, you'd need to use the .listdir_attr() method instead, it returns a list of SFTPAttributes instances.
An SFTPAttributes instance tells you what mode the file has, through the .st_mode attribute. Use the stat.S_ISDIR(mode) function to test if the file is a directory.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to map facebook authenticate users to roles using the asp.net RoleProvider?
I'm trying to switch my site from the asp.net membership sql provider to using facebook connect to do OAuth single signon. I'd like to keep using the role provider as it makes it pretty easy secure sections of my site by flagging the controller class or controller methods with the Authorize(Roles="...") attribute. The site isn't live yet so I'll be completely ditching the Asp.net membership provider if I can. (keeping the roles and profile provider)
I've got the facebook connect logging the user in and I can get his info. But how do I associate that with a role?
I'd like the system to automatically add a new user to the "SuperHero" role after he authenticates and authorizes my app.
Am I on track here? Is there a better way to handle roles when using OAuth2? I'd like to add other OAuth providers later.
An alternate approach would be to keep the asp membership, then when I user logs in through facebook connect, I could find his record and sign him in with aspmembership. But that seems sloppy.
Some sample code would be great and I'd think others would find it helpful too.
thx,
Dan
A:
The easiest way to do this ime is to actually implement a FacebookMembershipProvider for yourself. That way it ties in to all the other providers naturally. The main downsides are a) a lot of code b/c Membership is a fat interface, and b) some cruft b/c it assumes you'll be doing passwords, etc, which obviously you don't need for OAuth.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
An INSERT conditioned on COUNT
How can I construct a MySQL INSERT query that only executes if the number of rows satisfying some condition already in the table is less than 20, and fails otherwise?
That is, if the table has 18 rows satisfying the condition, then the INSERT should proceed. If the table has 23 rows satisfying the condition, then the INSERT should fail.
For atomicity, I need to express this in a single query, so two requests can not INSERT at the same time, each in the 'belief' that only 19 rows satisfy the condition.
Thank you.
A:
What about:
INSERT INTO TargetTable(Column1, Column2, ...)
SELECT 'Value For Column 1', 'Value For Column 2', ...
FROM Dual
WHERE (SELECT COUNT(*) FROM TargetTable WHERE ...Some Condition...) < 20;
If the WHERE clause is not satisfied, no row is inserted; if the where clause is satisfied, then one row is inserted.
You can adapt the same mechanism to select from another table (instead of a single row of values from DUAL).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
A question about how to factorise a binomial.
If $x=\frac{-1}{3}$
$(x+1)^3-{3(x+1)}^2+3(x+1)$ =?
Using the binomial theorem coefficients I'm going to add 1 at the end
[$(a-b)^3=a^3-3a^2b+3ab^2-b^3]
So we now have
$(x+1)^3-{3(x+1)}^2+3(x+1)+1$
How do I continue from here?
A:
Note that by
$$(a-b)^3=a^3-3a^2b+3ab^2-b^3$$
with
$a=x+1$
$b=-1$
we have
$$(x+1)^3-{3(x+1)}^2+3(x+1)=(x+1)^3-{3(x+1)}^2+3(x+1)-1+1=[(x+1)-1)]^3+1=x^3+1$$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Python: Why does interpreter search for variable assignment in a function below the line being executed?
Context
I am relatively new to python / computer programming and trying to wrap my head around some basic concepts by playing around with them.
In my understanding, python is an interpreted language i.e. it evaluates the line of code as it is being executed.
Question
In a function, why does interpreter check for a variable assignment by going down the code and not execute the line it is on, especially, since all relevant information is available?
Example:
def spam():
eggs = 'spam local'
print(eggs)
global eggs
print(eggs)
eggs = 'global'
print(eggs)
Error:
The code above results in the following error:
"SyntaxError: name 'eggs' is used prior to global declaration"
Confusion:
In my mind, 2nd line explicitly assigns "spam local" to the variable 'eggs'. Hence, when the interpreter reaches line 3 i.e print(eggs), it should print "spam local" and not go down the code to see there is a global declaration of the variable and return the SyntaxError.
Why is the interpreter not executing the line it is one, given that all relevant information is available?
A:
In my understanding, python is an interpreted language i.e. it evaluates the line of code as it is being executed.
No.1 Python compiles a module at a time. All function bodies are compiled to bytecode, and the top-level module code is compiled to bytecode. That's what a .pyc file is—all those bytecode objects marshaled into a container.2
When you import a module, its top-level bytecode is interpreted. (If there isn't a .pyc file, the .py file is compiled on the fly to get that bytecode.)
One more thing that might not seem obvious at first: While a function body is compiled, a def statement (or lambda expression) is compiled into interpretable bytecode, basically a call to a function that builds a function object out of the body's compiled bytecode.
You can reproduce all of this manually if you want to, which can be handy for experimenting with how things work. You can call compile on some module source with exec mode to compile it the same way an import would, and you can call exec on the result to run it the same way an import would, and you can even play with the marshal module to build your own .pyc files from scratch or load them up. (In fact, if you're on Python 3.3+, this isn't just equivalent to what import does, it's exactly what import does; importlib is written in Python.)
You can also view what the compiler has done (or would do, on source code that you haven't compiled yet and just have as a string) with the inspect and dis modules.
Part of the process of compiling a function body is detecting which names are local, cell, free, or global. A name is always consistently just one kind, for the entire lifetime of the function, which makes things easier to reason about.
Forgetting about cellvar/freevar cases (which are only needed for closures), the rule is very simple:
If there's a global statement for a name in a function body, it's global.
Otherwise, if there's an assignment to a name in a function body,3 it's local.
Otherwise, it's global.
For the full details (and slightly more accurate details4), see Naming and binding in the reference documentation.
In versions of Python before 2.2, it was legal to assign to a variable and then declare it global later in the same function. In 2.1, this followed the rules explained above: the first assignment was to the global. Which is pretty misleading, especially since it almost always happened only be accident. Which is presumably why it was made an error to do that. In earlier versions, things are just nuts.5
1. Well, in the interactive interpreter, it does sort of do this—but even there, it's a statement at a time, not a line at a time. For example, a four-line compound statement like a def or for is compiled and interpreted all at once.
2. Actually, the "container" bit is pretty trivial. In fact, everything is recursively already part of the top-level module bytecode object—e.g., a top-level function's name, bytecode, etc. are all just constant values stored in the module bytecode, just like any other constant values.
3. Things that count as assignments including being a parameter, or being a target or member of a target list for an assignment statement, a del statement, a for statement or clause, an as clause, an import, a def or class, or, in 3.8+, an assignment expression.
4. A Python implementation doesn't actually have to determine all of this stuff at compile time, as long as the semantics end up the same. So the reference is written in terms that could be followed even by an implementation without a compiler. But in practice, at least CPython, PyPy, MicroPython, Jython, and IronPython work out the name bindings at compile time.
5. Python 0.9 had no global, and different scoping rules in general. In 1.1, as far as I can tell, the rule is that an assignment before the global statement rebinds the global if there already is one (you still et a local in the frame, but it stays unbound), but binds a local variable otherwise, which makes no sense to me. I've never managed to get 1.5, 1.6, or 2.0 to build on a modern system, but the code is clearly different from early 1.x and from 2.1, so for all I know they actually did what you were expecting here… or maybe they did something just as crazy as 1.1, but completely different.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Centre Woocommerce shortcode products
I'm trying to center a Woocommerce shortcode product object, see product example 'Chanel printed logo shopper', here: http://vintageheirloom.biz/blog/2013/10/forever-fashion-everlasting-trends/
Woocommerce provide this code: [product id="6606"].
I've tried using standard Wordpress align center, I've tried putting inside a div along the lines of:
div.displayed {
display: block;
margin-left: auto;
margin-right: auto;
}
No luck, any ideas?
Much appreciated !
A:
Add the below code to your CSS, As you have only one item in it. Not suggested if you have multiple li
CSS
.displayed ul.products li.product {
float: none;
margin: 0 auto;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Types of Tables in oracle sql
I have searched for types of tables in sql, but I didn't understand those answers what I get. Please help me by providing answer.
A:
Oracle supports 4 types of tables based on how data is organized in storage:
Ordinary (heap-organized) table
•A basic, general purpose table
•Data is stored as an unordered collection (heap)
Clustered table
•A part of a cluster
•Cluster: A cluster is a group of tables that share the same data blocks as they share common columns and are often used together.
Index-organized table
•Data is stored in a B-tree index structure in a primary key sorted manner.
•Each index entry in the B-tree stores the non-key column values as well.
Partitioned table
•Data is broken down into smaller, more manageable pieces called partitions or sub-partitions.
•Each partition can be managed individually
•Each partition can operate independently
Read more in the source
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Squaring a space with the fixed-point property
We say that a space $(X,\tau)$ has the fixed point property (FPP) if for every continuous map $f:X\to X$ there is $x\in X$ with $f(x) = x$.
What is an example of a space $X$ with FPP such that $X^2$ (with the product topology) does not have FPP?
A:
The topological space
$$
X = \{ (x,\sin \left( \frac{\pi}{1-x} \right)) \ | \ 0 \leq x < 1 \} \cup {(1,1)} \subseteq \mathbb{R}^2
$$
has the FPP but its square does not. See Example $2$ p.$977$ of E. H. Connell, Properties of Fixed Point Spaces.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Question about streams in Java
I have been reading about streams in Java the past days. After reading quite a bit I start to understand that the name "stream" was chosen because of similarity to what we use the word about in "real life" such as water. And that it is not necessary to know where the data comes from. Please correct if I have interpreted it wrong.
But I do not understand this. When I say getOutputStream or getInputStream on a socket for example I get a InputStreamwhich I can chain to whatever I like. But isn't the InputStream/OutputStream abstract classes? I don't know exactly how to explain it properly but I do not understand that a socket connection just by invoking that method automatically has a stream/channel where bytes/characters can flow? What is in fact a InputStream / OutputStream? Are streams a way of abstracting the real sources?
I think I understand the various ways of chaining them though, however I feel I miss the core of the concept.
In lack of a proper way of explaining it I will delete question if it is bad.
Thank you for your time.
A:
When you call getInputStream, the socket returns an instance of some concrete subclass of InputStream. Usually you don't worry about the exact class of the returned object; since it is an InputStream, you just work with it that way. (The subclass may even be a private nested class of the socket class.)
A:
InputStream is indeed an abstraction. On each occasion a different implementation of the stream concept can be used. But the user of the stream does not need to know what was the exact implementation.
In the case of Socket, the implementation is a SocketInputStream which extends FileInputStream
A:
InputStream/OutputStream are, well, abstractions. They give you some basic API for reading/writing bytes or groups of bytes without exposing the actual implementation. Let's take OutputStream as an example:
OutputStream receives a bunch of bytes through the public API. You don't actually know (and care) what is happening with these bytes afterwards: they are sent. Real implementation may: append them to file, ignore them (NullOutputStream in Apache Commons), save them in memory or... send through socket.
This is what happens when you call Socket.getOutputStream(): you get some implementation of OutputStream, just don't care, it is implementation-dependent and specific. When you send bytes to this stream, underlying implementation will push them using TCP/IP or UDP. In fact TCP/IP itself is a stream protocol, even though it operates on packets/frames.
The situation is similar for InputStream - you get some implementation from socket. When you ask the stream for few bytes, the underlying InputStream implementation will ask OS socket for the same amount of bytes, possibly blocking. But this is the real fun of inheritance: you don't care! Just use these stream any way you want, chaining, buffering, etc.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Grails spring security core, how to set principal manually
Hi im trying to make facebook's login in a grails app, the problem I have is that when the user is logged in facebook, spring security core doesn't recognize him, how can I set the user's principal manually?
I can look for the user object but i don't know how to set it in order to get a true user when i call getAuthenticatedUser() (now it returns a null object)
Thanks in advance,
Regards
A:
Cannot say anything regarding facebook, but Spring Security has a SecurityContextHolder that can be used to manipulate the authentication (and therefore the principal) like this:
import org.springframework.security.core.context.SecurityContextHolder as SCH
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken
....
def securityContext = SCH.context
def principal = <whatever you use as principal>
def credentials = <...>
securityContext.authentication = new PreAuthenticatedAuthenticationToken(principal, credentials)
Maybe you'll need to use a different implementation of the Authentication interface as the one used in the example.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Need a resizeable container for std::mutex
I need to be able to store "n" number of mutexes at any given time.
These URLs relate directly to my problem
storing mutexes in a vector/deque c++
How can I use something like std::vector<std::mutex>?
And I am confident I understand why mutexes can not be stored in containers that might have to move them (as mutexes can't be moved). My question is, have there been any developments in c/c++ since these articles were posted that I might be able to utilize that I don't know about?
A simple array would be nice, but won't work for obvious reasons. A vector or similar would work, except for the fact that the mutexes can't be moved and therefore generates a compiler error. The following does work, but seems to be decried by some. Is there a programmatic reason why the following code example shouldn't be used to solve the problem?
std::vector<std::timed_mutex*> myMutexes;
myMutexes.push_back(new std::timed_mutex());
A:
From the linked page,
If you need to add non-movable items to the end of a sequence, switch to deque, that will work where vector won't.
If you need insertions or deletions that are neither at the beginning nor at the end, then of course std::deque won't work either and you would need to use something like std::vector<std::unique_ptr<std::mutex>>. This is better than using raw pointers because it guarantees that the mutexes will get released when they're removed from the vector or when the vector goes out of scope (except in the case of abnormal program termination).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to reset watchOS deployment target in WatchKit extension target (XCode7 beta 6)
I develop iOS app using watchOS.
After upgrading XCode to version7 beta 6, watchOS Deployment Target(Build settings) changed to 2.0 in WatchKit extension target automatically.
Though I tried to return to 1.0, couldn't change it.
Any workaround? (without creating or duplicating watchkit extension target)
A:
According to Xcode 7 Beta 6 Release Notes:
You are not be able to debug a watchOS 1 app extension in a project that also has watchOS 2 app built in the same iOS app.
Workaround: The system prefers the watchOS 2 app when both are present, so you need to remove it from the iOS app bundle. Edit the Build Phases of the iOS App to remove the watchOS 2 app as a build dependency of the iOS App and remove it from the Embed Watch Content build phase. Clean the build products, and then Run to debug the watchOS 1 app extension. (21173814)
http://adcdownload.apple.com/Developer_Tools/Xcode_7_beta_6/Xcode_7_beta_6_Release_Notes.pdf
|
{
"pile_set_name": "StackExchange"
}
|
Q:
TinyMCE dropdown arrows below buttons and buttons not working correctly
I have downloaded TinyMCE V4.0.1 and really want to work with it. Unfortunately, when I use it, some things happen that should not happen:
At the buttons that have a drop down (like the color button), the dropdown falls beneath the button
When selecting a piece of text and for example pressing the B button to make it bold, the cursor jumps back to the start of the editor and nothing happens.
This is the code I'm using for the editor:
tinymce.init({
selector: "#fulltext_editor",
theme: "modern",
plugins: [
"advlist autolink lists link image charmap print preview hr anchor pagebreak",
"searchreplace wordcount visualblocks visualchars code fullscreen",
"insertdatetime media nonbreaking save table contextmenu directionality",
"emoticons template paste textcolor"
],
menubar: false,
toolbar1: "save | insertfile undo redo | styleselect | bold italic underline subscript superscript | alignleft aligncenter alignright alignjustify",
toolbar2: "bullist numlist | forecolor backcolor | link image media | table | searchreplace | code"
});
Even with a more simple code the above points happen. I haven't found any explanation of why this should happen and how this would be resolved. Also, I can't get the jQuery version to work at all (I am using jQuery for other stuff on my website)
A:
For the problem with the dropdowns, you have probably set the HTML span element to display: block somewhere in your CSS. Add the following to fix it:
.mce-menubtn span {
display: inline-block
}
In terms of the bold functionality not working, I can only imagine there is a JS conflict somewhere. Is anything showing up in the JS Console when you load the page or click the button?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
just for the kick in the teeth
From the movie Godzilla (2014)
One day, I met a guy who runs a cargo boat offshore. Everyday he goes right past the reactor site. So, he places a couple frequency monitors on buoys for me. Two weeks ago, because I check this thing like every other day just for the kick in the teeth. Two weeks ago, I'm tuning in...
What does this expression mean? There is the expression kick in the teeth that's used to describe how badly you're being treated by someone, but it doesn't seem like that's what the person in the quote is saying.
A:
There is a series of expressions in English starting with "just for" that mean "for no particular reason." Examples include:
Just for the sake of doing it
Just for the hell of it
Just for shits and giggles
Just for laughs
Just for fun
Just for kicks
One of these expressions is:
Just for a kick in the pants
In this context, "a kick in the pants" means "fun".
Normally, "a kick in the teeth" as an idiom means something like "a sudden and devastating event" or "a painful setback". However, in this context, it takes on the meaning of the primary expression, and the primary meaning is still "for no particular reason."
The secondary implication is that the behavior is known to be unproductive or disappointing--that he's not checking for any particular reason, but he keeps doing it, even though he know he's going to be disappointed every time he checks.
So the sentence might be rephrased something like:
I monitor this frequency every other day or so. I don't have any good reason to, and I know I'm never going to hear anything, but I do it anyway.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Elegant proof of $e^{nf}=\cosh(n)+\sinh(n)f$ where $f^2=1$
The following transition comes up in various physics texts, often without explanation, so I was wondering if there is a nice way to prove it:
Given $n$ and $f$ such that $f^2=1$, we have
$$e^{nf}=\cosh(n)+\sinh(n)f$$
I managed to prove it through series expansion, but it is far from elegant.
I tried to make sense of a different way of viewing it, $$e^{nf}=\frac {e^n+e^{-n}}2+\frac {e^n-e^{-n}}2f$$
but I still don't see it.
Any idea?
A:
$$\cosh(n)=\frac{e^n+e^{-n}}{2}$$
$$\sinh(n)=\frac{e^n-e^{-n}}{2}$$
There is only 2 possible $f$ value, so it's easy to check for both, Let's start with $f=1$:
$$\cosh(n)+\sinh(n)=\frac{e^n+e^{-n}}{2}+\frac{e^n-e^{-n}}{2}=2\frac{e^n}{2}+\frac{e^{-n}}{2}-\frac{e^{-n}}{2}=2\frac{e^n}{2}=e^{n}=e^{fn}=\cosh(n)+\sinh(n)f$$
Now $f=-1$:
$$\cosh(n)-\sinh(n)=\frac{e^n+e^{-n}}{2}-\frac{e^n-e^{-n}}{2}=2\frac{e^{-n}}{2}+\frac{e^{n}}{2}-\frac{e^{n}}{2}=2\frac{e^{-n}}{2}=e^{-n}=e^{fn}=\cosh(n)+\sinh(n)f$$
Q.E.D.
Edit: I've seen the comments about the possibility of a different $f$, so I'm trying to prove it a different way.
Let's examine the ratio of the two side. If it's derivate is $0$, then their ratio is constant (assuming associativity, distributivity, commutativity):
$$\frac{\mathrm{d}}{\mathrm{d}n}\bigg(\frac{\cosh(n)+f\sinh(n)}{e^{fn}}\bigg)=\frac{\mathrm{d}}{\mathrm{d}n}\bigg((\cosh(n)+f\sinh(n))e^{-fn}\bigg)=-fe^{-fn}(\cosh(n)+f\sinh(n))+e^{-fn}(\sinh(n)+f\cosh(n))=e^{-fn}(-f\cosh(n)+f\cosh(n)-f^2\sinh(n)+\sinh(n))=e^{-fn}\sinh(n)(1-f^2)=e^{-fn}\sinh(n)(0)=0$$
Now substitute $n=0$ into the fraction to get their ratio:
$$\frac{\cosh(0)+f\sinh(0)}{e^{f0}}=\frac{1+0f}{1}=1$$
So the $2$ sides are equal.
Q.E.D.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
call variable from another form c#
I have a DataGridView in Form1 and I'm using this code to display another form called Generator:
private void button1_Click(object sender, EventArgs e)
{
Form gen = new Generator();
// Form gen = new Generator(Form this); //* I tried this but is not working *//
gen.Show();
}
In the Generator form I need to read or modify something in the datagridview wich is in the Form1.
public partial class Generator : Form
{
public Form myForm;
public Generator()
{
InitializeComponent();
}
public Generator(Form frm)
{
myForm = frm;
}
private void button1_Click(object sender, EventArgs e)
{
myForm.mydatagridview.! // this is not working
}
}
How can I resolve this problem, so I can manipulate the DataGridViewfrom the Generator form.
Thanks.
A:
Form 1:
private void button1_Click(object sender, EventArgs e)
{
Form gen = new Generator(this.mydatagridview);
gen.Show();
}
Generator Form:
DataGridView _dataGridView;
public Generator(DataGridView dataGridView)
{
InitializeComponent();
this._dataGridView = dataGridView;
}
private void button1_Click(object sender, EventArgs e)
{
this._dataGridView...! // this will work
}
Things that you must do, and know (just tips, you are not forced to do these but I believe you will be a better programmer if you do! ;)
Always call InitializeComponent() in all form constructors. In your sample you didn't call it in one of the constructors.
C# knows only information of the type you have passed. If you pass a Form, then you only get Form properties (i.e. the properties of type Form), not the properties of your own form.
Try to encapsulate things. Do not pass a whole form to another form. Instead, pass things that you would like to use on the other form.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Windows Phone MVVM Animated button
I want to create animated button in Windows Phone 8 Silverlight using MVVM pattern.
This control should work like this:
When clicked, if it's value is correct, it would trigger rotating animation. When text wouldn't be visible(rotated 90 degrees around Y axis), I'd change text on button to something like "Yes!" and then it would rotate back to normal state.
In case the value would be incorrect, I'd change background to red, without rotation.
In WPF I could use DataTriggers, so I would look like this:
1)User Clicks button -> Command is executed
2a)If value is correct, i change in viewmodel some value, which triggers DataTrigger, which starts first animation rotating button 90 degrees
3a)End of animation triggers command, which change text value
4a)Text change Triggers second rotation, which at the beginning rotates button 180 degrees and then do normal 90 degrees rotation, so it looks like new text is on other site
2b)If value is incorrect I change some value to value triggering wrong value animation
But in windows phone silverlight there are no triggers in styles, so easiest way would be to just use code-behind, but I wanted to do it in MVVM.
Maybe someone have faced similar problem.
I'm currently thinking about using messages from MVVM Light toolkit, but I'm not sure, if it'll work
Edit:
Ok, thanks to Muhammad Saifullah's tip, I managed to make it work. I use button's command to send click to VM, next i use MVVM light Toolkit to send message to view to start the animation. Unfortunatly EventToCommand from MVVM light toolkit does not work for Storyboard, so I just Execute VM's command in code behind Completed event ant it changes the value and sends next messages.
A:
You can bind command from your xaml to your VM. Below is an example how you bind command in MVVM Light.
For Button
<Button ....>
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<MvvmLight_Command:EventToCommand Command="{Binding Navigate}" CommandParameter="{Binding ElementName=btnClockin,Path=Tag}"></MvvmLight_Command:EventToCommand>
</i:EventTrigger>
</i:Interaction.Triggers>
Add following assembly references in page xaml
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:MvvmLight_Command="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WP8"
Command code in VM
/// <summary>
/// Gets the Navigate.
/// </summary>
public RelayCommand<object> Navigate
{
get
{
return _navigate
?? (_navigate = new RelayCommand<object>(
page =>
{
if (page.ToString() == "0")
MessageBox.Show("Comming Soon");
else
Messenger.Default.Send<NavigateCommand, MyPge33>(new NavigateCommand(page.ToString()));
}));
}
}
You can Bind commands on your story board in the similar way. But for starting the story board you can send message form your VM to your view.xaml.cs to start the storyboard.
Hope this helps.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
For an external USB device, why does Linux require a firmware in addition to the driver?
A few days ago I was trying to install a USB WiFi adapter in old version of linux. I installed it successfully.
But the procedure I followed required me to install not only driver, but also the firmware of the chip used in that adapter.
I searched about firmware and came to know that firmware is software that runs on hardware. But isn't the firmware preloaded in the adapter like the firmware in routers? Why if it isn't preloaded in chip?
A:
From the Ubuntu Wiki:
Many devices have two essential software pieces that make them function in your operating system. The first is a working driver, which is the software that lets your system talk to the hardware. The second is firmware, which is usually a small piece of code that is uploaded directly to the device for it to function correctly. You can think of the firmware as a way of programming the hardware inside the device. In fact, in almost all cases firmware is treated like hardware in that it's a black box; there's no accompanying source code that is freely distributed with it.
and
The firmware is usually maintained by the company that develops the hardware device. In Windows land, firmware is usually a part of the driver you install. It's often not seen by the user. In Linux, firmware may be distributed from a number of sources. Some firmware comes from the Linux kernel sources. Others that have redistribution licenses come from upstream. Some firmware unfortunately do not have licenses allowing free redistribution.
Firmware has an important feature in common with BIOS software: it cannot update itself. It is completely closed source (as opposed to open source), can be re-installed via some procedure, but it can neither be inspected nor corrected by downstream users.
A:
The main reason is that vendors want to be able to change the firmware of their USB devices after they launched the product, because...
...the firmware might have been buggy
...jurisdiction may change
...the vendor wants to be able to support more features later
...compatibility problems may arise in the field
Therefore, more and more USB devices are only equipped with a bootloader and require a firmware upload.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
JADE in Eclipse ICP exception
I want to start writing JADE in Eclipse. To do so I added the following script provided by Java Agent Development Framework - Eclipse and Maven integration.
I made an agent:
public class Test extends Agent {
private static final long serialVersionUID = 1L;
String nickname = "Peter";
AID id = new AID(nickname, AID.ISLOCALNAME);
protected void setup() {
// Printout a welcome message
System.out.println("Hello! Buyer-agent " +getAID().getName()+ " is ready.");
}
}
And when I run my JadeBootThread.run() with the following parameters:
private final String ACTOR_NAMES_args = "buyer:test.Test";
private final String GUI_args = "-gui";
I get the following error:
Jan 29, 2015 5:33:33 PM jade.core.Runtime beginContainer
INFO: ----------------------------------
This is JADE 4.3.3 - revision 6726 of 2014/12/09 09:33:02
downloaded in Open Source, under LGPL restrictions,
at http://jade.tilab.com/
----------------------------------------
Jan 29, 2015 5:33:33 PM jade.imtp.leap.CommandDispatcher addICP
WARNING: Error adding ICP jade.imtp.leap.JICP.JICPPeer@71e070c0[Cannot bind server socket to localhost port 1099].
Jan 29, 2015 5:33:33 PM jade.core.AgentContainerImpl joinPlatform
SEVERE: Communication failure while joining agent platform: No ICP active
jade.core.IMTPException: No ICP active
at jade.imtp.leap.LEAPIMTPManager.initialize(LEAPIMTPManager.java:138)
at jade.core.AgentContainerImpl.init(AgentContainerImpl.java:319)
at jade.core.AgentContainerImpl.joinPlatform(AgentContainerImpl.java:492)
at jade.core.Runtime.createMainContainer(Runtime.java:166)
at jade.Boot.main(Boot.java:89)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at main.JadeBootThread.run(JadeBootThread.java:33)
at main.Main.main(Main.java:7)
Jan 29, 2015 5:33:33 PM jade.core.Runtime$1 run
INFO: JADE is closing down now.
I tried messing around with the private final String GUI_args = "-gui"; parameters and added "-local-port 1111" but this gave the exact same error (the port in the error also stayed 1099)
A:
Add the following while running your code as arguments in eclipse
-gui -host 192.168.2.9 -port 12344
agentttt:com.DAO.test_agents.PingAgent
Then name main class as
jade.Boot
Then just run your code with all the external jar files added ,i guess this won't give any ICP error.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Reactstrap - Carousel caption to right of image
I am trying to make the caption for my Reactstrap carousel to appear to the right of the image but still in the carousel. At present, the test is appearing over the image like in the example provided in the documentation.
My JS:
render() {
const { activeIndex } = this.state;
const slides = items.map((item) => {
return (
<CarouselItem
onExiting={this.onExiting}
onExited={this.onExited}
key={item.src}
>
<div className='ImgCont'>
<img width='100%' src={item.src} alt={item.altText} />
</div>
<div className='TextCont'>
<CarouselCaption captionHeader={item.header} captionText={item.caption} />
</div>
</CarouselItem>
);
});
render() {
<div className='TrustedMechs'>
<Carousel
className='trustedMechCarousel'
activeIndex={activeIndex}
next={this.next}
previous={this.previous}
>
<CarouselIndicators items={items} activeIndex={activeIndex} onClickHandler={this.goToIndex} />
{slides}
<CarouselControl direction="prev" directionText="Previous" onClickHandler={this.previous} />
<CarouselControl direction="next" directionText="Next" onClickHandler={this.next} />
</Carousel>
</div>
});
My CSS:
.TrustedMechs{
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 4%;
width: 100%;
}
.trustedMechCarousel{
width: 50%;
height: 100%;
}
.ImgCont{
float: left !important;
}
.TextCont{
float: right !important;
}
A:
I was able to figure this out. My code is as follows:
JavaScript:
import {
Carousel,
CarouselItem,
CarouselControl,
CarouselIndicators,
CarouselCaption } from 'reactstrap';
const items = [
{
src: ./path/to/image,
altText: 'Image alt Text',
header: 'Heading',
caption: 'Content here'
},
{
src: ./path/to/image,
altText: 'Image alt Text',
header: 'Heading',
caption: 'Content here'
},
{
src: ./path/to/image,
altText: 'Image alt Text',
header: 'Heading',
caption: 'Content here'
}
];
class CarouselExample extends Component {
constructor(props) {
super(props);
this.state = {
activeIndex: 0,
};
this.next = this.next.bind(this);
this.previous = this.previous.bind(this);
this.goToIndex = this.goToIndex.bind(this);
this.onExiting = this.onExiting.bind(this);
this.onExited = this.onExited.bind(this);
}
onExiting() {
this.animating = true;
}
onExited() {
this.animating = false;
}
next() {
if (this.animating) return;
const nextIndex = this.state.activeIndex === items.length - 1 ? 0 :
this.state.activeIndex + 1;
this.setState({ activeIndex: nextIndex });
}
previous() {
if (this.animating) return;
const nextIndex = this.state.activeIndex === 0 ? items.length - 1 :
this.state.activeIndex - 1;
this.setState({ activeIndex: nextIndex });
}
goToIndex(newIndex) {
if (this.animating) return;
this.setState({ activeIndex: newIndex });
}
render() {
const { activeIndex } = this.state;
const slides = items.map((item) => {
return (
<CarouselItem
onExiting={this.onExiting}
onExited={this.onExited}
key={item.src}
>
<div className='carouselCont'>
<div className='ImgCont'>
<img width='100%' src={item.src} alt={item.altText} />
</div>
<div className='TextCont'>
<CarouselCaption captionHeader={item.header} captionText={item.caption} />
</div>
</div>
</CarouselItem>
);
});
return (
<div>
<Carousel className='trustedMechCarousel' activeIndex={activeIndex} next={this.next} previous={this.previous}>
<CarouselIndicators items={items} activeIndex={activeIndex} onClickHandler={this.goToIndex} />
{slides}
<CarouselControl direction="prev" directionText="Previous" onClickHandler={this.previous} />
<CarouselControl direction="next" directionText="Next" onClickHandler={this.next} />
</Carousel>
</div>
);
}
}
export default CarouselExample ;
The CSS is as follows:
.trustedMechCarousel{
width: 100%;
height: 100%;
}
.carouselCont{
background-color: #f1f2ed;
display: flex !important;
flex-direction: row !important;
align-items: center;
}
.ImgCont{
float: left !important;
width: 50%;
}
.TextCont{
padding: 1% !important;
position: relative;
height: 50%;
right: 4%;
width: 50%;
font-size: 25px;
}
.carousel-caption{
position: relative !important;
top: 0 !important;
height: 100% !important;
width: 75% !important;
}
.TextCont p{
color: black !important;
}
.TextCont h3{
color: black !important;
}
.carousel-control-prev-icon,
.carousel-control-next-icon {
height: 100px;
width: 100px;
outline: black;
background-size: 100%, 100%;
background-image: none;
}
.carousel-control-next-icon:after{
content: '>';
font-size: 55px;
color: black;
}
.carousel-control-prev-icon:after {
content: '<';
font-size: 55px;
color: white;
}
This is for my carousel. The custom control icons were used because the default ones were getting in the way of text.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Unable to import test module in Django 3
I'm trying to run tests for my app as described in the Django documentation: https://docs.djangoproject.com/en/3.0/intro/tutorial05/
However, with the minimal example I have shown below, I get an error complaining that:
RuntimeError: Model class myproject.myapp.models.MyModel doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
Is there some extra configuration I need to make to enable running of tests, or some other mistake that I may have done or forgotten?
Full stacktrace:
$ ./manage.py test myapp
System check identified no issues (0 silenced).
E
======================================================================
ERROR: myproject.myapp.tests (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: myproject.myapp.tests
Traceback (most recent call last):
File "/usr/lib64/python3.8/unittest/loader.py", line 436, in _find_test_path
module = self._get_module_from_name(name)
File "/usr/lib64/python3.8/unittest/loader.py", line 377, in _get_module_from_name
__import__(name)
File "/home/simernes/workspace/myproject/myapp/tests.py", line 2, in <module>
from .models import MyModel
File "/home/simernes/workspace/myproject/myapp/models.py", line 5, in <module>
class MyModel(models.Model):
File "/home/simernes/workspace/myproject/env/lib/python3.8/site-packages/django/db/models/base.py", line 112, in __new__
raise RuntimeError(
RuntimeError: Model class myproject.myapp.models.MyModel doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
settings.py:
INSTALLED_APPS = [
'myapp.apps.MyAppConfig',
...
]
apps.py:
from django.apps import AppConfig
class MyAppConfig(AppConfig):
name = 'myapp'
tests.py:
from django.test import TestCase
from .models import MyModel
# Create your tests here.
class MyModelTests(TestCase):
def model_names_are_unique(self):
"""
The database crashes if the same name is registered twice
:return:
"""
unique_name = "Unique Name"
model_first = MyModel(name=unique_identifier)
model_first.save()
model_second = MyModel(name=unique_identifier)
model_second.save()
self.assertTrue(True) # todo: assert that an error is raised
models.py:
from django.db import models
class MyModel(models.Model):
name = models.CharField(max_length=255, unique=True)
def __str__(self):
return self.name
A:
The issue was caused by somehow a __init__.py was placed in the root folder of the django project. By deleting this file it was solved.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Better way to cbind newly calculated column and quickly naming output
I've finally lost my habit of loops in R. Basically usually calculating new columns, and then doing calculations and aggregations on these new columns.
But I have a question regarding cbind which I use for adding columns.
Is there a better way than using bind for things like this?
Naming this new column always is done by me in this tedious way... Anything cleverer/simpler out there?
library(quantmod)
getSymbols("^GSPC")
GSPC <- cbind(GSPC, lag(Cl(GSPC), k=1)) #Doing some new column calculation
names(GSPC)[length(GSPC[1,])] <- "Laged_1_Cl" #Naming this new column
GSPC <- cbind(GSPC, lag(Cl(GSPC), k=2))
names(GSPC)[length(GSPC[1,])] <- "Laged_2_Cl"
tail(GSPC)
** EDITED **
Roman Luštrik added a great solution in comments below.
GSPC$Laged_3_Cl <- lag(Cl(GSPC), k=3)
tail(GSPC)
A:
One way of adding new variables to a data.frame is through the $ operator. Help page (?"$") shows common usage in the form of
x$i <- value
Where i is the new variable name and value are its associated values.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there anyway to change the size of values in ggplot in R (geom_point)?
The values are automatically set as 0.25, 0.50, 0.75, and 1. However, I would like to change these ranges, specifically make them smaller numbers. Here is my code. I also added some sample data, as you can see the p-values (the variable I am interested in) ranges from numbers as small as "1.72e-50" to "1".
library(ggplot2)
data(TFRC, package="ggplot2")
#imports/scans the data from file explorer/spreadsheets
TFRC <- read.csv(file.choose(), header = TRUE)
# bubble chart showing position of polymorphisms on gene, the frequency of each of these polymorphisms, where they are prominent on earth, and p-value
TFRCggplot <- ggplot(TFRC, aes(Position, Frequency))+
geom_jitter(aes(col=Geographical.Location, size=p.value))+
labs(subtitle="Frequency of Various Polymorphisms", title="TFRC") +
scale_size_continuous(range=c(1,5), trans = "reverse")
TFRCggplot + guides(size = guide_legend(reverse = TRUE))
Here is some sample data.
structure(list(Variant = structure(c(28L, 28L, 28L, 28L, 28L,
23L, 23L, 23L, 23L, 23L, 21L, 21L, 21L, 21L, 21L, 6L, 6L, 6L,
6L, 6L, 8L, 8L, 8L, 8L, 8L, 10L, 10L, 10L, 10L, 10L, 14L, 14L,
14L, 14L, 14L, 15L, 15L, 15L, 15L, 15L, 25L, 25L, 25L, 25L, 25L,
16L, 16L, 16L, 16L, 16L, 22L, 22L, 22L, 22L, 22L, 9L, 9L, 9L,
9L, 9L, 7L, 7L, 7L, 7L, 7L, 19L, 19L, 19L, 19L, 19L, 11L, 11L,
11L, 11L, 11L, 1L, 1L, 1L, 1L, 1L, 20L, 20L, 20L, 20L, 20L, 27L,
27L, 27L, 27L, 27L, 5L, 5L, 5L, 5L, 5L, 12L, 12L, 12L, 12L, 12L,
26L, 26L, 26L, 26L, 26L, 24L, 24L, 24L, 24L, 24L, 3L, 3L, 3L,
3L, 3L, 4L, 4L, 4L, 4L, 4L, 13L, 13L, 13L, 13L, 13L, 29L, 29L,
29L, 29L, 29L, 17L, 17L, 17L, 17L, 17L, 18L, 18L, 18L, 18L, 18L,
2L, 2L, 2L, 2L, 2L), .Label = c("rs140316777", "rs141165322",
"rs144131234", "rs149088653", "rs184956956", "rs199637290", "rs200128950",
"rs201408488", "rs34490397", "rs3817672", "rs41295849", "rs41295879",
"rs41298067", "rs41301381", "rs41303529", "rs533268185", "rs534595346",
"rs536971550", "rs537759332", "rs539830157", "rs541010181", "rs541398971",
"rs545061104", "rs559739602", "rs563942755", "rs571673598", "rs572837317",
"rs576156970", "rs577771580"), class = "factor"), Position = c(66L,
66L, 66L, 66L, 66L, 90L, 90L, 90L, 90L, 90L, 138L, 138L, 138L,
138L, 138L, 141L, 141L, 141L, 141L, 141L, 312L, 312L, 312L, 312L,
312L, 426L, 426L, 426L, 426L, 426L, 636L, 636L, 636L, 636L, 636L,
762L, 762L, 762L, 762L, 762L, 810L, 810L, 810L, 810L, 810L, 831L,
831L, 831L, 831L, 831L, 879L, 879L, 879L, 879L, 879L, 891L, 891L,
891L, 891L, 891L, 975L, 975L, 975L, 975L, 975L, 1002L, 1002L,
1002L, 1002L, 1002L, 1011L, 1011L, 1011L, 1011L, 1011L, 1056L,
1056L, 1056L, 1056L, 1056L, 1137L, 1137L, 1137L, 1137L, 1137L,
1143L, 1143L, 1143L, 1143L, 1143L, 1221L, 1221L, 1221L, 1221L,
1221L, 1260L, 1260L, 1260L, 1260L, 1260L, 1692L, 1692L, 1692L,
1692L, 1692L, 1791L, 1791L, 1791L, 1791L, 1791L, 1794L, 1794L,
1794L, 1794L, 1794L, 1815L, 1815L, 1815L, 1815L, 1815L, 2031L,
2031L, 2031L, 2031L, 2031L, 2070L, 2070L, 2070L, 2070L, 2070L,
2103L, 2103L, 2103L, 2103L, 2103L, 2172L, 2172L, 2172L, 2172L,
2172L, 2259L, 2259L, 2259L, 2259L, 2259L), Geographical.Location = structure(c(1L,
2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L,
3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L,
4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L,
5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L,
1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L,
2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L,
3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L,
4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L,
5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L
), .Label = c("AFR", "AMR", "EAS", "EUR", "SAS"), class = "factor"),
Frequency = c(0, 0, 0.202, 0, 0, 0, 0.295, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0.192, 0, 0, 0, 0, 0.384, 7.654, 5.934, 30.13571429,
58.955, 26.458, 4.008, 0.598, 0, 0, 3.782, 0, 0.196, 0.1328571429,
0, 0, 4.056, 5.592, 0, 0, 0, 0, 0.196, 0.1257142857, 0, 0,
0, 0, 0, 0, 0, 1.414, 0.404, 0.2814285714, 0.24, 0, 0, 0,
0, 0.265, 0, 0, 0, 0.3357142857, 0, 0, 0, 0, 0, 0, 1.188,
0, 0.232, 0.4414285714, 0, 0, 0, 0, 0, 0.5875, 0, 0.186,
0, 0, 0, 0, 0.186, 0, 0, 0, 0.572, 0, 0, 7.765714286, 0.265,
0, 0, 0, 0, 0, 0, 0, 0, 0.1442857143, 0, 0, 0, 0, 0.2528571429,
0, 0, 0.56, 0, 0.2885714286, 0, 0, 0, 2.692, 0.1328571429,
0, 0, 0.422, 0, 0.1442857143, 0, 0, 0, 0, 0.1485714286, 0,
0, 0, 0, 0, 0, 0, 0, 0.232, 0, 0, 0, 0, 0), p.value = c(1,
1, 0.201, 1, 1, 1, 0.139, 1, 1, 1, 1, 1, 1, 1, 0.195, 1,
1, 0.201, 1, 1, 0.579, 1, 0.183, 0.59, 0.173, 2.69e-30, 1.03e-05,
3.1e-31, 1.72e-50, 3.62e-08, 0.00641, 0.0959, 4.49e-14, 0.0205,
0.0357, 0.264, 1, 1, 1, 1, 1, 1, 1, 0.201, 1, 0.264, 1, 1,
1, 1, 1, 1, 1, 1, 0.195, 0.172, 0.361, 1, 1, 1, 1, 0.139,
1, 1, 1, 0.0696, 1, 1, 1, 1, 0.351, 1, 6.49e-05, 0.607, 0.604,
0.0183, 1, 1, 1, 1, 0.579, 0.0949, 0.589, 0.182, 1, 1, 1,
1, 1, 0.195, 0.571, 1, 0.00812, 1, 1, 7.27e-30, 0.00741,
1.28e-05, 1.27e-05, 1.26e-05, 0.334, 1, 0.59, 0.59, 0.000279,
0.264, 1, 1, 1, 1, 0.0696, 1, 1, 1, 1, 0.0696, 1, 1, 1, 1,
0.264, 1, 1, 1, 1, 0.264, 1, 1, 1, 1, 0.264, 1, 1, 1, 1,
1, 1, 1, 1, 0.195, 1, 1, 1, 0.201, 1)), row.names = c(NA,
145L), class = "data.frame")
> dput(head(TFRC,150))
structure(list(Variant = structure(c(28L, 28L, 28L, 28L, 28L,
23L, 23L, 23L, 23L, 23L, 21L, 21L, 21L, 21L, 21L, 6L, 6L, 6L,
6L, 6L, 8L, 8L, 8L, 8L, 8L, 10L, 10L, 10L, 10L, 10L, 14L, 14L,
14L, 14L, 14L, 15L, 15L, 15L, 15L, 15L, 25L, 25L, 25L, 25L, 25L,
16L, 16L, 16L, 16L, 16L, 22L, 22L, 22L, 22L, 22L, 9L, 9L, 9L,
9L, 9L, 7L, 7L, 7L, 7L, 7L, 19L, 19L, 19L, 19L, 19L, 11L, 11L,
11L, 11L, 11L, 1L, 1L, 1L, 1L, 1L, 20L, 20L, 20L, 20L, 20L, 27L,
27L, 27L, 27L, 27L, 5L, 5L, 5L, 5L, 5L, 12L, 12L, 12L, 12L, 12L,
26L, 26L, 26L, 26L, 26L, 24L, 24L, 24L, 24L, 24L, 3L, 3L, 3L,
3L, 3L, 4L, 4L, 4L, 4L, 4L, 13L, 13L, 13L, 13L, 13L, 29L, 29L,
29L, 29L, 29L, 17L, 17L, 17L, 17L, 17L, 18L, 18L, 18L, 18L, 18L,
2L, 2L, 2L, 2L, 2L), .Label = c("rs140316777", "rs141165322",
"rs144131234", "rs149088653", "rs184956956", "rs199637290", "rs200128950",
"rs201408488", "rs34490397", "rs3817672", "rs41295849", "rs41295879",
"rs41298067", "rs41301381", "rs41303529", "rs533268185", "rs534595346",
"rs536971550", "rs537759332", "rs539830157", "rs541010181", "rs541398971",
"rs545061104", "rs559739602", "rs563942755", "rs571673598", "rs572837317",
"rs576156970", "rs577771580"), class = "factor"), Position = c(66L,
66L, 66L, 66L, 66L, 90L, 90L, 90L, 90L, 90L, 138L, 138L, 138L,
138L, 138L, 141L, 141L, 141L, 141L, 141L, 312L, 312L, 312L, 312L,
312L, 426L, 426L, 426L, 426L, 426L, 636L, 636L, 636L, 636L, 636L,
762L, 762L, 762L, 762L, 762L, 810L, 810L, 810L, 810L, 810L, 831L,
831L, 831L, 831L, 831L, 879L, 879L, 879L, 879L, 879L, 891L, 891L,
891L, 891L, 891L, 975L, 975L, 975L, 975L, 975L, 1002L, 1002L,
1002L, 1002L, 1002L, 1011L, 1011L, 1011L, 1011L, 1011L, 1056L,
1056L, 1056L, 1056L, 1056L, 1137L, 1137L, 1137L, 1137L, 1137L,
1143L, 1143L, 1143L, 1143L, 1143L, 1221L, 1221L, 1221L, 1221L,
1221L, 1260L, 1260L, 1260L, 1260L, 1260L, 1692L, 1692L, 1692L,
1692L, 1692L, 1791L, 1791L, 1791L, 1791L, 1791L, 1794L, 1794L,
1794L, 1794L, 1794L, 1815L, 1815L, 1815L, 1815L, 1815L, 2031L,
2031L, 2031L, 2031L, 2031L, 2070L, 2070L, 2070L, 2070L, 2070L,
2103L, 2103L, 2103L, 2103L, 2103L, 2172L, 2172L, 2172L, 2172L,
2172L, 2259L, 2259L, 2259L, 2259L, 2259L), Geographical.Location = structure(c(1L,
2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L,
3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L,
4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L,
5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L,
1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L,
2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L,
3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L,
4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L,
5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L
), .Label = c("AFR", "AMR", "EAS", "EUR", "SAS"), class = "factor"),
Frequency = c(0, 0, 0.202, 0, 0, 0, 0.295, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0.192, 0, 0, 0, 0, 0.384, 7.654, 5.934, 30.13571429,
58.955, 26.458, 4.008, 0.598, 0, 0, 3.782, 0, 0.196, 0.1328571429,
0, 0, 4.056, 5.592, 0, 0, 0, 0, 0.196, 0.1257142857, 0, 0,
0, 0, 0, 0, 0, 1.414, 0.404, 0.2814285714, 0.24, 0, 0, 0,
0, 0.265, 0, 0, 0, 0.3357142857, 0, 0, 0, 0, 0, 0, 1.188,
0, 0.232, 0.4414285714, 0, 0, 0, 0, 0, 0.5875, 0, 0.186,
0, 0, 0, 0, 0.186, 0, 0, 0, 0.572, 0, 0, 7.765714286, 0.265,
0, 0, 0, 0, 0, 0, 0, 0, 0.1442857143, 0, 0, 0, 0, 0.2528571429,
0, 0, 0.56, 0, 0.2885714286, 0, 0, 0, 2.692, 0.1328571429,
0, 0, 0.422, 0, 0.1442857143, 0, 0, 0, 0, 0.1485714286, 0,
0, 0, 0, 0, 0, 0, 0, 0.232, 0, 0, 0, 0, 0), p.value = c(1,
1, 0.201, 1, 1, 1, 0.139, 1, 1, 1, 1, 1, 1, 1, 0.195, 1,
1, 0.201, 1, 1, 0.579, 1, 0.183, 0.59, 0.173, 2.69e-30, 1.03e-05,
3.1e-31, 1.72e-50, 3.62e-08, 0.00641, 0.0959, 4.49e-14, 0.0205,
0.0357, 0.264, 1, 1, 1, 1, 1, 1, 1, 0.201, 1, 0.264, 1, 1,
1, 1, 1, 1, 1, 1, 0.195, 0.172, 0.361, 1, 1, 1, 1, 0.139,
1, 1, 1, 0.0696, 1, 1, 1, 1, 0.351, 1, 6.49e-05, 0.607, 0.604,
0.0183, 1, 1, 1, 1, 0.579, 0.0949, 0.589, 0.182, 1, 1, 1,
1, 1, 0.195, 0.571, 1, 0.00812, 1, 1, 7.27e-30, 0.00741,
1.28e-05, 1.27e-05, 1.26e-05, 0.334, 1, 0.59, 0.59, 0.000279,
0.264, 1, 1, 1, 1, 0.0696, 1, 1, 1, 1, 0.0696, 1, 1, 1, 1,
0.264, 1, 1, 1, 1, 0.264, 1, 1, 1, 1, 0.264, 1, 1, 1, 1,
1, 1, 1, 1, 0.195, 1, 1, 1, 0.201, 1)), row.names = c(NA,
145L), class = "data.frame")
A:
The main problem in the question was to make the points easier to read. That was solved with a suggestion by Gregor in a comment.
A secondary question is to have the legend display the log10 labels as powers of 10. Since I have not found a solution to this easily, surely not in the StackOverflow posts, here it is. It uses scales::math_format in a different way than the one used for the axis labels.
library(ggplot2)
library(scales)
TFRCggplot <- ggplot(TFRC, aes(Position, Frequency)) +
geom_jitter(aes(colour = Geographical.Location, size = log10(p.value))) +
labs(subtitle="Frequency of Various Polymorphisms", title="TFRC") +
scale_size_continuous(range = c(1, 5),
breaks = seq(0, -50, by = -10),
labels = math_format(10^.x),
trans = "reverse")
TFRCggplot + guides(size = guide_legend(reverse = TRUE))
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Nível de detalhamento de casos de uso
Estou começando a usar casos de uso pra documentar requisitos de sistemas orientados a objetos e estou com um pouco de dúvida quanto ao nível de detalhamento de um caso de uso. Basicamente, eu tenho dúvidas em relação a "o que deve constar no cenário". Vou dar dois exemplos disso: o primeiro deles é CRUD.
É comum encontrar requisitos de um sistema como "cadastrar/ler/editar/excluir produtos", ou analogamente pra clientes. De qualquer forma, o requisito é basicamente "fazer CRUD de tal entidade". Eu realmente fico em dúvida no quanto detalher de um caso de uso desses. Eu tenho duas possibilidades: simplesmente escrever um caso de uso "Manter Produtos" com cenário contendo um único passo "Manter dados dos produtos", por exemplo.
Ou posso fazer um caso de uso pra cada uma das operações, contendo todos os detalhes, como quais campos tem e tudo mais. No caso de CRUD qual dessas é a abordagem mais usada normalmente?
Existem ainda outros pontos dos sistemas que eu nem sempre sei muito bem o que realmente precisa ser detalhado num caso de uso. Pra explicar melhor isso vou pegar um exemplo de um sistema que estou desenvolvendo agora (para controle de um restaurante). Basicamente, o dono do restaurante ao inicio de cada expediente precisa ir no programa e criar uma nova sessão, ou seja, "inicializar as atividades do restaurante" dentro do sistema.
Esse caso de uso não é algo de CRUD, é realmente uma operação que um ator (o gerente) está interessado em fazer no sistema. Mas só consegui pensar em um passo: "Gerente inicializa nova sessão" e isso parece ser muito mais simplório do que deveria.
Não sei se consegui explicar muito bem com o exemplo o tipo de situação que estou falando. São situações em que parece que o único passo realmente é o que o próprio titulo do caso de uso diz e nesses casos fica dificil saber o que realmente detalhar
O quanto eu preciso detalhar em casos como esse? Apesar de ter dado esse exemplo, a pergunta é no geral mesmo, o exemplo é só pra ter algo concreto pra facilitar a pergunta.
Uma vez li sobre isso e falava-se bastante sobre entender quem vai ler isso, se é a equipe de perguntas e respostas, ou outra equipe, etc. Como eu trabalho sozinho, gostaria de saber como se lida com isso em casos como o meu, no qual não tem esse nível de formalidade e os casos de uso são escritos mais pra documentar e organizar os requisitos.
A:
Não faça casos de uso de CRUD
Imagine o seguinte cenário:
O Cliente pode realizar o caso de uso Remover Pedido sendo que ele nunca criou um pedido? Não, não pode. Tampouco pode consultar, alterar ou atualizar um pedido.
Os Casos de Uso devem representar as necessidades principais do sistema. Na figura acima foi criado um cenário pensando em funcionalidades, e isso deve ser evitado pois o objetivo dos casos de uso é dar contexto ao projeto, ele deve descrever os requisitos funcionais, ou seja, ele deve descrever o sistema sob a perspectiva do usuário. Em outras palavras, o diagrama de Casos de Uso deve fornecer uma visão gráfica resumida da operação do sistema.
A intenção principal do usuário no diagrama acima é Criar Pedido. Todos os elementos restantes se tornarão fluxos alternativos na especificação do caso de uso principal.
Outro problema gerado no diagrama acima é que a decomposição funcional, que é o ato de desmembrar um caso de uso em objetivos menores, gerando uma quantidade maior de casos de uso que possuem objetivos cada vez mais específicos. Essa estratégia vai contra a real finalidade do sistema, que deve descrever a parte funcional do sistema em objetivos macros, e ao desmembrá-los, temos várias ações isoladas que não representam as funcionalidades reais do sistema.
Nomeando os casos de uso
Esqueça o nome "Manter produtos", você está cadastrando produtos, você não mantém os produtos, ninguém acessa o sistema para manter um produto. O termo "mantém" nesse contexto é completamente vago e não passa a real intenção do usuário.
"Inicializar nova sessão", esse sim é um suposto caso de uso completamente equivocado, ele na verdade é apenas uma etapa de um fluxo de algum caso de uso. Ou seja, de maneira alguma ele é um caso de uso. Casos de uso são requisitos funcionais do seu sistema.
Pense no caso de uso como algo atômico, que você executa do início ao fim com um propósito bem definido, como algo que visa solucionar um problema que foi o motivo pelo qual o cliente decidiu comprar o seu sistema. Como uma dica, se quiser identificar se o caso de uso possui um fluxo completo ou não sempre imagine o cliente falando:
Preciso de um sistema para poder [SUPOSTO CASO DE USO]
Para o exemplo acima, ficaria:
Preciso de um sistema para poder "Inicializar uma nova sessão"
Ninguém compra um sistema para poder "Inicializar uma nova sessão". Seu sistema existiria se seu único caso de uso fosse "Inicializar uma nova sessão"? Não. Portanto ele não deve fazer parte do seu diagrama. Seu sistema põe um pedido, fecha uma conta, cadastra um cliente, faz recebimento de matérias primas, etc.. as coisas mais banais são apenas detalhes que serão especificadas em algum determinado documento do seu projeto.
Se o fluxo "Inicializar nova sessão" for utilizado inúmeras vezes por outros casos de uso você pode criar um Caso de Uso de Inclusão para ele, que representa um caso de uso sem um fluxo completo e consequentemente nunca interagirá com um Ator, ele apenas pode ser incluído por outros casos de uso em prol do reuso, evitando assim a repetição desnecessária de textos e possibilitando uma fácil manutenção dos casos de uso que incluem ele.
Nomeando os atores
Não confunda papel com cargos ou até mesmo pessoas.
Você disse que criou um Ator gerente para cadastrar os produtos, será que só o gerente pode cadastrar? Nunca outro funcionário poderá fazer o papel de cadastrar produtos? Considere em dar um nome para seu Ator que represente que papel ele está assumindo na hora de executar o Caso de Uso. Que tal Mantenedor?
Utilidade dos casos de uso
São 14 os tipos de diagramas que pertencem a linguagem UML, 7 estruturais e 7 comportamentais, ou seja, são mais diagramas do que costumamos sequer saber da existência, cada diagrama tem um propósito específico e bem definido, e a aplicabilidade de cada um varia de projeto para projeto, de ocasião para ocasião. O Diagrama de Caso de Uso não é exceção.
Como você disse que trabalha sozinho eu diria que uma situação em que o Diagrama de Casos de Uso pode ser importante é quando se utiliza a metodologia de desenvolvimento ICONIX. "Pode" ser importante pois obviamente tudo depende do tamanho e importância do seu projeto.
Detalhando seu Caso de Uso
Cada Diagrama de Caso de Uso deve ser acompanhado de um documento que se chama de especificação, esse documento que possuirá uma análise muito mais detalhada. Um exemplo de tópicos que uma especificação aborda:
Nome do Caso de Uso
1.1 Breve Descrição
Fluxo de Eventos
2.1 Fluxo Básico
2.2 Fluxos Alternativos
Requisitos Especiais
Precondições
Pós-condições
Pontos de Extensão
Cenários
7.1 Cenários de Sucesso
7.2 Cenários de Insucesso
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to use bind correctly here?
I can not figure out the correct syntax to bind member functions.
If I have a function that takes a function with a single argument,
how do I pass an object to it?
In the following example, what would be the correct syntax of passing the function?
#include <iostream>
#include <functional>
void caller(std::function<void(int)> f)
{
f(42);
}
class foo
{
public:
void f(int x)
{
std::cout<<x<<std::endl;
}
};
int main()
{
foo obj;
caller(std::bind(&foo::f,obj));
//^Wrong
}
Error was:
a.cpp: In function ‘int main()’:
a.cpp:18:34: error: could not convert ‘std::bind(_Func&&, _BoundArgs&& ...) [with _Func = void (foo::*)(int); _BoundArgs = {foo&}; typename std::_Bind_helper<std::__or_<std::is_integral<typename std::decay<_Tp>::type>, std::is_enum<typename std::decay<_Tp>::type> >::value, _Func, _BoundArgs ...>::type = std::_Bind<std::_Mem_fn<void (foo::*)(int)>(foo)>]((* & obj))’ from ‘std::_Bind_helper<false, void (foo::*)(int), foo&>::type {aka std::_Bind<std::_Mem_fn<void (foo::*)(int)>(foo)>}’ to ‘std::function<void(int)>’
caller(std::bind(&foo::f,obj));
A:
There is an implicit first argument to member functions, which is the this point. You need to send it as a pointer; you also need a placeholder for the int argument. So:
caller(std::bind(&foo::f, &obj, std::placeholders::_1));
// ^ ^^^^^^^^^^^^^^^^^^^^^^^
A:
Placeholders create a "space" for the actual arguments to be bound later:
int main()
{
foo obj;
caller(std::bind(&foo::f, &obj, std::placeholders::_1));
// ^ placeholder
// ^ address or even foo()
}
These placeholders are needed to correctly generate an appropriate signature for the std::bind result to be bound to the std::function<void(int)>.
You may also want to use the address of your object, or std::ref (so it won't be copied); this will vary on what you want the semantics to be.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
PHP echo value of a object from array
I have a array which I am printing using print_r.
<?php
print_r ($this)
?>
I get following result in my browser.
PackingListForm Object
(
[objShipment:protected] => Shipment Object
(
[objCustomFieldArray] =>
[intShipmentId:protected] => 38
[strShipmentNumber:protected] => 1035
[intTransactionId:protected] => 97
[intFromCompanyId:protected] => 1
[intFromContactId:protected] => 1
[intFromAddressId:protected] => 1
[intToCompanyId:protected] => 2
[intToContactId:protected] => 3
[intToAddressId:protected] => 2
[intCourierId:protected] => 1
[strTrackingNumber:protected] =>
[dttShipDate:protected] => QDateTime Object
)
)
Now I want to print / echo intTransactionId.
I have used following variable to echo the result, but I am getting undefined variable.
<?php
$noted = $this->objShipment->intTransactionId;
print_r ($noted);
?>
I am getting following php exception error in my browser.
Undefined GET property or variable in 'Shipment' class: intTransactionId
Line 33: $noted = $this->objShipment->intTransactionId;
My question is how can I echo / print value of intTransactionId?
A:
intTransactionId is a protected property which means that you can't access it outside of the class itself (or parennt class or child class).
The exception, I think, is thrown in a __get magic method defined in Shipment (or one of its parent classes). This method is called when trying to access an unset property (or non-accesible property).
Please check this behaviour.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Extracting and saving attachments from maildir, deduplicated
I would like to know if there exists a solution for archiving email, stripping out the attachments and saving them separately, deduplicated?
The ideal would be a maildir-setup, with a script running over the messages, extracting the attachments, using e.g. hard links for existing/identical attachments, leaving a link/URL to the saved attachment left in the message.
Does anything like this exist, as scripts or anything that can be run on a linux server?
AFAIK Zimbra is set up similar, with a custom maildir+database backed storage, however, I would like something a bit more "transparent" for my archiving needs.
A:
Dovecot does exactly this (Single Instance Storage) now with their dbox maildir format.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
s3fs and fuse: failed to open /dev/fuse: Permission denied
Just installed Debian 6 box. I wanted to mount my S3 bucket for some backups.
So I followed instructions for http://code.google.com/p/s3fs/ .
1) I installed all perquisites asked in installation instruction.
2) Compiled and installed s3fs.
3) Configured by putting my credentials to passwd-s3fs.
4) Tried to mount my bucket: "/usr/bin/s3fs backupejekabsons /mnt"
I get error message "fuse: failed to open /dev/fuse: Permission denied"
After googling a bit, I found out that I need to add "fuse" group to my account.
I added a group and relogged. Didn't help.
I tried to reboot VM, still no result.
Some output that may be helpful:
1) edgarsj@1310-700-4568:~$ groups
fuse edgarsj rvm
2) edgarsj@1310-700-4568:~$ id
uid=1001(edgarsj) gid=111(fuse) groups=1002(edgarsj),111(fuse),1000(rvm)
3) edgarsj@1310-700-4568:~$ ls -la /dev/fuse
crw-rw---- 1 root fuse 10, 229 Aug 12 15:36 /dev/fuse
I also tried to add this group to root and run as sudo. Same result.
Thanks for your attention, mates. Any help is appreciated.
A:
Does this discussion help? http://groups.google.com/group/s3ql/msg/8cf247561362f378
Basically, the VM host may not be actually giving you permission to use /dev/fuse.
They've added to solution to the s3ql FAQ: http://code.google.com/p/s3ql/wiki/FAQ
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Rails Naming Convention Issue?
Hello I have a 1:M relationship between Customer_Status and Customer. Customer_Status applies to many Customers. I put the associations in the corresponding models.
Below is my schema
create_table "customer_statuses", force: :cascade do |t|
t.string "customer_status_desc"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "customers", force: :cascade do |t|
t.integer "customerstatus_id"
t.integer "customertype_id"
t.string "first_name"
t.string "last_name"
t.string "primaryemail"
t.string "secondaryemail"
t.string "billingcity"
t.string "billingstreet"
t.integer "billingzip"
t.integer "primaryphone"
t.integer "secondaryphone"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
In my Customer Index View I am trying to display attribute customer_status_desc from the Customer Status table instead of the customerstatus_id found in the Customers table.
In the Customer Index View I have:
<% @customers.each do |customer| %>
<tr>
<td><%= customer.customer_status.customer_status_desc %></td>
<td><%= customer.customertype_id %></td>
<td><%= customer.first_name %></td>
<td><%= customer.last_name %></td>
</tr>
<% end %>
For the life of me I cannot get the customer_status_desc to display. I get the error undefined method customer_status_desc for nil:NilClass I have tried naming it differently such as customer.customerstatus.customer_status_desc
After some research it appears the naming conventions are out of whack. Is there any way to resolve this without changing all of the names. Can I help rails understand what I am trying to call - or possibly force it through a query?
EDIT:
I am using postgres and rails 4
Customers Controller
def index
@customers = Customer.order(sort_col + " " + sort_dir)
end
A:
Your column customerstatus_id should be named customer_status_id, and be sure that you have a belongs_to :customer_status in your Customer model.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What all do I need for a simple speaker circuit?
I'm trying to use a 555 timer in astable mode to play a square wave sound out of a small speaker, but I'm having trouble understanding all the components I should use.
I think I need something like this:
simulate this circuit – Schematic created using CircuitLab
So the output of the 555 timer switches Q1 on and off, playing a sound out of the speaker. R1 is to limit the current going to the speaker. D1 is a "flyback diode" (?). My speaker is supposedly 0.2 W with 8 Ω impedance.
So here are my questions:
Given those numbers for my speaker (0.2 W and 8 Ω), how do I calculate what value of resistor I need for R1, assuming I'm giving it 5 V? (The actual math is preferred over just telling me the value.) I want the speaker to be loud but not damage it.
What the heck is a "flyback diode", and why do I need it? I tried reading the Wikipedia page, but I think I don't really understand how inductance works. So maybe someone can explain like I'm five. Also, what type of diode should I use for this, and why?
I read something somewhere about putting a capacitor in there somewhere, I think in series with the speaker to protect it somehow. Why would I need that?
Is there anything else I'm missing, and why?
A:
Given those numbers for my speaker (0.2 W and 8 Ω), how do I calculate
what value of resistor I need for R1, assuming I'm giving it 5 V? (The
actual math is preferred over just telling me the value.) I want the
speaker to be loud but not damage it
E=IR, Voltage=current times resistance
P=IE, Power=Current times voltage
You have Power and Resistance, and you want to know current, so knowing that E=IR, lets replace the E in P=IE with IR.
P=I^2R
Now we can solve for current.
I^2=P/R
I=sqrt(P/R)
Plugging in the values for your speaker, you get a max current of about 158 mA rms. Note that speaker values give you impedance, not resistance, as they take the inductive reactance of the speaker into account as well as it's resistance. There are probably more accurate formulas but these will allow you to ballpark it. If you want to get more in depth, study "RLC circuits" and all associated formulas.
Taking the 158ma max current and the source voltage of 5v, the total resistance you want will be
E=IR
R = E/I = 5v/0.158A = 31.64 ohms
Note that impedance is not the same thing as resistance, but that the impedance of the speaker will factor into the current flow and is included in this 31.64 ohms. I'd do a few quick tests with resistance from 25-40 ohms.
Note that it is likely more practical to use a rheostat or potentiometer of sufficient wattage and simply decrease the resistance, increasing volume until you start to hear distortion, then back it off to where it's clean, disconnect, and measure the resistance. Generally speaking if you don't push the speaker hard enough to produce distortion, you won't damage it.
What the heck is a "flyback diode", and why do I need it? I tried
reading the Wikipedia page, but I think I don't really understand how
inductance works. So maybe someone can explain like I'm five. Also,
what type of diode should I use for this, and why?
A flyback diode is used to protect circuits from inductive surges. Inductance is the property of an object that causes it to resist changes in current. A speaker is an inductor. At the moment you give power to an uncharged inductor, it has no magnetic field, and it has only the natural resistance of the wire. As current begins to flow, the current produces a magnetic field, storing some of the energy going into producing that current. When you close the switch and stop providing power to the speaker, it still has a magnetic field, and because you are no longer pushing current through it and supporting the magnetic field, the field, collapses, delivering the energy it stored through producing the magnetic field and changing the position of the magnet core, by dumping that current back into the circuit, in the opposite direction. If this current has nowhere to go, it can produce a high voltage (given that current is flow rate and voltage is pressure, watch a few youtube videos on "water hammer" if you need to visualise) and that voltage can be much higher than intended in the design, damaging components. This flyback diode gives a low impediance path for this discharge, preventing it from building up and damaging the circuit.
As for which diode, I would just go for a fast one to reduce any switching losses, but you can probably get away with just about any diode.
I read something somewhere about putting a capacitor in there
somewhere, I think in series with the speaker to protect it somehow.
Why would I need that?
If they advise to put a capacitor in series, that would likely let only the AC portion of the wave through, meaning that it will protect from a DC short circuit(always ON condition) and may give you a smoother sound. I'd just hook it up in series and test it on a breadboard. Make sure you use bipolar capacitors.
Is there anything else I'm missing, and why?
Have to know a bit more about your goals to answer this, but note that you can likely vary the voltage of your square wave to control the current and eliminate most of the resistance, making it more efficient. Other than that,
all I can gather is that you want to produce a loud noise(relative to what?) electronically, and judging by the 555 timer inclusion, you likely want to be able to vary the frequency or tone. You're using a transistor. Nothing wrong with that but you could get a better switch if you want to. If you want maximum volume, experimentation is definitely the way to go over calculation for a simple speaker circuit. Personally I'd do a 2 stage pulse modulator, 1 stage to regulate the voltage from 5v down to 0v and use this to control volume to a level you find optimal, then check what voltage did that and use that voltage instead of 5v. You could use a benchtop variable power supply to do the same if you have one. Then make your current circuit and 555 the second stage. Eliminates the resistor and makes it a bit more efficient. However, assuming you run 158ma RMS across roughly 32 ohms, that's roughly .8W, which is kind of wasteful, especially if you're getting your 5V off of something like a linear regulator, but might not matter on the scale of a car or boat, and is only being wasted when the device is on, which may be almost never. Note that even if you want 5v circuit logic, you can still use that to switch a lower voltage.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why are there so many files in the Silverlight Bin when I build my project?
There's just so many files. The XAP file, DLL file, HTML file, PDB File, and then I have all these folders with 2 letter words where inside each folders are 2 dll files.
What do these files (in general) represent?
Thanks
A:
The XAP file represents the Silverlight application (Silverlight Application Package, the X likely refers to the XAML base of Silverlight).
DLL files are your application's dependencies, some of which are created to facilitate serialization and localization.
Because Silverlight is browser-hosted, it requires an HTML page to host the control when you debug it.
The PDB file contains the "program database" which includes all the metadata Visual Studio uses to provide those nice descriptive tooltips when you mouse over a variable in the IDE.
Folders with two letters represent country codes and are used for localization.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why does the EM algorithm have to be iterative?
Suppose that you have a population with $N$ units, each with a random variable $X_i \sim \text{Poisson}(\lambda)$. You observe $n = N-n_0$ values for any unit for which $X_i > 0$. We want an estimate of $\lambda$.
There are method of moments and conditional maximum likelihood ways of getting the answer, but I wanted to try the EM algorithm. I get the EM algorithm to be
$$
Q\left(\lambda_{-1}, \lambda\right) = \lambda \left(n + \frac{n}{\text{exp}(\lambda_{-1}) - 1}\right) + \log(\lambda)\sum_{i=1}^n{x_i} + K,
$$
where the $-1$ subscript indicates the value from the previous iteration of the algorithm and $K$ is constant with respect to the parameters. (I actually think that the $n$ in the fraction in parentheses should be $n+1$, but that doesn't seem accurate; a question for another time).
To make this concrete, suppose that $n=10$, $\sum{x_i} = 20$. Of course, $N$ and $n_0$ are unobserved and $\lambda$ is to be estimated.
When I iterate the following function, plugging in the previous iteration's maximum value, I reach the correct answer (verified by CML, MOM, and a simple simulation):
EmFunc <- function(lambda, lambda0){
-lambda * (10 + 10 / (exp(lambda0) - 1)) + 20 * log(lambda)
}
lambda0 <- 2
lambda <- 1
while(abs(lambda - lambda0) > 0.0001){
lambda0 <- lambda
iter <- optimize(EmFunc, lambda0 = lambda0, c(0,4), maximum = TRUE)
lambda <- iter$maximum
}
> iter
$maximum
[1] 1.593573
$objective
[1] -10.68045
But this is a simple problem; let's just maximize without iterating:
MaxFunc <- function(lambda){
-lambda * (10 + 10 / (exp(lambda) - 1)) + 20 * log(lambda)
}
optimize(MaxFunc, c(0,4), maximum = TRUE)
$maximum
[1] 2.393027
$objective
[1] -8.884968
The value of the function is higher than in the un-iterative procedure and the result is inconsistent with the other methodologies. Why is the second procedure giving a different and (I presume) incorrect answer?
A:
When you've found your objective function for the EM algorithm I assume you treated the number of units with $x_i=0$, which I'll call $y$, as your latent parameter. In this case, I'm (again) assuming $Q$ represents a reduced form of the expected value over $y$ of the likelihood given $\lambda_{-1}$. This is not the same as the full likelihood, because that $\lambda_{-1}$ is treadted as given.
Therefore you cannot use $Q$ for the full likelihood, as it this does not contain information about how changing $\lambda$ changes the distribution of $y$ (and you want to select the most likely values of $y$ as well when you maximize the full likelihood). This is why the full maximum likelihood for the zero truncated Poisson differs from your $Q$ function, and why you get a different (and incorrect) answer when you maximize $f(\lambda)=Q(\lambda,\lambda)$.
Numerically, maximizing $f(\lambda)$ will necessarily result in an objective function at least as large as your EM result, and probably larger as there is no guarantee that the EM algorithm will converge to a maximum of $f$ - it's only supposed to converge to a maximum of the likelihood function!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why comparing Timestamp and date in Firebird result in weird value?
I'm comparing some dates and times and found that I do not understand Firebird Date Literals and their conversions as I thought so.
Please, see this query:
SELECT
iif('2016-01-25' <= '2016-01-25', 1, 0) AS TSCASE,
iif('2016-01-25 00:00:00.000' <= '2016-01-25', 1, 0) AS TSCASE1,
iif('2016-01-25 00:00:00.000' <= cast('2016-01-25' as timestamp), 1, 0) AS TSCASE2,
iif(cast('2016-01-25 00:00:00.000' as timestamp) <= '2016-01-25', 1, 0) AS TSCASE3,
iif('2016-01-25 00:00:00.000' <= '2016-01-25 00:00:00.000', 1, 0) AS TSCASE4,
iif('2016-01-25 00:00:00.000' <= '2016-01-25 23:59:59.999', 1, 0) AS TSCASE5,
iif('2016-01-25 00:00:00.000' <= '2016-01-25 23:59:59.999', 1, 0) AS TSCASE6,
iif('2016-01-25 00:00:00.000' <= cast('2016-01-25 23:59:59.999' as timestamp), 1, 0) AS TSCASE7
FROM RDB$DATABASE
I'm expecting that every column result was 1. But this is the result:
TSCASE TSCASE1 TSCASE2 TSCASE3 TSCASE4 TSCASE5 TSCASE6 TSCASE7
1 0 1 1 1 1 0 1
So why '2016-01-25 00:00:00.000' <= '2016-01-25' is false but, when I do any cast to TIMESTAMP, is true?
Also why '2016-01-25 00:00:00.000' <= '2016-01-25 23:59:59.999' and '2016-01-25 00:00:00.000' <= cast('2016-01-25 23:59:59.999' as timestamp) are true, but '2016-01-25 00:00:00.000' <= '2016-01-25 23:59:59.999' is false?
Please note the extra space between the date and time in these last two expressions. I did think that the extra space would not change the result as you can see in this quote also from the first link:
White Space in Date Literals
Spaces or tabs can appear between elements. A date part must be separated from a time part by at least one space.
A:
The problem is that you are not comparing timestamps and dates in most of your expressions. Instead you are comparing string (CHAR) literals.
To answer your specific inquiries:
'2016-01-25 00:00:00.000' <= '2016-01-25' is false because in string sorting 2016-01-25 comes before 2016-01-25 00:00:00.000
'2016-01-25 00:00:00.000' <= '2016-01-25 23:59:59.999' is false because 2016-01-25 23:59:59.999 has a second space before the time part, and in string sorting a space comes before a 0.
To use date or timestamp literals, you either need to explicitly prefix the string literal with DATE or TIMESTAMP, or you need to use a cast, otherwise it is just a string. Change your query to the one below and you do get your expected values:
SELECT
iif(DATE'2016-01-25' <= DATE'2016-01-25', 1, 0) AS TSCASE,
iif(TIMESTAMP'2016-01-25 00:00:00.000' <= DATE'2016-01-25', 1, 0) AS TSCASE1,
iif(TIMESTAMP'2016-01-25 00:00:00.000' <= cast('2016-01-25' as timestamp), 1, 0) AS TSCASE2,
iif(cast('2016-01-25 00:00:00.000' as timestamp) <= DATE'2016-01-25', 1, 0) AS TSCASE3,
iif(TIMESTAMP'2016-01-25 00:00:00.000' <= TIMESTAMP'2016-01-25 00:00:00.000', 1, 0) AS TSCASE4,
iif(TIMESTAMP'2016-01-25 00:00:00.000' <= TIMESTAMP'2016-01-25 23:59:59.999', 1, 0) AS TSCASE5,
iif(TIMESTAMP'2016-01-25 00:00:00.000' <= TIMESTAMP'2016-01-25 23:59:59.999', 1, 0) AS TSCASE6,
iif(TIMESTAMP'2016-01-25 00:00:00.000' <= cast('2016-01-25 23:59:59.999' as timestamp), 1, 0) AS TSCASE7
FROM RDB$DATABASE
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Почему программа на Java работает неправильно?
Я написал простенькую программу, которая должна просить ввести 1 символ, пока не будет введена точка. Если точка введена, то отображается количество нажатий Enter (то есть количество попыток для того, чтобы угадать символ). Если пользователь вводит "q", то программа завершает свою работу.
import java.util.Scanner;
class Main {
public static void main(String args[])
throws java.io.IOException {
Scanner scanner = new Scanner(System.in);
char choice;
int count = 0;
do {
System.out.print("Введите любой символ: ");
choice = scanner.next().charAt(0);
System.out.println();
count++;
} while (choice != '.' && choice != 'q');
switch(choice) {
case '.':
System.out.println("Вы нажали Enter " + count + " раз.");
break;
case 'q':
break;
}
}
}
При выполнении программа работает неправильно, запрашивая по три раза ввод символа. До сих пор не могу понять в чем дело.
C:\Users\Alex\Desktop\Projects\Point>java Point
Введите любой символ: f
Введите любой символ:
Введите любой символ:
Введите любой символ: h
Введите любой символ:
Введите любой символ:
Введите любой символ: k
Введите любой символ:
Введите любой символ:
Введите любой символ: .
Вы нажали Enter 10 раз.
C:\Users\Alex\Desktop\Projects\Point>
A:
Всё корректно у меня работает. Перезагрузите компьютер, нажмите Build ->Rebuild project. Вот лог:
Введите любой символ: h
Введите любой символ: h
Введите любой символ: d
Введите любой символ: j
Введите любой символ: t
Введите любой символ: r
Введите любой символ: e
Введите любой символ: y
Введите любой символ: r
Попробуйте онлайн компилятор java
|
{
"pile_set_name": "StackExchange"
}
|
Q:
JavaScript can't reach the weather API
I just want to code a simple weather app for learning JS. I can't find the mistake after searching the whole web...
I don't get any information from the API. I checked this in the browser console.
I just want to show the current weather conditions from LA.
window.addEventListener("load", () => {
let temperatureDescription = document.querySelector(".temperature-description");
let temperatureDegree = document.querySelector(".temperature-degree");
let locationTimezone = document.querySelector(".location-timezone");
const proxy = "https://cors-anywhere.herokuapp.com/";
const api = '${proxy}https://api.darksky.net/forecast/4d5ddfbfc8eabb0dddcb9e78fb408a99/37.8267,-122.4233';
fetch(api)
.then(response => {
return response.json();
})
.then(data => {
console.log(data);
const {
temperature,
summary
} = data.currently;
temperatureDegree.textContent = temperature;
temperatureDescription.textContent = summary;
locationTimezone.textContent = data.timezone;
});
});
A:
Just from a quick overview it seems like you're using the wrong quotation marks.
Try putting your API variable into `` instead of ''.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
CSS: Padding issue. Need help please
I'm experiencing a strange CSS spacing issue in Chrome (but not in Firefox and/or IE)
My site is here.
The vertical spacing in Firefox between the "Real Estate Search" (H2 tag) and the form input field for "San Francisco, CA" (#city-field input tag) is perfect, but in Chrome, Chrome is applying more/extra vertical spacing than desired.
To help, I've attached a screenshot. The redline represent the extra spacing that Chrome is adding that Firefox/IE are not.
Any ideas why Chrome is apply more spacing than Firefox & IE.
And how to fix this issue.
Thanks in advance
UPDATE
I'm also using a "reset stylesheet" to standardize across all browsers the H2 spacing, etc. It can be found in my linked HTML document above yet still am experiencing this issue.
A:
I'm thinking that the line-height is the culprit. Try setting the line height of the h2 to somewhere around 13 to 15 pixels. By default it is set to normal. According to W3C, line-height: normal "Tells user agents to set the used value to a "reasonable" value based on the font of the element." Firefox and Chrome could be setting different "reasonable" values since they are built on entirely different rendering engines.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there a way to manually open the Recovered Documents Pane in Word 2013
Every reference that I've looked at suggests forcing a crash, and then re-opening word. This seem like an kludgey way of resolving the issue, and was hoping there was a manual way to force open the Recovery Pane, or some kind of plugin I can download to simulate the process.
A:
Since no one seems to actually understand your question, I will take a stab at it.
If I understand your problem correctly, you open Excel and the Document Recovery task pane appears with a list of files for you to view. You click on a file, review it for errors, save and/or close the file depending on whether you found errors, etc, and then go back to the task pane to open the next file.
But wait...it's gone! Slightly confused about why that panel would disappear after clicking on only one file in the list, you search around on the File menu and all the other tabs, frustrated that you can't find the stupid panel again. So you close Excel and restart it, hoping the panel appears again. And it does! You quickly realize, though, that since you have something like 20 files to review, closing and re-opening Excel after each file is beyond annoying.
I had this problem, too. It's unbelievably annoying. Who the hell thought that was a good idea??
tl;dr
Anyway, I found the answer by accident. Next time you have this panel open and you click on a file, when you are finished but before you close the document, look at the bottom left corner of the window. You should see the word "Ready" and then "Recovered". Click on the word "Recovered" to reopen the task pane. Next, write an angry note to Microsoft via the Feedback button. Because this is just asinine.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
realloc: invalid checksum for freed object
I have an error using realloc to replace malloc.
This code below runs OK on my computer.
int vector_grow(Vector* vec) {
unsigned long newcap;
int * newarr;
if (0 == vec->cap) {
vec->arr = (int*)malloc(START_CAPACITY * sizeof(*vec->arr));
if (NULL == vec->arr)
return -1;
vec->cap = START_CAPACITY;
return 0;
}
newarr = malloc (newcap * sizeof(*vec->arr));
if (NULL == newarr)
return -1;
memcpy (newarr, vec->arr, vec->len * sizeof(*vec->arr));
free (vec->arr);
vec->arr = newarr;
vec->cap = newcap;
return 0;
}
I want to change the malloc to realloc, but the error occurs.
int vector_grow(Vector* vec) {
unsigned long newcap;
if (0 == vec->cap) {
vec->arr = (int*)malloc(START_CAPACITY * sizeof(*vec->arr));
if (NULL == vec->arr)
return -1;
vec->cap = START_CAPACITY;
return 0;
}
newcap = 2 * vec->cap;
if ((vec->arr = (int*)realloc(vec->arr, newcap * sizeof(int))) == NULL)
return -1;
return 0;
}
It says
malloc: *** error for object 0x7fca64c02598: incorrect checksum for freed object - object was probably modified after being freed.
I don't know any difference between those two snippets of code, if you know what causes the error, please tell me! Thank you very much!
A:
Bug in missing vec->cap = in updated code certainly contribute to various calls to malloc() and calling code's misuse of data.
int vector_grow(Vector* vec) {
unsigned long newcap;
if (0 == vec->cap) {
... // not important to show the bug
}
newcap = 2 * vec->cap;
if ((vec->arr = (int*)realloc(vec->arr, newcap * sizeof(int))) == NULL)
return -1;
// Add missing update
vec->cap = newcap;
return 0;
}
Also better to test for allocation success
void *p = realloc(vec->arr, sizeof *(vec->arr) * newcap);
if (p == NULL) {
return -1;
}
vec->arr = p;
vec->cap = newcap;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Given $A\in M_{6} (\mathbb{Q})$ and $f(x)=2x^9+x^8+5x^3+x+a$, for what values of $a$ is $f(A)$ invertible?
Let $A \in \mathbb{Q}^{6 \times 6}$ be the block matrix below:
$$A=\left(\begin{array}{rrrr|rr}
-3 &3 &2 &2 & 0 & 0\\
-1 &0 &1 &1 & 0 & 0\\
-1&0 &0 &1 & 0 & 0\\
-4&6 &4 &3 & 0 & 0\\
\hline
0 & 0 & 0 & 0 & 0 &1 \\
0 & 0 & 0 & 0 & -9 &6
\end{array}\right).$$
I found out that the minimal polynomial of $A$ is $(x-3)^3(x+1)^2$, and now let
$$f(x)=2x^9+x^8+5x^3+x+a$$
a polynomial, $a\in N$. I need to find out for which $a$ the matrix $f(A)$ is invertible.
It has some similarity to to my last question, but I still can't understand and solve it. Thanks again.
A:
Expanding on the comment:
If $A$ has eigenvalue $\lambda$, then $f(A)$ has eigenvalue $f(\lambda)$. So $f(A)$ is not invertible if $f(\lambda)=0$.
A:
Theorem. Let $V$ be a finite $\mathbb{K}$-vector space and let $f \in \mathrm{End}(V)$ an endomorphism with minimal polynomial $m_f(t) \in \mathbb{K}[t]$. If $a(t) \in \mathbb{K}[t]$, then $a(f) \in \mathrm{GL}(V)$ if and only if $\gcd(a,m_f)=1$.
Proof. $\Leftarrow$) Since Bezout's identity, $1 = \lambda m_f + \mu a$ for some polynomials $\lambda, \mu$. So, evaluating in $f$, one has $\mathrm{id}_V = \mu(f) \circ a(f)$, that proves that $a(f)$ is invertible.
$\Rightarrow$) Let $d$ the greatest common divisor between $a$ and $m_f$. One has $a = \tilde{a} d$ for a polynomial $\tilde{a}$, then $a(f) = \tilde{a}(f) \circ d(f)$, so $\ker d(f) \subseteq \ker a(f)$. But $a(f)$ is invertible, so also $d(f)$ is invertible. One has $m_f = \tilde{m} d$, so $0 = \tilde{m}(f) \circ d(f)$; but $d(f)$ is invertible, so $\tilde{m}(f) = 0$. But $m_f$ is the minimal polynomial, so $m_f = \tilde{m}$ and then $d = 1$. $\square$
A:
Put $A$ in Jordan form. The diagonal is made of $3$s and $-1$s. In this vector basis, $f(A)$ is also upper triangular and its diagonal is made of $f(3)$s and $f(-1)$s. Hence $f(A)$ is invertible if and only if there is no zero on the diagonal of its Jordan form if and only if $f(3)$ and $f(-1)$ are nonzero (and this condition is equivalent to the fact that the gcd of $f$ and the minimal polynomial of $A$ is $1$).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Python return deque from outside thread
So I am making this program and I would like to get a list value from a thread outside of the thread. With the queue module I can get a value, but not a list. Deque seems to do what I want, but only works if the deque is being read inside another thread. What I got so far:
from collections import deque
import datetime
values = deque()
def addValues(values):
while True:
found = 1
now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
values.append((found,now))
time.sleep(5)
t1 = threading.Thread(target=addValues, args=(values,))
t1.start()
while True:
print(values)
time.sleep(5)
At the moment it just prints an empty deque. I want it to print the deque with the added values
EDIT: Nevermind, I asked the wrong question. The whole thread should be in a Flask site. when I at return to the while True, than it doesn't return anything. Sorry, I will make another question for this
A:
Works for me:
deque([(1, '2018-01-30 14:38:22')])
deque([(1, '2018-01-30 14:38:22'), (1, '2018-01-30 14:38:27')])
deque([(1, '2018-01-30 14:38:22'), (1, '2018-01-30 14:38:27'), (1, '2018-01-30 14:38:32')])
Python 3.6.3
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Coding DRY how to combine common functionality in these two objects?
DRY - Don't Repeat Yourself
ControlSignUp and ControSignIn are nearly identical. I've commented a "here" on the only 4 lines which are different. How can I combine this common functionality?
Actually it seem obvious..I can just pass in a single variable through the constructor...just a sec.
Answer:
/**
* ControlSign
*/
var ControlSign = function( type )
{
var form_element = document.getElementById( type );
var response_element = document.getElementById( type + '_response' );
var text_object = new Text( form_element );
var message_object = new Message( response_element );
this.invoke = function( )
{
if( Global.validate_input_on === 1 )
{
if( !text_object.checkEmpty() )
{
message_object.display( 'empty' );
return false;
}
if( type === 'signup' && !text_object.checkPattern( 'name' ) )
{
message_object.display( 'name' );
return false;
}
if( !text_object.checkPattern( 'email' ) )
{
message_object.display( 'email' );
return false;
}
if( !text_object.checkPattern( 'pass' ) )
{
message_object.display( 'pass' );
return false;
}
}
AjaxNew.repeatUse( ajaxSerialize( form_element ) + '&ajax_type=' + type + '_control', function( server_response_text ) { ajaxType( server_response_text, response_element, 'respond' ); } );
}
};
ControlSign.in = function()
{
new ControlSignIn( 'signin' ).invoke();
};
ControlSign.up = function()
{
new ControlSignUp( 'signup' ).invoke();
};
A:
Simple solution: Make it a function ControlSign with a parameter, invoked with "in" or "up". You could call this "factory pattern".
Complex solution: you use a factory function to create the two constructors. OK, what I meant is the use of a closure to create constructors:
function makeControlSign(type) {
function constructor(...) {
this.invoke = function(){...};
// use the variable "type" where needed
...
}
constructor[type] = function(){...};
return constructor;
}
var ControlSignUp = makeControlSign("up");
var ControlSignIn = makeControlSign("in");
I guess this should neither be called "factory pattern" nor "abstract factory pattern".
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Evaluating $\int_{0}^{1} \frac{x^{2} + 1}{x^{4} + 1 } \ dx$
How do I evaluate $$\int_{0}^{1} \frac{x^{2} + 1}{x^{4} + 1 } \ dx$$
I tried using substitution but I am getting stuck. If there was $x^3$ term in the numerator, then this would have been easy, but this one doesn't.
A:
Hints:
Try dividing the numerator and denominator by $x^{2}$.
Then you get $\displaystyle \int\frac{1 + \frac{1}{x^2}}{x^{2}+\frac{1}{x^2}} \ dx$.
Write $\displaystyle x^{2} +\frac{1}{x^2}$ as $\displaystyle \biggl(x-\frac{1}{x}\biggr)^{2} + 2$
A:
Another way, if you want to sweat harder instead of the elegant suggestion of Chandrasekhar:$$x^4+1=(x^2+\sqrt{2}\,x+1)(x^2-\sqrt{2}\,x+1)\Longrightarrow$$$$ \frac{x^2+1}{x^4+1}=1-\frac{\sqrt 2\,x}{x^2+\sqrt 2\,x+1}+1+\frac{\sqrt 2\,x}{x^2-\sqrt 2\,x+1}$$ so for example$$\int\frac{\sqrt 2\,x}{x^2+\sqrt 2\,x+1}dx=\frac{1}{\sqrt 2}\int\frac{2x+\sqrt 2}{x^2+\sqrt 2\,x+1}dx-\frac{1}{2\sqrt 2}\int\frac{\sqrt 2dx}{(\sqrt 2 x+1)^2+1}=$$$$=\frac{1}{\sqrt 2}\log|x^2+\sqrt 2\,x+1|-\frac{1}{2\sqrt 2}\arctan(\sqrt 2\,x+1)+C$$ and etc.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
lmer function in R-understading the formula structure in lmer4
I am a novice. I wonder, like the formula
lmer(extro~1+open+social, data)
or
lmer(extro~open+social+(1+agree|school),data)
or
glm(extro ~ open + agree + social + school*class - 1, data)
what is the meaning of 1 playing as the predictor variable?
A:
1 indicates an intercept. By default, intercepts are always present, so 1 + doesn't actually add anything, but it can make it explicit that an intercept is being estimated, which can be useful for clarity. - 1 signals that an intercept should not be estimated. Another way to do this is 0 +.
In lmer(), when including random effects, including 1 is sometimes necessary but always useful. (1|school) means you want to estimate a random intercept that varies by school. (1 + open|school) means you want to estimate a random intercept and a random slope for open. Another way to write this is (open|school) because the intercept is implicit. This is bad practice because it's ambiguous whether a random intercept is being requested, whereas when including 1 + it is explicit. It's possible to estimate models with a fixed intercept but a random slope; to do this, you could include (open - 1|school).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Solving dual problem by Conjugate Gradients
So, today I've encountered the article and there was the speed of convergence of CG compared for primal and dual problem.
The point is, up today I've only briefly heard about "primal" and "dual" problems and I'm not even very experienced generally in optimizations.
So, could you, please, help me to understand this with some simple example?
My attempt
Let's try to use the example from Wikipedia:
We want to solve following problem:
$$
A\textbf{x}
=
\begin{bmatrix}
4 & 1\\
1 & 3
\end{bmatrix}
\textbf{x}
=
\begin{bmatrix}
1 \\
2
\end{bmatrix}
=
\textbf{b}\\
x_*
=
\begin{bmatrix}
\frac{1}{11}\\
\frac{7}{11}
\end{bmatrix}
$$
Matrix $A$ is symmetrical and positive-definite, so we know, that the solution is the minimum of the quadratic form. And so we can solve this system by finding its minimum with CG.
$x_*$ is the analytical solution of the system.
I presume, that the primal problem is the minimization of the quadratic function given by my system of equations,so it's something like this:
$$
f(x) = \frac{1}{2}\textbf{x}^TA\textbf{x} - \textbf{x}^T\textbf{b}\\
x_* = \inf\limits_{x} f(x)
$$
Could you, please, show me, how can I deduce and solve dual problem from this?
A:
You need at least one constraint to derive the dual. Let's use the Cholesky decomposition of $A$ to write the problem as:
$$\inf_x \frac{1}{2}x^TU^TUx - x^Tb$$
The constraint can now be introduced by taking $y=Ux$:
$$\inf_{x,y} \left\{ \frac{1}{2}y^Ty - x^Tb : Ux=y\right\}$$
The dual is typically derived via the Lagrangian:
$$L(x,y,z) = \frac{1}{2}y^Ty - x^Tb + z^T(Ux-y) \}$$
The dual is now:
$$\sup_z \inf_{x,y} L(x,z)$$
To find $\inf_{x,y} L(x,z)$, set the derivatives to zero to obtain $-b+U^Tz = 0$ and $y-z=0$. The dual is therefore:
$$\sup_z \left\{ -\frac{1}{2} z^T z : U^T z = b \right\}$$
The dual problem is a constrained problem and can therefore not be solved with "pure" CG. However, there are "projected" CG algorithms that can cope with linear equality constraints, see, e.g., https://www.math.uwaterloo.ca/~tfcolema/articles/Linearly%20Constrained%20Optimization%20and%20Projected%20Preconditioned%20Conjugate%20Gradients.pdf
Note that the solution to the unconstrained problem $\sup_y -\frac{1}{2}y^Ty$ solves $-y=0$, so you really need a projected CG to make any sense of this.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Installing instiki on Windows
I am attempting to install instiki on Windows 7 and am hitting a roadblock.
I have the following installed:
Ruby 1.9.2
Rails 2.3.4
SQLite 3
Latest Development Kit
I ran the bundler and all gems were installed. When I run the *.bat file I get the following error:
ruby.exe script\server -e production
:29:in
require': no such file to load --
script/../config/boot (LoadError)
from <internal:lib/rubygems/custom_require>:29:in
require'
from script/server:2:in 'main'
A:
AFAIK, Instiki has not been updated to work with Ruby 1.9.2
I would recommend downgrade to Ruby 1.8.7 and try again.
You can find installers for it at RubyInstaller website.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Notation of a set which contains all numbers of an interval
How to denote that a set $S$ contains all the numbers of a discrete interval interval $I$?
For example: be $I = [0, 3]$, thus $S = \{ 0, 1, 2, 3 \}$.
The best I came up with is $S = \{ \min(I), ..., \max(I) \}$, but I think $\min/\max$ are pretty non-standard for this.
A:
The usual notation for $\{a,a+1,\dots, b\}$ is $[[a,b]]$, although it's not really all that common and I almost always have to explain what it is in real life.
In your particular case you may want to use $S=I\cap \mathbb Z$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Catch "applied coupon" event to trigger a JS function in Woocommerce
In Woocommerce, is there any way trigger JS after applied coupon like this?
I would like to use it in something like this:
$( document.body ).on( 'updated_cart_totals', function(){
//do something
});
Any help is appreciated.
A:
You can use applied_coupon delegated event like in this example that will display an alert box with the applied coupon code (where the variable coupon is the applied coupon code):
<script type="text/javascript">
jQuery(function($){
$( "body" ).on( 'applied_coupon', function(event, coupon){
// Example: Displaying an alert message with the applied coupon code
alert('Applied coupon code: "' + coupon + '"\n' + 'Event type: "' + event.type + '"');
});
});
</script>
Tested and works.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Concurrent open TCP connections in WCF service
We have a WCF service with multiple TCP endpoints. I am interested in monitoring the total number of concurrent open connections at any given time. Are there any perfmon counters that will allow us to do this out of the box? Note that number of instances != number of connections in our case.
A:
If you prefer to use PerfMon, have a look at these performance counters.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
why angular-datatables plugin buttons doesn't work
I am using angular-datatables from the following resource: http://l-lin.github.io/angular-datatables/#/welcome
I am trying to run the example of 'with buttons' from here:
http://l-lin.github.io/angular-datatables/#/withButtons
I am doing everything exactly like in the example but apparently I don't see any buttons on the table and I should see them.
Any clue why it is acting like this.
Update:
I can see only custom button without excel or pdf button.I still have a problem not all buttons are presented.
My code is here:
[http://codepen.io/Barak/pen/aNPZgN][3]
[http://codepen.io/Barak/pen/aNPZgN][3]
A:
Try to include buttons.html5.js, buttons.flash.js to your html.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Get declared values in function in PHP
This is about RAW php coding. I have a page - "config.php" and there are some declarations here.
//config.php
<?php
$myvalue = "This is a test";
include("functions.php");
?>
//functions.php
<?php
function testFunction()
{
$dd = $myvalue;
echo $dd;
}
?>
And when I call "testFunction()" from another page like "page.php" I want it to echo "This is a test". How can I do this? "config.php" is included to "page.php". Hope the scenario is understandable.
//page.php
<?php
include('config.php');
testFunction();
?>
A:
In the first line of your function, add:
global $myvalue;
Your $myvalue-variable is transfered into functions.php when you include that php-file after declaring the variable, but you have to tell your function to use this global variable.
Your function would look like this:
function testFunction()
{
global $myvalue;
$dd = $myvalue;
echo $dd;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Determining whether a file struct (Describing a file descriptor) is a 'special file' (i.e. block/character device)
I have modified the system-call table such that my own mmap handler will be called upon a user-space call to mmap.
My handler calls the original mmap and according to the result chooses what to do.
Here's a very short code snippet:
asmlinkage unsigned long my_mmap_handler(unsigned long addr,
unsigned long len,
int prot,
int flags,
int fd,
long off)
{
unsigned long ret_val = old_mmap(addr,len,prot,flags,fd,off);
if (IS_ERR((void*)ret_val))
goto end;
// Do some stuff..
end:
return ret_val;
}
while in "Do some stuff" I do some operations on the actual mapped file (i.e. reading from the file).
Here's the problem:
I have encountered programs that try to mmap character/block devices (e.g. /dev/rdi/card0). Whenever I try to read (e.g. using vfs_read) from such a file, the kernel freezes (Not a panic, but it feels like something is blocking). Why exactly does that happen?
Anyway, I don't need to perform operations on character/block devices so I've been trying to find a way of finding out if a given 'struct file' represents a block/character device and in case it is just ignore it. No luck so far.
Help would be appreciated
A:
Solved it using the preprocessor macro:
#define special_file(m) (S_ISCHR(m)||S_ISBLK(m)||S_ISFIFO(m)||S_ISSOCK(m))
defined in linux/fs.h
The macro can be then used as follows to determine whether a file pointer 'describes' a special file:
struct file * f;
// ...
if (special_file(file_inode(f)->i_mode))
{
/* If we're here then it is a
block/character device or FIFO/SOCKET file */
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What does -1 in numpy reshape mean?
I have a numpy array (A) of shape = (100000, 28, 28)
I reshape it using A.reshape(-1, 28x28)
This is very common use in Machine learning pipelines.
How does this work ? I have never understood the meaning of '-1' in reshape.
An exact question is this
But no solid explanation. Any answers pls ?
A:
in numpy, creating a matrix of 100X100 items is like this:
import numpy as np
x = np.ndarray((100, 100))
x.shape # outputs: (100, 100)
numpy internally stores all these 10000 items in an array of 10000 items regardless of the shape of this object, this allows us to change the shape of this array into any dimensions as long as the number of items on the array does not change
for example, reshaping our object to 10X1000 is ok as we keep the 10000 items:
x = x.reshape(10, 1000)
reshaping to 10X2000 wont work as we does not have enough items on the list
x.reshape(10, 2000)
ValueError: total size of new array must be unchanged
so back to the -1 question, what it does is the notation for unknown dimension, meaning:
let numpy fill the missing dimension with the correct value so my array remain with the same number of items.
so this:
x = x.reshape(10, 1000)
is equivalent to this:
x = x.reshape(10, -1)
internally what numpy does is just calculating 10000 / 10 to get the missing dimension.
-1 can even be on the start of the array or in the middle.
the above two examples are equivalent to this:
x = x.reshape(-1, 1000)
if we will try to mark two dimensions as unknown, numpy will raise an exception as it cannot know what we are meaning as there are more than one way to reshape the array.
x = x.reshape(-1, -1)
ValueError: can only specify one unknown dimension
A:
It means, that the size of the dimension, for which you passed -1, is being inferred. Thus,
A.reshape(-1, 28*28)
means, "reshape A so that its second dimension has a size of 28*28 and calculate the correct size of the first dimension".
See documentation of reshape.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Notepad++ TextFX to escape a regular string for regular expression
In Notepad++ TextFX, is there a feature that can escape all reserved characters in a given string? Thanks.
A:
No, there is not such a tool in the TextFX package that comes with Notepad++.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
zend gdata api showing white screen :(
I am using byethost for my project..
I am trying to install zend gdata on the server..
I copied all the file to server to "root/ladert/Zend/library"
I tried running the zend installation checker.. but it gives white screen.. NO output( even in view source)
So I tried error show on by runnning php script with "ini_set('display_errors', 'on');" .....since I don have php ini access I tried that.
But still all what I get is white screen..
what am I doing wrong ?
A:
@kavisiegel yes I tried that..
@charles thanks..
I finally found that the problem is with my hosting provider... They'll hopefully fix it soon... :)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
when should we have Portlet-class to have an predefined class and a custom class
This is my Portlet.xml inside the existing project .
Could anybody please tell me when should we have Portlet-class to have an predefined class and a custom class ??
<portlet>
<portlet-name>DataUpload</portlet-name>
<display-name>DataUpload</display-name>
<portlet-class>org.apache.struts2.portlet.dispatcher.Jsr168Dispatcher</portlet-class>
<init-param>
<name>viewNamespace</name>
<value>/view</value>
</init-param>
</portlet>
<portlet>
<portlet-name>Reports</portlet-name>
<display-name>Reports</display-name>
<portlet-class>com.tata.ReportAction</portlet-class>
</portlet>
A:
This is an ample question and hard to answer in its full sense. However, there are some rules that are almost always followed:
If your portlet does use some Java framework (like Struts 2, JSF) it will almost certainly use a predefined javax.portlet.GenericPortlet subclass. All the processing is made by the framework and the portlet class has the sole purpose of redirecting the requests to the framework. This kind of portlet class is called bridge. In your example, your bridge is org.apache.struts2.portlet.dispatcher.Jsr168Dispatcher.
If your portlet does use the Liferay MVC portlet and only show retrieved data in JSPs (without updating them), then you may not need to write your custom portlet class. You may not need another class because the com.liferay.util.bridges.mvc .MVCPortlet class does present JSPs automatically. I will not explain it in detail, but that is the point. This is a rare situation, so do not think much about it.
If your portlet does not use Liferay MVC but instead is written in plain JSR 286 API, then you will probably need to write your custom portlet class. It is because the default render(), doView() etc. methods of GenericPortlet are not enough to present JSPs.
If your portlet does not use any Java generic framework, uses Liferay MVC and does process data by updating it, then you will probably need some custom subclass of MVCPortlet. This is so because the processing of data is made by methods called during the action phase. These methods (usually called "process action methods") are recognized by having two parameters of the types javax.portlet .ActionRequest and javax.portlet .ActionResponse.
In your example, you have two portlets: one which uses Struts (so the portlet class just dispatches requests to Struts 2) and another one which uses a custom portlet class. This portlet class can either extend GenericPortlet or MVCPortlet. If it uses GenericPortlet, then it is inevitable to have a custom class. If it does use MVCPortlet, then this class probably has some process action methods.
I bet my answer is way too abstract, but I hope it gives you some ideas about other questions, more specific and answerable.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Async task can't update GUI
My basic question is how do you update the GUI with AsyncTask. I am setting a String in onPostExecute that the GUI thread references. Using logging, I can see the String getting set in the onPostExecute method, but it never gets set on my GUI under my onClickListener to update the GUI. Any help is appreciated.
Main Program:
public class Main extends Activity {
/** Called when the activity is first created. */
Arduino.ToAndroid.Temperature.GetJSON jsonHttpClass = new Arduino.ToAndroid.Temperature.GetJSON();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new GetJSON().execute(url_to_Http);
}
View.OnClickListener temperatureListener = new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// buttonTemperature = json.getTemp();
tempView.setText(jsonHttpClass.value);
Log.i("ROSS LOG", "Button Clicked");
}
}; }
Async Task:
class GetJSON extends AsyncTask {
public String value;
@Override
protected String doInBackground(String... url) {
String result = this.getHttpJson(url[0]);
return result;
}
@Override
protected void onPostExecute(String result) {
value = new String(result);
Log.i("ROSS LOG", value);
}
}
A:
In onCreate(), you should be using the handle for the already created object of the AsyncTask and not create a new object.
Use
jsonHttpClass.execute(url_to_Http);
instead of
new GetJSON().execute(url_to_Http);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to set adaptive constraints the right way
I'm building an app and I want it to work on every iPhone and iPad.
How do I do to make adaptive constraints that change for each device?
I know you can do something to detect the screen size and adapt the constraints, how do I do that? Is there an easy and clear tutorial?
A:
First of all constraints are depended on your project.when you can start project you take the view and add the 4 constant 0,0,0,0.After this if you can add multiple item in the page,you take the particular view for the particular item.If you take the particular view it can be easy for the set constraints.Very most important thing that you complete the design of your page and after create design you can set the constraints.It's can be easy way to set the constraints.Another most important thing is you can create your project in the small device like iphone-SE and after set constraints and run in medium device like iphone-6,7,8 and in the last run your program in big device like iphone-X,XSmax.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
MIPS Floating Point Error
I'm attempting to figure out what exactly is going wrong with my code below.
Quick background: The idea of this program is to calculate the Batting Average and Slugging Percentage based upon the amount of Singles, Doubles, Triples, Homeruns and Outs performed by a player. One of the test cases I am running against the code has the values for these being astronomical, and whenever I attempt any sort of addition with them, the code fails. I realize that I need to use double-point floats (particularly when adding Outs and Hits, which should end up with the number 31,500,032 but instead stores 26,207,920), but I'm not at all sure how to go about working with my code to do so. Any suggestions?
# test with three batters, both average and slugging percentage
# First batter has no hits, but does have outs
# Second batter has hits and outs, with realistic values
# Third hitter has large values for some of the hits and for the
# outs. This means the hits and outs *have* to be converted from int's
# to float's in order to get the right answer.
.data
mainNumBatters:
.word 3
mainBatter1:
.word 0, 0, 0, 15, 0 # player with no atBats
mainBatter2:
.word 101 # singles
.word 22 # doubles
.word 4 # triples
.word 423 # outs
.word 10 # home runs
mainBatter3:
.word 8000000 # singles
.word 22 # doubles
.word 500000 # triples
.word 23000000 # outs
.word 10 # home runs
mainNewline:
.asciiz "\n"
mainBatterNumber:
.asciiz "Batter number: "
mainBattingAverage:
.asciiz "Batting average: "
mainSluggingPercentage:
.asciiz "Slugging percentage: "
.text
main:
# Function prologue -- even main has one
subu $sp, $sp, 24 # allocate stack space -- default of 24 here
sw $fp, 0($sp) # save frame pointer of caller
sw $ra, 4($sp) # save return address
addiu $fp, $sp, 20 # setup frame pointer of main
# for (i = 0; i < mainNumBatters; i++)
# compute batting average
# compute slugging average
la $s0, mainNumBatters
lw $s7, 0($s0) # $s7 = number of batters
addi $s6, $zero, 0 # $s6 = i = 0
la $s0, mainBatter1 # $s0 = addr of current batter's stats
mainLoopBegin:
slt $t0, $s6, $s7 # $t0 = i < number of batters
beq $t0, $zero, mainDone
la $a0, mainBatterNumber
addi $v0, $zero, 4
syscall
addi $a0, $s6, 1
addi $v0, $zero, 1
syscall
la $a0, mainNewline
addi $v0, $zero, 4
syscall
lw $a1, 0($s0) # $a1 = singles
lw $a2, 4($s0) # $a2 = doubles
lw $a3, 8($s0) # $a3 = triples
lw $s5, 16($s0) # $s5 = home runs
lw $s4, 12($s0) # $s4 = outs
sw $s4, -4($sp) # put outs at top of average's stack
sw $s5, -8($sp) # put homeruns 2nd fm top of average's stack
addi $a0, $zero, 1 # $a0 = 1 = compute batting average
jal average
# Print the average
mtc1 $v0, $f12 # get result fm $v0 before we print string
la $a0, mainBattingAverage
addi $v0, $zero, 4
syscall
addi $v0, $zero, 2 # print the average
syscall
la $a0, mainNewline
addi $v0, $zero, 4
syscall
syscall
# do it again for the slugging percentage
lw $a1, 0($s0) # $a1 = singles
lw $a2, 4($s0) # $a2 = doubles
lw $a3, 8($s0) # $a3 = triples
lw $s5, 16($s0) # $s5 = home runs
lw $s4, 12($s0) # $s4 = outs
sw $s4, -4($sp) # put outs at top of average's stack
sw $s5, -8($sp) # put homeruns 2nd fm top of average's stack
addi $a0, $zero, 2 # $a0 = 1 = compute batting average
jal average
# Print the slugging percentage
mtc1 $v0, $f12 # get result fm $v0 before we print string
la $a0, mainSluggingPercentage
addi $v0, $zero, 4
syscall
addi $v0, $zero, 2 # print the average
syscall
la $a0, mainNewline
addi $v0, $zero, 4
syscall
syscall
addi $s6, $s6, 1 # i++
addi $s0, $s0, 20 # $s0 = addr of next batter's stats
j mainLoopBegin
mainDone:
# Epilogue for main -- restore stack & frame pointers and return
lw $ra, 4($sp) # get return address from stack
lw $fp, 0($sp) # restore frame pointer for caller
addiu $sp, $sp, 24 # restore frame pointer for caller
jr $ra # return to caller
.data
printHitsOuts:
.asciiz "Outs: "
printHitsSingles:
.asciiz "Singles: "
printHitsDoubles:
.asciiz "Doubles: "
printHitsTriples:
.asciiz "Triples: "
printHitsHomeruns:
.asciiz "Homeruns: "
printHitsNewline:
.asciiz "\n"
.text
printHits:
# Function prologue
addiu $sp, $sp, -28 # allocate stack space
sw $fp, 0($sp) # save frame pointer of caller
sw $ra, 4($sp) # save return address
sw $a0, 8($sp) # save $a0 thru $a3
sw $a1, 12($sp)
sw $a2, 16($sp)
sw $a3, 20($sp)
addiu $fp, $sp, 24 # setup frame pointer of average
# print the outs
la $a0, printHitsOuts
addi $v0, $zero, 4
syscall
lw $a0, 24($sp) # the outs are at the top of our stack
addi $v0, $zero, 1
syscall
la $a0, printHitsNewline
addi $v0, $zero, 4
syscall
# print the singles
la $a0, printHitsSingles
addi $v0, $zero, 4
syscall
lw $a0, 8($sp)
addi $v0, $zero, 1
syscall
la $a0, printHitsNewline
addi $v0, $zero, 4
syscall
# print the doubles
la $a0, printHitsDoubles
addi $v0, $zero, 4
syscall
addi $a0, $a1, 0
addi $v0, $zero, 1
syscall
la $a0, printHitsNewline
addi $v0, $zero, 4
syscall
# print the triples
la $a0, printHitsTriples
addi $v0, $zero, 4
syscall
addi $a0, $a2, 0
addi $v0, $zero, 1
syscall
la $a0, printHitsNewline
addi $v0, $zero, 4
syscall
# print the homeruns
la $a0, printHitsHomeruns
addi $v0, $zero, 4
syscall
addi $a0, $a3, 0
addi $v0, $zero, 1
syscall
la $a0, printHitsNewline
addi $v0, $zero, 4
syscall
printHitsDone:
# Epilogue for average -- restore stack & frame pointers and return
lw $ra, 4($sp) # get return address from stack
lw $fp, 0($sp) # restore frame pointer for caller
addiu $sp, $sp, 28 # restore frame pointer for caller
jr $ra # return to caller
# Your code goes below this line
# $s1 = Homeruns = $f6
# Outs = $f8
# atBats = $f10
# $a1 = Singles = $f12
# $a2 = Doubles = $f14
# $a3 = Triples = $f16
# $f20 = Slugging Percentage (Not Divided)
# $f18 = Hits
# $f2 = Batting Average
average:
# Function prologue
addiu $sp, $sp, -56 # allocate stack space
sw $fp, 0($sp) # save frame pointer of caller
sw $ra, 4($sp) # save return address
sw $a0, 8($sp) # 1 or 2 ; 1, batting average ; 2, slugging percentage
sw $a1, 12($sp) # Number of Singles
sw $a2, 16($sp) # Number of Doubles
sw $a3, 20($sp) # Number of Triples
addiu $fp, $sp, 24 # setup frame pointer of average
sw $s0, 28($sp)
sw $s1, 32($sp)
sw $s2, 36($sp)
sw $s3, 40($sp)
sw $s4, 44($sp)
# Grab Outs and Homeruns from Top of Main stack
lw $s0, 52($sp) # Number of Outs
lw $s1, 48($sp) # Number of Homeruns
# Convert Everything to Floating
mtc1 $s1, $f6 # $f6 = Homeruns
mtc1 $s0, $f8 # $f8 = Outs
mtc1 $a1, $f12 # $f12 = Singles
mtc1 $a2, $f14 # $f14 = Doubles
mtc1 $a3, $f16 # $f16 = Triples
# Calculate Hits ($f18)
add.s $f18, $f12, $f14 # Add Singles and Doubles
add.s $f18, $f18, $f16 # Add Triples
add.s $f18, $f18, $f6 # Add Homeruns
#Calculate atBats ($f10)
add.s $f10, $f8, $f18 # Add Outs and Hits
#Check if Batting or Slugging is to be computed
add $s4, $zero, $zero
addi $s4, $s4, 2
beq $s4, $a0, averageSlugging
averageBatting:
#Skip when atBats = 0
mfc1 $s3, $f10
beqz $s3, averageFinish
#Calculate Batting Average ($f4)
div.s $f4, $f18, $f10 # Divide Hits by atBats
j averageFinish
averageSlugging:
#Skip when atBats = 0
mfc1 $s3, $f10
beqz $s3, averageFinish
#Calculate Slugging Average ($f0)
add.s $f20, $f12, $f14 # $f20 = Singles + Doubles
add.s $f20, $f20, $f14 # $f20 = Singles + Doubles*2
add.s $f20, $f20, $f16 # $f20 = Singles + Doubles*2 + Triples
add.s $f20, $f20, $f16 # $f20 = Singles + Doubles*2 + Triples*2
add.s $f20, $f20, $f16 # $f20 = Singles + Doubles*2 + Triples*3
add.s $f20, $f20, $f6 # $f20 = Singles + Doubles*2 + Triples*3 + Homeruns
add.s $f20, $f20, $f6 # $f20 = Singles + Doubles*2 + Triples*3 + Homeruns*2
add.s $f20, $f20, $f6 # $f20 = Singles + Doubles*2 + Triples*3 + Homeruns*3
add.s $f20, $f20, $f6 # $f20 = Singles + Doubles*2 + Triples*3 + Homeruns*4
div.s $f4, $f20, $f10 # Divide Hits by atBats
averageFinish:
#Call printHits
add $a0, $a1, $zero # $a0 = Singles
add $a1, $a2, $zero # $a1 = Doubles
add $a2, $a3, $zero # $a2 = Triples
add $a3, $s1, $zero # $a3 = Homeruns
sw $s0, -4($sp) # Outs at the top of printHits Stack
jal printHits
#Prepare for Return
mfc1 $v0, $f4
mtc1 $zero, $f4 # $f4 = 0
# Epilogue for average -- restore stack & frame pointers and return
lw $ra, 4($sp) # get return address from stack
lw $fp, 0($sp) # restore frame pointer for caller
lw $a0, 8($sp) # 1 or 2 ; 1, batting average ; 2, slugging percentage
lw $a1, 12($sp) # Number of Singles
lw $a2, 16($sp) # Number of Doubles
lw $a3, 20($sp) # Number of Triples
lw $s0, 28($sp)
lw $s1, 32($sp)
lw $s2, 36($sp)
lw $s3, 40($sp)
lw $s4, 44($sp)
addiu $sp, $sp, 56 # restore frame pointer for caller
jr $ra # return to caller
A:
Your problem is that you are mixing integer and floating point arithmetics.
Your input numbers are represented as integers.
Then you put them into floating point registers and operate with them. However you did not convert them to floating point representation.
For small numbers the addition and division works fine (you only add or divide the mantissas). However, when the numbers involved in any arithmetic operation differ in their exponent the operation will yield wrong results.
What you should do is convert the integer representation of your numbers to a floating point representation before performing floating point operations.
In MIPS this is done with the cvt.s.w instruction.
So basically, you have to add one of this conversions after each mtc1 you have issued:
# Convert Everything to Floating
mtc1 $s1, $f6 # $f6 = Homeruns
cvt.s.w $f6, $f6 # (convert to floating point)
mtc1 $s0, $f8 # $f8 = Outs
cvt.s.w $f8, $f8
mtc1 $a1, $f12 # $f12 = Singles
cvt.s.w $f12, $f12
mtc1 $a2, $f14 # $f14 = Doubles
cvt.s.w $f14, $f14
mtc1 $a3, $f16 # $f16 = Triples
cvt.s.w $f16, $f16
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Jquery width and height of body
I have the following jquery code to check for the window dimensions. Unfortunately it seems to only pick up the width - the height is returning as zero. Where am I going wrong?
$(document).ready(function() {
var $window = $('body');
function checkSize() {
var windowWidth = $window.width();
var windowHeight = $window.height();
if (windowWidth < 765) {
$('#index_right').hide();
$('.btn').removeClass("btn-large");
}
else if (windowWidth < 880) {
$('#index_right').hide();
$('.btn').addClass("btn-large");
}
else
{
$('#index_right').fadeIn(1000);
$('.btn').addClass("btn-large");
}
if (windowHeight < 3000) {
//alert(windowHeight);
$('#index_base').hide();
}
else
{
$('#index_base').fadeIn(1000);
}
}
checkSize();
$(window).resize(checkSize);
});
A:
Try using jquery's built in height method instead:
$(window).height();
|
{
"pile_set_name": "StackExchange"
}
|
Q:
set "the following user or group can join to a domain" after creating the computer
I have come across an issue where a user can create a computer in AD, nobody else can join the computer to the domain except for the user who created it in AD.
When creating the computer in admin tools there is an option titled "the following user or group can join to a domain" if this is set to a certain group then that group can join to the domain.
When I look at the properties of a computer in the admin tools I cannot find this setting anywhere.
Where do I find this setting? Can this setting be changed using a script?
A:
This isn't really a setting, but rather permissions. What the wizard does, is assigning the required permissions required to join a computer to that computer-object on the object for the user/group that you specified.
Usually what people do is adding a user to a ADgroup which has the required permissions to join computers; permissions being assigned on a parent container of the computers with inheritance enabled.
If you need to make only THAT person be able to join THAT computer, you would need to script it. Ex:
Create a computer-object and choose a specific user in the wizard.
Use ADSI or Powershell etc. to export the ACLs created for the specified user on that computer object
Create a script that assigns the same permissions for a specified user on a specified computer.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
In PHP using slim I can not route to URL /loveshared
A very weird question.
I can not setup a route in slim to use the URL /loveshared
$app->get('/loveshared', function() use ($app) {
echo "hello";
});
If I navigate in my browser to localhost/loveshared, I get a 404. I also get this 404 message when I push to my server.
I did a Find in Files... in the top direction of my project for the string loveshared. The only place it found the string was in my router file.
I also went through and did:
/l, /lo, /lov, /love, /loves.../loveshared All the routes work, up until loveshared. I also did /sharedlove and /stuffshared and they both worked.
Can anyone else confirm that /loveshared does not work with slim as a route?
A:
Ok, I downloaded a fresh copy of Slim 2.2.0, placed it as-is on my personal site (PHP 5.3.13) running on Linux duhr 2.6.32.8 in shared host environment (Dreamhost). Then I created a file, t.php, and pasted the following into it:
<?php
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app->get('/loveshared', function () use ($app) {
echo "<p>This is a test of the loveshared controller label in the URL of a Slim project.</p>";
});
$app->run();
http://jfcoder.com/slim/t.php/loveshared
And it runs as expected. There's either some kind of environment cause (rogue or misconfigured .htaccess file?), or something. You would need to recreate it in some way to be able to triangulate and find the problem.
Have you tried what I have done and see if it still causes the problem you're describing?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
jQuery ajax unable retrieve json
So here is the ajax call that is making the problem
$.ajax({
type: "POST",
url: "src/login.php",
dataType: "JSON",
data: {username: usr, password: pwd},
success: function(json){
loggedStatus=json.status;
alert(json.status);
}
});
It is succesfully passing the variables to the php file, but it isn't entering th success: part.
This is example of what the php file returns
{
"status": "Wrong"
}
or
{
"status": "154414707fe8d22bb6239648ce11a9c9bede1a3e"
}
Which is totaly fine.
A:
Try putting the url as the first parameter in your $.ajax({ function.
because the syntax is: $.ajax(url[, options])
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Questionnaire program using many wxPython windows
I have over 300 questions that I plan to include in the program. The flow is pretty much like this:
Create a window with the question
Store answer in variable
Create NEW window with question
Store NEW answer
(This continues on for over 300 questions.)
I have 2 questions:
Will this eventually lead to a crash since I'm creating so many windows?
Everything works with this code if you select 'Yes' to the second question (A2) but it does not work if you select 'No'. Can you please see if you can find what's wrong with it?
import wx
a1 = ['Apples', 'Bananas', 'Strawberries', 'Watermelon',
"Don't remember", 'None of the above']
a2 = ['No', 'Yes']
a4 = ['No', 'Yes']
class Fruit(wx.Frame):
def __init__(self, parent, id):
wx.Frame.__init__(self, parent, id, 'Fruit', size=(300,200))
#create panel and button
panel = wx.Panel(self)
# B1 - create multiple choice list
box = wx.MultiChoiceDialog(None, """
A1. What kind of fruit did you buy at the store?""", 'Fruit', a1)
if box.ShowModal() == wx.ID_OK:
a_1 = box.GetSelections()
print (a_1, '\n')
# A2 - create single choice list
box = wx.SingleChoiceDialog(None, """
A2. Do you like eating fruit?
""", 'Fruit', a2)
if box.ShowModal() == wx.ID_OK:
a_2 = box.GetStringSelection()
print (a_2, '\n')
if a_2 == 'Yes':
box = wx.TextEntryDialog(None, "A3. What kind of fruit is your favorite? ", "Fruit", "")
if box.ShowModal() == wx.ID_OK:
a_3 = box.GetValue()
print (a_3, '\n')
box = wx.SingleChoiceDialog(None, """
A4. Did you eat the fruit that you bought?
""", 'Fruit', a4)
if box.ShowModal() == wx.ID_OK:
a_4 = box.GetStringSelection()
print (a_4, '\n')
A:
import wx
a1 = ['Apples', 'Bananas', 'Strawberries', 'Watermelon',
"Don't remember", 'None of the above']
a2 = ['No', 'Yes']
a4 = ['No', 'Yes']
The Python style guide recommend ALL_CAPS for global constants.
class Fruit(wx.Frame):
def __init__(self, parent, id):
wx.Frame.__init__(self, parent, id, 'Fruit', size=(300,200))
#create panel and button
panel = wx.Panel(self)
# B1 - create multiple choice list
box = wx.MultiChoiceDialog(None, """
A1. What kind of fruit did you buy at the store?""", 'Fruit', a1)
When strings get long enough that they force breaking across multiple lines, its usually best to move them to global constants
if box.ShowModal() == wx.ID_OK:
a_1 = box.GetSelections()
print (a_1, '\n')
I don't think this does what you think it does. For python 2.x (which unless wxPython has been ported to python 3.x recently, must be what you are using), you shouldn't put parenthesis around your print statements.
# A2 - create single choice list
box = wx.SingleChoiceDialog(None, """
A2. Do you like eating fruit?
""", 'Fruit', a2)
if box.ShowModal() == wx.ID_OK:
a_2 = box.GetStringSelection()
print (a_2, '\n')
if a_2 == 'Yes':
box = wx.TextEntryDialog(None, "A3. What kind of fruit is your favorite? ", "Fruit", "")
if box.ShowModal() == wx.ID_OK:
If the answer to the previous question was "Yes", then box is now the result of asking question A3. However, otherwise its the still the previous question. As a result, it'll ask the same question again. You probably want to indent this if block so that it only happens if a_2 was Yes.
a_3 = box.GetValue()
print (a_3, '\n')
box = wx.SingleChoiceDialog(None, """
A4. Did you eat the fruit that you bought?
""", 'Fruit', a4)
if box.ShowModal() == wx.ID_OK:
a_4 = box.GetStringSelection()
print (a_4, '\n')
As for your questions:
You can probably get away with creating that many windows. However, you can make sure that a dialog gets destroyed by calling its Destroy() method.
I explained above what was wrong with your logic.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to force a user to select an option, using frames, excel userform
I have 4 frames on my userform.
Frames 1, 2, and 4 have two option buttons.
Frame 3 has 5 options buttons.
What I want to do, is that when the command button is selected, that if an option button in a frame has not been selected, a message will appear.
I would like to have a custom message for each frame.
I have made a start, but really struggling to get to grips with the different frames... can someone point me in the right direction? (Still very beginner and trying to learn, so if all replies could be dumbed-down, that would be great!! :D )
(I have pulled this code from an example, so it might not be the best approach to my problem...)
Dim ThisControl As Control
For Each ThisControl In UserForm2.Frame1.Controls
If TypeName(ThisControl) = "OptionButton" And _
ThisControl.Value = True Then
Unload Me
End If
Next ThisControl
MsgBox "Please Select an Option", vbCritical, "Select Opton"
A:
Try the following:
If Me.[ControlName].Value = False And Me.[ControlName].Value = False Then
MsgBox "[Message]", vbExclamation, "[Message Box Name]"
Exit Sub
End If
Do the same for each frame, replacing [ControlName] with the control's name and replacing [Message] and [Message Box Name] with the custom message you want.
For frame 3, you will need to include an additional 3 'And' statements.
A:
Probably not the most eligant solution, but it works fine. Cycles through each frame (you will need to update frame names to match yours [Name, not caption!]), then makes sure at least one option is set, else shows a message. Adapt as needed
Private Sub CommandButton1_Click()
For Each ctrl In Frame1.Controls
If TypeOf ctrl Is msforms.OptionButton Then
If ctrl.Value = True Then
F1D = True
Exit For
End If
End If
Next ctrl
If F1D = False Then
MsgBox "No Option Selected In Frame 1"
End If
For Each ctrl In Frame2.Controls
If TypeOf ctrl Is msforms.OptionButton Then
If ctrl.Value = True Then
F2D = True
Exit For
End If
End If
Next ctrl
If F2D = False Then
MsgBox "No Option Selected In Frame 2"
End If
For Each ctrl In Frame3.Controls
If TypeOf ctrl Is msforms.OptionButton Then
If ctrl.Value = True Then
F3D = True
Exit For
End If
End If
Next ctrl
If F3D = False Then
MsgBox "No Option Selected In Frame 3"
End If
For Each ctrl In Frame4.Controls
If TypeOf ctrl Is msforms.OptionButton Then
If ctrl.Value = True Then
F4D = True
Exit For
End If
End If
Next ctrl
If F4D = False Then
MsgBox "No Option Selected In Frame 4"
End If
End Sub
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Scaling a GIF hosting site
My friend runs a popular Youtube-to-GIF conversion site. Right now, he has converted 250,000 Youtube videos to GIFs (each video gets 6 thumbnails for 1.5m total GIF files) and serves about 80TB of bandwidth per month.
His server is IO blocking -- I'm not a guru admin, but it seems to be the harddrive seek time for non-sequential GIFs that's clogging everything up. He has a server with 100tb.com for $300/mo, and it comes with 100TB free bandwidth. At first, I advised him to get a CDN to solve his problems, because then the GIFs get served without consuming his server resources, and his main box could just handle the encoding -- We found one CDN for $600/mo that was too slow/unreliable, and the rest wanted at least $2000/mo for 80TB of bandwidth. We're trying to keep the whole project under $900/mo, right now.
So the cheapest bandwidth we can find is with 100TB, but we're outgrowing one server. We could add another server, but I don't really know how to partition the GIF storage so that the load is distributed evenly between two boxes. Our host recommended using software like Aflexi.net, but I'm sure there must be a cheaper solution.
Can anyone help? I'm a programmer by trade, not a sysadmin, but trying to learn the ropes. Thanks!
A:
S3 is no alternative, the bill for 80 TByte will be over 8k$ alone per month.
It looks like you serve the GIFs right out of the filesystem. Why don't you put all the GIFs on 2 machines, use a hash-algorithm mapping the name to one of the 2 machines and deliver them this way? This would easily scale to more machines as long as your loadbalancer holds up…
|
{
"pile_set_name": "StackExchange"
}
|
Q:
prototyping bool functions, undefined Foo
I have wery little code:
// prototype
bool Foo();
int main( ... )
{
if( Foo() == false )
return 1;
return 0;
}
bool Foo()
{
return true;
}
What is wrong with this? The compiler (VS 2010) shows a lot of syntax error with ")" and ";" and im not doing it right with my prototype?
A:
I think your problem is that bool is not defined.
It depends how your compiler is set but bool is a type that is frequently not supported without defining it yourself or including it.
I found this :
http://msdn.microsoft.com/en-us/library/tf4dy80a.aspx
Cheers
Jason
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.