qid
int64 1
74.6M
| question
stringlengths 45
24.2k
| date
stringlengths 10
10
| metadata
stringlengths 101
178
| response_j
stringlengths 32
23.2k
| response_k
stringlengths 21
13.2k
|
---|---|---|---|---|---|
51,317 | [Danny Schoemmann](https://judaism.stackexchange.com/users/501/danny-schoemann) mentions a ceremony called a chol-kreisch in [this answer](https://judaism.stackexchange.com/a/7500/4504) for giving the secular name of a child. Is this custom still observed, and if so, how is it practiced? | 2015/01/04 | ['https://judaism.stackexchange.com/questions/51317', 'https://judaism.stackexchange.com', 'https://judaism.stackexchange.com/users/4504/'] | A description of the ceremony is given in [מדריך
למנהג אשכנז המובהק](http://www.moreshesashkenaz.org/mm/publications/Madrich.pdf).
My translation:
>
> On that Shabbos when the mother of the new born goes to synagogue, a
> "Chol Kreisch"is made for the child. On the day of the miloh the
> child acquired his Jewish name by which he will be called to the Torah
> and on this Shabbos he is given his secular name. For example Yitzchok
> (will be called) Itzik; Eliezer, Leizer; Alexander, Sender; Mordechai,
> Mottel; Yechezkel, Chizki. There are those who do not give a secular
> name but repeat the Jewish name to make known that this is the name by
> which the child will be known in his secular life.
>
>
> This is the order of the chol kreisch. After the Shabbos meal,
> children under barmitzvah come to the house of the new born. The baby
> is clothed in the same clothes that he wore to his circumcision and
> the cot is decorated and the child is covered with a tallis with
> tzitzis and a Chumash Vayikro is placed near him. The children sit
> round the table or stand round the cot and say the pesukim for chol
> kreisch as printed in the Avodas Yisroel and Sefas Emes siddurim.
> After saying the pessukim the children lift the cot and say aloud
> “Chol Kreisch, Chol Kreisch. What will the child be called Ploni,
> Ploni, Ploni” and they repeat this three times. Before the children
> leave they are given a bag of fruit, nuts and nosh. Girls also have a
> chol kreisch but they do not say the pessukim nor put the chumash in
> the cot.
>
>
>
[Kahal Adas Yeshurun, Jerusalem reports (5 Oct '10)](http://www.kayj.net/en/news/43-newsletter-25)
>
> Our Rov, Harav Yehudoh Gans Shlito, made a Chol Kreisch for his
> newborn son (Yosef) on שמחת תורה saying all the Pesukim as they appear
> in the Rodelheim Siddur, and he stated at this event, that it is a
> very old Minhog, which is brought already in the Seifer Chassidim.
>
>
>
The Nussach in question is the following:
 | My family origins are in Alsace and various places in Germany, which are places where the minhag was practiced historically. I have a 10 month old son, and I made a chol kreisch for him. I did it as it says in the Rodelheim siddur.
I'm not sure why it seems odd to give the child a "street name". The names that were given in much older times were so common and so accepted that they are now part of what everyone considers "Jewish" names. The names that we today think of as "double-barreled names" are combinations of the shem kodesh and the "street name". In "old time" Germany and France, a child named Shlomo was given the name Zalman at his chol kreisch. He was called Zalman (the exact same as the German secular name Salman or Salomon) on the street and at home, and was called to the Torah as Shlomo. The same is true of Zev, who would be called Volf by most people (with the nickname Velvel at home perhaps); Dov, who would be called Behr; Eliezer, who would be called Lipman; Elyakim, who would be called Goetzel; Meshulam, who would be called Zalman; Shraga or Uri, who would be called Feist or Feit or Feis; Yehoshua, who would be called Falk; Aryeh or Yehudah would be called Loeb/Leib; and on and on. Some of these names have fallen out of usage (such as Falk and Feist), and are today found only among Jews with closer ancestry from Germany. Others, like Zalman and Behr, are very commonly used.
These "street names" seem to have entered the "full" shem kodesh whenever Jews gave the names in lands where the "street name" no longer made sense, since German wasn't spoken in those places, such as Russia or Poland. Even still, while some people may be called to the Torah as Yehudah Leib, for instance, others will be called it only as a nickname. I have two friends named Leibish, one is called "Aryeh Leibish" fully, and the other is named Aryeh Yehudah, and goes by Leibish. While many might call it a "Jewish name", the fact is that Leibish originated as the German version of Hebrew names connected to "lion".
The Chasam Sofer has a tshuvah that says you should not call the person to the Torah by both their shem kodesh and "street name", like Shlomo Zalman, but only by their shem kodesh. The problem with that today is, since certain areas of Europe were no longer aware that both names weren't the shem kodesh, the "street name" entered the shem kodesh, and for many people is inseparable.
When I did my son's chol kreisch, I didn't say the name as it appears on his birth certificate, but the name that we call him, which is the "nickname" for his name. This is a bit funny, as he is named after my wife's side, and has a double barreled name that includes the old German-Yiddish "street name" in his shem kodesh. |
15,719,092 | I am having a problem in getting the string name of the currently selected database.
this is what i did.. i am trying to echo the name of the database but it produces an error "Warning: mysql\_fetch\_array() expects parameter 1 to be resource"
```
<?php
$dbcon = mysql_connect("localhost", "root", "")
or die(mysql_error()."Not Connected");
$sql = mysql_query("select database()");
$row = mysql_fetch_array($sql);
echo "db ".$row[0];
```
?>
i need to get the selected database name because i will use it for
```
mysql_select_db()
``` | 2013/03/30 | ['https://Stackoverflow.com/questions/15719092', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1647596/'] | You yourself need to select a database after connecting to MySQL, it's not selected by default, like this:
```
$dbcon = mysql_connect("localhost", "root", "")
or die(mysql_error()."Not Connected");
mysql_select_db("databasename"); # add this line
$sql = mysql_query("select database()");
$row = mysql_fetch_array($sql);
echo "db ".$row[0];
```
Please don't use mysql\_\* function as they're deprecated, instead use mysqli\_\*. | first, I would suggest you use mysqli functions instead of mysql as they are being deprecated.
Then, you just select the database by adding the database name in the parameter to mysql\_select\_db():
```
mysql_select_db('dbname');
```
note that another advantage of mysqli is you can specify the database in the connect string |
15,719,092 | I am having a problem in getting the string name of the currently selected database.
this is what i did.. i am trying to echo the name of the database but it produces an error "Warning: mysql\_fetch\_array() expects parameter 1 to be resource"
```
<?php
$dbcon = mysql_connect("localhost", "root", "")
or die(mysql_error()."Not Connected");
$sql = mysql_query("select database()");
$row = mysql_fetch_array($sql);
echo "db ".$row[0];
```
?>
i need to get the selected database name because i will use it for
```
mysql_select_db()
``` | 2013/03/30 | ['https://Stackoverflow.com/questions/15719092', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1647596/'] | You should either select a database right after connecting using your login credentials. Or, if you want to see what databases the `root` user has access to, use:
```
SHOW DATABASES;
``` | first, I would suggest you use mysqli functions instead of mysql as they are being deprecated.
Then, you just select the database by adding the database name in the parameter to mysql\_select\_db():
```
mysql_select_db('dbname');
```
note that another advantage of mysqli is you can specify the database in the connect string |
15,719,092 | I am having a problem in getting the string name of the currently selected database.
this is what i did.. i am trying to echo the name of the database but it produces an error "Warning: mysql\_fetch\_array() expects parameter 1 to be resource"
```
<?php
$dbcon = mysql_connect("localhost", "root", "")
or die(mysql_error()."Not Connected");
$sql = mysql_query("select database()");
$row = mysql_fetch_array($sql);
echo "db ".$row[0];
```
?>
i need to get the selected database name because i will use it for
```
mysql_select_db()
``` | 2013/03/30 | ['https://Stackoverflow.com/questions/15719092', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1647596/'] | `select Database()` shows the name of the name of the slected database.
It will work only after you have already selected the database using `mysql_select_db()`.
If you want to get the name of the databases available to you then use `SHOW DATABASES` | first, I would suggest you use mysqli functions instead of mysql as they are being deprecated.
Then, you just select the database by adding the database name in the parameter to mysql\_select\_db():
```
mysql_select_db('dbname');
```
note that another advantage of mysqli is you can specify the database in the connect string |
33,886,993 | For Marklogic, it's a NoSQL db and powerful server engine. I use \*.xqy file to write code before,but marklogic 8 has an advanced function is that it can write javascript code directly.For more speed to search at database, I want to transplant the xquery project to javascript project.But there is no existing frame to build my project. Actually, I was use the Roxy frame for my xquery project. And I need the same MVC framework for javascript. | 2015/11/24 | ['https://Stackoverflow.com/questions/33886993', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5319952/'] | There’s a lot to untangle here.
First, the runtime performance differences between the equivalent functionality written in XQuery and JavaScript will be negligible. I’d suggest you weigh other factors more heavily when deciding between them. For example, what will your developers be most productive with? What parts of the language ecosystem will be relevant to you? Is your data primarily XML or JSON?
As for [Roxy](https://github.com/marklogic/roxy), there currently isn’t an equivalent in the JavaScript world. If you’re interested in creating a fork, I’m sure the community would be willing to offer guidance. | If you are talking about a server-side MVC model, then it's true there is no JS framework available yet. There is a lot going on though:
* Christy Haragan is putting a lot of effort in various [TypeScript-related projects](http://github-search.demo.marklogic.com/search?f=owner:christyharagan) that cover the full stack
* [Slush-marklogic-node](https://developer.marklogic.com/blog/slush-marklogic-node) provides a client-side framework, building on top of the MarkLogic REST-api
* [MarkLogic Samplestack](http://www.marklogic.com/what-is-marklogic/whats-new/samplestack/) provides reference architectures for Java and NodeJS 3-tier applications
Last but not least, Roxy can deploy your custom server-side JavaScript just as easy as XQuery, and other code..
HTH! |
19,669,054 | I have an excel sheet that contains phone calls with Start day, Start Time and End Time. I would like to find a way to loop through the calls to see how many of our phone trunks are in use during each call. There may be a better way to check this but here is the logic I was thinking of using.
In Cell C1 I have the Start time of the first call of the month. In D1 I have the end time of that call. I know at the beginning of that first call only one trunk is in use. I need to loop through each call to see if the End time of any calls prior to the current checked call is greater than the start time of the current call being checked.
So the work really begins with the second row and a check to see if C2 (call Start time of call 2) is < D1 ( end time of call 1).
The next loop through would check if C3 < D1 and then check if C3 < D2. If any of the checks are true then a value called Trunks (With a starting value of 1) would increment by 1. Once the row check was finished Trunks would be written to column E corresponding with the row being checked.
The next loop would check if C4 < D1 then C4 < D2 then C4 < D3 and write the value of trunks to E4
Then on to C5 and so on until the end of the sheet. The sheet will be from 12,000 to 15,000 rows.
Can this be done through a sub in VBA? Can anyone help write this sub for me? Here are the values of C1 - C11 and D1 - D11. In the example below the value of trunk in every row would be 1 until you arrived at row 7. since the start time of the call in row 7 (6:10:05) is less than end time of the call from row 6 (6:10:59), that means two calls were happening at the same time so trunks would equal 2.
```
C1 2:44:00 AM D1 2:45:08 AM
C2 3:30:15 AM D2 3:33:10 AM
C3 4:02:50 AM D3 4:04:12 AM
C4 4:48:15 AM D4 4:48:32 AM
C5 6:02:25 AM D5 6:03:57 AM
C6 6:08:54 AM D6 6:10:59 AM
C7 6:10:05 AM D7 6:10:34 AM
C8 6:10:05 AM D8 6:10:41 AM
C9 6:23:30 AM D9 6:29:07 AM
C10 6:36:28 AM D10 6:39:54 AM
C11 7:16:56 AM D11 7:24:56 AM
```
Thanks in Advance! | 2013/10/29 | ['https://Stackoverflow.com/questions/19669054', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2933813/'] | You do not necessarily need VBA. Try the following, adjusting for your data ranges. You cannot use full column references in this case, or else the formula will take a long time to run.
```
=SUM(IF(C$1:C$11<=C1,IF(D$1:D$11>=C1,1,0),0))
```
When you enter this, you'll have to press `CTRL+SHIFT+ENTER` instead of just `ENTER`. You'll know it worked because Excel will surround the formula with `{}`.
```
{=SUM(IF(C$1:C$11<=C1,IF(D$1:D$11>=C1,1,0),0))}
```
This is an Array formula, or CSE Formula. It treats each cell in the ranges you specify as a single instance. The `IFs` are emulating an `AND` operation. This is essentially summing the number of rows that have a start time `<=` current row's start time, and a end time `>=` the start time.
This formula needs to appear on every row.
This works for your example above, but is NOT a complete solution. There are missed cases.
EDIT: The following may cover the missed cases. Same rules as above apply. This is still something for you to learn about on your own, however, so the explanation is very light.
```
=SUM(IF(C$1:C$11<=C1,IF(D$1:D$11>=C1,1,0),IF(C1:C11>=C1,IF(C1:C11<=D1,1,0),0)))
``` | The basic idea of looping through a bunch of cells, comparing it with values in another column is shown in the following. I have used a similar one in one of the programs. Now you can use if/else logic matching your requirement.
```
For rowIndex = 2 To lr2
calcFormula1 = (Application.SumIf(Range("C2:C100"), Range(rowIndex, "D2:D99").Text, Range("E:E")))
Cells(rowIndex, "O").Value = calcFormula1
Next rowIndex
``` |
48,374,126 | [](https://i.stack.imgur.com/WDUOp.png)
I do have a problem when I'm going to submit my form, i dont have any idea to add this format "2018-00XX" automatically when someone submitted a form and the data will be transferred to google spreadsheet.
As you can see the picture, I gave you an example of how the control number should be entered automatically when the user submitted a form from google form.
Thanks in advance to anyone can answer my problem! | 2018/01/22 | ['https://Stackoverflow.com/questions/48374126', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5330802/'] | A2:
```
=ARRAYFORMULA("201800"&text(ROW(A$1:INDEX(B:B,COUNTA(B:B)-1)),"00"))
``` | You can use formula like this in the 1st Column
```
=if(EQ(B2,),"", A1+1)
```
This will check if column 2 is empty or not if, it isn't then it'll set value of cell just above it plus one.
NOTE : For 1st cell you'll need to set value 20180001 manually and apply this formula to rest of the whole column one cells. |
48,374,126 | [](https://i.stack.imgur.com/WDUOp.png)
I do have a problem when I'm going to submit my form, i dont have any idea to add this format "2018-00XX" automatically when someone submitted a form and the data will be transferred to google spreadsheet.
As you can see the picture, I gave you an example of how the control number should be entered automatically when the user submitted a form from google form.
Thanks in advance to anyone can answer my problem! | 2018/01/22 | ['https://Stackoverflow.com/questions/48374126', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5330802/'] | A2:
```
=ARRAYFORMULA("201800"&text(ROW(A$1:INDEX(B:B,COUNTA(B:B)-1)),"00"))
``` | With *2018* hardcoded in,
```
=text(row(1:1), "\2\0\1\80000")
```
Using the date from column B,
```
=year(B2)&text(COUNTIFS(B$2:B2, ">="&date(year(B2), 1, 1), B$2:B2, "<"&date(year(B2)+1, 1, 1)), "0000")
``` |
7,903,423 | I am displaying a graph using jQplot to monitor data.
To refresh the div holding the graph, I invoke an ajax call every 5 seconds (see JavaScript excerpt below).
On the server, a PHP script retrieves the data from a database.
On success, the ajax call is reinvoked after 5 seconds with a JavaScript setTimeout(ajax,5000).
On error, the ajax call is retried 10 times with setTimeout(ajax,5000) before displaying an error message.
Monitoring XHR learns that the browser crashes after approximately 200 requests.
As a temporary remedy, a location.reload() is issued after 50 iterations to prevent the browser from crashing.
This works, but is not an ideal situation.
Any better solution to this problem is very much appreciated.
Thanks and regards, JZB
```
function ajax() {
$.ajax({
cache: false,
url: 'monitor.php',
data : { x: id },
method: 'GET',
dataType: 'json',
success: onDataReceived,
error: onDataError
});
function onDataReceived(series) {
$('#chartdiv_bar').html('');
$.jqplot('chartdiv_bar', [series['initHits']], CreateOptions(series,'Inits'));
errorcount = 0;
setTimeout(ajax, 5000);
}
function onDataError(jqXHR, textStatus, errorThrown) {
errorcount++;
if (errorcount == 10) {
alert("No server response:\n\n" + textStatus + "\n" + errorThrown);
} else {
setTimeout(ajax, 5000);
}
}
}
``` | 2011/10/26 | ['https://Stackoverflow.com/questions/7903423', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1014584/'] | Since you're re-calling ajax() after a good or fail ajax call, you're starting multiple timers. This is why your browser is crashing.
you may want to try to clear the current timer and then start the next timer
```
var t; //global
```
In each of your call back functions:
```
if(t)
clearTimeout(t);
t = setTimeout(ajax, 5000);
```
more info on timer here: [w3 school](http://www.w3schools.com/js/js_timing.asp) | I removed the jqplot call as suggested and the problem disappeared.
Apparently jqplot is the culprit and I found numerous entries referring to jqPlot memory leaks.
I use jQuery 1.6.4 and installed jqPlot Charts version 1.0.0b2\_r792 which supposedly addresses memory leak issues.
Furthermore, I replaced
```
$('#chartdiv_bar').html('');
```
with
```
$('#chartdiv_bar').empty();
```
Thank you for your support. |
15,711,158 | My program calls exec() on a binary that has been written to a directory specified by the user. If the directory resides in a tree mounted with "noexec", the exec() fails with EACCES.
Instead of failing the exec(), I would like to be able to figure out if a directory was mounted with noexec, but none of fcntl(), stat() or mount() return this info (from reading the manpages). Looking at the kernel source for the exec system call, it looks like this info is stored in the metadata of the inode, and I don't see this info being returned from any system call.
```
673 struct nameidata nd;
(..)
677 err = path_lookup_open(AT_FDCWD, name, LOOKUP_FOLLOW, &nd, FMODE_READ|FMODE_EXEC);
678 file = ERR_PTR(err);
(..)
682 file = ERR_PTR(-EACCES);
683 if (!(nd.mnt->mnt_flags & MNT_NOEXEC) &&
684 S_ISREG(inode->i_mode)) {
```
Does anyone know of a way to do this?
Thanks. | 2013/03/29 | ['https://Stackoverflow.com/questions/15711158', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/901185/'] | You can use [statvfs](http://man7.org/linux/man-pages/man3/fstatvfs.3.html)()
```
struct statvfs st;
inr rc = statvfs("/mnt/foo", &st);
if (rc == -1)
error();
if (st.f_flag & ST_NOEXEC) {
//no exec flags was set
}
``` | Did you consider reading `/proc/mounts` then determining which file system your program binary resides on, perhaps using [statfs(2)](http://man7.org/linux/man-pages/man2/fstatfs.2.html) and/or [realpath(3)](http://man7.org/linux/man-pages/man3/realpath.3.html)?
But you always should care about, and handle, the failure of [execve(2)](http://man7.org/linux/man-pages/man2/execve.2.html) and related `exec` functions, which can fail for a variety of reasons.
There are many ways `execve` can fail, and some of them are not easily reproducible; likewise for the failure of `fork` or any other syscall.
I would either leave and report the `EACCESS` error (of `execve`), or, if you absolutely want to catch & explain more the `noexec` mount option, do the more complex thing (`statfs` and/or `realpath` and scanning of `/proc/mounts` or `/proc/self/mounts`) after such an `EACCESS` failure.
There is no much point in testing a binary path before `execve`-ing it ... just report the error after... |
1,620,729 | For a hostname to resolve into its IP address, there are several DNS servers that may be queried. Assuming caching doesn't happen, it goes from whoever made the request (the client), the recursive DNS, the root DNS, the TLD DNS and finally the authoritative name server.
Do I have the order right? Are requests forwarded or does the server just reply with IP address of the server on the next level that should be contacted by the client? For example does the recursive name server do the actually querying on the root server or does it just pass the IP address of the root server along ? I'm guessing it's the first for caching purposes. Also, what stages can caching happen at, for example would the root server have a cached response from the TLD server? Since there's only 13 unique root servers, what is the point of having that level instead of just going directly to the TLD server? | 2021/01/25 | ['https://superuser.com/questions/1620729', 'https://superuser.com', 'https://superuser.com/users/699180/'] | To start with, the type `[Microsoft.Update.Session]` is not really a built-in Powershell object, but part of the [windows update agent (WUA) API](https://docs.microsoft.com/en-us/windows/win32/wua_sdk/searching--downloading--and-installing-updates). As such, it doesn't have any built-in help files or examples powershell can show you, but it is searcheable on the Microsoft site.
The linked MS doc has some good examples of how to use the api to do different things with windows update, and it can mostly be directly converted for use in Powershell.
I happen to have used this before, so here are some basics in powershell:
```
# Create a new update session, and search for updates
$updateObject = New-Object -ComObject Microsoft.Update.Session
$updateObject.ClientApplicationID = "Example Client ID"
$updateSearcher = $updateObject.CreateUpdateSearcher()
# Search for updates using a simple search filter, and save the results to a variable:
$searchResults = $updateSearcher.Search("IsInstalled=0")
# If there are updates available, download them:
if ($searchResults.Updates -and $searchResults.Updates.count -gt 0){
$count=$searchResults.Updates.count
Write-Output ( "Found " + $searchResults.Updates.Count + " Updates" )
$updateDownloader = $updateObject.CreateUpdateDownloader()
$updateDownloader.Updates = $searchResults.Updates
Write-Output "Downloading..."
$updateDownloader.Download()
# Then install the updates:
$updateInstaller = $updateObject.CreateUpdateInstaller()
$updateInstaller.Updates = $searchResults.Updates
Write-Output "Installing..."
$result = $updateInstaller.Install()
# Then output the result
Write-Output ("Installation Result: " + $Result.ResultCode)
Write-Output ("Reboot Required: " + $Result.RebootRequired)
}
else { Write-Output "No updates found. Exiting..." }
```
As far as searching for specific updates, you'll want to add your filters to the `$UpdateSearcher.`[Search()](https://docs.microsoft.com/en-us/windows/win32/api/wuapi/nf-wuapi-iupdatesearcher-search) method. Looks like this can have type='Software' or type='Driver' for example.
Note that the WUA API has a bug/feature that generally **requires** it to be run locally on a machine instead of started remotely, though you can get around this by creating a scheduled task that runs your script.
And finally, to actually answer your question - As a general rule, `Get-Member $MyObject` and `Get-Help $MyCommand` will help you through discovering most built-in Powershell capabilities. | The easiest is to use the `Get-Member` cmdlet, like:
```
$Updates | Get-Member
```
in this case it is most likely a COM object, but it should still show you the Methods and Properties |
15,164,450 | I try to run a Linux command and read the output from it by using C/C++ code.
I search for exec but this don't deal with input/output.
What I am trying to achieve is to get information about wireless LAN by using this command `iwconfig`, invoking it from C/C++ code.
also i need a suitable code to use it as lib for android using NDK.
i see in android open source they called this function
what do you think about this code ?
```
int wpa_ctrl_request(struct wpa_ctrl *ctrl, const char *cmd, size_t cmd_len,
char *reply, size_t *reply_len,
void (*msg_cb)(char *msg, size_t len))
{
DWORD written;
DWORD readlen = *reply_len;
if (!WriteFile(ctrl->pipe, cmd, cmd_len, &written, NULL))
return -1;
if (!ReadFile(ctrl->pipe, reply, *reply_len, &readlen, NULL))
return -1;
*reply_len = readlen;
return 0;
```
}
this is the [link](http://androidxref.com/4.2_r1/xref/external/wpa_supplicant_6/wpa_supplicant/src/common/wpa_ctrl.c#505) | 2013/03/01 | ['https://Stackoverflow.com/questions/15164450', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2110922/'] | You could try running the command and outputting the results to a file, then reading it
```
system("iwconfig > temp.txt");
FILE *fp=fopen("temp.txt","w");
``` | i see in android open source they called this function
what do you think about this code ?
```
int wpa_ctrl_request(struct wpa_ctrl *ctrl, const char *cmd, size_t cmd_len,
char *reply, size_t *reply_len,
void (*msg_cb)(char *msg, size_t len))
{
DWORD written;
DWORD readlen = *reply_len;
if (!WriteFile(ctrl->pipe, cmd, cmd_len, &written, NULL))
return -1;
if (!ReadFile(ctrl->pipe, reply, *reply_len, &readlen, NULL))
return -1;
*reply_len = readlen;
return 0;
}
```
this is the [link](http://androidxref.com/4.2_r1/xref/external/wpa_supplicant_6/wpa_supplicant/src/common/wpa_ctrl.c#505) |
6,473,882 | I have a custom control with a panel wrapping all the other controls. The control is in one of two states, edit-mode and normal. When in edit-mode I want the control to have the option of a different background color.
I have:
In Pre\_Render:
```
Panel1.BackColor = EditMode ? BackEditColor : BackColor;
```
And the control properties:
```
[Bindable(true)]
[Category("Misc")]
[Description("The background color.")]
[DefaultValue("white")]
[Localizable(true)]
public Color BackColor
{
get { return Color.FromName(Convert.ToString(ViewState["BackColor"] ?? "white")); }
set { ViewState["BackColor"] = value.Name; }
}
[Bindable(true)]
[Category("Misc")]
[Description("The edit-mode background color.")]
[DefaultValue("#FFFFCC")]
[Localizable(true)]
public Color BackEditColor
{
get { return Color.FromName(Convert.ToString(ViewState["BackEditColor"] ?? "#FFFFCC")); }
set { ViewState["BackEditColor"] = value.Name; }
}
```
I can set the colors with no problem via the control's properties, but they only show as white on render. How should I be saving/reading to ViewState the colors? | 2011/06/24 | ['https://Stackoverflow.com/questions/6473882', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/353147/'] | ```js
var y = [1,2,3,4,5,6,7,8,9,10];
console.log(y.slice((y.length - 5), y.length))
```
you can do this! | ```
array.reverse()
.slice(0,5)
.reverse() //if you wanna keep the order of last 5
```
---
```
const myOriginalArray = [...Array(10).keys()] //making an array of numbers
const instanceFromlastFiveItemsOfMyArray = [
...myOriginalArray.reverse().slice(0,5).reverse()
]
``` |
6,473,882 | I have a custom control with a panel wrapping all the other controls. The control is in one of two states, edit-mode and normal. When in edit-mode I want the control to have the option of a different background color.
I have:
In Pre\_Render:
```
Panel1.BackColor = EditMode ? BackEditColor : BackColor;
```
And the control properties:
```
[Bindable(true)]
[Category("Misc")]
[Description("The background color.")]
[DefaultValue("white")]
[Localizable(true)]
public Color BackColor
{
get { return Color.FromName(Convert.ToString(ViewState["BackColor"] ?? "white")); }
set { ViewState["BackColor"] = value.Name; }
}
[Bindable(true)]
[Category("Misc")]
[Description("The edit-mode background color.")]
[DefaultValue("#FFFFCC")]
[Localizable(true)]
public Color BackEditColor
{
get { return Color.FromName(Convert.ToString(ViewState["BackEditColor"] ?? "#FFFFCC")); }
set { ViewState["BackEditColor"] = value.Name; }
}
```
I can set the colors with no problem via the control's properties, but they only show as white on render. How should I be saving/reading to ViewState the colors? | 2011/06/24 | ['https://Stackoverflow.com/questions/6473882', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/353147/'] | Here is one I haven't seen that's even shorter
```
arr.slice(1).slice(-5)
```
Run the code snippet below for proof of it doing what you want
```js
const arr = [];
for (let i = 0; i < 8; i++) {
arr.push(i);
console.log(`Array ${i + 1}: ${arr} -> ${arr.slice(1).slice(-5)}`);
}
```
Another way to do it would be using lodash <https://lodash.com/docs#rest> - that is of course if you don't mind having to load a huge JavaScript minified file if you're trying to do it from your browser.
```
_.slice(_.rest(arr), -5)
``` | Beginner solution:
```
var givme = function(n) {
if(n.length == 1) {
return [];
}
if(n.length > 5) {
return n.slice(n.length-5, n.length);
}
if(n.length <= 5) {
return n.slice(1, n.length);
}
}
// console.log(givme([1, 55, 77, 88, 99, 22, 33, 44]));
``` |
6,473,882 | I have a custom control with a panel wrapping all the other controls. The control is in one of two states, edit-mode and normal. When in edit-mode I want the control to have the option of a different background color.
I have:
In Pre\_Render:
```
Panel1.BackColor = EditMode ? BackEditColor : BackColor;
```
And the control properties:
```
[Bindable(true)]
[Category("Misc")]
[Description("The background color.")]
[DefaultValue("white")]
[Localizable(true)]
public Color BackColor
{
get { return Color.FromName(Convert.ToString(ViewState["BackColor"] ?? "white")); }
set { ViewState["BackColor"] = value.Name; }
}
[Bindable(true)]
[Category("Misc")]
[Description("The edit-mode background color.")]
[DefaultValue("#FFFFCC")]
[Localizable(true)]
public Color BackEditColor
{
get { return Color.FromName(Convert.ToString(ViewState["BackEditColor"] ?? "#FFFFCC")); }
set { ViewState["BackEditColor"] = value.Name; }
}
```
I can set the colors with no problem via the control's properties, but they only show as white on render. How should I be saving/reading to ViewState the colors? | 2011/06/24 | ['https://Stackoverflow.com/questions/6473882', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/353147/'] | If you are using lodash, its even simpler with [takeRight](https://lodash.com/docs#takeRight).
`_.takeRight(arr, 5);` | ES6 way:
I use [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) for array to get `first` and remaining `rest` elements and then I'll take last five of the `rest` with [slice](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) method:
```js
const cutOffFirstAndLastFive = (array) => {
const [first, ...rest] = array;
return rest.slice(-5);
}
cutOffFirstAndLastFive([1, 55, 77, 88]);
console.log(
'Tests:',
JSON.stringify(cutOffFirstAndLastFive([1, 55, 77, 88])),
JSON.stringify(cutOffFirstAndLastFive([1, 55, 77, 88, 99, 22, 33, 44])),
JSON.stringify(cutOffFirstAndLastFive([1]))
);
``` |
6,473,882 | I have a custom control with a panel wrapping all the other controls. The control is in one of two states, edit-mode and normal. When in edit-mode I want the control to have the option of a different background color.
I have:
In Pre\_Render:
```
Panel1.BackColor = EditMode ? BackEditColor : BackColor;
```
And the control properties:
```
[Bindable(true)]
[Category("Misc")]
[Description("The background color.")]
[DefaultValue("white")]
[Localizable(true)]
public Color BackColor
{
get { return Color.FromName(Convert.ToString(ViewState["BackColor"] ?? "white")); }
set { ViewState["BackColor"] = value.Name; }
}
[Bindable(true)]
[Category("Misc")]
[Description("The edit-mode background color.")]
[DefaultValue("#FFFFCC")]
[Localizable(true)]
public Color BackEditColor
{
get { return Color.FromName(Convert.ToString(ViewState["BackEditColor"] ?? "#FFFFCC")); }
set { ViewState["BackEditColor"] = value.Name; }
}
```
I can set the colors with no problem via the control's properties, but they only show as white on render. How should I be saving/reading to ViewState the colors? | 2011/06/24 | ['https://Stackoverflow.com/questions/6473882', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/353147/'] | You can call:
```
arr.slice(Math.max(arr.length - 5, 1))
```
If you don't want to exclude the first element, use
```
arr.slice(Math.max(arr.length - 5, 0))
``` | Here is one I haven't seen that's even shorter
```
arr.slice(1).slice(-5)
```
Run the code snippet below for proof of it doing what you want
```js
const arr = [];
for (let i = 0; i < 8; i++) {
arr.push(i);
console.log(`Array ${i + 1}: ${arr} -> ${arr.slice(1).slice(-5)}`);
}
```
Another way to do it would be using lodash <https://lodash.com/docs#rest> - that is of course if you don't mind having to load a huge JavaScript minified file if you're trying to do it from your browser.
```
_.slice(_.rest(arr), -5)
``` |
6,473,882 | I have a custom control with a panel wrapping all the other controls. The control is in one of two states, edit-mode and normal. When in edit-mode I want the control to have the option of a different background color.
I have:
In Pre\_Render:
```
Panel1.BackColor = EditMode ? BackEditColor : BackColor;
```
And the control properties:
```
[Bindable(true)]
[Category("Misc")]
[Description("The background color.")]
[DefaultValue("white")]
[Localizable(true)]
public Color BackColor
{
get { return Color.FromName(Convert.ToString(ViewState["BackColor"] ?? "white")); }
set { ViewState["BackColor"] = value.Name; }
}
[Bindable(true)]
[Category("Misc")]
[Description("The edit-mode background color.")]
[DefaultValue("#FFFFCC")]
[Localizable(true)]
public Color BackEditColor
{
get { return Color.FromName(Convert.ToString(ViewState["BackEditColor"] ?? "#FFFFCC")); }
set { ViewState["BackEditColor"] = value.Name; }
}
```
I can set the colors with no problem via the control's properties, but they only show as white on render. How should I be saving/reading to ViewState the colors? | 2011/06/24 | ['https://Stackoverflow.com/questions/6473882', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/353147/'] | Try this:
```
var array = [1, 55, 77, 88, 76, 59];
var array_last_five;
array_last_five = array.slice(-5);
if (array.length < 6) {
array_last_five.shift();
}
``` | You can do it in one line like this:
```js
const y = [1,2,3,4,5,6,7,8,9,10];
const lastX = 5;
const res = y.filter((val, index, arr) => index > arr.length - lastX - 1);
console.log(res);
```
```
.filter((val, index, arr) => index > arr.length - 6)
``` |
6,473,882 | I have a custom control with a panel wrapping all the other controls. The control is in one of two states, edit-mode and normal. When in edit-mode I want the control to have the option of a different background color.
I have:
In Pre\_Render:
```
Panel1.BackColor = EditMode ? BackEditColor : BackColor;
```
And the control properties:
```
[Bindable(true)]
[Category("Misc")]
[Description("The background color.")]
[DefaultValue("white")]
[Localizable(true)]
public Color BackColor
{
get { return Color.FromName(Convert.ToString(ViewState["BackColor"] ?? "white")); }
set { ViewState["BackColor"] = value.Name; }
}
[Bindable(true)]
[Category("Misc")]
[Description("The edit-mode background color.")]
[DefaultValue("#FFFFCC")]
[Localizable(true)]
public Color BackEditColor
{
get { return Color.FromName(Convert.ToString(ViewState["BackEditColor"] ?? "#FFFFCC")); }
set { ViewState["BackEditColor"] = value.Name; }
}
```
I can set the colors with no problem via the control's properties, but they only show as white on render. How should I be saving/reading to ViewState the colors? | 2011/06/24 | ['https://Stackoverflow.com/questions/6473882', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/353147/'] | Here is one I haven't seen that's even shorter
```
arr.slice(1).slice(-5)
```
Run the code snippet below for proof of it doing what you want
```js
const arr = [];
for (let i = 0; i < 8; i++) {
arr.push(i);
console.log(`Array ${i + 1}: ${arr} -> ${arr.slice(1).slice(-5)}`);
}
```
Another way to do it would be using lodash <https://lodash.com/docs#rest> - that is of course if you don't mind having to load a huge JavaScript minified file if you're trying to do it from your browser.
```
_.slice(_.rest(arr), -5)
``` | ES6 way:
I use [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) for array to get `first` and remaining `rest` elements and then I'll take last five of the `rest` with [slice](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) method:
```js
const cutOffFirstAndLastFive = (array) => {
const [first, ...rest] = array;
return rest.slice(-5);
}
cutOffFirstAndLastFive([1, 55, 77, 88]);
console.log(
'Tests:',
JSON.stringify(cutOffFirstAndLastFive([1, 55, 77, 88])),
JSON.stringify(cutOffFirstAndLastFive([1, 55, 77, 88, 99, 22, 33, 44])),
JSON.stringify(cutOffFirstAndLastFive([1]))
);
``` |
6,473,882 | I have a custom control with a panel wrapping all the other controls. The control is in one of two states, edit-mode and normal. When in edit-mode I want the control to have the option of a different background color.
I have:
In Pre\_Render:
```
Panel1.BackColor = EditMode ? BackEditColor : BackColor;
```
And the control properties:
```
[Bindable(true)]
[Category("Misc")]
[Description("The background color.")]
[DefaultValue("white")]
[Localizable(true)]
public Color BackColor
{
get { return Color.FromName(Convert.ToString(ViewState["BackColor"] ?? "white")); }
set { ViewState["BackColor"] = value.Name; }
}
[Bindable(true)]
[Category("Misc")]
[Description("The edit-mode background color.")]
[DefaultValue("#FFFFCC")]
[Localizable(true)]
public Color BackEditColor
{
get { return Color.FromName(Convert.ToString(ViewState["BackEditColor"] ?? "#FFFFCC")); }
set { ViewState["BackEditColor"] = value.Name; }
}
```
I can set the colors with no problem via the control's properties, but they only show as white on render. How should I be saving/reading to ViewState the colors? | 2011/06/24 | ['https://Stackoverflow.com/questions/6473882', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/353147/'] | You can call:
```
arr.slice(Math.max(arr.length - 5, 1))
```
If you don't want to exclude the first element, use
```
arr.slice(Math.max(arr.length - 5, 0))
``` | You can do it in one line like this:
```js
const y = [1,2,3,4,5,6,7,8,9,10];
const lastX = 5;
const res = y.filter((val, index, arr) => index > arr.length - lastX - 1);
console.log(res);
```
```
.filter((val, index, arr) => index > arr.length - 6)
``` |
6,473,882 | I have a custom control with a panel wrapping all the other controls. The control is in one of two states, edit-mode and normal. When in edit-mode I want the control to have the option of a different background color.
I have:
In Pre\_Render:
```
Panel1.BackColor = EditMode ? BackEditColor : BackColor;
```
And the control properties:
```
[Bindable(true)]
[Category("Misc")]
[Description("The background color.")]
[DefaultValue("white")]
[Localizable(true)]
public Color BackColor
{
get { return Color.FromName(Convert.ToString(ViewState["BackColor"] ?? "white")); }
set { ViewState["BackColor"] = value.Name; }
}
[Bindable(true)]
[Category("Misc")]
[Description("The edit-mode background color.")]
[DefaultValue("#FFFFCC")]
[Localizable(true)]
public Color BackEditColor
{
get { return Color.FromName(Convert.ToString(ViewState["BackEditColor"] ?? "#FFFFCC")); }
set { ViewState["BackEditColor"] = value.Name; }
}
```
I can set the colors with no problem via the control's properties, but they only show as white on render. How should I be saving/reading to ViewState the colors? | 2011/06/24 | ['https://Stackoverflow.com/questions/6473882', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/353147/'] | Here is one I haven't seen that's even shorter
```
arr.slice(1).slice(-5)
```
Run the code snippet below for proof of it doing what you want
```js
const arr = [];
for (let i = 0; i < 8; i++) {
arr.push(i);
console.log(`Array ${i + 1}: ${arr} -> ${arr.slice(1).slice(-5)}`);
}
```
Another way to do it would be using lodash <https://lodash.com/docs#rest> - that is of course if you don't mind having to load a huge JavaScript minified file if you're trying to do it from your browser.
```
_.slice(_.rest(arr), -5)
``` | If you are using lodash, its even simpler with [takeRight](https://lodash.com/docs#takeRight).
`_.takeRight(arr, 5);` |
6,473,882 | I have a custom control with a panel wrapping all the other controls. The control is in one of two states, edit-mode and normal. When in edit-mode I want the control to have the option of a different background color.
I have:
In Pre\_Render:
```
Panel1.BackColor = EditMode ? BackEditColor : BackColor;
```
And the control properties:
```
[Bindable(true)]
[Category("Misc")]
[Description("The background color.")]
[DefaultValue("white")]
[Localizable(true)]
public Color BackColor
{
get { return Color.FromName(Convert.ToString(ViewState["BackColor"] ?? "white")); }
set { ViewState["BackColor"] = value.Name; }
}
[Bindable(true)]
[Category("Misc")]
[Description("The edit-mode background color.")]
[DefaultValue("#FFFFCC")]
[Localizable(true)]
public Color BackEditColor
{
get { return Color.FromName(Convert.ToString(ViewState["BackEditColor"] ?? "#FFFFCC")); }
set { ViewState["BackEditColor"] = value.Name; }
}
```
I can set the colors with no problem via the control's properties, but they only show as white on render. How should I be saving/reading to ViewState the colors? | 2011/06/24 | ['https://Stackoverflow.com/questions/6473882', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/353147/'] | Here is one I haven't seen that's even shorter
```
arr.slice(1).slice(-5)
```
Run the code snippet below for proof of it doing what you want
```js
const arr = [];
for (let i = 0; i < 8; i++) {
arr.push(i);
console.log(`Array ${i + 1}: ${arr} -> ${arr.slice(1).slice(-5)}`);
}
```
Another way to do it would be using lodash <https://lodash.com/docs#rest> - that is of course if you don't mind having to load a huge JavaScript minified file if you're trying to do it from your browser.
```
_.slice(_.rest(arr), -5)
``` | ```js
var y = [1,2,3,4,5,6,7,8,9,10];
console.log(y.slice((y.length - 5), y.length))
```
you can do this! |
6,473,882 | I have a custom control with a panel wrapping all the other controls. The control is in one of two states, edit-mode and normal. When in edit-mode I want the control to have the option of a different background color.
I have:
In Pre\_Render:
```
Panel1.BackColor = EditMode ? BackEditColor : BackColor;
```
And the control properties:
```
[Bindable(true)]
[Category("Misc")]
[Description("The background color.")]
[DefaultValue("white")]
[Localizable(true)]
public Color BackColor
{
get { return Color.FromName(Convert.ToString(ViewState["BackColor"] ?? "white")); }
set { ViewState["BackColor"] = value.Name; }
}
[Bindable(true)]
[Category("Misc")]
[Description("The edit-mode background color.")]
[DefaultValue("#FFFFCC")]
[Localizable(true)]
public Color BackEditColor
{
get { return Color.FromName(Convert.ToString(ViewState["BackEditColor"] ?? "#FFFFCC")); }
set { ViewState["BackEditColor"] = value.Name; }
}
```
I can set the colors with no problem via the control's properties, but they only show as white on render. How should I be saving/reading to ViewState the colors? | 2011/06/24 | ['https://Stackoverflow.com/questions/6473882', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/353147/'] | Try this:
```
var array = [1, 55, 77, 88, 76, 59];
var array_last_five;
array_last_five = array.slice(-5);
if (array.length < 6) {
array_last_five.shift();
}
``` | ```
array.reverse()
.slice(0,5)
.reverse() //if you wanna keep the order of last 5
```
---
```
const myOriginalArray = [...Array(10).keys()] //making an array of numbers
const instanceFromlastFiveItemsOfMyArray = [
...myOriginalArray.reverse().slice(0,5).reverse()
]
``` |
63,735,775 | Here is my `Get` request:
```
@GetMapping("/stats/{fromDate}/{toDate}")
public StatsSummary getStatsSummary(@PathVariable String fromDate, @PathVariable String toDate) {
logger.info("Calculating statistics between" + fromDate + ",to" + toDate);
return statsService.getStatsSummary(fromDate, toDate);
}
```
I've tried adding the annotation `@NotBlank` as:
```
public StatsSummary getStatsSummary(@PathVariable String fromDate, @PathVariable @NotBlank String toDate) {
```
but when I invoke `/stats/2020-05-30/` which does not include `toDate` I receive the response:
```
{
"timestamp": "2020-09-04T06:02:46.567+00:00",
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/stats/2020-05-30/"
}
```
So the annotation is not being registered correctly?
Update:
It seems PathVariable is not meant to be validated:
[The validators (@Validated @Valid) do not work with Spring and TomEE](https://stackoverflow.com/questions/53997703/the-validators-validated-valid-do-not-work-with-spring-and-tomee) | 2020/09/04 | ['https://Stackoverflow.com/questions/63735775', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/470184/'] | Actually Spring by sending 404 returns correct answer to a client.
When someone doesn't provide full URL, the 404 is the status to respond.
The proper way to validate that is to use some date class like **Date** or **LocalDate** or similar instead of **String**.
Probably you'll need to define proper formatting of date so take a look at the following link for details.
<https://www.baeldung.com/spring-date-parameters> | Add the following annotation to the class worked for me.(Not to the method)
```
@Validated
``` |
63,735,775 | Here is my `Get` request:
```
@GetMapping("/stats/{fromDate}/{toDate}")
public StatsSummary getStatsSummary(@PathVariable String fromDate, @PathVariable String toDate) {
logger.info("Calculating statistics between" + fromDate + ",to" + toDate);
return statsService.getStatsSummary(fromDate, toDate);
}
```
I've tried adding the annotation `@NotBlank` as:
```
public StatsSummary getStatsSummary(@PathVariable String fromDate, @PathVariable @NotBlank String toDate) {
```
but when I invoke `/stats/2020-05-30/` which does not include `toDate` I receive the response:
```
{
"timestamp": "2020-09-04T06:02:46.567+00:00",
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/stats/2020-05-30/"
}
```
So the annotation is not being registered correctly?
Update:
It seems PathVariable is not meant to be validated:
[The validators (@Validated @Valid) do not work with Spring and TomEE](https://stackoverflow.com/questions/53997703/the-validators-validated-valid-do-not-work-with-spring-and-tomee) | 2020/09/04 | ['https://Stackoverflow.com/questions/63735775', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/470184/'] | In REST, path variables are part of the resource URL. Therefore, if a part of the path/URL is missing, the resource is different.
That is why a 404 is the correct response code.
If those two variables can be empty, they should be @RequestParam. | Add the following annotation to the class worked for me.(Not to the method)
```
@Validated
``` |
63,735,775 | Here is my `Get` request:
```
@GetMapping("/stats/{fromDate}/{toDate}")
public StatsSummary getStatsSummary(@PathVariable String fromDate, @PathVariable String toDate) {
logger.info("Calculating statistics between" + fromDate + ",to" + toDate);
return statsService.getStatsSummary(fromDate, toDate);
}
```
I've tried adding the annotation `@NotBlank` as:
```
public StatsSummary getStatsSummary(@PathVariable String fromDate, @PathVariable @NotBlank String toDate) {
```
but when I invoke `/stats/2020-05-30/` which does not include `toDate` I receive the response:
```
{
"timestamp": "2020-09-04T06:02:46.567+00:00",
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/stats/2020-05-30/"
}
```
So the annotation is not being registered correctly?
Update:
It seems PathVariable is not meant to be validated:
[The validators (@Validated @Valid) do not work with Spring and TomEE](https://stackoverflow.com/questions/53997703/the-validators-validated-valid-do-not-work-with-spring-and-tomee) | 2020/09/04 | ['https://Stackoverflow.com/questions/63735775', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/470184/'] | In REST, path variables are part of the resource URL. Therefore, if a part of the path/URL is missing, the resource is different.
That is why a 404 is the correct response code.
If those two variables can be empty, they should be @RequestParam. | Actually Spring by sending 404 returns correct answer to a client.
When someone doesn't provide full URL, the 404 is the status to respond.
The proper way to validate that is to use some date class like **Date** or **LocalDate** or similar instead of **String**.
Probably you'll need to define proper formatting of date so take a look at the following link for details.
<https://www.baeldung.com/spring-date-parameters> |
74,610,023 | Hazelcast cluster running in different hosts IP1, IP2...
hazelcast.xml configure the TCP-IP members
[enter image description here](https://i.stack.imgur.com/RQCRa.png)
Now I want to expanding the cluster to support more service.
I install a new hazelcast in new IP3
How can I add the new IP3 to the exsiting cluster without restarting IP1, IP2? | 2022/11/29 | ['https://Stackoverflow.com/questions/74610023', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/20630141/'] | You should pass `log` prop in Sign component and take it like this.
```
export default function Sign({ navigation, log }) {
async function onGoogleButtonPress() {
await GoogleSignin.hasPlayServices();
const userInfo = await GoogleSignin.signIn();
setuserInfo(userInfo);
navigation.navigate('dash', {userInfo, log});
}
// some code
}
```
after all, `log` will be located inside `props.route.params` object
```
export default function dash(props) {
const [text, setTextbaby] = useState();
const {userInfo, log} = props?.route?.params;
console.log(log);
}
```
UPDATED: use double brackets (in order to pass object)
```
log={{name: "register"}}
log={{name: "login"}}
```
--- | we can pass a value from one screen to another screen through `async-storage` `react-navigation` or declare a value globally.
To pass a value from login to dashboard I recommend you to see this async-storage Docs <https://react-native-async-storage.github.io/async-storage/docs/install>
async-storage store a value in App while React navigation does not store a value in App, React navigation just transfer value from one screen to another.
react navigation Docs <https://reactnavigation.org/docs/navigating/>
passing a value from one component to another
```
import { Text, View, Button } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
function HomeScreen({ navigation }) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
<Button
title="Go to Details"
onPress={() => {
/* 1. Navigate to the Details route with params */
navigation.navigate('Details', {
itemId: 86,
otherParam: 'anything you want here',
});
}}
/>
</View>
);
}
function DetailsScreen({ route, navigation }) {
/* 2. Get the param */
const { itemId } = route.params;
const { otherParam } = route.params;
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Details Screen</Text>
<Text>itemId: {JSON.stringify(itemId)}</Text>
<Text>otherParam: {JSON.stringify(otherParam)}</Text>
<Button
title="Go to Details... again"
onPress={() =>
navigation.push('Details', {
itemId: Math.floor(Math.random() * 100),
})
}
/>
<Button title="Go to Home" onPress={() => navigation.navigate('Home')} />
<Button title="Go back" onPress={() => navigation.goBack()} />
</View>
);
}
const Stack = createNativeStackNavigator();
export default function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Details" component={DetailsScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}```
``` |
157,931 | From an outsider/student's view, STEM professors are:
1. not taking courses
2. mostly not doing things outside of their research comfort zones
3. not (?) studying up much except for their research, certainly not doing exercises from the back of a book and looking up solutions somewhere
4. some graduated 40 years ago or even more.
5. teaching the same course for past 20 years, which let's face it, is sort of like teaching history with numbers.
6. not visibly getting taught by their research students or anyone else for that matters.
How is it that a lot of the professors are publishing cutting edge research (especially in STEM) involving the latest tech and gadgets? If I am not reading the news, I wouldn't know what Apple is doing right now let alone develop an algorithm that mimics what their Face Recognition AI is doing.
How is it possible that a professor with a PhD in analog circuit back in the 70s could do research in today's massive microchip fabrication process when a tremendous amount of information/material is needed to get up to speed both in terms of theory and practical knowledge? Do these professors have fabrication facilities in their garage or something? How would they know without being in industry or taking a course?
How is it possible that a professor with a PhD in numerical optimization from the 80s where the latest and the great was quasi-Newton method is doing research on the latest deep learning algorithm? How can this person even be proficient at this? Are they taking courses on Coursera or something?
How do you do it? | 2020/10/22 | ['https://academia.stackexchange.com/questions/157931', 'https://academia.stackexchange.com', 'https://academia.stackexchange.com/users/87227/'] | In short, your premises are wrong.
* Professors read papers to learn.
* Professors meet with their peers, both at conferences and informally, and learn from them.
* Professors do learn from their research students.
These are slow methods of learning, but over many years they add up.
Further, in fast-moving fields of research, nobody "keeps up" in the sense of knowing everything that is going on. It isn't necessary to know everything that is already known to create new knowledge. | By having PhD students and post docs. Not saying professors don't do research but a big part is having the idea then handing it off to a student/post doc who does the research. PhD students gets to spend 3-4 years becoming the expert in their tiny subfield. At some point the PhD student will start teaching the professor new things. Post docs help to really push an idea forward and make progress. Master students are also helpful in "testing the waters" in new areas. It doesn't matter so much if their research goes no where but can be a helpful probe to see if an idea has some merit.
Professors are also usually usually the ones organising conferences and sitting on the committee's deciding who gets to speak and who gets money. So not only do they get a front row seat to learning what people are doing, and where the field is going they are also the ones helping to direct where their field goes. |
11,826,441 | How can I reduce the clustered index scan cost of below mentioned query
```
DECLARE @PARAMVAL varchar(3)
set @PARAMVAL = 'CTD'
select * from MASTER_RECORD_TYPE where RECORD_TYPE_CODE=@PARAMVAL
```
if I run the above query it was showing index scan 99 %
Please find here below my table particularities:

here below i have pasted my index for the table:
```
CREATE TABLE [dbo].[MASTER_RECORD_TYPE] ADD CONSTRAINT [PK_MASTER_REPORD_TYPE] PRIMARY KEY CLUSTERED
(
[Record_Type_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY]
GO
```
kindly advise how can i reduce index scan cost? | 2012/08/06 | ['https://Stackoverflow.com/questions/11826441', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1494292/'] | First of all - if you search for `RECORD_TYPE_CODE` you should make sure to have an index on that column.
Besides that mainly two things:
* **don't** use `SELECT *` - that'll always have to go back to the clustered index to get the full data page; use a `SELECT` that explicitly specifies which columns to use
* if ever possible, try to find a way to have a **covering** nonclustered index, e.g. an index that contains all the columns needed to satisfy the query
If you have such a covering nonclustered index, then the query optimizer will most likely use that covering index (instead of the actual clustered index which is the full table data) to fetch the results | You need to try and use a covered index. But the problem you're going to have is that you're using `SELECT *`. Do you really need the entire record?
Either way, add `RECORD_TYPE_CODE` to another index and it will help with the query because at least that field can be read off of an index page. |
11,826,441 | How can I reduce the clustered index scan cost of below mentioned query
```
DECLARE @PARAMVAL varchar(3)
set @PARAMVAL = 'CTD'
select * from MASTER_RECORD_TYPE where RECORD_TYPE_CODE=@PARAMVAL
```
if I run the above query it was showing index scan 99 %
Please find here below my table particularities:

here below i have pasted my index for the table:
```
CREATE TABLE [dbo].[MASTER_RECORD_TYPE] ADD CONSTRAINT [PK_MASTER_REPORD_TYPE] PRIMARY KEY CLUSTERED
(
[Record_Type_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY]
GO
```
kindly advise how can i reduce index scan cost? | 2012/08/06 | ['https://Stackoverflow.com/questions/11826441', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1494292/'] | First of all - if you search for `RECORD_TYPE_CODE` you should make sure to have an index on that column.
Besides that mainly two things:
* **don't** use `SELECT *` - that'll always have to go back to the clustered index to get the full data page; use a `SELECT` that explicitly specifies which columns to use
* if ever possible, try to find a way to have a **covering** nonclustered index, e.g. an index that contains all the columns needed to satisfy the query
If you have such a covering nonclustered index, then the query optimizer will most likely use that covering index (instead of the actual clustered index which is the full table data) to fetch the results | In your query, you have used column `RECORD_TYPE_CODE` which is not part of `clustered index` and also not included in any `non-clustered index` too. So SQL Optimizer will decide to scan the clustered index to do comparison of where clause predicate.
[Why is there a scan on my clustered index?](https://stackoverflow.com/questions/1161303/why-is-there-a-scan-on-my-clustered-index) |
11,826,441 | How can I reduce the clustered index scan cost of below mentioned query
```
DECLARE @PARAMVAL varchar(3)
set @PARAMVAL = 'CTD'
select * from MASTER_RECORD_TYPE where RECORD_TYPE_CODE=@PARAMVAL
```
if I run the above query it was showing index scan 99 %
Please find here below my table particularities:

here below i have pasted my index for the table:
```
CREATE TABLE [dbo].[MASTER_RECORD_TYPE] ADD CONSTRAINT [PK_MASTER_REPORD_TYPE] PRIMARY KEY CLUSTERED
(
[Record_Type_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY]
GO
```
kindly advise how can i reduce index scan cost? | 2012/08/06 | ['https://Stackoverflow.com/questions/11826441', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1494292/'] | You need to try and use a covered index. But the problem you're going to have is that you're using `SELECT *`. Do you really need the entire record?
Either way, add `RECORD_TYPE_CODE` to another index and it will help with the query because at least that field can be read off of an index page. | In your query, you have used column `RECORD_TYPE_CODE` which is not part of `clustered index` and also not included in any `non-clustered index` too. So SQL Optimizer will decide to scan the clustered index to do comparison of where clause predicate.
[Why is there a scan on my clustered index?](https://stackoverflow.com/questions/1161303/why-is-there-a-scan-on-my-clustered-index) |
55,196,362 | I have an array in for format as below (consol.log in browser). How would I iterate the array in php?
```
stdClass Object
(
[SIEcat7] => stdClass Object
(
[text] => test1
[amount] => 1 000.00
)
[SIEcat8] => stdClass Object
(
[text] => test2
[amount] => 0.00
)
)
``` | 2019/03/16 | ['https://Stackoverflow.com/questions/55196362', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/712430/'] | When use `find_package(XXX)`, it can work in two modes: *MODULE* and *CONFIG*. And resulted variables and targets of this call **depend on the mode**.
If `FindXXX.cmake` file exists (and can be found), the *MODULE* mode is used and given file is processed. Otherwise, if the package is shipped with `XXXConfig.cmake` file, *CONFIG* mode is used and given file is processed. If none of this file exists, CMake emits an error (if called with *REQUIRED* keyword) or a warning (without *REQUIRED* keyword).
In case of `gtest` package, CMake is shipped with `FindXXX.cmake` script, so this script is processed in *MODULE* mode. You may find description of this script in the [documentation](https://cmake.org/cmake/help/v3.6/module/FindGTest.html), which tells that you need to use `GTest::GTest` target for link with gtest:
```
target_link_libraries(main GTest::GTest)
``` | Not all packages provide a CMake library definition. If you're lucky, then `vcpkg install` will show you the name:
```
$ ./vcpkg install openssl
The package openssl is compatible with built-in CMake targets:
find_package(OpenSSL REQUIRED)
target_link_libraries(main PRIVATE OpenSSL::SSL OpenSSL::Crypto)
```
This will work even if you've already installed the package, so you can use it anytime to query the package name.
On the other hand, if `vcpkg install <pkg>` doesn't say anything about CMake, then you need to include it manually in your CMake file, by finding the `include` path and the `library` files.
Here is an example of such a case, here for the `live555` library:
```
# Use one of the headers to locate the include location
find_path(LIVE555_INCLUDE_DIR liveMedia.hh)
# Find the libraries
find_library(LIVE555_LIBRARY1 liveMedia)
find_library(LIVE555_LIBRARY2 groupsock)
find_library(LIVE555_LIBRARY3 BasicUsageEnvironment)
find_library(LIVE555_LIBRARY4 UsageEnvironment)
add_executable(rtsp testRTSPClient.cpp)
target_include_directories(rtsp PRIVATE ${LIVE555_INCLUDE_DIR})
target_link_libraries(rtsp PRIVATE ${LIVE555_LIBRARY1} ${LIVE555_LIBRARY2} ${LIVE555_LIBRARY3} ${LIVE555_LIBRARY4})
``` |
15,729,395 | I created a small php site for gameserver management, but it is not forcing unlogged in users to login. I have added a redirect if a session is not active, and have destroyed the sessions on logout. The site is here <http://zelware.co.uk/gameman>
It forces you to login the first time but if you take login.php off of the URL it allows you into the main area again. Any help would be appreciated, thank you! | 2013/03/31 | ['https://Stackoverflow.com/questions/15729395', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1593366/'] | The Linux kernel pages in the `man` program reside in section 9, which is (un)fortunately a non-standard section. See [this](http://manpages.ubuntu.com/manpages/lucid/man1/man.1.html). Popular Linux distributions like Ubuntu don't distribute the man pages that fall under this section through their software channels (?).
They're still available, for example, Debian provides [one](http://packages.debian.org/wheezy/linux-manual-3.2). There are also online versions of the man pages. | Actually the kernel has an ABI and not an API, as the internal interface is changing quickly.
The best way to learn the Linux kernel is reading the source code. If you are interested in character device drivers, then I would recommend to read LDD3 book and have a look how other device driver use the mentioned calls in your kernel source code. This way you will get an idea how to use the kernel ABI for your driver. |
26,279,114 | I would like to split a string at every blank character (' ', '\n', '\r', '\t', '\v', '\f')
The string is stored in UTF8 encoding in a byte array (char\*, or vector or string, for instance)
Can I just split the byte array at each splitting character? Said otherwise, am I sure that the byte values corresponding to these characters cannot be found in a multi-byte character? By looking at the UTF-8 spec it seems all multibyte characters have only bytes higher than 128.
Thanks | 2014/10/09 | ['https://Stackoverflow.com/questions/26279114', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2042388/'] | Yes, you can.
Multibyte sequences necessarily include one lead byte (the two MSBs equal to `11`) and one ore more continuation bytes (two MSBs equal to `10`). The total length of the multibyte sequence (lead byte+continuation bytes) is equal to the number of count of MSBs equal to 1 in the lead byte, before the first bit 0 appears (e.g.: if lead byte is `110xxxxx`, exactly one continuation byte should follow; if it is `11110xxx`, there should be exactly three continuation bytes).
So, if you find short MB sequences or stray continuationb bytes without a lead byte, your string is probably invalid anyway, and you split procedures probably wouldn't screw it any further than what it probably already was.
But there is something you might want to note: Unicode introduces other “blank” symbols in the upper, non-ASCII compatible ranges. You might want to treat them accordingly. | If you limit yourself to the set of whitespace characters you mention, the answer is definitely "yes".
Of course, there is always an issue of checking whether your text is valid UTF-8 in the first place... |
28,123 | I have created my entity-relationship diagram (ERD for brevity) and it has derived attributes.
When it comes to database design using a relational schema, I've designed my tables and linked everything properly.
I don't know if I should add a column to my table that has a derived attribute? For example, the derived attribute is calculated as follows:
* `Total` = `Price * Quantity`
And it is related to the following illustrative table schema:
```
Customer (
ID,
CustomerName,
ItemsID,
Total
);
```
Should `Total` be included in the `Customer` table? | 2012/11/03 | ['https://dba.stackexchange.com/questions/28123', 'https://dba.stackexchange.com', 'https://dba.stackexchange.com/users/12845/'] | What you can do is not always appropriate for the various usages of your relational model. If you were creating a data warehouse in order to analyze customer sales then derived attributes would be appropriate. I have done this for a summary table for a reporting tool. The query would have joined upwards of thirty tables with many aggregations such as sums and show all values an entity has had. A summary table, refreshed daily, listed derived attributes was a great solution for reporting.
For an online transaction processing database using derived attributes is not always the best solution.
For example: now your total is price \* quantity
Next month management decides to implement a discount of 10% for customers who order more than $1000 in a calendar year. Your total column now looks inflexible.
Unfortunately the things you can say today that "will never change" such as Total = price \* quantity are really an example of business logic. Business logic can change anytime in unexpected ways.
To continue with your example....if management institutes a discount and you have a customers table, orders table then all you have to do is add a discount table. Then you can create a view which encapsulates the business logic of the day to derive total sales. When the logic changes you can change the view much easier than recalculating the derived attributes that are fixed in a table.
And if you really want to be prepared you could store the changes in the business logic in a table in the database and cover off "Who, What, why". So if the Bob the Manager offers a discount and five years later Sue, the new manager, says "When did we start offering discounts and who authorized it?" you are a database star. | we should not create our table with derived attributes in it. Instead, the values can be calculated at the time of retrieval. Assume we have millions of records of a table, the redundunt column (e.g. totall) is written for every field, while we can calculate it at the time of retrieval. |
30,347,289 | I'm doing an AJAX request and somehow a trailing newline is added somewhere.
My PHP script echoes (or is supposed to echo) `'SUCCESS'` if the request succeeded, `'ERROR'` otherwise.
But currently it returns: `'SUCCESS'` (i.e. `'SUCCESS\n'`).
I saw that by adding an `alert("!" + msg + "!")` that showed the line break.
My AJAX call:
```
function addMedia() {
var addMediaName = $("#addMediaName").val();
var notif;
if(addMediaName != ""){
$.ajax({
url : '../../controler/add/addMedia.php',
type : 'POST',
data : "mediaName="+ addMediaName,
dataType : 'text',
success: function(msg,data, settings){
if(msg == 'SUCCESS'){
$.toaster({ priority : 'success', title : 'Success', message : 'Mode created' });
} else {
$.toaster({ priority : 'warning', title : 'Failed', message : 'Mode already exists' });
}
},
});
}
}
```
My PHP controller:
```
<?php
include ('../../model/request/add.php');
if((include_once '../../model/request/add.php')===FALSE) exit('erreur include');
$mediaName = $_POST['mediaName'];
$mediaName = ucfirst(strtolower($mediaName));
$media = addMedia($mediaName);
?>
```
And the `addMedia` function:
```
function addMedia($mediaName)
{
global $conn;
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$sql = 'INSERT INTO media (mediaName) VALUES
("'.$mediaName.'")';
$conn->exec($sql);
echo 'SUCCESS';
} catch(PDOException $e) {
echo 'ERREUR';
}
}
```
Any idea where that newline is coming from and how I can fix it? | 2015/05/20 | ['https://Stackoverflow.com/questions/30347289', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4915360/'] | That is most likely caused by the end of the PHP file, where a newline follows the `?>`.
Now while it is possible to `die`/`exit` at a previous point, I consider it a much cleaner solution to simply remove the `?>`.
The closing tag is not required by PHP, and it is usually even considered better practise not to use it, see [this SO question](https://stackoverflow.com/questions/4410704/why-would-one-omit-the-close-tag). | add [die()](http://www.w3schools.com/php/func_misc_die.asp) or [exit()](http://www.w3schools.com/php/func_misc_exit.asp) after
```
echo 'SUCCESS'; die;
```
or
```
echo 'ERREUR'; die;
```
if you can't add `die` then code execute next line of code or in this case it will call 'view' in MVC. |
42,129,900 | ```
public class mychatorderdetails extends ActionBarActivity {
private MyApplication app;
private String order_id;
private String orderdate;
private String cust_name;
private String cust_address;
private String cust_pincode;
private String cust_mobile;
private String action;
private String UPI;
private Button bt;
private OrderDetailsAdapter oa;
private ListView lv;
private ArrayList<HashMap<String, String>> messageList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mychatorderdetails);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
messageList = new ArrayList<HashMap<String, String>>();
app=((MyApplication) getApplicationContext());
Bundle extras = getIntent().getExtras();
if(extras != null) {
order_id = extras.getString("order_id");
orderdate = extras.getString("orderdate");
cust_name = extras.getString("cust_name");
cust_address = extras.getString("cust_address");
cust_pincode = extras.getString("cust_pincode");
cust_mobile=extras.getString("cust_mobile");
UPI=extras.getString("UPI");
action=extras.getString("action"); //setaccepted, setdelivered
}
bt = (Button) findViewById(R.id.btnAction);
switch (action)
{
case "setdelivered":{
bt.setText("Delivered");
break;
}
case "setaccepted":{
bt.setText("Accept");
break;
}
default:
}
try {
String dpart = orderdate.substring(0, 10);
String tpart = orderdate.substring(11, 19);
orderdate = dpart.substring(8,10);
orderdate+="/"+dpart.substring(5,7);
orderdate+="/"+dpart.substring(0,4);
orderdate+=" "+tpart;
}
catch (Exception e)
{
Log.d(getString(R.string.app_name), e.getMessage());
}
HashMap<String, String> row = new HashMap<String, String>();
row.put("type", "text");
row.put("details", "Order ID:"+order_id);
messageList.add(row);
HashMap<String, String> rowd = new HashMap<String, String>();
rowd.put("type", "text");
rowd.put("details", "Order Date:"+orderdate);
messageList.add(rowd);
HashMap<String, String> row1 = new HashMap<String, String>();
row1.put("type", "text");
row1.put("details",cust_name);
messageList.add(row1);
HashMap<String, String> row2 = new HashMap<String, String>();
row2.put("type", "text");
row2.put("details",cust_address);
messageList.add(row2);
HashMap<String, String> row3 = new HashMap<String, String>();
row3.put("type", "text");
row3.put("details","Pin:"+cust_pincode);
messageList.add(row3);
HashMap<String, String> row4 = new HashMap<String, String>();
row4.put("type", "text");
row4.put("details","Mob:"+cust_mobile);
messageList.add(row4);
HashMap<String, String> row5 = new HashMap<String, String>();
row5.put("type", "text");
row5.put("details","UPI:"+UPI);
messageList.add(row5);
oa=new OrderDetailsAdapter(mychatorderdetails.this,messageList);
lv = (ListView) findViewById(R.id.lstOrderDetails);
lv.setAdapter(oa);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try {
HashMap<String, String> temp = new HashMap<String, String>();
temp = messageList.get(position);
if(temp.get("type")=="image")
{
//Uri uri = Uri.parse(temp.get("details"));
showImage(temp.get("details"));
}
} catch (Exception e) {
Log.d(getString(R.string.app_name), e.getMessage());
}
}
});
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
JSONArray det = app.getMyChatOrderDetails(order_id);
for (int i = 0; i < det.length(); i++) {
JSONObject cat = det.getJSONObject(i);
HashMap<String, String> row = new HashMap<String, String>();
if(!TextUtils.isEmpty(cat.getString("msg_image").toString()))
{
row.put("type", "image");
row.put("details",cat.getString("msg_image").toString());
}
else
{
row.put("type", "text");
String mfv=cat.getString("msg_for_vendor").toString();
if(mfv.equals("1"))
{
row.put("details","Customer: "+cat.getString("msg_text").toString());
}
else{
row.put("details","Me: "+cat.getString("msg_text").toString());
}
}
messageList.add(row);
}
oa.notifyDataSetChanged();
} catch (JSONException e) {
Log.d(getString(R.string.app_name), e.getMessage());
} catch (Exception e) { //connection timeout
Log.d(getString(R.string.app_name), e.getMessage());
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
public void showImage(String imageUri) {
Dialog builder = new Dialog(this);
builder.requestWindowFeature(Window.FEATURE_NO_TITLE);
builder.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialogInterface) {
//nothing;
}
});
try {
ImageView imageView = new ImageView(this);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(imageUri).getContent());
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(450, 400);
imageView.setLayoutParams(layoutParams);
imageView.setVisibility(View.VISIBLE);
builder.addContentView(imageView, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
builder.show();
}
}
catch (Exception e)
{
Log.d(getString(R.string.app_name), e.getMessage());
}
}
public void doAction(View v)
{
switch (action)
{
case "setdelivered":{
if(app.setOrderDelivered(order_id)) {
Toast.makeText(this,"Order marked as delivered...",Toast.LENGTH_LONG).show();
bt.setVisibility(View.INVISIBLE);
}
break;
}
case "setaccepted":{
if(app.acceptChatOrder(order_id)){
Toast.makeText(this,"Order accepted...",Toast.LENGTH_LONG).show();
bt.setVisibility(View.INVISIBLE);
}
break;
}
default:
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_mychatorderdetails, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
Intent intent;
//noinspection SimplifiableIfStatement
if (id == R.id.action_logout) {
app = ((MyApplication) getApplicationContext());
app.logOut();
intent = new Intent(mychatorderdetails.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
mychatorderdetails.this.startActivity(intent);
}
mychatorderdetails.this.finish();
return super.onOptionsItemSelected(item);
}
}
```
Following is the code to display my List ITEMS. I wanted my 5th row item i.e UPI to be enabled copying when long pressed on it. How do I do this? Please edit my code for the same to happen. | 2017/02/09 | ['https://Stackoverflow.com/questions/42129900', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7457008/'] | Use,
```
DROP DATABASE database_name CASCADE;
```
By default, the mode is `RESTRICT` which blocks the deletion of database if it holds tables. | You can use this command:
```
DROP DATABASE IF EXISTS HIVE_DATABASE_NAME CASCADE;
```
In case, you are using older version of Hive:
Drop all tables and views from hive database first, and then drop the database. You can consolidate below command in a shell script to execute.
```
hive -e 'use HIVE_DATABASE_NAME;show tables' | xargs -I '{}' hive -e 'use HIVE_DATABASE_NAME;DROP TABLE IF EXISTS {}'
hive -e 'use HIVE_DATABASE_NAME;show tables' | xargs -I '{}' hive -e 'use HIVE_DATABASE_NAME;DROP VIEW IF EXISTS {}'
hive -e 'DROP DATABASE IF EXISTS HIVE_DATABASE_NAME;'
``` |
42,129,900 | ```
public class mychatorderdetails extends ActionBarActivity {
private MyApplication app;
private String order_id;
private String orderdate;
private String cust_name;
private String cust_address;
private String cust_pincode;
private String cust_mobile;
private String action;
private String UPI;
private Button bt;
private OrderDetailsAdapter oa;
private ListView lv;
private ArrayList<HashMap<String, String>> messageList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mychatorderdetails);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
messageList = new ArrayList<HashMap<String, String>>();
app=((MyApplication) getApplicationContext());
Bundle extras = getIntent().getExtras();
if(extras != null) {
order_id = extras.getString("order_id");
orderdate = extras.getString("orderdate");
cust_name = extras.getString("cust_name");
cust_address = extras.getString("cust_address");
cust_pincode = extras.getString("cust_pincode");
cust_mobile=extras.getString("cust_mobile");
UPI=extras.getString("UPI");
action=extras.getString("action"); //setaccepted, setdelivered
}
bt = (Button) findViewById(R.id.btnAction);
switch (action)
{
case "setdelivered":{
bt.setText("Delivered");
break;
}
case "setaccepted":{
bt.setText("Accept");
break;
}
default:
}
try {
String dpart = orderdate.substring(0, 10);
String tpart = orderdate.substring(11, 19);
orderdate = dpart.substring(8,10);
orderdate+="/"+dpart.substring(5,7);
orderdate+="/"+dpart.substring(0,4);
orderdate+=" "+tpart;
}
catch (Exception e)
{
Log.d(getString(R.string.app_name), e.getMessage());
}
HashMap<String, String> row = new HashMap<String, String>();
row.put("type", "text");
row.put("details", "Order ID:"+order_id);
messageList.add(row);
HashMap<String, String> rowd = new HashMap<String, String>();
rowd.put("type", "text");
rowd.put("details", "Order Date:"+orderdate);
messageList.add(rowd);
HashMap<String, String> row1 = new HashMap<String, String>();
row1.put("type", "text");
row1.put("details",cust_name);
messageList.add(row1);
HashMap<String, String> row2 = new HashMap<String, String>();
row2.put("type", "text");
row2.put("details",cust_address);
messageList.add(row2);
HashMap<String, String> row3 = new HashMap<String, String>();
row3.put("type", "text");
row3.put("details","Pin:"+cust_pincode);
messageList.add(row3);
HashMap<String, String> row4 = new HashMap<String, String>();
row4.put("type", "text");
row4.put("details","Mob:"+cust_mobile);
messageList.add(row4);
HashMap<String, String> row5 = new HashMap<String, String>();
row5.put("type", "text");
row5.put("details","UPI:"+UPI);
messageList.add(row5);
oa=new OrderDetailsAdapter(mychatorderdetails.this,messageList);
lv = (ListView) findViewById(R.id.lstOrderDetails);
lv.setAdapter(oa);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try {
HashMap<String, String> temp = new HashMap<String, String>();
temp = messageList.get(position);
if(temp.get("type")=="image")
{
//Uri uri = Uri.parse(temp.get("details"));
showImage(temp.get("details"));
}
} catch (Exception e) {
Log.d(getString(R.string.app_name), e.getMessage());
}
}
});
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
JSONArray det = app.getMyChatOrderDetails(order_id);
for (int i = 0; i < det.length(); i++) {
JSONObject cat = det.getJSONObject(i);
HashMap<String, String> row = new HashMap<String, String>();
if(!TextUtils.isEmpty(cat.getString("msg_image").toString()))
{
row.put("type", "image");
row.put("details",cat.getString("msg_image").toString());
}
else
{
row.put("type", "text");
String mfv=cat.getString("msg_for_vendor").toString();
if(mfv.equals("1"))
{
row.put("details","Customer: "+cat.getString("msg_text").toString());
}
else{
row.put("details","Me: "+cat.getString("msg_text").toString());
}
}
messageList.add(row);
}
oa.notifyDataSetChanged();
} catch (JSONException e) {
Log.d(getString(R.string.app_name), e.getMessage());
} catch (Exception e) { //connection timeout
Log.d(getString(R.string.app_name), e.getMessage());
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
public void showImage(String imageUri) {
Dialog builder = new Dialog(this);
builder.requestWindowFeature(Window.FEATURE_NO_TITLE);
builder.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialogInterface) {
//nothing;
}
});
try {
ImageView imageView = new ImageView(this);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(imageUri).getContent());
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(450, 400);
imageView.setLayoutParams(layoutParams);
imageView.setVisibility(View.VISIBLE);
builder.addContentView(imageView, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
builder.show();
}
}
catch (Exception e)
{
Log.d(getString(R.string.app_name), e.getMessage());
}
}
public void doAction(View v)
{
switch (action)
{
case "setdelivered":{
if(app.setOrderDelivered(order_id)) {
Toast.makeText(this,"Order marked as delivered...",Toast.LENGTH_LONG).show();
bt.setVisibility(View.INVISIBLE);
}
break;
}
case "setaccepted":{
if(app.acceptChatOrder(order_id)){
Toast.makeText(this,"Order accepted...",Toast.LENGTH_LONG).show();
bt.setVisibility(View.INVISIBLE);
}
break;
}
default:
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_mychatorderdetails, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
Intent intent;
//noinspection SimplifiableIfStatement
if (id == R.id.action_logout) {
app = ((MyApplication) getApplicationContext());
app.logOut();
intent = new Intent(mychatorderdetails.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
mychatorderdetails.this.startActivity(intent);
}
mychatorderdetails.this.finish();
return super.onOptionsItemSelected(item);
}
}
```
Following is the code to display my List ITEMS. I wanted my 5th row item i.e UPI to be enabled copying when long pressed on it. How do I do this? Please edit my code for the same to happen. | 2017/02/09 | ['https://Stackoverflow.com/questions/42129900', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7457008/'] | Use,
```
DROP DATABASE database_name CASCADE;
```
By default, the mode is `RESTRICT` which blocks the deletion of database if it holds tables. | **General syntax is as follows:**
```
hive> DROP DATABASE [IF EXISTS] database_name [RESTRICT|CASCADE];
```
The default behaviour is RESTRICT, where DROP DATABASE will fail if the database is not empty. To drop the tables in the database as well, use DROP DATABASE … with CASCADE option.
***1. Drop database without table or Empty Database:***
```
hive> DROP DATABASE database_name;
```
***2. Drop database with tables:***
```
hive> DROP DATABASE database_name CASCADE;
```
It dropping respective tables before dropping the database. |
12,207,102 | I am currently working on a University assignment, and have a (most likely simple) question regarding regex / regular expressions.
To summarize; this assignment is a simple RSS feed manager, which uses JSP and a RESTful web service.
I am currently working on a section of the assignment spec which requires me to be able to input XML feed data (e.g. <feeds><feed><name>FEED NAME</name><uri>http://FEEDuri/</uri></feed></feeds> etc..) and from this data, extract the FEED NAME & FEEDuri via regex.
My lecturer has provided a base method for us to work off, and I think I have implemented it correctly within my RESTful web service, and now I am implementing error handling.
I have successfully implemented error handling for the case where there is no data input by user. My question is this: **Based on the example method (below), is it possible to implement error handling for the case where the feed format input is incorrect**
eg: `< fed> FEED NAME < /fiid> < uro>http://FEEDuri< /pro>`The XML tags here are obviously incorrect.
**Will regex ONLY pull the group from the String IF it lies between the defined values passed as the arguement to the compile method?**
To supplement my question, here is the base method given to us to use (instead of an XML parser):
```
public static List<Feed> getFeedsFromXml(String xml) {
Pattern feedPattern = Pattern.compile("<feed>\\s*<name>\\s*([^<]*)</name>\\s*<uri>\\s*([^<]*)</uri>\\s*</feed>");
Matcher feedMatch = feedPattern.matcher(xml);
while (feedMatch.find()) {
String feedName = feedMatch.group(1);
String feedURI = feedMatch.group(2);
feeds.add(new Feed(feedName, feedURI));
}
return feeds;
}
``` | 2012/08/30 | ['https://Stackoverflow.com/questions/12207102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1603861/'] | It is preferable, yes, since JSON is defined to be unicode.
If you have more specific things that are causing you trouble you should share them, otherwise I'd recommend watching [Ned Batchelder's Intro](http://bit.ly/unipain) if you're just generally uncomfortable with Unicode (in Python in particular). I don't know what is causing this to be a nuisance to you, since I don't know what you're doing with this dict. | You should keep everything internal to python in unicode if there's any chance you will need it. Where python speaks to other programs, use `s.encode('UTF-8')` to make a regular string that you can write to a file or socket or whatever. Use `s.decode('UTF-8')` to convert a string from a file/socket back to unicode. (UTF-8 seems like a reasonable default, but use whatever your protocol specifies.) |
12,207,102 | I am currently working on a University assignment, and have a (most likely simple) question regarding regex / regular expressions.
To summarize; this assignment is a simple RSS feed manager, which uses JSP and a RESTful web service.
I am currently working on a section of the assignment spec which requires me to be able to input XML feed data (e.g. <feeds><feed><name>FEED NAME</name><uri>http://FEEDuri/</uri></feed></feeds> etc..) and from this data, extract the FEED NAME & FEEDuri via regex.
My lecturer has provided a base method for us to work off, and I think I have implemented it correctly within my RESTful web service, and now I am implementing error handling.
I have successfully implemented error handling for the case where there is no data input by user. My question is this: **Based on the example method (below), is it possible to implement error handling for the case where the feed format input is incorrect**
eg: `< fed> FEED NAME < /fiid> < uro>http://FEEDuri< /pro>`The XML tags here are obviously incorrect.
**Will regex ONLY pull the group from the String IF it lies between the defined values passed as the arguement to the compile method?**
To supplement my question, here is the base method given to us to use (instead of an XML parser):
```
public static List<Feed> getFeedsFromXml(String xml) {
Pattern feedPattern = Pattern.compile("<feed>\\s*<name>\\s*([^<]*)</name>\\s*<uri>\\s*([^<]*)</uri>\\s*</feed>");
Matcher feedMatch = feedPattern.matcher(xml);
while (feedMatch.find()) {
String feedName = feedMatch.group(1);
String feedURI = feedMatch.group(2);
feeds.add(new Feed(feedName, feedURI));
}
return feeds;
}
``` | 2012/08/30 | ['https://Stackoverflow.com/questions/12207102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1603861/'] | There is nothing wrong with this, and you don't need to do anything about it.
In Python 2, a `str` is similar to a C string - it's just a sequence of bytes, sometimes incorrectly assumed to be ASCII text. It can contain *encoded* text, e.g. as UTF-8 or ASCII.
The `unicode` type represents an actual string of text, similar to a Java `String`. It is text in the abstract sense, not tied to a particular encoding. You can decode a `str` into `unicode`, or encode a `unicode` into a `str`.
JSON keys and values are strings - they are not byte arrays, but text - so they are represented by `unicode` objects in Python.
If you need JSON output for use in another language, use the `json` module to produce it from your dictionary:
```
>>> import json
>>> print json.dumps({u'words': [u'every', u'single', u'word']})
{"words": ["every", "single", "word"]}
``` | You should keep everything internal to python in unicode if there's any chance you will need it. Where python speaks to other programs, use `s.encode('UTF-8')` to make a regular string that you can write to a file or socket or whatever. Use `s.decode('UTF-8')` to convert a string from a file/socket back to unicode. (UTF-8 seems like a reasonable default, but use whatever your protocol specifies.) |
12,207,102 | I am currently working on a University assignment, and have a (most likely simple) question regarding regex / regular expressions.
To summarize; this assignment is a simple RSS feed manager, which uses JSP and a RESTful web service.
I am currently working on a section of the assignment spec which requires me to be able to input XML feed data (e.g. <feeds><feed><name>FEED NAME</name><uri>http://FEEDuri/</uri></feed></feeds> etc..) and from this data, extract the FEED NAME & FEEDuri via regex.
My lecturer has provided a base method for us to work off, and I think I have implemented it correctly within my RESTful web service, and now I am implementing error handling.
I have successfully implemented error handling for the case where there is no data input by user. My question is this: **Based on the example method (below), is it possible to implement error handling for the case where the feed format input is incorrect**
eg: `< fed> FEED NAME < /fiid> < uro>http://FEEDuri< /pro>`The XML tags here are obviously incorrect.
**Will regex ONLY pull the group from the String IF it lies between the defined values passed as the arguement to the compile method?**
To supplement my question, here is the base method given to us to use (instead of an XML parser):
```
public static List<Feed> getFeedsFromXml(String xml) {
Pattern feedPattern = Pattern.compile("<feed>\\s*<name>\\s*([^<]*)</name>\\s*<uri>\\s*([^<]*)</uri>\\s*</feed>");
Matcher feedMatch = feedPattern.matcher(xml);
while (feedMatch.find()) {
String feedName = feedMatch.group(1);
String feedURI = feedMatch.group(2);
feeds.add(new Feed(feedName, feedURI));
}
return feeds;
}
``` | 2012/08/30 | ['https://Stackoverflow.com/questions/12207102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1603861/'] | There is nothing wrong with this, and you don't need to do anything about it.
In Python 2, a `str` is similar to a C string - it's just a sequence of bytes, sometimes incorrectly assumed to be ASCII text. It can contain *encoded* text, e.g. as UTF-8 or ASCII.
The `unicode` type represents an actual string of text, similar to a Java `String`. It is text in the abstract sense, not tied to a particular encoding. You can decode a `str` into `unicode`, or encode a `unicode` into a `str`.
JSON keys and values are strings - they are not byte arrays, but text - so they are represented by `unicode` objects in Python.
If you need JSON output for use in another language, use the `json` module to produce it from your dictionary:
```
>>> import json
>>> print json.dumps({u'words': [u'every', u'single', u'word']})
{"words": ["every", "single", "word"]}
``` | It is preferable, yes, since JSON is defined to be unicode.
If you have more specific things that are causing you trouble you should share them, otherwise I'd recommend watching [Ned Batchelder's Intro](http://bit.ly/unipain) if you're just generally uncomfortable with Unicode (in Python in particular). I don't know what is causing this to be a nuisance to you, since I don't know what you're doing with this dict. |
40,956,103 | I want to stream multipart file directly to AWSS3 instead of saving file to disk at first. Receiving file of type \*multipart.FileHeader in my golang REST API. Now I want to stream this to AWSS3, using [s3manager](https://godoc.org/github.com/aws/aws-sdk-go/service/s3/s3manager) upload method where it's required to pass \*bytes.Reader in body param. I have seen an example of [uploading file to AWSS3](https://www.nicolasmerouze.com/file-upload-web-service-golang-s3-aws/), written in a way that opening a file **os.Open("filepath")** of type \*os.File from disk,getting \*bytes.Reader out of it and passing to AWSS3. Now I am struggling to convert this \*multipart.FileHeader to \*os.File. | 2016/12/04 | ['https://Stackoverflow.com/questions/40956103', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3943467/'] | Call [Open](https://golang.org/pkg/mime/multipart/#FileHeader.Open) on the `multipart.FileHeader`. It will return a `multipart.File` which will provide a reader to the file (which will be held in memory). | If you have multipart.File, then you can use next solution:
```golang
file, ok := multipartFile.(*os.File)
if !ok {
responseError(w, errors.New("invalid file", errors.InvalidArguments))
return
}
``` |
33,584 | The body (身) is only one inch (寸), which should mean "矮".
Throwing (委) the arrow (矢), which should mean "射".
What is wrong here? | 2019/04/12 | ['https://chinese.stackexchange.com/questions/33584', 'https://chinese.stackexchange.com', 'https://chinese.stackexchange.com/users/21202/'] | >
> **The body (身) is only one inch (寸), which should mean "矮".**
>
>
>
Here are some characters containing「寸」as a semantic component, directly as part of the immediate decomposition or secondarily as part of one of the decomposed components:
* 得導持尋付尊奪肘專耐
It should be clear that「寸」probably never means *inch* as part of other characters.「寸」is a depiction of a *hand with a mark around the wrist area*, and when it contributes *meaning* to a character, you should treat it as the same *meaning* as「手・扌」.
`[秦](https://en.wikipedia.org/wiki/Qin_dynasty)
[簡](https://en.wikipedia.org/wiki/Bamboo_and_wooden_slips)
[](https://i.stack.imgur.com/1cAnA.png)
[睡](https://en.wikipedia.org/wiki/Shuihudi_Qin_bamboo_texts)・[秦](http://xiaoxue.iis.sinica.edu.tw/yanbian/Reference/QinwenziReference)51``今
[楷](https://en.wikipedia.org/wiki/Regular_script)
[](https://i.stack.imgur.com/ZT10U.png)`
>
> * *The mark around the wrist area* is called「寸口」in the terminology of Traditional Chinese Medicine, and indicates the location where the *pulse* is taken.「寸」was later used as a *unit of length*, but it should be clear that this is not its original meaning.
>
>
> + Like most other character components, the stand-alone character「寸」developed a wildly different meaning from its role as a component in other characters.
> * Other components with the same *meaning* function as「手・扌」include「又」(*picture of a right hand*),「」(*picture of a left hand*), and「爪・爫」(*picture of a hand pointing downwards*).
>
>
>
The「身」part of「射」is a graphical corruption, from a merger between「弓」(*bow*) and「矢」(*arrow*):
`[商](https://en.wikipedia.org/wiki/Shang_dynasty)
[甲](https://en.wikipedia.org/wiki/Oracle_bone_script)
[](https://i.stack.imgur.com/pxx8h.png)
[乙](http://xiaoxue.iis.sinica.edu.tw/yanbian/Reference/JiaguwenReference)1290
[合集974](http://www.guoxuedashi.com/jgwhj/?bhfl=1&bh=974&jgwfl=)``[西周](https://en.wikipedia.org/wiki/Western_Zhou)
[金](https://en.wikipedia.org/wiki/Chinese_bronze_inscriptions)
[](https://i.stack.imgur.com/2uHwt.png)
靜簋
[集成4273](http://www.guoxuedashi.com/yzjwjc/?bh=4273&jgwfl=)``[東周](https://en.wikipedia.org/wiki/Eastern_Zhou)・[秦](https://en.wikipedia.org/wiki/Qin_(state))
[石鼓](https://en.wikipedia.org/wiki/Stone_Drums_of_Qin)
[](https://i.stack.imgur.com/XCJHS.png)``[秦朝](https://en.wikipedia.org/wiki/Qin_dynasty)
[簡](https://en.wikipedia.org/wiki/Bamboo_and_wooden_slips)
[](https://i.stack.imgur.com/QYqAs.png)
[睡・雜](http://xiaoxue.iis.sinica.edu.tw/yanbian/Reference/QinwenziReference)34``今
楷
[](https://i.stack.imgur.com/DqOUL.png)`
In the sequence above, Shape #1 is plainly a picture of a *bow and arrow*. Shape #2 adds a *hand*「又」, emphasising the *action* meaning in「射」. Shapes #3-4 show the corruption process of the *bow and arrow* into「身」. Shape #4 changes「又」into「寸」.
>
> A character with a similar structure to「射」is「發」([*Zhengzhang*](https://en.wikipedia.org/wiki/Reconstructions_of_Old_Chinese#Zhengzhang_(1981%E2%80%931995)) [OC](https://en.wikipedia.org/wiki/Old_Chinese): **/\*pad/**, *to shoot arrows > to emit > expand, develop*).「發」is comprised of phonetic「癶」(OC: **/\*paːd/**), semantic「弓」, and semantic「殳」(*hand holding a striking weapon*, emphasising an *attacking action*).
>
>
>
---
>
> **Throwing (委) the arrow (矢), which should mean "射".**
>
>
>
「矮」(*Zhengzhang* OC: **/\*qraːlʔ/**, *short stature*) is comprised of semantic「矢」and phonetic「委」(**/\*qrolʔ/**).
* 「矢」(*arrow [shaft]*) is being used as a *length* measurement here; you can view it as either the length of the arrow itself or a standardised distance for measuring archery prowess. In English, *yard*, *feet*, etc. were similar measures of length, taken from actual objects.
+ Compare some characters describing *length* or *measurement*: 短矩矬矱.
+ There are other characters that use「矢」for the meaning *arrow* rather than *length*, *measurement*.
* The sound development is **/\*qraːlʔ/** > [MC](https://en.wikipedia.org/wiki/Middle_Chinese): **/ʔˠɛX/, 烏蟹[切](https://en.wikipedia.org/wiki/Fanqie)** > Pinyin: **ǎi**.
---
**References:**
* 季旭昇《說文新證》
* [小學堂](http://xiaoxue.iis.sinica.edu.tw/)
* [國學大師](http://www.guoxuedashi.com/)
+ [郭沫若《甲骨文合集》](http://www.guoxuedashi.com/jgwhj/)
+ [中國社會科學院考古研究所《殷周金文集成》](http://www.guoxuedashi.com/yzjwjc/) | >
> 射 <http://www.zdic.net/z/18/xs/5C04.htm>
>
>
> [](https://i.stack.imgur.com/uzI2G.gif)
>
>
> (1) (本作“射”。会意。金文字形,象箭在弦上,手(寸)在发放。**小篆把弓矢形讹变成“身”字,误。** 本义:用弓发箭使中远处目标)
>
>
>
射 is a 会意字 (ideogrammic compound character)
The 寸 part in 射 was originally a pictograph of hand (手)
The 身 part in 射 was originally a pictograph of bow (弓) and arrow (矢), **it was mistakenly changed into 身 when the character evolved to 小篆 style**
>
> 矮 <http://www.zdic.net/z/1f/sw/77EE.htm>
>
>
> [](https://i.stack.imgur.com/DXMF6.gif)
>
>
> 短人也。从矢委聲
>
>
>
矮 is a 形声字 (phono-semantic compound character)
The 矢 part in 矮 was originally a pictograph of an arrow head, that represents short stature (arrow head is short compare to all other pointed weapon); the 委 part is the phonetic component of the character, it is there for the sound, and the actual meaning of 委 is irrelevant. |
33,584 | The body (身) is only one inch (寸), which should mean "矮".
Throwing (委) the arrow (矢), which should mean "射".
What is wrong here? | 2019/04/12 | ['https://chinese.stackexchange.com/questions/33584', 'https://chinese.stackexchange.com', 'https://chinese.stackexchange.com/users/21202/'] | >
> **The body (身) is only one inch (寸), which should mean "矮".**
>
>
>
Here are some characters containing「寸」as a semantic component, directly as part of the immediate decomposition or secondarily as part of one of the decomposed components:
* 得導持尋付尊奪肘專耐
It should be clear that「寸」probably never means *inch* as part of other characters.「寸」is a depiction of a *hand with a mark around the wrist area*, and when it contributes *meaning* to a character, you should treat it as the same *meaning* as「手・扌」.
`[秦](https://en.wikipedia.org/wiki/Qin_dynasty)
[簡](https://en.wikipedia.org/wiki/Bamboo_and_wooden_slips)
[](https://i.stack.imgur.com/1cAnA.png)
[睡](https://en.wikipedia.org/wiki/Shuihudi_Qin_bamboo_texts)・[秦](http://xiaoxue.iis.sinica.edu.tw/yanbian/Reference/QinwenziReference)51``今
[楷](https://en.wikipedia.org/wiki/Regular_script)
[](https://i.stack.imgur.com/ZT10U.png)`
>
> * *The mark around the wrist area* is called「寸口」in the terminology of Traditional Chinese Medicine, and indicates the location where the *pulse* is taken.「寸」was later used as a *unit of length*, but it should be clear that this is not its original meaning.
>
>
> + Like most other character components, the stand-alone character「寸」developed a wildly different meaning from its role as a component in other characters.
> * Other components with the same *meaning* function as「手・扌」include「又」(*picture of a right hand*),「」(*picture of a left hand*), and「爪・爫」(*picture of a hand pointing downwards*).
>
>
>
The「身」part of「射」is a graphical corruption, from a merger between「弓」(*bow*) and「矢」(*arrow*):
`[商](https://en.wikipedia.org/wiki/Shang_dynasty)
[甲](https://en.wikipedia.org/wiki/Oracle_bone_script)
[](https://i.stack.imgur.com/pxx8h.png)
[乙](http://xiaoxue.iis.sinica.edu.tw/yanbian/Reference/JiaguwenReference)1290
[合集974](http://www.guoxuedashi.com/jgwhj/?bhfl=1&bh=974&jgwfl=)``[西周](https://en.wikipedia.org/wiki/Western_Zhou)
[金](https://en.wikipedia.org/wiki/Chinese_bronze_inscriptions)
[](https://i.stack.imgur.com/2uHwt.png)
靜簋
[集成4273](http://www.guoxuedashi.com/yzjwjc/?bh=4273&jgwfl=)``[東周](https://en.wikipedia.org/wiki/Eastern_Zhou)・[秦](https://en.wikipedia.org/wiki/Qin_(state))
[石鼓](https://en.wikipedia.org/wiki/Stone_Drums_of_Qin)
[](https://i.stack.imgur.com/XCJHS.png)``[秦朝](https://en.wikipedia.org/wiki/Qin_dynasty)
[簡](https://en.wikipedia.org/wiki/Bamboo_and_wooden_slips)
[](https://i.stack.imgur.com/QYqAs.png)
[睡・雜](http://xiaoxue.iis.sinica.edu.tw/yanbian/Reference/QinwenziReference)34``今
楷
[](https://i.stack.imgur.com/DqOUL.png)`
In the sequence above, Shape #1 is plainly a picture of a *bow and arrow*. Shape #2 adds a *hand*「又」, emphasising the *action* meaning in「射」. Shapes #3-4 show the corruption process of the *bow and arrow* into「身」. Shape #4 changes「又」into「寸」.
>
> A character with a similar structure to「射」is「發」([*Zhengzhang*](https://en.wikipedia.org/wiki/Reconstructions_of_Old_Chinese#Zhengzhang_(1981%E2%80%931995)) [OC](https://en.wikipedia.org/wiki/Old_Chinese): **/\*pad/**, *to shoot arrows > to emit > expand, develop*).「發」is comprised of phonetic「癶」(OC: **/\*paːd/**), semantic「弓」, and semantic「殳」(*hand holding a striking weapon*, emphasising an *attacking action*).
>
>
>
---
>
> **Throwing (委) the arrow (矢), which should mean "射".**
>
>
>
「矮」(*Zhengzhang* OC: **/\*qraːlʔ/**, *short stature*) is comprised of semantic「矢」and phonetic「委」(**/\*qrolʔ/**).
* 「矢」(*arrow [shaft]*) is being used as a *length* measurement here; you can view it as either the length of the arrow itself or a standardised distance for measuring archery prowess. In English, *yard*, *feet*, etc. were similar measures of length, taken from actual objects.
+ Compare some characters describing *length* or *measurement*: 短矩矬矱.
+ There are other characters that use「矢」for the meaning *arrow* rather than *length*, *measurement*.
* The sound development is **/\*qraːlʔ/** > [MC](https://en.wikipedia.org/wiki/Middle_Chinese): **/ʔˠɛX/, 烏蟹[切](https://en.wikipedia.org/wiki/Fanqie)** > Pinyin: **ǎi**.
---
**References:**
* 季旭昇《說文新證》
* [小學堂](http://xiaoxue.iis.sinica.edu.tw/)
* [國學大師](http://www.guoxuedashi.com/)
+ [郭沫若《甲骨文合集》](http://www.guoxuedashi.com/jgwhj/)
+ [中國社會科學院考古研究所《殷周金文集成》](http://www.guoxuedashi.com/yzjwjc/) | Looking at modern forms of characters and trying to analyze them for their meaning doesn't always work out. If you are planning to go deeper into these studies you might want to try out [Outlier Linguistics](https://www.outlier-linguistics.com)' Dictionary. You can see their analysis of the two characters you're asking about below.
---
*Outlier*
**矮**
>
> **FORM**
>
> 矮 ǎi is composed of 委 wěi (also wēi) and 矢 “arrow,” hinting at the original meaning “to be of short stature.” 委 gives the sound.
>
>
> Reference
>
> 李學勤,2012《字源》,天津:天津古籍出版社,2013年7月2次印刷。p. 473
>
>
>
**射**
>
> **FORM**
>
> Ancient form:
>
> [](https://i.stack.imgur.com/HVZU0.png)
>
> 射 was originally a bow (弓) and arrow (矢) being drawn by a hand (寸), depicting the original meaning “to shoot an arrow.”
> Over time, 弓 and 矢 merged together and were corrupted into 身.
>
>
> Reference
>
> 李學勤,2012《字源》,天津:天津古籍出版社,2013年7月2次印刷。p. 471
>
>
>
---
Here is the original reference material outlier translated above:
《字源》
**矮**
>
> 形声字。从矢,委声。本义为身材短。《说文》:“矮,短人也。”
>
>
>
**射**
>
> shè 船纽、铎部;船纽、祃韵、神夜切。
>
> yè 喻纽、铎部;以纽、祃韵、羊谢切。
>
>
> 会意字。像矢(箭)在弓弦上将射发之形。《说文》:“䠶,弓弩发于身而中于远也,从矢,从身。”又说:“[](https://i.stack.imgur.com/pv2a2.png),篆文䠶,从寸。寸,法度也,亦手也。”商代文字偶见繁形,像一人两手拉弓射箭形。一般商周文字射字则省去“人”,只作弓上注箭形。西周文字或作一手(又)拉弓射箭形。战国文字“射”形变,“弓”、“矢”二者不再互相配合为象形字,而是相并立;“弓”不再用象形字,改为简省形并且成为偏旁;“矢”字倒书并加短横,或虽正书而形变较大。秦简中“弓”又被讹作“身”,“又”则被加一短画成为“寸”。汉代隶书显然受秦文字的影响而定型。射用做动词,义为射箭,多见于商代田猎卜辞。 《粹》 1018:“王其射鹿,(擒)。弗。”或指祭祀之射牲。《粹》314:“于且(祖)丁[]。于父己。于父甲。其射。”做名词用时, “射”指官名或射手。 《粹》15:“贞:令多射䢍。”西周金文“射”指射箭。长甶盉:“穆王鄉(饗)豊,即井(邢)白(伯)大祝射。”西周有“司射”之官。静簋:“王令静司射學宫。”静盖任“射人”官职。战国文字“射”字通“夜”,《包山楚简》 138有“坪射公”,“坪射”,地名,读为“平夜(舆)”。《春秋·桓公九年》“射姑”,《史记·鲁周公世家》作“夜姑”,可证。
>
>
> |
40,419,732 | I'm basically trying to call a function which is outside of my AJAX inside the AJAX success response.
To explain this better, this is what I have.
These are two functions:
```
function watchCurrentPosition() {
var positionTimer = navigator.geolocation.watchPosition(function(position) {
setMarkerPosition(userLocation, position);
map.panTo(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
});
}
function clearmyWatch() {
navigator.geolocation.clearWatch(positionTimer);
}
```
One of them keeps watching the users location and the other one 'should' stop it.
And this is how I'm calling the `clearmyWatch();` function inside the AJAX:
```
$.ajax({
type:"post",
url:"TEST.PHP",
datatype:"html",
success:function(data)
{
clearmyWatch();
}
});
```
However, this doesn't work and the `watchCurrentPosition();` constantly running and I also get an error in my console.
The error that I am getting is this:
```
ReferenceError: positionTimer is not defined
```
Could someone please advise on this issue?
Thanks in advance. | 2016/11/04 | ['https://Stackoverflow.com/questions/40419732', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4517577/'] | You need to define `positionTimer` at global level outside of `function watchCurrentPosition()` like:
```
var positionTimer = null;
function watchCurrentPosition() {
positionTimer = navigator.geolocation.watchPosition(function(position) {
setMarkerPosition(userLocation, position);
map.panTo(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
});
}
function clearmyWatch() {
if(positionTimer)
navigator.geolocation.clearWatch(positionTimer);
}
``` | `positionTimer` is local to `watchCurrentPosition`
**The better way to solve it without global variables is:**
```
function watchCurrentPosition() {
var positionTimer = navigator.geolocation.watchPosition(function(position) {
setMarkerPosition(userLocation, position);
map.panTo(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
});
clearmyWatch=()=>{
navigator.geolocation.clearWatch(positionTimer);
}
}
function clearmyWatch() {}
```
Explanation: `clearmyWatch` is defined in a way that it does nothing.However calling `watchCurrentPosition` sets `clearmyWatch` as an inner function of `watchCurrentPosition` that can get to `positionTimer`. Actually by setting `clearmyWatch` to an inner function of `watchCurrentPosition` we create a closure (read about it of you don't know what it is, it's important). |
61,356,244 | I'm developing a simple ecommerce store. Product information is stored in DynamoDB (NoSQL).
Items in Product table has an "image" attribute with a single URL, and also an "images" attribute which store multiple strings. I just added the "items" attribute to test if I can store multiple URLs (which point to images in S3 bucket)
In my function component, I get the data from Graphql API and set the state correctly. In my template I use `{image}` to render it. However if I try to use `{images[0]}` or `{images[1]}`, the page is not rendered and I got the following error: "images is undefined".
In React Developers Tools I can see the "images" variable correctly displaying 3 urls. The query to the API also works correctly.
Why does my app works correctly when using `{image}` but not when using `{images[0]}`?
[](https://i.stack.imgur.com/8RN22.jpg)
[](https://i.stack.imgur.com/a04p0.jpg) | 2020/04/22 | ['https://Stackoverflow.com/questions/61356244', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5041588/'] | You need to change,
```
{images[0]}
```
To,
```
{images && images[0] ? images[0] : null}
```
Reason for the above code is, the `images` array doesn't gets populated in template as it is async(as you are fetching from api).
So at initial stage it will be empty array and you are trying to access the first index value using, `images[0]` which is undefined.
So to wait for the data to get loaded, you could check the condition like,
**1)** Let us confirm we have `images` value first.
**2)** If the condition is met then proceed with `images[0]`.
**3)** If both condition is satisfied, then render `images[0]` until then keep it null.
Also the reason that `{image}` gets loaded without any error is, as it is a string, it checks the condition straight a way, so it only render if `{image}` has value which happens behind the scenes..
When you are trying to access the value from undefined, then you will get that error. | Looks like you are accessing the array before the data is populated.
You need to check the `loading` flag if you are using `react-apollo` query component. And if [loading](https://www.apollographql.com/docs/react/data/queries/#executing-a-query) is false then only you need to render your component.
Alternately you can try this
```
{images && Array.isArray(images) && images.length ? images[0] : null}
``` |
822,920 | I was trying to prove that a continuous function $f:[a,b]\to\Bbb{R}$ is integrable and thought that I came up with an easy solution so I checked the internet and here is a long proof: <https://proofwiki.org/wiki/Continuous_Function_is_Riemann_Integrable>. This makes me think that something is wrong with my argument:
We know that $f$ attains its maximum and minimum on $[a,b]$, call them $A$ and $B$ resp. Assume that $f$ is not constant so that $A\not=B$ (when $f$ is constant it is trivial to prove that $f$ is integrable). Let $\epsilon>0$. It suffices to find a partition such that $U(P)-L(P)<\epsilon$. This is true for a partition with mesh $<\epsilon/(A-B)$. Isn't it? | 2014/06/06 | ['https://math.stackexchange.com/questions/822920', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/155603/'] | No, this proof is not correct - there's not a nice connection between the size of the mesh and the difference in $y$-values. Let's look at a specific function, $y = \sqrt x$, on the interval $[0,1]$. Choose $\epsilon = .1$, so the proposed mesh size is $0.1$.
Looking at the interval partitioned as $[0, .1] \cup [.1, .2] \cup ... \cup [.9, 1]$, we have that the difference between the partitions is *at least* $\sqrt{.1} > .1$ - just look at the very first piece of the partition. | Consider $f\_c\colon[0,2\pi]\to\mathbb R$, $x\mapsto \sin cx$ where $c$ is some constant. For all $c\ge 1$m you will find $A=1$ and $B=-1$, so your proof suggests that $U(P)-L(P)<\epsilon$ as soon as the mesh is $\delta<\frac{\epsilon}{A-B}$ - no matter what $c$ is. But for suitable $c$ (namely $c>\frac{2\pi}\delta$), you will notice that $f$ assumes the values $A$ and $B$ also in each interval of length $\delta$, hence any such partition will sitll have $U(P)-L(P)\ge 4\pi$. |
822,920 | I was trying to prove that a continuous function $f:[a,b]\to\Bbb{R}$ is integrable and thought that I came up with an easy solution so I checked the internet and here is a long proof: <https://proofwiki.org/wiki/Continuous_Function_is_Riemann_Integrable>. This makes me think that something is wrong with my argument:
We know that $f$ attains its maximum and minimum on $[a,b]$, call them $A$ and $B$ resp. Assume that $f$ is not constant so that $A\not=B$ (when $f$ is constant it is trivial to prove that $f$ is integrable). Let $\epsilon>0$. It suffices to find a partition such that $U(P)-L(P)<\epsilon$. This is true for a partition with mesh $<\epsilon/(A-B)$. Isn't it? | 2014/06/06 | ['https://math.stackexchange.com/questions/822920', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/155603/'] | No, this proof is not correct - there's not a nice connection between the size of the mesh and the difference in $y$-values. Let's look at a specific function, $y = \sqrt x$, on the interval $[0,1]$. Choose $\epsilon = .1$, so the proposed mesh size is $0.1$.
Looking at the interval partitioned as $[0, .1] \cup [.1, .2] \cup ... \cup [.9, 1]$, we have that the difference between the partitions is *at least* $\sqrt{.1} > .1$ - just look at the very first piece of the partition. | Use the fact that a continuous function on a closed interval is uniformly continuous to find $\delta$ such that
$$|x-y| \leq \delta \rightarrow |f(x)-f(y)| \leq \frac{\epsilon}{b-a}$$ then $\delta$ is the size of the mesh. |
61,958,842 | I have a list of base files:
```
file1.txt
file2.txt
file3.txt
```
and a list of target files:
```
target1.txt
target2.txt
target3.txt
```
and I want to use bash to perform the following command using a loop:
```
grep -wf "file1.txt" "target1.txt" > "result1.txt"
grep -wf "file2.txt" "target2.txt" > "result2.txt"
```
The files will all have the same name besides the final integer, which will be in a series (1:22). | 2020/05/22 | ['https://Stackoverflow.com/questions/61958842', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13456823/'] | With a for loop:
```
for((i=1; i<=22; i++)); do
grep -wf "file$i.txt" "target$i.txt" > "result$i.txt"
done
``` | This is a one-line version suitable for the command line with brace expanion:
```
for i in {1..22};do grep -wf "file$i.txt" "target$i.txt" > "result$i.txt"; done
``` |
61,958,842 | I have a list of base files:
```
file1.txt
file2.txt
file3.txt
```
and a list of target files:
```
target1.txt
target2.txt
target3.txt
```
and I want to use bash to perform the following command using a loop:
```
grep -wf "file1.txt" "target1.txt" > "result1.txt"
grep -wf "file2.txt" "target2.txt" > "result2.txt"
```
The files will all have the same name besides the final integer, which will be in a series (1:22). | 2020/05/22 | ['https://Stackoverflow.com/questions/61958842', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13456823/'] | With a for loop:
```
for((i=1; i<=22; i++)); do
grep -wf "file$i.txt" "target$i.txt" > "result$i.txt"
done
``` | Do them all in parallel with **GNU Parallel**:
```
parallel 'grep -wf file{}.txt target{}.txt > result{}.txt' ::: {1..22}
``` |
61,958,842 | I have a list of base files:
```
file1.txt
file2.txt
file3.txt
```
and a list of target files:
```
target1.txt
target2.txt
target3.txt
```
and I want to use bash to perform the following command using a loop:
```
grep -wf "file1.txt" "target1.txt" > "result1.txt"
grep -wf "file2.txt" "target2.txt" > "result2.txt"
```
The files will all have the same name besides the final integer, which will be in a series (1:22). | 2020/05/22 | ['https://Stackoverflow.com/questions/61958842', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13456823/'] | With arbitrary number of `file#.txt` and `target#.txt`:
```sh
#!/usr/bin/env bash
shopt -s extglob # Enable extended globbing patterns
# Iterate all file#.txt
for f in file+([[:digit:]]).txt; do
# Extract the index from the file name by stripping-out all non digit characters
i="${f//[^[:digit:]]//}"
file="$f"
target="target$i.txt"
result="result$i.txt"
# If both file#.txt and target#.txt exists
if [ -e "$file" ] && [ -e "$target" ]; then
grep -wf "$file" "$target" >"$result"
fi
done
``` | This is a one-line version suitable for the command line with brace expanion:
```
for i in {1..22};do grep -wf "file$i.txt" "target$i.txt" > "result$i.txt"; done
``` |
61,958,842 | I have a list of base files:
```
file1.txt
file2.txt
file3.txt
```
and a list of target files:
```
target1.txt
target2.txt
target3.txt
```
and I want to use bash to perform the following command using a loop:
```
grep -wf "file1.txt" "target1.txt" > "result1.txt"
grep -wf "file2.txt" "target2.txt" > "result2.txt"
```
The files will all have the same name besides the final integer, which will be in a series (1:22). | 2020/05/22 | ['https://Stackoverflow.com/questions/61958842', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13456823/'] | With arbitrary number of `file#.txt` and `target#.txt`:
```sh
#!/usr/bin/env bash
shopt -s extglob # Enable extended globbing patterns
# Iterate all file#.txt
for f in file+([[:digit:]]).txt; do
# Extract the index from the file name by stripping-out all non digit characters
i="${f//[^[:digit:]]//}"
file="$f"
target="target$i.txt"
result="result$i.txt"
# If both file#.txt and target#.txt exists
if [ -e "$file" ] && [ -e "$target" ]; then
grep -wf "$file" "$target" >"$result"
fi
done
``` | Do them all in parallel with **GNU Parallel**:
```
parallel 'grep -wf file{}.txt target{}.txt > result{}.txt' ::: {1..22}
``` |
8,880 | 
I bought a Black Pearl Wax Apple tree to grow in the Bay Area in California. This fruit is popular in tropical areas of Asia, but it virtually impossible to find in supermarkets outside of Asia. I've scoured Google for how to grow Wax Apple, but could not find any useful information.
1. What kind of soil does it like?
2. Is it self-fruitful or do I need to cross-pollinate?
3. Does it like to be pruned?
4. Is it deciduous and can it withstand winters of 45 degrees Fahrenheit at night?
5. How much light does it prefer? | 2014/01/20 | ['https://gardening.stackexchange.com/questions/8880', 'https://gardening.stackexchange.com', 'https://gardening.stackexchange.com/users/2709/'] | From what I can see from my online research, it looks like you will need to find a way to give your wax apple tree more heat than it probably will be getting outside in the Bay Area, given that it's a tropical fruit and the Bay Area is more of a cool maritime climate. [Here is a gentleman in Southern California who, rather cleverly, warms his wax apple tree orchard by planting the trees in holes drilled into a cement or asphalt courtyard](http://www.latimes.com/food/la-fo-market-news-online-20130824-story.html), which is also surrounded by buildings that trap the day's warmth and reflect it back.
If you could find or make a nice warm "micro-climate" for your tree, that would help a lot. Otherwise, you are probably looking at constructing a small "greenhouse" of sorts to hold it and raise the temperatures up to where the tree will be able to grow properly. The tree can grow to 50 feet tall, so the greenhouse option would only help it get started while young and small, and would not be practical after that. Luckily, larger trees are often more tolerant of less than perfect conditions. Overall, I think finding or creating a warmer microclimate, such as planting the tree in a south-facing courtyard, is your best bet.
As for hardiness, it can withstand temps to freezing, but not for long periods. So a low temp of 45 in the winter should not be a problem. [The tree apparently can be pruned](http://books.google.com/books?id=cjHCoMQNkcgC&pg=PA555&lpg=PA555&dq=pruning%20Syzygium%20samarangense&source=bl&ots=u-WnbAZFUX&sig=DV-T-DzxBBcROZ5_105JEmKazpw&hl=en&sa=X&ei=UamtU9bXD5L-oQSTpICwBA&ved=0CEcQ6AEwAw#v=onepage&q=pruning%20Syzygium%20samarangense&f=false), but I would recommend against "bald cutting" or "pollarding" as it is harmful to the tree and unsightly as well. If you will scroll to the next page in the book page linked above, it actually has a fair bit of information on growing this species. | From the comment:
>
> I got a response from the seller. The English is not very good and it is not detailed. *"Hi no cross-pollinate. Winter need protect. Grown in 5g until 12 "high go the ground. Midday sun. Evergreen. any soil ok."*
>
>
>
Trying to decipher this.
>
> *Hi*
>
>
>
**A greeting. :)**
>
> *no cross-pollinate.*
>
>
>
**This species is self-pollinating.**
>
> *Winter need protect*.
>
>
>
**It may need winter protection in your area.**
>
> *Grown in 5g until 12 "high go the ground.*
>
>
>
**The plant should be in a five gallon pot until 12 inches tall, at which time it can be planted in the ground.**
>
> *Midday sun.*
>
>
>
**The plant needs a full day of sun.**
>
> *Evergreen.*
>
>
>
**This plant is evergreen. If the leaves fall, you have a problem.**
>
> *any soil ok.*
>
>
>
**This plant does not have special soil requirements, and any healthy soil is fine.**
I would trust this information, because, as a grower, they know the best methods of growing a healthy looking plant (so people will buy it). |
8,880 | 
I bought a Black Pearl Wax Apple tree to grow in the Bay Area in California. This fruit is popular in tropical areas of Asia, but it virtually impossible to find in supermarkets outside of Asia. I've scoured Google for how to grow Wax Apple, but could not find any useful information.
1. What kind of soil does it like?
2. Is it self-fruitful or do I need to cross-pollinate?
3. Does it like to be pruned?
4. Is it deciduous and can it withstand winters of 45 degrees Fahrenheit at night?
5. How much light does it prefer? | 2014/01/20 | ['https://gardening.stackexchange.com/questions/8880', 'https://gardening.stackexchange.com', 'https://gardening.stackexchange.com/users/2709/'] | From what I can see from my online research, it looks like you will need to find a way to give your wax apple tree more heat than it probably will be getting outside in the Bay Area, given that it's a tropical fruit and the Bay Area is more of a cool maritime climate. [Here is a gentleman in Southern California who, rather cleverly, warms his wax apple tree orchard by planting the trees in holes drilled into a cement or asphalt courtyard](http://www.latimes.com/food/la-fo-market-news-online-20130824-story.html), which is also surrounded by buildings that trap the day's warmth and reflect it back.
If you could find or make a nice warm "micro-climate" for your tree, that would help a lot. Otherwise, you are probably looking at constructing a small "greenhouse" of sorts to hold it and raise the temperatures up to where the tree will be able to grow properly. The tree can grow to 50 feet tall, so the greenhouse option would only help it get started while young and small, and would not be practical after that. Luckily, larger trees are often more tolerant of less than perfect conditions. Overall, I think finding or creating a warmer microclimate, such as planting the tree in a south-facing courtyard, is your best bet.
As for hardiness, it can withstand temps to freezing, but not for long periods. So a low temp of 45 in the winter should not be a problem. [The tree apparently can be pruned](http://books.google.com/books?id=cjHCoMQNkcgC&pg=PA555&lpg=PA555&dq=pruning%20Syzygium%20samarangense&source=bl&ots=u-WnbAZFUX&sig=DV-T-DzxBBcROZ5_105JEmKazpw&hl=en&sa=X&ei=UamtU9bXD5L-oQSTpICwBA&ved=0CEcQ6AEwAw#v=onepage&q=pruning%20Syzygium%20samarangense&f=false), but I would recommend against "bald cutting" or "pollarding" as it is harmful to the tree and unsightly as well. If you will scroll to the next page in the book page linked above, it actually has a fair bit of information on growing this species. | The grower that says any healthy soil is ok, is not familiar with some of the productive but alkaline soils in the USA such as in the Imperial Valley. The wax apple trees grow well in the mountains around Palm springs at about 3000 feet, BUT you must treat the soil to get it slightly acidic to acidic (5.5 is a good target). |
8,880 | 
I bought a Black Pearl Wax Apple tree to grow in the Bay Area in California. This fruit is popular in tropical areas of Asia, but it virtually impossible to find in supermarkets outside of Asia. I've scoured Google for how to grow Wax Apple, but could not find any useful information.
1. What kind of soil does it like?
2. Is it self-fruitful or do I need to cross-pollinate?
3. Does it like to be pruned?
4. Is it deciduous and can it withstand winters of 45 degrees Fahrenheit at night?
5. How much light does it prefer? | 2014/01/20 | ['https://gardening.stackexchange.com/questions/8880', 'https://gardening.stackexchange.com', 'https://gardening.stackexchange.com/users/2709/'] | From what I can see from my online research, it looks like you will need to find a way to give your wax apple tree more heat than it probably will be getting outside in the Bay Area, given that it's a tropical fruit and the Bay Area is more of a cool maritime climate. [Here is a gentleman in Southern California who, rather cleverly, warms his wax apple tree orchard by planting the trees in holes drilled into a cement or asphalt courtyard](http://www.latimes.com/food/la-fo-market-news-online-20130824-story.html), which is also surrounded by buildings that trap the day's warmth and reflect it back.
If you could find or make a nice warm "micro-climate" for your tree, that would help a lot. Otherwise, you are probably looking at constructing a small "greenhouse" of sorts to hold it and raise the temperatures up to where the tree will be able to grow properly. The tree can grow to 50 feet tall, so the greenhouse option would only help it get started while young and small, and would not be practical after that. Luckily, larger trees are often more tolerant of less than perfect conditions. Overall, I think finding or creating a warmer microclimate, such as planting the tree in a south-facing courtyard, is your best bet.
As for hardiness, it can withstand temps to freezing, but not for long periods. So a low temp of 45 in the winter should not be a problem. [The tree apparently can be pruned](http://books.google.com/books?id=cjHCoMQNkcgC&pg=PA555&lpg=PA555&dq=pruning%20Syzygium%20samarangense&source=bl&ots=u-WnbAZFUX&sig=DV-T-DzxBBcROZ5_105JEmKazpw&hl=en&sa=X&ei=UamtU9bXD5L-oQSTpICwBA&ved=0CEcQ6AEwAw#v=onepage&q=pruning%20Syzygium%20samarangense&f=false), but I would recommend against "bald cutting" or "pollarding" as it is harmful to the tree and unsightly as well. If you will scroll to the next page in the book page linked above, it actually has a fair bit of information on growing this species. | I live in the Caribbean where there is only a rainy and dry season. Temperatures range from low 60’s to 80’s.
I was given 2 cuttings of the Java apple branch. I kept them in water and they grew roots after about 2 months. I planted one in a concrete pot out in a very windy but full Sun location and the other in a mostly shaded with afternoon speckled sun & almost no wind. The soil was from my compost. I have watered them once a week with tap water which is 9 PH, very alkaline. The one out in full Sun and high wind has not grown at even half the rate of the shaded one, which now (1 year from planting) is starting to bloom.
In terms of soil and water PH this plant seems to be very adaptable. It definitely needs heat being a tropical plant. It seems to be able to grow well in full Sun or part shade but definitely does not like high winds. It can also be dwarfed as mine are both in 4 gallon pots and look healthy. I hope this helps. |
8,880 | 
I bought a Black Pearl Wax Apple tree to grow in the Bay Area in California. This fruit is popular in tropical areas of Asia, but it virtually impossible to find in supermarkets outside of Asia. I've scoured Google for how to grow Wax Apple, but could not find any useful information.
1. What kind of soil does it like?
2. Is it self-fruitful or do I need to cross-pollinate?
3. Does it like to be pruned?
4. Is it deciduous and can it withstand winters of 45 degrees Fahrenheit at night?
5. How much light does it prefer? | 2014/01/20 | ['https://gardening.stackexchange.com/questions/8880', 'https://gardening.stackexchange.com', 'https://gardening.stackexchange.com/users/2709/'] | I grow Wax Jambu in the Bay Area. They freeze outside in the winter, so I grow mine as a house plant in the sunniest window at my house. It does great. A big crop of fruit every year. You don't want to let it dry out too much. Down in Southern California, I've seen them thrive outdoors (in San Diego), but I don't think it will work so well outdoors in the Bay Area, unless you live in a microclimate that is especially warm. It doesn't get too big in the pot indoors. I think indoors, and in a 5 gallon, or so, container, it will stay smallish. Yet it has grown nearly to the ceiling in just a few years. We'll see what happens in the future. | From the comment:
>
> I got a response from the seller. The English is not very good and it is not detailed. *"Hi no cross-pollinate. Winter need protect. Grown in 5g until 12 "high go the ground. Midday sun. Evergreen. any soil ok."*
>
>
>
Trying to decipher this.
>
> *Hi*
>
>
>
**A greeting. :)**
>
> *no cross-pollinate.*
>
>
>
**This species is self-pollinating.**
>
> *Winter need protect*.
>
>
>
**It may need winter protection in your area.**
>
> *Grown in 5g until 12 "high go the ground.*
>
>
>
**The plant should be in a five gallon pot until 12 inches tall, at which time it can be planted in the ground.**
>
> *Midday sun.*
>
>
>
**The plant needs a full day of sun.**
>
> *Evergreen.*
>
>
>
**This plant is evergreen. If the leaves fall, you have a problem.**
>
> *any soil ok.*
>
>
>
**This plant does not have special soil requirements, and any healthy soil is fine.**
I would trust this information, because, as a grower, they know the best methods of growing a healthy looking plant (so people will buy it). |
8,880 | 
I bought a Black Pearl Wax Apple tree to grow in the Bay Area in California. This fruit is popular in tropical areas of Asia, but it virtually impossible to find in supermarkets outside of Asia. I've scoured Google for how to grow Wax Apple, but could not find any useful information.
1. What kind of soil does it like?
2. Is it self-fruitful or do I need to cross-pollinate?
3. Does it like to be pruned?
4. Is it deciduous and can it withstand winters of 45 degrees Fahrenheit at night?
5. How much light does it prefer? | 2014/01/20 | ['https://gardening.stackexchange.com/questions/8880', 'https://gardening.stackexchange.com', 'https://gardening.stackexchange.com/users/2709/'] | I grow Wax Jambu in the Bay Area. They freeze outside in the winter, so I grow mine as a house plant in the sunniest window at my house. It does great. A big crop of fruit every year. You don't want to let it dry out too much. Down in Southern California, I've seen them thrive outdoors (in San Diego), but I don't think it will work so well outdoors in the Bay Area, unless you live in a microclimate that is especially warm. It doesn't get too big in the pot indoors. I think indoors, and in a 5 gallon, or so, container, it will stay smallish. Yet it has grown nearly to the ceiling in just a few years. We'll see what happens in the future. | The grower that says any healthy soil is ok, is not familiar with some of the productive but alkaline soils in the USA such as in the Imperial Valley. The wax apple trees grow well in the mountains around Palm springs at about 3000 feet, BUT you must treat the soil to get it slightly acidic to acidic (5.5 is a good target). |
8,880 | 
I bought a Black Pearl Wax Apple tree to grow in the Bay Area in California. This fruit is popular in tropical areas of Asia, but it virtually impossible to find in supermarkets outside of Asia. I've scoured Google for how to grow Wax Apple, but could not find any useful information.
1. What kind of soil does it like?
2. Is it self-fruitful or do I need to cross-pollinate?
3. Does it like to be pruned?
4. Is it deciduous and can it withstand winters of 45 degrees Fahrenheit at night?
5. How much light does it prefer? | 2014/01/20 | ['https://gardening.stackexchange.com/questions/8880', 'https://gardening.stackexchange.com', 'https://gardening.stackexchange.com/users/2709/'] | I grow Wax Jambu in the Bay Area. They freeze outside in the winter, so I grow mine as a house plant in the sunniest window at my house. It does great. A big crop of fruit every year. You don't want to let it dry out too much. Down in Southern California, I've seen them thrive outdoors (in San Diego), but I don't think it will work so well outdoors in the Bay Area, unless you live in a microclimate that is especially warm. It doesn't get too big in the pot indoors. I think indoors, and in a 5 gallon, or so, container, it will stay smallish. Yet it has grown nearly to the ceiling in just a few years. We'll see what happens in the future. | I live in the Caribbean where there is only a rainy and dry season. Temperatures range from low 60’s to 80’s.
I was given 2 cuttings of the Java apple branch. I kept them in water and they grew roots after about 2 months. I planted one in a concrete pot out in a very windy but full Sun location and the other in a mostly shaded with afternoon speckled sun & almost no wind. The soil was from my compost. I have watered them once a week with tap water which is 9 PH, very alkaline. The one out in full Sun and high wind has not grown at even half the rate of the shaded one, which now (1 year from planting) is starting to bloom.
In terms of soil and water PH this plant seems to be very adaptable. It definitely needs heat being a tropical plant. It seems to be able to grow well in full Sun or part shade but definitely does not like high winds. It can also be dwarfed as mine are both in 4 gallon pots and look healthy. I hope this helps. |
7,560 | I just read the following sentence
>
> Les voisins habitent dans la maison d'à côté
>
>
>
I couldn't understand why “maison” has been used in singular. Could you point out some rules with regard to plural formation?
Also, how would you say (in the sense of definition of neighbours) "Neighbours live in houses close by/next to each other" altering the above sentence minimally (just to understand the nuances). | 2013/09/18 | ['https://french.stackexchange.com/questions/7560', 'https://french.stackexchange.com', 'https://french.stackexchange.com/users/1743/'] | Here, "les voisins" refers to a family, not to multiple separate neighbors living in separate houses, hence the singular. | Answering the second part of your question:
>
> Les voisins habitent dans des maisons proches les unes des autres.
>
>
> |
12,195,583 | I have an application which redirect `System.out` for example;
```
System.setOut(new PrintStream(System.out){
@Override
public void print(String string)
{
//TODO: find out who sent the print before processing string
}
});
```
I want to be able to determine which class is sending the call to print to stdout? I think this is not possible, but cannot fully conclude unless `SO` say so. | 2012/08/30 | ['https://Stackoverflow.com/questions/12195583', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/340390/'] | Get the [stacktrace](http://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#getStackTrace%28%29) and find the class name from the currect index.
```
StackTraceElement[] trace = Thread.currentThread().getStackTrace();
``` | You could throw an exception, and examine the stack trace. Obviously not great for production code. |
12,195,583 | I have an application which redirect `System.out` for example;
```
System.setOut(new PrintStream(System.out){
@Override
public void print(String string)
{
//TODO: find out who sent the print before processing string
}
});
```
I want to be able to determine which class is sending the call to print to stdout? I think this is not possible, but cannot fully conclude unless `SO` say so. | 2012/08/30 | ['https://Stackoverflow.com/questions/12195583', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/340390/'] | You could throw an exception, and examine the stack trace. Obviously not great for production code. | There are a number of ways: SecurityManager might be the best. Check this post especially the second answer: [How do I find the caller of a method using stacktrace or reflection?](https://stackoverflow.com/questions/421280/in-java-how-do-i-find-the-caller-of-a-method-using-stacktrace-or-reflection) |
12,195,583 | I have an application which redirect `System.out` for example;
```
System.setOut(new PrintStream(System.out){
@Override
public void print(String string)
{
//TODO: find out who sent the print before processing string
}
});
```
I want to be able to determine which class is sending the call to print to stdout? I think this is not possible, but cannot fully conclude unless `SO` say so. | 2012/08/30 | ['https://Stackoverflow.com/questions/12195583', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/340390/'] | If you have a recent version of HotSpot or OpenJDK you can use `Reflection.getCallerClass(2 or 3)` This is more efficient than generating a full stack trace but not portable.
Otherwise, the most efficient way to get the stack trace is
```
StackTraceElement[] stes = Thread.currentThread.getStackTrace();
```
This avoid creating an Exception or Throwable. | You could throw an exception, and examine the stack trace. Obviously not great for production code. |
12,195,583 | I have an application which redirect `System.out` for example;
```
System.setOut(new PrintStream(System.out){
@Override
public void print(String string)
{
//TODO: find out who sent the print before processing string
}
});
```
I want to be able to determine which class is sending the call to print to stdout? I think this is not possible, but cannot fully conclude unless `SO` say so. | 2012/08/30 | ['https://Stackoverflow.com/questions/12195583', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/340390/'] | Get the [stacktrace](http://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#getStackTrace%28%29) and find the class name from the currect index.
```
StackTraceElement[] trace = Thread.currentThread().getStackTrace();
``` | There are a number of ways: SecurityManager might be the best. Check this post especially the second answer: [How do I find the caller of a method using stacktrace or reflection?](https://stackoverflow.com/questions/421280/in-java-how-do-i-find-the-caller-of-a-method-using-stacktrace-or-reflection) |
12,195,583 | I have an application which redirect `System.out` for example;
```
System.setOut(new PrintStream(System.out){
@Override
public void print(String string)
{
//TODO: find out who sent the print before processing string
}
});
```
I want to be able to determine which class is sending the call to print to stdout? I think this is not possible, but cannot fully conclude unless `SO` say so. | 2012/08/30 | ['https://Stackoverflow.com/questions/12195583', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/340390/'] | If you have a recent version of HotSpot or OpenJDK you can use `Reflection.getCallerClass(2 or 3)` This is more efficient than generating a full stack trace but not portable.
Otherwise, the most efficient way to get the stack trace is
```
StackTraceElement[] stes = Thread.currentThread.getStackTrace();
```
This avoid creating an Exception or Throwable. | There are a number of ways: SecurityManager might be the best. Check this post especially the second answer: [How do I find the caller of a method using stacktrace or reflection?](https://stackoverflow.com/questions/421280/in-java-how-do-i-find-the-caller-of-a-method-using-stacktrace-or-reflection) |
68,807,437 | I have a list of strings consisting of integers, and I am trying to replace them with the sum of their digits. E.g. `nums = ["12","23","33"]` -> `nums = [3,5,6]`
Here is my code:
```
strng = ['12','23','33']
for i in range(len(strng)):
print(list((map(lambda x:int[x],list(strng[i])))))
```
For the above I am getting a `TypeError: 'type' object is not subscriptable`. It works up until map(), but when I add the list(map(...)), I get this error.
Any ideas how to fix it?
My after this is fixed, my idea is to do the following:
strng = ['12','23','33']
```
for i in range(len(strng)):
strng[i] = sum(list((map(lambda x:int[x],list(strng[i]))))))
```
Which should replace each of strng with the sum of its digits. | 2021/08/16 | ['https://Stackoverflow.com/questions/68807437', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16510721/'] | The error you're getting is you because you wrote `int[x]` instead of `int(x)`. However, there are some additional issues with your existing solution.
The short and pythonic solution to this problem would be:
```py
answer = [sum(map(int, list(s))) for s in strng]
```
To break this down:
1. `[... for s in strng]`: this is a [list comprehension](https://www.w3schools.com/python/python_lists_comprehension.asp)
2. `list(s)`: This takes each string and converts it into a list of str of each character, so `"123"` becomes `["1","2","3"]`
3. `map(int, list(s))`: This applys the int conversion to each element in `list(s)`, so `["1","2","3"]` becomes `[1,2,3]`
4. `sum(...)`: We take the sum of the resulting list of ints
The equivalent of the above using a normal for loop would be something like this:
```py
answer = []
for s in strng:
list_of_chars = list(s)
list_of_ints = map(int, list_of_chars)
sum_of_ints = sum(list_of_ints)
answer.append(sum_of_ints)
``` | You can use comprehension, and iterate each digits, convert them to integer, finally pass it to `sum` builtin to get sum of the values.
```py
>>> [sum(int(i) for i in v) for v in strng]
[3, 5, 6]
``` |
68,807,437 | I have a list of strings consisting of integers, and I am trying to replace them with the sum of their digits. E.g. `nums = ["12","23","33"]` -> `nums = [3,5,6]`
Here is my code:
```
strng = ['12','23','33']
for i in range(len(strng)):
print(list((map(lambda x:int[x],list(strng[i])))))
```
For the above I am getting a `TypeError: 'type' object is not subscriptable`. It works up until map(), but when I add the list(map(...)), I get this error.
Any ideas how to fix it?
My after this is fixed, my idea is to do the following:
strng = ['12','23','33']
```
for i in range(len(strng)):
strng[i] = sum(list((map(lambda x:int[x],list(strng[i]))))))
```
Which should replace each of strng with the sum of its digits. | 2021/08/16 | ['https://Stackoverflow.com/questions/68807437', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16510721/'] | The error you're getting is you because you wrote `int[x]` instead of `int(x)`. However, there are some additional issues with your existing solution.
The short and pythonic solution to this problem would be:
```py
answer = [sum(map(int, list(s))) for s in strng]
```
To break this down:
1. `[... for s in strng]`: this is a [list comprehension](https://www.w3schools.com/python/python_lists_comprehension.asp)
2. `list(s)`: This takes each string and converts it into a list of str of each character, so `"123"` becomes `["1","2","3"]`
3. `map(int, list(s))`: This applys the int conversion to each element in `list(s)`, so `["1","2","3"]` becomes `[1,2,3]`
4. `sum(...)`: We take the sum of the resulting list of ints
The equivalent of the above using a normal for loop would be something like this:
```py
answer = []
for s in strng:
list_of_chars = list(s)
list_of_ints = map(int, list_of_chars)
sum_of_ints = sum(list_of_ints)
answer.append(sum_of_ints)
``` | Not really efficient, but try this :
```
strng = ['12','23','33']
def function(strng) :
my_list = []
for string in strng :
my_list.append(0)
for digit in string :
my_list[-1] += int(digit)
return my_list
strng = function(strng)
print(strng)
``` |
68,807,437 | I have a list of strings consisting of integers, and I am trying to replace them with the sum of their digits. E.g. `nums = ["12","23","33"]` -> `nums = [3,5,6]`
Here is my code:
```
strng = ['12','23','33']
for i in range(len(strng)):
print(list((map(lambda x:int[x],list(strng[i])))))
```
For the above I am getting a `TypeError: 'type' object is not subscriptable`. It works up until map(), but when I add the list(map(...)), I get this error.
Any ideas how to fix it?
My after this is fixed, my idea is to do the following:
strng = ['12','23','33']
```
for i in range(len(strng)):
strng[i] = sum(list((map(lambda x:int[x],list(strng[i]))))))
```
Which should replace each of strng with the sum of its digits. | 2021/08/16 | ['https://Stackoverflow.com/questions/68807437', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16510721/'] | You can use comprehension, and iterate each digits, convert them to integer, finally pass it to `sum` builtin to get sum of the values.
```py
>>> [sum(int(i) for i in v) for v in strng]
[3, 5, 6]
``` | Not really efficient, but try this :
```
strng = ['12','23','33']
def function(strng) :
my_list = []
for string in strng :
my_list.append(0)
for digit in string :
my_list[-1] += int(digit)
return my_list
strng = function(strng)
print(strng)
``` |
4,891,251 | A C++ program I'm working on is using lua for configuration. It sets up several lua functions using a hardcoded script:
```
luaL_loadbuffer(pmLuaState, headerscript, strlen(headerscript), "header script");
```
It then loads the configuration lua file (that calls the previously mentioned functions):
```
luaL_loadfile(pmLuaState, filename)
```
Unfortunately, the Lua configuration file uses a global variable named type, so attempting to call the built-in type() function from my headerscript fails with a Lua error:
```
attempt to call global 'type' (a string value)
```
Due to the constraints of my scenario, I am unable to edit the offending config file. I'm wondering if there's a way to explicity state that I want to use the built-in type() function.
I'm new to Lua, so if there's a better way to load in these scripts that will avoid this global hiding issue, I'm open to it (but again, I cannot edit the config script).
Lua version: 5.1.4 | 2011/02/03 | ['https://Stackoverflow.com/questions/4891251', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/590988/'] | Your are missing a dot.
It should be `.GlobalStore` as long as this class resides in the package set in the package attribute on the manifest node.
So it should look like this.
```
<application android:icon="@drawable/icon"
android:label="@string/app_name"
android:name=".GlobalStore">
``` | ```
android:name="GlobalStore"
```
This needs to be the full path including your package. ie
```
android:name="com.example.GlobalStore"
```
or whatever your package name is. |
44,406,544 | Im still kind of new to scripts, but i know what im trying to do is not impossible. im trying to use a select option to show div's, I have it currently so it shows 1 div at a time currently but I cannot get it to show 2 separate divs at the same time. so for example im trying to select option 1, and to unhide the same selected options that were selected.
I tried what was suggested in "[Can an Option in a Select tag carry multiple values?](https://stackoverflow.com/questions/3245967/can-an-option-in-a-select-tag-carry-multiple-values)"
but none of it worked
```js
<script>
document
.getElementByValue('target')
.addEventListener('change', function () {
'use strict';
var vis = document.querySelector('.vis'),
target = document.getElementByValue(this.value);
if (vis !== null) {
vis.className = 'initial';
}
if (target !== null ) {
target.className = 'vis';
}
});
</script>
```
```html
<div class="header">
<select name="dropdown" id='target'>
<option value="temp1" value2="form1">option1</option>
<option value="temp2" value2="form2">option2</option>
</select>
</div>
<div class="temps">
<div id="temp1" class="initial"><?php include "temp1.php"; ?></div>
<div id="temp2" class="initial"><?php include "temp2.php"; ?></div>
</div>
<div class="forms">
<div id="form1" class="initial"><?php include "form1.php"; ?></div>
<div id="form2" class="initial"><?php include "form2.php"; ?></div>
</div>
``` | 2017/06/07 | ['https://Stackoverflow.com/questions/44406544', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8112511/'] | ```js
document.getElementById('target').addEventListener('change', function () {
let divs = document.querySelectorAll('.initial, .vis'); // grab all divs that have the class "initial" or "vis"
for (let i = 0; i < divs.length; i++) {
// loop over all divs
let div = divs[i];
if (div.classList.contains(this.value)) {
// the div's class list contains the value of the select box, e.g. "option-1" or "option-2"
div.classList.remove('initial');
div.classList.add('vis'); // make the div visible
} else {
div.classList.add('initial');
div.classList.remove('vis'); // otherwise make the divs invisible
}
}
});
```
```css
.initial {
display: none;
}
```
```html
<div class="header">
<select name="dropdown" id="target">
<option value="option-1">option1</option>
<option value="option-2">option2</option>
</select>
</div>
<div class="temps">
<div class="initial option-1">Temp 1</div>
<div class="initial option-2">Temp 2</div>
</div>
<div class="forms">
<div class="initial option-1">Form 1</div>
<div class="initial option-2">Form 2</div>
</div>
``` | your selector was wrong its `document.getElementById()` not a `document.getElementByValue` .And you are using `querySelectorAll()` its matching all the `.vis` class element ,so you need to iterate with `forEach` .And change the if condition with `vis.length>0`
```js
document.getElementById('target').addEventListener('change', function() {
var vis = document.querySelectorAll('.vis'),
target = document.getElementById(this.value);
if (vis.length > 0) {
vis.forEach(function(a) {
a.className = 'initial';
console.log(a.outerHTML)
})
}
if (target !== null) {
target.className = 'vis';
}
console.log(target.outerHTML)
});
```
```html
<div class="header">
<select name="dropdown" id='target'>
<option value="temp1" value2="form1">option1</option>
<option value="temp2" value2="form2">option2</option>
</select>
</div>
<div class="temps">
<div id="temp1" class="initial">
<?php include "temp1.php"; ?>
</div>
<div id="temp2" class="initial">
<?php include "temp2.php"; ?>
</div>
</div>
<div class="forms">
<div id="form1" class="initial">
<?php include "form1.php"; ?>
</div>
<div id="form2" class="initial">
<?php include "form2.php"; ?>
</div>
</div>
``` |
808 | >
> **Possible Duplicate:**
>
> [Community Promotion Ads - 2013](https://wordpress.meta.stackexchange.com/questions/1309/community-promotion-ads-2013)
>
>
>
A new year means, a new start of ads! And hopefully better schedule adherence. Which we're doing by switching to a yearly cycle anyway.
### What are Community Promotion Ads?
Community Promotion Ads are community-vetted advertisements that will show up on the main site, in the right sidebar. The purpose of this question is the vetting process. Users will provide images of the advertisements, and community voting will enable the advertisements to be shown.
### Why do we have Community Promotion Ads?
This is a method for the community to control what gets promoted to visitors on the site. For example, you might promote the following things:
* open source wordpress plugins
* the site's twitter account
* scripts packs or power tools
* cool events or conferences
* anything else your community would genuinely be interested in
The goal is for future visitors to find out about *the stuff your community deems important*. This also serves as a way to promote information and resources that are *relevant to your own community's interests*, both for those already in the community and those yet to join.
### How does it work?
The answers you post to this question *must* conform to the following rules, or they will be ignored.
1. All answers should be in the exact form of:
```
[![Tagline to show on mouseover][1]][2]
[1]: http://image-url
[2]: http://clickthrough-url
```
Please **do not add anything else to the body of the post**. If you want to discuss something, do it in the comments.
2. The question must always be tagged with the magic [community-ads](/questions/tagged/community-ads "show questions tagged 'community-ads'") tag.
### Image requirements
* The image that you create must be **220 x 250 pixels**
* Must be hosted through our standard image uploader (imgur)
* Must be GIF or PNG
* No animated GIFs
* Absolute limit on file size of 150 KB
### Score Threshold
There is a **minimum score threshold** an answer must meet (currently 6) before it will be shown on the main site.
You can check out the ads that have met the threshold with basic click stats [here](https://wordpress.meta.stackexchange.com/ads/display/808). | 2011/12/02 | ['https://wordpress.meta.stackexchange.com/questions/808', 'https://wordpress.meta.stackexchange.com', 'https://wordpress.meta.stackexchange.com/users/7667/'] | [](http://queryposts.com/) | [](http://twitter.com/stackwordpress) |
808 | >
> **Possible Duplicate:**
>
> [Community Promotion Ads - 2013](https://wordpress.meta.stackexchange.com/questions/1309/community-promotion-ads-2013)
>
>
>
A new year means, a new start of ads! And hopefully better schedule adherence. Which we're doing by switching to a yearly cycle anyway.
### What are Community Promotion Ads?
Community Promotion Ads are community-vetted advertisements that will show up on the main site, in the right sidebar. The purpose of this question is the vetting process. Users will provide images of the advertisements, and community voting will enable the advertisements to be shown.
### Why do we have Community Promotion Ads?
This is a method for the community to control what gets promoted to visitors on the site. For example, you might promote the following things:
* open source wordpress plugins
* the site's twitter account
* scripts packs or power tools
* cool events or conferences
* anything else your community would genuinely be interested in
The goal is for future visitors to find out about *the stuff your community deems important*. This also serves as a way to promote information and resources that are *relevant to your own community's interests*, both for those already in the community and those yet to join.
### How does it work?
The answers you post to this question *must* conform to the following rules, or they will be ignored.
1. All answers should be in the exact form of:
```
[![Tagline to show on mouseover][1]][2]
[1]: http://image-url
[2]: http://clickthrough-url
```
Please **do not add anything else to the body of the post**. If you want to discuss something, do it in the comments.
2. The question must always be tagged with the magic [community-ads](/questions/tagged/community-ads "show questions tagged 'community-ads'") tag.
### Image requirements
* The image that you create must be **220 x 250 pixels**
* Must be hosted through our standard image uploader (imgur)
* Must be GIF or PNG
* No animated GIFs
* Absolute limit on file size of 150 KB
### Score Threshold
There is a **minimum score threshold** an answer must meet (currently 6) before it will be shown on the main site.
You can check out the ads that have met the threshold with basic click stats [here](https://wordpress.meta.stackexchange.com/ads/display/808). | 2011/12/02 | ['https://wordpress.meta.stackexchange.com/questions/808', 'https://wordpress.meta.stackexchange.com', 'https://wordpress.meta.stackexchange.com/users/7667/'] | [](http://queryposts.com/) | [](http://www.webmasters.stackexchange.com/) |
177,529 | I've been asked to look into placing a firewall between a webserver (Debian/Apache/PHP) in the DMZ and a backend MySQL database to achieve "isolation". Right now, iptables is running on the MySQL server and is only permitting TCP 22 and 3306 for SSH and MySQL respectively. However, this is apparently not good enough, and a hardware firewall is recommended.
Looking at Cisco's ASA 5505 for example, the max. throughput is 150Mbps, which seems like quite a step down compared to the Gigabit throughput that the **Webserver and MySQL server enjoy now being on the same GbE switch**.
Is this a concern? I can't really give you any numbers right now, but say your typical form-driven, data entry CRUD webapp with perhaps 100 concurrent user sessions at any time.
If this is impossible to determine without any real throughput numbers, can anyone suggest any methods of measuring? I was thinking of grabbing JMeter, simulating some load, and measuring bandwidth on a port mirror of the MySQL interface (or perhaps on the MySQL server itself) with ntop.
EDIT:
I bolded the item about the Gigabit Ethernet, which should have a theoretical throughput of 125MB/s, whereas the Cisco 5505 has a max throughput of 150Mbps (or ~18MB/s) and that's not accounting for NAT or ACL parsing etc (although I can't see NAT or ACL parsing being a big deal for a one-node network). Even still, the firewall would definitely be a potential bottleneck between the webserver and the MySQL server, seeing as a good, RAID1 setup with high-quality SAS disks and other server components should at least be able to push 50-75MB/s. | 2010/09/02 | ['https://serverfault.com/questions/177529', 'https://serverfault.com', 'https://serverfault.com/users/43041/'] | I'm not quite sure where you're getting your max. throughput numbers because [Cisco's website](http://www.cisco.com/en/US/products/ps6120/prod_models_comparison.html) tells a different story (150Mbps).
It's a 100Mb ethernet connection and of course your real-world throughput will depend entirely on numerous factors, including what kind of filtering you have going on on the ASA. The advantage to having the ASA there is that you can add the AIP-SSC card and get intrusion prevention/detection also.
You could always try the ASA5505 from a vendor that allows returns. I can't speak to your throughput as I only have 5510s and 5520s. I use a 5505 personally from home and see no issues with throughput, but of course it's just me and my family. | The throughput of asa 5505 is 150 mbit/s.
I do not see the benefit security wise.
Probably decided by someone who does not know much about firewalling. |
177,529 | I've been asked to look into placing a firewall between a webserver (Debian/Apache/PHP) in the DMZ and a backend MySQL database to achieve "isolation". Right now, iptables is running on the MySQL server and is only permitting TCP 22 and 3306 for SSH and MySQL respectively. However, this is apparently not good enough, and a hardware firewall is recommended.
Looking at Cisco's ASA 5505 for example, the max. throughput is 150Mbps, which seems like quite a step down compared to the Gigabit throughput that the **Webserver and MySQL server enjoy now being on the same GbE switch**.
Is this a concern? I can't really give you any numbers right now, but say your typical form-driven, data entry CRUD webapp with perhaps 100 concurrent user sessions at any time.
If this is impossible to determine without any real throughput numbers, can anyone suggest any methods of measuring? I was thinking of grabbing JMeter, simulating some load, and measuring bandwidth on a port mirror of the MySQL interface (or perhaps on the MySQL server itself) with ntop.
EDIT:
I bolded the item about the Gigabit Ethernet, which should have a theoretical throughput of 125MB/s, whereas the Cisco 5505 has a max throughput of 150Mbps (or ~18MB/s) and that's not accounting for NAT or ACL parsing etc (although I can't see NAT or ACL parsing being a big deal for a one-node network). Even still, the firewall would definitely be a potential bottleneck between the webserver and the MySQL server, seeing as a good, RAID1 setup with high-quality SAS disks and other server components should at least be able to push 50-75MB/s. | 2010/09/02 | ['https://serverfault.com/questions/177529', 'https://serverfault.com', 'https://serverfault.com/users/43041/'] | What about two NICs on the webserver, one on the DMZ and one on the LAN?
Edit: Since the answer was accepted I am putting more details.
The webserver is necessarily public facing, the idea is to firewall that so only ports 80,443 are publicly accessible. Then internally it can communicate with the database server on a LAN interface. This also has the advantage to putting your public traffic on a separate interface from your internal traffic. This is a very common configuration and provides extra security because public traffic and internal traffic are **physically** separated, instead of relying on a firewall. | The throughput of asa 5505 is 150 mbit/s.
I do not see the benefit security wise.
Probably decided by someone who does not know much about firewalling. |
177,529 | I've been asked to look into placing a firewall between a webserver (Debian/Apache/PHP) in the DMZ and a backend MySQL database to achieve "isolation". Right now, iptables is running on the MySQL server and is only permitting TCP 22 and 3306 for SSH and MySQL respectively. However, this is apparently not good enough, and a hardware firewall is recommended.
Looking at Cisco's ASA 5505 for example, the max. throughput is 150Mbps, which seems like quite a step down compared to the Gigabit throughput that the **Webserver and MySQL server enjoy now being on the same GbE switch**.
Is this a concern? I can't really give you any numbers right now, but say your typical form-driven, data entry CRUD webapp with perhaps 100 concurrent user sessions at any time.
If this is impossible to determine without any real throughput numbers, can anyone suggest any methods of measuring? I was thinking of grabbing JMeter, simulating some load, and measuring bandwidth on a port mirror of the MySQL interface (or perhaps on the MySQL server itself) with ntop.
EDIT:
I bolded the item about the Gigabit Ethernet, which should have a theoretical throughput of 125MB/s, whereas the Cisco 5505 has a max throughput of 150Mbps (or ~18MB/s) and that's not accounting for NAT or ACL parsing etc (although I can't see NAT or ACL parsing being a big deal for a one-node network). Even still, the firewall would definitely be a potential bottleneck between the webserver and the MySQL server, seeing as a good, RAID1 setup with high-quality SAS disks and other server components should at least be able to push 50-75MB/s. | 2010/09/02 | ['https://serverfault.com/questions/177529', 'https://serverfault.com', 'https://serverfault.com/users/43041/'] | Yes, it would be a bottleneck, and if you want to handle 1Gbps linespeed, you will probably need a bigger firewall.
However, do you really need to run at 1Gbps today? It might be a future requirement, but if you are currently only really using, for example, 5Mbps, you'd still have plenty of capacity left for now.
On the switch that is connecting the SQL and web server, you could use something to retrieve the port utilisation status from the MIBs to see how much bandwidth you really need. We use Cacti at work as it was free, quick and easy to set up. We can monitor switchport utilisations when we anticipate/experience performance issues, and use the evidence to decide what to do next. | The throughput of asa 5505 is 150 mbit/s.
I do not see the benefit security wise.
Probably decided by someone who does not know much about firewalling. |
177,529 | I've been asked to look into placing a firewall between a webserver (Debian/Apache/PHP) in the DMZ and a backend MySQL database to achieve "isolation". Right now, iptables is running on the MySQL server and is only permitting TCP 22 and 3306 for SSH and MySQL respectively. However, this is apparently not good enough, and a hardware firewall is recommended.
Looking at Cisco's ASA 5505 for example, the max. throughput is 150Mbps, which seems like quite a step down compared to the Gigabit throughput that the **Webserver and MySQL server enjoy now being on the same GbE switch**.
Is this a concern? I can't really give you any numbers right now, but say your typical form-driven, data entry CRUD webapp with perhaps 100 concurrent user sessions at any time.
If this is impossible to determine without any real throughput numbers, can anyone suggest any methods of measuring? I was thinking of grabbing JMeter, simulating some load, and measuring bandwidth on a port mirror of the MySQL interface (or perhaps on the MySQL server itself) with ntop.
EDIT:
I bolded the item about the Gigabit Ethernet, which should have a theoretical throughput of 125MB/s, whereas the Cisco 5505 has a max throughput of 150Mbps (or ~18MB/s) and that's not accounting for NAT or ACL parsing etc (although I can't see NAT or ACL parsing being a big deal for a one-node network). Even still, the firewall would definitely be a potential bottleneck between the webserver and the MySQL server, seeing as a good, RAID1 setup with high-quality SAS disks and other server components should at least be able to push 50-75MB/s. | 2010/09/02 | ['https://serverfault.com/questions/177529', 'https://serverfault.com', 'https://serverfault.com/users/43041/'] | You're going to need to hook up some monitoring (there should be [munin](http://munin-monitoring.org/) packages that get it all going easy cheesy) and get an idea of what you really need.
If you find you really are pushing beyond 100Mbps then you're simply going to need a faster firewall (or even something like a couple OpenBSD boxes in failover with carp+pfsync). | The throughput of asa 5505 is 150 mbit/s.
I do not see the benefit security wise.
Probably decided by someone who does not know much about firewalling. |
177,529 | I've been asked to look into placing a firewall between a webserver (Debian/Apache/PHP) in the DMZ and a backend MySQL database to achieve "isolation". Right now, iptables is running on the MySQL server and is only permitting TCP 22 and 3306 for SSH and MySQL respectively. However, this is apparently not good enough, and a hardware firewall is recommended.
Looking at Cisco's ASA 5505 for example, the max. throughput is 150Mbps, which seems like quite a step down compared to the Gigabit throughput that the **Webserver and MySQL server enjoy now being on the same GbE switch**.
Is this a concern? I can't really give you any numbers right now, but say your typical form-driven, data entry CRUD webapp with perhaps 100 concurrent user sessions at any time.
If this is impossible to determine without any real throughput numbers, can anyone suggest any methods of measuring? I was thinking of grabbing JMeter, simulating some load, and measuring bandwidth on a port mirror of the MySQL interface (or perhaps on the MySQL server itself) with ntop.
EDIT:
I bolded the item about the Gigabit Ethernet, which should have a theoretical throughput of 125MB/s, whereas the Cisco 5505 has a max throughput of 150Mbps (or ~18MB/s) and that's not accounting for NAT or ACL parsing etc (although I can't see NAT or ACL parsing being a big deal for a one-node network). Even still, the firewall would definitely be a potential bottleneck between the webserver and the MySQL server, seeing as a good, RAID1 setup with high-quality SAS disks and other server components should at least be able to push 50-75MB/s. | 2010/09/02 | ['https://serverfault.com/questions/177529', 'https://serverfault.com', 'https://serverfault.com/users/43041/'] | What about two NICs on the webserver, one on the DMZ and one on the LAN?
Edit: Since the answer was accepted I am putting more details.
The webserver is necessarily public facing, the idea is to firewall that so only ports 80,443 are publicly accessible. Then internally it can communicate with the database server on a LAN interface. This also has the advantage to putting your public traffic on a separate interface from your internal traffic. This is a very common configuration and provides extra security because public traffic and internal traffic are **physically** separated, instead of relying on a firewall. | I'm not quite sure where you're getting your max. throughput numbers because [Cisco's website](http://www.cisco.com/en/US/products/ps6120/prod_models_comparison.html) tells a different story (150Mbps).
It's a 100Mb ethernet connection and of course your real-world throughput will depend entirely on numerous factors, including what kind of filtering you have going on on the ASA. The advantage to having the ASA there is that you can add the AIP-SSC card and get intrusion prevention/detection also.
You could always try the ASA5505 from a vendor that allows returns. I can't speak to your throughput as I only have 5510s and 5520s. I use a 5505 personally from home and see no issues with throughput, but of course it's just me and my family. |
177,529 | I've been asked to look into placing a firewall between a webserver (Debian/Apache/PHP) in the DMZ and a backend MySQL database to achieve "isolation". Right now, iptables is running on the MySQL server and is only permitting TCP 22 and 3306 for SSH and MySQL respectively. However, this is apparently not good enough, and a hardware firewall is recommended.
Looking at Cisco's ASA 5505 for example, the max. throughput is 150Mbps, which seems like quite a step down compared to the Gigabit throughput that the **Webserver and MySQL server enjoy now being on the same GbE switch**.
Is this a concern? I can't really give you any numbers right now, but say your typical form-driven, data entry CRUD webapp with perhaps 100 concurrent user sessions at any time.
If this is impossible to determine without any real throughput numbers, can anyone suggest any methods of measuring? I was thinking of grabbing JMeter, simulating some load, and measuring bandwidth on a port mirror of the MySQL interface (or perhaps on the MySQL server itself) with ntop.
EDIT:
I bolded the item about the Gigabit Ethernet, which should have a theoretical throughput of 125MB/s, whereas the Cisco 5505 has a max throughput of 150Mbps (or ~18MB/s) and that's not accounting for NAT or ACL parsing etc (although I can't see NAT or ACL parsing being a big deal for a one-node network). Even still, the firewall would definitely be a potential bottleneck between the webserver and the MySQL server, seeing as a good, RAID1 setup with high-quality SAS disks and other server components should at least be able to push 50-75MB/s. | 2010/09/02 | ['https://serverfault.com/questions/177529', 'https://serverfault.com', 'https://serverfault.com/users/43041/'] | I'm not quite sure where you're getting your max. throughput numbers because [Cisco's website](http://www.cisco.com/en/US/products/ps6120/prod_models_comparison.html) tells a different story (150Mbps).
It's a 100Mb ethernet connection and of course your real-world throughput will depend entirely on numerous factors, including what kind of filtering you have going on on the ASA. The advantage to having the ASA there is that you can add the AIP-SSC card and get intrusion prevention/detection also.
You could always try the ASA5505 from a vendor that allows returns. I can't speak to your throughput as I only have 5510s and 5520s. I use a 5505 personally from home and see no issues with throughput, but of course it's just me and my family. | You're going to need to hook up some monitoring (there should be [munin](http://munin-monitoring.org/) packages that get it all going easy cheesy) and get an idea of what you really need.
If you find you really are pushing beyond 100Mbps then you're simply going to need a faster firewall (or even something like a couple OpenBSD boxes in failover with carp+pfsync). |
177,529 | I've been asked to look into placing a firewall between a webserver (Debian/Apache/PHP) in the DMZ and a backend MySQL database to achieve "isolation". Right now, iptables is running on the MySQL server and is only permitting TCP 22 and 3306 for SSH and MySQL respectively. However, this is apparently not good enough, and a hardware firewall is recommended.
Looking at Cisco's ASA 5505 for example, the max. throughput is 150Mbps, which seems like quite a step down compared to the Gigabit throughput that the **Webserver and MySQL server enjoy now being on the same GbE switch**.
Is this a concern? I can't really give you any numbers right now, but say your typical form-driven, data entry CRUD webapp with perhaps 100 concurrent user sessions at any time.
If this is impossible to determine without any real throughput numbers, can anyone suggest any methods of measuring? I was thinking of grabbing JMeter, simulating some load, and measuring bandwidth on a port mirror of the MySQL interface (or perhaps on the MySQL server itself) with ntop.
EDIT:
I bolded the item about the Gigabit Ethernet, which should have a theoretical throughput of 125MB/s, whereas the Cisco 5505 has a max throughput of 150Mbps (or ~18MB/s) and that's not accounting for NAT or ACL parsing etc (although I can't see NAT or ACL parsing being a big deal for a one-node network). Even still, the firewall would definitely be a potential bottleneck between the webserver and the MySQL server, seeing as a good, RAID1 setup with high-quality SAS disks and other server components should at least be able to push 50-75MB/s. | 2010/09/02 | ['https://serverfault.com/questions/177529', 'https://serverfault.com', 'https://serverfault.com/users/43041/'] | What about two NICs on the webserver, one on the DMZ and one on the LAN?
Edit: Since the answer was accepted I am putting more details.
The webserver is necessarily public facing, the idea is to firewall that so only ports 80,443 are publicly accessible. Then internally it can communicate with the database server on a LAN interface. This also has the advantage to putting your public traffic on a separate interface from your internal traffic. This is a very common configuration and provides extra security because public traffic and internal traffic are **physically** separated, instead of relying on a firewall. | Yes, it would be a bottleneck, and if you want to handle 1Gbps linespeed, you will probably need a bigger firewall.
However, do you really need to run at 1Gbps today? It might be a future requirement, but if you are currently only really using, for example, 5Mbps, you'd still have plenty of capacity left for now.
On the switch that is connecting the SQL and web server, you could use something to retrieve the port utilisation status from the MIBs to see how much bandwidth you really need. We use Cacti at work as it was free, quick and easy to set up. We can monitor switchport utilisations when we anticipate/experience performance issues, and use the evidence to decide what to do next. |
177,529 | I've been asked to look into placing a firewall between a webserver (Debian/Apache/PHP) in the DMZ and a backend MySQL database to achieve "isolation". Right now, iptables is running on the MySQL server and is only permitting TCP 22 and 3306 for SSH and MySQL respectively. However, this is apparently not good enough, and a hardware firewall is recommended.
Looking at Cisco's ASA 5505 for example, the max. throughput is 150Mbps, which seems like quite a step down compared to the Gigabit throughput that the **Webserver and MySQL server enjoy now being on the same GbE switch**.
Is this a concern? I can't really give you any numbers right now, but say your typical form-driven, data entry CRUD webapp with perhaps 100 concurrent user sessions at any time.
If this is impossible to determine without any real throughput numbers, can anyone suggest any methods of measuring? I was thinking of grabbing JMeter, simulating some load, and measuring bandwidth on a port mirror of the MySQL interface (or perhaps on the MySQL server itself) with ntop.
EDIT:
I bolded the item about the Gigabit Ethernet, which should have a theoretical throughput of 125MB/s, whereas the Cisco 5505 has a max throughput of 150Mbps (or ~18MB/s) and that's not accounting for NAT or ACL parsing etc (although I can't see NAT or ACL parsing being a big deal for a one-node network). Even still, the firewall would definitely be a potential bottleneck between the webserver and the MySQL server, seeing as a good, RAID1 setup with high-quality SAS disks and other server components should at least be able to push 50-75MB/s. | 2010/09/02 | ['https://serverfault.com/questions/177529', 'https://serverfault.com', 'https://serverfault.com/users/43041/'] | What about two NICs on the webserver, one on the DMZ and one on the LAN?
Edit: Since the answer was accepted I am putting more details.
The webserver is necessarily public facing, the idea is to firewall that so only ports 80,443 are publicly accessible. Then internally it can communicate with the database server on a LAN interface. This also has the advantage to putting your public traffic on a separate interface from your internal traffic. This is a very common configuration and provides extra security because public traffic and internal traffic are **physically** separated, instead of relying on a firewall. | You're going to need to hook up some monitoring (there should be [munin](http://munin-monitoring.org/) packages that get it all going easy cheesy) and get an idea of what you really need.
If you find you really are pushing beyond 100Mbps then you're simply going to need a faster firewall (or even something like a couple OpenBSD boxes in failover with carp+pfsync). |
177,529 | I've been asked to look into placing a firewall between a webserver (Debian/Apache/PHP) in the DMZ and a backend MySQL database to achieve "isolation". Right now, iptables is running on the MySQL server and is only permitting TCP 22 and 3306 for SSH and MySQL respectively. However, this is apparently not good enough, and a hardware firewall is recommended.
Looking at Cisco's ASA 5505 for example, the max. throughput is 150Mbps, which seems like quite a step down compared to the Gigabit throughput that the **Webserver and MySQL server enjoy now being on the same GbE switch**.
Is this a concern? I can't really give you any numbers right now, but say your typical form-driven, data entry CRUD webapp with perhaps 100 concurrent user sessions at any time.
If this is impossible to determine without any real throughput numbers, can anyone suggest any methods of measuring? I was thinking of grabbing JMeter, simulating some load, and measuring bandwidth on a port mirror of the MySQL interface (or perhaps on the MySQL server itself) with ntop.
EDIT:
I bolded the item about the Gigabit Ethernet, which should have a theoretical throughput of 125MB/s, whereas the Cisco 5505 has a max throughput of 150Mbps (or ~18MB/s) and that's not accounting for NAT or ACL parsing etc (although I can't see NAT or ACL parsing being a big deal for a one-node network). Even still, the firewall would definitely be a potential bottleneck between the webserver and the MySQL server, seeing as a good, RAID1 setup with high-quality SAS disks and other server components should at least be able to push 50-75MB/s. | 2010/09/02 | ['https://serverfault.com/questions/177529', 'https://serverfault.com', 'https://serverfault.com/users/43041/'] | Yes, it would be a bottleneck, and if you want to handle 1Gbps linespeed, you will probably need a bigger firewall.
However, do you really need to run at 1Gbps today? It might be a future requirement, but if you are currently only really using, for example, 5Mbps, you'd still have plenty of capacity left for now.
On the switch that is connecting the SQL and web server, you could use something to retrieve the port utilisation status from the MIBs to see how much bandwidth you really need. We use Cacti at work as it was free, quick and easy to set up. We can monitor switchport utilisations when we anticipate/experience performance issues, and use the evidence to decide what to do next. | You're going to need to hook up some monitoring (there should be [munin](http://munin-monitoring.org/) packages that get it all going easy cheesy) and get an idea of what you really need.
If you find you really are pushing beyond 100Mbps then you're simply going to need a faster firewall (or even something like a couple OpenBSD boxes in failover with carp+pfsync). |
72,156,337 | This is my very first Rust program that actually has a purpose and I'm still lost with the syntax. So I have trait objects like these:
```
trait HC<'a> {
fn info(&self) -> TestInfo<'static>;
fn test(&self) -> HCResult<'a>;
}
#[allow(non_camel_case_types)]
struct Test_NTP;
impl<'a> HC<'a> for Test_NTP {
fn info(&self) -> TestInfo<'static> {
TestInfo { ... }
}
fn test(&self) -> HCResult<'a> {
...
}
}
#[allow(non_camel_case_types)]
struct Test_Last;
impl<'a> HC<'a> for Test_Last {
fn info(&self) -> TestInfo<'static> {
TestInfo { ... }
}
fn test(&self) -> HCResult<'a> {
...
}
}
```
I want to construct an array of these objects those define the HC trait, tupled with an ID, so I can iterate through them and call their `test()` functions.
```
const HC_TESTS: [(i16, &dyn HC)] = [
(1, &Test_NTP),
(2, &Test_Last)
];
```
I tried several variations, but I always get a "*doesn't have a size known at compile-time*" error. I thought putting the objects in Boxes would solve the problem, but I get the same error:
```
error[E0277]: the size for values of type `[(i16, Box<&'static (dyn HC<'static> + 'static)>)]` cannot be known at compilation time
--> src/hc.rs:125:17
|
125 | const HC_TESTS: [(i16, Box<&dyn HC>)] = [
| ^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
|
= help: the trait `Sized` is not implemented for `[(i16, Box<&'static (dyn HC<'static> + 'static)>)]`
```
The structs don't have any fields, the only reason I use them is to bound the `info()` and `test()` functions together, and I don't even use `&self`, they're only needed to dispatch virtual methods. What am I doing wrong? | 2022/05/07 | ['https://Stackoverflow.com/questions/72156337', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6774964/'] | Your syntax is off just slightly. The error
`the trait `Sized` is not implemented for `[(i16, Box<&'static (dyn HC<'static> + 'static)>)]`
refers to the most outer `[...]`, which is a `slice`.
In
`const HC_TESTS: [(i16, Box<&dyn HC>)] =`
you explicitly set the type of `HC_TESTS` to be a `slice`, not an `array`. A slice is always unsized, so the compiler complains. What you want is simply
`const HC_TESTS: [(i16, Box<&dyn HC>); 2] =`
which sets the type of `HC_TESTS` to be an `array` of exactly two elements.
Notice that the other answers and comments here ("works for me") use this syntax as well. | ~~Your problem is that you cannot use `&`~~ ([you actually can](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=71f8cd8bebff8ce9aedf41eaa604786f), the problem is that you didn't actually set the **array length** `[(i16, &dyn HC); 2]`).
Also you could have use `Box`. But since `Box::new` is not `const`, you would need to wrap it in some other lazy wrapper, `std::lazy::Lazy` is not stable jet but would work:
```rust
const HC_TESTS: Lazy<[(i16, Box<dyn HC>); 2]> = Lazy::new(|| [
(1, Box::new(Test_NTP)),
(2, Box::new(Test_Last))
]);
```
[Playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=ae3aa8adbea043207467759d6564160e)
Meanwhile you can use [`once_cell`](https://docs.rs/once_cell/latest/once_cell/index.html) [`Lazy`](https://docs.rs/once_cell/latest/once_cell/unsync/struct.Lazy.html), which works the same.
Another option is to wrap all of them in a `enum`, so you can construct them, and impl the trait for that enum so you can use it later:
```rust
enum Tests {
NTP(Test_NTP),
Last(Test_Last)
}
impl<'a> HC<'a> for Tests {
fn info(&self) -> TestInfo<'static> {
match self {
Self::NTP(e) => e.info(),
Self::Last(e) => e.info()
}
}
fn test(&self) -> HCResult<'a> {
match self {
Self::NTP(e) => e.test(),
Self::Last(e) => e.test()
}
}
}
const HC_TESTS: [(i16, Tests); 2] = [
(1, Tests::NTP(Test_NTP)),
(2, Tests::Last(Test_Last))
];
```
[Playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=0b48091daeb64ba6d80fbdcd5b38a8a5) |
8,150 | WE tried to unpublish a page from the CME in Tridion 2013 & it was marked successful. However, the unpublish was not successful because the page is still in the Broker DB. How do we get rid of the page? How do we diagnose issues like this? We looked through the Deployer logs & did not see any error related to that page.
**UPDATE**
For the record, I followed the steps listed in [this](http://tridion.kb.sdl.com/#tab:homeTab:crumb:7:artId:5315) kb article. Make sure to hit the appropriate HTTPUpload.aspx page so that the package is picked up. That worked. | 2014/10/15 | ['https://tridion.stackexchange.com/questions/8150', 'https://tridion.stackexchange.com', 'https://tridion.stackexchange.com/users/109/'] | With regards to your question about diagnosing this type of error, I would probably go through the following:
1. When you un-publish the Page, check that the (un)publish package is arriving in the `incoming` folder on the expected Deployer server correctly.
2. Check that the database connection string, and other `Storage` settings in the Deployer's `cd_storage_conf.xml` file are correct
3. Double-check that the database that you are querying is definitely the correct one. I've been known in the past to be looking at the wrong Broker database (e.g Staging instead of Live), or in the wrong environment (e.g. UAT instead of Prod) even.
4. Determine whether the `cd_storage_conf.xml` file settings could have changed recently. For example, were Pages previously stored in the database, and now they're stored on the file system?
5. Double-check that the Page you are seeing in the database is definitely the one that you have unpublished. I've been caught out in the past with **not** checking the Publication Id of an item, and it has actually been published from a child or parent Publication.
6. Increase the logging level of the Deployer in the **logback.xml** file, restart the Deployer and check in the logs for anything unusual.
7. Confirm that the instruction to unpublish the Page is definitely in the (un)publish package that lands in the Deployer's `incoming` folder. This could be caused, for example, by a Custom Resolver that prevents certain pages from being unpublished. (I've seen Custom Resolvers in the past that prevent the homepage from being un-published).
8. If none of the above work, you could run a SQL Trace on the Broker database to ensure that a SQL query to remove the offending records is run
9. Failing that, I'd suggest that you log a case with Tridion Support. | This is one of those annoying issues where the CM and the CD DBs are out of sync for an item. I believe this was addressed sometime in the 2011 SP1 release, but it looks like you're still experiencing it.
There are two ways I've dealt with this:
1. Submit a support ticket, they'll give you a SQL script to run on your CM DB to force set the page to "unpublished". You can then republish it and all is dandy.
2. Force set the page to unpublished via the CM DB yourself. Note: this risks voiding the warranty if you mess anything up. I do this in my own sandbox VM all the time, but there is no risk there. Consider yourself warned. Here is how: update the STATE column for your Page's (REFERENCE\_ID = page ID) record to 0. Back in 2011 there was another table with this status that needed updating, but I don't see any other "STATE" columns in the DB in 2013. |
8,150 | WE tried to unpublish a page from the CME in Tridion 2013 & it was marked successful. However, the unpublish was not successful because the page is still in the Broker DB. How do we get rid of the page? How do we diagnose issues like this? We looked through the Deployer logs & did not see any error related to that page.
**UPDATE**
For the record, I followed the steps listed in [this](http://tridion.kb.sdl.com/#tab:homeTab:crumb:7:artId:5315) kb article. Make sure to hit the appropriate HTTPUpload.aspx page so that the package is picked up. That worked. | 2014/10/15 | ['https://tridion.stackexchange.com/questions/8150', 'https://tridion.stackexchange.com', 'https://tridion.stackexchange.com/users/109/'] | Also, convince yourself the Structure Group the Page is in is marked 'Publishable'.
If this is not the case a Publish or Unpublish action will be 'Success' in the Queue, but nothing really happens. | This is one of those annoying issues where the CM and the CD DBs are out of sync for an item. I believe this was addressed sometime in the 2011 SP1 release, but it looks like you're still experiencing it.
There are two ways I've dealt with this:
1. Submit a support ticket, they'll give you a SQL script to run on your CM DB to force set the page to "unpublished". You can then republish it and all is dandy.
2. Force set the page to unpublished via the CM DB yourself. Note: this risks voiding the warranty if you mess anything up. I do this in my own sandbox VM all the time, but there is no risk there. Consider yourself warned. Here is how: update the STATE column for your Page's (REFERENCE\_ID = page ID) record to 0. Back in 2011 there was another table with this status that needed updating, but I don't see any other "STATE" columns in the DB in 2013. |
8,150 | WE tried to unpublish a page from the CME in Tridion 2013 & it was marked successful. However, the unpublish was not successful because the page is still in the Broker DB. How do we get rid of the page? How do we diagnose issues like this? We looked through the Deployer logs & did not see any error related to that page.
**UPDATE**
For the record, I followed the steps listed in [this](http://tridion.kb.sdl.com/#tab:homeTab:crumb:7:artId:5315) kb article. Make sure to hit the appropriate HTTPUpload.aspx page so that the package is picked up. That worked. | 2014/10/15 | ['https://tridion.stackexchange.com/questions/8150', 'https://tridion.stackexchange.com', 'https://tridion.stackexchange.com/users/109/'] | With regards to your question about diagnosing this type of error, I would probably go through the following:
1. When you un-publish the Page, check that the (un)publish package is arriving in the `incoming` folder on the expected Deployer server correctly.
2. Check that the database connection string, and other `Storage` settings in the Deployer's `cd_storage_conf.xml` file are correct
3. Double-check that the database that you are querying is definitely the correct one. I've been known in the past to be looking at the wrong Broker database (e.g Staging instead of Live), or in the wrong environment (e.g. UAT instead of Prod) even.
4. Determine whether the `cd_storage_conf.xml` file settings could have changed recently. For example, were Pages previously stored in the database, and now they're stored on the file system?
5. Double-check that the Page you are seeing in the database is definitely the one that you have unpublished. I've been caught out in the past with **not** checking the Publication Id of an item, and it has actually been published from a child or parent Publication.
6. Increase the logging level of the Deployer in the **logback.xml** file, restart the Deployer and check in the logs for anything unusual.
7. Confirm that the instruction to unpublish the Page is definitely in the (un)publish package that lands in the Deployer's `incoming` folder. This could be caused, for example, by a Custom Resolver that prevents certain pages from being unpublished. (I've seen Custom Resolvers in the past that prevent the homepage from being un-published).
8. If none of the above work, you could run a SQL Trace on the Broker database to ensure that a SQL query to remove the offending records is run
9. Failing that, I'd suggest that you log a case with Tridion Support. | Also, convince yourself the Structure Group the Page is in is marked 'Publishable'.
If this is not the case a Publish or Unpublish action will be 'Success' in the Queue, but nothing really happens. |
168,033 | I see lots of mentions of this option on Android sites, [including Android.StackExchange.com](https://android.stackexchange.com/questions/116508/how-do-you-enable-hotspot-wifi-sharing-on-nexus-5-android-m-version-on-sprint-t), but I don't see any technical exploitation for what it does. What does this option actually do? | 2017/01/30 | ['https://android.stackexchange.com/questions/168033', 'https://android.stackexchange.com', 'https://android.stackexchange.com/users/7425/'] | Tells telephony manager dial up networking emulation not required, not sure if thats actually required if you use net.tethering.noprovisioning=true in build.prop you can see the telephony and tethering code in the links below
<https://android.googlesource.com/platform/frameworks/base/+/master/telephony/java/android/telephony/TelephonyManager.java>
<https://github.com/android/platform_frameworks_base/blob/355dbae680994002c48d7a66cb276a65393ecbbb/services/core/java/com/android/server/connectivity/Tethering.java> | Not exactly sure what it does, but a lot of people seem tho think this in `adb shell` gets them free tethering.
```
su
settings put global tether_dun_required 0
exit
``` |
26,530,261 | I have a checkbox and i want to make my checkbox checked by default, if the user unchecks the checkbox and save the form, i need the checkbox to be unchecked while retrieving or editing the form data.
**My view page**
```
<div class="form-group {{ $errors->has('active') ? 'error' : '' }}">
<label for="active" class="col-md-3 control-label">@lang('admin/assetdetails/form.active')</label>
<div class="controls col-md-7">
{{ Form::checkbox('active', 1, Input::old('active', $assetdetail->active), array('class'=>'isnesdbox')) }}
{{ $errors->first('active', '<span class="alert-msg"><i class="icon-remove-sign"></i> :message</span>') }}
</div>
</div>
```
**Giving this brings back the old data from database correctly but i couldn't make my checkbox checked as default**
**Controller:**
```
public function postEdit($assetdetailId = null)
{
// Check if the location exists
if (is_null($assetdetail = Assetdetail::find($assetdetailId)))
{
// Redirect to the blogs management page
return Redirect::to('admin/settings/assetdetails')->with('error', Lang::get('admin/assetdetails/message.does_not_exist'));
}
// get the POST data
$new = Input::all();
// attempt validation
if ($assetdetail->validate($new))
{
// Update the location data
$assetdetail ->asset_number = e(Input::get('asset_number'));
$assetdetail ->location_id = e(Input::get('location_id'));
$assetdetail ->assign_to = e(Input::get('assign_to'));
$assetdetail ->asset_type_id = e(Input::get('asset_type_id'));
$assetdetail ->nesd = e(Input::get('nesd'));
$assetdetail ->active = e(Input::get('active'));
$assetdetail ->shift = e(Input::get('shift'));
$assetdetail ->supplier_name = e(Input::get('supplier_name'));
$assetdetail ->description = e(Input::get('description'));
$assetdetail ->dateof_purchase = e(Input::get('dateof_purchase'));
$assetdetail ->label_number = e(Input::get('label_number'));
$assetdetail ->purchase_price = e(Input::get('purchase_price'));
$assetdetail ->dateof_disposed = e(Input::get('dateof_disposed'));
$assetdetail ->depreciation_type = e(Input::get('depreciation_type'));
$assetdetail ->salvage_value = e(Input::get('salvage_value'));
$assetdetail ->asset_life = e(Input::get('asset_life'));
// Was the asset created?
if($assetdetail->save())
{
// Redirect to the saved location page
return Redirect::to("admin/settings/assetdetails/$assetdetailId/edit")->with('success', Lang::get('admin/assetdetails/message.update.success'));
}
}
else
{
// failure
$errors = $assetdetail->errors();
return Redirect::back()->withInput()->withErrors($errors);
}
// Redirect to the location management page
return Redirect::to("admin/settings/assetdetails/$assetdetailId/edit")->with('error', Lang::get('admin/assetdetails/message.update.error'));
}
```
**I tried**
```
{{ Form::checkbox('active', 1, true, Input::old('active', $assetdetail->active), array('class'=>'isnesdbox')) }}
```
But i get the follwing error
Cannot use a scalar value as an array
**I also tried this**
```
<input class="col-md-1 controls isnesdbox" type="checkbox" name="active" checked id="active" value="1" {{ $assetdetail->active === '1' ? 'checked' : '' }} />
```
Please help me to achieve this
Note:iam using mysql database and the database type iam using is bit which stores 0's and 1's depending on the user input. | 2014/10/23 | ['https://Stackoverflow.com/questions/26530261', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3532653/'] | It sounds like you don't really care what the value of $assetdetail->active is, you just want the checkbox checked until the user unchecks it.
Does this do what you're looking for:
```
{{ Form::checkbox('active', 1, Session::hasOldInput() ? array_key_exists('active', Input::old()) : true, array('class'=>'isnesdbox')) }}
```
Or have I misread what you're trying to do?
For this solution, it checks if there is old input in the session. If there is old input data, it uses the existence of the `'active'` key to determine the state of the checkbox [1]. If there is not old input data, it defaults the checkbox to checked.
[1] Checkboxes submit differently then other form elements. An unchecked checkbox is not considered a "successful" control, so it does not submit any data, and will therefore not exist in the `Input::old()` array. So, if the key exists, it was checked; if the key does not exist, it was not checked. You can read more about "successful" form controls [here](http://www.w3.org/TR/html401/interact/forms.html#h-17.13.2).
---
Edit
----
Based on the comments, it looks like the same form is used for both creating and editing the Assetdetail object. When creating, you want the checkbox checked by default, when editing you want the checkbox to reflect the value stored in the database.
The code I posted above should be close, but you'll need to change the hardcoded `true` in the ternary operator.
If $assetdetail is null during create, you'll want:
```
{{ Form::checkbox('active', 1, Session::hasOldInput() ? array_key_exists('active', Input::old()) : (!empty($assetdetail) ? $assetdetail->active : true), array('class'=>'isnesdbox')) }}
```
If $assetdetail is an Assetdetail instance during create, you'll want:
```
{{ Form::checkbox('active', 1, Session::hasOldInput() ? array_key_exists('active', Input::old()) : ($assetdetail->exists ? $assetdetail->active : true), array('class'=>'isnesdbox')) }}
``` | Since Google apparently still thinks this answer is relevant, here's an updated answer for Laravel 5.8:
```html
<input type="checkbox" value="true" name="notify" @if(!old() || old('notify') == 'true') checked="checked" @endif />
``` |
26,530,261 | I have a checkbox and i want to make my checkbox checked by default, if the user unchecks the checkbox and save the form, i need the checkbox to be unchecked while retrieving or editing the form data.
**My view page**
```
<div class="form-group {{ $errors->has('active') ? 'error' : '' }}">
<label for="active" class="col-md-3 control-label">@lang('admin/assetdetails/form.active')</label>
<div class="controls col-md-7">
{{ Form::checkbox('active', 1, Input::old('active', $assetdetail->active), array('class'=>'isnesdbox')) }}
{{ $errors->first('active', '<span class="alert-msg"><i class="icon-remove-sign"></i> :message</span>') }}
</div>
</div>
```
**Giving this brings back the old data from database correctly but i couldn't make my checkbox checked as default**
**Controller:**
```
public function postEdit($assetdetailId = null)
{
// Check if the location exists
if (is_null($assetdetail = Assetdetail::find($assetdetailId)))
{
// Redirect to the blogs management page
return Redirect::to('admin/settings/assetdetails')->with('error', Lang::get('admin/assetdetails/message.does_not_exist'));
}
// get the POST data
$new = Input::all();
// attempt validation
if ($assetdetail->validate($new))
{
// Update the location data
$assetdetail ->asset_number = e(Input::get('asset_number'));
$assetdetail ->location_id = e(Input::get('location_id'));
$assetdetail ->assign_to = e(Input::get('assign_to'));
$assetdetail ->asset_type_id = e(Input::get('asset_type_id'));
$assetdetail ->nesd = e(Input::get('nesd'));
$assetdetail ->active = e(Input::get('active'));
$assetdetail ->shift = e(Input::get('shift'));
$assetdetail ->supplier_name = e(Input::get('supplier_name'));
$assetdetail ->description = e(Input::get('description'));
$assetdetail ->dateof_purchase = e(Input::get('dateof_purchase'));
$assetdetail ->label_number = e(Input::get('label_number'));
$assetdetail ->purchase_price = e(Input::get('purchase_price'));
$assetdetail ->dateof_disposed = e(Input::get('dateof_disposed'));
$assetdetail ->depreciation_type = e(Input::get('depreciation_type'));
$assetdetail ->salvage_value = e(Input::get('salvage_value'));
$assetdetail ->asset_life = e(Input::get('asset_life'));
// Was the asset created?
if($assetdetail->save())
{
// Redirect to the saved location page
return Redirect::to("admin/settings/assetdetails/$assetdetailId/edit")->with('success', Lang::get('admin/assetdetails/message.update.success'));
}
}
else
{
// failure
$errors = $assetdetail->errors();
return Redirect::back()->withInput()->withErrors($errors);
}
// Redirect to the location management page
return Redirect::to("admin/settings/assetdetails/$assetdetailId/edit")->with('error', Lang::get('admin/assetdetails/message.update.error'));
}
```
**I tried**
```
{{ Form::checkbox('active', 1, true, Input::old('active', $assetdetail->active), array('class'=>'isnesdbox')) }}
```
But i get the follwing error
Cannot use a scalar value as an array
**I also tried this**
```
<input class="col-md-1 controls isnesdbox" type="checkbox" name="active" checked id="active" value="1" {{ $assetdetail->active === '1' ? 'checked' : '' }} />
```
Please help me to achieve this
Note:iam using mysql database and the database type iam using is bit which stores 0's and 1's depending on the user input. | 2014/10/23 | ['https://Stackoverflow.com/questions/26530261', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3532653/'] | It sounds like you don't really care what the value of $assetdetail->active is, you just want the checkbox checked until the user unchecks it.
Does this do what you're looking for:
```
{{ Form::checkbox('active', 1, Session::hasOldInput() ? array_key_exists('active', Input::old()) : true, array('class'=>'isnesdbox')) }}
```
Or have I misread what you're trying to do?
For this solution, it checks if there is old input in the session. If there is old input data, it uses the existence of the `'active'` key to determine the state of the checkbox [1]. If there is not old input data, it defaults the checkbox to checked.
[1] Checkboxes submit differently then other form elements. An unchecked checkbox is not considered a "successful" control, so it does not submit any data, and will therefore not exist in the `Input::old()` array. So, if the key exists, it was checked; if the key does not exist, it was not checked. You can read more about "successful" form controls [here](http://www.w3.org/TR/html401/interact/forms.html#h-17.13.2).
---
Edit
----
Based on the comments, it looks like the same form is used for both creating and editing the Assetdetail object. When creating, you want the checkbox checked by default, when editing you want the checkbox to reflect the value stored in the database.
The code I posted above should be close, but you'll need to change the hardcoded `true` in the ternary operator.
If $assetdetail is null during create, you'll want:
```
{{ Form::checkbox('active', 1, Session::hasOldInput() ? array_key_exists('active', Input::old()) : (!empty($assetdetail) ? $assetdetail->active : true), array('class'=>'isnesdbox')) }}
```
If $assetdetail is an Assetdetail instance during create, you'll want:
```
{{ Form::checkbox('active', 1, Session::hasOldInput() ? array_key_exists('active', Input::old()) : ($assetdetail->exists ? $assetdetail->active : true), array('class'=>'isnesdbox')) }}
``` | For variable-based default value
--------------------------------
In below, if `$myDefault` is set to `true`, it equals checking the check-box by default.
```html
<input type="checkbox" value="myOnValue"
name="myField"
@if((!old() && $myDefault) || old('myField') == 'myOnValue') checked="checked" @endif />
```
Always checked by default
-------------------------
```html
<input type="checkbox" value="on"
name="myField"
@if(!old() || old('myField') == 'on') checked="checked" @endif />
```
Always unchecked by default
---------------------------
Below does not need "`!old()`" workaround.
```html
<input type="checkbox" value="on"
name="myField"
@if(old('myField') == 'on') checked="checked" @endif />
```
>
> Related Laracast: <https://laracasts.com/discuss/channels/laravel/how-to-set-old-value-for-checkbox-input-using-blade?page=1&replyId=771230>
>
>
> |
26,530,261 | I have a checkbox and i want to make my checkbox checked by default, if the user unchecks the checkbox and save the form, i need the checkbox to be unchecked while retrieving or editing the form data.
**My view page**
```
<div class="form-group {{ $errors->has('active') ? 'error' : '' }}">
<label for="active" class="col-md-3 control-label">@lang('admin/assetdetails/form.active')</label>
<div class="controls col-md-7">
{{ Form::checkbox('active', 1, Input::old('active', $assetdetail->active), array('class'=>'isnesdbox')) }}
{{ $errors->first('active', '<span class="alert-msg"><i class="icon-remove-sign"></i> :message</span>') }}
</div>
</div>
```
**Giving this brings back the old data from database correctly but i couldn't make my checkbox checked as default**
**Controller:**
```
public function postEdit($assetdetailId = null)
{
// Check if the location exists
if (is_null($assetdetail = Assetdetail::find($assetdetailId)))
{
// Redirect to the blogs management page
return Redirect::to('admin/settings/assetdetails')->with('error', Lang::get('admin/assetdetails/message.does_not_exist'));
}
// get the POST data
$new = Input::all();
// attempt validation
if ($assetdetail->validate($new))
{
// Update the location data
$assetdetail ->asset_number = e(Input::get('asset_number'));
$assetdetail ->location_id = e(Input::get('location_id'));
$assetdetail ->assign_to = e(Input::get('assign_to'));
$assetdetail ->asset_type_id = e(Input::get('asset_type_id'));
$assetdetail ->nesd = e(Input::get('nesd'));
$assetdetail ->active = e(Input::get('active'));
$assetdetail ->shift = e(Input::get('shift'));
$assetdetail ->supplier_name = e(Input::get('supplier_name'));
$assetdetail ->description = e(Input::get('description'));
$assetdetail ->dateof_purchase = e(Input::get('dateof_purchase'));
$assetdetail ->label_number = e(Input::get('label_number'));
$assetdetail ->purchase_price = e(Input::get('purchase_price'));
$assetdetail ->dateof_disposed = e(Input::get('dateof_disposed'));
$assetdetail ->depreciation_type = e(Input::get('depreciation_type'));
$assetdetail ->salvage_value = e(Input::get('salvage_value'));
$assetdetail ->asset_life = e(Input::get('asset_life'));
// Was the asset created?
if($assetdetail->save())
{
// Redirect to the saved location page
return Redirect::to("admin/settings/assetdetails/$assetdetailId/edit")->with('success', Lang::get('admin/assetdetails/message.update.success'));
}
}
else
{
// failure
$errors = $assetdetail->errors();
return Redirect::back()->withInput()->withErrors($errors);
}
// Redirect to the location management page
return Redirect::to("admin/settings/assetdetails/$assetdetailId/edit")->with('error', Lang::get('admin/assetdetails/message.update.error'));
}
```
**I tried**
```
{{ Form::checkbox('active', 1, true, Input::old('active', $assetdetail->active), array('class'=>'isnesdbox')) }}
```
But i get the follwing error
Cannot use a scalar value as an array
**I also tried this**
```
<input class="col-md-1 controls isnesdbox" type="checkbox" name="active" checked id="active" value="1" {{ $assetdetail->active === '1' ? 'checked' : '' }} />
```
Please help me to achieve this
Note:iam using mysql database and the database type iam using is bit which stores 0's and 1's depending on the user input. | 2014/10/23 | ['https://Stackoverflow.com/questions/26530261', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3532653/'] | Since Google apparently still thinks this answer is relevant, here's an updated answer for Laravel 5.8:
```html
<input type="checkbox" value="true" name="notify" @if(!old() || old('notify') == 'true') checked="checked" @endif />
``` | For variable-based default value
--------------------------------
In below, if `$myDefault` is set to `true`, it equals checking the check-box by default.
```html
<input type="checkbox" value="myOnValue"
name="myField"
@if((!old() && $myDefault) || old('myField') == 'myOnValue') checked="checked" @endif />
```
Always checked by default
-------------------------
```html
<input type="checkbox" value="on"
name="myField"
@if(!old() || old('myField') == 'on') checked="checked" @endif />
```
Always unchecked by default
---------------------------
Below does not need "`!old()`" workaround.
```html
<input type="checkbox" value="on"
name="myField"
@if(old('myField') == 'on') checked="checked" @endif />
```
>
> Related Laracast: <https://laracasts.com/discuss/channels/laravel/how-to-set-old-value-for-checkbox-input-using-blade?page=1&replyId=771230>
>
>
> |
29,825,154 | I'm working in a custom `keyboard` `(iOS App Extension)`. I have a `UICollectionView` in my `Keyboard` `Layout`, so when one `item` is selected I want to show a `message` (`UIAlerView` for example).
Here is my code:
```
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
...
UIAlertController * alert= [UIAlertController
alertControllerWithTitle:@"My Title"
message:@"Enter User Credentials"
preferredStyle:UIAlertControllerStyleAlert];
[self presentViewController:alert animated:YES completion:nil];
}
```
I get this error: `'Feature not available in extensions of type com.apple.keyboard-service'`
So...is there any way to show a `message` from an `App Extension`?
**EDIT:**
Here is an example. The `IKEA Emoticons Keyboard` shows a message (like an `Android Toast` after selecting one item).
I also have tried this library:
[iOS Toast Library](https://github.com/scalessec/Toast)
 | 2015/04/23 | ['https://Stackoverflow.com/questions/29825154', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2274847/'] | Finally I solved the problem. It's not the best solution, but at least I get the effect that I wanted.
I've created a `View` simulating a `Toast` in the `xib` file and set it to `hidden`.
When the item is selected, I show the "faked" `Toast` for 2 seconds and hide it again.
```
self.popUpView.hidden = NO;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 2.0 * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
self.popUpView.hidden = YES;
});
```
I don't know if it's a good solution, but I really had to find a solution for that.
For Swift you can use this :
```
self.popUpView.isHidden = false
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
self.popUpView.isHidden = true
}
``` | Sad to say that, but there's no way to show a UIAlertView in keyboard extension. Actually, nothing above the frame of InputViewController can be showed. It's pretty clear in the Apple's doc:
>
> ...a custom keyboard can draw only within the primary view of its UIInputViewController object... it is not possible to display key artwork above the top edge of a custom keyboard’s primary view, as the system keyboard does on iPhone when you tap and hold a key in the top row.
>
>
>
As for message inside the keyboard, there are some useful libraries that can help us with it. For example <https://github.com/scalessec/Toast> and <https://github.com/sergeylenkov/PTHintController>. |
60,329,971 | I'm developing a quiz app and I'm this error:
>
> Fatal error: Uncaught Error: Call to a member function fetch\_assoc() on array in C:\wamp64\
>
>
>
What's going wrong?
```
/**
* Get the Question
*/
$query = "SELECT * FROM questions
WHERE question_number = $number";
//Get result
$result = mysqli_query ($conn,$query);
$question = $result->fetch_assoc();
/*
* Get choices
*/
$query = "SELECT * FROM choices
WHERE question_number = $number";
//Get result
$result = mysqli_query ($conn,$query);
$choices = $result->fetch_assoc();
?>
<html>
<body>
<main>
<div class="container" >
<div class="current">Question 1 of 5</div>
<p class="question">
<?php echo $question ['text']; ?>
</p>
<?php while ($row = $choices->fetch_assoc()) : ?>
<li><input name="choice" type="radio value="<?php echo $row ['id'];?> " /><?php echo $row ['text']; ?></li>
<input type="submit" value="Sumbit your answer"/>
</ul>
</main>
</body>
</html>
<?php endwhile;
``` | 2020/02/20 | ['https://Stackoverflow.com/questions/60329971', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12915120/'] | The error indicates that you're trying to fetch from an array, rather than from a database result set.
In your code:
```
$choices = $result->fetch_assoc();
```
This [`fetch_assoc`](https://www.php.net/manual/en/mysqli-result.fetch-assoc.php) returns "an associative array of strings representing the fetched row in the result set", so `$choices` will be an array of the first row.
```
while ($row = $choices->fetch_assoc()) ...
```
This `fetch_assoc` expects a "result set identifier returned by mysqli\_query", but `$choices` is an array that's already been fetched, so the `while` loop fails with:
>
> Call to a member function fetch\_assoc() on array
>
>
>
---
Consider looping over the result set `$result` to fetch rows one-by-one, like this:
```
$result = mysqli_query($conn,$query);
while ($row = $result->fetch_assoc()) ...
```
Alternatively, use [`fetch_all`](https://www.php.net/manual/en/mysqli-result.fetch-all.php) to fetch all rows at once and a `for` loop to iterate through the resulting `$choices` array:
```
$result = mysqli_query($conn,$query);
$choices = $result->fetch_all();
foreach ($choices as $choice) ....
```
---
As mentioned by Dharman, [`mysqli_result` is traversable](https://www.php.net/manual/en/class.mysqli-result.php). You can iterate with a `foreach` loop directly:
```
$choices = mysqli_query($conn,$query);
foreach ($choices as $choice) {
echo $choice['text'];
}
```
That being said, consider the [observation from Your Common Sense](https://stackoverflow.com/a/59028348/924299):
>
> But it is actually just a syntax sugar for a while loop - you cannot access values of this "array" values directly, which makes this feature of a little use actually.
>
>
> | You are fetching a single row into PHP array with this line:
```
$choices = $result->fetch_assoc();
```
Then you use that array in your `while` loop:
```
while ($row = $choices->fetch_assoc())
```
You can't call `fetch_assoc()` on an array!
What you should have done is fetched all rows into a multi-dimensional array and then `foreach` on that array.
```
$result = mysqli_query($conn, $query);
$choices = $result->fetch_all(MYSQLI_ASSOC);
// and then loop:
foreach($choices as $row) :
```
`$result` is an object of mysqli\_object class. Working directly with this object can be difficult. It is recommended to fetch all records into an array with `fetch_all()`. You can then change the array, filter, loop, access specific rows, etc. You can't do it with the mysqli\_result object and the methods for reading row by row can be confusing.
You can loop on mysqli\_result directly though, which is much better than `while ($row = $choices->fetch_assoc())`. The biggest advantage is that it will always loop from the beginning to the end, so you can loop it many times without rewinding. For example:
```
$result = $conn->query('SELECT * FROM users LIMIT 3'); // 3 rows returned
var_dump($result->fetch_all(MYSQLI_ASSOC)); // <-- this works
var_dump($result->fetch_all(MYSQLI_ASSOC)); // <-- this will not work without rewiding
// both of the loops will work
foreach ($result as $row) {
var_dump($row);
}
foreach ($result as $row) {
var_dump($row);
}
```
A `foreach` loop is also cleaner and easier to understand. You run a query and then you loop on the result.
Of course, mysqli\_result object is not an array. You can loop on it, but you can't access specific rows via array index. This will not get you the first row:
```
mysqli_query($conn, '...')[0]; // <-- Uncaught Error: Cannot use object of type mysqli_result as array
```
You should be using prepared statements if you have variable input in your SQL. Your queries fixed should look like this:
```
$stmt = $conn->prepare("SELECT * FROM choices WHERE question_number = ?");
$stmt->bind_param('i', $number);
$stmt->execute();
$result = $stmt->get_result();
foreach ($result as $row) {
// echo HTML
}
``` |
59,812,671 | i have a NVIDIA GeFroce GTX 1650. This GPU is not CUDA enabled/supported ([as seen here](https://developer.nvidia.com/cuda-gpus)). However, I still want to use Tensorflow. Is there any possibility to do this? | 2020/01/19 | ['https://Stackoverflow.com/questions/59812671', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] | Yes, you can run `Tensorflow` on your CPU.
Use the following code block:
```
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
import tensorflow as tf
```
If you really want to install CUDA compatible version to your graphic card, check last message [here](https://devtalk.nvidia.com/default/topic/1051268/cuda-setup-and-installation/trying-to-install-cuda-toolkit-for-use-on-gtx-1650-on-ubuntu-18-04/). Good luck! | For anybody else looking for this info the GTX 1650 has compute capability of 7.5. See on the NVidia forums here: <https://forums.developer.nvidia.com/t/cuda-enabled-geforce-1650/81010/2> and also on the [CUDA Wikipedia page](https://en.wikipedia.org/wiki/CUDA) |
2,277,465 | I have been creating a 2D game in Qt and I want to allow others to connect to hosted games to play. Would I just make a "server" in the game and allow others to connect to it? | 2010/02/17 | ['https://Stackoverflow.com/questions/2277465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/274437/'] | Generally, one will need a few things to get something like that going.
Namely, a directory server. Maybe everyone connects to other players who host games to play, but you need to run a directory for games to be listed in order for people to connect.
Either that or you need to run a server and host them there. The choice is yours, the first option is probably easiest on you. | If I were you, I would make a server separated from, but bundled with, the "client". Believe me or not, many games out there take similar approach. |
2,277,465 | I have been creating a 2D game in Qt and I want to allow others to connect to hosted games to play. Would I just make a "server" in the game and allow others to connect to it? | 2010/02/17 | ['https://Stackoverflow.com/questions/2277465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/274437/'] | If this is just a small project and you aren't intended to mass distribute it across the web (it doesn't sound like you are), then you can code up a simple socket server. You will need to modify your existing game code to send the "moves" as a message to the server. It will probably be easiest if you make up a simple network protocol to transmit the move data (if you are ambitious you could try serialization).
A pseudo-code example for a simple Tic-Tac-Toe game:
```
move1 = "Move X:1:1" //placed an 'X' in square at row 1, column 1
move2 = "Move O:1:2" //placed an 'O' in square at row 1, column 2
reset = "Reset" //clear the board for a new game
...etc...
```
Your game code will need to generate these messages. Each player will run your game on their machine and this will act as the client.
Meanwhile, back in the server code, you will need to listen for move messages sent by the clients. When you get a move message, you need to broadcast the message to all the other clients so that there boards can be updated. I would recommend moving the server code outside of the game code for now; this will allow you to setup a dedicated server that will handle all the sockets and then everyone who wants to play will simply connect their client up to the server.
The basic idea is that your client needs to broadcast the details about what it's player is doing to the server, as well as listen for data from the server to update the details about the other player(s).
You can find some good discussion of high-level algorithms of a simple Client-Server game in this question as well: [Algorithm for Client-Server Games](https://stackoverflow.com/questions/811906/algorithm-for-client-server-games)
Hopefully this is enough to get you started! I have used this approach for some simple games (Tetris, Pong, etc) using C++/Qt and they worked out pretty well.
PS. Don't let the idea of writing your own server scare you off. It sounds daunting but it is really not very complicated at all (~100 lines of code or less) and a great learning experience. | If I were you, I would make a server separated from, but bundled with, the "client". Believe me or not, many games out there take similar approach. |
2,277,465 | I have been creating a 2D game in Qt and I want to allow others to connect to hosted games to play. Would I just make a "server" in the game and allow others to connect to it? | 2010/02/17 | ['https://Stackoverflow.com/questions/2277465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/274437/'] | If this is just a small project and you aren't intended to mass distribute it across the web (it doesn't sound like you are), then you can code up a simple socket server. You will need to modify your existing game code to send the "moves" as a message to the server. It will probably be easiest if you make up a simple network protocol to transmit the move data (if you are ambitious you could try serialization).
A pseudo-code example for a simple Tic-Tac-Toe game:
```
move1 = "Move X:1:1" //placed an 'X' in square at row 1, column 1
move2 = "Move O:1:2" //placed an 'O' in square at row 1, column 2
reset = "Reset" //clear the board for a new game
...etc...
```
Your game code will need to generate these messages. Each player will run your game on their machine and this will act as the client.
Meanwhile, back in the server code, you will need to listen for move messages sent by the clients. When you get a move message, you need to broadcast the message to all the other clients so that there boards can be updated. I would recommend moving the server code outside of the game code for now; this will allow you to setup a dedicated server that will handle all the sockets and then everyone who wants to play will simply connect their client up to the server.
The basic idea is that your client needs to broadcast the details about what it's player is doing to the server, as well as listen for data from the server to update the details about the other player(s).
You can find some good discussion of high-level algorithms of a simple Client-Server game in this question as well: [Algorithm for Client-Server Games](https://stackoverflow.com/questions/811906/algorithm-for-client-server-games)
Hopefully this is enough to get you started! I have used this approach for some simple games (Tetris, Pong, etc) using C++/Qt and they worked out pretty well.
PS. Don't let the idea of writing your own server scare you off. It sounds daunting but it is really not very complicated at all (~100 lines of code or less) and a great learning experience. | Generally, one will need a few things to get something like that going.
Namely, a directory server. Maybe everyone connects to other players who host games to play, but you need to run a directory for games to be listed in order for people to connect.
Either that or you need to run a server and host them there. The choice is yours, the first option is probably easiest on you. |
42,236,697 | ```
@RequestMapping(value="/portfolios", method = RequestMethod.GET)
public @ResponseBody List<PortfolioVO> getPortfolios(HttpServletRequest request, @RequestParam(required= false) String region) {
List<PortfolioVO> portfolios = gmiCacheService.getPortoliosForRegion(user, region);
return portfolios;
}
```
I have another List from another function that I need to add.
to then just return portfolios. I am very new to Java and do not know how to implement this. | 2017/02/14 | ['https://Stackoverflow.com/questions/42236697', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7470849/'] | In c#, I would use `Tuple` for storing those two list separately. But in Java, I didn't get similar data structure. But you can make your custom tuple structure.
[From this answer](https://stackoverflow.com/questions/2670982/using-pairs-or-2-tuples-in-java) :
```
public class Tuple<X, Y> {
public final X x;
public final Y y;
public Tuple(X x, Y y) {
this.x = x;
this.y = y;
}
}
```
Using above structure, you can store two different list and use it.
If you are allowed to use third party library, you can have [javatuples](http://www.javatuples.org/) where you can use `Pair` structure | I see two ways:
1) return array of lists: `public @ResponseBody List[]<PortfolioVO> getPortfolios( ... )`
inside it: `return new List[] { list1, list2 };`
This is fast to implement, but it is not nice and little bit dirty.
2) More proper way, I think, create class for this case:
```
static class ListPairHolder {
List<PortfolioVO> list1;
List<PortfolioVO> list2;
ListPairHolder(List<PortfolioVO> list1, List<PortfolioVO> list2){
this.list1 = list1; this.list2 = list2;
}
}
```
and return this type from method. |
42,236,697 | ```
@RequestMapping(value="/portfolios", method = RequestMethod.GET)
public @ResponseBody List<PortfolioVO> getPortfolios(HttpServletRequest request, @RequestParam(required= false) String region) {
List<PortfolioVO> portfolios = gmiCacheService.getPortoliosForRegion(user, region);
return portfolios;
}
```
I have another List from another function that I need to add.
to then just return portfolios. I am very new to Java and do not know how to implement this. | 2017/02/14 | ['https://Stackoverflow.com/questions/42236697', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7470849/'] | Since Java [doesn't have built-in pairs](https://stackoverflow.com/questions/156275/what-is-the-equivalent-of-the-c-pairl-r-in-java), the "Java way" of doing it is to return a custom class that has two `List` fields. Something like:
```
public class MyReturnType{
public List<PortfolioV0> l1,l2;
}
```
Another option is to return a `List<List<PortfolioV0>>` (a list of lists), and have the first item be the first list, and the second item, the second list.
A third option is to give up, and write your own `Pair` class (or use [Apache's](https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/Pair.html)), and return a `Pair<List<PortfolioV0>,List<PortfolioV0>>` | I see two ways:
1) return array of lists: `public @ResponseBody List[]<PortfolioVO> getPortfolios( ... )`
inside it: `return new List[] { list1, list2 };`
This is fast to implement, but it is not nice and little bit dirty.
2) More proper way, I think, create class for this case:
```
static class ListPairHolder {
List<PortfolioVO> list1;
List<PortfolioVO> list2;
ListPairHolder(List<PortfolioVO> list1, List<PortfolioVO> list2){
this.list1 = list1; this.list2 = list2;
}
}
```
and return this type from method. |
47,644,183 | i am using spring boot and i want to deploy a rest API war file into tomcat server.
There is no errors in the tomcat server logs but when i call any endpoint i got 404 "not found" and i got the same from the tomcat server .
java version : 8.
tomcat version : 9.
maybe i miss something , here are my code samples :
Pom :
```
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test</groupId>
<artifactId>test</artifactId>
<version>1.1</version>
<packaging>war</packaging>
<name>test</name>
<description>test API</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-
8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!-- tag::security[] -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- end::security[] -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
<build>
<defaultGoal>install</defaultGoal>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.0.0</version>
</plugin>
</plugins>
</pluginManagement>
<!-- To use the plugin goals in your POM or parent POM -->
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
```
2.Application.java
```
@SpringBootApplication
public class TestApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder
application) {
return application.sources(TestApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
``` | 2017/12/05 | ['https://Stackoverflow.com/questions/47644183', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9053563/'] | It's not possible.
an bn is not [regular](https://en.wikipedia.org/wiki/Regular_language), thus matching with a regular expression is mathematically not possible, even with enhanced regular expressions.
You can use the following function to get the range which doesn't use a regular expression:
```js
var input = "a cat bit a dog on the butt b";
console.log(getRange(input, "a", "b"));
function getRange(input, char1, char2){
var indexStart = -1;
var count1 = 0, count2 = 0;
for(var i = 0; i < input.length; i++){
var char = input[i];
switch(char){
case char1:
count1 += 1; break
case char2:
count2 += 1; break;
}
if(char == char1 || char == char2){
if(indexStart == -1)
indexStart = i;
if(count1 == count2)
return [indexStart, i];
}
}
return [-1, -1];
}
``` | ```js
var a = 0,
b = 0;
var result = 0;
var patten = /./g;
for (;patten.exec("a cat bit a dog on the butt before running away") != null;) {
if (RegExp['$&'] == "a") {
a++;
if (a == b) {
result = patten.lastIndex;
}
}
if (RegExp['$&'] == "b") {
b++;
if (a == b) {
result = patten.lastIndex;
}
}
}
console.log("1~" + result);
console.log("a cat bit a dog on the butt before running away".slice(0,result));
```
by the way, 朕也会功夫。 |
39,099,218 | [](https://i.stack.imgur.com/PKlCN.png)I am using yii2 framework since last few weeks. But now I am getting some issues with composer itself.
Just for info, I am using ubuntu 14.04
When I require some new package / extensions, I do the composer add by using composer require command. But I noticed that sometimes it's removing few of the existing packages from my vendor and project.
I tried with following commands.
```
composer require dmstr/yii2-adminlte-asset "*"
composer require 2amigos/yii2-file-upload-widget:~1.0
```
And also tried with some googling.
<http://www.yiiframework.com/wiki/672/install-specific-yii2-vendor-extension-dependency-without-updating-other-packages/>
But it's not working.
Is there a way to add a new package / extension into your existing yii 2 project without removing existing packages or without any composer update command?
**Composer.json**
```
{
"name": "sganz/yii2-advanced-api-template",
"description": "Improved Yii 2 Advanced Application Template By Sandy Ganz, Original by Nenad Zivkovic",
"keywords": ["yii2", "framework", "advanced", "improved", "application template", "nenad", "sganz"],
"type": "project",
"license": "BSD-3-Clause",
"support": {
"tutorial": "http://www.freetuts.org/tutorial/view?id=6",
"source": "https://github.com/sganz/yii2-advanced-api-template.git"
},
"minimum-stability": "dev",
"prefer-stable":true,
"require": {
"php": ">=5.4.0",
"yiisoft/yii2": "*",
"yiisoft/yii2-bootstrap": "*",
"yiisoft/yii2-swiftmailer": "*",
"nenad/yii2-password-strength": "*",
"mihaildev/yii2-ckeditor": "*",
"dmstr/yii2-adminlte-asset": "*"
},
"require-dev": {
"yiisoft/yii2-codeception": "*",
"yiisoft/yii2-debug": "*",
"yiisoft/yii2-gii": "*",
"yiisoft/yii2-faker": "*",
"codeception/specify": "*",
"codeception/verify": "*"
},
"config": {
"vendor-dir": "protected/vendor",
"process-timeout": 1800
},
"extra": {
"asset-installer-paths": {
"npm-asset-library": "protected/vendor/npm",
"bower-asset-library": "protected/vendor/bower"
}
}
}
```
Any help on this would be greatly appreciated. | 2016/08/23 | ['https://Stackoverflow.com/questions/39099218', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6608101/'] | Try
```
composer --no-update require dmstr/yii2-adminlte-asset:*
``` | To avoid uninstallation of other extensions just do following steps.
```
1) "dmstr/yii2-adminlte-asset" : "2.*"
2) "2amigos/yii2-file-upload-widget": "~1.0"
```
to the require section of your composer.json file.
```
2) php composer.phar update
```
run this command in Cmd. |
39,099,218 | [](https://i.stack.imgur.com/PKlCN.png)I am using yii2 framework since last few weeks. But now I am getting some issues with composer itself.
Just for info, I am using ubuntu 14.04
When I require some new package / extensions, I do the composer add by using composer require command. But I noticed that sometimes it's removing few of the existing packages from my vendor and project.
I tried with following commands.
```
composer require dmstr/yii2-adminlte-asset "*"
composer require 2amigos/yii2-file-upload-widget:~1.0
```
And also tried with some googling.
<http://www.yiiframework.com/wiki/672/install-specific-yii2-vendor-extension-dependency-without-updating-other-packages/>
But it's not working.
Is there a way to add a new package / extension into your existing yii 2 project without removing existing packages or without any composer update command?
**Composer.json**
```
{
"name": "sganz/yii2-advanced-api-template",
"description": "Improved Yii 2 Advanced Application Template By Sandy Ganz, Original by Nenad Zivkovic",
"keywords": ["yii2", "framework", "advanced", "improved", "application template", "nenad", "sganz"],
"type": "project",
"license": "BSD-3-Clause",
"support": {
"tutorial": "http://www.freetuts.org/tutorial/view?id=6",
"source": "https://github.com/sganz/yii2-advanced-api-template.git"
},
"minimum-stability": "dev",
"prefer-stable":true,
"require": {
"php": ">=5.4.0",
"yiisoft/yii2": "*",
"yiisoft/yii2-bootstrap": "*",
"yiisoft/yii2-swiftmailer": "*",
"nenad/yii2-password-strength": "*",
"mihaildev/yii2-ckeditor": "*",
"dmstr/yii2-adminlte-asset": "*"
},
"require-dev": {
"yiisoft/yii2-codeception": "*",
"yiisoft/yii2-debug": "*",
"yiisoft/yii2-gii": "*",
"yiisoft/yii2-faker": "*",
"codeception/specify": "*",
"codeception/verify": "*"
},
"config": {
"vendor-dir": "protected/vendor",
"process-timeout": 1800
},
"extra": {
"asset-installer-paths": {
"npm-asset-library": "protected/vendor/npm",
"bower-asset-library": "protected/vendor/bower"
}
}
}
```
Any help on this would be greatly appreciated. | 2016/08/23 | ['https://Stackoverflow.com/questions/39099218', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6608101/'] | Try
```
composer --no-update require dmstr/yii2-adminlte-asset:*
``` | 1. Your problem is, that the packages which are removed are NOT in the `require` nor in `require-dev` section of your `composer.json`. So I assume that the removed packages formerly were (sub-)required by any of the other packages in your `composer.json` and with the newer version of these packages this requirement was dropped. This should be a normal behavior and should be no problem for your project!
2. As @Bizley already showed you can add a requirement without updating the old ones:
```
composer --no-update require dmstr/yii2-adminlte-asset:*
``` |
39,099,218 | [](https://i.stack.imgur.com/PKlCN.png)I am using yii2 framework since last few weeks. But now I am getting some issues with composer itself.
Just for info, I am using ubuntu 14.04
When I require some new package / extensions, I do the composer add by using composer require command. But I noticed that sometimes it's removing few of the existing packages from my vendor and project.
I tried with following commands.
```
composer require dmstr/yii2-adminlte-asset "*"
composer require 2amigos/yii2-file-upload-widget:~1.0
```
And also tried with some googling.
<http://www.yiiframework.com/wiki/672/install-specific-yii2-vendor-extension-dependency-without-updating-other-packages/>
But it's not working.
Is there a way to add a new package / extension into your existing yii 2 project without removing existing packages or without any composer update command?
**Composer.json**
```
{
"name": "sganz/yii2-advanced-api-template",
"description": "Improved Yii 2 Advanced Application Template By Sandy Ganz, Original by Nenad Zivkovic",
"keywords": ["yii2", "framework", "advanced", "improved", "application template", "nenad", "sganz"],
"type": "project",
"license": "BSD-3-Clause",
"support": {
"tutorial": "http://www.freetuts.org/tutorial/view?id=6",
"source": "https://github.com/sganz/yii2-advanced-api-template.git"
},
"minimum-stability": "dev",
"prefer-stable":true,
"require": {
"php": ">=5.4.0",
"yiisoft/yii2": "*",
"yiisoft/yii2-bootstrap": "*",
"yiisoft/yii2-swiftmailer": "*",
"nenad/yii2-password-strength": "*",
"mihaildev/yii2-ckeditor": "*",
"dmstr/yii2-adminlte-asset": "*"
},
"require-dev": {
"yiisoft/yii2-codeception": "*",
"yiisoft/yii2-debug": "*",
"yiisoft/yii2-gii": "*",
"yiisoft/yii2-faker": "*",
"codeception/specify": "*",
"codeception/verify": "*"
},
"config": {
"vendor-dir": "protected/vendor",
"process-timeout": 1800
},
"extra": {
"asset-installer-paths": {
"npm-asset-library": "protected/vendor/npm",
"bower-asset-library": "protected/vendor/bower"
}
}
}
```
Any help on this would be greatly appreciated. | 2016/08/23 | ['https://Stackoverflow.com/questions/39099218', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6608101/'] | Try
```
composer --no-update require dmstr/yii2-adminlte-asset:*
``` | I had this problem few days ago to install a package but when I installed the package all the project updated and my project became broken.So I replace my last vendor again,So I found a safe way for better and safer upgrading packages:
1. archiving your vendor to a zip or rar file and copy composer.json too.
2. add package to composer or install with composer require.
3. dont clear command line screen and copy its screen into a txt file to find versions
4. find your vital and main packages like yiisoft/yii2 and .... and copy their versions.
for doing this open txt file and search in upgrade lines and find something like below:
`- Upgrading yiisoft/yii2 (2.0.39.3 => 2.0.41.1): Extracting archive` means that your current version is 2.0.39.3,so copy this version on composer.json like below:*(without ~ and ^)*
`"yiisoft/yii2": "2.0.39",`
5. remove project vendor folder and extract backup vendor and finally run
`composer install` or `composer update`.
***note:*** dont remove vendor and composer.json backup till your project will works correctly then you can remove them.
\**this is a manually way for upgrading vendors for don't upgrade in vital framework updates temporary like for my project update that yii released Yii2.0.41.*
**a very important note is from yii upgrade notes from [here](https://github.com/yiisoft/yii2/blob/2.0.41/framework/UPGRADE.md) that:**
>
> Note: This document assumes you have composer installed globally so that you can run the composer command. If you have a composer.phar file inside of your project you need to replace composer with php composer.phar in the following.
>
>
> Tip: Upgrading dependencies of a complex software project always comes at the risk of breaking something, so make sure you have a backup (you should be doing this anyway ;) ).
>
>
>
so running `composer update` command directly could break part of your application like me that my admin pannel was broken.
good luck ;) |
39,099,218 | [](https://i.stack.imgur.com/PKlCN.png)I am using yii2 framework since last few weeks. But now I am getting some issues with composer itself.
Just for info, I am using ubuntu 14.04
When I require some new package / extensions, I do the composer add by using composer require command. But I noticed that sometimes it's removing few of the existing packages from my vendor and project.
I tried with following commands.
```
composer require dmstr/yii2-adminlte-asset "*"
composer require 2amigos/yii2-file-upload-widget:~1.0
```
And also tried with some googling.
<http://www.yiiframework.com/wiki/672/install-specific-yii2-vendor-extension-dependency-without-updating-other-packages/>
But it's not working.
Is there a way to add a new package / extension into your existing yii 2 project without removing existing packages or without any composer update command?
**Composer.json**
```
{
"name": "sganz/yii2-advanced-api-template",
"description": "Improved Yii 2 Advanced Application Template By Sandy Ganz, Original by Nenad Zivkovic",
"keywords": ["yii2", "framework", "advanced", "improved", "application template", "nenad", "sganz"],
"type": "project",
"license": "BSD-3-Clause",
"support": {
"tutorial": "http://www.freetuts.org/tutorial/view?id=6",
"source": "https://github.com/sganz/yii2-advanced-api-template.git"
},
"minimum-stability": "dev",
"prefer-stable":true,
"require": {
"php": ">=5.4.0",
"yiisoft/yii2": "*",
"yiisoft/yii2-bootstrap": "*",
"yiisoft/yii2-swiftmailer": "*",
"nenad/yii2-password-strength": "*",
"mihaildev/yii2-ckeditor": "*",
"dmstr/yii2-adminlte-asset": "*"
},
"require-dev": {
"yiisoft/yii2-codeception": "*",
"yiisoft/yii2-debug": "*",
"yiisoft/yii2-gii": "*",
"yiisoft/yii2-faker": "*",
"codeception/specify": "*",
"codeception/verify": "*"
},
"config": {
"vendor-dir": "protected/vendor",
"process-timeout": 1800
},
"extra": {
"asset-installer-paths": {
"npm-asset-library": "protected/vendor/npm",
"bower-asset-library": "protected/vendor/bower"
}
}
}
```
Any help on this would be greatly appreciated. | 2016/08/23 | ['https://Stackoverflow.com/questions/39099218', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6608101/'] | 1. Your problem is, that the packages which are removed are NOT in the `require` nor in `require-dev` section of your `composer.json`. So I assume that the removed packages formerly were (sub-)required by any of the other packages in your `composer.json` and with the newer version of these packages this requirement was dropped. This should be a normal behavior and should be no problem for your project!
2. As @Bizley already showed you can add a requirement without updating the old ones:
```
composer --no-update require dmstr/yii2-adminlte-asset:*
``` | To avoid uninstallation of other extensions just do following steps.
```
1) "dmstr/yii2-adminlte-asset" : "2.*"
2) "2amigos/yii2-file-upload-widget": "~1.0"
```
to the require section of your composer.json file.
```
2) php composer.phar update
```
run this command in Cmd. |
Subsets and Splits