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 |
|---|---|---|---|---|---|
109,409 | What are the key strengths of ASP.NET Webforms (2.0-3.5)? I'm not looking for comparisons to other frameworks, I'm just am looking for feedback on ASP.NET as it stands today. | 2008/09/20 | [
"https://Stackoverflow.com/questions/109409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3289/"
] | One key strength (to some) is a drag-and-drop development environment integrated into Visual Studio. This allows you to get simple things up and running quickly, but can also be a liability when the time comes that you actually need to understand the underlying code. | * State Management
* Low learning curve to get started on something simple (However becomes complicated quickly as soon as you have a page with dynamically added elements).
* Huge library of mature controls
* Huge amount of documentation and resources
* Great performance
Despite what other people may have said, it's possible to keep things from turning into a complete mess. |
7,880,355 | If you are a package author, you are hopefully well aware of upcoming changes in package structure when we move to 2.14 in about a week. One of the changes is that all packages will require a NAMESPACE, and one will be generated for you in the event you do not make one (the R equivalent of your Miranda rights in the US). So being good citizen I was trying to figure this out. Here is the section from R-exts:
>
> 1.6.5 Summary – converting an existing package
>
>
> To summarize, converting an existing package to use a namespace
> involves several simple steps:
>
>
> Identify the public definitions and place them in export directives.
> Identify S3-style method definitions and write corresponding S3method
> declarations. Identify dependencies and replace any require calls by
> import directives (and make appropriate changes in the Depends and
> Imports fields of the DESCRIPTION file). Replace .First.lib functions
> with .onLoad functions or useDynLib directives.
>
>
>
To ensure I do the right thing here, can someone give a short clear definition/answer (am I breaking a rule by having several small but related questions together?). All answers should take 2.14 into account, please:
1. A definition of NAMESPACE as used by R
2. Is there a way to generate a NAMESPACE prior to build and check, or do we b/c once and then edit the NAMESPACE created automatically?
3. The difference between "Depends:" and "Imports:" in the DESCRIPTION file. In particular, why would a I put a package in "Depends:" instead of the "Imports:" or vice versa?
4. It sounds like "require" is no longer to be used, though it doesn't say that. Is this the correct interpretation?
Thanks! | 2011/10/24 | [
"https://Stackoverflow.com/questions/7880355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/633251/"
] | CRAN packages have had NAMESPACEs since almost time immortal. Just pick a few of your favorite CRAN packages and look at their NAMESPACE files.
It can be as easy as this one-liner (plus comment) taken from [snow](http://cran.r-project.org/package=snow):
```
# Export all names unless they start with a dot
exportPattern("^[^.]")
```
The run `R CMD check` as usual, and you should be fine in most circumstances. | I recently worked on this for one of my packages. Here are my new Depends, Imports, and Suggests lines
```
Depends: R (>= 2.15.0)
Imports: nlme, mvtnorm, KFAS (>= 0.9.11), stats, utils, graphics
Suggests: Hmisc, maps, xtable, stringr
```
stats, utils and graphics are part of base R, but the user could detach them and then my package wouldn't work. If you use R from the command line, you might think 'why would anyone detach those?'. But if a user is using RStudio, say, I could see them going through and 'unclicking' all the packages. Strange thing to do, nonetheless, I don't want my package to stop working if they do that. Or they might redefine, say, the plot function (or some other function) , and then my package would fail.
My NAMESPACE then has the following lines
```
import(KFAS)
import(stats)
import(utils)
import(graphics)
```
I don't want to go through and keep track of which stats, utils and graphics functions I use, so I import their whole namespaces. For KFAS, I only need 2 functions, but the exported function names changed between versions so I import the whole namespace and then in my code test which version the user has.
For mvtnorm and nlme, I only use one function so I import just those. I could import the whole namespace, but try to only import what I really use.
```
importFrom(mvtnorm, rmvnorm)
importFrom(nlme, fdHess)
```
The vignettes where the Suggests packages appear have
```
require(package)
```
lines in them.
For the exported functions in my NAMESPACE, I'm a little torn. CRAN has become strict in not allowing ::: in your package code. That means that if I don't export a function, I am restricting creative re-use. On the other hand, I understand the need to only export functions that you intend to maintain with a stable arg list and output otherwise we break each other's packages by changing the function interface. |
21,918,354 | I want to generate event on start and end of the method to log time stamp for QOS & instrumentation purpose. In spring framework that it is easy to achieve using AOP without writing boiler plate code in each of the methods.
I want to do similar in play. I looked in action & @with annotation however it is not giving desired result.
What is best way to log event & time stamp on start (before) and on completion (after) method?
Below is my action class:
```
import play.libs.F.Promise;
import play.mvc.Action;
import play.mvc.Http;
import play.mvc.SimpleResult;
public class PublishEventAction extends Action<PublishEvent> {
@Override
public Promise<SimpleResult> call(Http.Context context) throws Throwable
{
try {
before(context);
Promise<SimpleResult> result = delegate.call(context); // This part calls your real action method
after(context);
return result;
} catch (RuntimeException e) {
throw e;
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
private void before(Http.Context context) {
// Do the before things here
System.out.println("Before: " + context.request().path()+context.toString()+"current time : "+System.currentTimeMillis());
}
private void after(Http.Context context) {
// Do the after things here
System.out.println("After: " + context.request().path()+context.toString()+"current time : "+System.currentTimeMillis());
}
}
```
Thanks in advance! | 2014/02/20 | [
"https://Stackoverflow.com/questions/21918354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1557197/"
] | You can intercept before and after the request like shown below and log all your requests:
```
public Action onRequest(final Http.Request request, Method method) {
Action action = new Action.Simple() {
public Promise<Result> call(Http.Context ctx) throws Throwable {
Long start = System.currentTimeMillis();
Promise<Result> result = delegate.call(ctx);
//This part is not executed immediately
Long finish = System.currentTimeMillis();
Logger.info("method=" + request.method() + " uri=" + request.uri() + " remote-address=" + request.remoteAddress() + " time=" + (finish-start));
return result;
}
};
return action;
}
``` | As has been mentioned you want to extend the Global Settings object.
Play's documentation is solid: [Application Global Settings](https://www.playframework.com/documentation/2.0/JavaGlobal) and [Intercepting Requests](https://www.playframework.com/documentation/2.2.x/JavaInterceptors)
```
import play.*;
import play.mvc.Action;
import play.mvc.Http.Request;
import java.lang.reflect.Method;
public class Global extends GlobalSettings {
public Action onRequest(Request request, Method actionMethod) {
System.out.println("before each request..." + request.toString());
return super.onRequest(request, actionMethod);
}
}
```
The documentation explains that if you want to intercept a specific action, you can do so with [action composition](https://www.playframework.com/documentation/2.2.x/JavaActionsComposition). |
21,706,256 | I post here a snippet of code where I get a runtime error. The variable `x` changes is value inside an ajax call:
```
$("#acquisto").click(function(){
var x = 0;
for(x = 0; x < numRighe; x++){
if( $("#ch"+x).prop("checked") == true){
alert("#tr"+x);
$.ajax({
url:"eliminazioneRecord.php",
type: "GET",
data: { Codice: $("#ch"+x).val() },
success:function(result){
//$("#tr"+x).fadeOut("slow");
alert("#tr"+x);
},
error:function(richiesta,stato,errori){
alert("<strong>Chiamata fallita:</strong>"+stato+" "+errori);
}
});
}
}
});
```
I realized that because the in the alert before the ajax call `x` has a value that is different from the one showed in the alert inside the success function. Where I am wrong? | 2014/02/11 | [
"https://Stackoverflow.com/questions/21706256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2337094/"
] | All the anonymous functions passed to `success` in `$.ajax` reference the same `x` variable from the outer scope which is incremented by the for structure. You need each function to have it's own copy of `x`.
```
success:function(copy_x) {
return function(result){
//$("#tr"+copy_x).fadeOut("slow");
alert("#tr"+copy_x);
}
}(x),
``` | It is because your are using the loop variable `x` in a closure within the loop.
```
$("#acquisto").click(function () {
for (var x = 0; x < numRighe; x++) {
(function (x) {
if ($("#ch" + x).prop("checked") == true) {
alert("#tr" + x);
$.ajax({
url: "eliminazioneRecord.php",
type: "GET",
data: {
Codice: $("#ch" + x).val()
},
success: function (result) {
//$("#tr"+x).fadeOut("slow");
alert("#tr" + x);
},
error: function (richiesta, stato, errori) {
alert("<strong>Chiamata fallita:</strong>" + stato + " " + errori);
}
});
}
})(x)
}
});
```
Read:
* [Creating closures in loops: A common mistake](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures#Creating_closures_in_loops.3A_A_common_mistake)
* [Javascript closure inside loops - simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) |
24,461 | I have a frying pan with a metal lid. The lid has a small threaded post sticking out of the top of it onto which a wooden knob is screwed. The threads inside the knob have become stripped so the knob will no longer stay attached to the pan lid.
This would seem like a job for either Krazy Glue or Gorilla Glue if not for the high temperature that the fix will have to endure. All of the glues that I find that boast a specific temperature rating do not seem appropriate to the task (pastes, ribbons, etc.). Many glues are described as "temperature resistant" or "can handle temperature changes", but I don't know what those phrases really mean.
One common high-temp substance is silicon sealer, but that isn't going to provide the strength I need for this job, right?
In short, what is the best glue to use on a frying pan lid/knob? | 2021/02/06 | [
"https://lifehacks.stackexchange.com/questions/24461",
"https://lifehacks.stackexchange.com",
"https://lifehacks.stackexchange.com/users/32967/"
] | I fixed my kettle's wooden knob a while ago.
I used normal white glue (not school glue which doesn't harden completely).
The knob was heavily carboned (burnt). It slid on and off the threaded post easily. I figured that I had nothing left to lose so I filled the burned hole with some white glue and set the lid on it upside down until the glue hardened. It took a day or so.
It's been over a year using my kettle many times a day, everyday, without a hitch.
Good luck. | If you are concerned about the glue being exposed to high temperature, automotive stores sell high temperature glue designed to exist near an internal combustion engine when hot. |
122,472 | Why do we usually pre-whiten the data before doing independent components analysis (ICA), like making all eigenvalues equal? Doesn't that take away some information regarding the data? | 2014/11/03 | [
"https://stats.stackexchange.com/questions/122472",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/59859/"
] | ICA assumes that the observed data $\mathbf x$ are a linear combination of independent components: $\mathbf x = \mathbf A \mathbf s$, where $\mathbf A$ is usually called *mixing matrix*.
Covariance matrix of the data is then given by $\mathbf A \mathbf A^\top$, because the covariance matrix of independent components $\mathbf s$ is identity (indeed, independent components must have zero correlation between each other and are assumed to be scaled to have unit variance each). This means that if the data are pre-whitened, then $\mathbf A$ must be an orthogonal matrix. This is often convenient.
Here is e.g. a quote from [Hyvärinen & Oja, 2000, Independent Component Analysis: Algorithms and Applications](http://www.maths.tcd.ie/~mnl/store/HyvarinenOja2000a.pdf), section 5.2, called "Whitenening":
>
> Here we see that whitening reduces the number of parameters to be estimated. Instead of having to
> estimate the $n^2$ parameters that are the elements of the original matrix $\mathbf A$ , we only need to estimate
> the new, orthogonal mixing matrix $ \tilde{\mathbf A}$ . An orthogonal matrix contains $n ( n - 1)/ 2$ degrees of freedom.
> For example, in two dimensions, an orthogonal transformation is determined by a single angle parameter.
> In larger dimensions, an orthogonal matrix contains only about half of the number of parameters of an
> arbitrary matrix. Thus one can say that whitening solves half of the problem of ICA. Because whitening is
> a very simple and standard procedure, much simpler than any ICA algorithms, it is a good idea to reduce
> the complexity of the problem this way.
>
>
> | ICA is a invertible problem, so ideally W should be rotation matrix. If you Whiten the signal the covariant matrix will be rotation. So you can take advantage of Natural Stochastic Gradient Descent by using grassmann manifold or stiefel manifold which can promise fast coverage. |
14,648,318 | Is there a key binding to move the point to end of the next string? | 2013/02/01 | [
"https://Stackoverflow.com/questions/14648318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1458283/"
] | If point is at the beginning of the string, you can use `C-M-f` to move past the end:
```
"this is my string"
↑ from here ↑ to here
```
However, this doesn't work if point is inside the string. `C-s "` might be the simplest way. | Most programming modes will define a syntax class for delimiters of string literals. You can use `skip-syntax-forward` to move to these. I don't know exactly the behavior you want, but this is the key to finding where string delimiters are.
```
(skip-syntax-forward "^\"")
```
* <http://www.gnu.org/software/emacs/manual/html_node/elisp/Motion-and-Syntax.html>
* <http://www.gnu.org/software/emacs/manual/html_node/elisp/Syntax-Class-Table.html> |
3,698 | The review queue presents itself across the top like:

Which when you click on it takes you to:

The numbers almost always are out of sync with what is in the queue, (the pictures above show 7 whilst all the different categories are empty - i.e. a real time scenario).
1/2 hour previously it read 4, then bumped up to 9 (but there were 7 new things in the queue - so it should have gone to 11) I deal with those and then came back to see a 7 displayed (implying that I'd only dealt with 2 - when it should have shown 0) and now it has been stuck at 7 for about 20 minutes.
I understand a processing delay, or a lower priority (background) process so I don't expect this to be an absolute status indicator, given how dynamic this site can be, but this seems to me more like sticky behaviour i.e. a bug. | 2014/05/18 | [
"https://electronics.meta.stackexchange.com/questions/3698",
"https://electronics.meta.stackexchange.com",
"https://electronics.meta.stackexchange.com/users/11861/"
] | DIP
===
Dual-Inline Package, an integrated packaging style for through-hole assembly | ROM
===
[Read-only memory](https://en.wikipedia.org/wiki/Read-only_memory)
Data persists after power is removed. |
5,913,943 | Hey guys I'm trying to create something similar to the image below. As you can see I have 2 containers both will be of varying sizes. ({DEPARTMENT OF BUSINESS} {-------}) The left container will have text, and the right container a line image. I basically want the 2 to take up 100% of that space. I think my code should explain what I'm trying to do.
I don't even know if I'm going about this the correct way because even if I use the line as the background image how would I then push it down to make it vertically center? I'm getting no where with margins and padding.

Here's my code:
```
<div id="DepartmentHeader" class="clearfix" style="width: 626px">
<div id="DepartmentHeaderText" style="float:left">DEPARTMENT OF BUSINESS</div>
<div id="DepartmentHeaderDivider" style="float: left; width: 50%; background: url('images/DepartmentHeaderDividerLine.png') repeat-x;"> </div>
</div>
``` | 2011/05/06 | [
"https://Stackoverflow.com/questions/5913943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/546489/"
] | If I understand correctly what you're trying to do you could probably make the image the same height as the DepartmentHeader div with the line in the center, set that as a background image on DepartmentHeader (which would eliminate the need for the DepartmentHeaderDivider div), style the DepartmentHeaderText div with a background color of the rest of the page. As long as you make the DepartmentHeader div 100% of the width and you keep the text for the DepartmentHeaderText div left-aligned you should be good. | This can be done with a little CSS Trickery (No Images)
**Live Fiddle:**
<http://jsfiddle.net/Jaybles/zPvv5/>
**HTML**
```
<div class="container">
<div class="line"></div>
<div class="cap">Business Items</div>
</div>
<div class="container">
<div class="line"></div>
<div class="cap">Business Items 2</div>
</div>
```
**CSS**
```
.container{
width:100%;
height:46px;
font-size:30pt;
font-family:verdana;
margin-bottom:20px;
}
.container .line{
width:100%;
border-bottom:3px solid #000;
height:23px;
position:absolute;
}
.container .cap{
position:absolute;
padding-right:10px;
background:#fff;
}
``` |
238,800 | I have a query:
UPDATE choices SET votes = votes + 1 WHERE choice\_id = '$user\_choice'
But when I execute it in my script, the votes field is updated twice, so the votes will go from 4 to 6 instead to 5. It doesn't seem that it is getting called twice because I echo out stuff to test this and only get one echo. Is there a way to have it so PHP will only execute this query once per page "refresh"?
**EDIT**: Thanks for the responses, I'm using regular MySQL, no MySQLi or PDO. Another thing I found is that when doing the query, it works when you start out with 0 and update to 1, but then after that it goes 3, 5, 7, ... | 2008/10/26 | [
"https://Stackoverflow.com/questions/238800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | One other option is, if you are using firefox at all and have firbug installed you need to disable your cache. For some reason firbug results in two calls to the dB. Took weeks to figure this out where I work as QA was getting all kinds of strange results when testing. he was the only one with firebug. | You may just need to put brackets around the `votes + 1` such as:
```
UPDATE choices SET votes = (votes + 1) WHERE choice_id = '$user_choice';
```
I might also put a `LIMIT 1` at the end.
Also, have tried running the query outside of your PHP, like through PHPMyAdmin? Also, try echoing out your SQL in whole before running it...you may just find an error. |
52,042,198 | I am using a split function to separate a column with two street addresses.
The information is separated by `,`.
Some of the rows only have one address associated with them.
In those rows for my Street Address 2, I'm getting `#ERROR` when I want it to be `null`.
I've tried an `IIF()` statement for the expression, but I am having trouble with it.
```
Split(Fields!Street.Value, ",").GetValue(2)
``` | 2018/08/27 | [
"https://Stackoverflow.com/questions/52042198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10177680/"
] | (Use a custom function for each Address.
Adapted from: [Split String](https://social.msdn.microsoft.com/Forums/sqlserver/en-US/42757123-d65f-4587-8995-dda2760772f3/split-the-column-into-two-columns-using-custom-code?forum=sqlreportingservices)
```
Public Function GetAddress1(ByVal a as String)
Dim b() as string
b=Split(a,",")
Dim str_1(b.Length) As String
Dim i As Integer
For i = 0 To b.Length - 1
str_1(i) = b(i).Split(",")(0)
Next
return str_1
End Function
Public Function GetAddress2 (ByVal a as String)
Dim b() as string
b=Split(a,",")
Dim str_1(b.Length) As String
Dim i As Integer
For i = 0 To b.Length - 1
str_1(i) = b(i).Split(",")(1)
Next
return str_1
End Function
``` | Unlike the If statement, IIf statements evaluate all code paths even though only one code path is used. This means that an error in an unused code-path will bubble up to an error in the IIf statement, preventing it from executing correctly.
To fix this, you need to use functions that won't throw an error when there is nothing to split.
Here is an example of code that should do what you want:
```
=IIf(
InStr(
InStr(
Parameters!Street.Value
, ","
) + 1
,
Parameters!Street.Value
, ","
) = 0
, Nothing
, Right(
Parameters!Street.Value
, Parameters!Street.Value.ToString().Length - (
InStr(
InStr(
Parameters!Street.Value
, ","
) + 1
,
Parameters!Street.Value
, ","
)
)
)
)
```
Let's break this down.
I've used a combination of InStr(), Right(), Length(), and IIf() functions to split the string without throwing an error.
InStr() is used to find the position of the string "," within the address. This returns 0 rather than an error if it can't find the string.
```
InStr(Parameters!Street.Value, ",")
```
Since you appear to be looking for the second comma in your split function you will need to nest the InStr function. Use the location of the first comma as the start location to search for the second comma. Don't forget to +1 or you will find the first comma again.
```
InStr(InStr(Parameters!Street.Value, ",") + 1, Parameters!Street.Value, ",")
```
Now you can find the second comma without throwing an error even if no commas exist.
Based on the location of the second comma use the Right() function to grab all characters to the right of the second comma. Since Right() needs to know how many characters from the end rather than from the beginning, you will need to subtract the location of the comma from the Length() of the string. This effectively splits the string at the comma.
```
Right(
Parameters!Street.Value
, Parameters!Street.Value.ToString().Length - (
InStr(InStr(Parameters!Street.Value, ",") + 1, Parameters!Street.Value, ","))
)
)
```
*If you have more than 2 commas you can grab just the string between the 2nd and 3rd comma by following up with a Left() function that finds the location of the 3rd comma.*
Now you can use your IIf() function to return NULL (Nothing) if there is not a 2nd comma. The function at the top shows how this all fits together.
This could be cleaned up by using functions, but the provided code shows you how it can be done. |
15,491,294 | I need to retrieve the current balance of bank Account in Netsuite using SuiteTalk(Netsuite Webservise).In suite talk API there is no field/parameter to refer the balance of account.But There is UI field Balance which shows the current balance of the account.Any help/suggestions on this is appreciated | 2013/03/19 | [
"https://Stackoverflow.com/questions/15491294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1863050/"
] | WinLister from [NirSoft](http://www.nirsoft.net) list all windows active on a machine as well as associated information (title, path, handle, class, position, process ID, thread ID, etc.). It has a GUI interface rather than command-line. | Use powershell. The command is: Get-Process
You can try this:
```
##Method 1: (Gives you all the processes)
Get-Process
## Method 2: Detailed Info On a specific named Process
$ProcessTerm="chrome"
#Run This:
$FindProcess = Get-Process | Where-Object {$_.MainWindowTitle -like "*$processterm*"}
Get-Process -ID $FindProcess.ID | Select-Object *
# FindProcess.ID will give you the ID of the above process
#Method 3: (if you know the process ID)
$ProcessID = "9068"
$FindProcess = Get-Process | Where-Object {$_.id -eq "$ProcessID"}
Get-Process -ID $FindProcess.Id | Select-Object *
``` |
59,233,133 | Today I have seen a video lecture in which they gave the `foriegn key` by using `ADD INDEX` on a table -
### CASE 1 -
DECRIPTION OF TABLE 1 : **subjects**
```
+-----------+------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| menu_name | int(11) | YES | | NULL | |
| position | int(3) | YES | | NULL | |
| visible | tinyint(1) | YES | | NULL | |
+-----------+------------+------+-----+---------+----------------+
```
DECRIPTION OF TABLE 2 : **pages**
```
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| subject_id | int(11) | YES | | NULL | |
| menu_name | varchar(255) | YES | | NULL | |
| position | int(3) | YES | | NULL | |
| visible | tinyint(1) | YES | | NULL | |
| content | text | YES | | NULL | |
+------------+--------------+------+-----+---------+----------------+
```
So in the column `subject_id` of table `pages` should store the `id` of table `subjects`.
Which one should i use and why ? -
**ALTER TABLE pages ADD INDEX fk\_subject\_id (subject\_id);**
OR
**ALTER TABLE pages
ADD FOREIGN KEY (subject\_id) REFERENCES students(id)**;
video lecture uses `ALTER TABLE pages ADD INDEX fk_subject_id (subject_id);`.
---
### CASE 2 -
Now Please cosider one more example -
According to above details, If I have 5 more tables including `pages` table(defined above).
All 5 tables have column `subject_id` which should store the data accodring to column `id` of table `subjects`.
So in this case
In this case, Which one Should I use `ADD INDEX` or `FOREIGN KEY` and why ? | 2019/12/08 | [
"https://Stackoverflow.com/questions/59233133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12483634/"
] | A local variable is essentially guaranteed to be fast, whereas there is an unknown amount of overhead involved in accessing the property.
It's almost always a good idea to avoid repeating code whenever possible. Storing the value once means that there is only one thing to change if it needs changing, rather than two or more.
Using a variable allows you to provide a name, which gives you an opportunity to describe your intent.
I would also point out that if you're referring to other members of an object a lot in one place, that can often be a strong indication that the code you're writing actually belongs in that other type instead. | You should consider that getting a value from a method that is calculated from an I/O-bound or CPU-bound process can be irrational. Therefore, it's better to define a var and store the result to avoid multiple same processing.
In the case that you are using a value like `object.Id`, utilizing a variable decorated with `const` keyword guarantees that the value will not change in the scope.
Finally, it's better to use a local var in the classes and methods. |
3,832,089 | I have a third-party program installed, and I want to find out what version of the [.NET](http://en.wikipedia.org/wiki/.NET_Framework) framework it is using.
How do I figure that out? | 2010/09/30 | [
"https://Stackoverflow.com/questions/3832089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/109035/"
] | Load ILDASM and import your DLL. Double click on the 'Manifest' and it will display the framework version. | I found *[How to identify the framework version a DLL is using](http://www.vbdotnetforums.com/net-framework/26246-how-identify-framework-version-dll-using.html)*. It might mean writing a small secondary program to perform the action. |
8,777,216 | I my way to learn Haskell I'm starting to grasp the monad concept and starting to use the known monads in my code but I'm still having difficulties approaching monads from a designer point of view. In OO there are several rules like, "identify nouns" for objects, watch for some kind of state and interface... but I'm not able to find equivalent resources for monads.
So how do you identify a problem as monadic in nature? What are good design patterns for monadic design? What's your approach when you realize that some code would be better refactored into a monad? | 2012/01/08 | [
"https://Stackoverflow.com/questions/8777216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38483/"
] | A helpful rule of thumb is when you see values *in a context*; monads can be seen as layering "effects" on:
* **Maybe:** partiality (uses: computations that can fail)
* **Either:** short-circuiting errors (uses: error/exception handling)
* **[] (the list monad):** nondeterminism (uses: list generation, filtering, ...)
* **State:** a single mutable reference (uses: state)
* **Reader:** a shared environment (uses: variable bindings, common information, ...)
* **Writer:** a "side-channel" output or accumulation (uses: logging, maintaining a write-only counter, ...)
* **Cont:** non-local control-flow (uses: too numerous to list)
Usually, you should generally design your monad by layering on the monad transformers from the standard [Monad Transformer Library](http://hackage.haskell.org/package/mtl), which let you combine the above effects into a single monad. Together, these handle the majority of monads you might want to use. There are some additional monads not included in the MTL, such as the [probability](http://www.randomhacks.net/articles/2007/02/22/bayes-rule-and-drug-tests) and [supply](http://hackage.haskell.org/package/monad-supply) monads.
As far as developing an intuition for whether a newly-defined type is a monad, and how it behaves as one, you can think of it by going up from `Functor` to `Monad`:
* **Functor** lets you transform values with pure functions.
* **Applicative** lets you embed pure values and express application — `(<*>)` lets you go from an embedded function and its embedded argument to an embedded result.
* **Monad** lets the structure of embedded computations depend on the *values* of previous computations.
The easiest way to understand this is to look at the type of `join`:
```
join :: (Monad m) => m (m a) -> m a
```
This means that if you have an embedded computation whose result is a *new* embedded computation, you can create a computation that executes the result of that computation. So you can use monadic effects to create a new computation based on values of previous computations, and *transfer* control flow to that computation.
Interestingly, this can be a *weakness* of structuring things monadically: with `Applicative`, the structure of the computation is static (i.e. a given `Applicative` computation has a certain structure of effects that cannot change based on intermediate values), whereas with `Monad` it is dynamic. This can restrict the optimisation you can do; for instance, applicative parsers are less powerful than monadic ones (well, this isn't [strictly true](http://byorgey.wordpress.com/2012/01/05/parsing-context-sensitive-languages-with-applicative/), but it effectively is), but they can be optimised better.
Note that `(>>=)` can be defined as
```
m >>= f = join (fmap f m)
```
and so a monad can be defined simply with `return` and `join` (assuming it's a `Functor`; all monads are applicative functors, but Haskell's typeclass hierarchy unfortunately doesn't require this for [historical reasons](https://stackoverflow.com/questions/8658384/relationship-between-functor-applicative-functor-and-monad/8659094#8659094)).
As an additional note, you probably shouldn't focus too heavily on monads, no matter what kind of buzz they get from misguided non-Haskellers. There are many typeclasses that represent meaningful and powerful patterns, and not everything is best expressed as a monad. [Applicative](http://hackage.haskell.org/packages/archive/base/latest/doc/html/Control-Applicative.html), [Monoid](http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-Monoid.html), [Foldable](http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-Foldable.html)... which abstraction to use depends entirely on your situation. And, of course, just because something is a monad doesn't mean it can't be other things too; being a monad is just another property of a type.
So, you shouldn't think too much about "identifying monads"; the questions are more like:
* Can this code be expressed in a simpler monadic form? With which monad?
* Is this type I've just defined a monad? What generic patterns encoded by the standard functions on monads can I take advantage of? | This is sort of a non-answer, but I feel it is important to say anyways. **Just ask!** StackOverflow, /r/haskell, and the #haskell irc channel are all great places to get quick feedback from smart people. If you are working on a problem, and you suspect that there's some monadic magic that could make it easier, just ask! The Haskell community loves to solve problems, and is ridiculously friendly.
Don't misunderstand, I'm not encouraging you to never learn for yourself. Quite the contrary, interacting with the Haskell community is one of the *best* ways to learn. [LYAH](http://learnyouahaskell.com/) and [RWH](http://book.realworldhaskell.org/), 2 Haskell books that are freely available online, come highly recommended as well.
Oh, and don't forget to *play, play, play!* As you play around with monadic code, you'll start to get the feel of what "shape" monads have, and when monadic combinators can be useful. If you're rolling your own monad, then usually the type system will guide you to an obvious, simple solution. But to be honest, you should rarely need to roll your own instance of Monad, since Haskell libraries provide tons of useful things as mentioned by other answerers. |
1,246,766 | How do you prove that
$$
\Gamma'(1)=-\gamma,
$$
where $\gamma$ is the Euler-Mascheroni constant? | 2015/04/22 | [
"https://math.stackexchange.com/questions/1246766",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/93122/"
] | The Weierstrass product for the $\Gamma$ function gives:
$$\Gamma(z+1)=e^{-\gamma z}\cdot\prod\_{n\geq 1}\left(1+\frac{z}{n}\right)^{-1}e^{z/n}\tag{1}$$
hence by considering $\frac{d}{dz}\log(\cdot)$ of both terms we get:
$$ \psi(z+1)=\frac{\Gamma'(z+1)}{\Gamma(z+1)}=-\gamma+\sum\_{n\geq 1}\left(\frac{1}{n}-\frac{1}{n+z}\right) \tag{2}$$
and by evaluating the previous identity in $z=0$ it follows that:
$$ \psi(1) = \Gamma'(1) = -\gamma.\tag{3}$$ | I was wrong I cannot delete my post because I having trouble singing in sorry for my lapse in judgement and failed math skills I will try to be better the solutions above work just fine.
$$\Gamma^{\prime}(z) = \frac{d}{dz} \int^{\infty}\_{0} e^{-t}t^{z-1}dt = \int^{\infty}\_{0} \frac{d}{dz} e^{-t}t^{z-1}dt =
\int^{\infty}\_{0} e^{-t} \frac{d}{dz} t^{z-1} dt =
\int^{\infty}\_{0} e^{-t} ln(t) t^{z-1} dt$$
$$\Gamma^{\prime}(1) = \int^{\infty}\_{0} e^{-t} ln(t) t^{1-1} dt = \int^{\infty}\_{0} e^{-t} ln(t) dt$$ this integral can be solved numerically to show that it comes out to $$-\gamma\_{\,\_\mathrm{EM}}$$ |
24,917,832 | I installed Postgres with this command
```
sudo apt-get install postgresql postgresql-client postgresql-contrib libpq-dev
```
Using `psql --version` on terminal I get `psql (PostgreSQL) 9.3.4`
then I installed `pgadmin` with
```
sudo apt-get install pgadmin3
```
Later I opened the UI and create the server with this information

but this error appear

how can I fix it? | 2014/07/23 | [
"https://Stackoverflow.com/questions/24917832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3167016/"
] | It helps me:
---
1. **Open the file** `pg_hba.conf`
>
> sudo nano /etc/postgresql/9.x/main/pg\_hba.conf
>
>
>
and change this line:
```
Database administrative login by Unix domain socket
local all postgres md5
```
to
```
Database administrative login by Unix domain socket
local all postgres trust
```
2. **Restart the server**
>
> sudo service postgresql restart
>
>
>
3. **Login into psql** and **set password**
>
> psql -U postgres
>
>
>
`ALTER USER postgres with password 'new password';`
4. Again **open the file** `pg_hba.conf` and change this line:
```
Database administrative login by Unix domain socket
local all postgres trust
```
to
```
Database administrative login by Unix domain socket
local all postgres md5
```
5. **Restart the server**
>
> sudo service postgresql restart
>
>
>
---
It works.
[](https://i.stack.imgur.com/ZRFpg.jpg)
---
Helpful links
1: [PostgreSQL](https://help.ubuntu.com/community/PostgreSQL) (from ubuntu.com) | if you open the `psql` console in a terminal window, by typing
$ `psql`
you're super user username will be shown before the `=#`, for example:
`elisechant=#`$
That will be the user name you should use for localhost. |
44,704,705 | I have an **ADD** button that adds a form field when clicked on. I want the new form field button to change when it is added to a **REMOVE** button. How do I change the buttons (keep in mind I'm still learning jquery). Here's my code
HTML
```
<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }} inputFields">
<label for="name" class="col-md-4 control-label">Name</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control" name="name" value="{{ old('name') }}" required autofocus>
@if ($errors->has('name'))
<span class="help-block">
<strong>{{ $errors->first('name') }}</strong>
</span>
@endif
</div>
<a class="addbtn"><i class="fa fa-plus-circle fa-2x" aria-hidden="true"></i></a>
</div>
```
Script
```
$(document).ready(function(){
$(".addbtn").on('click', function(){
var ele = $(this).closest('.inputFields').clone(true);
$(this).closest('.inputFields').after(ele);
})
});
``` | 2017/06/22 | [
"https://Stackoverflow.com/questions/44704705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5583517/"
] | There are two options. Create two buttons and hide/show them or you can use one button and change its content to what you need. Of cours with the second option you have to check the click event if it should be a delete or an add.
I think this is what you are looking for
```js
$(document).ready(function(){
$(".deletebtn").hide();
$(".wrapper").on('click', '.addbtn', function(){
var ele = $(this).closest('.inputFields').clone(true);
$(this).closest('.inputFields').after(ele);
var el = $(this).closest('.inputFields').next();
el.find('.addbtn').hide();
el.find('.deletebtn').show();
});
$(".wrapper").on('click', '.deletebtn', function(){
$(this).closest('.inputFields').remove();
});
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="form-group inputFields">
<label for="name" class="col-md-4 control-label">Name</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control" name="name" value="" required autofocus>
</div>
<a class="addbtn"><i class="fa fa-plus-circle fa-2x" aria-hidden="true"></i> Add</a>
<a class="deletebtn"><i class="fa fa-plus-circle fa-2x" aria-hidden="true"></i> Remove</a>
</div>
</div>
``` | Add this to your `$('.addbtn').on('click'...);`...
```
$('.addbtn').hide();
$('.removebtn').show();
```
And add this to your html right below your addbtn...
```
<a class="removebtn">
<i class="fa fa-plus-circle fa-2x" aria-hidden="true"></i>
</a>
``` |
103,174 | I work in a Microsoft environment, so I can use my C# hammer on any nails I come across. That being said, what languages (compiled, interpreted, scripting, functional, any types!) complement knowing C#, and for what purposes? For example, I've moved a lot of script functionality away from compiled console apps and into Powershell scripts. If you're an MS developer, have you found a niche in your world for other languages like F#, IronRuby, IronPython, or something similar, and what niche do they fill?
Note: this question is directed at the Microsoft dev people since I can't run off and start installing LAMP stacks around my company, and therefore having to support it forever. :) However, feel free to mention any other languages that you found interesting to fulfill a certain task/role in your world apart from your main language. | 2008/09/19 | [
"https://Stackoverflow.com/questions/103174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1212/"
] | Since you are in a MS shop, I would suggest [PowerShell](http://www.microsoft.com/windowsserver2003/technologies/management/powershell/default.mspx) as a decent scripting language to learn. It plays well with C#.
I'm a big fan of Ruby too. | While it's a bit of a fringe language, I'm compelled to mention [Erlang](http://www.erlang.org/index.html). Erlang is an excellent language to have in your toolbox since it's unusual strengths tend to compliment other programming platforms. Erlang is very useful for building distributed, concurrent, fault-tolerant systems. It's used a lot in the instant-messaging and telephony world where there's a need for distributed, yet interconnected architectures. |
63,467,816 | I have the following code from SO:
```
import { Injectable } from '@angular/core';
@Injectable()
export class CookieService {
constructor() { }
public getCookie(name: string) {
const ca: Array<string> = document.cookie.split(';');
const caLen: number = ca.length;
const cookieName = `${name}=`;
let c: string;
for (let i = 0; i < caLen; i += 1) {
c = ca[i].replace(/^\s+/g, '');
if (c.indexOf(cookieName) === 0) {
return c.substring(cookieName.length, c.length);
}
}
return '';
}
public deleteCookie(name: string) {
this.setCookie(name, '', -1);
}
/**
* Expires default 1 day
* If params.session is set and true expires is not added
* If params.path is not set or value is not greater than 0 its default value will be root "/"
* Secure flag can be activated only with https implemented
* Examples of usage:
* {service instance}.setCookie({name:'token',value:'abcd12345', session:true }); <- This cookie will not expire
* {service instance}.setCookie({name:'userName',value:'John Doe', secure:true }); <- If page is not https then secure will not apply
* {service instance}.setCookie({name:'niceCar', value:'red', expireDays:10 }); <- For all this examples if path is not provided default will be root
*/
public setCookie(name: string, value: string, expireDays: number, path: string = '') {
const d: Date = new Date();
d.setTime(d.getTime() + expireDays * 24 * 60 * 60 * 1000);
const expires: string = 'expires=' + d.toUTCString();
document.cookie = name + '=' + value + '; ' + expires + (path.length > 0 ? '; path=' + path : '');
}
}
```
When I try to `console.log(this.CookieService.getCookie('cookienamehere');` the cookie does not get displayed and an empty string gets printed out instead... What happened? It used to work... The code has been mildly corrected to contain const and etc as you can see in the code. | 2020/08/18 | [
"https://Stackoverflow.com/questions/63467816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12360035/"
] | This is happening because you have used the float left on inner divs, whenever you use the float on the child, and if you do not clear it or used overflow: hidden on its parent, the inner items will not take the height,
just use overflow hidden on the parent or clear the float,
I would suggest you to use Display flex on parent and not float on child.
[Here is the pen.](https://codepen.io/atulraj89/pen/ZEWOmob)
```
.containerBigOverview{
margin: 3%;
padding-bottom: 0;
overflow: hidden;
background-color:red;
}
```
```css
.containerBigOverview{
margin: 3%;
padding-bottom: 0;
overflow: hidden;
background-color:red;
}
.containerOverview {
position: relative;
width: 31%;
margin: 1%;
float: left;
}
@media screen and (max-width: 500px) {
.containerOverview {
position: relative;
width: 100%;
width: 100%;
margin: 3%;
float: none;
}
}
.svg {
display: block;
width: 100%;
height: auto;
}
.overlay {
position: absolute;
bottom: 0;
left: 0;
right: 0;
background-color: rgb(176, 224, 230, 0.9);
overflow: hidden;
width: 100%;
height: 0;
transition: .5s ease;
}
.containerOverview:hover .overlay {
height: 50%;
}
.text {
color: white;
font-size: 20px;
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
text-align: center;
}
/* FOOTER */
footer {
width:100%;
background-color: #aaa;
color: white;
padding: 2%;
}
footer a{
text-decoration: none;
color:white;
padding: 1%;
}
```
```html
<div class="containerBigOverview">
<div class="containerOverview">
<svg width="10em" height="1oem" viewBox="0 0 16 16" class="bi bi-alarm-fill" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" d="M5.5.5A.5.5 0 0 1 6 0h4a.5.5 0 0 1 0 1H9v1.07a7.002 7.002 0 0 1 3.537 12.26l.817.816a.5.5 0 0 1-.708.708l-.924-.925A6.967 6.967 0 0 1 8 16a6.967 6.967 0 0 1-3.722-1.07l-.924.924a.5.5 0 0 1-.708-.708l.817-.816A7.002 7.002 0 0 1 7 2.07V1H5.999a.5.5 0 0 1-.5-.5zM.86 5.387A2.5 2.5 0 1 1 4.387 1.86 8.035 8.035 0 0 0 .86 5.387zM13.5 1c-.753 0-1.429.333-1.887.86a8.035 8.035 0 0 1 3.527 3.527A2.5 2.5 0 0 0 13.5 1zm-5 4a.5.5 0 0 0-1 0v3.882l-1.447 2.894a.5.5 0 1 0 .894.448l1.5-3A.5.5 0 0 0 8.5 9V5z"/>
</svg>
<div class="overlay">
<div class="text">Hello World</div>
</div>
</div>
<div class="containerOverview">
<svg width="10em" height="1oem" viewBox="0 0 16 16" class="bi bi-alarm-fill" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" d="M5.5.5A.5.5 0 0 1 6 0h4a.5.5 0 0 1 0 1H9v1.07a7.002 7.002 0 0 1 3.537 12.26l.817.816a.5.5 0 0 1-.708.708l-.924-.925A6.967 6.967 0 0 1 8 16a6.967 6.967 0 0 1-3.722-1.07l-.924.924a.5.5 0 0 1-.708-.708l.817-.816A7.002 7.002 0 0 1 7 2.07V1H5.999a.5.5 0 0 1-.5-.5zM.86 5.387A2.5 2.5 0 1 1 4.387 1.86 8.035 8.035 0 0 0 .86 5.387zM13.5 1c-.753 0-1.429.333-1.887.86a8.035 8.035 0 0 1 3.527 3.527A2.5 2.5 0 0 0 13.5 1zm-5 4a.5.5 0 0 0-1 0v3.882l-1.447 2.894a.5.5 0 1 0 .894.448l1.5-3A.5.5 0 0 0 8.5 9V5z"/>
</svg>
<div class="overlay">
<div class="text">Hello World 2</div>
</div>
</div>
<div class="containerOverview">
<svg width="10em" height="1oem" viewBox="0 0 16 16" class="bi bi-alarm-fill" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" d="M5.5.5A.5.5 0 0 1 6 0h4a.5.5 0 0 1 0 1H9v1.07a7.002 7.002 0 0 1 3.537 12.26l.817.816a.5.5 0 0 1-.708.708l-.924-.925A6.967 6.967 0 0 1 8 16a6.967 6.967 0 0 1-3.722-1.07l-.924.924a.5.5 0 0 1-.708-.708l.817-.816A7.002 7.002 0 0 1 7 2.07V1H5.999a.5.5 0 0 1-.5-.5zM.86 5.387A2.5 2.5 0 1 1 4.387 1.86 8.035 8.035 0 0 0 .86 5.387zM13.5 1c-.753 0-1.429.333-1.887.86a8.035 8.035 0 0 1 3.527 3.527A2.5 2.5 0 0 0 13.5 1zm-5 4a.5.5 0 0 0-1 0v3.882l-1.447 2.894a.5.5 0 1 0 .894.448l1.5-3A.5.5 0 0 0 8.5 9V5z"/>
</svg>
<div class="overlay">
<div class="text">Hello World 3</div>
</div>
</div>
</div>
<footer>
<a href="impressum.html"> Impressum </a>
<a href="datenschutz.html"> Datenschutz </a>
</footer>
``` | Instead of floating your 3 divs (.containerOverview) use `display: inline-block;`.
Voila
`Float` takes elements out of the flow (similar but not the same as `postion: absolute`), which means they have no effect on their parent, so parent's `height` is 0. |
319,970 | For some reason my CentOS VPS refuses all connections except for HTTP, SSH and Telnet. Whenever I try to connect to a port such as 25 (SMTP) or even a random port such as 225 I get a connection refused error :S
netstat -ap shows that the server is listening and iptables is turned off.
However I can interface with the same ports on the server through telnet...
```
# iptables -L
Chain INPUT (policy ACCEPT)
target prot opt source destination
Chain FORWARD (policy ACCEPT)
target prot opt source destination
Chain OUTPUT (policy ACCEPT)
target prot opt source destination
# netstat -an | fgrep LISTEN
tcp 0 0 0.0.0.0:25 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:225 0.0.0.0:* LISTEN
tcp 0 0 :::22 :::* LISTEN
tcp 0 0 :::80 :::* LISTEN
unix 2 [ ACC ] STREAM LISTENING 169786017 /tmp/.font-unix/fs7100
unix 2 [ ACC ] STREAM LISTENING 169786045 /var/run/saslauthd/mux
```
This is the error message i'm getting from my php script. My PHP script works fine with every other SMTP server I've come across
Warning: fsockopen() [function.fsockopen]: unable to connect to :25 (Connection refused) | 2011/10/09 | [
"https://serverfault.com/questions/319970",
"https://serverfault.com",
"https://serverfault.com/users/97335/"
] | It looks like there is something upstream of your VPS that is blocking access except for the ports noted. You should contact your VPS provider and ask them about it. | Okay, to make things clear - if you are running CentOS, chances are that you are at release 5 with sendmail as the default. In that case, you will not be to connect externally, because sendmail will only listen to localhost by default. To make it listen on the main IP, you will need to disable the line in /etc/sendmail.mc from this:
```
DAEMON_OPTIONS(`Port=smtp,Addr=127.0.0.1, Name=MTA')dnl
```
to this:
```
dnl DAEMON_OPTIONS(`Port=smtp,Addr=127.0.0.1, Name=MTA')dnl
```
Then rebuild sendmail.cf with the following:
```
/etc/mail/make
/etc/init.d/sendmail restart
```
(if it is postfix, it may be a different story. IIRC, postfix will only listen by default on localhost as well, so you will need to configure it as well to listen on the main IP).
HOWEVER, since you are just trying to test external connectivity, you may just need to install nc and then run it to listen to a specific. Here is my example:
```
[root@kvm0006 mail]# nc -l 50
```
Here I am listening on port 50 (hence, the -l). Now when I connect from outside the server on that port, I will get this:
```
yvaine:Downloads rilindo$ telnet 192.168.15.36 50
Trying 192.168.15.36...
Connected to kvm0006.monzell.com.
Escape character is '^]'.
Hello
```
Which will return the following on the server side:
```
[root@kvm0006 mail]# nc -l 50
Hello
```
To install nc:
```
yum -y install nc
``` |
14,648,062 | I am seeing a lot of code that explains how to centre a subview inside a view. The code examples typically go like this:
```
SubView.center = view.center;
```
Could someone explain to me how this works? I just don't get it.
The `view.center` gives the center point of the view. For example width is 100, height is 100, it will return (50,50). I get it.
Setting `subview.center` is weird to me. `subview.center` will return the center point of the subview. Somehow, setting it to (50,50) will position the subview within it's parent to coordinates of 50/50. But then accessing this property will return let's say (25,25) if the subview itself was width of 50 and height of 50.
Undestand what I mean? The concept here is weird to me as the setter and getter are doing different functions.
If someone could explain this please do. Or, if I am way off base I would like to know that too. I am new to iOS dev.
If I am correct and this is really the way it works, would you not consider this an anti-pattern. Certainly within .NET something like this would be an anti-pattern. Maybe not for Obj-C? | 2013/02/01 | [
"https://Stackoverflow.com/questions/14648062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1060500/"
] | So when setting it, it is setting it inside it's superview. When getting the subviews center it gives you the actual views center.
So half of 50 is 25, hence 25,25. You are wanting the subview's center not its parent's center so there is no reason for it to return its parent's center coordinates, just its own.
To be a bit more technical it has to related to Frame and Bounds of a view (the getter is getting the center by using the view's **bounds** and the setter is using the view's **frame**). [Here](https://stackoverflow.com/questions/1210047/cocoa-whats-the-difference-between-the-frame-and-the-bounds) is a link that describes what those are and how they are different. | The view.center gives the center point of the view *in the view's superviews coordinate space*. So it allows you to reposition a view within it's superview.
If you have a view size {100,100} and set it's center {200,200} - it's centerpoint will be positioned {200,200} from the origin of it's superview. Effectively it will be inset 150 points from the superview's origin.
Thus the view.center and view.bounds.width are not related to each other. But there *is* a relationship between view.center and view.frame.origin (which in the example will be {150,150}).
This allows you to fix the size and position of a view object either by using it's frame property or by setting it's center and bounds properties.
The center that you describe is not a property of the view, but can be got and set via {view.bounds.size.width/2,view.bounds.size.height/2}. |
142,086 | In the final scene Jack goes to the TET
>
> to blow it up.
>
>
>
The video has spoilers.
And when he gets there he is confronted with something that also looks like the TET with a huge red light in the middle. Jack refers to it as Sally and we are led to believe that this is who has been giving commands to them all this time.
[](https://i.stack.imgur.com/T4bQJ.jpg)
So we know it is a machine, but who or what made the TET and Sally? | 2016/10/03 | [
"https://scifi.stackexchange.com/questions/142086",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/65457/"
] | This was discussed by the film's Director in an interview for CinemaBlend. In short, the aliens who created the TET **are aboard the ship**, but as uploaded '***digital***' minds rather than as physical forms, that being the only way in which any crew could survive the immense amount of time that it takes to travel from star system to star system.
>
> **Q.** *We see the Tet at the end-- were there ever any creatures? Was it always that Borg voice?*
>
>
> **Joseph Kosinski:** *Y'know, I met with a group of scientists at the beginning of this project. My own belief, and the consensus among the
> scientists, was that if we ever actually encounter another intelligent
> life form, it will much more likely be in the way it is depicted in
> Oblivion than the way it's depicted in other science fiction films. It
> won't be some other bipedal creature. **The time required to travel
> the distances that exist between stars is so great that organic life
> forms aren't going to be able to survive the trip. Any hyper-advanced
> civilization that has the technology to do what the Tet does is going
> to be a deeply digital life form. We're ants on an ant hill,
> basically.***
>
>
> [Oblivion Spoilers: Director Joseph Kosinski Answers Your Burning
> Questions](http://www.cinemablend.com/new/Oblivion-Spoilers-Director-Joseph-Kosinski-Answers-Your-Burning-Questions-37271.html)
>
>
> | Unknown
=======
Spoilers. Duh.
At the start of the film Tom Cruise's character operates under the assumption that the Tet is a power station for humanity, relocated to Titan after an alien attack and invasion of Earth. The alien invaders, Scavs, are still on Earth and try to destroy the Tet. Sally is the mission controller for the Tet.
In the end it is revealed that the Scavs are what remains of humanity and that it was the Tet that is of alien origin and invaded Earth and killed most of humanity. Sally is an AI controlling/running the Tet. The reason for the invasion is never revealed, nor are the origins of the Tet or Sally. |
536,768 | I was trying to make a commutative diagram using something like `\arrow[r, "A"]` at some point, and I kept getting weird errors. I finally found out that I got no errors if I removed "dutch" from `\usepackage[dutch, english]`. Alternatively, I can get it to work by enclosing the tikzcd environment with `\shorthandoff{"}...\shorthandon{"}`. Apparently, something in "dutch" clashes with the use of " in `\arrow[r, "A"]`. Two questions.
* What is exactly the clash here? What is "predefined" or whatever in the dutch option in babel that does not like the use of "" in the arrow command?
* Is there a nicer solution to this problem? The only thing I can think of is to redefine the tikzcd environment to be something like
`\shorthandoff{"}\begin{tikzcd}...\end{tikzcd}\shorthandon{"}`
This is really just wrapping the earlier inelegant solution in a large blanket, so I'm not a fan.
Loading tikzlibrary{babel} solves the issue if one does not wrap the tikzcd in an align environment (and there is not a good reason to do this). I'm still curious what exactly align messes up here, though.
After all, a MWE. I do something like this.
```
\documentclass{report}
\usepackage[a4paper]{geometry}
\usepackage{libertine}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[dutch, english]{babel}
\usepackage{mathtools}
\usepackage{tikz}
\usetikzlibrary{cd}
\usetikzlibrary{babel}
\begin{document}
\begin{align*}
\begin{tikzcd}[ampersand replacement = \&]
A \arrow[r, "A"] \& B
\end{tikzcd}
\end{align*}
\end{document}
``` | 2020/04/04 | [
"https://tex.stackexchange.com/questions/536768",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/91138/"
] | First some general words. We invite to present the question with a minimal example of code for several reasons:
* often the question is presented with no hint about the actual error message(s);
* preparing a MWE sometimes helps in spotting the error or in finding a workaround;
* it's kind to whoever wants to help.
More specific to your post, you probably had *two* sources for errors. One due to `babel` making `"` active for Dutch, the other one because of using `tikzcd` inside an `align` environment.
Solution for the first problem: `\usetikzlibrary{babel}`.
Solution for the second problem: use the `ampersand replacement=\&` option and `\&` in the body of `tikzcd` to mark column delimiters. But also `\shorthandoff{"}` and `\shorthandon{"}`.
Why is that? Because `align` (and the other `amsmath` display environments) absorb the contents as the argument to a macro and so `tikzcd` cannot do the trick it usually does to `&`. Neither it can do the job for `"`.
If you're used to generally employ `align` or `align*` for single equation (or diagram), change your habit and use `equation` or `equation*` in these cases. It's semantically sounder, more efficient and avoids doing some tricks. Moreover, the spacing is better. I guess you can spot below the difference in spacing, which is excessive with `align*`.
```latex
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[dutch, english]{babel}
\usepackage{mathtools}
\usepackage{tikz-cd}
\usetikzlibrary{babel}
\usepackage{lipsum} % for mock text
\begin{document}
\lipsum[2][1-2]
\begin{equation*}
\begin{tikzcd}
A \arrow[r, "A"] & B
\end{tikzcd}
\end{equation*}
\lipsum[2][1-2]
\shorthandoff{"}\begin{align*}
\begin{tikzcd}[ampersand replacement = \&]
A \arrow[r, "A"] \& B
\end{tikzcd}
\end{align*}\shorthandon{"}%
\lipsum[3]
\end{document}
```
[](https://i.stack.imgur.com/o0Axw.png) | My answer is off-topic with the tags I hope to have understood your request. I have used `xy` package without the hard tip arrows with the options `[all,cmtip]` leaving your babel `\usepackage[dutch]{babel}`.
PS: I have only thinked an alternative.
```
\documentclass[a4paper,12pt]{article}
\usepackage[a4paper]{geometry}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[dutch,english]{babel}
\usepackage{mathtools}
\usepackage[all,cmtip]{xy}
\begin{document}
One morning, when Gregor Samsa woke from troubled dreams, he found himself transformed in his bed into a horrible vermin. He lay on his armour-like back, and if he lifted his head a little he could see his brown belly, slightly domed and divided by arches into stiff sections.
\begin{align*}
\xymatrix@1{
A\ar[r]^A & B}
\end{align*}
The bedding was hardly able to cover it and seemed ready to slide off any moment.
\begin{align*}
\xymatrix@1{
A\ar[r]^A & B}
\end{align*}
Gregor then turned to look out the window at the dull weather. Drops
\end{document}
```
[](https://i.stack.imgur.com/GlQ45.png) |
13,366,708 | I just read this article <http://javascriptweblog.wordpress.com/2011/05/31/a-fresh-look-at-javascript-mixins/>.
In the section entitled "#4 Adding Caching" it says:
>
> By forming a closure around the mixins we can cache the results of the initial definition run and the performance implications are outstanding.
>
>
>
I don't understand how this works-- how does using the module pattern here lead to a faster/cached version of the code? | 2012/11/13 | [
"https://Stackoverflow.com/questions/13366708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/94958/"
] | basically, without using the closure, the mixin function will be created every
time the mixin is used. By creating a closure, each of the function will be
created once, and the mixin will reference those functions every time it is
called. Since the mixin doesn't have to recreate those functions every time it
runs, its faster.
**without the closure**
```
var asRectangle = function() {
// every time this function is called, these three functions are created
// from scratch, slowing down execution time
this.area = function() {
return this.length * this.width;
}
this.grow = function() {
this.length++, this.width++;
}
this.shrink = function() {
this.length--, this.width--;
}
})();
```
**with the closure**
```
var asRectangle = (function() {
// these functions are 'cached' in the closure
function area() {
return this.length * this.width;
}
function grow() {
this.length++, this.width++;
}
function shrink() {
this.length--, this.width--;
}
// this function is set to asRectangle. it references the above functions
// every time it is called without having to create new ones
return function() {
this.area = area;
this.grow = grow;
this.shrink = shrink;
return this;
};
})();
``` | In the second case only this code is executed: upon applying the mixin:
```
this.area = area;
this.grow = grow;
this.shrink = shrink;
return this;
```
While in the first case `area`,`grow`, and `shrink` are redefined for each and every `asXXX` call. The definition of the methods and their caching is done at "parsing" time of the mixin declaration in the second case and thus needs to be done only once. |
30,093,115 | So every time I make a website, I have issues with the footer. Now, after some googling, I found the following:
<http://getbootstrap.com/examples/sticky-footer/>
I tried to apply it, but it didn't really work out... Instead of the footer staying in the bottom of the page, it just sticks at the bottom of my screen.
This is where the footer sticks:

That is, when I fully scroll to the top of the page, the bottom of google chrome's display on my mac.
This is the HTML I use:
```
<body>
<div id="wrapper">
<!-- A lot of content -->
</div>
<footer>
</footer>
</body>
```
And the CSS:
```
html {
box-sizing: border-box;
height: 100%;
}
body {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
overflow-x: hidden;
background: url(../img/bg.png);
}
#wrapper {
min-height: 100%;
height: auto;
margin: 0 auto -60px;
padding: 0,0,60px;
}
footer {
background-color: #292929;
position: absolute;
bottom: 0;
width: 100%;
height: 60px;
}
```
So how is it that this footer confuses the bottom of my screen with the bottom of my page?
Thanks. | 2015/05/07 | [
"https://Stackoverflow.com/questions/30093115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3216434/"
] | Your oncreateview should be like below:
```
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_find_people, container, false);
listView = (ListView)rootView.findViewById(R.id.card_listView);
listView.addHeaderView(new View(this));
listView.addFooterView(new View(this));
cardArrayAdapter = new CardArrayAdapter(getApplicationContext(), R.layout.list_item_card);
for (int i = 0; i < 10; i++) {
Card card = new Card("Card " + (i+1) + " Line 1", "Card " + (i+1) + " Line 2");
cardArrayAdapter.add(card);
}
listView.setAdapter(cardArrayAdapter);
return rootView;
}
``` | Fragment does not have findViewById(). You have to use View object to access that method in Fragment (In your case "rootView"). If you are using Activity than you can directly use findViewById() because Activity have that method.
Update your a line in your code as below, it will make it working.
```
listView = (ListView)rootView.findViewById(R.id.card_listView);
```
At end of onCreateView() add below line.
```
return rootView;
``` |
7,711,068 | >
> **Possible Duplicate:**
>
> [separating keys and objects from NSMutable dictionary and use the values in insert command of sqlite](https://stackoverflow.com/questions/5677396/separating-keys-and-objects-from-nsmutable-dictionary-and-use-the-values-in-inser)
>
>
>
I have an NSDictionary containing parsed JSON data. How can I push these data to a database so that I can extract them from database for further use?
I am using SBJSON for parsing. | 2011/10/10 | [
"https://Stackoverflow.com/questions/7711068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/970668/"
] | If your design requirements specify sqlite, then I would recommend using Gus Mueller's [FMDB](https://github.com/ccgus/fmdb) so that you do not have to work directly with raw sqlite.
```
NSString $title = [jsonDictionary objectForKey:@"title"];
// other keys, values, etc...
NSString $query = [NSString stringWithFormat:@"INSERT INTO myTable t (t.some_column) VALUES ('%@'),$title];
FMResultSet *results = [_db executeQuery:$query];
```
That said, as Chris said above, Core Data is often a better solution than sqlite. Brent Simmons (NetNewsWire developer) has a series of posts about this subject, like [this one.](http://inessential.com/2011/09/22/core_data_revisited)
The exception to the "Core Data is better than sqlite" mantra for me is the situation where you want to provide initial data but do not want to perform an initial import into Core Data. | Following code goes to create the dynamic plist file and that file stores into the bundle and that data can be access and the insert the data into the .plist file.
```
NSString *strPathToAudioCache=[NSString stringWithFormat:@"%@/%@",
[(NSArray*)NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0],
@"data.plist"];
NSMutableDictionary *dOfAudios=[NSMutableDictionary dictionaryWithContentsOfFile:strPathToAudioCache];
NSLog([dOfAudios allKeys].count>0?@"Value is exist":@"Value is not exist");
if([dOfAudios allKeys].count>0) {
[dOfAudios setValue:@"Key_for_value" forKey:@"value_for_key"];
} else {
dOfAudios=[NSMutableDictionary dictionary];
[dOfAudios setValue:@"Key_for_value" forKey:@"value_for_key"];
}
[dOfAudios writeToFile:strPathToAudioCache atomically:YES];
``` |
61,238,773 | I’m using SwfitUI in my project and I have a NavigationView and List. I’m clicking cell after open the detail view and click navigation back button. I want to remove view (it’s struct, in SwiftUI) after click navigation back button. Because if I click the same cell or button again, it isn’t initialize new view, it’s shows old view. I want to do refresh this view. How do I do?
My FirstView Struct is:
```
struct FirstView: View {
@ObservedObject var viewModel: FirstViewModel
var body: some View {
List(self.viewModel.objects, id: \.id) { object in
ZStack {
DetailViewCell(object: object)
NavigationLink(destination: DetailViewBuilder.make(object)) {
EmptyView()
}.buttonStyle(PlainButtonStyle())
}
}
}
}
```
My DetailView Struct is:
```
struct DetailView: View {
@ObservedObject var viewModel: DetailViewModel
var body: some View {
ZStack(alignment: .top) {
Color.mainBackground.edgesIgnoringSafeArea(.all)
VStack {
ZStack {
Image("Square")
Image(self.viewModel.currentImage)
}
Text(self.viewModel.currentText)
.padding()
.frame(alignment: .center)
.minimumScaleFactor(0.1)
Spacer()
Button(action: {
self.viewModel.pressedPlayOrPauseButton()
}, label: {
Image(self.viewModel.isPlaying ? "Pause" : "Play").foregroundColor(Color("Orange"))
}).padding()
}
}
}
}
```
First of all, I go to the detail by clicking a cell in FirstView. Then I come back with the back button. I click on a cell again to go to the details, but a new view does not open. It shows the old view.
Before I forget, My Builder Class is:
```
final class DetailViewBuilder {
static func make(object: Something) -> DetailView {
let viewModel = DetailViewModel(object: object)
let view = DetailView(viewModel: viewModel)
return view
}
}
```
Note: If I will use Sheet Presented, It's working. It's creating new View. But I want to use NavigationLink. Thank you. | 2020/04/15 | [
"https://Stackoverflow.com/questions/61238773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3215402/"
] | You just need to defer your destination creation in your builder, and the `@ViewBuilder` is a good instrument for this.
It can be used the following wrapper for to create real destination only in when `body` will be rendered (ie. explicitly in time of navigation clicked in your case)
Tested with Xcode 11.4 / iOS 13.4
```
struct DeferView<Content: View>: View {
let content: () -> Content
init(@ViewBuilder _ content: @escaping () -> Content) {
self.content = content
}
var body: some View {
content() // << everything is created here
}
}
```
and now your builder
```
final class DetailViewBuilder {
static func make(object: Something) -> some View {
DeferView {
DetailView(viewModel: DetailViewModel(object: object))
}
}
}
``` | SwiftUI initialises `NavigationView` links eagerly, so you can't rely on their initialiser to run every time. If you write a custom init() for DetailView
```
init(viewModel: DetailViewModel) {
self.viewModel = viewModel
print("Initialising \(self)")
}
```
you'll see the line print out for every navigation link when your FirstView loads.
Depending on what you want to do you could implement a `.onAppear {}` closure on the DetailView which will change the data when the view appears. It's a little tricky to try to offer implementation examples since I'm unsure what your goal here is specifically.
There's some interesting discussion of this at:
<https://www.notion.so/Lazy-Loading-Data-with-SwiftUI-and-Combine-70546ec6aca3481f80d104cd1f10a31a>
Do any of the suggestions here look like they could be relevant to what you're trying to do? |
22,843,734 | I wanna ask about little tricky javascript, this is about if/else if/else question.
I want make question about 'YES' or 'NO', this is the logic : If question1 is 'yes' and question2 is 'yes' and question3 is 'NO' the result is 'good', and if question1 is 'yes' and question2 is 'no' and question3 is 'yes'the result is 'not good'. I was make the code for this case but not working properly, this is my codes, i use checkbox in html for choice answers :
javascript
```
<script type="text/javascript">
var question1 = document.getElementById("a");
question2 = document.getElementById("b");
question3 = document.getElementById("c");
answer1 = document.getElementById("d");
answer2 = document.getElementById("e");
answer3 = document.getElementById("f");
answer4 = document.getElementById("g");
answer5 = document.getElementById("h");
answer6 = document.getElementById("i");
function TheResult(form){
if(question1 == answer1 && question2 == answer3 && question3 == answer6 ){
document.write('good');
}else if(question1 == answer1 && question2 == answer4 && question3 == answer5 ){
document.write('not good');
}else {
document.write('ERROR');
}
}
```
html
```
<form>
<p id = "a"><b>Question1</b></p>
<input type="checkbox" name="a1" value="YES" id = "d">YES
<input type="checkbox" name="a1" value="NO" id = "e">NO<br><br>
<p id = "b"><b>Question2</b></p>
<input type="checkbox" name="a2" value="YES" id = "f" >YES
<input type="checkbox" name="a2" value="NO" id = "g" >NO<br><br>
<p id = "c"><b>Question3</b></p>
<input type="checkbox" name="a3" value="YES" id = "h">YES
<input type="checkbox" name="a3" value="NO" id = "i">NO<br><br>
<input type="button" name="Submit" value="Result" style="margin-left:100px;" onClick="TheResult(this.form)" >
</form>
```
my codes always print out 'good' in every situation, please help. | 2014/04/03 | [
"https://Stackoverflow.com/questions/22843734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3492238/"
] | I'm actually pretty confused by the logic that you're presenting. As many have pointed out, you're trying to compare elements against each other. This won't give you the result that you want. You'll want to use `.innerHTML` or `.value` depending on the element type.
The next problem that I see is that your HTML structure, the Questions & Answers aren't associated with each other in any way.
Another problem I see comes when you are declaring your JS variables. You're trying to chain your declarations, which is fine. Although you need to be using `,` instead of `;`. The `;` should only be on the last one to be declared.
I assume most of these problems just came from you giving us some sample code. I expect your real code doesn't look like this, or you'd be having other problems noted in your question.
Regardless, I have a solution for you. I rewrote it in a way that makes more sense to me:
**[View Demo Here - JSFiddle](http://jsfiddle.net/enigmarm/9Z6jf/1/)**
HTML:
```
<form>
<label for="a1" id="a">Question 1</label>
<input type="radio" name="a1" value="YES" id="d">YES
<input type="radio" name="a1" value="NO" id="e">NO
<br>
<br>
<label for="a2" id="b">Question 2</label>
<input type="radio" name="a2" value="YES" id="f">YES
<input type="radio" name="a2" value="NO" id="g">NO
<br>
<br>
<label for="a3" id="c">Question 3</label>
<input type="radio" name="a3" value="YES" id="h">YES
<input type="radio" name="a3" value="NO" id="i">NO
<br>
<br>
<input type="button" name="Submit" value="Result" style="margin-left:100px;" onClick="theResult()">
</form>
```
I made 2 changes. I got rid of the `<p>` elements in favor of `<label>`. And then I changed the checkboxes to radio buttons.
The JS
```
function theResult(){
var inputs = document.getElementsByTagName('input');
var question = [ {selected: '', expected: 'YES'},
{selected: '', expected: 'YES'},
{selected: '', expected: 'NO'}
];
var tmpSelected = [];
for(var i = 0; i < inputs.length; i++){
var tmp = inputs[i];
if(tmp.type == 'radio' && tmp.checked){
tmpSelected.push(tmp.value);
}
}
for(var i = 0; i < tmpSelected.length; i++){
question[i].selected = tmpSelected[i];
}
validateResults(question);
};
function validateResults(results){
var status = '';
for(var i = 0; i < results.length; i++){
if(results[i].selected != results[i].expected){
status = 'Not Good'
break;
} else {
status = 'Good';
}
}
console.log(status);
return status;
}
```
As you can see, I've made a lot of changes to this one. I wanted to make a better mapping between selected answer & the expected.
* We then go through and grab all the inputs on the page. In the first loop, we make sure that we're only accepting `radio` buttons & only looking at the ones that have been `checked` or selected. We stuff those off into an array `tmpSelected` for a bit.
* Then we assign the values of `tmpSelected` to our `question` object, specifically to `.selected`. This will make it easy to compare against the expected answer.
* Then we'll make a call to a different function to validate the results (this logic could've been kept in the previous function, I just like splitting things up a bit to make them more modular).
* the `validateResults()` simple compares `.selected` with `.expected`. If they don't match, we `break` our loop and return the `status` of `'Not Good'`. Otherwise we keep evaluating. I did it this way because it seemed like your code was just returning a success/failure type message, and not necessarily saying which answers were incorrect.
The results are correctly logged to the console. So you'd just need to change that back to your `document.write()`. | Try using this in each case:
```
var question1 = document.getElementById("a").innerHTML;
var answer1 = document.getElementById("d").innerHTML;
if(question1 == answer1 ){
document.write('good');
}
```
Start simple and build up. |
3,456,758 | When I add a .dll file as a reference in C# application it shows an error :
>
> A reference to the "....dll" could not be added.Please make sure that
> the file is accessible and that it is a valid assembly or COM
> component.
>
>
>
ILDissassembler says there is no valid CLR header so I try to register it using regsvr32 and that gives me another error:
>
> The module "" was loaded but the call to DLLRegisterServer failed with
> error code '0x80004005'
>
>
>
I am using VS2010 ultimate version on a 64bit Windows 7 machine. What could be the problem?
Thanks for any hints/replies | 2010/08/11 | [
"https://Stackoverflow.com/questions/3456758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20358/"
] | I just ran into that issue and after all the explanations about fixing it with command prompt I found that if you add it directly to the project you can then simply include the library on each page that it's needed | I needed to change architecture to x86 from x64 in configuration manager and copy my 32 bit dll (C language - pcProxAPI.dll) into new folder this created.. This is on top of the steps described by "Sashus" [below](https://stackoverflow.com/a/36566032/3254405).
C:\Projects..\bin\x86\Debug |
690,748 | Is there a way to cast objects in objective-c much like the way objects are cast in VB.NET?
For example, I am trying to do the following:
```
// create the view controller for the selected item
FieldEditViewController *myEditController;
switch (selectedItemTypeID) {
case 3:
myEditController = [[SelectionListViewController alloc] init];
myEditController.list = listOfItems;
break;
case 4:
// set myEditController to a diff view controller
break;
}
// load the view
[self.navigationController pushViewController:myEditController animated:YES];
[myEditController release];
```
However I am getting a compiler error since the 'list' property exists in the SelectionListViewController class but not on the FieldEditViewController even though SelectionListViewController inherits from FieldEditViewController.
This makes sense, but is there a way to cast myEditController to a SelectionListViewController so I can access the 'list' property?
For example in VB.NET I would do:
```
CType(myEditController, SelectionListViewController).list = listOfItems
```
Thanks for the help! | 2009/03/27 | [
"https://Stackoverflow.com/questions/690748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83724/"
] | Typecasting in Objective-C is easy as:
```
NSArray *threeViews = @[[UIView new], [UIView new], [UIView new]];
UIView *firstView = (UIView *)threeViews[0];
```
However, what happens if first object is not `UIView` and you try to use it:
```
NSArray *threeViews = @[[NSNumber new], [UIView new], [UIView new]];
UIView *firstView = (UIView *)threeViews[0];
CGRect firstViewFrame = firstView.frame; // CRASH!
```
It will crash. And it's easy to find such crash for this case, but what if those lines are in different classes and the third line is executed only once in 100 cases. I bet your customers find this crash, not you! A plausible solution is to [crash early](https://pragprog.com/the-pragmatic-programmer/extracts/tips), like this:
```
UIView *firstView = (UIView *)threeViews[0];
NSAssert([firstView isKindOfClass:[UIView class]], @"firstView is not UIView");
```
Those assertions doesn't look very nice, so we could improve them with this handy category:
```
@interface NSObject (TypecastWithAssertion)
+ (instancetype)typecastWithAssertion:(id)object;
@end
@implementation NSObject (TypecastWithAssertion)
+ (instancetype)typecastWithAssertion:(id)object {
if (object != nil)
NSAssert([object isKindOfClass:[self class]], @"Object %@ is not kind of class %@", object, NSStringFromClass([self class]));
return object;
}
@end
```
This is *much* better:
```
UIView *firstView = [UIView typecastWithAssertion:[threeViews[0]];
```
P.S. For collections type safety Xcode 7 have a much better than typecasting - [generics](https://stackoverflow.com/questions/848641/are-there-strongly-typed-collections-in-objective-c) | Sure, the syntax is exactly the same as C - `NewObj* pNew = (NewObj*)oldObj;`
In this situation you may wish to consider supplying this list as a parameter to the constructor, something like:
```
// SelectionListViewController
-(id) initWith:(SomeListClass*)anItemList
{
self = [super init];
if ( self ) {
[self setList: anItemList];
}
return self;
}
```
Then use it like this:
```
myEditController = [[SelectionListViewController alloc] initWith: listOfItems];
``` |
32,502,077 | I am building an application in Xamarin.Forms, on the iOS app I want the status bar color to be white. Here is what I have so far:
**App.cs**
```
public App()
{
NavigationPage _navigationPage = new NavigationPage(new RootPage());
MainPage = _navigationPage;
}
``` | 2015/09/10 | [
"https://Stackoverflow.com/questions/32502077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3571997/"
] | After a recent Xamarin update you are now able to do this by setting the BarTextColorProperty,
`_navigationPage.SetValue(NavigationPage.BarTextColorProperty, Color.White);`
However just like in [pvnak's answer](https://stackoverflow.com/a/32512897/3571997) you still need to add the following to your Info.plist
* Property: `UIViewControllerBasedStatusBarAppearance`
* Type: `boolean`
* Value: `No` | globaly change status bar text color and background color for ios
in App.xaml.cs:
```
var page = new NavigationPage(new MainPage()) { BarTextColor = Color.White };
```
in Info.plist:
```
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
```
and changing background color
in AppDelegate.cs => override bool FinishedLaunching(...):
```
var statusBar = UIApplication.SharedApplication.ValueForKey(new NSString("statusBar")) as UIView;
if (statusBar.RespondsToSelector(new ObjCRuntime.Selector("setBackgroundColor:")))
{
statusBar.BackgroundColor = UIColor.Black;
}
```
and set padding top = 20 on every page |
258,532 | Yesterday my daughter watched me acting on my favorite SE site. She essentially said:
>
> *"Hey, that's cool. Can you recommend me a me a site there, where I could go to with my bunch of questions I have to ask?"*
>
>
>
I admittedly had to deny her going here, since
1. She's going to get 12 that month (IIRC minimum age to legally
participate at SE is 13, correct me if I'm wrong)
2. Her english skills aren't well developed enough, to participate in internationally aimed sites
I've done more research then later and found [this beautiful site](http://www.br-online.de/kinder/fragen-verstehen/wissen/)1, specifically designed for children's questions.
They're controlling more questions, and missing topics coming in from the interested children via e-mail.
I appreciate this model somehow, since (vs. a forum or SE), it's moderated by adults, and directed e-mail channels.
Though *adults* have their "blinders" strapped on, and may totally miss the question.
Also it keeps the kids safe from any totally off question attends of pedophile nature or such.
---
I've been infected now with the thought, if it would be possible to make up a site using the SE engine, that is specifically designed for
* childrens asking
* mainly children answering
* decent moderation by adults, merely keeping them safe
* probably language specific, since we can't expect children to be familiar with english to ask well formed questions
I know it's kind of opinion based, but could you imagine one goes well and have the right controls at hand, to set up such kind of sites with SE (in Area51)?
---
As @Oded and others confirmed the point, that it generally wouldn't be legal for children younger than 13, besides parent's explicit agreement, which apparently can't be managed properly,
BREATHE
I still think that +13 year aged teens till at least 16 need to be treated as **children**, and it would be a good idea to give them protection level moderated sites.
---
1)Sorry it's in german, and that's also part of the question somehow. But I'd suppose everyone else here might be intelligent enough to extrapolate this for their native languages. | 2015/06/11 | [
"https://meta.stackexchange.com/questions/258532",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/186472/"
] | I can see a few problems with this idea, although not *bad*, it would need *a lot* of thought if it was going to be successful.
The main problems:
* What would the site scope be?
Stack Exchange isn't going to change it's model to let children ask and answer questions - so there would need to be a *well-defined scope* stating what's on-topic and what's off-topic
* [Data Protection Laws](https://meta.stackexchange.com/a/258533/260841)
* Would children be able to answer all questions?
This, again links back to scope - what would the children ask? And would other children know about this? Will they be able to provide *high quality answers*? Because, again SE will always want sites with high quality posts and they probably won't make a site that doesn't do that
* Why would the moderators monitor the site if adults are not really *supposed* to answer
This sounds a bit weird - but mods on sites are mods because they are enthusiastic about the *topic* the site talks about and because they want to help the site prosper - will they really *want* to be mods to a site where they can't gain knowledge relevant to them?
So, I don't think the SE platform is fit for this kind of site! Sorry! | What's wrong with just letting 13-16 yo participate on regular sites? I'm not sure why they need a specific site just for them.
1. Many under-18 year olds participate successfully on SE sites, so it's not like they are excluded from regular sites.
2. I don't think moderation is an issue: Stack Exchange is relatively safe and professional, even when compared to sites dedicated solely to children.
3. The whole point in anyone participating in Stack Exchange is to learn things. Wouldn't teenagers learn more from experienced adults than from other teenagers? |
598,436 | Does asynchronous call always create a new thread?
Example:
If JavaScript is single threaded then how can it do an async postback? Is it actually blocking until it gets a callback? If so, is this really an async call? | 2009/02/28 | [
"https://Stackoverflow.com/questions/598436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40118/"
] | The Javascript model is *single-threaded*. An asynchronous call is *not* a new thread, but rather interrupts an existing thread. It's analogous to interrupts in a kernel.
Yes it makes sense to have asynchronous calls with a single thread. Here's how to think about it: When you call a function within a single thread, the state for the current method is pushed onto a stack (i.e. local variables). The subroutine is invoked and eventually returns, at which time the original state is popped off the stack.
With an asynchronous callback, the same thing happens! The difference is that the subroutine is invoked by the system, not by the current code invoking a subroutine. | A couple notes about JavaScript in particular:
`XMLHttpRequest`s are non-blocking by default. The `send()` method returns immediately after the request has been relayed to the underlying network stack. A response from the server will schedule an invocation of your callback on the event loop as discussed by the other excellent answers.
This does not require a new thread. The underlying socket API is selectable, similar to [`java.nio.channels`](http://java.sun.com/javase/6/docs/api/java/nio/channels/package-summary.html) in Java.
It's possible to construct *synchronous* `XMLHttpRequest` objects by passing `false` as the third parameter to [`open()`](https://developer.mozilla.org/en/XMLHttpRequest#open()). This will cause the `send()` method to block until a response has been received from the server, thus placing the event loop at the mercy of network latency and potentially hanging the browser until network timeout. This is a Bad Thing™.
Firefox 3.5 will introduce honest-to-god multithreaded JavaScript with the [`Worker`](https://developer.mozilla.org/En/Using_web_workers) class. The background code runs in a completely separate environment and communicates with the browser window by scheduling callbacks on the event loop. |
23,574,264 | If a parent control asks its children "How big do you want to be?", then what use is the availableSize parameter that's passed along? I've taken a peek via Reflector into the StackPanel's source and I still can't figure it out.
If the child wants to be 150x30, then it still reports 150x30 even if availableSize is 100x20, doesn't it? And if the child is expected to constrain itself to the availableSize, then that might as well be done on the size that's returned from calling MeasureOverride on the child - no point in passing that parameter.
Is there something that I'm not taking into account? | 2014/05/09 | [
"https://Stackoverflow.com/questions/23574264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/532501/"
] | >
> If the child wants to be 150x30, then it still reports 150x30 even if availableSize is 100x20, doesn't it?
>
>
>
It depends on the control, but generally the answer is no. In any case, the point is to give it the opportunity to fit itself to the container, but it is not required to do so.
Think about the difference between a Grid and a StackPanel. The Grid will typically size itself precisely to the available size. The StackPanel, by contrast, will size itself infinitely in one direction only (depending on its orientation), regardless of the available size. In the other direction, it will extend itself only as far as the space needed for its children, unless its "HorizontalAlignment" / "VerticalAlignment" is set to "Stretch", in which case it will stretch itself out to the available size in that direction.
The [ViewBox](http://msdn.microsoft.com/en-us/library/system.windows.controls.viewbox.aspx) is a more complex example that makes good use of "availableSize". It generally sizes itself to the available space, and scales/stretches its children depending on the values of "Stretch" and "StretchDirection". | The point is to give the element the opportunity to size itself correctly. After all the parent control might clip it if it doesn't respect the available size. |
10,914,245 | From my code, I call an SP using:
```
using (var cmd = new SqlCommand("sp_getnotes"))
{
cmd.Parameters.Add("@ndate", SqlDbType.SmallDateTime).Value
= Convert.ToDateTime(txtChosenDate.Text);
cmd.CommandType = commandType;
cmd.Connection = conn;
var dSet = new DataSet();
using (var adapter = new SqlDataAdapter { SelectCommand = cmd })
{
adapter.Fill(dSet, "ntable");
}
}
```
The Stored Procedure itself runs a simple query:
```
SELECT * FROM tblNotes WHERE DateAdded = @ndate
```
The problem is no records are returned! `DateAdded` is a `smalldatetime` column.
When I change the query to the following, it works:
```
SELECT * FROM tblNotes WHERE CONVERT(DATETIME, FLOOR(CONVERT(FLOAT, DateAdded))) = @ndate
```
Why is this happening? This change affects the entire application and I'd like to find the root cause before getting into changing every single query... The only changes we made are to use parameterized queries and upgrade from SQL Server 2005 to 2008.
TIA. | 2012/06/06 | [
"https://Stackoverflow.com/questions/10914245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/131992/"
] | `smalldatetime` has a time portion which needs to match as well.
Use this:
```
SELECT *
FROM tblNotes
WHERE dateAdded >= CAST(@ndate AS DATE)
AND dateAdded < DATEADD(day, 1, CAST(@ndate AS DATE))
```
`SQL Server 2008` and above also let you use this:
```
SELECT *
FROM tblNotes
WHERE CAST(dateAdded AS DATE) = CAST(@ndate AS DATE)
```
efficiently, with the transformation to a range performed by the optimizer. | SQL Server 2008 now has a DATE data type, which doesn't keep the time porttion like SMALLDATETIME does. If you can't change the data type of the column, then you'll have to truncate when doing the compare, or simply cast to DATE:
```
SELECT *
FROM tblNotes
WHERE cast(dateAdded as date) = @ndate
``` |
63,787,476 | I try create a function with a loop for inside. The script work without function but declare the python function don't work. (The original script is is more longer but with this part i think the is enough)
```
import numpy as np
import math as mt
from sympy import*
import fractions
init_printing(use_latex='mathjax')
PHnumbers=4
PHnumbers2=2
statetype= 1
for d in range(1,9):
modes=d+1
if statetype==1:
comb=modes
elif statetype==2:
comb=int((modes*(modes+1))/2)
exec(f'Phases{d}=[]'), exec(f'Phasesv{d}=[]')
for i in range(modes):
exec(f'theta_{i+1}= symbols(\'theta_{i+1}\', real=True)')
exec(f'Phases{d}.append(globals()[\'\'.join([\'theta_\',str(i+1)])])')
exec(f'Phasesv{d}.append(globals()[\'\'.join([\'theta_\',str(i+1)])])')
exec(f'v{i+1}=[[0]]*modes')
exec(f'Phasesv{d}[0]*=0')
for i in range(modes):
exec(f'globals()[\'\'.join([\'v\',str(i+1)])][i]=[PHnumbers*diff(Phasesv{d}[i],Phases{d}[i])]')
conteo = d
for j in range(modes):
for i in range(modes):
if j<i:
conteo = conteo + 1
exec(f'v{conteo+1}=[[0]]*modes')
exec(f'globals()[\'\'.join([\'v\',str(conteo+1)])][i]=[PHnumbers2*diff(Phasesv{d}[i],Phases{d}[i])]')
exec(f'globals()[\'\'.join([\'v\',str(conteo+1)])][j]=[PHnumbers2*diff(Phasesv{d}[j],Phases{d}[j])]')
exec(f'Vec{d}=[]'),exec(f'Coeff{d}=[]'), exec(f'Nii{d}=[]'), exec(f'Nij{d}=[]')
for i in range(comb):
exec(f'Vec{d}.append(globals()[\'\'.join([\'v\',str(i+1)])])')
```
for i in range(len(Vec4)):
print(Vec4[i])
The previous script work, no problems up to here. Now I declare python function:
```
def metro(PHnumbers):
statetype=1
PHnumbers2=2
for d in range(1,9):
modes=d+1
if statetype==1:
comb=modes
elif statetype==2:
comb=int((modes*(modes+1))/2)
exec(f'Phases{d}=[]'), exec(f'Phasesv{d}=[]')
for i in range(modes):
exec(f'theta_{i+1}= symbols(\'theta_{i+1}\', real=True)')
exec(f'Phases{d}.append(globals()[\'\'.join([\'theta_\',str(i+1)])])')
exec(f'Phasesv{d}.append(globals()[\'\'.join([\'theta_\',str(i+1)])])')
exec(f'v{i+1}=[[0]]*modes')
exec(f'Phasesv{d}[0]*=0')
for i in range(modes):
exec(f'globals()[\'\'.join([\'v\',str(i+1)])][i]=[PHnumbers*diff(Phasesv{d}[i],Phases{d}[i])]')
conteo = d
for j in range(modes):
for i in range(modes):
if j<i:
conteo = conteo + 1
exec(f'v{conteo+1}=[[0]]*modes')
exec(f'globals()[\'\'.join([\'v\',str(conteo+1)])][i]=[PHnumbers2*diff(Phasesv{d}[i],Phases{d}[i])]')
exec(f'globals()[\'\'.join([\'v\',str(conteo+1)])][j]=[PHnumbers2*diff(Phasesv{d}[j],Phases{d}[j])]')
exec(f'Vec{d}=[]'),exec(f'Coeff{d}=[]'), exec(f'Nii{d}=[]'), exec(f'Nij{d}=[]')
for i in range(comb):
exec(f'Vec{d}.append(globals()[\'\'.join([\'v\',str(i+1)])])')
for i in range(len(Vec4)):
print(Vec4[i])
```
The second code show problem: 'theta\_1 is not defined' | 2020/09/08 | [
"https://Stackoverflow.com/questions/63787476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13803655/"
] | You can look at the [subprocess](https://docs.python.org/3/library/subprocess.html) library in Python
You must pass the argument as a string. Then you can convert it back in your R script
**Python**:
```
import subprocess
i = 0
with open(result_filename, 'a') as result:
output = subprocess.run(['Rscript', 'RScriptWeeklyActives.R', str(i)], stdout=result)
```
**R**:
```
#! /usr/bin/Rscript
args = commandArgs(trailingOnly=TRUE)
i = strtoi(args[1])
print(i)
print(3)
``` | Use [Subprocess](https://docs.python.org/3/library/subprocess.html#subprocess.Popen)
```
import subprocess
i = 0
with open(result_filename, 'a') as result:
command = subprocess.Popen(['Rscript', 'RScriptWeeklyActives.R', 'i'], stdout=result)
```
Rscript will get value 0 as a string you have to convert it to int. |
11,093,884 | this is my code:
```
ViewBag.idprofesor = new SelectList(db.Profesor, "IDProfesor", "nombre");
```
this code generate a dropdown that only shows the name (nombre) of the teachers (profesor) in the database, id like the dropdown to show the name and the lastname of the teacher. | 2012/06/19 | [
"https://Stackoverflow.com/questions/11093884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1462933/"
] | You may have to manually create a ist of SelectListItems that manually specify the fields you want. Like so:
```
List<SelectListItem> professors = new List<SelectListItem>();
foreach(var professor in db.Professors) {
professors.Add( new SelectListItem() { Text = professor.Fn + " " + professor.Ln, Value = professor.Id } );
}
ViewVag.Professors = professors;
```
Then in your view:
```
Html.DropDownListFor( m => m.Professor, ViewBag.Professors );
``` | You just have to pass an IEnumerable of *SelectListItem* to the constructor. Using Linq to select from the *Professor* collection:
```
@{
var mySelectList =
db.Professor.Select(prof => new SelectListItem(
Text = prof.lastName + ", " + prof.nombre,
Value = prof.IDProfessor
)
).AsEnumerable();
}
```
Using Razor, you should be able to create the drop down list like this:
```
@Html.DropDownList("mydropdownlist", mySelectList)
```
To bind it to a property in your model, the syntax is slightly different:
```
@Html.DropDownListFor(model => model.someproperty, mySelectList)
``` |
70,934,723 | I want to be able to get the first and last name always starting with a capital letter... This I've already achieved in a post here on stackoverflow, it's this one:
`[A-Z][a-z]+([ ][A-Z][a-z]+)*`
However, according to my business rules, I need to be able to validate names and surnames with only the first letter of the first and last name followed by a period and space, or only by a period if the period is at the end of the string.
For example:
```
"John Doe" -> true
"John D." -> true
"John D. D." -> true
"John D. D. " -> false (as here we have a space after the last dot in S.)
"John D. D." -> false (as here two spaces after the first . in B.)
"John D.oe" -> false (as here we have a point not being followed by a space)
```
In order to get around this situation, I wrote the following code that simply means a dot ( `.`) followed by a space (), however I don't know what else to do and I don't know how to introduce this code there in the REGEX specified above...
([.][\s]?)
The regex I came up with is incomplete and does not produce the result I am seeking for:
`^[A-Z](?:[a-z]|[\.])+(?:[ ][A-Z](?:[a-z]|[\.])+)*$`
`John D.oe` -> matches true, however it should not as there is supposed to have a space after every dot...
Does someone out there know how can I solve this issue? | 2022/02/01 | [
"https://Stackoverflow.com/questions/70934723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17075354/"
] | Adapt it as you need ...
```
using System.Xml;
static void GetArtistFromXml()
{
var xml = "<?xml version=\"1.0\" encoding=\"ISO - 8859 - 1\"?><catalog><cd><title>Empire Burlesque</title><artist>Bob Dylan</artist><price>10.90</price></cd><cd><title>Hide your heart</title><artist>Bonnie Tyler</artist><price>10.0</price></cd><cd><title>Greatest Hits</title><artist>Bob Dylan</artist><price>10.90</price></cd></catalog>";
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xml);
var artistElement = xmlDocument.DocumentElement.SelectSingleNode("//cd[title[text()=\"Greatest Hits\"]]/artist");
Console.WriteLine(artistElement.InnerText);
}
``` | It is better to use **LINQ to XML** API. It is available in the .Net Framework since 2007.
**c#**
```
void Main()
{
const string filename = @"e:\Temp\AmeyP.xml";
XDocument xdoc = XDocument.Load(filename);
string artist = xdoc.Descendants("cd")
.Where(x => x.Element("title").Value.Equals("Greatest Hits"))
.Elements("artist").FirstOrDefault()?.Value;
Console.WriteLine(artist);
}
```
**Output**
**Bob Dylan** |
45,099,420 | Due to label output is coming on the next line
```
while ($row=mysqli_fetch_array($res))
{
echo "<label for='A'> <input type='radio' class='muted pull-left' name ='radio' id='A' value=".$row['dis']."> ".$row['dis']."</label>";
}
```
Output should be :
```
Radio button 1 Radio button 2 ..... Radio button n
``` | 2017/07/14 | [
"https://Stackoverflow.com/questions/45099420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | That's a CSS problem. Make the `<label>` tag `display:inline`. | Don't put the input inside the label. Furthermore, a radio button doesn't have a value. It's checked or not checked.
```html
<div class="row">
<label for='A'>Label A</label>
<input type='radio' class='muted pull-left' name='radio' value='A' id='A' />
<label for='B'>Label B</label>
<input type='radio' class='muted pull-left' name='radio' value='B' id='B' />
<label for='C'>Label C</label>
<input type='radio' class='muted pull-left' name='radio' value='C' id='C' checked />
</div>
``` |
5,712 | When I want to move data between two databases (e.g source: Oracle, destination: SQL Server), I think I have two options: Linked Server and SQL Server Integration Services. But is there any benefit using Linked Server? Is there any use of Linked Server if I have SSIS in my hand? | 2011/09/13 | [
"https://dba.stackexchange.com/questions/5712",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/2038/"
] | Linked Servers allow you to connect from SQL Server on an adhoc basis to another datasource, be it SQL Server, Oracle, or something else. Adhoc is the key word, so occasional use is fine. You'll see a lot of negative comments online about performance, hopefully Microsoft will fix in the next SQL Server after Denali.
SSIS is a more robust way of moving and transforming data, with very good exception handling. Getting some data out of Oracle should be straightforward (try the import/export wizard), but SSIS is generally considered to have a steep learning curve. On the other hand, it will make you a more valuable database professional.
It's worth mentioning replication - whilst not trivial, it's a great way of getting data around the enterprise. | If you want to move data then SSIS is definitely a better choice as it does a lot more. SSIS is an feature rich ETL (Extract/Transform/Load) tool and was built for moving data around. Linked servers on the other hand is more suitable for the occasional quick querying of a remote server.
With SSIS you can even save your packages and just deploy/run them the next time onwards to replay your data import/export process. Configuration files can be created to provide dynamic data while running your packages. You can even redistribute your packages if you have created them to be portable. |
38,207,138 | Problem
-------
I have these panels, which I have successfully changed the colors of:
[](https://i.stack.imgur.com/c22Xq.png)
But when I expand the panels, there is a thin grey border at the bottom of each panel header:
[](https://i.stack.imgur.com/gGPkL.png)
[](https://i.stack.imgur.com/dBRXz.png)
How can I get rid of that sliver of grey?
My Code
-------
*CSS*
```
.panel-wrong{
border-color: #FED0D3;
}
.panel-wrong > .panel-heading{
background: #FED0D3;
color: #F53240;
border-color: #FED0D3;
}
.panel-right{
border-color: #E5FFFB;
}
.panel-right > .panel-heading{
background: #E5FFFB;
color: #02C8A7;
border-color: #E5FFFB;
}
```
*HTML*
```
<div class="panel-group" id="accordion">
<div class="panel panel-default panel-wrong">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapse1">Collapsible Group 1</a>
</h4> </div>
<div id="collapse1" class="panel-collapse collapse in">
<div class="panel-body">
</div>
</div>
</div>
<div class="panel panel-default panel-wrong">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapse2">
Collapsible Group 2</a>
</h4> </div>
<div id="collapse2" class="panel-collapse collapse">
<div class="panel-body">panel body 2</div>
</div>
</div>
<div class="panel panel-default panel-right">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapse3">
Collapsible Group 3</a>
</h4> </div>
<div id="collapse3" class="panel-collapse collapse">
<div class="panel-body">panel body 3</div>
</div>
</div>
</div>
```
[JSFiddle](https://jsfiddle.net/14ongm/wzepw41a/12/) | 2016/07/05 | [
"https://Stackoverflow.com/questions/38207138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4581003/"
] | ```
.panel-group .panel-heading + .panel-collapse > .panel-body {
border: none;
}
```
[JSFIDDLE](https://jsfiddle.net/wzepw41a/14/)
--------------------------------------------- | The particular property that you are hunting for is the `border-top-color` property of the `.panel-body` selector. By changing it's value to `transparent` you should remove that, thus:
```
.panel-default>.panel-heading+.panel-collapse>.panel-body {
border-top-color: transparent;
}
``` |
3,435 | Any ideas of how to create such looking logo like this:

This logo in [site](http://designerthemes.com/).
I like this roundness feel around letters. Dribble logo is also with similar effect.
I do not think that it is only shadow (if its shadow at all). | 2011/08/26 | [
"https://graphicdesign.stackexchange.com/questions/3435",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/2124/"
] | What you're seeing is anti-aliasing of the curved shapes combined with a bit of artifacting because the image is an 8-bit PNG. It looks a little fuzzy, in other words, because it *is* a little fuzzy. There is no glow or shadow applied to give that effect. | I am agree with mike,
but if you want to create manually you have to really work hard on illustrator, and the good news is, its a font named [Wendy LP](http://new.myfonts.com/fonts/adobe/wendy-lp/) you can use it.
and you can download [dribbble logo vector file here](http://dribbble.com/site/brand) see if it can help... |
48,757,458 | While crawling through the intrinsics avaiable, I've noticed there's nowhere to be seen an horizontal addsub/subadd intruction avaiable. It's avaiable in the obsolete 3DNow! extension however it's use is impratical for obvious reasons. What is the reason for such "basic" operation not being implemented in the SSE3 extension along with similar horizontal and addsub operations?
And by the way what's the fastest alternative in a modern instruction set (SSE3, SSE4, AVX, ...)? (with 2 doubles per value i.e. \_\_m128d) | 2018/02/12 | [
"https://Stackoverflow.com/questions/48757458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2054583/"
] | Generally you want to avoid designing your code to use horizontal ops in the first place; try to do the same thing to multiple data in parallel, instead of different things with different elements. But sometimes a local optimization is still worth it, and horizontal stuff can be better than pure scalar.
Intel experimented with adding horizontal ops in SSE3, but never added dedicated hardware to support them. They decode to 2 shuffles + 1 vertical op on all CPUs that support them (including AMD). See [Agner Fog's instruction tables](http://agner.org/optimize/). More recent ISA extensions have mostly not included more horizontal ops, except for SSE4.1 `dpps`/[`dppd`](https://github.com/HJLebbink/asm-dude/wiki/DPPD) (which is also usually not worth using vs. manually shuffling).
[SSSE3 `pmaddubsw`](https://github.com/HJLebbink/asm-dude/wiki/PMADDUBSW) makes sense because element-width is already a problem for widening multiplication, and [SSE4.1 `phminposuw`](https://github.com/HJLebbink/asm-dude/wiki/PHMINPOSUW) got dedicated HW support right away to make it worth using (and doing the same thing without it would cost a lot of uops, and it's specifically very useful for video encoding). But AVX / AVX2 / AVX512 horizontal ops are very scarce. AVX512 did introduce some nice shuffles, so you can build your own horizontal ops out of the powerful 2-input lane-crossing shuffles if needed.
---
If the most efficient solution to your problem already includes shuffling together two inputs two different ways and feeding that to an add or sub, then sure, `haddpd` is an efficient way to encode that; especially without AVX where preparing the inputs might have required a `movaps` instruction as well because `shufpd` is destructive (silently emitted by the compiler when using intrinsics, but still costs front-end bandwidth, and latency on CPUs like Sandybridge and earlier which don't eliminate reg-reg moves).
But if you were going to use the same input twice, `haddpd` is the wrong choice. See also [Fastest way to do horizontal float vector sum on x86](https://stackoverflow.com/questions/6996764/fastest-way-to-do-horizontal-float-vector-sum-on-x86). `hadd` / `hsub` are only a good idea with two different inputs, e.g. as part of an on-the-fly transpose as part of some other operation on a matrix.
---
Anyway, the point is, **build your own `haddsub_pd` if you want it, out of two shuffles + [SSE3 `addsubpd`](https://github.com/HJLebbink/asm-dude/wiki/addsubpd)** (which *does* have single-uop hardware support on CPUs that support it.) With AVX, it will be **just as fast as a hypothetical `haddsubpd` instruction**, and without AVX will typically cost one extra `movaps` because the compiler needs to preserve both inputs to the first shuffle. (Code-size will be bigger, but I'm talking about cost in uops for the front-end, and execution-port pressure for the back-end.)
```
// Requires SSE3 (for addsubpd)
// inputs: a=[a1 a0] b=[b1 b0]
// output: [b1+b0, a1-a0], like haddpd for b and hsubpd for a
static inline
__m128d haddsub_pd(__m128d a, __m128d b) {
__m128d lows = _mm_unpacklo_pd(a,b); // [b0, a0]
__m128d highs = _mm_unpackhi_pd(a,b); // [b1, a1]
return _mm_addsub_pd(highs, lows); // [b1+b0, a1-a0]
}
```
[With `gcc -msse3` and clang (on Godbolt)](https://gcc.godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAKxAEZSAbAQwDtRkBSAJgCFufSAZ1QBXYskwgA5NwDMeFsgYisAag6yAwngC2OhQWIKAdAg3YOABgCCV66tUB6R6oUAHEQUEhVTDQBEOAFYeJlpfS2D/BwAjAOCeGPCYyKDAmwdnVVECDwIfBwSk/hTSX1oAWiZU/zLVBjwAa0xVBCZ0dDd0VQAzElUY3xZuhEERGK7e/r8bAH1ZnVouAA4R9vQxmNmuiHnFle6mMr2l1YGASnUAdj4Mh1UTg/rUAHdBQtlohZ1ZkRY3JjIRoMVDbdAQI4xc4aHiZFxFSx1BzVKJ2e4PBanEZ4YCjdSfB56X7/QGNBB4MEQ0hQmFw9QhJJI8qou4OYiYAhiFiEn7rTaU8m4wRlEFvaGyWHorJFWglRHlKo1OwcK7pWw2LIGTDswQEBTAVREVSCTAtBCvVwEVRoHRuPAMTDvfA9HrazAsAgMACeqhehAQqmAyGQjiUrGAdkeZzaHX5XVm7IAbtqTUxiMBBLtMU8Ysds2cmJcVbd7Pco91Re98V8iX8AUCQZTIeLJdKGfL7ii0miy/nsULqzzifWyRSds3aU54Qz6OiwizS2yOVyh3zxgKcaMRa9BC30VP6YlZbxSgqu2qVRebMquPIelgehjrAA1AAa80jCy4QQAbGtY%2BM34/pSexAd0uYYjoYG%2BEWNw9g4oG/hWO4fDWUG/sOpKNuO1J7geRRcGUTBcNcmgDPK57wZB0GCniAQ8kBmFAuSTa4ZObaJLIRGyKRAyzvO3asqo7KcsQ3LfIxa5bDstHCs8YqTvcHExLIJSEb4shVCRKpkcUJ4UZUlHXqqN6yO6zrKhqLgiVy7wJPOvDVMihlKnMfbGiIOjOj0Wb7AWsElui5bGi8TBuG4mDdPR3yzIICAiC6DqsUcqiWCktB4Rx1REbKgmLsJy5iauAHSeCgiheFkVES2yqqlI5yMNIQRSKQLDSJYLWoNImj8PwxqiOILRyLQLX5FIHXnA1jQgCsxg/isVxBFcXBcFcsi0EEQQAJw/o1UgACwtW142ddILXeIiY0TaQcCwEgNp2g6ZAUBAD32tqIDAGtpA9PaBAppQMTtS1MQKGmXrSCNpA2jo7oEAA8iw3rA6QWA6OGDoo/g7LIHqybeCdpCYAAHpgyCeJIUhQ1qDAo4YuiQ/VjDhigvW8IweAxN4kANagbh6qgLAExUxPIKoFTwzxFTo%2BIZifCwmBtA6OjnQNEh0A1tNSM1rUo11UjE8sP4VD%2B%2B2BsGqhXMYPEQLghD9MNZSaKgtrvcQ6i3hlqg9bw/CjcDk2kNNXD7cY%2B0rbQVz7UE%2B3LLI%2B2yMsW17YdpA6HQliIsdHWkPr50gJdAc3TAUAlxA90u492rkJQb1PSgzBsEEmc/X9AMQEDhOgyw4OM9DLuwx6iPI4TaMY5TOfY2TeOOijJNkxTfc03TRjp1TTON%2BwbMCA0XPwLz/N4ILwui%2BLkvizoggmrIqtiOrGV7Tr2enQbRsm2bYZsKoQTGJYv%2BqLbfARB3aO29pXN2HtZBcEuD7PgvB/YnUDsHLgxgtqWB/FHWgG1lixyuFtWQu0tap3TssFBP445bVIeQ2QlCuDkN1oTPOQgC6kCukzW6iAQA5DyDXV64D66EUivbYgGtH5HT1tIOQJE/QEADIbY2ptrSb2/r/X%2BCCJoNQQJgdoH0ICa2kMQugVt1o/ksJHExZi1qEWfrnM6zDC6IKmjNWQ1tvw0K4FtOheDLCyCCHtG%2BDCc5MLYQ1Dh5cUD8Ori9OuH1P7AGboiX6DB/rEG8B3FG3de7r37noOGw8Iaj0wOjNgmNR54BxjPAmOd57k3%2BkvD0mAtY53pmvEamsWacF9uzXe3M9G50PsfaQIsxYSyljLZAct/CCEaF6ZgzRb6DVEVrJ%2BEjX4KI/son%2Bf9LAALtsAyBs5nauyepA2QMDt7qPqk428c1bwYKCB4xazdaD0KIeIxhdiLqsIDvoqQXAWrp1oC3GxwSfmkGTKko%2BbV9pAA) we get the expected:
```
movapd xmm2, xmm0 # ICC saves a code byte here with movaps, but gcc/clang use movapd on double vectors for no advantage on any CPU.
unpckhpd xmm0, xmm1
unpcklpd xmm2, xmm1
addsubpd xmm0, xmm2
ret
```
This wouldn't typically matter when inlining, but as a stand-alone function gcc and clang have trouble when they need the return value in the same register that `b` starts in, instead of `a`. (e.g. if the args are reversed so it's `haddsub(b,a)`).
```
# gcc for haddsub_pd_reverseargs(__m128d b, __m128d a)
movapd xmm2, xmm1 # copy b
unpckhpd xmm1, xmm0
unpcklpd xmm2, xmm0
movapd xmm0, xmm1 # extra copy to put the result in the right register
addsubpd xmm0, xmm2
ret
```
clang actually does a better job, using a different shuffle (`movhlps` instead of `unpckhpd`) to still only use one register-copy:
```
# clang5.0
movapd xmm2, xmm1 # clangs comments go in least-significant-element first order, unlike my comments in the source which follow Intel's convention in docs / diagrams / set_pd() args order
unpcklpd xmm2, xmm0 # xmm2 = xmm2[0],xmm0[0]
movhlps xmm0, xmm1 # xmm0 = xmm1[1],xmm0[1]
addsubpd xmm0, xmm2
ret
```
---
**For an AVX version with `__m256d` vectors, the in-lane behaviour of `_mm256_unpacklo/hi_pd` is actually what you want, for once**, to get the even / odd elements.
```
static inline
__m256d haddsub256_pd(__m256d b, __m256d a) {
__m256d lows = _mm256_unpacklo_pd(a,b); // [b2, a2 | b0, a0]
__m256d highs = _mm256_unpackhi_pd(a,b); // [b3, a3 | b1, a1]
return _mm256_addsub_pd(highs, lows); // [b3+b2, a3-a2 | b1+b0, a1-a0]
}
# clang and gcc both have an easy time avoiding wasted mov instructions
vunpcklpd ymm2, ymm1, ymm0 # ymm2 = ymm1[0],ymm0[0],ymm1[2],ymm0[2]
vunpckhpd ymm0, ymm1, ymm0 # ymm0 = ymm1[1],ymm0[1],ymm1[3],ymm0[3]
vaddsubpd ymm0, ymm0, ymm2
```
---
Of course, if you have the same input twice, i.e. you wanted the sum and difference between the two elements of a vector, you only need one shuffle to feed `addsubpd`
```
// returns [a1+a0 a1-a0]
static inline
__m128d sumdiff(__m128d a) {
__m128d swapped = _mm_shuffle_pd(a,a, 0b01);
return _mm_addsub_pd(swapped, a);
}
```
This actually compiles quite clunkily with both gcc and clang:
```
movapd xmm1, xmm0
shufpd xmm1, xmm0, 1
addsubpd xmm1, xmm0
movapd xmm0, xmm1
ret
```
But the 2nd movapd should go away when inlining, if the compiler doesn't need the result in the same register it started with. I think gcc and clang are both missing an optimization here: they could swap `xmm0` after copying it:
```
# compilers should do this, but don't
movapd xmm1, xmm0 # a = xmm1 now
shufpd xmm0, xmm0, 1 # swapped = xmm0
addsubpd xmm0, xmm1 # swapped +- a
ret
```
Presumably their [SSA](https://en.wikipedia.org/wiki/Static_single_assignment_form)-based register allocators don't think of using a 2nd register for the same value of `a` to free up xmm0 for `swapped`. Usually it's fine (and even preferable) to produce the result in a different register, so this is rarely a problem when inlining, only when looking at the stand-alone version of a function | How about:
```
__m128d a, b; //your inputs
const __m128d signflip_low_element =
_mm_castsi128_pd(_mm_set_epi64(0,0x8000000000000000));
b = _mm_xor_pd(b, signflip_low_element); // negate b[0]
__m128d res = _mm_hadd_pd(a,b);
```
This builds haddsubpd in terms of haddpd, so it's only one extra instruction. Unfortunately `haddpd` is not very fast, with a throughput of one per 2 clock cycles on most CPUs, limited by FP shuffle throughput.
But this way is good for code-size (of the x86 machine code). |
52,193 | I'm trying to develop a module to create a log for each product visited by a user.
To generate a log, I'm using event observer. But the event never is called.
What could be wrong?
My code:
C:\Users\miudo\AppData\Local\Temp\scp44107\home\sr\localhos.t\app\code\local\Bit\Itemsviewed\Model\Observer.php
```
<?php
class Bit_Itemsviewed_Model_Observer
{
public function saveProductVisitHistory(Varien_Event_Observer $observer) {
$event = $observer->getEvent();
Mage::log('id ' . $observer->getEvent()->getProduct()->getId() , null, 'custom.log');
return $this;
}
}
```
C:\Users\miudo\AppData\Local\Temp\scp47708\home\sr\localhos.t\app\code\local\Bit\Itemsviewed\etc\Config.xml
```
<?xml version="1.0"?>
<config>
<modules>
<Bit_Itemsviewed>
<version>0.1.0</version>
</Bit_Itemsviewed>
</modules>
<global>
<helpers>
<itemsviewed>
<class>Bit_Itemsviewed_Helper</class>
</itemsviewed>
</helpers>
<blocks>
<itemsviewed>
<class>Bit_Itemsviewed_Block</class>
</itemsviewed>
</blocks>
<catalog>
<rewrite>
<product_view>Bit_Itemsviewed_Block_Itemsviewed</product_view>
</rewrite>
</catalog>
<models>
<itemsviewed>
<class>Bit_Itemsviewed_Model</class>
</itemsviewed>
</models>
<!--/global>
<frontend-->
<events>
<catalog_controller_product_view>
<observers>
<itemsviewed>
<type>model</type>
<class>bit_itemsviewed/observer</class>
<method>saveProductVisitHistory</method>
</itemsviewed>
</observers>
</catalog_controller_product_view>
</events>
</global>
</config>
```
C:\Users\miudo\AppData\Local\Temp\scp57676\home\sr\localhos.t\app\code\local\Bit\Itemsviewed\Helper\Data.php
```
<?php
class Bit_Itemsviewed_Helper_Data extends Mage_Core_Helper_Abstract{
}
```
C:\Users\miudo\AppData\Local\Temp\scp48515\home\sr\localhos.t\app\code\local\Bit\Itemsviewed\Block\Itemsviewed.php
```
<?php
class Bit_Itemsviewed_Block_Itemsviewed extends Mage_Catalog_Block_Product_View{
}
```
Thanks
EDITED:
I had been trying to use
```
<itemsviewed>
<type>model</type> also <singleton>
<class>itemsviewed/observer</class> also <class> Bit_Itemsviewed_Model_Observer </class>
[...]
</itemsviewed>
``` | 2015/01/14 | [
"https://magento.stackexchange.com/questions/52193",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/20333/"
] | D Millar try this event
`catalog_controller_product_init_after` instead of `catalog_controller_product_view` event .
```
Mage::dispatchEvent('catalog_controller_product_init_after',
array('product' => $product,
'controller_action' => $controller
)
```
**for Observer code is look like:**
-----------------------------------
```
<?php
class Bit_Itemsviewed_Model_Observer
{
public function saveProductVisitHistory(Varien_Event_Observer $observer)
{
$event = $observer->getEvent();
$product=$event->getProduct()
$controller_action=$event->getControllerAction()
Mage::log('id ' . $observer->getEvent()->getProduct()->getId() , null, 'custom.log');
return $this;
}
}
```
Also as Cags said you need to change you class of observer from `bit_itemsviewed/observer` to `itemsviewd` as Your model identifier is <`itemsviewed`> because of
```
<models>
<itemsviewed> <!-- model indentifier -->
<class>Bit_Itemsviewed_Model</class>
</itemsviewed>
</models>
``` | Use this example to make it work, as I just tested it:
```
<frontend>
<events>
<catalog_controller_product_init_after>
<observers>
<gtm_see_product_details>
<class>gtm/observer</class>
<method>setGTMSeeProductDetails</method>
</gtm_see_product_details>
</observers>
</catalog_controller_product_init_after>
...
```
path: app\code\local\OsfMinitrade\GTM\etc\config.xml
```
/**
* @param Varien_Event_Observer $observer
* @return Varien_Event_Observer
*/
public function setGTMSeeProductDetails(Varien_Event_Observer $observer)
{
var_dump($observer->getEvent()->getProduct()->getId());
die;
return $observer;
}
```
path: app\code\local\OsfMinitrade\GTM\Model\Observer.php |
63,713,604 | Spark: 2.4.5 with Scala
I am having a column in my Dataframe which holds the number of days since epoch (1970). I am looking for a way to convert that into a Date Column.
So I am working on writing a function like below:
```
def from_epochday(epochDays: Column):Column = {
date_add(to_date(lit("1970-01-01"), "YYYY-MM-DD") , epochDays /* Need to int and not a Column*/)
}
```
The data Frame will have :
```
df.withColumn("dob", from_epochday(col(epochDays)))
```
The problem is date\_add take Int as input and I am not able to figure out how to get the value as Int.
Probably I can do it via UDF function but not trying to avoid that. | 2020/09/02 | [
"https://Stackoverflow.com/questions/63713604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5828621/"
] | Here is another way that you can do it.
```
df = spark.createDataFrame(
[
(1, 18508),
],
schema=StructType(
[
StructField('Id', StringType(), True),
StructField('Epoch_days', LongType(), True)
]
)
)
df.withColumn(
'date',
(col('Epoch_days')*86400).cast('timestamp')
).show(truncate=False)
#+---+----------+-------------------+
#|Id |Epoch_days|date |
#+---+----------+-------------------+
#|1 |18508 |2020-09-03 00:00:00|
#+---+----------+-------------------+
``` | ```
val df = Seq(1).toDF("seq").select(
from_unixtime(unix_timestamp(),"MM-dd-yyyy").as("date_1"),
from_unixtime(unix_timestamp(),"dd-MM-yyyy HH:mm:ss").as("date_2"),
from_unixtime(unix_timestamp(),"yyyy-MM-dd").as("date_3")
).show(false)
```
* <https://sparkbyexamples.com/spark/spark-epoch-time-to-timestamp-date/> |
10,310,441 | When compiling with ARC, method arguments often appear to be retained at the beginning of the method and released at the end. This retain/release pair seems superfluous, and contradicts the idea that ARC "produces the code you would have written anyway". Nobody in those dark, pre-ARC days performed an extra retain/release on all method arguments just to be on the safe side, did they?
Consider:
```
@interface Test : NSObject
@end
@implementation Test
- (void)testARC:(NSString *)s
{
[s length]; // no extra retain/release here.
}
- (void)testARC2:(NSString *)s
{
// ARC inserts [s retain]
[s length];
[s length];
// ARC inserts [s release]
}
- (void)testARC3:(__unsafe_unretained NSString *)s
{
// no retain -- we used __unsafe_unretained
[s length];
[s length];
// no release -- we used __unsafe_unretained
}
@end
```
When compiled with Xcode 4.3.2 in release mode, the assembly (such that I'm able to understand it) contained calls to `objc_retain` and `objc_release` at the start and end of the second method. What's going on?
This is not a huge problem, but this extra retain/release traffic does show up when using Instruments to profile performance-sensitive code. It seems you can decorate method arguments with `__unsafe_unretained` to avoid this extra retain/release, as I've done in the third example, but doing so feels quite disgusting. | 2012/04/25 | [
"https://Stackoverflow.com/questions/10310441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192102/"
] | See [this reply](http://lists.apple.com/archives/objc-language/2011/Nov/msg00005.html) from the Objc-language mailing list:
>
> When the compiler doesn't know anything about the
> memory management behavior of a function or method (and this happens a
> lot), then the compiler must assume:
>
>
> 1) That the function or method might completely rearrange or replace
> the entire object graph of the application (it probably won't, but it
> could). 2) That the caller might be manual reference counted code, and
> therefore the lifetime of passed in parameters is not realistically
> knowable.
>
>
> Given #1 and #2; and given that ARC *must* never allow an object to be
> prematurely deallocated, then these two assumptions force the compiler
> to retain passed in objects more often than not.
>
>
>
I think that the main problem is that your method’s body might lead to the arguments being released, so that ARC has to act defensively and retain them:
```
- (void) processItems
{
[self setItems:[NSArray arrayWithObject:[NSNumber numberWithInt:0]]];
[self doSomethingSillyWith:[items lastObject]];
}
- (void) doSomethingSillyWith: (id) foo
{
[self setItems:nil];
NSLog(@"%@", foo); // if ARC did not retain foo, you could be in trouble
}
```
That might also be the reason that you don’t see the extra retain when there’s just a single call in your method. | Passing as a parameter does not, in general, increase the retain count. However, if you're passing it to something like `NSThread`, it is specifically documented that it *will* retain the parameter for the new thread.
So without an example of how you're intending to start this new thread, I can't give a definitive answer. In general, though, you should be fine. |
667,412 | I'm trying to organize my Music better m4a, mp3, etc. Since the files are tagged I thought I could make a script to read the file and pull the album and artist info from the file then mv the file in the proper folder. I also wanted to learn some AWK in the process.
I started with:
```
for file in *.m4a; do
tageditor get artist -f "$file" | awk '/Artist/{ print }'
done
```
Output:
```
Artist Periphery
Artist Meshuggah, Tomas Haake, Marten Hagström, Fredrik Thordendal,
Artist Varials, Bryan Garris
Artist Cannibal Corpse
Artist Lamb of God
Artist Ingested
Artist Linkin Park
Artist Car Bomb
Artist Whitechapel
Artist Divine Destruction
Artist Ingested, Sean Hynes, Sam Yates, Jason Evans, Lyn Jeffs
```
Then:
```
for file in *.m4a; do
tageditor get artist -f "$file" | awk '/Artist/{ print $2 }'
done
```
Output:
```
Periphery
Angelmaker,
Meshuggah,
Varials,
Cannibal
Lamb
Ingested
Linkin
Car
Whitechapel
Divine
Ingested,
```
I am still trying to understand how awk works so I reworked my code
for file in ./\*.m4a; do
info=$(tageditor get artist album -f "${file}")
prt1=$(echo "$info" | awk 'sub(/^.{22}/,"")')
prt2=$(echo "$prt1" | awk 'NR>2' )
art="$prt2"
albm=$(echo "$prt2" | awk 'NR==1' ) band=$(echo "$art" | awk 'NR==2' )
echo "$info"
echo
echo "$prt1"
echo
echo "$prt2"
echo
echo "$albm" #ALBUM
echo
echo "$band" #ARTIST
echo
I got:
Tag information for "./Do Not Look Down.m4a":
* MP4/iTunes tag
Album Koloss
Artist Meshuggah, Tomas Haake, Marten Hagström, Fredrik Thordendal, Tomas Haake
/Do Not Look Down.m4a":
[0m
Koloss
Meshuggah, Tomas Haake, Marten Hagström, Fredrik Thordendal, Tomas Haake
Koloss
Meshuggah, Tomas Haake, Marten Hagström, Fredrik Thordendal, Tomas Haake
Koloss
Meshuggah, Tomas Haake, Marten Hagström, Fredrik Thordendal, Tomas Haake
How can I use awk to delete everything after the , in the last line. | 2021/09/03 | [
"https://unix.stackexchange.com/questions/667412",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/475899/"
] | You can use `sub()` function to remove unwanted part from the beginning of each line:
```
for file in ./*.m4a; do
tageditor get artist -f "$file" | awk 'sub(/^Artist */, "")'
done
```
I'm also thinking the output of the `tageditor` command is Tab delimited output; if that was, you can restrict awk's default whitespace (Tabs/SPCs) seperators into Tab character only then print the second column of it:
```
for file in ./*.m4a; do
tageditor get artist -f "$file" | awk -F'\t' '/^Artist/{ print $2 }'
done
```
also I found that `tageditor` command can read multiple files by itself, so you can do as following too.
```
tageditor get artist -f /path/to/*.m4a | awk -F'\t' '/^Artist/{ print $2 }'
``` | Is this what you're trying to do (using `cat file` in place of `tageditor...` which I don't have)?
```
$ cat file | awk 'sub(/^Artist[[:space:]]+/,""){sub(/,.*/,""); print}'
Periphery
Meshuggah
Varials
Cannibal Corpse
Lamb of God
Ingested
Linkin Park
Car Bomb
Whitechapel
Divine Destruction
Ingested
```
Don't use `/Artist/` unanchored as that will match anywhere on the line, not just when `Artist` is the first string:
```
$ printf 'Foo\tBob The Artist\nArtist\tLamb of God\nArtistically\tIs how we do it\n'
Foo Bob The Artist
Artist Lamb of God
Artistically Is how we do it
$ printf 'Foo\tBob The Artist\nArtist\tLamb of God\nArtistically\tIs how we do it\n' |
awk '/Artist/'
Foo Bob The Artist
Artist Lamb of God
Artistically Is how we do it
$ printf 'Foo\tBob The Artist\nArtist\tLamb of God\nArtistically\tIs how we do it\n' |
awk '/^Artist[[:space:]]/'
Artist Lamb of God
``` |
35,989 | >
> **Related Question**
>
> [Free Antivirus solutions for Windows](https://superuser.com/questions/2/free-antivirus-solutions-for-windows)
>
>
>
I am looking for a free native 64 Bit Anti virus package. I know lots / nearly all packages will run in 32bit emulated mode, but I can't seem to find a truly native 64 bit package, that's free. Anyone? | 2009/09/04 | [
"https://superuser.com/questions/35989",
"https://superuser.com",
"https://superuser.com/users/6938/"
] | [Microsoft Security Essentials](http://www.softpedia.com/get/Antivirus/Microsoft-Security-Essentials.shtml)
-----------------------------------------------------------------------------------------------------------
Link is to Softpedia. It's in beta right now but I've been using it for about a month and so far it works great. It has a 64bit version. | I've always used [AVAST](http://www.avast.com/eng/x64.html) and never had any problems. The link provides you information on a 64BIT AVAST. |
11,066,080 | I'm beginning to analyse datas for my thesis. I first need to count consecutive occurences of strings as one. Here's a sample vector :
```
test <- c("vv","vv","vv","bb","bb","bb","","cc","cc","vv","vv")
```
I would like to simply extract unique values, as in the unix command uniq. So expected output would be a vector as :
"vv","bb","cc","vv"
I looked at rle function, wich seems to be fine, but how would I get the output of rle as a vector ? I don't seem to understand the rle class...
```
> rle(test)
Run Length Encoding
lengths: int [1:5] 3 3 1 2 2
values : chr [1:5] "vv" "bb" "" "cc" "vv"
```
How to get one vector of the values output by rle and another one for the lengths ? Hope I'm making myself clear...
Thanks again for any help ! | 2012/06/16 | [
"https://Stackoverflow.com/questions/11066080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/645118/"
] | What you probably want is some kind of bound service.
<http://developer.android.com/guide/topics/fundamentals/bound-services.html>
You can send messages to and receive messages from it.
So when your activity is started again, it can bind to the service again and receive callbacks when downloads have finished.
Plus the activity can send messages to the service to start or stop downloads.
The nice part: The service gets started when you bind to it and it's not already running.
Hope this helped :) | possible answer to your question 1 and also question 2:
use broadcastReceivers: <http://developer.android.com/reference/android/content/BroadcastReceiver.html>
for question 1: you can register your activity to some kind of receiver you'll define, and send whenever you'd like a broadcast to it. if the activity is registered to the broadcast - it receive it...
for question 2: same answer: register your service to special broadcast represents your message you want to deliver to the service. if it not running (and not registerd to the broadcast) - then nothing would hepend. |
122,686 | I bought a turkey right after thanksgiving to turn into broth but didn’t the day of so I froze it and now I don’t know if I can put the frozen turkey into a pot as is or if I’d have to thaw it like normal first. I’m considering cutting the turkey in half to put in two pots to make more broth and have more space.
So, can I put a frozen turkey in a pot of water on the stove and cook it? Or do I need to thaw it first? | 2022/12/18 | [
"https://cooking.stackexchange.com/questions/122686",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/102124/"
] | >
> Are whole dried Shiitake sufficient for complete flavour extraction in my stock
>
>
>
Of course! Don't bother cutting them up, as that would make them prone to releasing too much of their flavor long before the stock is ready. | This comes down to one simple question: Is the flavor you are getting while leaving them whole sufficiently strong for your tastes?
If the answer is yes, then just keep doing what you’re doing.
If the answer is no, then you *might* consider increasing the surface area, or you might consider adding more of them, or you might consider cooking longer, or possibly even cooking hotter.
In this particular case, I would probably go for adding more of them over the other options. You’re probably already cooking long enough to extract as much flavor as possible (you will not get all of it, as it becomes harder to extract more the more you extract), so increasing cook time, temperature, or surface area is not likely to have a very big impact. |
10,187,659 | I'd like to get the following layout:
```
[ ][ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ][ ]
```
where each `[ ]` should be at most 300x150px, but scale down to the
bounding box as needed, conserving aspect ratio.
```
.field {
width: 16%;
}
.field .placeholder{
float: left;
width: 300px;
height: 150px;
}
```
I tried adding a placeholder div inside the divs, but that didn't
really help, it gives me something akin to
```
[ ]
[ ]
[ ]
...
``` | 2012/04/17 | [
"https://Stackoverflow.com/questions/10187659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/411944/"
] | Yes you can via multipart uploading: <http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMPphpAPI.html>
Multipart uploading is a three-step process: You initiate the upload, you upload the object parts, and after you have uploaded all the parts, you complete the multipart upload. Upon receiving the complete multipart upload request, Amazon S3 constructs the object from the uploaded parts, and you can then access the object just as you would any other object in your bucket.
<http://docs.aws.amazon.com/AmazonS3/latest/dev/mpuoverview.html>
I will be doing this personally very soon but this is what you need to start. | Yes,you can do this by modifying s3.php like this,
```
<?php
class S3Withprogressbar {
// ACL flags
const ACL_PRIVATE = 'private';
const ACL_PUBLIC_READ = 'public-read';
const ACL_PUBLIC_READ_WRITE = 'public-read-write';
private static $__accessKey; // AWS Access key
private static $__secretKey; // AWS Secret key
public static $_uploadProgressFileName="" ;//uploadProgressFileName
public function __construct($accessKey = null, $secretKey = null) {
if ($accessKey !== null && $secretKey !== null)
self::setAuth($accessKey, $secretKey);
}
public static function setAuth($accessKey, $secretKey) {
self::$__accessKey = $accessKey;
self::$__secretKey = $secretKey;
}
public static function listBuckets($detailed = false) {
$rest = new S3Request('GET', '', '');
$rest = $rest->getResponse();
if ($rest->error === false && $rest->code !== 200)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false) {
trigger_error(sprintf("S3Withprogressbar::listBuckets(): [%s] %s", $rest->error['code'], $rest->error['message']), E_USER_WARNING);
return false;
}
$results = array(); //var_dump($rest->body);
if (!isset($rest->body->Buckets)) return $results;
if ($detailed) {
if (isset($rest->body->Owner, $rest->body->Owner->ID, $rest->body->Owner->DisplayName))
$results['owner'] = array(
'id' => (string)$rest->body->Owner->ID, 'name' => (string)$rest->body->Owner->ID
);
$results['buckets'] = array();
foreach ($rest->body->Buckets->Bucket as $b)
$results['buckets'][] = array(
'name' => (string)$b->Name, 'time' => strtotime((string)$b->CreationDate)
);
} else
foreach ($rest->body->Buckets->Bucket as $b) $results[] = (string)$b->Name;
return $results;
}
public static function getBucket($bucket, $prefix = null, $marker = null, $maxKeys = null) {
$rest = new S3Request('GET', $bucket, '');
if ($prefix !== null && $prefix !== '') $rest->setParameter('prefix', $prefix);
if ($marker !== null && $prefix !== '') $rest->setParameter('marker', $marker);
if ($maxKeys !== null && $prefix !== '') $rest->setParameter('max-keys', $maxKeys);
$response = $rest->getResponse();
if ($response->error === false && $response->code !== 200)
$response->error = array('code' => $response->code, 'message' => 'Unexpected HTTP status');
if ($response->error !== false) {
trigger_error(sprintf("S3Withprogressbar::getBucket(): [%s] %s", $response->error['code'], $response->error['message']), E_USER_WARNING);
return false;
}
$results = array();
$lastMarker = null;
if (isset($response->body, $response->body->Contents))
foreach ($response->body->Contents as $c) {
$results[(string)$c->Key] = array(
'name' => (string)$c->Key,
'time' => strToTime((string)$c->LastModified),
'size' => (int)$c->Size,
'hash' => substr((string)$c->ETag, 1, -1)
);
$lastMarker = (string)$c->Key;
//$response->body->IsTruncated = 'true'; break;
}
if (isset($response->body->IsTruncated) &&
(string)$response->body->IsTruncated == 'false') return $results;
// Loop through truncated results if maxKeys isn't specified
if ($maxKeys == null && $lastMarker !== null && (string)$response->body->IsTruncated == 'true')
do {
$rest = new S3Request('GET', $bucket, '');
if ($prefix !== null) $rest->setParameter('prefix', $prefix);
$rest->setParameter('marker', $lastMarker);
if (($response = $rest->getResponse(true)) == false || $response->code !== 200) break;
if (isset($response->body, $response->body->Contents))
foreach ($response->body->Contents as $c) {
$results[(string)$c->Key] = array(
'name' => (string)$c->Key,
'time' => strToTime((string)$c->LastModified),
'size' => (int)$c->Size,
'hash' => substr((string)$c->ETag, 1, -1)
);
$lastMarker = (string)$c->Key;
}
} while ($response !== false && (string)$response->body->IsTruncated == 'true');
return $results;
}
public function putBucket($bucket, $acl = self::ACL_PRIVATE) {
$rest = new S3Request('PUT', $bucket, '');
$rest->setAmzHeader('x-amz-acl', $acl);
$rest = $rest->getResponse();
if ($rest->error === false && $rest->code !== 200)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false) {
//trigger_error(sprintf("S3Withprogressbar::putBucket({$bucket}): [%s] %s", $rest->error['code'], $rest->error['message']), E_USER_WARNING);
return false;
}
return true;
}
public function deleteBucket($bucket = '') {
$rest = new S3Request('DELETE', $bucket);
$rest = $rest->getResponse();
if ($rest->error === false && $rest->code !== 204)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false) {
trigger_error(sprintf("S3Withprogressbar::deleteBucket({$bucket}): [%s] %s",
$rest->error['code'], $rest->error['message']), E_USER_WARNING);
return false;
}
return true;
}
public static function inputFile($file, $md5sum = true) {
if (!file_exists($file) || !is_file($file) || !is_readable($file)) {
trigger_error('S3Withprogressbar::inputFile(): Unable to open input file: '.$file, E_USER_WARNING);
return false;
}
return array('file' => $file, 'size' => filesize($file),
'md5sum' => $md5sum !== false ? (is_string($md5sum) ? $md5sum :
base64_encode(md5_file($file, true))) : '');
}
public static function inputResource(&$resource, $bufferSize, $md5sum = '') {
if (!is_resource($resource) || $bufferSize <= 0) {
trigger_error('S3Withprogressbar::inputResource(): Invalid resource or buffer size', E_USER_WARNING);
return false;
}
$input = array('size' => $bufferSize, 'md5sum' => $md5sum);
$input['fp'] =& $resource;
return $input;
}
// Modified Function with one more parameter $uploadProgressFileName
public static function putObject($input, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $contentType = null,$uploadProgressFileName) {
if ($input == false) return false;
$rest = new S3Request('PUT', $bucket, $uri);
// Set public variable value($uploadProgressFileName) in S3Request class
$rest->uploadProgressFileName = $uploadProgressFileName;
if (is_string($input)) $input = array(
'data' => $input, 'size' => strlen($input),
'md5sum' => base64_encode(md5($input, true))
);
// Data
if (isset($input['fp']))
$rest->fp =& $input['fp'];
elseif (isset($input['file']))
$rest->fp = @fopen($input['file'], 'rb');
elseif (isset($input['data']))
$rest->data = $input['data'];
// Content-Length (required)
if (isset($input['size']) && $input['size'] > 0)
$rest->size = $input['size'];
else {
if (isset($input['file']))
$rest->size = filesize($input['file']);
elseif (isset($input['data']))
$rest->size = strlen($input['data']);
}
// Content-Type
if ($contentType !== null)
$input['type'] = $contentType;
elseif (!isset($input['type']) && isset($input['file']))
$input['type'] = self::__getMimeType($input['file']);
else
$input['type'] = 'application/octet-stream';
// We need to post with the content-length and content-type, MD5 is optional
if ($rest->size > 0 && ($rest->fp !== false || $rest->data !== false)) {
$rest->setHeader('Content-Type', $input['type']);
if (isset($input['md5sum'])) $rest->setHeader('Content-MD5', $input['md5sum']);
$rest->setAmzHeader('x-amz-acl', $acl);
foreach ($metaHeaders as $h => $v) $rest->setAmzHeader('x-amz-meta-'.$h, $v);
$rest->getResponse();
} else
$rest->response->error = array('code' => 0, 'message' => 'Missing input parameters');
if ($rest->response->error === false && $rest->response->code !== 200)
$rest->response->error = array('code' => $rest->response->code, 'message' => 'Unexpected HTTP status');
if ($rest->response->error !== false) {
//trigger_error(sprintf("S3Withprogressbar::putObject(): [%s] %s", $rest->response->error['code'], $rest->response->error['message']), E_USER_WARNING);
return false;
}
return true;
}
// Modified Function with one more parameter $uploadProgressFileName
public static function putObjectFile($file, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $contentType = null,$uploadProgressFileName) {
return self::putObject(S3Withprogressbar::inputFile($file), $bucket, $uri, $acl, $metaHeaders, $contentType,$uploadProgressFileName);
}
public function putObjectString($string, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $contentType = 'text/plain') {
return self::putObject($string, $bucket, $uri, $acl, $metaHeaders, $contentType);
}
public static function getObject($bucket = '', $uri = '', $saveTo = false) {
$rest = new S3Request('GET', $bucket, $uri);
if ($saveTo !== false) {
if (is_resource($saveTo))
$rest->fp =& $saveTo;
else
if (($rest->fp = @fopen($saveTo, 'wb')) == false)
$rest->response->error = array('code' => 0, 'message' => 'Unable to open save file for writing: '.$saveTo);
}
if ($rest->response->error === false) $rest->getResponse();
if ($rest->response->error === false && $rest->response->code !== 200)
$rest->response->error = array('code' => $rest->response->code, 'message' => 'Unexpected HTTP status');
if ($rest->response->error !== false) {
trigger_error(sprintf("S3Withprogressbar::getObject({$bucket}, {$uri}): [%s] %s",
$rest->response->error['code'], $rest->response->error['message']), E_USER_WARNING);
return false;
}
$rest->file = realpath($saveTo);
return $rest->response;
}
public static function getObjectInfo($bucket = '', $uri = '', $returnInfo = true) {
$rest = new S3Request('HEAD', $bucket, $uri);
$rest = $rest->getResponse();
if ($rest->error === false && ($rest->code !== 200 && $rest->code !== 404))
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false) {
trigger_error(sprintf("S3Withprogressbar::getObjectInfo({$bucket}, {$uri}): [%s] %s",
$rest->error['code'], $rest->error['message']), E_USER_WARNING);
return false;
}
return $rest->code == 200 ? $returnInfo ? $rest->headers : true : false;
}
public static function setBucketLogging($bucket, $targetBucket, $targetPrefix) {
$dom = new DOMDocument;
$bucketLoggingStatus = $dom->createElement('BucketLoggingStatus');
$bucketLoggingStatus->setAttribute('xmlns', 'http://s3.amazonaws.com/doc/2006-03-01/');
$loggingEnabled = $dom->createElement('LoggingEnabled');
$loggingEnabled->appendChild($dom->createElement('TargetBucket', $targetBucket));
$loggingEnabled->appendChild($dom->createElement('TargetPrefix', $targetPrefix));
// TODO: Add TargetGrants
$bucketLoggingStatus->appendChild($loggingEnabled);
$dom->appendChild($bucketLoggingStatus);
$rest = new S3Request('PUT', $bucket, '');
$rest->setParameter('logging', null);
$rest->data = $dom->saveXML();
$rest->size = strlen($rest->data);
$rest->setHeader('Content-Type', 'application/xml');
$rest = $rest->getResponse();
if ($rest->error === false && $rest->code !== 200)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false) {
trigger_error(sprintf("S3Withprogressbar::setBucketLogging({$bucket}, {$uri}): [%s] %s",
$rest->error['code'], $rest->error['message']), E_USER_WARNING);
return false;
}
return true;
}
public static function getBucketLogging($bucket = '') {
$rest = new S3Request('GET', $bucket, '');
$rest->setParameter('logging', null);
$rest = $rest->getResponse();
if ($rest->error === false && $rest->code !== 200)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false) {
trigger_error(sprintf("S3Withprogressbar::getBucketLogging({$bucket}): [%s] %s",
$rest->error['code'], $rest->error['message']), E_USER_WARNING);
return false;
}
if (!isset($rest->body->LoggingEnabled)) return false; // No logging
return array(
'targetBucket' => (string)$rest->body->LoggingEnabled->TargetBucket,
'targetPrefix' => (string)$rest->body->LoggingEnabled->TargetPrefix,
);
}
public static function setAccessControlPolicy($bucket, $uri = '', $acp = array()) {
$dom = new DOMDocument;
$dom->formatOutput = true;
$accessControlPolicy = $dom->createElement('AccessControlPolicy');
$accessControlList = $dom->createElement('AccessControlList');
// It seems the owner has to be passed along too
$owner = $dom->createElement('Owner');
$owner->appendChild($dom->createElement('ID', $acp['owner']['id']));
$owner->appendChild($dom->createElement('DisplayName', $acp['owner']['name']));
$accessControlPolicy->appendChild($owner);
foreach ($acp['acl'] as $g) {
$grant = $dom->createElement('Grant');
$grantee = $dom->createElement('Grantee');
$grantee->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
if (isset($g['id'])) { // CanonicalUser (DisplayName is omitted)
$grantee->setAttribute('xsi:type', 'CanonicalUser');
$grantee->appendChild($dom->createElement('ID', $g['id']));
} elseif (isset($g['email'])) { // AmazonCustomerByEmail
$grantee->setAttribute('xsi:type', 'AmazonCustomerByEmail');
$grantee->appendChild($dom->createElement('EmailAddress', $g['email']));
} elseif ($g['type'] == 'Group') { // Group
$grantee->setAttribute('xsi:type', 'Group');
$grantee->appendChild($dom->createElement('URI', $g['uri']));
}
$grant->appendChild($grantee);
$grant->appendChild($dom->createElement('Permission', $g['permission']));
$accessControlList->appendChild($grant);
}
$accessControlPolicy->appendChild($accessControlList);
$dom->appendChild($accessControlPolicy);
$rest = new S3Request('PUT', $bucket, '');
$rest->setParameter('acl', null);
$rest->data = $dom->saveXML();
$rest->size = strlen($rest->data);
$rest->setHeader('Content-Type', 'application/xml');
$rest = $rest->getResponse();
if ($rest->error === false && $rest->code !== 200)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false) {
trigger_error(sprintf("S3Withprogressbar::setAccessControlPolicy({$bucket}, {$uri}): [%s] %s",
$rest->error['code'], $rest->error['message']), E_USER_WARNING);
return false;
}
return true;
}
public static function getAccessControlPolicy($bucket, $uri = '') {
$rest = new S3Request('GET', $bucket, $uri);
$rest->setParameter('acl', null);
$rest = $rest->getResponse();
if ($rest->error === false && $rest->code !== 200)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false) {
trigger_error(sprintf("S3Withprogressbar::getAccessControlPolicy({$bucket}, {$uri}): [%s] %s",
$rest->error['code'], $rest->error['message']), E_USER_WARNING);
return false;
}
$acp = array();
if (isset($rest->body->Owner, $rest->body->Owner->ID, $rest->body->Owner->DisplayName)) {
$acp['owner'] = array(
'id' => (string)$rest->body->Owner->ID, 'name' => (string)$rest->body->Owner->DisplayName
);
}
if (isset($rest->body->AccessControlList)) {
$acp['acl'] = array();
foreach ($rest->body->AccessControlList->Grant as $grant) {
foreach ($grant->Grantee as $grantee) {
if (isset($grantee->ID, $grantee->DisplayName)) // CanonicalUser
$acp['acl'][] = array(
'type' => 'CanonicalUser',
'id' => (string)$grantee->ID,
'name' => (string)$grantee->DisplayName,
'permission' => (string)$grant->Permission
);
elseif (isset($grantee->EmailAddress)) // AmazonCustomerByEmail
$acp['acl'][] = array(
'type' => 'AmazonCustomerByEmail',
'email' => (string)$grantee->EmailAddress,
'permission' => (string)$grant->Permission
);
elseif (isset($grantee->URI)) // Group
$acp['acl'][] = array(
'type' => 'Group',
'uri' => (string)$grantee->URI,
'permission' => (string)$grant->Permission
);
else continue;
}
}
}
return $acp;
}
public static function deleteObject($bucket = '', $uri = '') {
$rest = new S3Request('DELETE', $bucket, $uri);
$rest = $rest->getResponse();
if ($rest->error === false && $rest->code !== 204)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false) {
trigger_error(sprintf("S3Withprogressbar::deleteObject(): [%s] %s", $rest->error['code'], $rest->error['message']), E_USER_WARNING);
return false;
}
return true;
}
public static function __getMimeType(&$file) {
$type = false;
// Fileinfo documentation says fileinfo_open() will use the
// MAGIC env var for the magic file
if (extension_loaded('fileinfo') && isset($_ENV['MAGIC']) &&
($finfo = finfo_open(FILEINFO_MIME, $_ENV['MAGIC'])) !== false) {
if (($type = finfo_file($finfo, $file)) !== false) {
// Remove the charset and grab the last content-type
$type = explode(' ', str_replace('; charset=', ';charset=', $type));
$type = array_pop($type);
$type = explode(';', $type);
$type = array_shift($type);
}
finfo_close($finfo);
// If anyone is still using mime_content_type()
} elseif (function_exists('mime_content_type'))
$type = mime_content_type($file);
if ($type !== false && strlen($type) > 0) return $type;
// Otherwise do it the old fashioned way
static $exts = array(
'jpg' => 'image/jpeg', 'gif' => 'image/gif', 'png' => 'image/png',
'tif' => 'image/tiff', 'tiff' => 'image/tiff', 'ico' => 'image/x-icon',
'swf' => 'application/x-shockwave-flash', 'pdf' => 'application/pdf',
'zip' => 'application/zip', 'gz' => 'application/x-gzip',
'tar' => 'application/x-tar', 'bz' => 'application/x-bzip',
'bz2' => 'application/x-bzip2', 'txt' => 'text/plain',
'asc' => 'text/plain', 'htm' => 'text/html', 'html' => 'text/html',
'xml' => 'text/xml', 'xsl' => 'application/xsl+xml',
'ogg' => 'application/ogg', 'mp3' => 'audio/mpeg', 'wav' => 'audio/x-wav',
'avi' => 'video/x-msvideo', 'mpg' => 'video/mpeg', 'mpeg' => 'video/mpeg',
'mov' => 'video/quicktime', 'flv' => 'video/x-flv', 'php' => 'text/x-php'
);
$ext = strToLower(pathInfo($file, PATHINFO_EXTENSION));
return isset($exts[$ext]) ? $exts[$ext] : 'application/octet-stream';
}
public static function __getSignature($string) {
return 'AWS '.self::$__accessKey.':'.base64_encode(extension_loaded('hash') ?
hash_hmac('sha1', $string, self::$__secretKey, true) : pack('H*', sha1(
(str_pad(self::$__secretKey, 64, chr(0x00)) ^ (str_repeat(chr(0x5c), 64))) .
pack('H*', sha1((str_pad(self::$__secretKey, 64, chr(0x00)) ^
(str_repeat(chr(0x36), 64))) . $string)))));
}
}
final class S3Request {
private $verb, $bucket, $uri, $resource = '', $parameters = array(),
$amzHeaders = array(), $headers = array(
'Host' => '', 'Date' => '', 'Content-MD5' => '', 'Content-Type' => ''
);
public $fp = false, $size = 0, $data = false, $response;
public $uploadProgressFileName;
function __construct($verb, $bucket = '', $uri = '') {
$this->verb = $verb;
$this->bucket = strtolower($bucket);
$this->uri = $uri !== '' ? '/'.$uri : '/';
if ($this->bucket !== '') {
$this->bucket = explode('/', $this->bucket);
$this->resource = '/'.$this->bucket[0].$this->uri;
$this->headers['Host'] = $this->bucket[0].'.s3.amazonaws.com';
$this->bucket = implode('/', $this->bucket);
} else {
$this->headers['Host'] = 's3.amazonaws.com';
if (strlen($this->uri) > 1)
$this->resource = '/'.$this->bucket.$this->uri;
else $this->resource = $this->uri;
}
$this->headers['Date'] = gmdate('D, d M Y H:i:s T');
$this->response = new STDClass;
$this->response->error = false;
$this->response->body = false;
$CI =& get_instance();
$CI->load->helper('file');
}
public function setParameter($key, $value) {
$this->parameters[$key] = $value;
}
public function setHeader($key, $value) {
$this->headers[$key] = $value;
}
public function setAmzHeader($key, $value) {
$this->amzHeaders[$key] = $value;
}
//:callback function for upload progress.
public function progressCallback_new_curl($new,$download_size, $downloaded_size, $upload_size, $uploaded_size )
{
ob_start();
static $previousProgress = 0;
if ( $upload_size == 0 )
$progress = 0;
else
$progress = round( $uploaded_size * 100 / $upload_size );
if ( $progress > $previousProgress)
{
flush();
$previousProgress = $progress;
$new_file_path = FCPATH.'upload/'.$this->uploadProgressFileName.'.txt'; // modify this line to point to the actual location of the file
write_file($new_file_path, $progress."\n");
// Check for Cancel upload text file and if exists return 1 to interrupt curl upload process.
$cancel_path=FCPATH.'upload/cancel_'.$this->uploadProgressFileName.'.txt';
if(file_exists($cancel_path)){
unlink($cancel_path);
if(file_exists($new_file_path)){
unlink($new_file_path);
}
return 1;
}
}
ob_flush();
flush();
}
public function progressCallback_old_curl($download_size, $downloaded_size, $upload_size, $uploaded_size )
{
ob_start();
static $previousProgress = 0;
if ( $upload_size == 0 )
$progress = 0;
else
$progress = round( $uploaded_size * 100 / $upload_size );
if ( $progress > $previousProgress)
{
flush();
$previousProgress = $progress;
$new_file_path = FCPATH.'upload/'.$this->uploadProgressFileName.'.txt'; // modify this line to point to the actual location of the file
write_file($new_file_path, $progress."\n");
// Check for Cancel upload text file and if exists return 1 to interrupt curl upload process.
$cancel_path=FCPATH.'upload/cancel_'.$this->uploadProgressFileName.'.txt';
if(file_exists($cancel_path)){
unlink($cancel_path);
if(file_exists($new_file_path)){
unlink($new_file_path);
}
return 1;
}
}
ob_flush();
flush();
}
public function getResponse() {
$query = '';
if (sizeof($this->parameters) > 0) {
$query = substr($this->uri, -1) !== '?' ? '?' : '&';
foreach ($this->parameters as $var => $value)
if ($value == null || $value == '') $query .= $var.'&';
else $query .= $var.'='.$value.'&';
$query = substr($query, 0, -1);
$this->uri .= $query;
if (isset($this->parameters['acl']) || !isset($this->parameters['logging']))
$this->resource .= $query;
}
$url = (extension_loaded('openssl')?'https://':'http://').$this->headers['Host'].$this->uri;
//var_dump($this->bucket, $this->uri, $this->resource, $url);
// Basic setup
$curl = curl_init();
curl_setopt($curl, CURLOPT_USERAGENT, 'S3/php');
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_URL, $url);
//:callback function call for upload progress.
curl_setopt($curl, CURLOPT_NOPROGRESS, false);
if (!defined('PHP_VERSION_ID') || PHP_VERSION_ID < 50500) {
curl_setopt($curl, CURLOPT_PROGRESSFUNCTION, array($this, 'progressCallback_old_curl'));
} else {
curl_setopt($curl, CURLOPT_PROGRESSFUNCTION, array($this, 'progressCallback_new_curl'));
}
// Headers
$headers = array(); $amz = array();
foreach ($this->amzHeaders as $header => $value)
if (strlen($value) > 0) $headers[] = $header.': '.$value;
foreach ($this->headers as $header => $value)
if (strlen($value) > 0) $headers[] = $header.': '.$value;
foreach ($this->amzHeaders as $header => $value)
if (strlen($value) > 0) $amz[] = strToLower($header).':'.$value;
$amz = (sizeof($amz) > 0) ? "\n".implode("\n", $amz) : '';
// Authorization string
$headers[] = 'Authorization: ' . S3Withprogressbar::__getSignature(
$this->verb."\n".
$this->headers['Content-MD5']."\n".
$this->headers['Content-Type']."\n".
$this->headers['Date'].$amz."\n".$this->resource
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, false);
curl_setopt($curl, CURLOPT_WRITEFUNCTION, array(&$this, '__responseWriteCallback'));
curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this, '__responseHeaderCallback'));
// Request types
switch ($this->verb) {
case 'GET': break;
case 'PUT':
if ($this->fp !== false) {
curl_setopt($curl, CURLOPT_PUT, true);
curl_setopt($curl, CURLOPT_INFILE, $this->fp);
if ($this->size > 0)
curl_setopt($curl, CURLOPT_INFILESIZE, $this->size);
} elseif ($this->data !== false) {
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($curl, CURLOPT_POSTFIELDS, $this->data);
if ($this->size > 0)
curl_setopt($curl, CURLOPT_BUFFERSIZE, $this->size);
} else
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
break;
case 'HEAD':
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'HEAD');
curl_setopt($curl, CURLOPT_NOBODY, true);
break;
case 'DELETE':
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
break;
default: break;
}
// Execute, grab errors
if (curl_exec($curl))
$this->response->code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
else
$this->response->error = array(
'code' => curl_errno($curl),
'message' => curl_error($curl),
'resource' => $this->resource
);
@curl_close($curl);
// Parse body into XML
if ($this->response->error === false && isset($this->response->headers['type']) &&
$this->response->headers['type'] == 'application/xml' && isset($this->response->body)) {
$this->response->body = simplexml_load_string($this->response->body);
// Grab S3 errors
if (!in_array($this->response->code, array(200, 204)) &&
isset($this->response->body->Code, $this->response->body->Message)) {
$this->response->error = array(
'code' => (string)$this->response->body->Code,
'message' => (string)$this->response->body->Message
);
if (isset($this->response->body->Resource))
$this->response->error['resource'] = (string)$this->response->body->Resource;
unset($this->response->body);
}
}
// Clean up file resources
if ($this->fp !== false && is_resource($this->fp)) fclose($this->fp);
return $this->response;
}
private function __responseWriteCallback(&$curl, &$data) {
if ($this->response->code == 200 && $this->fp !== false)
return fwrite($this->fp, $data);
else
$this->response->body .= $data;
return strlen($data);
}
private function __responseHeaderCallback(&$curl, &$data) {
if (($strlen = strlen($data)) <= 2) return $strlen;
if (substr($data, 0, 4) == 'HTTP')
$this->response->code = (int)substr($data, 9, 3);
else {
list($header, $value) = explode(': ', trim($data));
if ($header == 'Last-Modified')
$this->response->headers['time'] = strtotime($value);
elseif ($header == 'Content-Length')
$this->response->headers['size'] = (int)$value;
elseif ($header == 'Content-Type')
$this->response->headers['type'] = $value;
elseif ($header == 'ETag')
$this->response->headers['hash'] = substr($value, 1, -1);
elseif (preg_match('/^x-amz-meta-.*$/', $header))
$this->response->headers[$header] = is_numeric($value) ? (int)$value : $value;
}
return $strlen;
}
}
?>
``` |
17,843,622 | I measure cpu time and wall time of sorting algorithms on linux. Im using `getrusage` to measure a cpu time and `clock_gettime CLOCK_MONOTONIC` to get a wall time. Althought I noticed that a cpu time is bigger than wall time - is that correct? I always thought that cpu time MUST be less than wall time. My example results:
```
3.000187 seconds [CPU]
3.000001 seconds [WALL]
``` | 2013/07/24 | [
"https://Stackoverflow.com/questions/17843622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1367705/"
] | If a computation requires two seconds of processor time, then two processors can (ideally) complete it in one second. Hence a two-processor system has two CPU seconds for every wall-clock second. Even if you do not use multi-threading explicitly in your process, a library you use or the operating system may use multiple processors to perform work for your process.
Additionally, some of the accounting is approximate. A system might track processor time in some small unit, say microseconds for the purpose of argument, and charge a process for a microsecond anytime the process receives at least half a microsecond of processor time. (Which should be a lesson to all the people who answer floating-point questions with recommendations to use integer arithmetic to avoid rounding errors. All discrete arithmetic can have rounding errors.) | Depending on the argument you use, `getrusage` may return the sum of CPU time across all threads in your process. If you have more than one thread this can cause the CPU time to be higher than the wall clock time.
Also, while the result structure stores the values in microseconds, the actual precision may be much lower than that, hence the small discrepancy. |
6,062,306 | Looking for a jQuery ninja's assistance. My jQuery below works but I have a strong suspicion that how I have selected these elements can be much improved. How best to select these elements? Can my code be improved? (See purpose below, important to note I only want to select the first div class results and image within)
```
<div id="priceInventory">
<div class="Hdr">Some Unique Header</div>
<div class="results">
<div onclick="showInfo('#RandomId');" class="xx yy"><img class="arrow" src="/images/arrow-up.png"> Title</div>
<div style="display: none;" id="RandomId">Unique Content</div>
</div>
<div class="results">
<div onclick="showInfo('#RandomId');" class="xx yy"><img class="arrow" src="/images/arrow-up.png"> Title</div>
<div style="display: none;" id="RandomId">Unique Content</div>
</div>
<div class="results">
<div onclick="showInfo('#RandomId');" class="xx yy"><img class="arrow" src="/images/arrow-up.png"> Title</div>
<div style="display: none;" id="RandomId">Unique Content</div>
</div>
<!-- results repeats -->
```
```
<script>
$("body div#priceInventory div:nth-child(2) div:nth-child(2)").show();
$("body div#priceInventory div:nth-child(2) div:nth-child(1) img").attr('src','/images/arrow-dwn.png');
</script>
```
The general purpose of the code is to display the content of only the first set of content when the page loads. The arrow is also updated to indicate the this content is being displayed.
Thanks so much, I heart you stackoverflow friends. I hope others find this helpful as well. | 2011/05/19 | [
"https://Stackoverflow.com/questions/6062306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/337529/"
] | You'd need an Objective-C class to handle Objective-C notifications. *Core Foundation to the rescue!*
In.. wherever you start listening for notifications, e.g. your constructor:
```
static void notificationHandler(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo);
MyClass::MyClass() : {
// do other setup ...
CFNotificationCenterAddObserver
(
CFNotificationCenterGetLocalCenter(),
this,
¬ificationHandler,
CFSTR("notify"),
NULL,
CFNotificationSuspensionBehaviorDeliverImmediately
);
}
```
When done, e.g. in your destructor:
```
MyClass::~MyClass() {
CFNotificationCenterRemoveEveryObserver
(
CFNotificationCenterGetLocalCenter(),
this
);
}
```
And finally, a static function to handle the dispatch:
```
static void notificationHandler(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo) {
(static_cast<MyClass *>(observer))->reallyHandleTheNotification();
}
```
Ta da! | You can't add a C++ method as an observer because of how Objective-C method handles method invocation vs C++. You must have an Objective-C class (Declared with `@interface Class` .. `@end`) to respond to those methods.
Your only option is to wrap your C++ class in an Objective-C class, or just have a very light wrapper that just has a reference to an object and calls a method statically once the notification arrives. |
44,211,253 | I have two numpy arrays (with different lengths)
The first one is (n) like:
```
a = [0, 1, 2, 5, 6, 7]
```
The second one is (n,3) like:
```
b = [[0, 1, 3],[8, 3, 9],[9, 8, 4],[0, 4, 5],[1, 7, 3],[1, 5, 7],[2, 3, 7],[4, 2, 6],[5, 4, 6],[5, 6, 7]]
```
Now I want to check every column of the second array whether it contains one of the numbers from the first array and return the index of that column if possible.
```
b[0] -> [0, 1, 3] contains 0 and 1 so I need that index (only once)
b[1] -> [8, 3, 9] does not contain any of the numbers from a, so I don't need that index
```
The result shell be an array which contains all those indexes, in this example like:
```
indexes = [0, 3, 4, 5....]
```
Is there a way to check that? Processing speed is not a matter! | 2017/05/26 | [
"https://Stackoverflow.com/questions/44211253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7580878/"
] | List **b** is to be understood as a matrix where the sublists are *rows*, NOT *columns*.
That being said, and considering the examples you have provided, I assume that what you actually want to do is finding the matches in the rows of b. Then we would proceed as follows:
1. Check if any of the numbers within **a** match the ones contained on a given sublist of **b**.
2. Obtain an array whose elements are the indexes that identify those sublists of **b** that have, at least, one of the numbers of **a**.
I would go with standard Python 3 sintax, using a list. Then, I would convert it into an array using the numpy *asarray* function:
```
import numpy as np
def matches(a,b):
list = []
for i in range(len(b)):
for j in range(len(b[0])):
if b[i][j] in a:
list = list+[i]
break
else:
pass
arrayIndexes = np.asarray(list)
return arrayIndexes
print(matches([0,1,2,5,6,7],
[[0,1,3],
[8,3,9],
[9,8,4],
[0,4,5],
[1,7,3],
[1,5,7],
[2,3,7],
[4,2,6],
[5,4,6],
[5,6,7]]))
```
And the return numpy array with the indexes would be the object called *arrayIndexes*, and would contain the following:
```
array([0,3,4,5,6,7,8,9])
``` | You can do it simply with `list comprehension` and using `any()` like this example:
```
a = [0, 1, 2, 5, 6, 7]
b = [[0, 1, 3],[8, 3, 9],[9, 8, 4],[0, 4, 5],[1, 7, 3],[1, 5, 7],[2, 3, 7],[4, 2, 6],[5, 4, 6],[5, 6, 7]]
final = [k for k in range(len(b)) if any(j in b[k] for j in a)]
print(final)
```
Output:
```
[0, 3, 4, 5, 6, 7, 8, 9]
``` |
261,974 | How much overhead does x86/x64 virtualization (I'll probably be using VirtualBox, possbly VMWare, definitely not paravirtualization) have for each of the following operations a Win64 host and Linux64 guest using Intel hardware virtualization?
* Purely CPU-bound, user mode 64-bit code
* Purely CPU-bound, user mode 32-bit code
* File I/O to the hard drive (I care mostly about throughput, not latency)
* Network I/O
* Thread synchronization primitives (mutexes, semaphores, condition variables)
* Thread context switches
* Atomic operations (using the `lock` prefix, things like compare-and-swap)
I'm primarily interested in the hardware assisted x64 case (both Intel and AMD) but wouldn't mind hearing about the unassisted binary translation and x86 (i.e. 32-bit host and guest) cases, too. I'm not interested in paravirtualization. | 2011/04/20 | [
"https://serverfault.com/questions/261974",
"https://serverfault.com",
"https://serverfault.com/users/43050/"
] | I found that there isn't simple and absolute answer for questions like yours. Each virtualization solution behaves differently on specific performance tests. Also, tests like disk I/O throughput can be split in many different tests (read, write, rewrite, ...) and the results will vary from solution to solution, and from scenario to scenario. This is why it is not trivial to point one solution as being the fastest for disk I/O, and this is why there is no absolute answer for labels like overhead for disk I/O.
It gets more complex when trying to find relation between different benchmark tests. None of the solutions I've tested had good performance on micro-operations tests. For example: Inside VM one single call to "gettimeofday()" took, in average, 11.5 times more clock cycles to complete than on hardware. The hypervisors are optimized for real world applications and do not perform well on micro-operations. This may not be a problem for your application that may fit better as real world application. I mean by micro-operation any application that spends less than 1,000 clock cycles to finish(For a 2.6 GHz CPU, 1,000 clock cycles are spent in 385 nanoseconds, or 3.85e-7 seconds).
I did extensive benchmark testing on the four main solutions for data center consolidation for x86 archictecture. I did almost 3000 tests comparing performance inside VMs with the hardware performance. I've called 'overhead' the difference of maximum performance measured inside VM(s) with maximum performance measured on hardware.
**The solutions:**
* VMWare ESXi 5
* Microsoft Hyper-V Windows 2008 R2 SP1
* Citrix XenServer 6
* Red Hat Enterprise Virtualization 2.2
**The guest OSs:**
* Microsoft Windows 2008 R2 64 bits
* Red Hat Enterprise Linux 6.1 64 bits
**Test Info:**
* Servers: 2X Sun Fire X4150 each with 8GB of RAM, 2X Intel Xeon E5440 CPU, and four gigabit Ethernet ports
* Disks: 6X 136GB SAS disks over iSCSI over gigabit ethernet
**Benchmark Software:**
* CPU and Memory: [Linpack benchmark](http://software.intel.com/en-us/articles/intel-math-kernel-library-linpack-download/) for both 32 and 64 bits. This is CPU and memory intensive.
* Disk I/O and Latency: Bonnie++
* Network I/O: Netperf: TCP\_STREAM, TCP\_RR, TCP\_CRR, UDP\_RR and UDP\_STREAM
* Micro-operations: [rdtscbench](https://github.com/petersenna/rdtscbench): System calls, inter process pipe communication
**The averages are calculated with the parameters:**
* CPU and Memory: AVERAGE(HPL32, HPL64)
* Disk I/O: AVERAGE(put\_block, rewrite, get\_block)
* Network I/O: AVERAGE(tcp\_crr, tcp\_rr, tcp\_stream, udp\_rr, udp\_stream)
* Micro-operations AVERAGE(getpid(), sysconf(), gettimeofday(), malloc[1M], malloc[1G], 2pipes[], simplemath[])
For my test scenario, using my metrics, the averages of the results of the four virtualization solutions are:
**VM layer overhead, Linux guest:**
* CPU and Memory: 14.36%
* Network I/O: 24.46%
* Disk I/O: 8.84%
* Disk latency for reading: 2.41 times slower
* Micro-operations execution time: 10.84 times slower
**VM layer overhead, Windows guest:**
* CPU and Memory average for both 32 and 64 bits: 13.06%
* Network I/O: 35.27%
* Disk I/O: 15.20%
Please note that those values are generic, and do not reflect the specific cases scenario.
Please take a look at the full article: <http://petersenna.com/en/projects/81-performance-overhead-and-comparative-performance-of-4-virtualization-solutions> | There are too many variables in your question, however I could try to narrow it down. Let's assume that you go with VMware ESX, you do everything right - latest CPU with support for virtualaization, VMware tools with paravirtualized storage and network drivers, plenty of memory. Now let's assume that you run a single virtual machine on this setup. From my experience, you should have ~90% of CPU speed for CPU bound workload. I cannot tell you much about network speeds, since we are using 1Gbps links and I can saturate it without a problem, it may be different with 10Gbps link however we do not have any of those. Storage throughput depends on type of storage, with I can get around ~80% of storage throughput with local storage, but for 1Gbps NFS it is close to 100% since networking is bottleneck here. Cannot tell about other metrics, you will need to do experimentation with your own code.
These numbers are very approximate and it highly depends on your load type, your hardware, your networking. It is getting even fuzzier when you run multiple workloads on the server. But what I'm truing to say here is that under ideal conditions you should be able to get as close as 90% of native performance.
Also from my experience the much bigger problem for high performance applications is latency and it is especially true for client server applications. We have a computation engine that receives request from 30+ clients, performs short computations and returns results. On bare metal it usually pushes CPU to 100% but same server on VMware can only load CPU to 60-80% and this is primarily because of the latency in handling requests/replies. |
59,576,578 | Very new to React and I keep getting the warning above. Have tried various methods to fix it, but had no luck, code is where I'm up to now. Probably something very simple, but I just cannot see it. I'm not running React through NodeJs and it's working apart from this warning.
**BuildList.js file**
```
const ListItem = props => {
return (
<li key={`${props.title}${props.index}`} className="my-list" onClick={props.onDelete}>
{props.title}
</li>
)
}
```
```
class BuildList extends React.Component {
constructor(props) {
super(props);
this.state = {items: props.data};
}
addItemHandler() {
this.setState(prevState => {
var newItem = prompt("Enter some text");
if(newItem) {
return {items: prevState.items.concat(newItem)};
}
});
}
deleteItemHandler(txt) {
this.setState(prevState => {
if(confirm('Are you sure?')) {
return {items: prevState.items.filter(item => {
return item !== txt;
}
)};
}
});
}
render() {
return (
<div>
<p style={{'fontWeight': '700'}}>{this.props.intro}</p>
<ul className="list-unstyled">
{this.state.items.map((item, index) => {
return (
<ListItem key={item} title={item} onDelete={this.deleteItemHandler.bind(this, item)} />
)
})}
</ul>
<button onClick={this.addItemHandler.bind(this)} className="btn btn-sm btn-success">Add</button>
</div>
)
}
}
```
**app.js file**
```
(function(){
//Defaults
const domContainer = document.querySelector('#root');
//Final output
ReactDOM.render(
[
<BuildList data = {['Item 1','Item 2', 'Item 3', 'Item 4']} intro="My first React list" />,
], domContainer);
}) ()
```
***Below is the full warning message:***
```
react-dom.development.js:524 Warning: Each child in a list should have a unique "key" prop. See LINK TO WEBSITE for more information.
warningWithoutStack @ react-dom.development.js:524
warning @ react-dom.development.js:1012
warnForMissingKey @ react-dom.development.js:14793
warnOnInvalidKey @ react-dom.development.js:15259
reconcileChildrenArray @ react-dom.development.js:15310
reconcileChildFibers @ react-dom.development.js:15744
reconcileChildren @ react-dom.development.js:18242
updateHostRoot @ react-dom.development.js:18713
beginWork$1 @ react-dom.development.js:20336
beginWork$$1 @ react-dom.development.js:25902
performUnitOfWork @ react-dom.development.js:24841
workLoopSync @ react-dom.development.js:24817
performSyncWorkOnRoot @ react-dom.development.js:24416
scheduleUpdateOnFiber @ react-dom.development.js:23844
updateContainer @ react-dom.development.js:27249
(anonymous) @ react-dom.development.js:27674
unbatchedUpdates @ react-dom.development.js:24579
legacyRenderSubtreeIntoContainer @ react-dom.development.js:27673
render @ react-dom.development.js:27754
(anonymous) @ apps-dist.js:1
(anonymous) @ apps-dist.js:1
``` | 2020/01/03 | [
"https://Stackoverflow.com/questions/59576578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/717192/"
] | Try this
```
render() {
return (
<div>
<p style={{'fontWeight': '700'}}>{this.props.intro}</p>
<ul className="list-unstyled">
{this.state.items.map((item, index) => {
return (
<ListItem key={index} title={item} onDelete={this.deleteItemHandler.bind(this, item)} />
)
})}
</ul>
<button onClick={this.addItemHandler.bind(this)} className="btn btn-sm btn-success">Add</button>
</div>
)
}
``` | [Codesandbox Link](https://codesandbox.io/embed/unruffled-colden-o66t2?fontsize=14&hidenavigation=1&theme=dark)
I have reproduced a minimal example using your code. After adding `key={index}`, i do not see any warnings. However if you remove "key" attribute, you will see warnings. |
10,404,067 | I have a UITextField that when clicked brings up a number pad with a decimal point in the bottom left. I am trying to limit the field so that a user can only place 1 decimal mark
e.g.
2.5 OK
2..5 NOT OK | 2012/05/01 | [
"https://Stackoverflow.com/questions/10404067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1282180/"
] | Implement the shouldChangeCharactersInRange method like this:
```
// Only allow one decimal point
// Example assumes ARC - Implement proper memory management if not using.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSArray *arrayOfString = [newString componentsSeparatedByString:@"."];
if ([arrayOfString count] > 2 )
return NO;
return YES;
}
```
This creates an array of strings split by the decimal point, so if there is more than one decimal point we will have at least 3 elements in the array. | **Swift 3** Implement this UITextFieldDelegate method to prevent user from typing an invalid number:
```
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let text = (textField.text ?? "") as NSString
let newText = text.replacingCharacters(in: range, with: string)
if let regex = try? NSRegularExpression(pattern: "^[0-9]*((\\.|,)[0-9]*)?$", options: .caseInsensitive) {
return regex.numberOfMatches(in: newText, options: .reportProgress, range: NSRange(location: 0, length: (newText as NSString).length)) > 0
}
return false
}
```
It is working with both comma or dot as decimal separator. You can also limit number of fraction digits using this pattern: `"^[0-9]*((\\.|,)[0-9]{0,2})?$"` (in this case 2). |
139,716 | In theory what is 'cheaper': buying a home or building one?.
For simplicity we could assume that the terrain size is the same, in the same area, using the same house model (to calculate the material used to build the home).
***What I'm looking for is for a simple formula to evaluate if it's more convenient buy or build.*** | 2021/04/09 | [
"https://money.stackexchange.com/questions/139716",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/39200/"
] | The question is "in theory," so the answer may be that custom house building is more expensive in theory than the semi-automated house building by a professional homebuilder, even including the professional homebuilder's profit.
However, if you enjoy the process of haggling with landowners, lenders and contractors, getting government approvals and wrangling the contractors, then you could value your time at zero and come out ahead. Some people do genuinely love this stuff and it could count as a beloved hobby for them. | It's much cheaper to buy a house than build one. Modern house builders take lots of shortcuts to try to make their products competitive with older houses in price and the result of this is that modern houses are much lower quality than houses made in the 1950s or before. The only houses that are worse than the houses now are houses built in the 1970s. Never buy a house built between 1968 and 1978. Houses built in the 1990s will be higher quality and cheaper than anything you could build now.
Also, building a house takes at least a year, if you can even find the workers. Due to government free money it is hard to find people willing to work, especially on manual labor jobs, so cost of construction is astronomical right now as well as being slow. |
17,775,772 | I have the following...
```
var request = require('request');
exports.list = function(req, res){
res.send("Listing");
};
exports.get = function(req, res){
request.get("<URL>", function (err, res, body) {
if (!err) {
res.send(body,"utf8");
}
});
};
```
This fails with the following....
```
TypeError: Object #<IncomingMessage> has no method 'send'
```
How do I do this?
**UPDATE** tried to use write instead of send but...
```
/Users/me/Development/htp/routes/property.js:9
res.setHeader('Content-Type', 'text/html');
^
TypeError: Object #<IncomingMessage> has no method 'setHeader'
```
Also writing out to the console instead works fine. | 2013/07/21 | [
"https://Stackoverflow.com/questions/17775772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/125212/"
] | Problem was with scope of variables, my response output was the same name as the response object I got back in my callback. Changing this around (resp vs res) made it work....
```
exports.get = function(req, res){
request.get("<url>", function (err, resp, body) {
if (!err) {
res.send(body);
}
});
};
``` | I wasn't aware OP is using Express. You will encounter a similar error if you attempt to use `req.send` with the vanilla HTTP module instead of Express.
```
var http = require('http');
function requestHandler(req, res){
//res.send(200, '<html></html>'); // not a valid method without express
res.setHeader('Content-Type', 'text/html');
res.writeHead(200);
res.end('<html><body>foo bar</body></html>');
};
http.createServer(handler).listen(3000);
``` |
2,568,842 | All,
I am trying to use JQuery's URL Validator plugin.
<http://docs.jquery.com/Plugins/Validation/Methods/url>
I have a text box that has a URL. I want to write a function which takes the textbox value, uses the jquery's validator plugin to validate urls and returns true or false.
Something like Ex:
```
function validateURL(textval)
{
// var valid = get jquery's validate plugin return value
if(valid)
{
return true;
}
return false;
}
```
I wanted this to be a reusable function..
Thanks | 2010/04/02 | [
"https://Stackoverflow.com/questions/2568842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/229853/"
] | The validate() jQuery is made to validate a form itself I believe, not just an individual field.
I think you would be better off using a regex to validate a single textbox if you are not trying to a do a form validation.
Here's an example of a SO question that works.
```
function validateURL(textval) {
var urlregex = new RegExp(
"^(http:\/\/www.|https:\/\/www.|ftp:\/\/www.|www.){1}([0-9A-Za-z]+\.)");
return urlregex.test(textval);
}
```
Source: [here](https://stackoverflow.com/questions/1303872/url-validation-using-javascript) | While validating URLs you should consider that there are new TLDs being approved and now you can use non-Latin characters in domain names (e.g. [http://пример.испытание](http://%D0%BF%D1%80%D0%B8%D0%BC%D0%B5%D1%80.%D0%B8%D1%81%D0%BF%D1%8B%D1%82%D0%B0%D0%BD%D0%B8%D0%B5) is a valid URL). So proper regex which complies with RFC 3987 (<http://www.faqs.org/rfcs/rfc3987.html>) looks like this ([taken from this post](https://stackoverflow.com/questions/161738/what-is-the-best-regular-expression-to-check-if-a-string-is-a-valid-url))
```
/^[a-z](?:[-a-z0-9\+\.])*:(?:\/\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:])*@)?(?:\[(?:(?:(?:[0-9a-f]{1,4}:){6}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|::(?:[0-9a-f]{1,4}:){5}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:[0-9a-f]{1,4}:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+[-a-z0-9\._~!\$&'\(\)\*\+,;=:]+)\]|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}|(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=@])*)(?::[0-9]*)?(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*|\/(?:(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*)?|(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*|(?!(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])))(?:\?(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])|[\x{E000}-\x{F8FF}\x{F0000}-\x{FFFFD}|\x{100000}-\x{10FFFD}\/\?])*)?(?:\#(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])|[\/\?])*)?$/i
```
You can use this expression with JavaScript, or use [jQuery validation plugin](http://bassistance.de/jquery-plugins/jquery-plugin-validation/) which has build in validators for URL and email addresses |
538,996 | I have installed 3 new packages recently through NPM and none of them are executing.
I ran `sudo npm install -g ionic` and the installation looked like normal.
Then I can run `which ionic` and I get `/usr/local/bin/ionic` which looks good.
But if I run `ionic start myApp tabs` according to the documentation this should create a new ionic project. But instead it does absolutely nothing. No output on the command line, no project created. I press enter to execute the command and it **immediately** returns to another line on the command line as if I simply pressed enter with no command entered at all... This may not be clear, sorry.
I tried uninstalling ionic with `sudo npm uninstall -g ionic` which uninstalled it successfully, and then re-installed it. No change in behavior. Same is happening for the packages `cordova` and `bower`. Note: all of these I installed at the same time, and all of them are not working. No output, no errors, no nothing. Running them with `sudo` doesn't make a difference either.
I am running ubuntu 14.04.
Has anyone experienced this before? | 2014/10/19 | [
"https://askubuntu.com/questions/538996",
"https://askubuntu.com",
"https://askubuntu.com/users/340229/"
] | 1. Run
```
which node
```
and in my case it displayed `/usr/sbin/node`.
2. If it says `command not found`, skip to 3. Remove it by
```
sudo rm /usr/sbin/node
```
3. Run
```
which nodejs
```
in my case it displayed `/usr/bin/nodejs`.
4. Make a link
```
sudo ln -s /usr/bin/nodejs /usr/bin/node
```
OR
```
sudo ln -s /usr/bin/nodejs /usr/sbin/node
``` | it also can be because of outdated nodejs installed
according to <https://stackoverflow.com/questions/21362636/phonegap-cli-on-linux-doesnt-do-anything> it can be fixed in next way:
```
sudo apt-get install curl
npm update npm -g
sudo npm install n -g
sudo n stable
```
and then `npm remove -g ionic && npm install -g ionic` |
49,796,312 | I'm trying to convert an existing callback based function from the crypto library to be used with es6 `async/await` in the method above it. Whenever I make a call to `generateSubkey(password,salt)` it returns `[function]`. Inside this if I call `toString()` it shows my methods code as opposed to executing it.
```
import crypto from 'crypto';
import Promise from 'bluebird';
async hashPassword(password) {
try {
// Create a salt with cryptographically secure method.
let salt = await crypto.randomBytes(16);
let subkey = await this.generateSubkey(password, salt);
console.log(subkey);
} catch (e) {
}
}
generateSubkey(password, salt) {
return new Promise.resolve((resolve, reject) => {
return crypto.pbkdf2(password, salt, 10000, 32, 'sha256', (err, buffer) => {
if (err) {
reject();
}
resolve(buffer);
});
})
}
``` | 2018/04/12 | [
"https://Stackoverflow.com/questions/49796312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3342835/"
] | If I understood you correctly, you just want to print every occurrence of the first item regardless of repetitions, and print it only once? To do so, you can use a `set`:
```
print(", ".join(set(e[0] for e in rows)))
# python, html, PHP
```
If you need to keep the order, then it's a bit more difficult - you'll have to use a temporary set to weed out the duplicates:
```
seen = set() # temp set
print(", ".join(l for l, p in rows if l not in seen and not seen.add(l)))
# python, PHP, html
``` | you can use a list ( as checklist )
```
rows = (('python', 'kivy'), ('python', 'tkinter'),("python","wxpython"),('PHP', 'bootstrap'),('html', 'ajax'),('html', 'css') )
lista=[]
for i in rows:
if i[0] not in lista:
lista.append(i[0])
print(i[0])
```
or
```
rows = (('python', 'kivy'), ('python', 'tkinter'),("python","wxpython"),('PHP', 'bootstrap'),('html', 'ajax'),('html', 'css') )
lista=[]
[lista.append(i[0]) for i in rows if i[0] not in lista]
for i in lista: print(i)
``` |
60,845,822 | A bit of background, I mainly work in .Net/C# and never did any PHP my whole life and my company gave me an existing PHP code and asked me add some feature to it.
The webpage I need to work on is a catering system. The page recalculates the total price when there are changes to the number of pax. This worked fine if every item in the menu is similarly priced.
```
function RefreshPrice() {
menuid = getQueryString('menuid');
$.ajax({
url: "ajax.php",
type: "POST",
data: {
refreshprice: "refreshprice",
menuid: menuid,
},
success: function(data, textStatus, jqXHR) {
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error");
}
});
}
```
But now there are items that cost more than others, so I need to recalculate on each item selection. I'm trying to use a hidden field to store the additional price for the item.
```
<input type="checkbox" class="validate-checkbox" item-name="<?php echo $item["Name"];?>"
name="menuitem[]" value="<?php echo $item["Id"];?>">
<input type="hidden" class="addprice" name="addprice" value="<?php echo $item["AddPrice"];?>">
```
But how do I get the values of the hidden field of each selected item so I can do something like this.
```
function RefreshPrice() {
menuid = getQueryString('menuid');
addprice= document.getElementsByClassName("addprice:checked").val(); //OR $(".addprice:checked").val();
$.ajax({
url: "ajax.php",
type: "POST",
data: {
refreshprice: "refreshprice",
menuid: menuid,
addprice: addprice,
},
success: function(data, textStatus, jqXHR) {
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error");
}
});
}
```
Sorry if this is a duplicate question, but most answer I found were using form submit POST method and got them using `$_POST["addprice"]`, but this is manually constructing the ajax POST. | 2020/03/25 | [
"https://Stackoverflow.com/questions/60845822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6459097/"
] | To quote from psycopg2's [documentation](https://www.psycopg.org/docs/usage.html):
*Warning Never, never, NEVER use Python string concatenation (+) or string parameters interpolation (%) to pass variables to a SQL query string. Not even at gunpoint.*
Now, for an upsert operation you can do this:
```
insert_sql = '''
INSERT INTO tablename (col1, col2, col3, col4)
VALUES (%s, %s, %s, %s)
ON CONFLICT (col1) DO UPDATE SET
(col2, col3, col4) = (EXCLUDED.col2, EXCLUDED.col3, EXCLUDED.col4);
'''
cur.execute(insert_sql, (val1, val2, val3, val4))
```
Notice that the **parameters** for the query are being passed as a tuple to the `execute` statement (this assures psycopg2 will take care of adapting them to SQL while shielding you from injection attacks).
The `EXCLUDED` bit allows you to reuse the values without the need to specify them twice in the data parameter. | Try:
```
INSERT INTO tablename (col1, col2, col3,col4)
VALUES (val1,val2,val3,val4)
ON CONFLICT (col1)
DO UPDATE SET
(col2, col3, col4)
= (val2, val3, val4) ; '''
``` |
4,927,860 | I'm making a little chat messenger program, which needs a list of chat channels the user has joined. To represent this list graphically, I have made a list of `QPushButtons`, which all represent a different channel. These buttons are made with the following method, and that's where my problem kicks in:
```
void Messenger::addToActivePanels(std::string& channel)
{
activePanelsContents = this->findChild<QWidget *>(QString("activePanelsContents"));
pushButton = new QPushButton(activePanelsContents);
pushButton->setObjectName("pushButton");
pushButton->setGeometry(QRect(0, 0, 60, 60));
pushButton->setText("");
pushButton->setToolTip(QString(channel.c_str()));
pushButton->setCheckable(true);
pushButton->setChecked(false);
connect(pushButton, SIGNAL(clicked()), this, SLOT(switchTab(channel)));
}
```
(activePanelContents is a QWidget that holds the list.)
The point is that each button should call the `switchTab(string& tabname)` method when clicked, including the specific channel's name as variable. This implementation doesn't work though, and I haven't been able to find out how to properly do this. | 2011/02/07 | [
"https://Stackoverflow.com/questions/4927860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/598639/"
] | Use `QSignalMapper` to pass variables;
```
QSignalMapper* signalMapper = new QSignalMapper (this) ;
QPushButton *button = new QPushButton();
signalMapper -> setMapping (button, <data>) ;
connect (signalMapper, SIGNAL(mapped(QString)), this,
SLOT(buttonClicked(QString))) ;
```
in slot i.e
```
void class::buttonClicked(QString data){
//use data
// to get sender
QSignalMapper *temp = (QSignalMapper *)this->sender();
QPushButton *btn = (QPushButton *)temp->mapping(data);
// use btn
}
```
Hope my ans may help you | Don't use the sender method unless you absolutely have to. It ties the function directly to being used only as a slot (can't be called directly). Retain the behavior of having the function accept a string and simply make a mechanism by which you can call it.
One method, among others you might find, is to leverage use of QSignalMapper. It will map objects to values and regenerate signals of the appropriate signature. |
49,685,217 | Suppose I have the following DataFrame:
```
scala> val df1 = Seq("a", "b").toDF("id").withColumn("nums", array(lit(1)))
df1: org.apache.spark.sql.DataFrame = [id: string, nums: array<int>]
scala> df1.show()
+---+----+
| id|nums|
+---+----+
| a| [1]|
| b| [1]|
+---+----+
```
And I want to add elements to the array in the `nums` column, so that I get something like the following:
```
+---+-------+
| id|nums |
+---+-------+
| a| [1,5] |
| b| [1,5] |
+---+-------+
```
Is there a way to do this using the `.withColumn()` method of the DataFrame? E.g.
```
val df2 = df1.withColumn("nums", append(col("nums"), lit(5)))
```
I've looked through the API documentation for Spark, but can't find anything that would allow me to do this. I could probably use `split` and `concat_ws` to hack something together, but I would prefer a more elegant solution if one is possible. Thanks. | 2018/04/06 | [
"https://Stackoverflow.com/questions/49685217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2251463/"
] | ```
import org.apache.spark.sql.functions.{lit, array, array_union}
val df1 = Seq("a", "b").toDF("id").withColumn("nums", array(lit(1)))
val df2 = df1.withColumn("nums", array_union($"nums", lit(Array(5))))
df2.show
+---+------+
| id| nums|
+---+------+
| a|[1, 5]|
| b|[1, 5]|
+---+------+
```
The `array_union()` was added since spark 2.4.0 release on 11/2/2018, 7 months after you asked the question, :) see <https://spark.apache.org/news/index.html> | If you are, like me, searching how to do this in a Spark SQL statement; here's how:
```
%sql
select array_union(array("value 1"), array("value 2"))
```
You can use array\_union to join up two arrays. To be able to use this, you have to turn your value-to-append into an array. Do this by using the array() function.
You can enter a value like array("a string") or array(yourColumn). |
15,296,637 | Why after the first loop, the switch will execute twice before it stop to wait for my input? Is there any char left in the standard input? How can I fix the issue?
```
while(true)
{
int choice = System.in.read();
switch(choice)
{
case '1':
break;
default:
break;
}
}
``` | 2013/03/08 | [
"https://Stackoverflow.com/questions/15296637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1701045/"
] | If you again print choice somewhere, probably you will get 10 and 13.
* '10' is LF (line feed control char).
* '13' is CR (carriage return control char).
This is why the switch is executing twice.
And the better way of taking input already have been shown by Reimeus, Chris Cooney. | You can use **Break to Labeled Statement** in this case. for more information <http://www.javaspecialists.eu/archive/Issue110.html>
**Here is workign code:**
```
import java.io.IOException;
public class Switch {
public static void main(String[] args) throws IOException {
exitWhile: {
while (true) {
System.out.println("type>");
int choice = System.in.read();
switch (choice) {
case '1':
break;
default:
System.out.println("Default");
break exitWhile;
}
}
}
}
}
``` |
65,338,957 | For a school project, I'm trying to re-create the `printf` function of the `stdio.h` library in C.
I'm currently working on getting the `unsigned int` printing part working, but for some reason, why I try the real `printf` to print an unsigned int, it gives me a warning (which is considered as an error in my school). Could you someone explain me why?
Here is the code line I have used: `printf("%u\n", 4294967295);`. And here is the error I'm gettting:
```
main.c:18:17: warning: format specifies type 'unsigned int' but the argument has type 'long' [-Wformat]
printf("%u\n", 4294967295);
~~ ^~~~~~~~~~
%ld
1 warning generated.
``` | 2020/12/17 | [
"https://Stackoverflow.com/questions/65338957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14608442/"
] | All integer constants such as `4294967295` have a type, just like declared variables. The C compiler assigns a type to such a constant based on various intricate rules. A simplified explanation is that these rules basically boil down to:
* "Does it fit in an `int`? If so, make it `int`."
* "Otherwise does it fit in a `long`?" ... and so on.
Note that these default types are signed types.
On a 32 bit computer with 32 bit int, the largest number you can store in an `int` is 2^31 - 1 = `2147483647`. `4294967295` is larger than that, so the compiler has to store it in a `long`. Hence the warning.
Since `4294967295` would have fit in an `unsigned int`, so you could fix the code by simply forcing the compiler to treat the integer constant as unsigned: `4294967295u`. | The type of an integer literal is taken as the first type in the list in the standard that fits. The list for literals without the any suffix is `int`, `long int`, `long long int`/`unsigned long int`. As 4294967295 doesn't fit in `int`, it'll be `long` if `long` is a type wider than 32-bit (which is the case on your platform). To get an `unsigned int` literal you need to use the `U` suffix
>
> [The type of integer constant](https://en.cppreference.com/w/c/language/integer_constant)
> =========================================================================================
>
>
> The type of the integer literal is the first type in which the value can fit, from the list of types which depends on which numeric base and which *integer-suffix* was used.
>
>
> **Types allowed for integer constants:**
>
>
> * no suffix
> + decimal bases:
> - int
> - long int
> - unsigned long int (until C99)
> - long long int (since C99)
> + other bases:
> - int
> - unsigned int
> - long int
> - unsigned long int
> - long long int (since C99)
> - unsigned long long int (since C99)
> * ...
>
>
> If the value of the integer constant is too big to fit in any of the types allowed by suffix/base combination and the compiler supports extended integer types (such as `__int128`), the constant may be given the extended integer type; otherwise, the program is ill-formed.
>
>
> |
28,391,798 | How can I change the supported TLS versions on my HttpClient?
I'm doing:
```
SSLContext sslContext = SSLContext.getInstance("TLSv1.1");
sslContext.init(
keymanagers.toArray(new KeyManager[keymanagers.size()]),
null,
null);
SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext, new String[]{"TLSv1.1"}, null, null);
Scheme scheme = new Scheme("https", 443, socketFactory);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(scheme);
BasicClientConnectionManager cm = new BasicClientConnectionManager(schemeRegistry);
httpClient = new DefaultHttpClient(cm);
```
But when I check the created socket, it still says the supported protocols are TLSv1.0, TLSv1.1 and TLSv1.2.
In reality I just want it to stop using TLSv1.2, for this specific HttpClient. | 2015/02/08 | [
"https://Stackoverflow.com/questions/28391798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/719153/"
] | This is how I got it working on httpClient 4.5 (as per Olive Tree request):
```
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(AuthScope.ANY_HOST, 443),
new UsernamePasswordCredentials(this.user, this.password));
SSLContext sslContext = SSLContexts.createDefault();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
new String[]{"TLSv1", "TLSv1.1"},
null,
new NoopHostnameVerifier());
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider)
.setSSLSocketFactory(sslsf)
.build();
return httpclient;
``` | If you have a [javax.net.ssl.SSLSocket](https://docs.oracle.com/javase/8/docs/api/index.html?javax/net/ssl/SSLSocket.html) class reference in your code, you can set the enabled TLS protocols by a call to [SSLSocket.setEnabledProtocols()](https://docs.oracle.com/javase/8/docs/api/javax/net/ssl/SSLSocket.html#setEnabledProtocols-java.lang.String:A-):
```
import javax.net.ssl.*;
import java.net.*;
...
Socket socket = SSLSocketFactory.getDefault().createSocket();
...
if (socket instanceof SSLSocket) {
// "TLSv1.0" gives IllegalArgumentException in Java 8
String[] protos = {"TLSv1.2", "TLSv1.1"}
((SSLSocket)socket).setEnabledProtocols(protos);
}
``` |
58,743,664 | I have been trying to install `PySide2` on my PC (`Windows 10 64bits`) with `Python 3.8` installed, but I keep getting errors every time.
I used the command `pip install PySide2`. It is not working for me.
Any help will be appreciated.
**Error:**
```
ERROR: Could not find a version that satisfies the requirement pyside2 (from versions: none)
ERROR: No matching distribution found for pyside2
``` | 2019/11/07 | [
"https://Stackoverflow.com/questions/58743664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12336141/"
] | If you check the available files on the [pypi page](https://pypi.org/project/PySide2/#files), you will see that there are only wheels for `cp35.cp36.cp37` so python 3.5 to 3.7, no files for 3.8. That is why `pip` cannot find a version, since there is no compatible version on `pypi`.
There is also no python 3.8 release on the [qt website](http://download.qt.io/snapshots/ci/pyside/5.12/latest/pyside2/)
Now you have two options:
1. Try installing from source by following the official [docs](https://wiki.qt.io/Qt_for_Python/GettingStarted) (I would not recommend this for a beginner)
2. Uninstall python 3.8 and install 3.7 instead or use a virtual environment with python 3.7 (I would recommend this, since you most likely don't rely on the difference between python 3.8 and 3.7)
**UPDATE**
Since the time of writing above answer, a new version of `pyside2` was released and `pip install` should now be able to find a `whl` for `pyside2` if you have `python 3.8` | Additionally for anyone trying to install this on Raspbian (maybe also other Linux
systems):
You can install PySide2 without pip wheel using the following command
```
$sudo apt-get install python3-pyside2.qt3dcore python3-pyside2.qt3dinput python3-pyside2.qt3dlogic python3-pyside2.qt3drender python3-pyside2.qtcharts python3-pyside2.qtconcurrent python3-pyside2.qtcore python3-pyside2.qtgui python3-pyside2.qthelp python3-pyside2.qtlocation python3-pyside2.qtmultimedia python3-pyside2.qtmultimediawidgets python3-pyside2.qtnetwork python3-pyside2.qtopengl python3-pyside2.qtpositioning python3-pyside2.qtprintsupport python3-pyside2.qtqml python3-pyside2.qtquick python3-pyside2.qtquickwidgets python3-pyside2.qtscript python3-pyside2.qtscripttools python3-pyside2.qtsensors python3-pyside2.qtsql python3-pyside2.qtsvg python3-pyside2.qttest python3-pyside2.qttexttospeech python3-pyside2.qtuitools python3-pyside2.qtwebchannel python3-pyside2.qtwebsockets python3-pyside2.qtwidgets python3-pyside2.qtx11extras python3-pyside2.qtxml python3-pyside2.qtxmlpatterns python3-pyside2uic
```
Should include all standard Qt functionality. I was able to run my app - it worked surprisingly well.
Just in case - I came by because I couldn't install it via pip on Raspbian.
If you use ArchLinux on your Raspberry Pi, a working wheel should be available though.
See this [thread](https://forum.qt.io/topic/112813/installing-pyside2-on-raspberry-pi) for more info. |
12,201,487 | I have been working on the problem sets at [Project Euler](http://projecteuler.net/) for some time and have enjoyed the challenges presented. I am currently on [Problem 59](http://projecteuler.net/problem=59) which involves the process of encryption and decryption.
The problem is, by any reasonable standard, a very simple decryption problem.
* I have been told that the encryption key consists of 3 lowercase letters.
* I have been given a description of the encryption/decryption process.
* I have been given an encrypted text file which contains only encrypted common English words
I fully understand the process of importing the data, cycling through all possible keys, and attempting to decrypt the file data with each possible key. My trouble is, after a decryption attempt with one of the keys, how can I tell if that key was the correct decryption key? As far as the computer is concerned, every decryption key just converts the data from one value to another. The meaning of that value is purely subjective/interpreted. How can I tell if a decryption key has decrypted the data into something meaningful (ie. common English words)
**Here is the code I have so far (C#):**
```
static void Main(string[] args)
{
/* Get the data from the file and convert to byte array*/
StreamReader inData = new StreamReader(@"C:\Users\thantos\Desktop\cipher1.txt");
string[] strData = inData.ReadLine().Split(new char[] {','});
byte[] fileData = new byte[strData.Length];
foreach (string x in strData) { byte.Parse(x); }
/* for each three character lowercase password */
for (uint i = 0; i < 26; i++) {
for (uint j = 0; j < 26; j++){
for (uint k = 0; k < 26; k++) {
/* create a key */
byte[] key = new byte[3];
key[0] = (byte)(i + 97);
key[1] = (byte)(j + 97);
key[2] = (byte)(k + 97);
/* create temp copy of data */
byte[] dataCopy = new byte[fileData.Length];
fileData.CopyTo(dataCopy, 0);
/* decrypt using key */
for (uint l = 0; l < dataCopy.Length; l++) {
dataCopy[l] = (byte)(dataCopy[l] ^ key[l%key.Length]);
}
/* cannot figure out how to check
* if data is meaningfully decrypted
*/
bool dataIsMeaningful = isMeaningful(dataCopy);
if(dataIsMeaningful) {
/* do stuff with data if correct
* decryption key was found
*/
}
}
}
}
}
```
I have tried this method for `isMeaningful()`:
```
public static isMeaningful(byte[] inData) {
bool isGood = true;
for (uint i = 0; good && i < inData.Length; i++) {
isGood &= (char.IsLower((char)inData[i]));;
}
return isGood;
}
```
But it returns true for all 17576 possible keys.
How can I determine if the decryption key has decrypted the file data into meaningful data? I'm not looking for solution code or the answer to the Project Euler problem, I am looking for an explanation of how to check that your decryption attempt was successful. | 2012/08/30 | [
"https://Stackoverflow.com/questions/12201487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1465011/"
] | Well, you can assume only valid ASCII values are permitted (since it should be plaintext). So for every letter you decode, just check that the resulting XOR results in a valid value: `if(dataCopy[l] < 32 || dataCopy[l] > 122) continue;` This should help to eliminate a vast majority of the possible key combinations.
Actually, this technique could even be used to narrow down your keyset to begin with. So instead of iterating through the loop 26^3 times over the entire 1200 character string, initially iterate 26 times and keep track of which letter at which position is still valid.
```
var letters = Enumerable.Repeat(Enumerable.Range((int)'a', 'z'-'a' + 1).Select(e => (char)e), 3).Select (e => e.ToList()).ToList();
for(int i = 0, j = 0; i < passwordBytes.Length; i++)
{
j = i % 3;
for(int k = 0; k < letters[j].Count; k++)
{
byte r = (byte)(letters[j][k] ^ passwordBytes[i]);
if(r < 32 || r > 122) letters[j].RemoveAt(k--);
}
}
```
That should get your valid characters down to almost nothing, at which point you can just iterate over your remaining values (which shouldn't take too long) and look for a few valid sequences (I hear looking for `" the "` is a good option). | Can you send a checksum of the original message along with the encrypted message? After decryption, compute the checksum and see if they match.
If that is not available, what about a test message? You could send a test message first such as "This is my test message" and check to see if the decrypted message matches verbatim. It's not fool-proof, but it may cover you. |
67,481,342 | I am trying to solve a problem where I have to find all the sub pairs which sum to zero.
In my solution when sum == 0, it goes into an infinite loop. What I am doing wrong here.
```
function sumZero(data) {
let left = 0;
let right = data.length - 1;
let finalArray = [];
while (left < right) {
let sum = data[left] + data[right];
if (sum === 0) {
finalArray.push([data[left], data[right]]);
} else if (sum > 0) {
right--;
} else {
right++;
}
}
}
``` | 2021/05/11 | [
"https://Stackoverflow.com/questions/67481342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10636599/"
] | If sum==0, you push the items in finalArray, but you don't manage the left or right, thus it will be forever the same items and the same sum. Try to increase left (left++) if sum ==0 | Your main issue lies in here:
```
else if (sum > 0) {
right--;
} else {
right++;
}
```
You might either want to replace a `right` with a `left`. The reason why your are getting an infinite loop is when the sum < 0. The right will increment, thus, having the same behavior as the previous iteration and hence, the algorithm will be stuck in a infinite loop between right++ and right-- |
43,774,129 | I wanted to check if variable is there or not in blade ..for that i have used following lines:
```
@if(is_null($products))
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
@else
@foreach($products as $product)
//
@endforeach
@endif
```
The problem is when there is `$products` on blade I could show inside of `foreach` loop but when i get empty variable.I couldn't show the message `No Data Found` instead it shows only empty space?
is there any problem of checking variable inside of blade?
Controller code :
```
public function productSearch(Request $request)
{
$name = $request->name;
$products = Product::where('name' , 'like', '%'.$name.'%')->get();
return view('cart.product',compact('products'));
}
``` | 2017/05/04 | [
"https://Stackoverflow.com/questions/43774129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6196521/"
] | As of Laravel 5.7, You can also do this:
```
@empty(!$products)
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
@endempty
``` | ```
@forelse($products as $product)
<p>do some thing</p>
@empty
<p>No Products</p>
@endforelse
```
[Refer](https://laravel.com/docs/5.1/blade#control-structures) |
56,408,020 | This portion of my assignment is instructing me to change the src attribute of a collection of star images to another image file.
I've tried numerous combinations of **removeAttribute()** and **setAttribute()**, but no luck. I'm probably thinking down the wrong path here.
```
function lightStars () {
var starNumber = e.target.alt;
var stars = document.querySelectorAll("span#stars img");
for (var i = 0; i < starNumber; i++) {
stars.setAttribute("src", "bw_star2.png");
}
}
```
**HTML Code:**
```
<label id="ratingLabel" for="rating">Rate this title
<span id="stars">
<img src="bw_star.png" alt="1" />
<img src="bw_star.png" alt="2" />
<img src="bw_star.png" alt="3" />
<img src="bw_star.png" alt="4" />
<img src="bw_star.png" alt="5" /></span>
<input type="text" name="rating" id="rating" readonly value="" />
</label>
```
The purpose of this function is to color a star when the user moves the mouse pointer over a star image in order to reflect the user’s rating of the book.
I hope I explained this properly. | 2019/06/01 | [
"https://Stackoverflow.com/questions/56408020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11511460/"
] | We can make extensive use of `pandas` + `numpy` here:
1. Mask all values which are greater than `0`
```
m = df.gt(0)
A B C D
0 True False False True
1 False True False False
2 False False False False
```
2. Mask rows which dont contain any values above 0:
```
s1 = m.any(axis=1).astype(int).values
```
3. Get all the values greater than `0` in an array:
```
s2 = df.values[m]
```
4. Finally concat both arrays with each other:
```
np.concatenate([s2, s1[s1==0]]).tolist()
```
**Output**
```
[1, 2, 1, 0]
``` | You could apply a custom function which will process each row of the DataFrame and return a list. Then to sum returned lists.
```
In [1]: import pandas as pd
In [2]: df = pd.read_clipboard()
In [3]: df
Out[3]:
A B C D
0 1 0 0 2
1 0 1 0 0
2 0 0 0 0
In [4]: def get_positive_values(row):
...: # If all elements in a row are zeros
...: # then return a list with a single zero
...: if row.eq(0).all():
...: return [0]
...: # Else return a list with positive values only.
...: return row[row.gt(0)].tolist()
...:
...:
In [5]: df.apply(get_positive_values, axis=1).sum()
Out[5]: [1, 2, 1, 0]
``` |
62,525 | I'm looking for some way to run a batch file (.bat) without anything visible to the user (no window, no taskbar name, .etc..).
I don't want to use some program to do that, I'm looking for something cleaner. I've found [a solution](http://www.computing.net/answers/dos/run-batch-file-invisiblestealth/14270.html) that uses VBScript, but I don't really like using VBS, either. | 2009/10/29 | [
"https://superuser.com/questions/62525",
"https://superuser.com",
"https://superuser.com/users/1799/"
] | To Hide batch files or command files or any files.... Use Windows XP built in `IExpress.exe` utility to build a .EXE out of the batch file. When using `IExpress` make sure you check the run hidden option and check mark all the boxes about not showing anything. After you create your .exe place it in whatever run command folder you choose and you will never see it come up. | You do not need to do any special.
If you are running the batch files from a windows service, they should be hidden by default unless you enable the "Allow service to interact with desktop" option on the service. |
50,007,055 | I'm trying to make a request in a local file, but I don't know when I try to do on my computer show me an error. Is possible make a fetch to a file inside your project?
```
// Option 1
componentDidMount() {
fetch('./movies.json')
.then(res => res.json())
.then((data) => {
console.log(data)
});
}
error: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 at App.js: 10 --> .then(res => res.json())
// Option 2
componentDidMount() {
fetch('./movies.json', {
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then( res => res.json())
.then((data) => {
console.log(data);
});
}
error1: GET http://localhost:3000/movies.json 404 (Not Found) at App.js:15 --> fetch('./movies.json', {
error2: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 at App.js: 10 --> .then(res => res.json())
// This works
componentDidMount() {
fetch('https://facebook.github.io/react-native/movies.json')
.then( res => res.json() )
.then( (data) => {
console.log(data)
})
}
``` | 2018/04/24 | [
"https://Stackoverflow.com/questions/50007055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/989470/"
] | The error
```
Unexpected token < in JSON at position 0
```
comes from the HTML file that is returned if the request is unsuccessful. The first element (at position 0) of an HTML file is typically a '<'. Instead of a JSON, an attempt is made to read in an HTML file.
You can find the returned HTML File in the Inspect Tool -> Network -> Erroneous file marked in red -> Reponse. There you can see what the specific error is. [Example Error Message](https://i.stack.imgur.com/4HjpL.png)
To fix the error for me, it helped to move the file to be imported to the Public folder of my React project and then import it like this from a file in the 'src' folder: `fetch('dataTemplate.json')` | You can place your json file in the public folder. In your React component you can use userEffect (). You don't need Express.js for this case.
```
React.useEffect(() => {
fetch("./views/util/cities.json")
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
});
``` |
460,172 | I have a simple html block like:
```
<span id="replies">8</span>
```
Using jquery I'm trying to add a 1 to the value (8).
```
var currentValue = $("#replies").text();
var newValue = currentValue + 1;
$("replies").text(newValue);
```
What's happening is it is appearing like:
81
then
811
not 9, which would be the correct answer. What am I doing wrong? | 2009/01/20 | [
"https://Stackoverflow.com/questions/460172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/50711/"
] | parseInt didn't work for me in IE. So I simply used + on the variable you want as an integer.
```
var currentValue = $("#replies").text();
var newValue = +currentValue + 1;
$("replies").text(newValue);
``` | You can use parseInt() method to convert string to integer in javascript
You just change the code like this
```
$("replies").text(parseInt($("replies").text(),10) + 1);
``` |
294,428 | My server is under DDoS attacks. I see my access log and get something:
```
968966 93-97-53-41.zone5.bethere.co.uk - - [27/Jul/2011:12:13:58 +0700] "GET /forum/forum.php HTTP/1.1" 200 91231 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5. 1)"
968967 61.120.148.12 - - [27/Jul/2011:12:13:39 +0700] "GET /forum/forum.php HTTP/1.0" 200 91539 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
968968 222.122.206.203 - - [27/Jul/2011:12:13:38 +0700] "GET /forum/forum.php HTTP/1.1" 200 91228 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
968969 cable-27-4.botevgrad.com - - [27/Jul/2011:12:13:39 +0700] "GET /forum/forum.php HTTP/1.1" 200 91228 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
968970 213.197.182.78 - - [27/Jul/2011:12:13:39 +0700] "GET /forum/forum.php HTTP/1.0" 200 91539 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
968971 200.27.142.30 - - [27/Jul/2011:12:13:39 +0700] "GET /forum/forum.php HTTP/1.0" 200 91539 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
968972 189.77.140.57 - - [27/Jul/2011:12:13:35 +0700] "GET /forum/forum.php HTTP/1.0" 200 91539 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
968973 221.226.9.22 - - [27/Jul/2011:12:13:58 +0700] "GET /forum/forum.php HTTP/1.1" 200 91542 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
968974 ::1 - - [27/Jul/2011:12:14:03 +0700] "OPTIONS * HTTP/1.0" 200 - "-" "Apache (internal dummy connection)"
968975 221.226.9.22 - - [27/Jul/2011:12:13:58 +0700] "GET /forum/forum.php HTTP/1.1" 200 91231 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
968976 ::1 - - [27/Jul/2011:12:14:03 +0700] "OPTIONS * HTTP/1.0" 200 - "-" "Apache (internal dummy connection)"
```
I don't have any experiences about DDoS, please help me find and resolve issue? :(
My server is CentOs 5.4 Apache 2.2 and PHP 5.2.6.
Thanks, | 2011/07/27 | [
"https://serverfault.com/questions/294428",
"https://serverfault.com",
"https://serverfault.com/users/89091/"
] | As [Jason](https://serverfault.com/a/294432/101655) already pointed out, your best current option is to call your ISP/Hoster for help.
After that, sign up for a CDN, if possible - they thwart most DDoS'es by design, or at least, make them only a localized nuisance. There are many CDN's which provide some free plan, which might be sufficient for you. I heard good stuff about [CloudFlare](https://www.cloudflare.com/index), and used it a bit at some point. YMMV. | Theoretically, u can use Client Puzzle to solve DDos attack. Depend on the situation, you may use different kind of puzzle to solve your problems.
[May I know, how do you know if you are under DDos attack from above log?] |
8,011 | Let's say I shoot with [Canon EF 35mm f/1.4L](http://www.the-digital-picture.com/reviews/canon-ef-35mm-f-1.4-l-usm-lens-review.aspx), [Canon EF 50mm f/1.4](http://www.the-digital-picture.com/reviews/canon-ef-50mm-f-1.4-usm-lens-review.aspx), and a [Canon EF 85mm f/1.8](http://www.the-digital-picture.com/reviews/canon-ef-85mm-f-1.8-usm-lens-review.aspx). Can these 3 primes be replaced with a [Canon EF 24-70mm f/2.8](http://www.the-digital-picture.com/reviews/canon-ef-24-70mm-f-2.8-l-usm-lens-review.aspx) for the convenience of not needing to change lens so often?
Also I just wanna clarify that when I'm comparing image quality I'm talking about what can be actually be seen in a 10R print, I don't need a pixel by pixel comparison. In addition I'm just a amateur shooter, mainly shooting portraits and street, with some landscape, architecture, and random things lying around.
EDIT:
I shoot with a 5D, so 24mm is enough for my wide-angle needs. Also I'll still be using the primes when I have a specific thing in mind to shoot. I just prefer to shoot light when walking around in the city or when I'm travelling. | 2011/02/01 | [
"https://photo.stackexchange.com/questions/8011",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/1635/"
] | I'd say, based on your criteria, the answer is yes. However, the fact is, primes are usually a better option at a given focal length versus a zoom, a result of less complex optical construction. In terms of the lens range, it's good for portrait/street, but I think a little too long for landscape and architecture, though not terribly so, it rather depends on which Canon camera you actually have.
Now, despite all that, the big advantage of an SLR, beyond sensor size, is the ability to change lenses for the scene. Don't get too caught up in the idea of a "one size fits all" concept on your lens, it's a compromise versus a prime and will, in the long run, be something you'll see. Changing lenses isn't that hard, after all. | Besides the DoF that most people talked about, for the sizes you will be printing, i really don't think you will be noticing a LOT of difference in image quality.
The 24-70 will have more chromatic aberration and such, being a zoom lens, but it's also a 1200$ Canon L lens, it certainly won't be rubbish.
And f2.8 gives a reasonably shallow DoF, it can be more than enough, if you use it well. And this goes to every lens: they all have limits, but when you get to know them and work around it, you get good (better:P) results!
I'd go for convenience and flexibility over sheer IQ everyday, especially for the range of hardware we're talking about.
OR, alternatively, go with just one prime and Cartier-Bresson'it. :D
(this will probably be the cheapest solution) |
62,028,537 | I use VS as my IDE.
I set all up for web development and the command `flutter doctor` doesn't state any errors.
When I run my project with Chrome as device, VS gets stuck in "Syncing files to device Chrome".
I also tried running my project through terminal with `flutter run -d chrome --verbose`, the strange thing that happens when I run that command is that it Syncs successfully all the files (at least that's what the – verbose states) but the browser doesn't show any content.
There aren't errors in the browser console and I have the latest version installed. | 2020/05/26 | [
"https://Stackoverflow.com/questions/62028537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12248145/"
] | In UWP, access to files by path is restricted. The recommended practice is to use FileOpenPicker to select files.
But if you just save the data locally, you can use `ApplicationData.Current.LocalFolder` to access the local application folder.
like this:
```cs
private async void Save()
{
BinaryFormatter bf = new BinaryFormatter();
var localFolder = ApplicationData.Current.LocalFolder;
var file = await localFolder.CreateFileAsync("viewModel.txt", CreationCollisionOption.OpenIfExists);
// Serialize the Binary Object and save to file
using (Stream fsout = await file.OpenStreamForWriteAsync())
{
bf.Serialize(fsout, dataContext);
}
}
```
For details about saving data to local files, you can refer to this document:
* [Create and read a local file](https://learn.microsoft.com/en-us/windows/uwp/design/app-settings/store-and-retrieve-app-data#create-and-read-a-local-file) | I managed to get the following to work:
```
private void Save()
{
BinaryFormatter bf = new BinaryFormatter();
// Serialize the Binary Object and save to file
using (Stream fsout = new FileStream(System.IO.Path.GetTempPath() + "viewModel.txt", FileMode.Create, FileAccess.ReadWrite, FileShare.None))
{
bf.Serialize(fsout, dataContext);
}
}
```
I am however unsure if this is a good place to be storing data for the production application. |
11,695,556 | I trying to write a Prolog script that can create a list of strings that would after a simple procedure result in a given string. My knowledge of Prolog is very limited and I am not sure it is even able to perform this, so please tell me if it's impossible.
I got this so far
```
replace_word(Old, New, Orig, Replaced) :-
atomic_list_concat(Split, Old, Orig),
atomic_list_concat(Split, New, Replaced).
```
It can perform this operation
```
10 ?- replace_word('a','e','glava',X).
X = gleve.
```
But it cannot backtrack it
```
11 ?- replace_word('a','e',X,'gleve').
ERROR: atomic_list_concat/3: Arguments are not sufficiently instantiated
```
I can imagine what causes the problem, but is there a way around it? | 2012/07/27 | [
"https://Stackoverflow.com/questions/11695556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1558704/"
] | Here's my super duper solution:
The HTML
```
<div class="ratioBox">
<div class="dummy"></div>
<div class="el">This is the super duper ratio element </div>
</div>
```
The CSS
```
.ratioBox{
position: relative;
overflow: hidden; /* to hide any content on the .el that might not fit in it */
width: 75%; /* percentage width */
max-width: 225px;
min-width: 100px;
max-height: 112.5px;
min-height: 50px;
}
.dummy {
padding-top: 50%; /* percentage height */
}
.el {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
background-color: silver;
}
```
**See it working here:** <http://jsfiddle.net/joplomacedo/7rAcH/>
The explanation, in case you can't understand what is happening, will come at the end of the day as I'm unfortunately out of time. [it's July 28, 2:54PM (GMT Time) as I write this] | Resize a div like an image with CSS
-----------------------------------
**[DEMO](http://jsfiddle.net/webtiki/p78y4/)** : resize the result window (width and height) to see the div resize like the image.
In the demo you can see both image and div resize the same way according to the height and the width of the result window viewport.
This technique uses **[vh/vw](https://developer.mozilla.org/en-US/docs/Web/CSS/length#Viewport-percentage_lengths)** units. They alow you to set the **width according to the height of viewport** and the **height according to the width of viewport**.
With the combined use of max-width and max-height you can make it behave and resize like an image on browser resize.
Browser support for these units : IE9+. For more info see [canIuse](http://caniuse.com/viewport-units).
The above demo uses a 1:1 aspect ratio but you may with a bit of calculation use any other aspect ratio, examples :
* 4:3 aspect ratio : [demo](http://jsfiddle.net/webtiki/p78y4/2/)
* 16:9 aspect ratio : [demo](http://jsfiddle.net/webtiki/p78y4/3/)
*CSS (for a 1:1 aspect ratio)*
```
div{
width: 80vw;
height: 80vh;
max-width: 80vh;
max-height: 80vw;
}
```
One step further : vmin and vmax
--------------------------------
You can also use [vmin/vmax](https://developer.mozilla.org/fr/docs/CSS/longueur). These units select the minimum or maximum value between the width and height of viewport so you can have the max/min-height and max/min-width desired behaviour. But the browser support for these units isn't as good as `vh/vw` ([canIuse](http://caniuse.com/viewport-units)).
**[Demo](http://jsfiddle.net/webtiki/p78y4/5/)**
*CSS (for a 1:1 aspect ratio) :*
```
div{
min-width:200px;
min-height:200px;
width: 80vmin;
height: 80vmin;
max-width: 800px;
max-height: 800px;
}
``` |
45,808,662 | I'm trying to pass data forward from a table view cell button to a view controller. Depending on which row the button is selected in I want the following view controller label's text to be set accordingly. However, when I try to do so, my labels in the following view controller stay blank and don't change. How can I change this?
I added an action to `tipButton` in a table view controller that creates segue to the `KeysController` FYI.
Code for table view cell:
```
class DrillsTableViewCell: UITableViewCell {
var videoURL:[URL] = [URL(fileURLWithPath: "/Users/RalphSimmonds/Desktop/plainjayne/coolinDB/cook.mov"), URL(fileURLWithPath: "/Users/RalphSimmonds/Desktop/plainjayne/coolinDB/check.MOV")]
var video = URL(fileURLWithPath: String())
var initialRow = Int()
var firstTips = ["Tip 1: Stay Hydrated", "Tip 1: Keep elbow tucked", "x", "Tip 1: Take quick breaks:", "Tip 1: Keep your head up", "Tip 1: Don't cross your feet", "Tip 1: Don't do more than 15 reps"]
var player: AVPlayer?
var playerController = AVPlayerViewController()
@IBOutlet weak var drillTitle: UILabel!
@IBOutlet weak var tipButton: UIButton!
@IBAction func tipsButton(_ sender: UIButton) {
print(String(initialRow))
let tipsVC = UIStoryboard(name: "main", bundle: nil).instantiateViewController(withIdentifier: "KeysController") as! KeysController
tipsVC.key1.text = firstTips[initialRow]
}
```
Code for the view controller whose labels I'm trying to update:
```
import UIKit
class KeysController: UIViewController {
@IBOutlet weak var topLabel: UILabel!
@IBOutlet weak var key1: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
}
``` | 2017/08/22 | [
"https://Stackoverflow.com/questions/45808662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8480380/"
] | Your outlets aren't wired up until the view loads.
Try creating a property in your KeysController, say:
```
var keyText: String?
```
Set the property after instantiating the view controller:
```
tipsVC.keyText = firstTips[initialRow]
```
Then in your `KeysController.viewDidLoad` method:
```
key1.text = keyText
``` | it's because the label key1 is not loaded yet, it's better to update it on viewdidload instead
```
@IBAction func tipsButton(_ sender: UIButton) {
print(String(initialRow))
let tipsVC = UIStoryboard(name: "main", bundle: nil).instantiateViewController(withIdentifier: "KeysController") as! KeysController
tipsVC.key1String = firstTips[initialRow] }
import UIKit
class KeysController: UIViewController {
var key1String:String = ""
@IBOutlet weak var topLabel: UILabel!
@IBOutlet weak var key1: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
key1.text = key1String
}
``` |
4,313,643 | I want to put an icon on the left and an input type text on the right occupying all the remaining space.
```
----------------------------------------------------
| [ico] ---------------------------------------- |
| | input type="text" | |
| ---------------------------------------- |
----------------------------------------------------
```
If I set both with `display: inline-block` and set the **input's width to `100%`** it **jumps the line**, because `100%` is **not considering the `space - icosize`**...
I want to **expand the input to the remaining available space** (**I don't care for vertical align**). Is there a way to achieve this behavior without using tables?
>
> **[An example of the problem on jsFiddle.](http://jsfiddle.net/sUYBS/)**
>
>
> | 2010/11/30 | [
"https://Stackoverflow.com/questions/4313643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/340760/"
] | Try `display: table-cell` . | Did you try to use align="absmiddle" in the icon?
```
<img src="img.jpg" align="absmiddle">
``` |
19,716,803 | I have got one big array.
The content of that array is:
```
Array
(
[0] => Array
(
[id] => 12
[user_id] => 1
[date] => 2013-10-21 23:01:52
[type] => 1
[quantity] => 0
[value] => 1700
)
[1] => Array
(
[id] => 13
[user_id] => 1
[date] => 2013-10-21 23:01:52
[type] => 0
[quantity] => 0
[value] => 90
)
[2] => Array
(
[id] => 16
[user_id] => 1
[date] => 2013-10-21 23:01:52
[type] => 0
[quantity] => 0
[value] => 0
[3] => Array
(
[id] => 19
[user_id] => 1
[date] => 2013-10-31 02:49:12
[type] => 0
[quantity] => 0
[value] => 0
[bills] => Array
(
[0] => Array
(
[id] => 5
[data_id] => 19
[quantity] => 10
[value] => 15
)
[1] => Array
(
[id] => 5
[data_id] => 19
[quantity] => 20
[value] => 1
)
[2] => Array
(
[id] => 5
[data_id] => 19
[quantity] => 1
[value] => 50
)
)
)
)
```
I want to display this array in foreach.
So i have:
```
echo '<ol>';
foreach ( $this->data as $d )
{
echo '<li><strong>'.$d['name'].'</strong><br /></li>';
if ( $d['bills'] )
{
echo '<ul>';
foreach ( $d['bills'] as $b )
{
echo '<li>';
echo $b['name'];
echo '</li>';
}
echo '</ul>';
}
}
echo '</ol>';
```
It's simple, until I want to display only arrays containing a key['type'] == 1.
I have no idea how can I do that.
In MySQL it's only have to add 'WHERE type = 1'.
I learn about PHP arrays so sorry if that filtering is simple function to do.
Best cheers! | 2013/10/31 | [
"https://Stackoverflow.com/questions/19716803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2190042/"
] | If you actually need to create a filtered array, you could use [`array_filter()`](http://php.net/manual/en/function.array-filter.php) with a callback:
```
$filtered = array_filter($this->data, function($element) {
return $element['type'] == 1;
});
```
Otherwise, the simplest solution is probably just to put something like this at the top of your `foreach` loop:
```
if($d['type'] != 1) {
continue;
}
``` | You can use a simple `IF` statement with `continue` to check to see if `type` equals 1. If it doesn't you can skip it.
```
foreach ( $this->data as $d )
{
if ($d['type'] != 1) continue;
``` |
54,124,051 | I'm doing a hackernet challenge where n is an int input. The conditions are:
* If n is odd, print Weird
* If n is even and in the inclusive range of 2 to 5, print Not Weird
* If n is even and in the inclusive range of 6 to 20, print Weird
* If n is even and greater than 20, print Not Weird.
Im sure the code makes logic and dont think theres syntax. It gives the correct responses and hackernet still says its incorrect so ive come here to see if anyone can see what the problem is
```
public static void main(String[] args)
{
int N = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
if (N % 2 != 0 || N % 2 == 0 && N >= 6 && N <= 20)
{
System.out.print("weird");
}
else
{
System.out.print("not weird");
}
}
``` | 2019/01/10 | [
"https://Stackoverflow.com/questions/54124051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10893731/"
] | Read this condition :
```
if (N % 2 != 0 || N % 2 == 0 && N >= 6 && N <= 20)
```
as
```
if (N % 2 != 0 || (N % 2 == 0 && N >= 6 && N <= 20))
```
Then see how operator precedence changes the behaviour and yield desired results. | Check the following one
```
public static void main(String[] args)
{
int N = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
if(N%2!=0) {
System.out.print("weird");
}else if(N>=2 && N<=5) {
System.out.print("not weird");
}else if(N>=6 && N<=20) {
System.out.print("weird");
}else if(N>20) {
System.out.print("not weird");
}
}
``` |
16,058 | The question of [*why* is there religion in Harry Potter](https://scifi.stackexchange.com/q/16030/1234) made me wonder as to whether wizards, any of them, do practice religion. Whether there be magic-person only religions or shared muggle faiths, I do not recall any wizards (born in the wizard world anyway) saying that they did practice a religion.
Many of them do celebrate Christmas, but as was commented on the above linked question, there are many non-christian muggles that also observe Christmas. So I am not sure that can be an accurate identifier. Answering this question may link into identifying [what holidays the wizards celebrate](https://scifi.stackexchange.com/q/16050/1234). | 2012/05/03 | [
"https://scifi.stackexchange.com/questions/16058",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/1234/"
] | There are, to the best of my memory, no instances of wizard-raised wizards mentioning religion at all in the books. As you stated, many of them do celebrate Christmas, and one might think that if there was some form of Jewish, Pagan, Muslim, or other Muggle faith with a winter holiday prevalent in the wizarding world, Harry would have heard about it. On the other hand, the only other people Harry interacts with a lot are Hermione - Muggle-raised - and Ron - raised by a nontraditional and Muggle-loving family. There are many fanfics and essays which explain Harry's ignorance, and therefore our ignorance, of wizarding religious traditions as being a side effect of him belonging to the most Muggle-associated house and having only Muggle-associated friends.
That being said, in *Harry Potter and the Deathy Hallows*, Harry finds two tombstones with Bible (New Testament) quotes on them. His parents' reads "The last enemy that shall be destroyed is death" (1 Corinthians 15:26) while Kendra and Ariana Dumbledore's reads "Where your treasure is, there will your heart be also" (Matthew 6:21). Both Lily Potter and Kendra Dumbledore were Muggle-born, however, while it is possible the verses were placed on their gravestones for the mothers alone, their funerals were held by wizards, in the wizarding world, and I believe that if the Bible was not part of the culture of the wizarding world at large, the phrases may have stirred up trouble for the Dumbledores, and lessened the heroism of the Potters (if prejudice exists in the wizarding world - religious prejudice, that is).
Rowling's only direct quote on the religion of wizards was to say once, in 2007, that "Hogwarts is a multifaith school," never specifying what those faiths may or may not be. The presence of the New Testament quotes on wizarding tombstones in a church graveyard in a famous wizarding village, however, signifies to me that Christianity at least is a religion practiced by at least some wizards. Probably not all of them, but, then again, all Muggles don't practice Christianity either. People bring religions with them, and Muggle-born wizards have been around since before Hogwarts was founded. If there aren't any wizards who practice the faiths we are familiar with, well...I'd certainly be surprised. | I always think about religion in the wizarding world when the hospital is mentioned. It isn't something like London Memorial Hospital, it's Saint Mungo's. So there had to be a wizard who not only got canonised but also was proud of it. And he got canonised while still alive because he founded the hospital himself. |
63,006,132 | I was able to create a data masking policy for a json column for the top level keys with the following, but couldn't figure out to go to deeper layers in json. Anybody has done that?
```
CREATE OR REPLACE MASKING POLICY json_mask_test AS
(val variant) returns variant ->
CASE
WHEN invoker_role()='ADMIN' THEN val
ELSE object_insert(
object_insert(
object_insert(val, 'pii_field', '***', true),
'address','***', true),
'lastName','***', true)
END
```
If `object_insert` is the only way to create a masking policy on a json field, looks like it's limited to top level keys.
I was using the example for [On Variant Data](https://docs.snowflake.com/en/user-guide/security-column-ddm-use.html#additional-masking-policy-examples)
Also as a side effect this policy inserts the keys into the json fields when the keys don't exist in original field. To be able to eliminate this would be desirable.
Edit:
I have used this json for the example above
`{"regular_field": "regular data", "pii_field": "pii data"}`
I was trying to mask LastNames in a json like the following
```
'{"root":[{"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]}]}'
``` | 2020/07/21 | [
"https://Stackoverflow.com/questions/63006132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1628812/"
] | `display: flex` makes us happy.
You're HTML should be like this.
```
<div class="wrapper">
<div id="1"></div>
<div class="wrapper_two>
<div id="2"></div>
<div id="3"></div>
</div>
</div>
```
div 1, 2, 3 must have height.
And css code is like
```
.wrapper {
display: flex;
}
.wrapper_two {
display: flex;
flex-direction: column;
}
```
`flex` sets child elements in one line because it's default direction is `row`.
So `#1` and `wrapper_two` sets in one line.
`wrapper_twop` has `flex-direction: column;`, so it sets child elements in one column. | ```css
#container{
width:80%;
margin:40px 10%;
background-color:lightgray;
height:auto;
display:flex;
justify-content:space-between;
align-items:center;
}
#left{
width:50%;
height:200px;
background-color:blue;
}
#right{
width:50%;
height:200px;
display:flex;
flex-direction:column;
justify-content:space-between;
align-items:center;
}
.list-div{
width:100%;
height:100px;
background-color:yellow;
}
.legend{
width:100%;
height:100px;
background-color:red;
}
```
```html
<div id="container">
<div id="left">
<div class="calendar-div"> Calendar</div>
</div>
<div id="right">
<div class="list-div">List</div>
<div class="legend"> LEGEND</div>
</div>
</div>
``` |
54,098,448 | So I am reading this excellent [intro](https://medium.freecodecamp.org/demystifying-dynamic-programming-3efafb8d4296) to Dynamic Programming, and I am trying to decipher this python code (DP approach for Fibonacci numbers). I code mainly in C/C#, so its kinda hard for me to understand Python.
So this is the code:
```
def fibonacciVal(n):
memo = [0] * (n+1)
memo[0], memo[1] = 0, 1
for i in range(2, n+1):
memo[i] = memo[i-1] + memo[i-2]
return memo[n]
```
So, the bits I am trying to understand are:
1. memo = [0] \* (n+1) : I get that this is an array, but how are the values being stored here, how is it being initialized?
2. for i in range(2, n+1): : why is it looping till n+1, shouldn't it be till n only?
That's all. I am trying to decipher this myself, and it would help to have someone with python experience help me here.
Thanks! | 2019/01/08 | [
"https://Stackoverflow.com/questions/54098448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9187905/"
] | ```
1: [0]*3 -> [0,0,0] i.e. multiplying an array duplicates it that many times -n+1 in your case-.
2: because you start with [0,1,0,0,0, ...]
the first index you add to is ^
... the last index you add to will be at n+1 because the first index you added to was 2
[0,1,1,2,3,5,8,13,21,...]
``` | What tools are you using for "trying to understand"? A couple of basic `print` commands will help a lot:
```
def fibonacciVal(n):
memo = [0] * (n+1)
print("INIT", memo)
memo[0], memo[1] = 0, 1
for i in range(2, n+1):
memo[i] = memo[i-1] + memo[i-2]
print("TRACE", i, memo)
return memo[n]
fibonacciVal(5)
```
Output:
```
INIT [0, 0, 0, 0, 0, 0]
TRACE 2 [0, 1, 1, 0, 0, 0]
TRACE 3 [0, 1, 1, 2, 0, 0]
TRACE 4 [0, 1, 1, 2, 3, 0]
TRACE 5 [0, 1, 1, 2, 3, 5]
``` |
141,421 | I am looking for a word that is close in meaning to *nostalgia*, but not so passive. Something that is compulsive. It should also be unambiguously negative. A bonus would be a connotation of anxiety.
**Edit:** I am looking for a noun, like *nostalgia*, that describes the state or emotion. | 2013/12/11 | [
"https://english.stackexchange.com/questions/141421",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/23650/"
] | [*Rumination*](http://en.wikipedia.org/wiki/Rumination_%28psychology%29) is the term I have used in the past to describe the given situation. | Reminiscing
indulge in enjoyable recollection of past events.
It is often more of a positive term than negative, it is a verb (to reminisce).
It is all about you are in the present thinking back on the past. |
3,760,838 | I am trying to evaluate this very long definite integral given below:
$$ \int\_{-\infty}^{+\infty} \frac{\cos(4x)}{x^2 + 2x + 2} \, dx$$
The direction it can go is by decomposing the denominator to $(x−i+1)$ and $(x+i+1)$ and then taking a partial fraction as:
$$ \frac{i\cos(4x)}{2(x−i+1)} - \frac{i\cos(4x)}{2(x−i+1)}. $$
The online mathematical integral solvers follow this procedure, which ends up with a long and ugly solution to this integral. Is there a better way to go about this integral, and are there any elegant solutions?
Thanks for your time! | 2020/07/18 | [
"https://math.stackexchange.com/questions/3760838",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/407650/"
] | Let $x+1=t$. Then,
\begin{align}
I=& \int\_{-\infty}^{+\infty} \frac{\cos(4x)}{x^2 + 2x + 2} \, dx
=\cos4 \int\_{-\infty}^{+\infty} \frac{\cos(4t)}{t^2 +1} \, dt
\end{align}
where the odd $\sin 4t$ term vanishes upon integration. Denote $J(a)=\int\_{0}^{\infty} \frac{\cos(at)}{t^2 +1} dt$.
Then
$$J’(a)=-\frac\pi2+ \int\_{0}^{\infty} \frac{\sin(at)}{t(t^2 +1)} dt,\>\>\>\>\>J’’(a)=J(a)
$$
With $J(0) = -J’(0)= \frac\pi2$, solve for $J(a)= \frac\pi2 e^{-a}$. Thus,
$$I=2 \cos4 J(4) =\pi e^{-4} \cos4$$ | $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
\newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
\newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
\newcommand{\dd}{\mathrm{d}}
\newcommand{\ds}[1]{\displaystyle{#1}}
\newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
\newcommand{\ic}{\mathrm{i}}
\newcommand{\mc}[1]{\mathcal{#1}}
\newcommand{\mrm}[1]{\mathrm{#1}}
\newcommand{\pars}[1]{\left(\,{#1}\,\right)}
\newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
\newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
\newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
\newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
With $\ds{r \equiv -1 + \ic}$:
\begin{align}
\int\_{-\infty}^{\infty}{\cos\pars{4x} \over x^{2} + 2x + 2}\,\dd x & =
\Re\int\_{-\infty}^{\infty}{\expo{4\ic x} \over \pars{x - r}\pars{x - \overline{r}}}\,\dd x =
\Re\bracks{2\pi\ic\,{\expo{4\ic r} \over r - \overline{r}}}
\\[5mm] & =
\Re\bracks{2\pi\ic\,{\expo{-4\ic}\expo{-4} \over 2\ic}} =
\bbx{\pi\expo{-4}\cos\pars{4}}\ \approx\ -0.0376
\end{align} |
5,880,748 | For the sake of "post processing" on a method, I want to import an extra function into a method.
**How can I import a `Func` that returns an anonymous Type as a parameter for a .Select extension method?**
The expression is anounymous like:
```
p => new
{
ThumnailUrl = p.PicasaEntry.Media.Thumbnails[0].Attributes["url"],
ImageUrl = p.PhotoUri
}
```
and needs to be used at parameter ????? and performed at .Select(?????)
```
private void BindControl<T, U>(string uri, DataBoundControl target, ?????)
where T : KindQuery, new()
where U : PicasaEntity, new()
{
PicasaFeed feed = CreateFeed<T>(uri);
albumList.DataSource = GetPicasaEntries<U>(feed).Select(?????);
albumList.DataBind();
}
```
**update:**
finally I want to call it like:
```
string albumUri = PicasaQuery.CreatePicasaUri(PicasaUserID, PicasaAlbumID);
BindControls<AlbumQuery, Album>(albumUri, albumList, ?????);
string photoUri = PicasaQuery.CreatePicasaUri(PicasaUserID, PicasaAlbumID);
BindControls<PhotoQuery, Photo>(photoUri, slideShow, ?????);
```
the other methods are like:
```
private PicasaFeed CreateFeed<T>(string uri)
where T : KindQuery, new()
{
PicasaFeed feed = null;
try
{
PicasaService service = new PicasaService(PicasaApplicationName);
T query = new T();
query.BaseAddress = uri;
feed = service.Query(query);
}
catch (Exception ex)
{
//exception handling not shown
}
return feed;
}
private IEnumerable<T> GetPicasaEntries<T>(PicasaFeed feed)
where T : PicasaEntity, new()
{
if(feed == null){
return null;
}
IEnumerable<T> entries = null;
string cacheKey = feed.Id.ToString();
if(Cache.Get(cacheKey) == null)
{
entries = feed.Entries.Select(x => new T() { AtomEntry = x }).ToList();
Cache.Insert(cacheKey, entries,
null, Cache.NoAbsoluteExpiration, new TimeSpan(0,20,0));
}
return entries;
}
``` | 2011/05/04 | [
"https://Stackoverflow.com/questions/5880748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/400223/"
] | Anonymous types are really only designed for local use. In a strongly typed language types that can't be strongly typed are not really encouraged for general use... They are just a part of c#s little dance in the dynamic world.
You have two choices.
Create a strong type.
```
class Entry
{
public string ThumnailUrl { get; set; }
public string ImageUrl { get; set; }
}
```
And then use :
```
p => new Entry
{
ThumnailUrl = p.PicasaEntry.Media.Thumbnails[0].Attributes["url"],
ImageUrl = p.PhotoUri
}
```
Or refer to it as Object. Then use reflection to get the data out - I wouldn't recommend this. | Did you try this, not sure whether it will work?
```
private void BindControl<T, U, V>(string uri, DataBoundControl target, Func<U,V> selector)
where T : KindQuery, new()
where U : PicasaEntity, new()
{
PicasaFeed feed = CreateFeed<T>(uri);
albumList.DataSource = GetPicasaEntries<U>(feed).Select(selector);
albumList.DataBind();
}
``` |
49,334,505 | I am porting my Angular 4 application to Angular 5 and although the application successfully builds the application does not load. I am getting the following error when I run my application: `Uncaught Error: No NgModule metadata found for 'AppModule'.`
**Full Stack Trace**
[](https://i.stack.imgur.com/ISgtF.png)
I have tried researching for a possible solution - and I have found plenty, but none have helped. I have tried:
* Deleting the node\_modules folder and reinstalling everything
* Some suggested that simply making a change in the AppModule and saving solves the problem. However after updating any file I'm always getting this error:
>
> ERROR in Debug Failure. False expression: Host should not return a
> redirect source file from getSourceFile
>
>
>
* I've went through all my project dependencies and they are up to date
* As mentioned [here](https://github.com/angular/angular/issues/20095#issuecomment-341364333) I have updated all the rxjs imports to the correct way, i.e. do not use `import {...} from rxjs/Rx`
What I find strange is that I'm building my application using AOT however the error mentions the Jit Compiler so I'm not sure if the application is indeed trying to use AOT.
**main.browser.ts**
```
/**
* Angular bootstrapping
*/
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { environment } from 'environments/environment';
/**
* App Module
* our top level module that holds all of our components
*/
import { AppModule } from './app';
/**
* Bootstrap our Angular app with a top level NgModule
*/
export function main(): Promise<any> {
return platformBrowserDynamic()
.bootstrapModule(AppModule)
.then(environment.decorateModuleRef)
.catch((err) => console.error(err));
}
/**
* Needed for hmr
* in prod this is replace for document ready
*/
switch (document.readyState) {
case 'loading':
document.addEventListener('DOMContentLoaded', _domReadyHandler, false);
break;
case 'interactive':
case 'complete':
default:
main();
}
function _domReadyHandler() {
document.removeEventListener('DOMContentLoaded', _domReadyHandler, false);
main();
}
```
**app.module.ts**
```
import { APP_INITIALIZER, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
/*
* Platform and Environment providers/directives/pipes
*/
import { environment } from '../environments/environment';
// App is our top level component
import { AppComponent } from './app.component';
import { APP_RESOLVER_PROVIDERS } from './app.resolver';
import { NoContentComponent } from './no-content';
import { CoreModule, AppConfigService } from './core';
import { AppRoutingModule } from './app-routing.module';
import { AppConfigLoader } from './app-config.loader';
// Application wide providers
const APP_PROVIDERS = [
...APP_RESOLVER_PROVIDERS
];
/**
* `AppModule` is the main entry point into Angular2's bootstraping process
*/
@NgModule({
bootstrap: [
AppComponent
],
declarations: [
AppComponent,
NoContentComponent
],
imports: [ // import Angular's modules
BrowserModule,
FormsModule,
HttpModule,
BrowserAnimationsModule,
CoreModule,
AppRoutingModule
],
providers: [ // expose our Services and Providers into Angular's dependency injection
environment.ENV_PROVIDERS,
APP_PROVIDERS,
AppConfigService,
{
provide: APP_INITIALIZER,
useFactory: AppConfigLoader,
deps: [AppConfigService],
multi: true
}
]
})
export class AppModule { }
```
**Environment**
* **Angular:** 5.2.8
* **TypeScript:** 2.6.2
* **Webpack:** 3.11.0 | 2018/03/17 | [
"https://Stackoverflow.com/questions/49334505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2312637/"
] | It is possible that the confusion about why inlining can hurt i-cache hit rate or cause thrashing lies in the difference between static instruction count and dynamic instruction count. Inlining (almost always) reduces the latter but often increases the former.
Let us briefly examine those concepts.
Static Instruction Count
------------------------
Static instruction count for some execution trace is the number of unique instructions0 that appear in the binary image. Basically, you just count the instruction lines in an assembly dump. The following snippet of x86 code has a static instruction count of 5 (the `.top:` line is a label which doesn't translate to anything in the binary):
```
mov eci, 10
mov eax, 0
.top:
add eax, eci
dec eci
jnz .top
```
The static instruction count is mostly important for binary size, and caching considerations.
Static instruction count may also be referred to simply as "code size" and I'll sometimes use that term below.
Dynamic Instruction Count
-------------------------
The *dynamic* instruction count, on the other hand, depends on the actual runtime behavior and is the number of instructions *executed*. The same static instruction can be counted multiple times due to loops and other branches, and some instructions included in the static count may never execute at all and so no count in the dynamic case. The snippet as above, has a dynamic instruction count of `2 + 30 = 32`: the first two instructions are executed once, and then the loop executes 10 times with 3 instructions each iteration.
As a very rough approximation, dynamic instruction count is primarily important for runtime performance.
The Tradeoff
------------
Many optimizations such as loop unrolling, function cloning, vectorization and so on increase code size (static instruction count) in order to improve runtime performance (often strongly correlated with dynamic instruction count).
Inlining is also such an optimization, although with the twist that for some call sites inlining *reduces* both dynamic *and* static instruction count.
>
> How does inlining affect the instruction cache hit rate?
>
>
>
The article mentioned *too much* inlining, and the basic idea here is that a lot of inlining increases the code footprint by increasing the working set's *static instruction count* while usually reducing its *dynamic instruction count*. Since a typical instruction cache1 caches static instructions, a larger static footprint means increased cache pressure and often results in a worse cache hit rate.
The increased static instruction count occurs because inlining essentially duplicates the function body at each the call site. So rather than one copy of the function body an a few instructions to call the function `N` times, you end up with `N` copies of the function body.
Now this is a rather *naive* model of how inlining works since *after* inlining, it may be the case that further optimizations can be done in the context of a particular call-site, which may dramatically reduce the size of the inlined code. In the case of very small inlined functions or a large amount of subsequent optimization, the resulting code may be even *smaller* after inlining, since the remaining code (if any) may be smaller than the overhead involved in the calling the function2.
Still, the basic idea remains: too much inlining can bloat the code in the binary image.
The way the i-cache works depends on the *static instruction count* for some execution, or more specifically the number of instruction cache lines touched in the binary image, which is largely a fairly direct function of the static instruction count. That is, the i-cache caches regions of the binary image so the more regions and the larger they are, the larger the cache footprint, even if the dynamic instruction count happens to be lower.
>
> How does inlining increase the size of the binary executable file?
>
>
>
It's exactly the same principle as the i-cache case above: larger static footprint means that more distinct pages need to paged in, potentially leading to more pressure on the VM system. Now we usually measure code sizes in megabytes, while memory on servers, desktops, etc are usually measured in gigabytes, so it's highly unlikely that excessive inlining is going to meaningfully contribute to the thrashing on such systems. It could perhaps be a concern on much smaller or embedded systems (although the latter often don't have a MMU at at all).
---
0 Here *unique* refers, for example, to the IP of the instruction, not to the actual value of the encoded instruction. You might find `inc eax` in multiple places in the binary, but each are unique in this sense since they occur at a different location.
1 There are exceptions, such as some types of trace caches.
2 On x86, the necessary overhead is pretty much just the `call` instruction. Depending on the call site, there may also be other overhead, such as shuffling values into the correct registers to adhere to the ABI, and spilling caller-saved registers. More generally, there may be a large cost to a function call simply because the compiler has to reset many of its assumptions across a function call, such as the state of memory. | Lets say you have a function thats 100 instructions long and it takes 10 instructions to call it whenever its called.
That means for 10 calls it uses up 100 + 10 \* 10 = 200 instructions in the binary.
Now lets say its inlined everywhere its used. That uses up 100\*10 = 1000 instructions in your binary.
So for point 3 this means that it will take significantly more space in the instructions cache (different invokations of an inline function are not 'shared' in the i-cache)
And for point 6 your total binary size is now bigger, and a bigger binary size can lead to thrashing |
1,298,441 | I am using VS 2005 (C# ). My Webservice returns a type as follow :
```
[WebMethod]
public Employee getEmployee( )
{
Employee emp=new Employee();
emp.EmpID=1000;
emp.EmpName="Wallace";
return emp;
}
```
---
from Client side i have created a Proxy.
```
localhost.Service1 svc = new WindowsApplication1.localhost.Service1();
```
How can i get the Employee object returned by getEmployee() method.
Do i need to create a Employee class in client side ?
**.... like ...**
```
localhost.Service1 svc = new WindowsApplication1.localhost.Service1();
Employee emp = new Employee();
object obj= svc.getEmployee();
emp = (Employee)obj;
MessageBox.Show("Id=:" + emp.EmpID.ToString() + "," + "Name:=" + emp.EmpName);
```
By doing so also i am receiving casting error. | 2009/08/19 | [
"https://Stackoverflow.com/questions/1298441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/158977/"
] | Your links need valid href values pointing to the alternative non-JavaScript pages, and in your click event, you need to return false, to avoid JavaScript enabled browsers to follow the links:
```
<a id="aboutLink" href="about-us.html">About Us</a>
```
---
```
$('#aboutLink').click(function () {
// ajax content retrieval here...
return false; // stop the link action...
});
``` | I would simply write down the HTML as it would look like without JavaScript, and then modify the content as it should look with JavaScript enabled.
In case JS is enabled, the site might load a little bit slower and may look a bit weird while it is being built, but the functionality remains.
In case JS is disabled, the site stays as it is and remains accessible for non-JS Users |
49,023,973 | I am new to React.I am facing this error.I have the code which is pasted below.Please help get out of this error.
```
import React from 'react';
import { Card} from 'semantic-ui-react';
import axios from 'axios';
export default class PersonList extends React.Component {
state = {
persons: []
}
componentDidMount() {
axios.get(`http://localhost:8080/locations`)
.then(res => {
const persons = res.data;
this.setState({ persons });
})
}
render() {
return (
<div class="ui stackable two column grid">
{ this.state.persons.map(person =>
<div class="column">
<Card
header={person.LOCATION}
/>
</div>)
}
</div>
)
}
}
```
The error message is pasted below
```
TypeError: this.state.persons.map is not a function
PersonList.render
C:/Users/user/Desktop/src/Sample.js:22
19 | render() {
20 | return (
21 | <div class="ui stackable two column grid">
> 22 | { this.state.persons.map(person =>
23 | <div class="column">
```
Output of `console.log('data', res.data)`:
```
{LOCATION: "CHINA9, SWEDEN9, CANADA9, austin, ", searchKey: {…}}
```
I request anyone to figure me out this error. | 2018/02/28 | [
"https://Stackoverflow.com/questions/49023973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9239986/"
] | You can create an array from the `LOCATION` string using `.split(',')` :
```
function render() {
const locationArr = this.state.persons.LOCATION
? this.state.persons.LOCATION.split(',')
: [];
return (
<div className="ui stackable two column grid">
{locationArr.map((location) => {
if (location !== ' ') {
return (
<div className="column">
<Card header={location} />
</div>
);
}
return null;
})}
</div>
);
}
``` | you set `this.state.persons` to `res.data` which is probably an object.. you cannot use `map` on an object...
instead you maybe want to push the the object to an array of objects. like this:
```
let persons = this.state.persons.slice()
persons.push(res.data)
this.setState({persons})
``` |
672 | [This question](https://mathoverflow.net/questions/139975/positivity-of-the-norm-of-an-element-of-a-cyclotomic-field) was originally asked in MSE about a year ago.
Nobody has answered it.
So I posted it here.
I wonder why they think it's not of research level. | 2013/08/21 | [
"https://meta.mathoverflow.net/questions/672",
"https://meta.mathoverflow.net",
"https://meta.mathoverflow.net/users/37646/"
] | It is for days I want to write this answer. Now that I've come to write it, your question is not there anymore. Thus please consider my answer as a general impression of another "newcomer" about how MO works. Generally speaking:
>
> People in MO land do not like "naked" questions.
>
>
>
That means, more often than not, questions like "solve this" or "I couldn't solve this, could you?" and so on have little chance to get enough attention. People often like to see the surrounding story as well as the question per se. That includes your personal attempt to solve the problem, the relation of the problem to other things, the reason that you are interested in the problem and so on. As you can see, the comments above, all coming from more experienced people than me, somehow try to clarify the surrounding story of your question. And I am sure those people are more qualified than me to tell the story of the importance of the surrounding stories in general. | I respectfully disagree with Noah Snyder; I think the question makes perfect sense as stated. I would phrase it as follows: "Here is a proof that the norm map $K = \mathbf Q[\alpha]/(1+\alpha+\ldots+\alpha^{p-1}) \to \mathbf Q$ takes only positive values. The proof uses that $K$ embeds in the complex numbers. Is there a different proof that avoids this fact?"
Certainly one can make sense of the statement $N(K) \subseteq \mathbf Q^+$ without mentioning the real numbers. I don't understand what Michael Zieve is getting at in his comments. For what it's worth I don't know how to answer Makoto Kato's question. |
49,504,614 | ```
class Feline {
public String type = "f";
public Feline() {
System.out.println("feline");
}
}
public class Cougar extends Feline {
public Cougar() {
System.out.println("cougar");
}
void go() {
type = "c";
System.out.println(this.type + super.type);
}
public static void main(String[] args) {
new Cougar().go();
}
}
```
In the output of the console I get this:
```
feline
cougar
cc
```
I am not sure why I get this output if I am creating a Cougar object and the constructor of the cougar class does not make a super call to the feline class constructor, also I don't understand why I get "C C" when calling the go() method. Sorry if it's a very basic question but I will appreciate your help. | 2018/03/27 | [
"https://Stackoverflow.com/questions/49504614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9334394/"
] | Java objects are constructed from the inside out: When you say `new Cougar()`, first space is allocated for the object, then a Feline object is constructed in that space by calling a Feline constructor, then finally your Cougar constructor is run.
You can specify *which* Cougar constructor is run by calling it explicitly with a `super(..)` call; that's particularly useful if there are several and you want to pick one by specifying arguments. But if you don't invoke one, the compiler will insert the `super()` call.
As to the 'cc', when `type = "c";` was encountered, there was no local variable named "type" defined. That means it's a member variable, so the compiler interprets that as `this.type = "c";`. But there's only one member called "type", and that's in Cougar. So `this.type` and `super.type` are both the same thing, have been set to "c", and "c" is typed twice. | You have created two classes where `Feline` is a super class and `Cougar` is a child class. As `Cougar` extends `Feline`, `Cougar` inherits `type` variable from `Feline`.
Now, `Feline` has a default constructor where `feline` string is printed. `Cougar` also has a default constructor. As per the line `new Cougar().go();` in the `main` method, you are creating a new object of `Cougar` which calls the default constructor and implicitly, it calls `super()` that calls the constructor of `Feline` class.
Now `new Cougar().go()` method is setting the type to `"c"`which means the value of the variable is changed as `super.type` and `this.type` are the same copy. So when you call this method, it prints this way:
>
> feline
>
>
> cougar
>
>
> cc
>
>
> |
30,610,438 | One can declare and initialize an unordered map in a single line like this:
```
std::unordered_map<std::string,std::string> colors({{"sky","blue"}});
```
But is it possible to do it in place of a function argument ?
For example, if I have a function with the following signature:
```
void foo(std::unordered_map<std::string,std::string> inputColors);
```
Can I call it by declaring and initialising the map as the argument some how ?
Eg:
```
foo(std::unordered_map<std::string,std::string> colors({{"sky","blue"}});
```
EDIT: What is the correct way to do it ? Provide the syntax with example please. | 2015/06/03 | [
"https://Stackoverflow.com/questions/30610438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1266109/"
] | You can just provide an initializer:
```
foo({{"sky", "blue"}});
```
That will be used to construct a temporary `unordered_map`, which will be passed to the function. If the function is overloaded such that there is an ambiguity, then you can spell the name out fully.
```
foo(std::unordered_map<std::string,std::string>{{"sky","blue"}});
``` | Yes, it is possible. program will create a `rvalue` reference for that parameter.
```
void foo(std::unordered_map<std::string,std::string> colors)
{
for(auto &x : colors)
{
std::cout<< x.first<<"\n";
std::cout<<x.second<<"\n";
}
}
int main()
{
foo({{"sky","blue"}});
}
``` |
70,663,112 | I am trying to create a table. left side image and right side information. i am not sure if it's possible
here is the structure i am trying to make.

here is a rough table structure I came up with
```
<table border="2" bordercolor="green">
<tr>
<td><img src="https://i.postimg.cc/sD9MZPKb/image.png"></td>
<td><table border="2" bordercolor="green">
<tr><td>test</td><td>second cell</td></tr>
<tr><td>test</td><td>second cell</td></tr>
<tr><td>test</td><td>second cell</td></tr>
<tr><td>test</td><td>second cell</td></tr>
<tr><td>test</td><td>second cell</td></tr>
<tr><td>test</td><td>second cell</td></tr>
</td>
</tr>
</table>
```
above html code making the right side table vertically center, which i am trying to make the position top
 | 2022/01/11 | [
"https://Stackoverflow.com/questions/70663112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16499922/"
] | The problem is that `@Pattern` [only works on strings](https://docs.oracle.com/javaee/7/api/javax/validation/constraints/Pattern.html).
You could use a [`@Digits`](https://docs.oracle.com/javaee/7/api/javax/validation/constraints/Digits.html) validator to validate how many digits you must have in the integer part: <https://www.baeldung.com/javax-bigdecimal-validation#3-digits>
If this doesn't work for you, then you will have to write your own custom validator: <https://www.baeldung.com/spring-mvc-custom-validator#custom-validation> | `@Pattern` Annotation works **only** with strings and not integers. You could migrate your `int` to a `String` if that is suitable. Then it would work.
You could also implement your own `Validator` as seen [here](https://www.baeldung.com/spring-mvc-custom-validator). |
65,211,610 | I have this dataset, I want to make triple y axis where "Country" will be X axis. in the y axis I want to do two clustered column with one line graph overlapping.
I am a new user, learning for 16 days
```
dput(data)
structure(list(Country = c("China", "Indonesia", "Vietnam", "Thailand",
"Egypt", "India", "Turkey", "Brazil", "United States", "Russia"
), Plastic.Consumption = c(44.14201935, 12.87658986, 23.6336878,
52.92058216, 13.93164324, 6.994354455, 64.77526757, 31.53076177,
87.30070657, 32.01972449), Plastic.Production.Kt. = c(42421L,
2258L, 387L, 5881L, 411L, 7211L, 939L, 5860L, 33985L, 3487L),
Plastic.Waste.Mismanagemet..kt. = c(8819.716784, 3216.855605,
1833.819141, 1027.739178, 967.0123574, 599.8191155, 485.937142,
471.4039969, 275.4244968, 80.75948103)), class = "data.frame",
row.names = c(NA, -10L))
``` | 2020/12/09 | [
"https://Stackoverflow.com/questions/65211610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14711964/"
] | Arrow functions with a body may require an ***explicit*** `return` statement if the function is to return a value. Arrow functions without a body (i.e. no `{}`) have an ***implicit*** return.
Solution
========
Return the entire ternary expression.
```
<TableRow>
{tableData.header.map((header) => {
return header.id === "name" ? ( // <-- return entire ternary expression
<TableCell style={{ width: 100 }} align="center" key={header.id}>
{header.title}
</TableCell>
) : (
<TableCell style={{ minWidth: 185 }} align="center" key={header.id}>
{header.title}
</TableCell>
);
})}
</TableRow>
```
This is still a lot of duplicated code, it could be more **DRY**. Move the ternary to branch logic on the minimal amount of code. The only diff I see if the `width` value, so branch there.
```
<TableRow>
{tableData.header.map((header) => {
return (
<TableCell
style={{ width: header.id === "name" ? 100 : 185 }}
align="center"
key={header.id}
>
{header.title}
</TableCell>
);
})}
</TableRow>
``` | So I solved it by using this code:
```
<TableRow>
{
tableData.header.map(header => header.id === "name" ?
<TableCell style={{minWidth: 80}} align="center" key={header.id}>
{
header.title
}
</TableCell>
:
<TableCell style={{minWidth: 185}} align="center" key={header.id}>
{
header.title
}
</TableCell>
)
}
</TableRow>
```
I basically removed some of the curly braces and somehow got the solution. |
747,518 | Any help would be appreciated, I'm trying to convert the code below to C#, I've never used VB.NET so ReDim is a new one to me.
Thanks
```
Dim inFile As System.IO.FileStream
Dim binaryData() As Byte
Dim strFileName As String
strFileName = "C:\MyPicture.jpeg"
inFile = New System.IO.FileStream(strFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read)
''//Retrive Data into a byte array variable
ReDim binaryData(inFile.Length)
Dim bytesRead As Long = inFile.Read(binaryData, 0, CInt(inFile.Length))
inFile.Close()
``` | 2009/04/14 | [
"https://Stackoverflow.com/questions/747518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/88081/"
] | This very easy to convert to C#.
```
FileStream inFile;
byte[] binaryData;
string strFileName;
strFileName = @"C:\MyPicture.jpeg";
inFile = new System.IO.FileStream(strFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
binaryData = new byte[inFile.Length];
int bytesRead = inFile.Read(binaryData, 0, binaryData.Length);
inFile.Close();
```
But there is a much better way to write this.
```
string fileName = @"C:\MyPicture.jpeg";
byte[] binaryData = File.ReadAllBytes(fileName);
``` | ReDim is used is resize arrays. (You can preserve the content if desired also. This code doesn't do that) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.