qid int64 10 74.7M | question stringlengths 15 26.2k | date stringlengths 10 10 | metadata list | response_j stringlengths 27 28.1k | response_k stringlengths 23 26.8k |
|---|---|---|---|---|---|
160,048 | Take a graph with `VertexWeight`s and/or `EdgeWeight`s like
```
g = Graph[{1, 2, 3}, {1 <-> 2, 2 <-> 3, 3 <-> 1},
EdgeWeight -> {1 <-> 2 -> "edge1", 2 <-> 3 -> "edge2", 3 <-> 1 -> "edge3"},
VertexWeight -> {1 -> "vertex1", 2 -> "vertex2", 3 -> "vertex3"},
VertexLabels -> "VertexWeight", EdgeLabels -> "EdgeWeight"]
```
[](https://i.stack.imgur.com/jT5Hs.png)
How can one map a function over vertices and/or edges? | 2017/11/16 | [
"https://mathematica.stackexchange.com/questions/160048",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/4597/"
] | The kernel crashes due to [stack overflow](https://en.wikipedia.org/wiki/Stack_overflow). It is not safe to recurse too deeply. Increasing [`$RecursionLimit`](http://reference.wolfram.com/language/ref/$RecursionLimit.html) to values that are too great (and actually recursing that deep) risks a crash.
(So yes, in a way it's due to insufficient memory, but it has nothing to do with memoization. It is due to insufficient stack space.)
From the documentation:
>
> On most computers, each level of recursion uses a certain amount of stack space. $RecursionLimit allows you to control the amount of stack space that the Wolfram Language can use from within the Wolfram Language. On some computer systems, your whole Wolfram Language session may crash if you allow it to use more stack space than the computer system allows.
>
>
>
What you *can* do in the most general case using memoization is to invoke the functions with gradually increasing parameter values, allowing it to memoize the results. This will limit the depth of the recursion compared to the situation when you pass the highest parameter immediately.
```
Block[{$RecursionLimit = Infinity}, Table[fib[ 10^3 k], {k, 1, 10}]]
```
What you *should try to do* is transform the recursion into iteration. This also avoids the exponential complexity of `fib` without requiring memoization.
```
Nest[{Last[#], First[#] + Last[#]} &, {1, 1}, 10^5]
```
Of course, there are explicit formulas for Fibonacci numbers (though they're not necessarily easy to compute accurately) and Mathematica also has [`Fibonacci`](http://reference.wolfram.com/language/ref/Fibonacci.html). | A general answer from the computer science perspective:
Stack depth limits are common and exist for virtually all programming environments. As Nicolas pointed out, tail recursion is a technique for recursion which does not take up any stack space because the context of the current call (i.e. the variables in that function call's scope) are not needed for any future computations. While recursively defined functions are elegant and concise, it is sometimes necessary to write such functions iteratively to avoid stack depth limits. In theory, all recursive functions can be written iteratively.
As a desirable side effect, iterative implementations are often faster than their recursive counterparts because they cut out the overhead of making a function call and make the best use of CPU cache. |
17,681,804 | I am using CSV Import Pro to import products into my store using OpenCart.
The other day I was importing products which was going fine. Then after an import the extension keeps giving me this fatal error.
I've tried contacting support for damn near 5 days and I haven't gotten much from them. I really need to get this fixed.
**Fatal error:** Cannot use object of type stdClass as array in /home/content/71/11151671/html/admin/view/template/tool/csv\_import.tpl on line 234
Usually there are tabs at the top that let me navigate to the other pieces of the module.
It would not let me post images | 2013/07/16 | [
"https://Stackoverflow.com/questions/17681804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2371362/"
] | `this` should be used like `jQuery(this)`.
Use:
```
$('.content').mouseenter(function() {
$( ".content" ).each(function (i) {
if ( this.style.color != "#F7F7F7" ) {
this.style.color = "#F7F7F7";
this.style.opacity = "0.5";
}
});
jQuery(this).addClass('full');
});
``` | You are setting inline styles with javascript. These will always overrule class styles. |
35,143,944 | I have "channels" in my Android application being represented by an integer in a MySQL db on my server. Basically there are five zones in the application each with five sub channels. The "zones" increment the integer by multiples of 1 while the sub channels increment by 100. (i.e. zone 1, sub-channel 3 equates to int "300") (i.e. zone 3, sub-channel 3 equates to int "303") Okay so this php returns an array[5] with the total number of users in each zone. How can I make this script more efficient? It works but it takes time.
```
<?php
ini_set('display_errors',1);
$json=$_POST['user'];
$json=str_replace('\\','',$json);
$user=json_decode($json);
$pdo=new PDO('mysql://hostname=localhost;dbname=database', 'user', 'password');
$channels=array(100,200,300,400,500);
$full_status=array();
$current_status=array();
for($i=0;$i<5;$i++){
for($j=0;$j<5;$j++){
$total=$pdo->query("SELECT count(user_id) AS count FROM accounts WHERE channel!='0' AND channel='{$channels[$j]}'");
$total=$total->fetchAll(PDO::FETCH_ASSOC);
$total=$total[0]['count'];
$current_status[$j]=$total;
$channels[$j]++;
}
$full_status[]=array_sum($current_status);
}
echo json_encode(array("data"=>$full_status));
?>
``` | 2016/02/02 | [
"https://Stackoverflow.com/questions/35143944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4722559/"
] | You haven't allocated any space for `input` to point to. I saw your
earlier version had a `malloc`; you can use that, or just a `char`
array.
Did you mean to use `data`? Because you're not, yet.
`fgets` reads at most one line at a time, so you need to put your reads
in a loop.
You appear to be converting the string to a number multiple times. For
instance, if the first line were `"12345"`, this code would get `12345`,
then `2345`, `345`, etc. This was presumably not your intention.
You're incrementing `i` up to `size`. `size` is the file size and might
be quite large, but you only read a maximum of 64 characters into the
buffer. (Or would have, if space had been allocated.)
In short, this code is very confused and I recommend starting over from
scratch. Decide whether you want to read the entire file at once, or one
line at a time; I recommend the latter, it takes less memory and is
simpler. If you want to store them in an array, you can do that with
`malloc` and then `realloc` as needed to grow the array dynamically. | do not use strtol, use atoi instead.
and use a loop to read the lines.
just a quick answer:
```
int count = 0;
while( fgets (input, 64, fp) != NULL )
{
count++;
}
fseek(fp, 0, SEEK_SET);
int* arr = new int[count];
count = 0;
while( fgets (input, 64, fp) != NULL )
{
int a =atoi(input);
arr[count++] = a;
}
``` |
71,306,107 | **UPDATE**
Busy with an optimization on battery storage, I face an issue while trying to optimize the model based on loops of 36 hours, for example, running for a full year of data.
By doing this, I reinitialize the variable that matters at each step and therefore compromising the model. How to extract the last value of a variable and use it for the next iteration as first value ? Here is the problem in a simple way:
```
#creation of list to store last variable values:
df1=[]
df2=[]
df3=[]
# Loop
for i in range (0,3)
step = 36
first_model_hour = step * i
last_model_hour = (step * (i+1)) - 1
model = ConcreteModel()
model.T = Set(doc='hour of year',initialize=df.index.tolist())
model.A = Var(model.T, NonNegativeReals)
model.B = Var(model.T, NonNegativeReals)
model.C = Var(model.T, NonNegativeReals)
def constraints_x(model,t)
for t == 0
return model.C == 100
elif t == first_model_hour
return model.C[t] == model.A[from previous loop] + model.B[from previous loop] + model.C[from previous loop]
else
return model.C[t] == model.A[t-1]+model.B[t-1]+model.C[t-1]
model.constraint = Constraint(model.T, rule=constraint_x)
solver = SolverFactory('cbc')
solver.solve(model)
df1.append(model.S[last_model_hour])
df2.append(model.B[last_model_hour])
df3.append(model.C[last_model_hour])
```
Is it possible to retrieve the last value of variables from pyomo to use it a initialization for the next loop and hence not loosing the continuous state of charge of the battery over time ? | 2022/03/01 | [
"https://Stackoverflow.com/questions/71306107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18099078/"
] | There are examples of how to INVOKE AWS Services from a Spring BOOT app. Here are a few that show use of the **AWS SDK for Java V2**:
1. [Creating your first AWS Java web application](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_first_project)
2. [Creating a dynamic web application that analyzes photos using the AWS SDK for Java](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_photo_analyzer_app).
3. [Creating the Amazon DynamoDB web application item tracker](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_dynamodb_web_app)
There are more Spring BOOT/AWS Service examples in [Github](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases).
While there are no Spring BOOT examples for Kendra client (yet), the pattern is the same. You can build a MVC app and build a service that uses <https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/kendra/KendraClient.html>. | You can use the [AWS SDK for Java](https://aws.amazon.com/sdk-for-java/) to make API calls to AWS services. You can find code examples in the link above.
Setting up your Kendra client will look something like this:
```
String accessKey = "YOUR_ACCESS_KEY";
String secretKey = "YOUR_SECRET_KEY";
BasicAWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
AWSkendra kendraClient = AWSkendraClientBuilder
.standard()
.withCredentials(new AWSStaticCredentialsProvider(awsCredentials))
.build();
```
After you set up your Kendra client, you can then use the [query method](https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/kendra/AWSkendra.html#query-com.amazonaws.services.kendra.model.QueryRequest-) to query your Kendra index. |
18,618,459 | I'm tearing my hair out trying to do what should be a really simple adjustment to a macro.
copy and paste doesn't seem to work. I get a property not supported error.
All I am trying to do is copy all cell contents from the original activesheet in the originating workbook (which will be sName) and paste it to the new workbook sheet(rvname)
Here is my current code: (I need it to work in excel 2003 and 2007)
```
Sub create_format_wb()
'This macro will create a new workbook
'Containing sheet1,(job plan) Original, (job plan) Revised, and 1 sheet for each task entered in the inputbox.
Dim Newbook As Workbook
Dim i As Integer
Dim sName As String
Dim umName As String
Dim rvName As String
Dim tBox As Integer
Dim jobplannumber As String
Dim oldwb As String
line1:
tBox = Application.InputBox(prompt:="Enter Number of Tasks", Type:=1)
If tBox < 1 Then
MsgBox "Must be at least 1"
GoTo line1
Else
sName = ActiveSheet.Name
umName = (sName & " Original")
rvName = (sName & " Revised")
jobplannumber = sName
Set Newbook = Workbooks.Add
With Newbook
.Title = sName
.SaveAs Filename:=(sName & " .xls")
.Application.SheetsInNewWorkbook = 1
.Sheets.Add(, After:=Sheets(Worksheets.Count)).Name = umName
Worksheets(umName).Range("A1").Select
With Worksheets(umName).QueryTables.Add(Connection:= _
"ODBC;DSN=MX7PROD;Description=MX7PROD;APP=Microsoft Office 2003;WSID=USOXP-93BPBP1;DATABASE=MX7PROD;Trusted_Connection=Yes" _
, Destination:=Range("A1"))
.CommandText = Array( _
"SELECT jobplan_print.taskid, jobplan_print.description, jobplan_print.critical" & Chr(13) _
& "" & Chr(10) & "FROM MX7PROD.dbo.jobplan_print jobplan_print" & Chr(13) & "" & Chr(10) _
& "WHERE (jobplan_print.jpnum= '" & jobplannumber & "' )")
.Name = "Query from MX7PROD"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.Refresh BackgroundQuery:=False
End With
.Worksheets(umName).UsedRange.Columns.AutoFit
.Sheets.Add(, After:=Sheets(Worksheets.Count)).Name = rvName
For i = 1 To tBox
.Sheets.Add(, After:=Sheets(Worksheets.Count)).Name = ("Task " & i)
Next i
End With
Worksheets(rvName).UsedRange.Columns.AutoFit
End If
End Sub
```
Can somone walk me through how to go about this?
Any help appreciated. | 2013/09/04 | [
"https://Stackoverflow.com/questions/18618459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2747573/"
] | You could do something like this:
```
Sub Copy()
Workbooks("Book1").Worksheets("Sheet1").Cells.Copy
Workbooks("Book2").Worksheets("Sheet1").Range("A1").Select
Workbooks("Book2").Worksheets("Sheet1").Paste
End Sub
```
FYI, if you record macros in Excel while doing the operations you'd like to code, you can often get what you're looking for with minimal modifications to the automatically-generated macro code. | Would you consider copying the worksheet as a whole? Here's a basic example, you'll have to customize your workbook organization and naming requirements.
```
Sub CopyWkst()
Dim wksCopyMe As Worksheet
Set wksCopyMe = ThisWorkbook.Worksheets("Sheet1")
wksCopyMe.Copy After:=ThisWorkbook.Sheets(Worksheets.Count)
ThisWorkbook.ActiveSheet.Name = "I'm New!"
End Sub
``` |
1,345,506 | I absolutely loved [Dive Into Python](http://www.diveintopython.net/) when I picked up Python.
In fact, "tutorials" such as Dive Into Python work really well for me; short brief syntax explanations, and plenty of examples to get things going.
I learn really well via examples.
I have programming experience in Java, Scheme, Python, PHP, Javascript, etc.
Is there anywhere you would recommend online to quickly pick up the C programming language, and best practices? | 2009/08/28 | [
"https://Stackoverflow.com/questions/1345506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/118644/"
] | Install an open source unix operating system. Use it. Tweak it. You'll be sitting on a mountain of C code organized into projects of all sizes, all easily available as source. if you don't make an effort to stay in the *user* category, you're bound to make incremental inroads into C and keep the learning process 100% practical.
The great advantage of this approach is that, since programming techniques, code structure and alike are extremely volatile among project, you get to see very early what works in which circumstances. It may require more active participation (asking questions on mailing lists or programming sites) than following a course outlined by a book author, but you'll probably pick up some idioms useful in the real world earlier.
At least that's the way I got into C, and it was fun, relevant and rewarding every single minute (fun rhymes with frustrating, well, learning hurts). | If you really want an online tutorial you can try <http://einstein.drexel.edu/courses/Comp_Phys/General/C_basics/>. It covers the basics and also points out some general C conventions.
That said, K&R is the Bible and if you are serious about learning C then it is almost mandatory reading. |
26,043,411 | I am trying to modify an Android app to suit my need.
The original app has page 1 to display list of notes, and page 2 displays the detailed note.
What I'm trying to achieve is instead of having only 1 textbox in the detailed note page, I want it to have several textboxes, and persist it as well.
Here is how I thought it would be (but failed miserably of course).
This the transmitter on the page 2 (detailed page) activity:
```
private void saveAndFinish()
{
EditText et = (EditText) findViewById(R.id.eventTitle);
String eventTitle = et.getText().toString();
EditText et2 = (EditText) findViewById(R.id.eventDate);
String eventDate = et2.getText().toString();
EditText et3 = (EditText) findViewById(R.id.eventVenue);
String eventVenue = et3.getText().toString();
EditText et4 = (EditText) findViewById(R.id.eventLocation);
String eventLocation = et4.getText().toString();
EditText et5 = (EditText) findViewById(R.id.eventNote);
String eventNote = et5.getText().toString();
EditText et6 = (EditText) findViewById(R.id.eventAttendees);
String eventAttendees = et6.getText().toString();
Intent intent = new Intent();
// pass these to the main activity will ya?
intent.putExtra("key", data.getKey());
intent.putExtra("title", eventTitle); // eventTitle is the edited text!
intent.putExtra("date", eventDate);
intent.putExtra("venue", eventVenue);
intent.putExtra("location", eventLocation);
intent.putExtra("note", eventNote);
intent.putExtra("attendees", eventAttendees);
setResult(RESULT_OK, intent);
// work done, go back to calling activity
finish();
}
```
This the receiver on the page 1 (main page) activity:
```
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode==DETAIL_ACTIVITY_REQ && resultCode==RESULT_OK)
{
DataItem event = new DataItem();
event.setKey(data.getStringExtra("key"));
event.setTitle(data.getStringExtra("title"));
event.setDate(data.getStringExtra("date"));
event.setVenue(data.getStringExtra("venue"));
event.setLocation(data.getStringExtra("location"));
event.setNote(data.getStringExtra("note"));
event.setAttendees(data.getStringExtra("attendees"));
datasource.update(event);
refreshDisplay();
}
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
// which list view item was selected?
DataItem data = eventsList.get(position);
//now, to navigate. which class should i go to next?
Intent intent = new Intent(this, DetailedActivity.class);
// and also, pass data to the next activity will ya?
intent.putExtra("key", data.getKey());
intent.putExtra("title", data.getTitle());
intent.putExtra("date", data.getDate());
intent.putExtra("venue", data.getVenue());
intent.putExtra("location", data.getLocation());
intent.putExtra("note", data.getNote());
intent.putExtra("attendees", data.getAttendees());
// go go go!
startActivityForResult(intent, DETAIL_ACTIVITY_REQ);
}
```
Apparently only the "title" is saved, everything else is not. Help? | 2014/09/25 | [
"https://Stackoverflow.com/questions/26043411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2804102/"
] | `update-java-alternatives -l` will list all the java versions installed via the alternatives system.
For instance on one of my systems it will display the version and the path:
```
java-1.6.0-openjdk-amd64 1061 /usr/lib/jvm/java-1.6.0-openjdk-amd64
java-7-oracle 1069 /usr/lib/jvm/java-7-oracle
```
If you want the oracle one then I guess you could do:
```
update-java-alternatives -l | grep oracle | awk '{ print $1 }'
```
This would alternatively find all oracle versions and issue the `-version` command against each one in the list:
```
update-java-alternatives -l | grep oracle | awk '{system($3"/bin/java -version")}'
```
Output may look something like this:
```
java version "1.7.0_67"
Java(TM) SE Runtime Environment (build 1.7.0_67-b01)
Java HotSpot(TM) 64-Bit Server VM (build 24.65-b04, mixed mode)
```
One step further would be to parse out the java version from the `-version` command and simply display it:
```
(update-java-alternatives -l | grep oracle | awk '{system(""$3"/bin/java -version 2>&1 | grep \"java version\"")}') | awk -F\" '{print $2}'
```
The `2>&1` is needed because Java will display version to standard error. The output would simply look like this (and could be easily assigned to a bash variable if you needed it that way):
```
1.7.0_67
```
If you had multiple oracle instances this would display the version for each one. If you wanted to find all the versions for every Java you could simply remove the `| grep oracle` | Go to the installation folder of the oracle Java, and then open the `bin` folder. Now open a terminal "here" and type `java -version`
alternativelly,
paste the entire path to that bin folder in the command line followed by `java -version` i.e. `/path/to/bin/java -version` |
1,580,758 | I'm using Eclipse to develop a Java program, and figured I'd add an option to my program to parse stdin if there are no arguments. (otherwise it parses a file)
I am having problems if I execute `"somecommand | java -jar myjar.jar"` and went to debug... then realized I don't know how to start a process in Eclipse like that. And if I run it on the command prompt, I can't attach to a running process since the process starts immediately.
Any suggestions on how to debug?
**edit**: see, the thing is, I wrote my program originally to take a filename argument. Then I figured it would be useful for it to take stdin as well, so I *did* abstract InputStream out of my program (as Mr. Queue suggests). It works fine operating on a file (`java -jar myjar.jar myfile`), but not operating when I run `type myfile | java -jar myjar.jar`. I suspect that there's something different in the two scenarios (eof detection is different?) but I really would like to debug.
```
// overall program structure follows:
public static void doit(InputStream is)
{
...
}
public static void main(String[] args)
{
if (args.length > 0)
{
// this leaves out the try-catch-finally block,
// but you get the idea.
FileInputStream fis = new FileInputStream(args[0]);
doit(fis);
fis.close();
}
else
{
doit(System.in);
}
}
``` | 2009/10/16 | [
"https://Stackoverflow.com/questions/1580758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44330/"
] | Run your app, with the pipe, on the command line but add JVM args for remote debugging, like this:
```
-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=1044
```
`suspend=y` will tell the JVM to not actually run the program until the debugger is attached.
Next, go into the Eclipse debug launch configurations (`Run -> Debug Configurations...`) and create a "Remote Java Application" to connect to your app. Run the launch in Eclipse (after setting some breakpoints) and you should be able to debug. Not terribly convenient, but if you can't reproduce your issues without the pipe, this is an option. | If I'm interpreting your question right, I believe you just want to know how to send input across standard in and debug through it in eclipse.
If it's simple input, you can actually manually enter System.in data via the eclipse Console window while the program is running. Just start typing in the console window, and press enter to send the text to Standard in.
If it's something more complicated, I'd suggest abstracting the read you're trying to do to take an InputStream. In your program, you can send System.in as the InputStream. To Debug, you can send any other InputStream. For example, you could put your input in a file, and pass a FileInputStream to the method to test it.
EDIT:
Without seeing some more code, I'm not sure, but you might be on to something with eof detection. A FileInputStream has a defined end of file, but I'd guess System.in has nothing of the sort. Your reader might just be waiting to read the next character and never advancing. You might have to manually stop the read after you know you've read "enough". |
2,931,234 | I am trying to get the value of first td in each tr when a users clicks "click".
The result below will output aa ,ee or ii. I was thinking about using closest('tr').. but it always output "Object object". Not sure what to do on this one.
My html is
```
<table>
<tr>
<td>aa</td>
<td>bb</td>
<td>cc</td>
<td>dd</td>
<td><a href="#" class="hit">click</a></td>
</tr>
<tr>
<td>ee</td>
<td>ff</td>
<td>gg</td>
<td>hh</td>
<td><a href="#" class="hit">click</a></td>
</tr>
<tr>
<td>ii</td>
<td>jj</td>
<td>kk</td>
<td>ll</td>
<td><a href="#" class="hit">click</a></td>
</tr>
</table>
```
Jquery
```
$(".hit").click(function(){
var value=$(this).// not sure what to do here
alert(value) ;
});
``` | 2010/05/28 | [
"https://Stackoverflow.com/questions/2931234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/401147/"
] | ```
$(this).parent().siblings(":first").text()
```
`parent` gives you the `<td>` around the link,
`siblings` gives all the `<td>` tags in that `<tr>`,
`:first` gives the first matched element in the set.
`text()` gives the contents of the tag. | ```
$(".hit").click(function(){
var values = [];
var table = $(this).closest("table");
table.find("tr").each(function() {
values.push($(this).find("td:first").html());
});
alert(values);
});
```
You should avoid `$(".hit")` it's really inefficient. Try using event delegation instead. |
39,673,700 | I think much explanation is not required, why below calculation gives result as 1?
```
int a = 2147483647;
int b = 2147483647;
int c = a * b;
long d = a * b;
double e = a * b;
System.out.println(c); //1
System.out.println(d); //1
System.out.println(e); //1.0
``` | 2016/09/24 | [
"https://Stackoverflow.com/questions/39673700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4117061/"
] | 2147483647 \* 2147483647 = 4611686014132420609
Which in Hexa = 3FFFFFFF 00000001, after truncation only 00000001 remains which represents 1. | First of all, the reason that the three attempts all give the same answer is that they are all performing 32 bit multiplications and the multiplication overflows, resulting in "loss of information". The overflow / loss of information happens *before* the value of the RHS1 expression is assigned to the variable on the LHS.
In the 2nd and 3rd case you could cause the expression to be evaluated using 64 bit or floating point:
```
int c = a * b;
long d = ((long) a) * b;
double e = ((double) a) * b;
```
and you would not get overflow.
As to why you get overflow in the 32 bit case, that is simple. The result is larger than 32 bits. The other answers explain why the answer is `1`.
Just for fun, here is an informal proof.
Assume that we are talking about a modular number system with numbers in the range 2N-1 to 2N-1 - 1. In such a number system, X \* 2N maps to zero ... for all integers X.
If we multiply the max value by itself we get
>
> (2N-1 - 1) \* (2N-1 - 1)
>
>
> -> 22N-2 - 2 \* 2N-1 + 1
>
>
> -> 22N-2 - 2N + 1
>
>
>
Now map that into the original range:
>
> 22N-2 maps to 0
>
>
> 2N maps 0
>
>
> 1 maps to 1
>
>
> 0 + 0 + 0 -> 1
>
>
>
---
1 - LHS == left hand side, RHS == right hand side. |
46,526,736 | Why does the following code not print "Hello, World!"?
```
using System;
namespace Test
{
public class Program
{
public static void Main(string[] args)
{
var a = new A();
var b = new B(a);
b.Evnt += val => Console.WriteLine(val);
a.Do();
}
}
public class A
{
public void Do()
{
Evnt("Hello, World!");
}
public event Action<string> Evnt = v => {};
}
public class B
{
public B(A a)
{
a.Evnt += Evnt; // this does not work
}
public event Action<string> Evnt = v => {};
}
}
```
But if I replace line
```
a.Evnt += Evnt;
```
with
```
a.Evnt += v => Evnt(v);
```
everything works fine.
If this is forbidden to do so, what meaning has subscribing one event to another, and why are there no compilation errors or warnings when doing so? | 2017/10/02 | [
"https://Stackoverflow.com/questions/46526736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4586004/"
] | It fails for the same reason this code prints "2":
```
int x = 2;
int y = x;
Action a = () => Console.WriteLine(y);
x = 3;
a();
```
Here, your event handler is the value of `a.Evnt` *at the time of assignment* -- whatever `a` has for `Evnt` at the time when you pass `a` into `B`'s constructor, that's what `B` gets for an event handler.
```
public B(A a)
{
a.Evnt += Evnt; // this does not work
}
```
It actually works fine -- it does what you told it to. It's just that you thought you were telling it to do something different.
Here, you have a handler that evaluates `Evnt` itself, at whatever time the handler is executed. So with this one, if `a.Evnt` is changed in the mean time, you'll see the output from the new value of `a.Evnt`.
```
public B(A a)
{
a.Evnt += v => Evnt(v);
}
```
Rewrite B like this, and you'll get a clearer picture:
```
public class B
{
public B(A a)
{
a.Evnt += Evnt; // this does not work
}
public event Action<string> Evnt = v => { Console.WriteLine("Original"); };
}
```
The title of your question isn't well phrased; you're not assigning an event, you're assigning an event handler. Also, "this does not work" is not a useful way to describe a problem. There is an infinity of ways for things not to work. My first assumption was that your code wouldn't even compile. Next time, please describe the behavior you expected to see, and what you actually saw instead. Say whether it failed to compile, or threw an exception at runtime, or just quietly did something you didn't anticipate. If there's an error message or an exception message, provide the text of the message. | Because lambda evaluates and captures on call, otherwise += attaches once and then called on ref (without evaluation) |
34,279,946 | I am trying to declare an array of `Set<String>` so I do not have to manage each sets separately. But things go wrong:
```
ArrayList<Set<String>> categories=new LinkedHashSet<>();
```
Here, Java says that type `Set<String>` is erroneous and then reports an error.
If this is wrong, then how can I make an array of :
```
static Set<String> category1 = new LinkedHashSet<>();
``` | 2015/12/15 | [
"https://Stackoverflow.com/questions/34279946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1042952/"
] | You are initialising an ArrayList with LinkedHashSet object and hence the error:
```
ArrayList<Set<String>> categories=new LinkedHashSet<>();
```
change it to
```
ArrayList<Set<String>> categories=new ArrayList<>();
```
you need to use HashSet when you create a Set to be added into the list. Something like this:
```
Set<String> firstSet = new HashSet<String>();
//build your set
//add set to list
categories.add(firstSet);
```
Btw, you mentioned Array in your question description, so here is the declaraiton for plain array of Sets:
```
Set<String>[] categories=new HashSet[10];
``` | You can do something like:
```
List<HashSet> list =new ArrayList<HashSet>();
HashSet<String> hs =new HashSet<String>();
hs.add(value1);
hs.add(value2);
list.add(hs);
```
You can use for or while loop to add values to set(hs) and then add the set to list. |
9,693,161 | Here's the situation. I have an NSTimer in Appdelegate.m that performs a method that checks the users location and logs him out if he is out of a region. When that happens I want to load the login view controller. However, with the following lines of code, I am able to see the VC but if I click on a textfield to type, I get a sigbart. Any ideas how to load the initial VC from app delegate correctly?
```
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle: nil];
LoginViewController *loginViewController = (LoginViewController *)[mainStoryboard instantiateViewControllerWithIdentifier:@"Login"];
[self.window addSubview:loginViewController.view];
[self.window makeKeyAndVisible];
``` | 2012/03/13 | [
"https://Stackoverflow.com/questions/9693161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/981512/"
] | Both audiophilic and Flaviu 's approaches are ok. But both of you are missing one extra line of code.
I found out that you have to allocate and init the UIWindow object first. I dont know why but initializing the object solved the problems.
```
self.window=[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
```
**audiophilic's approach:**
```
self.window=[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle: nil];
ResultsInListViewController *resultsInListViewController = (ResultsInListViewController *)[mainStoryboard instantiateViewControllerWithIdentifier:@"ResultsInListViewController"];
[self.window addSubview:resultsInListViewController.view];
[self.window makeKeyAndVisible];
```
**Flaviu's approach:**
```
self.window=[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle: nil];
ResultsInListViewController *resultsInListViewController = (ResultsInListViewController *)[mainStoryboard instantiateViewControllerWithIdentifier:@"ResultsInListViewController"];
[self.window setRootViewController:resultsInListViewController];
[self.window makeKeyAndVisible];
``` | This is the code I use when I want to change views:
```
#import "LoginViewController.h"
LoginViewController *screen = [[LoginViewController alloc] initWithNibName:nil bundle:nil];
screen.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController:screen animated:YES];
//or
[self.window addSubView:screen];
```
Using that code will create a brand new instance of it and show it, so it should accomplish your question. You may have to move some things around, but it should work.
Let me know if you need any more help.
Hope this helps you! |
60,290,836 | I'm pretty new to React, I'm trying to return a JSX from a method, code as follows:
```js
import React, { useReducer } from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import * as serviceWorker from './serviceWorker';
const formatName = (user) => {
return user.firstName + ' ' + user.lastName;
}
const getGreeting = (user) => {
if (user) {
return {greeting}
}
else {
return {forbidden}
}
}
const user = {
firstName: 'John',
lastName: 'Smith'
};
const greeting = (
<h1>Hello {formatName(user)}</h1>
);
const forbidden = (
<h1>Hello stranger!</h1>
);
const element = (
<div>{getGreeting(user)}</div>
);
ReactDOM.render(
element, document.getElementById('root')
);
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
```
As you can see, `element` contains a div which I wish to render `getGreeting`, since `user == true`, it should return `greeting`, which calls the method `formatName`. However it returns an error:
```
Error: Objects are not valid as a React child (found: object with keys {greeting}). If you meant to render a collection of children, use an array instead.
```
What am I doing wrong here? | 2020/02/18 | [
"https://Stackoverflow.com/questions/60290836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8720421/"
] | `getGreeting` should return a JSX and not an object
try this:
```
const greeting = (
<h1>Hello {formatName(user)}</h1>
);
const forbidden = (
<h1>Hello stranger!</h1>
);
const getGreeting = (user) => {
if (user) {
return greeting
}
else {
return forbidden
}
}
``` | In JavaScript, when you write:
`return {greeting}`
...what you are saying is "return an object, with a property named 'greeting', which is set to value of the variable `greeting`"
The last part of that, where the value is set, is an ES6 shortcut, essentially replacing `{ "greeting": greeting }` with `{greeting}` for brevity's sake.
In other words, you are currently returning an object with a single property, "greeting", which is basically what your error message says.
What you are returning is:
```
{
"greeting": <h1>Hello ... </h1>
}
```
What you want to return is:
```
<h1>Hello ... </h1>
```
Since your `greeting` const is valid JSX, you can just return it directly! i.e. `return greeting;` |
47,015,853 | I define `arr = []` before anything else. Why do I get an error when my class references it?
```
arr = []
class BST:
key = 0
left = None
right = None
height = 0
index = 0
def __init__(self):
height = 0
def __str__(self):
return str(self.key)
def populate(self):
print("populating")
print(self.key)
if (self.left != None):
arr = arr + [self.left.populate()]
if (self.right != None):
arr = arr + [self.right.populate()]
return self.key
m1 = BST()
m1.key = 3
m2 = BST()
m2.key = 5
m1.left = m2
print(m1.left != None)
m3 = BST()
m3.key = 6
m2.left = m3
res = m1.populate()
print(res)
```
```none
~/py/python bst.py
True
populating
3
Traceback (most recent call last):
File "bst.py", line 41, in <module>
res = m1.populate()
File "bst.py", line 22, in populate
arr = arr + [self.left.populate()]
UnboundLocalError: local variable 'arr' referenced before assignment
~/py/
``` | 2017/10/30 | [
"https://Stackoverflow.com/questions/47015853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172232/"
] | Your concern is valid. Reading suitable [reference documentation for `std::thread`](http://en.cppreference.com/w/cpp/thread/thread/%7Ethread) tells us that on destruction:
>
> If `*this` has an associated thread (`joinable() == true`), `std::terminate()` is called.
>
>
>
So destroying `t` without either detaching or joining it will end your program.
You therefore have two options, depending on what you want to happen. If you want the function to wait for the thread to finish, call `t.join()` before returning. If you instead want the thread to keep running after the function returns, call `t.detach()`. | Yes it is a reason of concern. The code will not work as intended. You can either do
```
t.join ()
```
This should be written if you want your main function to wait till execution of the threaded func. is completed.
Or
```
t.detach ()
```
This should be called if you want the threaded func. to run independently, i mean main func. should not wait for it complete.
You can also use Sleep (x). If you want the function to run for x seconds only.
Calling terminate() is generally not recommended as it kills all threads including main () thread. There is no need to kill a thread. When the finction running in a thread completes the threads automatically cleans itself up.
Refer to this: [How to Destroy a thread object](https://stackoverflow.com/q/46827203/8619231) |
38,794,206 | Suppose I have a Matrix class and I'd like to initialize my Matrix objects in two ways:
```
Matrix a = {1,2,3} // for a row vector
```
and
```
Matrix b = {{1,2,3},{4,5,6},{7,8,9}} // for a matrix
```
As a result, I implemented two copy constructors as below
```
class Matrix {
private:
size_t rows, cols;
double* mat;
public:
Matrix() {}
Matrix(initializer_list<double> row_vector) { ... }
Matrix(initializer_list< initializer_list<double> > matrix) { ... }
...
}
```
No matter how I change my interface, such as adding an `explicit` keyword or change the nested version to `Matrix(initializer_list< vector<double> > matrix)`. It will always cause ambiguities between these two cases:
```
Matrix a = {1,2,3};n
Matrix b = {{1}, {2}, {3}};
```
I'm not quite familiar with the stuff like direct/copy initialization or implicit type conversion. Are there any solutions for this problem? | 2016/08/05 | [
"https://Stackoverflow.com/questions/38794206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3970363/"
] | Well, here's a very dirty trick:
```
#include <iostream>
#include <initializer_list>
struct Matrix
{
template<class = void> Matrix(std::initializer_list<double>) { std::cout << "vector\n"; }
Matrix(std::initializer_list<std::initializer_list<double>>) { std::cout << "matrix\n"; }
};
int main()
{
Matrix a = {1, 2, 3};
Matrix b = {{1}, {2}, {3}};
(void)a; (void)b;
}
```
The two overloads cannot be distinguished based on conversions, so we rely on a subsequent step in the overload resolution process: a non-template function is preferred over a template specialization. | Why not just create one constructor that takes a matrix, create a private function copy and inside copy you check for a row\_vector.
```
private void Matrix::copy(const Matrix &matrix)
{
if (matrix.rows == 1)
{
//row vector stuff here
}
else if (matrix.cols == 1)
{
//col vector stuff here
}
else
{
//matrix stuff here
}
}
``` |
40,079,575 | [](https://i.stack.imgur.com/bBdj7.png)
I want to put button like above picture. But I have below image. I can't success this. Search a lot of but can't find it.
[](https://i.stack.imgur.com/XYJoz.png)
LinearLayout in LinearLayout has transparent background and there is button left of this.
Activity.xml :
```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/genel_arkaplan"
android:orientation="vertical" >
<LinearLayout
android:orientation="vertical"
android:layout_width="750dp"
android:layout_height="wrap_content"
android:paddingLeft="40dp"
android:layout_gravity="center_vertical|center_horizontal"
android:background="@drawable/lay_transparan_aramasecenek"
android:layout_marginTop="100dp">
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/lay_transparan_aramasecenek_beyaz">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="fitCenter"
android:background="@drawable/kod_ile_arama"
android:id="@+id/imageButton" />
</LinearLayout>
</LinearLayout>
``` | 2016/10/17 | [
"https://Stackoverflow.com/questions/40079575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6249798/"
] | remove `android:paddingLeft="40dp` from **LinearLayout** Tag | Just remove below code from your "LinearLayout"
```
android:paddingLeft="40dp"
```
This is adding extra padding to your parent layout.
Below will be your final code.
```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/genel_arkaplan"
android:orientation="vertical" >
<LinearLayout
android:orientation="vertical"
android:layout_width="750dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:background="@drawable/lay_transparan_aramasecenek"
android:layout_marginTop="100dp">
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/lay_transparan_aramasecenek_beyaz">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="fitCenter"
android:background="@drawable/kod_ile_arama"
android:id="@+id/imageButton" />
</LinearLayout>
</LinearLayout>
``` |
1,988,503 | An Excel table consists of two columns (e.g., A1:B5):
```
0 10
1 20
3 30
2 20
1 59
```
I need to get the minimal value in column B for which the corresponding value in column A is greater than zero. In the above example it should be 20.
I tried using various combinations of INDEX(), MIN(), IF(), ROW(), array formulas, etc. - but I just can't figure out how to do it. :-( Any help would be appreciated. | 2010/01/01 | [
"https://Stackoverflow.com/questions/1988503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/241914/"
] | Grsm almost had it
if you enter the following formula in C1 as an array (Ctrl+Shift+End)
```
=MIN(IF(A1:A5>0,B1:B5))
```
That should do the trick. | You need to do it in 2 stages
* First use the MIN function to find the minimum
* Then take that answer and use the LOOKUP function to select the row and column that you need. |
3,529,386 | For our application, we need to get all the US interstate highway exits along with their Geocodes. Can you please explain how to get these using Google Maps API or Google Local search or otherwise? So far I have no clue as to how to proceed. I greatly appreciate if you can point me in right direction.
I am looking for a free or a paid solution that is around $1000. I know there are people who provide geocodes. But they are out of our budget. | 2010/08/20 | [
"https://Stackoverflow.com/questions/3529386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/186148/"
] | You might be able to extract the data you need from [openstreetmap](http://www.openstreetmap.org). I shortly looked at the API they are providing, but it seems rather difficult to extract the data, although not impossible. | You can easily buy this data from Esri and it is very accurate stuff:
<http://www.esri.com/products/index.html#data_panel>
I also recommend checking on <https://gis.stackexchange.com/>, as someone there might know a free resource. |
86,125 | I have a laser and a container of water. Putting the laser beam into the water at a certain angle makes all of the laser beam reflected and none of it refracted, so no laser gets above the water. I wanted to take a photo with the lights off of such an experiment, but the results are extremely poor.
Here is a photo of my setup with light on:
[](https://i.stack.imgur.com/mL1mG.jpg)
As you can see, there is no laser beam above the water: total reflection. How can I shoot a photo of such an experiment with the lights off so that the actual laser beam is visible? It looks really good in real life. | 2017/01/09 | [
"https://photo.stackexchange.com/questions/86125",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/59835/"
] | >
> How to shoot a photo of such experiment with lights off so that the actual laser beam is visible?
>
>
>
The thing about a laser beam is that all the light is traveling in the same direction, so none of it is leaving the beam and heading toward your camera. If you shine a laser pointer at the wall, for example, you generally don't see the beam at all -- you only see the spot on the wall. If you want to see the beam, you need to add something to disperse the beam to the medium (the air in the room or the water in your tank) through which the beam is traveling. If you've ever been to a rock concert that uses lasers in the lighting, you probably noticed that they always use smoke or fog machines along with the lasers to make the beams visible.
You probably won't need to add much to the water to get the beam to show up brighter. It sounds like you can already see the beam with the naked eye, so it's possible that you just need a dark room and larger aperture and/or slower shutter speed and/or higher ISO to get a good exposure from the laser. But stirring a small quantity of some very fine particulate matter into the water will help disperse the beam and make for a much better photo. I'd start with very fine particulate like wood flour (like sawdust, but much finer), abrasive powder, powdered metal, etc. You might want to experiment with different additives, as you might get different results. For example, I'd guess that a very small amount of powdered mica would give you a sort of sparkly effect, whereas something that just makes the water a little cloudy (a little milk, maybe?) would give a more solid line.
One more thing I'd do to get the best photo would be to use a tank with very clean, clear walls, like a small glass fish tank. The plastic container shown in your photo looks rather cloudy, scratched, and just less attractive than it could be. Put a black sheet of black or white paper behind the tank, depending on what you want the background to look like. | I followed the advice in the accepted answer and added some iron powder into the water, so that the laser can reflect more hitting the impurities. The result is fine considering the very low quality camera and very low power laser I am using:
[](https://i.stack.imgur.com/Rldmf.jpg) |
30,267,223 | While this seems simple at first glance, I'm having trouble getting what I want. I have many DIVs on a page with the same class which I use to find their text contents:
```
var Name = $(".class").text();
```
While this works, it returns all of the text from all DIVs on the page at once such as
```
Name1Name2Name3Name4Name5
```
I am calling this request from a jQuery onclick event that is inside one of these DIVs. So my goal is to get the contents of the DIV that the onclick was fired from, not everything. The end result would be if I press the onclick from Name 3 it would only get the contents for that DIV, thus giving me Name3 only.
The DIV does have a unique ID I can also check against but I can't figure out how to use that to my advantage. The DIV structure looks like:
```
<div id="2242yrcwrmz5t1zyt03" class="class1" tabindex="-1">
```
Thank you! | 2015/05/15 | [
"https://Stackoverflow.com/questions/30267223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1763917/"
] | So read the text from the current div with `this`
```
$(".class").on("click", function() {
console.log($(this).text());
});
``` | I believe you need to use the `event.target` property to find the element that you actually clicked on.
Assuming your DIV that contains Name1, Name2, etc. has the id `outerElement`:
```
$("#outerElement").on("click", function(e) {
var Name = $(e.target).text();
});
```
More info here:
<https://api.jquery.com/category/events/event-object/> |
36,776,784 | I am trying to capitalize the first character of a `std::string`, using the same method [mentioned here](https://stackoverflow.com/questions/8530529/convert-first-letter-in-string-to-uppercase). For example for the following program
```
#include <cctype>
#include <iostream>
#include <string>
int main()
{
std::string name = "foobar";
name[0] = std::toupper(name[0]);
std::cout << name;
}
```
I am expecting the output to be
```
Foobar
```
When I [compile this online](http://cpp.sh/8vjl) (using GCC 4.9.2) I get the correct output **without any warnings**. However, when I compile the same code in Visual Studio 2013, I get a warning during the assignment back from `toupper`
```
warning C4244: '=' : conversion from 'int' to 'char', possible loss of data
```
Is the above method valid according to the C++ standard or is the warning correct? Otherwise is this just a false warning by Visual Studio? | 2016/04/21 | [
"https://Stackoverflow.com/questions/36776784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2296458/"
] | The warning is correct as far the types go; the type of `std::toupper` as defined in the standard is:
```
int toupper( int ch );
```
Mostly because it's a remnant from the dark C ages (the `cctype` header is a hint at that).
However, this is just a part of the story. There's *another* `toupper` residing in the `locale` header:
```
template< class charT >
charT toupper( charT ch, const locale& loc );
```
This one shouldn't give you any warnings. If you're not sure what locale to provide, `std::locale()` will give you the default one. | [`std::toupper`](http://en.cppreference.com/w/c/string/byte/toupper) comes from the C standard, not C++, and has an annoying interface in that it takes and returns an `int` not a `char`. Using `static_cast<char>(std::toupper(name[0]))` will suit you. |
33,401,522 | Hi I am trying to make this program work without using reverse or sort functions in python 3. It is simply supposed to check for palindromes. The problem I am running into is that I get an index out of range everytime I run it. Is there a way to work around this?
```
def is_palindrome(word):
if len(word) <= 1:
return True
else:
left = 0
right = len(word) - 1
while left < right:
if word[left] == word[right]:
left += 1
right += 1
else:
return False
return True
is_palindrome("mom")
is_palindrome("root")
is_palindrome("racecar")
``` | 2015/10/28 | [
"https://Stackoverflow.com/questions/33401522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4914525/"
] | `right += 1` should be `right -= 1`. | You can write it a bit more succinctly.
```
>>> def is_palin(w):
... return len(w) <= 1 or (w[0] == w[-1] and is_palin(w[1:-1]))
...
>>> is_palin("xax")
True
>>> is_palin("xaax")
True
>>> is_palin("xaab")
False
``` |
1,028,578 | I'm running a headless device that I want to connect to wifi(it's currently on ethernet), so I'm using `nmcli`. I scan for connections with the following:
```
sudo nmcli dev wifi rescan
sudo nmcli dev wifi list
```
and the WiFi network I want is at 95% strength. So, I connect with:
```
sudo nmcli dev wifi connect "SSID" password "wifipassword"
```
and I get the following error:
```
Error: Connection activation failed: (53) The Wi-Fi network could not be found.
```
and I've tried copying and pasting from `list` to ensure I did not mistype the SSID, and it still does not work. It works fine from other devices that use Ubuntu and network-manager, so I know it's not the router.
How can it not find the network when I connect, but find it just fine when scanning, and how do I fix this? | 2018/04/27 | [
"https://askubuntu.com/questions/1028578",
"https://askubuntu.com",
"https://askubuntu.com/users/711310/"
] | this one fixed the issue for me - <https://unix.stackexchange.com/a/519620/407616>
add this
```
[device]
wifi.scan-rand-mac-address=no
```
to `/etc/NetworkManager/NetworkManager.conf`
then run
```
sudo systemctl restart NetworkManager
```
then you can connect to the ssid by
```
sudo nmcli dev wifi connect "SSID" password "wifipassword"
``` | I solved my problem by just turn your system in sleep mode then again turn it on this solve my problem without restart |
22,295,665 | How much is the overhead of smart pointers compared to normal pointers in C++11? In other words, is my code going to be slower if I use smart pointers, and if so, how much slower?
Specifically, I'm asking about the C++11 `std::shared_ptr` and `std::unique_ptr`.
*Obviously, the stuff pushed down the stack is going to be larger (at least I think so), because a smart pointer also needs to store its internal state (reference count, etc), the question really is, how much is this going to affect my performance, if at all?*
For example, I return a smart pointer from a function instead of a normal pointer:
```
std::shared_ptr<const Value> getValue();
// versus
const Value *getValue();
```
Or, for example, when one of my functions accept a smart pointer as parameter instead of a normal pointer:
```
void setValue(std::shared_ptr<const Value> val);
// versus
void setValue(const Value *val);
``` | 2014/03/10 | [
"https://Stackoverflow.com/questions/22295665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/202919/"
] | As with all code performance, the only really reliable means to obtain hard information is to **measure** and/or **inspect** machine code.
That said, simple reasoning says that
* You can expect some overhead in debug builds, since e.g. `operator->` must be executed as a function call so that you can step into it (this is in turn due to general lack of support for marking classes and functions as non-debug).
* For `shared_ptr` you can expect some overhead in initial creation, since that involves dynamic allocation of a control block, and dynamic allocation is very much slower than any other basic operation in C++ (do use `make_shared` when practically possible, to minimize that overhead).
* Also for `shared_ptr` there is some minimal overhead in maintaining a reference count, e.g. when passing a `shared_ptr` by value, but there's no such overhead for `unique_ptr`.
Keeping the first point above in mind, when you measure, do that both for debug and release builds.
The international C++ standardization committee has published a [technical report on performance](http://www.open-std.org/jtc1/sc22/wg21/docs/TR18015.pdf), but this was in 2006, before `unique_ptr` and `shared_ptr` were added to the standard library. Still, smart pointers were old hat at that point, so the report considered also that. Quoting the relevant part:
>
> “if
> accessing a value through a trivial smart pointer is significantly slower than accessing it
> through an ordinary pointer, the compiler is inefficiently handling the abstraction. In the
> past, most compilers had significant abstraction penalties and several current compilers
> still do. However, at least two compilers
> have been reported to have abstraction
> penalties below 1% and another a penalty of 3%, so
> eliminating this kind of overhead is
> well within the state of the art”
>
>
>
As an informed guess, the “well within the state of the art” has been achieved with the most popular compilers today, as of early 2014. | Chandler Carruth has a few surprising "discoveries" on `unique_ptr` in his 2019 Cppcon talk. ([Youtube](https://youtu.be/rHIkrotSwcc?t=1063)). I can't explain it quite as well.
I hope I understood the two main points right:
* Code without `unique_ptr` will (often incorrectly) not handle cases where owership is not passed while passing a pointer. Rewriting it to use `unique_ptr` will add that handling, and that has some overhead.
* A `unique_ptr` is still a C++ object, and objects will be passed on stack when calling a function, unlike pointers, which can be passed in registers. |
5,184,923 | I just generated a class using the xsd.exe (See [previous question](https://stackoverflow.com/questions/5183550/design-strongly-typed-object-from-xml)) and then I tried to use it to deserialize my XML file.
My XML files start like this:
```
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type='text/xsl' href='STIG_unclass.xsl'?>
<Benchmark xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cpe="http://cpe.mitre.org/language/2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:dsig="http://www.w3.org/2000/09/xmldsig#" id="Windows_2003" xml:lang="en" xsi:schemaLocation="http://checklists.nist.gov/xccdf/1.1 http://nvd.nist.gov/schema/xccdf-1.1.4.xsd http://cpe.mitre.org/dictionary/2.0 http://cpe.mitre.org/files/cpe-dictionary_2.1.xsd" xmlns="http://checklists.nist.gov/xccdf/1.1">
```
and the generated class from xsd.exe starts off like this:
```
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://checklists.nist.gov/xccdf/1.1")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://checklists.nist.gov/xccdf/1.1", IsNullable = false)]
public partial class Benchmark
```
but when I try and deserialize my XML file, using the following code:
```
var groups = new List<Benchmark>();
XmlSerializer serializer = new XmlSerializer(typeof(List<Benchmark>));
using (TextReader textReader = new StreamReader(open.FileName))
groups = (List<Benchmark>)serializer.Deserialize(textReader); // ERROR HERE
SetGroups(groups);
```
I get an error message that says "There is an error in XML document (3, 2)." with an inner exception that says: "http://checklists.nist.gov/xccdf/1.1'> was not expected."
What am I doing wrong? | 2011/03/03 | [
"https://Stackoverflow.com/questions/5184923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/490326/"
] | Yes.
Any headers can be ignored.
You should kill the page exit() right after you redirect the user. | Well, if you output data and your users ignore the header redirect (non-standard browser) - yes. |
10,980,435 | I got a "normal" ascx-Page which contains HTML-Parts as well as code behind. These elements should all be shown in normal conditions (works).
Now I want to be able to set a request-parameter which causes the page zu render differently. Then it sends the information on that page not human-readable but for a machine:
```
string jsonProperty = Request["JSonProperty"];
if (!string.IsNullOrEmpty(jsonProperty))
{
Response.Clear();
Response.Write(RenderJSon());
// Response.Close();
return;
```
This code is inside the Page\_PreRender.
Now my problem is:The string is correctly sent to the browser but the "standard" html-content is still rendered after that.
When I remove the "Response.Close();" Comment I receive an "ERR\_INVALID\_RESPONSE"
Any clue how to solve this without creating an additional Page? | 2012/06/11 | [
"https://Stackoverflow.com/questions/10980435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/680026/"
] | Try adding [`Response.End()`](http://msdn.microsoft.com/en-us/library/system.web.httpresponse.end.aspx)
>
> Sends all currently buffered output to the client, stops execution of the page, and raises the EndRequest event.
>
>
>
Also, as @Richard said, add
```
context.Response.ContentType = "application/json";
``` | It is [recommended to avoid calling `Response.End()`](https://stackoverflow.com/a/3917180/429091) even if it results in the correct behavior. This is because that method is provided for backwards compatibility with old ASP and was not designed to support performance. To prevent further processing, it throws a [`ThreadAbortException`](https://learn.microsoft.com/en-us/dotnet/api/system.threading.threadabortexception?view=netcore-3.1), trashing the thread, forcing the system to start a new thread later when processing a new request instead of being able to return that thread to the ASP.NET thread pool. The recommended alternative to stop further processing of the ASP.NET pipeline is to call [`HttpApplication.CompleteRequest()`](https://learn.microsoft.com/en-us/dotnet/api/system.web.httpapplication.completerequest?view=netframework-4.8#System_Web_HttpApplication_CompleteRequest) and return immediately. However, this does not terminate processing of the ASP.NET page.
To prevent further content from being sent to the client, one can certainly set [`Response.SuppressContent`](https://learn.microsoft.com/en-us/dotnet/api/system.web.httpresponse.suppresscontent?view=netframework-4.8) to `true`. That will prevent the contents of the `.aspx` file from being sent to the client. However, the `.aspx` will still be rendered. This includes running logic in the `.aspx` which may rely on data you’d load in your `Load` event.
To avoid rendering, you can set [`Page.Visible`](https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.page.visible?view=netframework-4.8) to `false`. This [causes the call to `Rendercontrol()` to be skipped](https://github.com/microsoft/referencesource/blob/a7bd3242bd7732dec4aebb21fbc0f6de61c2545e/System.Web/UI/Control.cs#L2605).
For this to work, you need to move your logic into the `Load()` event instead of `PreRender()` event.
With your code, that would be:
```cs
protected void Page_Load(object sender, EventArgs e)
{
var jsonProperty = Request["JSonProperty"];
if (!string.IsNullOrEmpty(jsonProperty))
{
Response.ContentType = "application/json";
Response.Write(RenderJSon());
Context.ApplicationInstance.CompleteRequest();
Visible = false;
return;
}
}
``` |
66,246 | Correlation does not imply causation.
Causation does imply correlation but not necessarily linear correlation.
...
So does correlation imply high-order causation?
If A and B are correlated, is it always possible to find `K={K1 K2 ... Kn}` variables such that
```
A~K1, K1~K2, ...,Kn-1~Kn and Kn~B
```
where ~ denotes causality.
In other words, if there is no causality in a correlation, does a common-causal variable(s) always exist? | 2013/08/01 | [
"https://stats.stackexchange.com/questions/66246",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/21852/"
] | You can simply have an omitted variable which has a causal impact on A and a causal impact on B. In that case, you will have a correlation between A and B but no "high-order causation". This issue is known in econometrics as the omitted variable bias. It is discussed in most econometrics textbooks. See for instance Cameron and Trivedi Microeconometrics. For a more advanced discussion see Judea Pearl's book on causality. | No.
For example, we can find a correlation between global average temperature and the world population of pirates ("Arrrgh!"), but nobody would suggest there is any sort of causality involved:

**Edit:**
Okay, the pirates vs global temperatures example is not a very good one here. Because (a) the x-axis of the chart is highly distorted, and (b) we could probably actually stretch to find an omitted variable (like some measure of industrialization).
A better example was given in answer to a [previous question](https://stats.stackexchange.com/questions/36/examples-to-teach-correlation-does-not-mean-causation/618#618) on CV:
 |
109,793 | Recently, one of the main file servers at our company failed. It was using a 4 disk RAID array, but apparently 3 of the disks died, and all the data on the server has been lost.
Speaking to the sys admin, he says that he has been warning the upper management about the backup situation for months. He had been trying to get approval to buy an enterprise-level backup solution, but he never got the budget approved for it - because management thought it was over the top.
The sys admin is a dedicated properly certified sys admin, whereas his managers are not IT-oriented.
His manager is asking why he didn't buy a cheap external drive and use this to backup the file server. The sys admin thinks that this is just a mickey-mouse solution that's suitable for use at home, but not a professional IT company - which is why he did not do it.
It seems to me that the sys admin wants proper, text-book IT strategy that costs a lot more money, whereas the management (without a deep IT understanding) wants cheaper solutions that they think are adequate.
I'm wondering what is the opinion of other sys admins? Was this sys admin correct in his actions? Or should he always make sure there is a backup of the important data, even if he believes that the cheaper way is not good enough?
---
Edit: based upon the answers, I'll add that the sys admin has an IT manager who would've known of the situation. He reports to the ultimate boss. I don't know if the manager ever reported the full situation to the boss. I think it is quite tough for the manager, as he is stuck in the middle, and he wants to be diplomatic with both sides. | 2010/02/04 | [
"https://serverfault.com/questions/109793",
"https://serverfault.com",
"https://serverfault.com/users/7018/"
] | Unfortunately, companies skimping on backups is all too common. Most never change until they get burned and lose everything.
BUT
If you are employed to be the sysadmin you have to work with the tools that you have including your brain. No matter what management or anyone else says on good days, when the poop hits the fan everyone gets selective memory.
A mickey mouse backup is better than no backup at all. | Did the same situation happen with the RAID array? As soon as one disk dies, you are in a situation where one more means data loss.. you better replace that drive immediately.
If I was in the sys admin's shoes, the instant the first drive went:
1. Email manager with formal request to replace the drive, reminding that no backup system has been approved so this is a critical situation. Cite the prior requests for the backup system by attaching that email, or even better, the manager's response denying the request.
2. If no response, re-send message, this time CC'ing your manager's manager.
3. If still no response, well.. not much more you can do. Polish the resume and start looking for a better job.
If you get denied along the way, at least you have it in writing for when the shit hits the fan (Get it in writing/email, do not accept a verbal response. You need a paper trail here. If your manager refuses to write it, then go over his/her head, because that's just shady -- there is no legit reason not to write it down.)
The same process should have been followed for getting a backup system, though perhaps without escalation as quickly (or going over your manager's head at all). If none of the requests are in writing, well.. shit rolls downhill. At least it's a good life lesson.
If you don't lose your job over the situation, well, start making that request again, citing the disaster it caused last time your request was denied. If it's still denied, then you need to decide if that's an environment you want to work in, and it's worth the stress. If every morning you expect to walk into work finding a panic because data was lost, well, that's no way to live. |
1,747,421 | Let $(a\_n)$ be a sequence of non-negative numbers such that $a\_1 > 0$ and $\sum a\_n$ diverges. Let $S\_n = \sum\_{k=1}^n a\_k$. Prove that, for all $n \geq 2$,
$$\frac{a\_n}{S\_n^2} \leq \frac{1}{S\_{n-1}}-\frac{1}{S\_n}$$
How would I start this proof? I've just been staring at it and am very stuck. All i know so far is that $S\_n-S\_{n-1}=a\_n$. Where does the inequality come from? | 2016/04/18 | [
"https://math.stackexchange.com/questions/1747421",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/266268/"
] | Since $a\_n$ is nonnegative, $S\_n$ is non-decreasing.
Thus $S\_{n-1} \leqslant S\_n \implies 1/S\_n \leqslant 1/S\_{n-1},$ and
$$\frac{a\_n}{S\_n^2} = \frac{S\_n - S\_{n-1}}{S\_n^2}\leqslant \frac{S\_n - S\_{n-1}}{S\_{n-1}S\_n} = \frac1{S\_{n-1}} - \frac1{S\_n}.$$
Hence, with $a\_1 > 0$ we have
$$\begin{align}\sum\_{n=1}^m \frac{a\_n}{S\_n^2} &= \frac1{a\_1} + \sum\_{n=2}^m \frac{a\_n}{S\_n^2} \\ &\leqslant \frac1{a\_1} + \sum\_{n=2}^m \left(\frac1{S\_{n-1}} - \frac1{S\_n} \right) \\ &= \frac1{a\_1} + \frac{1}{S\_1} - \frac{1}{S\_m} \\ & \leqslant \frac{2}{a\_1}.\end{align}$$
Thus, the sequence of partial sums is bounded and increasing (since the terms are non-negative) and the series converges. | You have $S\_n^2(1/S\_n-1/S\_{n-1})\ge a\_n$, or $S\_n/S\_{n-1}(S\_n-S\_{n-1}) \ge a\_n$. Ultimately, $S\_n/S\_{n-1}a\_n \ge a\_n$ or $S\_n \ge S\_{n-1}$, which is true, since $S\_n-S\_{n-1} = a\_n > 0$. Hope this helps. |
55,696,544 | If you make a new Flutter project and include the dependencies and then replace your main.dart file you should be where I am on this question.
---
I left the original load: with Future.delayed but it doesn't seem to matter. I know partially what my problem is but am unable to come up with a better solution.
1) I don't seem to be using my snapshot.data and instead I am just making a empty List with `str` and then i just addAll into it and use that. So i'd love to not do that, i originally was using snapshot.data but ran into problems when I tried to "pull to load more data" which happens after you scroll to the bottom of the list.
**The problem** with my current method of doing this is that if you pull to load more users and then try to pull again before the users have loaded, The app breaks and doesn't wait for the data to properly load. I believe that I need to be doing that all in the `load:` of this library `easy_refresh`... but I am not sure how to rewrite my code to accomplish that.
How can I get my data to load with snapshot.data and then when I pull to refresh, I append 100 more users to that list but the UI waits for the list to update before it finishes the load. Would I be better off just putting a Blocking UI element and after the str list updates? and when new users are loaded I unblock the UI? which sorta feels hackish and not the correct way to solve this. The plugin itself should be able to do the loading and when its ready it stops the spinner under the list and says "finished".
**pubspec.yaml**
```
dependencies:
flutter:
sdk: flutter
flutter_easyrefresh: ^1.2.7
http: ^0.12.0+2
```
**main.dart**
```
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:http/http.dart' as http;
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
backgroundColor: Colors.white
),
home: DuelLeaderBoards(),
);
}
}
class DuelLeaderBoards extends StatefulWidget {
@override
_DuelLeaderBoardsState createState() => _DuelLeaderBoardsState();
}
class _DuelLeaderBoardsState extends State<DuelLeaderBoards> {
List<Entry> str = [];
GlobalKey<EasyRefreshState> _easyRefreshKey = new GlobalKey<EasyRefreshState>();
GlobalKey<RefreshHeaderState> _headerKey = new GlobalKey<RefreshHeaderState>();
GlobalKey<RefreshHeaderState> _connectorHeaderKey = new GlobalKey<RefreshHeaderState>();
GlobalKey<RefreshFooterState> _footerKey = new GlobalKey<RefreshFooterState>();
GlobalKey<RefreshFooterState> _connectorFooterKey = new GlobalKey<RefreshFooterState>();
Future<LeaderBoards> getLeaderBoards(start) async {
String apiURL = 'https://stats.quake.com/api/v2/Leaderboard?from=$start&board=duel&season=current';
final response = await http.get(apiURL);
if (response.statusCode == 200) {
final responseBody = leaderBoardsFromJson(response.body);
return responseBody;
} else {
throw Exception('Failed to load Data');
}
}
void updateLeaderBoardList(e) async {
setState(() {
str.addAll(e.entries);
});
}
@override
void initState() {
getLeaderBoards(0).then((onValue) => str = onValue.entries );
super.initState();
}
@override
Widget build(BuildContext context) {
Widget header = ClassicsHeader(
key: _headerKey,
refreshText: "pullToRefresh",
refreshReadyText: "releaseToRefresh",
refreshingText: "refreshing...",
refreshedText: "refreshed",
moreInfo: "updateAt",
bgColor: Colors.transparent,
textColor: Colors.white,
);
Widget footer = ClassicsFooter(
key: _footerKey,
loadHeight: 50.0,
loadText: "pushToLoad",
loadReadyText: "releaseToLoad",
loadingText: "loading",
loadedText: "loaded",
noMoreText: "Finished",
moreInfo: "updateAt",
bgColor: Colors.transparent,
textColor: Colors.white,
);
return FutureBuilder(
future: getLeaderBoards(0),
builder:
(BuildContext context, AsyncSnapshot<LeaderBoards> snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
} else {
return Builder(builder: (BuildContext context) {
return Center(
child: new EasyRefresh(
key: _easyRefreshKey,
behavior: ScrollOverBehavior(),
refreshHeader: ConnectorHeader(
key: _connectorHeaderKey,
header: header,
),
refreshFooter: ConnectorFooter(
key: _connectorFooterKey,
footer: footer,
),
child: CustomScrollView(
semanticChildCount: str.length,
slivers: <Widget>[
SliverList(
delegate: SliverChildListDelegate(<Widget>[header]),
),
SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
return new Container(
height: 70.0,
child: Card(
child: new Text(
'${index+1}: ${str[index].userName}',
style: new TextStyle(fontSize: 18.0),
),
));
},
childCount: str.length,
)),
SliverList(
delegate: SliverChildListDelegate(<Widget>[footer]),
)
],
),
onRefresh: () async {
await new Future.delayed(const Duration(seconds: 0), () {
setState(() {});
});
},
loadMore: () async {
getLeaderBoards(str.length).then((onValue) => {
updateLeaderBoardList(onValue)
});
},
// loadMore: () async {
// await new Future.delayed(const Duration(seconds: 0), () {
// getLeaderBoards(str.length).then((onValue) => {
// updateLeaderBoardList(onValue)
// });
// });
// },
)
);
});
}
});
}
}
LeaderBoards leaderBoardsFromJson(String str) {
final jsonData = json.decode(str);
return LeaderBoards.fromJson(jsonData);
}
String leaderBoardsToJson(LeaderBoards data) {
final dyn = data.toJson();
return json.encode(dyn);
}
class LeaderBoards {
String boardType;
List<Entry> entries;
int totalEntries;
LeaderBoards({
this.boardType,
this.entries,
this.totalEntries,
});
factory LeaderBoards.fromJson(Map<String, dynamic> json) => new LeaderBoards(
boardType: json["boardType"] == null ? null : json["boardType"],
entries: json["entries"] == null ? null : new List<Entry>.from(json["entries"].map((x) => Entry.fromJson(x))),
totalEntries: json["totalEntries"] == null ? null : json["totalEntries"],
);
Map<String, dynamic> toJson() => {
"boardType": boardType == null ? null : boardType,
"entries": entries == null ? null : new List<dynamic>.from(entries.map((x) => x.toJson())),
"totalEntries": totalEntries == null ? null : totalEntries,
};
}
class Entry {
String userName;
int eloRating;
String profileIconId;
String namePlateId;
Entry({
this.userName,
this.eloRating,
this.profileIconId,
this.namePlateId,
});
factory Entry.fromJson(Map<String, dynamic> json) => new Entry(
userName: json["userName"] == null ? null : json["userName"],
eloRating: json["eloRating"] == null ? null : json["eloRating"],
profileIconId: json["profileIconId"] == null ? null : json["profileIconId"],
namePlateId: json["namePlateId"] == null ? null : json["namePlateId"],
);
Map<String, dynamic> toJson() => {
"userName": userName == null ? null : userName,
"eloRating": eloRating == null ? null : eloRating,
"profileIconId": profileIconId == null ? null : profileIconId,
"namePlateId": namePlateId == null ? null : namePlateId,
};
}
``` | 2019/04/15 | [
"https://Stackoverflow.com/questions/55696544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/891041/"
] | Calling `A100` as written, you need to pass in `INTIM` and accept the return value
```
INTIM = A100(INTIM);
```
But... The initiqal state of `INTIM` is never used, so you could
```
INTIM = A100();
```
and change `A100` to look more like
```
bool A100()
{
int choice;
cout << " Repugnis turns a paler...\n 1. Onwards, Mr Artanon.\n (enter in a menu option): ";
cin >> choice;
while (choice != 1)
{
cout << "Enter in a valid option (1)";
cin >> choice; // added here because otherwise choice never changes
// and this loop will go on for a long, long time.
}
A232(); // moved ahead of return. Code after a return is not run
return true;
}
```
But since `A232` is called and may set additional flags you cannot return, you have a design flaw: What if `A232` also modifies a boolean? You can only return one thing from a function. You could pass `A232`'s boolean in by reference, but what it `A232` then calls `B484` and it also has a boolean?
You don't want to have to pass around every possible boolean, that would be a confusing mess, so consider making a data structure that stores all of your booleans to pass around.
And that leads to an even better idea: encapsulating the booleans and the functions in the same data structure so that you don't have to pass anything around; it's all in the same place. | >
> Do I need to pass them [the boolean results] to the functions?
>
>
>
Often, but not always, it is my preference to pass them by reference, and yes, it can get to be a big chain thru many functions. sigh.
But your question is "Do you **need** to pass them ...".
The answer is No.
Because
a) you have tagged this post as C++, and
b) the key feature of C++ is the user-defined-class.
---
1. Consider declaring every 'adventurous function' of your story within a class scope.
2. Each 'adventurous function', **as an attribute** of the class, is implemented with one 'hidden' parameter, the 'this' pointer to the class instance.
3. So .. if you place all your 'result' booleans **as data attributes** of the class, invoking any 'adventurous function' will also 'pass' all the class instance data attributes (all your bools!) as part of the invocation. No data is actually moving, just a pointer, the 'this' pointer.
---
It might look something like this:
```
#include <iostream>
using std::cout, std::cerr, std::flush, std::endl;
// using std::cin;
#include <iomanip>
using std::setw, std::setfill;
#include <sstream>
using std::stringstream;
#include <string>
using std::string;
namespace AS // Adventure Story
{
class CreateYourOwnAdventureStory_t
{
private:
// diagnostic purposes
stringstream ssUI;
// command line arguments concatenated into one string
// contents: strings convertable to ints to mimic cin
bool INTIM;
// other results go here
public:
int operator()(int argc, char* argv[]) {return exec(argc, argv);}
private:
int exec(int argc, char* argv[])
{
int retVal = 0;
// capture all command line arguments into a string
for (int i=1; i<argc; ++i)
ssUI << argv[i] << " ";
cout << "\n ssUI: " << ssUI.str() << "\n\n\n";
A1();
cout << "\n INTIM : " << INTIM << endl;
// ?more here?
return retVal;
}
void A1()
{
int choice = 0;
cout << "Well, Mr Artanon, ...\n "
"\n 1. ’It’s you who’ll get a rare cut across that corpulent neck of yours "
"if you don’t speed things along, you feckless blob of festering lard. "
"\n 2. ’Surely in such an industrious kitchen, there must be a starter or two "
"ready to send along and sate His Abhorentness’s appetite?’"
"\n (enter a menu option): ";
ssUI >> choice; // cin >> choice;
if (choice == 1) { A100(); }
if (choice == 2) { A167(); }
}
void A100()
{
int choice = 0;
INTIM = true;
ssUI >> choice; // cin >> choice;
cout << "\n\n A100() choice:" << choice
<< " INTIM: " << INTIM << endl;
}
void A167()
{
int choice = 0;
INTIM = false;
ssUI >> choice; // cin >> choice;
cout << "\n\n A167() choice:" << choice
<< " INTIM: " << INTIM << endl;
}
// other action-functions go here
}; // class CreateYourOwnAdventureStory_t
typedef CreateYourOwnAdventureStory_t CreateYOAS_t;
} // namespace AS
int main(int argc, char* argv[]){return AS::CreateYOAS_t()(argc,argv);}
```
Notes:
This example grabs the command line parameters and appends them to a string stream. The result is use-able in a fashion much like your cin statements.
Did you notice you (probably) will not need forward declarations for your functions? The compiler has to scan a lot of the class declaration to decide various issues, and thus can figure out that A100 (and A167) are actually with-in the scope of AS::CreateYOAS\_t::. The functions can still be moved into a cpp file, so you can still take advantage of separate compilation. (and maybe save some effort compiling smaller files, and only the changed files.)
Did you notice that the functions accessing INTIM simply use the bool, without needing any 'this->' to de-reference?
Main invokes a simple Functor. Nothing else. Main invokes operator(). Simple, minimal. The ctor and dtor are currently default. If you need to use the ctor to initialize results or other intermediate info, I would simply add it near the operator() implementation.
PS: You mentioned using bools to return results. You might as, an alternative, consider using a stringstream ... a single stream with text ... use like a log for capturing the ongoing game, or for a single simple overall report to the user.
Good luck. |
1,103,361 | I have installed Windows 10 via the free install that was offered last year.
I had no issues and everything worked until around April this year after an update.
I start the computer, log in and everything works for a while and then for some reason I can not open the Start menu with either mouse or keyboard. I can open Word which is in my task bar, I can open a doc but cannot do anything else in Word. Cortana wont open etc. I have Chrome on the task bar which still is active.
I can right click on Start and click restart and then I'm back to it working, everything is fine until it freezes again. The tech guy reckoned it was my mouse (it wasn't), then some programs which he got rid of (it wasn't) so $110 dollars later I'm still looking for help.
I cant access the programs using touch screen either.
Is there any way to either fix this and find out what it causing it? | 2016/07/21 | [
"https://superuser.com/questions/1103361",
"https://superuser.com",
"https://superuser.com/users/619571/"
] | Give this a go. Opens new tabs to the left or right of the current tab with default or customisable shortcuts in Chrome.
<https://nextab.co>
<https://chrome.google.com/webstore/detail/nextab/okknollmafgigeimghbepomindhjnabj> | While all of these options works. What I find most helpful and simple are these two extensions:
NextTab:
Open a new tab to the right with Alt + T, and a new tab to the left with Shift + Alt + T -https://chrome.google.com/webstore/detail/nextab/okknollmafgigeimghbepomindhjnabj/related
Open tab next to current:
Replaces Chrome's default shortcut (Cmd/Window + T) to open a new tab next to the current tab. - <https://chrome.google.com/webstore/detail/open-tabs-next-to-current/gmpnnmonpnnmnhpdldahlekfofigiffh/related> |
7,141,343 | Does anyone know a database that I can export, I need world countries information including: country code, culture (ex. en\_US), flag image and currency.
I'm tried to google it, but haven't found anything. | 2011/08/21 | [
"https://Stackoverflow.com/questions/7141343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/329200/"
] | Here I collected countries with their flags, cities with their photos and other various information inside MySQL database:
<https://github.com/turalus/openDB> | Inversely to @JamWaffles, I can't supply icons, but I can provide you with a decent list of country/currency codes.
I found the info on [PayPal XDevelopers site](https://www.x.com/community/home) about a year ago, but I can't find the exact page.
Sample:
```
'USD' => array(
'title' => 'U.S. Dollar',
'symbol_left' => '$', // $
'symbol_right' => '',
'decimal_point' => '.',
'thousands_point' => ',',
'decimal_places' => 2)
```
See the full array at <https://gist.github.com/1161248>
You can also grab a database of currency data, but I haven't looked at it, never mind used it before. <http://www.unece.org/etrades/download/archives.htm> |
24,440,712 | I'm running front-end tests using nightwatch.js using the Chrome Driver. I need to test that image uploading works properly, presumably through the provided file input since there are callbacks that run on a successful post.
I'm aware that this can be done using sendKeys method of the Selenium Web Driver.
How can you accomplish this using javascript and nightwatch.js?
Can you access the Selenium webdriver or an interface with it? | 2014/06/26 | [
"https://Stackoverflow.com/questions/24440712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/755844/"
] | Use client.setValue function to set the absolute path of your image. Here is the working example in my project.
client.setValue('#editPictures .modal-body input[type="file"]', '/Users/testing/pictures/CAM00003.jpg'); | this worked for me.
`.setValue('input[type="file"]', require('path').resolve('/home/My-PC/Desktop/img.png'))`
Only thing maybe others running into might the different versions of firefox where it didn't work 2 yrs back for a co-worker. |
34,413 | I am getting a `NoClassDefFoundError` when I run my Java application. What is typically the cause of this? | 2008/08/29 | [
"https://Stackoverflow.com/questions/34413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3535/"
] | This is the [best solution](https://en.wikipedia.org/wiki/Classpath_%28Java%29#Setting_the_path_to_execute_Java_programs) I found so far.
Suppose we have a package called `org.mypackage` containing the classes:
* HelloWorld (main class)
* SupportClass
* UtilClass
and the files defining this package are stored physically under the directory `D:\myprogram` (on Windows) or `/home/user/myprogram` (on Linux).
The file structure will look like this:
[](https://i.stack.imgur.com/XOzAE.png)
When we invoke Java, we specify the name of the application to run: `org.mypackage.HelloWorld`. However we must also tell Java where to look for the files and directories defining our package. So to launch the program, we have to use the following command:
[](https://i.stack.imgur.com/cM8gu.png) | I had this error but could not figure out the solution based on this thread but solved it myself.
For my problem I was compiling this code:
```
package valentines;
import java.math.BigInteger;
import java.util.ArrayList;
public class StudentSolver {
public static ArrayList<Boolean> solve(ArrayList<ArrayList<BigInteger>> problems) {
//DOING WORK HERE
}
public static void main(String[] args){
//TESTING SOLVE FUNCTION
}
}
```
I was then compiling this code in a folder structure that was like /ProjectName/valentines
Compiling it worked fine but trying to execute: `java StudentSolver`
I was getting the NoClassDefError.
To fix this I simply removed: `package valentines;`
I'm not very well versed in java packages and such but this how I fixed my error so sorry if this was already answered by someone else but I couldn't interpret it to my problem. |
239,006 | I want to prove that the source code I am using is the same as the open-sourced version, which is publicly available. My idea was to publish a hash of the open-sourced version and compare it to the hash of the deployed server at boot. However, because the open-sourced hash is available pre-deployment, it is possible for a bad actor to hard code the hash into the server and avoid the hash function.
Is there a way I can prevent this from happening? I found that Heroku is using a similar approach where they are fetching the commit hash. Is this tamperproof? And if so, how is this different from my approach? | 2020/09/30 | [
"https://security.stackexchange.com/questions/239006",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/243476/"
] | This is essentially an impossible task.
---------------------------------------
If you have read Ken Thompson's "[Reflections on Trusting Trust](https://www.cs.cmu.edu/%7Erdriley/487/papers/Thompson_1984_ReflectionsonTrustingTrust.pdf)", then you already know everything I am about to say. If not, please keep reading:
Imagine I publish an open-source project, that is written in some language, and simply takes input and returns the input unchanged - like a very simple version of [`echo`](https://www.gnu.org/software/coreutils/manual/html_node/echo-invocation.html). You download my source code, read through it all (it's just a few lines long anyways) and then you compile it. You can be sure that your program does exactly what you think it does, right?
**Wrong.**
How do you know that your compiler didn't add any extra instructions, such as checking whether or not the input's sha-256 hash is `e257f6eccac764b6cea785a0272e34d3dbc56419eac2ad436b9fb4bddcd10494` and if it is, do something unexpected.
You might say that that is unlikely, but you cannot ever be fully certain of it. But perhaps you *want* to be fully certain of it, right? After all, you want to cryptographically prove that the software you are running does exactly what the source code says it should do. So you inspect the binary with a reverse-engineering tool, like Ghidra or IDA Pro. But...how can you be sure *these* tools do what you think they do? Sure, on the surface they might seem as if they show you the binary as it is, but how can you be sure that they don't hide the maliciously inserted code from you?
You could completely forego existing compilers and write your own in bytecode, byte by byte, instruction for instruction, but how would you do that? You need some program that writes those bytes to disk. How do you know that *those* are not infected and write some extra bytes?
And even if you completely forego programs and just use a [magnetized needle and a steady hand](https://xkcd.com/378/), how can you be sure that your CPU actually runs the instructions you want it to run and doesn't run some extra instructions? After all, CPUs run microcode these days, which is difficult to inspect.
### In summary...
... it's extremely hard to prove that a computer does what we think it does. Can you show some hash of some source code or deployment state to show something to your customers? Of course you can. But that really doesn't mean anything. | If I understand you question correctly, what you are asking is impossible because a server acts like a kind of "black box", and normal users have no way to inspect what is really going on.
You don't simply have to prove that you have something, or that you know something: you would actually need to prove that you *use* something exactly as expected, including every single step and every single detail of the process. Proving the exact behavior of a black box involves a lot of analysis and inspection that normal users cannot be allowed to do.
In other words, to give a simple example, there is no way that StackExchange can really convince us that they are really storing passwords securely, using a specific implementation of a secure hash function. Some things might help convincing us though: for example, having a continuous and thorough audit system, made by some external trusted authorities. Then, if we can trust the external auditors, we can consider whatever they report to be a proof. Full compliance is however never fully guaranteed (the auditors might be corrupt). As you can see, the issue is pretty complicated. |
60,796,646 | When trying to list down all tables names in a database having a specific name format, the following query works fine :
```
show tables like '*case*';
```
while the following does not
```
show tables like '%case%';
```
On the other hand, when comparing the actual data inside string columns its the vice-versa case
Working query :
```
select column from database.table where column like '%ABC%' limit 5;
```
Not working query :
```
select column from database.table where column like '*ABC*' limit 5;
```
What's the difference between the 2 operators \* and % ? | 2020/03/22 | [
"https://Stackoverflow.com/questions/60796646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5069746/"
] | This is the difference between regular expressions and like patterns.
`LIKE` is built into the SQL language. It has two wildcards:
* `%` represents any number of characters including zero.
* `_` represents exactly one character.
Regular expressions are much more flexible for matching almost any pattern in a string.
When SQL was invented, I don't think regular expressions were in common use in computer systems -- at the very least, the folks at IBM who worked on relational databases may not have been familiar with the folks at ATT who were inventing Unix.
Regular expressions are much more powerful than `LIKE` patterns, of course. And Hive supports them via the `RLIKE` operator (and some other functions).
The `SHOW` functionality is not standard SQL. So, the developers of Hive chose the more flexible method for pattern matching. | HiveQL attempts to mimic the SQL, but it does not strictly follow its standards.
The usage of the wildcards are not pertinent to the `LIKE` clause, but to the statement itself. [`SHOW`](https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL#LanguageManualDDL-Show) statements validate the wildcards based on the Java regular expression whereas when it comes to `SELECT` statements, Hive tries to stick with the SQL's wildcard validation. |
18,783,625 | I have a class which i can read but not write because of the company policy. I have following structures in my project.
```
public class Name // can not touch this class OR modify it
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string GetNames()
{
return FirstName + " " + LastName;
}
}
public class Details
{
// some methods and properties.
public Name LoadName() // This method return type i can not change as this method is used in ObjectDataSource for GridView
{
var names = new Name();
if (txtInpput.Text == "Jermy")
{
names.FirstName = "Jermy";
names.LastName = "Thompson";
}
else
{
names.FirstName = "Neville";
names.LastName = "Vyland";
}
return
names;
}
}
```
No I want to add extra property in `class Name` called `"Email Address"` and use `class Details` **LoadName()** method to return the type which includes the `**Email Address**` as well. as i am bound to use that method i can not change the return type `Name` to something else.
I can extend the `class Name` and `overrides` the `GetNames()` method to include the newly created property but that wont help as i can not change the return type in `class Details LoadName()` method.
I am not sure this is even possible BUT just wondering if there are any solutions.
```
I am suing
.NET 3
VS 2010
``` | 2013/09/13 | [
"https://Stackoverflow.com/questions/18783625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/927002/"
] | If you cannot change the signature of the method, your callers would need to do some casting. This is not optimal, but you can still do it:
```
public class NameWithEmail : Name {
public string EMail {get;set;}
}
...
public Name LoadName() {
...
return new NameWithEmail(); // OK because NameWithEmail extends Name
}
```
Now the caller would need to know the new type, do a cast, and access the email through it:
```
NameWithEmail name = Details.LoadName() as NameWithEmail;
if (name != null) {
Console.WriteLine("{0} {1} : {2}", name.FirstName, name.LastName, name.EMail);
}
```
The trickiest part is binding the new property to a data grid. [This answer](https://stackoverflow.com/a/628022/335858) explains how this can be done. | Try this:
```
public class Name // can not touch this class OR modify it
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string GetNames()
{
return FirstName + " " + LastName;
}
}
public class Name1:Name {
public string EmailAddress { get; set; }
public override string GetNames()
{
return FirstName + " " + LastName+" "+EmailAddress;
}
}
public class Details
{
// some methods and properties.
public Name LoadName() // This method return type i can not change as this method is used in ObjectDataSource for GridView
{
TextBox txtInpput = new TextBox();
var names = new Name();
if (txtInpput.Text == "Jermy")
{
names.FirstName = "Jermy";
names.LastName = "Thompson";
}
else
{
names.FirstName = "Neville";
names.LastName = "Vyland";
}
return
names;
}
}
public class Details1:Details {
public override Name LoadName()
{
TextBox txtInpput = new TextBox();
var names = new Name();
if (txtInpput.Text == "Jermy")
{
names.FirstName = "Jermy";
names.LastName = "Thompson";
}
else
{
names.FirstName = "Neville";
names.LastName = "Vyland";
}
return
names;
}
}
``` |
3,656,644 | I noticed that sometimes I get errors in my R scripts when I forget checking whether the dataframe I'm working on is actually empty (has zero rows).
For example, when I used apply like this
`apply(X=DF,MARGIN=1,FUN=function(row) !any(vec[ row[["start"]]:row[["end"]] ]))`
and `DF` happened to be empty, I got an error about the subscripts.
Why is that? Aren't empty dataframes valid? Why does `apply()` with `MARGIN=1` even try to do anything when there are no rows in the dataframe? Do I really need to add a condition before each such apply to make sure the dataframe isn't empty?
Thank you! | 2010/09/07 | [
"https://Stackoverflow.com/questions/3656644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/377031/"
] | This has absolutely nothing to do with `apply`. The function you are applying does not work when the data.frame is empty.
```
> myFUN <- function(row) !any(vec[ row[["start"]]:row[["end"]] ])
> myFUN(DF[1,]) # non-empty data.frame
[1] FALSE
> myFUN(data.frame()[1,]) # empty data.frame
Error in row[["start"]]:row[["end"]] : argument of length 0
```
Add a condition to your function.
```
> apply(X=data.frame(),MARGIN=1, # empty data.frame
+ FUN=function(row) {
+ if(length(row)==0) return()
+ !any(vec[ row[["start"]]:row[["end"]] ])
+ })
NULL
``` | I would use mapply instead:
```
kk <- data.frame( start = integer(0), end = integer(0) )
kkk <- data.frame( start = 1, end = 3 )
vect <- rnorm( 100 ) > 0
with(kk, mapply( function(x, y) !any( vect[x]:vect[y] ), start, end ) )
with(kkk, mapply( function(x, y) !any( vect[x]:vect[y] ), start, end ) )
``` |
6,094,401 | I am writing a shell script. The tutorial that I am reading have the first line like this :
`#!/usr/bin/env bash/`
but it isn't working for me. (`error : no such directory`)
How can I find out which bash I am using and where is it located?
Appreciate for any advice and help.
**Thanks a lot. It works now**.
**solution is** `#!/usr/bin/env bash`
Another problem: Why it just can't read the word 'restart'
my code in the start.sh:
```
#!/usr/bin/env bash/
RESTART="apachectl restart"
$RESTART
```
I does not work.
```
Usage: /usr/local/apache2/bin/httpd [-D name] [-d directory] [-f file]
[-C "directive"] [-c "directive"]
[-k start|restart|graceful|graceful-stop|sto p]
[-v] [-V] [-h] [-l] [-L] [-t] [-S]
Options:
-D name : define a name for use in <IfDefine name> directives
-d directory : specify an alternate initial ServerRoot
-f file : specify an alternate ServerConfigFile
-C "directive" : process directive before reading config files
-c "directive" : process directive after reading config files
-e level : show startup errors of level (see LogLevel)
-E file : log startup errors to file
-v : show version number
-V : show compile settings
-h : list available command line options (this page)
-l : list compiled in modules
-L : list available configuration directives
-t -D DUMP_VHOSTS : show parsed settings (currently only vhost settings)
-S : a synonym for -t -D DUMP_VHOSTS
-t -D DUMP_MODULES : show all loaded modules
-M : a synonym for -t -D DUMP_MODULES
-t : run syntax check for config files
```
why is it like that? it seems that it can read the word restart.
Thank you all! I have fixed it now.
**solution**: edit the file in unix (vim/nano and whatever but not in windows)
```
Thank again :)
``` | 2011/05/23 | [
"https://Stackoverflow.com/questions/6094401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/744721/"
] | If you remove the `/` from `bash/`, it should work. | Remove the extra character(s) you have at the end of lines. No slash is required and
`dos2unix yourscript` will remove the unwanted CRs.
```
#!/usr/bin/env bash
``` |
2,410,994 | The quartic form
$$(x^2 + y^2 + z^2)^2 - 3 ( x^3 y + y^3 z + z^3 x)$$
is non-negative for all real $x$, $y$, $z$, as one can check (with some effort). A theorem of Hilbert implies that there exist quadratic forms $Q\_1$, $Q\_2$, $Q\_3$ so that
$$(x^2 + y^2 + z^2)^2 - 3( x^3 y + y^3 z + z^3 x) = Q\_1^2 + Q\_2^2 + Q\_3^2$$
I would like to find an explicit writing of the quartic forms, with rational quadratic forms $Q\_i$. Maybe more than $3$ terms are necessary. | 2017/08/30 | [
"https://math.stackexchange.com/questions/2410994",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/168051/"
] | We are given a trivariate quartic form
$$ f (x, y, z) := (x^2 + y^2 + z^2)^2 - 3 ( x^3 y + y^3 z + z^3 x) $$
which can be rewritten as the sum of $9$ monomials
$$f (x, y, z) = x^4 + y^4 + z^4 + 2 x^2 y^2 + 2 x^2 z^2 + 2 y^2 z^2 - 3 x^3 y - 3 y^3 z - 3 z^3 x $$
and we would like to write it as the sum of squares (SOS) of quadratic forms. The fewer the better.
---
SOS decomposition
-----------------
A general trivariate quartic form is parametrized as follows
$$\begin{array}{c} \begin{bmatrix} x^2\\ y^2\\ z^2\\ x y\\ x z\\ y z\end{bmatrix}^\top \begin{bmatrix} q\_{11} & q\_{12} & q\_{13} & q\_{14} & q\_{15} & q\_{16}\\ q\_{12} & q\_{22} & q\_{23} & q\_{24} & q\_{25} & q\_{26}\\ q\_{13} & q\_{23} & q\_{33} & q\_{34} & q\_{35} & q\_{36}\\ q\_{14} & q\_{24} & q\_{34} & q\_{44} & q\_{45} & q\_{46}\\ q\_{15} & q\_{25} & q\_{35} & q\_{45} & q\_{55} & q\_{56}\\ q\_{16} & q\_{26} & q\_{36} & q\_{46} & q\_{56} & q\_{66}\end{bmatrix} \begin{bmatrix} x^2\\ y^2\\ z^2\\ x y\\ x z\\ y z\end{bmatrix} = \\\\ = q\_{11} x^4 + q\_{22} y^4 + q\_{33} z^4 + 2 q\_{14} x^3 y + 2 q\_{15} x^3 z + 2 q\_{24} x y^3 + 2 q\_{26} y^3 z + 2 q\_{35} x z^3 + 2 q\_{36} y z^3 + (2 q\_{12} + q\_{44}) x^2 y^2 + (2 q\_{13} + q\_{55}) x^2 z^2 + (2 q\_{23} + q\_{66}) y^2 z^2 + (2 q\_{16} + 2 q\_{45}) x^2 y z + (2 q\_{46} + 2 q\_{25}) x y^2 z + (2 q\_{34} + 2 q\_{56}) x y z^2\end{array}$$
Note that the $6 \times 6$ matrix above, which we denote by $\mathrm Q$, is **symmetric** by construction. Hence, we have $1 + 2 + \cdots + 6 = 21$ unknowns (instead of $6^2 = 36$). We recover the particular quartic $f$ if the following $15$ *affine* equality constraints are satisfied
$$\begin{array}{rl} q\_{11} &= 1\\ q\_{22} &= 1\\ q\_{33} &= 1\\ 2 q\_{14} &= -3\\ q\_{15} &= 0\\ q\_{24} &= 0\\ 2 q\_{26} &= -3\\ 2 q\_{35} &= -3\\ q\_{36} &= 0\\ 2 q\_{12} + q\_{44} &= 2\\ 2 q\_{13} + q\_{55} &= 2\\ 2 q\_{23} + q\_{66} &= 2\\ 2 q\_{16} + 2 q\_{45} & = 0\\ 2 q\_{46} + 2 q\_{25} &= 0\\ 2 q\_{34} + 2 q\_{56} &= 0\end{array}$$
Note that we have $21 - 15 = 6$ **degrees of freedom**. These $15$ equality constraints can be written much more economically in the following form
$$\mathcal A (\mathrm Q) = \mathrm b$$
where $\mathcal A : \mbox{Sym}\_6 (\mathbb R) \to \mathbb R^{15}$ is a linear function and $\mathrm b \in \mathbb R^{15}$.
Our goal is to find a (symmetric) **positive semidefinite** $6 \times 6$ matrix $\rm Q$ such that the $15$ equality constraints above are satisfied. If such a matrix $\rm Q$ exists, then there exists a ("square root") matrix $\rm R$ such that $\rm Q = R R^T$ and, thus, $f$ can be written as a SOS of quadratic forms.
---
Approximate solution
--------------------
We would like matrix $\rm Q$ to be **low-rank**, in order to have as few terms in the SOS decomposition as possible. Hence, we have the following rank-minimization problem
$$\begin{array}{ll} \text{minimize} & \mbox{rank} (\mathrm Q)\\ \text{subject to} & \mathcal A (\mathrm Q) = \mathrm b\\ & \mathrm Q \succeq \mathrm O\_6\end{array}$$
Unfortunately, the objective function, $\mbox{rank} (\mathrm Q)$, is *non*-convex. One popular heuristic is to minimize the **nuclear norm** of $\rm Q$, which is a convex proxy for $\mbox{rank} (\mathrm Q)$. Fortunately, the nuclear norm of a symmetric, positive semidefinite matrix is its *trace*, i.e., a linear function of the matrix's (diagonal) entries. Thus, we obtain the following **semidefinite program** (SDP)
$$\begin{array}{ll} \text{minimize} & \mbox{tr} (\mathrm Q)\\ \text{subject to} & \mathcal A (\mathrm Q) = \mathrm b\\ & \mathrm Q \succeq \mathrm O\_6\end{array}$$
which is convex and, thus, computationally tractable. The following Python + [NumPy](http://www.numpy.org) + [CVXPY](http://www.cvxpy.org) script solves the SDP above:
```
from cvxpy import *
import numpy as np
np.set_printoptions(linewidth=125)
# matrix variable
Q = Semidef(6)
# objective function
objective = Minimize( trace(Q) )
# constraints
constraints = [ Q[0,0] == 1,
Q[1,1] == 1,
Q[2,2] == 1,
2*Q[0,3] == -3,
Q[0,4] == 0,
Q[1,3] == 0,
2*Q[1,5] == -3,
2*Q[2,4] == -3,
Q[2,5] == 0,
2*Q[0,1] + Q[3,3] == 2,
2*Q[0,2] + Q[4,4] == 2,
2*Q[1,2] + Q[5,5] == 2,
2*Q[0,5] + 2*Q[3,4] == 0,
2*Q[3,5] + 2*Q[1,4] == 0,
2*Q[2,3] + 2*Q[4,5] == 0 ]
# create optimization problem
prob = Problem(objective, constraints)
# solve optimization problem
prob.solve()
print "Solution = \n", Q.value
print "Solution after rounding = \n", np.round(Q.value, 1)
# compute eigendecomposition of the solution
Lambda, V = np.linalg.eigh( Q.value )
print "Eigenvalues = \n", Lambda
```
This script produces the following output:
```
Solution =
[[ 1.00052427e+00 -4.93986993e-01 -4.93986993e-01 -1.50131075e+00 8.16263094e-04 1.48128400e+00]
[ -4.93986993e-01 1.00052427e+00 -4.93986993e-01 8.16263094e-04 1.48128400e+00 -1.50131075e+00]
[ -4.93986993e-01 -4.93986993e-01 1.00052427e+00 1.48128400e+00 -1.50131075e+00 8.16263095e-04]
[ -1.50131075e+00 8.16263094e-04 1.48128400e+00 2.98994780e+00 -1.48087234e+00 -1.48087234e+00]
[ 8.16263094e-04 1.48128400e+00 -1.50131075e+00 -1.48087234e+00 2.98994780e+00 -1.48087234e+00]
[ 1.48128400e+00 -1.50131075e+00 8.16263095e-04 -1.48087234e+00 -1.48087234e+00 2.98994780e+00]]
Solution after rounding =
[[ 1. -0.5 -0.5 -1.5 0. 1.5]
[-0.5 1. -0.5 0. 1.5 -1.5]
[-0.5 -0.5 1. 1.5 -1.5 0. ]
[-1.5 0. 1.5 3. -1.5 -1.5]
[ 0. 1.5 -1.5 -1.5 3. -1.5]
[ 1.5 -1.5 0. -1.5 -1.5 3. ]]
Eigenvalues =
[ -3.66863824e-04 1.62150777e-03 1.62150779e-03 4.11202771e-02 5.96370990e+00 5.96370990e+00]
```
The SDP solver produces a matrix $\rm Q$ whose (numerical) rank is $2$. Note that one of the eigenvalues of $\rm Q$ is slightly negative due to numerical noise.
---
Exact solution
--------------
The approximate solution produced by the SDP solver suggests that the exact solution is
$$\mathrm Q = \begin{bmatrix} 1 & - \frac{1}{2} & - \frac{1}{2} & - \frac{3}{2} & 0 & \frac{3}{2}\\- \frac{1}{2} & 1 & - \frac{1}{2} & 0 & \frac{3}{2} & - \frac{3}{2}\\- \frac{1}{2} & - \frac{1}{2} & 1 & \frac{3}{2} & - \frac{3}{2} & 0\\- \frac{3}{2} & 0 & \frac{3}{2} & 3 & - \frac{3}{2} & - \frac{3}{2}\\0 & \frac{3}{2} & - \frac{3}{2} & - \frac{3}{2} & 3 & - \frac{3}{2}\\ \frac{3}{2} & - \frac{3}{2} & 0 & - \frac{3}{2} & - \frac{3}{2} & 3\end{bmatrix}$$
It is easy to verify that, indeed, this is the exact solution. Using Python + [SymPy](http://www.sympy.org):
```
from sympy import *
# build Q matrix
U = Matrix([[ 1, -1, -1, -3, 0, 3],
[ 0, 1, -1, 0, 3, -3],
[ 0, 0, 1, 3, -3, 0],
[ 0, 0, 0, 3, -3, -3],
[ 0, 0, 0, 0, 3, -3],
[ 0, 0, 0, 0, 0, 3]])
Q = (U + U.T) / 2
print "Determinant = ", Q.det()
print "Rank = ", Q.rank()
print "Eigenvalues = ", Q.eigenvals()
# compute Cholesky decomposition
L = Q.cholesky()
print "6x2 square root = ", L[:,[0,1]]
#####################################
# compute the exact SOS decomposition
#####################################
x, y, z = symbols('x y z')
# quartic form
f = (x**2 + y**2 + z**2)**2 - 3 * ( x**3 * y + y**3 * z + z**3 * x)
# quadratic forms
q1 = (L[:,0].T * Matrix([x**2, y**2, z**2, x*y, x*z, y*z]))[0,0]
q2 = (L[:,1].T * Matrix([x**2, y**2, z**2, x*y, x*z, y*z]))[0,0]
print "Error polynomial = ", simplify(q1**2 + q2**2 - f)
```
This script produces the following output:
```
Determinant = 0
Rank = 2
Eigenvalues = {0: 4, 6: 2}
6x2 square root = Matrix([[ 1, 0],
[-1/2, sqrt(3)/2],
[-1/2, -sqrt(3)/2],
[-3/2, -sqrt(3)/2],
[ 0, sqrt(3)],
[ 3/2, -sqrt(3)/2]])
Error polynomial = 0
```
Thus, a **SOS decomposition** of $f$ is
$$\boxed{\begin{array}{rl} f (x,y,z) &= \left( x^{2} - \frac{y^{2}}{2} - \frac{z^{2}}{2} - \frac{3}{2} x y + \frac{3}{2} y z \right)^2 + \left( \frac{\sqrt{3}}{2} \left( y^{2} - z^{2} - x y + 2 x z - y z \right) \right)^2\\ &= \frac{1}{4} \left( 2 x^{2} - y^{2} - z^{2} - 3 x y + 3 y z \right)^2 + \frac{3}{4} \left( y^{2} - z^{2} - x y + 2 x z - y z \right)^2\end{array}}$$
---
References
----------
* Pablo Parrilo, [Semidefinite programming relaxations for semialgebraic problems](http://www.mit.edu/~parrilo/pubs/files/SDPrelaxations.pdf), 2001.
* Helfried Peyrl, Pablo Parrilo, [Computing sum of squares decompositions with rational coefficients](https://doi.org/10.1016/j.tcs.2008.09.025), Theoretical Computer Science, Volume 409, Issue 2, December 2008. | Using [Macaulay2](https://faculty.math.illinois.edu/Macaulay2) (version 1.16) with package [SumsOfSquares](https://sums-of-squares.github.io/sos):
```
i1 : needsPackage( "SumsOfSquares" );
i2 : R = QQ[x,y,z];
i3 : f = (x^2 + y^2 + z^2)^2 - 3*( x^3 * y + y^3 * z + z^3 * x);
i4 : sosPoly solveSOS f
1 2 1 1 1 2 2 9 1 2 2 2 1 2 2
o4 = (3)(- -x + x*y - -x*z - -y*z + -z ) + (-)(- -x + -y + x*z - y*z - -z )
2 2 2 2 4 3 3 3
o4 : SOSPoly
```
Printing:
```
i5 : tex o4
o5 = $\texttt{SOSPoly}\left\{\texttt{coefficients}\,\Rightarrow\,\left\{3,\,\frac{9}{4}\right\},\,\texttt{generators}\,\Rightarrow\,\left\{-\frac{1}{2}\,x^{2}+x\,y-\frac{1}{2}\,x\,z
-\frac{1}{2}\,y\,z+\frac{1}{2}\,z^{2},\,-\frac{1}{3}\,x^{2}+\frac{2}{3}\,y^{2}+x\,z-y\,z-\frac{1}{3}\,z^{2}\right\},\,\texttt{ring}\,\Rightarrow\,R\right\}$
```
In $\TeX$:
$$\texttt{SOSPoly}\left\{\texttt{coefficients}\,\Rightarrow\,\left\{3,\,\frac{9}{4}\right\},\,\texttt{generators}\,\Rightarrow\,\left\{-\frac{1}{2}\,x^{2}+x\,y-\frac{1}{2}\,x\,z
-\frac{1}{2}\,y\,z+\frac{1}{2}\,z^{2},\,-\frac{1}{3}\,x^{2}+\frac{2}{3}\,y^{2}+x\,z-y\,z-\frac{1}{3}\,z^{2}\right\},\,\texttt{ring}\,\Rightarrow\,R\right\}$$
Hence,
$$\boxed{ f = 3 \left( -\frac{1}{2}\,x^{2}+x\,y-\frac{1}{2}\,x\,z
-\frac{1}{2}\,y\,z+\frac{1}{2}\,z^{2} \right)^2 + \frac{9}{4} \left( -\frac{1}{3}\,x^{2}+\frac{2}{3}\,y^{2}+x\,z-y\,z-\frac{1}{3}\,z^{2} \right)^2 }$$
---
[polynomials](/questions/tagged/polynomials "show questions tagged 'polynomials'") [sum-of-squares-method](/questions/tagged/sum-of-squares-method "show questions tagged 'sum-of-squares-method'") [macaulay2](/questions/tagged/macaulay2 "show questions tagged 'macaulay2'") |
1,108,428 | How can I convert an Excel date (in a number format) to a proper date in Python? | 2009/07/10 | [
"https://Stackoverflow.com/questions/1108428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5363/"
] | Please refer to this link: [Reading date as a string not float from excel using python xlrd](https://stackoverflow.com/questions/13962837/reading-date-as-a-string-not-float-from-excel-using-python-xlrd)
it worked for me:
in shot this the link has:
```
import datetime, xlrd
book = xlrd.open_workbook("myfile.xls")
sh = book.sheet_by_index(0)
a1 = sh.cell_value(rowx=0, colx=0)
a1_as_datetime = datetime.datetime(*xlrd.xldate_as_tuple(a1, book.datemode))
print 'datetime: %s' % a1_as_datetime
``` | Since there's a chance that your excel files are coming from different computers/people; there's a chance that the formatting is messy; so be extra cautious.
I just imported data from 50 odd excels where the dates were **entered** in `DD/MM/YYYY` or `DD-MM-YYYY`, but most of the Excel files **stored** them as `MM/DD/YYYY` (Probably because the PCs were setup with `en-us` instead of `en-gb` or `en-in`).
Even more irritating was the fact that dates above `13/MM/YYYY` were in `DD/MM/YYYY` format still. So there was variations within the Excel files.
The most reliable solution I figured out was to manually set the Date column on each excel file to to be Plain Text -- then use this code to parse it:
```
if date_str_from_excel:
try:
return datetime.strptime(date_str_from_excel, '%d/%m/%Y')
except ValueError:
print("Unable to parse date")
``` |
10,584,370 | I've read about the jQuery.ajax method and believe this should be what I need -- but so far can't get it to work.
I created a test mysql database with a table called "users", added rows to that table for "name" and "location", and then made sure I could save data to it using the command line, which I could. Then I made a test page with a button on it and added this copy to my scripts file (the $.ajax part comes straight from the jQuery api examples):
```
$('#button').click(function(){
saveData();
});
function saveData(){
$.ajax({
type: "POST",
url: "process.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data was saved: " + msg );
});
}
```
I do indeed get an alert message, "Data was saved", but nothing has actually been saved to my database. I must be doing something wrong with process.php, but not sure what. Here's the code in process.php (I set variables for database, db\_host, user, etc that I don't display here):
```
// 1. Create a connection to the server.
$connection = mysql_connect($db_host, $db_user,$db_pwd);
// make sure a connection has been made
if (!$connection){
die("Database connection failed: " . mysql.error());
}
// 2. Select the database on the server
$db_select = mysql_select_db($database, $connection);
if (!$db_select){
die("Database selection failed: " . mysql.error());
}
// START FORM PROCESSING
if (isset($_POST['submit'])) { // Form has been submitted.
$name = trim(mysql_prep($_POST['name']));
$location = trim(mysql_prep($_POST['location']));
// INSERT THE DATA
$query = "INSERT INTO user ( name, location )
VALUES ( '{$name}','{$location}' )";
// Confirm if the query is successful.
$result = mysql_query($query, $connection);
}
``` | 2012/05/14 | [
"https://Stackoverflow.com/questions/10584370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1392641/"
] | In this example, $\_POST['submit'] is not set because you are no sending the form as usual, you are rsendin data with ajax and there isn't any variable called "submit".
This may work better:
```
if ((isset($_POST['name'])) && (isset($_POST['location']))) { // Form has been submitted.
$name = trim(mysql_prep($_POST['name']));
$location = trim(mysql_prep($_POST['location']));
// INSERT THE DATA
$query = "INSERT INTO user ( name, location )
VALUES ( '{$name}','{$location}' )";
// Confirm if the query is successful.
$result = mysql_query($query, $connection);
}
``` | Since you aren't submitting via a traditional form, but using ajax, I suspect submit isn't part of the post. Check that by putting in the following else clause to your code. If you're hitting that die statement, then remove the if test
```
if (isset($_POST['submit'])) { // Form has been submitted.
$name = trim(mysql_prep($_POST['name']));
$location = trim(mysql_prep($_POST['location']));
// INSERT THE DATA
$query = "INSERT INTO user ( name, location )
VALUES ( '{$name}','{$location}' )";
// Confirm if the query is successful.
$result = mysql_query($query, $connection);
} else {
die("$_POST['submit'] didn't exist");
}
``` |
13,703,596 | I have been trying to get H264 encoding to work with input captured by the camera on an Android tablet using the new low-level [MediaCodec](http://developer.android.com/reference/android/media/MediaCodec.html). I have gone through some difficulties with this, since the MediaCodecAPI is poorly documented, but I've gotten something to work at last.
I'm setting up the camera as follows:
```
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewFormat(ImageFormat.YV12); // <1>
parameters.setPreviewFpsRange(4000,60000);
parameters.setPreviewSize(640, 480);
mCamera.setParameters(parameters);
```
For the encoding part, I'm instantiating the MediaCodec object as follows:
```
mediaCodec = MediaCodec.createEncoderByType("video/avc");
MediaFormat mediaFormat = MediaFormat.createVideoFormat("video/avc", 640, 480);
mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, 500000);
mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, 15);
mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT,
MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar); // <2>
mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 5);
mediaCodec.configure(mediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
mediaCodec.start();
```
The final goal is to create an RTP-stream (and correspond with Skype), but so far I am only streaming the raw H264 directly to my desktop. There I use the following GStreamer-pipeline to show the result:
```
gst-launch udpsrc port=5555 ! video/x-h264,width=640,height=480,framerate=15/1 ! ffdec_h264 ! autovideosink
```
All works well, except for the colors. I need to set 2 colorformats in the computer: one for the camera-preview (line tagged with `<1>`) and one for the MediaCodec-object (tagged with `<2>`)
To determine the acceptable values for the lines `<1>` I used `parameters.getSupportedPreviewFormats()`. From this, I know that the only supported formats on the camera are [ImageFormat.NV21](http://developer.android.com/reference/android/graphics/ImageFormat.html#NV21) and [ImageFormat.YV2](http://developer.android.com/reference/android/graphics/ImageFormat.html#YV12).
For `<2>`, I retrieved the [MediaCodecInfo.CodecCapabilities](http://developer.android.com/reference/android/media/MediaCodecInfo.CodecCapabilities.html)-object for type *video/avc*, being the integer values 19 (corresponding with [MediaCodecInfo.CodecCapabilities.COLOR\_FormatYUV420Planar](http://developer.android.com/reference/android/media/MediaCodecInfo.CodecCapabilities.html#COLOR_FormatYUV420Planar) and 2130708361 (which doesn't correspond with any value of [MediaCodecInfo.CodecCapabilities](http://developer.android.com/reference/android/media/MediaCodecInfo.CodecCapabilities.html)).
Any other value than the above results in a crash.
Combining these settings gives different results, which I'll show below. Here's the screenshot on Android (i.e. the "real" colors):

Here are the results as shown by Gstreamer:
`<1>` = NV21, `<2>` = COLOR\_FormatYUV420Planar

`<1>` = NV21, `<2>` = 2130708361

`<1>` = YV2, `<2>` = COLOR\_FormatYUV420Planar

`<1>` = YV2, `<2>` = 2130708361

As can be seen, none of these are satisfying. The YV2-colorspace looks the most promising, but it looks like red (Cr) and blue (Cb) are inverted. The NV21 looks interlaced I guess (however, I'm no expert in this field).
Since the purpose is to communicate with Skype, I assume I shouldn't change the decoder (i.e. the Gstreamer-command), right? Is this to be solved in Android and if so: how? Or can this be solved by adding certain RTP payload information? Any other suggestion? | 2012/12/04 | [
"https://Stackoverflow.com/questions/13703596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/726156/"
] | I think it's more efficient to swap the values in place.
```
int wh4 = input.length/6; //wh4 = width*height/4
byte tmp;
for (int i=wh4*4; i<wh4*5; i++)
{
tmp = input[i];
input[i] = input[i+wh4];
input[i+wh4] = tmp;
}
```
Maybe even better, you can instead replace
```
inputBuffer.put(input);
```
With the 3 planar slices in the correct order
```
inputBuffer.put(input, 0, wh4*4);
inputBuffer.put(input, wh4*5, wh4);
inputBuffer.put(input, wh4*4, wh4);
```
I think that should only have a tiny overhead | With ImageFormat.NV21 set on camera and COLOR\_FormatYUV420Planar for encoder , similar blue shadow is seen to overlap in my case. As I understand the above swap function cannot be used in my case, any suggestions on an algorithm that can be used for this?
ps: Its a complete black screen at decoder when the camera preview format is set as YV12 |
934,236 | That question may appear strange.
But every time I made PHP projects in the past, I encountered this sort of bad experience:
Scripts cancel running after 10 seconds. This results in very bad database inconsistencies (bad example for an deleting loop: User is about to delete an photo album. Album object gets deleted from database, and then half way down of deleting the photos the script gets killed right where it is, and 10.000 photos are left with no reference).
It's not transaction-safe. I've never found a way to do something *securely*, to ensure it's *done*. If script gets killed, it gets killed. Right in the middle of a loop. It gets just killed. That never happened on tomcat with java. Java runs and runs and runs, if it takes long.
Lot's of newsletter-scripts try to come around that problem by splitting the job up into a lot of packages, i.e. sending 100 at a time, then relading the page (oh man, really stupid), doing the next one, and so on. Most often something hangs or script will take longer than 10 seconds, and your platform is crippled up.
But then, I hear that very big projects use PHP like studivz (the german facebook clone, actually the biggest german website). So there is a tiny light of hope that this bad behavior just comes from unprofessional hosting companies who just kill php scripts because their servers are so bad. What's the truth about this? Can it be configured in such a way, that scripts never get killed because they take a little longer? | 2009/06/01 | [
"https://Stackoverflow.com/questions/934236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62553/"
] | Instead of studivz (the German Facebook clone), you could look at the actual Facebook which is entirely PHP. Or Digg. Or many Yahoo sites. Or many, many others.
ignore\_user\_abort is probably what you're looking for, but you could also add another layer in terms of scheduled maintenance jobs. They basically run on a specified interval and do various things to make sure your data/filesystem are in a state that you want... deleting old/unlinked files is just one of many things you can do. | For these large loops like deleting photo albums or sending 1000's of emails your looking for ignore\_user\_abort and set\_time\_limit.
Something like this:
```
ignore_user_abort(true); //users leaves webpage will not kill script
set_time_limit(0); //script can take as long as it wants
for(i=0;i<10000;i++)
costly_very_important_operation();
```
Be carefull however that this could potentially run the script forever:
```
ignore_user_abort(true); //users leaves webpage will not kill script
set_time_limit(0); //script can take as long as it wants
while(true)
do_something();
```
That script will never die, unless you restart your server.
Therefore it is best to never set the time\_limit the 0. |
24,438,010 | I'm having trouble exporting an app for Ad Hoc Distribution on Xcode 6 beta 2:

When exporting my project for ad hoc development on Xcode 6, I receive this alert. I've tried exporting it on Xcode 5 and had no problems at all saving the .ipa. Is anyone experiencing this problem as well? | 2014/06/26 | [
"https://Stackoverflow.com/questions/24438010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2052961/"
] | **I resolved it following the next steps:**
1)in your apple developer account: Create a new Production Certificate Choose the App Store and Ad Hoc Option
2)in your apple developer account: Create a new provisioning profile with you current bundle id and the certificate created in the step one
3)in your xcode:
* Select your target
* In the tab Build Settings in the zone Code Signing
* In the sub-zone Code Signing Identity - Release
* Set your new distribution certificate (ad hoc)
* In the Provisioning Profile - set your new provisioning profile (ad hoc)
Seems that xcode 6 now requires an ad hoc distribution certificate in order to export your IPA.
 | Step1:-Login to your apple developer account
Step2:-Choose Certificates
Step3:-Delete if there are more than one distribution certificates
Step4:-Then retry archiving ( if error still exist, revoke all certificates and create new distribution certificate and edit your provision profiles.) |
15,725,445 | I am trying to learn angularjs, and have hit a block in trying to databind to an array returned from a Rest API. I have a simple azure api returning an array of person objects. Service url is <http://testv1.cloudapp.net/test.svc/persons>.
My controller code looks like:
```
angular.module("ToDoApp", ["ngResource"]);
function TodoCtrl($scope, $resource) {
$scope.svc = $resource('http://testv1.cloudapp.net/test.svc/persons', {
callback: 'JSON_CALLBACK'
}, {
get: {
method: 'JSONP',
isArray: true
}
});
$scope.items = $scope.svc.get();
$scope.msg = "Hello World";
}
```
My html looks like:
```
<html>
<head></head>
<body>
<div ng-app="ToDoApp">
<div ng-controller="TodoCtrl">
<h1>{{msg}}</h1>
<table class="table table-striped table-condensed table-hover">
<thead>
<th>Email</th>
<th>First Name</th>
<th>Last Name</th>
</thead>
<tbody>
<tr ng-repeat="item in items">
<td>{{item.Email}}</td>
<td>{{item.FirstName}}</td>
<td>{{item.LastName}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>
```
Question: The table in above html is not displaying any data. I can see the call to the api in Firebug, and can also see the JSON response from the api. What am I doing incorrectly that is causing the databinding to the REST api not work?
PS:JSFiddle demonstrating this issue is at: <http://jsfiddle.net/jbliss1234/FBLFK/4/> | 2013/03/31 | [
"https://Stackoverflow.com/questions/15725445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2175791/"
] | Just wanted to cross-post my adaptation of a solution Aleksander gave on another stackoverflow question: <https://stackoverflow.com/a/16387288/626810>:
```
methodName: {method:'GET', url: "/some/location/returning/array", transformResponse: function (data) {return {list: angular.fromJson(data)} }}
```
So when I call this function:
```
var tempData = ResourceName.methodName(function(){
console.log(tempData.list); // list will be the array in the expected format
});
```
Obviously this a little bulky if you need to GET arrays in multiple methods / resources, but it seems to work. | Use isArray param, if you have nested objects:
```
angular.module('privilegeService', ['ngResource']).
factory('Privilege', function ($resource) {
return $resource('api/users/:userId/privileges',
{userId: '@id'},
{'query': {method:'GET', isArray:false}});
});
```
Than you can use `container.object.property` notation to access objects and its properties. |
5,615 | I have been going to karate for many years and have had a bit of experience teaching our students, mostly in a 1-on-1 setting (I'm not the teacher, I just help out here and there when required).
Recently, we have had a few new students join, one of whom particularly has trouble staying still and paying attention (he's between 7-10 years old). It's not been brought to our attention that he has ADHD or anything like that but it's very similar in behaviour.
Occasionally when I have been teaching him (either alone, or with a single other student), I have been stern in telling him to stop fidgeting and to his credit, he does stop, but only for a short period of time.
As I was taught that Karate is about discipline and you need to pay attention to your teacher, his behaviour is very different to what I'm used to. More to the point, though, is due to his lack of concentration, he doesn't actually pick up on what we're doing to try and help his techniques.
Has anyone else been in a similar situation? Are there any techniques that can be used to help him concentrate more and improve quicker? | 2015/11/06 | [
"https://martialarts.stackexchange.com/questions/5615",
"https://martialarts.stackexchange.com",
"https://martialarts.stackexchange.com/users/6136/"
] | **Quick Summary as this post is long:** It is easier to keep focus when learning something if you aren't just trying to repeat it, but fully conceptualizing the mechanics, reasoning, and technique of a thing. Having the student realize the benefit of improved understanding and the downside of lack was also a huge help in getting past attention issues as it significantly improved self driven interest in learning.
**Disclaimer:** I have no experience as an educator, my opinion is based on what did and did not work for me as a child with ADHD issues strong enough that at 6 years old (1st grade) the school wasn't going to let me progress unless I was given medication or another form of professional treatment, they allowed us to try martial arts first. For the first 6 months or so there was no improvement and I just couldn't focus enough to learn anything, but we had an instructor move and his replacement had a different instruction style and I had rapid improvement.
For further background, my teachers/parents didn't think I had 'behavioural' issues, I was respectful of authority, highly empathetic of others, and pretty shy, so I wasn't one of the kids with the violent tantrums/outbursts/etc... I just would daydream or get distracted so easily I pretty much couldn't learn anything, and even entertainment didn't hold my attention for long. I hated losing focus, I felt like I was letting down my instructors, my parents, and myself, honestly I was consciously trying my hardest to stick with it, but during the conditions in which I would lose focus my ability to maintain control of my body/mind was just compromised, and there was no amount or style of scolding/punishment that could make me feel worse about it than what I already self-imposed. Given that, my information is likely not going to work on a kid that doesn't want to get better at concentrating/learning, and again I have never been an educator professionally or voluntarily, so take the following with a grain of salt.
**Failing Strategies\Conditions (for me)**:
* Simple rote based initial instruction, like Instructor shows the move a couple times, and then expects emulation. This failed because first and foremost it only captured my conscious attention (watching/assessing the task) and my body attention when trying to repeat it, my 'mind' essentially checked out as it was not needed and distractions would begin. Secondly, if I didn't repeat it successfully I didn't know why and that was amazingly frustrating and this would be amplified as the instructor tried to re-show or especially physically position me.
* Strict demands for my attention, my attention would snap back, but there was no long term affect and I would quickly lose focus again if the contextual situation had not changed.
* Long periods on a singular task, it is hard to define long, but more than a minute or twos/a dozen repetitions of the same maneuver, for me there is a finite amount of improvement/work that can be done on an individual task during any 1 period, and once I hit that wall, try as I might I cannot care about that task until I've had time to refresh with a different task/problem.
* Sideline attempts to recapture my attention, like requests that I perform some unrelated task in the hopes to put me back in the now, these always felt purposeless, and the end result was an overall reduction in interest in the whole concept.
**Successful Strategies/Conditions:**
* Specific and guided instruction/focus on mindfulness. Knowing exactly what my mind and body should be doing at any given snapshot in time during a given task gave me a whole new level of focus and significantly improved my ability to learn tasks presented in this way. Examples:
1. Periods of time spent on very simple meditation with guidance like sit in specific given position, and rhythmically repeated instructions to think about this specific thing that does not allow for interpretation like breathe in/breathe out,... or 1/2.1/2,...
2. The same rote based instruction from the first failure example, but with the initial demonstration being very slow, with thorough descriptions of what the different parts of my body should be doing at every point in the process, then when I don't have it right having the instructor initiate and guide a discussion where I end up figuring out (not being told) what was wrong. This way I am focusing on perceiving the action, physically repeating it, and mindfully contemplating/processing it.
* Switching the task context in regular intervals, I could effectively spend all day practicing just 3 maneuvers so long as each interval was short and the switches were on a schedule/routine, like 10 horse stance punches, 10 round house kicks, 10 axe kicks, (repeat in the same order). It is additionally helpful if there are specific repeated behaviours between the changing points (moving to an attention stance and "yes sensei" before each new task set, and maybe a full bow between each round of sets), and if the specific actions have an additional component, breathe in/out on alternate punches, kia'ing on each kick, etc.
* Being stern when I falter, and on repeated events or if I lose attention at a significant point like learning a brand new concept, rather than scolding show me why I should have paid attention like having me demonstrate the move to the class and ask them to critique it or have me publicly spar with a class mate (one who the instructor is confident will defeat me), something that makes me realize the lack created by my inattention, especially when that lack is present even compared to the others at my same level.
* If any class segment is going to require a lack of participation, I need to know upfront that at the end of that segment I will be tested in some way, like maybe the instructor wants to spend 10 minutes or so just talking about effective ways to combine the actions we had been going over, each student should then very briefly spar (just a couple strikes) with an authority (instructor, higher grade student, etc) where the result corresponds to their implementation of the given info, complete shutdown/moderate fall to the mat/mild embarrassment on no utilization to even draw/pat on the back for great utilization.
* Having students act as instructor and try to teach the class how to use a maneuver they have been practicing is a big help for encouraging a desire to actually learn the material.
* As the student shows a greater ability to reign in their own attention, the hand holding/guidance should reduce to increase the challenge and autonomy, additionally the actual consequences of success or failure should become noticeably more significant, but the demonstrative consequences reduced, the hope is that eventually they will begin/increase self-governing, but they won't if they don't need to.
I never really got good at martial arts, but I did become a good student and enjoyed how much easier it became to learn that I began self-imposing these strategies for actual school and that similarly improved.
Also, I am not a medical professional in any way, these techniques helped me get past a lot of my attention issues, but as an adult I've started using medication as well, and that has made a whole new world of difference.
Different situations require different types/levels of treatments, so just wanted to be clear that I'm not advocating ignoring the advice of doctors, that's for you to decide. | Teaching children is very different from teaching adults. Kids have shorter attention spans than adults, and they also have greater difficulty with delayed gratification. It's important to tailor teaching to the audience.
For kids, designing a game to work on particular skills is very effective. The kids can focus on doing well in the game (immediate gratification) and learn skills as a side effect. For example, say you want to work on horse stance. Get the kids to play freeze tag, and have kids who are frozen stand in horse stance, and require another kid to crawl through the frozen kid's legs to unfreeze them. Or to work on hand speed and hand-eye coordination, put clothespins on the kids' uniforms and have them try to grab the clothespins off a partner's uniform while defending their own clothespins.
Kids also like to do things that are usually forbidden. For example, to get kids to kiai, you can encourage them to use their outdoor voices while indoors in this specific situation.
If your goal is to get a kid to be better behaved, I think you have to start with ensuring they are well behaved at times like the beginning of class bow-in or when an instructor is talking to them. Then provide the kids the freedom to burn off some of their energy and be a bit crazy. Then when the class comes back together, enforce good behavior again. In my experience, this is much more effective than trying to straitjacket the kids at all times. |
3,463,919 | I'm trying to fetch some data from a column whose DATA\_TYPE=NUMBER(1,0) with this piece of code:
```
import cx_Oracle
conn = cx_Oracle.connect(usr, pwd, url)
cursor = conn.cursor()
cursor.execute("SELECT DELETED FROM SERVICEORDER WHERE ORDERID='TEST'")
print(cursor.fetchone()[0])
```
which complains thus:
```
Traceback (most recent call last):
File "main.py", line 247, in <module>
check = completed()
File "main.py", line 57, in completed
deleted = cursor.fetchone()[0]
cx_Oracle.DatabaseError: OCI-22061: invalid format text [T
```
Replacing 'DELETED' column with one whose DATA\_TYPE=VARCHAR2 does not throw such a complaint. | 2010/08/12 | [
"https://Stackoverflow.com/questions/3463919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/321731/"
] | These types of errors went away when I upgraded to cx\_Oracle 5.1. If the RPM doesn't install (like it happened for me on Red Hat 5.5) then you can usually rpm2cpio the file, take the cx\_Oracle.so and put it into your python site-packages directory. | I had the same error.
Commit helped me:
```
conn = cx_Oracle.connect(...)
...
cursor.execute()
conn.commit()
``` |
29,773,981 | i.e. `$(".class")[0].data().num;`
I ask because a console.log says data() is an undefined function.
```
<div class="class" data-num="1"></div>
<div class="class" data-num="2"></div>
<div class="class" data-num="3"></div>
``` | 2015/04/21 | [
"https://Stackoverflow.com/questions/29773981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4681615/"
] | Another way of stopping the handler with the use of `WeakReference` to the fragment:
```
static final class UpdateUIRunnable implements Runnable {
final WeakReference<RouteGuideFragment> weakRefToParent;
final Handler handler;
public UpdateUIRunnable(RouteGuideFragment fragment, Handler handler) {
weakRefToParent = new WeakReference<RouteGuideFragment>(fragment);
this.handler = handler;
}
public void scheduleNextRun() {
handler.postDelayed(this, INTERVAL_TO_REDRAW_UI);
}
@Override
public void run() {
RouteGuideFragment fragment = weakRefToParent.get();
if (fragment == null || fragment.hasBeenDestroyed()) {
Log.d("UIUpdateRunnable", "Killing updater -> fragment has been destroyed.");
return;
}
if (fragment.adapter != null) {
try {
fragment.adapter.forceUpdate();
} finally {
// schedule again
this.scheduleNextRun();
}
}
}
}
```
where `fragment.hasBeenDestroyed()` is simply a getter for `mDestroyed` property of a fragment:
```
@Override
public void onDestroy() {
super.onDestroy();
mDestroyed = true;
}
``` | Someone posted another question similar and the problem is due to a bug in the `ChildFragmentManager`. Basically, the `ChildFragmentManager` ends up with a broken internal state when it is detached from the `Activity`. Have a look at the [original answer here](https://stackoverflow.com/questions/15207305/getting-the-error-java-lang-illegalstateexception-activity-has-been-destroyed) |
21,734,131 | I have an array of javascript objects that represent users, like so:
```
[
{ userName: "Michael",
city: "Boston"
},
{ userName: "Thomas",
state: "California",
phone: "555-5555"
},
{ userName: "Kathrine",
phone: "444-4444"
}
]
```
Some of the objects contain some properties but not others. What I need is a clean way to ensure ALL objects get the same properties. If they don't exist, I want them to have an empty string value, like so:
```
[
{ userName: "Michael",
city: "Boston",
state: "",
phone: ""
},
{ userName: "Thomas",
city: "",
state: "California",
phone: "555-5555"
},
{ userName: "Kathrine",
city: "",
state: "",
phone: "444-4444"
}
]
```
**Update**
I should have been a little more specific. I was looking for an option that would handle this situation dynamically, so I don't have to know the properties ahead of time.
For jQuery specific, the `$.extend()` option is a good one, but will only work if you know ALL the properties ahead of time.
A few have mentioned that this should probably be a server-side task, and while I normally agree with that, there are two reasons I'm not handling this at the server-side:
1) it will be a smaller JSON object if say 900 of 1000 objects only contain 1 of a possible 9 properties.
2) the "empty" properties need to be added to satisfy a JS utility that could be replaced in the future with something that doesn't care if some properties are missing. | 2014/02/12 | [
"https://Stackoverflow.com/questions/21734131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3183431/"
] | ```
var list = [
{ userName: "Michael",
city: "Boston"
},
{ userName: "Thomas",
state: "California",
phone: "555-5555"
},
{ userName: "Kathrine",
phone: "444-4444"
}
];
for(var i = 0; i < list.length; i++){
if(list[i].state === undefined)
list[i].state = "";
if(list[i].phone === undefined)
list[i].phone = "";
};
console.log(list);
```
<http://jsfiddle.net/g5XPk/1/> | vanilla js
```js
let A = [
{
userName: "Michael",
city: "Boston",
},
{
userName: "Thomas",
state: "California",
phone: "555-5555",
},
{
userName: "Kathrine",
phone: "444-4444",
},
];
// set-difference
const diff = (a,b) => new Set([...a].filter((x) => !b.has(x)));
// all keys
const K = new Set(arr.map(o => Object.keys(o)).flat());
// add missing keys and default vals
A.forEach((e,i) => diff(K, new Set(Object.keys(e))).forEach(k => A[i][k] = ""));
``` |
16,882,196 | I try to move my project to cloudbees CI.
The android SDK is provided by cloudbees. it's located at path /opt/android/android-sdk-linux
But unfortunately, I got the following stack trace with maven-android-plugin 3.6.0:
```
message : Failed to execute goal com.jayway.maven.plugins.android.generation2:android-maven-plugin:3.6.0:generate-sources (default-generate-sources) on project wizardpager: Execution default-generate-sources of goal com.jayway.maven.plugins.android.generation2:android-maven-plugin:3.6.0:generate-sources failed: Invalid SDK: Platform/API level 16 not available. This command should give you all you need:
/opt/android/android-sdk-linux/tools/android update sdk --no-ui --obsolete --force
cause : Execution default-generate-sources of goal com.jayway.maven.plugins.android.generation2:android-maven-plugin:3.6.0:generate-sources failed: Invalid SDK: Platform/API level 16 not available. This command should give you all you need:
/opt/android/android-sdk-linux/tools/android update sdk --no-ui --obsolete --force
Stack trace :
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal com.jayway.maven.plugins.android.generation2:android-maven-plugin:3.6.0:generate-sources (default-generate-sources) on project wizardpager: Execution default-generate-sources of goal com.jayway.maven.plugins.android.generation2:android-maven-plugin:3.6.0:generate-sources failed: Invalid SDK: Platform/API level 16 not available. This command should give you all you need:
/opt/android/android-sdk-linux/tools/android update sdk --no-ui --obsolete --force
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:225)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
at org.jvnet.hudson.maven3.launcher.Maven3Launcher.main(Maven3Launcher.java:79)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchStandard(Launcher.java:329)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:239)
at org.jvnet.hudson.maven3.agent.Maven3Main.launch(Maven3Main.java:158)
at hudson.maven.Maven3Builder.call(Maven3Builder.java:98)
at hudson.maven.Maven3Builder.call(Maven3Builder.java:64)
at hudson.remoting.UserRequest.perform(UserRequest.java:118)
at hudson.remoting.UserRequest.perform(UserRequest.java:48)
at hudson.remoting.Request$2.run(Request.java:326)
at hudson.remoting.InterceptingExecutorService$1.call(InterceptingExecutorService.java:72)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722)
Caused by: org.apache.maven.plugin.PluginExecutionException: Execution default-generate-sources of goal com.jayway.maven.plugins.android.generation2:android-maven-plugin:3.6.0:generate-sources failed: Invalid SDK: Platform/API level 16 not available. This command should give you all you need:
/opt/android/android-sdk-linux/tools/android update sdk --no-ui --obsolete --force
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:110)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
... 27 more
Caused by: com.jayway.maven.plugins.android.InvalidSdkException: Invalid SDK: Platform/API level 16 not available. This command should give you all you need:
/opt/android/android-sdk-linux/tools/android update sdk --no-ui --obsolete --force
at com.jayway.maven.plugins.android.AndroidSdk.invalidSdkException(AndroidSdk.java:100)
at com.jayway.maven.plugins.android.AndroidSdk.<init>(AndroidSdk.java:78)
at com.jayway.maven.plugins.android.AbstractAndroidMojo.getAndroidSdk(AbstractAndroidMojo.java:1150)
at com.jayway.maven.plugins.android.phase01generatesources.GenerateSourcesMojo.generateR(GenerateSourcesMojo.java:461)
at com.jayway.maven.plugins.android.phase01generatesources.GenerateSourcesMojo.execute(GenerateSourcesMojo.java:195)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101)
... 28 more
channel stopped
Finished: FAILURE
```
It seems that the Platform/API level 16 is not available but it's not the case. I checked.
I used also the parameters from command line but :
clean install -Pstandard -X -Dandroid.sdk.path=/opt/android/android-sdk-linux -Dandroid.sdk.platform=16
Any advice will be appreciate. | 2013/06/02 | [
"https://Stackoverflow.com/questions/16882196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/925165/"
] | ```
int take = 3;
int skip = 2;
string s = "ABCDEFGHIJKL";
var newstr = String.Join("", s.Where((c,i) => i % (skip + take) < take));
```
---
**EDIT**
Here are my test results....
```
int take = 3;
int skip = 2;
string s = String.Join("",Enumerable.Repeat("0123456789", 200));
var t1 = Measure(10000, () => { var newstr = String.Join("", s.Where((c, i) => i % (skip + take) < take)); });
var t2 = Measure(10000, () => { var newstr = new string(s.Where((c, i) => i % (skip + take) < take).ToArray()); });
var t3 = Measure(10000, () => { var newstr = GetString(s, take, skip); });
long Measure(int n,Action action)
{
action(); //JIT???
var sw = Stopwatch.StartNew();
for (int i = 0; i < n; i++)
{
action();
}
return sw.ElapsedMilliseconds;
}
```
**OUTPUT:**
```
1665 ms. (String.Join)
1154 ms. (new string())
7457 ms. (Sayse's GetString)
```
---
**EDIT 2**
Modifying Sayse's answer as below gives the fastest result among the codes i tested. (**311** ms)
```
public string GetString(string s, int substringLen, int skipCount)
{
StringBuilder newString = new StringBuilder(s.Length);
for (int i = 0; i < s.Length; i += skipCount)
{
for (int j = 0; j < substringLen && i < s.Length; j++)
{
newString.Append(s[i++]);
}
}
return newString.ToString();
}
``` | Amidst so many good looking answer, mine might not be so sophisticated but I thought I would post it anyways. Simple logic.
```
var take = 3;
var skip = 2;
StringBuilder source = new StringBuilder("ABCDEFGHIJKL");
StringBuilder result = new StringBuilder();
while (source.Length > 0)
{
if (source.Length >= take)
{
result.Append(source.ToString().Substring(0, take));
}
else
{
result.Append(source.ToString());
}
if (source.Length > skip + take)
{
source.Remove(0, skip + take);
}
else
source.Clear();
}
``` |
8,482,059 | I want to compile this source code in Windows (It just an example):
```
start:
NOP
NOP
```
When I compile it with NASM or FASM, output file length is 2 bytes. But when I compile it with GNU assembler (as) the output file length is 292 bytes!
How to compile an assembly file to a raw binary (like DOS .com) format with GNU assembler (as)?
---
Why I do this?
I want to write my own simple OS, I write my codes with C (without using any C standard libraries even stdio.h or math.h) and convert it to assembly:
```
gcc -S my_os.c -o my_os.asm -masm=intel
```
Then, I compile assembly file to a raw binary:
```
as my_os.asm
```
Then I rename `a.out` (output of assembler) to `my_os.flp` and finally start my OS with VMWare :) | 2011/12/12 | [
"https://Stackoverflow.com/questions/8482059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/309798/"
] | **`ld --oformat binary`**
For quick and dirty tests you can do:
```
as -o a.o a.S
ld --oformat binary -o a.out a.o
hd a.out
```
Gives:
```
00000000 90 90 |..|
00000002
```
Unfortunately this gives a warning:
```
ld: warning: cannot find entry symbol _start; defaulting to 0000000000400000
```
which does not make much sense with `binary`. It could be silenced with:
```
.section .text
.globl start
start:
nop
nop
```
and:
```
ld -e start --oformat binary -o a.out a.o
```
or simply with:
```
ld -e 0 --oformat binary -o a.out a.o
```
which tells `ld` that the entry point is not `_start` but the code at address `0`.
It is a shame that neither `as` nor `ld` can take input / ouptut from stdin / stdout, so no piping.
**Proper boot sector**
If you are going to to something more serious, the best method is to generate a clean minimal linker script. `linker.ld`:
```
SECTIONS
{
. = 0x7c00;
.text :
{
*(.*)
. = 0x1FE;
SHORT(0xAA55)
}
}
```
Here we also place the magic bytes with the linker script.
The linker script is important above all to control the output addresses after relocation. Learn more about relocation at: <https://stackoverflow.com/a/30507725/895245>
Use it as:
```
as -o a.o a.S
ld --oformat binary -o a.img -T linker.ld a.o
```
And then you can boot as:
```
qemu-system-i386 -hda a.img
```
Working examples on this repository: <https://github.com/cirosantilli/x86-bare-metal-examples/blob/d217b180be4220a0b4a453f31275d38e697a99e0/Makefile>
Tested on Binutils 2.24, Ubuntu 14.04. | ```
org 100h
nop
nop
```
You can use [fasm](https://flatassembler.net/download.php) to compile:
```
fasm yourcode.asm targetfilename.com
``` |
32,088,019 | I want my frame to have 3 panels that will look like that
[](https://i.stack.imgur.com/y53Nq.png)
I'm a total newbie at `JPanel` and i cant organize it, so if someone can help i'd appreciate it | 2015/08/19 | [
"https://Stackoverflow.com/questions/32088019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5235859/"
] | Start by having a look at [Laying Out Components Within a Container](http://docs.oracle.com/javase/tutorial/uiswing/layout/index.html). While you could use a `GridBagLayout`, you could simply use a series of compound containers using `BorderLayouts`
For example...
```
JPanel left = new JPanel(new BorderLayout());
left.add(new TestPane(), BorderLayout.NORTH);
left.add(new TestPane());
JPanel main = new JPanel(new BorderLayout());
main.add(left);
main.add(new TestPane(), BorderLayout.EAST);
```
[](https://i.stack.imgur.com/kp1wE.png)
```
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.LineBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JPanel left = new JPanel(new BorderLayout());
left.add(new TestPane(), BorderLayout.NORTH);
left.add(new TestPane());
JPanel main = new JPanel(new BorderLayout());
main.add(left);
main.add(new TestPane(), BorderLayout.EAST);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(main);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setBorder(new LineBorder(Color.RED));
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
``` | You must use a [`LayoutManager`](http://docs.oracle.com/javase/7/docs/api/java/awt/LayoutManager.html).
There's plenty of information about SWING and layout manager on the net.
Check
* [A visual guide to LayoutMangers](https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html)
* [Using Layout Mangers](https://docs.oracle.com/javase/tutorial/uiswing/layout/using.html)
Or just google for SWING and layout. |
31,909,427 | Why is it considered "best practice" in java to use `Logger` with `static` as:
```
public static final Logger LOGGER = LoggerFactory.getLogger(....)
```
I can't figure the reson why. If I use one logger instance and pass it by constructor, it shouldn't affect performance.
Can anybody explain why? Is it better then DI? If so, why? There are lot of opinions. Or is it just "because of java way"? | 2015/08/09 | [
"https://Stackoverflow.com/questions/31909427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1815451/"
] | I'm arguing that you can achieve the same results with using **setter injection** and **Dependency Injection Container**.
You can still have very simple logging, it just isn't static and therefore can be configured and changed in the DI Container, without configuring some global static state of some global static factory, that is usually really hard to test and maintain.
However, I know that making it static is pragmatic. I'm just arguing that doing it the DI way is cleaner. | That's because doing logging properly is very difficult. [Consider the single responsibility principle](https://en.wikipedia.org/wiki/Single_responsibility_principle):
>
> In object-oriented programming, the single responsibility principle states that every class should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility.
>
>
>
However, if you think about it, code that manages logging is *never going to be the primary responsibility of a class.* The class is going to do what it does, and then you might add some logging statements that are a **second responsibility** of the class. How can this be resolved?
One way is to use [Aspect Oriented Programming](https://en.wikipedia.org/wiki/Aspect-oriented_programming) and reflection to go through your code and try to log activities as they happen, but this is ugly and needs to be tacked on to the language. Another way would be to add `Logger` objects to the construction of classes, but this has a few drawbacks:
1. You can only do this without adding *lots* of boilerplate if you are using a DI framework
2. You still have to configure the `Logger`'s name somehow, which means the injection now depends on the class that it's being injected into.
3. Again, if you aren't using a DI framework, then you have to somehow maintain access to the same `Logger` object at object creation, or you end up creating many duplicate objects that cost memory, for no advantage, which is even more boilerplate code.
So, what to do? The *easiest* way would be to allow all classes to have static access to a `Logger` object. SLF4J provides this mechanism with `LoggerFactory.getLogger()`, as you correctly point out. It's one line of code that can enable fully customizable behavior within all of your classes to use logging functionality, using the [Factory Pattern](https://en.wikipedia.org/wiki/Factory_(object-oriented_programming)). You don't have to worry about injection, about reflection, about configuring AOP; it's simple, straightforward, and works. |
40,949,342 | When pushing images to Amazon ECR, if the tag already exists within the repo the old image remains within the registry but goes in an untagged state.
So if i docker push `image/haha:1.0.0` the second time i do this (provided that something changes) the first image gets untagged from `AWS ECR`.
Is there a way to safely clean up all the registries from untagged images? | 2016/12/03 | [
"https://Stackoverflow.com/questions/40949342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/314407/"
] | Now, that ECR support lifecycle policies (<https://docs.aws.amazon.com/AmazonECR/latest/userguide/LifecyclePolicies.html>) you can use it to delete the untagged images automatically.
>
> Setting up a lifecycle policy preview using the console
>
>
> Open the Amazon ECS console at <https://console.aws.amazon.com/ecs/>.
>
>
> From the navigation bar, choose the region that contains the
> repository on which to perform a lifecycle policy preview.
>
>
> In the navigation pane, choose Repositories and select a repository.
>
>
> On the All repositories: repository\_name page, choose Dry-Run
> Lifecycle Rules, Add.
>
>
> Enter the following details for your lifecycle policy rule:
>
>
> For Rule Priority, type a number for the rule priority.
>
>
> For Rule Description, type a description for the lifecycle policy
> rule.
>
>
> For Image Status, choose either Tagged or Untagged.
>
>
> If you specified Tagged for Image Status, then for Tag Prefix List,
> you can optionally specify a list of image tags on which to take
> action with your lifecycle policy. If you specified Untagged, this
> field must be empty.
>
>
> For Match criteria, choose values for Count Type, Count Number, and
> Count Unit (if applicable).
>
>
> Choose Save
>
>
> Create additional lifecycle policy rules by repeating steps 5–7.
>
>
> To run the lifecycle policy preview, choose Save and preview results.
>
>
> Under Preview Image Results, review the impact of your lifecycle
> policy preview.
>
>
> If you are satisfied with the preview results, choose Apply as
> lifecycle policy to create a lifecycle policy with the specified
> rules.
>
>
>
From here:
<https://docs.aws.amazon.com/AmazonECR/latest/userguide/lpp_creation.html> | Setting a Lifecycle policy is definitely the best way of managing this. That being said - if you do have a bunch of images that you want to delete keep in mind that the max for batch-delete-images is 100. So you need to do this is for the number of untagged images is greater than 100:
```
IMAGES_TO_DELETE=$( aws ecr list-images --repository-name $ECR_REPO --filter "tagStatus=UNTAGGED" --query 'imageIds[0:100]' --output json )
echo $IMAGES_TO_DELETE | jq length # Gets the number of results
aws ecr batch-delete-image --repository-name $ECR_REPO --image-ids "$IMAGES_TO_DELETE" --profile qa || true
``` |
48,477,427 | I've got a problem with the infamous "Too many redirects" error on my website since I put an SSL certificate on with certbot.
I've been looking for hours here to find a solution to my problem, tried different solutions but none of them worked in my case.
Some background informations about the server : Debian 9 with Apache2 (both up to date)
I'm struggling with my VirtualHost files to get rid of this "too many redirect" error.
There are two of them, one for non-HTTPS connections and one for HTTPS connections, both are activated in Apache of course.
Here the non-HTTPS config file (pretty simple)
```
<VirtualHost *:80>
ServerAdmin contact@website.com
ServerName website.com
Redirect permanent / https://www.website.com/
</VirtualHost>
<VirtualHost *:80>
ServerAdmin contact@website.com
ServerName www.website.com
Redirect permanent / https://www.website.com/
</VirtualHost>
```
Here is the HTTPS config file
```
<IfModule mod_ssl.c>
<VirtualHost *:443>
ServerAdmin contact@website.com
ServerName website.com
Redirect permanent / https://www.website.com/
SSLCertificateFile /etc/letsencrypt/live/website.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/website.com/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf
</VirtualHost>
<VirtualHost *:443>
ServerAdmin contact@website.com
ServerName www.website.com
DocumentRoot /var/www/html
<Directory /var/www/html>
Options FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>
SSLCertificateFile /etc/letsencrypt/live/website.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/website.com/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf
</VirtualHost>
</IfModule>
```
As you notice, I want the "official" address to be "<https://www.website.com>" and all connection without "www." and/or "https" being redirected to this address.
Can someone help me ?
Many thanks ! | 2018/01/27 | [
"https://Stackoverflow.com/questions/48477427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9276847/"
] | I use CloudFlare and it suddenly stopped working with this error. I changed my CloudFlare SSL setting from flexible to full and that resolved the problem I was having. | I had the same issue. Had to add to my `/etc/apache2/sites-available/example.com-le-ssl.conf`
`RequestHeader set X-Forwarded-Proto https`
Hope this helps someone. |
33,770,964 | I just recently started learning MEAN stack so forgive me if this seems like a really dumb question. My problem is as follows:
On the client side (controller.js) I have,
```
$http({
method : 'POST',
url : '/root',
// set the headers so angular passing info as form data (not request payload)
headers : { 'Content-Type': 'application/x-www-form-urlencoded' },
data : {
type:'root',
username:$scope.rEmail,
password:$scope.rPassword
}
})
```
On the server side I have,
```
app.post('/root', function(req, res) {
console.log(req.body);
console.log(req.body.username);
});
```
My console log shows:
```
17 Nov 21:39:04 - [nodemon] starting `node server/server.js`
{ '{"type":"root","username":"testUserName","password":"testPassword"}': '' }
undefined
```
I would imagine req.body.username to give me testUserName but I get undefined. The JSON format I am getting is slightly weird. Can anyone help me out this one? I did some reading and tried using body-parser and went through angular js $http.post documentation but didn't find anything that would help me out.
I imagine the problem is at:
```
{ '{"type":"root","username":"testUserName","password":"testPassword"}': '' }
```
but I cant seem to figure out how I would pass the data from $http.post in my angular controller so that I would just get my request in identifier:value format. | 2015/11/18 | [
"https://Stackoverflow.com/questions/33770964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Nevermind, I figured it out. Seems like I needed a break from coding.
```
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
```
to
```
headers : { 'Content-Type': 'application/json' }
```
fixed the problem. | I've tried with "params" instead of "data" and worked ok, and doesn't matter if headers are "application/x-www-form-urlencoded" or "application/json"
But using "application/json" works with request.query.param1 on node. |
1,920,163 | I have a small question in JavaScript.
Here is a declaration:
```
function answerToLifeUniverseAndEverything() {
return 42;
}
var myLife = answerToLifeUniverseAndEverything();
```
If I do `console.log(myLife)`, it will print `42`, as I am just invoking the same instance of function resulting in `42` as the answer. (Basic rule on JavaScript that only references of objects are passed and not the object.)
Now, on the other, hand if I do:
```
var myLife = new answerToLifeUniverseAndEverything();
```
then I can't invoke the function; instead, `myLife` becomes just an object? I understand that this is a new copy of the same function object and not a reference, but why can't I invoke the method?
Can you please clarify the basic fundamental I am missing here? | 2009/12/17 | [
"https://Stackoverflow.com/questions/1920163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/57847/"
] | When you do `var myLife = answerToLifeUniverseAndEverything();`, myLife is simply holding the return value from the function call - in this case, 42. `myLife` knows nothing about your function in that case, because the function was already called, returned, and *then* it assigned the resulting value (42) to the new variable `myLife`.
A completely different thing happens when you do `var myLife = new answerToLifeUniverseAndEverything();` - instead, a new object is created, passed to the function as `this`, and then (assuming the function doesn't return an object itself), stored in the newly created variable. Since your function returns a number, not an object, the newly generated object is stored. | I think i've described the behaviour of `new` elsewhere. Basically when you do `new f()` the JS engine creates an object and passes that as `this`, then uses that object if the return value of `f()` is not an object.
eg.
```
o = new f();
```
is equivalent (approximately) to
```
temp = {};
temp2 = f.call(temp);
o = typeof temp2 === "object" ? temp2 : temp;
``` |
65,732,119 | ```json
"scripts": {
"release": "npm run release| tee output1.txt",
"build":"npm run build | tee output.txt"
},
```
Then I used:
```
npm run release
```
Output:Killed
Please help I pass two test cases one is remaining | 2021/01/15 | [
"https://Stackoverflow.com/questions/65732119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15010797/"
] | This is what you are expecting.
```
"scripts": {
"release": "npm -v && node -v",
"build":"node index.js"
}
```
run below commands and you can get the output as expected.
```
npm run release| tee output1.txt
npm run build | tee output.txt
``` | This is a perfect case for [post scripts](https://docs.npmjs.com/cli/v6/using-npm/scripts#pre--post-scripts):
```
"scripts": {
"release": "do something",
"postrelease": "tee output1.txt",
"build": "do something different",
"postbuild": "tee output.txt"
},
``` |
5,658 | Consider these YAML tasks which are based on two different parts of some locally-executed Ansible playbook [I read here](https://www.tricksofthetrades.net/2017/10/02/ansible-local-playbooks/):
```
- name: Update the apt package-index cache i.e. apt-get update
apt: update_cache=yes
- name: Ensure aptitude is installed
command: apt-get install -y aptitude
```
As an Ansible newbie, I recognize two different Ansible modules here: `apt` and `command`.
Why did the OP use both `apt: update_cache=yes` and `command: apt-get install -y` instead using the `apt` module in both tasks?
Note: I myself no longer use `apt-get` but `apt` even in regular Bash scripting. | 2018/12/09 | [
"https://devops.stackexchange.com/questions/5658",
"https://devops.stackexchange.com",
"https://devops.stackexchange.com/users/-1/"
] | I would highly recommend looking at this [tutorial](https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-ansible-on-ubuntu-18-04) by digital ocean. How to install and configure Ansible on Ubuntu.
Although this tutorial is not a book, I had a similar situation with the ansible docs and trying to understand them when I first got started. This tutorial will provide an in depth hands on experience for getting started with ansible. | I used the O'Reilly Ansible book: "Ansible: Up and Running, 2nd Edition" to learn Ansible and found it well-paced and helpful. It suggests using Vagrant to work with a virtual machine (VM) on your normal desktop/laptop to practise what you've learned, an approach I find very helpful - including now, since this is also a great way to prototype Ansible playbooks before deploying them.
Vagrant is also the tool advocated by Michael Heap in his "Ansible from Beginner to Pro", which is a bit faster-paced. Published in 2016 it won't have some of the newer Ansible features.
PacktPub have several Ansible books, so one of those may suit, and finally you've found LeanPub's "Ansible for DevOps" by Jeff Geerling already. (Update: Jeff Geerling now has several 1-hour [Ansible videos](https://www.jeffgeerling.com/blog/2020/ansible-101-jeff-geerling-youtube-streaming-series) [on YouTube](https://www.youtube.com/channel/UCR-DXc1voovS8nhAvccRZhg))
I hope that helps.
PS: re. your wish to avoid Vagrant, Virtualbox etc - I suggest that you consider these as useful tools to help you on your Ansible journey: You don't need to know much about them atall (sufficient info is given in the books mentioned), but they make for a really helpful way of quickly testing and prototyping your Ansible work - particularly since you can create and destroy them at will - so it's easy to recover if you mess up badly, and easy to test a playbook on several different distros at once. If you really don't like the Vagrant/Virtualbox aspect, use a spare Linux machine, be that on your local network or out there on the 'net. |
132,075 | I want to create a list of random integers in the range [0, 9], that sums up to 100 in Excel, using VBA. The list should be printed in a single column.
The routine I've written is as follows:
```vbs
Sub RandomList()
Dim arr(100) As Integer
Dim i As Integer
i = 0
Do
arr(i) = Int(10 * Rnd())
i = i + 1
Loop Until WorksheetFunction.Sum(arr) >= 100
arr(i - 1) = 100 - WorksheetFunction.Sum(arr) + arr(i - 1)
Range("A1").Resize(i, 1) = Application.Transpose(arr)
End Sub
```
This gives the correct result, but I'm sure there are ways to improve it:
* Initializing the size to 100, seems odd. I want to use a [dynamic sized array](http://www.excel-easy.com/vba/examples/dynamic-array.html), but I can't get it to work. I've tried different approaches, but all result in a list containing only zeros (or an error).
* I tried to sum all elements except the last one, but I didn't manage to make it work. Therefore I had to sum all elements, and subtract the last one. I can't believe that's optimal.
* Should I delete the `(100-i)` last elements of the list somehow, before writing it to Excel? How and why?
* Is the last line a good way of writing to Excel, or is there a better way?
* I'm looking for a nice and clean way of doing this task, not necessarily the fastest way
I can do the same thing using `Function RandomList()` too, but as far as I can tell, that's used when I want to call the function from the worksheet.
PS! I'm not interested in some builtin function that can do the task directly, as I'm doing this to learn VBA, not to do that specific task.
---
This is inspired by [this](https://stackoverflow.com/q/37835877/2338750) (bad) question on SO. There are other approaches there that can be used, but they are substantially different. I'm wondering if the way I'm doing this is a "good way" of doing it, or if it's filled with "Bad practice" code. | 2016/06/15 | [
"https://codereview.stackexchange.com/questions/132075",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/109032/"
] | The procedure is doing a number of completely unrelated things that should be separated:
* Populating an array with random integers
* Dumping an array of random integers onto a worksheet
Make the procedure a `Function`, and rename it to something that starts with a verb, something that *tells the reader what it does*. `GenerateRandomValues` for example.
I'd take the magic cap-value `100` as a (perhaps `Optional`) parameter.
Every time you use `WorksheetFunction.Sum`, you're making Excel iterate all values in the array, add up all the values and return a value *that you should already know*.
Declare a local variable to hold the cumulative sum, and add every new generated integer to it as you add it to the array: then when you need to know what the total is, *you don't need to calculate or iterate anything*, it's right there waiting to be used.
Make the function return the array, and then make another procedure responsible for calling that function, and consuming its result: then you can write as many test methods (in a dedicated test module) as you like, to document your specifications and programmatically validate that the function works as intended given any input!
I'd rename `arr` to either `result` or `values`.
---
>
> *Initializing the size to 100, seems odd. I want to use a dynamic sized array*
>
>
>
Indeed. See [@Zak's answer](https://codereview.stackexchange.com/a/132081/23788), but then I'd make sure to minimize the amount of resizing happening, and initialize the dynamic array with 11 items, since it's a given that you're going to need *at least* that many iterations to get to a sum of 100 if you're generating random numbers between 0 and 9. This could be calculated if the 100 is a parameter.
>
> *Is the last line a good way of writing to Excel, or is there a better way?*
>
>
>
You're dumping an entire array of values in a single write, it doesn't get any better than that! If transposing the output makes it look the way it needs to be, then having Excel to the hard work of transposing the values is the best way to go about it IMO. The only problem I'm seeing is that you're implicitly referring to the active sheet, which may or may not be where you want to dump the results: it's always best to use an explicit worksheet reference, rather than `[_Global].Range()`. | I think it's pretty good. An alternate way of handling some of that would be
```
Option Explicit
Public Sub RandomList()
Columns(1).Clear
Dim myNumbers(100) As Long
Dim i As Long
Dim j As Long
Dim k as Long
i = 0
k = 0
Do
j = Int(10 * Rnd())
'If j = 0 Then j = 1 optional if you want to keep 0s
If k + j > 100 Then j = 100 - k
k = k + j
myNumbers(i) = j
i = i + 1
Loop Until k = 100
Range("A1").Resize(i, 1) = Application.Transpose(myNumbers)
End Sub
```
It's just eliminating `0`s and fixing the last element before exiting the loop.
---
Actually, since you're looking for *n* I might do this
```
Option Explicit
Public Sub RandomList()
Const mySum = 100
Columns(1).Clear
Dim myNumbers(mySum) As Long
Dim i As Long
Dim j As Long
Dim k As Long
i = 0
k = 0
Do
j = Int(10 * Rnd())
'If j = 0 Then j = 1 optional if you want to keep 0s
If k + j > mySum Then j = mySum - k
k = k + j
myNumbers(i) = j
i = i + 1
Loop Until k = mySum
Range("A1").Resize(i, 1) = Application.Transpose(myNumbers)
End Sub
``` |
46,056,121 | I am having trouble with understanding `%in%`. In Hadley Wickham's Book "R for data science" in section 5.2.2 it says, "A useful short-hand for this problem is `x %in% y`. This will select every row where x is one of the values in y." Then this example is given:
```
nov_dec <- filter(flights, month %in% c(11, 12))
```
However, I when I look at the syntax, It appears that it should be selecting every row where y is one of the values in x(?) So in the example, all the cases where 11 and 12 (y) appear in "month" (x).
`?"%in%"` doesn't make this any clearer to me. Obviously I'm missing something, but could someone please spell out exactly how this function works? | 2017/09/05 | [
"https://Stackoverflow.com/questions/46056121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5024631/"
] | >
> It appears that it should be selecting every row where y is one of the values in x(?) So in the example, all the cases where 11 and 12 appear in "month."
>
>
>
If you don't understand the behavior from looking at the example, try it out yourself. For example, you could do this:
```
> c(1,2,3) %in% c(2,4,6)
[1] FALSE TRUE FALSE
```
So it looks `%in%` gives you a vector of `TRUE` and `FALSE` values that correspond to each of the items in the first argument (the one before `%in%`). Let's try another:
```
> c(1,2,3) %in% c(2,4,6,8,10,12,1)
[1] TRUE TRUE FALSE
```
That confirms it: the first item in the returned vector is `TRUE` if the first item in the first argument is found anywhere in the second argument, and so on. Compare that result to the one you get using `match()`:
```
> match(c(1,2,3), c(2,4,6,8,10,12,1))
[1] 7 1 NA
```
So the difference between `match()` and `%in%` is that the former gives you the actual position in the second argument of the first match for each item in the first argument, whereas `%in%` gives you a logical vector that just tells you whether each item in the first argument appears in the second.
In the context of Wickham's book example, `month` is a vector of values representing the months in which various flights take place. So for the sake of argument, something like:
```
> month <- c(2,3,5,11,2,9,12,10,9,12,8,11,3)
```
Using the `%in%` operator lets you turn that vector into the answers to the question *Is this flight in month 11 or 12?* like this:
```
> month %in% c(11,12)
[1] FALSE FALSE FALSE TRUE FALSE FALSE TRUE FALSE FALSE TRUE FALSE TRUE
[13] FALSE
```
which gives you a logical vector, i.e. a list of true/false values. The `filter()` function uses that logical vector to select corresponding rows from the `flights` table. Used together, `filter` and `%in%` answer the question *What are all the flights that occur in months 11 or 12?*
If you turned the `%in%` around and instead asked:
```
> c(11,12) %in% month
[1] TRUE TRUE
```
you're really just asking *Are there any flights in each of month 11 and month 12?*
I can imagine that it might seem odd to ask whether a large vector is "in" a vector that has only two values. Consider reading `x %in% y` as *Are each of the values from `x` also in `y`?* | this explicitly means: are value from x also in y
The best way to understand is a exemple :
```
x <- 1:10 # numbers from 1 to 10
y <- (1:5)*2 # pair numbers between 2 and 10
y %in% x # all pair numbers between 2 and 10 are in numbers from 1 to 10
x %in% y #only pair numbers are return as True
``` |
40,084,287 | As shown in image, I have added the same fragment 5 times in activity by performing on click operation on **ADD FRAGMENT** button:

Now I want to get all user entered data from those 5 edittext on click of GET DATA button. Is this possible?
(Both buttons is in Main Activity) | 2016/10/17 | [
"https://Stackoverflow.com/questions/40084287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5629657/"
] | My team colleague found a way which allows you to run migrations on build artefacts without sources. Following command replace `migrate.exe` for us:
```
dotnet exec
--runtimeconfig ./HOST.runtimeconfig.json
--depsfile ./HOST.deps.json Microsoft.EntityFrameworkCore.Design.dll
--assembly ./DB_CONTEXT_DLL.dll
--startup-assembly ./HOST.dll --data-dir ./
--root-namespace DB_CONTEXT_NAMESPACE
--verbose database update --context DB_CONTEXT_CLASS -e development
```
Update for 2.1.x version:
```
dotnet exec
--runtimeconfig ./HOST.runtimeconfig.json
--depsfile ./HOST.deps.json /PATH/TO/microsoft.entityframeworkcore.tools/.../ef.dll
--verbose database update --context DB_CONTEXT_CLASS
--assembly ./DB_CONTEXT_DLL.dll
--startup-assembly ./HOST.dll --data-dir ./
``` | Seems not possible run `dotnet ef database update` only with the DLL, and if you use the docker, the actual version of runtime `microsoft/dotnet:1.1.0-preview1-runtime` do not have the sdk installed (with the `dotnet ef database update` command).
One option to update database without use `dotnet ef database update` is execute the command bellow in some default action or startup routine.
```
_dbContext.Database.Migrate();
``` |
518,985 | My laptop diagnostic shows several pre-fails and has other issues so I am urgently shopping for a new laptop, my second using Ubuntu. I need a laptop with good graphics capabilities and have come across a couple with the Nvidia GeForce 840M graphics card. In other words, I do not have a problem now and am hoping to avoid one.
My research on Ask Ubuntu and elsewhere shows that there have been some bugs with Ubuntu 14.04 and Nvidia drivers (not just for the 840M driver) but that fixes were made or a least suggested. But I have seen nothing definitive, e.g. the Ubuntu Certification for laptops is barely starting with 14.04.
I am about to spend a 1000 dollars and would love a little more assurance before I proceed -- my understanding is that a Live CD cannot perform a full simulation. Are there easy-to-recognize concrete factors which make compatibility (more) predictable, such as specific models of computer and their processors?
I am a considering a [MSI GP60](http://www.msimobile.com/level3_productpage.aspx?id=471) with an Intel i5 4200M and an [ASUS n56jn-mb71](http://www.asus.com/Notebooks_Ultrabooks/N56JN/specifications) with an Intel i7 4700HQ. Both use an Nvidia 840M graphics card. | 2014/09/02 | [
"https://askubuntu.com/questions/518985",
"https://askubuntu.com",
"https://askubuntu.com/users/88517/"
] | I had a very similar problem and spent several days trying to get my card working.
I have an ASUS X550LN which has an Intel Graphics Driver on the CPU and a dedicated NVIDIA GEFORCE GT 840M.
First, installing the nvidia-340 drivers would cause Unity and Gnome to fail when launching. I could drop to a shell `Ctrl + Alt + F1` and remove the driver `sudo apt-get remove nvidia*` to get things back to running solely on the Intel Graphics Driver.
After some research, I discovered that having both these interfaces made the system an NVIDIA Optimus (which is actually good just not well supported on Linux yet). Luckily, there is a project called Bumblebee which will help. More info here: <https://wiki.ubuntu.com/Bumblebee>
Here is what finally worked for me:
1. Install bumbleebee
* Add bumblebee repository: `add-apt-repository ppa:bumblebee/stable`
* Update repository information: `apt-get update`
* Install packages: `apt-get install bumblebee bumblebee-nvidia virtualgl linux-headers-generic`
* Reboot
For me, at this point bumblebee was installed but the `nvidia-304` package was installed as this is what is installed with `nvidia-current`. Looking online I found that I needed Driver 337+. At the time of writing this, the best driver for me was `nvidia-340`. This however is not in the default repo so you will need to add another one.
2. Install correct nvidia driver
* Add xorg-edgers repository: `add-apt-repository ppa:xorg-edgers/ppa`
* Update repository information: `apt-get update`
* Install nvidia-xxx drivers (for 840m it was nvidia-340): `apt-get install nvidia-xxx`
For me I got an error message the first time I ran `apt-get install nvidia-xxx`. However, simply running it again worked fine. I'm not 100% sure what happened.
3. Configure bumblebee to use latest driver
* Using your favorite text editor open `/etc/bumblebee/bumblebee.conf`
* Find the line starting with `Driver` and change it to `Driver=nvidia`
* Find the line starting with `KernelDriver` and change it to `KernelDriver=nvidia-xxx`
* Find the line starting with `LibraryPath` and change it to `LibraryPath=/usr/lib/nvidia-xxx:/usr/lib32/nvidia-xxx`
* Find the line starting with `XorgModulePath` and change it to `XorgModulePath=/usr/lib/nvidia-xxx/xorg,/usr/lib/xorg/modules`
Basically, replace all of the nvidia bits with the nvidia driver you installed in step 2.
4. Reboot
After rebooting, hopefully you are able to access Unity, Gnome, or whatever display manager you're using.
5. Test that everything is working
* First test without using NVIDIA card: `glxspheres`
* Second test with NVIDIA card: `optirun glxspheres`
I hope this works for the next person! | Well, I had the same problem on my Z50-70. I tried many solutions including the ones described here. And I discovered something that worked much better for me than these two.
First add the apt-repository: `sudo add-apt-repository ppa:xorg-edgers/ppa`.
Then update package database `sudo apt-get update`.
And then install the nvidia-331 driver. Install **this exact version**, not any newer version. I tried some newer versions (and also lot of other stuff) and they were working but much worse. `sudo apt-get install nvidia-331`.
Then simply reboot. Everything should work fine.
You don't have to install additionally any things like nvidia-prime or nvidia-settings as they are installed automatically with nvidia-331.
This solution is good for both hybrid and normal systems.
For hybrid system owners:
The default used GPU should be the nVidia one but if you want to use the Intel one (e.g. for saving power) you can easilly change it with `nvidia-settings`.
Hope that helps. :-) |
228,759 | Unlike everyone elses problems! Mine crashes after I've logged on; at the part that says: "Mojang".
I had mods installed but have since removed them completely and it still isn't working.
Below I've attached the minecraft crash report:
```
---- Minecraft Crash Report ----
// My bad.
Time: 7/20/15 9:27 PM
Description: Initializing game
java.lang.OutOfMemoryError: Java heap space
at bmi.a(SourceFile:230)
at bmh.b(SourceFile:130)
at bmh.a(SourceFile:77)
at bot.j(SourceFile:553)
at bot.a(SourceFile:139)
at bou.a(SourceFile:23)
at bnn.a(SourceFile:99)
at ave.am(SourceFile:448)
at ave.a(SourceFile:310)
at net.minecraft.client.main.Main.main(SourceFile:124)
A detailed walkthrough of the error, its code path and all known details is as follows:
---------------------------------------------------------------------------------------
-- Head --
Stacktrace:
at bmi.a(SourceFile:230)
at bmh.b(SourceFile:130)
at bmh.a(SourceFile:77)
at bot.j(SourceFile:553)
at bot.a(SourceFile:139)
at bou.a(SourceFile:23)
at bnn.a(SourceFile:99)
at ave.am(SourceFile:448)
-- Initialization --
Details:
Stacktrace:
at ave.a(SourceFile:310)
at net.minecraft.client.main.Main.main(SourceFile:124)
-- System Details --
Details:
Minecraft Version: 1.8.7
Operating System: Mac OS X (x86_64) version 10.9.5
CPU: 2x Intel(R) Core(TM)2 Duo CPU P8600 @ 2.40GHz
Java Version: 1.6.0_65, Apple Inc.
Java VM Version: Java HotSpot(TM) 64-Bit Server VM (mixed mode), Apple Inc.
Memory: 282712 bytes (0 MB) / 1060372480 bytes (1011 MB) up to 1060372480 bytes (1011 MB)
JVM Flags: 5 total; -Xmx1G -XX:+UseConcMarkSweepGC -XX:+CMSIncrementalMode -XX:-UseAdaptiveSizePolicy -Xmn128M
IntCache: cache: 0, tcache: 0, allocated: 0, tallocated: 0
Launched Version: 1.8.7
LWJGL: 2.9.2
OpenGL: NVIDIA GeForce 320M OpenGL Engine GL version 2.1 NVIDIA-8.24.16 310.90.9.05f01, NVIDIA Corporation
GL Caps: Using GL 1.3 multitexturing.
Using GL 1.3 texture combiners.
Using framebuffer objects because ARB_framebuffer_object is supported and separate blending is supported.
Shaders are available because OpenGL 2.1 is supported.
VBOs are available because OpenGL 1.5 is supported.
Using VBOs: Yes
Is Modded: Probably not. Jar signature remains and client brand is untouched.
Type: Client (map_client.txt)
Resource Packs: [PureBDcraft 512x MC18, herobrinepack9110877]
Current Language: English (US)
Profiler Position: N/A (disabled)
```
And this is the text Mojang/Minecraft shows me all the time!
>
> Uhoh, it looks like the game has crashed! Sorry for the inconvenience.
>
>
> With magic and love (?) we've managed to grab some details about the crash and >we will get on it as soon as we can
> You can see the full crash below
>
>
>
Can anyone here help me? It would mean the world to me! | 2015/07/20 | [
"https://gaming.stackexchange.com/questions/228759",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/119026/"
] | Try upgrading your Java to a newer version, because the crash report indicates an older version. (Possibly an error for the indication, because it is possible to misindicate Java 8 as Java 1.40) | Go to Options > Video Settings. Make sure both VBOs and VSync are turned on. I see from your crash report VBOs are on, but VSync isn't there. I assume you don't have it on. |
129,185 | What word would mean "a grand, symbolic action" more specifically, taken in an attempt to prove a point?
For example, I am trying to figure out the word that would fill in the following sentence using the above definition:
>
> "Charlie gave every last dime he had to charity, just to prove that he didn't care about material possessions. That's one hell of a [*word-for-grand-symbolic-action*]!"
>
>
> | 2013/09/28 | [
"https://english.stackexchange.com/questions/129185",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/19688/"
] | >
> The gift of the signet ring to Mordecai by Ashuerus was [an impressive **gesture**](http://books.google.co.uk/books?id=zMVbuD633XEC&pg=PA329&dq=%22an+impressive+gesture%22&hl=en&sa=X&ei=TjpHUuOvK6KK4wS_44HgCA&ved=0CEcQ6AEwBDgU#v=onepage&q=%22an%20impressive%20gesture%22&f=false) of the honor in which he was held.
>
>
>
Because there's are negative connotation to expressions such as [gesture politics](http://dictionary.reference.com/browse/gesture+politics), you probably need some kind of *positive* qualifier for this sense ("impressive" in my example, "one hell of a" in OP's). | Here, we can reach for a French "coup de something" term.
A brilliantly successful action, or something of that sort, is a *coup d’[éclat](http://en.wiktionary.org/wiki/%C3%A9clat)*.
If we fit this into
>
> "Charlie gave every last dime he had to charity, just to prove that he didn't care about material possessions. That's one hell of a *coup d’éclat*!"
>
>
>
it seems to work, more or less. |
10,021,927 | I have a 10GB file with 200 million lines. I need to get unique lines of this file.
My code:
```
while(<>) {
chomp;
$tmp{$_}=1;
}
#print...
```
I only have 2GB memory. How can I solve this problem? | 2012/04/05 | [
"https://Stackoverflow.com/questions/10021927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1314230/"
] | If you don't care about time/IO constraints, nor disk constraints (e.g. you have 10 more GB space), you can do the following dumb algorithm:
1) Read the file (which sounds like it has 50 character lines). While scanning it, remember the longest line length `$L`.
2) Analyze the first 3 characters (if you know char #1 is identical - say `"["` - analyze the 3 characters in position N that is likely to have more diverse ones).
3) For each line with 3 characters $XYZ, append that line to file 3char.$XYZ and keep the count of how many lines in that file in a hash.
4) When your entire file is split up that way, you should have a whole bunch (if the files are A-Z only, then 26^3) of smaller files, and at most 4 files that are >2GB each.
5) Move the original file into "Processed" directory.
6) For each of the large files (>2GB), choose the next 3 character positions, and repeat steps #1-#5, with new files being 6char.$XYZABC
7) Lather, rinse, repeat. You will end up with one of the 2 options eventually:
8a) A bunch of smaller files each of which is under 2GB, all of which have mutually different strings, and each (due to its size) can be processed individually by standard "stash into a hash" solution in your question.
8b) Or, most of the files being smaller, but, you have exausted all `$L` characters while repeating step 7 for >2GB files, and you still have between 1-4 large files. Guess what - since
those up-to-4 large files have identical characters within a file in positions 1..$L, they can ALSO be processed using the "stash into a hash" method in your question, since they are not going to contain more than a few distinct lines despite their size!
Please note that this may require - at the worst possible distributions - `10GB * L / 3` disk space, but will ONLY require 20GB disk space if you change step #5 from "move" to "delete".
Voila. Done.
---
As an alternate approach, consider hashing your lines. I'm not a hashing expert but you should be able to compress a line into a hash <5 times line size IMHO.
If you want to be fancy about this, you will do a frequency analysis on character sequences on the first pass, and then do compression/encoding this way. | If you have more processor and have at least 15GB free space and your storage fast enough, you could try this out. This will process it in paralel.
```
split --lines=100000 -d 4 -d input.file
find . -name "x*" -print|xargs -n 1 -P10 -I SPLITTED_FILE sort -u SPLITTED_FILE>unique.SPLITTED_FILE
cat unique.*>output.file
rm unique.* x*
``` |
503,617 | So I recovered a text file from an old hdd, but I failed to completely recover all of the data. The data that wasn't correctly recovered has returned as null bytes. How can I remove every line from the file that contains these bytes?
Example of corrupt data
```
xE3
xAF
xE2
xBF
NUL
xBD
```
and a ton more...
I know NULL is equal to \x00.
How can I remove every line containing corrupt data with sed rather than removing the bytes individually?
There are so many variations of bytes/corrupt data that I doubt I would be able to discover all of them with regex.. | 2019/02/28 | [
"https://unix.stackexchange.com/questions/503617",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/339364/"
] | To remove lines that contain byte 0 or bytes 128 to 255, you can use:
```
perl -ne 'print unless /[\0\200-\377]/'
```
Or with GNU `grep` built with PCRE support:
```
LC_ALL=C grep -vaP '[\0\200-\377]'
```
See also the `strings` command to extract what looks like printable text from data.
To just remove those bytes:
```
tr -d '\0\200-\377'
``` | Yes. You can do it like this:
`sed -e '/\x00/d' [filename] > [new_filename]`
If you want to edit the file in-place:
`sed -i '/\x00/d' [filename]`
You can also, combine the two, change the original file and keep a backup copy:
`sed -i~ '/\x00/d' [filename]`
That will delete any line of the file that contains at least 1 NULL. |
21,506,505 | Here is the link to the documentation on GitHub:
<https://github.com/Unitech/pm2#startup-script-generation--pm2-startup>
It is setup to work with Ubuntu/CentOS/Redhat. I need it to work with my Dreamhost VPS which is a Debian machine.
Can someone advise me on how I might tweak the init script to make it work on a Debian box? Thanks!! | 2014/02/02 | [
"https://Stackoverflow.com/questions/21506505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1766637/"
] | Try ubuntu solution. Since ubuntu is a debian fork, it should work there. | You can just add a cronjob like:
```
@reboot cd /path/to/app && pm2 start app.js
```
Remember to install the cron in the user that will run the daemon, **NOT ROOT**.
If you user can't install the cron, just install the cron where you prefer and add the parameter `-u` to specify the daemon runner user. |
3,505,128 | The latter makes perfect sense to me, but what's the skinny with the former? I researched but couldn't understand the drift. TIA | 2020/01/11 | [
"https://math.stackexchange.com/questions/3505128",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/740977/"
] | Consider the Number line marked with integers. Now, Paste the integer $60$ over $0$ and wrap around the entire number line over the circle formed as above.
Now, we see that when we count on the above number line constructed by the above procedure, the integer $-1$ coincides with the integer $59$. This is called **Modular Arithmetic**.
**Remarks:**
$1$. The above construction can be generalized to any positive integer $n$ by replacing $60$ with $n$.
$2$. In general, while doing Modular arithmetic, we look for a solution inside the set $\{0,1,2,...,n-1\}$. But we can consider any set containing "$n$" consecutive integers.
Note: You can refer to any *Elementary Number Theory* Book. It will be more helpful.
This [video Link](https://www.youtube.com/watch?v=5OjZWSdxlU0) might be useful for the above-said construction
I hope this answers your questions. | Welcome to Maths SX! I suppose you're asking why $-1\bmod 60\equiv 59$? This is is because $59+1\equiv 0\bmod 60$, so in the ring $\;\mathbf Z/60\mathbf Z$, the opposite of the congruence class of $1$ is the congruence class of $59$, by definition of the opposite of an element (i.e. its additive inverse). |
32,132,333 | I tried various methods fro internet to pass spinner selected item to other class and display in text view
Below is my code.
Whenever I open my app,It crashes.
Your suggestions are greatly appreciated.
Thanks in Advance.
This is my first class BuddyActivity
```
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonSubmit = (Button) findViewById(R.id.buttonGo);
buttonSubmit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Spinner transportSpinner = (Spinner) findViewById(R.id.spinnerSection);
Intent i = new Intent(BuddyActivity.this.getApplicationContext(),search_project.class);
i.putExtra("transportSpinnerValue", transportSpinner.getSelectedItem().toString());
BuddyActivity.this.startActivity(i);
}
});
}
;
```
This is my second class:
```
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_project);
Bundle extras = getIntent().getExtras();
String transportItemChosen = extras.getString("transportSpinnerValue");
}
``` | 2015/08/21 | [
"https://Stackoverflow.com/questions/32132333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4975774/"
] | Use this peice of code in your BuddyActivity:
```
Intent i = new Intent(BuddyActivity.this,search_project.class);
String selectedItem = transportSpinner.getSelectedItem().toString();
i.putExtra("transportSpinnerValue", selectedItem);
startActivity(i);
```
And use this peice of code in your second class:
```
Intent getItemIntent = getIntent();
String getItem = getItemIntent.getStringExtra("transportSpinnerValue");
```
make sure you have register your second activity in your Menifest file. | Class.1.java
```
but.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Spinner transportSpinner = (Spinner) findViewById(R.id.spinnerSection);
Intent i = new Intent(BuddyActivity.this,search_project.class);
i.putExtra("transportSpinnerValue", transportSpinner.getSelectedItem().toString());
startActivity(i);
}
});
```
Class2.java
```
Intent extras = getIntent();
String transportItemChosen = extras.getStringExtra("transportSpinnerValue");
``` |
22,043,480 | I'm using java 1.6.
I have a set of items, and each item has a name and a set of components. each component also has a name.
```
Set<Item>
Class Item
String name
Set<Component>
Class Component
String name
```
I'm now tasked with writing a method with input: item name + component name, and output: does this pair exist in the list of items.
```
public boolean hasItemComponentPair(String itemName, String componentName)
{
for(Item item : getItems())
{
if (item.getName() == itemName)
{
for(Component component : item.getComponents())
{
if (component.getName() == componentName)
{
return true;
}
}
}
}
return false;
}
```
The easiest way to do is by simply going through the elements of the sets one-by-one, and break if a match is found. This approach is doable for small sets.
My set of items is typically between 5 and 20 items, and the set of components is about the same. So there's between 25 and 400 unique item-component pairs. This amount of pairs seems too large for the naive algorithm to be efficient, especially if the method is called several times. But I also think a divide and conquer technique is too verbose for the given amount of elements.
What data structures and algorithms are typically used for this problem, keeping in mind the giving size of the sets? | 2014/02/26 | [
"https://Stackoverflow.com/questions/22043480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1884155/"
] | If you can change your Item class you can do it like that:
```
class Item {
String name;
Map<String, Component> components;
}
```
In the map above key is the name of component.
Than change your code to:
```
public boolean hasItemComponentPair(String itemName, String componentName)
{
for(Item item : getItems())
{
if (item.getName().equals(itemName))
{
return item.getComponents().containsKey(componentName);
}
}
return false;
}
```
Now you need to traverse only one collection. | Override the equals and hashCode method in your Item and Component classes like following:
```
// Item.java
import java.util.Set;
public class Item
{
private String name;
private Set<Component> components;
public Item(String name)
{
this.name = name;
}
@Override
public int hashCode()
{
return name.hashCode();
}
@Override
public boolean equals(Object obj)
{
if (obj instanceof Item)
{
Item item = (Item) obj;
if (item.name != null && this.name != null)
return item.name.equals(this.name);
}
return false;
}
public Set<Component> getComponents()
{
return components;
}
public void setComponents(Set<Component> components)
{
this.components = components;
}
}
// Component.java
public class Component
{
private String name;
public Component(String name)
{
this.name = name;
}
@Override
public int hashCode()
{
return name.hashCode();
}
@Override
public boolean equals(Object obj)
{
if (obj instanceof Component)
{
Component component = (Component) obj;
if (component.name != null && name != null)
return component.name.equals(this.name);
}
return false;
}
}
```
This will give you constant time lookup. So you can search for elements in constant time.
Following is a demonstration:
```
import java.util.HashSet;
public class SearchDemo
{
public static void main(String[] args)
{
Item item1 = new Item("Item 1");
item1.setComponents(new HashSet<Component>());
item1.getComponents().add(new Component("Component A"));
item1.getComponents().add(new Component("Component B"));
item1.getComponents().add(new Component("Component C"));
Item item2 = new Item("Item 2");
item2.setComponents(new HashSet<Component>());
item2.getComponents().add(new Component("Component X"));
item2.getComponents().add(new Component("Component Y"));
item2.getComponents().add(new Component("Component Z"));
HashSet<Item> items = new HashSet<>();
items.add(item1);
items.add(item2);
// Input from user
String inputItem = "Item 2";
String inputComponent = "Component Y";
// Cast it to item and component
Item searchItem = new Item(inputItem);
Component searchComponent = new Component(inputComponent);
if (items.contains(searchItem)) // Constant time search
{
System.out.println("Contains Item");
for (Item item : items)
{
if (item.equals(searchItem))
{
if (item.getComponents().contains(searchComponent)) // Constant time search
{
System.out.println("Contains even the component");
}
}
}
}
}
}
```
The only issue is the for loop in the above lookup.
The item can be searched in constant time, but it has to be searched for again in the set (if it really exists) because I kind of fooled the program into believing that the `searchItem` is equal to the `item` in the set. Once the item is really found and its component set is extracted from it, its a constant time search for the `componentItem`.
If you have a `HashMap` of `Component`s in the `Item` class, instead of the `Set`, and each key in the `HashMap` is the `name` of the `component`, then the input from the user can be searched in constant time! |
44,708,248 | Despite the conventions of R, data collection and entry is for me most easily done in vertical columns. Therefore, I have a question about efficiently converting to horizontal rows with the gather() function in the tidyverse library. I find myself using gather() over and over which seems inefficient. Is there a more efficient way? And can an existing vector serve as the key? Here is an example:
Let's say we have the following health metrics on baby birds.
```
bird day_1_mass day_2_mass day_1_heart_rate day_3_heart_rate
1 1 5 6 60 55
2 2 6 8 62 57
3 3 3 3 45 45
```
Using the gather function I can reorganize the mass data into rows.
```
horizontal.data <- gather(vertical.data,
key = age,
value = mass,
day_1_mass:day_2_mass,
factor_key=TRUE)
```
Giving us
```
bird day_1_heart_rate day_3_heart_rate age mass
1 1 60 55 day_1_mass 5
2 2 62 57 day_1_mass 6
3 3 45 45 day_1_mass 3
4 1 60 55 day_2_mass 6
5 2 62 57 day_2_mass 8
6 3 45 45 day_2_mass 3
```
And use the same function again to similarly reorganize heart rate data.
```
horizontal.data.2 <- gather(horizontal.data,
key = age2,
value = heart_rate,
day_1_heart_rate:day_3_heart_rate,
factor_key=TRUE)
```
Producing a new dataframe
```
bird age mass age2 heart_rate
1 1 day_1_mass 5 day_1_heart_rate 60
2 2 day_1_mass 6 day_1_heart_rate 62
3 3 day_1_mass 3 day_1_heart_rate 45
4 1 day_2_mass 6 day_1_heart_rate 60
5 2 day_2_mass 8 day_1_heart_rate 62
6 3 day_2_mass 3 day_1_heart_rate 45
7 1 day_1_mass 5 day_3_heart_rate 55
8 2 day_1_mass 6 day_3_heart_rate 57
9 3 day_1_mass 3 day_3_heart_rate 45
10 1 day_2_mass 6 day_3_heart_rate 55
11 2 day_2_mass 8 day_3_heart_rate 57
12 3 day_2_mass 3 day_3_heart_rate 45
```
So it took two steps, but it worked. The questions are 1) Is there a way to do this in one step? and 2) Can it alternatively be done with one key (the "age" vector) that I can then simply replace as numeric data? | 2017/06/22 | [
"https://Stackoverflow.com/questions/44708248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8201326/"
] | if I get the question right, you could do that by first gathering everything together, and then "spreading" on mass and heart rate:
```
library(forcats)
library(dplyr)
mass_levs <- names(vertical.data)[grep("mass", names(vertical.data))]
hearth_levs <- names(vertical.data)[grep("heart", names(vertical.data))]
horizontal.data <- vertical.data %>%
gather(variable, value, -bird, factor_key = TRUE) %>%
mutate(day = stringr::str_sub(variable, 5,5)) %>%
mutate(variable = fct_collapse(variable,
"mass" = mass_levs,
"hearth_rate" = hearth_levs)) %>%
spread(variable, value)
```
, giving:
```
bird day mass hearth_rate
1 1 1 5 60
2 1 2 6 NA
3 1 3 NA 55
4 2 1 6 62
5 2 2 8 NA
6 2 3 NA 57
7 3 1 3 45
8 3 2 3 NA
9 3 3 NA 45
```
we can see how it works by going through the pipe one pass at a time.
First, we gather everyting on a long format:
```
horizontal.data <- vertical.data %>%
gather(variable, value, -bird, factor_key = TRUE)
bird variable value
1 1 day_1_mass 5
2 2 day_1_mass 6
3 3 day_1_mass 3
4 1 day_2_mass 6
5 2 day_2_mass 8
6 3 day_2_mass 3
7 1 day_1_heart_rate 60
8 2 day_1_heart_rate 62
9 3 day_1_heart_rate 45
10 1 day_3_heart_rate 55
11 2 day_3_heart_rate 57
12 3 day_3_heart_rate 45
```
then, if we want to keep a "proper" long table, as the OP suggested we have to create a single `key` variable. In this case, it makes sense to use the day (= age). To create the `day` variable, we can extract it from the character strings now in `variable`:
```
%>% mutate(day = stringr::str_sub(variable, 5,5))
```
here, str\_sub gets the substring in position 5, which is the day (note that if in the full dataset you have multiple-digits days, you'll have to tweak this a bit, probably by splitting on `_`):
```
bird variable value day
1 1 day_1_mass 5 1
2 2 day_1_mass 6 1
3 3 day_1_mass 3 1
4 1 day_2_mass 6 2
5 2 day_2_mass 8 2
6 3 day_2_mass 3 2
7 1 day_1_heart_rate 60 1
8 2 day_1_heart_rate 62 1
9 3 day_1_heart_rate 45 1
10 1 day_3_heart_rate 55 3
11 2 day_3_heart_rate 57 3
12 3 day_3_heart_rate 45 3
```
now, to finish we have to "spread " the table to have a `mass` and a `heart rate` column.
Here we have a problem, because currently there are 2 levels each corresponding to mass and hearth rate in the `variable` column. Therefore, applying `spread` on `variable` would give us again four columns.
To prevent that, we need to aggregate the four levels in `variable` into two levels. We can do that by using `forcats::fc_collapse`, by providing the association between the new level names and the "old" ones. Outside of a pipe, that would correspond to:
```
horizontal.data$variable <- fct_collapse(horizontal.data$variable,
mass = c("day_1_mass", "day_2_mass",
heart = c("day_1_hearth_rate", "day_3_heart_rate")
```
However, if you have many levels it is cumbersome to write them all. Therefore, I find beforehand the level names corresponding to the two "categories" using
```
mass_levs <- names(vertical.data)[grep("mass", names(vertical.data))]
hearth_levs <- names(vertical.data)[grep("heart", names(vertical.data))]
```
>
> mass\_levs
>
> [1] "day\_1\_mass" "day\_2\_mass"
>
> hearth\_levs
>
> [1] "day\_1\_heart\_rate" "day\_3\_heart\_rate"
>
>
>
therefore, the third line of the pipe can be shortened to:
```
%>% mutate(variable = fct_collapse(variable,
"mass" = mass_levs,
"hearth_rate" = hearth_levs))
```
, after which we have:
```
bird variable value day
1 1 mass 5 1
2 2 mass 6 1
3 3 mass 3 1
4 1 mass 6 2
5 2 mass 8 2
6 3 mass 3 2
7 1 hearth_rate 60 1
8 2 hearth_rate 62 1
9 3 hearth_rate 45 1
10 1 hearth_rate 55 3
11 2 hearth_rate 57 3
12 3 hearth_rate 45 3
```
, so that we are now in the condition to "spread" the table again according to `variable` using:
```
%>% spread(variable, value)
bird day mass hearth_rate
1 1 1 5 60
2 1 2 6 NA
3 1 3 NA 55
4 2 1 6 62
5 2 2 8 NA
6 2 3 NA 57
7 3 1 3 45
8 3 2 3 NA
9 3 3 NA 45
```
HTH | Though already answered, I have a different solution in which you save a list of the gather parameters you would like to run, and then run the gather\_() command for each set of parameters in the list.
```
# Create a list of gather parameters
# Format is key, value, columns_to_gather
gather.list <- list(c("age", "mass", "day_1_mass", "day_2_mass"),
c("age2", "heart_rate", "day_1_heart_rate", "day_3_heart_rate"))
# Run gather command for each list item
for(i in gather.list){
df <- gather_(df, key_col = i[1], value_col = i[2], gather_cols = c(i[3:length(i)]), factor_key = TRUE)
}
``` |
2,693,883 | I'd like to write a python function that has a dynamically created docstring. In essence for a function `func()` I want `func.__doc__` to be a descriptor that calls a custom `__get__` function create the docstring on request. Then `help(func)` should return the dynamically generated docstring.
The context here is to write a python package wrapping a large number of command line tools in an existing analysis package. Each tool becomes a similarly named module function (created via function factory and inserted into the module namespace), with the function documentation and interface arguments dynamically generated via the analysis package. | 2010/04/22 | [
"https://Stackoverflow.com/questions/2693883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/323631/"
] | You can't do what you're looking to do, in the way you want to do it.
From your description it seems like you could do something like this:
```
for tool in find_tools():
def __tool(*arg):
validate_args(tool, args)
return execute_tool(tool, args)
__tool.__name__ = tool.name
__tool.__doc__ = compile_docstring(tool)
setattr(module, tool.name, __tool)
```
i.e. create the documentation string dynamically up-front when you create the function.
Is the a reason why the docstring has to be dynamic from one call to `__doc__` to the next?
Assuming there is, you'll have to wrap your function up in a class, using `__call__` to trigger the action.
But even then you've got a problem. When help() is called to find the docstring, it is called on the class, not the instance, so this kind of thing:
```
class ToolWrapper(object):
def __init__(self, tool):
self.tool = tool
self.__name__ = tool.name
def _get_doc(self):
return compile_docstring(self.tool)
__doc__ = property(_get_doc)
def __call__(self, *args):
validate_args(args)
return execute_tool(tool, args)
```
won't work, because properties are instance, not class attributes. You can make the doc property work by having it on a metaclass, rather than the class itself
```
for tool in find_tools():
# Build a custom meta-class to provide __doc__.
class _ToolMetaclass(type):
def _get_doc(self):
return create_docstring(tool)
__doc__ = property(_get_doc)
# Build a callable class to wrap the tool.
class _ToolWrapper(object):
__metaclass__ = _ToolMetaclass
def _get_doc(self):
return create_docstring(tool)
__doc__ = property(_get_doc)
def __call__(self, *args):
validate_args(tool, args)
execute_tool(tool, args)
# Add the tool to the module.
setattr(module, tool.name, _ToolWrapper())
```
Now you can do
```
help(my_tool_name)
```
and get the custom docstring, or
```
my_tool_name.__doc__
```
for the same thing. The `__doc__` property is in the `_ToolWrapper` class is needed to trap the latter case. | *(Python 3 solution)*
You could make use of Python's duck typing to implement a dynamic string:
```
import time
def fn():
pass
class mydoc( str ):
def expandtabs( self, *args, **kwargs ):
return "this is a dynamic strting created on {}".format( time.asctime() ).expandtabs( *args, **kwargs )
fn.__doc__ = mydoc()
help( fn )
```
**Caveats:**
This assumes that the `help` function is calling `.expandtabs` to get the text from the `__doc__` object, which works in Python 3.7. A more robust solution would implement the other `str` methods in order to have our duck continue acting like a duck even if the `help` method changes. Also note that our `mydoc` class derives from `str`, this is because `help`, somewhat atypically, enforces strong typing by asserting `isinstance(thing.__doc__, str)`. Like all solutions this is a bit hacky, but whether this is a problem largely depends on the full project requirements. |
753,687 | I have a model that has an ordering field under its Meta class. When I perform a query and get back a QuerySet for the model it is in the order specified. However if I have instances of this model that are in a list and execute the sort method on the list the order is different from the one I want. Is there a way to sort a list of instances of a model such that the order is equal to that specified in the model definition? | 2009/04/15 | [
"https://Stackoverflow.com/questions/753687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/84952/"
] | Not automatically, but with a bit of work, yes. You need to define a comparator function (or **cmp** method on the model class) that can compare two model instances according to the relevant attribute. For instance:
```
class Dated(models.Model):
...
created = models.DateTimeField(default=datetime.now)
class Meta:
ordering = ('created',)
def __cmp__(self, other):
try:
return cmp(self.created, other.created)
except AttributeError:
return cmp(self.created, other)
``` | Building on Carl's answer, you could easily add the ability to use all the ordering fields and even detect the ones that are in reverse order.
```
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
birthday = date = models.DateField()
class Meta:
ordering = ['last_name', 'first_name']
def __cmp__(self, other):
for order in self._meta.ordering:
if order.startswith('-'):
order = order[1:]
mode = -1
else:
mode = 1
if hasattr(self, order) and hasattr(other, order):
result = mode * cmp(getattr(self, order), getattr(other, order))
if result: return result
return 0
``` |
54,823,669 | I get this JSON from my server. But to work with this JSON i need to Add Square Brackets to the MH Object. How can i do that. I tried `.map` but i dont get it to work for me. Is there any better solution. Or is `.map`to use there. If yes can you show me a hint how to do that. Or is there a better solution?
```
{
"PAD": [
{
"PADPS286": "Dampf",
"PADPS124": "Hans",
"PADPS60": "2018-05-01",
"PADPS143": "1",
"MH": {
"MHVSS1": [
{}
],
"MHDIRW214": 2017,
"MHDIRW215": 2018,
"birthdate": "2018-05-01",
"MHDIRW129 ": "0"
}
},
{
"PADPS286": "Snow",
"PADPS124": "Jon",
"PADPS60": "2077-05-01",
"PADPS143": "",
"MH": {
"MHVSS1": [
{}
],
"MHDIRW214": 4,
"MHDIRW215": 4,
"birthdate": "2077-05-01",
"MHDIRW129 ": "0"
}
}
]
}
```
I need this JSON with sqare Brackets arround teh MH Object
```
{
"PAD": [
{
"PADPS286": "Dampf",
"PADPS124": "Hans",
"PADPS60": "2018-05-01",
"PADPS143": "1",
"MH": [{
"MHVSS1": [
{}
],
"MHDIRW214": 2017,
"MHDIRW215": 2018,
"birthdate": "2018-05-01",
"MHDIRW129 ": "0"
}]
},
{
"PADPS286": "Snow",
"PADPS124": "Jon",
"PADPS60": "2077-05-01",
"PADPS143": "",
"MH": [{
"MHVSS1": [
{}
],
"MHDIRW214": 4,
"MHDIRW215": 4,
"birthdate": "2077-05-01",
"MHDIRW129 ": "0"
}
]}
]
}
``` | 2019/02/22 | [
"https://Stackoverflow.com/questions/54823669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10743267/"
] | It's not really "adding square brackets", it's wrapping the "MH" object in an array.
Anyway, here's a `.map` statement that will do it for you (without mutating the original data, hence the `Object.assign` shenanigans):
```
data.PAD = data.PAD.map((padObj) => Object.assign({}, padObj, {MH: [padObj.MH]}));
```
Basically, for each entry in the `PAD` array, we're merging three objects there:
* a fresh empty object `{}`
* the original `padObj` entry
* a small object that only has the MH element from the original `padObj` wrapped in an array.
The output is as expected:
```
{
"PAD": [
{
"PADPS286": "Dampf",
"PADPS124": "Hans",
"PADPS60": "2018-05-01",
"PADPS143": "1",
"MH": [
{
"MHVSS1": [{}],
"MHDIRW214": 2017,
"MHDIRW215": 2018,
"birthdate": "2018-05-01",
"MHDIRW129 ": "0"
}
]
},
{
"PADPS286": "Snow",
"PADPS124": "Jon",
"PADPS60": "2077-05-01",
"PADPS143": "",
"MH": [
{
"MHVSS1": [{}],
"MHDIRW214": 4,
"MHDIRW215": 4,
"birthdate": "2077-05-01",
"MHDIRW129 ": "0"
}
]
}
]
}
``` | If you want to add an array of strings (adding brackets only around the strings) then the above may work, however if you are trying to make the property an array what you need to do is cast the JSON Property as a list in the class as per:
```
public class AddressElements
implements Serializable
{
@JsonProperty("Street")
private List<Street> Street = new ArrayList<Street>();
@JsonProperty("HouseNumber")
private List<HouseNumber> HouseNumber = new ArrayList <HouseNumber>();
@JsonProperty("Locality")
private List<Locality> Locality = new ArrayList<Locality>();
@JsonProperty("AdministrativeDivision")
private List<AdministrativeDivision> AdministrativeDivision = new
ArrayList<AdministrativeDivision>();
@JsonProperty("PostalCode")
private List<PostalCode> PostalCode = new ArrayList<PostalCode>();
@JsonProperty("Country")
private String Country;
<getters and setters>
}
```
The resulting output (after initializing) would look like:
```
"body": {
"Login": "ssssss",
"Password": "eeeeee",
"UseTransactionPool": "test",
"JobToken": "",
"Request": {
"parameters": {
"Mode": "Certified"
},
"IO": {
"Inputs": {
"AddressElements": {
"Street": [
{
"Value": "Wilder Rd."
}
],
"HouseNumber": [
{
"Value": "123"
}
],
"Locality": [
{
"Value": "Newton"
}
],
"AdministrativeDivision": [
{
"Value": "NY"
}
],
"PostalCode": [
{
"Value": "12345"
}
],
"Country": "USA"
}
}
}
}
```
}
} |
30,855,864 | I am trying to build a springboot project I built with Spring Tools Suite. I get the following error when I execute `$mvn spring-boot:run`
```
Downloading: https://repo.maven.apache.org/maven2/org/codehaus/mojo/maven-metadata.xml
Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-metadata.xml
Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-metadata.xml (13 KB at 14.0 KB/sec)
Downloaded: https://repo.maven.apache.org/maven2/org/codehaus/mojo/maven-metadata.xml (20 KB at 21.8 KB/sec)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.032 s
[INFO] Finished at: 2015-06-15T17:46:50-04:00
[INFO] Final Memory: 11M/123M
[INFO] ------------------------------------------------------------------------
[ERROR] No plugin found for prefix 'spring-boot' in the current project and in the plugin groups [org.apache.maven.plugins, org.codehaus.mojo] available from the repositories [local (/Users/admin/.m2/repository), central (https://repo.maven.apache.org/maven2)] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/NoPluginFoundForPrefixException`
```
Heres my pom.xml plugin
```
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<arguments>
<argument>--spring.profiles.active=dev</argument>
</arguments>
</configuration>
</plugin>
</plugins>
</build>
```
I tried the jhipster plugin above and no change in the error. | 2015/06/15 | [
"https://Stackoverflow.com/questions/30855864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5013168/"
] | Typos are a possible reason for this error.
Be sure to check you wrote `spring-boot` and not e.g. `springboot` or `sprint-boot` or `springbok` or whatever.
Also check the ordering : use `spring-boot:run` and not `run:spring-boot`. | In my case I got this error after updating my spring boot in pom.xml and running it in Eclipse.
The source of the error is that the run configuration was set to offline, thus it couldn't download plugins on run. |
13,603,215 | How do I use a loop to name variables? For example, if I wanted to have a variable `double_1 = 2`, `double_2 = 4` all the the way to `double_12 = 24`, how would I write it?
I get the feeling it would be something like this:
```
for x in range(1, 13):
double_x = x * 2
# I want the x in double_x to count up, e.g double_1, double_2, double_3
```
Obviously, this doesn't work, but what would be the correct syntax for implementing the looped number into the variable name? I haven't coded for a while, but I do remember there was a way to do this. | 2012/11/28 | [
"https://Stackoverflow.com/questions/13603215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1859481/"
] | expanding my comment: "use a dict. it is exactly why they were created"
using defaultdict:
```
>>> from collections import defaultdict
>>> d = defaultdict(int)
```
using normal dict:
```
>>> d = {}
```
the rest:
```
>>> for x in range(1, 13):
d['double_%02d' % x] = x * 2
>>> for key, value in sorted(d.items()):
print key, value
double_01 2
double_02 4
double_03 6
double_04 8
double_05 10
double_06 12
double_07 14
double_08 16
double_09 18
double_10 20
double_11 22
double_12 24
``` | As already mentioned, you should use a dict. Here's a nice easy way to create one that meets your requirements.
```
>>> {k:k*2 for k in range(1,13)}
{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18, 10: 20, 11: 22, 12: 24}
``` |
198,182 | I am creating an application that visually displays world regions, e.g. to place markers within an administrative region.
Does a dataset exist with geometrical or geographical (long/lat) descriptions of the world's current country borders (and possibly other administrative divisions)? Ideally the dataset would be in a format that I could easily generate border images of the size that I require. | 2013/05/15 | [
"https://softwareengineering.stackexchange.com/questions/198182",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/65587/"
] | <http://gadm.org/> seems to have exactly what you want (and more).
>
> ### GADM database of Global Administrative Areas
>
>
> GADM is a spatial database of the location of the world's administrative areas (or adminstrative boundaries) for use in GIS and similar software. Administrative areas in this database are countries and lower level subdivisions such as provinces, departments, bibhag, bundeslander, daerah istimewa, fivondronana, krong, landsvæðun, opština, sous-préfectures, counties, and thana. GADM describes where these administrative areas are (the "spatial features"), and for each area it provides some attributes, such as the name and variant names...
>
>
> | Just earned the "popular question" bagde for this question. Therefore, maybe for someone helps the next.
I'm currently using free 1:110 mil. shapefiles from <http://www.naturalearthdata.com>.
From their site:
>
> Natural Earth was built through a collaboration of many volunteers and
> is supported by NACIS (North American Cartographic Information
> Society), and is free for use in any type of project (see our Terms of
> Use page for more information).
>
>
>
For my needs (drawing an simple word map with an perl script) it is the simplest possible way. |
14,421,846 | I'm working on a search feature to search for model numbers and I'm trying to get MySQL to show me results similar to what I'm asking for but LIKE %$var% doesn't do it.
Example (we'll call table, "tbl\_models"):
```
id model
+-------+--------------------+
| 1 | DV6233SE |
| 2 | Studio 1440 |
| 3 | C762NR |
+-------+--------------------+
```
When searching using a search box I'm currently using:
```
SELECT id, model FROM tbl_models WHERE model LIKE %$var% ORDER BY id DESC
```
If I search for "C7" it'll return "C762NR" which is fine, but say I were to search for "C760" or "C700" or a typo of "C726NR"? Is there a way in MySQL (or PHP, JS, jQuery) that I can expand the limit of what results are returned to include different variations or close matches?
I'm not looking for someone to write it for me either, just a push in the right direction would be very helpful! | 2013/01/20 | [
"https://Stackoverflow.com/questions/14421846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1992593/"
] | Based on the answer provided by SaurabhV (thanks again!), I was able to create a function which takes a string and replaces each letter with an underscore in sequence. I hope this can help someone else down the road also!
```
function get_combination($string) {
// Pa = Pass, Pos = Character Position, Len = String Length
$str_arr = array($string);
$Len = strlen($string);
for ($Pa=0;$Pa<$Len;$Pa++) {
for($Pos=1;($Pos+$Pa)<=$Len;$Pos++) {
if($Pos+$Pa == $Len && $Pos<$Pa) {
array_push($str_arr, substr_replace($string, str_repeat('_', $Pos), $Pa, 1));
} else if($Pos+$Pa == $Len && $Pos>$Pa) {
// End of String
} else if($Pos == $Len || ($Len > 2 && $Pos == ($Len-1))) {
// Do nothing - $Pos is too high
} else if($Pos > $Len/2 && $Len > 6) {
array_push($str_arr, substr_replace($string, str_repeat('_', $Pos-4), $Pa, $Pos-4));
} else {
array_push($str_arr, substr_replace($string, str_repeat('_', $Pos), $Pa, $Pos));
}
}
}
return $str_arr;
}
```
Example:
```
$string = get_combination('dv6000');
```
Returns:
```
Array ( [0] => dv6000 [1] => _v6000 [2] => __6000 [3] => ___000 [4] => ____00 [5] => d_6000 [6] => d__000 [7] => d___00 [8] => d____0 [9] => dv_000 [10] => dv__00 [11] => dv___0 [12] => dv6_00 [13] => dv6__0 [14] => dv6___ [15] => dv60_0 [16] => dv60__0 [17] => dv600_ )
```
Now, using MySQLi and a foreach loop I'm able to search the database against the array for similar results to what was asked. As you can see in the example, "dv6000" was the string asked but in tbl\_models (see OP) there is no dv6000. Once the database hits index 14 (dv6\_\_\_) it will find the correct entry:
```
SELECT model_number FROM tbl_models WHERE model_number LIKE %string[14]%
```
It's messy, probably not very efficient, but it works. If anyone can elaborate or maybe help me neaten up this code to make it more simplified, if possible, I'd appreciate it! | You can use `PHP` function as described above,or maybe `SOUNDEX` can help you. Look at [this](http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_soundex). |
17,084,708 | In an example of android code given in a book regarding action bar, the sample given is as the following:
```
MenuItem menu1 = menu.add(0, 0, 0, "Item 1");
{
menu1.setIcon(R.drawable.ic_launcher);
menu1.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
}
```
How is using curly braces after a semi-colon possible? There is clearly some concept that I do not understand right here. | 2013/06/13 | [
"https://Stackoverflow.com/questions/17084708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2277257/"
] | They are completely optional in this case and have no side-effect at all. In your example it sole serves to purpose of making the code more readable by intending the property assignment which belong to the control. You could as well do it without the braces. But if you'd use a tool to reformat your code, the indentation is likely gone.
However, if you have a Method and you put {} in there, you can create a new variable scope:
```
void someMethod() {
{
int x = 1;
}
// no x defined here
{
// no x here, so we may define a new one
string x = "Hello";
}
}
```
You can start a new scope anywhere in a Method where you can start a statement (a variable declaration, a method call, a loop etc.)
Note: When you have for example an if-statement you also create a new variable scope with that braces.
```
void someMethod() {
if (someThing) {
int x = 1;
}
// no x defined here
if (somethingElse) {
// no x here, so we may define a new one
string x = "Hello";
}
}
```
The same is true for while, for, try, catch and so on. If you think about it even the braces of a method body work in that way: they create a new scope, which is a "layer" on top of the class-scope. | It's called anonymous code blocks, they are supposed to `restrict the variable scope`. |
258,959 | Many times I heard people say that "beat up someone". But on the internet, I can only found this definition which does not seem matching with the word beat up in the above sentence
"beat-up:`(of a thing) worn out by overuse; in a state of disrepair.`" <https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=what+is+beat+up>
So, **what does the preposition "up" mean in "He got beaten up by other kids in school"?**
Note:
"beat" means "strike repeatedly" & "beat up" also means "strike repeatedly". So, "up" should have a certain meaning and what is the difference between "beat" and "beat up"? | 2015/07/13 | [
"https://english.stackexchange.com/questions/258959",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/105551/"
] | The particle "up" in "beat up" is a *telicity marker*.
[***Telicity***](https://en.wikipedia.org/wiki/Telicity) is a property of the verb that can be simply rendered as *completed-ness* of the action expressed by it.
The book [*Particle verbs in English*](http://www.amazon.co.uk/gp/search?index=books&linkCode=qs&keywords=9789027227805) by Nicole Dehé quotes (p. 61) L.J.Brinton (1985):
>
> [Particles] may add the concept of a goal or an endpoint to durative situations which otherwise have no necessary terminus. That is, the particles may affect the intrinsic temporal situation and hence alter its [aktionsart](https://en.wikipedia.org/wiki/Lexical_aspect) from **atelic** to **telic**.
>
>
>
(emphasis mine)
Thus, one can say *She ate the meal for hours* (atelic), but not \**she ate up the meal for hours* (here the telic marker "up" conflicts with the imperfective timespan "for hours"). | Aside from the already present answers (and expanding on StoneyB's answer) this could originate from the fact that English is a Germanic language. There are many similarities between English and German and one of them is what in German is known as a "separable verb".
First you need a "separable prefix". An example is "an", a preposition meaning "at" or "on". In other contexts it can mean "on", such as describing a light.
You then take a verb (such as "machen", or "to do").
Merging the two, you get "anmachen" meaning "to turn on"
Similar to how there isn't a German verb for "turn on (a light)" but instead there is a modified version of an existing verb, there isn't a *single* English verb for "to give up". You can think of this as being formed from "up" and the verb "to give", both of which have meanings completely irrelevant to the verb they form together.
I think you can say that "to beat up" is another one of these verbs. "To beat" means "to defeat" or "to strike" but with by adding this particle you can change the meaning to something *closer* (but not *exactly*) to "to bully" but not nearly as violent as "to beat".
The only way to know what these verbs with particles mean is by remembering them as you would remember any other word. |
18,104,600 | I can set action on click for html button. But I need to set action only on FIRST click. Is there any way to do this? The button is radio in form. Some javascript maybe?
What's important - the radio button still might be changed. But action has to be done only once.
This doesn't work
```
function myfunction(i){
oForm = document.forms["myform"];
if(oForm.elements["field"+i].checked)
alert("action done earlier");
else
action
}
``` | 2013/08/07 | [
"https://Stackoverflow.com/questions/18104600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2125442/"
] | The cleanest solution is probably to use [removeEventListener](https://developer.mozilla.org/fr/docs/DOM/element.removeEventListener) to... remove the event listener :
```
var myButton = document.getElementById('someId');
var handler = function(){
// doSomething
myButton.removeEventListener('click',handler);
}
myButton.addEventListener('click', handler);
```
(to make it cleaner, you could wrap this in an IIFE, as in the example below)
[Demonstration](http://jsbin.com/ayufat/2/) | To resolve this problem I have used jQuery.on as well as jQuery.off - see my code on jsfiddle!
```
$(document).ready(function() {
var button = $('#my-button');
function onClick() {
alert('clicked');
button.off('click', onClick);
};
button.on('click', onClick);
});
```
<http://jsfiddle.net/VxRyn/> |
16,869,043 | Here's a C/C++ for loop:
```
int i;
for (i = myVar; i != someCondition(); i++)
doSomething();
// i is now myVar plus the number of iterations until someCondition
```
I recently had to use a loop like this. I needed to keep the value of `i` because I wanted to know what `i` was when the return value of `someCondition()` became true. And the start value of `i` was `myVar` which had no further reason of existing. So what *wanted* to do was:
```
for (myVar; myVar != someCondition(); myVar++)
doSomething();
// myVar is now myVar + the number of iterations.
```
This made a lot more sense to me. I didn't see why I had to use a whole new variable when `myVar` was just what I needed. But this is not valid code. Is there a way around creating a whole new variable for this situation? | 2013/06/01 | [
"https://Stackoverflow.com/questions/16869043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/313273/"
] | What you need is,
```
for( ; myVar != someCondition(); myVar++)
doSomething();
```
But you statement about the following loop being incorrect is wrong,
```
for (myVar; myVar != someCondition(); myVar++)
doSomething();
```
The above code will also work fine in C. | I feel that a `while` loop more closely resembles your intentions. Indeed, you are doing something `while` `someCondition()` is `true`, and increasing `myVar` is a side effect.
```
while(myvar != someCondition()) {
doSomething();
myVar++;
}
```
To be clear: the statements are equivalent. I am just advocating for what I believe to be more idiomatic code.
You could even use a `do`/`while` loop, but it somewhat does not feel idiomatic to me. Below you will find three examples; they all do the same, but *feel* different. Take your pick!
```
#include<iostream>
int someCondition() {
return 10;
}
void doSomething(int myVar) {
std::cout<<"... I'm doing something with myVar = "<<myVar<<std::endl;
}
int using_for() {
int myVar = 7;
for( ; myVar!=someCondition(); myVar++) {
doSomething(myVar);
}
return myVar;
}
int using_while() {
int myVar = 7;
while(myVar != someCondition()) {
doSomething(myVar);
myVar++;
}
return myVar;
}
int using_do() {
int myVar = 7;
do {
doSomething(myVar);
} while(++myVar != someCondition());
return myVar;
}
int main() {
std::cout<<"using for: "<<using_for()<<std::endl;
std::cout<<"using while: "<<using_while()<<std::endl;
std::cout<<"using do/while: "<<using_do()<<std::endl;
}
```
Output:
```
... I'm doing something with myVar = 7
... I'm doing something with myVar = 8
... I'm doing something with myVar = 9
using for: 10
... I'm doing something with myVar = 7
... I'm doing something with myVar = 8
... I'm doing something with myVar = 9
using while: 10
... I'm doing something with myVar = 7
... I'm doing something with myVar = 8
... I'm doing something with myVar = 9
using do/while: 10
``` |
50,865,661 | I'm using Stripe Checkout in my React App. Somehow I'm not passing the properties to my onToken function correctly as I'm getting not defined errors.
I eventually need to send a bunch of props, but for now just trying to get it to work correctly.
```
import axios from 'axios'
import React from 'react'
import StripeCheckout from 'react-stripe-checkout';
const PAYMENT_SERVER_URL = '3RD_PARTY_SERVER';
const CURRENCY = 'USD';
export default class Stripe25 extends React.Component {
onToken = (token) => {
axios.post(PAYMENT_SERVER_URL,
{
description,
source: token.id,
currency: CURRENCY,
amount: amount
})
.then(successPayment)
.catch(errorPayment);
}
render() {
return (
<StripeCheckout
token={this.onToken}
stripeKey="STRIPE_PUBLIC_KEY"
name=""
description=""
image=""
panelLabel="Donate"
amount={2500} // cents
currency="USD"
locale="auto"
zipCode={false}
billingAddress={true}
>
<button className="btn btn-primary">
$25
</button>
</StripeCheckout>
)
}
}
``` | 2018/06/14 | [
"https://Stackoverflow.com/questions/50865661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5153877/"
] | `isset()` is a function in PHP that will return true if the variable, in this case, $var has been assigned a value. If the variable has been created but nothing assigned, has the value of null or undefined, it will return false. basically, `isset($var)` says is this variable safe to use or not.
Update
======
To explain the differences between a `NULL` value and an `undefined` the following code was provided by Jonathan Kuhn in the commits above.
```
<?php
//test 1 is defined, but has a value of null. isset will return false, use causes no error.
$test1 = null;
var_dump($test1);
var_dump(isset($test1));
echo "\n----------\n\n";
//test2 is defined with a string value. isset will return true
$test2 = "test";
var_dump($test2);
var_dump(isset($test2));
echo "\n----------\n\n";
//test3 is not defined, isset returns false and use causes error.
var_dump($test3);
var_dump(isset($test3));
```
Which will output:
```
NULL
bool(false)
----------
string(4) "test"
bool(true)
----------
Notice: Undefined variable: test3 in /in/Nmk0t on line 17
NULL
bool(false)
``` | Basically a variable that is not declared, not assigned, or NULL is not set.
To prove the comparison table you can test it with `isset()`
```
if (isset($var)) {
echo "it is set.";
}
``` |
90,112 | Is Double-Encoding still a security vulnerability on IIS6 as it was in IIS4/5? | 2009/12/02 | [
"https://serverfault.com/questions/90112",
"https://serverfault.com",
"https://serverfault.com/users/22918/"
] | The answer is yes and no, Strictly speaking, on the MS-API level, The issue has been rectified. Of course, if your application deals with encoding and requests paths that may not be contingent upon the URI provided - You're vulnerable and you're going to want to provide filtering AFTER any applicable encoding has been done. | If you are talking about [this kind of web application attack](http://www.owasp.org/index.php/Double_Encoding), then this is really most often due to a problem in the web application's code and not the web server behaviour. This particular issue is a problem on any and all web servers. |
1,040,547 | What is the range of $$\large\frac{1}{e^{x^2}+3}$$
I know that the answer is $\dfrac{1}{4}\ge h(x)\gt0$, but how do I show it
 | 2014/11/27 | [
"https://math.stackexchange.com/questions/1040547",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/173503/"
] | * $x^2$ has a range of $[0,\infty)$.
* So $e^{x^2}$ has a range of $[1,\infty)$
(knowing that $\exp$ is increasing tells us this).
* So $e^{x^2}+3$ has a range of $[4,\infty)$.
* So $\frac{1}{e^{x^2}+3}$ has a range of $(0,1/4]$
(knowing that the reciprocal function is decreasing and continuous on $[4,\infty)$ tells us this). | $e^{x^2}\geq1 $ for $x\geq0$ . So, $e^{x^2} + 3 \geq 4$. If $y \geq4 $, then $1/y \leq 1/4$. |
19,441,921 | I'm writing a nodejs cli utility (NPM module intended to be installed globally) that will need to store some user-supplied values. What is the best way to store these values on a system?
For example, should I create my own config file under say: `/etc/{my-utility-name}/conf.json` and have this directory+file initialized in my `install` script
(<https://npmjs.org/doc/misc/npm-scripts.html>) | 2013/10/18 | [
"https://Stackoverflow.com/questions/19441921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/480807/"
] | I found that the yeoman project has a package for this called [configstore](https://github.com/yeoman/configstore). I tried it out and the API is incredibly simple and easy to use and abstracts out any need to worry about OS compatibility.
Getting and setting configs is as easy as:
```js
const Configstore = require('configstore')
const config = Configstore(packageName, defaults)
config.set(key, value)
config.get(key)
```
Yeoman is a large well tested project so the fact that they built and use this in their project should indicate that this is a safe stable package to use in your own project. | I wrote the **cli-config** API to manage NodeJS app configuration including:
* Package defaults
* Local user config
* Command line options
* App overrides
Visit <https://github.com/tohagan/cli-config> for more details.
### Example 1:
Combines configuration options from package file `defaults.config` then `~/.<appname>.config` then command line options then force the `debug` option to be `true`. Uses a shallow merge so only the top level properties are merged.
```
var config = require('../cli-config')
.getConfig({dirname: __dirname, override: {debug: true}});
```
### Example 2:
Deep merge nested configuration settings from package `defaults.config` then `./config.json` then command line options. If `./config.json` does not exist, clone a copy from `defaults.config` so the user can use it to override `defaults.config` in the future.
```
var config = require('../cli-config').getConfig({
dirname: __dirname,
clone: true,
configFile: './config.json',
merge: 'deep'
});
```
### Example 3:
The command line parser returns an object that can be used to override the system settings or user settings options. You can configure this parser using the **cli** option. Refer to [minimist](https://github.com/substack/minimist) for more details about command line parsing options.
```
var config = require('../cli-config').getConfig({
dirname: __dirname,
cli: {
boolean: {
'd': 'debug',
'v': 'verbose'
}
}
});
```
Sets the config.debug and config.verbose options to true.
```
$ myapp -d -v
``` |
629 | On my Ubuntu UNR install, for some reason, I'm only able to switch the input language if I press `Shift` and then `Alt`. This is quite the opposite of what usually works -- on Windows and other Ubuntu/other Linux systems -- where I press `Alt` and then add `Shift`.
Anyone know why this is? | 2010/08/01 | [
"https://askubuntu.com/questions/629",
"https://askubuntu.com",
"https://askubuntu.com/users/199/"
] | Unfortunately, there are a number of long-standing bugs in handling switching between keyboard layout. I, for one, had problem with those in 9.10. For me they were fixed in 10.04. (FYI, [this](https://bugs.edge.launchpad.net/gdm/+bug/460328) is the bug that bit me.) Perhaps and upgrade to 10.04, which is a stable one after all, might fix this. Alternatively you might use a different key - I use the menu key, which has no use whatever for me. | In my case it seems to be doing this whenever I set any `Shift` keys to toggle or cancel Caps Lock under the `Miscellaneous compatibility options` in the Keyboard Preferences (Keyboard Layout Options). |
1,893,780 | I have e table like this :
```
A B
1 1.5
1 1.5
2 2.3
2 2.3
2 2.3
3 1.5
3 1.5
```
how could i make the sum of column B, grouped by in 1.5, 2.3 and 1.5.
in few words, I want to group by first and then make the sum(), but in one select.
in this table, if you group by A column the result is:
```
A B
1 1.5
2 2.3
3 1.5
```
now i want to sum() the B column. | 2009/12/12 | [
"https://Stackoverflow.com/questions/1893780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/98655/"
] | ```
select A, sum(B) from table
group by A
```
Should do the trick. | ```
SELECT SUM(B)
FROM (SELECT DISTINCT A, B FROM tbl) PLEASE
``` |
52,076,149 | I was trying to link my MySQL table to my java project and I wanted to reciprocate my MySQL table on my java frame. I have written this code so far.
```
try{
Class.forName(cn);
Connection con = (Connection) DriverManager.getConnection(url, u, p);
Statement stmt = (Statement) con.createStatement();
String q = "select eno,name,salary,dept,(salary*12) as spa from employee;";
ResultSet rs = stmt.executeQuery(q);
ResultSetMetaData rsmd = rs.getMetaData();
int cc=rsmd.getColumnCount();
Vector columns = new Vector(cc);
Vector data = new Vector();
Vector row;
while(rs.next()) {
row=new Vector(cc);
for (int i = 1; i <= cc; i++) {
row.add(rs.getString(i));
}
data.add(row);
}
JTable table=new JTable(data,columns);
DefaultTableModel m = new DefaultTableModel(data, columns);
jTable1.setModel(m);
} catch (Exception e){
System.out.println(e.getMessage());
}
```
I have used vectors and now I'm unable to make to how to define a model for my table 'jTable1'.[MySQL table and its description](https://i.stack.imgur.com/iQEZD.jpg)
Any help is appreciated. | 2018/08/29 | [
"https://Stackoverflow.com/questions/52076149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10285186/"
] | I think if you are learning Java programming with Swing and a database here are couple of ideas:
1. Try to do the application in stages.
2. To start with code the GUI portion only with some dummy data (not the database data; you are not connected to the database yet).
3. At this point you are able to display a window (a `JFrame`) and a `JTable` in it with some dummy data (created within the program, for example).
4. Now, code the database aspect of the application.
5. Get the data from the database table and verify you are able to read and print it to the console in your IDE.
6. Once successful, substitute the `JTable`'s dummy data with db data.
7. You should be having the application showing a window with a `JTable` and queried database data in it.
Here is the link to build `JTable` using Swing GUI at [Oracle's Java tutorials](https://docs.oracle.com/javase/tutorial/uiswing/components/table.html). | I can offer a few suggestions to improve your code:
1. Don't create database connections in method scope. Use a pool to manage them and pass the connection into the object that requires it.
2. Make your SQL a static string.
3. What is that stored procedure doing for you? Straight, vanilla SQL should be enough to query a table.
4. You should know what your stored procedure is returning. Why use ResultSetMetaData?
5. Per camickr's suggestion, continue with Vector b/c you're using Swing.
6. You don't close any resources in method scope.
7. Don't print the exception message to the console. Log the entire stack trace; it'll have more information than the mere message. |
42,688,211 | \*\*\*\*Css File Cannot connect with the below\*\*\*\*
it is in the flow of
root
/index.html
/server.js
/css/style.css
**My /server.js Code**
```js
var http = require('http'),
fs = require('fs');
fs.readFile('./index.html', function (err, html) {
if (err) {
throw err;
}
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}).listen(8000);
});
```
```css
**CSS css/style.css**
.raj{
background-color: red;
}
```
```html
**html /index.html**
<html>
<head>
<title></title>
<!-- <link rel="stylesheet" type="text/css" href="/css/style.css" /> -->
<link rel="stylesheet" type="text/css" href="/css/style.css" />
</head>
<body>
<span class="raj">
asldfasd <br/>
fasd <br/>
fas <br/>
dfa <br/>
sdf <br/>
sadf <br/>
asd <br/>
fas <br/>
df <br/>
sad <br/>
</span>
</body>
</html>
```
css cannot connect with this above html file | 2017/03/09 | [
"https://Stackoverflow.com/questions/42688211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7682440/"
] | The problem is caused by your web server not checking the path of the URL request but is rather going to return the same HTML file no mater the path or file extension you use. To get around this shortcoming of the node http module I would recommend utilizing a framework such as express.js
Or if you only want to serve static files I would recommend you use http-server, you can install it using the following command:
```
npm install http-server -g
```
After installation you can navigate to the folder you store your html and CSS files in then run your webserver using the following command:
```
http-server
```
You can read more about the module [here](https://www.npmjs.com/package/http-server) | Just Replace this line of code :
```
<link rel="stylesheet" type="text/css" href="/css/style.css" />
```
with this,
```
<link rel="stylesheet" type="text/css" href="./css/style.css" />
``` |
312,530 | [Cisco antenna explanation](http://www.cisco.com/c/en/us/support/docs/wireless-mobility/wireless-lan-wlan/82068-omni-vs-direct.html)
Here it says that antenna is passive device which doesn't offer any added power to the signal. But at same time it says that antenna is responsible for increasing the amount of energy to a radio frequency (RF) signal.
So I don't get aren't they opposite things? How can it be a passive device and increase the amount of energy to a RF signal? | 2017/06/22 | [
"https://electronics.stackexchange.com/questions/312530",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/152875/"
] | An antenna is a passive device.
The gain of an antenna refers to its directivity times efficiency compared to an isotropic antenna.
An isotropic antenna is a theoretical antenna that radiates equally in all directions. If this antenna were encapsulated in the center of a sphere, it would illuminate all parts of the sphere equally and uniformly.
All other real world antennas do not illuminate a sphere equally. Some areas of the surface have more power than other areas. As a result of the antenna favoring some areas of the surface compared to others, the antenna is said to have gain when compared to an evenly illuminated sphere. The area or direction with the most power is considered to be the major lobe of the radiation.
While radiation has been used in this description, due to the theory of reciprocity, it applies equally to a receiving antenna.
You can also think of this in the context of a flashlight/torch bulb. If you illuminate the bulb without its reflector, it does not appear to be very bright. But if you now place a very narrow beam reflector behind it, you can shine it at someone's eyes with nearly blinding results. The energy emitted by the bulb has not changed, but to the observer it is as if the bulb is many times brighter. This is analogous to antenna gain. | It is passive, in that there are no electronics in it and it requires no power supply.
However the shape and size of the antenna affects the shape and size of the radiation pattern that is emitted from it.
At the heart all antennae are just a "dipole" - that is, two conductors heading away from each other (or a monopole and the ground (the second pole) which is what you see with a traditional FM antenna). This dipole creates a radiation pattern with a polarisation (depending on the angle of the dipole). Different lengths create different radiation patterns (often pictured as doughnuts around the antenna). Some lengths cause the current waveform inside the conductor to fold back on itself (1/4 wavelength) doubling the apparent current at any one point in the conductor, thus increasing the instantaneous power but at the cost of "height" of the radiation pattern.
Then many antennae also have external portions that shape that radiated energy into a more usable pattern. For instance a parabolic dish will form the radiated energy into more of a beam. A Yagi array (TV antenna) makes it more like the shape of a flame. There are many arrangements for different situations.
But basically:
* The length of the dipole creates the base radiation pattern by shaping the wave in the conductor
* The external elements shape that radiation pattern so it goes where you want.
Since there is a fixed and finite amount of energy in that radiation pattern you can now see that shaping it is merely a case of moving energy from one portion to another. You get less power behind a Yagi array than you do in front. Such antennae are then said to be *directional* in that they work better in one direction. Without those external shaping elements you get an *omni-directional* antenna (which is actually a misnomer, since it's only really in 2 dimensions that it's "omni").
[](https://i.stack.imgur.com/ld3Bb.png)
* Half wave radiation pattern
[](https://i.stack.imgur.com/eJjsz.jpg)
* Quarter wave radiation pattern
[](https://i.stack.imgur.com/Ag8X4.jpg)
* Yagi array radiation pattern |
31,370,624 | I have looked up and there are a few threads similar to this but I cant make any of them work for me so I have to ask my code at the moment is.It is different
```
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="stylespacewars.css" />
<script src="jsspacewars.js"></script>
<script src="jquery.js"></script>
<img class="Ship" src="Ally ship.gif" alt="HTML5 Icon" >
<img class="EnemieBasic" src="Basic enemie.gif" alt="HTML5 Icon" >
<img class="Core" src="Corelevel1.gif" alt="HTML5 Icon" >
<img class="Shot" src="Shot.gif" alt="HTML5 Icon" >
</head>
<body>
</body>
</html>
```
Then i have another part of the code in css
```
html, body {
width: 100%;
height: 100%;
background-color: black; }
IMG.Core {
display: block;
margin-left: auto;
margin-right: auto }
IMG.Ship {
position:absolute;}
```
Then the final part is in Javascript
```
$(document).mousemove(function(e){
$("Ship").css({left:e.pageX, top:e.pageY});
});
```
This does not allow the image ship to follow the mouse pointer can anyone help correct this please. | 2015/07/12 | [
"https://Stackoverflow.com/questions/31370624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5108449/"
] | Your HTML and JS is a bit off. `img` tags go in the `body`. And for the jQuery you need to use `.` when referencing by class name.
<http://jsfiddle.net/imthenachoman/1h3vsa3w/1/>
The HTML:
```
<body>
<img class="Ship" src="Ally ship.gif" alt="HTML5 Icon" />
<img class="EnemieBasic" src="Basic enemie.gif" alt="HTML5 Icon" />
<img class="Core" src="Corelevel1.gif" alt="HTML5 Icon" />
<img class="Shot" src="Shot.gif" alt="HTML5 Icon" />
</body>
```
The JavaScript:
```
$(document).mousemove(function (e)
{
$(".Ship").css({ left: e.pageX, top: e.pageY });
});
``` | Like this?
<http://jsfiddle.net/JPvya/1275/>
You weren't targeting the class by using the `.selector` method. Furthermore, you had the `img` in the `head` of your document. It needed to be part of the `body`. |
233,399 | I'm wondering if that is possible, so that I can use some X11 window manager for everything. | 2016/04/01 | [
"https://apple.stackexchange.com/questions/233399",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/4304/"
] | No. Native OS X apps don't call down to X11 protocol and no one (Apple or other) has implemented any sort of shim/translation layer/conversion tool to port over the API.
It would surely involve slowdown, reduced acceleration, possibly loss of fidelity and loss of functionality. | You could have an alternate login to X11, but use a non- Apple X11 VNC client to call Apple screen sharing. |
24,232,064 | Code below is me trying to do just that. It returns all rows but only like DEFAULT VALUES (0, empty string, empty date...) and "Allow Nulls" is false for all columns in my db table. I am truly stuck. I am still in process of learning c#, so if someone could please explain to me WHAT am I doing wrong here? Is there a better way to do this?
```
public List<XNarudzbe> GetXNarudzbe()
{
var listXnar = new List<XNarudzbe>();
using (SqlConnection NConnection = new SqlConnection(Params.ConnectionStr))
{
NConnection.Open();
using (var cmd = new SqlCommand("SELECT * FROM [dbo].[XDATA_NARUDZBE]", NConnection))
{
SqlDataReader reader = cmd.ExecuteReader();
int id = reader.GetOrdinal("ID");
int dt_get = reader.GetOrdinal("DT_GET");
int rn_datum = reader.GetOrdinal("RN_DATUM");
int datum = reader.GetOrdinal("DATUM");
int dt_stamp = reader.GetOrdinal("DT_STAMP");
int art_id = reader.GetOrdinal("ART_ID");
int cijena_k = reader.GetOrdinal("CIJENA_K");
int cijena_mp = reader.GetOrdinal("CIJENA_MP");
int cijena_vp = reader.GetOrdinal("CIJENA_VP");
int faktura = reader.GetOrdinal("FAKTURA");
int isporuceno = reader.GetOrdinal("ISPORUCENO");
int iznos_k = reader.GetOrdinal("IZNOS_K");
int iznos_p = reader.GetOrdinal("IZNOS_P");
int naruceno = reader.GetOrdinal("NARUCENO");
int narudzba = reader.GetOrdinal("NARUDZBA");
int otpremnica = reader.GetOrdinal("OTPREMNICA");
int pdv = reader.GetOrdinal("PDV");
int povrat_k = reader.GetOrdinal("POVRAT_K");
int povrat_p = reader.GetOrdinal("POVRAT_P");
int pp_id = reader.GetOrdinal("PP_ID");
int preporuka = reader.GetOrdinal("PREPORUKA");
int rabat = reader.GetOrdinal("RABAT");
int rn_id = reader.GetOrdinal("RN_ID");
int skart = reader.GetOrdinal("SKART");
int user_id = reader.GetOrdinal("USER_ID");
int var_n = reader.GetOrdinal("VAR_N");
int var_v = reader.GetOrdinal("VAR_V");
int veleprodaja = reader.GetOrdinal("VELEPRODAJA");
int vraceno = reader.GetOrdinal("VRACENO");
int isporuka_id = reader.GetOrdinal("ISPORUKA_ID");
int otpremljeno = reader.GetOrdinal("OTPREMLJENO");
int promjena = reader.GetOrdinal("PROMJENA");
int rj_id = reader.GetOrdinal("RJ_ID");
int zakljucano = reader.GetOrdinal("ZAKLJUCANO");
if (reader.HasRows)
{
while (reader.Read())
{
var recXNar = new XNarudzbe();
recXNar.id = reader["ID"] as decimal? ?? 0M; // reader.GetDecimal(id);
recXNar.dt_get = reader.GetDateTime(dt_get);
recXNar.rn_datum = reader.GetDateTime(rn_datum);
recXNar.datum = reader.GetDateTime(datum);
recXNar.dt_stamp = reader.GetDateTime(dt_stamp);
recXNar.art_id = reader.GetDecimal(art_id);
recXNar.cijena_k = reader.GetDecimal(cijena_k);
recXNar.cijena_mp = reader.GetDecimal(cijena_mp);
recXNar.cijena_vp = reader.GetDecimal(cijena_vp);
recXNar.faktura = reader.GetDecimal(faktura);
recXNar.isporuceno = reader.GetDecimal(isporuceno);
recXNar.iznos_k = reader.GetDecimal(iznos_k);
recXNar.iznos_p = reader.GetDecimal(iznos_p);
recXNar.naruceno = reader.GetDecimal(naruceno);
recXNar.narudzba = reader.GetDecimal(narudzba);
recXNar.otpremnica = reader.GetDecimal(otpremnica);
recXNar.pdv = reader.GetDecimal(pdv);
recXNar.povrat_k = reader.GetDecimal(povrat_k);
recXNar.povrat_p = reader.GetDecimal(povrat_p);
recXNar.pp_id = reader.GetDecimal(pp_id);
recXNar.preporuka = reader.GetDecimal(preporuka);
recXNar.rabat = reader.GetDecimal(rabat);
recXNar.rn_id = reader.GetDecimal(rn_id);
recXNar.skart = reader.GetDecimal(skart);
recXNar.user_id = reader.GetDecimal(user_id);
recXNar.var_n = reader.GetDecimal(var_n);
recXNar.var_v = reader.GetDecimal(var_v);
recXNar.veleprodaja = reader.GetDecimal(veleprodaja);
recXNar.vraceno = reader.GetDecimal(vraceno);
recXNar.isporuka_id = reader.GetString(isporuka_id);
recXNar.otpremljeno = reader.GetString(otpremljeno);
recXNar.promjena = reader.GetString(promjena);
recXNar.rj_id = reader.GetString(rj_id);
recXNar.zakljucano = reader.GetString(zakljucano);
listXnar.Add(recXNar);
}
}
reader.Close();
}
}
return listXnar;
}
``` | 2014/06/15 | [
"https://Stackoverflow.com/questions/24232064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/448923/"
] | There is a better way ( You need to just do it once and it will help in future). Derive a class from DbDataReader that will take sqldatareader in the constructor:
```
public class CustomReader : DbDataReader
{
private readonly SqlDataReader sqlDataReader;
//Set the sqlDataReader
public CustomReader(SqlDataReader sqlDataReader)
{
this.sqlDataReader = sqlDataReader;
//Cache the names
this.CacheColumns();
}
private Dictionary<string,int> nameOrdinals = new Dictionary<string, int>();
private void CacheColumns()
{
int fieldCount= this.sqlDataReader.FieldCount;
for (int i = 0; i <= fieldCount-1; i++)
{
string name=sqlDataReader.GetName(i);
nameOrdinals.Add(name,i);
}
}
public override object this[string name]
{
get
{
int ordinal=this.nameOrdinals[name];
return this.GetValue(ordinal);
}
}
//Custom implementation
public string GetString(string name)
{
int ordinal = this.nameOrdinals[name];
return this.GetString(ordinal);
}
//Custom implementation
public string GetString(string name,string defaultValue)
{
int ordinal = this.nameOrdinals[name];
if (this.IsDBNull(ordinal))
{
return defaultValue;
}
return this.GetString(ordinal);
}
//return from sqlDataReader
public override string GetString(int ordinal)
{
return sqlDataReader.GetString(ordinal);
}
public override void Close()
{
sqlDataReader.Close();
}
```
So what I have done is passed the SqlDataReader in custom class that can cache the column names with the positions. Then you are free to call the Custom implementation using the delegate sqldatareader or write your own functions on top - like I have done for string. Little bit of work initially but you can put all checks here like check for DbNull etc and return default values based on that.
```
SqlCommand sqlCommand = new SqlCommand("select * from cats",sqlConnection);
SqlDataReader reader = sqlCommand.ExecuteReader();
CustomReader customReader = new CustomReader(reader);
List<Cat> list = new List<Cat>();
while (customReader.Read())
{
Cat cat = new Cat();
cat.Id = customReader.GetString("id");
cat.Name = customReader.GetString("name");
list.Add(cat);
}
```
You may need to check the names of the columns coming back so may be store in lower case and then read in lower case. Your code doesnt need to do getordinal anymore and it is much cleaner as well. | Well it turns out that the code in my first post is OK! The mistake was in my POCO definition.
This is what caused the problem :
```
...
private DateTime _dt_get;
public DateTime dt_get
{
get { return _dt_get; }
set { value = _dt_get; } // <-- !!! insted of set { _dt_get = value; }
}
...
```
Thx for any help... |
50,434,546 | I am having an issue. I have the code defined here:
```js
$('.js-cars-item [type="checkbox"]').change(function() {
var idx = $(this).closest('li').index(); //Get the index - Number in order
var chk = $(this).is(":checked"); //Get if checked or not
var obj = this; //Checkbox object
$('.js-cars-item').each(function() { //Loop every js-cars-item
//Find the checkbox with the same index of clicked checkbox. Change disabled property
$(this).find('li:eq(' + idx + ') [type="checkbox"]').not(obj).prop("checked", false);
});
var checkeds = [];
$(".cars-item input:checkbox:checked").each(function(index) {
checkeds[index] = $(this).attr('id');
});
console.clear();
console.log("These are checked:", checkeds);
})
$('.js-add-category').click(function() {
var categoryContent = `<div class="cars">
<div class="cars-item js-cars-item">
<ul>
<li>
<input type="checkbox" id="car-1-3">
<label for="car-1-3"><i class="icon-tick"></i></label>
</li>
<li>
<input type="checkbox" id="car-2-3">
<label for="car-2-3"><i class="icon-tick"></i></label>
</li>
<li>
<input type="checkbox" id="car-3-3">
<label for="car-3-3"><i class="icon-tick"></i></label>
</li>
</ul>
</div>
<button type="button" class="js-add-section">Add Section</button>
</div> <br>`
$('.main').append(categoryContent);
});
$(document.body).on('click', 'button.js-add-section', function() {
var sectionContent = `<div class="cars-item js-cars-item">
<ul>
<li>
<input type="checkbox" id="car-1-6>
<label for="car-1-6"><i class="icon-tick"></i></label>
</li>
<li>
<input type="checkbox" id="car-2-6>
<label for="car-2-6"><i class="icon-tick"></i></label>
</li>
<li>
<input type="checkbox" id="car-3-6>
<label for="car-3-6"><i class="icon-tick"></i></label>
</li>
</ul> </div>`
$('.cars').append(sectionContent);
});
```
```css
.cars-item {
border-bottom: 1px solid gray;
}
ul {
/* Added to fully show console in snippet */
margin: 2px;
}
li {
display: inline;
}
.cars {
box-sizing: content-box;
width: 250px;
height: auto;
padding: 10px;
border: 5px solid blue;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="js-add-category">Add Category</button> <br> <br>
<div class="main">
<div class="cars">
<div class="cars-item js-cars-item">
<ul>
<li>
<input type="checkbox" id="car-1-3">
<label for="car-1-3"><i class="icon-tick"></i></label>
</li>
<li>
<input type="checkbox" id="car-2-3">
<label for="car-2-3"><i class="icon-tick"></i></label>
</li>
<li>
<input type="checkbox" id="car-3-3">
<label for="car-3-3"><i class="icon-tick"></i></label>
</li>
</ul>
</div>
<button type="button" class="js-add-section">Add Section</button>
<br>
<div class="section">
</div>
</div>
<br>
```
The issue is I am facing that, when I click on the `Add Section` button in a box, it adds duplicate rows in the other boxes. What I want to achieve is to add a row of checkboxes only in the box that I have clicked the 'Add Section' button.
When I click `Add Category`, it generates another box with another button `Add Section`
Please demo the code to get an overview. Please someone help me with this, I am totally stuck.
Thanks. | 2018/05/20 | [
"https://Stackoverflow.com/questions/50434546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7930353/"
] | 1. Just use two different paths for processed and not processed blobs.
2. Put your new blobs with prefix ("notprocessed-" for example), when renaming remove prefix. Set `"path": "input/notprocessed-{name}"` | Actually, blob service only **supports filtering by blob prefix and not by suffix**. Your only option would be to list blobs and then do client side filtering.
Also, the list blobs operation has an additional `delimiter` parameter that enables the caller to traverse the blob namespace by using a user-configured delimiter.
You could refer to this [article](https://learn.microsoft.com/en-us/rest/api/storageservices/enumerating-blob-resources) for more details. |
1,111,527 | I'm writing a Java application that will instantiate objects of a class to represent clients that have connected and registered with an external system on the other side of my application.
Each client object has two nested classes within it, representing front-end and back-end. the front-end class will continuously receive data from the actual client, and send indications and data to the back-end class, which will take that data from the front-end and send it to the external system in using the proper format and protocol that system requires.
In the design, we're looking to have each instantiation of a client object be a thread. Then, within each thread will naturally be two sockets [EDIT]with their own NIO channels each[/EDIT], one client-side, one system-side residing in the front- and back-end respectively. However, this now introduces the need for nonblocking sockets. I have been reading the tutorial [here](http://rox-xmlrpc.sourceforge.net/niotut/) that explains how to safely use a Selector in your main thread for handling all threads with connections.
But, what I need are multiple selectors--each operating in their own thread. From reading the aforementioned tutorial, I've learned that the key sets in a Selector are not threadsafe. Does this mean that separate Selectors instantiated in their own repsective threads may create conflicting keys if I try to give them each their own pair of sockets and channels? Moving the selector up to the main thread is a slight possibility, but far from ideal based on the software requirements I've been given. Thank you for your help. | 2009/07/10 | [
"https://Stackoverflow.com/questions/1111527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/136475/"
] | HTTPS is HTTP over SSL. So the whole HTTP communication is encrypted. | The entire HTTP session is encrypted including both the header and the body.
Any packet sniffer should be able to show you the raw traffic, but it'll just look like random bytes to someone without a deep understanding of SSL, and even then you won't get beyond seeing the key exchange as a third party. |
51,515 | I've searched the Internet and found the question [Pattern(s) about hierarchical settings overwriting](https://softwareengineering.stackexchange.com/questions/159185/patterns-about-hierarchical-settings-overwriting) on Software Engineering SE. It exactly describes my need, the only difference is that I need to store the settings in a SQL Server database.
How can I implement it in SQL Server?
Whenever I select the setting for `level1-child1`, I want all overridden settings from `child1`, plus inherited ones from `level1`. For example:
```
level1: max-value:100; min-value:10; enable-alarm:true;
level-child1: min-value:30;
```
after select:
```
level1-child1: max-value:100; min-value:30; enable-alarm:true;
```
Currently I use hierarchy path to implement hierarchies. | 2013/10/15 | [
"https://dba.stackexchange.com/questions/51515",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/10817/"
] | You don't give a lot of detail on your current structure, so I'm assuming each node in the hierarchy is in a simple table with a single parent relationship like so and the path being a string of ID like `/<rootNodeID>/<GPNodeID>/<PNodeID>/<LeadNodeID>` and that you intend to store the settings in a property bag arrangement rather than needing to update the DB structure when a new setting is added to the applcation logic, resulting insomething like this:
```
Nodes NodeSettings
============= ============ Settings
NodeID (PK) <--.-- NodeID (FK) =========
ParentID (FK) ---' Name (FK) ---> Name (PK)
FullPath Value
OtherProp1
OtherProp2
```
In this arrangement you can pull all settings that have a value anywhere up the tree from a given location (with values closer like so:
```
SELECT Name = s.Name
Value = (SELECT TOP 1 ns.value
FROM NodeSetting ns
JOIN Nodes n ON n.NodeID = ns.NodeID AND '<PathToTargetNode>' LIKE n.FullPath+'%'
WHERE ns.Name = s.Name
ORDER BY LEN(n.FullPath) DESC
)
FROM Settings s
```
The use of a sub-query like this my not be efficient enough if you have many settings but whould be fine otherwise. Of more concern is using `LIKE` that way: it will not be able to properly use any index on Nodes.FullPath so an index scan (or worse, a table scan) could be performed for each call of the sub-query. Off the top of my head I can't think of a way to significantly optimise this as a single query without adding new structure to your storage of the relationships between nodes such as keeping map between ascendants and descendants like:
```
RelationshipDistance
=======================
Ascendant (FK->NodeID)
Descendant (FK->NodeID)
Distance
```
(making sure to store the node's relationship with itself, as AscNode='NodeID', DescNode='NodeID', Distance=0). Then you can do:
```
SELECT Name = s.Name
Value = (SELECT TOP 1 s2.value
FROM RelationshipDistance r
JOIN Settings s2 ON n.NodeID = s.NodeID AND s2.Name = s.Name
WHERE r.Descendant = '<IDOfNodeYouAreLookingFor>'
ORDER BY r.Distance DESC
)
FROM Setting s
```
The disadvantage here is needing to maintain the extra structure (through triggers or work in another layer of your code).
Of course this is assuming that you want to return the settings from a single statement. You could always define a procedure that walks up the path collecting the settings in a temporary table or table variable, adding new settings found at each step towards the root - this is likely to be more efficient than a single statement version that causes index/table scans. | SQL Server 2016 has Hierarchical Data. Please refer to [Hierarchical Data (SQL Server)](https://msdn.microsoft.com/en-us/library/bb677173.aspx) in the product documentation.
You can use `hierarchyid` to define the node hierarchy for each row.
The link gives a clear example of how to use `hierarchyid` data type for a database column, and showcases how it can be queried. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.