source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0001084627.txt" ]
Q: EntityManager throws TransactionRequiredException on merge() in JBoss JSF bean I've set up a JSF application on JBoss 5.0.1GA to present a list of Users in a table and allow deleting of individual users via a button next to each user. When deleteUser is called, the call is passed to a UserDAOBean which gets an EntityManager injected from JBoss. I'm using the code public void delete(E entity) { em.remove(em.merge(entity)); } to delete the user (code was c&p from a JPA tutorial). Just calling em.remove(entity) has no effect and still causes the same exception. When this line is reached, I'm getting a TransactionRequiredException: (skipping apparently irrelevant stacktrace-stuff) ... 20:38:06,406 ERROR [[Faces Servlet]] Servlet.service() for servlet Faces Servlet threw exception javax.persistence.TransactionRequiredException: EntityManager must be access within a transaction at org.jboss.jpa.deployment.ManagedEntityManagerFactory.verifyInTx(ManagedEntityManagerFactory.java:155) at org.jboss.jpa.tx.TransactionScopedEntityManager.merge(TransactionScopedEntityManager.java:192) at at.fhj.itm.utils.DAOImplTemplate.delete(DAOImplTemplate.java:54) at at.fhj.itm.UserBean.delete(UserBean.java:53) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ... I already tried to wrap a manually managed transaction (em.getTransaction().begin() + .commit() ) around it, but this failed because it is not allowed within JBoss container. I had no success with UserTransaction either. Searches on the web for this issue also turned up no similar case and solution. Has anyone experienced something similar before and found a solution to this? A: Found the missing link. It was indeed a missing transaction but the solution was not to use the EntityManager to handle it but to add an injected UserTransaction. @Resource UserTransaction ut; ... public void delete(E entity) { ut.begin(); em.remove(em.merge(entity)); ut.commit(); } Thanks to all suggestions which somehow over 100 corners lead to this solution.
[ "stackoverflow", "0011417168.txt" ]
Q: Sort records by time inserted How can I query data in the order it was created? I don't have a date-created field in this table. A: If you don't have a field storing the time of insertion, or any other meta-data regarding the order of insertion, there is no reliable way to get this information. You could maybe depend on a clustered index key, but these are not guaranteed. Neither are IDENTITY fields or other auto-generated fields. To clarify, an IDENTITY field does auto-increment, but... You can insert explicit values with IDENTITY_INSERT You can reseed and start reusing values There is no built-in enforcement of uniqueness for an identity field If the ID field is your PK, you can probably use that to get a rough idea: SELECT * FROM MyTable ORDER BY IdField ASC Per your comment, the field is a GUID. In that case, there is no way to return any sort of reliable order since GUIDs are inherently random and non-sequential.
[ "stackoverflow", "0011387493.txt" ]
Q: Draw an arc based on 2 Points and radius I'm trying to draw an Arc2D object inside a panel. however I'm not sure how to calculate it. What I have given is starting Point2D and an end Point2D and a radius. The problem is that when the radius changes, the startAngle and AngleExtent parameters are different every time. another problem is that since the radius changes, the center of the 'to-be' circle containing the arc is in a different point every time, another parameter which changes based on input, so I can't use (or don't know how) to use setCenter() method. Any help is appreciated! A: Two points and a radius define two arcs (in 2D). You can find their center points by calculating the intersection (java.awt.geom.Area.intersects) of the two Circles of radius r centered at your two points. The center point of the arcs' circles will be the points on the perimeter of that area halfway between your two initial points.
[ "ru.stackoverflow", "0001094641.txt" ]
Q: Как сверстать такой список? VUE.JS Во front-end я новичок. Подскажите, как сверстать данную таблицу? Не знаю как реализовать такую логику. Данные падают извне в виде массива объектов. Один объект соответствует одной строке таблицы. P.S. На две кнопки справа вверху не обращайте внимания, просто эта таблица является выпадающей при клике на элемент другой таблицы. upd: немного не так выразился. Сверстать то я сверстал. Я просто не могу понять как реализовать настраиваемое отображение этой таблицы по средствам vue. upd2: попросили код верстки. Вот кусок html без стилей. Целиком кидать код нет смысла, компонент очень большой, кода много. Эта таблица лишь небольшой фрагмент. <div class="panel2"> <!--Верхняя часть, с кнопками--> <div class="panel__filter d-flex align-items-center justify-content-between"> <div class="p__filter"> <span style="margin: 0px 15px;">Отображать по</span> <input type="text" class="count__input" v-model="count" style="margin-right: 58px"> <span style="margin-right: 10px;">Страница</span> </div> <div class="d-flex justify-content-end" style="width: 50%"> <button class="panel__btn" style="max-width: 350px; margin-right: 10px;">Изменить данные исполнителя</button> <button class="panel__btn" style="max-width: 262px; margin-right: 32px;">Удалить исполнителя</button> </div> </div> <!--Шапка таблицы, средняя часть--> <div class="panel__table__header"> <ul class="d-flex align-items-center" style="height: inherit"> <li class="ul__elem">Дата</li> <li class="ul__elem">Адрес</li> <li class="ul__elem">Статус</li> <li class="ul__elem">CRM</li> <li class="ul__elem">Отчет</li> </ul> </div> <!--Контентая часть таблицы--> <div class="panel__table"> <div class="table__element" v-for="requests in requestList"> <ul class="d-flex align-items-center" style="height: inherit"> <li class="ul__elem">{{ request.data }}</li> <li class="ul__elem">{{ request.address }}</li> <li class="ul__elem">{{ request.status }}</li> <li class="ul__elem"><a :href="request.crm">Ссылка</a></li> <li class="ul__elem"> <a href="#">Отчет</a></li> </ul> </div> </div> </div> A: Если я вас правильно понял, вам нужно что-то такое? Возможно я навелосипедил тут с вотчером. new Vue({ el: "#app", data: { rows: [ { date: "1", adress: "Адрес 1", status: "Выполнена", Crm_title: "qwer", Crm_link: "127.0.0.1/crm1", report_link: "127.0.0.1/report1" }, { date: "2", adress: "Адрес 1", status: "Принята", Crm_title: "qwer", Crm_link: "127.0.0.1/crm2", report_link: "127.0.0.1/report2" }, { date: "3", adress: "Адрес 1", status: "Принята", Crm_title: "qwer", Crm_link: "127.0.0.1/crm3", report_link: "127.0.0.1/report3" }, { date: "4", adress: "Адрес 1", status: "Принята", Crm_title: "qwer", Crm_link: "127.0.0.1/crm3", report_link: "127.0.0.1/report3" }, { date: "5", adress: "Адрес 1", status: "Принята", Crm_title: "qwer", Crm_link: "127.0.0.1/crm3", report_link: "127.0.0.1/report3" }, { date: "6", adress: "Адрес 1", status: "Принята", Crm_title: "qwer", Crm_link: "127.0.0.1/crm3", report_link: "127.0.0.1/report3" }, { date: "7", adress: "Адрес 1", status: "Принята", Crm_title: "qwer", Crm_link: "127.0.0.1/crm3", report_link: "127.0.0.1/report3" }, { date: "8", adress: "Адрес 1", status: "Принята", Crm_title: "qwer", Crm_link: "127.0.0.1/crm3", report_link: "127.0.0.1/report3" }, { date: "9", adress: "Адрес 1", status: "Принята", Crm_title: "qwer", Crm_link: "127.0.0.1/crm3", report_link: "127.0.0.1/report3" }, { date: "10", adress: "Адрес 1", status: "Принята", Crm_title: "qwer", Crm_link: "127.0.0.1/crm3", report_link: "127.0.0.1/report3" }, { date: "11", adress: "Адрес 1", status: "Принята", Crm_title: "qwer", Crm_link: "127.0.0.1/crm3", report_link: "127.0.0.1/report3" }, { date: "12", adress: "Адрес 1", status: "Принята", Crm_title: "qwer", Crm_link: "127.0.0.1/crm3", report_link: "127.0.0.1/report3" }, ], count: 1, currentPage: 1 }, methods: { }, watch:{ // Чтобы текущая строка отображаемая в вершине страницы осталась, после изменения параметра "ОТОБРАЖАТЬ ПО" count: function (newval,oldval) { let pageInTopIndex = (this.currentPage - 1) * oldval + 1; this.currentPage = Math.ceil(pageInTopIndex / newval); }, }, computed:{ // Данные которые мы отображаем ( рассчитываются динамически, после изменения одного из параметров) paginationData(){ let start = (this.currentPage - 1) * this.count; let end = start*1 + this.count*1; return this.rows.slice(start, end); }, // количество страниц ( после изменения ОТОБРАЖАТЬ ПО, произойдет пересчет данной величины) countPage(){ return Math.ceil(this.rows.length / this.count); }, // Список с кнопочками paginationList(){ let list = []; list.push(this.currentPage - 1); // предыдущая list.push(this.currentPage); // текущая страница list.push(this.currentPage + 1); // следующая list = list .filter(num => num > 0) // оставляем страницы только больше 0 .filter( num => num <= this.countPage); // отсекаем страницы больше самой последней // возвращаем список return list; } } }) .tr > td{ width: 150px; } <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <div> Отображать по <input type="number" min="1" :max="rows.length" step="1" v-model="count"> <br> count = {{count}} <br> countPage = {{countPage}} <br> currentPage = {{currentPage}} </div> <div> <!--используем пересчитываемый динамически списко, для отображения кнопок--> <button v-for="asdf in paginationList" @click="currentPage = asdf" style="background-color: lightblue; margin-right: 10px" > {{asdf}} </button> </div> <div> <table> <tr class="tr" v-for="row in paginationData"> <td>{{row.date}}</td> <td>{{row.adress}}</td> <td>{{row.status}}</td> <td v-if="row.status === 'Выполнена'" >-</td> <td v-if="row.status !== 'Выполнена'" ><a :href="row.Crm_link">{{row.Crm_title}}</a></td> <td><a :href="row.report_link">Отчет</a></td> </tr> </table> </div> </div>
[ "math.stackexchange", "0003166202.txt" ]
Q: Is There a Binomial Theorem Equivalent for Permutations? I got to the following explicit formula for $\int_{}x^ne^xdx$: $$\int_{}x^ne^xdx = e^x\sum_{k=0}^{n}(-1)^kP(n,k)x^{n-k} + c$$ where n ∈ N, x ∈ R, $P(n,k) = \frac{n!}{(n-k)!}$ Now, the solution looks like the Binomial Theorem with $y = -1$: $$e^x\sum_{k=0}^{n}(-1)^k\binom{n}{k}x^{n-k} = e^x(x-1)^n$$ However, instead of the combination, we have a permutation, so I am wondering if there's a simplification like there would be if it were a combination instead. i.e. A simplification of the explicit formula of $\int_{}x^ne^xdx$ without the use of a summation. On WolframAlpha, after inputting $\int_{}x^ne^xdx$, the following is returned: $$\int{x^ne^x}dx = (-x)^{-n}x^n\Gamma(n+1,-x) +c$$ I suppose I should provide a derivation of the formula: $$\int{x^ne^xdx} = e^x\sum_{k=0}^{n}(-1)^kP(n,k)x^{n-k} + c$$ Clearly, this is an integration by parts problem by the following reduction formula: $$\int{x^ne^x}dx = x^ne^x -n\int{x^{n-1}e^xdx}$$ $n=1$: $\int{x^1e^xdx} = xe^x - e^x + c= e^x(x-1) + c$ $n=2$: $\int{x^2e^xdx} = x^2e^x - 2xe^x + 2e^x + c= e^x(x^2-2x+2) + c$ $n=3$: $\int{x^3e^xdx} = x^3e^x - 3x^2e^x + 6xe^x - 6e^x + c= e^x(x^3-3x^2+6x-6)+c$ $n=4$: $\int{x^3e^xdx} = ... = e^x(x^4-4x^3+12x^2-24x+24)+c$ $n=5$: $\int{x^3e^xdx} = ... = e^x(x^5-5x^4+20x^3-60x^2+120x-120)+c$ $$...$$ Looking at the polynomial factors: Now, collecting all the first terms, namely the $x^n$ coefficients, we get $1,1,1,1,1,...,1 = \binom{0}{0}$ Collecting all the second terms, namely the $x^{n-1}$ coefficients, we get $1,2,3,4,5,...,n = $ Collecting all the third terms, namely the $x^{n-2}$ coefficients, we get $2,6,12,20,...$ dividing this sequence by 2, we get $1,3,6,10,...$ [TRIANGULAR NUMBERS] (since we divided by 2, we need to multiply the triangular numbers by 2 = $2!$) Collecting all the fourth terms, namely the $x^{n-3}$ coefficients, we get $6,24,60,120,...$ dividing this sequence by 6, we get $1,4,10,20,...$ [TETRAHEDRAL NUMBERS] (since we divided by 6, we need to multiply the tetrahedral numbers by 6 = $3!$) Collecting all the fifth terms, namely the $x^{n-4}$ coefficients, we get $24,120,360,840,...$ dividing this sequence by 24, we get $1,5,15,35,...$ [PENTALOPE NUMBERS] (since we divided by 24, we need to multiply the tetrahedral numbers by 24 = $4!$) I hope the pattern is evident by now... Let me illustrate it for $n=5$: $$\int{x^5e^xdx} = e^x(\binom{0}{0}x^5-\binom{5}{1}x^4+2!\binom{5}{2}-3!\binom{5}{3}+4!\binom{5}{4}-5!\binom{5}{5}) + c$$ $$\int{x^5e^xdx}=e^x(x^5-5x^4+20x^3-60x^2+120x-120)+c$$ Following that, the formula becomes: $$\int{x^5e^xdx} = e^x\sum_{k=0}^{5}(-1)^{k}k!\binom{5}{k}x^{5-k}$$ $$\int{x^5e^xdx} = e^x\sum_{k=0}^{5}(-1)^{k}k!\frac{5!}{(5-k)!k!}x^{5-k}$$ $k!$ is thus cancelled out of the equation with the $k!$ in the combination denominator $$\int{x^5e^xdx} = e^x\sum_{k=0}^{5}(-1)^{k}\frac{5!}{(5-k)!}x^{5-k}$$ Finally, using $\frac{5!}{(5-k)!} = P(5,k)$, we get the final result: $$\int{x^5e^xdx} = e^x\sum_{k=0}^{5}(-1)^{k}P(5,k)x^{5-k}$$ Extended to a general $n$: $$\int_{}x^ne^xdx = e^x\sum_{k=0}^{n}(-1)^kP(n,k)x^{n-k} + c$$ where n ∈ N, x ∈ R, $P(n,k) = \frac{n!}{(n-k)!}$ End of derivation. TL;DR I have the following expression: $$e^x\sum_{k=0}^{n}(-1)^kP(n,k)x^{n-k}$$ where n ∈ N, x ∈ R, $P(n,k) = \frac{n!}{(n-k)!}$ and I want to know if there is a way to simplify the expression in a way similar to the binomial theorem (i.e. without the use of a sum): $$e^x\sum_{k=0}^{n}(-1)^k\binom{n}{k}x^{n-k} = e^x(x-1)^n$$ A: The expression can be written as \begin{align*} e^x\sum_{k=0}^{n}(-1)^kP(n,k)x^{n-k}&=e^x\sum_{k=0}^{n}(-1)^k\frac{n!}{(n-k)!}x^{n-k}\\ &=e^x\sum_{k=0}^{n}(-1)^{n-k}\frac{n!}{k!}x^{k}\tag{1}\\ &=(-1)^nn!e^x\color{blue}{\sum_{k=0}^n(-1)^k\frac{x^k}{k!}}\tag{2} \end{align*} with $$e^{-x}=\sum_{k=0}^\infty (-1)^k\frac{x^k}{k!}$$ So, in (2) the summands are the first $n+1$ terms of the Taylor series expansion at $x=0$ of $e^{-x}$ which do not admit a nice closed form. In (1) we changed the order of summation by $k\to n-k$.
[ "stackoverflow", "0032324876.txt" ]
Q: How to save an answer in a riddle game without creating a database? I've created a question and answer game with different levels, each level consisting a question. I didn't create it with a database. I just used string. When the user answers a question in level one he is taken to level two but when the user returns back to level one, he has to type the answer again even though he's solved it before. Is there anyway in JAVA to keep the answer in the type panel (if the user's solved it) without having to create a database?? Also, while typing in the type panel, the user has to delete the "Type here..." and then answer. Is there anyway that when user taps to type the "Type here..." is automatically erased? Here's my level one activity.xml: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/background" android:weightSum="1" android:textAlignment="center" android:id="@+id/level1"> <TextView android:layout_width="300dp" android:layout_height="200dp" android:text="What has 88 keys but cannot open a single door?" android:id="@+id/que1" android:width="255dp" android:textSize="30dp" android:layout_margin="50dp" android:textStyle="italic" android:gravity="center" /> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/type1" android:layout_gravity="center_horizontal" android:text="Type here..." /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Check answer..." android:id="@+id/check1" android:layout_gravity="center_horizontal" /> </LinearLayout> and here's my Oneactivity.java package com.golo.user.gaunkhanekatha; import android.app.Activity; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import android.os.Handler; public class OneActivity extends Activity { public SharedPreferences preferences; //ADDED THIS LINE public Button check; public EditText typeh; private Toast toast; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_one); toast = Toast.makeText(OneActivity.this, "", Toast.LENGTH_SHORT); check = (Button)findViewById(R.id.check1); //R.id.button is the id on your xml typeh = (EditText)findViewById(R.id.type1); //this is the EditText id check.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Perform action on click //Here you must get the text on your EditText String Answer = (String) typeh.getText().toString(); //here you have the text typed by the user //You can make an if statement to check if it's correct or not if(Answer.equals("Piano") || (Answer.equals("Keyboard"))) { preferences = PreferenceManager.getDefaultSharedPreferences(v.getContext()); SharedPreferences.Editor editor = preferences.edit(); editor.putInt("Level 1 question 1 ", 1); //Depends of the level he have passed. editor.apply(); ///Correct Toast toast.setText("Correct"); toast.setGravity(Gravity.TOP | Gravity.LEFT, 500, 300); toast.show(); Intent i = new Intent(OneActivity.this, TwoActivity.class); startActivity(i); finish(); } else{ //It's not the correct answer toast.setText("Wrong! Try again..."); toast.show(); } } }); } @Override protected void onDestroy() { super.onDestroy(); if(toast!= null) { toast.cancel(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_aboutus, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } Also, the toast is displayed where there's keyboard. Is there anyway to move the toast screen to somewhere on the screen where it is clearly visible? A: I'll give to you two methods to do it : Create a LevelEarned class as follows : public class LevelEarned { public static int level = 0; } Everytime you get an Intent (because user has answered the question correctly) just type : LevelEarned.level = 1; // 1 depends with the level you have answered correctly And the best method that it's that I'd use to this it's called SharedPreferences You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed). The first thing you have to do is store this data on SharedPreferences and you do it with an Editor as follows : SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(v.getContext()); SharedPreferences.Editor editor = preferences.edit(); editor.putInt("player_level",1); //Depends of the level he have passed. editor.apply(); NOTE I guess you will do it immediately when the user accepts the question so, you'll do it on a Button click so you'll have to pass as a context v.getContext() if you are not on a ButtonClick and you are on your onCreate() just call this to refer your context. To get the stored data (level) you'll need to do this : SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); int level = preferences.getInt("player_level", 0); Let's explain to you a little bit. The first parameter it's the key to find the SharedPreference so it won't change and the second one is a default value that it's used in case it doesn't find any "player_level" SharedPreferences. Hope it helps to you to keep going in your code :) EDIT2 Create SharedPreferences preferences as a global variable as follows : public SharedPreferences preferences; Then inside of your onClick() method add those lanes : check.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Perform action on click //Here you must get the text on your EditText String Answer = (String) typeh.getText().toString(); //here you have the text typed by the user //You can make an if statement to check if it's correct or not if(Answer.equals("4") || (Answer.equals("four"))) { preferences = PreferenceManager.getDefaultSharedPreferences(v.getContext()); SharedPreferences.Editor editor = preferences.edit(); editor.putInt("player_level",1); //Depends of the level he have passed. editor.apply(); //Create a Toast because it's correct Toast.makeText(OneActivity.this, "Correct!", Toast.LENGTH_LONG).show(); } else{ //It's not the correct answer Toast.makeText(OneActivity.this, "Wrong! Try Again", Toast.LENGTH_LONG).show(); } } }); And where you want to know the level you only will have to do : SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); int level = preferences.getInt("player_level", 0); //level is the current level of the player. EDIT 3 Create a class as follows : public static class LevelPlayer(){ public int static getLevelPlayer(){ SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); int level = preferences.getInt("player_level", 0); //level is the current level of the playe return level; } } And every time you want to ask the level of the player you do : int Level = LevelPlayer.getLevelPlayer(); //that's the level So after every question you can ask the level and put the next question. EDIT4 I've made some changes, delete your lvl class and put this code : public class lvl{ public Context mcontext; public lvl(Context context){ this.mcontext = context; } public int getLevelPlayer(){ SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mcontext); int level = preferences.getInt("player_level", 0); //level is the current level of the playe return level; } Then on your MainActivity(or wherever you have to know what's the level of the player) you have to put this : public levelplayer mlevelplayer; Then inside on your onCreate() add this : mlevelplayer = new levelplayer(this); int level = mlevelplayer.getLevelPlayer();
[ "math.stackexchange", "0001186140.txt" ]
Q: I am looking to understand vectors I am trying to learn intro calculus. I am wondering if this proof is correct for vector. If we have some vector function , r(t) and say that the length of this vector is a constant, say 1, then is it always the case we will have r'(t) being perpendicular to r(t)? To me this seems like it might me true, but I do not understand it geometrically. The proof I am writing I am also unsure if it is fully valid. Proof: I took the fact that $r(t) \bullet r(t)= ||r(t)||^{2}=c^{2}$ but I am not sure where to go exactly next. Im thinking I should use the derivative? My first time so hopefully the formatting came out well, I used the guide. A: Yes, that is so far a good start. And using the derivative is the right idea, you could write , because $c^{2}$ is also just a constant, $0=d/dt[r(t) \bullet r(t)] , = r'(t) \bullet r(t) + r(t) \bullet r'(t)= 2 r'(t) \bullet r(t)$ so you have the dot product is equal to 0, thus they are always orthogonal!
[ "stackoverflow", "0011402874.txt" ]
Q: What is the valid numerical range for Content-Range? Specifically, is this range legal? Content-Range: 0-1/12818084 A: The bytes-unit is missing. Here are the production rules for Content-Range: Content-Range = "Content-Range" ":" content-range-spec content-range-spec = byte-content-range-spec byte-content-range-spec = bytes-unit SP byte-range-resp-spec "/" ( instance-length | "*" ) byte-range-resp-spec = (first-byte-pos "-" last-byte-pos) | "*" instance-length = 1*DIGIT But with bytes as byte-unit it would be valid: bytes 0-1/12818084 0 is first-byte-pos 1 is last-byte-pos 12818084 is instance-length A: It should be: Content-Range: bytes 0-1/12818084 According to the RFC, this is legal. There is no minimum limit as long as in Content-Range: bytes a-b/c, a <= b, and c > b. Practical example: I was able to obtain a 2 byte partial response from mirrors.kernel.org (I checked that I could also get a 1 byte response):
[ "stackoverflow", "0040587182.txt" ]
Q: SQL query problems using CASE I have a database with 2 types of users, a user can either be an individual or organization which are children of the parent user user, reason I did this is because there are attributes an organization has that an individual do not have, unlike having single table where all the attributes for both users can be defined and having to have empty fields I decided to create a user table which has the common attributes between the two types of users, then there is a column which keeps the user type, so if its 1 then the user is an individual so I have to look in the individual table for all the other attributes vice versa, the individual and organization tables hold the user foreign key to have it identified here is a graphical representation of my database tables Incase you are wondering why I did not make one table, I plan on adding more attributes to both the user and organization tables as the app grows, am leaving room for expansion, so here is my problem, I want to get a user's data, I have their ID already, but how can I check the userType and point to the right table for the next set of attributes, for example if a user named John whose Id is 2 and is in the individual table how do I get their first and last name? my idea of the query is like: Select users.email, users.profilePhoto, users.userSince, CASE WHEN userType = 1 THEN SELECT individual.fname, individual.lname WHERE users.id = 1 AND individual.userFK = 1 END FROM users But am not familiar with the CASE statement so I always get an error, anyone who would like to help, you are most welcome. A: You are trying to build the dataset in the SELECT part, but the SELECT part is only for altering the output, not the input and not for building a dataset. The dataset is build using the WHERE statement in combination with crossselections with JOIN. Aggregation can be done using GROUP BY but you do not need this by now. SELECT u.*, i.*, o.* FROM users u LEFT JOIN individual i ON i.userFK = u.userFK LEFT JOIN organization o ON o.userFK = u.userFK
[ "stackoverflow", "0053348540.txt" ]
Q: Laravel Web Push notification using edujugon push-notification I have a problem in my project. I am using edujugon push-notification for push notification of my app, I created push notification to android, ios devices successfully with title, body. But when I integrate the notification in my web devices it does not show the title and body rather it shows the site is upgrated in backend. Also I want to set an url in my web notification. But dont know how. Here is my code public static function sendPushNotification($devices, $pushData, $partner = false) { $android = $devices->where('type', 2)->pluck('token')->all(); if (!empty($android)) { $push = new PushNotification('fcm'); $push->setMessage( [ 'data' => $pushData, ] ) ->setDevicesToken($android) ->send(); } $ios = $devices->where('type', 1)->pluck('token')->all(); if (!empty($ios)) { $push = new PushNotification('apn'); $feedback = $push->setMessage( [ 'aps' => [ 'alert' => [ 'title' => $pushData['title'], 'body' => $pushData['body'], ], 'sound' => 'default', 'badge' => 1 ], 'data' => $pushData ] )->setDevicesToken($ios)->send()->getFeedback(); } $web = $devices->where('type', 3)->pluck('token')->all(); if (!empty($web)) { $push = new PushNotification('fcm'); $push->setMessage($pushData)->setDevicesToken($web)->send(); } } and my push data is $pushData = [ 'title' => 'Test', 'body' => 'Test', ]; Please help me solving this A: You should write this if (!empty($web)) { $push = new PushNotification('fcm'); $push->setMessage( [ 'notification' => $pushData, ] )->setDevicesToken($web)->send(); } Hopefully this will solve your problem.
[ "stackoverflow", "0022880932.txt" ]
Q: Im trying to display latest post from my sharepoint discussion board to my main page? I have a community site with a discussion board and I would like to display a few of the latest posts on my main start-up page? How would one go about it in SharePoint 2013? A: The proposed solution allows to modify Discussion List web part properties that are not available from UI. Enable web part Export capabilities In order to modify web part properties that are not available from UI, we need to enable Export capabilities: Add Discussions List on the page. Open the page in SharePoint Designer (SPD) Find the property ExportControlledProperties and set its value to True in order to enable web part Export capabilities Save the page in SPD Change web part properties From now the export action have to be available as shown on picture below Assume we need to display the 4 latest discussions. Discussion default view (Subject) has the following properties: <RowLimit Paged="TRUE">20</RowLimit> In order to change these properties follow the steps below: Export web part file Find the property XmlDefinition and change RowLimit element Paged attribute to FALSE and value to 4 Upload and add web part on page Result How to display Discussions using CQWP In order to aggregate Discussions from a different site you could utilize Content Query web part (CQWP). Steps: add Content Query web part (located under Content Roollup category) go to web part settings and specify the Querysettings as shown on picture below and specify Sorting settings as shown on picture
[ "gis.stackexchange", "0000069590.txt" ]
Q: Route through water polygons I have a water-polygon grid shape file as shown (Each grid is 1latx1long): I have created this in QGIS and files (coastal lines and land polygons) selected from http://openstreetmapdata.com/data Now if I have given a source grid and a destination grid, I have to come up with different routing ways (shortest path, dijkstra or at-least one of them). pgrouting is the way to go, if I am interested in all the different algorithms. These are my questions: 1. Is there any other simpler way than pgrouting 2. How can I create the road topology for this grid structure. A: If your objective is to develop a routing program over the sea returning various maritime routes from (origin,destination) pairs, you should rather rely on a linear mesh covering the seas, instead of polygons. I had exactly the same goal and I did something using: The shipping lane dataset "Oak Ridge National Labs CTA Transportation Network Group, Global Shipping Lane Network, World, 2000" available on geocommon. I did not find any more detailled dataset despite this question... The Dijskra shortest path finder in geotools. If you know a bit of Java, it is rather easy to use. You have to load the maritime lines from the SHP file, transform it into a graph using the FeatureGraphGenerator, assign some weight to the edges with EdgeWeighter, and compute the shortest path with DijkstraShortestPathFinder. Tada! I find PGrouting a bit to big for just computing shortest paths. It is possible to densify the input dataset to get more detailled routes, but then execution time should increase. Here is an example of output (the red line): EDIT: I have released a library/program implementing the approach mentioned above - Here it is: SeaRoute. Feel free to reuse/contribute !
[ "stackoverflow", "0041127130.txt" ]
Q: Capistrano deploy - Permission denied I'm trying to deploy my application with capistrano but I'm having some problems. My machine is a ec2 amazon and I have the .pem locally. I can do ssh and run commands with no problem, but for cap production deploy I get the following error: DEBUG [4f4633f7] Command: ( export GIT_ASKPASS="/bin/echo" GIT_SSH="/tmp/git-ssh-hybrazil-production-ronanlopes.sh" ; /usr/bin/env git ls-remote --heads git@[email protected]:fneto/hybrazil.git ) DEBUG [4f4633f7] Permission denied (publickey). DEBUG [4f4633f7] DEBUG [4f4633f7] fatal: Could not read from remote repository. DEBUG [4f4633f7] DEBUG [4f4633f7] DEBUG [4f4633f7] Please make sure you have the correct access rights DEBUG [4f4633f7] and the repository exists. DEBUG [4f4633f7] On my production/deploy.rb, I have the config like this: set :ssh_options, { keys: %w(/home/ronanlopes/Pems/hybrazil-impulso.pem ~/.ssh/id_rsa), forward_agent: true, auth_methods: %w(publickey) } any ideas? Thanks in advance! A: You can add your key to agent, use command: ssh-add ~/.ssh/id_rsa In your code you should use full path to ssh key, without pem: keys: %w(/home/user_name/.ssh/id_rsa)
[ "security.stackexchange", "0000043351.txt" ]
Q: What could be the order of these ciphers following as first criteria the security and just then the performance? I need some guide to decide in which order I must put the following ciphers if I want prioritize security and in cases of tied, consider performance to decide. ECDHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH Au=RSA Enc=AESGCM(256) Mac=AEAD ECDHE-ECDSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH Au=ECDSA Enc=AESGCM(256) Mac=AEAD ECDHE-RSA-AES256-SHA384 TLSv1.2 Kx=ECDH Au=RSA Enc=AES(256) Mac=SHA384 ECDHE-ECDSA-AES256-SHA384 TLSv1.2 Kx=ECDH Au=ECDSA Enc=AES(256) Mac=SHA384 ECDH-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH/ECDSA Au=ECDH Enc=AESGCM(256) Mac=AEAD ECDH-ECDSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH/ECDSA Au=ECDH Enc=AESGCM(256) Mac=AEAD ECDH-RSA-AES256-SHA384 TLSv1.2 Kx=ECDH/ECDSA Au=ECDH Enc=AES(256) Mac=SHA384 ECDH-ECDSA-AES256-SHA384 TLSv1.2 Kx=ECDH/ECDSA Au=ECDH Enc=AES(256) Mac=SHA384 And what about this list? DHE-DSS-AES256-GCM-SHA384 TLSv1.2 Kx=DH Au=DSS Enc=AESGCM(256) Mac=AEAD DHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=DH Au=RSA Enc=AESGCM(256) Mac=AEAD DHE-RSA-AES256-SHA256 TLSv1.2 Kx=DH Au=RSA Enc=AES(256) Mac=SHA256 DHE-DSS-AES256-SHA256 TLSv1.2 Kx=DH Au=DSS Enc=AES(256) Mac=SHA256 different list, I don't want mix them ;) A: Security: if you don't do stupid things like using a 512-bit RSA key, these cipher suites are all equally secure: they are all very far in the "cannot break it" zone. So that's a meh. You cannot say that one is more secure than any other. With an exception though: the "ECDHE" suites use an ephemeral key pair for actual encryption; since the corresponding private key is never stored in a file, this grants a nifty property known as Perfect Forward Secrecy. Basically it makes communications immune to attackers who steal a copy of the server private key after the fact. PFS looks good in technical audits. Performance issues exist only after having been duly measured. As Knuth said: Premature optimization is the root of all evil. So you should not ask such questions; you should try it out and measure. In any case, answer will depend a lot on the context: involved machines, bandwidth, usage patterns... Short answer: won't matter. Long answer: The "GCM" cipher suites use GCM; the non-GCM cipher suites use AES in CBC mode and an extra HMAC (here, with SHA-384). Performance issues depend on the involved systems: On small 32-bit systems (embedded ARM...), the MAC part of GCM will be expensive, but so will SHA-384 (because 64-bit computations...); I'd guess a tie. On PC, AES cost will dominate; ... except on very recent PC with AES-NI, where AES is very fast, and so is GCM. So the GCM cipher suite should, usually, be a better bargain. However, it takes a lot of bandwidth, or a very small CPU, to actually notice the difference. Even without AES-NI, a normal server has enough juice to do SSL at full gigabit bandwidth, with CPU to spare. For the asymmetric cryptography part: The ECDHE suites imply on the server an (elliptic-curve) Diffie-Hellman and a signature for each full handshake, whereas the ECDH cipher suites require only the elliptic-curve Diffie-Hellman, and half of that one is already done. ... But a normal PC will crunch through thousands of those per second and per code, so this very rarely matters. ... Especially since normal SSL clients reuse SSL sessions, which means that the asymmetric cryptography occurs only for the first ever connection of the day from a given client. ECDSA signatures are faster than RSA signatures. ... Depending on key sizes, of course. ... But for verification, this is the other way round. ... And, again, it takes an awful lot of new clients per second for this to actually matter. A normal PC will do hundreds of 2048-bit RSA signatures per seconds, thousands of 256-bit ECDSA signatures per second. ECDSA signatures are shorter than RSA signatures, so this saves a bit of network (but, again, only a few dozen bytes per full handshake). DHE and ECDHE cipher suites also imply a few dozen extra bytes per full handshake. DHE is like ECDHE but without the elliptic curves. You need it to use bigger mathematics to achieve the same security levels (2048-bit modulus instead of a 256-bit curve point), so it is like RSA vs ECDSA: a bit bigger, a bit slower, won't matter in practice. So, really, you will not make a useful distinction based on security or even performance. In fact, you are already making a fashion statement, by insisting on AES-256 (instead of AES-128) and SHA-384 (instead of SHA-256). You may as well keep it on and bring it to its logical conclusion: use as much GCM and elliptic curves as possible ! This will grant brownie points from impressionable auditors.
[ "stackoverflow", "0025581656.txt" ]
Q: Segue from code doesn't work I've created a segue from one VC to another VC (Dragging form the VC to the other VC), and called it RegisterUserSegue , its a Push segue and all my view controllers are embedded in a navigation controller. I'm calling the segue like this: [self performSegueWithIdentifier:@"RegisterUserSegue" sender:self]; and in performSegueWithIdentifier I've set an NSLog that is called every time I call the segue, but the viewController doesn't change. EDIT: however if i comment out the - (void)performSegueWithIdentifier:(NSString *)identifier sender:(id)sender method, everything works just fine. This is the method: - (void)performSegueWithIdentifier:(NSString *)identifier sender:(id)sender { NSLog(@"Called"); } help? thanks! A: By implementing prepareForSegueWithIdenitifer you have overridden the default implementation in UIViewController with a method that does nothing (except write to the log). You could use - - (void)performSegueWithIdentifier:(NSString *)identifier sender:(id)sender { [super performSegueWithIdentifier:identifier sender:sender]; NSLog(@"Called"); } But you typically do not override this method. If you want to pass properties through to the destination view controller you would use prepareForSegue:sender:
[ "stackoverflow", "0038723277.txt" ]
Q: Tkinter Toplevel : Destroy window when not focused I have a Toplevel widget that I want to destroy whenever the user clicks out of the window. I tried finding solutions on the Internet, but there seems to be no article discussing about this topic. How can I achieve this. Thanks for any help ! A: You can try something like that : fen is your toplevel fen.bind("<FocusOut>", fen.quit)
[ "math.stackexchange", "0002449560.txt" ]
Q: How to find farthest see-able corners of a rectangle? I don't know English well enough to explain so here a picture that explains. This is on a coordinate plane. A: As zwim writes in his answer, the vertices that correspond to the two extremes of the visual angles are the ones you want. However, you don’t really need to compute these angles explicitly. If you project the vertices onto a line that doesn’t pass through the view point, you can use the positions along the line of these projections as proxies for these angles: the vertices that have the outermost projections are the ones you want. A convenient choice for the line onto which to project is one that lies between the view point and the rectangle. This choice guarantees that none of the rays from the view point to a vertex is parallel to the line onto which you’re projecting, so you don’t have to deal with this additional (minor) complication. Since the rectangle is axis-aligned, you can always find either a horizontal or vertical line that meets this criterion, which simplifies the computations even further. I’ll illustrate with a vertical line, but the calculations for a horizontal line are similar. Given a view point $\mathbf p$ and line $\mathbf l$, the projection of a vertex $\mathbf v$ onto the line is simply the intersection of $\mathbf l$ with the line through $\mathbf p$ and $\mathbf v$. Working in homogeneous coordinates, this can be expressed via cross products as $\mathbf v'=\mathbf l\times(\mathbf p\times\mathbf v) = (\mathbf l^T \mathbf v)\mathbf p-(\mathbf l^T \mathbf p)\mathbf v = (\mathbf p\mathbf l^T-\mathbf p^T\mathbf l)\mathbf v$. Using the cross-product formula on the left is straightforward, but it might be less expensive to construct a matrix that captures the parenthesized term in the last expression and use that to compute the projections. Then, convert the resulting projection points $\mathbf v'$ to Cartesian coordinates and find the ones with the maximal and minimal $y$-coordinates. For the illustrated example, the view point is $(1,1)$, the four vertices of the rectangle are $(4,2)$, $(8,2)$, $(8,5)$ and $(4,5)$, and we will be projecting onto the line $x=2$. In homogeneous coordinates, $\mathbf l=[1:0:-2]$ and the homogeneous coordinates of all of the points are obtained by appending a $1$. We compute: $$\begin{align} [1:0:-2]\times([1:1:1]\times[4:2:1]) &= [6:4:3] \to \left(2,\frac43\right) \\ [1:0:-2]\times([1:1:1]\times[8:2:1]) &= [14:8:7] \to \left(2,\frac87\right) \\ [1:0:-2]\times([1:1:1]\times[8:5:1]) &= [14:11:7] \to \left(2,\frac{11}7\right) \\ [1:0:-2]\times([1:1:1]\times[4:5:1]) &= [6:7:3] \to \left(2,\frac73\right). \end{align}$$ The second and fourth vertices have the minimum and maximum $y$-coordinates, so those are the ones you want. In matrix form we have $$\mathbf p\mathbf l^T-\mathbf p^T\mathbf l\,I_3 = \begin{bmatrix}2&0&-2\\1&1&-2\\1&0&1\end{bmatrix}.$$ Since we’re only interested in the Cartesian $y$-coordinate of the projected point, we can discard the first row of this matrix. We can also fold in the conversion to Cartesian coordinates, yielding the formula $$y'={[1:1:-2]\cdot\mathbf v\over[1:0:1]\cdot\mathbf v}.$$ I’ll leave it to you to verify that this produces the same $y$-coordinates as the cross-product computation. If you end up with two vertices with the same max/min coordinate, you’ll need to compare their distances from the view point, which you can do with a simple coordinate comparison, and select the nearer one. If projecting onto a horizontal line instead, you would of course compare the $x$-coordinates instead of the $y$-coordinates of the projections.
[ "wordpress.stackexchange", "0000131038.txt" ]
Q: How to setup a permalink structure for a custom post type I would like to know the correct way to setup the permalink structure for a custom post type. Is there any attribute I am to set when I run a register_post_type() ? e.g. custom post type: product expected permalink structure: /product/<slug> A: I think you need to use the rewrite argument. Here's an example setting the url to tips $args = array( 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'show_in_menu' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'tips' ), // Here! 'capability_type' => 'post', 'has_archive' => true, 'hierarchical' => false, 'menu_position' => 20, 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments', 'revisions', 'custom-fields') ); register_post_type( 'tips', $args ); More info: http://codex.wordpress.org/Function_Reference/register_post_type
[ "stackoverflow", "0008694802.txt" ]
Q: Java and FTP server I have a problem with connection with FTP server. I have a application, which must read data from files. I have code where I searching files at my local disk, but I must change that because I have all data at FTP server. At this time I using: FileChannel fc = new FileInputStream("C:/Data/" + nameFile) .getChannel(); where nameFile is name my file. I create channel where I load data from file from local disk. Can I change that code that I can search files at FTP server? A: I don't fully understand your post, but it sounds like you are looking for some code to check whether a file exists on the remote FTP server, correct? If so, then you will want to do the following: Connect to server and authenticate. Navigate to directory on remote system Perform a directory listing of remote system Check to see if any of the files in directory listing match the file you are looing for. I've done this successfully using Secure FTP Factory at http://www.jscape.com/products/components/java/secure-ftp-factory/ Example Code Ftp ftp = new Ftp(hostname,username,pass); ftp.connect(); // get directory listing Enumeration listing = ftp.getDirListing(); // enumerate thru listing while(listing.hasMoreElements()) { FtpFile file = (FtpFile)listing.nextElement(); // check to see if filename matches System.out.println("Filename: " + file.getFilename()); }
[ "math.stackexchange", "0001386778.txt" ]
Q: Equality of two matrices If we have a diagonal matrix D which verify $D = A^*MA = B^*MB$ where $^*$ denotes the conjugate transpose, with A, B and M being unitary matrices Plus, B is symetric, M is real, and none of these matrices are equal to I. Do we have $A = B$ ? A: This is not true in general. Let me first do a parallel with the spectral Theorem. This Theorem says that for a hermitian matrix $P$ there exists a unitary matrix $U$ and a diagonal matrix $D$ such that $P=UDU^*$. Now if we switch two diagonal elements in $D$, we just need to switch the corresponding columns of $U$ to get a pair $\tilde D,\tilde U$ of matrix that also satisfies $P=\tilde U\tilde D \tilde U^*$. Note also that if $v$ is an eigenvectors of $M$ then it is also the case of $-v$. Based on this observation you can already guess that the equality $A=B$ is not always true. For a counter example, just choose $D=\operatorname{diag}(a,a,b),a,b\in\Bbb R$ and any unitary matrix $A$ now set $B$ to be $A$ where you switch the first two columns or multiply a column by $-1$. Nevertheless, since $A$ and $B$ are unitary, they have linearly independent columns $A(1),\ldots,A(n)$ and $B(1),\ldots,B(n)$ satisfying $MA(i)=d_{i,i}A(i)$ and $MB(i)=d_{i,i}B(i)$ for every $i$. It follows that the columns of $A$ are normed eigenvectors of $M$ and the same holds for $B$ (note that a matrix of dimension $n$ cannot have more than $n$ linearly independant eigenvectors). It follows that $$A=B\Delta \Pi$$ where $\Pi$ is a permutation matrix (to replace the columns in the good order) and $\Delta $ is a diagonal matrix with only $1$ and $-1$ on its diagonal (because if $v$ is a normed eigenvector of $M$, the this is also the case of $-v$). Finally note that if all diagonal elements of $D$ are distinct, then $A(i),B(i)$ are both normed eigenvectors belonging to an eigenvalue of multiplicity one and thus $A(i)= B(i)$ or $A(i) = -B(i)$, i.e. $A=B\Delta$ where $\Delta$ is a diagonal matrix with $1$ and $-1$ on its diagonal.
[ "superuser", "0000803109.txt" ]
Q: Unknown .exe file I downloaded a program called glasswire to see which programs are using the internet. One program doesn't show in task manager and I can't find out what it does. Does someone know what it is or how I can find it out? Info about the program: name: gwinstst.exe traffic type: HTTP Host: 199.7.51.72 incoming: 3.4kb outgoing: 0.447kb location: c:\users\thijs\appdata\local\temp\nsx8a46.tmp\gwinstst.exe Thanks in advance. A: The fact that this file is in the Appdata\Temp area to me is a big red flag that it's suspect. I'd try uploading it to VirusTotal - but also be prepared to do a full virus scan on your machine. A: @GlassWireLabs Twitter account confirmed that gwinstst.exe is their own application. In their words: "Yes it is ours. It lets us know how many installs we get per day." Source: https://twitter.com/GlassWireLabs/status/504363540074221568 (They also confirmed they will be rewriting their FAQ/Privacy Policy pages to reflect more detail in what they collect and why.)
[ "stackoverflow", "0043815973.txt" ]
Q: Hadoop2.7.3: Cannot see DataNode/ResourceManager process after starting hdfs and yarn I'm using mac and java version: $java -version java version "1.8.0_111" Java(TM) SE Runtime Environment (build 1.8.0_111-b14) Java HotSpot(TM) 64-Bit Server VM (build 25.111-b14, mixed mode) followed this link: https://dtflaneur.wordpress.com/2015/10/02/installing-hadoop-on-mac-osx-el-capitan/ I first brew install hadoop, config ssh connection and xml files as required, and start-dfs.sh start-yarn.sh The screen output is like this: $start-dfs.sh 17/05/06 09:58:32 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable Starting namenodes on [localhost] localhost: namenode running as process 74213. Stop it first. localhost: starting datanode, logging to /usr/local/Cellar/hadoop/2.7.3/libexec/logs/hadoop-x-datanode-xdeMacBook-Pro.local.out Starting secondary namenodes [0.0.0.0] 0.0.0.0: secondarynamenode running as process 74417. Stop it first. 17/05/06 09:58:39 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable $start-dfs.sh 17/05/06 09:58:32 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable Starting namenodes on [localhost] localhost: namenode running as process 74213. Stop it first. localhost: starting datanode, logging to /usr/local/Cellar/hadoop/2.7.3/libexec/logs/hadoop-x-datanode-xdeMacBook-Pro.local.out Starting secondary namenodes [0.0.0.0] 0.0.0.0: secondarynamenode running as process 74417. Stop it first. 17/05/06 09:58:39 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable Then using jps I cannot see "DataNode" and "ResourceManager". I suppose DataNode is hdfs module and ResourceManager is yarn module: $jps 74417 SecondaryNameNode 75120 Jps 74213 NameNode 74539 ResourceManager 74637 NodeManager I can list hdfs files: $hdfs dfs -ls / 17/05/06 09:58:59 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable Found 1 items drwxr-xr-x - x supergroup 0 2017-05-05 23:50 /user But running the pi examples throws exception: $hadoop jar /usr/local/Cellar/hadoop/2.7.3/libexec/share/hadoop/mapreduce/hadoop-mapreduce-examples-2.7.3.jar pi 2 5 Number of Maps = 2 Samples per Map = 5 17/05/06 10:19:48 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable 17/05/06 10:19:49 WARN hdfs.DFSClient: DataStreamer Exception org.apache.hadoop.ipc.RemoteException(java.io.IOException): File /user/x/QuasiMonteCarlo_1494037188550_135794067/in/part0 could only be replicated to 0 nodes instead of minReplication (=1). There are 0 datanode(s) running and no node(s) are excluded in this operation. I wonder if I missed any configuation, how can I make sure that they run successfully, and how to check or trouble shoot possible failure reasons? Thanks. A: I am too in learning phase yet. This error comes when there is no datanode available to read/write. You can check Resource Manager using this URL: http://localhost:50070 Is there any datanode running or not. For trouble shooting you can check logs generated under installation directory of hadoop . If you can share that logs i can try to help.
[ "chemistry.stackexchange", "0000005005.txt" ]
Q: Why is periodicity seen in these certain properties? I missed my lesson on periodicity so had to teach myself, and have always forgotten to ask my teacher to explain to me why these trends are seen, which, unfortunately, the textbooks don't. Density: the density of an element tends to increase across a period up to group 3, and then starts to decrease and become very low at group 5 or so. Why is this? Melting and boiling point: they tend to rise up to about group 3 or 4, before falling rapidly after that. I would suggest that this is because group 4 elements tend to have giant covalent structures, so also a higher boiling point, whereas on the right hand side of a period they are simple molecular structures, so have a low boiling point. Am I correct? Atomic size: atomic size always decreases along a period from left to right. My suggestion is that this is because there are more electrons and more protons as the group increases, so there becomes a stronger attraction between them, pulling the electrons closer to the nucleus. Am I right? So the only one I have no idea about really is density, and the other two I just need clarification on. A: For 2. I would add, on top of what you already have, that the elements start as metallic elements, hence we have metallic bonding. Across the period, the number of electrons increase, meaning there are more delocalised electrons among the metal cations so that electrostatic attraction increases along the period. For period 2, that's the trend. For period 3 however, it is a bit more tricky because of the transition metal elements and I think Nicolau explains it better than I could in this answer. But I don't think that you will be required to know those for your level, but it's still interesting for your own knowledge. :) For 3. I would add that the number of electron shells containing electrons remains constant. If it increased instead, the atomic radius would increase as well. And you could use 2. and 3. to explain 1: First, we observe that the atomic mass increases along the period, and that the atomic radius decreases. For giant structures, this generally means that the density increases ($\rho = \dfrac{m}{V}$ and while $m$ increases, $V$ is decreasing slightly, so $\rho$ increases) When we hit the simple molecular structures, the density sharply falls again, because of the average distance between the atoms of the element has drastically risen, so the volume increases. With $m$ increasing gradually and a sharp rise in $V$, you get a sharp decrease in $\rho$. These observations change down the groups though. For instance, Astatine is a solid, so you won't expect a huge fall in density across period 6 around group 5. But for the purpose of your syllabus coverage (I'm assuming High School), those should be enough.
[ "dba.stackexchange", "0000138672.txt" ]
Q: Fill in missing dates with data value from previous populated date for group Picture help desk tickets that gets transfered between departments. We want to know what the department is at the end of the day for each ticket for each day that the ticket is open. The table contains the last department for each ticket for each day it is open on which there is a change in the department (including a row for the date the ticket was initially opened and the date it was closed). The data table looks like this: CREATE TABLE TicketAssigment ( TicketId INT NOT NULL, AssignedDate DATE NOT NULL, DepartmentId INT NOT NULL); What I need is to fill in any missing dates for each TicketId, using the DepartmentId from the previous TicketAssigment row ordered by Date. If I have TicketAssigment rows like this: 1, '1/1/2016', 123 -- Opened 1, '1,4,2016', 456 -- Transferred and closed 2, '1/1/2016', 25 -- Opened 2, '1/2/2016', 52 -- Transferred 2, '1/4/2016', 25 -- Transferred and closed I want this output: 1, '1/1/2016', 123 1, '1/2/2016', 123 1, '1/3/2016', 123 1, '1/4/2016', 456 2, '1/1/2016', 25 2, '1/2/2016', 52 2, '1/3/2016', 52 2, '1/4/2016', 25 This looks like it might be close to what I need, but I haven't had the patience to let it finish, and the estimated plan cost has 6 digits: SELECT l.TicketId, c.Date, MIN(l.DepartmentId) FROM dbo.Calendar c OUTER APPLY (SELECT TOP 1 TicketId, DepartmentId FROM TicketAssigment WHERE AssignedDate <= c.Date ORDER BY AssignedDate DESC) l WHERE c.Date <= (SELECT MAX(AssignedDate) FROM TicketAssigment) GROUP BY l.TicketId, c.Date ORDER BY l.TicketId, c.Date; I suspect there is a way to do this using LAG and a window frame, but I haven't quite figured it out. What is a more efficient way of meeting the requirement? A: Use LEAD() to get the next row within the TicketId partition. Then join to a Calendar table to get all the dates between. WITH TAwithnext AS (SELECT *, LEAD(AssignmentDate) OVER (PARTITION BY TicketID ORDER BY AssignmentDate) AS NextAssignmentDate FROM TicketAssignment ) SELECT t.TicketID, c.Date, t.DepartmentID FROM dbo.Calendar c JOIN TAwithnext t ON c.Date BETWEEN t.AssignmentDate AND ISNULL(DATEADD(day,-1,t.NextAssignmentDate),t.AssignmentDate) ; All kinds of ways to get a Calendar table... A: This is a quick way of doing (I have not tested for performance or scalablity) -- create Calendar table -- borrowed from @Aaron's post http://sqlperformance.com/2013/01/t-sql-queries/generate-a-set-3 CREATE TABLE dbo.Calendar(d DATE PRIMARY KEY); INSERT dbo.Calendar(d) SELECT TOP (365) DATEADD(DAY, ROW_NUMBER() OVER (ORDER BY number)-1, '20160101') FROM [master].dbo.spt_values WHERE [type] = N'P' ORDER BY number; --- create your test table CREATE TABLE dbo.TicketAssigment ( TicketId INT NOT NULL, AssignedDate DATE NOT NULL, DepartmentId INT NOT NULL); -- truncate table dbo.TicketAssigment; insert into dbo.TicketAssigment values (1 , '1-1-2016' , 123 ) insert into dbo.TicketAssigment values (1 , '1-4-2016' , 456 ) insert into dbo.TicketAssigment values (2 , '1-1-2016' , 25 ) insert into dbo.TicketAssigment values (2 , '1-2-2016' , 52 ) insert into dbo.TicketAssigment values (2 , '1-4-2016' , 25 ) --- Query to get desired output ;with Cte as ( select TicketID, min(AssignedDate) minAD, -- This is the min date max(AssignedDate) maxAD -- This is the max date from TicketAssigment group by TicketID ) select Cte.TicketID, c.d as AssignedDate, ( -- Get DeptID select top(1) T.departmentID from dbo.TicketAssigment as T where T.TicketID = cte.TicketID and T.AssignedDate <= c.d order by T.AssignedDate desc ) as DepartmentID from Cte left outer join dbo.Calendar as c on c.d between Cte.minAD and Cte.maxAD order by Cte.TicketID
[ "stackoverflow", "0001759771.txt" ]
Q: Java Midlet Deployment So, I've develop a simple hello world midlet using the Samsung SDK 1.1.2 and I've Packaged the midlet. Now I have two files (a JAR/JAD) combination. How do I get these installed on my phone? As you can tell from the question, I'm new to phone development. Trying to deploy to a Samsung handset on ATT. I'm trying to test out the entire development cycle - the emulators work great for writing code but I really need to make sure the Midlet works as expected on the target phone. A: Suggest you read up a little on OTA delivery of applications, for background. You have a number of options for deployment, here's a few. Connect your handset to a computer via bluetooth, cable, or wifi and copy the JAR file over. I'm not sure if Samsung support this, but other handset manufacturers certainly provide 'manager' software you can download and install on a computer to do this. If your app relies on user data in the JAD this may not be an idea option, or you could include default data in the JAR. Place your JAD and JAR file on a web server you have access to, from which they can be downloaded to your phone. You'll need to ensure that the MIME types for the JAD and JAR files are set correctly, they may not be by default. Exactly how you do this depends on your server - here's an example method. (Presumably you have a web/data access service from AT&T.) If all is well you can fetch the JAD file from the phone's browser and the handset will then prompt you to confirm you wish to proceed and download the full JAR and install. Mobile Network Operators have a variable attitude to supporting JAD and JAR access, for example you may find you have to run your server on port 80 or 8080 for it to work in some cases. Join a service that will host an application for you. One I'm aware of is GetJar. I'm not sure of the details, but doing this will mean you don't have to run your own web server. Apart from basic deployment you might consider signing your application - a process that basically allows you to assert your 'true' identity to a handset. The advantage of doing this is that signed applications can present fewer network access confirmation dialogs and the like to the handset owner. Also, when the application is being deployed, the user will see a message about unsignedness that might include the word 'untrusted' or similar, and that can be off-putting. (Having said that, some major applications out there have been unsigned.) Hope that gets you started.
[ "stackoverflow", "0028874302.txt" ]
Q: Using wildcards in LDAP query to match trustParent property I'm using code like below to build a tree of domains using LDAP query. DirectorySearcher configSearch = new DirectorySearcher( context.AuthContext.ConfigurationDirectoryEntry) configSearch.Filter = string.Format("(&(netbiosname=*)(trustParent=CN={0},CN=Partitions,CN=Configuration,{1}))", parentFolder.Name.Split('.').First(), parentFolder.GetNcName()); // Configure search properties to return configSearch.PropertiesToLoad.Add("dnsroot"); configSearch.PropertiesToLoad.Add("ncname"); configSearch.PropertiesToLoad.Add("netbiosname"); configSearch.PropertiesToLoad.Add("trustParent"); SearchResultCollection forestPartitionList = configSearch.FindAll(); // Loop through each returned domain in the result collection foreach (SearchResult domainPartition in forestPartitionList) { // Use domain information } Such an LDAP filter works properly: (trustParent=CN=**NETBIOSNAME**,CN=Partitions,CN=Configuration,DC=domain,DC=com) However, a version with wildcards doesn't work (returns empty results): (trustParent=*,DC=domain,DC=com) I'm using the query in a stateless web app, so I have only parent domain name as input and I want to avoid additional LDAP query to get a NetBIOS name or DistinguishedName (of a remote AD domain, which may belong to another sub-network). Any hints to filter the search result on trustParent property using wildcard? A: If the syntax of the trustParent attribute is a DistinguishedName, then it's not possible to do wildcard match, as there is no standard for matching substrings on a DistinguishedName in LDAP.
[ "salesforce.stackexchange", "0000143541.txt" ]
Q: Set To: address as the value of the Opportunity owner How do I set the value of the To: field to the opportunity owner? global class OpOwnerOldService_Scheduled Implements Schedulable { global void execute(SchedulableContext sc) { sendEmailtoOppOwner(); } public void sendEmailtoOppOwner() { List<Opportunity> listOpportunity = new List<Opportunity>(); listOpportunity = [SELECT Id, OwnerId FROM Opportunity WHERE Id In (SELECT OpportunityId FROM OpportunityLineItem WHERE Product2.Make_unavailable_for_opps_and_proposals__c = TRUE)]; for(Opportunity opp : listOpportunity) { Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); // Strings to hold the email addresses to which you are sending the email. String[] toAddresses = new String[] {'[email protected]'}; // Assign the addresses for the To and CC lists to the mail object. mail.setToAddresses(); // Specify the address used when the recipients reply to the email. mail.setReplyTo('[email protected]'); // Specify the name used as the display name. mail.setSenderDisplayName('Salesforce Support'); // Specify the subject line for your email address. mail.setSubject('Historic Service attached to current opportunity : ' + opportunitylineitem.Product2.Name); // Specify the text content of the email. mail.setPlainTextBody(opportunity.Id +' has been created.'); // Send the email you have created. Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); } update listOpportunity; } } A: You'll want to use the setTargetObjectId method. From the documentation: All emails must have a recipient value in at least one of the following fields: toAddresses ccAddresses bccAddresses targetObjectId So instead of: String[] toAddresses = new String[] {'[email protected]'}; mail.setToAddresses(toAddresses); You'd want: mail.setTargetObjectId(opp.OwnerId);
[ "stackoverflow", "0056915901.txt" ]
Q: How to make a GIF picture as a SplashScreen in an UWP app? I want to use a GIF picture (with animation) as my Splash Screen in an UWP app. But I do not know how to achieve it. I find some link to give some solution but it seems they are not for UWP app. Like this one: https://social.msdn.microsoft.com/Forums/en-US/3fe32aae-84cb-47fe-a2b0-6650ce22e25c/splashscreen-that-loads-an-animated-gif?forum=vssmartdevicesvbcs private void Form1_Load(object sender, EventArgs e) { String imgPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase.ToString()) + "\\Ani.gif"; StringBuilder sb = new StringBuilder(); sb.Append("<html><body>"); sb.Append("<img src = \"" + imgPath + "\">"); sb.Append("</body></html>"); webBrowser1.DocumentText = sb.ToString(); } Do you have workable solution for UWP app? Please advise. Thanks! More: By checking Mr. Zhu gives link, I make a gif Splash Screen and it works. But there is new issue: before the gif shows, there will be maybe 5s white screen. How to remove it? The new test code is as below: Package.appxmanifest: comment out the original splash screen png file <!--<uap:SplashScreen Image="Assets\SplashScreen.png" />--> App.xaml.cs: protected override void OnLaunched(LaunchActivatedEventArgs e) { if (e.PreviousExecutionState != ApplicationExecutionState.Running) { bool loadState = (e.PreviousExecutionState == ApplicationExecutionState.Terminated); ExtendedSplash extendedSplash = new ExtendedSplash(e.SplashScreen, loadState); Window.Current.Content = extendedSplash; } Window.Current.Activate(); } ExtendedSplash.xaml: <Page x:Class="SplashScreenExample.ExtendedSplash" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:SplashScreenExample" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"> <Grid Background="#464646"> <Image x:Name="extendedSplashImage" Source="Assets/test.gif"/> </Grid> ExtendedSplash.xaml.cs: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; using Windows.ApplicationModel.Activation; using Windows.UI.Core; using System.Diagnostics; using Windows.UI.ViewManagement; // The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace SplashScreenExample { partial class ExtendedSplash : Page { internal Rect splashImageRect; // Rect to store splash screen image coordinates. private SplashScreen splash; // Variable to hold the splash screen object. internal bool dismissed = false; // Variable to track splash screen dismissal status. internal Frame rootFrame; // Define methods and constructor public ExtendedSplash(SplashScreen splashscreen, bool loadState) { InitializeComponent(); ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.FullScreen; splash = splashscreen; if (splash != null) { // Register an event handler to be executed when the splash screen has been dismissed. splash.Dismissed += new TypedEventHandler<SplashScreen, Object>(DismissedEventHandler); // Retrieve the window coordinates of the splash screen image. splashImageRect = splash.ImageLocation; splashImageRect.Width = 1092; splashImageRect.Height = 1080; splashImageRect.X = 0; splashImageRect.Y = 0; } // Create a Frame to act as the navigation context rootFrame = new Frame(); } // Include code to be executed when the system has transitioned from the splash screen to the extended splash screen (application's first view). void DismissedEventHandler(SplashScreen sender, object e) { dismissed = true; // Complete app setup operations here... } void DismissExtendedSplash() { // Navigate to mainpage rootFrame.Navigate(typeof(MainPage)); // Place the frame in the current Window Window.Current.Content = rootFrame; } } } A: Please check Display a splash screen for more time that teach how to extend the splash, and you could custom the splash with Gif image. For complete code sample please check this link.
[ "stackoverflow", "0039022447.txt" ]
Q: How to catch read permission denial in Firebase using the js web API I've set up the rules so that only users in a white-list can read the database. Everything works fine for the white-listed users. However, I could not figure out how to handle the other cases, especially the authenticated users who are not on the white-list. Since they fail the security rules, the .on('value') listener doesn't fire, and it doesn't raise any exception either. Please enlighten me on how to detect authenticated users without read permission. A: The on() method takes a so-called "cancel callback", which will be called when the user doesn't have (or loses) permission to listen at the location. From the reference documentation for on(): cancelCallbackOrContext Optional An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an Error object indicating why the failure occurred. So in most cases, use something like: ref.on('value', function(snapshot) { console.log(snapshot.val()); }, function(error) { console.error(error); })
[ "stackoverflow", "0012088183.txt" ]
Q: Static Library and -weak-lSystem I build a static library that links against other frameworks, particularly CoreLocation. I want to use features provided by iOS 5 but be compatible with 4.3. My app crash at launch when I start it on iOS devices in 4.3 with this error : Date/Time: 2012-08-22 16:44:53.900 +0200 OS Version: iPhone OS 4.3.3 (8J3) Report Version: 104 Exception Type: EXC_BREAKPOINT (SIGTRAP) Exception Codes: 0x00000001, 0xe7ffdefe Crashed Thread: 0 Dyld Error Message: Symbol not found: _UIKeyboardDidChangeFrameNotification The problem I encounter is described in this post : iOS 4 app crashes at startup on iOS 3.1.3: Symbol not found: __NSConcreteStackBlock. But how do you deal with that when building a static library ?? I can't compile when I set the -weak-lSystem flag. Here is a trace : /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool: -dynamic not specified, -all_load invalid /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool: -dynamic not specified the following flags are invalid: -ObjC /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool: can't locate file for: -weak-lSystem /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool: file: -weak-lSystem is not an object file (not allowed in a library) /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool: file: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.1.sdk/usr/lib/libxml2.2.dylib is a dynamic library, not added to the static library /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool: file: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.1.sdk/usr/lib/libxml2.2.dylib is a dynamic library, not added to the static library /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool: file: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.1.sdk/usr/lib/libz.dylib is a dynamic library, not added to the static library /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool: file: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.1.sdk/usr/lib/libz.dylib is a dynamic library, not added to the static library Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool failed with exit code 1 Resolved See accepted answer below and do not forget to mark libraries used in different versions as Optional in Xcode. Ex: I use UIKit new notification for iOS 5 but my deployement target is 4.3 so I need to mark this library as Optional in order to make things work. It is the same for CoreLocation CLGeocoder new iOS 5 class. A: The problem is that UIKeyboardDidChangeFrameNotification is not available on iOS 4 and therefore the dynamic loader (Dyld) fails. From the perspective of the static library developer you don't have to do anything. The -weak-lSystem flag should be set in the Xcode project that uses the static library for an application (see the post mentioned in the question) - not in the project for the static library.
[ "stackoverflow", "0012085976.txt" ]
Q: Graphing data along a timeline I need to create an interface like the below: Each block represents a client's project, and each position is determined by the project's start date, and width is determined by duration in days. This data is attached to each block in the form of data attributes. Is there some library that would make this easier for me? I'm having trouble getting the blocks to stack vertically when they overlap dates. Basically, I need to move a block down if there is a previous block occupying the same left position, but I'm not coming up with a reasonable way of doing this. Thanks. A: I believe you want a Gantt chart library. Google brings up these two quickly: http://dhtmlx.com/docs/products/dhtmlxGantt/index.shtml http://jsgantt.com/ Additionally, if you google "javascript chart library" you'll come up with dozens of others, some of which have some sort of gantt chart support.
[ "salesforce.stackexchange", "0000279747.txt" ]
Q: Nonprofit Success Pack (NPSP): Filter Group I'm attempting to create a rollup summary on the Account Object for related a field on related Contacts. I'm using NPSP-Customizable Rollup-Filter Groups. The end result will be the combined weights of species=dog on related contacts will appear in a field on the Account object. ISSUE: In Filter Groups, I can't get it to show the "Species" field. In fact, (as shown below), picking the Contact object only shows two available fields. What am I doing wrong here? Account Object. Contact Object. Filter Group Screen. Customizable Rollup in NPSP. A: NPSP's Customizable Rollups feature is designed to facilitate complex, filtered rollups of giving data, from Opportunities and Payments, based upon hard or soft credit mechanics. The feature doesn't provide fully generalized rollups of any object to any object. You can read about the types of CRLPs that are available in NPSP documentation. You've selected an Opportunity Rollup based on Contact Soft Credit, which allows you to roll up Opportunity data based on soft credits to associated Contacts. It doesn't make other Contact fields available. To achieve this objective, you'll need a different product, such as the open source Declarative Lookup Rollup Summaries.
[ "stackoverflow", "0027433285.txt" ]
Q: Java IllegalStateException with regex I'm trying to do a simple regex match but keep running into an IllegalStateException. I've looked at other similar questions with the same issue, and they all say that find() or matches() must first be called before we can use group(). The thing is that I'm already doing that but I'm still getting the exact same exception. try { Pattern p = Pattern.compile(strPattern); Matcher m = p.matcher(strInput); m.matches(); m.find(); System.out.println(m.groupCount()); //returns 9 groups System.out.println(m.group(0)); //will crash here } catch (Exception e) { e.printStackTrace(); } Here's the exception I get from this: java.lang.IllegalStateException: No match found at java.util.regex.Matcher.group(Unknown Source) at RegexThing.<init>(RegexThing.java:24) at Test.main(Test.java:14) A: You shouldn't call Matcher#matches followed by Matcher#find. The first method will attempt to match the entire input against the pattern. When find executes next, it will attempt to match the next substring that matches the pattern but it will fail to detect any matched pattern because the previous matches has covered the entire input. Simply call one of them depending on whether you want to match the entire input (matches) or the first subsequence that matches the pattern (find). You should also print the matched groups only if the match is found: if(m.find()) { System.out.println(m.groupCount()); //returns 9 groups System.out.println(m.group(0)); //will crash here }
[ "stackoverflow", "0029256403.txt" ]
Q: How to save datepicker date as mongodb date? In a meteor app I select a date via jquery datepicker, this is triggered by click .tododateDue. After providing all information in my dialog all fields of the todo are saved via click .saveTodo I like to display the date in my input field as dd.mm.yy but I need to save it in a mongodb collection as 'date'. Since I use todo.datedue = tmpl.find('.tododateDue').value; to save the date I get a String in my collection. How can I save this date as the type 'date' in the mongodb collection? Template.todoDlg.events({ 'click .saveTodo':function(evt,tmpl){ console.log('tmpl',tmpl); var todo = {}; todo.note = tmpl.find('.todoitem').value; todo.title = tmpl.find('.todotitle').value; todo.datedue = tmpl.find('.tododateDue').value; todo.project = Session.get('active_project'); Meteor.call('addTodo',todo); Session.set('adding_todo',false); }, 'click .tododateDue': function (evt, tmpl) { Meteor.setTimeout(function () { $('.tododateDue').datepicker({ onSelect: function (dateText) { console.log('date',tmpl.find('.tododateDue').value); //Meteor.call('updateProjectDate', Session.get('active_project'), dateText); }, dateFormat:'dd.mm.yy' }); }, 100) } }) A: I think, you can use moment.js: todo.datedue = moment(tmpl.find('.tododateDue').value, "dd.mm.yy").toDate(); It will return Date-object...
[ "stackoverflow", "0061855757.txt" ]
Q: Unable to webscrape HTML table with BeautifulSoup and load it into a Pandas dataframe with Python My objective is to access the table on the following webpage https://www.countries-ofthe-world.com/world-currencies.html and turn it into a Pandas dataframe that has columns "Country or territory", "Currency", and "ISO-4217". I am able to access the columns correctly, but I am having a hard time figuring out how to append each row to a dataframe. Do you all have any suggestions on how I can do this? For example, on the webpage, the first row in the table is the letter "A". However, I need the first row in the dataframe to be Afghanistan, Afghan afghani, and AFN. Here is what I have so far: from urllib.request import Request, urlopen from bs4 import BeautifulSoup import pandas as pd url = "https://www.countries-ofthe-world.com/world-currencies.html" req = Request(url, headers={"User-Agent":"Mozilla/5.0"}) webpage=urlopen(req).read() soup = BeautifulSoup(webpage, "html.parser") table = soup.find("table", {"class":"codes"}) rows = table.find_all('tr') columns = [v.text for v in rows[0].find_all('th')] print(columns) # ['Country or territory', 'Currency', 'ISO-4217'] Please see this image as well. Thank you all for your time. Tony A: With your fix in place, it's something that can be pretty easily parsed by pd.read_html: url = "https://www.countries-ofthe-world.com/world-currencies.html" req = Request(url, headers={"User-Agent":"Mozilla/5.0"}) webpage = urlopen(req).read() df = pd.read_html(webpage)[0] print(df.head()) Country or territory Currency ISO-4217 0 A A A 1 Afghanistan Afghan afghani AFN 2 Akrotiri and Dhekelia (UK) European euro EUR 3 Aland Islands (Finland) European euro EUR 4 Albania Albanian lek ALL It has those alphabet headers, but you can get rid of those with something like df = df[df['Currency'] != df['ISO-4217']]
[ "stackoverflow", "0005083786.txt" ]
Q: Connect Azure-hosted Ruby on Rails app to on-premise SQL Server through Windows Azure Connect What I've learned: 1. activerecord-sqlserver-adapter can be used to connect a RoR app to an SQL Server by simply changing the database.yml file. Much respect to Ken Collins (http://www.engineyard.com/blog/2011/modern-sql-server-rails/) 2. Nick Hill has showed us how to host a RoR app in a Windows Azure web role (http://blogs.msdn.com/b/mcsuksoldev/archive/2010/02/26/9969876.aspx) 3. Wely Lau, in "How to establishing virtual network connection between cloud and on-premise with Windows Azure Connect (Part 2–Preparing the application)", has showed us how to setup a virtual network connection between a Windows Azure web role and an on-premise SQL server with Windows Azure Connect. Specifically, Wely establishes the on-premise SqlDataSource in step 2 and 3 of her article. I would post a link, but i'm such a newb to stackoverflow, that i'm only allowed to post 2 links :( Anyway, what I'm trying to figure out: 4. How to connect a RoR app, hosted in a Windows Azure web role, to an on-premise SQL Server using a virtual network connection with Windows Azure Connect (i don't think it's as simple as changing the database.yml file to point to the on-premise database unfortunately) I feel like the ingredients are there, but can't figure out how to cook the meal so to speak. For some context, my app users are grouped into teams and it's necessary that teams be able to specify exactly where their databases reside (e.g. either in the cloud or on one of their own servers) - hence the RoR/Azure thing, otherwise, Heroku would be my host. An alternative I've been considering is to distribute a separate copy of the app for those teams who wish to use their own databases and host it themselves, in which case, i'm all set. However, I fear that could become messy quickly as I think about future updates and developer happiness. Appreciate your thoughts. A: Once you've got Connect set up (mostly consists of installing the agent on your database server), it should indeed be as simple as changing database.yml. Why do you think it's harder than that?
[ "stackoverflow", "0000168426.txt" ]
Q: How do I add a shortcut key to Eclipse 3.2 Java plug-in to build the current project? One of the few annoying things about the Eclipse Java plug-in is the absence of a keyboard shortcut to build the project associated with the current resource. Anyone know how to go about it? A: In the Preferences dialog box, under the General section is a dialog box called "Keys". This lets you attach key bindings to many events, including Build Project. A: You can assign a keyboard binding to Build Project doing the following Open up the Keys preferences, Window> Preferences >General>Keys Filter by type Build Project Highlight the binding field. You can then choose the binding you want i.e. Ctrl+ALt+B, P,
[ "physics.stackexchange", "0000420769.txt" ]
Q: Analyticity of the generalized susceptibility in the linear response theory In linear response theory, the generalized susceptibility $\chi(\omega)$ is defined as $$\chi(\omega)=\int\limits_{0}^{\infty}\phi(t) e^{i\omega t} dt, ~~t\geq 0\tag{1}$$ where $\phi(t)$ is the response function$^1$. If it is assumed that $\chi(\omega)$ exists for all real, non-negative $\omega$, then its integral representation as given in (1) suggests that $\chi(\omega)$ also exists when ${\rm Im}\omega\geq 0$ i.e., in the complex upper half plane of $\omega$. This is because an additional damping factor increases the convergence of the integral (1). From (1), how can one argue that $\chi(\omega)$ is also analytic in the complex upper half plane of $\omega$? It's crucial in deriving the so-called Kramer's-Kronig relations in physics. $^1$ On physical grounds, $\phi(t)$ is smooth (which @AFT enquired in his comment) and is also bounded as $t\to\infty$. A: I believe that this follows from causality, namely that $\phi(t)=0$ for $t<0$. Physically, the response of the system cannot precede the perturbation that causes it. In your integral defining $\chi(\omega)$, the lower limit of integration may therefore be extended to $-\infty$, making $\phi(t)$ and $\chi(\omega)$ a Fourier transform pair. Then the Titchmarsh theorem applies: $\chi(\omega)$ is analytic in the upper half complex plane of $\omega$.
[ "stackoverflow", "0026833242.txt" ]
Q: NullPointerException (@PhoneWindow:onKeyUpPanel:1002) {main} I get strange exceptions in my analytics lately. java.lang.NullPointerException at com.android.internal.policy.impl.PhoneWindow.onKeyUpPanel(PhoneWindow.java:1002) at com.android.internal.policy.impl.PhoneWindow.onKeyUp(PhoneWindow.java:1703) at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:2114) at android.view.ViewRootImpl.deliverKeyEventPostIme(ViewRootImpl.java:3626) at android.view.ViewRootImpl.handleImeFinishedEvent(ViewRootImpl.java:3596) at android.view.ViewRootImpl$ViewRootHandler.handleMessage(ViewRootImpl.java:2839) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:4904) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557) at dalvik.system.NativeStart.main(Native Method) I am missing a lead on what I can do to prevent this. A: Until LG fixes this issue (which could be months, depending on how long it takes them to release new firmware), the following workaround worked for me. Just add the following code to your Activity class: @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_MENU && "LGE".equalsIgnoreCase(Build.BRAND)) { return true; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_MENU && "LGE".equalsIgnoreCase(Build.BRAND)) { openOptionsMenu(); return true; } return super.onKeyUp(keyCode, event); } A: Looks like a bug in support library on LG devices https://code.google.com/p/android/issues/detail?id=78154
[ "stackoverflow", "0023720886.txt" ]
Q: Downloading Qt with MinGW I am trying to download Qt with MinGW from the following : URL : http://qt-project.org/downloads Link : Qt 5.2.1 for Windows 32-bit (MinGW 4.8, OpenGL, 634 MB) (Info) But it is extremely slow. Can someone please suggest a better place to download the same stuff. Thanks!! A: You could try a mirror close to your place: http://download.qt-project.org/static/mirrorlist/
[ "bioinformatics.stackexchange", "0000011431.txt" ]
Q: RepeatMasker annotation I collected my own denovo library using many different tools Pipeline (structure-based ) and I updated all the headers corresponding to RepeatMasker format, to obtain Repeat coverage in the genome and .tbl annotation. when I run repeatmasker the annotation results assume to be Homosapien, where Homo annotation table ( .tbl) is limited as shown below Table (1) Actually my denovo repeat library consists of more than what is in the table above, example, rolling circles, Copia, Gypsy etc.. RepeatMasker -Lib myOwnLibrary.fa Mygenome.fa Table (1) My question is how can I run RepeatMasker with my own library using -lib Flag and result like the table (2) below, the table below assume to be vertebrates genome, this is my aim. RepeatMasker -Species Vertebrates Mygenome.fa Table (2) Regards A: After long years of just conceptual knowledge of what the software does, I was dealing with RepearMasker this week. So, I am not entirely sure I am correct, but this is how I understand it. The two flags you explored serve for different scenarios: -species - if the taxa/species is present in the repeat database (repBase or Dfam) -lib - if you want to give repeatModeler something different. In your case it seems like your library is completely missing all LINEs, SINEs and a few others. What you can do is to get from the database all repetitions of the corresponding taxa and catinate it with the repeats you are interested in (the one you supplied in the -lib argument in the first command). util/queryRepeatDatabase.pl -species Vertebrates > flavoured_vertebrate_repetitions.lib cat myOwnLibrary.fa >> flavoured_vertebrate_repetitions.lib RepeatMasker -lib flavoured_vertebrate_repetitions.lib Mygenome.fa This should produce annotation similar to the bottom case, but also using the repetitions you manually added. P.S. util/queryRepeatDatabase.pl is a script to query the database of repeats and it is shipped together with repeatModeler. -- edit -- The TE classification in the summary file of repeatMasker is based on headers of the repetitive elements in the fasta file you specify in to -lib argument. So if you want to get the second-table-like, you need to somehow reclassify the repeat library to contan repBase-like classification of TEs. The explanation of lib argument from the manual: The recommended format for IDs in a custom library is: >repeatname#class/subclass or simply >repeatname#class In this format, the data will be processed (overlapping repeats are merged etc), alternative output (.ace or .gff) can be created and an overview .tbl file will be created. Classes that will be displayed in the .tbl file are 'SINE', 'LINE', 'LTR', 'DNA', 'Satellite', anything with 'RNA' in it, 'Simple_repeat', and 'Other' or 'Unknown' (the latter defaults when class is missing). Subclasses are plentiful. They are not all tabulated in the .tbl file or necessarily spelled identically as in the repeat files, so check the RepeatMasker.embl file for names that can be parsed into the .tbl file.
[ "askubuntu", "0000846564.txt" ]
Q: how to create a udev rule for usb flash with two partitions to create persistent node under /dev? I have a USB flash memory, I created two partitions on it, when it is attached sometimes it takes sda , sda1 and sda4 instead of sdb, sdb1, sdb4. To prevent that confusion I decided to create a udev rule to symlink it under /dev persistently. I created the below rule ACTION=="add", SUBSYSTEM=="usb", ATTRS{idVendor}=="0461", ATTRS{idProduct}=="4d81", SYMLINK+="myusb" When I reboot it creates symlink under /dev/myusb but I can not mount it. sudo mount /dev/myusb /media/myusb mount: /dev/bus/usb/002/003 is not a block device I think I get that error because it contains two partitions. So what shoul I do? A: I think the problem is that you cannot mount a whole drive with several partitions at once. You have to mount each partition for itself. Mounting means getting access to the filesystem, which can be very different on two different partitions. And how would you put two filesystems into one directory? You have to have at least two subdirectories like /media/myusb/part1. That said we are back to UUIDs and labels. You could create an udev rule triggering a script that mounts the two partitions by their uuid, like #!/bin/bash mount /dev/disk/by-uuid/xxxxx-xxxx-xxxxx-xxxxxx /media/myusb/part1 mount /dev/disk/by-uuid/yyyyy-yyyy-yyyyyy-yyyyy /media/myusb/part2 Alternatively you could place the partitions into /etc/fstab, and let udev do a mount -a . Use 'blkid' to print the universally unique identifier for a device; this may be used with UUID= as a more robust way to name devices that works even if disks are added and removed. Maybe you could try that: For partition one: KERNEL=="sd?1", SUBSYSTEMS=="usb", ATTRS{idVendor}=="0461", ATTRS{idProduct}=="4d81", SYMLINK+="myusb1" For partition two KERNEL=="sd?4", SUBSYSTEMS=="usb", ATTRS{idVendor}=="0461", ATTRS{idProduct}=="4d81", SYMLINK+="myusb2" Not sure if it works, but you could give it a try. https://oracle-base.com/articles/linux/udev-scsi-rules-configuration-in-oracle-linux https://wiki.ubuntuusers.de/udev/
[ "stackoverflow", "0053014998.txt" ]
Q: msys2 and docker run specifying the command: looks for the command locally before running in docker Within msys2, anytime I try to execute a docker run [image] [cmd] command such that I'm trying to run in the docker container overwrites the command specified in the Dockerfile, it looks for the command locally and fails if it doesn't exist. For example, my organization has a docker image where the python executable is at /usr/src/venv/bin/python and python is not in $PATH. That is not where my local python is installed and when I try to run docker run myimage /usr/src/venv/bin/python test.py I get this error: OCI runtime create failed: container_linux.go:348: starting container process caused "exec: \"C:/msys64/usr/src/venv/bin/python\": stat C:/msys64/usr/src/venv/bin/python: no such file or directory" This image is not a windows image and so it shouldn't be looking at C: at all so I must conclude it's looking for that command locally instead of within the container. Note: The docker I'm running is Docker for windows added to my $PATH within msys2. $ which docker /c/Program Files/Docker/Docker/Resources/bin/docker.exe One workaround I've used is to create a new Dockerfile that just has a line to say to use the image I want and another that is the command I want. Then I can run docker run some-image without specifying a command and it works. Is there some way I can fix this problem within msys2 without the annoying workaround described above? A: This is due to MinGW Posix Path Convertion. I found two work arounds. Use double-slash // to start the path, then MSYS won't translate the path: docker run myimage //usr/src/venv/bin/python test.py ^^this Another way is to suppress the path translation by setting MSYS_NO_PATHCONV=1 in Windows Git MSys or MSYS2_ARG_CONV_EXCL="*" in MSYS2. Sources: How to stop mingw and msys from mangling path names given at the command line? https://github.com/git-for-windows/git/issues/577#issuecomment-166118846
[ "stackoverflow", "0056416145.txt" ]
Q: Full type name followed by index, what does it mean? I am trying to understand the logging output of dotnet run for an ASP.NET Core project. There are many places showing a full type name followed by what appears to be the indexer syntax. This page explains how array types are represented, but in that case there is no index. Console.WriteLine(new string[100]); shows:System.String[] This is an actual dotnet run output:info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[58] How to interpret the previous text? What is 58? Is it a general C# string representation? What code construct would output something like that? A: In the example provided, there are three components: info, which is the log level. Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager, which is the log category. 58, which is the log event ID. ASP.NET Core uses ILogger and ILogger<T> for logging, using calls such as: logger.LogInformation(...); The example log message you've shown is from a console provider, which has its own rules about how to format the message. By default, this starts with a header line of level: category[eventID], as I've shown. As a crude example, you might imagine the following code being used to generate the final message: var logLevel = "info"; var logCategory = "Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager"; var logEventId = 58; Console.Writeline($"{logLevel}: {logCategory}[{logEventId}]");
[ "pets.stackexchange", "0000017851.txt" ]
Q: How do I stop large german shepherd from dragging me through the yard to chase rabbits? I am dog sitting for my landlady, and she has a large male German shepherd. We have a fenced in yard that I walk him in a few times a day. He is not well trained and has even climbed over the fence before, so I have to keep him on a leash at all times. Most of the time I take him outside without incident, but the last few days there have been rabbits in the yard morning and night which causes him to go crazy and chase after them dragging me behind him. The same freakout happens if the neighbor lets his dogs out in the adjacent yard. I am a small lady, and it takes most of my body weight against his pulling to stop him, once I get him stopped he is still amped and is difficult to manage. He wears a circular chain collar that tightens as he pulls away. The real problem I am having is that he runs so abruptly that it causes me to run a few steps before I can stop him which has caused me to have pain in my leg like a pulled muscle. I try to anticipate these sudden movements, but he even lunges after bugs at times. Since I am only dog sitting for the next two weeks, I don't expect to be able to remove 7 years of bad habits/prey drive from the dog. Is there anything I can do short-term to avoid getting injured further? Send all your ideas, ill try anything! A: Two things I could immediately think of, although they cost a bit, but maybe the owners would be interested in it as well – both would also work in conjunction with each other: Get a harness in addition to a collar. This gives you two points of support to hold the dog back, while also giving you more control over where he's looking/turning (so you might even be able to avoid the dog seeing rabbits or anything else). Get a dampener between collar and actual leash. These are typically made from elastic materials and will consume most of the power applied when the dog starts jumping or running. Also in case of the collar, I'd replace that immediately, if there's no stopper or similar that keeps it from strangling the dog. This is not only outlawed in some regions, but it may also make the problem worse. Also if there's some treat the dog loves, you might be able to use that as a distraction, but it really depends on the individual dog. We've got two and while one would do anything for a treat (even ignoring wild animals or barking dogs), the other just won't care about food at all while on the road.
[ "stackoverflow", "0059277195.txt" ]
Q: I'm getting weird errors for seemingly simple Java code. What am I doing wrong here? I have a final project for my introduction to software class that is split into parts. For the first part, here are the instructions: Task 1-1: Create a Class called Inventory Consisting of three data members: a part number consisting of 2 letters followed by four numbers (e.g. AB1234), a description consisting of 5-25 letters describing the item (e.g. wooden claw-hammer), and a quantity consisting of an integer between 0 and 1000. Create a default constructor that sets the part number to AA0000, the description to Test Item, and the quantity to zero. Create a parameterized constructor that sets the part number, description, and quantity to argument values sent to the constructor. Create set methods for each data member that changes the value of the member to the argument passed to the method. Also create a group of get methods that retrieve each data member. Create a method called show part that displays the formatted contents of an object. Seems simple, yeah? Well obviously I'm doing something wrong but I'm not exactly sure what, could be a minor error or maybe I just don't know what I'm doing somehow. I've tried removing the constructors and certain methods (showPart() in particular) whilst getting the same or similar errors. Here's my code: public class InventoryFinal { public static void main(String[] args) { String partNo; String prodDesc; int quantity; public InventoryFinal() { partNo = "AA0000"; prodDesc = "Test Item"; quantity = 0; } public InventoryFinal(String s, String s2, int i) { partNo = s; prodDesc = s2; quantity = i; } public void setPartNo(String sSet) { partNo = sSet; } public void setProdDesc(String sSet2) { prodDesc = sSet2; } public void setQuantity(int iSet) { quantity = iSet; } public String getPartNo() { return partNo; } public String getProdDesc() { return prodDesc; } public int getQuantity() { return quantity; } public void showPart() { System.out.println("Item#: " + partNo); System.out.println("Description: " + prodDesc); System.out.println("Quantity: " + quantity); } showPart(); } } The errors it's giving me don't really make a whole lot of sense to me. What am I doing wrong? File: M:\Intro to Software\InventoryFinal.java [line: 8] Error: Syntax error on token "public", new expected File: M:\Intro to Software\InventoryFinal.java [line: 8] Error: Syntax error on token "{", { expected after this token File: M:\Intro to Software\InventoryFinal.java [line: 42] Error: Syntax error, insert "}" to complete ClassBody File: M:\Intro to Software\InventoryFinal.java [line: 42] Error: Syntax error, insert ";" to complete Statement A: You can not have embedded methods. At the moment you have all fields and methods inside your main method it should be more like public class InventoryFinal { String partNo; String prodDesc; int quantity; public static void main(String[] args) { //create new instances and call methods from here } public InventoryFinal() { partNo = "AA0000"; prodDesc = "Test Item"; quantity = 0; } public InventoryFinal(String s, String s2, int i) { partNo = s; prodDesc = s2; quantity = i; } public void setPartNo(String sSet) { partNo = sSet; } public void setProdDesc(String sSet2) { prodDesc = sSet2; } public void setQuantity(int iSet) { quantity = iSet; } } // close class
[ "meta.stackexchange", "0000035000.txt" ]
Q: "Please consider adding a comment" obscures the "Add comment" link If the answer you're voting down is short, the message that asks you to add a comment obscures the very link that lets you do that. Given that this message cannot even be clicked away, the overall experience is a little frustrating. IMO the best way to fix this is to let me click the message to close it, but I believe this idea is not very popular for some reason. Example: A: This must only happen on short messages/answers/questions because once the content is bigger than about 100 pixels, the box does not cover it up. At any rate, the box can be clicked to make it go away or you can just wait for the timeout.
[ "stackoverflow", "0055236708.txt" ]
Q: How to config Oracle cloud certificate? I try to connect to oracle cloud through Aws-java-sdk-s3-1.11.116. When i code a main method. every thing works well. But when i put the method to tomcat. it will wrong. I don't know why. see code. the follow is right when runing main method. public static void main(String[] args) { // TODO Auto-generated method stub AmazonS3 client = getAwsClient2(); List<Bucket> listRes = client.listBuckets(); for(int i=0; i< listRes.size();i++) { System.out.println(listRes.get(i).getName()); } } private static AmazonS3 getAwsClient2() { BasicAWSCredentials awsCreds = new BasicAWSCredentials("xxxxxxxxxxxxxxxx","xxxxxxxxxxxxxxxxxxxxxx"); AmazonS3 s3Client = AmazonS3ClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(awsCreds)) .withClientConfiguration(Init()) .withPathStyleAccessEnabled(true) .withEndpointConfiguration( new AwsClientBuilder.EndpointConfiguration("xxxx.compat.objectstorage.us-ashburn-1.oraclecloud.com", Region.getRegion(amzRegion).toString())) .build(); return s3Client; } the return is correct. 16:18:47.776 [main] DEBUG com.amazonaws.requestId - AWS Request ID: 975a50c6-a52b-c0e6-33b3-05d8d8ed44e5 FirstBucket xxxxx-css-test as-dev-xxxx-xxx-2dnav as-dev-xxxx-xxprxxxxoxy-2dvxx Process finished with exit code 0 But when i put it to tomcat. the certificate will error. @GET @Path("/users/testamazon") public Response testAmazon() { AmazonClient.testGetowner(); return Response.ok().build(); } //the method same as main method. public static void testGetowner(){ AmazonS3 client = getAwsClient2(); List<Bucket> listRes = client.listBuckets(); for(int i=0; i< listRes.size();i++) { System.out.println(listRes.get(i).getName()); } } When i call the restful api. /users/testamazon com.amazonaws.SdkClientException: Unable to execute HTTP request: Certificate for <xxxx.compat.objectstorage.us-ashburn-1.oraclecloud.com> doesn't match any of the subject alternative names: [swiftobjectstorage.us-ashburn-1.oraclecloud.com] at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleRetryableException(AmazonHttpClient.java:1069) at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1035) at com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:742) at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:716) at com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:699) at com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:667) at com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:649) at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:513) at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:4187) at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:4134) I don't know why when i call the method from restful api, i get the certificate is 'swiftobjectstorage.us-ashburn-1.oraclecloud.com'. But when i call from main method, the certificate is '*.compat.objectstorage.us-ashburn-1.oraclecloud.com'. I debug the code, the certificate chain from AbstractVerifier.class @Override public final boolean verify(final String host, final SSLSession session) { try { final Certificate[] certs = session.getPeerCertificates(); final X509Certificate x509 = (X509Certificate) certs[0]; when i call from restful api. the certs is incorrect. it is 'swiftobjectstorage.us-ashburn-1.oraclecloud.com'. I don't know why the behavior is not same. Do i need config something? A: In order to use OCI Object Storage endpoints, your client needs to support "Server Name Indication" (SNI). When the client does not support SNI, you will get the default certificate, which is "swiftobjectstorage.[region-identifier].oraclecloud.com". It seems to be what is happening here. With Java, SNI support has numerous caveats. Are you using the same Java version in these two tests?
[ "salesforce.stackexchange", "0000013279.txt" ]
Q: Calculating The Date Using Day of Week Month And Year in Apex My question is different than the other date questions Ive seen here. I'm trying to calculate all of the dates using Day, Month and Year inputs. Right now I'm using a Custom Setting but think might be able to use Apex which would be much better. Needs to include leap years of course. Input fields: Day, Month, Year Ex: Monday, June, 2013 Expected Output: June 3, 2013 June 10, 2013 June 17, 2013 June 24, 2013 A: public class myDateClass{ static map<string,integer> dowMap = new map<string,integer>{'Monday'=>0, 'Tuesday'=>1, 'Wednesday'=>2, 'Thursday'=>3, 'Friday'=>4, 'Saturday'=>5, 'Sunday'=>6}; public static list<date> getMyDates(string dayOfWeekName, integer month, integer year){ list<date> returnList = new list<date>(); date d = date.newInstance(year,month,1); d=d.addDays(math.mod(7-dayOfWeek(d)+dowMap.get(dayOfWeekName),7));//brings you to the first instance of the specified dayOfWeekName of the month do{ returnList.add(d); d=d.addDays(7); } while(d.month()==month); return returnList; } public static integer dayOfWeek(date d){ return math.mod(date.newInstance(1900,1,8).daysBetween(d),7); } } Example: list<date> dates = myDateClass.getMyDates('Monday',4,2013); for(date d:dates) system.debug(d); Output: 15:53:22:067 USER_DEBUG [3]|DEBUG|2013-04-01 00:00:00 15:53:22:067 USER_DEBUG [3]|DEBUG|2013-04-08 00:00:00 15:53:22:067 USER_DEBUG [3]|DEBUG|2013-04-15 00:00:00 15:53:22:067 USER_DEBUG [3]|DEBUG|2013-04-22 00:00:00 15:53:22:068 USER_DEBUG [3]|DEBUG|2013-04-29 00:00:00 If you need a special date format in a Visualforce page, you can use apex:outputText E.g. <apex:outputText value="{0,date,EEEE MM'/'dd'/'yyyy}"> <apex:param value="{!myDate}" /> </apex:outputText> Outputs: Wednesday 6/26/2013
[ "bicycles.stackexchange", "0000001590.txt" ]
Q: How much motor do I need for my electric-assist bike? I take my twins to preschool by car, and I'd like to switch to doing it by bike. There's a hill, and we're heavy, and I'm not in great shape, so it's hard. I've done it a few times, but I always collapse when I get home, and I certainly don't have the energy to do it twice (drop-off + pick-up). I take a while to recover. It takes a lot longer, too. I also would like to always bike to the grocery store and other errands, but they are within the range of the preschool, so let's focus on that one for now. I'm looking at electric-assist bikes as a way to overcome the hurdle and starting doing this trip by bike (almost) every time. I've seen bolt-on hub-motor systems for as little as $300, and Big Dummy + Stoke Monkey setups for $3000+. Data: The bike + trailer + me + passengers weigh 430 lbs. There's a 230' climb on the way there, and 110' climb on the way back. I can drive it in 4 minutes but biking takes 20 minutes. How much motor (and how much battery) do I need to invest in? A: A highly trained competitive cyclist can ride at ~ 350-400 watts of power output for a 2 hour ride. So adding a 400 watt electric assist motor is roughly equivalent to adding a competitive cyclist 'stoker' to your rig. The speed and battery size make a big difference but here are some rules of thumb: Some motors are measured in horsepower, rather than watts. 1/2 horsepower is roughly equal to 400 watts for this use. A 400-watt motor will usually be sufficient for the average rider. Your rig is a little heavier, so you might want to go with higher watts. On a typical 400 watt rig, two 12-volt, 12 amp-hour batteries will take an average rider 10 miles at 15 mph or up a hill that's 800 feet tall. To go faster (assuming you haven't maxed out the watts) or further, you need to increase the battery - range is proportional, so twice the battery size = twice the range at the same speed. There are companies like Convergence Tech that sell kits for motors in the 1 horsepower range that are pretty easy to add to an existing bike if you are mechanically inclined. That range is probably more than sufficient for your needs. Be aware that some areas limit the top speed or the available power for electric or gas-assisted bicycles. I've seen speed limits of 25-30 mph and power limits as low as 500 watts. You will want to check with your local road or transportation department to make sure you comply with local regulations. A: This is an oldie, but a good question. Many would-be electric cyclist get a lot of misinformation from corporate marketing, insurance companies, governments, etc.. Because ebike technology is in its relative infancy (compared to say gas engine vehicles like a motorcycle) a lot has been learned in the last 5 years! I ride a very similar to setup to what the original poster mentioned (Big Dummy Electric Bicycle) and have been riding it for over a year now to/from work as well as a half a dozen longer trips of 100km+ with total weight up towards that 400lbs mark you mentioned. Now Gary has given you some good information regarding total power output but not more specifics regarding voltage/amperage/windings/etc. The total power output will very likely be regulated by local laws to just slightly lower than what is reasonable for your application. That's just how it works today in most of the world for uninsured vehicles. So your choice in motor is more about how you use the maximum power output rather than selecting the power output. When a motor is manufactured a specific number of coils/turns of wire are wrapped around each pole in the motor of the appropriate thickness. By varying the number of turns and thickness of wire the same motor design can result in higher speeds or lower speeds. Most manufacturers will produce several common variations for targeting 20", 26" and 29" wheels. When I setup my ebike, I bought the "high speed" motor winding. This is capable of propelling the bike up to 50km/h with a 26" tire. Please note this will exceed the legal limit everywhere I know of in North America, so off road use only. I have a limiter built into my 'Cycle Analyst' ebike computer which can then tone it down to the the legal limit for daily commutes (In Canada that's 32km/h 500W). The high speed motor scores high on the 'cool points' when you show it off to your friends, but you'll soon change your mind and wish you got the lower speed winding for daily efficiency. The lower speed windings generally trade off speed for torque and/or thermal capacity (thicker wires - less likely to burn out on long uphill pulls). Also travelling at lower speeds will conserve battery power and allow you to make longer trips on the same battery. Wind resistance is not a linear force on your bike. For example on my bike maintaining 32km/h will take twice the power of maintaining 24 km/h, likewise maintaining 48-50km/h will take four times the power output (also exceeding most legal limitations). When hauling kids for a 4 minute 'drive', a steady pace of 20-24km/h is probably great. So the related question here to motor selection is battery selection. Again you'll have a total capacity expressed as AH (amp-hours) which is the number of hours the battery would sustain a 1 amp draw. But equally important here is the voltage for the overall system. The most popular voltages are 24, 36 and 48 volts. 24 volts are usually under powered kits for heavily restricted European countries but is not really suitable for your application. 36v and 48v will be your primary choices. The voltage will be directly proportional to your maximum capable speed. Again I went with 48v when I built my ebike because its very 'cool' to show off the speed/torque. However, if I went with 36v system with a motor designed to max out at 32km/h at 36v I would have been more happy in the longer run from a practical viewpoint. That is because given the same size/weight of battery, a 36v battery will likely contain at least 25% more capacity (AH) as the 48v. This equates to longer run times or more distance between charges. Again for practical use commuting with kids/trailers, you will be more interested in running a consistent reliable slightly slower electric bicycle than a 'hot rod' which burns through battery juice. So I would recommend a 36v motor/battery combination designed to just meet the maximum legal power output limits (Watts) for your local laws. For the electric-assist nay-sayers out there, I believe bicycles will make a big come back in north america during the next few decades as practical devices (not just sport). Bicycles are efficient, small and user maintainable in many cases. Electric assist enables us to do more with a bike within a reasonable amount of time. Not everyone can afford to triple their commute times each day. I do recommend to everyone to improve their health, but most people need to move 400lbs around daily today and in a reasonable amount of time similar to driving. Electric assist does that. Plus electric assist bicycling is a "gateway drug" to other forms of bicycling! You'll find many people who own an electric assist bicycle also own other bikes for other less practical uses.
[ "stackoverflow", "0028054979.txt" ]
Q: Laravel 4 Form Validation should be unique on update form, but not if current I am trying to validate an update user profile form, whereby the validation should check that the email doesn't exist already, but disregard if the users existing email remains. However, this continues to return validation error message 'This email has already been taken'. I'm really unsure where I'm going wrong. Otherwise, the update form works and updates perfectly. HTML {{ Form::text('email', Input::old('email', $user->email), array('id' => 'email', 'placeholder' => 'email', 'class' => 'form-control')) }} Route Route::post('users/edit/{user}', array('before' => 'admin', 'uses' => 'UserController@update')); User Model 'email' => 'unique:users,email,{{{ $id }}}' A: Your rule is written correctly in order to ignore a specific id, however, you'll need to update the value of {{{ $id }}} in your unique rule before attempting the validation. I'm not necessarily a big fan of this method, but assuming your rules are a static attribute on the User object, you can create a static method that will hydrate and return the rules with the correct values. class User extends Eloquent { public static $rules = array( 'email' => 'unique:users,email,%1$s' ); public static function getRules($id = 'NULL') { $rules = self::$rules; $rules['email'] = sprintf($rules['email'], $id); return $rules; } }
[ "stackoverflow", "0016168927.txt" ]
Q: Promote type from a list of types, with templates I have a vector with int elements and a vector with float elements. In that case most preffered type is float and in dot product I want to return a float type (if not specified). The following code does just this, but something goes wrong with template packs. Can I have a little bit of help? #include <iostream> #include <vector> #include <array> using namespace std; template<typename Tp, typename T1> struct contains { constexpr static bool value = std::is_same<Tp, T1>::value; }; template<typename Tp, typename T1, typename ... Tn> struct contains { constexpr static bool value = std::is_same<Tp, T1>::value || contains<Tp, Tn...>::value; }; template<typename ... T> struct perfect { typedef typename std::conditional<contains<long double, T...>::value, long double, typename std::conditional<contains<double , T...>::value, double, typename std::conditional<contains<float , T...>::value, float, typename std::conditional<contains<long long , T...>::value, long long, typename std::conditional<contains<unsigned long long, T...>::value, unsigned long long, typename std::conditional<contains<int , T...>::value, int, typename std::conditional<contains<unsigned int, T...>::value, unsigned int, //..... void >>>>>>>::type type; }; struct Vector1 : public std::vector<double> {}; struct Vector2 : public std::vector<int> {}; struct Vector3 : public std::vector<float> {}; template<typename C1, typename C2, typename T = perfect<typename C1::value_type, typename C2::value_type>::type> T dot_product(const C1 &c1, const C2 &c2) { return 0; // return c1 * c2 } int main() { Vector1 a; Vector2 b; cout << dot_product(a, b) << endl; cout << dot_product<Vector1, Vector2, long double>(a, b) << endl; } A: You're looking for decltype<C1() * C2()>, no need for your struct perfect.
[ "stackoverflow", "0049377898.txt" ]
Q: How std::bind(&T::memberFunc, this) can always bind to std::function regardless of what T is? As far as I know, the member function pointer only can be assigned to the pointer to member function type, and converted to any other except this will violate the standard, right? And when calling std::bind(&T::memberFunc, this), it should return a dependent type which depend on T.(in std of VC++ version, it's a class template called _Binder). So the question becomes to why one std::funcion can cover all _Binder(VC++ version) types. class A { public: void func(){} }; class B { public: void func(){} }; std::function<void(void)> f[2]; A a; B b; f[0] = std::bind(&A::func, &a); f[1] = std::bind(&B::func, &b); And I can't picture what type of the member of std::funcion which stored the function would be like, unless I am wrong from the first beginning. This question only covered the member function need to be called with it's instance. But mine is about why one std::function type can hold all T types. A: In short what is happening is that std::bind(&A::func, &a) returns an object of a class similar to class InternalClass { A* a_; // Will be initialized to &a public: void operator()(void) { a_->func(); } }; [Note that this is highly simplified] The callable operator() function is what is matches the void(void) signature of the std::function<void(void)>. A: I think the implementation would probably like this: template</*...*/> class std::bind</*...*/> { public: std::bind(callable_t call, param_t p) { _func = [call, p]()/* using lambda to capture all data for future calling */ { p->call(); }; } operator std::function<void(void)>() { return _func; } private: std::function<void(void)> _func; }; And lambda is the key.
[ "stackoverflow", "0023122889.txt" ]
Q: MySQL: How to select where column A not in column B? Suppose I have the following table named FRUITSALAD: | ID | FRUIT | SALAD | |----|--------|--------------| | 1 | apple | apple,orange | | 2 | orange | pear,banana | | 3 | banana | apple | | 4 | grape | apple,grape | | 5 | pear | | | 6 | | apple,pear | NOTE: The SALAD column contains any number of comma-separated fruits. How can I select ID where FRUIT is not in SALAD? (rows 2, 3, 5 / not row 6) My first thought was to try this, but it returned all rows where fruit exists: SELECT id FROM fruitsalad WHERE fruit NOT IN (salad) I'm hoping to do this without a join or nested subquery if possible, but I'd appreciate any suggestion that gets it done. Thanks in advance! A: In MySQL, you can do this using find_in_set(): select id from fruitsalad where find_in_set(fruit, salad) = 0; To handle row 6, you might need: select id from fruitsalad where find_in_set(fruit, salad) = 0 and fruit is not null and fruit <> '';
[ "math.stackexchange", "0001029046.txt" ]
Q: Maximum value of multiplicative order Let $x \in \mathbb{Z}_{n^2}^*$ and let us assume that the multiplicative order of $x$ is multiple of $n$, then what is the maximum value of multiplicative order possible for $x$ under modulo $n^2$ ? Is it $n \lambda$ , where $\lambda$ is Carmichael function of $n$ .How ? Is it possible to have multiplicative order of $x$ greater than $n \lambda$ ? A: $\lambda(m)$ is the exponent of $\mathbb{Z}_{m}^*$, that is, the lcm of the orders of all elements. In particular, no element can have order greater than $\lambda(m)$. Now, $\lambda(n^2)\le n\lambda(n) \ (\star)$. So, it is not possible to have elements of order greater than $n\lambda(n)$, because there are no elements of order greater than $\lambda(n^2)$. In particular, if an element has order $nk$, then $k\le \lambda(n)$. $(\star)$ Take $x$ with $(x,n^2)=1$. Then $(x,n)=1$ and $x^{\lambda(n)}\equiv 1 \bmod n$. Write $x^{\lambda(n)}=1+an$. Then $x^{n\lambda(n)}=(1+an)^n=1+\binom{n}1an+ \binom{n}2 (an)^2+\cdots+(an)^n \equiv1 \bmod n^2$. Thus, $n\lambda(n) \ge \lambda(n^2)$, because $\lambda(n^2)$ is the least exponent for $\mathbb{Z}_{n^2}^*$.
[ "stackoverflow", "0024638798.txt" ]
Q: How to detect which NSTableView is selected I have an NSViewController with 4 NSTableViews inside (View based), all of them have NSTextFields and I want to call a method for triggering an action after editing each of them called -(void)controlTextDidEndEditing:(NSNotification *)obj{ NSTextField *textfield = (NSTextField *) [obj object]{} but for do so, I need to know which NSTableView am I editing, what's the proper way to get that information A: with this: -(void)tableViewSelectionIsChanging:(NSNotification *)notification{ MyTableView *tableView = (MyTableView *)[notification object]; if (tableView == _tableView1) { NSLog(@"_tableView1"); } if (tableView == _tableView2) { NSLog(@"_tableView2"); } if (tableView == _tableView3) { NSLog(@"_tableView3"); } if (tableView == _tableView4) { NSLog(@"_tableView4"); } }
[ "stackoverflow", "0053877120.txt" ]
Q: How to Create an overlap chain in ConstraintLayout Android Studio I want to create an overlap chain which keep needed margin than other elements and they may have more elements next to each other. Like this: A: This can be achieved using Guidelines. Try something like this: <?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <View android:id="@+id/view_1" android:layout_width="200dp" android:layout_height="200dp" android:background="#f00" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <android.support.constraint.Guideline android:id="@+id/guideline_1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" app:layout_constraintGuide_percent="0.26" /> <View android:id="@+id/view_2" android:layout_width="200dp" android:layout_height="200dp" android:background="#0f0" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toEndOf="@id/guideline_1" app:layout_constraintTop_toTopOf="parent" /> <android.support.constraint.Guideline android:id="@+id/guideline_2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" app:layout_constraintGuide_percent="0.52" /> <View android:id="@+id/view_3" android:layout_width="200dp" android:layout_height="200dp" android:background="#00f" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toEndOf="@id/guideline_2" app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout>
[ "stackoverflow", "0022277447.txt" ]
Q: indexOf within Switch I have a Javascript-based bot for a Xat chatroom which also acts as an AI. I've recently decided to redo the AI part of it due to it becoming an absolutely massive chain of else if statements, becoming nearly impossible to work with. I did some research and came up with a new idea of how to handle responses. I'll give you the code segment first: function msgSwitch(id,msgRes) { var botResponse = []; switch (msgRes) { case (msgRes.indexOf("hi") !=-1): botResponse.push("HELLO. "); case (msgRes.indexOf("how are you") !=-1): botResponse.push("I AM FINE. ") case (msgRes.indexOf("do you like pie") !=-1): botResponse.push("I CAN'T EAT. THANKS, ASSHAT. ") default: respond (botResponse); spamCount(id); break; } } The idea here is to check msgRes (the user's input) and see how many cases it matches. Then for each match, it'll push the response into the botResponse array, then at the end, it'll reply with all the messages in that array. Example User Msg: Hi! How are you? msgRes: hi how are you Bot Matches: hi > pushes HELLO. to array how are you > pushes I AM FINE. to array Bot Responds: HELLO. I AM FINE. This in turn saves me the trouble of having to write an if for each possible combination. However, after looking into it some more, I'm not sure if it's possible use indexOf inside of a switch. Does anyone know of a way around this or have a better idea for handling responses in the same manner? EDIT: To Avoid the XY Problem (To clarify my problem) I need a clean alternative to using a massive chain of else if statements. There are going to be hundreds of word segments that the bot will respond to. Without the ability for it to keep searching for matches, I'd have to write a new else if for every combination. I'm hoping for a way to have it scan through every statement for a match, then combine the response for each match together into a single string. EDIT 2: I should also add that this is being ran on Tampermonkey and not a website. A: you just need to compare to true instead of msgRes (since cases use === comparison), and use break to prevent the annoying fall-though of the switch behavior: function msgSwitch(id,msgRes) { var botResponse = []; switch (true) { case (msgRes.indexOf("hi") !=-1): botResponse.push("HELLO. "); break; case (msgRes.indexOf("how are you") !=-1): botResponse.push("I AM FINE. "); break; case (msgRes.indexOf("do you like pie") !=-1): botResponse.push("I CAN'T EAT. THANKS, ASSHAT. "); break; default: respond (botResponse); spamCount(id); break; } } This is a perfectly valid logical forking pattern, known as an "overloaded switch". A lot of folks might not realize that each case: is an expression, not just a value, so you could even put an IIFE in there if needed... A: My two cents for the gist of what you're trying to do: function msgSwitch(id, msgRes) { var seed = {'hi': 'HELLO. ', 'how are you': 'I AM FINE'}; var botResponse = []; for (var key in seed) { if (msgRes.indexOf(key) !== -1) { botResponse.push(seed[key]); } } } In my opinion it is easier to change this program as you only have to edit the seed if you have more responses in the future. You can even stash the seed on some json file and read it (via ajax) so the program does not need to be changed if there are additional messages.
[ "stackoverflow", "0043384351.txt" ]
Q: Add additional pages to wordpress yoast seo sitemap xml programatically I have a stragne question, I have been gogoleing for a while, but have found no answer. I have a Wordpress site where the Yoast Seo plugin has been installed, titles, descriptions have been added, I could also manage to change the title tag, canonical url generated by it with the wpseo- filters. The sitemap xmls are also generated fine, but I would need to add additional pages to it. We have a search page on the site, we search by a rental custom post type. Rentals can be searched by location. The search page is eg.: /rentals. We have found, that there are several sites (I can show you one in hungarian, but I'm sure you will get it) where the search results are indexed by google. Like this one: https://www.trivago.hu/?iSemThemeId=8302&iPathId=36103&sem_keyword=hotel%20p%C3%A1rizs&sem_creativeid=187836310244&sem_matchtype=b&sem_network=g&sem_device=c&sem_placement=&sem_target=&sem_adposition=1t3&sem_param1=&sem_param2=&sem_campaignid=242651542&sem_adgroupid=15360737662&sem_targetid=kwd-4821159859&sem_location=1007624&cip=3612001012&gclid=CjwKEAjwoLfHBRD_jLW93remyAQSJABIygGpWkl9XD9HJ7G8ZC7NbJ93ygmeFVxpZcici062NnMlgRoCkNfw_wcB You get to this page if you search hotels paris. If you have a look at this page, this is already a search result, search parameters are set. Now we would like to do the same with the Wordpress site. I have done a redirection for the urls: /rentals/budapest /rentals/hungary ... there are more locations. so they go to the rentals page, where I set the search parameters, I have changed the canonical urls of these pages, but I would like to add these pages to the xml sitemap also. The problem is that these page do not exist in the database. Is there a filter that I coul use to add these pages to the sitemap.xml in Yoast Seo plugin? Has anyone done a similar thing in wp? Any help is appreciated, thank you! A: I have found the answer! There is a wpseo_do_sitemap_ filter, I had to use that one. Also, This filter only created a custom sitemap, I also needed the 'wpseo_sitemap_index' filter to add my custom sitemap xml to the sitemaps index page. Detailed solution was found under this link! https://gist.github.com/mohandere/4286103ce313d0cd6549
[ "stackoverflow", "0039298714.txt" ]
Q: Javascript onclick function does not display text assigned I am trying to display the text using javascript with the onclick function. i) When I click on both button it only displays the red color , not the blue one. ii) As well as, when I click on red button 1st time then it displays the red color and if I choose the red button again then it displays the blue color. function myFunction() { if (document.getElementById("demo").value == "11") { document.getElementById("flight").innerHTML = "<p style='color:red'>Red Color</p>"; } if (document.getElementById("demo").value == "22") { document.getElementById("flight").innerHTML = "<p style='color:blue'>Blue Color</p>"; } } <button id="demo" onclick="myFunction()" value="11">Red</button> <button id="demo" onclick="myFunction()" value="22">Blue</button> <div id="flight"></div> A: As you can see in the comments, an ID should be unique. Otherwise, it will screw up your JS. I suggest you pass the current DOM element to your function, and use it like so: function myFunction(elem) { switch(elem.getAttribute('value')) { case "11": document.getElementById("flight").innerHTML = "<p style='color:red'>Red</p>"; break; case "22": document.getElementById("flight").innerHTML = "<p style='color:blue'>Blue</p>"; break; } } <button onclick="myFunction(this)" value="11">Red</button> <button onclick="myFunction(this)" value="22">Blue</button> <div id="flight"></div>
[ "stackoverflow", "0016082100.txt" ]
Q: CFNotificationCenterRemoveObserver observer In the reference I see that registering an observer to notifications is possible with a null observer pointer. However, both remove methods require a valid pointer value that is not NULL. How do I overcome that when registration is done without one? I also noticed in this answer example CFNotificationCenter usage examples? removing is done with NULL, but again, according to the reference - that is wrong . So, what is the right way to remove registration done with NULL observer? Are they not supposed to be removed (they are just left there till memory is cleared due to application exit??)??? Any explanation is much appreciated! A: There's no real penalty to sending an observer (which is a void *, and not interpreted by the system at all). The preferred use case is that if you are going to remove the observer, you should send an observer to both the initial CFNotificationCenterAddObserver call and the subsequent CFNotificationCenterRemoveObserver. By example, it appears that passing NULL to both Add and Remove actually works, but as you point out it breaks the API contract to do so, therefore I wouldn't suggest using it in shipping code. The observer itself is often just a string pointer and as long as you pass in the same pointer, you should be fine. char *myObserver="anObserver"; CFNotificationCenterAddObserver ( notificationCenter, (void*)myObserver, myCallback, NULL, NULL, CFNotificationSuspensionBehaviorDrop); and later: CFNotificationCenterRemoveObserver ( notificationCenter, (void*)myObserver, NULL, NULL); Make sure you use the same string pointer, not just the same string, as Foundation is only checking for the equality of the void*, it knows nothing about the contents. By way of further explanation, the reason for this pattern is so that you can use a single callback to handle multiple observers.
[ "english.stackexchange", "0000002882.txt" ]
Q: "License" and "licence" What is the difference between license and licence? Are both variations accepted in US and UK? A: In British English license is the verb and licence is the noun. American English uses license for both noun and verb. A: The Corpus of Contemporary American English has 10263 incidences for license and just 91 for licence. The British National Corpus, in contrast, has 4217 for licence and 333 for license. Of those, 129 were for noun uses of license. From this we can say that in the United States, the spelling license is nearly universal and licence is virtually unknown (with a ratio of more than 100 to 1 in favor of license). In Britain, the spelling licence is much more common than license, but the more common spelling is only about 13 times more common, so license is a small minority but not unknown spelling. Update Oct 15, 2014: Here we can see that British use of "license" reached a nadir in the 1950s, but has been on a steady upswing since the 1960s. According to this graph, in recent years use of "license" accounts for about 1/3 of uses of both spellings in Britain.
[ "stackoverflow", "0011843485.txt" ]
Q: Looking for an html element/property that shows a line of text when it is clicked on (not a popup) These elements/properties should be able to be highlighted when hovered over. When clicked on, they should display a small box(not a popup) of information(only 1 line needed). I thought about the link element but I don't want it to link anywhere to. This doesn't necessarily have to be done through html alone, but it is preferable. A: You may to do it with some javascript and CSS. CSS: a { padding: 2px 20px; background: #ccc; } a:hover{ background: red; color: white; text-decoration:none; } #msg { display: none; padding: 0 15px; background: #ccc; }​ HTML: <div> <a href="#" onclick="showinfo('msg')">Click Me</a> <span id="msg">Do you want this?</span> </div>​ Javascript: function showinfo(id){ var elemID = document.getElementById(id); if( elemID.style.display == "inline-block") { elemID.style.display = "none"; } else { elemID.style.display = "inline-block"; } }​ SEE DEMO
[ "stackoverflow", "0039269634.txt" ]
Q: OpenImaj - recognize given face which is not taken from the face database The OpenImaj Tutorial for face analysis shows how to do face recognition using some test images from the face database - http://openimaj.org/tutorial/eigenfaces.html How a new given image which is not from the face db can be recognized? Can you give an example? Thanks. A: Simple - just modify the code in the tutorial so that instead of looping over all the faces in the database, it just takes in an image you specify and searches with that: FImage face = ...; //you load the face you want to search with here DoubleFV testFeature = eigen.extractFeature(face); String bestPerson = null; double minDistance = Double.MAX_VALUE; for (final String person : features.keySet()) { for (final DoubleFV fv : features.get(person)) { double distance = fv.compare(testFeature, DoubleFVComparison.EUCLIDEAN); if (distance < minDistance) { minDistance = distance; bestPerson = person; } } } System.out.println("Best Guess: " + bestPerson);
[ "stackoverflow", "0015093023.txt" ]
Q: Drupal very slow in Vagrant environment I've begun migrating a lot of our development environments to Vagrant. So far, this has been great for almost everything, but our first Drupal migration is unusable. It's unbelievably slow. Our Wordpress, CakePHP and Node.js sites all perform very adequately or better, but not Drupal. This think is just awful. The box is a Veewee-created Ubuntu 12.04 64bit machine. It's the same base box we use for all of our web-based projects so nothing unique there. In my sites directory, I have a canonical directory (sites/my-site/) with all of the site resources and a symlink to that canonical directory with the domain name (sites/dev.mysite.com -> /vagrant/www/sites/my-site) that is evidently required for some module that the team is using. This is a mixed Windows/OSX dev team and it's slow across both platforms. The only semi-unconventional snippet from my Vagrantfile is this: config.vm.forward_port 80, 8080 config.vm.share_folder( "v-root", "/vagrant", ".", :extra => 'dmode=777,fmode=777' ) # Allows symlinks to the host directory. config.vm.customize ["setextradata", :id, "VBoxInternal2/SharedFoldersEnableSymlinksCreate/v-root", "1"] Vagrant::Config.run do |config| config.vm.provision :shell, :path => "provision.vm.sh" end My shell provisioner only does a couple of things: Installs drush Creates the aforementioned symlink to the canonical site directory Writes out an Nginx server block If necessary, creates a settings.php file. Is there anything I can do to improve performance? Like, a lot? UPDATE I've narrowed this down to a point where it looks like the issue is the remote database. To compare apples to apples with no project baggage, I downloaded a fresh copy of Drupal 7.21 and performed a standard install from the Vagrant web server against 3 different databases: A new database created on the same Vagrant VM as the webserver (localhost) A new database created on the shared dev server used in the original question (dev) A new database created on an EC2 instance (tmp) Once that was done, I logged in to the fresh Drupal install and loaded the homepage (localhost:8080) 5 times. I then connected to each database and loaded the same page, the same way. What I found was that the page loaded 4-6x slower when Drupal was connected to the remote database. Remember, this is a fresh (standard) install. There is no project baggage. A: I am hit by similar problem, too. It seems that VirtualBox shared folder can be very slow for project tree with +1000 files. Switching to NFS might be the solution. A: The issue is almost certainly either skip_name_resolve (being needed in my.cnf) or VirtualBox's poor handling of shared directories with large numbers of files. Both are easy to track down with strace -c, but you may find it easier just to correct them one at a time and see which one fixes your performance issues. If you're still seeing slowness after both of these changes, let me know and we can debug it further. A: I got here via google for similar, so I'm replying in the hopes others find this useful. If you're using the precise32 vagrant box as your starting point, it's worth noting that the box by default has only 360MB of RAM. Up the ram (at least in Vagrant V2 with VirtualBox) like so config.vm.provider :virtualbox do |vb| vb.customize ["modifyvm", :id, "--memory", "1024"] end This made Drupal much more responsive for me.
[ "stackoverflow", "0036740478.txt" ]
Q: Django: Update or Change previous saved model data I have this code in my forms.py ref_user = User.objects.get( username=form.cleaned_data['referrer'] ) user = User.objects.create_user( username=form.cleaned_data['username'] ) # Count the referrer's direct referrals ref_recruits = DirectReferral.objects.filter(referrer=ref_user).count() # Get newly created direct referral get_ref = DirectReferral.objects.get(name=user) #Check if ref_recruits is not divisible by 2 or paired if ref_recruits % 2 != 0: # Newly created direct referral is_paired is False get_ref.is_paired = False get_ref.save() else: # Newly created direct referral is_paired is True get_ref.is_paired = True get_ref.save() # But I also want to update the previous is_paired to True # of the same referrer How do I update the previous is_paired to True of the same referrer? Check image below to have a better understanding of what I mean. I hope you understand. models.py(requested) class DirectReferral(models.Model): name = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True) referrer = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="direct_referrals") timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) is_paired = models.NullBooleanField(null=False) A: I think you should refactor your code. As per your implementation, I believe name field for `DirectReferral' will be unique. ref_user = User.objects.get( username=form.cleaned_data['referrer'] ) user = User.objects.create_user( username=form.cleaned_data['username'] ) # Count the referrer's direct referrals ref_recruits = DirectReferral.objects.filter(referrer=ref_user).count() # Get newly created direct referral get_ref = DirectReferral.objects.get(name=user) #Check if ref_recruits is not divisible by 2 or paired if ref_recruits % 2 == 0: get_ref.is_paired = True DirectReferral.objects.filter(referrer=ref_user, is_paired=False).update(is_paired=True) else: get_ref.is_paired = False get_ref.save()
[ "mathoverflow", "0000124484.txt" ]
Q: Stokes theorem for manifolds without orientation? In textbooks Stokes' theorem is usually formulated for orientable manifolds (at least I couldn't find any version not using orientability). Is Stokes theorem: $\int\limits_{M}d\omega=\int\limits_{\partial M} \omega$ also true for non-orientable manifolds? Are there any references, you can tell me? Regards. A: This is just more information on Jose's comment. Look at section 10 (pages 122 to 128) in: Peter W. Michor: Topics in Differential Geometry. Graduate Studies in Mathematics, Vol. 93 American Mathematical Society, Providence, 2008. (pdf) On the orientable double cover $\tilde M$ of $M$ (given by $\lbrace \xi\in Or(M): |\xi|=1\rbrace$ using 10.7) there are two kinds differential forms, namely the eigenspaces for $\pm 1$ under the action of the covering map. These are the "formes paire" and "formes impaire" on $M$ in the book of de Rham; for these you formulate Stokes' theorem directly on $M$, and it is the same as the Stokes' theorem on $\tilde M$. Note that you also have the corresponding double cover of the boundary. A: This is mostly an elaboration on Peter Michor's answer, but I think more deserves to be said, including a major caveat. A reference which treats this material more fully and explicitly than his book cited above is Theodore Frankel's The Geometry of Physics. From the "double-cover" perspective, I believe the usual differential forms are the ones in the $+1$ eigenspace of the covering map, which de Rahm calls paire ("even"). The ones in the $-1$ eigenspace ("odd forms" impaire) are called "pseudo-forms" by Frankel, although Frankel doesn't explicitly work in terms of the double cover. See section 2.8.e of Frankel for his definitions and section 3.4 for a discussion of integration, including a statement of Stokes' theorem for odd forms. (I had trouble finding such a statement in Michor's book...) The caveat I want to mention is that like the familiar even forms, odd forms do require some orientation data to integrate over a submanifold (as in Stokes' Theorem). It's just different data. Whereas an even form is integrated over an oriented submanifold, an odd form is integrated over a transverse-oriented submanifold. That is, if $N^k \subset M^n$ and $\omega$ is an even $k$-form, then you need to choose an orientation on the tangent bundle of $N$ before you can integrate $\omega$ over $N$. If $\omega$ is an odd form, then you need to choose an orientation on $N$'s normal bundle in order to integrate (a fair number of arbitrary need to be made to specify such a thing, including, at least locally, a choice of normal bundle, but they turn out not to matter). This treatment of orientation means that, for example, an odd $(n-1)$ form on an $n$-manifold can naturally represent a "flux": integrate over a hypersurface to determine the rate of transport through that hypersurface per unit time -- the transverse orientation tells you which direction of flow you consider to be "positive". But the case that comes out most naturally is when you have an odd $n$-form on an $n$-manifold. In this case, when you integrate over an $n$-submanifold, the normal bundle is 0-dimensional, so there is a canonical choice of transverse orientation (between "$+$" and "$-$", just take "$+$"!), so no orientation data is really needed to integrate. This is analogous to the fact that no orientation data is needed to integrate an even 0-form over a 0-submanifold (i.e. to add up the values of a function at a set of points!). The upshot is that a volume form or other nice measure is naturally an odd form, because the volume/measure of a submanifold certainly doesn't depend on any choice of orientation. Whereas when you try to treat volume as integration over an even form, you have to fix an orientation arbitrarily.
[ "stackoverflow", "0013705973.txt" ]
Q: How to draw the multiple lines with different color and undo,redo the paths in android? I want to draw multiple lines on the view with different colors and undo,redo the paths in android. i use the bitmap paint option, each paths has a unique color but undo,redo is not working.. Here is my code of bitmappaint: public MyView(Context context, Object object) { super(context); setFocusable(true); setFocusableInTouchMode(true); mPath = new Path(); mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setColor(0xFFFFFF00); mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeJoin(Paint.Join.ROUND); mPaint.setStrokeCap(Paint.Cap.ROUND); mPaint.setStrokeWidth(3); mBitmap = Bitmap.createBitmap(320, 480, Bitmap.Config.ARGB_8888); mCanvas = new Canvas(mBitmap); } protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); } protected void onDraw(Canvas canvas) { canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint); for (Path p : paths) { canvas.drawPath(p, mPaint); } canvas.drawPath(mPath, mPaint); } public boolean onTouchEvent(MotionEvent event) { float x = event.getX(); float y = event.getY(); int action = event.getAction(); int action1=event.getAction(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: undonePaths.clear(); mPath.reset(); mPath.moveTo(x, y); mX = x; mY = y; startPoint = new PointF(event.getX(), event.getY()); endPoint = new PointF(); invalidate(); // isDrawing = true; break; case MotionEvent.ACTION_MOVE: float dx = Math.abs(x - mX); System.out.println("action move"); float dy = Math.abs(y - mY); if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) { // currentDrawingPath.path.quadTo(mX,mY,(x + mX)/2, (y + mY)/2); } mX = x; mY = y; endPoint.x = event.getX(); endPoint.y = event.getY(); isDrawing = true; invalidate(); break; case MotionEvent.ACTION_UP: mPath.lineTo(mX, mY); paths.add(mPath); mPath = new Path(); // mCanvas.drawPath(mPath, ppaint); endPoint.x = event.getX(); endPoint.y = event.getY(); isDrawing = false; invalidate(); break; default: break; } } ![output of bitmappaint canvas][1] [1]: http://i.stack.imgur.com/9aQvE.png without bitmap using i faced the color problem if i select a blue color for a path means all the previous paths will be changed to blue color; Here is my code protected void onDraw(Canvas canvas) { canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint); for (Path p : paths) { canvas.drawPath(p, mPaint); } canvas.drawPath(mPath, mPaint); } ![output of without bitmap using canvas drawing][2] [2]: http://i.stack.imgur.com/eDp5Y.png pls help me to draw multiple paths with different color of unique paths in android. Thanks in advancde........ A: When you handle the MotionEvent.ACTION_UP : you need to save the color used to draw the path with something like this : case MotionEvent.ACTION_UP: paths.add(mPath); colorsMap.put(mPath,selectedColor); // store the color of mPath ... Before drawing a path, you need to set the paint color: protected void onDraw(Canvas canvas) { canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint); for (Path p : paths) { mPaint.setColor(colorsMap.get(p)); canvas.drawPath(p, mPaint); } mPaint.setColor(selectedColor); canvas.drawPath(mPath, mPaint); } And the colorsMap is a simple instance variable: private Map<Path, Integer> colorsMap = new HashMap<Path, Integer>(); To implement the Undo/Redo feature, you just have to remove the last element from paths (and store it in a undoneList so that on redo can restore it). see Android Canvas Redo and Undo Operation
[ "stackoverflow", "0007821555.txt" ]
Q: Integrate nonparametric curve in R Just a warning, I started using R a day ago...my apologies if anything seems idiotically simple. Right now im trying to have R take in a .txt file with acelerometer data of an impact and calculate a Head injury criterion test for it. The HIC test requires that curve from the data be integrated on a certain interval. The equation is at the link below...i tried to insert it here as an image but it would not let me. Apparently i need some reputation points before it'll let me do that. a(t) is the aceleration curve. So far i have not had an issue generating a suitable curve in R to match the data. The loess function worked quite well, and is exactly the kind of thing i was looking for...i just have no idea how to integrate it. As far as i can tell, loess is a non-parametric regression so there is no way to determine the equation of the curve iteslf. Is there a way to integrate it though? If not, is there another way to acomplish this task using a different function? Any help or insighful comments would be very much appreciated. Thanks in advance, Wes One more question though James, how can i just get the number without the text and error when using the integrate() function? A: You can use the predict function on your loess model to create a function to use with integrate. # using the inbuilt dataset "pressure" plot(pressure,type="l") # create loess object and prediction function l <- loess(pressure~temperature,pressure) f <- function(x) predict(l,newdata=x) # perform integration integrate(f,0,360) 40176.5 with absolute error < 4.6 And to extract the value alone: integrate(f,0,360)$value [1] 40176.5
[ "stackoverflow", "0012534278.txt" ]
Q: lookup usernames I am working on creating a page for each user, how do i lookup a username in my django user model views.py def user_page(request,user): user = User.objects.filter(user =user.username) return render_to_response('user_page.html',"user":user,context_instance=RequestContext(request)) A: from django.contrib.auth.models import User from django.shortcuts import get_object_or_404 def user_page(request, username): user = get_object_or_404(User, username=username) return render_to_response('user_page.html',{"user":user},context_instance=RequestContext(request))
[ "stackoverflow", "0010494903.txt" ]
Q: SQL Server : output inserted.Id join with inserted temporary user defined table I got a problem.. I use a stored procedure with user defined table (@logs). I insert it to other database table (InOutLog), with command OUTPUT into, where I get inserted id. The main problem is what I want to insert my user defined table to 2 database tables: InOutLog, where I get inserted id and.. Want to take inserted id and other defined table values (l.Title+';'+l.Comment) and insert it to table MessageLog But I can't access l.Title+';'+l.Comment. Also I can not find any simple solution to merge my user defined table and temporary table with inserted id values.. Here is the code: insert into InOutLog(NFCId, UserID, DateEnter, DateLeave, ProjectId, Status, ServerDateEnter) output inserted.Id, inserted.DateLeave, l.Title+';'+l.Comment, inserted.UserId into MessageLog(TagLogId, MessageDate, Answer, UserId) select l.NFCTagId, l.UserId, l.ScanDate, l.StartDate, @projectID, 0, getdate() from @logs l Any suggestions? What's the best practise in this case? A: Use MERGE not INSERT. This allows you to access the source tables in the OUTPUT clause for INSERTions. Example: http://sqlblog.com/blogs/jamie_thomson/archive/2010/01/06/merge-and-output-the-swiss-army-knife-of-t-sql.aspx
[ "stackoverflow", "0009849984.txt" ]
Q: Public functions vs Functions in CodeIgniter In PHP, What is the difference between declaring methods inside class like public function VS function For example: public function contact() { $data['header'] = "Contact"; $this->load->view('admin/admin_contact', $data); } VS function contact() { $data['header'] = "Contact"; $this->load->view('admin/admin_contact', $data); } Is it better practice to use public function or function and why? A: According to PHP.net Class methods may be defined as public, private, or protected. Methods declared without any explicit visibility keyword are defined as public. for best practice, i suggest using visibility keywords (esp when using higher versions of PHP). it prevents confusion (like the one you are in now) and promotes standard practice in coding. A: Methods declared with any explicit visibility keyword is best practice. It looks and feels better and it doesn't confuse people. Most PHP5 coding conventions (e.g. Zend, Symfony...) require the public keyword, so it's familiar. It means that variable and method declarations use the same syntax. It's more explicit and forces developers to consider their method visibility. A: There is no difference between these two. Both are the same. In codeigniter both have same meaning and can be called by using standard URI tags unless you give a '_' in front of your function name _fname() will not be called
[ "gaming.stackexchange", "0000136295.txt" ]
Q: What are the keyboard keys for regaining stamina in the chocobo race? In the PlayStation version of Final Fantasy VII, you could hold R1 and R2 to slowly restore stamina during races. What are the appropriate keys in the Windows version? A: Basically you need to use the keys that the L1 and R1 of a PS controller would have used according to the links in the default case the following should work given you haven't changed the keys yet. Try Page Down and End Methods to Change Controls (either one works) Access the in-game menu and navigate to config. You can edit the ff7inputcfg file which is located in your game directory. Source for Controls: http://www.finalfantasy7pc.com/game-info/game-controls/ Sources for Racing: http://www.neoseeker.com/forums/1169/t1485203-final-fantasy-7-chocobo-racing/ http://steamcommunity.com/app/39140/discussions/0/846959362240484250/ http://www.gamefaqs.com/pc/130791-final-fantasy-vii/answers?qid=351187
[ "stackoverflow", "0025926991.txt" ]
Q: How to integrate Azure AD Authentication with a Web API service whose service reference has been added automatically? I have an ASP.NET MVC website in which I have added a "Web API 2 OData Controller with Actions, using Entity Framework". This is the 1st set of code that is auto-generated. I am calling this web API from a native client. I have added a reference to the Web API service through, Right Click, Add References. This is the 2nd bit that is auto-generated. I've configured Azure AD authentication at the client side. This is working. What I want to do now is: setup authentication for each Web API call based on the user who logged in from the client. So the client's access token needs to be passed from the client to the Web API, and this token should be used to authenticate further. Note that a lot of the code is auto-generated. So the additions to code should have minimal effect on regeneration of the code, if possible. Later on the Web API will use the user information to filter data based on his identity, and use role based identity as well. Any pointers on how to start with this? I feel that all the various pieces are available, but how to gather them into a single solution is just out of grasp. A: The container that is part of the auto-generated solution is where we need to pass the token. Here's the code: autogenContainer.BuildingRequest += (sender, args) => { args.Headers.Add("Authorization", "Bearer " + access token retrieved from Azure); };
[ "math.stackexchange", "0001008360.txt" ]
Q: Help to translate this theorem to a more accessible language I'm trying to understand the chapter 2 of this article. I'm stuck in this part: The theorem he mentioned is from this book and it is the following: I need help to translate this theorem to a weaker one so that I could understand these comments in the article. My only background in Algebraic Geometry is Fulton's algebraic curves book. Thanks. A: The map $$ \varphi: V \otimes H^0(C,\mathscr{F}) \to H^0(C, \mathscr{F} \otimes L) $$ is just the map that sends $s \otimes t$ to the corresponding section of $\mathscr{F} \otimes L$ where $s$ is a section of $L$ contained in $V$ and $t$ is a section of $\mathscr{F}$. This is usually just written as a product $st$. Now we get an exact sequence $$ 0 \to \ker \varphi \to V \otimes H^0(C, \mathscr{F}) \to \operatorname{im}\varphi \to H^0(C, \mathscr{F} \otimes L) \to H^0(C,\mathscr{F} \otimes L)/\operatorname{im}\varphi \to 0 $$ By the definition of the map the image is just $$ H^0(C,\mathscr{F})s_1 + H^0(C,\mathscr{F})s_2 $$ and by the base-point-free pencil trick, $$ \ker \varphi = H^0(C, \mathscr{F} \otimes L^{-1}(B)). $$ So taking dimensions of the terms in the exact sequence, we have $$ \operatorname{codim} (H^0(C,\mathscr{F})s_1 + H^0(C, \mathscr{F})s_2) = $$ $$ \dim H^0(C,\mathscr{F} \otimes L) - \dim (V \otimes H^0(C, \mathscr{F})) + \dim H^0(C, \mathscr{F} \otimes L^{-1}(B)). $$ since $V$ is two dimensional, $\dim (V \otimes H^0(C, \mathscr{F})) = 2 \dim H^0(C, \mathscr{F})$ so we get $$ \operatorname{codim} (H^0(C, \mathscr{F})s_1 + H^0(C, \mathscr{F})s_2) = $$ $$ h^0(C, \mathscr{F} \otimes L) - 2 h^0(C, \mathscr{F}) + h^0(C, \mathscr{F} \otimes L^{-1}(B)) $$ where $h^0(\ldots) = \dim H^0(\ldots)$. Now this is applied to the special case $\mathscr{F} = \Omega^{n-1}(F - D)$ and $L = \Omega^1(D)$ where $D := \inf\{\operatorname{div}(\omega_g),\operatorname{div}(\omega_{g-1})\}$. By the definition of $D$, we have that $\omega_g, \omega_{g-1} \in H^0(C,L)$ and so we take $V$ to be the span of these two. Then we have that $\mathscr{F} \otimes L = \Omega^{n}(F - D + D) = \Omega^n(F)$ since the product of a one-form and an $n-1$ form is an $n$-form, and if $\operatorname{div}(s_1) \geq F - D$ and $\operatorname{div}(s_2) \geq D$, then $\operatorname{div}(s_1 s_2) = \operatorname{div}(s_1) + \operatorname{div}(s_2) \geq F - D + D = F$. And so the codimension of $\Omega^{n-1}(F - D)\omega_{g-1} + \Omega^{n-1}(F - D)\omega_g$ in $\Omega^{n}(F)$ is equal to $$ \dim \Omega^n(F) - 2 \dim \Omega^{n-1}(F - D) + \dim \Omega^{n-1}(F - D) \otimes L^{-1}(B) $$ by the statement on dimensions above (and some abuse of notation). Now $B = D$ by the definition of $D$ as the infimum of the divisors of $w_g, w_{g-1}$ and $$ L^{-1}(D) = (\Omega^1(D) \otimes \mathcal{O}(D))^{-1} = (\Omega^1 \otimes \mathcal{O}(2D))^{-1} = (\Omega^1)^{-1} \otimes \mathcal{O}(-2D) $$ and so $$ \Omega^{n-1}(F - D) \otimes L^{-1}(B) = \Omega^{n-1}(F - D) \otimes (\Omega^1)^{-1} \otimes \mathcal{O}(-2D) = \Omega^{n-2}(F - 2D) $$ as giving the required formula. Now all of this stuff about differentials $\Omega^n(F)$ etc seem to be in Fulton so I hope that makes sense. The only thing I don't see there is the base locus, so the base locus $B$ of sections $s_1$ and $s_2$ is exactly the divisors where $s_1$ and $s_2$ both vanish. In the case of $\omega_g, \omega_{g-1}$ above, this is the locus where both differentials have order of vanishing greater than $0$ and this is exactly $D$ as defined.
[ "stackoverflow", "0024969444.txt" ]
Q: win32com.client: AttributeError: wdHeaderFooterPrimary and AttributeError: wdAlignParagraphCenter We prepare the following python script to display pictures in word tables. import matplotlib.pyplot as plt import pylab import win32com.client as win32 import os # Skip picture making parts #Generate word file #Create and formating wordapp = win32.Dispatch("Word.Application") #create a word application object wordapp.Visible = 1 # hide the word application doc=wordapp.Documents.Add() # create a new application doc.PageSetup.RightMargin = 20 doc.PageSetup.LeftMargin = 20 doc.PageSetup.Orientation = 1 # a4 paper size: 595x842 doc.PageSetup.PageWidth = 595 doc.PageSetup.PageHeight = 842 header_range= doc.Sections(1).Headers(win32.constants.wdHeaderFooterPrimary).Range header_range.ParagraphFormat.Alignment = win32.constants.wdAlignParagraphCenter header_range.Font.Bold = True header_range.Font.Size = 12 header_range.Text = "" #Create and formating #insert table total_column = 3 total_row = len(compound_name)+1 rng = doc.Range(0,0) rng.ParagraphFormat.Alignment = win32.constants.wdAlignParagraphCenter table = doc.Tables.Add(rng,total_row, total_column) table.Borders.Enable = True if total_column > 1: table.Columns.DistributeWidth() #table title table.Cell(1,1).Range.InsertAfter("title1") table.Cell(1,2).Range.InsertAfter("title2") table.Cell(1,3).Range.InsertAfter("title3") #collect image frame_max_width= 167 # the maximum width of a picture frame_max_height= 125 # the maximum height of a picture # for index, filename in enumerate(filenames): # loop through all the files and folders for adding pictures if os.path.isfile(os.path.join(os.path.abspath("."), filename)): # check whether the current object is a file or not if filename[len(filename)-3: len(filename)].upper() == 'PNG': # check whether the current object is a JPG file cell_column= index % total_column + 1 cell_row = index / total_column + 2 cell_range= table.Cell(cell_row, cell_column).Range cell_range.ParagraphFormat.LineSpacingRule = win32.constants.wdLineSpaceSingle cell_range.ParagraphFormat.SpaceBefore = 0 cell_range.ParagraphFormat.SpaceAfter = 3 #this is where we are going to insert the images current_pic = cell_range.InlineShapes.AddPicture(os.path.join(os.path.abspath("."), filename)) doc.SaveAs(os.path.join(os.path.abspath("."),"final.doc")) doc.Close() However, when running it, the following error will pop out due to this line header_range= doc.Sections(1).Headers(win32.constants.wdHeaderFooterPrimary).Range Here is the error message: Traceback (most recent call last): File "Drawing.py", line 99, in <module> header_range= doc.Sections(1).Headers(win32.constants.wdHeaderFooterPrimary).Range File "C:\Python27\Lib\site-packages\win32com\client\__init__.py", line 170, in __getattr__ raise AttributeError(a) AttributeError: wdHeaderFooterPrimary It looks to me there are something wrong with "wdHeaderFooterPrimary". So I just mute the following lines and run again. #header_range= doc.Sections(1).Headers(win32.constants.wdHeaderFooterPrimary).Range #header_range.ParagraphFormat.Alignment = win32.constants.wdAlignParagraphCenter #header_range.Font.Bold = True #header_range.Font.Size = 12 #header_range.Text = "" Another error message will show up: Traceback (most recent call last): File "C:Drawing.py", line 114, in <module> rng.ParagraphFormat.Alignment = win32.constants.wdAlignParagraphCenter File "C:\Python27\Lib\site-packages\win32com\client\__init__.py", line 170, in __getattr__ raise AttributeError(a) AttributeError: wdAlignParagraphCenter I am running python 2.7.6 in 64 bit windows 7. The matplotlib.pyplot and pylab are installed. The win32com.client is 2.7.6 32 bit and build 219. The Office are 64 bits but the download site review says win32 32bit should work fine in office 64 bits/windows 7 64 bits (http://sourceforge.net/projects/pywin32/?source=navbar). May I know if any guru might have any comment/solution? Thanks! A: The constants are available only if static dispatching is available. The requires either using EnsureDispatch (instead of Dispatch) or generating the type library via makepy.py or genclient (which EnsureDispatch does for you). So I would try using the EnsureDispatch. Note: it is in win32com.client.gencache: xl = win32com.client.gencache.EnsureDispatch ("Word.Application")
[ "stackoverflow", "0051182535.txt" ]
Q: CSS dropdown navigation not displaying - toggle:checked This question has been asked before but I have searched and searched but because I am not so familiar with some of the terminology I am struggling to find an answer (I hope it's not too difficult). I am trying to create a navbar/toggle/hamburger responsive dropdown menu using purely CSS. However, when I click on the hamburger to reveal the dropdown nothing happens. Here is my CSS $navigation-height: 72px; section.navigation { width: 100%; margin-top: 0px; border-bottom: $base-border; display: flex; flex-flow: row nowrap; align-items: center; justify-content: flex-start; height: $navigation-height; figure { max-width: 25%; margin-left: $base-spacing; img#logo { max-height: 42px; display: block; } @media screen and (max-width: 700px) { max-width: 50%; } } nav { margin-left: auto; margin-right: $small-spacing; a { margin: 0 $small-spacing; text-decoration: none; } } } label { font-size: 30px; display: none; float: right; margin-right: 2%; color: $blue; } #toggle { display: none; } @media screen and (max-width: 500px) { label { display: block; cursor: pointer; } .menu { text-align: center; width: 100%; visibility: collapse; } .menu a { display: block; border-bottom: 1px solid black; line-height: 30px; } #toggle:checked ~ * .menu { display: block; } } And my html.erb is: <section class="navigation"> <figure> <%= link_to root_path do %> <%= image_tag 'logo.png', id: 'logo' %> <% end %> </figure> <nav class="menu"> <%= link_to 'FAQs', faqs_path %> <%= link_to 'Home', root_path %> <% if user_signed_in? %> <%= link_to 'Logout', destroy_user_session_path, method: :delete %> <% else %> <%= link_to 'Login', new_user_session_path %> <% end %> <% if current_admin %> <%= link_to 'Logout Admin', destroy_admin_session_path, method: :delete %> <% end %> </nav> <label for="toggle">HAMBURGER ICON</label> <input type="checkbox" id="toggle"></input> </section> I am 99% sure the problem lies with: #toggle:checked ~ * .menu { display: block; } But am not sure how/why idea! Thank you in advance. A: you need to move the input field to be a sibling before the menu and update your css selector to #toggle:checked ~ .menu. The ~ selector tells the class to look for subsequent siblings - and seeing that your #toggle element is at the end of your code, it is finding none. In addition the * selector is telling your code to look for any element following the input and within that element, look for a .menu class, which is why it should be removed. https://codepen.io/anon/pen/QxRvGv
[ "stackoverflow", "0037000552.txt" ]
Q: $.ajax JSON retrieval fails - JSP I'm trying to receive JSON Array from Servlet and add data to a table. But JSON or text don't come to jsp. I've try many things. Here is my JSP <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Search a User</title> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#search1').click(function () { var searchdata = $("#searchword").val(); $.ajax({ type: "GET", url: "Search", //this is my servlet data: {searchword :searchdata }, success: function(data){ alert(data); } }); }); }); </script> </head> <body> <form method="post" class="form-horizontal"> <fieldset> <div class="form-group"> <label class="col-md-4 control-label" for="searchword">Search a User</label> <div class="col-md-5"> <input id="searchword" type="text" placeholder="Add User's name" class="form-control input-md" required=""> </div> </div> <div class="form-group"> <label class="col-md-4 control-label" for=""></label> <div class="col-md-3"> <button id="search1" class="btn btn-block btn-success">Search</button> </div> </div> </fieldset> </form> </body> </html> Here I just try to make sure the success function is working. But alert won't work. I added Alerts without string we retrieve from the Servlet for demo propose. But they also didn't work. I'm pretty sure my fault is on the JSP side because I can see the JSON Array and Servlet retrieving the search word in the log4j logs. But for Make sure that I'll add the servlet also here. import com.google.gson.JsonArray; import com.google.gson.JsonObject; import hsenid.DBConnector; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class Search extends HttpServlet { private static final Logger logger = LogManager.getLogger(Search.class); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("application/json"); PrintWriter out = resp.getWriter(); PreparedStatement preparedStatement = null; ResultSet resultSet = null; String username = req.getParameter("searchword"); DBConnector dbpool = (DBConnector) getServletContext().getAttribute("DBConnection"); JsonArray jsonArray = new JsonArray(); logger.info(username); try { Connection myConn = dbpool.getConn(); String likeQuery = "Select * from userdetails WHERE username LIKE ?"; preparedStatement = myConn.prepareStatement(likeQuery); preparedStatement.setString(1, "%" + username + "%"); resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("firstName", resultSet.getString("fname")); jsonObject.addProperty("lastName", resultSet.getString("lname")); jsonObject.addProperty("dob", resultSet.getString("dob")); jsonObject.addProperty("country", resultSet.getString("country")); jsonObject.addProperty("email", resultSet.getString("email")); jsonObject.addProperty("mobile", resultSet.getString("mnumber")); jsonObject.addProperty("username", resultSet.getString("username")); jsonArray.add(jsonObject); } logger.info("JSON ARRAY Created"); logger.info(jsonArray.toString()); resp.getWriter().write(jsonArray.toString()); out.println(jsonArray); } catch (SQLException e) { logger.error(e.getMessage()); } } } A: You are writing the result JSON array twice, so the content is not a valid JSON response, and JQuery will not be able to parse it: resp.getWriter().write(jsonArray.toString()); out.println(jsonArray); // out is resp.getWriter() So simply remove the second line. To better diagnose such errors you should also add an error callback to your $.ajax call and look at the developer console if it shows any errors.
[ "stackoverflow", "0038030617.txt" ]
Q: How to know from which of 2 distributions the sample is drawn in R? I am writing a pop simulation using R. The "growth" parameter in this simulation is sampled with probability p from two normal distributions with different means and sd. The code I am using to do so is the following: R_0 <- sample(c(sample(rnorm(5000, mean = 3.5, sd = 0.7), 1),sample(rnorm(5000, mean = 1.5, sd = 0.3), 1)),1, prob = c(1 - p, p)) The two distributions correspond to a benign and stressful environment (B and S for simplicity). My problem is that later in the code I need to modify the growth rate R_0 according to a fixed quantity. This quantity depends on whether the R_0 coefficient was sampled from the B or the S environments. Is there a way to know from which of the two distributions R_0 is sampled? I guess I could use and if else statement but I am not quite sure how to initialize it. Thanks in advance. A: First save the first sampling result: set.seed(123) p <- .5 my_sample <- c(sample(rnorm(5000, mean = 3.5, sd = 0.7), 1),sample(rnorm(5000, mean = 1.5, sd = 0.3), 1)) R_0 <- sample(my_sample,1, prob = c(1 - p, p)) Then you can check from which (first/A or second/B distribution the sample came from): my_sample == R_0 [1] FALSE TRUE There is a tiny probability that the two samples values are identical. So you could also use a flag which tellst you from which sample the final sample came from: p <- .5 set.seed(123) sample(c(paste("A", sample(rnorm(5000, mean = 3.5, sd = 0.7), 1), sep = " "), paste("B", sample(rnorm(5000, mean = 1.5, sd = 0.3), 1), sep = " ")),1, prob = c(1 - p, p)) [1] "B 1.45624041440113"
[ "stackoverflow", "0013148152.txt" ]
Q: display:table-cell weird behaviour on adding image I have columns with display:table-cell (to make sure they are of same height.) There is some text inside of each of the column. When I add an image to one of the cells (on top of the text), text in ALL columns is pushed down, not just in the column with the image. Is there a way to prevent text in other columns from moving? <div class = 'column'> <h1>Some text</h1> </div> <div class = 'column'> <img src='image.png'/> <h1>Some other text</h1> </div> .column {display:table-cell} A: This is untested, but have you tried .column { display: table-cell; vertical-align: top; } Honestly, I'd avoid using display: table-cell. Set the height property with css instead.
[ "stackoverflow", "0023311101.txt" ]
Q: Abnormal behaviour of free() in C Note: I apologise if the question is too long or does not fit the format for SO. If not on the proper site, pls suggest for which StackExchange sites the question would be more appropriate. I have been following this tutorial about AVL Trees and decided to add a BFS search for the tree. This is my implementation (parts of it) - void *dequeue(struct q *q_instance) { struct q_node *temp; void *jsw_node_ptr; if (q_instance->beg == NULL) return NULL; temp = q_instance->beg; jsw_node_ptr = temp->node; if (q_instance->beg == q_instance->end) q_instance->beg = q_instance->end = NULL; else q_instance->beg = q_instance->beg->next; free(temp); return jsw_node_ptr; } void bfs_order(struct jsw_node *root) { struct q *q_instance = NULL; struct jsw_node *temp; if (root == NULL) return; q_instance = init_q(); enqueue(q_instance, root); while (q_instance->beg) { temp = /*(struct jsw_node *)*/dequeue(q_instance); fprintf(stdout, "%d\t", temp->data); if (temp->link[0]) enqueue(q_instance, temp->link[0]); if (temp->link[1]) enqueue(q_instance, temp->link[1]); free(temp); /* Here is my confusion */ } free(q_instance); } Now, even if I free() the variable returned from the function dequeue() it causes me no harm. However, the value returned has been assigned dynamically in some other function. How doesn't it cause any problem with my tree? Isn't free() supposed to free the allocated space? A: I'm using the C99 standard as an example here, which may or may not be what you're using. It should apply, though. In the C99 standard, appendix J.2 lists undefined behavior. You'd want to note: An object is referred to outside of its lifetime (6.2.4). The value of a pointer to an object whose lifetime has ended is used (6.2.4). mah alluded to this above - since the behavior is undefined, you don't know what will happen. In your case, the data is probably left behind and you're now improperly accessing free'd data which just so happens to still be accurate. Give it time and more malloc's and that data will likely/eventually change out from under you. Edit: Link to the document for reference: http://www.open-std.org/jtc1/sc22/WG14/www/docs/n1256.pdf
[ "stackoverflow", "0016108471.txt" ]
Q: d3.js zooming only works when cursor over pixels of graph I am trying to implement the zooming feature on a dendrogram in the simplest, most basic way and have gotten it to work. The only issue is that the zoom event only works when the cursor is over an edge, a node, or text. How do I allow zooming when the cursor is on any portion of the svg? var margin = {top: 20, right: 120, bottom: 20, left: 120}, width = 2000 - margin.right - margin.left, height = 2000 - margin.top - margin.bottom; var x = d3.scale.linear() .domain([0, width]) .range([0, width]); var y = d3.scale.linear() .domain([0, height]) .range([height, 0]); var tree = d3.layout.tree() .size([height, width]) .separation(function(a, b) { return (a.parent == b.parent ? 1 : 2) / a.depth; }); var diagonal = d3.svg.diagonal() .projection(function(d) { return [d.y, d.x]; }); var svg = d3.select("body").append("svg") .attr("width", width + margin.right + margin.left) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")") .attr("pointer-events", "all") .append('svg:g') .call(d3.behavior.zoom() .x(x) .y(y) .scaleExtent([1,8]) .on("zoom", zoom)) .append('svg:g'); function zoom(d) { svg.attr("transform", "translate(" + d3.event.translate + ")" + " scale(" + d3.event.scale + ")"); } d3.json("flare.json", function(error, root) { var nodes = tree.nodes(root), links = tree.links(nodes); var link = svg.selectAll(".link") .data(links) .enter().append("path") .attr("class", "link") .attr("d", diagonal); var node = svg.selectAll(".node") .data(nodes) .enter().append("g") .attr("class", "node") // .attr("transform", function(d) { return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")"; }) .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; }) node.append("circle") .attr("r", 4.5); node.append("text") .attr("dy", ".31em") .attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; }) // .attr("transform", function(d) { return d.x < 180 ? "translate(8)" : "rotate(180)translate(-8)"; }) .text(function(d) { return d.name; }); }); d3.select(self.frameElement).style("height", "800px"); I have been using the following jsfiddle as a guide and cannot see where the difference is: http://jsfiddle.net/nrabinowitz/QMKm3/ Thanks in advance. A: the jsfiddle you point to in your question has this... vis.append('svg:rect') .attr('width', w) .attr('height', h) .attr('fill', 'white'); This makes sure there's always something drawn no matter where you are. You need to adjust your code accordingly. You can make it opacity 0 if you don't like white and then you won't see it, but it does need to be there.
[ "math.stackexchange", "0003093186.txt" ]
Q: Is $T:X-X$ as $T(f(x))=\int_0^{x}f(t)dt,\; \forall f\in X$.one-one onto? Let $X=C(0,1)$. Define $T:X-X$ as $T(f(x))=\int_0^{x}f(t)dt,\; \forall f\in X$. Then I have to determine if the mapping is one-one onto or not. For one-one $T(f(x))=T(g(x))$ $\Rightarrow \int_0^{x}f(t)dt=\int_0^{x}g(t)dt$ Differentiating with respect to $x$ $\Rightarrow f(x)=g(x)$. Hence one-one. For onto I am not sure, $T(f(x))=\int_0^{x}f(t)dt$ according to me means that whatever function we input, we would get something that is dependent on $x$. Hence we won't be able to get any constant functions which do belong in $X$ Is this correct? A: No, it is not onto, since, for each $f\in X$, $T(f)(0)=0$. So, for instance, the constant function $1$ does not belong to the range of $T$.
[ "stackoverflow", "0048927421.txt" ]
Q: Is making this `getIndex` optic possible? Is it possible to make an optic with the following type: getIndex :: Lens.IndexedGetter i a i I couldn't find an existing one and in unsuccessfully trying to write one I got a feeling that it can't be done, but if that's the case I would like to know the explanation for why that is. A: The index is defined arbitrarily by the getter, so there is no universal way to create one. IndexedGetter i s i is isomorphic to s -> (i, i), via the following bijection: ito :: (s -> (i, a)) -> IndexedGetter i s a iview :: IndexedGetter i s a -> s -> (i, a) forall s i. IndexedGetter i s i (the fully quantified type of getIndex) would be isomorphic to forall s i. s -> (i, i), but that's not inhabited (it would imply () -> (Void, Void) with s ~ () and i ~ Void).
[ "stackoverflow", "0019750229.txt" ]
Q: can strict mode be removed without side-effects I have a JavaScript application and I would like to know if by removing all the "use strict;" statements in the program, I would be changing its behaviour in some way. As far as I understand, strict mode does not allow some stuff and once the application has finished development, I can remove it without causing any side-effects. There is also the case of the 'this' variable mentioned here but Chrome does not seem to have implemented this behaviour till now. Thanks! A: There are a few cases where your code may be affected, though most of them are rather contrived: When passing null or undefined as the this value (in non-strict mode this is converted to the global object, not an empty object): 'use strict'; (function () { if (!this) console.log('performs proper actions'); else console.log('fail! oops...'); }).call(undefined); // 'performs proper actions' In strict mode, this would log "performs proper actions". However, this isn't the same in non-strict mode, where you'd get the failure message: (function () { if (!this) console.log('performs proper actions'); else console.log('fail! oops...'); }).call(undefined); // 'fail! oops...' It also has the same behaviour if you use null instead of undefined. If your function relies on the this value not being coerced to an object -- in non-strict mode, this is implicitly coerced to an object. For example, values such as false, 'Hello World!', NaN, Infinity and 1 will be coerced to their object wrapper equivalents (as mentioned before, null and undefined have their own behaviour). Compare what happens in strict mode: 'use strict'; (function () { console.log(this); }).call(1); // 1 ... with what happens in non-strict mode: (function () { console.log(this); }).call(1); // '[object Number]' When relying on formal parameters and the arguments object not sharing their values on assignment: function strict(a, b, c) { 'use strict'; var a = 1; var b = 2; var c = 3; var d = 4; console.log('strict: ' + (arguments[0] === a ? 'same' : 'different')); // different console.log('strict: ' + (arguments[1] === b ? 'same' : 'different')); // different console.log('strict: ' + (arguments[2] === c ? 'same' : 'different')); // different console.log('strict: ' + (arguments[3] === d ? 'same' : 'different')); // of course they're different; by design } function notStrict(a, b, c) { var a = 1; var b = 2; var c = 3; var d = 4; console.log('non-strict: ' + (arguments[0] === a ? 'same' : 'different')); // same console.log('non-strict: ' + (arguments[1] === b ? 'same' : 'different')); // same console.log('non-strict: ' + (arguments[2] === c ? 'same' : 'different')); // same console.log('non-strict: ' + (arguments[3] === d ? 'same' : 'different')); // of course they're different; by design } strict(0, 1, 2, 3); notStrict(0, 1, 2, 3); What you get is the following: strict: different strict: different strict: different strict: different non-strict: same non-strict: same non-strict: same non-strict: different If you have been using eval and you call it directly, you'll find that variables and functions declared inside the eval call are leaked to the surrounding scope, instead of being in its own scope when in strict mode. For example, a retains its original value in strict mode: 'use strict'; var a = 42; eval('var a = -Infinity;'); console.log(a); // 42 ... while in non-strict mode, it is assigned a new value: var a = 42; eval('var a = -Infinity;'); console.log(a); // -Infinity If you were relying on a new scope being created, this would be a breaking change to your code. If you deliberately use the way that a ReferenceError is thrown if you attempt to assign to a variable that has not been defined yet, this will affect the way your code runs: try { randomVariableThatHasntBeenDefined = 1; } catch (e) { alert('performs logic'); } The alert will not be shown in non-strict mode. All of these can be found in Annex C of the ECMAScript 5.1 Specification, which is the authoritative reference for what happens in each of these cases. While it isn't exactly easy reading, it can be useful to understand particular corner cases and why they behave as they do.
[ "stackoverflow", "0059461087.txt" ]
Q: How do I render 2 different components in 2 different router-outlets using the same angular route? I have 2 views, one for representatives and one for admins, the admin route needs to render the dashboard in the main section as well as the admin sidebar in the sidebar section when the /admin route is activated, I've looked at a few youtube videos and documentation for named routes on angular, no dice. here is a simpified version of the code APP-ROUTING MODULE const routes: Routes = [ { path: 'admin', canActivate: [AdminGuard], component: AdminDashComponent }, { path: 'admin', canActivate: [AdminGuard], component: AdminSidebarComponent, outlet: 'sidebar' } ]; TEMPLATE <app-banner [userIconSwitch]="auth.loggedIn" (userIconEvent)="userIconClicked()" (menuClicked)="bannerMenuClicked()"> Datrix 2.0 </app-banner> <mat-sidenav-container class="example-container"> <mat-sidenav #sidenav mode="side" [(opened)]="opened"> <img src="https://i.ibb.co/6R6pcMm/MRG-Updated-Logo.jpg" alt=""/> <br /> <div class="spacer"></div> </mat-sidenav> <router-outlet name="sidebar"></router-outlet> <mat-sidenav-content> <router-outlet></router-outlet> </mat-sidenav-content> </mat-sidenav-container> EDIT The unnamed route is working while the named route is not. There are no errors in the console. A: To route directly to both router-outlets your url should be like this: http://localhost:4200/admin(sidebar:admin) If you are routing via a routerLink attribute: <a [routerLink]="[{ outlets: { primary: ['admin'], sidebar: ['admin'] } }]"> Navigate to admin on both outlets </a> Demo on stackblitz You can find more on secondary route navigation in the angular docs The interesting part of the URL follows the ...: The admin is the primary navigation. Parentheses surround the secondary route. The secondary route consists of an outlet name (sidebar), a colon searator, and the secondary route path (admin).
[ "stackoverflow", "0048818833.txt" ]
Q: Apply Flask changes to Apache2 server without restart Everytime I make a change to Flask in any .py file on my Apache2 server, the changes don't go into effect until I run sudo service apache2 restart. This was fine when I only had one application on the server but now I have a couple and I'd like to avoid restarting the entire server whenever I want to make a Flask change. Any suggestions? A: Thanks @AllinOne: graceful restart of apache where traffic wont be impacted, using apachectl -k graceful
[ "cs.stackexchange", "0000057424.txt" ]
Q: Solving T(n) = 2T(n/2) + log n with the recurrence tree method I was solving recurrence relations. The first recurrence relation was $T(n)=2T(n/2)+n$ The solution of this one can be found by Master Theorem or the recurrence tree method. The recurrence tree would be something like this: The solution would be: $T(n)=\underbrace{n+n+n+...+n}_{\log_2{n}=k \text{ times}}=\Theta(n \log{n})$ Next I faced following problem: $T(n)=2T(n/2)+\log{n}$ My book shows that by the master theorem or even by some substitution approach, this recurrence has the solution $\Theta(n)$. It has same structure as above tree with the only difference that at each call it performs $\log{n}$ work. However I am not able to use same above approach to this problem. A: The non-recursive term of the recurrence relation is the work to merge solutions of subproblems. The level $k$ of your (binary) recurrence tree contains $2^k$ subproblems with size $\frac {n}{2^k}$, so you need at first to find the total work on the level $k$ and then to summarize this work over all the tree levels. For example, if the work is constant $C$, then the total work on the level $k$ will be $2^k \cdot C$, and the total time $T(n)$ will be given by the following sum: $$T(n) = \sum_{k=1}^{\log_2{n}}2^k C = C(2^{\log_2{n}+1}-2) = \Theta(n)$$ However, if the work logarithmically grows with the problem size you'll need to accurately compute the solution. The series would be like the following: $$T(n)=\log_2{n}+\underbrace{2\log_2(\frac {n} {2})+4\log_2(\frac {n} {4})+8\log_2(\frac {n} {8}) + ....}_{\log_2{n} \text{ times}}$$ It'll be a quite complex sum: $$T(n)=\log_2{n}+\sum_{k=1}^{\log_2{n}}2^k \log_2(\frac {n} {2^k})$$ I'll temporarily denote $m=\log_2{n}$ and simplify the summation above: $$\sum_{k=1}^{m}2^k \log_2(\frac {n} {2^k})=\\=\sum_{k=1}^{m}2^k(\log_2{n}-k)=\\=\log_2{n}\sum_{k=1}^{m}2^k-\sum_{k=1}^{m}k2^k=\\=\log_2{n}(2^{m+1}-2)-(m2^{m+1}-2^{m+1}+2)$$ Here I used a formula for the $\sum_{k=1}^{m}k2^k$ sum from the Wolfram|Alpha online symbolic algebra calculator. Then we need to replace $m$ back by $\log_2{n}$: $$T(n)=\log_2{n}+2n\log_2{n}-2\log_2{n}-2n\log_2{n}+2n-2$$ $$=2n-\log_2{n}-2=\Theta(n)$$ Q.E.D.
[ "stackoverflow", "0004074613.txt" ]
Q: Adding an array of floating points Since FPU Stack only has 8 slots, how can I add more elements. I have an array of 10 elements that I need to add. Here's what I have so far _Average proc finit mov ecx, [esp + 4] ; get the number of elements mov ebx, [esp + 8] ; get the address of the array fld REAL8 PTR [ebx] ; get first element of array fld REAL8 PTR [ebx + 8] ; get second element of array fld REAL8 PTR [ebx + 16]; this element is now at the top of the stack fld REAL8 PTR [ebx + 24] fld REAL8 PTR [ebx + 32] fld REAL8 PTR [ebx + 40] fld REAL8 PTR [ebx + 48] fld REAL8 PTR [ebx + 56] ;fld REAL8 PTR [ebx + 64] ;fld REAL8 PTR [ebx + 72] fadd fadd fadd fadd fadd fadd fadd ;fadd ;fadd fwait ; if necessary wait for the co-processor to finish ret _Average endp extern "C" double Average (int, double []); void main () { double Array1 [10] = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.0}; double Array2 [11] = {-1.1, -2.2, -3.3, -4.4, -5.5, -6.6, -7.7, -8.8, -9.9, -10.0, -11.0}; cout << "Average of Array1 is " << Average (10, Array1) << endl; cout << "Average of Array2 is " << Average (11, Array2) << endl; } A: Keep a running total instead of loading them all and then adding them all. A: There's no need to load first then add, you can just do this: fld real8 ptr [ebx] fadd real8 ptr [ebx + 8] fadd real8 ptr [ebx + 16] fadd real8 ptr [ebx + 24] and so on...
[ "stackoverflow", "0060159433.txt" ]
Q: Do Redis keys expire while being read? What will happen if key expires when some process is reading the key? Does redis allows to read the key in this scenario? what will be its behavior/return value if key is deleted when process is reading the key? A: Redis is single-threaded, so only one request is being processed at a time. If you're able to read it, the read will complete before the delete/expiration is performed. Any expiration, deletion, or alteration operations will happen sequentially after.
[ "stackoverflow", "0000909417.txt" ]
Q: The state of LINQ to NHibernate ActiveRecord Does anyone know if the LINQ to NHibernate ActiveRecord is ready for production? I'm about to start a project that has some tight modelling deadlines. ActiveRecord looks like a winner as opposed to my previous experiences with LINQ to SQL. LINQ to SQLs db first is nice, but somewhat cumbersome after a while. What makes LINQ to SQL so attractive is LINQ queries. Can the same LINQ syntax be used in ActiveRecord? What does the community think of ActiveRecord and LINQ to ActiveRecord for production? V A: Time has passed, NHibernate has a LINQ provider since 2.1 and ActiveRecord since 2.0.
[ "stackoverflow", "0029618493.txt" ]
Q: Regex for Words with Apostrophes (Java) I am trying to figure out the regex to match strings that contain only letters and apostrophes. If a string contains an apostrophe, I only want to match it if there is a letter on both sides of it. What I have so far is [a-zA-Z]+('[a-zA-Z])? I want to match strings like: a'a aa'a a'aaa But not: bb' 'bb A: You're almost there, just you need to add + after the char class present inside the optional group. ^[a-zA-Z]+('[a-zA-Z]+)?$ OR Use this if you want to deal with more than one apostrophe. ^[a-zA-Z]+(?:'[a-zA-Z]+)*$ DEMO String s = "a'a'a'a a' a'a-'bb"; String parts[] = s.split("[ -]"); for(String i:parts) { if(!i.isEmpty()) { System.out.println(i + " => " + i.matches("[a-zA-Z]+(?:'[a-zA-Z]+)*")); } } Output: a'a'a'a => true a' => false a'a => true 'bb => false
[ "academia.stackexchange", "0000011927.txt" ]
Q: Letter of recommendation from a senior lecturer Is it OK to have a letter of recommendation from a senior lecturer rather than from a full professor? The lecturer knows me well (I took two of his classes and I'm TA'ing for him) and he really likes me. Unfortunately he is not involved in research, but I should have two other letters from research profs. A: A clarification for what you need a letter would help. But, any letter that highlight academic skills should be useful. It will show your capacity to plan and carry out work so regardless of whether it is research or teaching you should get a leter. And, in each case the person most qualified to provide the letter should write it. Providing letters that describe traits that are not sought after in an application will of course not be optimal (probably not detreimental, however). You therefore need to chose your authors of letters to match the skills requested for your application purpose. A: From a reader's perspective, there are three components to a letter of recommendation: what specific skills/accomplishments/qualities does it discuss? how relevant are those skills etc. to the position or program one is being considered for? and how much credibility does the letter writer have? If someone who is not involved with research writes a letter praising your research abilities, that probably won't have a lot of credibility. If someone who is deeply involved in teaching praises your teaching, that will have a lot more credibility. If teaching is important in the PhD program you're applying to (it usually is -- and definitely if you're going to be a TA), then that should count in your favor. Since you're getting letters from two research faculty who can speak to your ability to do research, it's probably OK to get a letter from an instructor -- as long as this person speaks about things within his/her sphere of expertise, it probably won't hurt and may possibly help your application.
[ "stackoverflow", "0061518653.txt" ]
Q: How to convert JS date time to Local MySQL datetime? Best result i get is this, its simplest code i found here and save to MySQL on correct format. but i need to get GMT+7 datetime, how to add additional 7 Hours to this script? <html> <head> <title>Web Page Design</title> <script> document.writeln(new Date().toISOString().slice(0, 19).replace('T', ' ')); </script> </head> <body><br>Current Date is displayed above...</body></html>` Result : 2018-11-23 11:14:38 Current Date is displayed above... A: If you just need to add 7 hours here is an example: <html> <head> <title>Web Page Design</title> <script> var now = new Date(); now.setHours(now.getHours() + 7); document.writeln(now.toISOString().slice(0, 19).replace('T', ' ')); </script> </head> <body><br>Current Date is displayed above...</body> </html>`
[ "stackoverflow", "0048689211.txt" ]
Q: How to create a extension function to make rx subscription to flowable cleaner? I'm developing an android app using room and RxAndroid. The problem is that i'm using the next code to refresh the info in my recycler view. observable.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe{adapter.data = it} if i implement this in my activity it works like a charm. But i want to create an extension function to make the code cleaner when using flowables from the database. I create this funtion fun <T> Flowable<T>.uiSubscribe(x : (T) -> Unit) { this.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe{x} but when i tried to use it, it does nothing. It doesn't trow an error or anything. Does somebody know a way to archive this? or does somebody know why it is not working? A: You should use subscribe { x(it) } or subscribe(x). In your case subscribe{x} creates an onNext consumer which does nothing but state x in the expression.
[ "physics.stackexchange", "0000065996.txt" ]
Q: Non-existence of gluon singlets: Any recent theoretical progress? An unanswered question from last year (2012) on gluon singlets asked whether there is any theoretical explanation for the experimental absence of the ninth or colorless (singlet) gluon. This is the gluon that, if it existed, would give allow the strong force to extend far beyond the range of atomic nuclei, with catastrophic results. (Non-experts can find an explanation of the singlet gluon in the Addendum below.) Qmechanic partially answered the question with a link to this 1996 paper by J.J. Lodder, which proposed that the singlet gluon exists but is so massive that its effects are negligible. However, Lubber's massive-singlet idea seems to have gone nowhere. On an cursory search I could not find any references to the 1996 draft, even though it was written seventeen years. I also do not find Ludder's approach very plausible. Theoretically he had to do a bit of mayhem to Standard Model symmetries to come up with his model. More importantly, though, its seems unlikely that the idea holds water experimentally. The mass of the singlet gluon would have to be astronomical indeed for it not to have shown up in high-energy experimental results, especially in the post-Higgs era. So, my version of the singlet question is this: Do there exist any plausible, Standard Model compatible theories for the observed absence of the singlet gluon, other than the apparently non-starter idea that the singlet exists but is very massive? Or alternatively, have searches for the Higgs boson produced any evidence that the singlet gluon state may in fact exist and have a very large mass? Addendum for non-experts: What is a "gluon singlet" and why is it important? One way to understand the "colorless" gluon singlet is through an analogy with how photons work for the electric force. Photons interact with electrically charged electrons, but do not carry any electric charge themselves. Because they have no charge, even low-energy photons can easily escape an atom or electron and travel infinite distances. Imagine, however, what would happen if photons did carry electric charge. Such photons would have the same energetic difficulties leaving a neutral atom as an electron, dramatically altering and limiting how they behave. (I should probably mention that electrically-charged photons in one sense really do exist: They are more-or-less the $W^\pm$ particles of electroweak theory.) Curiously, the charged situation is reversed for the otherwise photon-like gluons. It is the gluons that convey the strong force, and thereby hold quarks together to form protons and neutrons, as well as secondarily binding protons and neutrons together within atomic nuclei. There are eight types of gluons instead of just one, due to there being more than two types of charge in the strong force. However, in sharp contrast to photons, all of the eight gluons normally carry strong (color) charge. The color charges of gluons cause them to interact strongly with the quarks that emit them and with each other. As in the earlier hypothetical example of how electrical charges would dramatically limit the range of photons, the presence of color charges on gluons similarly limits the distances over gluons can convey the strong force. Consequently, the strong force has almost no impact beyond the scale of atomic nuclei. However, the same mathematical model that predicts the eight color-charged gluons also predicts a ninth neutral or strong-charge-free gluon, called the singlet gluon, that has never been seen experimentally. Its lack of color would make its impact far greater than that of any of the eight other gluons. In particular, just as charge-free photons can carry the electric force far beyond the range of atoms, a charge-free gluon, if it existed, would allow the strong force to extend far beyond the range of nuclei. The repercussions would be huge. In fact, the non-existence of the singlet gluon is best demonstrated by the fact that we exist at all. My best guess (only that, since I have not seen any papers on it) is that if the colorless singlet quark really did exist, every clump of two or more atoms in the universe would melt together into an amorphous sea of quarks. Even if that is not correct, I assure you it that the consequences of the existence of singlet gluons would be... very bad indeed! That is also why I find I think the non-existence of the singlet gluon is a truly interesting question, one that probably deserves more theoretical attention than it has received over the decades since strong force theory was first codified. A: For there to be a color singlet gluon color theory would have to be a U(3) theory, not SU(3), but the great weight of experimental evidence assembled over many years supports SU(3) not U(3). In the 60's (before the Standard Model had reached maturity) a couple papers by well-known theorists appeared investigating the possibility of U(3) rather than SU(3) symmetry, but that's about it. One of the papers worked out a scheme for integer rather than fractional charge for quarks, but none of the main ideas ended up in the Std Model, which is still firmly SU(3) => no singlet gluons. In addition there is no experimental evidence for any long range component to the strong force - quite the opposite. There are plenty of unaswered questions in physics and I suspect that most theorists feel that (if they even give the ninth gluon a moment's consideration at all :-) ) there are many other topics to research that are more likely to lead to interesting new results.
[ "security.stackexchange", "0000055272.txt" ]
Q: Heartbleed and Facebook logins on (once) vulnerable sites Users have been advised to consult a list of sites affected by heartbleed and to change their passwords on those sites once they are no longer vulnerable. Facebook appears to have been unaffected; but many affected sites use Facebook logins. What should users do about affected sites where they use Facebook to log in? A: Sites that use Facebook logins should never have access to your username/password. The Facebook API connects the user directly to Facebook, authenticates the user, and then passes that authentication back to the website that you're on. If something different is going on, that website is probably behaving maliciously (think, emulating the facebook login process like a phishing site, in which case your facebook login would already be compromised). In this case, there's a fairly narrow attack surface opened up by HeartBleed... if that site's private key is compromised, and the session where you sent your user/pass to them was previously captured by the attacker, then they would be able to decrypt your communication. I'm gonna put odds on this one as pretty low. Otherwise, if they are unpatched and you send your facebook user/pass to them again, then an attacker could grab it if they are attacking reasonably close to that moment. I'm not gonna suggest that such a scenario doesn't exist anywhere on the web, but any site that you typically would want to access that uses a Facebook login never had access to your user/pass to begin with, because the API specifically protects against that scenario.
[ "stackoverflow", "0005970338.txt" ]
Q: Query performance WHERE clause contains IN (subquery) SELECT Trade.TradeId, Trade.Type, Trade.Symbol, Trade.TradeDate, SUM(TradeLine.Notional) / 1000 AS Expr1 FROM Trade INNER JOIN TradeLine ON Trade.TradeId = TradeLine.TradeId WHERE (TradeLine.Id IN (SELECT PairOffId FROM TradeLine AS TradeLine_1 WHERE (TradeDate <= '2011-05-11') GROUP BY PairOffId HAVING (SUM(Notional) <> 0))) GROUP BY Trade.TradeId, Trade.Type, Trade.Symbol, Trade.TradeDate ORDER BY Trade.Type, Trade.TradeDate I am concerned about the performance of the IN in the WHERE clause when the table starts to grow. Does anyone have a better strategy for this kind of query? The number of records returned by the subquery grows much slower than the number of records in the TradeLine table. The TradeLine table itself grows at a rate of 10/day. Thank you. EDIT: I used the idea of moving the subquery from WHERE to FROM. I voted up on all answers that contributed to this new query. SELECT Trade.TradeId, Trade.Type, Trade.Symbol, Trade.TradeDate, PairOff.Notional / 1000 AS Expr1 FROM Trade INNER JOIN TradeLine ON Trade.TradeId = TradeLine.TradeId INNER JOIN (SELECT PairOffId, SUM(Notional) AS Notional FROM TradeLine AS TradeLine_1 WHERE (TradeDate <= '2011-05-11') GROUP BY PairOffId HAVING (SUM(Notional) <> 0)) AS PairOff ON TradeLine.Id = PairOff.PairOffId ORDER BY Trade.Type, Trade.TradeDate A: The subquery in the IN clause does not depend on anything in the outer query. You can safely move it into FROM clause; a sane query plan builder would do it automatically. Also, calling EXPLAIN PLAN on any query you're going to use in production is a must. Do it and see what the DBMS thinks of the plan for this query.
[ "money.stackexchange", "0000067852.txt" ]
Q: Can a business owner be the signatory on a check made out to themselves? I am curious as to whether a business owner can sign a check made out to them personally. A: They sure can. They are two different legal entities, so why not? You can even write a check to yourself, and then deposit it back into your own account. (Not very useful, but you can). The tax implications are a very different question, as this might constitute taking money out of the company. Edit: In some countries, when the business hires someone to work for them, it is forbidden by law to do that, unless he/she is explicitly allowed to do it in his contract. The business owner himself however, can always 'allow' himself to do that.
[ "stackoverflow", "0025914360.txt" ]
Q: Scala inference on _ I'm a newbie to scala(fxnl programming), though I put _ in context in a few places like the below list.map(_ * 1) I couldn't completely understand this statement val story = (catch _) andThen (eat _) though I can infer from the calling story(new Cat, new Bird) that underscore serves as placeholders to the the argument positions, I want to understand the concept behind it. A: Statement val story = (catch _) andThen (eat _) is incorrect - because catch is keyword. But this is correct: scala> def caught(x:Int) = x + 8 caught: (x: Int)Int scala> def eat(x:Int) = x + 3 eat: (x: Int)Int scala> val story = (caught _) andThen (eat _) // story is function. story: Int => Int = <function1> scala> story(90) // You put 90 - parameter for caught (first _). It returns 90 + 8 and put it to eat (second _). eat function return 98 + 3 res0: Int = 101