prompt
stringlengths
48
2.37k
chosen
stringlengths
7
4.28k
rejected
stringlengths
11
4.44k
Question: VB 6.0 does not have any global handler.To catch runtime errors,we need to add a handler in each method where we feel an error can occur.But, still some places might be left out.So,we end up getting runtime errors.Adding error handler in all the methods of an application,the only way? Answer:
While errors do propogate upwards, VB6 has no way to do a stack trace, so you never know which method raised the error. Unfortunately, if you need this information, you have to add a handler to each method just to log where you were.
on error resume next - is kinda close but its been a while. you might want to look up any caveats
Question: VB 6.0 does not have any global handler.To catch runtime errors,we need to add a handler in each method where we feel an error can occur.But, still some places might be left out.So,we end up getting runtime errors.Adding error handler in all the methods of an application,the only way? Answer:
I discovered this tool yesterday: <http://www.everythingaccess.com/simplyvba-global-error-handler.htm> It is a commercial product that enables global error handling in VB6 and VBA applications. It has its cost but does its job perfectly. I have seen other tools (free though) helping in this VB6 mangle, but none can cover a true real global error handling like "SimplyVB6 Global Error Handler for VB6" does. With "SimplyVB6 Global Error Handler for VB6", there is no need to change any line of existing code, and no need to number the lines of code (via a plug-in or something). Just enable Global error handling (one line of code in the main module) and you are all set. "SimplyVB6 Global Error Handler for VB6": * can show the call stack with real module and function names, as well as display the source code line. * Works only with P-Code compiled VB6 programs. * can work via early or late binding (no DLL Hell). I am not in any way affiliated to www.everythingaccess.com, just happy to have found it yesterday afternoon, was kind of looking at this problem again as one of my customers was having bugs in our VB6 application. I was able to test the tool yesterday afternoon, exchanging emails with the www.everythingaccess.com support and getting the evaluation product per mail. Their web side does not allow yet to download the evaluation version of the VB6 product, you have to email them but they are answering in less than an hour.
on error resume next - is kinda close but its been a while. you might want to look up any caveats
Question: VB 6.0 does not have any global handler.To catch runtime errors,we need to add a handler in each method where we feel an error can occur.But, still some places might be left out.So,we end up getting runtime errors.Adding error handler in all the methods of an application,the only way? Answer:
While errors do propogate upwards, VB6 has no way to do a stack trace, so you never know which method raised the error. Unfortunately, if you need this information, you have to add a handler to each method just to log where you were.
Also: errors do propagate upwards: if method X calls methods Y and Z, a single error handler in method X will cover all three methods.
Question: VB 6.0 does not have any global handler.To catch runtime errors,we need to add a handler in each method where we feel an error can occur.But, still some places might be left out.So,we end up getting runtime errors.Adding error handler in all the methods of an application,the only way? Answer:
Also: errors do propagate upwards: if method X calls methods Y and Z, a single error handler in method X will cover all three methods.
I discovered this tool yesterday: <http://www.everythingaccess.com/simplyvba-global-error-handler.htm> It is a commercial product that enables global error handling in VB6 and VBA applications. It has its cost but does its job perfectly. I have seen other tools (free though) helping in this VB6 mangle, but none can cover a true real global error handling like "SimplyVB6 Global Error Handler for VB6" does. With "SimplyVB6 Global Error Handler for VB6", there is no need to change any line of existing code, and no need to number the lines of code (via a plug-in or something). Just enable Global error handling (one line of code in the main module) and you are all set. "SimplyVB6 Global Error Handler for VB6": * can show the call stack with real module and function names, as well as display the source code line. * Works only with P-Code compiled VB6 programs. * can work via early or late binding (no DLL Hell). I am not in any way affiliated to www.everythingaccess.com, just happy to have found it yesterday afternoon, was kind of looking at this problem again as one of my customers was having bugs in our VB6 application. I was able to test the tool yesterday afternoon, exchanging emails with the www.everythingaccess.com support and getting the evaluation product per mail. Their web side does not allow yet to download the evaluation version of the VB6 product, you have to email them but they are answering in less than an hour.
Question: VB 6.0 does not have any global handler.To catch runtime errors,we need to add a handler in each method where we feel an error can occur.But, still some places might be left out.So,we end up getting runtime errors.Adding error handler in all the methods of an application,the only way? Answer:
While errors do propogate upwards, VB6 has no way to do a stack trace, so you never know which method raised the error. Unfortunately, if you need this information, you have to add a handler to each method just to log where you were.
I discovered this tool yesterday: <http://www.everythingaccess.com/simplyvba-global-error-handler.htm> It is a commercial product that enables global error handling in VB6 and VBA applications. It has its cost but does its job perfectly. I have seen other tools (free though) helping in this VB6 mangle, but none can cover a true real global error handling like "SimplyVB6 Global Error Handler for VB6" does. With "SimplyVB6 Global Error Handler for VB6", there is no need to change any line of existing code, and no need to number the lines of code (via a plug-in or something). Just enable Global error handling (one line of code in the main module) and you are all set. "SimplyVB6 Global Error Handler for VB6": * can show the call stack with real module and function names, as well as display the source code line. * Works only with P-Code compiled VB6 programs. * can work via early or late binding (no DLL Hell). I am not in any way affiliated to www.everythingaccess.com, just happy to have found it yesterday afternoon, was kind of looking at this problem again as one of my customers was having bugs in our VB6 application. I was able to test the tool yesterday afternoon, exchanging emails with the www.everythingaccess.com support and getting the evaluation product per mail. Their web side does not allow yet to download the evaluation version of the VB6 product, you have to email them but they are answering in less than an hour.
Question: Am trying to scrape info from a site. The site have like this ``` 127 East Zhongshan No 2 Rd; 中山东二路127号 ``` But when i try to scrap it & echo it then it will show ``` 127 East Zhongshan No 2 Rd; 中山ä¸äºè·¯127å· ``` I also try UTF-8 There is my php code now please help me for solve this problem. ``` function GrabPage($site){ $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); curl_setopt($ch, CURLOPT_TIMEOUT, 40); curl_setopt($ch, CURLOPT_COOKIEFILE, "cookie.txt"); curl_setopt($ch, CURLOPT_URL, $site); ob_start(); return curl_exec ($ch); ob_end_clean(); curl_close ($ch); } $GrabData = GrabPage($site); $dom = new DOMDocument(); @$dom->loadHTML($GrabData); $xpath = new DOMXpath($dom); $mainElements = array(); $mainElements = $xpath->query("//div[@class='col--one-whole mv--col--one-half wv--col--one-whole'][1]/dl/dt"); foreach ($mainElements as $Names2) { $Name2 = $Names2->nodeValue; echo "$Name2"; } ``` Answer:
First off, you need to set the charset before anything else on top of PHP file: ``` header('Content-Type: text/html; charset=utf-8'); ``` You need to convert the html markup you got with `mb_convert_encoding`: ``` @$dom->loadHTML(mb_convert_encoding($GrabData, 'HTML-ENTITIES', 'UTF-8')); ``` [Sample Output](http://codepad.viper-7.com/Du3gfM)
First thing is to see if the captured HTML source is properly encoded. If yes try ``` utf8_decode($Name2) ``` This should get your string ready for saving as well as printing
Question: In my understanding, miners wont accept non standard scripts. Then why are there several opcodes which cannot be used in custom scripts because they are nonstandard? Answer:
Those opcodes can be used in non-standard scripts as part of a Pay-to-Script-Hash address. They can be in the redeemScript of the P2SH address and be standard. Furthermore, standardness is not something that is set in stone; it is not a consensus rule, rather it is node policy. So in the future, we may create new script types which become standard that use other opcodes. Such scripts may be non-standard now (as P2SH and Segwit were in the past) but can become standard in the future. Those opcodes exist so that we can make scripts which perform smart contract-like things without needing a fork.
I figured out that we can use OPCODE to create a redeem script which is hashed for P2SH. So it seems that we can create our own smart contract: However Bitcoin script does not have enough OPCODEs to create smart contract that can do with Ethereum. Some people have proposed to add some OPCODEs to Bitcoin.
Question: ``` maxSumPair :: [(Int,Int)] -> (Int,Int) maxSumPair l = head $ sortBy (comparing auxSum) l auxSum :: (Int,Int) -> Int auxSum (a,b) = a+b ``` With the function `maxSumPair` and I want to calculate which of the doubles has the biggest sum. For example, this is how it should work: ``` > maxSumPairs [(1,10),(6,6),(10,1)] (6,6) ``` But my function gives me (1,10) instead of (6,6). What's my mistake? Answer:
[`sortBy`](http://hackage.haskell.org/package/base-4.7.0.2/docs/Data-List.html#v:sortBy), by default, does the stable sort *in ascending order*. So, `head` will get the smallest pair. Instead, you can tweak the `auxSum` to return negative sum values to sort the actual data in descending order and get the head, like this ``` auxSum :: (Int,Int) -> Int auxSum (a,b) = -(a + b) > maxSumPair [(1,10),(6,6),(10,1)] (6,6) ``` If you don't want to change the `auxSum`, then use [`last`](http://hackage.haskell.org/package/base-4.7.0.2/docs/Prelude.html#v:last) function instead of `head`, like this ``` auxSum :: (Int,Int) -> Int auxSum (a,b) = a + b maxSumPair :: [(Int,Int)] -> (Int,Int) maxSumPair l = last $ sortBy (comparing auxSum) l > maxSumPair [(1,10),(6,6),(10,1)] (6,6) ``` **Note:** Alternatively, you can use [`maximumBy`](http://hackage.haskell.org/package/base-4.7.0.2/docs/Data-List.html#v:maximumBy) function, which will be highly efficient for this case (because `sortBy` would run in O(n \* log n) time but `maximumBy` would finish it in O(n)), like this ``` auxSum :: (Int,Int) -> Int auxSum (a,b) = a + b > maximumBy (comparing auxSum) [(1,10),(6,6),(10,1)] (6,6) ```
Just to add to the discussion, note that you can perform reverse sorting by flipping the comparison function: ``` reverseSort xs = sortBy (flip compare) xs reverseSortBy cmp xs = sortBy (flip cmp) xs ``` so you could have written: ``` maxSumPair xs = head $ sortBy (flip $ comparing auxSum) xs ```
Question: I have a command which sends email to users according to their saved search terms. For now I have this: ``` public function handle() { $user = Alert::select('search', 'email', 'interval', 'emailSentAt')->join('users', 'alerts.uid', '=', 'users.id')->whereNotNull('search')->distinct()->get(); foreach ($user as $u) { $cl = new SphinxSearch(); $results = $cl->search('@*' . $u->search, 'spots'); $results = $cl->limit(10); $results = $cl->setMatchMode(\Sphinx\SphinxClient::SPH_MATCH_EXTENDED); $results = $cl->setSortMode(\Sphinx\SphinxClient::SPH_SORT_ATTR_DESC, "start"); $results = $cl->get(); Mail::send('emails.newSearchAlert', ['u' => $u, 'results' => $results], function ($m) use ($u) { $m->from('noreply@mydomain.com', 'My company'); $m->to($u->email)->subject('Your search alert - ' . $u->search); }); $u->emailSentAt = Carbon::now(); $u->save(); } } ``` Here I have two questions... 1. How can I save the sending date and time for each user? I am trying to do it like it is shown in the code. `$u->emailSentAt = Carbon::now();` and `$u->save();` but it doesn't update anything... The `emailSentAt` remains NULL. 2. In my database I have a column `interval` (it is selected in `$user` variable). The value of interval is 1 or 2, daily or weekly alert (respectively). How can I make command so that it runs according to user interval preference? If it is daily, I want emails to be sent daily... Answer:
For your first question, I proposed you two alternatives: * Add the `Alert` primary key on the select, and try to save again if that works. * Try to perform an `Alert::find($id)` and then, save it, to see if it's working. On your second question: * You can have two commands, one that will run daily and another weekly, and each command you will retrieve only the users that have selected the interval related to the command, e.g. `DailyEmailCommand` only query for the interval = 1 and `WeeklyEmailCommand` only query for the interval = 2. * In one command that will execute daily, query for all the users, send the email to the users that selected interval = 1, and check if it's the end of the week with Carbon and if that condition it's true, send the emails to the users that selected interval = 2.
Try this using laravel ``` use Carbon\Carbon; $u->emailSentAt = Carbon::now()->toDayDateTimeString(); //date $u->emailSentAt = Carbon::now()->timestamp; // timestamp ``` Using php ``` $date = new DateTime(); $u->emailSentAt = $date->format('Y-m-d H:i:s'); ```
Question: How can I make a interval breakdown chart like this: ![enter image description here](https://i.stack.imgur.com/J8RX0.png) Update: I checked `BarChart` and `Gauge` they do not have this capacity. Answer:
Here's one way to to it with `BarChart`. I didn't spend too much time on formatting the `Tooltip`. ``` names = {"apps", "pics", "vids", "free"}; vals = {10, 25, 50, 15}; BarChart[ Table[Tooltip[vals[[i]], Column[{ Style[names[[i]], 16, Bold], Style[ToString[vals[[i]]] <> " GB", 16, GrayLevel[0.5]]}], TooltipStyle -> {CellFrameColor -> GrayLevel[0.9], Background -> GrayLevel[0.9]}], {i, 1, 4}], ChartLayout -> "Stacked", BarOrigin -> Left, Axes -> False, AspectRatio -> 1/8] ``` ![enter image description here](https://i.stack.imgur.com/LUxJc.jpg)
Bottom-up approach using `Accumulate`: ``` {10, 25, 50, 15} // Prepend[0] // Accumulate // Partition[#, 2, 1] & // Map[{ColorData["HTML", RandomInteger[{1, 10}]], Rectangle[{First[#], 0}, {Last[#], 1}]}~ Join~ {Black, Text[Last[#], {Last[#], -1/4}]} &] // Graphics[#, AspectRatio -> 1/5] & ``` ![enter image description here](https://i.stack.imgur.com/vxGzL.png) `RandomInteger` color selection is not recommended, only used for brevity.
Question: I have the following query. ``` SELECT p.author_name, p.author_id, DISTINCT p.topic_id, t.title FROM `ibf_posts` p, `ibf_topics` t WHERE p.topic_id = t.tid ORDER BY pid DESC LIMIT 8" ``` When I run it, I get the following MySQL Error: ``` You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DISTINCT p.topic_id, t.title FROM `ibf_posts` p, `ibf_topics` t WHERE p' at line 1 ``` if I remove the `DISTINCT` keyword, then the query works without a problem. What am I doing wrong? This scheme is from Invision Power Board post and topic table. I am trying to get the title of the last 8 topics which has the newest posts. In the list of top latest posts, I don't want the same topic to appear more than once. I want a unique list of titles. table: ibf\_posts -pid -author\_name -author\_id -topic\_id table: ibf\_topics -tid -title tid is same as topic\_id Answer:
It's ``` SELECT DISTINCT ... ``` You can't specify `DISTINCT` only for a single column; it only works for keeping complete duplicate records out of the result set.
Distinct needs to be before p.author\_name. You can't choose only p.topic\_id to be distinct in this case. If what you're wanting to do is what I think it is, you should look up the GROUP BY clause.
Question: I've been assigned the task of changing some data columns in SQL tables (using Sql CE Server 3.5, if that matters). The tables are populated from hundreds of Comma Separated Excel text documents. The code makes a stab at determining the data type of the column and the table is created. Later, I need the ability to come back in and say, "No, this column with 'Y' and 'N' need to be changed to a Boolean type instead of a Character type." I have found information on how to [Alter the Table](http://www.w3schools.com/sql/sql_alter.asp) (drop a column and insert the new one), but would I be able to get the table's column back to the same Column Index value that it had before, like "Insert At Index=X"? ![enter image description here](https://i.stack.imgur.com/7BW8C.png) Answer:
There is no way to add a column at a specific index through ALTER TABLE. Tools like Sql Server Management Studio and Visual Studio Premium with Database tools can do it. But at least Visual Studio does it through a workaround: 1. Drop any constraints relating to the table, including FKs pointing at it. 2. Create a table with the new layout under temp name. 3. Move all the data (possibly including IDENTITY INSERT to preserve an IDENTITY column) 4. Drop the original table. 5. Rename the table with the temp name. 6. Recreate the constraints. If you have the possibility, I deeply recommend Visual Studio Premiums DB project. Its deploy engine can handle this automatically for you.
There is "dirty tricks" like this: [Reset Identity Column Index](http://www.howtogeek.com/howto/database/reset-identity-column-value-in-sql-server/) But I, honestly, never did it, cause why you ever need to care about next index implied by DB. May be I'm missing something, but why do not construct your DB relationships on **your own** IDs, on which you can have total control. Regards.
Question: I've been assigned the task of changing some data columns in SQL tables (using Sql CE Server 3.5, if that matters). The tables are populated from hundreds of Comma Separated Excel text documents. The code makes a stab at determining the data type of the column and the table is created. Later, I need the ability to come back in and say, "No, this column with 'Y' and 'N' need to be changed to a Boolean type instead of a Character type." I have found information on how to [Alter the Table](http://www.w3schools.com/sql/sql_alter.asp) (drop a column and insert the new one), but would I be able to get the table's column back to the same Column Index value that it had before, like "Insert At Index=X"? ![enter image description here](https://i.stack.imgur.com/7BW8C.png) Answer:
There is no way to add a column at a specific index through ALTER TABLE. Tools like Sql Server Management Studio and Visual Studio Premium with Database tools can do it. But at least Visual Studio does it through a workaround: 1. Drop any constraints relating to the table, including FKs pointing at it. 2. Create a table with the new layout under temp name. 3. Move all the data (possibly including IDENTITY INSERT to preserve an IDENTITY column) 4. Drop the original table. 5. Rename the table with the temp name. 6. Recreate the constraints. If you have the possibility, I deeply recommend Visual Studio Premiums DB project. Its deploy engine can handle this automatically for you.
There are a couple of way to deal with this 1. Do as Anders noted which is to recreate the table from scratch 2. Don't rely on the table's column order. Instead use a layer of abstraction, for example Views. (SQL Views or a .NET object view) 3. Don't drop and recreate the column but alter the column instead That 3rd option is tricky because you'd have to update the values before the alter. For example ``` Create table #temp (foo char(1), bar int) Insert into #temp VALUES ('Y', 0) Insert into #temp VALUES ('N', 1) UPDATE #temp SET foo = CASE WHEN foo = 'Y' THEN 1 ELSE 0 END ALTER table #temp alter column foo bit SELECT * FROM #temp ``` This is easy in the case. Converting a varchar(50) to a date-time for example would be a bit more difficult
Question: I've been assigned the task of changing some data columns in SQL tables (using Sql CE Server 3.5, if that matters). The tables are populated from hundreds of Comma Separated Excel text documents. The code makes a stab at determining the data type of the column and the table is created. Later, I need the ability to come back in and say, "No, this column with 'Y' and 'N' need to be changed to a Boolean type instead of a Character type." I have found information on how to [Alter the Table](http://www.w3schools.com/sql/sql_alter.asp) (drop a column and insert the new one), but would I be able to get the table's column back to the same Column Index value that it had before, like "Insert At Index=X"? ![enter image description here](https://i.stack.imgur.com/7BW8C.png) Answer:
There are a couple of way to deal with this 1. Do as Anders noted which is to recreate the table from scratch 2. Don't rely on the table's column order. Instead use a layer of abstraction, for example Views. (SQL Views or a .NET object view) 3. Don't drop and recreate the column but alter the column instead That 3rd option is tricky because you'd have to update the values before the alter. For example ``` Create table #temp (foo char(1), bar int) Insert into #temp VALUES ('Y', 0) Insert into #temp VALUES ('N', 1) UPDATE #temp SET foo = CASE WHEN foo = 'Y' THEN 1 ELSE 0 END ALTER table #temp alter column foo bit SELECT * FROM #temp ``` This is easy in the case. Converting a varchar(50) to a date-time for example would be a bit more difficult
There is "dirty tricks" like this: [Reset Identity Column Index](http://www.howtogeek.com/howto/database/reset-identity-column-value-in-sql-server/) But I, honestly, never did it, cause why you ever need to care about next index implied by DB. May be I'm missing something, but why do not construct your DB relationships on **your own** IDs, on which you can have total control. Regards.
Question: I've been assigned the task of changing some data columns in SQL tables (using Sql CE Server 3.5, if that matters). The tables are populated from hundreds of Comma Separated Excel text documents. The code makes a stab at determining the data type of the column and the table is created. Later, I need the ability to come back in and say, "No, this column with 'Y' and 'N' need to be changed to a Boolean type instead of a Character type." I have found information on how to [Alter the Table](http://www.w3schools.com/sql/sql_alter.asp) (drop a column and insert the new one), but would I be able to get the table's column back to the same Column Index value that it had before, like "Insert At Index=X"? ![enter image description here](https://i.stack.imgur.com/7BW8C.png) Answer:
You can just alter the column in place, then you won't have to worry about ordering it. ``` ALTER TABLE myTable ALTER COLUMN myColumn Boolean ```
There is "dirty tricks" like this: [Reset Identity Column Index](http://www.howtogeek.com/howto/database/reset-identity-column-value-in-sql-server/) But I, honestly, never did it, cause why you ever need to care about next index implied by DB. May be I'm missing something, but why do not construct your DB relationships on **your own** IDs, on which you can have total control. Regards.
Question: I've been assigned the task of changing some data columns in SQL tables (using Sql CE Server 3.5, if that matters). The tables are populated from hundreds of Comma Separated Excel text documents. The code makes a stab at determining the data type of the column and the table is created. Later, I need the ability to come back in and say, "No, this column with 'Y' and 'N' need to be changed to a Boolean type instead of a Character type." I have found information on how to [Alter the Table](http://www.w3schools.com/sql/sql_alter.asp) (drop a column and insert the new one), but would I be able to get the table's column back to the same Column Index value that it had before, like "Insert At Index=X"? ![enter image description here](https://i.stack.imgur.com/7BW8C.png) Answer:
You can just alter the column in place, then you won't have to worry about ordering it. ``` ALTER TABLE myTable ALTER COLUMN myColumn Boolean ```
There are a couple of way to deal with this 1. Do as Anders noted which is to recreate the table from scratch 2. Don't rely on the table's column order. Instead use a layer of abstraction, for example Views. (SQL Views or a .NET object view) 3. Don't drop and recreate the column but alter the column instead That 3rd option is tricky because you'd have to update the values before the alter. For example ``` Create table #temp (foo char(1), bar int) Insert into #temp VALUES ('Y', 0) Insert into #temp VALUES ('N', 1) UPDATE #temp SET foo = CASE WHEN foo = 'Y' THEN 1 ELSE 0 END ALTER table #temp alter column foo bit SELECT * FROM #temp ``` This is easy in the case. Converting a varchar(50) to a date-time for example would be a bit more difficult
Question: I have `rake` task which continuously need to be active. Whenever I ran it by command ``` RAILS_ENV=production rake jobs:abc ``` it works fine but when I close terminal `rake` job get stopped.So I found other solution on it by using `nohup` to run it in background. I execute command: ``` nohup RAILS_ENV=production rake jobs:work & ``` but it gives error: > > nohup: failed to run command ‘RAILS\_ENV=production’: No such file or directory > > > Please suggest, to way execute `rake` task in a production environment. Answer:
Set the environment variable before the `nohup` command. ``` RAILS_ENV=production nohup rake jobs:work ```
Try this one ``` nohup rake jobs:work RAILS_ENV=production ``` I have commented the solution above as well
Question: I have `rake` task which continuously need to be active. Whenever I ran it by command ``` RAILS_ENV=production rake jobs:abc ``` it works fine but when I close terminal `rake` job get stopped.So I found other solution on it by using `nohup` to run it in background. I execute command: ``` nohup RAILS_ENV=production rake jobs:work & ``` but it gives error: > > nohup: failed to run command ‘RAILS\_ENV=production’: No such file or directory > > > Please suggest, to way execute `rake` task in a production environment. Answer:
Set the environment variable before the `nohup` command. ``` RAILS_ENV=production nohup rake jobs:work ```
If you need `nohup` functionality, you should also consider [screen](https://www.howtoforge.com/linux_screen). ``` RAILS_ENV=production screen -L rake jobs:work ``` It starts a new terminal which isn't bound to your current session. To come back to your normal terminal, type `Ctrl+a` and then `d`. You can now log out safely without terminating the `rake` task. As a bonus, you automatically get a log file in `screenlog.0`. You can come back to your rake process by typing : ``` screen -r ```
Question: Is it possible for the inner product of any vector with the zero vector $ \mathbf{0} $ to be nonzero? Or must it always be zero? I'm struggling to find a counterexample. That is, is the following statement correct? $$ \langle \mathbf{v}, \mathbf{0}\rangle = 0 \space \forall \space v \in V$$ Answer:
Note that an inner product is conjugate-linear in the second component (Details at <http://en.wikipedia.org/wiki/Inner_product_space#Elementary_properties>). Thus, since 2 is its own conjugate, we have $2<v,0>=<v,2\cdot 0>=<v,0>$, hence $<v,0>=0$. So yes, it's true.
Think of it simply like this. $\langle \mathbf{v} , \mathbf0 \rangle = \langle \mathbf{v}, \mathbf{0}\*\mathbf{0} \rangle$ Here let one of the zeroes be the scalar, then the RHS will look like $\langle \mathbf{v} , \mathbf0 \rangle = \langle \mathbf{v} , \mathbf{0}\*\mathbf{0} \rangle = 0\cdot\langle \mathbf{v} , \mathbf{0} \rangle$ which is $0$.
Question: The full question is: How many ways can the 60 people from 20 countries be seated **around a table** so that each president, vice president, and poet laureate are sitting consecutively? The answer I come up with is : (19!)\*6 19! = the number of ways to arrange each country in the table = (20-1)! 6 = the number of ways to arrange the seat of three people in each country which are: [P,V,L] [P,L,V] [V,P,L] [V,L,P] [L,V,P] [L,P,V] But I'm an not sure if whether or not this answer is correct. Please help me. Thank you Answer:
You are nearly correct. Let's look at the steps needed to create a valid arrangement of people: Step 1: Order the countries. $19!$ orderings (correct). Step 2: Order the three people from country one. $6$ orderings (correct). Step 3: Order the three people from country two. $6$ orderings (important). ... Step 21: Order the three people from country $20$. $6$ orderings (important). By the product rule we then have a total of $19!6^{20}$ arrangements.
Consider, each triplet of [P, V, L] as one bundle. So, there are total $20$ bundles. Now, arranging these $20$ bundles on a circular table requires $(20-1)!$ Also, these bundles can be arranged internally which requires $3!$ Thus, the answer will be $$19! \* (3!)^{20}$$
Question: Some historical examples include the Gnostics, Advaita Vedanta, Kant, Schopenhauer, and countless mystics. I was just wondering if there is a common name for these sorts of worldviews. Thank you! Answer:
scientism <https://sniadecki.wordpress.com/2021/10/24/grothendieck-church/> Other than that, you are probably looking for "idealism" in some form or another.
There's *subjective idealism* which entails that the reality-generating apparatus of consciousness is itself the entirety of the world that we can have indubitable knowledge of… * An important subtype here is Kantian *transcendental idealism* which inverts the order of consideration here -- that is, taking the conditions of local transcendental structure as primary -- in a way which reveals a lot of prior philosophizing to be arguing one side or the other of an antinomy (an irresolvable problem for which it is perfectly possible to construct “rational” arguments for both sides). The transcendental ideas are in part proposed as partial resolutions to Cartesian *epistemic doubt* which arises due to thinking critically about subjectivity and the ideal construction of knowledge (that is: how is it that we can have indubitable knowledge of anything?) Perhaps *speculative idealism* characterizes the post-Kantian efforts most generally, if at the cost of gathering together some really disparate voices. Kant's closest readers like Solomon Maimon point the way beyond the antinomies and the transcendental ideas towards an abstract synthesis; in later accounts like Hegel's this synthetic process would achieve its formal elucidation as dynamic metaphysical process, yet still seemingly derived however from some form of self-knowledge and transcendental structure -- although the subject here is thoroughly decoded or translated, portrayed as the cosmos itself or the absolute etc
Question: Some historical examples include the Gnostics, Advaita Vedanta, Kant, Schopenhauer, and countless mystics. I was just wondering if there is a common name for these sorts of worldviews. Thank you! Answer:
This is a common concept for those who hold by idealist worldviews. That the world is really consciousness, and the appearance of matter around us, and its solidity, is an illusion. There is a term for this idea in Indian philosophy, and that is Maya -- that the appearance of a material world is an illusion. The concept of Maya is adopted from its Hindu origins in both Buddhist and Sikh thought, with slightly different but related definitions in both. Note that these religions give somewhat different answers as to what is "real", than mayanic Hinduism does. This view of our material world as at least partially illusory, or at least created by thought, is not limited to eastern thought. The "New Thought" brand of Christian and near-Christian religion holds that our physical universe is malleable to our willing. This is also a common view in the New Age movement. Modern paganism holds that our material world (and deities) are created by collective presumptions of humanity. A surprisingly related view is held among eliminative materialists, who hold that the world is "really" elementary particles, and the things we perceive (color, solidity, temperature, etc) are perceptually manufactured "shortcuts" to process the underlying "true" reductive reality, and the shortcuts basically are self-created illusions. This view is often called "scientific realism" <https://en.wikipedia.org/wiki/Na%C3%AFve_realism#Scientific_realism_and_na%C3%AFve_perceptual_realism>. Scientific realists also present the sensible world as illusory with the true reality being particles in motion. Sellars made the difficulties created by the opposition between "manifest image" and "scientific image" a centerpiece of his philosophy <https://plato.stanford.edu/entries/sellars/#PhilEnteImagHumaWorl>. A particular view of mind -- advocated by the materialist Daniel Dennett among others, is that consciousness is an DElusion. IE that it is not just our image of the external world that is seriously mistaken, but that we are also seriously mislead about what our minds themselves do and perceive. The term applied to this theory of mind is "Delusionism". <https://aeon.co/essays/what-if-your-consciousness-is-an-illusion-created-by-your-brain?utm_medium=feed&utm_source=atom-feed> A broader term to use across this whole collection of thought might be "illusionism" relative to matter and perception. But the diversity of views collected under the term, might make such a collective term more misleading than helpful.
There's *subjective idealism* which entails that the reality-generating apparatus of consciousness is itself the entirety of the world that we can have indubitable knowledge of… * An important subtype here is Kantian *transcendental idealism* which inverts the order of consideration here -- that is, taking the conditions of local transcendental structure as primary -- in a way which reveals a lot of prior philosophizing to be arguing one side or the other of an antinomy (an irresolvable problem for which it is perfectly possible to construct “rational” arguments for both sides). The transcendental ideas are in part proposed as partial resolutions to Cartesian *epistemic doubt* which arises due to thinking critically about subjectivity and the ideal construction of knowledge (that is: how is it that we can have indubitable knowledge of anything?) Perhaps *speculative idealism* characterizes the post-Kantian efforts most generally, if at the cost of gathering together some really disparate voices. Kant's closest readers like Solomon Maimon point the way beyond the antinomies and the transcendental ideas towards an abstract synthesis; in later accounts like Hegel's this synthetic process would achieve its formal elucidation as dynamic metaphysical process, yet still seemingly derived however from some form of self-knowledge and transcendental structure -- although the subject here is thoroughly decoded or translated, portrayed as the cosmos itself or the absolute etc
Question: Some historical examples include the Gnostics, Advaita Vedanta, Kant, Schopenhauer, and countless mystics. I was just wondering if there is a common name for these sorts of worldviews. Thank you! Answer:
The view you are describing, though possibly not the view you are thinking of, is called *indirect realism*. It is not a view of mystics, but the view of most materialists and physical realists today. Idealism denies that there is a real world at all. Idealists believe that only the mind exists (along with perceptions in the mind). An indirect realist believes in the real world, but believes that our minds have no direct experience of it. Indirect realism is a consequence of scientific realism, as was shown by Descartes. The scientific view of perception is that light strikes an object, then gets reflected into your eye, through the lens, and onto your retina. The light knocks electrons around to produce nerve impulses which then travel to your brain which does an enormous amount of processing on the signal before delivering it to your conscious awareness. The evidence for this view is overwhelming. It comes not only from optics and anatomy, but also from brain studies and instruments such as optical illusions and perspective, which show that what is reflected on the back of our eye is not what is brought to our consciousness. The conclusion from this is that what you see is not the real world, but a mental image of the real world created by your brain from data that wasn't even the real world when it entered the nervous system, but only a projected image. And the mental image you see is indistinguishable from images that can occur entirely in the mind without even the projection on the back of the eye. You can have hallucinations or dreams that show the same mental image. This shows that there is no necessary link between a physical object and the mental image you perceive. Furthermore, not only do you see only a mental image, but science says that a real object really isn't what your mental image shows you. That tree isn't really a whole; it's a swarm of subatomic particles, going in and out of the tree constantly. The particles even go in and out of existence. The tree isn't even physically identical from one moment to the next, yet you see a single tree persisting over time. All of this leads to the conclusion that we don't see the real world, but rather a mental image of the real world. The real world is a much different thing from what we see.
There's *subjective idealism* which entails that the reality-generating apparatus of consciousness is itself the entirety of the world that we can have indubitable knowledge of… * An important subtype here is Kantian *transcendental idealism* which inverts the order of consideration here -- that is, taking the conditions of local transcendental structure as primary -- in a way which reveals a lot of prior philosophizing to be arguing one side or the other of an antinomy (an irresolvable problem for which it is perfectly possible to construct “rational” arguments for both sides). The transcendental ideas are in part proposed as partial resolutions to Cartesian *epistemic doubt* which arises due to thinking critically about subjectivity and the ideal construction of knowledge (that is: how is it that we can have indubitable knowledge of anything?) Perhaps *speculative idealism* characterizes the post-Kantian efforts most generally, if at the cost of gathering together some really disparate voices. Kant's closest readers like Solomon Maimon point the way beyond the antinomies and the transcendental ideas towards an abstract synthesis; in later accounts like Hegel's this synthetic process would achieve its formal elucidation as dynamic metaphysical process, yet still seemingly derived however from some form of self-knowledge and transcendental structure -- although the subject here is thoroughly decoded or translated, portrayed as the cosmos itself or the absolute etc
Question: This is an elementary question, but I have been stuck on it for quite some time. I'm trying to group the values in ColumnB but only within each value in ColumnA. The initial data frame would be something like: ``` ColumnA = c(1,1,1,2,2,2) ColumnB = c("f","g","g","f","f","h") df <- data.frame(ColumnA,ColumnB) ``` ```html ColumnA ColumnB 1 f 1 g 1 g 2 f 2 f 2 h ``` The result would be: ```html ColumnA ColumnB 1 f 1 g 2 f 2 h ``` (One of the methods I tried using was with `dplyr` using: `group_by(df, ColumnB)`, but that attempt was unsuccessful.) Answer:
The `unique` function is uniquely suited (no pun intended) to solve your problem: ``` df <- data.frame(v1=c(1,1,1,2,2,2), v2=c("f", "g", "g", "f", "f", "h")) df <- unique(df) > df1 v1 v2 1 1 f 2 1 g 4 2 f 6 2 h ```
With `dplyr`, you'd want to perform an operation after grouping them; the grouping alone does not collapse the rows. You could calculate something with `summarise()`, pick one row within the group based on a variable, etc. Here's an example with `slice()` to select the first record within each group combination: ``` library(dplyr) df %>% group_by(ColumnA, ColumnB) %>% slice(1) # select the first row within each group combination Source: local data frame [4 x 2] Groups: ColumnA, ColumnB ColumnA ColumnB 1 1 f 2 1 g 3 2 f 4 2 h ```
Question: This is an elementary question, but I have been stuck on it for quite some time. I'm trying to group the values in ColumnB but only within each value in ColumnA. The initial data frame would be something like: ``` ColumnA = c(1,1,1,2,2,2) ColumnB = c("f","g","g","f","f","h") df <- data.frame(ColumnA,ColumnB) ``` ```html ColumnA ColumnB 1 f 1 g 1 g 2 f 2 f 2 h ``` The result would be: ```html ColumnA ColumnB 1 f 1 g 2 f 2 h ``` (One of the methods I tried using was with `dplyr` using: `group_by(df, ColumnB)`, but that attempt was unsuccessful.) Answer:
You can also try `duplicated` ``` df[!duplicated(df),] # ColumnA ColumnB #1 1 f #2 1 g #4 2 f #6 2 h ``` If needed, this would also give the logical index of rows.
With `dplyr`, you'd want to perform an operation after grouping them; the grouping alone does not collapse the rows. You could calculate something with `summarise()`, pick one row within the group based on a variable, etc. Here's an example with `slice()` to select the first record within each group combination: ``` library(dplyr) df %>% group_by(ColumnA, ColumnB) %>% slice(1) # select the first row within each group combination Source: local data frame [4 x 2] Groups: ColumnA, ColumnB ColumnA ColumnB 1 1 f 2 1 g 3 2 f 4 2 h ```
Question: I'm having trouble figuring out how to set [indexers](http://msdn.microsoft.com/en-us/library/6x16t2tx.aspx) in C# with Moq. The Moq documentation is weak, and I've done a lot of searching... what I'd like to do is similar in the solution to [How to Moq Setting an Indexed property](https://stackoverflow.com/questions/2372938/how-to-moq-setting-an-indexed-property): ``` var someClass = new Mock<ISomeClass>(); someClass.SetupSet(o => o.SomeIndexedProperty[3] = 25); ``` I want to modify the above to work for any index and any value so I can just do something like this: ``` someClass.Object.SomeIndexedProperty[1] = 5; ``` Currently I have the following, which works great for the indexed property getter, but if I ever set the value Moq ignores it: ``` var someValues = new int[] { 10, 20, 30, 40 }; var someClass = new Mock<ISomeClass>(); someClass.Setup(o => o.SomeIndexedProperty[It.IsAny<int>()]) .Returns<int>(index => someValues[index]); // Moq doesn't set the value below, so the Assert fails! someClass.Object.SomeIndexedProperty[3] = 25; Assert.AreEqual(25, someClass.Object.SomeIndexedProperty[3]); ``` Answer:
I found a solution to my problem. It requires a shift in my thinking... I had been looking to use NUnit's `Assert` to verify that the indexer setter in my `someClass` mock was being called with the correct value. It seems that with Moq the supported way to do this is to use the `VerifySet` function. A contrived example: ``` someClass.Object.SomeIndexedProperty[3] = 25; someClass.VerifySet(mock => mock.SomeIndexedProperty[3] = 25); ``` The unit test passes since `SomeIndexedProperty[3]` is set to 25, but would fail otherwise.
In your test your only set expectations for the getter of the indexer - and this will always return the corresponding value from your array. The indexer doesn't behave like a real thing. You can try a few things to have it fixed: 1. You can check if you can stub this indexer. I am personally using RhinoMocks, so I have no idea if this is implemented ``` someClass.SetupProperty(f => f.SomeIndexedProperty); ``` 2. You can try to mock the setter as well and make it to change the underlying array. My first guess would be to try something along these lines (no guarantee it will work): ``` someClass.Setup(o => o.SomeIndexedProperty[It.IsAny<int>()] = It.IsAny<int>()) .Callback((index, value) => someValues[index] = value); ``` 3. Or if the ISomeClass interface is small enough, you could just created a stub implementation yourself (that would have the indexer implemented as a dictionary, array etc.)
Question: I'm having trouble figuring out how to set [indexers](http://msdn.microsoft.com/en-us/library/6x16t2tx.aspx) in C# with Moq. The Moq documentation is weak, and I've done a lot of searching... what I'd like to do is similar in the solution to [How to Moq Setting an Indexed property](https://stackoverflow.com/questions/2372938/how-to-moq-setting-an-indexed-property): ``` var someClass = new Mock<ISomeClass>(); someClass.SetupSet(o => o.SomeIndexedProperty[3] = 25); ``` I want to modify the above to work for any index and any value so I can just do something like this: ``` someClass.Object.SomeIndexedProperty[1] = 5; ``` Currently I have the following, which works great for the indexed property getter, but if I ever set the value Moq ignores it: ``` var someValues = new int[] { 10, 20, 30, 40 }; var someClass = new Mock<ISomeClass>(); someClass.Setup(o => o.SomeIndexedProperty[It.IsAny<int>()]) .Returns<int>(index => someValues[index]); // Moq doesn't set the value below, so the Assert fails! someClass.Object.SomeIndexedProperty[3] = 25; Assert.AreEqual(25, someClass.Object.SomeIndexedProperty[3]); ``` Answer:
Using Moq 3.1.416.3 Setup won't work for indexers (because it takes an expression which means assignment statements are ruled out) so you need to use SetupSet like ``` _settingsStore.SetupSet(store => store["MruNotes"] = It.IsAny<string>()) .Callback<string,string>( (key, value) => persistedValue = value); ``` A small caveat: this expression only matches if the key is "MruNotes". I was not able to use a matcher like It.IsAny for the key.
In your test your only set expectations for the getter of the indexer - and this will always return the corresponding value from your array. The indexer doesn't behave like a real thing. You can try a few things to have it fixed: 1. You can check if you can stub this indexer. I am personally using RhinoMocks, so I have no idea if this is implemented ``` someClass.SetupProperty(f => f.SomeIndexedProperty); ``` 2. You can try to mock the setter as well and make it to change the underlying array. My first guess would be to try something along these lines (no guarantee it will work): ``` someClass.Setup(o => o.SomeIndexedProperty[It.IsAny<int>()] = It.IsAny<int>()) .Callback((index, value) => someValues[index] = value); ``` 3. Or if the ISomeClass interface is small enough, you could just created a stub implementation yourself (that would have the indexer implemented as a dictionary, array etc.)
Question: I'm having trouble figuring out how to set [indexers](http://msdn.microsoft.com/en-us/library/6x16t2tx.aspx) in C# with Moq. The Moq documentation is weak, and I've done a lot of searching... what I'd like to do is similar in the solution to [How to Moq Setting an Indexed property](https://stackoverflow.com/questions/2372938/how-to-moq-setting-an-indexed-property): ``` var someClass = new Mock<ISomeClass>(); someClass.SetupSet(o => o.SomeIndexedProperty[3] = 25); ``` I want to modify the above to work for any index and any value so I can just do something like this: ``` someClass.Object.SomeIndexedProperty[1] = 5; ``` Currently I have the following, which works great for the indexed property getter, but if I ever set the value Moq ignores it: ``` var someValues = new int[] { 10, 20, 30, 40 }; var someClass = new Mock<ISomeClass>(); someClass.Setup(o => o.SomeIndexedProperty[It.IsAny<int>()]) .Returns<int>(index => someValues[index]); // Moq doesn't set the value below, so the Assert fails! someClass.Object.SomeIndexedProperty[3] = 25; Assert.AreEqual(25, someClass.Object.SomeIndexedProperty[3]); ``` Answer:
I found a solution to my problem. It requires a shift in my thinking... I had been looking to use NUnit's `Assert` to verify that the indexer setter in my `someClass` mock was being called with the correct value. It seems that with Moq the supported way to do this is to use the `VerifySet` function. A contrived example: ``` someClass.Object.SomeIndexedProperty[3] = 25; someClass.VerifySet(mock => mock.SomeIndexedProperty[3] = 25); ``` The unit test passes since `SomeIndexedProperty[3]` is set to 25, but would fail otherwise.
Using Moq 3.1.416.3 Setup won't work for indexers (because it takes an expression which means assignment statements are ruled out) so you need to use SetupSet like ``` _settingsStore.SetupSet(store => store["MruNotes"] = It.IsAny<string>()) .Callback<string,string>( (key, value) => persistedValue = value); ``` A small caveat: this expression only matches if the key is "MruNotes". I was not able to use a matcher like It.IsAny for the key.
Question: I am using [CSSGram](http://una.im/CSSgram/) on my website to make images have Instagram-like filters. This is the method below to add a filter to a image: ``` <figure class="aden"> <img src="../img.png"> </figure> ``` How can i add this effect to all the images in the webpage, instead of using `<figure class="">` before every single image, and also in a css section for many images. Can this be done using `javascript` ? Answer:
While `a.append(x)` and `a[len(a):] = [x]` do the same thing, the first is clearer and should almost *always* be used. Slice replacement may have a place, but you shouldn't look for reasons to do it. If the situation warrants it, it should be obvious when to do it. Start with the fact that indexing returns an element of the list, and slicing returns a "sublist" of a list. While an element at a particular either exists or does not exist, it is mathematically convenient to think of every list have the empty list as a "sublist" between any two adjacent positions. Consider ``` >>> a = [1, 2, 3] >>> a[2:2] [] ``` Now consider the following sequence. At each step, we increment the starting index of the slice ``` >>> a[0:] # A copy of the list [1, 2, 3] >>> a[1:] [2, 3] >>> a[2:] [3] ``` Each time we do so, we remove one more element from the beginning of the list for the resulting slice. So what should happen when the starting index finally equals the final index (which is implicitly the length of the list)? ``` >>> a[3:] [] ``` You get the empty list, which is consistent with the following identities ``` a + [] = a a[:k] + a[k:] = a ``` (The first is a special case of the second where `k >= len(a)`. Now, once we see why it makes sense for the slice to exist, what does it mean to replace that slice with another list? In other words, what list do we get if we replace the empty list at the end of `[1, 2, 3]` with the list `[4]`? You get `[1, 2, 3, 4]`, which is consistent with ``` [1, 2, 3] + [4] = [1, 2, 3, 4] ``` Consider another sequence, this time involving slice replacements. ``` >>> a = [1,2,3]; a[0:] = ['a']; a ['a'] >>> a = [1,2,3]; a[1:] = ['a']; a [1, 'a'] >>> a = [1,2,3]; a[2:] = ['a']; a [1, 2, 'a'] >>> a = [1,2,3]; a[3:] = ['a']; a [1, 2, 3, 'a'] ``` Another way of looking at slice replacement is to treat it as appending a list to a sublist of the original. When that sublist is the list itself, then it is equal to appending to the original.
> > Why can I return a slice from a list that starts with a non-existent element? > > > I can't tell for sure, but my guess would be that it's because a reasonable value can be returned (there are no elements this refers to, so return an empty list). > > And why does this allow me to expand the list? > > > Your slice selects the last 0 elements of the list. You then replace those elements with the elements of another list. > > Also, of the first three above methods for appending an item, which one is preferred > > > Use `.append()` if you're adding a single element, and `.extend()` if you have elements inside another list. I'm not sure about performance, but my guess would be that those are pretty well optimized.
Question: This is something I've heard in some TV show. I don't remember which one. I just wrote it down when I heard it. Here it is. > > **-I'm on protecting the public. > > -Are you still on saving your girlfriend?** > > > What I'm especially interested is the meaning of **on** in these sentences. What does it mean or imply? Answer:
They're expressing where in some notional sequence of tasks they are up to. I'm only *on* page 7 of the book. I'm *on* the last question. I'll get *on* it right away. It might be better read with quotes: > > Your partner wants to go undercover, pretend she's his girlfriend, even though she is his girlfriend, even though he doesn't remember that. > > > To find out who's controlling him. > > > We've got a dead FBI guy, and you're still on "saving your boyfriend"? I'm on "protecting the public". > > >
I've never heard anyone say things like this, but it seems like it's a version of "I'm on it". But it completely depends on how the line was said. In any case, if the line was said the "I'm on it" sense, on means "engaged in" or "in the course of," again depending on context.. For example if you had the sentence: > > Sally is out on errands. > > > It could be reworded as: > > I'll go do the errands. > > > Oh, don't worry, Sally's on it. > > > Meaning, of course, that Sally is engaged in/doing the errands. Or... > > Who's doing the errands? > > > Don't worry, I'm on it. > > > Meaning that you are in the course of doing the errands. If you're volunteering for work, I could imagine one saying "I'm on [action]," though again, I don't usually hear people say things like that. But I imagine if you were watching something like Scandal someone might volunteer to do something they're good at by saying "I'm on [action]." Or in this way: > > We need a person to do the dishes, a person to mop the floors, a person to to inventory, and a person to wash the windows. > > > I'm on washing the windows! > > > But on could also mean "having [the thing in question] as a focus". So if you told a friend something like: > > I'm on a never-ending quest to save my girlfriend! > > > Then sometime later, they might ask (if your girlfriend isn't saved yet): > > Hey, are you still on saving your girlfriend? > > > Meaning "is saving your girlfriend still your goal" in this case. Especially if you don't seem to be right in the middle of saving said girlfriend but doing something marginal or unrelated. > > You're still here? Are you still on saving your girlfriend? You know you're not going to find her here, right? > > >
Question: i have a cakephp web app that i'm developing. I have a UsersController.php file,which handles all users registrations and logins. When a user is logged in,he can use the functionality of FeaturesController.php. The FueaturesController.php has a view file,the create.ctp . In create.ctp,the user inserts some data into an HTML form and these data are saved into a database,using $this->Modelname->save($this->request->data). NOW,i want to add into a field of the database the username of the user that did/used that HTML,but till now i have not succeed! My code looks like this: ``` $username = $this->Session->read('Auth.User.username'); ``` so that i save the username of the user into the variable $username. But now,how can i insert it into the database? I have tried various ways but it didn't work :/ Anyone's help is welcomed,thank you in advance :) Answer:
You shouldn't add the username to the form, it's not secure as a malicious user simply has to modify the HTML to change it. Instead, you should set it right before saving: ``` $this->request->data['Modelname']['username'] = $this->Auth->user('username'); $this->Modelname->save($this->request->data); ``` Assuming you're using the authentication component `$this->Auth->user('username');` is the same as `$this->Session->read('Auth.User.username');` by the way, just a bit shorter.
``` $data['modelname']['dbfieldname'] = $username; $this->modelname->save(data); ```
Question: If I have two datetimes like this : ``` transtime_in, transtime_out ``` How to get the difference between those datetimes in the following format : ``` hh:mm ``` --- I use ``` DATEDIFF(hour, transtime_in, transtime_out) ``` but i get the hours only . Answer:
Try this one - **Query:** ``` DECLARE @transtime_in DATETIME , @transtime_out DATETIME SELECT @transtime_in = '2013-05-19 08:58:07.000' , @transtime_out = '2013-05-19 16:40:53.000' SELECT LEFT(CONVERT(VARCHAR(10), @transtime_out - @transtime_in, 108), 5) ``` **Output:** ``` ----- 07:42 ```
``` declare @D1 datetime declare @D2 datetime set @D1 = '2014-03-25 00:00:00.000' set @D2 = '2014-03-24 17:14:05.000' --select datediff(hour, cast(@D1 as time(0)), cast(@D2 as time(0))) SELECT LEFT(CONVERT(VARCHAR(10), @D2 - @D1, 108), 8) ```
Question: If I have two datetimes like this : ``` transtime_in, transtime_out ``` How to get the difference between those datetimes in the following format : ``` hh:mm ``` --- I use ``` DATEDIFF(hour, transtime_in, transtime_out) ``` but i get the hours only . Answer:
Try this one - **Query:** ``` DECLARE @transtime_in DATETIME , @transtime_out DATETIME SELECT @transtime_in = '2013-05-19 08:58:07.000' , @transtime_out = '2013-05-19 16:40:53.000' SELECT LEFT(CONVERT(VARCHAR(10), @transtime_out - @transtime_in, 108), 5) ``` **Output:** ``` ----- 07:42 ```
``` declare @D1 datetime declare @D2 datetime set @D1 = '2014-03-25 00:00:00.000' set @D2 = '2014-03-24 17:14:05.000' SELECT LEFT(CONVERT(VARCHAR(10), @D1 - @D2, 108), 8) ```
Question: If I have two datetimes like this : ``` transtime_in, transtime_out ``` How to get the difference between those datetimes in the following format : ``` hh:mm ``` --- I use ``` DATEDIFF(hour, transtime_in, transtime_out) ``` but i get the hours only . Answer:
``` declare @D1 datetime declare @D2 datetime set @D1 = '2014-03-25 00:00:00.000' set @D2 = '2014-03-24 17:14:05.000' --select datediff(hour, cast(@D1 as time(0)), cast(@D2 as time(0))) SELECT LEFT(CONVERT(VARCHAR(10), @D2 - @D1, 108), 8) ```
``` declare @D1 datetime declare @D2 datetime set @D1 = '2014-03-25 00:00:00.000' set @D2 = '2014-03-24 17:14:05.000' SELECT LEFT(CONVERT(VARCHAR(10), @D1 - @D2, 108), 8) ```
Question: I am building a script to back-up files and directories in my linux. These backups are stored in the map Archive. Now i use in my source a specific directory but i have e.g. input.txt with these directories: ``` /Downloads /etc/var ``` or also with specific files ``` /etc/log/test.txt ``` Using /Downloads or /etc/var it must also backup the subdirectories of these directories. E.g. /Downloads has 3 other directories /dir1,/dir2,/dir3 these need to be archived also. How can i use that file input.txt as source? Of the whole input.txt file I have to make 1 archive. ``` #!/bin/sh source="/Downloads" archive="example.tgz" dest="Archive" path="input.txt" tar czf $dest/$archive $source ls $dest #this is how i read my file while read line do echo $line done < $path ``` Answer:
Using tar for creating an archive `-T` option can be used to take files from an input file. input.txt: ``` /Downloads /etc/var /etc/log/test.txt ``` script: ``` #!/bin/sh archive="example.tgz" dest="Archive" path="input.txt" tar czf $dest/$archive -T $path ```
You can do it like this: ``` #!/bin/bash output_dir="/tmp/snapshots" current_date="$( date +%F_%H-%M-%S )" script_name="$( basename $0 )" dirs="" while IFS='' read -r line || [[ -n "$line" ]]; do # directory exists? if [ -d "$line" ] || [ -f "$line" ]; then dirs="$dirs $line" else echo "${script_name}: cannot access $line. No such directory. Skip" fi done < "$1" output_file="${output_dir}/${current_date}.tar.gz" if [ -n "$dirs" ] ; then tar -czvf $output_file $dirs echo "${script_name}: done!" exit 0 else echo "${script_name}: operation failed. Cannot create an empty archive." fi ``` First, this script specifies a directory (`/tmp/snapshots` in my case) where a resulting archive will be saved. Current date is used as a name to make sure you do not accidentally overwrite you previous archive. Next you read you input file line by line, appending directory or file names to the `$dirs` variable if and only if they acrually exist in your filesystem. See [this thread](https://stackoverflow.com/questions/10929453/bash-scripting-read-file-line-by-line) for more details about what's going on in the while loop. Then, if your `$dirs` variable is not empty (i.e. at least one directory or file exists), you're creating an archive, quitting otherwise. Not save the script (say, as `snapshot.sh`), make it executable (`$ chmod +x snapshot.sh`) and run like this: ``` ./snapshot.sh input.txt ```
Question: Often I will do a search to find things in Vim, such as: ``` /-some-regex-here ``` And after seeing what if grabs and iterating through a few of the results, I want to do a find-replace. Is there a way to convert the `/` to a `:` command? Or do I have to `esc` and then press `:` and re-type (or copy-paste) the command again? Answer:
In command-line, you can use `ctrl-r` (see `:h c_ctrl-r`) to start inserting the content of a register. In your case, you could paste the content of the last search with: ``` <c-r>/ ``` --- Another way would be to use `:h incsearch` to show the matches as you type your search (in a `/` search, or a `:s` command, and so on), so you don't need to "check" your regex before using it in a substitute command.
Just to show another way in addition to the already existing answers: In both the `/` and `:` command modes, you can press `ctrl-f` to essentially open the respective history as a new temporary buffer. See `:help c_ctrl-f` for details. So, what you could to is the following: * enter `/` `ctrl-f` (or `q/`) to open this special buffer for the search mode * use any normal mode commands to yank the text you need * enter the `:` command mode and insert the text, either with `ctrl-r` `"` or again using `ctrl-f` Of course, `ctrl-r` `/` is quicker for this particular use case, but the `ctrl-f` method is more general, so maybe it's useful to someone who finds this question.
Question: Often I will do a search to find things in Vim, such as: ``` /-some-regex-here ``` And after seeing what if grabs and iterating through a few of the results, I want to do a find-replace. Is there a way to convert the `/` to a `:` command? Or do I have to `esc` and then press `:` and re-type (or copy-paste) the command again? Answer:
You could just do: ``` %s//REPLACEMENT/ ``` From the docs: > > If the {pattern} for the substitute command is empty, the command uses the > pattern from the last substitute or `:global` command. If there is none, but > there is a previous search pattern, that one is used. > > > A example can be found with `:h :s_r` and then a few lines down, beginning with "For `:s` with an argument this already happens:". The quote above is further down in the text.
Just to show another way in addition to the already existing answers: In both the `/` and `:` command modes, you can press `ctrl-f` to essentially open the respective history as a new temporary buffer. See `:help c_ctrl-f` for details. So, what you could to is the following: * enter `/` `ctrl-f` (or `q/`) to open this special buffer for the search mode * use any normal mode commands to yank the text you need * enter the `:` command mode and insert the text, either with `ctrl-r` `"` or again using `ctrl-f` Of course, `ctrl-r` `/` is quicker for this particular use case, but the `ctrl-f` method is more general, so maybe it's useful to someone who finds this question.
Question: In Cassandra Cluster, how can we ensure all nodes are having almost equal data, instead one node has more data, another has very less. If this scenario occurs, what are the best practices Thanks Answer:
The error for the different histories comes from your local repo and the remote (on GitHub) not having the same commit history. If you initialized a different repo, you may want to just clone the repo from GitHub and then redo any changes locally on top of the new clone. This should allow you to then push to GitHub. Instead if you do have different branches that don't have a common starting point, you could use `--allow-unrelated-histories`, but this should be used with caution and in only specific scenarios when you have different starting points and need to preserve both histories.
Try ``` git pull --rebase ``` followed by ``` git push origin master ```
Question: Im putting together a basic Gross Profit Calculator in Visual Studio and need the output to show as a £ value, ie to 2 decimal places. I have tried this so far: ``` String.Format("{0:0.00}", TextBox3.Text = CStr(sale)) ``` where TextBox3 is the output for the calculation. However on using this, nothing happens and the box remains empty and I can't work out why! Answer:
Your syntax is not correct, re-write your code this way: ``` TextBox3.Text = String.Format("{0:0.00}", sale) ``` The `String.Format`'s result wasn't being assigned to anything.
The syntax is wrong, and besides, `CStr` is just another way to format other types as a string. By using it you *prevent* `String.Format` from doing its job I think you are looking for ``` TextBox3.Text = String.Format("{0:0.00}", sale) ``` Furthermore, built-in numeric types override `ToString` and allow custom formatting as well. If `sale` is a float, double or decimal, you can write: ``` TextBox3.Text = sale.ToString("0.00") ``` or ``` TextBox3.Text = sale.ToString("N2") ```
Question: First we get the crude rate which is cancer count/population count \* 100,000, since cancer count might relate to the population of male/female ration, so need to turn the crude rate to standardized rate, so later we can compare rate among different populations, here the assumption of standard population of ratio of `Female:Male = 51:49`. So the Gender Standardized Rate is: ``` Female crude rate * female percentage + Male crude rate * male percentage = 671.7 * 0.51 + 716.7 * 0.49 = 693.7 ``` So for total standardized rate it will be 693.7, the rest standardized rate will be same as crude rate. The question is how to implement it? How should I define it in Calculation like `if currentmember.level = total then ... else [crude rate]` ![enter image description here](https://i.stack.imgur.com/TxWTL.png) Answer:
It seems that you want to ignore Undifferentiated, and calculate Satnsarized. You could try to use expression like below to see whether it will work or not with member[Measures].[SalesCalc2] AS ( IIF([Product].[Category].CurrentMember=[Product].[Category].&[3],"0",[Measures].[Internet Sales Count]) ) member[Measures].[SalesCalc3] AS [Measures].[SalesCalc2] \*[Measures].[Internet Sales Count] select [Product].[Category].[Category] on rows, {[Measures].[Internet Sales Count],[Measures].[SalesCalc2] ,[Measures].[SalesCalc3] } on columns from [Analysis Services Tutorial] [![enter image description here](https://i.stack.imgur.com/7W3qv.png)](https://i.stack.imgur.com/7W3qv.png) You could refer to [this post](https://social.msdn.microsoft.com/Forums/en-US/4f6a7381-9dd3-422e-9b8a-23e1f198890f/mdx-excluding-dimension-members-from-the-measure-calculation?forum=sqlanalysisservices) for details Zoe
The solution is to use SCOPE in calculation. The purpose of using SCOPE is to do the calculation first, which is Female crude rate \* female percentage and Male crude rate \* male percentage then add them together, so the formula is 671.7 \* 0.51 + 716.7 \* 0.49 = 693.7 Please refer to the following link for steps to implement it: <https://blog.crossjoin.co.uk/2013/05/29/aggregating-the-result-of-an-mdx-calculation-using-scoped-assignments/>
Question: How do I add padding, or some space between the textboxes when using dockstyle.top property? ``` for(int i =0; i< 10; i++) { textboxes[i] = new TextBox(); textboxes[i].Dock = DockStyle.Top; mypanel.Controls.Add(textboxes[i]); } ``` The code above puts textboxes right beneath each other. Can't figure this out without using mass panels or fixed positioning. How to do the following? 1) I would like to add around 10-20pixels between boxes. 2) How to change size (height,width) of the textboxes, since when using dockstyle.top it ignores the size commands ? Answer:
With DockStype.Top you can't change the width of your TextBoxes, cause they are docked. You can only change the height. But to change the height of a TextBox you have to set the `Multiline = true` beforehand. To get the space between the different boxes you have to put each TextBox within a panel, set the `TextBox.Dock = Fill`, the `Panel.Dock = Top` and the `Panel.Padding = 10`. Now you have some space between each TextBox. ### Sample Code ``` for (int i = 0; i < 10; i++) { var panelTextBox = CreateBorderedTextBox(); this.Controls.Add(panelTextBox); } private Panel CreateBorderedTextBox() { var panel = CreatePanel(); var textBox = CreateTextBox(); panel.Controls.Add(textBox); return panel; } private Panel CreatePanel() { var panel = new Panel(); panel.Dock = DockStyle.Top; panel.Padding = new Padding(5); return panel; } private TextBox CreateTextBox() { var textBox = new TextBox(); textBox.Multiline = true; textBox.Dock = DockStyle.Fill; return textBox; } ``` What i forgot, you can also give a try to the [FlowLayoutPanel](http://msdn.microsoft.com/en-us/library/zah8ywcc.aspx). Just remove the `DockStyle.Top` from the panels and put them into the FlowLayoutPanel. Also you should set the [FlowDirection](http://msdn.microsoft.com/en-us/library/system.windows.forms.flowlayoutpanel.flowdirection.aspx) to TopDown. Maybe this can also help you to solve your problem, too.
I know where you're coming from, this is especially frustrating after returning to WinForms from WPF. I would suggest using a [**TableLayoutPanel**](http://msdn.microsoft.com/en-us/library/system.windows.forms.tablelayoutpanel.aspx), in which each TextBox would get its own cell, and adjusting the properties of the cells. This should solve both your padding and size problems. Another alternative would be to use some more complex layout controls, such as the [DevExpress](http://www.devexpress.com/Products/NET/Controls/WinForms/Layout/) ones (not free).
Question: How do I add padding, or some space between the textboxes when using dockstyle.top property? ``` for(int i =0; i< 10; i++) { textboxes[i] = new TextBox(); textboxes[i].Dock = DockStyle.Top; mypanel.Controls.Add(textboxes[i]); } ``` The code above puts textboxes right beneath each other. Can't figure this out without using mass panels or fixed positioning. How to do the following? 1) I would like to add around 10-20pixels between boxes. 2) How to change size (height,width) of the textboxes, since when using dockstyle.top it ignores the size commands ? Answer:
Another work around that suits smaller layouts is to just add a `Label` control afterwards also docked to the `Top`, which is not AutoSized, `Text=" "`, `Height=your padding`. This is quite useful for the odd bit of padding when using the designer.
I know where you're coming from, this is especially frustrating after returning to WinForms from WPF. I would suggest using a [**TableLayoutPanel**](http://msdn.microsoft.com/en-us/library/system.windows.forms.tablelayoutpanel.aspx), in which each TextBox would get its own cell, and adjusting the properties of the cells. This should solve both your padding and size problems. Another alternative would be to use some more complex layout controls, such as the [DevExpress](http://www.devexpress.com/Products/NET/Controls/WinForms/Layout/) ones (not free).
Question: How do I add padding, or some space between the textboxes when using dockstyle.top property? ``` for(int i =0; i< 10; i++) { textboxes[i] = new TextBox(); textboxes[i].Dock = DockStyle.Top; mypanel.Controls.Add(textboxes[i]); } ``` The code above puts textboxes right beneath each other. Can't figure this out without using mass panels or fixed positioning. How to do the following? 1) I would like to add around 10-20pixels between boxes. 2) How to change size (height,width) of the textboxes, since when using dockstyle.top it ignores the size commands ? Answer:
With DockStype.Top you can't change the width of your TextBoxes, cause they are docked. You can only change the height. But to change the height of a TextBox you have to set the `Multiline = true` beforehand. To get the space between the different boxes you have to put each TextBox within a panel, set the `TextBox.Dock = Fill`, the `Panel.Dock = Top` and the `Panel.Padding = 10`. Now you have some space between each TextBox. ### Sample Code ``` for (int i = 0; i < 10; i++) { var panelTextBox = CreateBorderedTextBox(); this.Controls.Add(panelTextBox); } private Panel CreateBorderedTextBox() { var panel = CreatePanel(); var textBox = CreateTextBox(); panel.Controls.Add(textBox); return panel; } private Panel CreatePanel() { var panel = new Panel(); panel.Dock = DockStyle.Top; panel.Padding = new Padding(5); return panel; } private TextBox CreateTextBox() { var textBox = new TextBox(); textBox.Multiline = true; textBox.Dock = DockStyle.Fill; return textBox; } ``` What i forgot, you can also give a try to the [FlowLayoutPanel](http://msdn.microsoft.com/en-us/library/zah8ywcc.aspx). Just remove the `DockStyle.Top` from the panels and put them into the FlowLayoutPanel. Also you should set the [FlowDirection](http://msdn.microsoft.com/en-us/library/system.windows.forms.flowlayoutpanel.flowdirection.aspx) to TopDown. Maybe this can also help you to solve your problem, too.
Another work around that suits smaller layouts is to just add a `Label` control afterwards also docked to the `Top`, which is not AutoSized, `Text=" "`, `Height=your padding`. This is quite useful for the odd bit of padding when using the designer.
Question: I have to develop a small app to compare automatically generated folders. It must compare the folders, sub-folders and file contents. The problem is that this app needs to be launched either from a user on his computer to manually check for changes, or automatically along with the ANT nightlies. In the first case the results are displayed as a table in the Swing GUI. But in the other case, it must create a file to put the results in (format doesn't matter, XML, CSV, ...). Anyone got some tips, or a link to a tutorial ? Answer:
You might want to add some command line option that switches between ui and file export, e.g. `--gui` or `--export=[filename]`. You could use [Apache Commons CLI](http://commons.apache.org/cli/) for that.
The other method is to create a set of classes that performs the task, and returns a set of values, which can then be either written to disk, or displayed in a GUI. I.e., an engine, and two front-ends (the GUI and the CLI). for example: ``` public interface DirectoryComparer { CompareResult performCompare(Directory dir1, Directory dir2); public static interface CompareResult { //...things here that you need, such as, file or dir difference, etc Iterable<File> getFileDiff(); Iterable<Directory> getDirectoryDiff(); } } ``` then, the GUI clients will just use `DirectoryComparer` to display the results, and the CLI client will write these results to a file or three. But those two clients are completely separate, and can be maintained separately.
Question: I am using purely CSS to create a dynamically opening and closing sidebar based on the view-port with of the page. I have a couple issues with my code however: 1. How can I prevent an animation when the screen first loads? That is, I simply want the sidebar to be opened or closed on first loading, and then animated when the view-port is adjusted. 2. Why do I have to have two separate animations? Notice I have two identical keyframes `toggle` and `toggle1`, which are used for closing and opening respectively. If I try to use just `toggle` for both animations, the animation occurs instantly. Any workaround without duplicated code? ```css body { margin: 0; padding: 0; overflow: hidden; } #sidebar { position: absolute; width: 200px; background-color: #123456; height: 100vh; } @media (min-width: 500px) { #sidebar { animation: toggle 200ms ease-in 1 reverse forwards; } } @media (max-width: 500px) { #sidebar { animation: toggle1 200ms ease-out 1 normal forwards; } } @keyframes toggle { 0% { left: 0px; } 100% { left: -200px; } } @keyframes toggle1 { from { left: 0px; } to { left: -200px; } } ``` ```html <div id="sidebar"></div> ``` Answer:
Just use a simple transition instead of animation, and 1 media query ``` #sidebar { position: absolute; width: 200px; background-color: #123456; height: 100vh; transition:left 500ms ease; left:0; } @media (max-width: 500px) { #sidebar { left: -200px; } } ``` <https://jsfiddle.net/ufoste1y/3/> You can also use transform:translateX, which should provide [better performance](https://www.paulirish.com/2012/why-moving-elements-with-translate-is-better-than-posabs-topleft/). ``` #sidebar { position: absolute; width: 200px; background-color: #123456; height: 100vh; transition:transform 500ms ease; } @media (max-width: 500px) { #sidebar { transform: translateX(-200px); } } ``` <https://jsfiddle.net/ufoste1y/8/>
In order to force the sidebar to be opened or closed by default, that **cannot** be done with raw CSS. You'd need JavaScript to wait until the page has finished loading, and then dynamically update the element to have a class or similar that the CSS animation applies to. As for the duplicate code, you can certainly just use `toggle`. It not working for you was probably a result of you forgetting to also change the `@media` `animation` reference from `toggle1` to `toggle`. Here's an example showing the sidebar staying open by default with the aid of JavaScript. The animation is now triggering only on the `.loaded` class, and the JavaScript applies the `loaded` class to the element 1000 milliseconds after the page has loaded, meaning that it won't trigger the animation initially. Having said that, you'll probably only want to trigger the slide on some sort of condition anyway, and JavaScript would be much better suited to that :) ```js window.addEventListener("load", function() { setTimeout(function() { var sidebar = document.getElementById("sidebar"); sidebar.classList.add("loaded"); }, 1000); }); ``` ```css body { margin: 0; padding: 0; overflow: hidden; } #sidebar { position: absolute; width: 200px; background-color: #123456; height: 100vh; } @media (min-width: 500px) { #sidebar.loaded { animation: toggle 200ms ease-in 1 reverse forwards; } } @media (max-width: 500px) { #sidebar.loaded { animation: toggle 200ms ease-out 1 normal forwards; } } @keyframes toggle { 0% { left: 0px; } 100% { left: -200px; } } ``` ```html <div id="sidebar"></div> ```
Question: I have an application using Apache CXF with a lots of SOAP services implemented. So, i would like to use the "service registry" concept and then, i´d hear about UDDI, but i dont know how to implemented that. Is Apache CXF already composed by an API to deploy UDDI engine or should i fix another library to do that? Answer:
Take a look at JUDDI: <http://juddi.apache.org/> which is a UDDI service. The latest version is written to JAX-WS and is tested by default with CXF.
To add, jUDDI has a neat way to automate the registration of web services using annotations and a servlet startup listener. Source: <http://svn.apache.org/repos/asf/juddi/trunk/juddi-examples/uddi-annotations/>
Question: Could you please give me a sentence where *well* (meaning *good*) modifies another adverb? > > Centrifugal force is a well-known principle of physics. (*well* modifying an adjective) > > > She drives well. (*well* modifying a verb) > > > But can I create one where *well* will modify an another adverb? Answer:
> > He was well-deservedly knighted. > > > Here *well* modifies an adverb that modifies a participle. Going by [Internet search results](https://www.google.de/search?q=%22well+deservedly%22), *well-deservedly* seems to be actually used.
Adverbs *can* modify adverbs but that doesn't mean they must. It doesn't even mean that the majority can be used in that way. I cannot think of an example but it doesn't surprise me. For example, 'slowly' is an adverb. Can you find an example where 'slowly' modifies another adverb?
Question: I need to add info button to toolbar. can any one help me to solve this. Thanks in advance. Answer:
You need to create a `UIButton` of type `UIButtonTypeInfoLight` (or, depending on your toolbar color `UIButtonTypeInfoDark`). You'd then use this button as the custom view for a `UIBarButtonItem`: ``` UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeInfoLight]; UIBarButtonItem *infoButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:infoButton] autorelease]; myToolbar.items = [NSArray arrayWithObjects:infoButtonItem, nil]; ```
Create the info image, then use `-initWithImage:style:target:action:`.
Question: I'm developing a system which is planning to use elasticsearch as an data repository. I'm trying to choose the best way to develop my application that can index and query data from elasticsearch. The system I have is built on top of Spring framework. Is it a good choice to use **Spring-data-elasticsearch**(<https://github.com/spring-projects/spring-data-elasticsearch>)? Or is it a good choice to use **elasticsearch core libraries itself**? I need to handle nested data (inner object) but Spring-data-elasticsearch seems to have no operations for that recently. I hope I can find a solution for the question. Thanks in advance. Answer:
Spring data elasticsearch supports most of the common feature set of elasticsearch including Nested, Inner Objects and Parent Child (recently). When you said that want to use **nested data (inner object)**, please be clear as elasticsearch has two concepts: Inner Object and Nested Object. Detailed explanation can be found at [managing relationship in elasticsearch](http://www.elasticsearch.org/blog/managing-relations-inside-elasticsearch/) ### Nested document Example Person Entity: ``` @Document(indexName = "person" , type = "user") public class Person { @Id private String id; private String name; @Field( type = FieldType.Nested) private List<Car> car; // setters-getters } ``` Car Entity: ``` public class Car { private String name; private String model; //setters and getters } ``` Setting up data: ``` Person foo = new Person(); foo.setName("Foo"); foo.setId("1"); List<Car> cars = new ArrayList<Car>(); Car subaru = new Car(); subaru.setName("Subaru"); subaru.setModel("Imprezza"); cars.add(subaru); foo.setCar(cars); ``` Indexing: ``` IndexQuery indexQuery = new IndexQuery(); indexQuery.setId(foo.getId()); indexQuery.setObject(foo); //creating mapping elasticsearchTemplate.putMapping(Person.class); //indexing document elasticsearchTemplate.index(indexQuery); //refresh elasticsearchTemplate.refresh(Person.class, true); ``` Searching: ``` QueryBuilder builder = nestedQuery("car", boolQuery() .must(termQuery("car.name", "subaru")) .must(termQuery("car.model", "imprezza"))); SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build(); List<Person> persons = elasticsearchTemplate.queryForList(searchQuery, Person.class); ``` You can find more test cases about Nested and Inner Object at [Nested Object Tests](https://github.com/spring-projects/spring-data-elasticsearch/blob/master/src/test/java/org/springframework/data/elasticsearch/NestedObjectTests.java)
You can use IndexQuery for save AND update: ``` public Serializable saveOrUpdate(Car car) { return template.index(new IndexQueryBuilder().withObject(car).build()); } ```
Question: I'm developing a system which is planning to use elasticsearch as an data repository. I'm trying to choose the best way to develop my application that can index and query data from elasticsearch. The system I have is built on top of Spring framework. Is it a good choice to use **Spring-data-elasticsearch**(<https://github.com/spring-projects/spring-data-elasticsearch>)? Or is it a good choice to use **elasticsearch core libraries itself**? I need to handle nested data (inner object) but Spring-data-elasticsearch seems to have no operations for that recently. I hope I can find a solution for the question. Thanks in advance. Answer:
Spring data elasticsearch supports most of the common feature set of elasticsearch including Nested, Inner Objects and Parent Child (recently). When you said that want to use **nested data (inner object)**, please be clear as elasticsearch has two concepts: Inner Object and Nested Object. Detailed explanation can be found at [managing relationship in elasticsearch](http://www.elasticsearch.org/blog/managing-relations-inside-elasticsearch/) ### Nested document Example Person Entity: ``` @Document(indexName = "person" , type = "user") public class Person { @Id private String id; private String name; @Field( type = FieldType.Nested) private List<Car> car; // setters-getters } ``` Car Entity: ``` public class Car { private String name; private String model; //setters and getters } ``` Setting up data: ``` Person foo = new Person(); foo.setName("Foo"); foo.setId("1"); List<Car> cars = new ArrayList<Car>(); Car subaru = new Car(); subaru.setName("Subaru"); subaru.setModel("Imprezza"); cars.add(subaru); foo.setCar(cars); ``` Indexing: ``` IndexQuery indexQuery = new IndexQuery(); indexQuery.setId(foo.getId()); indexQuery.setObject(foo); //creating mapping elasticsearchTemplate.putMapping(Person.class); //indexing document elasticsearchTemplate.index(indexQuery); //refresh elasticsearchTemplate.refresh(Person.class, true); ``` Searching: ``` QueryBuilder builder = nestedQuery("car", boolQuery() .must(termQuery("car.name", "subaru")) .must(termQuery("car.model", "imprezza"))); SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build(); List<Person> persons = elasticsearchTemplate.queryForList(searchQuery, Person.class); ``` You can find more test cases about Nested and Inner Object at [Nested Object Tests](https://github.com/spring-projects/spring-data-elasticsearch/blob/master/src/test/java/org/springframework/data/elasticsearch/NestedObjectTests.java)
Spring data elasticsearch uses transport client, and transport client is not supported by AWS elasticsearch. AWS elasticsearch supports only HTTP clients. So i think the best java client for elasticsearch is JEST. It also provides support for AWS authentication using IAM.
Question: I'm developing a system which is planning to use elasticsearch as an data repository. I'm trying to choose the best way to develop my application that can index and query data from elasticsearch. The system I have is built on top of Spring framework. Is it a good choice to use **Spring-data-elasticsearch**(<https://github.com/spring-projects/spring-data-elasticsearch>)? Or is it a good choice to use **elasticsearch core libraries itself**? I need to handle nested data (inner object) but Spring-data-elasticsearch seems to have no operations for that recently. I hope I can find a solution for the question. Thanks in advance. Answer:
Spring data elasticsearch supports most of the common feature set of elasticsearch including Nested, Inner Objects and Parent Child (recently). When you said that want to use **nested data (inner object)**, please be clear as elasticsearch has two concepts: Inner Object and Nested Object. Detailed explanation can be found at [managing relationship in elasticsearch](http://www.elasticsearch.org/blog/managing-relations-inside-elasticsearch/) ### Nested document Example Person Entity: ``` @Document(indexName = "person" , type = "user") public class Person { @Id private String id; private String name; @Field( type = FieldType.Nested) private List<Car> car; // setters-getters } ``` Car Entity: ``` public class Car { private String name; private String model; //setters and getters } ``` Setting up data: ``` Person foo = new Person(); foo.setName("Foo"); foo.setId("1"); List<Car> cars = new ArrayList<Car>(); Car subaru = new Car(); subaru.setName("Subaru"); subaru.setModel("Imprezza"); cars.add(subaru); foo.setCar(cars); ``` Indexing: ``` IndexQuery indexQuery = new IndexQuery(); indexQuery.setId(foo.getId()); indexQuery.setObject(foo); //creating mapping elasticsearchTemplate.putMapping(Person.class); //indexing document elasticsearchTemplate.index(indexQuery); //refresh elasticsearchTemplate.refresh(Person.class, true); ``` Searching: ``` QueryBuilder builder = nestedQuery("car", boolQuery() .must(termQuery("car.name", "subaru")) .must(termQuery("car.model", "imprezza"))); SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build(); List<Person> persons = elasticsearchTemplate.queryForList(searchQuery, Person.class); ``` You can find more test cases about Nested and Inner Object at [Nested Object Tests](https://github.com/spring-projects/spring-data-elasticsearch/blob/master/src/test/java/org/springframework/data/elasticsearch/NestedObjectTests.java)
Also for like queries in Elasticsearch using Spring Boot you can make something like this: ``` Car car = new Car(); car.setName(new InnerField("name", "имя")); QueryBuilder builder = QueryBuilders .boolQuery() .should(QueryBuilders.regexpQuery("name.ru", ".*" + name + ".*")) .should(QueryBuilders.regexpQuery("name.kk", ".*" + name + ".*")) .should(QueryBuilders.regexpQuery("name.qq", ".*" + name + ".*")); NativeSearchQuery build = new NativeSearchQueryBuilder().withQuery(builder).build(); elasticsearchOperations.queryForList(build, tClass); ```
Question: I'm developing a system which is planning to use elasticsearch as an data repository. I'm trying to choose the best way to develop my application that can index and query data from elasticsearch. The system I have is built on top of Spring framework. Is it a good choice to use **Spring-data-elasticsearch**(<https://github.com/spring-projects/spring-data-elasticsearch>)? Or is it a good choice to use **elasticsearch core libraries itself**? I need to handle nested data (inner object) but Spring-data-elasticsearch seems to have no operations for that recently. I hope I can find a solution for the question. Thanks in advance. Answer:
You can use IndexQuery for save AND update: ``` public Serializable saveOrUpdate(Car car) { return template.index(new IndexQueryBuilder().withObject(car).build()); } ```
Also for like queries in Elasticsearch using Spring Boot you can make something like this: ``` Car car = new Car(); car.setName(new InnerField("name", "имя")); QueryBuilder builder = QueryBuilders .boolQuery() .should(QueryBuilders.regexpQuery("name.ru", ".*" + name + ".*")) .should(QueryBuilders.regexpQuery("name.kk", ".*" + name + ".*")) .should(QueryBuilders.regexpQuery("name.qq", ".*" + name + ".*")); NativeSearchQuery build = new NativeSearchQueryBuilder().withQuery(builder).build(); elasticsearchOperations.queryForList(build, tClass); ```
Question: I'm developing a system which is planning to use elasticsearch as an data repository. I'm trying to choose the best way to develop my application that can index and query data from elasticsearch. The system I have is built on top of Spring framework. Is it a good choice to use **Spring-data-elasticsearch**(<https://github.com/spring-projects/spring-data-elasticsearch>)? Or is it a good choice to use **elasticsearch core libraries itself**? I need to handle nested data (inner object) but Spring-data-elasticsearch seems to have no operations for that recently. I hope I can find a solution for the question. Thanks in advance. Answer:
Spring data elasticsearch uses transport client, and transport client is not supported by AWS elasticsearch. AWS elasticsearch supports only HTTP clients. So i think the best java client for elasticsearch is JEST. It also provides support for AWS authentication using IAM.
Also for like queries in Elasticsearch using Spring Boot you can make something like this: ``` Car car = new Car(); car.setName(new InnerField("name", "имя")); QueryBuilder builder = QueryBuilders .boolQuery() .should(QueryBuilders.regexpQuery("name.ru", ".*" + name + ".*")) .should(QueryBuilders.regexpQuery("name.kk", ".*" + name + ".*")) .should(QueryBuilders.regexpQuery("name.qq", ".*" + name + ".*")); NativeSearchQuery build = new NativeSearchQueryBuilder().withQuery(builder).build(); elasticsearchOperations.queryForList(build, tClass); ```
Question: I develop iOS app and it uses camera. AVCaptureDeviceInput is used to interface to camera. I checked Authorisation status as ``` - (void)checkDeviceAuthorizationStatus { NSString *mediaType = AVMediaTypeVideo; [AVCaptureDevice requestAccessForMediaType:mediaType completionHandler:^(BOOL granted) { if (granted) { //Granted access to mediaType [self setDeviceAuthorized:YES]; } else { //Not granted access to mediaType dispatch_async(dispatch_get_main_queue(), ^{ [[[UIAlertView alloc] initWithTitle:@"AVCam!" message:@"AVCam doesn't have permission to use Camera, please change privacy settings" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil] show]; [self setDeviceAuthorized:NO]; }); } }]; } ``` When I launch the application, why it does not ask user permission for access to the camera? So the app does not appear in settings/privacy/camera to manually allow to access camera. Then show this error `"AVCam doesn't have permission to use Camera, please change privacy settings"` and app can't use the camera. EDIT: That means the app is not allowed to access the camera without asking user permission. Not only camera, camera-roll also has the same problem. All these things happened after I reset settings in Settings/Reset/Rest All Settings. Before that the app was working well. Answer:
The problem is solved now. I need to trace back step by step and took me long time to solve the problem. Some people suggested to include NSCamerausageDescription Key. Actually it is necessary for devices with iOS 7 and above. I included the Key but still user permission is not asked yet. Finally I found the problem at Info.plist. There are some extra lines and I deleted three lines. Not sure how they are related to my problem. Those I deleted are (1)Get info string (2)Bundle display name (3)Application Category After deleting these three lines in the info.plist. Then the app asks the user permission. The point is that you may need to check your Info.plist for such problem.
You need to put the name of your app in "Bundle display name" in info.plist
Question: I develop iOS app and it uses camera. AVCaptureDeviceInput is used to interface to camera. I checked Authorisation status as ``` - (void)checkDeviceAuthorizationStatus { NSString *mediaType = AVMediaTypeVideo; [AVCaptureDevice requestAccessForMediaType:mediaType completionHandler:^(BOOL granted) { if (granted) { //Granted access to mediaType [self setDeviceAuthorized:YES]; } else { //Not granted access to mediaType dispatch_async(dispatch_get_main_queue(), ^{ [[[UIAlertView alloc] initWithTitle:@"AVCam!" message:@"AVCam doesn't have permission to use Camera, please change privacy settings" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil] show]; [self setDeviceAuthorized:NO]; }); } }]; } ``` When I launch the application, why it does not ask user permission for access to the camera? So the app does not appear in settings/privacy/camera to manually allow to access camera. Then show this error `"AVCam doesn't have permission to use Camera, please change privacy settings"` and app can't use the camera. EDIT: That means the app is not allowed to access the camera without asking user permission. Not only camera, camera-roll also has the same problem. All these things happened after I reset settings in Settings/Reset/Rest All Settings. Before that the app was working well. Answer:
The problem is solved now. I need to trace back step by step and took me long time to solve the problem. Some people suggested to include NSCamerausageDescription Key. Actually it is necessary for devices with iOS 7 and above. I included the Key but still user permission is not asked yet. Finally I found the problem at Info.plist. There are some extra lines and I deleted three lines. Not sure how they are related to my problem. Those I deleted are (1)Get info string (2)Bundle display name (3)Application Category After deleting these three lines in the info.plist. Then the app asks the user permission. The point is that you may need to check your Info.plist for such problem.
Well looking at above contradictory solutions - to remove and to add bundle display name - makes me think of the cause of this bug. I guess this (Apple) bug appears only on devices that had the same app installed at the time it didn't have camera permissions (older versions without camera functions or just bad testflight versions). So if you just delete and install from scratch the bugged app permissions will become okay. Speaking of workaround without uninstalling the existing app, if you change the bundle description (delete or add) in plist then iOS will use the new plist with permissions over already installed as we expect it should.
Question: I would like to route packages received by a VM host to different VM guest, on basis of application layer, in particular domains given in urls. It is impossible to route on network layer level, since IP address limitations (to the outside) do not allow this. Answer:
You mention URLs so forgive me if I make an assumption that this is web traffic. Could you put an apache + mod\_proxy on the domU / VM host and direct the traffic based on URL that way?
nginx is a light-weight proxy that can do this with web and e-mail traffic.
Question: Android can't update view direct on non-ui thread,but if I just read/get some information for ui? For example I have a method updateModel() like ``` void updateModel() { dailyReport.log.setValue(editLog.getText().toString()); dailyReport.plan.setValue(editPlan.getText().toString()); dailyReport.question.setValue(editQuestion.getText().toString()); } ``` Is it a problem if I run this method on non-ui thread. Answer:
Example below helped me solve this problem. Hope this will help you too ``` runOnUiThread(new Runnable() { @Override public void run() { //do your job } }); ```
Yes you can Update the UI from a Non UI thread. There are two ways of doing this. 1) Do this with activity object (easy option get and Update) 2) Do this using Message [Handler](http://developer.android.com/reference/android/os/Handler.html) (a bit difficult and Update only) Going for the 1st one all you need to do is Pass the Activity into the constructor. Here is Thread snippet ``` public class MyThread extends Thread { private Activity _activity; public MyThread(Activity activity) { this._activity = activity; } @Override public void run() { super.run(); //do all what you want. and at the end to Update the Views Do this if(!this._activity.isFinishing()) { // executed if the activity is not finishing this._activity.runOnUiThread(new Runnable() { @Override public void run() { //set the public variables UI Variables like this dailyReport.log.setValue(this._activity.editLog.getText().toString()); dailyReport.plan.setValue(this._activity.editPlan.getText().toString()); dailyReport.question.setValue(this._activity.editQuestion.getText().toString()); }); } } } ``` **Now in the Activity** ``` MyThread thread = new MyThread(this); thread.start; ```
Question: Android can't update view direct on non-ui thread,but if I just read/get some information for ui? For example I have a method updateModel() like ``` void updateModel() { dailyReport.log.setValue(editLog.getText().toString()); dailyReport.plan.setValue(editPlan.getText().toString()); dailyReport.question.setValue(editQuestion.getText().toString()); } ``` Is it a problem if I run this method on non-ui thread. Answer:
**Is it a problem if I run this method on non-ui thread?** With the assumption that `dailyPlan` is a model class and its methods do not modify the UI, then no, it is not a problem, Android will not complain and you will not receive any runtime errors. However, I would not follow this approach as in general it's a bad practice to access directly one threads data from another thread - you never know who is modifying what, read/write issues can occur and so on. These are usually solved by synchronizing the data, but if you put `synchronized` code in UI thread you made things even worse! For your kind of problem, why don't you pass the data from UI controls to the thread that uses above logic? When you create it, pass the 3 strings: 1. `editLog.getText().toString()` 2. `editPlan.getText().toString()` 3. `editQuestion.getText().toString()` Example: ``` private EditText editLog; private EditText editPlan; private EditText editQuestions; private void activityMethodThatStartsThread() { String log = editLog.getText().toString(); String plan = editPlan.getText().toString(); String questions = editQuestions.getText().toString(); DailyReportModel model = new DailyReportModel(log, plan, questions); model.start(); } public class DailyReportModel extends Thread { private String log; private String plan; private String questions; public DailyReportModel(String log, String plan, String questions) { super(); this.log = log; this.plan = plan; this.questions = questions; } void updateModel() { dailyReport.log.setValue(log); dailyReport.plan.setValue(plan); dailyReport.question.setValue(questions); } } ```
Yes you can Update the UI from a Non UI thread. There are two ways of doing this. 1) Do this with activity object (easy option get and Update) 2) Do this using Message [Handler](http://developer.android.com/reference/android/os/Handler.html) (a bit difficult and Update only) Going for the 1st one all you need to do is Pass the Activity into the constructor. Here is Thread snippet ``` public class MyThread extends Thread { private Activity _activity; public MyThread(Activity activity) { this._activity = activity; } @Override public void run() { super.run(); //do all what you want. and at the end to Update the Views Do this if(!this._activity.isFinishing()) { // executed if the activity is not finishing this._activity.runOnUiThread(new Runnable() { @Override public void run() { //set the public variables UI Variables like this dailyReport.log.setValue(this._activity.editLog.getText().toString()); dailyReport.plan.setValue(this._activity.editPlan.getText().toString()); dailyReport.question.setValue(this._activity.editQuestion.getText().toString()); }); } } } ``` **Now in the Activity** ``` MyThread thread = new MyThread(this); thread.start; ```
Question: I have a project with many branches. I would like to work on **several** branches simultaneously without switching back and forth with `git checkout`. Is there any way I can do that besides copying the whole repository somewhere else? Answer:
Git supports multiple worktree at the same time. For more information see: * [Multiple working directories with Git?](https://stackoverflow.com/questions/6270193/multiple-working-directories-with-git) * <https://git-scm.com/docs/git-worktree> How ever it is very hard to support multiple worktree with IDs. For example this is an [enhancement request](https://bugs.eclipse.org/bugs/show_bug.cgi?id=477475) in JGet (eclipse ID) to support worktree. So, you have to manage project manually (command line) with lots of problems or work with a single worktree in an IDE.
Here's a scalable version of the [accepted answer](https://stackoverflow.com/a/30186843/9962007) (upvoted), with sequentially named branches (`app1..app10`). Note we should try to *avoid duplicate checkout* (here: by checking out the `master` branch, which will not be covered by `git worktree add`): ``` $ git checkout master && for NUM in {1..10}; do git worktree add ~/git/<repo-name>/app$NUM app$NUM; done ```
Question: I have a project with many branches. I would like to work on **several** branches simultaneously without switching back and forth with `git checkout`. Is there any way I can do that besides copying the whole repository somewhere else? Answer:
Take a look at [$GIT\_SRC\_DIR/contrib/workdir/git-new-workdir](https://github.com/git/git/blob/master/contrib/workdir/git-new-workdir). According to the [commit logs](https://github.com/Khan/git-new-workdir/commit/88e4295fa435a339a39afecfed058e80a24ff35d) from a port of this repository: > > a simple script to create a working directory that uses symlinks to > point at an exisiting repository. This allows having different > branches in different working directories but all from the same > repository. > > >
I suggest my small script <http://www.redhotchilipython.com/en_posts/2013-02-01-clone-per-feature.html> It will do git clone and replace the config (to "look" at original repo, so pull/push will go into "main" repo) basically, but it's simple enough to serve an abstraction from actual bootstrapping.
Question: I have a project with many branches. I would like to work on **several** branches simultaneously without switching back and forth with `git checkout`. Is there any way I can do that besides copying the whole repository somewhere else? Answer:
Take a look at [$GIT\_SRC\_DIR/contrib/workdir/git-new-workdir](https://github.com/git/git/blob/master/contrib/workdir/git-new-workdir). According to the [commit logs](https://github.com/Khan/git-new-workdir/commit/88e4295fa435a339a39afecfed058e80a24ff35d) from a port of this repository: > > a simple script to create a working directory that uses symlinks to > point at an exisiting repository. This allows having different > branches in different working directories but all from the same > repository. > > >
Here's a scalable version of the [accepted answer](https://stackoverflow.com/a/30186843/9962007) (upvoted), with sequentially named branches (`app1..app10`). Note we should try to *avoid duplicate checkout* (here: by checking out the `master` branch, which will not be covered by `git worktree add`): ``` $ git checkout master && for NUM in {1..10}; do git worktree add ~/git/<repo-name>/app$NUM app$NUM; done ```
Question: I have a project with many branches. I would like to work on **several** branches simultaneously without switching back and forth with `git checkout`. Is there any way I can do that besides copying the whole repository somewhere else? Answer:
Git 2.5+ (Q2 2015) supports this feature! If you have a git repo `cool-app`, cd to root (`cd cool-app`), run `git worktree add ../cool-app-feature-A feature/A`. This checks out the branch `feature/A` in it's own new dedicated directory, `cool-app-feature-A`. That replaces an older script `contrib/workdir/git-new-workdir`, with a more robust mechanism where those "linked" working trees are actually recorded in the main repo new `$GIT_DIR/worktrees` folder (so that work on any OS, including Windows). Again, once you have cloned a repo (in a folder like `/path/to/myrepo`), you can add worktrees for different branches in *different* independent paths (`/path/to/br1`, `/path/to/br2`), while having those working trees linked to the main repo history (no need to use a `--git-dir` option anymore) See more at "**[Multiple working directories with Git?](https://stackoverflow.com/a/30185564/6309)**". And once you have created a [worktree, you can move or remove it](https://stackoverflow.com/a/49331132/6309) (with Git 2.17+, Q2 2018).
I suggest my small script <http://www.redhotchilipython.com/en_posts/2013-02-01-clone-per-feature.html> It will do git clone and replace the config (to "look" at original repo, so pull/push will go into "main" repo) basically, but it's simple enough to serve an abstraction from actual bootstrapping.
Question: I have a project with many branches. I would like to work on **several** branches simultaneously without switching back and forth with `git checkout`. Is there any way I can do that besides copying the whole repository somewhere else? Answer:
Git supports multiple worktree at the same time. For more information see: * [Multiple working directories with Git?](https://stackoverflow.com/questions/6270193/multiple-working-directories-with-git) * <https://git-scm.com/docs/git-worktree> How ever it is very hard to support multiple worktree with IDs. For example this is an [enhancement request](https://bugs.eclipse.org/bugs/show_bug.cgi?id=477475) in JGet (eclipse ID) to support worktree. So, you have to manage project manually (command line) with lots of problems or work with a single worktree in an IDE.
Not really as Git only supports to have *one* working copy of the repository data within the repository directory. If you want to commit/pull to the same repository with two different working copies, you could create a *bare* repository and clone it to two *working copies*. Whenever you have finished something, you simply push to the *"main"* bare repository. Some hints: `man git-clone` `git clone --bare`
Question: I have a project with many branches. I would like to work on **several** branches simultaneously without switching back and forth with `git checkout`. Is there any way I can do that besides copying the whole repository somewhere else? Answer:
Here's a scalable version of the [accepted answer](https://stackoverflow.com/a/30186843/9962007) (upvoted), with sequentially named branches (`app1..app10`). Note we should try to *avoid duplicate checkout* (here: by checking out the `master` branch, which will not be covered by `git worktree add`): ``` $ git checkout master && for NUM in {1..10}; do git worktree add ~/git/<repo-name>/app$NUM app$NUM; done ```
I suggest my small script <http://www.redhotchilipython.com/en_posts/2013-02-01-clone-per-feature.html> It will do git clone and replace the config (to "look" at original repo, so pull/push will go into "main" repo) basically, but it's simple enough to serve an abstraction from actual bootstrapping.
Question: I have a project with many branches. I would like to work on **several** branches simultaneously without switching back and forth with `git checkout`. Is there any way I can do that besides copying the whole repository somewhere else? Answer:
I suggest my small script <http://www.redhotchilipython.com/en_posts/2013-02-01-clone-per-feature.html> It will do git clone and replace the config (to "look" at original repo, so pull/push will go into "main" repo) basically, but it's simple enough to serve an abstraction from actual bootstrapping.
Not really as Git only supports to have *one* working copy of the repository data within the repository directory. If you want to commit/pull to the same repository with two different working copies, you could create a *bare* repository and clone it to two *working copies*. Whenever you have finished something, you simply push to the *"main"* bare repository. Some hints: `man git-clone` `git clone --bare`
Question: I have a project with many branches. I would like to work on **several** branches simultaneously without switching back and forth with `git checkout`. Is there any way I can do that besides copying the whole repository somewhere else? Answer:
Here's a scalable version of the [accepted answer](https://stackoverflow.com/a/30186843/9962007) (upvoted), with sequentially named branches (`app1..app10`). Note we should try to *avoid duplicate checkout* (here: by checking out the `master` branch, which will not be covered by `git worktree add`): ``` $ git checkout master && for NUM in {1..10}; do git worktree add ~/git/<repo-name>/app$NUM app$NUM; done ```
Not really as Git only supports to have *one* working copy of the repository data within the repository directory. If you want to commit/pull to the same repository with two different working copies, you could create a *bare* repository and clone it to two *working copies*. Whenever you have finished something, you simply push to the *"main"* bare repository. Some hints: `man git-clone` `git clone --bare`
Question: I have a project with many branches. I would like to work on **several** branches simultaneously without switching back and forth with `git checkout`. Is there any way I can do that besides copying the whole repository somewhere else? Answer:
Take a look at [$GIT\_SRC\_DIR/contrib/workdir/git-new-workdir](https://github.com/git/git/blob/master/contrib/workdir/git-new-workdir). According to the [commit logs](https://github.com/Khan/git-new-workdir/commit/88e4295fa435a339a39afecfed058e80a24ff35d) from a port of this repository: > > a simple script to create a working directory that uses symlinks to > point at an exisiting repository. This allows having different > branches in different working directories but all from the same > repository. > > >
Git supports multiple worktree at the same time. For more information see: * [Multiple working directories with Git?](https://stackoverflow.com/questions/6270193/multiple-working-directories-with-git) * <https://git-scm.com/docs/git-worktree> How ever it is very hard to support multiple worktree with IDs. For example this is an [enhancement request](https://bugs.eclipse.org/bugs/show_bug.cgi?id=477475) in JGet (eclipse ID) to support worktree. So, you have to manage project manually (command line) with lots of problems or work with a single worktree in an IDE.
Question: I have a project with many branches. I would like to work on **several** branches simultaneously without switching back and forth with `git checkout`. Is there any way I can do that besides copying the whole repository somewhere else? Answer:
Git 2.5+ (Q2 2015) supports this feature! If you have a git repo `cool-app`, cd to root (`cd cool-app`), run `git worktree add ../cool-app-feature-A feature/A`. This checks out the branch `feature/A` in it's own new dedicated directory, `cool-app-feature-A`. That replaces an older script `contrib/workdir/git-new-workdir`, with a more robust mechanism where those "linked" working trees are actually recorded in the main repo new `$GIT_DIR/worktrees` folder (so that work on any OS, including Windows). Again, once you have cloned a repo (in a folder like `/path/to/myrepo`), you can add worktrees for different branches in *different* independent paths (`/path/to/br1`, `/path/to/br2`), while having those working trees linked to the main repo history (no need to use a `--git-dir` option anymore) See more at "**[Multiple working directories with Git?](https://stackoverflow.com/a/30185564/6309)**". And once you have created a [worktree, you can move or remove it](https://stackoverflow.com/a/49331132/6309) (with Git 2.17+, Q2 2018).
Git supports multiple worktree at the same time. For more information see: * [Multiple working directories with Git?](https://stackoverflow.com/questions/6270193/multiple-working-directories-with-git) * <https://git-scm.com/docs/git-worktree> How ever it is very hard to support multiple worktree with IDs. For example this is an [enhancement request](https://bugs.eclipse.org/bugs/show_bug.cgi?id=477475) in JGet (eclipse ID) to support worktree. So, you have to manage project manually (command line) with lots of problems or work with a single worktree in an IDE.
Question: I've phone numbers like following formats, ``` 415-555-1234 (416)555-3456 202 555 4567 4035555678 1 416 555 9292 ``` I'm going to match all of them with this expression, ``` [\(|\d\s]?\d{3}[-|\)\s]?\d{3}[-|\s]?\d{4} ``` It matches all except the last one. The leading `"1 "` of last phone number can't be matched. I'm wondering why this expression doesn't work. Why can't `\d\s` match the leading `"1 "` of last phone number? Answer:
When you created your Rails application, it created a config/database.yml file. This file tells Rails where to store your data. By default, it stores the data in a sqlite database. This is a fine option for learning how to use Rails. Rails uses database migrations to create the structure of the database. The easiest way I can think of to get you started would be to use a scaffold. A scaffold creates a Rails model, a database migration, and all the views and controllers you'll need to get started. On the command line, run: ``` bin/rails generate scaffold Question question:string category:string ``` The will show a list of all the files it created, and the files are worth looking into. Now that the files are generated, run: ``` bin/rake db:migrate ``` This will migrate your database. The database migration will add a questions table to your database, with two string columns, question and category, and a a few Rails-specific columns. You can see the structure of the table it created in db/schema.rb. After you migrate your database, you'll be able to run the rails server with: ``` bin/rails server ``` Once the server is running, you can see your list of questions in a browser at localhost:3000/questions. Of course, you start with no questions, but the scaffold added code that will let you add, edit, and delete questions. There are a lot of good tutorials for the next steps, such as associating answers with questions.
You should check out the Ruby on Rails Guides. They are an excellent resource for learning how to create Rails applications <http://edgeguides.rubyonrails.org/>
Question: I've phone numbers like following formats, ``` 415-555-1234 (416)555-3456 202 555 4567 4035555678 1 416 555 9292 ``` I'm going to match all of them with this expression, ``` [\(|\d\s]?\d{3}[-|\)\s]?\d{3}[-|\s]?\d{4} ``` It matches all except the last one. The leading `"1 "` of last phone number can't be matched. I'm wondering why this expression doesn't work. Why can't `\d\s` match the leading `"1 "` of last phone number? Answer:
When you created your Rails application, it created a config/database.yml file. This file tells Rails where to store your data. By default, it stores the data in a sqlite database. This is a fine option for learning how to use Rails. Rails uses database migrations to create the structure of the database. The easiest way I can think of to get you started would be to use a scaffold. A scaffold creates a Rails model, a database migration, and all the views and controllers you'll need to get started. On the command line, run: ``` bin/rails generate scaffold Question question:string category:string ``` The will show a list of all the files it created, and the files are worth looking into. Now that the files are generated, run: ``` bin/rake db:migrate ``` This will migrate your database. The database migration will add a questions table to your database, with two string columns, question and category, and a a few Rails-specific columns. You can see the structure of the table it created in db/schema.rb. After you migrate your database, you'll be able to run the rails server with: ``` bin/rails server ``` Once the server is running, you can see your list of questions in a browser at localhost:3000/questions. Of course, you start with no questions, but the scaffold added code that will let you add, edit, and delete questions. There are a lot of good tutorials for the next steps, such as associating answers with questions.
I am quite new to rails too and found taking some time out to really get my head around the MVC framework and how it works really helped be to then take a step forward and apply things in the way i needed to. The rails guide listed above is great. It really helped me to break down the MVC into the three individual aspects and understand how they worked individually before putting them together. There are some really good projects with screencasts out there which helps put this into practice. I particularly like base rails and the odin project.
Question: If $a\_k$ is a sequence of complex numbers, is it true that $$\left|\sum\_{k}a\_k\right|\leq \sum\_k |a\_k|$$ Thank you Answer:
Yes; this is called the triangle inequality, which is true for complex numbers (and can be visualized in the same way). If your sums are infinite, then the inequality still holds since the partial sums on the left are less than or equal to those on the right, so the limits also satisfy this inequality. To prove the triangle inequality for $\Bbb{R}^n$, let $x,y\in \Bbb{R}^n$. Then $$||x+y||^2 = \langle x+y,x+y \rangle = \langle x,x\rangle+\langle y,y\rangle + 2\langle x,y \rangle \leq \langle x,x\rangle+\langle y,y\rangle + 2||x|| \cdot ||y|| = (||x||+||y||)^2$$ Where $||x||$ denote the norm ("absolute value") and $\langle x,y \rangle$ denotes the dot product of $x$ and $y$. The above inequality follows from the Cauchy-Schwarz-Bunyakovsky inequality, i.e that $\langle x,y \rangle \leq ||x||\cdot ||y||$.
First, read [Prove the triangle inequality involving complex numbers.](https://math.stackexchange.com/q/582433) Proof of the statement in question: Let $(a\_k)$ denote a sequence of complex numbers, and $s\_n=\sum\_{k=1}^n a\_k$ be the $n$th partial sum. One may observe, that for any $s\_n$ we have \begin{align\*} |s\_n| &= | a\_1+\cdots +a\_n|\\ & \leq |a\_1 + \cdots +a\_{n-1}| + |a\_n|\\ &\vdots\\ &\leq |a\_1|+\cdots+|a\_n| \end{align\*} As a result of this being true, we have that $$\left|\sum\_{k=1}^na\_k \right| \leq \sum\_{k=1}^n|a\_k|$$ for all finite $n.$ By computing the limit, $$\lim\_{n\to\infty}\left|\sum\_{k=1}^na\_k \right| \leq \lim\_{n\to\infty}\sum\_{k=1}^n|a\_k|$$ we get $$\left|\sum\_{k=1}^\infty a\_k \right| \leq \sum\_{k=1}^\infty|a\_k|.$$ And so the inequality holds for all finite sums, and infinite sums as well.
Question: I have an array of objects that looks like this: ```js const arr = [ {name: "Bill", email: "bill@email.com"}, {name: "Suzy", email: "suzy@email.com"}, {name: "Jill", email: "Jill@email.com"}, ] ``` I would like to return each value in an `<li>`. One list for names, one list for emails. Like this: ```js return ( <> <div className="names"> <ul> {arr.forEach((item) => { return <li>item.name</li>; })} </ul> </div> <div className="emails"> <ul> {arr.forEach((item) => { return <li>item.email</li>; })} </ul> </div> </> ); ``` so that it looks like this: ``` - Bill - Suzy - Jill - bill@email.com - suzy@email.com - jill@email.com ``` But, of course what I am doing does not look like this, which is why I am asking this question. What can I do with my array of objects to generate the desired list layout? Thanks. Answer:
The real problem with your code is this: ``` std::async(std::launch::async, [](int arg1, int arg2, Callback &&func) { func.OnResult({"API_Mul", arg1 + arg2}); }, arg1, arg2, std::forward<Callback>(func)); ``` The call to async that you are using has this signature: ``` template< class Function, class... Args> std::future<std::invoke_result_t<std::decay_t<Function>, std::decay_t<Args>...>> async( std::launch policy, Function&& f, Args&&... args); ``` The important thing to notice above is the returned future holds an invoke\_result\_t containing `std::decay_t<Args>...`, which removes references (and constness, decays arrays and functions to pointer, etc). But removing reference is the problem you're running into, as it would try to invoke your function with those args. Since you are passing a `Callback&` to the function, after decay it is `Callback`, and the instantiated template code attempts to hold just a Callback (base) by value. The real fix here, if you want to keep your original approach (for the most part) is to use a std::reference\_wrapper to hold your callback. This can be done with a call to std::ref() -- which returns a reference wrapper referencing its argument. Decaying a reference wrapper does not lose its "reference semantics": ``` std::async(std::launch::async, [](int arg1, int arg2, Callback &&func) { func.OnResult({"API_Mul", arg1 + arg2}); }, arg1, arg2, std::ref(func)); // <<<<< HERE ``` Of course, it's also your responsibility to ensure that the callback actually lives as long as the async code can run.
Use `override` for overriding functions. ``` // virtual void OnResult(ApiResultType res) { --> void OnResult(ApiResultType res) override { // ... ``` `std::forward<ApiCallBack>(Callable))` makes no sense, since Callable is not a rvalue or generic reference. Use `std::move(Callable))`. The above will not fix the error, but will make the code a bit better. The solution: ``` int main() { // Running API operations std::unique_ptr<Callback> Callable(new ApiCallBack); api_add(kOperationArg1, kOperationArg2, std::move(Callable)); ... } void api_add(int arg1, int arg2, std::unique_ptr<Callback> func) { std::async(std::launch::async, [](int arg1, int arg2, std::unique_ptr<Callback> func) { func->OnResult({"API_Mul", arg1 + arg2}); }, arg1, arg2, std::move(func)); } ``` The better approach is using `std::function<void(ApiResultType)>` instead of the Callback or unique pointer. ``` class ApiCallBack { public: void operator()(ApiResultType res) { std::cout << "OnResult: " << res.first << "; " << res.second << std::endl; ... } }; int main() { // Running API operations ApiCallback Callable; api_add(kOperationArg1, kOperationArg2, std::move(Callable)); ... } void api_add(int arg1, int arg2, std::function<void(ApiResultType)> func) { std::async(std::launch::async, [](int arg1, int arg2, std::function<void(ApiResultType)> func) { func({"API_Mul", arg1 + arg2}); }, arg1, arg2, std::move(func)); } ```
Question: I borrowed a piece of code for reversing a string in JavaScript. However it can't be done. ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>P4--Largest palindrome product</title> </head> <body> <!--A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. --> <script type="text/javascript"> var newdiv = document.createElement('div'); newdiv.innerHTML=Palindromic(); alert(Palindromic()); function Palindromic(){ var x; var a; var b; for(i=999*999;i>=100*100;i--) { x=i.toString(); if(x != x.reverse()) continue; else { for(j=100;j<999;j++) { if(i%j == 0) { var y =i/j; if(y>=100 && y<=999) { a=i;b=y; break; } } } } } return x; } String.prototype.reverse = function() { return this.split('').reverse().join(''); } </script> </body> </html> ``` The error is "has no method 'reverse'". Answer:
You need to define the `String.prototype.reverse` function before you use it. Put this code ``` String.prototype.reverse = function() { return this.split('').reverse().join(''); } ``` at the top instead of at the bottom.
**ES6:** try this function ``` function reverse(str) { // 1 // // 2 // // 3 // return [...str].reverse().reduce((rev,el) => rev + el,''); } ``` 1. spreads the string into an array of chars 2. reverses the array 3. reduce method on array to get the previous value and accumulate.
Question: I borrowed a piece of code for reversing a string in JavaScript. However it can't be done. ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>P4--Largest palindrome product</title> </head> <body> <!--A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. --> <script type="text/javascript"> var newdiv = document.createElement('div'); newdiv.innerHTML=Palindromic(); alert(Palindromic()); function Palindromic(){ var x; var a; var b; for(i=999*999;i>=100*100;i--) { x=i.toString(); if(x != x.reverse()) continue; else { for(j=100;j<999;j++) { if(i%j == 0) { var y =i/j; if(y>=100 && y<=999) { a=i;b=y; break; } } } } } return x; } String.prototype.reverse = function() { return this.split('').reverse().join(''); } </script> </body> </html> ``` The error is "has no method 'reverse'". Answer:
You need to define the `String.prototype.reverse` function before you use it. Put this code ``` String.prototype.reverse = function() { return this.split('').reverse().join(''); } ``` at the top instead of at the bottom.
Here is the easiest approach: ``` // reverse a string function reverseString(str) { return str.split('').reverse().join(''); } const reversedString = reverseString('hello world'); console.log(reversedString); // this would be logged as 'dlrow olleh' ```
Question: I borrowed a piece of code for reversing a string in JavaScript. However it can't be done. ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>P4--Largest palindrome product</title> </head> <body> <!--A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. --> <script type="text/javascript"> var newdiv = document.createElement('div'); newdiv.innerHTML=Palindromic(); alert(Palindromic()); function Palindromic(){ var x; var a; var b; for(i=999*999;i>=100*100;i--) { x=i.toString(); if(x != x.reverse()) continue; else { for(j=100;j<999;j++) { if(i%j == 0) { var y =i/j; if(y>=100 && y<=999) { a=i;b=y; break; } } } } } return x; } String.prototype.reverse = function() { return this.split('').reverse().join(''); } </script> </body> </html> ``` The error is "has no method 'reverse'". Answer:
**ES6:** try this function ``` function reverse(str) { // 1 // // 2 // // 3 // return [...str].reverse().reduce((rev,el) => rev + el,''); } ``` 1. spreads the string into an array of chars 2. reverses the array 3. reduce method on array to get the previous value and accumulate.
Here is the easiest approach: ``` // reverse a string function reverseString(str) { return str.split('').reverse().join(''); } const reversedString = reverseString('hello world'); console.log(reversedString); // this would be logged as 'dlrow olleh' ```
Question: Given: ``` scala> val ss = "hello_world".split("_") ss: Array[String] = Array(hello, world) ``` How to turn `ss` into a tuple `(hello, world)` with a function of `Array` (on `ss`)? I'm thinking about a function so the above snippet would end up as `"hello_world".split("_").to[Tuple2]` or alike. Is it possible using Scala 2.11.6 API only? Answer:
As mentioned in the [NGiNX documentation](http://nginx.org/en/docs/http/ngx_http_upstream_module.html#upstream), `upstream` is supposed to be defined in an `http` context. As mentioned in [`nginx` unkown directive “`upstream`”](https://stackoverflow.com/a/7844400/6309): > > When that file is included normally by `nginx.conf`, it is included already inside the `http` context: > > > ``` http { include /etc/nginx/sites-enabled/*; } ``` > > You either need to use `-c /etc/nginx/nginx.conf` or make a small wrapper like the above block and `nginx -c` it. > > > In case of Docker, you can see different options with [`abevoelker/docker-nginx`](https://github.com/abevoelker/docker-nginx#nginxconf): ``` docker run -v /tmp/foo:/foo abevoelker/nginx nginx -c /foo/nginx.conf ``` For a default `nginx.conf`, [check your `CMD`](https://github.com/abevoelker/docker-nginx/blob/master/mainline/Dockerfile#L37): ``` CMD ["nginx", "-c", "/data/conf/nginx.conf"] ```
An example for adding gzip config: ``` docker run -v [./]gzip.conf:/etc/nginx/conf.d/gzip.conf nginx ``` or docker-compose: ``` version: '3' services: nginx: image: nginx volumes: - ./gzip.conf:/etc/nginx/conf.d/gzip.conf - ./html:/usr/share/nginx/html:ro ```
Question: Given: ``` scala> val ss = "hello_world".split("_") ss: Array[String] = Array(hello, world) ``` How to turn `ss` into a tuple `(hello, world)` with a function of `Array` (on `ss`)? I'm thinking about a function so the above snippet would end up as `"hello_world".split("_").to[Tuple2]` or alike. Is it possible using Scala 2.11.6 API only? Answer:
As mentioned in the [NGiNX documentation](http://nginx.org/en/docs/http/ngx_http_upstream_module.html#upstream), `upstream` is supposed to be defined in an `http` context. As mentioned in [`nginx` unkown directive “`upstream`”](https://stackoverflow.com/a/7844400/6309): > > When that file is included normally by `nginx.conf`, it is included already inside the `http` context: > > > ``` http { include /etc/nginx/sites-enabled/*; } ``` > > You either need to use `-c /etc/nginx/nginx.conf` or make a small wrapper like the above block and `nginx -c` it. > > > In case of Docker, you can see different options with [`abevoelker/docker-nginx`](https://github.com/abevoelker/docker-nginx#nginxconf): ``` docker run -v /tmp/foo:/foo abevoelker/nginx nginx -c /foo/nginx.conf ``` For a default `nginx.conf`, [check your `CMD`](https://github.com/abevoelker/docker-nginx/blob/master/mainline/Dockerfile#L37): ``` CMD ["nginx", "-c", "/data/conf/nginx.conf"] ```
official nginx docker hub manual page: ```sh docker run --name my-custom-nginx-container -v /host/path/nginx.conf:/etc/nginx/nginx.conf:ro -d nginx ```
Question: Given: ``` scala> val ss = "hello_world".split("_") ss: Array[String] = Array(hello, world) ``` How to turn `ss` into a tuple `(hello, world)` with a function of `Array` (on `ss`)? I'm thinking about a function so the above snippet would end up as `"hello_world".split("_").to[Tuple2]` or alike. Is it possible using Scala 2.11.6 API only? Answer:
official nginx docker hub manual page: ```sh docker run --name my-custom-nginx-container -v /host/path/nginx.conf:/etc/nginx/nginx.conf:ro -d nginx ```
An example for adding gzip config: ``` docker run -v [./]gzip.conf:/etc/nginx/conf.d/gzip.conf nginx ``` or docker-compose: ``` version: '3' services: nginx: image: nginx volumes: - ./gzip.conf:/etc/nginx/conf.d/gzip.conf - ./html:/usr/share/nginx/html:ro ```
Question: I am looking to convert a `MySQL timestamp` to a epoch time in seconds using `PHP`, and vice versa. What's the cleanest way to do this? Answer:
There are two functions in MySQL which are useful for converting back and forth from the unix epoch time that PHP likes: [from\_unixtime()](http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_from-unixtime) [unix\_timestamp()](http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_unix-timestamp) For example, to get it back in PHP unix time, you could do: ``` SELECT unix_timestamp(timestamp_col) FROM tbl WHERE ... ```
From MySQL timestamp to epoch seconds: ``` strtotime($mysql_timestamp); ``` From epoch seconds to MySQL timestamp: ``` $mysql_timestamp = date('Y-m-d H:i:s', time()); ```
Question: I am looking to convert a `MySQL timestamp` to a epoch time in seconds using `PHP`, and vice versa. What's the cleanest way to do this? Answer:
See [strtotime](http://www.php.net/strtotime) and [date](http://www.php.net/date) functions in PHP manual. ``` $unixTimestamp = strtotime($mysqlDate); $mysqlDate = date('Y-m-d h:i:s', $unixTimestamp); ```
From MySQL timestamp to epoch seconds: ``` strtotime($mysql_timestamp); ``` From epoch seconds to MySQL timestamp: ``` $mysql_timestamp = date('Y-m-d H:i:s', time()); ```
Question: I was wondering why R sees `(1:10)` as an vector counting from 1 to 10 And `(0.1:1.0)` as 0.1? Should i define the steps from 0.05 by myself? or is there a trick to do this? Answer:
The colon makes a sequence from the first number to last with steps of exactly `1`. Since in `0.1:1` that is less than one step it only returns the first number. I think you are looking for `seq(0.1,1,length=10)`?
Try `0.1 * (1:10)`. It's (imho) clearer to read and easier to remember than the seq syntax, and while it may involve more processing is fine for everyday.
Question: I'm about to start a new project and i'm having a hard time choosing between Zen Grids & Susy. Could you guys tell me what the pros/cons of each framework are? **For reference** * <http://zengrids.com/> * <http://susy.oddbird.net/> Thanks in advance! Answer:
The following articles may help you: * [Adding Header Information to an existing HTTP Request](http://bijubnair.blogspot.com/2008/12/adding-header-information-to-existing.html) * [How to modify request headers in a J2EE web application.](http://vangjee.wordpress.com/2009/02/25/how-to-modify-request-headers-in-a-j2ee-web-application/) --- P.S. I am sorry I provided only links, that was one of my early answer on SO ))
Instead of writing a mock application, I used a browser add-on that allowed me to add custom headers!
Question: I'm about to start a new project and i'm having a hard time choosing between Zen Grids & Susy. Could you guys tell me what the pros/cons of each framework are? **For reference** * <http://zengrids.com/> * <http://susy.oddbird.net/> Thanks in advance! Answer:
In case you don't want to modify your code as suggested by @user1979427 you can use a proxy server to modify headers or add headers on the fly. For example in Apache HTTPD you would add something like below and proxy the ``` Header add HEADER "HEADERVALUE" RequestHeader set HEADER "HEADERVALUE" ``` Refer to [HTTPD doc](http://httpd.apache.org/docs/current/mod/mod_headers.html)
You should create a AddReqHeaderForFrowardWrapper request wrapper passing the headername and header values. And, override the request header related methods to return your custom header.
Question: I'm about to start a new project and i'm having a hard time choosing between Zen Grids & Susy. Could you guys tell me what the pros/cons of each framework are? **For reference** * <http://zengrids.com/> * <http://susy.oddbird.net/> Thanks in advance! Answer:
The following articles may help you: * [Adding Header Information to an existing HTTP Request](http://bijubnair.blogspot.com/2008/12/adding-header-information-to-existing.html) * [How to modify request headers in a J2EE web application.](http://vangjee.wordpress.com/2009/02/25/how-to-modify-request-headers-in-a-j2ee-web-application/) --- P.S. I am sorry I provided only links, that was one of my early answer on SO ))
For setting header in java, you can use: ``` request.setHeader(attributeName, attributeValue); ``` And for redirecting to another page, you can use: ``` request.sendRedirect(URL); ```
Question: I'm about to start a new project and i'm having a hard time choosing between Zen Grids & Susy. Could you guys tell me what the pros/cons of each framework are? **For reference** * <http://zengrids.com/> * <http://susy.oddbird.net/> Thanks in advance! Answer:
You can use Tracer to implement this. There are frameworks available to support this implementation. Spring has Sleuth, Zipkin, OpenTracing available. I find OpenTracing to be easy to use without worrying about dependency conflicts. Read more about it here: <https://opentracing.io/guides/java/>
For setting header in java, you can use: ``` request.setHeader(attributeName, attributeValue); ``` And for redirecting to another page, you can use: ``` request.sendRedirect(URL); ```
Question: I'm about to start a new project and i'm having a hard time choosing between Zen Grids & Susy. Could you guys tell me what the pros/cons of each framework are? **For reference** * <http://zengrids.com/> * <http://susy.oddbird.net/> Thanks in advance! Answer:
You should create a AddReqHeaderForFrowardWrapper request wrapper passing the headername and header values. And, override the request header related methods to return your custom header.
Instead of writing a mock application, I used a browser add-on that allowed me to add custom headers!
Question: I'm about to start a new project and i'm having a hard time choosing between Zen Grids & Susy. Could you guys tell me what the pros/cons of each framework are? **For reference** * <http://zengrids.com/> * <http://susy.oddbird.net/> Thanks in advance! Answer:
You should create a AddReqHeaderForFrowardWrapper request wrapper passing the headername and header values. And, override the request header related methods to return your custom header.
For setting header in java, you can use: ``` request.setHeader(attributeName, attributeValue); ``` And for redirecting to another page, you can use: ``` request.sendRedirect(URL); ```
Question: I'm about to start a new project and i'm having a hard time choosing between Zen Grids & Susy. Could you guys tell me what the pros/cons of each framework are? **For reference** * <http://zengrids.com/> * <http://susy.oddbird.net/> Thanks in advance! Answer:
In case you don't want to modify your code as suggested by @user1979427 you can use a proxy server to modify headers or add headers on the fly. For example in Apache HTTPD you would add something like below and proxy the ``` Header add HEADER "HEADERVALUE" RequestHeader set HEADER "HEADERVALUE" ``` Refer to [HTTPD doc](http://httpd.apache.org/docs/current/mod/mod_headers.html)
You can use Tracer to implement this. There are frameworks available to support this implementation. Spring has Sleuth, Zipkin, OpenTracing available. I find OpenTracing to be easy to use without worrying about dependency conflicts. Read more about it here: <https://opentracing.io/guides/java/>
Question: I'm about to start a new project and i'm having a hard time choosing between Zen Grids & Susy. Could you guys tell me what the pros/cons of each framework are? **For reference** * <http://zengrids.com/> * <http://susy.oddbird.net/> Thanks in advance! Answer:
In case you don't want to modify your code as suggested by @user1979427 you can use a proxy server to modify headers or add headers on the fly. For example in Apache HTTPD you would add something like below and proxy the ``` Header add HEADER "HEADERVALUE" RequestHeader set HEADER "HEADERVALUE" ``` Refer to [HTTPD doc](http://httpd.apache.org/docs/current/mod/mod_headers.html)
For setting header in java, you can use: ``` request.setHeader(attributeName, attributeValue); ``` And for redirecting to another page, you can use: ``` request.sendRedirect(URL); ```
Question: I'm about to start a new project and i'm having a hard time choosing between Zen Grids & Susy. Could you guys tell me what the pros/cons of each framework are? **For reference** * <http://zengrids.com/> * <http://susy.oddbird.net/> Thanks in advance! Answer:
The following articles may help you: * [Adding Header Information to an existing HTTP Request](http://bijubnair.blogspot.com/2008/12/adding-header-information-to-existing.html) * [How to modify request headers in a J2EE web application.](http://vangjee.wordpress.com/2009/02/25/how-to-modify-request-headers-in-a-j2ee-web-application/) --- P.S. I am sorry I provided only links, that was one of my early answer on SO ))
You should create a AddReqHeaderForFrowardWrapper request wrapper passing the headername and header values. And, override the request header related methods to return your custom header.
Question: I'm about to start a new project and i'm having a hard time choosing between Zen Grids & Susy. Could you guys tell me what the pros/cons of each framework are? **For reference** * <http://zengrids.com/> * <http://susy.oddbird.net/> Thanks in advance! Answer:
The following articles may help you: * [Adding Header Information to an existing HTTP Request](http://bijubnair.blogspot.com/2008/12/adding-header-information-to-existing.html) * [How to modify request headers in a J2EE web application.](http://vangjee.wordpress.com/2009/02/25/how-to-modify-request-headers-in-a-j2ee-web-application/) --- P.S. I am sorry I provided only links, that was one of my early answer on SO ))
In case you don't want to modify your code as suggested by @user1979427 you can use a proxy server to modify headers or add headers on the fly. For example in Apache HTTPD you would add something like below and proxy the ``` Header add HEADER "HEADERVALUE" RequestHeader set HEADER "HEADERVALUE" ``` Refer to [HTTPD doc](http://httpd.apache.org/docs/current/mod/mod_headers.html)
Question: I have created a feature where users can start new topics (similar to forums). At the moment on a page, the query for the topics are as follows: ``` $q = "SELECT ".TBL_COMMUNITYTHREADS.".title, ".TBL_COMMUNITYTHREADS.".id, ".TBL_COMMUNITYTHREADS.".date, ".TBL_COMMUNITYTHREADS.".author, ".TBL_USERS.".username FROM ".TBL_COMMUNITYTHREADS." INNER JOIN ".TBL_USERS." ON ".TBL_COMMUNITYTHREADS.".author = ".TBL_USERS.".id WHERE type = '$type' ORDER BY date DESC LIMIT $offset, $rowsperpage "; ``` The tables are constants and the offset and rowsperpage are variables passed in to limit how many posts are on a page. At the moment though, all the topics are ordered by the date. I want them to be ordered by the latest response. Similarly to forums, when the reponse inside the topic is newest, that topic will go to the top. The topics are stored in tbl\_communitythreads and the replies in tbl\_communityreplies. How can I ordered them by the latest repsonse. They are linked by the threadid in tbl\_communityreplies. Also in that one is the date column. Thankyou for reading, I just cant think of how to do this. Answer:
This: ``` SELECT c.title, c.id, c.date, c.author, u.username, ( SELECT MAX(reply_date) FROM tbl_communityreplies cr WHERE cr.thread = c.id ) AS last_reply FROM TBL_COMMUNITYTHREADS c JOIN TBL_USERS u ON u.id = c.author ORDER BY last_reply DESC, c.id DESC LIMIT $offset, $rowsperpage ``` or this: ``` SELECT c.title, c.id, c.date, c.author, u.username FROM ( SELECT cr.thread, cr.reply_date, cr.id FROM tbl_communityreplies cr WHERE (cr.last_reply, cr.id) = ( SELECT last_reply, id FROM tbl_communityreplies cri WHERE cri.thread = cr.thread ORDER BY thread DESC, last_reply DESC, id DESC ) ORDER BY last_reply DESC, id DESC LIMIT $offset, $rowsperpage ) q JOIN TBL_COMMUNITYTHREADS c ON c.id = q.thread JOIN TBL_USERS u ON u.id = c.author ORDER BY q.reply_date DESC, q.id DESC ``` The former query is more efficient for large values of `$offset`, or if you have few threads with lots of replies. Issue the following commands: ``` CREATE INDEX ix_communitythreads_replydate_id ON TBL_COMMUNITYTHREADS (reply_date, id) CREATE INDEX ix_communitythreads_thread_replydate_id ON TBL_COMMUNITYTHREADS (thread, reply_date, id) ``` for this to work fast.
by **join** with another table , then you can order by column from this table.
Question: Surrounding the Impeachment trial of President Trump many news outlets have voiced that an acquittal will be setting precedent. Does this mean that subsequent presidents will be able to do the same things and cite precedent without fear of retribution? Is there any legal standing to setting precedent? Could `President A` set precedent with something and then `President B` could do the same thing and be impeached for doing that same exact thing? I'm a bit confused how setting precedent holds any legal value. Answer:
It should be noted, first of all, that impeachment is a political process and not a legal one. This means that the precedent argument is not as strong as it would be in, for example, a Supreme Court case. In a legal case, a large part of a court's job is to interpret the meaning of a law. When a court makes a determination of the meaning of a law, then other courts are expected to apply the same meaning of a law to maintain consistency across the legal system. After all, if different courts apply the same law in different ways, it would become very confusing as to what a law actually means. This is unless or until a higher court rejects this interpretation on appeal, or legislation is passed to invalidate such an interpretation. Meanwhile, one Congress cannot bind any of its successor Congresses. They are under no obligation to look at precedent as they decide whether or not to impeach/convict.
Of course, it's not a matter of black letter law. But assuming a partisan situation, Democrats are unlikely to try and impeach another president for similar behavior, because they know the Republicans won't assist. (And if the Republicans do assist, it will make this impeachment look worse for them.) Any Republican trying to impeach a president for similar behavior will know the Democrats can simply quote their own words back at them, and will know that the Republicans are being grossly hypocritical. If the Republicans did have the power to force it through, it's going to get ugly, since that's clearly stating that impeachment is not about "high crimes", it's about who has the power. (There is a note that Senate Majority Leader Mitch McConnell did have his words quoted back at him; it's also worth noting that he's polling quite a bit worse than the partisan lean of his state, Kentucky, especially surprising for a long-term Congressional member with power in Congress.) Congress could pass laws against similar "quid pro quo", and then try and enforce those laws through impeachment, like was done against Johnson. But until if and when they do so, it's hard to imagine that something like this could be used for impeachment.
Question: Surrounding the Impeachment trial of President Trump many news outlets have voiced that an acquittal will be setting precedent. Does this mean that subsequent presidents will be able to do the same things and cite precedent without fear of retribution? Is there any legal standing to setting precedent? Could `President A` set precedent with something and then `President B` could do the same thing and be impeached for doing that same exact thing? I'm a bit confused how setting precedent holds any legal value. Answer:
It should be noted, first of all, that impeachment is a political process and not a legal one. This means that the precedent argument is not as strong as it would be in, for example, a Supreme Court case. In a legal case, a large part of a court's job is to interpret the meaning of a law. When a court makes a determination of the meaning of a law, then other courts are expected to apply the same meaning of a law to maintain consistency across the legal system. After all, if different courts apply the same law in different ways, it would become very confusing as to what a law actually means. This is unless or until a higher court rejects this interpretation on appeal, or legislation is passed to invalidate such an interpretation. Meanwhile, one Congress cannot bind any of its successor Congresses. They are under no obligation to look at precedent as they decide whether or not to impeach/convict.
Yes, they could be impeached, but it might be more difficult. The grounds for impeachment and removal in the Constitution are very vague, and it's up to Congress to interpret them and decide whether they apply to the current President's actions. In doing so, they often look at history for guidance. They review documents written by the framers of the Constition to understand their intent. And they look for similarities in past impeachment proceedings. For example, a significant portion of the arguments made on both sides in the Trump impeachment cited analogies with previous impeachments (not just of Presidents, since there have been so few, but also the many judicial impeachments). So while they're not legally bound by precedents, they can provide compelling arguments.
Question: Surrounding the Impeachment trial of President Trump many news outlets have voiced that an acquittal will be setting precedent. Does this mean that subsequent presidents will be able to do the same things and cite precedent without fear of retribution? Is there any legal standing to setting precedent? Could `President A` set precedent with something and then `President B` could do the same thing and be impeached for doing that same exact thing? I'm a bit confused how setting precedent holds any legal value. Answer:
> > Could President A set precedent with something and then President B could do the same thing and be impeached for doing that same exact thing? > > > Yes, absolutely. It is usually understood that Congress can impeach and remove a president for anything it deems official misconduct (so-called "high crimes and misdemeanors"). What Congress deems official misconduct can change from election to election (or minute to minute).
Of course, it's not a matter of black letter law. But assuming a partisan situation, Democrats are unlikely to try and impeach another president for similar behavior, because they know the Republicans won't assist. (And if the Republicans do assist, it will make this impeachment look worse for them.) Any Republican trying to impeach a president for similar behavior will know the Democrats can simply quote their own words back at them, and will know that the Republicans are being grossly hypocritical. If the Republicans did have the power to force it through, it's going to get ugly, since that's clearly stating that impeachment is not about "high crimes", it's about who has the power. (There is a note that Senate Majority Leader Mitch McConnell did have his words quoted back at him; it's also worth noting that he's polling quite a bit worse than the partisan lean of his state, Kentucky, especially surprising for a long-term Congressional member with power in Congress.) Congress could pass laws against similar "quid pro quo", and then try and enforce those laws through impeachment, like was done against Johnson. But until if and when they do so, it's hard to imagine that something like this could be used for impeachment.
Question: Surrounding the Impeachment trial of President Trump many news outlets have voiced that an acquittal will be setting precedent. Does this mean that subsequent presidents will be able to do the same things and cite precedent without fear of retribution? Is there any legal standing to setting precedent? Could `President A` set precedent with something and then `President B` could do the same thing and be impeached for doing that same exact thing? I'm a bit confused how setting precedent holds any legal value. Answer:
> > Could President A set precedent with something and then President B could do the same thing and be impeached for doing that same exact thing? > > > Yes, absolutely. It is usually understood that Congress can impeach and remove a president for anything it deems official misconduct (so-called "high crimes and misdemeanors"). What Congress deems official misconduct can change from election to election (or minute to minute).
Yes, they could be impeached, but it might be more difficult. The grounds for impeachment and removal in the Constitution are very vague, and it's up to Congress to interpret them and decide whether they apply to the current President's actions. In doing so, they often look at history for guidance. They review documents written by the framers of the Constition to understand their intent. And they look for similarities in past impeachment proceedings. For example, a significant portion of the arguments made on both sides in the Trump impeachment cited analogies with previous impeachments (not just of Presidents, since there have been so few, but also the many judicial impeachments). So while they're not legally bound by precedents, they can provide compelling arguments.
Question: Surrounding the Impeachment trial of President Trump many news outlets have voiced that an acquittal will be setting precedent. Does this mean that subsequent presidents will be able to do the same things and cite precedent without fear of retribution? Is there any legal standing to setting precedent? Could `President A` set precedent with something and then `President B` could do the same thing and be impeached for doing that same exact thing? I'm a bit confused how setting precedent holds any legal value. Answer:
Of course, it's not a matter of black letter law. But assuming a partisan situation, Democrats are unlikely to try and impeach another president for similar behavior, because they know the Republicans won't assist. (And if the Republicans do assist, it will make this impeachment look worse for them.) Any Republican trying to impeach a president for similar behavior will know the Democrats can simply quote their own words back at them, and will know that the Republicans are being grossly hypocritical. If the Republicans did have the power to force it through, it's going to get ugly, since that's clearly stating that impeachment is not about "high crimes", it's about who has the power. (There is a note that Senate Majority Leader Mitch McConnell did have his words quoted back at him; it's also worth noting that he's polling quite a bit worse than the partisan lean of his state, Kentucky, especially surprising for a long-term Congressional member with power in Congress.) Congress could pass laws against similar "quid pro quo", and then try and enforce those laws through impeachment, like was done against Johnson. But until if and when they do so, it's hard to imagine that something like this could be used for impeachment.
Yes, they could be impeached, but it might be more difficult. The grounds for impeachment and removal in the Constitution are very vague, and it's up to Congress to interpret them and decide whether they apply to the current President's actions. In doing so, they often look at history for guidance. They review documents written by the framers of the Constition to understand their intent. And they look for similarities in past impeachment proceedings. For example, a significant portion of the arguments made on both sides in the Trump impeachment cited analogies with previous impeachments (not just of Presidents, since there have been so few, but also the many judicial impeachments). So while they're not legally bound by precedents, they can provide compelling arguments.
Question: I have been working on RAD Studio and on that this is performed automatically if the background is fully transparent, but it seems that it isn't as simple to do in Visual Studio. I have read articles and questions of functions GetWindowLong() and SetWindowLong(), but when I try to use them myself, I get error "the name xxx does not exist in the current context". What I tried was: ``` namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); int initialStyle = GetWindowLong(this.Handle, -20); SetWindowLong(this.Handle, -20, initialStyle | 0x80000 | 0x20); } } } ``` So is there some file I have to include in order get it to work, or do I have to place the function elsewhere? I'm also curious to know why does it behave so differently in the RAD Studio and Visula Studio. Answer:
Assuming Form name as form1 Set these properties to following. ``` form1.BackColor = Control; form1.TransparencyKey = Control; ``` now you can easily click through the transparent area of the form. hope this is what you were looking for.
Shujaat Siddiqui's answer works just fine for clicking through the transparency. It will not hide the form's title though nor its borders. To do this you may either set the `Opacity=0d` **or** chose a `FormBorderStyle=none` along with a `Text=""` and `ControlBox=false;` You may also think about cutting holes into the window's region to get precise control where click will go through and where not. In all these cases you will also have to plan for control of the form's position and size.. But, as long as you don't go for semi-tranparency of the background all can be done..
Question: Linux has the ability to display protocol statistics with netstat -s. The output looks something like: Excerpt: ``` 7487 times unabled to send RST due to no memory TCPDSACKIgnoredOld: 817 TCPDSACKIgnoredNoUndo: 7246527 TCPSpuriousRTOs: 4583587 TCPSackShifted: 15825 TCPSackMerged: 455582 ``` But these are accumulated over all networking interfaces. Is there a way to see these statistics per interface? I know that there are packet level statistics in `/sys/class/net/$INTERFACE/statistics`, but have not been able to find any protocol related ones. Answer:
Netstat -s is a more intuitive display of `/proc/net/netstat`. Counters in it are global and not per interface. To get that kind of information you will need to use/write a monitoring tool using libpcap.
The code which captures these statistics is called in the various related TCP/UDP/IP codepaths and increments SNMP MIBs. There is no information stored about interface or any connection properties like port or IP, it's only a basic counter of the times that codepath has been entered. `netstat -s` just reads those counters.
Question: I want to make a drop down using the data given in the BootStrap.groovy. My City domain class ``` package city.model class City { String cityName static constraints = { cityName(maxSize: 50) } } ``` In my Service class ``` public class CityService { def citySelect(String cityName) //this is just a sample { City city = new City() city.cityName = city.findByCityName(cityName) } } ``` controller ``` public class CityController { def cityService def def selCity() { def selectCity = cityService.citySelect(params.cityName){ if(selectCity != null){ render view // my view } else{ render view // error select again view } } } ``` BootStrap.groovy ``` import city.City; class BootStrap { def init = { servletContext -> for(String cityName in ['Addis Ababa', 'Semera','Asosa','Gondar', 'Jijiga','Harar', 'Dire Dawa', 'Bahir Dar', 'Hawassa', 'Arba Minch', 'Adama', 'Mekelle']) { City.findOrSaveByCityName(cityName).save() } } def destroy = { } } ``` i used this ``` <g:select name="cities" from="${City.list()}" optionKey="id" optionValue="cityName"/> in my view but showing error cannot envoke method list on null object ``` What is wrong within mu code and what should i do to make it work. please any suggestions Answer:
Maybe you have misunderstood the point of Bootstrap. Bootstrap as per the naming convention is the part that is triggered when your site is booting up. You would typically use it to ensure required db table records are generated before it has booted up i.e. admin account or in your case generation of some cities. You would not be using Bootstrap to interact with the records you generated in the way of editing or selecting. Once this has all be done and saved - you would have also used the Controllers/Views to list/view/update/add cities. You would create your g:select tags in these views and matching controllers that would query the records you have saved via bootstrap **E2A:** Ok Just read your comment Either use an import on the top of your gsp ``` <%@ page import="city.City" %> ``` or call full packaged path to City domainClass **city.City.list** ``` <g:select name="cities" from="${city.City.list()}" optionKey="id" optionValue="cityName"/> ```
This should work: ``` <g:select name="cities" from="${city.model.City.list()}" optionKey="id" optionValue="cityName"/> ``` However, executing queries like `city.model.City.list()` in a GSP is not a recommended practice. Instead you should retrieve your data (the list of cities) in a controller action or a service and pass that via the model to the GSP.