source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0010694142.txt" ]
Q: SQLite Update Method for Android My question is how to you call a method like this. I already know how to implement it. Here is the method content: public boolean updateDebt(long updateId, String debtName, String debtTotal, String debtApr, String paymentGoal) { ContentValues values = new ContentValues(); values.put(MySQLiteHelper.COLUMN_DEBT_NAME, debtName); values.put(MySQLiteHelper.COLUMN_DEBT_TOTAL, debtTotal); values.put(MySQLiteHelper.COLUMN_APR, debtApr); values.put(MySQLiteHelper.COLUMN_PAYMENT, paymentGoal); String whereClause = MySQLiteHelper.COLUMN_ID + " = ?"; String[] whereArgs = new String[]{ String.valueOf(updateId) }; return database.update(MySQLiteHelper.TABLE_DEBT, values, whereClause, whereArgs) > 0; My questions lies in calling this updateDebt Method. Picture a dialog with four fields with an update button. The fields are pre-populated with table data. The user changes field data and hits update, the table should change. This is the code that comes before the call. Keep in mind, I am calling it via an onClick inside a dialog inside an onListItemClick. (I've edit lots of unrelated stuff out) List<Debt> values; MyArrayAdapter adapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.debts); datasource = new DebtDataSource(this); datasource.open(); values = datasource.getAllDebt(); adapter = new MyArrayAdapter(this, values); setListAdapter(adapter); } protected void onListItemClick(ListView l, View v, final int position, long id) { Debt item = values.get(position); final long boxId = item.getId(); final String BoxName = item.getName(); final String BoxBalance = item.getBalance(); final String BoxApr = item.getApr(); final String BoxPayment = item.getPayment(); // (edited out: setting up EditText fields here with data from above) // set up button Button button = (Button) dialog.findViewById(R.id.button1); button.setOnClickListener(new OnClickListener() { public void onClick(View v) { datasource.updateDebt(Long.valueOf(boxId), BoxName, BoxBalance, BoxApr, BoxPayment); values = datasource.getAllDebt(); adapter.notifyDataSetChanged(); dialog.dismiss(); } }); dialog.show(); } Simply put nothing happens when I hit update. The dialog dismisses, that' it. Nothing in logcat. I have logged out the variables just before the update method inside the updateDebt() method. I have toasted them back and all the variables match up perfectly. The database doesn't change though! Struggling on this for days.... A: I finally figured out the answer. This is what I WAS doing: Creating a String variable for each column in a specific row of debt. Pre-populating the fields in the dialog with that variable. Then passing the same variables into the update method For example (simplified): String name = null; EditText et; name = debt.getName(); et.setText(name); onclick { datasource.updateDebt(name); } I was missing a step between 2 and 3. Setting the variable again, inside the onClick method. Once the user pressed the update button, the variable had to be RE-SET to the new value of the EditText field. Like this: String name = null; EditText et; name = debt.getName(); et.setText(name); onclick { ***name = et.getText().toString();*** datasource.updateDebt(name); }
[ "stackoverflow", "0059604999.txt" ]
Q: Get Integers form a String using streams (Java) I'm currently working on a task where I'm supposed to program a very simple "chatbot". The goal is a public int method, that gets a List which contains questions as a parameter. Each question may or may not contain numbers and depending on which numbers the chatbot ist supposed to answer differently. I dont know in advance if and how many numbers will exist but it is safe to assume that they will be in integer value range. I also need to create an average number if there are more than one in the same question. Now I will need to extract all different numbers with streams and then reply acordingly. A question may Look like this: "Will there be 14 or perhaps 27 mails in my office today?" Now I need a way to extract all numbers form all questions from that list seperatly into e.g. an array using a stream. Any suggestions on how I can accomplish that? Lines of code doesnt realy matter. It should be quite fast and I need to use a stream as in java.util.stream for reasons. A: You can do it as follows: import java.util.ArrayList; import java.util.List; import java.util.OptionalDouble; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String[] args) { String str = "Will there be 14 or perhaps 27 mails in my office today?"; Pattern p = Pattern.compile("\\d+"); Matcher m = p.matcher(str); List<Integer> list = new ArrayList<Integer>(); while (m.find()) { list.add(Integer.parseInt(m.group())); } int sum = 0; for (int n : list) { sum += n; } System.out.println("Average: " + sum / list.size()); // Using Stream OptionalDouble average = list.stream().mapToDouble(a -> a).average(); System.out.println("Average: " + (int) average.getAsDouble()); // Another way of doing it using Stream int sumInts = list.stream().mapToInt(Integer::intValue).sum(); System.out.println("Average: " + sumInts / list.size()); } } Output: Average: 20 Average: 20 Average: 20 Update: posting the following update to do it without using any loop: import java.util.Arrays; import java.util.List; import java.util.OptionalDouble; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { String str = "Will there be 14 or perhaps 27 mails in my office today?"; String newStr = str.replaceAll("[^-0-9]+", " "); List<String> strList = Arrays.asList(newStr.trim().split(" ")); List<Integer> list = strList.stream().map(s -> Integer.parseInt(s)).collect(Collectors.toList()); // One way OptionalDouble average = list.stream().mapToDouble(a -> a).average(); System.out.println("Average: " + (int) average.getAsDouble()); // Another way int sumInts = list.stream().mapToInt(Integer::intValue).sum(); System.out.println("Average: " + sumInts / list.size()); } } Output: Average: 20 Average: 20 Another update: posting another update as per your request in the comment import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("Will there be 14 or perhaps 27 mails in my office today?"); list.add("There are 40 candidates competing for 4 places"); list.add("There are 6 teams each with 4 different channels"); System.out.println("Numbers in each string:"); list.stream().map(s -> Arrays.asList(s.replaceAll("[^-0-9]+", " ").trim().split(" "))) .collect(Collectors.toList()).stream() .map(lst -> lst.stream().map(s -> Integer.parseInt(s)).collect(Collectors.toList())) .forEach(System.out::println); System.out.println("Average of numbers in each string:"); list.stream().map(s -> Arrays.asList(s.replaceAll("[^-0-9]+", " ").trim().split(" "))) .collect(Collectors.toList()).stream() .map(lst -> lst.stream().map(s -> Integer.parseInt(s)).collect(Collectors.toList())) .forEach(lst -> System.out.println(lst.stream().mapToInt(Integer::intValue).sum() / lst.size())); } } Output: Numbers in each string: [14, 27] [40, 4] [6, 4] Average of numbers in each string: 20 22 5
[ "stackoverflow", "0011992461.txt" ]
Q: Facebook $signed_request['user_id'] Not Pulling User ID I've looked around so if this is a re-post, send me in the right direction but I keep getting 1 single random character when I run this. What am I doing wrong? I just want to output the user ID. <?php require 'facebook.php'; $facebook = new Facebook( array( 'appId' => "XXXXXXXXXXXXXXXXXXX", 'secret' => "XXXXXXXXXXXXXXXXXXXXXXX", 'cookie' => true ) ); try { $me = $facebook->api('/me'); } catch ( FacebookApiException $e ) { error_log( $e ); } $signed_request = $_REQUEST["signed_request"]; $user_id = $signed_request['user_id']; echo $user_id; $signed_request = $facebook->getSignedRequest(); $liked = $signed_request['page']['liked']; ?> Also the $signed_request['page']['liked'] works just fine. A: Is that a copy/paste from your code? If so $signed_request = $_REQUEST["signed_request"]; $user_id = $signed_request['user_id']; echo $user_id; won't work, it's not the correct signed_request and it won't be readable because you haven't decrypted the response (in the PHP SDK the decryption is automatic in the 'getSignedRequest()' function) The page code you have is correct, so to get the current user ID, assuming that the user has accepted the auth dialog for your app, the code should be $signed_request = $facebook->getSignedRequest(); $user_id = $signed_request['user_id']; echo $user_id
[ "stackoverflow", "0044510669.txt" ]
Q: Understanding Shared_ptr with cyclic references? I want to understand the way shared_ptr increments or decrements the reference counts? #include <iostream> #include <memory> class B; class A { public: std::shared_ptr<B> b_ptr_; }; class B { public: std::shared_ptr<A> a_ptr_; }; void func(std::shared_ptr<A> &aptr) { std::shared_ptr<B> bptr = std::make_shared<B>(); //Creating shared pointer bptr->a_ptr_ = aptr; // Creating cyclic dependency aptr->b_ptr_ = bptr; std::cout<<"\nFunc::a_ptr_ use_count = "<<bptr->a_ptr_.use_count(); std::cout<<"\nFunc::b_ptr_ use_count = "<<aptr->b_ptr_.use_count(); } int main() { std::shared_ptr<A> aptr = std::make_shared<A>(); std::cout<<"\nBefore func::a_ptr_ use_count = "<<aptr.use_count(); func(aptr); std::cout<<"\nAfter func::a_ptr_ use_count = "<<aptr.use_count(); std::cout<<"\nAfter func::b_ptr_ use_count = "<<aptr->b_ptr_.use_count(); return 0; } Output: This is the output I see: Before func::a_ptr_ use_count = 1 Func::a_ptr_ use_count = 2 Func::b_ptr_ use_count = 2 After func::a_ptr_ use_count = 2 After func::b_ptr_ use_count = 1 However I was expecting this "After func::a_ptr_ use_count = 1". After bptr goes out of scope in func() the reference counts should have decremented. What am I missing here? The question mentioned to be a duplicate does not explain about how the reference counts are incremented/decremented. I am more interested in the internal mechanics of how this is done(in shared_ptr) which is not explained in the answer of the other question attached. A: Why should the reference count have decremented? bptr may be out of scope, but bptr only affects the reference count for your B object. There are still two references to your A object: The shared pointer still in scope in main The shared pointer stored in your B object As long as there is live reference to your A object, your B object continues to exist, and vice versa (that's what you triggered intentionally by making cyclic shared references). To make your B object disappear, you'd need one reference in the reference cycle to be weak/raw, and clear the pointer stored in your main method so no top-level references persist.
[ "codereview.stackexchange", "0000094468.txt" ]
Q: Date validation with html5 dates This code validates the following: enddate should not be less than or equal to startdate. startdate should not be less than or equal to the date today unless document.getElementById("ltype").value == "1". The maximum gap between startdate and enddate is one year, more than that should cause an error alert. Please review my code. I think I covered all test cases, but I am extremely new to JavaScript, so this code might have bugs. And is it fine to compare dates as strings? I did this because as far as I know HTML5 date is a string. // creates a date object then converts it to a string with yyyy-mm-dd format function dateFormat(date, addyear) { // addyear is boolean, true means add another year to the date var dd = date.getDate(); var mm = date.getMonth()+1; var yyyy = date.getFullYear(); if (addyear) { yyyy++; } if(dd<10) { dd='0'+dd; } if(mm<10) { mm='0'+mm; } return yyyy+'-'+mm+'-'+dd; } function date_compare() { var today = dateFormat(new Date(),false); // from and to are html5 date fields var d1=document.getElementById("from").value; var d2=document.getElementById("to").value; var startdate = dateFormat(new Date(d1),false); var enddate = dateFormat(new Date(d2),false); var yeardate = dateFormat(new Date(d1),true); if (enddate <= startdate || enddate > yeardate) { alert("Dates out of range"); return false; } if (document.getElementById("ltype").value != "1" && startdate <= today) { alert("Error! date goes backwards!"); return false; } return true } A: Instead of giving your variables names like dd/mm/yyyy, you should give them names like day, month, year. Other names like d1 or d2. Should have better names. You need some space between operators. For example, you have this condition in your code: if(dd<10). Stuff like this can be expanded to if(dd < 10). Variable definitions should also not look like this: var x=...;, but rather, var x = ...;. You should add some more comments, e.g, describe what the functions/code blocks do, and how the processes behind them work. Finally, just a small nitpicky thing. Both of your functions should be in camelCase. One of them is in underscore_case.
[ "math.stackexchange", "0000090081.txt" ]
Q: Quaternion distance I am using quaternions to represent orientation as a rotational offset from a global coordinate frame. Is it correct in thinking that quaternion distance gives a metric that defines the closeness of two orientations? i.e. similar orientations give low distances, and dissimilar orientations give high distances. Does zero distance mean that the orientations are exactly the same? This seems obvious, but I want to ensure that there are no subtleties that get in the way of logic. A: First, I assume that you're using unit quaternions, i.e. quaternions $a+b\,\textbf{i}+c\,\textbf{j}+d\,\textbf{k}$ that satisfy $a^2 + b^2 + c^2 + d^2 = 1$. If not, you'll want to scale your quaternions before computing distance. Distance between quaternions will correspond roughly to distance between orientations as long as the quaternions are fairly close to each other. However, if you're comparing quaternions globally, you should remember that $q$ and $-q$ always represent the same orientation, even though the distance between them is $2$. There are better ways to compute the closeness of two orientations that avoid this problem. For example, the angle $\theta$ of rotation required to get from one orientation to another is given by the formula $$ \theta \;=\; \cos^{-1}\bigl(2\langle q_1,q_2\rangle^2 -1\bigr) $$ where $\langle q_1,q_2\rangle$ denotes the inner product of the corresponding quaternions: $$ \langle a_1 +b_1 \textbf{i} + c_1 \textbf{j} + d_1 \textbf{k},\; a_2 + b_2 \textbf{i} + c_2 \textbf{j} + d_2 \textbf{k}\rangle \;=\; a_1a_2 + b_1b_2 + c_1 c_2 + d_1d_2. $$ (This formula follows from the double-angle formula for cosine, together with the fact that the angle between orientations is precisely twice the angle between unit quaternions.) If you want a notion of distance that can be computed without trig functions, the quantity $$ d(q_1,q_2) \;=\; 1 - \langle q_1,q_2\rangle^2 $$ is equal to $(1-\cos\theta)/2$, and gives a rough estimate of the distance. In particular, it gives $0$ whenever the quaternions represent the same orientation, and it gives $1$ whenever the two orientations are $180^\circ$ apart.
[ "ru.stackoverflow", "0000385119.txt" ]
Q: Считывание данных из файла с произвольной строки У меня есть следующий текстовый файл: Input data: N tn t1 t2 tk u1 u2 21 5.000 20.000 50.000 65.000 100.000 95.000 i Time Uvx Uvix 1 5.000 0.000 0.000 2 8.000 20.000 50.000 3 11.000 40.000 50.000 4 14.000 60.000 50.000 5 17.000 80.000 50.000 6 20.000 100.000 50.000 7 23.000 99.500 50.000 8 26.000 99.000 50.000 9 29.000 98.500 50.000 Длительность переднего фронта: Uvx Uvix 9.000 0.000 Задача заключается в том, чтобы считать с этого файла все числовые значения, минуя при этом строки с названиями переменных и прочим текстом, а также пустые строки. Так вот как пропустить эти самые строки и начать считывать данные с произвольной строки? Язык - Си. A: Чтобы избежать загрузки в память строк, которые всё равно будут проигнорированы и чтобы поддерживать произвольно большие входные строки, можно читать файл побайтно, используя fgetc(). Чтобы пропустить строки до тех пор пока не встретится строка, которая начинается с цифры (строка с численными данными), игнорируя возможные пробелы, можно использовать автомат с двумя состояниями: читаем до тех пор пока не прочитан символ новой строки (\n) переходим в состояние ожидания цифры (expect_digit=1): все пробелы и табы игнорируются, если прочитана цифра, то возвращаем её назад в поток и выходим из функции, в противном случае (не цифра) возвращаемся в начальное состояние 1. #include <stdio.h> // read until a line that starts with a digit (ignoring leading hor.space) int skip_until_line_startswith_digit(FILE* file) { int expect_digit = 1; // expect a digit as the next character for (int c; (c = fgetc(file)) != EOF; ) { switch (c) { case '\n': // newline expect_digit = 1; break; case ' ': // horizontal whitespace case '\t': // ignore break; case '0': // digit case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (expect_digit) { if (ungetc(c, file) == EOF) return -2; // error return 0; // found digit } // unexpected digit: ignore break; default: // everything else expect_digit = 0; } } return feof(file) ? -1 : -2; // not found or an error } isdigit() может зависеть от локали на Винде, поэтому она здесь не используется. Пример использования FILE* file = stdin; if (skip_until_line_startswith_digit(file) < 0) exit(EXIT_FAILURE); // read 1st numeric block size_t N; double tn, t1, t2, tk, u1, u2; errno = 0; if (fscanf(file, "%zu %lf %lf %lf %lf %lf %lf", &N, &tn, &t1, &t2, &tk, &u1, &u2) != 7) { if (errno) perror("N tn t1 t2 tk u1 u2"); exit(EXIT_FAILURE); } printf("%zu %f %f %f %f %f %f\n", N, tn, t1, t2, tk, u1, u2); А по поводу зависимости isdigit от локали -- можно поподробнее (я думаю, это всем будет интересно)? В каких случаях это не будет работать для распознавания чисел (и почему только в винде)? С стандарт говорит (например, см. сноску в 7.11.1.1 в n1570), что isdigit() не зависит от локали, но на Винде isdigit() может зависеть от локали, например, '\xb2' в cp1252 кодировке в Danish локале распознается как десятичная цифра, что не правильно. Кстати, Unicode стандарт солидарен с С стандартом: верхние индексы такие как U+00B2 явно исключены see 4.6 Numerical Value (Unicode 6.2). A: @Иван Кущёв, fscanf не пойдет, т.к. она читает не по строкам. Можно, например, так: int c, nl = 0, skip_lines = сколько строк пропустить; while ((c = fgetc(f)) != EOF) if ((c == '\n') && (++nl == skip_lines)) break; if (feof(f)) fatal("Bad data"); Если размер строк, точнее смещение интересующей строки в файле известно (или его можно вычислить), то см. man 3 fseek. Обновление @VladD, после getline free не нужна (а если вызывать free, тогда указатель опять надо обнулить). Можно так (одной строкой): while (n-- && getline(&s, &len, file) > 0); if (n != -1) fatal(...); printf("last skipped line: %s", s); только сожрет немного больше ресурсов (а вообще-то, я отвечая, просто и забыл про getline). -- @Иван Кущёв, м.б. на практике для Вашей задачи лучше просто пропустить строки до начала данных? while (getline(&s, &len, file) > 0 && *s != 'i'); а дальше читать построчно и использовать sscanf(s, "%d %d %d %d", ...) для выборки данных. Обновление Ага, пусть так. Идея-то остается. Все равно ведь 3 разных блока данных. Просто 3 раза while (getline(...) && ...); потом чтение (один раз в цикле). А если у автора в libc нет getline, то пусть напишет свою версию (заодно потренируется, тем более что во втором блоке данных ему может понадобиться динамический массив структур).
[ "stackoverflow", "0032397804.txt" ]
Q: Preserve field in nested fields_for on errors I have a form = form_for(@user_group, :html => {:multipart => true}do |f| = f.fields_for :image, @user_group.build_image do |ff| = ff.file_field :file // other fields go here It works, but if there is a validation error it gets rerendered and selected file disappear (other fields does not, including other nested attributes). But image object is there: def create @user_group = User::Group.new(user_group_params) if @user_group.save redirect_to @user_group else ap @user_group.image render :new end end Prints this: #<Image:0x007fbf11b902a8> { :id => nil, :imageble_id => nil, :imageble_type => "User::Group", :file => #<ImageUploader:0x007fbf11b46dd8 @model=#<Image id: nil, imageble_id: nil, imageble_type: "User::Group", file: nil, created_at: nil, updated_at: nil>, @mounted_as=:file, @cache_id="1441368278-5413-2848", @filename="snapshot3.png", @original_filename="snapshot3.png", @file=#<CarrierWave::SanitizedFile:0x007fbf11b44560 @file="/home/oleg/projects/10levels-rails/public/uploads/tmp/1441368278-5413-2848/snapshot3.png", @original_filename=nil, @content_type="image/png">, @versions={:thumb=>#<ImageUploader::Uploader70228906242320:0x007fbf11b44510 @model=#<Image id: nil, imageble_id: nil, imageble_type: "User::Group", file: nil, created_at: nil, updated_at: nil>, @mounted_as=:file, @parent_cache_id="1441368278-5413-2848", @cache_id="1441368278-5413-2848", @filename="snapshot3.png", @original_filename="snapshot3.png", @file=#<CarrierWave::SanitizedFile:0x007fbf11b39408 @file="/home/oleg/projects/10levels-rails/public/uploads/tmp/1441368278-5413-2848/thumb_snapshot3.png", @original_filename=nil, @content_type="image/png">, @versions={}>}>, :created_at => nil, :updated_at => nil } Seems like it is a problem with files only A: You can use caching feature of Carrierwave. It preserves file selected. Read this
[ "stackoverflow", "0025587931.txt" ]
Q: Will a PHP value travel through an include and then through a linked php stylesheet? I have a index.php page, which has a header.php page included in it, which references a style.php file. The page I am working on has the following in the head: <?php $page = "testimonials"; include 'header.php'; ?> The header.php has if statements to set the correct style sheets and variables for the nav bar etc and also includes as I said, the style.php sheet using the following code: <link href="style.php" rel="stylesheet" type="text/css"> My question is, I am trying to use an if statement in style.php as below: <?php header("Content-type: text/css; charset: UTF-8"); if ($page == testimonials){ print "margin-top: 5%;\n"; } ?> The if statement does not seem to be working however as this is not being printed, and I am wondering if this is because I can't pull the value through the include, then through the stylesheet href? Thinking about it, I think that as stylesheets are not included like .php files, this may be the reason, could someone just confirm this is the case, or suggest a better work around? I was thinking of perhaps putting some CSS in the <head> of the PHP include for my file under an if statement, but I feel that may not be best practice. A: You cannot do this .... the link element is not an actual server side include. If you want to give the style.php file access to the variable in the header.php page, pass it via the query-string to the style.php page in the link tag. <link href="style.php?page=<?=$page?>" rel="stylesheet" type="text/css"> Then in the style.php page, read the value from the query-string parameter: <? $page = $_GET['page']; ?> Then, you can use it in an if statement inside the style.php page: if ($page == 'testimonials'){
[ "math.stackexchange", "0000021677.txt" ]
Q: Three non-coplanar lines in the 3D-space always have a fourth one that intersect them all? If I have three lines $a,$ $b$ and $c$ in the euclidean 3D space, which are pairwise non-coplanar, is there always a fourth line $x$, that intersects theses three lines? A: Label the three lines $\ell_1$, $\ell_2$, and $\ell_3$. They cannot intersect for then they would be co-planar. Since lines $\ell_1$ and $\ell_2$ do not intersect, they have points where they are closest and the line $m$ connecting those two points will be perpendicular to both $\ell_1$ and $\ell_2$. In fact, perpendicular to this line $m$ are two parallel planes: $\mathcal{P}_1$ which contains $\ell_1$ and $\mathcal{P}_2$ which contains $\ell_2$. Now pick any point $A$ of line $\ell_3$ not in either plane. The point $A$ together with the line $\ell_2$ defines a plane $\mathcal{Q}$ that contains them. This plane, since it intersects plane $\mathcal{P}_2$, must intersect the parallel plane $\mathcal{P}_1$. Moreover, the line $r$ formed by the intersection of planes $\mathcal{Q}$ and $\mathcal{P}_1$ is parallel to line $\ell_2$. Note that lines $r$ and $\ell_1$ are both on $\mathcal{P}_1$ and cannot be parallel. If they were, $\ell_2$ would also be parallel to $\ell_1$, and $\ell_1$ and $\ell_2$ would, therefore, be co-planar. So, lines $r$ and $\ell_1$ must intersect at some point $B$. If you connect points $A$ and $B$ with a line, it will connect point $A$ on $\ell_3$ passes through $\ell_2$ and connect to $B$ on $\ell_1$.
[ "tezos.stackexchange", "0000000401.txt" ]
Q: Why is the double-endorsement section on tzscan still empty? As you can see on tzscan's double-endorsement page, there are no evidence yet. but, why ? never occurred till now (very unlikely) the accuser does not recognize them yet other reason I'd be very curious to know, tnks A: Here is my attempt to explain why it is not surprising that we would see many more double bakes than endorsements: Under very nice conditions, with a deterministic signature scheme (like ed25519), you will not double endorse. Even if you fail to protect against double endorsements, if you sign endorsements for the same block twice, they are the very same endorsements, and there is no problem. Conditions won't always be very nice! But they have often been pretty nice so far. In contrast, one can easily double bake even under very nice conditions and with a deterministic signature scheme, by failing to protect against it. There is the proof of work nonce, the timestamp, the block contents... anything different will produce a different block, and so a double bake. A: I would say (99.99% sure) that double endorsement didn't happen until now. But, I may be wrong !
[ "stackoverflow", "0028273040.txt" ]
Q: Which c++ container can contain C int multidimensional arrays (C++03/MSVC11)? I have this multidimensional 2 arrays int anArray1[MAX_ROW][MAX_CELL] = { { 0, 1, 1, 0, 1, 1, 1, 0}, { 0, 1, 1, 0, 1, 1, 1, 0}, { 0, 1, 1, 0, 1, 1, 1, 0}, { 0, 1, 1, 0, 1, 1, 1, 0}, { 0, 0, 0, 0, 0, 0, 0, 0} } int anArray2[MAX_ROW][MAX_CELL] = { { 0, 1, 1, 0, 1, 1, 1, 0}, { 0, 1, 1, 0, 1, 1, 1, 0}, { 0, 1, 1, 0, 1, 1, 1, 0}, { 0, 1, 1, 0, 1, 1, 1, 0}, { 0, 0, 0, 0, 0, 0, 0, 0} } and i want to store them in index based container , i tryed to make another int array that supposed to hold them like this: int LevelsArray[LEVELS_COUNT] = { anArray1, anArray2}; im getting this error: error C2440: 'initializing' : cannot convert from 'int [68][8]' to 'int' i guess this is not the correct way .. what is the recommended way ? A: I wouldn't consider a plain old array a C++ container. I would rather use a combination of std::vector (or std::array), because of reasons. Here's an example: #include <iostream> #include <vector> typedef int cell; typedef std::vector<cell> row; typedef std::vector<row> level; typedef std::vector<level> levels; int main() { levels l = { { { 0, 1, 1, 0, 1, 1, 1, 0}, { 0, 1, 1, 0, 1, 1, 1, 0}, { 0, 1, 1, 0, 1, 1, 1, 0}, { 0, 1, 1, 0, 1, 1, 1, 0}, { 0, 0, 0, 0, 0, 0, 0, 0} }, { { 0, 1, 1, 0, 1, 1, 1, 0}, { 0, 1, 1, 0, 1, 1, 1, 0}, { 0, 1, 1, 0, 1, 1, 1, 0}, { 0, 1, 1, 0, 1, 1, 1, 0}, { 0, 0, 0, 0, 0, 0, 0, 0} }, }; for (int i = 0; i < l.size(); i++) { std::cout << "level " << i << ":\n" ; for (row & r : l[i]) { for (cell & c : r) std::cout << c << " "; std::cout << "\n"; } std::cout << "\n"; } } The output is: $ g++ test.cc -std=c++11 && ./a.out level 0: 0 1 1 0 1 1 1 0 0 1 1 0 1 1 1 0 0 1 1 0 1 1 1 0 0 1 1 0 1 1 1 0 0 0 0 0 0 0 0 0 level 1: 0 1 1 0 1 1 1 0 0 1 1 0 1 1 1 0 0 1 1 0 1 1 1 0 0 1 1 0 1 1 1 0 0 0 0 0 0 0 0 0 Using std::array instead could look something like this: #include <iostream> #include <vector> #include <array> const int cells_per_row = 8; const int rows_per_level = 5; const int nlevels = 2; typedef int cell; typedef std::array<cell, cells_per_row> row; typedef std::array<row, rows_per_level> level; typedef std::array<level, nlevels> levels; int main() { levels l = { level{ row{ 0, 1, 1, 0, 1, 1, 1, 0}, row{ 0, 1, 1, 0, 1, 1, 1, 0}, row{ 0, 1, 1, 0, 1, 1, 1, 0}, row{ 0, 1, 1, 0, 1, 1, 1, 0}, row{ 0, 0, 0, 0, 0, 0, 0, 0} }, level{ row{ 0, 1, 1, 0, 1, 1, 1, 0}, row{ 0, 1, 1, 0, 1, 1, 1, 0}, row{ 0, 1, 1, 0, 1, 1, 1, 0}, row{ 0, 1, 1, 0, 1, 1, 1, 0}, row{ 0, 0, 0, 0, 0, 0, 0, 0} }, }; for (int i = 0; i < l.size(); i++) { std::cout << "level " << i << ":\n" ; for (row & r : l[i]) { for (cell & c : r) std::cout << c << " "; std::cout << "\n"; } std::cout << "\n"; } } Note that the examples make some use of C++11 features (initializer lists, range-based for, std::array) that may not be supported by every compiler. While you can work around the initializer lists to initialize the containers and the range-based for loop for printing, there's no std::array prior to C++11. For reference: http://en.cppreference.com/w/cpp/container/vector http://en.cppreference.com/w/cpp/container/array Difference between std::vector and std::array initializer lists What is the easiest way to initialize a std::vector with hardcoded elements? http://en.cppreference.com/w/cpp/language/range-for
[ "stackoverflow", "0060339475.txt" ]
Q: Log the result on the console asp.net Core I want to make test for my application and for that I'm getting the informations from Prometheus API, I put that on a model and I try to get the data extracted from my controller. How can I get the data on my console ( something like Console.Write), do you have any ideas of how to do that ? I'v tried also debugging and I dont know how to work with visual studio debogger. Please be gentle I'm a newbie, thank you. my model of data where I will get the Json Data: using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Globalization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Prometheus_test_api.Models { public partial class FreeDiskSpace { [JsonProperty("status")] public string Status { get; set; } [JsonProperty("data")] public Data Data { get; set; } } public partial class Data { [JsonProperty("resultType")] public string ResultType { get; set; } [JsonProperty("result")] public Result[] Result { get; set; } } public partial class Result { [JsonProperty("metric")] public Metric Metric { get; set; } [JsonProperty("value")] public Value[] Value { get; set; } } public partial class Metric { [JsonProperty("__name__")] public string Name { get; set; } [JsonProperty("instance")] public string Instance { get; set; } [JsonProperty("job")] public string Job { get; set; } [JsonProperty("volume")] public string Volume { get; set; } } public partial struct Value { public double? Double; public string String; public static implicit operator Value(double Double) => new Value { Double = Double }; public static implicit operator Value(string String) => new Value { String = String }; } internal static class Converter { public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings { MetadataPropertyHandling = MetadataPropertyHandling.Ignore, DateParseHandling = DateParseHandling.None, Converters = { ValueConverter.Singleton, new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal } }, }; } internal class ValueConverter : JsonConverter { public override bool CanConvert(Type t) => t == typeof(Value) || t == typeof(Value?); public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer) { switch (reader.TokenType) { case JsonToken.Integer: case JsonToken.Float: var doubleValue = serializer.Deserialize<double>(reader); return new Value { Double = doubleValue }; case JsonToken.String: case JsonToken.Date: var stringValue = serializer.Deserialize<string>(reader); return new Value { String = stringValue }; } throw new Exception("Cannot unmarshal type Value"); } public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer) { var value = (Value)untypedValue; if (value.Double != null) { serializer.Serialize(writer, value.Double.Value); return; } if (value.String != null) { serializer.Serialize(writer, value.String); return; } throw new Exception("Cannot marshal type Value"); } public static readonly ValueConverter Singleton = new ValueConverter(); } } and my controller: using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Prometheus_test_api.Models; using Microsoft.Extensions.Logging.Debug; namespace Prometheus_test_api.Controllers { public class FreeDiskSpaceController : Controller { private readonly ILogger<FreeDiskSpaceController> _logger; public FreeDiskSpaceController(ILogger<FreeDiskSpaceController> logger) { _logger = logger; } public ActionResult Index() { IEnumerable<FreeDiskSpace> JsonData = null; using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:9090/api/v1/query?"); //HTTP GET var responseTask = client.GetAsync("query=wmi_logical_disk_free_bytes"); responseTask.Wait(); var result = responseTask.Result; if (result.IsSuccessStatusCode) { var readTask = result.Content.ReadAsAsync<IList<FreeDiskSpace>>(); readTask.Wait(); JsonData = readTask.Result; } else //web api sent error response { //log response status here.. JsonData = Enumerable.Empty<FreeDiskSpace>(); ModelState.AddModelError(string.Empty, "Server error. Please contact administrator."); } } Console.WriteLine(JsonData); return View(JsonData); } } } if its possible help me log my informations on a Razor page or in the console, thank you. A: You can put a debbug stop on any line by pressing F9 and drag your mouse over the variable that you want to inspect, the VS will show what it's stored inside that variable. OBS: Be sure to run your project in DEBUG mode, if it's in Release, VS will ignore your stops
[ "stackoverflow", "0006703774.txt" ]
Q: Separate Zend Application for control panel? Shall I create a separate Zend Application for the user backend of a web application? My main concern is that I have to have a separate Zend_Auth on both the public website (for clients to login) and for employees to manage the site. Since it appears to me that I can't use multiple Zend_Auth instances in one application this would be the only solution. The next concern would be that the two Zend_Auth sessions will collide since they run on the same webspace? Cheers A: Actually, Benjamin Cremer's solution won't work, because Zend_Auth_Admin extends a Singleton implementation, so its getInstance() would yield a Zend_Auth instance, not a Zend_Auth_Admin one. I myself was confronted with this situation, and seeing that the ZF people (at least in ZF1) see authetication as a single entry-point in an application (they could've made it so that Zend_Auth could contain multiple instances, using LSB in php etc.), made a minor modification to Benjamin Cremer's code - you must also override the getInstance(): <?php class AdminAuth extends Zend_Auth { /** * @var AdminAuth */ static protected $_adminInstance; /** * @return Zend_Auth_Storage_Interface */ public function getStorage() { if (null === $this->_storage) { $this->setStorage(new Zend_Auth_Storage_Session('Zend_Auth_Admin')); } return $this->_storage; } /** * Singleton pattern implementation. * * @return AdminAuth */ public static function getInstance() { if (null === self::$_adminInstance) { self::$_adminInstance = new self(); } return self::$_adminInstance; } }
[ "unix.stackexchange", "0000505373.txt" ]
Q: Can a subshell fetch an argument within the parent shell scope? I want to run different versions of a utility onto the same data like so: current_dir$ (cd my_utility_version_dir && exec ./my_util my_data_file) Is there a way for my_util to look for my_data_file in current_dir? A: If you run (cd my_utility_version_dir && exec ./my_util "$OLDPWD/my_data_file") then my_util's current working directory (.) will be my_utility_version_dir It will have been given the path to my_data_file in the previous working directory - the one you cded out of. Whether that looks for it there or not depends on exactly how my_util works inside, but it would be pretty common that it accepted a path to use.
[ "stackoverflow", "0025707163.txt" ]
Q: Why does this code cause the compiler to report "Unused Variable" in Xcode" NSTimer *valor = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(update) userInfo:nil repeats:YES]; A: You need to use valor somewhere else. Since it is a timer, you'd probably want to retain it somehow such as setting a property to it: self.timer = valor;
[ "stackoverflow", "0028309629.txt" ]
Q: Have image open in its own page with information I have a page with images on it. Each image has information associated with it, and when the image is clicked I'd like to have it open in its own page (not a new tab or window) with some of the associated information displayed around it. Is there a way to do this where I don't have to manually make a page for each image? I'm dealing with a large set of pictures so automation is key. A: Something like this ? info could be moved around , styled as per needs. .info{display:none} img:hover +.info{display:inline;} <img src="http://lorempixel.com/150/150"width="150" height="150" /> <span class="info">This pic is super</span> <img src="http://lorempixel.com/150/150"width="150" height="150" /> <span class="info">This pic is super</span> <img src="http://lorempixel.com/150/150"width="150" height="150" /> <span class="info">This pic is super</span> <img src="http://lorempixel.com/150/150"width="150" height="150" /> <span class="info">This pic is super</span><img src="http://lorempixel.com/150/150"width="150" height="150" /> <span class="info">This pic is super</span><img src="http://lorempixel.com/150/150"width="150" height="150" /> <span class="info">This pic is super</span><img src="http://lorempixel.com/150/150"width="150" height="150" /> <span class="info">This pic is super</span>*emphasized text*
[ "stackoverflow", "0047070331.txt" ]
Q: js map why is not changing my value with return I'm doing map with a variable, and doing a return to change his value, but it's not working, the value for the whole array is the same: //resultValues = processValues(table,resultValues,'toClient'); resultValues.map ( (record) => { record = processValues(table,record,'toClient'); return record; }); return Promise.resolve(resultValues); // does not change so I had to create another variable to be able to have a change on the array. why is this behavoiur? it's normal in map ?; is there another option with lodash by example to don't need create a second variable? let newResult = []; resultValues.map ( (record) => { record = processValues(table,record,'toClient'); newResult.push(record); // with this changes are sent to new var //return record; }); // return Promise.resolve(resultValues); return Promise.resolve(newResult); A: Array.map returns a new array instance where each element inside it is transformed: let ret = resultValues.map (record => processValues(table,record,'toClient')); return Promise.resolve(ret);
[ "stackoverflow", "0060285130.txt" ]
Q: Mathematical symbols rendering SVG unviewable I am trying to display subtraction of 2 numbers with the subtraction symbol &minus; to no success. It works when i simple use - but that is not how a subtraction symbol should look like. I've tried with &mdash;, &divide;, &multiply; with no success. Is there a way to display these symbols in SVG within the <text> tag? echo '<text x="165" y="'.$y_axis.'" font-size="30" font-family="Arial, Helvetica, sans-serif" fill="rgb(93, 130, 255)"> &minus;</text>'; A: Instead of HTML Entity (named): &minus; it must be in HTML Entity (HEX): &#x2212;. The same format applies to other symbols.
[ "wordpress.stackexchange", "0000085268.txt" ]
Q: watermarking gallery items How can I add an image watermark to only those images which are to be published in gallery using a function in functions.php? Images can be in .jpg, .png, .gif format. I also found this snippet which serves the same but it watermarks all the uploaded images. A: This is what I put into a watermark.php file : <?php // loads a png, jpeg or gif image from the given file name function imagecreatefromfile($image_path) { // retrieve the type of the provided image file list($width, $height, $image_type) = getimagesize($image_path); // select the appropriate imagecreatefrom* function based on the determined // image type switch ($image_type) { case IMAGETYPE_GIF: return imagecreatefromgif($image_path); break; case IMAGETYPE_JPEG: return imagecreatefromjpeg($image_path); break; case IMAGETYPE_PNG: return imagecreatefrompng($image_path); break; default: return ''; break; } } // load source image to memory $image = imagecreatefromfile($_GET['image']); if (!$image) die('Unable to open image'); // load watermark to memory $watermark = imagecreatefromfile($_GET['watermark']); if (!$image) die('Unable to open watermark'); // calculate the position of the watermark in the output image (the // watermark shall be placed in the lower right corner) $watermark_pos_x = imagesx($image) - imagesx($watermark) - 8; $watermark_pos_y = imagesy($image) - imagesy($watermark) - 10; // merge the source image and the watermark imagecopy($image, $watermark, $watermark_pos_x, $watermark_pos_y, 0, 0, imagesx($watermark), imagesy($watermark)); // output watermarked image to browser header('Content-Type: image/jpeg'); imagejpeg($image, '', 100); // use best image quality (100) // remove the images from memory imagedestroy($image); imagedestroy($watermark); ?> then into a .htaccess file : RewriteEngine on RewriteCond %{REQUEST_URI} (800x...|...x800)\.(png|jpe?g|gif) RewriteRule ^([^tn].*\.(gif|jpg|png))$ /wp-content/uploads/watermark.php?image=$1&watermark=watermark.png [NC] Place the watermark.php + .htaccess + watermark.png into wp-content/uploads folder (or any other place if you adapt the .htaccess line). Here the .htaccess grabs any request for jpg, png ou gif that contains 800x or x800 in the name (to apply watermark on big images only), redirect it to the watermark.php script who add the watermark on the image. This is a starter that you should adapt to your needs by defining the rules to apply in the .htaccessfile. For our case, we had define 800x800 size in the media options.
[ "stackoverflow", "0059129021.txt" ]
Q: undefined on variable with async await es6 function Not sure why I keep getting undefined on the possibleAnagrams variable, any help would be greatly appreciated! const anagramica = require('anagramica'); const processBody = async (generatedString, arrayOfWords) => { const possibleAnagrams = await anagramica.all(generatedString, (err, response) => { if (err) { console.log(`Could not find possible anagrams : ${err}`); } else { console.log("1", response.all); /// [ Array ] /// const array = response.all; console.log("2", array); /// [ Array ] /// return array; } }) console.log("3", possibleAnagrams) /// undefined /// return { possibleAnagrams, arrayOfWords } } A: It looks like anagramica does not return a Promise. If you'd like to use async/await, consider turning it into a Promise. const anagramica = require('anagramica'); const anagramicaPromise = generatedString => new Promise((res, rej) => { anagramica.all(generatedString, (err, response) => { if (err) { return rej(err); } res(response); } }); const processBody = async (generatedString, arrayOfWords) => { try { const possibleAnagrams = await anagramicaPromise(generatedString); console.log("3", possibleAnagrams); return { possibleAnagrams, arrayOfWords } } catch(err) { console.log(`Could not find possible anagrams : ${err}`); } }
[ "english.stackexchange", "0000056206.txt" ]
Q: What is a good alternative to "the film is set in"? I'm writing a paper about a movie. I would like to start like this: Monsters is a 2010 independent science-fiction film directed by Gareth Edwards and set in the Mexico-U.S. border region. It is set in the present; however, a significant event has changed human history six years before .... I would like to avoid duplicating "set", but I can't think of a good alternative. The thesaurus isn't helpful because it doesn't seem to cover the case of "to be set", at least dictionary.com's doesn't. What are good alternatives here? I'll restructure the sentences if none exists, but I thought I'd ask first. A: The film takes place in the present.
[ "stackoverflow", "0018425947.txt" ]
Q: Check Username Availability Error I got this error when i wanna try to check availability username that is have in database or not, the error says: "Input string was not in correct format". Here is the code: private void CheckUsername() { OleDbConnection conn = new OleDbConnection(); conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\Archives\Projects\Program\Sell System\Sell System\App_Data\db1.accdb"; conn.Open(); OleDbCommand cmd = new OleDbCommand("SELECT [Username] FROM [Member], conn); cmd.Parameters.Add("Username", System.Data.OleDb.OleDbType.VarChar); cmd.Parameters["Username"].Value = this.textBox1.Text; int count = Convert.ToInt32(cmd.ExecuteScalar()); if (count != 0) { System.Media.SoundPlayer sound = new System.Media.SoundPlayer(@"C:\Windows\Media\Windows Notify.wav"); sound.Play(); MessageBox.Show("Username already exists! Please use another username", "Warning"); } else { System.Media.SoundPlayer sound = new System.Media.SoundPlayer(@"C:\Windows\Media\Windows Notify.wav"); sound.Play(); MessageBox.Show("Username is not exists!", "Congratulations"); } } The error pointed in: int count = Convert.ToInt32(cmd.ExecuteScalar()); and the error says: "input string was not in correct format" Thanks in advance! A: Well first I'd like to give you a tip on using parameters in your queries, second, I think you meant to write COUNT() in your SQL: OleDbCommand cmd = new OleDbCommand("SELECT COUNT([Username]) FROM [Member] WHERE [Username] = ?", conn); cmd.Parameters.Add(textBox1.Text);
[ "stackoverflow", "0035876162.txt" ]
Q: Can't access data in a nested array I am kinda stuck, so I need you help. I have an nested array that looks like this: array (size=2) 0 => array (size=5) 'id' => int 7 'name' => string 'sad' (length=3) 'content' => string 'x' (length=1) 'created_at' => string '2016-03-08 17:41:12' (length=19) 'nm' => string 'test' (length=4) 1 => array (size=5) 'id' => int 8 'name' => string 'sadfafs' (length=7) 'content' => string 'x' (length=1) 'created_at' => string '2016-03-08 17:41:44' (length=19) 'nm' => string 'test' (length=4) I am trying to access data inside with this method: @if ($forms != null) @foreach($forms as $forma) @foreach($forma as $form) <tr class="gradeA"> <td>{!! $form['id'] !!}</td> <td>{!! $form['name'] !!}</td> <td class="center">{!! $form['created_by'] !!}</td> <td class="center">{!! $form['created_at'] !!}</td> <td> <a href="{{url('forms/delete?id=' . $form[0])}}">DELETE</a> <a href="{{url('forms/edit?id=' . $form[0])}}">EDIT</a></td> </tr> @endforeach @endforeach @else <p> Nufing</p> @endif Whatever I am doing I get error: Illegal string offset "name" Can someone advise me on how access this data in a correct manner? A: You need to remove inner foreach loop and every thing works fine. So code should be:- @if ($forms != null) @foreach($forms as $forma) <tr class="gradeA"> <td>{!! $form['id'] !!}</td> <td>{!! $form['name'] !!}</td> <td class="center">{!! $form['created_by'] !!}</td> <td class="center">{!! $form['created_at'] !!}</td> <td> <a href="{{url('forms/delete?id=' . $form[0])}}">DELETE</a> <a href="{{url('forms/edit?id=' . $form[0])}}">EDIT</a></td> </tr> @endforeach @else <p> Nufing</p> @endif
[ "aviation.stackexchange", "0000058154.txt" ]
Q: Would the wings of a Boeing 787 be snapped off in the same turbulence in which a DC-8 lost an engine and parts of a wing? From forbes.com: In 1992, a DC 8 cargo aircraft suffered turbulence so severe over the Front Range of Colorado’s Rocky Mountains that its left outboard engine was completely ripped off as well as some 12 feet of its left wing’s leading edge. Mercifully, the pilot was able to make an emergency landing at Denver International. If a 787 was put in the same turbulence as the DC-8, would the wings snap off? The DC-8 is from the '50s while the 787 is a new aircraft. A: It's very likely that the 787 would have less problems with turbulence than the DC-8 did. The wings of the Boeing 787 are more flexible than the DC-8, and that flexibility will damp the immediate impact of turbulence. More important, the Boeing 787 has a gust alleviation system that reacts to turbulence by counteracting the induced accelerations using the control surfaces. Note that the aircraft certification standards have changed a lot since the DC-8 was certified. Originally the focus was very much on the maximum g-forces the wing could sustain, but this is not a very good measure for turbulence. The g-forces encountered in turbulence are the result of a combination of the turbulence itself and the aero-elastic response of the aircraft. Using a more flexible wing and gust alleviation systems will result in a much smoother ride (less g-forces) than a traditional very rigid wing. Currently the certification standards define, in addition to a required g-force, the characteristics of the turbulence that the aircraft has to sustain. For example, see the FAA's regulation for large aircraft, FAR Part 25, Sec 25.341. This takes into account a range of characteristics of turbulence that can be encountered as well as the dynamic response of the aircraft to that turbulence. Apart for aerodynamic and structural differences between the DC-8 and the Boeing 787, better understanding of (mountain wave) turbulence, better weather prediction, better reporting of turbulence by aircrew (simply because there are more flights) and better weather radars on aircraft have reduced the risks of encountering turbulence since the DC-8 era.
[ "stackoverflow", "0004149291.txt" ]
Q: Installing a WP theme ive made locally to a web server Warning: Cannot modify header information - headers already sent by (output started at /home/content/82/6985782/html/wordpress/wp-content/themes/syntax/themeoptions.php:289) in /home/content/82/6985782/html/wordpress/wp-content/themes/syntax/themeoptions.php on line 136 Thats the error i get whenever i want to submit something in the admin panel. Here's the code for the themeoptions.php: http://pastebin.com/aFWHjEv0 It all works perfectly normal on localhost, any explanations?? A: It's probably output_buffering that is enabled on your local machine, but not on the remote server. (You can find out by using phpinfo). The easy fix is to prepend your script with a output_buffering command: <?php ob_start(); Even better is finding out where the output starts and fix it there.
[ "stackoverflow", "0012618581.txt" ]
Q: Excessive garbage collection in arithmetic evaluator I'm attempting to create an Android app which graphs simple mathematical functions that the user inputs (essentially a graphing calculator). Every onDraw call requires hundreds of arithmetic evaluations per second (which are plotted on screen to produce the graph). When my code evaluates the expression the program slows down considerably, when the inbuilt methods evaluate the expression, the app runs with no issue. According to 'LogCat', garbage collection occurs about 12 times per second, each time pausing the app for roughly 15 milliseconds, resulting in a few hundred milliseconds worth of freezes every second. I think this is the problem. Here is a distilled version of my evaluator function. The expression to be evaluated is named "postfixEquation", the String ArrayList "list" holds the final answer at the end of the process. There are also two String arrays titled "digits" and "operators" which store the numbers and signs which are able to be used: String evaluate(String[] postfixEquation) { list.clear(); for (int i = 0; i < postfixEquation.length; i++) { symbol = postfixEquation[i]; // If the first character of our symbol is a digit, our symbol is a numeral if (Arrays.asList(digits).contains(Character.toString(symbol.charAt(0)))) { list.add(symbol); } else if (Arrays.asList(operators).contains(symbol)) { // There must be at least 2 numerals to operate on if (list.size() < 2) { return "Error, Incorrect operator usage."; } // Operates on the top two numerals of the list, then removes them // Adds the answer of the operation to the list firstItem = Double.parseDouble(list.get(list.size() - 1)); secondItem = Double.parseDouble(list.get(list.size() - 2)); list.remove(list.size() - 1); list.remove(list.size() - 1); if (symbol.equals(operators[0])){ list.add( Double.toString(secondItem - firstItem) ); } else if (symbol.equals(operators[1])) { list.add( Double.toString(secondItem + firstItem) ); } else if (symbol.equals(operators[2])) { list.add( Double.toString(secondItem * firstItem) ); } else if (symbol.equals(operators[3])) { if (firstItem != 0) { list.add( Double.toString(secondItem / firstItem) ); } else { return "Error, Dividing by 0 is undefined."; } } else { return "Error, Unknown symbol '" + symbol + "'."; } } } // The list should contain a single item, the final answer if (list.size() != 1) { return "Error, " + list has " + list.size() + " items left instead of 1."; } // All is fine, return the final answer return list.get(0); } The numerals used in the operations are all Strings, as I was unsure if it was possible to hold multiple types within one array (i.e. Strings and Doubles), hence the rampant "Double.parseDouble" and "Double.toString" calls. How would I go about reducing the amount of garbage collection that occurs here? If it's of any help, I have been using these steps to evaluate my postfix expression: http://scriptasylum.com/tutorials/infix_postfix/algorithms/postfix-evaluation/index.htm. I have been unable to get past this issue for weeks and weeks. Any help would be appreciated. Thanks. A: The rule for tight loops in Java is don't allocate anything. The fact that you're seeing such frequent GC collections is proof of this. You appear to be doing calculations with Double, then converting to a String. Don't do that, it's terrible for performance because you create tons and tons of strings then throw them out (plus you are converting back and forth between strings and doubles a lot). Just maintain an ArrayDeque<Double> and use it as a stack -- this also saves you from doing the array resizes that are probably also killing performance. Precompile the input equations. Convert all the input operations to enum instances -- they are faster to compare (just takes a switch statement), and may even use less memory. If you need to handle doubles, either use a generic Object container and instanceof, or a container class that contains both an operation enum and a double. Precompiling saves you from having to do expensive tests in your tight loop. If you do these things, your loop should positively fly.
[ "stackoverflow", "0019244796.txt" ]
Q: How to parse a JSON twice for the same HttpResponse? (ANDROID) I use the library GSON to parse the response of a web service in JSON format. In the event that the web service returns me a positive response, I'll return it as a USER Class, otherwise it returns me as an ERROR Class. I would like, if when I'm trying to get my USER and that fails, you can recover my ERROR with the same HttpResponse but it does not work. Does anyone have an idea? try { //Create an HTTP client HttpClient client = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(URL); //Add your POST data List<NameValuePair> post = new ArrayList<NameValuePair>(3); post.add(new BasicNameValuePair("login", login)); post.add(new BasicNameValuePair("pwd", pwd)); post.add(new BasicNameValuePair("id_tablet", InfoTab.getPhoneInfo(context))); httpPost.setEntity(new UrlEncodedFormEntity(post)); //Perform the request and check the status code HttpResponse response = client.execute(httpPost); StatusLine statusLine = response.getStatusLine(); if(statusLine.getStatusCode() == 200) { HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); try { //Read the server response and attempt to parse it as JSON Reader reader = new InputStreamReader(content); GsonBuilder gsonBuilder = new GsonBuilder(); Gson gson = gsonBuilder.create(); User user = gson.fromJson(reader, User.class); if(user.getIdLms()==null) { Error error = gson.fromJson(reader, Error.class); // ERROR TREATMENT } else { // USER TREATMENT } content.close(); } catch (Exception ex) { Log.e(getClass().getSimpleName(), "Failed to parse JSON due to: " + ex); } } else { Log.e(getClass().getSimpleName(), "Server responded with status code: " + statusLine.getStatusCode()); } } catch(Exception ex) { Log.e(getClass().getSimpleName(), "Failed to send HTTP POST request due to: " + ex); } A: You can cache your JSON once you make a successful call, and on later calls if fails read your JSON from cache. As a pseudo code you would have. try { read JSON from server; //write JSON to cache; //after coding with java JSONObject jsonObject = // cast you gson into JSONObject in a way writeJSONToCache( jsonObject , cacheFolderPath , cahceFileName); } catch (ClientProtocolException e) //fail.. no connection or something { read JSON from cache; } edit java code for storing json cache file public static void writeJSONToCache( JSONObject jsonObject , String cacheFolderPath , String cahceFileName) throws IOException, JSONException { String jsonString = jsonObject.toString(4) new File(cacheFolderPath).mkdirs(); File cahceFile = new File(cacheFolderPath, cahceFileName); // if file doesnt exists, then create it if (!cahceFile.exists()) cahceFile.createNewFile(); FileWriter fileWriter = new FileWriter(cahceFile.getAbsoluteFile()); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); bufferedWriter.write(jsonString); bufferedWriter.close(); }
[ "math.stackexchange", "0001131843.txt" ]
Q: Proof of Hall's subgroup Theorem So I'm working through Hall's Theorem for Solvable groups and there is one part of it which I cannot seem to prove. I am following through Isaac's book on Finite group Theory for reference. Currently I can prove Hall-E (existence of a Hall-$\pi$-subgroup), Hall-C (any two such are conjugate) however the proof of Hall-D eludes me. For those without the book it is stated as; Let $U \subseteq G$ be a $\pi$ subgroup, where $\pi$ is a set of primes and $G$ is a finite solvable group. Then $U$ is contained in some Hall-$\pi$-subgroup of $G$. A: I don't know how the proof in Isaacs' book goes but let's try a standard induction argument. Since $G$ is soluble, it has a normal subgroup $N$ which is an elementary abelian $p$-group for some prime $p$ and, by induction we may assume that the result is true in $G/N$, so $UN/N$ is contained in a Hall $\pi$-subgroup $H/N$ of $G/N$. There are two cases $p \in \pi$ and $p \not\in \pi$. If $p \in \pi$ then $H$ is a Hall $\pi$-subgroup of $G$ and $U \le H$, so we are done. If $p \not\in \pi$, then by the existence part applied to $H$, there is a Hall $\pi$-subgroup $J$ of $H$ (and hence also of $G$) that complements $N$ in $H$. Then $J(NU) = JN = H$, so $|J \cap NU| =|J||N||U|/|H| = |U|$. Now, by the conjugacy part applied to the complements $J \cap NU$ and $U$ of $N$ in $NU$, there is $h \in H$ with $(J \cap NU)^h = U$, so $U$ is contained in the Hall $\pi$-subgroup $J^h$ of $G$.
[ "stackoverflow", "0056768387.txt" ]
Q: How to Manipulate TableView from another Controller? Note: AlbumAvailble is a ComboBox contains the Albums of a Singer. :AvailableSinger a ComboBox dontains the Singers. I'm trying to display songs of an album in TableView in a different dialog which is "DisplaySongs.fxml". I've tried to create a method in "DisplaySongs.java" controller of "DisplaySongs.fxml" to add all album songs to the table. so in the method which will display the dialog I've passed the selectedItem of AlbumAvailble and get the songlist of it. the main window controller: @FXML public void Display() { Dialog<ButtonType>DisplaySong = new Dialog<>(); DisplaySong.initOwner(DisplayBorder.getScene().getWindow()); DisplaySong.setTitle("DisPlay Songs"); FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(getClass().getResource("DisplaySongs.fxml")); try { DisplaySong.getDialogPane().setContent(fxmlLoader.load()); }catch (IOException E){ E.getStackTrace(); } DisplaySong.getDialogPane().getButtonTypes().add(ButtonType.CLOSE); Optional<ButtonType> result = DisplaySong.showAndWait(); if(result.isPresent()) { DisplaySongs controller = fxmlLoader.getController(); controller.Display(AlbumAvailble.getSelectionModel().getSelectedItem()); } } The Display of Songs controller: public class DisplaySongs { @FXML private TableView<Song> Songs ; public void Display(Album Alb) { Songs.getItems().addAll(Alb.getSongsList()); } } The Song class: package MusicManiPulation; import javafx.beans.property.SimpleStringProperty; import java.time.LocalDate; public class Song { private SimpleStringProperty SongName = new SimpleStringProperty("") ; private SimpleStringProperty SongLength = new SimpleStringProperty(""); private LocalDate ReleasedDay ; public Song(String songName, String songLength, LocalDate releasedDay) { SongName.set(songName); SongLength.set(songLength); ReleasedDay = releasedDay; } public String getSongName() { return SongName.get(); } public void setSongName(String songName) { SongName.set(songName); } public String getSongLength() { return SongLength.get(); } public void setSongLength(String songLength) { SongLength.set(songLength); } public LocalDate getReleasedDay() { return ReleasedDay; } public void setReleasedDay(LocalDate releasedDay) { ReleasedDay = releasedDay; } } Album class: package MusicManiPulation; import java.time.LocalDate; import java.util.ArrayList; public class Album { private String AlbumNam ; ArrayList<Song> SongsList ; public Album(String albumNam) { AlbumNam = albumNam; this.SongsList = new ArrayList<>(); } public boolean addNewSongToAlbum(String SongName , String SongLength , LocalDate ReleadsedDay) { boolean song = findSong(SongName); if (song) { return false; } SongsList.add(new Song(SongName , SongLength,ReleadsedDay)); return true; } public boolean removeSong(String SongName){ for(Song song :SongsList){ if(song.getSongName().equalsIgnoreCase(SongName)){ SongsList.remove(song); return true; } } return false; } private boolean findSong(String SongName){ for(Song song:SongsList){ if(song.getSongName().equalsIgnoreCase(SongName)){ return true; } } return false; } public String getAlbumNam() { return AlbumNam; } public ArrayList<Song> getSongsList() { return SongsList; } @Override public String toString() { return AlbumNam; } } the getSongList method in Album class: public ArrayList<Song> getSongsList() { return SongsList; } Every time I press the "Display" Button the Table is Empty A: public void Display(){ Dialog<ButtonType>DisplaySong = new Dialog<>(); DisplaySong.initOwner(DisplayBorder.getScene().getWindow()); DisplaySong.setTitle("DisPlay Songs"); FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(getClass().getResource("DisplaySongs.fxml")); try { DisplaySong.getDialogPane().setContent(fxmlLoader.load()); }catch (IOException E){ E.getStackTrace(); } DisplaySong.getDialogPane().getButtonTypes().add(ButtonType.CLOSE); System.out.println("BEFORE Show"); //Optional<ButtonType> result = DisplaySong.showAndWait(); //removed this line too DisplaySong.show(); // if(result.isPresent()){ REMOVED THIS LINE. // YOU FORGOT THE CAST HERE : DisplaySongs controller = (DisplaySongs) fxmlLoader.getController(); controller.Display(AlbumAvailble.getSelectionModel().getSelectedItem()); }
[ "stackoverflow", "0024494838.txt" ]
Q: Migrating Android Studio 0.6.1 to 0.8: [PATH] does not appear to be Android Studio config folder or installation home So I'm trying to migrate from the last preview build, 0.6.1 to the new beta, 0.8. I have two Android Studio dirs in my \Program Files\Android\ dir, 0.6.1: \android-studio\ and the new one, \android-studio1\ from 0.8 since you can't upgrade via client from preview to beta. When starting up the exe from 0.8 and prompted to import settings from a previous version of AS from a "config folder or installation home of the previous version of Android Studio" I select "C:\Program Files (x86)\Android\android-studio" but it complains that the dir "does not appear to be Android Studio config folder or installation home." Since it doesn't like my installation home path, where is the settings config folder for AS 0.6.1? EDIT: I've tried the configuration folders in C:\Program Files (x86)\Android\android-studio\sdk\tools\lib\ monitor folders and they don't work either A: Android Studio is based on IntelliJ and uses the same config folder. On Mac OS X the config folder is located at ~/Library/Preferences/AndroidStudioPreview. Not sure for Windows but you can look in C:\Documents and Settings\<USER ACCOUNT NAME>\.AndroidStudioPreview or C:\Users\<USER ACCOUNT NAME>\.AndroidStudioPreview according to http://devnet.jetbrains.com/docs/DOC-181.
[ "stackoverflow", "0036431106.txt" ]
Q: Python string to list 2D I have this string: [0, 0], [1, 7], [2, 1], [3, 1], [4, 4], [5, 3], [6, 0], [7, 0], [8, 0], [9,0], [10, 0], [11, 0], [12, 0], [13, 0], [14, 0], [15, 0], [16, 0], [17, 0], [18,0], [19, 0], [20, 0], [21, 0], [22, 0], [23, 0], [24, 0], [25, 0], [26, 0], [27, 0], [28, 0], [29, 0], [30, 0] and I need to convert it in a 2D list Can you help me?, I have tried with string.split(), but I can't find the correct combination. Thanks a lot. A: You can use literal_eval and list to do this: import ast s = "[0, 0], [1, 7], [2, 1], [3, 1], [4, 4], [5, 3], [6, 0], [7, 0], [8, 0], [9,0],[10, 0], [11, 0], [12, 0], [13, 0], [14, 0], [15, 0], [16, 0], [17, 0], [18,0], [19, 0], [20, 0], [21, 0], [22, 0], [23, 0], [24, 0], [25, 0], [26, 0], [27, 0], [28, 0], [29, 0], [30, 0]" l = list(ast.literal_eval(s)) Output: >>> l [[0, 0], [1, 7], [2, 1], [3, 1], [4, 4], [5, 3], [6, 0], [7, 0], [8, 0], [9, 0], [10, 0], [11, 0], [12, 0], [13, 0], [14, 0], [15, 0], [16, 0], [17, 0], [18, 0], [19, 0], [20, 0], [21, 0], [22, 0], [23, 0], [24, 0], [25, 0], [26, 0], [27, 0], [28, 0], [29, 0], [30, 0]]
[ "stackoverflow", "0041280103.txt" ]
Q: Perl: how to use string variables as search pattern and replacement in regex I want to use string variables for both search pattern and replacement in regex. The expected output is like this, $ perl -e '$a="abcdeabCde"; $a=~s/b(.)d/_$1$1_/g; print "$a\n"' a_cc_ea_CC_e But when I moved the pattern and replacement to a variable, $1 was not evaluated. $ perl -e '$a="abcdeabCde"; $p="b(.)d"; $r="_\$1\$1_"; $a=~s/$p/$r/g; print "$a\n"' a_$1$1_ea_$1$1_e When I use "ee" modifier, it gives errors. $ perl -e '$a="abcdeabCde"; $p="b(.)d"; $r="_\$1\$1_"; $a=~s/$p/$r/gee; print "$a\n"' Scalar found where operator expected at (eval 1) line 1, near "$1$1" (Missing operator before $1?) Bareword found where operator expected at (eval 1) line 1, near "$1_" (Missing operator before _?) Scalar found where operator expected at (eval 2) line 1, near "$1$1" (Missing operator before $1?) Bareword found where operator expected at (eval 2) line 1, near "$1_" (Missing operator before _?) aeae What do I miss here? Edit Both $p and $r are written by myself. What I need is to do multiple similar regex replacing without touching the perl code, so $p and $r have to be in a separate data file. I hope this file can be used with C++/python code later. Here are some examples of $p and $r. ^(.*\D)?((19|18|20)\d\d)年 $1$2<digits>年 ^(.*\D)?(0\d)年 $1$2<digits>年 ([TKZGD])(\d+)/(\d+)([^\d/]) $1$2<digits>$3<digits>$4 ([^/TKZGD\d])(\d+)/(\d+)([^/\d]) $1$3分之$2$4 A: With $p="b(.)d"; you are getting a string with literal characters b(.)d. In general, regex patterns are not preserved in quoted strings and may not have their expected meaning in a regex. However, see Note at the end. This is what qr operator is for: $p = qr/b(.)d/; forms the string as a regular expression. As for the replacement part and /ee, the problem is that $r is first evaluated, to yield _$1$1_, which is then evaluated as code. Alas, that is not valid Perl code. The _ are barewords and even $1$1 itself isn't valid (for example, $1 . $1 would be). The provided examples of $r have $Ns mixed with text in various ways. One way to parse this is to extract all $N and all else into a list that maintains their order from the string. Then, that can be processed into a string that will be valid code. For example, we need '$1_$2$3other' --> $1 . '_' . $2 . $3 . 'other' which is valid Perl code that can be evaluated. The part of breaking this up is helped by split's capturing in the separator pattern. sub repl { my ($r) = @_; my @terms = grep { $_ } split /(\$\d)/, $r; return join '.', map { /^\$/ ? $_ : q(') . $_ . q(') } @terms; } $var =~ s/$p/repl($r)/gee; With capturing /(...)/ in split's pattern, the separators are returned as a part of the list. Thus this extracts from $r an array of terms which are either $N or other, in their original order and with everything (other than trailing whitespace) kept. This includes possible (leading) empty strings so those need be filtered out. Then every term other than $Ns is wrapped in '...', so when they are all joined by . we get a valid Perl expression, as in the example above. Then /ee will have this function return the string (such as above), and evaluate it as valid code. We are told that safety of using /ee on external input is not a concern here. Still, this is something to keep in mind. See this post, provided by Håkon Hægland in a comment. Along with the discussion it also directs us to String::Substitution. Its use is demonstrated in this post. Another way to approach this is with replace from Data::Munge For more discussion of /ee see this post, with several useful answers. Note on using "b(.)d" for a regex pattern In this case, with parens and dot, their special meaning is maintained. Thanks to kangshiyin for an early mention of this, and to Håkon Hægland for asserting it. However, this is a special case. Double-quoted strings directly deny many patterns since interpolation is done -- for example, "\w" is just an escaped w (what is unrecognized). The single quotes should work, as there is no interpolation. Still, strings intended for use as regex patterns are best formed using qr, as we are getting a true regex. Then all modifiers may be used as well.
[ "stackoverflow", "0051692955.txt" ]
Q: How to access a ForeignKey Object's attribute on a dynamic basis I'm currently trying to access the ForeignKey to attribute in a for loop as I require it to be dynamic. Neither django's docs nor online search delivered any helpful results. Here's what I'm using: Django 1.11 with Django CMS 3.5.2 and Django Countries package. The error message is: AttributeError: 'ForeignKey' object has no attribute 'to However, accessing the field's name or verbose_name or even choices attribute (for charFields or IntegerFields) works. models.py company = models.ForeignKey(verbose_name=_('Company'), blank=False, null=False, to='accounts.CompanyName', on_delete=models.CASCADE) views.py def generate_view(instance): model = apps.get_model(app_label='travelling', model_name=str(instance.model)) data = dict() field_list = eval(instance.fields) fields = model._meta.get_fields() output_list = list() for field in fields: for list_field in field_list: if field.name == list_field: options = list() if field.__class__.__name__ == 'ForeignKey': print(field.to) # Here's the error elif field.__class__.__name__ == 'CountryField': for k, v in COUNTRIES.items(): options.append((k, v)) # Works properly elif field.__class__.__name__ == 'ManyToManyField': pass # Yields the same issues as with foreign keys output_list.append({ 'name': field.name, 'verbose': field.verbose_name, 'options': options, 'type': field.__class__.__name__ }) return data A: As you see, there isn't an attribute called to. That's the name of a parameter of the ForeignKey initializer. Since the argument can be a string model reference, or "self", it makes sense that the attribute representing the actual model target should have a different name. The Field attribute reference defines the API for introspecting field objects. What you're after is something like: if field.many_to_one: print(field.related_model)
[ "gaming.stackexchange", "0000038829.txt" ]
Q: In Battlefield 3, is there a console command to disable chat? Even in 1080p, the chat box is rather annoyingly sized on a 22in monitor. Does anyone know if there is a console command to disable it? A: Since the last patch there is a key that lets you toggle the chat between "always", "popup" and "never". By default it is bound to H
[ "boardgames.stackexchange", "0000010780.txt" ]
Q: Spawning from special zombie cards inside buildings In Zombicide, when spawning zombies inside buildings when a player opens a door, what do we do when we draw a "special card"? By "special card" I mean "additional activation of zombies", "sewer spawn", etc. For example: During the player's turn, one of them opens a door. In one room they draw an "additional activation of runners". Can the runners be activated in the player's turn? Or do we discard this card and draw another? Or does nothing spawn in that room? A: Yes, zombies of that type get an immediate activation. Do not discard that card and draw another, do whatever is on the card. Nothing will spawn in room/zone of the corresponding "special" card. This is covered in the first page of the FAQ Q: When spawning the Zones of a building I just opened, what happens if I draw an extra activation or manhole card? A: Always do exactly what the card says no matter when you draw it. If you draw an extra activation card, that Zombie type receives an extra activation immediately. If tou draw a manhole card, spawn Zombies in the manholes normally. in these cases, the building Zone for which the card was originally drawn receives no Zombies. This is also repeated at the bottom of page 10 of the rule book, just above the so many zombies, so few miniatures sidebar. There are two special cases: the “extra activation” cards and the “manhole” cards. In both cases, no Zombies appear on the designated Zone.
[ "unix.stackexchange", "0000226622.txt" ]
Q: Ccache hits only once during kernel build I installed and set up ccache and built the kernel with it. Here are the stats: cache directory /home/marcin/.ccache cache hit (direct) 1 cache hit (preprocessed) 0 cache miss 15878 called for link 31 called for preprocessing 2655 unsupported source language 102 no input file 4733 files in cache 35882 cache size 2.7 Gbytes max cache size 3.0 Gbytes Why is ccache so inefficient for me? Why do I get so many misses? A: ccache will only reduce compilation time if you compile the same code several times; it's perfectly normal to see (nearly) only cache misses when compiling a project once, because the code being compiled hasn't been cached.
[ "stackoverflow", "0021030392.txt" ]
Q: GwtEvent does not get dispatched I have an application that uses EventBus for dispatching Application wide events. For some reason if I call one event and then try to register handler immediately before firing the second event it does not get dispatched. Is there any other way to dynamically register handlers on event ? Please see the code below: MyEntry.java package com.example.eventbus.client; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.event.shared.SimpleEventBus; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.RootPanel; public class MyEntry implements EntryPoint { SimpleEventBus bus; @Override public void onModuleLoad() { bus = new SimpleEventBus(); fireEvent1(); } private void fireEvent1(){ bus.addHandler(MyEvent1.TYPE,new MyEvent1.Handler() { @Override public void onEvent1(MyEvent1 event) { RootPanel.get().add(new Label("Event1")); fireEvent2(); } }); bus.fireEvent(new MyEvent1()); } private void fireEvent2(){ bus.addHandler(MyEvent2.TYPE,new MyEvent2.Handler() { @Override public void onEvent2(MyEvent2 event) { RootPanel.get().add(new Label("Event2")); //!!!!!This line is not being called } }); bus.fireEvent(new MyEvent2()); } } MyEvent1.java package com.example.eventbus.client; import com.google.gwt.event.shared.EventHandler; import com.google.gwt.event.shared.GwtEvent; public class MyEvent1 extends GwtEvent<MyEvent1.Handler>{ public static Type<MyEvent1.Handler> TYPE=new Type<MyEvent1.Handler>(); @Override public com.google.gwt.event.shared.GwtEvent.Type<Handler> getAssociatedType() { return TYPE; } @Override protected void dispatch(Handler handler) { System.out.println("dispatch Event1"); handler.onEvent1(this); } public interface Handler extends EventHandler{ public void onEvent1(MyEvent1 event); } } MyEvent2.java package com.example.eventbus.client; import com.google.gwt.event.shared.EventHandler; import com.google.gwt.event.shared.GwtEvent; public class MyEvent2 extends GwtEvent<MyEvent2.Handler>{ public static Type<MyEvent2.Handler> TYPE=new Type<MyEvent2.Handler>(); @Override public com.google.gwt.event.shared.GwtEvent.Type<Handler> getAssociatedType() { return TYPE; } @Override protected void dispatch(Handler handler) { System.out.println("dispatch Event2"); //!!!! This line is never called handler.onEvent2(this); } public interface Handler extends EventHandler{ public void onEvent2(MyEvent2 event); } } A: The issue is that while an event bus is firing events, it queues up any added or removed handler, and deals with them when it is finished. The idea is that if you only start listening to something while another event is still going off, then you are not interested for this round of events, but for the next round. The same thing happens when removing a handler - you will still hear about events that are still in the process of happening, but after the event bus is finished firing, it will deal with removal. Try changing your code to wire up both handlers before firing anything, then try firing one event to the other.
[ "gis.stackexchange", "0000112551.txt" ]
Q: Using FME to convert a MapInfo TAB to GML with style attributes I have a FME transformer that converts MapInfo TAB files to GML. What I would like is for the pen colour, pattern and width information to be brought across to the GML somehow. It really doesn't matter how it appears in the GML as the resulting file is parsed by some custom code anyway. It would probably be ideal for it to appear as an XML attribute on each feature in the file, though. I put in an AttributeExposer with the following attributes: mapinfo_pen_color mapinfo_pen_pattern mapingo_pen_width and I was hoping to see these in the output, but sadly not. What am I doing wrong? Here's what I have currently: The Pen_Color isn't coming through, so I added another attribute Test set to a constant to see whether the expression on the former was the issue. That does not appear in the output GML either. A: You can't build style into a GML the same way as you can in a MapInfo tab, however you can still bring that information over into your GML as an attribute against the features. You will need to add attributes to you GML feature to accept your MapInfo pen, color and width . Then link the exposed mapinfo_pen_* attributes to those attributes. Once that is done you could potentially use those attributes to style your features in the application that you are using to display the GML. You may want to decode the integer values into more user friendly definitions before writing them to the GML. If you want to retain the styling as part of the feature, KML may be a better option.
[ "stackoverflow", "0011765714.txt" ]
Q: IAsyncResult does not complete and locks UI I am making a REST call, the server side response is in the form of an XML. I am making this call asynchronously. I've test it as a Console application and it works as it should. However, when I test it on the XBOX , the asynchronous request is never completed. My processVideo method parses the XML and places the items into a List. I needed to reference this List from another class so I added (result.IsCompleted == false) to ensure that asynchronous call is completed before I reference and utilize the List. It seems that the asynchronous request is never completed and locks UI, any ideas? public void initilaizeRest() { WebRequest request = HttpWebRequest.Create(URI); request.Method = GET; // RequestState is a custom class to pass info to the callback RequestState state = new RequestState(request, URI); IAsyncResult result = request.BeginGetResponse(new AsyncCallback(getVideoList), state); Logger.Log("Querystate :"+QUERYSTATE+" URI:"+URI); /// Wait for aynchronous response to be completed while (result.IsCompleted == false) { Logger.Log("Sleeping"); Thread.Sleep(100); } } public void getVideoList(IAsyncResult result) { RequestState state = (RequestState)result.AsyncState; WebRequest request = (WebRequest)state.Request; HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result); //Process response switch (QUERYSTATE) { case (int)Querystate.SERIESQUERY: Logger.Log("Processing series state"); processSeries(response); break; case (int)Querystate.VIDEOQUERY: Logger.Log("Processing video state"); processVideo(response); break; } } public void processVideo(HttpWebResponse response) { //parses XML into an object and places items in a LIST } A: The while loop is your problem. You shouldn't wait like this for the async call to complete. You should do whatever you are wanting to do in the async callback that you send to the Begin method. The reason is that UI sets up a synchronization context which is used for async callbacks. The way this works is that the callbacks are marshalled onto the UI thread so that the UI context is maintained. Because your while loop is blocking your UI thread, the callback never occurs resulting in async call not completing. Hope this helps.
[ "stats.stackexchange", "0000445397.txt" ]
Q: Bayesian Homework: Uniform Prior Suppose posterior density of parameter $\theta$ is $$\pi(\theta|\mathbf x)=\frac{\Gamma(5)}{\Gamma(3)\Gamma(2)}\theta^{3-1}(1-\theta)^{2-1}.$$ Now I have to find which of the two hypotheses $H_1:\theta\le0.5$ and $H_2:\theta>0.5,$ has greater posterior probability under the uniform prior? I have the solution of the question too, but I didn't understand. It said: $P(H_1 \text{is true}|\mathbf x)=\int_{0}^{0.5}\frac{\Gamma(5)}{\Gamma(3)\Gamma(2)}\theta^{3-1}(1-\theta)^{2-1}d\theta$ What is uniform prior? Why didn't they incorporate the information of uniform prior in the above integration? A: As also pointed out in the comments, you don't need prior since all you need is the posterior: $$P(\text{$H_1$ is true}|\mathbf{x})=P(\theta\leq0.5|\mathbf{x})=\int_0^{0.5} \pi(\theta|\mathbf{x})d\theta$$ Since this is Beta distribution, $0\leq\theta\leq1$, a uniform prior on $\theta$ would be $\pi(\theta)=1$ and you wouldn't notice it in the integration even if it was used mistakenly.
[ "stackoverflow", "0059549423.txt" ]
Q: Adding a (click) event handler directly to mat-step? Is it possible to add a click event handler directly to the mat-step element? I tried adding one to step 2 in this demo, but I don't see the click being logged: The code that I tried: HTML: <mat-step label="Step 2" (click)="click()" optional> // Other stuff </mat-step> TS: click() { console.log("CLICKED STEP 2") } Stackblitz Demo to reproduce the behaviour. Related Angular Material Issue https://github.com/angular/components/issues/18080 It only works when completed on step 1 is true A: You can use (selectionChange) event for parent tag which is mat-horizontal-stepper. HTML: <mat-horizontal-stepper linear (selectionChange)="selectionChange($event)"> <mat-step label="Step 1" [completed]="step1Complete"> <h4>Step 1</h4> <button (click)="toggleStep1Complete()" mat-flat-button color="primary">{{ step1Complete === true ? "Toggle:Complete" : "Toggle:Incomplete"}} </button> <div> <button mat-button matStepperNext>Next</button> </div> </mat-step> <mat-step label="Step 2" optional> <p>Step 2</p> <div> <button mat-button matStepperPrevious>Back</button> <button mat-button matStepperNext>Next</button> </div> </mat-step> <mat-step label="Step 3"> <p>Step 3</p> </mat-step> </mat-horizontal-stepper> TS Code: import { StepperSelectionEvent } from '@angular/cdk/stepper'; -- Better to use to get an intellisense about properties and available methods selectionChange(event: StepperSelectionEvent) { console.log(event.selectedStep.label); let stepLabel = event.selectedStep.label; if (stepLabel == "Step 2") { console.log("CLICKED STEP 2"); } } A working demo EDIT: If you want every step should be clickable or available for user then you have to remove linear attribute of mat-horizontal-stepper or just set it to false. Documentation
[ "stackoverflow", "0011048734.txt" ]
Q: Convert a single datarow in a CSV like string in C# How can I convert a single datarow (of a datatable) into a CSV like string with only few C# commands. In other words into a string like "value_1;value_2;...;value_n" A: Quick and dirty for a single DataRow: System.Data.DataRow row = ...; string csvLine = String.Join( CultureInfo.CurrentCulture.TextInfo.ListSeparator, row.ItemArray); If you do not care about the culture specific separator you may do this to convert a full DataTable: public static string ToCsv(System.Data.DataTable table) { StringBuilder csv = new StringBuilder(); foreach (DataRow row in table.Rows) csv.AppendLine(String.Join(";", row.ItemArray)); return csv.ToString(); } Here a more complex example if you need to handle a little bit of formatting for the values (in case they're not just numbers). public static string ToCsv(DataTable table) { StringBuilder csv = new StringBuilder(); foreach (DataRow row in table.Rows) { for (int i = 0; i < row.ItemArray.Length; ++i) { if (i > 0) csv.Append(CultureInfo.CurrentCulture.TextInfo.ListSeparator); csv.Append(FormatValue(row.ItemArray[i])); } csv.AppendLine(); } return csv.ToString(); } Or, if you prefer LINQ (and assuming table is not empty): public static string ToCsv(DataTable table, string separator = null) { if (separator == null) separator = CultureInfo.CurrentCulture.TextInfo.ListSeparator; return table.Rows .Cast<DataRow>() .Select(r => String.Join(separator, r.ItemArray.Select(c => FormatValue(c))) .Aggregate(new StringBuilder(), (result, line) => result.AppendLine(line)) .ToString(); } Using this private function to format a value. It's a very naive implementation, for non primitive types you should use TypeConverter (if any, see this nice library: Universal Type Converter) and quote the text only if needed (2.6): private static string FormatValue(object value) { if (Object.ReferenceEquals(value, null)) return ""; Type valueType = value.GetType(); if (valueType.IsPrimitive || valueType == typeof(DateTime)) return value.ToString(); return String.Format("\"{0}\"", value.ToString().Replace("\"", "\"\""); } Notes Even if there is a RFC for CSV many applications does not follow its rules and they handle special cases in their very own way (Microsoft Excel, for example, uses the locale list separator instead of comma and it doesn't handle newlines in strings as required by the standard). A: Here is a start: StringBuilder line = new StringBuilder(); bool first = true; foreach (object o in theDataRow.ItemArray) { string s = o.Tostring(); if (s.Contains("\"") || s.Contains(",")) { s = "\"" + s.Replace("\"", "\"\"") + "\""; } if (first) { first = false; } else { line.Adppend(','); } line.Append(s); } String csv = line.ToString(); It will handle quoted values and values containing the separator, i.e. a value that contains quotation marks or the separator needs to be surrounded by quotation marks, and the quotation marks inside it needs to be escaped by doubling them. Note that the code uses comma as separator, as that's what the C in CSV stands for. Some programs might be more comfortable using semicolon. Room for imrovement: There are also other characters that should trigger quoting, like padding spaces and line breaks. Note: Even if there is a standard defined for CSV files now, it's rarely followed because many programs were developed long before the standard existed. You just have to adapt to the peculiarities of any program that you need to communicate with.
[ "askubuntu", "0000680659.txt" ]
Q: how to do an on-change one-way sync/backup between folders on primary drive to secondary drive? I have two HDs in my machine. All of Ubuntu is installed on the main drive. The 2nd HD is empty and is for backup purposes. I want to configure a one-way sync/backup of /home/* to the 2nd HD. I know I can use rsync and create a cron job but I am wondering if there is any way to do the sync/copy when files are changed in /home/*? A: I use lsyncd for this exact thing. It will watch a directory and sync changes over whenever files change, without needing cron. This page over at LiquidWeb may help you get up and running. This page over at Rackspace may help too, but seems to require more manual labor.
[ "math.stackexchange", "0000182861.txt" ]
Q: Trigonometry problem involving oblique triangle How would I solve the following problem? A ship sails $15$ miles on a course $S40^\circ10'W$(south 40 degrees 10 minutes west) and then $21$ miles on a course $N28^\circ20'W$(north 28 degrees 20 minutes west). Find the distance and direction of the last position from the first. I think that to solve this problem I must make an oblique triangle. One side of the triangle would be $15$ and have an angle of $40^\circ10'$ and the other side would be $21$ and have a angle of $28^\circ20'$. I think what I have to find is the side which connect these two sides. A: The distances sailed are small enough that the curvature of the Earth makes no significant difference and we can use plane trigonometry. Let $P$ be our start point, $Q$ where we change course, and $R$ the end point. First choose $P$. Then draw a North-South thin line through $P$ as a guide. To reach $Q$ we turned $40^\circ 10'$ clockwise from due South, and sailed $15$ km. Draw $Q$. Draw a thin North-South line through $Q$ as a guide. We sail $21$ km in a direction $28^\circ 20'$ counterclockwise from due North. Draw the point $R$ that we reach. By properties of transversals to parallel lines (our two guide lines), $$\angle Q=40^\circ 10'+28^\circ 20'=68^\circ30'.$$ We can now find the required distance $PR$ we are from our start position by using the Cosine Law. For $$(PR)^2=15^2+21^2-2(15)(21)\cos 68^\circ30'.$$ (I get $PR\approx 20.86$, but my calculations are not to be trusted.) Now for the direction. We will know everything once we know $\angle A$. For this, we could use the Cosine Law, but the Sine Law is easier. We have $$\frac{\sin A}{21}=\frac{\sin 68.5^\circ}{PR}.$$ I get (but again don't trust me) that $A\approx 69.5^\circ$. If we use the North-South guideline, our position at $R$, as viewed from $P$ is obtained by facing due South and turning clockwise through about $40^\circ10'+69^\circ 30'$. To express this in the notation that your problem was put, subtract from $180^\circ$. We get $70^\circ 20'$. So $R$ is North, $70^\circ 20'$ West from $P$.
[ "stackoverflow", "0008544771.txt" ]
Q: How to write data with FileOutputStream without losing old data? If you work with FileOutputStream methods, each time you write your file through this methods you've been lost your old data. Is it possible to write file without losing your old data via FileOutputStream? A: Use the constructor that takes a File and a boolean FileOutputStream(File file, boolean append) and set the boolean to true. That way, the data you write will be appended to the end of the file, rather than overwriting what was already there. A: Use the constructor for appending material to the file: FileOutputStream(File file, boolean append) Creates a file output stream to write to the file represented by the specified File object. So to append to a file say "abc.txt" use FileOutputStream fos=new FileOutputStream(new File("abc.txt"),true);
[ "math.stackexchange", "0002033338.txt" ]
Q: Complex exponential and the Cauchy problem $\begin{cases} f'=f\\ f(0)=1 \end{cases}$ How do you prove that the exponential function is the unique solution to this Cauchy problem in $\mathbb{C}$? $$\begin{cases} f'=f\\ f(0)=1 \end{cases}$$ A: As suggested, see that $$g(z)=\frac{f(z)}{e^z}$$ Differentiate this to see that $$g'(z)=\frac{f'(z)e^z-f(z)e^z}{e^{2z}}=0$$ $$g'(z)=0$$ Integrate both sides to now see that $$g(z)=C\equiv\frac{f(z)}{e^z}$$ Let $z=0$ to show that $C=1$, leaving us with $$1=\frac{f(z)}{e^z}\implies f(z)=e^z$$
[ "drupal.stackexchange", "0000020900.txt" ]
Q: Display one recent comment in node teaser? Trying to find the easiest way to include the first most recent comment in my view that is using the 'teaser' mode. I am using the rate module to display number of votes in the view as well which doesn't have a 'field' to add so that is why I need to use teaser mode instead of fields mode. Thanks A: Add Views, Token, and Viewfield modules. Make a new view. The first page gives you most of it: Show comments, newest first. Make a page, limit the number to 1. Continue & Edit, and set the contextual filter to Content: Nid. Be sure and save it. :-) Edit your content type. Add a new field, of type Views. Set the default view to be the 'recent comment' one you just made. Under 'Default Values,' have it always use the default view, and have [node:id] as an argument. Save that. Now you can manage the display of this field in the 'manage display' tab, and place it in the 'teaser' view. You might find that showing the whole comment under the teaser looks wrong, so then it's time to go back to the view and tweak it so it uses fields instead of the whole comment. HTH.
[ "es.stackoverflow", "0000103831.txt" ]
Q: Click en el elemento hijo Hice una directiva que lo inserto en el div padre para restringir algunas cosas (tales restricciones que realizo no pongo en el ejemplo), pero también quiero escuchar cuando se hace click en el segundo elemento solo en el segundo elemento, como puedo escuchar cuando se hace click? Nota: solo quiero insertar en el div padre la directiva angular .module('MyApp', []) .directive( 'clickMe', function() { return { link: function(scope, element) { element.on('click', function() { console.log('click'); }); }, }; } ); <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="MyApp"> <div click-me> clickeame <div id="one"> click 2 </div> </div> </div> A: Es tan fácil como comprobar quién está recibiendo el evento: angular .module('MyApp', []) .directive( 'clickMe', function() { return { link: function(scope, element) { element.on('click', function(evento) { if (evento.target.id=='one') { console.log('Click on click 2'); } else { console.log('click'); } }); }, }; } ); <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="MyApp"> <div click-me> clickeame <div id="one"> click 2 </div> </div> </div>
[ "dba.stackexchange", "0000152064.txt" ]
Q: How can I redirect database requests in my postgres server So I have a list of(lot many) scrapers which push lot many data into one of my database location. Unfortunately I have a requirement that my database location have to be changed for some performance issues. Rather than changing my so many scripts config can I have some mechanism implemented in my db server so that database requests coming from certain IP(machines) I would redirect them to other database/server? A: As @horse_with_no_name already comment: you can use pgbouncer to do that. Basically you need to create a pool configuration, and during your maintenance you ajust the pool config to a new server or database. Take a look at the session [databases] on /etc/pgbouncer.ini file: [databases] ; no connection info enforces unix socket foodb = ; bardb config bardb = host=127.0.0.1 dbname=bardb So, if you want to redirect the connections for the database bardb for another database, what you need to do is edit the dbname and reload de pgbouncer service. E.G.: ; bardb config bardb = host=127.0.0.1 dbname=maintenancedb Please, take a look at the documentation[1] for more details. You can do the same with the pgpool[2]. Hope it helps. References: https://pgbouncer.github.io/config.html http://www.pgpool.net
[ "stackoverflow", "0019641866.txt" ]
Q: ASP.NET PasswordRecovery Control - Always "Success" even when wrong answer supplied? I'm working with a PasswordRecovery control that is always resetting passwords, even when the answer the user provides is incorrect. It doesn't seem to be firing the "OnAnswerLookupError" event. Has anyone ever run into this or have any idea what I'm doing wrong? Pretty straightforward code, I'll paste it below. The only real customization it's got is letting the users who are locked out reset their passwords (per request from our client): <%@ Page Title="Password Recovery" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="PasswordRecovery.aspx.cs" Inherits="OurApp.UI.Account.PasswordRecovery" %> <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> </asp:Content> <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <h2> Password Recovery </h2> <p> Follow instructions to reset your password. </p> <asp:Label ID="lblMessage" runat="server" Font-Bold="true" ForeColor="red" /> <asp:PasswordRecovery SuccessText="Your password was successfully reset and emailed to you." OnAnswerLookupError="UserLookupError" OnUserLookupError="UserLookupError" OnVerifyingUser="UserCheck" QuestionFailureText="Incorrect answer. Please try again." runat="server" ID="RecoveryInput" UserNameFailureText="Username not found." OnSendingMail="RecoveryInput_SendingMail"> <MailDefinition IsBodyHtml="false" BodyFileName="~/Account/email.ascx" From="[email protected]" Subject="Our App - Password Reset" Priority="High"> </MailDefinition> <UserNameTemplate> <asp:Panel ID="pnl1" runat="server" DefaultButton="submit"> <dl> <dd>User Name</dd> <dd> <asp:TextBox ID="Username" runat="server" AUTOCOMPLETE="OFF" /> </dd> <dt></dt> <dd> <asp:Button ID="submit" CausesValidation="true" ValidationGroup="PWRecovery" runat="server" CommandName="Submit" Text="Submit" /> </dd> <dt></dt> <dd> <p class="Error"><asp:Literal ID="ErrorLiteral" runat="server"></asp:Literal> </p> </dd> </dl> </asp:Panel> </UserNameTemplate> <QuestionTemplate> <asp:panel ID="pnl1" runat="server" DefaultButton="submit"> Hello <asp:Literal runat="server" ID="personname" />, <p> You must answer your recovery question in order to have a new email sent to you. </p> <dl> <dt>Question:</dt> <dd> <asp:Literal runat="server" ID="Question" /> </dd> <dt></dt> <dt>Answer:</dt> <dd> <asp:TextBox runat="server" ID="Answer" AUTOCOMPLETE="OFF" /> </dd> <dt></dt> <dd> <asp:Button runat="server" ID="submit" Text="Submit" CommandName="submit" /> </dd> <dt></dt> <dd> <p class="Error"> <asp:Literal ID="FailureText" runat="server"></asp:Literal> </p> </dd> </dl> </asp:panel> </QuestionTemplate> </asp:PasswordRecovery> <asp:HyperLink NavigateUrl="~/Account/Login.aspx" runat="server">Login</asp:HyperLink> </asp:Content> public partial class PasswordRecovery : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { lblMessage.Text = string.Empty; } protected void UserCheck(object sender, EventArgs e) { MembershipUser mu = Membership.GetUser(RecoveryInput.UserName); if (mu == null) { UserLookupError(sender, e); return; } if (mu.IsLockedOut) { //UserLookupError(sender, e); //return; mu.UnlockUser(); } } protected void UserLookupError(object sender, EventArgs e) { lblMessage.Text = "There was a problem resetting your password. Please contact your Administrator or Account Executive for assistance."; } protected void RecoveryInput_SendingMail(object sender, MailMessageEventArgs e) { try { MembershipUser mu = Membership.GetUser(RecoveryInput.UserName); mu.Comment = "MustChangePassword"; Membership.UpdateUser(mu); } catch (Exception ex) { Utilities.ErrorHandling.HandleError(ex); lblMessage.Text = "There was a problem resetting your password. Please contact your administrator."; } } } A: Update: This ended up being due to an internal implementation of the SqlMembershipProvider and failing to capture the return code of the aspnet_Membership_ResetPassword stored procedure. It's not a problem with ASP.NET itself. Due to the way we have to access this stored proc (think layers of an onion) -- it wasn't readily apparent to me. This question can be closed!
[ "stackoverflow", "0047407357.txt" ]
Q: How to return multiple values from a filter function? I am trying to return multiple values in typescript, implementing search filter. If am return separately works fine, but if am trying to return both it seems not working. Here's my code: import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'category' }) export class CategoryPipe implements PipeTransform { transform(categories: any, searchText: any): any { if(searchText == null) return categories; return categories.filter( function(category){ var a = category.DistrictName.toLowerCase().indexOf(searchText.toLowerCase()) > -1; var b = category.Population.toLowerCase().indexOf(searchText.toLowerCase()) > -1; return a; //return [a,b]; } ) } } A: Returning categories.filter(categories) will return array of all the value inside categories array which match the condition mentioned in the logic. In your case, you are trying to return the boolean values. Basically, if you want to filter among the categories where district name has some search text or population has some search text then you can do something like below: var searchText = 'ist2'; var categories = [ { 'DistrictName': 'dist1', 'Population': 'pop1' }, { 'DistrictName': 'dist2', 'Population': 'popist2' }, { 'DistrictName': 'dist3', 'Population':'pop3' } ]; function test() { return categories.filter( function(category){ return category.DistrictName.toLowerCase(). indexOf(searchText.toLowerCase()) > -1 || category.Population.toLowerCase() .indexOf(searchText.toLowerCase()) > -1; }); } var filteredArray = test(); console.log(filteredArray); //output **[{ 'DistrictName': 'dist2', 'Population': 'popist2' }]**
[ "stackoverflow", "0040317365.txt" ]
Q: How to remove property from a child element? I’m using an image to replace the regular checkbox element, and the filter property for visual effects when unchecked selected to gray the image. .ckbx { display: none; } .ckbx + label { background: url('https://pixabay.com/static/uploads/photo/2012/04/11/12/08/check-mark-27820_960_720.png') no-repeat; background-size: 100%; height: 50px; width: 50px; padding: 0px; display: inline-block; filter: grayscale(100%) opacity(30%); } .ckbx:checked + label { filter: none; } label span { margin-left: 55px; display: inline-block; width: 200px; } <div> <input type="checkbox" class="ckbx" id="bike"> <label for="bike"><span>I have a bike</span></label> </div> The problem is that the span is influenced by the filter so we can’t read the text when changing states (checked/unchecked). How to make the span unaffected by the filter (use native CSS)? A: Demo: https://jsfiddle.net/z63b6qwL/ You can't remove filter from child element, but you can change your html and css a little: HTML: <div> <input type="checkbox" class="ckbx" id="bike"> <label for="bike"><span class="image"></span><span class="text">I have a bike</span></label> </div> CSS: .ckbx { display: none; } .ckbx + label > .image { background: url('https://pixabay.com/static/uploads/photo/2012/04/11/12/08/check-mark-27820_960_720.png') no-repeat; background-size: 100%; height: 50px; width: 50px; padding: 0px; display: inline-block; filter: grayscale(100%) opacity(30%); vertical-align: middle; } .ckbx:checked + label > .image { filter: none; } label span.text { margin-left: 5px; display: inline-block; width: 200px; }
[ "stackoverflow", "0055289244.txt" ]
Q: Image Widget -> Dynamic -> Shortcode -> No output I'm using Elementor Pro and want to display an image via a custom shortcode (https://docs.elementor.com/article/449-dynamic-shortcode): But it isn't working. There is simply nothing displayed. Neither in the editor, nor in the frontend. Also not if I remove the brackets [ ... ] around the shortcode and try brand_banner only. It does not produce any DOM output in the frontend, just an empty elementor-widget-wrap div: <div class="elementor-element elementor-element-4f1547ad elementor-column elementor-col-50 elementor-inner-column" data-id="4f1547ad" data-element_type="column"> <div class="elementor-column-wrap elementor-element-populated"> <div class="elementor-widget-wrap"> </div> </div> </div> However, if I use a simple text editor widget and put the shortcode in, it works as expected: DOM: <div class="elementor-element elementor-element-37728dd elementor-widget elementor-widget-text-editor" data-id="37728dd" data-element_type="widget" data-widget_type="text-editor.default"> <div class="elementor-widget-container"> <div class="elementor-text-editor elementor-clearfix"> <img src="https://some.domain.com/wp-content/uploads/banner-a.jpg"></div> </div> </div> </div> This is the code for the shortcode: public function shortcode_brand_banner( $atts ) { $brand = $this->getRandomBrandFromPool(); $variantIndex = 1; $variantLabel = [ '0', 'a', 'b', 'c' ]; // Return the rendered image HTML. return ( types_render_field( 'image-brand-' . $variantLabel[ $variantIndex ], [ 'post_id' => $brand->post->ID ] ) ); } I thought maybe it is because it doesn't expect rendered image HTML, but only an image URL. So I changed the code to this, but it doesn't work either: public function shortcode_brand_banner( $atts ) { $brand = $this->getRandomBrandFromPool(); $variantIndex = 1; $variantLabel = [ '0', 'a', 'b', 'c' ]; // Only return image URL like "https://some.domain.com/wp-content/uploads/banner-a.jpg" $image = get_post_meta( $brand->post->ID, 'wpcf-image-brand-' . $variantLabel[ $variantIndex ] )[ 0 ]; return ( $image ); } What am I doing wrong here? How can I display an image via Dynamic Shortcode? A: To close this question, long story short: The image widget was kind of never supposed to support the "Shortcode" feature, because internally the function expects an array, which a Shortcode can not return. The Shortcode feature was now removed from the Image widget. See: https://github.com/elementor/elementor/issues/7730
[ "stackoverflow", "0004879336.txt" ]
Q: BeginRequest-like filter in MVC 3? I have some code in my application that I need to execute on every request, before anything else executes (even before authentication). So far I've been using the Application_BeginRequest event in my Global.asax, and this has worked fine. But this code needs to hit the database, and doing this from Global.asax doesn't feel right for some reason. Also, the Ninject.MVC3 nuget I'm using won't inject dependencies into my HttpApplication ctor. So what I decided to do is move this code into its own global action filter. The problem I'm having now is that no matter what Order or FilterScope I give this filter, I can't get it to execute first; my authorization filter always beats it. MSDN seems to confirm this: Filter Order Filters run in the following order: Authorization filters Action filters Response filters Exception filters For example, authorization filters run first and exception filters run last. Within each filter type, the Order value specifies the run order. Within each filter type and order, the Scope enumeration value specifies the order for filters. I know I can use an HttpModule, but that doesn't feel very MVCish, so I am trying to exhaust all possiblities before going that route, which leads to my question: Is there a BeginRequest equivalent for global action filters? A: You could do this in the Initialize method of a base controller. Another possibility is to register a global filter: public class MyGlobalFilter : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { // that's gonna be hit } } and in the RegisterGlobalFilters event of your Global.asax: public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); filters.Add(new MyGlobalFilter()); }
[ "stackoverflow", "0018017879.txt" ]
Q: MFC Formatting Dates with Locale I have to print out a date in "extendend mode", like this: Thursday 02 August 2013 Using COleDateTime I have no problems, but I need to print this stuff in local language, in my case Italian. I've found this code in an old compiler that use base SDK commands: char lpDateStr[128], lpTimeStr[128]; SYSTEMTIME today; WString str; FileTimeToSystemTime( &IdUnicoK1, &today ); GetDateFormat( LOCALE_USER_DEFAULT, DATE_LONGDATE, &today, NULL, lpDateStr, sizeof(lpDateStr) ); GetTimeFormat( LOCALE_USER_DEFAULT, TIME_FORCE24HOURFORMAT, &today, NULL, lpTimeStr, sizeof(lpTimeStr) ); str.Sprintf( "%s, %s", lpDateStr, lpTimeStr ); that in MFC, according to the MSDN is: SYSTEMTIME stBuf; CString strD; CString strT; CString strData; FileTimeToSystemTime( &m_pK1->m_ftMyData, &stBuf ); strD = _T("dddd dd MMMM yyyy"); GetDateFormat( LOCALE_USER_DEFAULT, DATE_LONGDATE, &stBuf, NULL, strD.GetBuffer(), strD.GetLength() ); strT = _T("HH':'mm':'ss"); GetTimeFormat( LOCALE_USER_DEFAULT, TIME_FORCE24HOURFORMAT, &stBuf, NULL, strT.GetBuffer(), strT.GetLength() ); strData.Format( _T("%s, %s"), strD, strT ); but this lead me to the following result: dddd dd MMMM yyyy, HH':'mm':'ss Where I'm doing wrong? A: Your MFC version is not functionally equivalent to the "straight C" version. You can use the first version and convert the result to a CString, like: CString strDateTime; strDateTime.Format("%s, %s", lpDateStr, lpTimeStr); Otherwise, you will need to do something like: FileTimeToSystemTime( &m_pK1->m_ftMyData, &stBuf ); GetDateFormat( LOCALE_USER_DEFAULT, DATE_LONGDATE, &stBuf, NULL, strD.GetBuffer(128), 128); GetTimeFormat( LOCALE_USER_DEFAULT, TIME_FORCE24HOURFORMAT, &stBuf, NULL, strT.GetBuffer(128), 128); strD.ReleseBuffer(); strT.ReleseBuffer(); strData.Format(_T("%s, %s"), strD, strT);
[ "tex.stackexchange", "0000148463.txt" ]
Q: How can I display date information in document class "amsproc"? I tried to display the date information by the command \date{June, 2013} in document class "amsproc", but failed. How to fix this problem? Here is my LaTeX code: \documentclass{amsproc} \begin{document} \title{This is a title} % Remove any unused author tags. % author one information \author{Shan Zhang} \address{Department of Economics, University of Pennsylvania} \curraddr{Philidelphia, PA} \email{[email protected]} \thanks{This is thanks 1} % author two information \author{Si Li} \address{Department of Economics, UToronto} \curraddr{Toronto} \email{[email protected]} \thanks{This is thanks 2} \date{June, 2013} \dedicatory{To our families} \begin{abstract} This is abstract. \end{abstract} \maketitle \section{Section 1} Let's do section 1. \end{document} A: The amsart class prints the date in the footnote before the thanks. Maybe you could just switch to using the amsart class. Or you can adopt its definition of the respective macro \@adminfootnotes for use with amsproc. The definitions in amsproc and amsart differ only in the line concerning the date: \documentclass{amsproc} \makeatletter \def\@adminfootnotes{% \let\@makefnmark\relax \let\@thefnmark\relax \ifx\@empty\@date\else \@footnotetext{\@setdate}\fi%% <------ added \ifx\@empty\@subjclass\else \@footnotetext{\@setsubjclass}\fi \ifx\@empty\@keywords\else \@footnotetext{\@setkeywords}\fi \ifx\@empty\thankses\else \@footnotetext{% \def\par{\let\par\@par}\@setthanks}% \fi } \makeatother \begin{document} \title{This is a title} % author one information \author{Shan Zhang} \address{Department of Economics, University of Pennsylvania} \curraddr{Philidelphia, PA} \email{[email protected]} \thanks{This is thanks 1} % author two information \author{Si Li} \address{Department of Economics, UToronto} \curraddr{Toronto} \email{[email protected]} \thanks{This is thanks 2} \date{June, 2013} \dedicatory{To our families} \begin{abstract} This is abstract. \end{abstract} \maketitle \section{Section 1} Let's do section 1. \end{document} Depending on your use case you must redefine \@maketitle to include your date somewhere, or use e.g. \patchcmd from the etoolbox package to change a part of the macro. A: From the documentation of amsproc, page 1: The AMS produces three major types of publications: journals (both print and electronic), proceedings volumes, and monographs. There is a core AMS document class for each: amsart, amsproc and amsbook, respectively. and page 4: Since amsproc is designed for proceedings volumes, the date field is not needed. Hence, this field is not supported in amsproc. Do you REALLY need this document class?
[ "stackoverflow", "0002915399.txt" ]
Q: SVN naming convention: repository, branches, tags Just curious what your naming conventions are for the following: Repository name Branches Tags Right now, we're employing the following standards with SVN, but would like to improve on it: Each project has its own repository Each repository has a set of directories: tags, branches, trunk Tags are immutable copies of the the tree (release, beta, rc, etc.) Branches are typically feature branches Trunk is ongoing development (quick additions, bug fixes, etc.) Now, with that said, I'm curious how everyone is not only handling the naming of their repositories, but also their tags and branches. For example, do you employ a camel case structure for the project name? So, if your project is something like Backyard Baseball for Youngins, how do you handle that? backyardBaseballForYoungins backyard_baseball_for_youngins BackyardBaseballForYoungins backyardbaseballforyoungins That seems rather trivial, but it's a question. If you're going with the feature branch paradigm, how do you name your feature branches? After the feature itself in plain English? Some sort of versioning scheme? I.e. say you want to add functionality to the Backyard Baseball app that allows users to add their own statistics. What would you call your branch? {repoName}/branches/user-add-statistics {repoName}/branches/userAddStatistics {repoName}/branches/user_add_statistics etc. Or: {repoName}/branches/1.1.0.1 If you go the version route, how do you correlate the version numbers? It seems that feature branches wouldn't benefit much from a versioning schema, being that 1 developer could be working on the "user add statistics" functionality, and another developer could be working on the "admin add statistics" functionality. How are these do branch versions named? Are they better off being: {repoName}/branches/1.1.0.1 - user add statistics {repoName}/branches/1.1.0.2 - admin add statistics And once they're merged into the trunk, the trunk might increment appropriately? Tags seem like they'd benefit the most from version numbers. With that being said, how are you correlating the versions for your project (whether it be trunk, branch, tag, etc.) with SVN? I.e. how do you, as the developer, know that 1.1.1 has admin add statistics, and user add statistics functionality? How are these descriptive and linked? It'd make sense for tags to have release notes in each tag since they're immutable. But, yeah, what are your SVN policies going forward? A: I use the trunk, tags, branches model. Trunk: should always be in a stable form. (not necessarily releasable but stable as in no compiler errors) I typically make minor changes and new features that are small and can be completed in less than a single day. If I will be developing something that takes several days and checkins would leave the trunk in an unstable state, I will create a branch. branches: are for feature development that may leave the trunk in an unstable state. It is also used for "testing" new features and ideas. I make sure to do a trunk to branch update merge to keep the latest developments in trunk in sync with my branch. tags: are for releases or stable versions of the code that I would want to quickly get back to. Typically I use these for a particular version (1.00) of a module or application. I try not to make any check-ins to tags. If there are bugs, then those changes are made in trunk and will be there for next release. The only exceptions I make are for emergency bugs. This implies that a tag will have been properly QA'd and is quite stable.
[ "stackoverflow", "0040356704.txt" ]
Q: Ordering then Grouping in Mysql I'm trying to order mysql then group it. this is my table : |------ |Column|Type|Null|Default |------ |//**id**//|int(11)|No| |consultantid|int(11)|Yes|NULL |startdate|datetime|Yes|NULL |enddate|datetime|Yes|NULL |target|varchar(255)|No| |dateinserted|datetime|No|CURRENT_TIMESTAMP == Dumping data for table consultant_targets |1|1|2016-11-01 00:00:00|2016-11-29 00:00:00|10000|2016-10-31 21:34:55 |2|1|2016-10-31 00:00:00|2016-11-23 00:00:00|15000|2016-10-31 22:03:09 The second record is inserted later than the first, and thats what i'm looking to get - so if there was 50 of these it would just grab the latest one. This is my SQL : SELECT * FROM ( SELECT ct.*, u.username, u.colorcode FROM consultant_targets ct INNER JOIN user u ON u.id = ct.consultantid ORDER BY dateinserted desc ) AS ctu GROUP BY consultantid But im just getting the first row every time, the one with the 10000 target A: You can use NOT EXISTS() : SELECT t.*, u.username, u.colorcode FROM consultant_targets t INNER JOIN user u ON u.id = t.consultantid WHERE NOT EXISTS(SELECT 1 FROM consultant_targets s WHERE t.consultantid = s.consultantid AND s.dateinsereted > t.dateinsereted)
[ "stackoverflow", "0034672549.txt" ]
Q: RabbitMQ Windows - Start Server automatically We are working with RabbitMQ on a Windows Environment. At the moment I have installed RabbitMQ and it runs as a Service. It starts automatically as shown here: But if I send a Message or if I query the server here: http://localhost:15672/#/queues the server returns 404 Now, if I open the Shell and hit this command: rabbitmq-server The server startup and I can send and receive messages and browse the administration page. Questions: What is the difference then between RabbitMQ Windows Service and RabbitMQ Server? How can I have the RabbitMQ Server run as a daemon when the PC boot? Is there a command or configuration for that? A: After further investigations I found out that all RabbitMQ have been installed before configuring the plugin rabbitmq_management and amqp_client so actually the Windows Service was running without doing anything. I fixed the problem on all my server by doing these steps: Remove RabbitMQ using rabbitmq-service stop, rabbitmq-service remove Remember that the CMD must run under Administrator credentials on Windows 10 and Windows Server 2012 Install the plugin using rabbitmq-plugins enable rabbitmq_management Re-install and start the serice rabbitmq-service install, rabbitmq-service start Also, I restarted Windows and verified that after the reboot the RabbitMQ was up and running.
[ "stackoverflow", "0016540746.txt" ]
Q: compare file line by line python What is the most elegant way to go through a sorted list by it's first index? Input: Meni22 xxxx xxxx Meni32_2 xxxx xxxx Meni32_2 xxxx xxxx Meni45_1 xxxx xxxx Meni45_1 xxxx xxxx Meni45 xxxx xxxx Is it to go trough line by line: list1 = [] list2 = [] for line in input: if line[0] not in list1: list.append(line) else: list2.append(line) Example won't obviously work. It adds the first match of the line[0] and continues. I would rather have it go through the list, add to list1 lines that it finds only once and rest to list2. After script: List1: Meni22 xxxx xxxx Meni45 xxxx xxxx List2: Meni45_1 xxxx xxxx Meni45_1 xxxx xxxx Meni32_2 xxxx xxxx Meni32_2 xxxx xxxx A: Since the file is sorted, you can use groupby from itertools import groupby list1, list2 = res = [], [] with open('file1.txt', 'rb') as fin: for k,g in groupby(fin, key=lambda x:x.partition(' ')[0]): g = list(g) res[len(g) > 1] += g Or if you prefer this longer version from itertools import groupby list1, list2 = [], [] with open('file1.txt', 'rb') as fin: for k,g in groupby(fin, key=lambda x:x.partition(' ')[0]): g = list(g) if len(g) > 1: list2 += g else: list1 += g A: You can use collections.Counter: from collections import Counter lis1 = [] lis2 = [] with open("abc") as f: c = Counter(line.split()[0] for line in f) for key,val in c.items(): if val == 1: lis1.append(key) else: lis2.extend([key]*val) print lis1 print lis2 output: ['Meni45', 'Meni22'] ['Meni32_2', 'Meni32_2', 'Meni45_1', 'Meni45_1'] Edit: from collections import defaultdict lis1 = [] lis2 = [] with open("abc") as f: dic = defaultdict(list) for line in f: spl =line.split() dic[spl[0]].append(spl[1:]) for key,val in dic.items(): if len(val) == 1: lis1.append(key) else: lis2.append(key) print lis1 print lis2 print dic["Meni32_2"] #access columns related to any key from the the dict output: ['Meni45', 'Meni22'] ['Meni32_2', 'Meni45_1'] [['xxxx', 'xxxx'], ['xxxx', 'xxxx']]
[ "stackoverflow", "0022065864.txt" ]
Q: AdMobs causes project error: Multiple dex files define Lcom/google/ads/AdRequest$ErrorCode I'm trying to add adMob to my Android project. When I add GoogleAdMobAdsSdk-6.4.1.jar to libs folder it gives me a dialog that contains this text Your project contains error(s), please fix them before running your application. and in console, it gives me this message Unable to execute dex: Multiple dex files define Lcom/google/ads/AdRequest$ErrorCode; Conversion to Dalvik format failed: Unable to execute dex: Multiple dex files define Lcom/google/ads/AdRequest$ErrorCode; Consider that I added the GoogleAdMobAdsSdk-6.4.1.jar in Build path and did clean and restarted the eclipse and it still gives me the error. Also I'm using 'google-play-services_lib' because my app is Google Map Api V2. When I remove the GoogleAdMobAdsSdk-6.4.1.jar from libs folder, the app runs and gives me ClassNotFound Exception. A: I Solved it, The Problem was because I was trying to add GoogleAdMobAdsSdk-6.4.1.jar while using google-play-services_lib I done like what in this link and it now works
[ "stackoverflow", "0048085705.txt" ]
Q: How to use entire plugin configuration in Maven Mojo I am trying to build a Maven plugin that uses a Spring Boot application internally. Now, I'd like to make the Spring Boot app configurable using a <configuration> tag in the pom.xml. <plugin> <groupId>org.example</groupId> <artifactId>my-maven-plugin</artifactId> <version>0.1.0-SNAPSHOT</version> <configuration> <my-maven-plugin.key1>value1</my-maven-plugin.key1> <my-maven-plugin.key2>value2</my-maven-plugin.key2> </configuration> </plugin> These properties can be injected into a Mojo using the @Parameter annotation. @Mojo(name = "generate", defaultPhase = LifecyclePhase.SITE) public class GenerateMojo extends AbstractMojo { @Parameter(name = "my-maven-plugin.key1", readonly = true) private String key1; @Parameter(name = "my-maven-plugin.key2", readonly = true) private String key2; @Override public void execute() { Properties props = new Properties(); props.setProperty("my-maven-plugin.key1", key1); props.setProperty("my-maven-plugin.key2", key2); new SpringApplicationBuilder(GenerateApp.class) .web(false) .bannerMode(OFF) .logStartupInfo(false) .properties(props) .run(); } } A Properties object is being created that can be used in Spring. But I'd like to avoid building the Properties on my own. While I could rearrange the <configuration> like this <configuration> <my-maven-plugin> <key1>value1</key1> <key2>value2</key2> </my-maven-plugin> </configuration> and inject all properties like so @Parameter(name = "my-maven-plugin", readonly = true) private Properties myProperties; I'd prefer not having to wrap all my properties in another tag as this feels more natural in a Maven plugin. Is there a way to inject the entire configuration in a single Properties object in Maven without wrapping properties in another tag? A Map<String, Object> or similar would also be fine for me. A: I don't think there is a straight forward way to do what you ask about. However, you may try the following alternatives. 1) You could use project properties: <project> ... <properties> <key1>value1</key1> <key2>value1</key2> </properties> ... </project> 2) There is a couple of ways to access mojo configuration in runtime: see answers here. 3) This is more like an idea, not actually an answer: you could look at how @Parameter annotation works and add code to your plugin which would use same annotations and populate a Map or Properties object.
[ "stackoverflow", "0030336410.txt" ]
Q: Get a word in textarea on mouse over I have a HTML element. My goal is when mouse is over a word in the textarea I need to get the word and do something with it. How can it be implemented? What event should I use? A: As per my knowledge, you can't do that. Only way you can do this, wrap each with element like <span> and add on mouse hover event to all <span> element. <div class="spanhover"><span>Wrap</span><span>all</span><span>elements</span></div> <script> $(document).ready(function () { $('.spanhover span').bind('mouseenter', function () { alert($(this).html() + " is your word"); }); }); </script>
[ "english.stackexchange", "0000452518.txt" ]
Q: Are these two sentences correct? Excuse me, I heard these two sentences from an English teacher. But I do not know what do they mean and even if they are grammatically correct. Would you please help me to find out if they are correct? What did you do used to do when you where a child? How long can you studied English? A: Saying "What did you do used to do when you where a child?" sounds incorrect grammatically. It contains following errors: Repititive in using the verb "do". Using -d in "Used to" even after "did" [if you write it in written exams, it's incorrect]. Use of unsuitable word "where" rather than using "were". Instead say: What did you use to do when you were a child? [don't write "did you used to" in written exams, though it's acceptable in other cases]. Your second sentence is also wrong. We can't say "How long can you studied English?" because it's incorrect to use past form of the verb "study" [as studied] before we use auxiliary verb "can". It will be correct to say: How long can you study English? Reference: https://dictionary.cambridge.org/grammar/british-grammar/past/used-to
[ "stackoverflow", "0061717471.txt" ]
Q: giraffe routef async function I've been creating a Giraffe api server using f# and have happily been using the route functions: type Person = { id: BsonObjectId; name: string; age: int; } let getPeople (databaseFn: unit-> IMongoDatabase) : HttpHandler = fun (next : HttpFunc) (ctx : HttpContext) -> let database = databaseFn() let collection = database.GetCollection<Person> "people" task { let! cursor = collection.FindAsync<Person>(fun p -> true) let! hasMoved = cursor.MoveNextAsync() let result = match hasMoved with | true -> json cursor.Current next ctx | false -> let message = { message = "No People found" } RequestErrors.notFound (json message) next ctx return! result } let savePerson (databaseFn: unit -> IMongoDatabase ) : HttpHandler = fun (next : HttpFunc) (ctx : HttpContext) -> let database = databaseFn() let collection = database.GetCollection<Person> "people" task { let serialiser = ctx.GetJsonSerializer() let! person = ctx.BindJsonAsync<Person>() let personWithId = { person with id = BsonObjectId ( ObjectId.GenerateNewId() ) } do! collection.InsertOneAsync(personWithId) return! text "nailed it" next ctx } let deletePerson (databaseFn: unit -> IMongoDatabase ) = fun (id: string) -> let database = databaseFn() let collection = database.GetCollection<Person> "people" task { let oId = BsonObjectId (ObjectId id) let! result = collection.FindOneAndDeleteAsync<Person>(fun p -> p.id = oId) return text "awesomesauce" } let personHandler getPeople savePerson deletePerson = let path = "/people" choose [ GET >=> choose [ route path >=> getPeople ] POST >=> choose [ route path >=> savePerson ] DELETE >=> choose [ routef "/people/%s" >=> deletePerson ] ] But I've add the deletePerson handler but it's now complaining that routef "/people/%s" >=> deletePerson The type 'HttpFuncResult' does not match the type 'HttpHandler' I get that the types don't match, but when I use it like so routef "/people/%s" deletePerson it complains that the deletePerson function returns System.Threading.Tasks.Task<(HttpFunc -> HttpContext -> HttpFuncResult)> instead of a HttpHandler I'm just not sure how I have a routef where I can get the value from the route parameter and have an async HttpHandler in one go? A: I don't have all the types imported to make the whole thing compile, but I think you need to remove the >=> from the delete: DELETE >=> choose [ (routef "/people/%s" deletePerson) ] And the deletePerson signature would be: let deletePerson (databaseFn: unit -> IMongoDatabase ) (id: string) : HttpHandler = fun (next : HttpFunc) (ctx : HttpContext) -> let database = databaseFn() //etc
[ "stackoverflow", "0008750645.txt" ]
Q: SQLite multi insert from C++ just adding the first one I have the following code for SQLite: std::vector<std::vector<std::string> > InternalDatabaseManager::query(std::string query) { sqlite3_stmt *statement; std::vector<std::vector<std::string> > results; if(sqlite3_prepare_v2(internalDbManager, query.c_str(), -1, &statement, 0) == SQLITE_OK) { int cols = sqlite3_column_count(statement); int result = 0; while(true) { result = sqlite3_step(statement); std::vector<std::string> values; if(result == SQLITE_ROW) { for(int col = 0; col < cols; col++) { std::string s; char *ptr = (char*)sqlite3_column_text(statement, col); if(ptr) s = ptr; values.push_back(s); } results.push_back(values); } else { break; } } sqlite3_finalize(statement); } std::string error = sqlite3_errmsg(internalDbManager); if(error != "not an error") std::cout << query << " " << error << std::endl; return results; } When I try to pass a query string like: INSERT INTO CpuUsage (NODE_ID, TIME_ID, CORE_ID, USER, NICE, SYSMODE, IDLE, IOWAIT, IRQ, SOFTIRQ, STEAL, GUEST) VALUES (1, 1, -1, 1014711, 117915, 175551, 5908257, 112996, 2613, 4359, 0, 0); INSERT INTO CpuUsage (NODE_ID, TIME_ID, CORE_ID, USER, NICE, SYSMODE, IDLE, IOWAIT, IRQ, SOFTIRQ, STEAL, GUEST) VALUES (1, 1, 0, 1014711, 117915, 175551, 5908257, 112996, 2613, 4359, 0, 0); INSERT INTO CpuUsage (NODE_ID, TIME_ID, CORE_ID, USER, NICE, SYSMODE, IDLE, IOWAIT, IRQ, SOFTIRQ, STEAL, GUEST) VALUES (1, 1, 1, 1014711, 117915, 175551, 5908257, 112996, 2613, 4359, 0, 0); It results just inserting the first insert. Using some other tool lite SQLiteStudio it performs ok. Any ideas to help me, please? Thanks, Pedro EDIT My query is a std::string. const char** pzTail; const char* q = query.c_str(); int result = -1; do { result = sqlite3_prepare_v2(internalDbManager, q, -1, &statement, pzTail); q = *pzTail; } while(result == SQLITE_OK); This gives me Description: cannot convert ‘const char*’ to ‘const char**’ for argument ‘5’ to ‘int sqlite3_prepare_v2(sqlite3*, const char*, int, sqlite3_stmt*, const char*)’ A: SQLite's prepare_v2 will only create a statement from the first insert in your string. You can think of it as a "pop front" mechanism. int sqlite3_prepare_v2( sqlite3 *db, /* Database handle */ const char *zSql, /* SQL statement, UTF-8 encoded */ int nByte, /* Maximum length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: Statement handle */ const char **pzTail /* OUT: Pointer to unused portion of zSql */ ); From http://www.sqlite.org/c3ref/prepare.html If pzTail is not NULL then *pzTail is made to point to the first byte past the end of the first SQL statement in zSql. These routines only compile the first statement in zSql, so *pzTail is left pointing to what remains uncompiled. The pzTail parameter will point to the rest of the inserts, so you can loop through them all until they have all been prepared. The other option is to only do one insert at a time, which makes the rest of your handling code a little bit simpler usually. Typically I have seen people do this sort of thing under the impression that they will be evaluated under the same transaction. This is not the case, though. The second one may fail and the first and third will still succeed.
[ "stackoverflow", "0037749151.txt" ]
Q: Background rsync and pid from a shell script I have a shell script that does a backup. I set this script in a cron but the problem is that the backup is heavy so it is possible to execute a second rsync before the first ends up. I thought to launch rsync in a script and then get PID and write a file that script checks if the process exist or not (if this file exist or not). If I put rsync in background I get the PID but I don't know how to know when rsync ends up but, if I set rsync (no background) I can't get PID before the process finish so I can't write a file whit PID. I don't know what is the best way to "have rsync control" and know when it finish. My script #!/bin/bash pidfile="/home/${USER}/.rsync_repository" if [ -f $pidfile ]; then echo "PID file exists " $(date +"%Y-%m-%d %H:%M:%S") else rsync -zrt --delete-before /repository/ /mnt/backup/repositorio/ < /dev/null & echo $$ > $pidfile # If I uncomment this 'rm' and rsync is running in background, the file is deleted so I can't "control" when rsync finish # rm $pidfile fi Can anybody help me?! Thanks in advance !! :) A: # check to make sure script isn't still running # if it's still running then exit this script sScriptName="$(basename $0)" if [ $(pidof -x ${sScriptName}| wc -w) -gt 2 ]; then exit fi pidof finds the pid of a process -x tells it to look for scripts too ${sScriptName} is just the name of the script...you can hardcode this wc -w returns the word count by words -gt 2 no more than one instance running (instance plus 1 for the pidof check) if more than one instance running then exit script Let me know if this works for you.
[ "stackoverflow", "0012517360.txt" ]
Q: Oracle function within a transaction I am inserting a record within a transaction and then later I am retrieving the same record via an Oracle function. The oracle function is returning no records. My DBA told me that Oracle functions do not operate inside a transaction. How do I get around this? Example: Begin transaction using the oracle provider Execute some SQL: INSERT OWNER (FIRST_NAME, LAST_NAME) VALUES ('JOHN', 'SMITH') Get the record back within the transaction from a function (71 is an example ID): select * from table (GET_OWNER_DETAILS_FNC (71) ) Here is the Oracle Function: CREATE OR REPLACE FUNCTION "AROH"."GET_OWNER_DETAILS_FNC" (p_owner_information_oid in aroh_owner_information.owner_information_oid%type ) return OWNER_DETAILS_TABLE_TYPE_FNC IS PRAGMA AUTONOMOUS_TRANSACTION; v_owner_details_set OWNER_DETAILS_TABLE_TYPE_FNC := OWNER_DETAILS_TABLE_TYPE_FNC(); CURSOR c_owner_dtls IS select oi.owner_information_oid, oi.first_name, oi.last_name, oi.company_name, oi.license_information, oi.company_ind, oi.middle_initial, oi.title_type_oid, oi.suffix, oi.status_type_code, oi.primary_phone, oi.secondary_phone, oi.secondary_phone_type_code, oi.primary_phone_type_code, oi.email_address, oi.comments, oi.primary_phone_extension, oi.secondary_phone_extension, poa.owner_address_oid as primaryaddressid, poa.address_type_code as primaryaddresscode, poa.address1 as primaryaddress1, poa.address2 as primaryaddress2, poa.city as primarycity, poa.state as primarystate, poa.postal_code as primaryzip, poa.current_ind as primarycurrent, soa.owner_address_oid as secondaryaddressid, soa.address_type_code as secondaryaddresscode, soa.address1 as secondaryaddress1, soa.address2 as secondaryaddress2, soa.city as secondarycity, soa.state as secondarystate, soa.postal_code as secondaryzip, soa.current_ind as secondarycurrent, ( select ( select oa2.owner_information_oid from aroh_owner_aircraft_rlshp oa2 where upper(primary_owner) like '%PRIMARY%' and oa2.aircraft_oid = oa1.aircraft_oid and rownum = 1) as prim_owner_oid from aroh_owner_aircraft_rlshp oa1 where oa1.owner_information_oid = p_owner_information_oid and rownum = 1 ) as primary_owner_oid, ( select case when (upper(primary_owner) like '%PRIMARY%') then 'Y' else 'N' end as isprimary from aroh_owner_aircraft_rlshp where owner_information_oid = p_owner_information_oid and rownum = 1 ) as is_primary from aroh_owner_information oi inner join (select * from aroh_owner_address where upper(current_ind) = 'Y' and address_type_code = 'OPRIM') poa on oi.owner_information_oid = poa.owner_information_oid left outer join (select * from aroh_owner_address where upper(current_ind) = 'Y' and address_type_code = 'OSEC') soa on oi.owner_information_oid = soa.owner_information_oid where oi.owner_information_oid = p_owner_information_oid; begin For main_row in c_owner_dtls loop v_owner_details_set.EXTEND; v_owner_details_set(v_owner_details_set.LAST) := OWNER_DETAILS_TYPE (main_row.owner_information_oid , main_row.first_name , main_row.last_name , main_row.company_name , main_row.license_information , main_row.company_ind , main_row.middle_initial , main_row.title_type_oid , main_row.suffix , main_row.status_type_code , main_row.primary_phone , main_row.secondary_phone , main_row.secondary_phone_type_code , main_row.primary_phone_type_code , main_row.email_address , main_row.comments , main_row.primary_phone_extension , main_row.secondary_phone_extension , main_row.primaryaddressid , main_row.primaryaddresscode , main_row.primaryaddress1 , main_row.primaryaddress2 , main_row.primarycity , main_row.primarystate , main_row.primaryzip , main_row.primarycurrent , main_row.secondaryaddressid , main_row.secondaryaddresscode , main_row.secondaryaddress1 , main_row.secondaryaddress2 , main_row.secondarycity , main_row.secondarystate , main_row.secondaryzip , main_row.secondarycurrent , main_row.primary_owner_oid , main_row.is_primary ); end loop; return v_owner_details_set; EXCEPTION When others then dbms_output.put_line ('Oracle error: '||SQLERRM); end; A: The AUTONOMOUS_TRANSACTION pragma means that the function operates in the context of a separate transaction. By default (see http://docs.oracle.com/cd/B19306_01/server.102/b14220/consist.htm#sthref1972) this uses the "read committed" isolation level, meaning that, when the transaction queries data, it sees only data that was committed before the query began. Since the data you inserted has not been committed, this means that the function can't see it.
[ "stackoverflow", "0053961802.txt" ]
Q: How to use an environment variable in powershell command I have an env variable set, named GOPATH), in old style command shell I could run the command %GOPATH%\bin\hello like this: Is there an equivalently simple command in Windows PowerShell 10? Edit: I am not trying to print the environment variable. I am trying to USE it. The variable is set correctly: C:\WINDOWS\system32> echo $env:gopath C:\per\go Now I want to actually use this in a command line call, and it fails: C:\WINDOWS\system32> $env:gopath\bin\hello At line:1 char:12 + $env:gopath\bin\hello + ~~~~~~~~~~ Unexpected token '\bin\hello' in expression or statement. + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : UnexpectedToken A: Use $env:[Variablename] For example: $env:Appdata or $env:COMPUTERNAME using your example: $env:GOPATH To use this to execute a script use & "$env:GOPATH\bin\hello"
[ "stackoverflow", "0042093472.txt" ]
Q: Check for User-Input in Batch-Script Iam currently starting batch-script with this method (async) private void executor(string path) { //Vars ProcessStartInfo processInfo; Process process; processInfo = new ProcessStartInfo(path); processInfo.CreateNoWindow = true; processInfo.UseShellExecute = false; processInfo.RedirectStandardError = true; processInfo.RedirectStandardOutput = true; process = Process.Start(processInfo); process.OutputDataReceived += new DataReceivedEventHandler((sender, e) => { //Handle Output }); process.ErrorDataReceived += new DataReceivedEventHandler((sender, e) => { //Handle Errors }); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); //Handle Exit } The user chose the script (which will be performed by my program) and can run it. But the user can chose a script, which contains a pause-Command. This will cause a deadlock. How can I check that the script need a user-input? A: I found a solution. Iam not longer use the OutputDataReceived-Event. Here is my new (well-working) code: private void executor(string path) { //Vars ProcessStartInfo processInfo; Process process; processInfo = new ProcessStartInfo(path); processInfo.CreateNoWindow = true; processInfo.UseShellExecute = false; processInfo.RedirectStandardError = true; processInfo.RedirectStandardOutput = true; process = Process.Start(processInfo); process.ErrorDataReceived += new DataReceivedEventHandler((sender, e) => { //Handle Errors }); process.BeginErrorReadLine(); //Try read while script is running (will block thread until script ended) while (!process.HasExited) while (!process.StandardOutput.EndOfStream) { char c = (char)process.StandardOutput.Read(); if (c == '\n') { _outputList.Add(_lastOutputStringBuilder.ToString()); _lastOutputStringBuilder.Clear(); //Handle Output } else _lastOutputStringBuilder.Append(c); } //Handle Exit } With this code, I can store the last line (which must not end with a linebreak) and can check it for lines like "Press a key ..."
[ "stackoverflow", "0015270517.txt" ]
Q: Is there a nice way to wrap each Meteor.user in an object with prototype functions and such? I'm trying to come up with a nice way to wrap each user I fetch from the Meteor Accounts Collection in a function, including a few prototype helper functions and counts from other collections, etc. The best way to describe this is in code. The User function I want to wrap each user in would look something like this: // - - - - - - // USER OBJECT // - - - - - - var currentUser = null; // holds the currentUser object when aplicable function User(fbId) { var self = this, u = (typeof id_or_obj == 'string' || id_or_obj instanceof String ? Meteor.users.findOne({'profile.facebook.id': id_or_obj}) : id_or_obj); self.fb_id = parseInt(u.profile.facebook.id, 10), // Basic info self.first_name = u.profile.facebook.first_name, self.last_name = u.profile.facebook.last_name, self.name = u.name, self.birthday = u.birthday, self.email = u.profile.facebook.email, // Quotes self.likeCount = Likes.find({fb_id: self.fb_id}).count() || 0; } // - - - - - - - // USER FUNCTIONS // - - - - - - - User.prototype = { // Get users avatar getAvatar: function() { return '//graph.facebook.com/' + this.fb_id + '/picture'; }, getName: function(first_only) { return (first_only ? this.first_name : this.name); } }; I can easily have a global 'currentUser' variable, that holds this information about the currently logged in user on the client side like this: Meteor.autorun(function() { if (Meteor.user()) { currentUser = new User(Meteor.user().profile.facebook.id); } }); It's also easy to implement this into a Handlebars helper, replacing the use of {{currentUser}} like this: Handlebars.registerHelper('thisUser', function() { if (Meteor.user()) { return new User(Meteor.user()); } else { return false; } }); What I want to do in addition to this is to make it so that when Meteor returns Meteor.user() or Meteor.users.find({}).fetch(), it includes these helper functions and short handles for first_name, last_name, etc. Can I somehow extend Meteor.user() or is there some way to do this? A: In Meteor 0.5.8, you can just tack on a transform function like so: Meteor.users._transform = function(user) { // attach methods, instantiate a user class, etc. // return the object // e.g.: return new User(user); } You can do the same with non-user collections, but you can also do it this way when you instantiate the Collection: Activities = new Meteor.Collection("Activities", { transform: function (activity) { return new Activity(activity); } }); (this way doesn't seem to work with the 'special' users collection)
[ "stackoverflow", "0013338668.txt" ]
Q: Unable to make Navigation Bar totally transparent in iOS6 I was using the following code to make my Navigation Bar transparent in iOS5: const float colorMask[6] = {222, 255, 222, 255, 222, 255}; UIImage *img = [[UIImage alloc] init]; UIImage *maskedImage = [UIImage imageWithCGImage: CGImageCreateWithMaskingColors(img.CGImage, colorMask)]; [self.navigationController.navigationBar setBackgroundImage:maskedImage forBarMetrics:UIBarMetricsDefault]; Upgraded to iOS6 and the Navigation Bar is still transparent but now has a thin black line underneath it. How can I make the Navigation Bar totally transparent? I have also tried all of the following: self.navigationController.navigationBar.translucent = YES; self.navigationController.navigationBar.opaque = YES; self.navigationController.navigationBar.tintColor = [UIColor clearColor]; self.navigationController.navigationBar.backgroundColor = [UIColor clearColor]; [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault]; [self.navigationController.navigationBar setBarStyle:UIBarStyleBlackTranslucent]; [[UINavigationBar appearance] setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault]; Thanks in advance. A: Solved. iOS6 has added a drop shadow to the Navigation Bar. So the masking code that I was using with iOS5 still works fine - I just need to add if ([self.navigationController.navigationBar respondsToSelector:@selector(shadowImage)]) { [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]]; } to get rid of the drop shadow.
[ "stackoverflow", "0018769053.txt" ]
Q: Service object reusable? I'm using the Python Google Drive SDK with a service account app and I want to try to cache the service object in some way to minimize web requests when building it. service = build('drive', 'v2', http=http) If I reuse this object and possibly in multiple threads will this cause problems? A: Httplib2 objects are not thread safe. However, you should have no issue reusing the service, just make sure you're getting a new access token after an hour.
[ "stackoverflow", "0046388205.txt" ]
Q: Laravel 5.5 API resources for collections (standalone data) I was wondering if it is possible to define different data for item resource and collection resource. For collection I only want to send ['id', 'title', 'slug'] but the item resource will contain extra details ['id', 'title', 'slug', 'user', etc.] I want to achieve something like: class PageResource extends Resource { /** * Transform the resource into an array. * * @param \Illuminate\Http\Request * @return array */ public function toArray($request) { return [ 'id' => $this->id, 'title' => $this->title, 'slug' => $this->slug, 'user' => [ 'id' => $this->user->id, 'name' => $this->user->name, 'email' => $this->user->email, ], ]; } } class PageResourceCollection extends ResourceCollection { /** * Transform the resource collection into an array. * * @param \Illuminate\Http\Request * @return array */ public function toArray($request) { return [ 'id' => $this->id, 'title' => $this->title, 'slug' => $this->slug, ]; } } PageResourceCollection will not work as expected because it uses PageResource so it needs return [ 'data' => $this->collection, ]; I could duplicate the resource into PageFullResource / PageListResource and PageFullResourceCollection / PageListResourceCollection but I am trying to find a better way to achieve the same result. A: The Resource class has a collection method on it. You can return that as the parameter input to your ResourceCollection, and then specify your transformations on the collection. Controller: class PageController extends Controller { public function index() { return new PageResourceCollection(PageResource::collection(Page::all())); } public function show(Page $page) { return new PageResource($page); } } Resources: class PageResource extends Resource { public function toArray($request) { return [ 'id' => $this->id, 'title' => $this->title, 'slug' => $this->slug, 'user' => [ 'id' => $this->user->id, 'name' => $this->user->name, 'email' => $this->user->email, ], ]; } } class PageResourceCollection extends ResourceCollection { public function toArray($request) { return [ 'data' => $this->collection->transform(function($page){ return [ 'id' => $page->id, 'title' => $page->title, 'slug' => $page->slug, ]; }), ]; } }
[ "stackoverflow", "0026167426.txt" ]
Q: Why assign a variable to another variable? I don't understand why this is done: public class Example { private String name; private String surname; Example(String firstName, String secondName) { name = firstName; surname = secondName; } // whatever other code goes here } I don't see why I'd need to set name = firstName and surname = secondName. Why can't I just set name and surname directly? A: These are not the same kinds of variables: firstName and secondName are method parameters. As soon as the method is over, these variables go out of scope name and surname, on the other hand, are fields in a class. They remain "attached" to the instance of that class for as long as the instance exists. Here is an illustration of what that means: String a = "Hello"; String b = "World"; // For the duration of the constructor, a becomes firstName, // and b becomes secondName Example e = new Example(a, b); // Once the constructor exists, firstName and secondName disappear. // Resetting a and b after the call is no longer relevant a = "Quick brown fox jumps"; b = "over the lazy dog"; System.out.println(e.getName()+" "+e.getSurname()); The valuesof a and b have changed, but the values stored in Example remain set to what you passed to the constructor.
[ "stackoverflow", "0008316906.txt" ]
Q: change working directory to one located on a different volume in cmd In the command prompt I am able to change the working directory by typing CD "new path" for example take a look on how I am able to select directories that are located in my C drive: but note that when I select a directory located in a different volume (A:...) the command prompt will not change the working directory... A: cd /d A:\Users does what your looking for.
[ "es.stackoverflow", "0000271456.txt" ]
Q: Dividir string con split cada 3 caracteres Estoy intentando dividir un número de teléfono cada 3 caracteres con str_split de la siguiente forma con PHP: $telefono = "600700800"; $telefono = str_split($telefono, 3); echo $telefono; Pero el resultado del echo me devuelve Array. A: El resultado que devuelve la función str_split es un array, lo compruebas haciendo esto: echo gettype($telefono); Que imprime: array Entonces para mostrar el resultado puedes hacer lo siguiente indicando entre corchetes el índice o posición que deseas obtener: <?php $telefono = "600700800"; $telefono = str_split($telefono, 3); echo $telefono[0]; //devolverá 600 echo $telefono[1]; //devolverá 700 echo $telefono[2]; //devolverá 800 O mediante un bucle, por ejemplo un foreach así: foreach($telefono as $value){ echo $value."<br/>"; } Da este resultado: 600 700 800
[ "stackoverflow", "0011614062.txt" ]
Q: SQL query to see differentiated value I take a daily snapshot of the user-login logs(logged in or not) at every 4am which is categorised by each regions with the sum of the daily users. However, I want to create a SQL query to see the differentiated values(possibly with percentage) with the day before so that I can see which region has increased or decreased their users. I know I can hardcode this but is there any elegant ways to do that in rather simple SQL query? A: There are two ways to do this: First Way: 1. Create a table in your database CREATE TABLE user_logs (id int(11) AUTO_INCREMENT, daily_number varchar(1000), current_percentage varchar(30), date datetime) 2. Run the script to get the number of users for that day INSERT INTO user_logs (daily_number) VALUES ($daily_value) 3. Create function to compare the latest two DB rows, then insert percentage into (numberOfRows-1) Second Way: 1. Create a log of the user records in a txt file 2. In the log, append each number seperated by comma 3. Create function to compare the last two values in log and take the average of the two
[ "stackoverflow", "0018387336.txt" ]
Q: Adding Percentages to jquery knob input value I'm using jQuery plugin called Jquery Knob http://anthonyterrien.com/knob/ To create circular progress bar , So here's my code <input type="text" value="90" class="dial" data-width="80" data-height="90" data-readOnly=true data-fgColor="#2ecc71"> JS Knob Execute $(".dial").knob(); Tried to append ( % ) to value attribute but it's not rendered $('.dial').each(function() { $(this).attr("value", $(this).attr("value") + "%"); }); Any Suggestions ? Thanks ! A: As of version 1.2.7 of this plugin there is a format hook that you can use to change the way that the number is displayed. For example you can specify: $(".dial").knob({ 'format' : function (value) { return value + '%'; } }); A: Use below code it will work $(".dial").knob({ 'change': function (v) { console.log(v); }, draw: function () { $(this.i).val(this.cv + '%'); } });
[ "mechanics.stackexchange", "0000004318.txt" ]
Q: cover for seats I just bought some covers for my car seats. The problem is that I don't know how to remove the head rest of the front seats. My car is Fiat Punto (not Grande). If someone can provide a graphical representation, it would be great. After some Google search, someone described the process, but it sounds scary in that version. A: Yes there is a way of taking them off though it's not an easy job. First wind the backrest of the seat forwards and push the whole seat forwards on the rails. At the bottom of the fabric you'll see a plastic strip which with a bit of force (flat bladed screwdriver) will first slide from side to side but it should come apart. lying on the back seat wriggle your arm up the back of the seat and find the stalks that have the headrest on them. There is a metal clip that you have prise apart/away from the stalk and with the other hand push the headrest off. Fit the seat covers and it's really a reverse to get them back on. I found a friend to help to put them back on as it's not easy opening the clip and pushing down on the headrest at the same time. Remember to connect the plastic strip back together before you tie-up underneath. [source]
[ "chemistry.stackexchange", "0000034007.txt" ]
Q: A compound that absorbs all visible light Is there a compound that absorbs all visible light? A: Substances which absorb almost all the light falling on them appear black. Therefore you are looking for the blackest known compound. The record is currently held by Vantablack[1], a substance composed of vertically aligned carbon nanotubes, which absorbs up to 99.965% of visible light incident upon it. As you can see it is really black. Previously, the record was held by Superblack[2,3], a nickel-phosphorus alloy with an absorbance of up to 99.65%. For comparison, regular black paint generally absorbs around 97.5% of visible light. Sources [1] https://en.wikipedia.org/wiki/Vantablack [2] https://www.newscientist.com/article/dn3356-mini-craters-key-to-blackest-ever-black [3] http://pubs.rsc.org/en/Content/ArticleLanding/2002/JM/b204483h#!divAbstract A: All metals are capable of absorbing photons of any wavelength below hard ultraviolet, as ideally there are allowed electronic transitions of arbitrarily small energy between states in the unfilled valence band. This means metals are theoretically the materials with the widest wavelength range for photon absorption (except for plasmas). However, this comes to odds with the idea most people have of metals, which is a collection of shiny (highly reflective) grey solids. This is because while they can absorb photons of almost arbitrary wavelength, the absorption probability is not as high as in other materials. As such, a secondary effect can take place where the incoming photons interact with the free electrons in the metal and cause the light to be reflected back, rather than absorbed. One simple way to decrease reflection and hence turn pure metals into black substances is to grind them into a very fine dust or otherwise make a very rough surface on the microscopic level, which causes incident light to bounce around more times when hitting the material, increasing the odds of the light being absorbed. Furthermore, while we often think of metals as materials which are composed chiefly of atoms from the $s$/$d$/$f$/early $p$ blocks of elements from the periodic table (the "metallic elements"), metals are actually not defined by their composition at all, but by their electronic structure. It is even possible to have metals made out of "non-metals" such as pure carbon, for example (carbon nanotubes of certain chiralities). Thus metallic character is actually likely a contributing factor to the darkness of Vantablack, which bon mentions in his answer. A: Any black compound absorbs photons in all the visible spectrum; that is why essentially it appears black to our eyes. So, for instance, iron(II,III) oxide, $\ce{Fe3O4}$ will do so; it is even used as a black pigment. It is very unlikely though that it will absorb each and every photon of any wavelength in the visible spectrum, but the search for such a perfect absorber is meaningless in any case since the very notion of a visible spectrum is not strict.
[ "stackoverflow", "0042654945.txt" ]
Q: How can I loop through a list of on react? I've tried everything for what ever reason I can't return the current item in a list. when I do console log it shows theres a property inside of it but it does not render. What am I doing wrong? This is the data I'm getting from the parent component: [ { id: 3, sku: "3008_Brown", parent_sku: "3008", name: "Leonardo", description: "Frame with light & thin Rx lenses, UV & Scratch coatings, and polished edges", product_type_id: 1, gender_id: 3, kids: 0, price: "49.00", retail_price: "200.00", is_active: 1, mfr: "CAC", mfr_model: null, mfr_color: "GREEN", meas_a: 55, meas_b: null, meas_dbl: 17, temple_length: 140, total_frame_width: 142, spring_hinge: null, has_progressive: 0, created_at: null, updated_at: null } ] This is the code: class Result extends Component { constructor(props) { super(props); // set initial state this.state = { datas: '', users: [ {name: "John", id: 120, age: 22, gender: "male"}, {name: "Beth", id: 443, age: 24, gender: "female"}, {name: "Jane", id: 510, age: 19, gender: "female"} ] }; // binding 'this' to class this.displayList = this .displayList .bind(this); } // events we want to happen before it comes up componentWillMount(){ } // events after load componentDidMount(){ } displayList() { if (this.props.dataresults.length > 0) { this.props.dataresults.map(function(user, i){ console.log('user'); console.log(user.description); return <li key={i}>{user.description}</li>; }) } else { return (<h1>No Results </h1>) } } render() { console.log(this.state.users); return ( <div class="search-results"> <ul> {this.displayList()} </ul> </div> ); } } A: As I mentioned in the comment, you need to return the result. displayList() { if (this.props.dataresults.length > 0) { return this.props.dataresults.map(function(user, i){ console.log('user'); console.log(user.description); return <li key={i}>{user.description}</li>; }) } else { return (<h1>No Results </h1>) } }
[ "stackoverflow", "0001622281.txt" ]
Q: How should I best structure my web application using job queues [and Perl/Catalyst]? I'm writing a web application using the Catalyst framework. I'm also using a Job Queue called TheSchwartz. I'm wanting to use a job queue because I'm wanting as much of the application specific code decoupled from the web application interface code. Essentially the whole system consists of three main components: GUI (Catalyst web interface) A crawler An "attacking component" (the app is being written to look for XSS and SQLi vulnerabilities in other webapps/sites) So in theory the GUI creates jobs for the crawler which in turn creates jobs for the "attacking component". Currently I have a Model in Catalyst which instantiates a TheSchwartz object so that Controllers in the web app can add jobs to the job queue. I also need to create some job worker scripts that continuously listen (/check the database) for new jobs so they can perform the required actions. Currently the DB specific stuff for TheSchwartz is in the Model in Catalyst and I don't think I can easily access that outside of Catalyst? I don't want to duplicate the DB connection data for TheSchwartz job queue in the Model and then in my job worker scripts. Should I wrap the creation of TheSchwartz object in another class sitting outside of Catalyst and call that in the Model that is currently instantiating TheSchwartz object? Then I could also use that in the worker scripts. Or should I have the DB data in a config file and instantiate new TheSchwartz objects as and when I need them (inside Catalyst/inside job worker scripts)? Or am I just over thinking this? Some links to meaty web app architecture articles may also be useful (I've never built one of moderate complexity before..). Cheers A: Are you using DBIx::Class? The basic idea here applies even if you're not, but I'm going to go ahead and assume that you are. A Catalyst model should be a wrapper for another class, providing just enough behavior to interface with Catalyst, and nothing else. For example Catalyst::Model::DBIC::Schema is just a wrapper for DBIx::Class::Schema. It gets the config from Catalyst and passes it to DBIC, it injects the ResultSets into the Model namespace (so that you can do the $c->model('DB::Table') trick), and then it gets out of the way. The advantage is that since all of the important code lives outside of Catalyst::Model, it's completely independent of Catalyst. You can load up your Schema from a maintenance script or a jobqueue worker or whatever else, pass it some config, tell it to connect and go, without ever invoking Catalyst. All of the information and logic that's in your ResultSets and whatever else is equally available outside of Catalyst as inside. A: If I understand correct, your question is "how can reuse my database connection outside of Catalyst?". You should have used DBIx::Class within your Catalyst application. You can reuse the same files in any other application. $c->mode('DB::MyTable')->search(...) in Catalyst is the same as this outside of catalyst: my $schema = MyApp::Model::DB->new(); $schema->resultset('MyTable')->search(...) Any Model can be called outside of Catalyst like a regular package MyApp::Model::Library->new(). You just want to make sure you do not use $c as an argument.
[ "math.stackexchange", "0000218818.txt" ]
Q: Finding the least possible value of f(a) given the value of f(b) and that f'(x) is less than a specified c. I've tried several ways of answering this type of question but I can't seem to figure it out. This is one variation of it: Suppose that $f(x)$ is differentiable on [38,50]. Also suppose that $f(50)=21$ and $f'(x)<=10$ for all $x\in[38,50]$. What is the least possible value that $f(38)$ can take? I have concluded that this is rooted in the Extreme-Value theorem but I'm not totally sure how to use that here. My attempt to answer this: $f'(x)<=10$ -- integrates to $f(x)<=10x$ this leads me to conclude that the highest value that f(38) can take is 380. Which is not what the question is asking me. If you can help that would be splendid. A: Hint: By the Mean Value Theorem, $$\frac{f(50)-f(38)}{50-38}=f'(c)$$ for some $c$ between $38$ and $50$. Remark: We gave a formal solution, supported by the MVT. But the intuition goes as follows. The rate of change of $f(x)$ is $\le 10$. So from $38$ to $50$, the function $f$ can grow by at most $(10)(12)$. Thus $f(38) \ge f(50)-120$. We can easily produce an example where $f(38)$ is exactly equal to $21-120$ by letting $f'(x)=10$ for all $x$, that is, by using a function $f(x)$ of the shape $10x+b$.
[ "stackoverflow", "0057964129.txt" ]
Q: calculate the days between two dates I did a program that calculates the days different, between two dates, but I am not sure how can I add a statement that makes sure the program wont include the end date. then will only include the end date, if I write the word include after writing the two dates! for instance the program will say the following ./daysCalulcatorA dd1 mm2 yyyy1 dd2 mm2 yyyy2, and the end date ( dd2 mm2 yyyy2 will not be included, until i write the word "incude" like this: ./daysCalulcatorA dd1 mm2 yyyy1 dd2 mm2 yyyy2 incude for example: /daysCalulcatorA 19 2 2019 22 4 2019 include How do i do that? A: You can check if argv[7] is "include" using strcmp from <string.h>, and set a variable to ignore the end date if it's not /* Rest of the code above */ if (mm2<mm1) { mm2 += 12; yyyy2 -= 1; } int include = 0; if (argc >= 8) { if (strcmp("include", argv[7]) == 0) { include = 1; } } day_diff = dd2 - dd1; if (include == 0) { day_diff--; } printf("%d", day_diff); return 0; But i recommend you search about getopts, a flag seems more user friendly ./daysCalculatorA -i 19 2 2019 22 4 2019
[ "stackoverflow", "0055741851.txt" ]
Q: input with value dont allow to change itself I have input, and inside of it I have value={this.state.date} I can't type in this input, when value is still there. I tried to use second variable this.state.subdate to change it first, but this made no effect. I tried placeholder, but this property can't make needed stuff. import React, {Component} from 'react'; import { Col, Button, FormGroup, Input, Popover, Row } from "reactstrap"; import Calendar from 'react-calendar'; import moment from 'moment'; import { spawn } from 'child_process'; let id = 0; function idGen(){ return 'ds_select_'+(id++) } export default class Datetime extends Component{ state={ date: new Date(), isOpen : false, hours : '', minutes : '', subdate : '', } onChange(e){ e.setHours(this.state.date.getHours()) e.setMinutes(this.state.date.getMinutes()) this.setState({ date : e }) //this.props.onChange({name : this.props.name, value : this.dateMs(e)}) } constructor(props){ super(props); this.id = idGen(); } componentDidMount(){ var da = new Date() this.setState({date : da, hours : da.getHours(), minutes : da.getMinutes(), subdate : da }) } close(){ this.setState({isOpen : !this.state.isOpen}) } render(){ return(<> {this.renderInput()} {this.renderCalendar()} </>) } dateMs(date){ return Date.parse(date) } renderInput(){ return( <Input onBlur={(e) => {console.log('blur',e.target.value); this.setState({date : new Date(this.state.subdate), hours : new Date(this.state.subdate).getHours(), minutes :new Date(this.state.subdate).getMinutes()})}} onClick={() => this.setState({isOpen : !this.state.isOpen})} id={this.id} type="text" name="date" placeholder={this.state.subdate} value={this.state.date} onChange={ e => {this.setState({subdate : e.target.value},() => {console.log(this.state.subdate)})}} /> ) } renderCalendar(){ return( <Popover id={'_'+this.id} placement="bottom-start" hideArrow offset={0} isOpen={this.state.isOpen} target={this.id} toggle={() =>this.close()}> <Row style={{display: 'inline-grid', gridTemplateColumns:'360px 250px'}} form> <Col md={12}> <FormGroup style={{marginBottom:'0px'}}> <Calendar onChange={(e) => this.onChange(e)} e={this.onChange} value={this.state.date} /> </FormGroup> </Col> <Col style={{gridColumnStart: 2}} md={10}> <FormGroup row> <Col sm={6}> <Input valid={this.state.hours >= 0 && this.state.hours <= 23} id={this.id+'hours'} style={{textAlign:'center'}} type='number' max='23' min='0' name='hours' id='hours' placeholder={23} value={this.state.hours} onChange={e => { var dat = this.state.date; dat.setHours(e.target.value); this.setState({date : dat, hours : e.target.value, subdate : dat}) }} /> </Col> <Col sm={6}> <Input valid={this.state.minutes >= 0 && this.state.minutes <= 59} id={this.id+'minutes'} style={{textAlign:'center'}} type='number' max='59' min='0' name='minutes' id='minutes' placeholder={23} value={this.state.minutes} onChange={e => { var dat = this.state.date; dat.setMinutes(e.target.value); this.setState({date : dat, minutes : e.target.value, subdate : dat}) }} /> </Col> </FormGroup> </Col> </Row> </Popover> ) } } probably it is easy questions, because I just need an input property, like value\placeholder, but with some other features, that allow it to be real (so I can edit this thing by keyboard) and changeable by this.setState() My problems were value and onChange variable should be equal value and onChange variable should not be new Date(e.target.value), because it not allow you to delete something from string, if you want to change it you should highlight a letter and print a substitute. my aim was to send changes with onBlur, so inside it I'd just make new Date(value) from value I printed A: Please check my fiddle to know how to achieve real time date updates: Change Hour You can change logic accordingly. But setting state must be follow by the method described in my fiddle. Very basic rule of setting state for particular input is that onChange only affects to your input value when your setting state and assigned value state is same. Hope this helps.
[ "stackoverflow", "0006380728.txt" ]
Q: JPA 2.0: Adding entity classes to PersistenceUnit *from different jar* automatically I have a maven-built CDI-based Java SE app, which has a core module, and other modules. Core has the persistence.xml and some entities. Modules have additional entities. How can I add the entities to the spotlight of the persistence unit? I have read Hibernate manual, http://docs.jboss.org/hibernate/stable/entitymanager/reference/en/html/configuration.html#setup-configuration-packaging I have also seen these SO questions How can I merge / extend persistence units from different JARs? define jpa entity classes outside of persistence.xml Programmatically loading Entity classes with JPA 2.0? I am looking for a solution where Hibernate would scan for all loaded classes, or, would pick up some config file form the other jars (like e.g. CDI does with beans.xml). My app does not use Spring. I don't insist on portability - I'll stick with Hibernate. Is there some such solution? Is there's a way to create a PU from persistence.xml and add classes to it programmatically? Can I add @Entity classes to EntityManagerFactory after it was created? Update: I found in org.​hibernate.​ejb.​Ejb3Configuration: public Ejb3Configuration configure(String persistenceUnitName, Map integration) http://docs.jboss.org/hibernate/entitymanager/3.6/javadocs/ A: There are several way to solve it: As described in Do I need <class> elements in persistence.xml?, you can set hibernate.archive.autodetection property and Hibernate should be able to look up all annotated classes from classpath. However, that's not JPA spec compliant. If you are using Spring, from Spring 3.1.2 (or probably even a bit earlier), in LocalContainerEntityManagerFactoryBean, you can define packageToScan which will ask LocalContainerEntityManagerFactoryBean to scan in classpath to find all annotated classes. Again, not JPA spec compliant. I was using Maven as build tools. Years before, I have written a little plugin which will generate persistence.xml during build process. The plugin will scan from build classpath to find out all annotated classes, and list them in the generated persistence.xml. This is most tedious but the result is JPA spec compliant. One drawback (which does not apply to most people I believe) is the lookup happens in build-time, not runtime. That means if you are having an application for which entities JARs are provided only at deploy/runtime but not build time, this approach is not going to work. A: Ejb3Configuration has been removed in 4.3.0. If you don't want to create a Hibernate's Integrator, you can use the property hibernate.ejb.loaded.classes. properties.put(org.hibernate.jpa.AvailableSettings.LOADED_CLASSES, entities); Persistence.createEntityManagerFactory("persistence-unit", properties); Where entities is a List<Class> of entity classes. A: I have a slightly different setup where I am placing persistence.xml in the WAR file but some of its dependencies includes @Entity annotated classed to include in the persistence unit. I have solved my problem using Maven a bit like Adrian Shum described in #3, but using the element to include the jars to be scanned for @Entity annotations. I added a property to my-web/pom.xml for each dependency including extra entities. All my jars are part of a Maven multiproject build so for me it looks like. <properties> <common.jar>common-${project.version}.jar</common.jar> <foo.jar>foo-${project.version}.jar</foo.jar> </properties> I thereafter add the following to the persistence.xml <?xml version="1.0" encoding="UTF-8"?> <persistence version="2.0" ... > <persistence-unit name="primary"> <jta-data-source>java:jboss/datasources/mysource</jta-data-source> <jar-file>lib/${common.jar}</jar-file> <jar-file>lib/${foo.jar}</jar-file> ... </persistence-unit> </persistence> Lastly I configure the maven-resource-plugin in web/pom.xml to replace the $expressions in persistence.xml with the properties set in the POM <build> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> <includes> <include>**/persistence.xml</include> </includes> </resource> <resource> <directory>src/main/resources</directory> <filtering>false</filtering> <excludes> <exclude>**/persistence.xml</exclude> </excludes> </resource> </resources> ... </build>
[ "stackoverflow", "0060766911.txt" ]
Q: What is the fastest way to read text file using julia I had a hard time using Julia to read a large text file (968MB, 8.7 million rows). Each line is like: 0.3295747E+01 0.3045123E+01 0.3325542E+01 0.1185458E+01 -0.4827727E-05 -0.1033694E-04 0.3306459E-03 I used parse.(Float64, split(line)) to convert every line to numbers. function openfile() datafile = open("data.dat","r") lines = readlines(datafile) close(datafile) lines end function parseline(lines::Array{String}) for line in lines zzz = parse.(Float64, split(line)) end end import Base: tryparse_internal function myreadfile(str::String, T::Type, dlm=' ', eol='\n') row, clm, bg, ed = 0, 0, 0, 0 data = Array{T}(undef,0) isnu0, isnu = false, false for (idx, chr) in enumerate(str) isnu = false (chr != eol && chr != dlm) && (isnu = true) if isnu0 == false && isnu == true bg, isnu0 = idx, true end if isnu0 == true && isnu == false ed, isnu0 = idx-1, false push!(data, tryparse_internal(T, str, bg, ed)) end end isnu == true && (push!(data, tryparse(T, str[bg:end]))) data end @time lines = openfile() @time parseline(lines) using DelimitedFiles @time readdlm("data.dat") @time myreadfile(read("data.dat",String), Float64) and got 3.584656 seconds (17.59 M allocations: 1.240 GiB, 28.44% gc time) 78.099010 seconds (276.14 M allocations: 6.080 GiB, 1.50% gc time) 52.504199 seconds (185.93 M allocations: 3.960 GiB, 0.53% gc time) 46.085581 seconds (61.70 M allocations: 2.311 GiB, 0.28% gc time) Compare with fortran code call cpu_time(start) open(10, file="data.dat",status="old") do i=1, 8773632 read(10,*) a, b, c, d, e, f, g end do call cpu_time(finish) print '("Time = ",f6.3," seconds.")',finish-start Which is Time = 14.812 seconds. It seems Julia spends much longer time doing the same thing. Is there a better way to convert string to float? split and parse are so slow. A: As the comment says above, the fastest is most likely the readdlm function. That will return a Matrix which is most likely what you want. If you do want to do it by hand it's usually better to read through the file and process it line by line, instead of storing everything in big intermediary objects. Memory reads and writes are slow. Something like ret = open("data.dat","r") do datafile [parse.(Float64, split(line)) for line in eachline(datafile)] end It's probably not faster than your last line anyway though. A: Though I don't know your Fortran compiler, I will hazard a guess here. I think the difference in execution time is because the Julia code is doing two things your Fortran compiler does do not at the time the files are processed. The extra work Julia does makes Julia more versatile overall in its file handling than Fortran, but definitely slow it down here, since in this case they are not needed: Julia is using Unicode strings, 32 bits per digit rather than Fortran's 8 bits, which slows the assembly level byte comparisons in conversion of file to text line and splitting of text lines. I think Fortran is doing 32-bit floats and not 64-bit floating point numbers, whereas Julia is definitely using 64-bit floating point here, which might in some situations double the conversion times to floating point.
[ "stackoverflow", "0025646033.txt" ]
Q: aspdotnetstorefront - How to change Product image tooltip that shows "Click here for larger image"? When I mouse over a Product image the tooltip shows "Click here for larger image" How can we change this to show the product name or image name for better Seo? This is coming from within the Get Product Image call, Someone suggested I could simply string replace the output in the product XmlPackage and replace the "Click here for larger image" with your better for SEO version... but I need an example of how to do this. A: If you login to the Admin section of your storefront, and go to "Configuration -> Localization -> String Resource Manager". Once in string resource manager search for "showproduct.aspx.19". Then just click edit and change it to whatever you want the tooltip to show.
[ "ru.stackoverflow", "0000485658.txt" ]
Q: дополнительная таблица во вложенном запросе mysql Есть запрос: UPDATE requests SET status = 'В работе' WHERE id IN (SELECT id_request FROM resolutions WHERE name > 0) В целом он делает то что мне нужно, но мне хотелось бы проверять не только таблицу resolutions но и другую по условию. Например: UPDATE requests SET status = 'В работе' WHERE id IN (SELECT id_request FROM resolutions WHERE name > 0 AND id_request FROM responsibility WHERE name > 0) Выглядит топорно, и разумеется не работает хотя бы по тому, что вложение должно вернуть 1 результат что бы присвоить его полю id. Как то так. Есть идеи ? можно попробовать что нибудь с применением JOIN. A: Если нужны записи которые одновременно есть в обоих таблицах и в обоих таблицах name>0, то: UPDATE requests SET status = 'В работе' WHERE id IN ( SELECT A.id_request FROM resolutions A, responsibility B WHERE A.name > 0 AND A.id_request=B.id_request and B.name > 0 ) Если же надо получить id которые есть хотя бы в одной из таблиц, то: UPDATE requests SET status = 'В работе' WHERE id IN ( SELECT id_request FROM resolutions WHERE name > 0 union SELECT id_request FROM responsibility WHERE name > 0 )
[ "gis.stackexchange", "0000131478.txt" ]
Q: Using Checkboxes in Layer Tree of GeoExt? I am trying to generate a customized layer tree using GeoExt 2.0.2 My code is as follows: var store = Ext.create('Ext.data.TreeStore', { model: 'GeoExt.data.LayerTreeModel', root: { expanded: true, children: [ { plugins: ['gx_baselayercontainer'], expanded: true, text: "Mappe di base" },{ expanded: true, text: 'Dati amministrativi', leaf: false, children: [ { text: "Area progetto", layer: "area_progetto", nodeType: "gx_layer", iconCls: 'area_progetto', checked: true }, { text: "Comuni italiani", layer: "comuni_italia", nodeType: "gx_layer", iconCls: 'comuni_italia', checked: true } ] },{ expanded: true, text: 'Percorso Via Regina', leaf: false, children: [ { text: "Tratte", layer: "via_regina_tratte", nodeType: "gx_layer", iconCls: 'via_regina_tratte', checked: true } ] } ] } }); tree = Ext.create('GeoExt.tree.Panel', { border: true, region: "west", title: "Layers", width: 250, split: true, collapsible: true, collapseMode: "mini", autoScroll: true, rootVisible: false, lines: false, store: store }); My purpose here is to create multiple folders with the layers that I select and I want to assign different icons for each layer. This code created subnodes as I want, and I can assign a different icon for each layer in the tree, but the checkboxes are not working. Do you have any ideas or suggestions about why they are not working and how I can make them work? NOTE: radio buttons for base layers are working NOTE2: Setting the "store" as follows actually work for overlay layers, but in this case one big folder is created containing every layer except the base maps and I cannot create different folders and assign different icons for each layer. var store = Ext.create('Ext.data.TreeStore', { model: 'GeoExt.data.LayerTreeModel', root: { expanded: true, children: [ { plugins: ['gx_baselayercontainer'], expanded: true, text: "Base Maps" },{ plugins: [{ ptype: 'gx_overlaylayercontainer' }], expanded: true, text: 'Overlay Layers' } ] } }); A: For someone who may need the answer in the future I solved the problem by changing the definition of the node slightly: { plugins: ['gx_layer'], text: "Area progetto", layer: area_progetto, iconCls: 'area_progetto', onCheckChange: true }
[ "stackoverflow", "0059326223.txt" ]
Q: How do I manage having multiple screens with different sets of controls in WinForms? I'm creating the game of strategic tic-tac-toe in C# using WinForms. I have the main game screen all contained inside a TableLayoutPanel, and as of right now I have the app close when somebody wins. Current state of the board, if helpful I want to create a separate screen within the same form that displays a congratulating message to the winner, but my current idea (using a panel to hold the win screen, and programmatically toggling its visibility) feels clunky to design. How should I manage these multiple sets of controls efficiently and comfortably? A: There are a few ways to handle this. One way would be to create a new UserControl for your win screen. This makes it easy to edit the win screen without having to mess with things on your Form. Then on your Form, the controls would be laid out like this. Form1 containing a Panel. The Panel containing a WinScreenUserControl and a TableLayoutPanel (for the game board). You probably want the win screen and the TableLayoutPanel docked in the Panel. Send the WinScreenUserControl to the back, so it's behind the TableLayoutPanel. Now the win screen will be out of the way for when you want to edit the game board. And if you want to edit the win screen you just open the WinScreenUserControl. When the game is won you simply call winScreenUserControl1.BringToFront(); to bring the win screen in front of the game board. You could also make the game board a UserControl and edit it like the win screen.
[ "stackoverflow", "0055067783.txt" ]
Q: In a set of HTML radio buttons, how to highlight the correct/wrong choice There are three HTML radio buttons with ids 1, 2, 3 and some text next to them. The "correct" answer is 2. When the user selects 2, the radio button and it's text should be highlighted with a green color. Otherwise, (choices 1 and 3) they should be highlighted with red. How can this behavior be achieved with HTML,CSS and/or JavaScript? This is what I've tried so far (Instead of radio button I am highlighting the border of an image) HTML: <input type="radio" name="group1" id="1" class="input-hidden"/> <label for="1"> <img src="1.jpg"/> </label> <input type="radio" name="group1" id="2" class="input-hidden" /> <label for="2"> <img src="2.jpg"/> </label> CSS: input[type=radio]:checked + label>img { border: 1px solid #fff; box-shadow: 0 0 3px 3px #090; } A: You can add class to the img to separate the wrong and correct answers. input[type=radio]:checked+label>.wrongAnswer { border: 1px solid #990000; box-shadow: 0 0 3px 3px #990000; } input[type=radio]:checked+label>.correctAnswer { border: 1px solid #090; box-shadow: 0 0 3px 3px #090; } <input type="radio" name="group1" id="1" class="input-hidden" /> <label for="1"> <img class="wrongAnswer" src="1.jpg"/> </label> <input type="radio" name="group1" id="2" class="input-hidden" /> <label for="2"> <img class="correctAnswer" src="2.jpg"/> </label> <input type="radio" name="group1" id="3" class="input-hidden" /> <label for="3"> <img class="wrongAnswer" src="3.jpg"/> </label>
[ "math.stackexchange", "0003775749.txt" ]
Q: How many angles can be drawn using only a ruler and a compass? So far I know that it’s possible to draw angles which are multiples of 15° (ex. 15°, 30°, 45° etc.). Could anybody please tell me if it's possible to draw other angles which are not multiples of 15° using only a compass and a ruler. A: You can construct a regular $n$-gon with straightedge and compass if and only if $n$ is a power of $2$ times a product of Fermat primes - primes of the form $2^{2^j} +1$. That tells you what fractional angles you can construct. For example, the $17$-gon is constructible, so you can construct an angle of $360/17$ degrees.
[ "stackoverflow", "0026149945.txt" ]
Q: Wait for an actor response indefinitely in a future akka java I have a non-actor-based piece of code which delegates some operations to an akka actor and I would like to wait this actor response indefinitely, I mean, until this actor returns a response whatever time it takes. The problem is I have not idea how to wait indefinitely in a Future with Pattern.ask and Await.result methods. I would something like this: Timeout timeout = new Timeout(Duration.inf()); Future<Object> future = Patterns.ask(actor, msg, timeout); String result = (String) Await.result(future, timeout.duration()); but this does not work because Timeout does not accept a Duration object as constructor parameter, it only accepts FiniteDuration objetcs... Any idea? Cheers A: You may never receive an answer, since message delivery is not 100% guaranteed. As such, waiting indefinitely isn't a good approach -- you could well end up waiting forever. You probably want some level of timeout (perhaps a long one, if it suits), and then a fallback case where you re-send your request as necessary. This would be the more robust way of handling this situation.
[ "stackoverflow", "0004309546.txt" ]
Q: C Array change causing variable modification I am trying to modify a value in an array using the C programming language and I seem to be hitting a blank wall with this seemingly easy operation. Please see code snippet below: while(1) { printf("Current prime candidate is %i\n",nextPrimeCandidate); int innerSieve;//=2; int currentPrimeCandidate=0; for (innerSieve=2;innerSieve<SIEVELIMIT;innerSieve++) { currentPrimeCandidate = nextPrimeCandidate * innerSieve; //printf("Inner Sieve is b4 funny place %i,%i\n",innerSieve,currentPrimeCandidate); //initArray[currentPrimeCandidate]=5; //VERY UNIQUE LINE myArray[currentPrimeCandidate] = 0; //printf("Inner Sieve after funny place is %i,%i \n",innerSieve,currentPrimeCandidate); } nextPrimeCandidate=getNextPrimeCandidate(myArray,++nextPrimeCandidate); if ((nextPrimeCandidate^2) > SIEVELIMIT ) break; } The problem is with the line highlighted with the VERY UNIQUE LINE comment. For some reason, when the innerSieve variable reaches 33 and gets to that line, it sets the contents of the innerSieve variable to the value of that line ( which currently is 0) and basically forces the loop into an infinite loop( the SIEVELIMIT variable is set at 50). It seems that there is some funny stuff going on in the registers when I checked using the Eclipse Debug facility but I am not too sure what I should be looking for. If you need the whole code listing, this can be provided.( with a particular variable which is not yet initialised in the code being initialised at the precise point that the innerSieve variable hits 32) Any help will be greatly appreciated. A: Guessing that currentPrimeCandidate is greater than the maximum index of myArray, and you're overwriting innerSieve (which likely follows myArray on the stack). A: @ruslik hit on it in the comment. The problem is this line: if ((nextPrimeCandidate^2) > SIEVELIMIT ) break; In C, the ^ operator is not the power operator, it is the bitwise xor operator. You're iterating far too many times than you intend, which is resulting in an array-index-out-of-bounds error, so you're overwriting random memory and getting strange results. There is no power operator in C (though there is the pow function). Since you're just squaring a number, the simplest fix is to multiply the number by itself: if ((nextPrimeCandidate * nextPrimeCandidate) > SIEVELIMIT ) break;
[ "stackoverflow", "0055964299.txt" ]
Q: ConcurrentModificationException when updating sprite images I keep getting a ConcurrentModificationException when running my game which utilizes multithreading to create new sprites and move them. The main problem appears to happen with the creation and/or movement of "Fireballs". I've been able to run my program successfully with no exceptions appearing by commenting out the createNewFireballs method. However, whenever I do utilize the createNewFireballs method, the error commonly appears whenever I call a function that updates the image of the Fireball Sprite (and doesn't ever happen for any other type of sprite.) I was wondering if anyone could help me locate the source of my problem and potentially solve the issue. public synchronized void createNewFireball() { new Thread(new Runnable() { public void run() { while (gameNotPaused && hero.isNotDead()) { fireball = new Fireball(dragon.getX(), dragon.getY()); fireballs.add(fireball); try { Thread.sleep(100); //Waits for .1 second } catch(InterruptedException e) { e.printStackTrace(); Thread.currentThread().interrupt(); } } } }).start(); } //The problem commonly occurs in the update method, //specifically the line "FireballIter.next().updateImage(g);" public synchronized void update(Graphics g) { Iterator<Sprite> FireballIter = fireballs.iterator(); Iterator<Sprite> arrowIter = arrows.iterator(); while (arrowIter.hasNext()) { arrowIter.next().updateImage(g); } Iterator<Sprite> iterator = sprites.iterator(); while (iterator.hasNext()) { iterator.next().updateImage(g); } while (FireballIter.hasNext()) { FireballIter.next().updateImage(g); } } //Although sometimes it occurs as a result of updateScene, which is //called in another method which moves all the "projectile" sprites public synchronized void updateScene(int width, int height) { Iterator<Sprite> arrowIter = arrows.iterator(); while(arrowIter.hasNext()) { Sprite spriteObject = arrowIter.next(); ((Arrow) spriteObject).updateState(); if (spriteObject.overlaps(dragon, 350, 350)) { dragon.arrowHit(); System.out.printf("Dragon was hit at %d, %d%n, while arrow was at %d,%d%n", dragon.getX(), dragon.getY(), spriteObject.getX(), spriteObject.getY()); arrowIter.remove(); } } Iterator<Sprite> fireballIter = fireballs.iterator(); while(fireballIter.hasNext()) { Sprite spriteObject = fireballIter.next(); ((Fireball) spriteObject).updateState(); } } @Override public synchronized void run() { while (model.getGameNotPaused()) { model.updateScene(view.getWidth(), view.getHeight()); view.repaint(); try { Thread.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); Thread.currentThread().interrupt(); JOptionPane.showMessageDialog(null, "Press R to resume game."); } } } A: Making createNewFireball synchronized does nothing useful: the synchronization only applies to the execution of that method, not the runnable executed by the thread (which is good, because otherwise none of the other methods would be able to execute until the while loop finished). Put the fireballs.add into a synchronized block, taking care to ensure you are synchronizing on the right thing: If you simply use synchronized (this), you would be synchronizing on the Runnable. Instead, use synchronized (TheContainingClass.this) (where TheContainingClass is the name of the class containing these methods).
[ "rpg.stackexchange", "0000007737.txt" ]
Q: Convert a D&D 4e adventure to another level How can I easily port an adventure to another level? Say take Keep on the Shadowfell and instead of it being 1st to 4th level it becames 6th to 9th level. A: Converting monsters up or down by 5 or fewer levels is straightforward and listed in the DMG (I think around pg 190, but I'm not positive). You can also swap out monsters pretty easily with premade monsters from the DDI compendium. Skills are going to be a bit tougher. A ladder has a consistent DC. If there's climbing to be done you can't just say the ladder is suddenly more challenging to climb. You have to change it to something else. A knotted rope is a good substitution if they're climbing a cliff wall. But what if they're climbing up a castle tower. It makes sense that there's a ladder for guards to climb up, but a rope makes no sense. Furthermore some things that were challenges won't be challenges past a certain level. You can scale the width of a pit as the player's ability to jump increases, but once they can fly that pit is near useless. I don't think this will be much of an issue scaling from 1-4 to 6-9, as flight will probably be a temporary thing granted by a daily power. But you should expect that there are some challenges the PCs will straight up trump and you won't be able to fix them. If they happens just tell the PCs they're awesome and move along to the next challenge. A: Restat monsters, check pacing, and reflavour the environment For all adventures, except for maybe the most recent, the monster design reflects "Pre MM3" design philosophy and therefore... sucks. You'll want to redesign the monsters for the new levels or re-skin modern monsters to match the story. I strongly recommend taking monsters from the MM3 or monster vault in any event. Reskinning can be quite trivial with 4e monster design: simply call a set of powers by different names. If necessary change iconic racial or theme powers to match your desired theme. Even with racial powers, they should be adapted for role as was done for these Duergar. Especially check the mechanics of traps. They tended to be extremely horrible initially. The pacing may change, especially from early designs where resources were used at unanticipated rates. You'll want to figure out good stopping points for your party and the consequences of pushing on or holding back. The environment may or may not change. With Kobold Hall, one of the neater ways to swing is is that the hall is identical, but a new crop of monsters has moved in. It will give your heroes quite a sense of personal power for them to breeze through lower level challenges. If you're taking this route, add in ovbious retrofitting where appropriate, such as thick new locks bolted on doors, flakes of rust around a recently repaired portcullis, and so on. This approach can give an excellent feeling of a "living world" and may encourage your heroes to take the area as their base, if only to prevent yet another group of monsters from taking it over. If you choose to change the environment, the theme should be roughly: Mundane for Heroic, Expensive and elaborate for paragon and Magical for Epic. The lower end of each tier should feature run-down and badly out of repair examples of architecture and environment while the higher end should feature good or exemplary design. Kobold hall at level 1 is an overgrown ruin. At level 5, the internals should be well maintained with a crumbling curtain wall or other outer defence. At 10, it should be a proper fortification, taking cunning and care to infiltrate. Level 11 should feature well designed architecture enhanced with some magic. Metal walls are now the norm, with hints of the unusual. Magical locks and traps are far more prevalent here, with expected player encounters. As paragon progresses, these semi-fantastic environments should be in better and better repair. A decent level 20 capstone can feature entire structures made out of steel, silver, runes, and gold. Level 21 is the realm of the fanastic. Adventures in the Astral Sea and other worlds should feature dungeons of force walls, adamantine plates, and other flatly inconceivable items. In general, the wealth of the party is such that dismantling the dungeon should never be an attractive proposition time-wise. Using these as strong motifs can give the party a clue as to the relative difficulty of an encounter or delve. DCs, in general, should scale with the party, representing the areas of challenge shifting. While a lower level party could sneak through a cracked wall and have difficulty with a ladder, a higher level party needs to surmount the wall, the wards, and/or the guards. The easy stuff becomes trivial and unmentioned while the environment stops doing players favours.
[ "stackoverflow", "0008110905.txt" ]
Q: JavaScript. a loop with innerHTML is not updating during loop execution I'm trying to refresh a div from Javascript at each loop and see 1, 2, 3, .... The following code works, but only displays the final result (9998). How is it possible to display all the steps? Thank you in advance. <html> <head> </head> <body> <div id="cadre" style="width=100%;height=100%;"> <input type="button" value="Executer" onclick="launch();"/> <div id="result" ></div> </div> <script type="text/javascript"> function launch(){ for (inc=0;inc<9999;inc++){ document.getElementById('result').innerHTML = inc; } } </script> </body> </html> A: JavaScript execution and page rendering are done in the same execution thread, which means that while your code is executing the browser will not be redrawing the page. (Though even if it was redrawing the page with each iteration of the for loop it would all be so fast that you wouldn't really have time to see the individual numbers.) What you want to do instead is use the setTimeout() or setInterval() functions (both methods of the window object). The first allows you to specify a function that will be executed once after a set number of milliseconds; the second allows you to specify a function that will be executed repeatedly at the interval specified. Using these, there will be "spaces" in between your code execution in which the browser will get a chance to redraw the page. So, try this: function launch() { var inc = 0, max = 9999; delay = 100; // 100 milliseconds function timeoutLoop() { document.getElementById('result').innerHTML = inc; if (++inc < max) setTimeout(timeoutLoop, delay); } setTimeout(timeoutLoop, delay); } Notice that the function timeoutLoop() kind of calls itself via setTimeout() - this is a very common technique. Both setTimeout() and setInterval() return an ID that is essentially a reference to the timer that has been set which you can use with clearTimeout() and clearInterval() to cancel any queued execution that hasn't happened yet, so another way to implement your function is as follows: function launch() { var inc = 0, max = 9999; delay = 100; // 100 milliseconds var iID = setInterval(function() { document.getElementById('result').innerHTML = inc; if (++inc >= max) clearInterval(iID); }, delay); } Obviously you can vary the delay as required. And note that in both cases the inc variable needs to be defined outside the function being executed by the timer, but thanks to the magic of closures we can define that within launch(): we don't need global variables. A: var i = 0; function launch(){ var timer = window.setInterval(function(){ if( i == 9999 ){ window.clearInterval( timer ); } document.getElementById('result').innerHTML = i++; }, 100); } launch();