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 |
|---|---|---|---|---|---|
867,967 | It might be a silly question, but to me it is not obvious why the following expression holds:
$$
\lim\limits\_{x\rightarrow 0}\frac{0}{x}=0 ?
$$ | 2014/07/15 | [
"https://math.stackexchange.com/questions/867967",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/113891/"
] | A limit $L$ of a function $f(x)$ evaluated at a point $x = a$ is not necessarily the value $f(a)$ itself. It is a value for which $f(x)$ approaches $L$ "as close as we like" if we make $x$ "sufficiently close" **but not equal** to $a$. The subtlety is in how we mathematically formalize the language in quotation marks, which is how we arrived at the Cauchy definition of limit:
>
> We say that $\displaystyle \lim\_{x \to a} f(x) = L$ if, for any $\epsilon > 0$, there exists a $\delta > 0$ such that $|f(x) - L| < \epsilon$ whenever $0 < |x - a| < \delta$.
>
>
>
Of course, we do not need to appeal to such a definition in this case because as others have pointed out, $f(x) = 0/x = 0$ whenever $x \ne 0$; hence $$\lim\_{x \to 0} \frac{0}{x} = \lim\_{x \to 0} 0 = 0$$ directly, because again, the limit is evaluated by considering the behavior of $f(x)$ in a *neighborhood* of $a = 0$, not the value of $f(0)$. | This is true simply because as you take $x \to 0$ (for $x\ne 0$), we have $0/x=0$. (Think about the convergence of the sequence $0,0,0,0,\ldots$.) When you take the limit, you don't care about what happens when $x=0$; you only care about what happens around it. |
6,018,293 | I need to get the last part of current directory, for example from `/Users/smcho/filegen_from_directory/AIRPassthrough`, I need to get `AIRPassthrough`.
With python, I can get it with this code.
```
import os.path
path = "/Users/smcho/filegen_from_directory/AIRPassthrough"
print os.path.split(path)[-1]
```
Or
```
print os.path.basename(path)
```
How can I do the same thing with C#?
ADDED
-----
With the help from the answerers, I found what I needed.
```
using System.Linq;
string fullPath = Path.GetFullPath(fullPath).TrimEnd(Path.DirectorySeparatorChar);
string projectName = fullPath.Split(Path.DirectorySeparatorChar).Last();
```
or
```
string fullPath = Path.GetFullPath(fullPath).TrimEnd(Path.DirectorySeparatorChar);
string projectName = Path.GetFileName(fullPath);
``` | 2011/05/16 | [
"https://Stackoverflow.com/questions/6018293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/260127/"
] | Well, to *exactly* answer your question title :-)
```
var lastPartOfCurrentDirectoryName =
Path.GetFileName(Environment.CurrentDirectory);
``` | This works perfectly fine with me :)
```
Path.GetFileName(path.TrimEnd('\\')
``` |
42,941,927 | I currently run this code:
```
searchterm = "test"
results = resultsArray.filter { $0.description.contains (searchterm!) }
```
My question is how do I search in `company_name` or `place` or any other field in my model and add it to the results.
Do I need to use filters together and then append the results to a new variable instance of my model?
EDIT:
If "test" is in company\_name, place and description. I want all three results returned. However, if "test" is only in place, I need only place to be returned.
EDIT2:
This is an example of my model return. Is this a dictionary or an array? I'm sorry I dont 100% percent know the difference. I know ' "this": is ' what a dictionary looks like, however because there were [] brackets around them, I thought that made it an array...
```
struct GraphData {
var description: String
var company_name: String
var places: String
init(description: String, company_name: String, places: String){
self.description = description
self.company_name = company_name
self.places = places
}
func toAnyObject() -> Any {
print("return")
return [
"description": description,
"company_name": company_name,
"places": places,
]
}
``` | 2017/03/22 | [
"https://Stackoverflow.com/questions/42941927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7237391/"
] | The easiest way to do this would be to create a custom `contains` method in your model which can you can use to match the search term against any property in the model:
```
class YourModel {
var company_name: String
var description: String
var place: String
// ...
func contains(_ searchTerm: String) -> Bool {
return self.company_name.contains(searchTerm)
|| self.description.contains(searchTerm)
|| self.place.contains(searchTerm)
}
}
```
You can then simply filter using your custom method:
```
let searchTerm = "test"
let results = resultsArray.filter { $0.contains(searchTerm) }
``` | Is this **resultsArray** a *dictionary* or an *array*?
You can do something like this
```
let searchTerm = "test"
let filter = resultsArray.filter{ $0.company_name!.contains(searchTerm) || $0.place!.contains(searchTerm) }
```
Edit
```
class TestClass: NSObject {
var place: String?
var company_name: String?
func contain(searchTerm: String) -> [String] {
var result = [String]()
if let placeVal = place, placeVal.contains(searchTerm) {
result.append(placeVal)
}
if let companyVal = company_name, companyVal.contains(searchTerm) {
result.append(companyVal)
}
return result
}
}
let searchTerm = "test"
let filter = resultsArray.map { $0.contain(searchTerm: searchTerm) }
``` |
27,475,831 | On Excel 2011 for Mac, OsX 10.9
`=DATEVALUE("08/22/2008")` returns a `#VALUE` error on my Mac.
I tried the same command on Excel 2013 on Windows, as well as Office 365, both places work fine.
Also a different variation `=DATEVALUE("22-AUG-2008")` works fine on my mac.
According to the help doc, both are supposed to work. (I have a screen shot, but evidently I am too new to post images)
Any one seen problems like this? Any work around? | 2014/12/15 | [
"https://Stackoverflow.com/questions/27475831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4360666/"
] | What you are trying to do can be done with LINQ. What you are basically asking for is a *projection*.
[MSDN describes a projection](http://msdn.microsoft.com/en-us/library/bb546168.aspx) as this:
>
> Projection refers to the operation of transforming an object into a new form that often consists only of those properties that will be subsequently used. By using projection, you can construct a new type that is built from each object. You can project a property and perform a mathematical function on it. You can also project the original object without changing it.
>
>
>
So we want to project the objects in your `the_people` array into a new array. The documentation recommends using the `Select` LINQ operator:
```
var the_people_names = the_people.Select(p => p.first_name);
```
What goes inside of the `Select` is a delegate, often in the form of a [lambda expression](http://msdn.microsoft.com/en-us/library/bb397687.aspx) or anonymous delegate.
But we aren't quite there yet. `Select` is just a deferred evaluation that creates an enumerable sequence. It does not return an array. To create an array, we use [`.ToArray()`](http://msdn.microsoft.com/en-us/library/x303t819(v=vs.110).aspx):
```
var the_people_names_array = the_people.Select(p => p.first_name).ToArray();
```
You can use this approach to any property of `people` class, including the date of birth.
You can learn more about LINQ on MSDN on the [LINQ about page](http://msdn.microsoft.com/en-us/library/bb397926.aspx). | ```
var firstNames = the_people.Select(p => p.first_name).ToArray();
var dates_of_birth = the_people.Select(p => p.date_of_birth).ToArray();
``` |
14,216 | Why is a pre fade aux used for monitoring and a post fade aux for effects? | 2012/06/05 | [
"https://sound.stackexchange.com/questions/14216",
"https://sound.stackexchange.com",
"https://sound.stackexchange.com/users/243/"
] | +1 to Sonsey's explanation of Pre and Post-fade sends.
However, I'd add that you don't ALWAYS send monitor mixes prefade, either.
I have a large vocal ensemble that I mix regularly, whose monitors sends I almost always send POST-fader. Why? Because I want them to hear in their monitors the same mix that the house is hearing, so that they can more accurately adjust and balance between each other. I also want their monitors to fade up and out with the house mix (for a variety of reasons).
The key take-away here should be that there are no hard and fast rules. Learn what your tools do, and then choose the best one available to accomplish the job at hand.
If you are clear on what PRE and POST-fader sends do, how they differ, and the relative tradeoffs you have to deal with when using them, you can make an intelligent decision to use either one based on your needs at that specific time. | In a building changing levels on the main mix only will change the sound in the main mix if you don't change the levels in the monitor mix together in most rooms, EQ all speakers the same and go (Post Fader) All Aux sends or Monitor sends set at unity, And all adjustments will be made at the main fader, Made my sound 100% better, The trick is perfect balance between monitor mixes and House Mix.
Keep some head room in the pre' so you can raise volume wherever in the mix to make everyone happy. |
21,043,147 | I have a list of integers with 50 items:
```
List<int> list = CreateList();
```
How could I split it into chunks of 9 items?
```
List<List<int>> chunks = CreateChucks(list);
```
I've written this, is there any better way?
```
private static List<List<T>> GetChunks<T>(List<T> list, int maxChunkSize = 1000)
{
var chunks = new List<List<T>>();
for (int i = 0; i < list.Count; i = i + maxChunkSize)
{
chunks.Add(list.Skip(i).Take(maxChunkSize).ToList());
}
return chunks;
}
``` | 2014/01/10 | [
"https://Stackoverflow.com/questions/21043147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/133212/"
] | I suggest you to use `Batch` operator of [MoreLINQ](http://code.google.com/p/morelinq/wiki/OperatorsOverview) (available from NuGet):
```
IEnumerable<IEnumerable<int>> chuncks = list.Batch(9);
```
If you want list of lists, then you can create own extension:
```
public static List<List<T>> Batch(this IEnumerable<T> source, int batchSize)
{
List<List<T>> result = new List<List<T>>();
List<T> batch = new List<T>(batchSize);
foreach(T item in source)
{
if (batch.Count == batchSize)
{
result.Add(batch);
batch = new List<T>(batchSize);
}
batch.Add(item);
}
if (batch.Any())
result.Add(batch);
return result;
}
```
Your current implementation has big drawback - `list.Skip(i)` will enumerate source list from beginning for each batch you are adding to result. | Try this,
```
var list = new List<int>();
for (var i = 0; i < 50; i++)
list.Add(i);
var chunk = new List<List<int>>();
var chunkSize = list.Count / 9;
for (var i = 0; i < 9; i++)
{
var p = list.Skip(i * chunkSize).Take(chunkSize).ToList();
chunk.Add(p);
}
``` |
619,205 | I am currently trying to build a shutdown script for a windows server 2012 which will perform a planned failover to my replica server when the primary shuts down.
My problem is that the shutdown script gets executed *after* the Hyper-V service has been stopped.
Is there any possibility to get it executed before? | 2013/07/12 | [
"https://superuser.com/questions/619205",
"https://superuser.com",
"https://superuser.com/users/239195/"
] | This may be overkill, but one might create a service that depends on the Hyper-V service and performs the required action during service termination ... | Actually you can try to use schedule to create an task which trigger on the service stop event, and then perform shutdown -a, do the failover, and the shutdown -r.
The keypoint is get the right event to launch the tasks, and make sure it can abort the shutdown.
also, do not let window update to do auto-reboot, use the scheduler and do the event trigger to do failover and then planned reboot. |
258,960 | Is there a way for me to serialize an object in .NET without the XML Namespaces automatically serializing also? It seems that by default .NET believes the XSI and XSD namespaces should be included, but I don't want them there. | 2008/11/03 | [
"https://Stackoverflow.com/questions/258960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13611/"
] | If you want to get rid of the extra `xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"` and `xmlns:xsd="http://www.w3.org/2001/XMLSchema"`, but still keep your own namespace `xmlns="http://schemas.YourCompany.com/YourSchema/"`, you use the same code as above except for this simple change:
```
// Add lib namespace with empty prefix
ns.Add("", "http://schemas.YourCompany.com/YourSchema/");
``` | ```
XmlWriterSettings settings = new XmlWriterSettings
{
OmitXmlDeclaration = true
};
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
StringBuilder sb = new StringBuilder();
XmlSerializer xs = new XmlSerializer(typeof(BankingDetails));
using (XmlWriter xw = XmlWriter.Create(sb, settings))
{
xs.Serialize(xw, model, ns);
xw.Flush();
return sb.ToString();
}
``` |
12,855,448 | ```
console.log("20">10); //true
console.log("20a">"10"); //true
console.log("20a">10); //false
```
I want to know why the last one turns false.
And "20a" transforms to what before comparing. | 2012/10/12 | [
"https://Stackoverflow.com/questions/12855448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1726273/"
] | From the MDN page on [comparison operators](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Comparison_Operators):
>
> For relational abstract comparisons (e.g. <=), the operands are first converted to primitives, then the same Type, before comparison.
>
>
>
```
console.log("20">10); //true
```
This converts `"20"` to a number `20` and compares it. Since `20` is greater than `10`, it is true.
```
console.log("20a">"10"); //true
```
This compares the two strings. Since `"20a"` is greater (alphabetically) than `"10"`, it is true.
```
console.log("20a">10); //false
```
This converts `"20a"` to a number. The result is `NaN` (do `+"20a"` to see this in action). `NaN` is not greater than any number, so it returns false. | For the last case, Notice that even `"20a" < 10` return false. This highlights the evaluation of `"20a"` at `NaN` during the comparison, as `NaN` compared to any number always returns `false`. |
51,525,234 | I am trying to do something like this on **global scope** in nodejs REPL. As per my understanding both the following statements are valid. [see docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await)
```
let x = await Promise.resolve(2);
let y = await 2;
```
However, both these statements are throwing an error.
Can somebody explain why?
my node version is v8.9.4 | 2018/07/25 | [
"https://Stackoverflow.com/questions/51525234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6903290/"
] | since node 10, you can run node process with --experimental-repl-await to allow top level await
<https://nodejs.org/api/repl.html#repl_await_keyword> | You could wrap all the code in the global scope in an async function.
For example:
```
// ...global imports...
new Promise (async () => {
// ...all code in the global scope...
}).then()
``` |
106,270 | I have often wondered what the purpose of monopods is. It seems to me that they
remove only two degrees of freedom out of three possible degrees of freedom of
camera shake. And the situation is even worse for telephoto lenses, where one of the removed degrees of freedom isn't problematic, so that's one out of two removed. I usually don't need stabilization provided by a tripod unless it's for long exposures (where a monopod probably doesn't help) or tele photography (where I suspect monopod isn't that good either).
Camera shake can be, using [aircraft terminology](https://en.wikipedia.org/wiki/Aircraft_principal_axes):
* Pitch shake: this is removed by a monopod
* Roll shake: this is removed by a monopod
* Yaw shake: this is completely unaffected by a monopod
When using a telephoto lens, my understanding is that the yaw and pitch shake become
more problematic and the problematicity of roll shake is not that big. So, when
taking a tele photograph, you are affected mainly by:
* Pitch shake: this is removed by a monopod
* Yaw shake: this is completely unaffected by a monopod
So, when taking a tele photograph, a monopod removes only one of the two
problematic degrees of freedom of camera shake.
Based on this, my intuition is that a monopod offers probably around one
additional stop in possible exposure time when taking tele photographs, if even that. Is this intuition correct? Are
monopods really useful in practice to be used with telephoto lenses? How much extra stops do they offer in
reality for tele photography?
A good image stabilizer can offer 3-4 stops of advertised improvement, and I genuinely believe it achieves most of that for intermediate exposures (not short or long), having tested the IS of Canon 55-250 mm lens.
Related: [How much benefit can one expect from a monopod?](https://photo.stackexchange.com/questions/3015/how-much-benefit-can-one-expect-from-a-monopod) ...although the existing question is for general purpose photography, not for tele photography. Here I'm interested only in answers related to tele photography, such as photographing birds or the moon with a monopod and without image stabilization (which I suspect won't be a good idea). | 2019/03/30 | [
"https://photo.stackexchange.com/questions/106270",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/81735/"
] | It's instructive to look where monopods are most often used: sporting events, and shooting wildlife. In all of these cases, it's not a matter of "how many stops" a monopod can provide. It's simply a matter of increasing the keeper rate of shots.
### Competitive Sports (football, soccer, etc.)
Monopod are ubiquitous along the sidelines of professional football (international, American, etc.). For sports shooters, a fast shutter speed is necessary to capture the shot because the subject is moving fast. By-and-large, people like perfectly captured moments in time for these types of sports photos, with no motion blur. There are exceptions where motion blur in the background is desirable, but those shots are rare, and tend to be understood to be more artistic than the typical sports reportage.
Sports photographers have to be able to move, and move around each other, so tripods are unwieldy, impractical, and when near other sports photographers, inconsiderate. But when trying to capture events across the pitch, they need to use their longer lenses, and those lenses are heavy. So stability is required. The photographer *could* kneel down and use their knee as an elbow rest to provide some stability, but that limits them to shooting from a low position, and also reduces their mobility. A monopod allows comfortable shooting from a standing position, and the ability to move at a moment's notice. Even though a monopod is a compromise tool, it just so happens to be the best tool for this shooting situation.
### Autosports
The distances are much greater in autosport, so there's more reliance on telephoto lenses than there is in football/stadium/arena sports. But there's an extra element not present in team/stadium/arena sports: controlled motion blur is actually desirable. Very fast shutter speeds in car racing yields *boring* shots, where the cars' entire motion is stopped — the wheels don't look like they're spinning. Other than perhaps a heavily loaded front corner suspension when the car is braking hard into a turn, with a fast shutter speed the cars look like they're static and parked on the asphalt, rather than dynamic.
So autosport photographers slow down the shutter speed, maybe as low as ¹⁄₃₀ s, depending on the cars' speed from the photographer's viewpoint, focal length, etc. But that's not enough, because the entire car will be blurred. The photographer also has to **move the camera to follow the car's movement**. This requires lots of practice, and even when done by seasoned professionals, results in a lot of subpar (unusable) shots. This shot is only really effective for a panning shot, which just so happens to be perfect for a monopod: the monopod doesn't restrict the panning axis (so-called yaw axis) at all, while removing or reducing the other axes of motion.
Incidentally, this is also why most lenses with a tripod mounting foot, and image stabilization, have 3 modes of IS: off; full on; and tripod-mode, meaning the IS ignores panning / yaw motion in its stabilization. Not specifically for *motorsport*, but for tracking laterally-moving subjects with a telephoto lens.
### Wildlife
This is very similar to the competitive sports situation, but often at much further distances, similar to motorsports. In this case, the camera support is chosen depending on the particular subject intended to be tracked. Birders often sit in one spot, or move very infrequently and slowly, so a tripod is desirable for stability and to help carry the load of heavy supertelephoto lenses. Other game might require more mobility of the photographer, so the hassle of constantly moving and setting up a tripod would justify using a monopod instead. | To be precise monopode do not remove completely pitch and roll. It just move the point of rotation to be not the camera itself but the point where monopod touch the ground. This mitigate a lot but do not remove completely.
About yaw shake - you should be not afraid of. You should name it freedom and I think many sport photographers will agree. |
26,180,822 | I'm trying to figure this out since last week without going any step further. Ok, so I need to apply some **constraints** ***programmatically*** in **Swift** to a `UIView` using this code:
```
var new_view:UIView! = UIView(frame: CGRectMake(0, 0, 100, 100));
new_view.backgroundColor = UIColor.redColor();
view.addSubview(new_view);
var constX:NSLayoutConstraint = NSLayoutConstraint(item: new_view, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0);
self.view.addConstraint(constX);
var constY:NSLayoutConstraint = NSLayoutConstraint(item: new_view, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0);
self.view.addConstraint(constY);
var constW:NSLayoutConstraint = NSLayoutConstraint(item: new_view, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: new_view, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: 0);
self.view.addConstraint(constW);
var constH:NSLayoutConstraint = NSLayoutConstraint(item: new_view, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: new_view, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: 0);
self.view.addConstraint(constH);
```
But Xcode returns this weird output:
```
2014-10-03 09:48:12.657 Test[35088:2454916] Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
"<NSLayoutConstraint:0x7fa4ea446830 UIView:0x7fa4ea429290.centerX == UIView:0x7fa4ea4470f0.centerX>",
"<NSAutoresizingMaskLayoutConstraint:0x7fa4ea4516c0 h=--& v=--& UIView:0x7fa4ea429290.midX == + 50>",
"<NSLayoutConstraint:0x7fa4ea452830 'UIView-Encapsulated-Layout-Width' H:[UIView:0x7fa4ea4470f0(375)]>",
"<NSAutoresizingMaskLayoutConstraint:0x7fa4ea446db0 h=-&- v=-&- 'UIView-Encapsulated-Layout-Left' H:|-(0)-[UIView:0x7fa4ea4470f0] (Names: '|':UIWindow:0x7fa4ea444b20 )>"
)
Will attempt to recover by breaking constraint <NSLayoutConstraint:0x7fa4ea446830 UIView:0x7fa4ea429290.centerX == UIView:0x7fa4ea4470f0.centerX>
Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in
<UIKit/UIView.h> may also be helpful.
2014-10-03 09:48:12.658 Test[35088:2454916] Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
"<NSLayoutConstraint:0x7fa4ea44d160 UIView:0x7fa4ea429290.centerY == UIView:0x7fa4ea4470f0.centerY>",
"<NSAutoresizingMaskLayoutConstraint:0x7fa4ea451b30 h=--& v=--& UIView:0x7fa4ea429290.midY == + 50>",
"<NSLayoutConstraint:0x7fa4ea44cf00 'UIView-Encapsulated-Layout-Height' V:[UIView:0x7fa4ea4470f0(667)]>",
"<NSAutoresizingMaskLayoutConstraint:0x7fa4ea452700 h=-&- v=-&- 'UIView-Encapsulated-Layout-Top' V:|-(0)-[UIView:0x7fa4ea4470f0] (Names: '|':UIWindow:0x7fa4ea444b20 )>"
)
Will attempt to recover by breaking constraint <NSLayoutConstraint:0x7fa4ea44d160 UIView:0x7fa4ea429290.centerY == UIView:0x7fa4ea4470f0.centerY>
Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
```
Can you help me?
Thanks a lot | 2014/10/03 | [
"https://Stackoverflow.com/questions/26180822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3588489/"
] | If you find the above to be ugly. You should consider using a DSL for constraints. Such as [SnapKit](https://github.com/SnapKit/SnapKit)
Makes constraint API much more user-friendly
```
view.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
``` | ```
var xCenterConstraint : NSLayoutConstraint!
var yCenterConstraint: NSLayoutConstraint!
xCenterConstraint = NSLayoutConstraint(item: self.view, attribute: .CenterX, relatedBy: .Equal, toItem: (Your view NAme), attribute: .CenterX, multiplier: 1, constant: 0)
self.view.addConstraint(xCenterConstraint)
yCenterConstraint = NSLayoutConstraint(item: self.view, attribute: .CenterY, relatedBy: .Equal, toItem: (Your view Name), attribute: .CenterY, multiplier: 1, constant: 0)
self.view.addConstraint(yCenterConstraint)
``` |
24,316,071 | I have a lot of experience with AngularJS and I'm also playing around with Web Components and Polymer for a long time now.
What I really love about the these libraries and technologies, is the fact that they let me build my own components.
AngularJS gives me something called "Directives" and Web Components consists of a set of specs where one is called "Custom Elements", which pretty much does how it's called.
So with these I can do something like:
```
<my-element></my-element>
```
This is where the web goes, this is what everybody loves about HTML. Declarative tags that are easy to read and encapsulate functionality and behaviour. Also very nice: once Web Components are fully supported in the browsers, I could for example very easily remove my directive and rely on a web component, that looks and works the same without changing any code.
I know, that EmberJS has something called "Ember Components" which lets you basically build your own kind of components too. However, using them in HTML looks something like this:
```
{{#my-component}}
{{/my-component}}
```
Is it possible in EmberJS to also use components declaratively as tags? | 2014/06/19 | [
"https://Stackoverflow.com/questions/24316071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1531806/"
] | This does not answer your specific question
```
if [[ $h>=11 ]]; then
if [[ $h<=18 ]] && [[ $s<=00 ]]; then
```
**All** of those tests **always return true**.
The `test`, `[` and `[[` commands act differently based on the number of arguments they see.
All those tests have 1 single argument. In that case, if it's a non-empty string, you have a success return code.
Crucial crucial crucial to put whitespace around the operators.
```
if [[ $h >= 11 ]]; then
if [[ $h <= 18 ]] && [[ $s <= 00 ]]; then
```
Question for you: what do you expect this test to do? `[[ $s <= 00 ]]`
Be aware that these are all *lexical* comparisions. You probably want this instead:
```
# if hour is between 11 and 18 inclusive
if (( 10#$h >= 11 && 10#$h <= 18 )); then
``` | If I add the command "wc -l" at the end of my loop, I can get exactly what I wanted, means that number of lines (9 lines). But I want to know if there is a way to get it exactly inside the loop, maybe using the same command "wc -l" or not.
```
#!/bin/bash
let count=0
while read cdat ctim clat clon
do
h=${ctim:0:2}; # substring hours from ctim
m=${ctim:3:2};
s=${ctim:6:2};
if [[ $h>=11 && $h<=17 ]] || [[ $ctim == "18:00:00" ]]; then
echo "$count $LINE" $cdat $ctim $clat $clon
let count=$count+1
fi
done < cloud.txt | wc -l
```
exit
The result is exactly: **9**
But now how to do it inside the loop? |
28,786,473 | I'm trying to compile the following simple C++ code using Clang-3.5:
test.h:
```
class A
{
public:
A();
virtual ~A() = 0;
};
```
test.cc:
```
#include "test.h"
A::A() {;}
A::~A() {;}
```
The command that I use for compiling this (Linux, uname -r: 3.16.0-4-amd64):
```
$clang-3.5 -Weverything -std=c++11 -c test.cc
```
And the error that I get:
```
./test.h:1:7: warning: 'A' has no out-of-line virtual method definitions; its vtable will be emitted in every translation unit [-Wweak-vtables]
```
Any hints why this is emitting a warning? The virtual destructor is not inlined at all. Quite the opposite, there's a out-of-line definition provided in test.cc. What am I missing here?
**Edit**
I don't think that this question is a duplicate of :
[What is the meaning of clang's -Wweak-vtables?](https://stackoverflow.com/questions/23746941/what-is-the-meaning-of-clangs-wweak-vtables)
as Filip Roséen suggested. In my question I specifically refer to pure abstract classes (not mentioned in the suggested duplicate). I know how `-Wweak-vtables` works with non-abstract classes and I'm fine with it. In my example I define the destructor (which is pure abstract) in the implementation file. This should prevent Clang from emitting any errors, even with `-Wweak-vtables`. | 2015/02/28 | [
"https://Stackoverflow.com/questions/28786473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3129160/"
] | We don't want to place the vtable in each translation unit. So there must be some ordering of translation units, such that we can say then, that we place the vtable in the "first" translation unit. If this ordering is undefined, we emit the warning.
You find the answer in the [Itanium CXX ABI](https://mentorembedded.github.io/cxx-abi/abi.html "Itanium CXX ABI"). In the section about virtual tables (5.2.3) you find:
>
> The virtual table for a class is emitted in the same object containing the definition of its key function, i.e. the first non-pure virtual function that is not inline at the point of class definition. If there is no key function, it is emitted everywhere used. The emitted virtual table includes the full virtual table group for the class, any new construction virtual tables required for subobjects, and the VTT for the class. They are emitted in a COMDAT group, with the virtual table mangled name as the identifying symbol. Note that if the key function is not declared inline in the class definition, but its definition later is always declared inline, it will be emitted in every object containing the definition.
>
> *NOTE*: In the abstract, a pure virtual destructor could be used as the key function, as it must be defined even though it is pure. However, the ABI committee did not realize this fact until after the specification of key function was complete; **therefore a pure virtual destructor cannot be the key function**.
>
>
>
The second section is the answer to your question. A pure virtual destructor is no key function. Therefore, it is unclear where to place the vtable and it is placed everywhere. As a consequence we get the warning.
You will even find this explanation in the [Clang source documentation](http://clang.llvm.org/doxygen/classclang_1_1ASTContext.html#a439522ed0cae62952acae5f30f283de2 "Clang").
So specifically to the warning: You will get the warning when all of your virtual functions belong to one of the following categories:
1. `inline` is specified for `A::x()` in the class definition.
```
struct A {
inline virtual void x();
virtual ~A() {
}
};
void A::x() {
}
```
2. B::x() is inline in the class definition.
```
struct B {
virtual void x() {
}
virtual ~B() {
}
};
```
3. C::x() is pure virtual
```
struct C {
virtual void x() = 0;
virtual ~C() {
}
};
```
4. (Belongs to 3.) You have a pure virtual destructor
```
struct D {
virtual ~D() = 0;
};
D::~D() {
}
```
In this case, the ordering could be defined, because the destructor must be defined, nevertheless, by definition, there is still no "first" translation unit.
For all other cases, the key function is the first *virtual* function that does not fit to one of these categories, and the vtable will be placed in the translation unit where the key function is defined. | For a moment, let's forget about pure virtual functions and try to understand how the compiler can avoid emitting the vtable in all translation units that include the declaration of a polymorphic class.
When the compiler sees the declaration of a class with virtual functions, it checks whether there are virtual functions that are only declared but not defined inside the class declaration. If there is exactly one such function, the compiler knows for sure that it *must* be defined somewhere (otherwise the program will not link), and emits the vtable only in the translation unit hosting the definition of that function. If there are multiple such functions, the compiler choses one of them using some deterministic selection criteria and - with regard to the decision of where to emit the vtable - ignores the other ones. The simplest way to select such a single representative virtual function is to take the first one from the candidate set, and this is what clang does.
So, the key to this optimization is to select a virtual method such that the compiler can guarantee that it will encounter a (single) definition of that method in some translation unit.
Now, what if the class declaration contains pure virtual functions? A programmer *can* provide an implementation for a pure virtual function but (s)he **is not obliged to**! Therefore pure virtual functions do not belong to the list of candidate virtual methods from which the compiler can select the representative one.
But there is one exception - a pure virtual destructor!
A pure virtual destructor is a special case:
1. An abstract class doesn't make sense if you are not going to derive other classes from it.
2. A subclass' destructor always calls the base class' destructor.
3. The destructor of a class deriving from a class with a virtual destructor is automatically a virtual function.
4. All virtual functions of all classes, that the program creates objects of, are *usually* linked into the final executable (including the virtual functions that can be statically proved to remain unused, though that would require static analysis of the full program).
5. Therefore a pure virtual destructor *must* have a user-provided definition.
Thus, clang's warning in the question's example is not conceptually justified.
However, from the practical point of view the importance of that example is minimal, since a pure virtual destructor is rarely, if at all, needed. I can't imagine a more or less realistic case where a pure virtual destructor won't be accompanied by another pure virtual function. But in such a setup the need for the pureness of the (virtual) destructor completely disappears, since the class becomes abstract due to the presence of other pure virtual methods. |
8,156,448 | I have a random string of numbers
(numbers can only be used once, only from 1-9, almost any length(min 1,max 9)):
```
var
Input: String;
begin
Input := '431829576'; //User inputs random numbers
```
**And now I need to get specified number to front**. How about `5`.
```
var
Number: Integer;
begin
Number := 5;
```
and function executes with result `543182976`.
I don't have any ideas how to make a function like this, Thanks. | 2011/11/16 | [
"https://Stackoverflow.com/questions/8156448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/715707/"
] | Do you mean like this?
```
function ForceDigitInFront(const S: string; const Digit: Char): string;
begin
result := Digit + StringReplace(S, Digit, '', []);
end;
```
A more lightweight solution is
```
function ForceDigitInFront(const S: string; const Digit: Char): string;
var
i: Integer;
begin
result := S;
for i := 1 to Length(S) do
if result[i] = Digit then
begin
Delete(result, i, 1);
break;
end;
result := Digit + result;
end;
``` | Here is a solution that reduces the numer of String allocations needed, as well as checks if the digit is already in the front:
```
function ForceDigitInFront(const S: string; const Digit: Char): string;
var
dPos : Integer;
begin
Result := s;
for dPos := 1 to Length(Result) do
begin
if Result[dPos] = Digit then
begin
if dPos > 1 then
begin
UniqueString(Result);
Move(Result[1], Result[2], (dPos-1) * SizeOf(Char));
Result[1] := Digit;
end;
Exit;
end;
end;
end;
``` |
2,716,596 | In Java I need to put content from an OutputStream (I fill data to that stream myself) into a ByteBuffer. How to do it in a simple way? | 2010/04/26 | [
"https://Stackoverflow.com/questions/2716596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/311865/"
] | Though the above-mention answers solve your problem, none of them are efficient as you expect from NIO. ByteArrayOutputStream or MyByteArrayOutputStream first write the data into a Java heap memory and then copy it to ByteBuffer which greatly affects the performance.
An efficient implementation would be writing ByteBufferOutputStream class yourself. Actually It's quite easy to do. You have to just provide a write() method. See this link for [ByteBufferInputStream](http://www.snippetit.com/2010/01/java-use-bytebuffer-as-inputstream/). | // access the protected member **buf** & **count** from the extend class
```
class ByteArrayOutputStream2ByteBuffer extends ByteArrayOutputStream {
public ByteBuffer toByteBuffer() {
return ByteBuffer.wrap(buf, 0, count);
}
}
``` |
906,486 | The following doesn't work... (at least not in Firefox: `document.getElementById('linkid').click()` is not a function)
```
<script type="text/javascript">
function doOnClick() {
document.getElementById('linkid').click();
//Should alert('/testlocation');
}
</script>
<a id="linkid" href="/testlocation" onclick="alert(this.href);">Testlink</a>
``` | 2009/05/25 | [
"https://Stackoverflow.com/questions/906486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45311/"
] | The best way to solve this is to use Vanilla JS, but if you are already using jQuery, there´s a very easy solution:
```
<script type="text/javascript">
function doOnClick() {
$('#linkid').click();
}
</script>
<a id="linkid" href="/testlocation" onclick="alert(this.href);">Testlink</a>
```
Tested in IE8-10, Chrome, Firefox. | Granted, OP stated very similarly that this didn't work, but it did for me. Based on the notes in my source, it seems it was implemented around the time, or after, OP's post. Perhaps it's more standard now.
```
document.getElementsByName('MyElementsName')[0].click();
```
In my case, my button didn't have an ID. If your element has an id, preferably use the following (untested).
```
document.getElementById('MyElementsId').click();
```
I originally tried this method and it didn't work. After Googling I came back and realized my element was by name, and didn't have an ID. Double check you're calling the right attribute.
Source: <https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click> |
10,190,332 | I'm trying to write a Perl script which writes to a file and then uses linux's mail command to send whatever the Perl script wrote to the file.
My code is the following:
```
my $pathfile='some_pathfile';
open(W_VAR,">>$pathfile");
print W_VAR 'hello';
close W_VAR;
my $email_command='mail -s'." header".' some_email_address'.' <'." $pathfile";
system($email_command);
```
The problem is that the content in the pathfile never gets sent.
If I personally fill out that file, all is fine, but whatever perl has written is simply not sent. The content is in the file when i check though.
What is the problem? | 2012/04/17 | [
"https://Stackoverflow.com/questions/10190332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/322537/"
] | I suspect the problem is that your program doesn't terminate the line with a newline `"\n"` character. No doubt you put one into the file when you edited it manually?
Something like this may fix it, but I don't have a Linux box to hand so I can't test it.
```
use strict;
use warnings;
my $pathfile = 'path/to/file';
open my $w_var, '>>', $pathfile or die $!;
print $w_var "Hello\nWorld!\n";
close $w_var;
my $email_command = "mail -s header some\@emailaddress.com < $pathfile";
system $email_command;
```
---
**Edit**
But it would be far nicer to use something like [Mail::Sendmail](https://metacpan.org/module/Mail%3a%3aSendmail). [Email::Sender](https://metacpan.org/module/Email%3a%3aSender) is by far the best, but together with its dependencies it is a huge module for so simple a task and I hesitate to recommend it here.
The code to use `Mail::Sendmail` would look like this:
```
use strict;
use warnings;
use Mail::Sendmail;
my $pathfile = 'path/to/file';
open my $w_var, '>>', $pathfile or die $!;
print $w_var "Hello\n", "World!\n";
my $message = do {
open $w_var, '<', $pathfile or die $!;
local $/;
<$w_var>;
};
sendmail(
To => 'some@emailaddress.com',
From => 'my.address@email.com',
Message => $message,
)
or die $Mail::Sendmail::error;
``` | My bet is that your command is not well formed:
Try:
```
my $header = "My Subject";
my $some_email_address = "myaccount@myemail.com";
my $email_command="mail -s \"$header\" $some_email_address < $pathfile";
``` |
2,219,566 | I was asked a question in an interview and i wasn't able to answer it... Here is the question
* How will you define an instance[c#]?
My answer was it is an other name of an `object`... what is the right answer for this question... | 2010/02/08 | [
"https://Stackoverflow.com/questions/2219566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146857/"
] | I would describe instance as a single copy of an object. There might be one, there might be thousands, but an instance is a specific copy, to which you can have a reference. | **Instance is synonymous of object and when we create an object of class then we say that we are creating instance of class**
in simple word instance means creating reference of object(copy of object at particular time)
and object refer to memory address of class |
64,894,785 | What standard-defined integer type should I use for holding pointer to functions? Is there a `(void*)`-like type for functions that can hold any functions?
It's very certain that it's not `[u]intptr_t` because the standard said explicitly it's for pointers to objects and the standard makes a clear distinction between pointer to objects and pointer to functions. | 2020/11/18 | [
"https://Stackoverflow.com/questions/64894785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6230282/"
] | There is no specified type for an integer type that is sufficient to encode a function pointer.
Alternatives:
* Change code to negate the need for that integer type. Rarely is such an integer type truly needed.
* Use an array: `unsigned char[sizeof( int (*)(int)) )]` and `int (*f)(int))` within `union` to allow some examination of the integer-ness of the pointer. Still there may be padding issues. Comes down to what code want to do with such an integer.
* Use `uintmax_t` and *hope* it is sufficient. A `_Static_assert(sizeof (uintmax_t) >= sizeof (int (*)(int)) );` is a reasonable precaution though not a guarantee of success.
---
The limiting spec
>
> Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type. C17dr § 6.3.2.3 6
>
>
>
---
Note even `[u]intptr_t` for object pointer types are a guarantee either as they are optional types. | >
> It's very certain that it's not `[u]intptr_t`
>
>
>
It's true. But the distinction is **only** made to guarantee the correctness of some essential conversions. If you look at the 2nd edition of "The C Programming Language", then the distinction is more subtle to notice than the current wording in the standard.
If you target platforms with operating systems, then `[u]intptr_t` is probably *exactly* what you want, as:
1. POSIX specifies `dlsym` function that returns `void *` with the requirement that result can be casted to function pointers and be usable.
2. Win32 [`GetProcAddress`](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getprocaddress) is defined in such way that, if the return values' not NULL, it'll be a valid memory address that's valid for functions and/or objects. |
22,157,780 | What I have is php that updates the database field after a client signs a form. This works, but I want it to redirect to a new page after it is confirmed that the user signed it by clicking OK. It they click CANCEL it will leave them on the same page.
```
<?php
$username = 'joeblow';
require_once ("/mypath/include/connnect_db.php");
?>
<p>Please only submit this after above form is completely signed.</p>
<form id="item_complete" method="post">
<input name="submit" type="submit" form="item_complete" value="Submit After Signing">
</form>
<?php
if(isset($_POST['submit'])) { //if the submit button is clicked
$complete = 'c';
$query = "UPDATE mytbale SET mycolumn='c' WHERE username='$username'";
mysqli_query($con,$query) or die("Cannot Update");
echo "<script> confirmFunction(); </script>";
}
require_once ("/mypath/include/disconnect_db.php");
?>
<script type="text/x-javascript">
function confirmFunction(){
var r=confirm("Confirm that you have signed the form!");
if (r==true){
window.open("http://smartpathrealty.com/smart-path-member-page/");
}
else {
}
}
</script>
```
My problem is the javascript function does not execute after the php updtates the database.
I appreciate any advice or comments you have about this. | 2014/03/03 | [
"https://Stackoverflow.com/questions/22157780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3376610/"
] | You could post the form via **ajax** and in your php you can return a response to the javascript. That was you could use a callback to fire the new window.
Heres a jquery example:
```
$.post('/myscript.php', {foo: 'bar'}).done(function (response) {
window.open(......);
});
``` | Try:
```
if (r==true) {
window.open("http://smartpathrealty.com/smart-path-member-page/");
}
else {
window.location = "PAGE THAT YOU WANT";
}
``` |
7,855,060 | Is there a c++ operator that i could use for a for loop where it would add or subtract to variables based on whether one of the variables is less than or greater 0.
For instance
```
int a;
int b;
for(int i=0;i<some_number; i++)
result = a +< b
result = a-> b
``` | 2011/10/21 | [
"https://Stackoverflow.com/questions/7855060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1003543/"
] | No.
You can combine with the `?:` operator.
```
int a;
int b;
for(int i=0;i<some_number; i++)
result = (a < b)? result+b:result-b;
```
That is if I understood your example correctly.
`->` is an existing dereference operator.
Operator `?:` is an equivalent to the `if...else` construct. If the statement before `?` evaluates to `true`, the statement right after the `?` gets executed, otherwise the statement after the `:` gets executed. | Not sure if this would be any help?
```
result = a + (b*(a < b));
result = a - (b*(a > b));
```
Basically, `(a < b)` is converted into a boolean, which is basically either 1 (true) or 0 (false). `b` multiplied by 0 is of course zero, so nothing is added, and `b` multiplied by 1 is exactly `b`'s value. |
20,609,654 | I have the following code.
```
$resu = array_map(function($aVal, $bVal){
return "$bVal [$aVal]";
}, $result, $intersect);
$sorAr = array();
array_walk($resu, function($element) use (&$sorAr) {
$parts = explode(" ", $element);
$sorAr[$parts[0]] = trim($parts[1], ' []');
});
```
The problem lies when i need to use the anonymous function in both variable $resu and on array\_walk. the error shows as follows
>
> Parse error: syntax error, unexpected T\_FUNCTION in /dir...
>
>
>
I try to read on this site different suggestion but no luck. how do i solve this problem. Some one help please?
I have tried this code...
```
function arrSwap() {
$arraySwap = function($aVal, $bVal){
return "$bVal [$aVal]";
};
$resu = array_map($arraySwap, $result, $intersect);
}
$sorAr = array();
function arrSwap2() {
$arrayWalk = function($element) use (&$sorAr) {
$parts = explode(" ", $element);
$sorAr[$parts[0]] = trim($parts[1], ' []');
};
array_walk($resu, $arrayWalk);
}
```
but i get this error...
Fatal error: Cannot redeclare arrSwap() (previously declared in on line 100...
which the line 100 is this -> function arrSwap() { | 2013/12/16 | [
"https://Stackoverflow.com/questions/20609654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2685296/"
] | Anonymous functions are **not** available in **5.2**
See the changelog [here](http://www.php.net/manual/en/functions.anonymous.php).
>
> **5.3.0** Anonymous functions become available.
>
>
> | ```
function arr1($aVal, $bVal){ return "$bVal [$aVal]"; }
function arrayWalk($element){ $parts = explode(" ", $element); $sorAr[$parts[0]] = trim($parts[1], ' []'); }
function arrSwap(){ $resu = array_map('arr1', $result, $intersect); $sorAr = array(); array_walk($resu, 'arrayWalk'); }
```
if still prob there let me know all these values being passed there |
18,957,200 | I have confusion that what is the differnce between the two ?
Cycle and circuit so please make me sure by diagrams if possible.
what i have in mind is that the cycle is always in undirected graph the circuit is always a directed graph. please correct me if i am wrong ? | 2013/09/23 | [
"https://Stackoverflow.com/questions/18957200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2058543/"
] | A cycle is a closed path. A path is a walk with no repeated vertices.
Circuits refer to the closed trails.
Trails refer to a walk where no edge is repeated. | There's no official and/or widely accepted definition of a **difference** between `cycle` and `circuit`.
Most literature I've seen uses them interchangeably; if it doesn't: you should expect it to define this somewhere in its glossary of terms (if it has one). |
4,849,985 | I've just started learning C (coming from a C# background.) For my first program I decided to create a program to calculate factors. I need to pass a pointer in to a function and then update the corresponding variable.
I get the error 'Conflicting types for findFactors', I think that this is because I have not shown that I wish to pass a pointer as an argument when I declare the findFactors function. Any help would be greatly appreciated!
```
#include <stdio.h>
#include <stdlib.h>
int *findFactors(int, int);
int main (int argc, const char * argv[])
{
int numToFind;
do {
printf("Enter a number to find the factors of: ");
scanf("%d", &numToFind);
} while (numToFind > 100);
int factorCount;
findFactors(numToFind, &factorCount);
return 0;
}
int *findFactors(int input, int *numberOfFactors)
{
int *results = malloc(input);
int count = 0;
for (int counter = 2; counter < input; counter++) {
if (input % counter == 0){
results[count] = counter;
count++;
printf("%d is factor number %d\n", counter, count);
}
}
return results;
}
``` | 2011/01/31 | [
"https://Stackoverflow.com/questions/4849985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/596684/"
] | I apologise for adding yet another answer but I don't think anyone has covered every point that needs to be covered in your question.
1) Whenever you use `malloc()` to dynamically allocate some memory, you must also `free()` it when you're done. The operating system will, usually, tidy up after you, but consider that you have a process during your executable that uses some memory. When said process is done, if you `free()` that memory your process has more memory available. It's about efficiency.
To use free correctly:
```
int* somememory = malloc(sizeyouwant * sizeof(int));
// do something
free(somememory);
```
Easy.
2) Whenever you use `malloc`, as others have noted, the actual allocation is in bytes so you must do `malloc(numofelements*sizeof(type));`. There is another, less widely used, function called `calloc` that looks like this `calloc(num, sizeof(type));` which is possibly easier to understand. *calloc also initialises your memory to zero*.
3) You do not need to cast the return type of `malloc`. I know a lot of programming books suggest you do and C++ mandates that you must (but in C++ you should be using `new`/`delete`). See [this question](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc).
4) Your function signature was indeed incorrect - function signatures must match their functions.
5) On returning pointers from functions, it is something I discourage but it isn't wrong per se. Two points to mention: always keep 1) in mind. I [asked](https://stackoverflow.com/questions/2231477/calloc-inside-function) exactly what the problem was and it basically comes down to keeping track of those `free()` calls. As a more advanced user, there's also the allocator type to worry about.
Another point here, consider this function:
```
int* badfunction()
{
int x = 42;
int *y = &x;
return y;
}
```
This is bad, bad, bad. What happens here is that we create and return a pointer to `x` which only exists as long as you are in `badfunction`. When you return, you have an address to a variable that *no longer exists* because `x` is typically created on the stack. You'll learn more about that over time; for now, just think that the variable doesn't exist beyond its function.
Note that `int* y = malloc(...` is a different case - that memory is created on the heap because of the malloc and therefore survives the end of said function.
What would I recommend as a function signature? I would actually go with [shybovycha](https://stackoverflow.com/questions/4849985/newbie-question-how-to-pass-pointers-in-to-a-function-in-c/4850110#4850110)'s function with a slight modification:
```
int findFactors(int* factors, const int N);
```
My changes are just personal preference. I use `const` so that I know something is part of the input of a function. It isn't strictly necessary with just an int, but if you're passing in pointers, remember the source memory can be modified unless you use `const` before it, whereon your compiler should warn you if you try to modify it. So its just habit in this case.
Second change is that I prefer output parameters on the left because I always think that way around, i.e. `output = func(input)`.
Why can you modify function arguments when a pointer is used? Because you've passed a pointer to a variable. This is just a memory address - when we "dereference" it (access the value at that address) we can modify it. Technically speaking C is strictly pass by value. Pointers are themselves variables containing memory addresses and the contents of those variables are copied to your function. So a normal variable (say `int`) is just a copy of whatever you passed in. `int* factors` is a copy of the address in the pointer variable you pass in. By design, both the original and this copy point to the same memory, so when we dereference them we can edit that memory in both the caller and the original function.
I hope that clears a few things up. | EDIT: no reference in C (C++ feature)
Don't forget to modify numberOfFactors in the method (or remove this parameter if not useful). The signature at the beginning of your file must also match the signature of the implementation at the end (that's the error you receive).
Finally, your malloc for results is not correct. You need to do this:
```
int *results = malloc(input * sizeof(int));
``` |
43,757,455 | Why doest this script return diff error on Windows10 and Mac for the same Powershell Version?
Script executed:
[](https://i.stack.imgur.com/Na8b2.jpg)
[](https://i.stack.imgur.com/1uLUu.png)
[](https://i.stack.imgur.com/rRi6u.jpg) | 2017/05/03 | [
"https://Stackoverflow.com/questions/43757455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3101813/"
] | If they are coded as lists, you can just take the `[0]` element | Are you sure it was a numpy array?
I think just use
```
my_list[0]
```
to get the first element (in the first element is `[0,3.49,0,4.55]`) |
17,021,852 | Is there a widget for PointField as separate latitude/longitude inputs? Like SplitDateTimeWidget for DateTimeField. | 2013/06/10 | [
"https://Stackoverflow.com/questions/17021852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/820807/"
] | The answers are great for building your own solution, but if you want a simple solution that looks good and is easy to use, try:
<http://django-map-widgets.readthedocs.io/en/latest/index.html>
You can:
* enter coordinates
* select directly on the map
* look up items from Google places.
[](https://i.stack.imgur.com/CllSI.png) | Create a custom widget for this, you can get inspired by `SelectDateWidget` [here](https://github.com/django/django/blob/master/django/forms/extras/widgets.py). |
36,005,518 | I want too create a php loop table with 10 row and 1 column. There should be a loop of every odd row should print "H" and even row need to have select menu of year. I'm beginner of php
I tried this :
```
<?php
function year()
{
echo '<select>';
for ($i = 1998; $i<2015;)
{
echo "<option>$i</option>";
$i++;
}
echo '</select>';
}
$try = year();
echo '<table border="1">';
for ($row =1; $row < 10;)
{
echo "<tr><td>$row</td></tr>
<tr><td>$try</td></tr>";
$row++;
}
echo '</table>';
?>
``` | 2016/03/15 | [
"https://Stackoverflow.com/questions/36005518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6032796/"
] | @tommus solution is the best approach.
---
If you want to go with simple or less code approach, You can use a boolean flag to ensure that both are executed and move forward based on condition.
Declare a volatile boolean variable that will be used as a flag.
```
private volatile boolean flag = false;
```
flag would be false at start. Now, make call to both webservices. Any service that is executed will turn this flag TRUE.
```
getDataFromServer1();
function void onCompleteServer1() {
if(flag) {
loadViews();
} else {
flag = true;
}
}
getDataFromServer2();
onCompleteServer2Request() {
if(flag) {
loadViews();
} else {
flag = true;
}
}
``` | Not Perfect But I hope this logic works for you
```
onDatafromServer1Fetched{
flag1 = true;
}
onDataFromServer2Fetched{
flag2=true;
}
main(){
boolean flag1 = false;
boolean flag2 =false;
getDataFromSerVer1();
getDataFromServer2();
while(!flag1 && !flag2){/**no code required here*/}
loadView();
}
``` |
58,132,841 | I have a program that do several things.
Two of them is **read a date from a txt** and **rewrite a date in the same txt**.
The read of the date is a regex expression like:
```
[0-9]{2}/[0-9]{2}/[0-9]{4} [0-9]{2}:[0-9]{2}:[0-5]{1}[0-9]{1})
```
The problem is that my regex expression only works in the format
"DD/MM/YYYY hh:mm:ss" and its impossible to make sure my regex expression can match all system datetime formats.
So, I need to make sure my program run's in every system, regardless the system datetime.now.
For that, i thought about format every system datetime.now, at start, to the format mentioned "DD/MM/YYYY hh:mm:ss".
At the moment i have the following code:
```
Datetime currentDate = DateTime.ParseExact(DateTime.Now.ToString(), "DD/MM/YYYY hh:mm:ss", CultureInfo.InvariantCulture);
```
However, when running some tests, using a system date in format "D/M/YYYY h:m:s" i get the error:
**"String was not recognized as a valid DateTime."**
The problem is that if my date, for example, is "9/27/2019 04:26:46"(M/D/YYYY h:m:s) it can't fit in the format i defined.
Any idea?
Thank you in advance! | 2019/09/27 | [
"https://Stackoverflow.com/questions/58132841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7974748/"
] | You need to use the same format string and culture in every place where you convert the `DateTime` to string as well. In your sample code, you're doing
```
DateTime.Now.ToString()
```
This uses the default culture for the thread, and the default format. Unless assigned otherwise, the thread is probably using the local culture info. Instead, you would want to use the same format and the invariant culture:
```
DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
```
(note the lowercase "dd". "DD" is not a valid format specifier for date times; these things are case sensitive. Also note the "HH", which gives a 24-hour value, rather than 12-hour)
In practice, just using the invariant culture should be enough for persistence. Cultures already include default datetime formats, so unless you have a specific need to use a different format, why not use the default?
Also note that `DateTime` *doesn't have a format*. The format only comes into play when you convert from or to a string. That is the place where you need to ensure the same culture and format is used for both sides of the operation (and that's why for persistence, especially for data shared between different users or computers, you generally want to use the invariant culture). | If you need
>
> to make sure my program run's in **every system**, regardless the system datetime.now
>
>
>
you can adapt *international standard* for this, say, [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601).
In order to validate the `DateTime`, *regular expressions* like you have are not enough (just imagine *leap years*), but `TryParse` does it job:
```
string source = "2019-09-26T23:45:59";
// Either current culture date and time format or ISO
bool isValid = DateTime.TryParse(
source,
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeLocal,
out var _date);
```
Or if you want to be more restrictive use `TryParseExact`:
```
// ISO only
bool isValid = DateTime.TryParseExact(
source,
"s",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeLocal,
out var _date);
```
If you want to represent `DateTime.Now` in **ISO 8601**, add `"s"` standard format string:
```
string dateAsString = DateTime.Now.ToString("s");
```
Alas, you can provide a bunch of formats which are able to cope with any date and time formats; a classical example of *ambiguous date* is
```
01/02/03 - 01 Feb 2003 (Russia)
01/02/03 - 02 Jan 2003 (USA)
01/02/03 - 03 Feb 2001 (China)
```
You can *alleviate* the problem, while providing *several* `formats`:
```
// Here we try to support 4 formats (note different delimeters)
string[] formats = new string[] {
"s", // try ISO first
"dd'.'MM'.'yyyy HH':'mm':'ss", // if failed try Russian
"MM'/'dd'/'yyyy HH':'mm':'ss", // on error have a look at USA
"yyyy'-'MM'-'dd HH':'mm':'ss", // the last hope is Chinese
};
bool isValid = DateTime.TryParse(
source,
formats,
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeLocal,
out var date);
``` |
44,888,223 | I am getting the `java.io.IOException: No space left on device` that occurs after running a simple query in `sparklyr`. I use both last versions of `Spark` (2.1.1) and `Sparklyr`
```
df_new <-spark_read_parquet(sc, "/mypath/parquet_*", name = "df_new", memory = FALSE)
myquery <- df_new %>% group_by(text) %>% summarize(mycount = n()) %>%
arrange(desc(mycount)) %>% head(10)
#this FAILS
get_result <- collect(myquery)
```
I do have set both
* `spark.local.dir <- "/mypath/"`
* `spark.worker.dir <- "/mypath/"`
using the usual
```
config <- spark_config()
config$`spark.executor.memory` <- "100GB"
config$`spark.executor.cores` <- "3"
config$`spark.local.dir` <- "/mypath/"
config$`spark.worker.dir` <- "mypath/"
config$`spark.cores.max`<- "2000"
config$`spark.default.parallelism`<- "4"
config$`spark.total-executor-cores`<- "80"
config$`sparklyr.shell.driver-memory` <- "100G"
config$`sparklyr.shell.executor-memory` <- "100G"
config$`spark.yarn.executor.memoryOverhead` <- "100G"
config$`sparklyr.shell.num-executors` <- "90"
config$`spark.memory.fraction` <- "0.2"
Sys.setenv(SPARK_HOME="mysparkpath")
sc <- spark_connect(master = "spark://mynode", config = config)
```
where `mypath` has more than 5TB of disk space (I can see these options in the `Environment` tab). I tried a similar command in `Pyspark` and it failed the same way (same error).
By looking at the `Stages` tab in `Spark`, I see that the error occurs when `shuffle write` is about `60 GB`. (input is about `200GB`). This is puzzling given that I have plenty of space available. I have have looked at the other SO solutions already...
**The cluster job is started with magpie** <https://github.com/LLNL/magpie/blob/master/submission-scripts/script-sbatch-srun/magpie.sbatch-srun-spark>
Every time I start a Spark job, I see a directory called `spark-abcd-random_numbers` in my `/mypath` folder. but the size of the files in there is very small (nowhere near the 60GB shuffle write)
* there are about 40 parquet files. each is `700K` (original `csv` files were 100GB) They contain strings essentially.
* cluster is 10 nodes, each has 120GB RAM and 20 cores.
What is the problem here?
Thanks!! | 2017/07/03 | [
"https://Stackoverflow.com/questions/44888223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1609428/"
] | I ve had this problem multiple times before. The reason behind is the temporary files. most of servers have a very small size partition for `/tmp/` which is the default temporary directory for spark.
Usually, I used to change that by setting that in `spark-submit` command as the following:
```
$spark-submit --master local[*] --conf "spark.driver.extraJavaOptions=-Djava.io.tmpdir=/mypath/" ....
```
In your case, I think that you can provide that to the configuration in R as following (I have not tested that but that should work):
```
config$`spark.driver.extraJavaOptions` <- "-Djava.io.tmpdir=/mypath/"
config$`spark.executor.extraJavaOptions ` <- "-Djava.io.tmpdir=/mypath/"
```
Notice that you have to change that for the driver and executors since you're using Spark standalone master (as I can see in your question) | Once you set the parameter, you can see the new value of spark.local.dir in Spark environment UI. But it doesn't reflect.
Even I faced the similar problem. After setting this parameter, I restarted the machines and then started working. |
38,759,018 | I have db with few 1000 of contacts and would like to delete all duplicated records. Sql query I have at the moment works well ( when in records - **tel**, **email**, **name1** are duplicated). Query deletes duplicates with lower id then last occurring record. But in some cases another fields of the record a filled in already (important ones will by **title** and **name2**). What i would like to achieve is for mysql to check if these fields are filled in and keep only the record with most information filed in.
My Query
```
<?php
$del_duplicate_contacts = $mysqli->query("
DELETE ca
FROM contacts ca
LEFT JOIN
(
SELECT MAX(id) id, name1, tel, email
FROM contacts
GROUP BY name1, tel, email
) cb ON ca.id = cb.id AND
ca.name1 = cb.name1 AND
ca.tel = cb.tel AND
ca.email = cb.email
WHERE cb.id IS NULL
");
?>
```
Example of table:
```
ID title name1 name2 tel email
1 John 01234 1@1.com
2 Mr John Smith 01234 1@1.com
3 John 01234 1@1.com
```
My query will delete record 1 and 2. I would like to keep only nr 2 and delete 1 and 3.
How I can achieve that? Is is possible? Or maybe i should involve PHP, if so How? | 2016/08/04 | [
"https://Stackoverflow.com/questions/38759018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1826668/"
] | Use `order by` in `group_concat`, you can try this:
```
DELETE c1 FROM contacts c1
JOIN (
SELECT
substring_index(group_concat(id ORDER BY ((title IS NULL OR title ='') AND (name2 IS NULL OR name2 = '')), id DESC), ',', 1) AS id,
name1, tel, email
FROM contacts
GROUP BY name1, tel, email
) c2
ON c1.name1 = c2.name1 AND c1.tel = c2.tel AND c1.email = c2.email AND c1.id <> c2.id;
```
[`Demo Here`](http://sqlfiddle.com/#!9/9f70b/1) | I have got solution using NOT EXIST clause instead of NOT IN
```
DELETE FROM contacts
WHERE NOT EXISTS (
SELECT 1 FROM (
SELECT * FROM (
SELECT * FROM contact AS tmp ORDER BY title DESC, name1 DESC, name2 DESC, email DESC, tel DESC )
as tbl group by name1)
as test WHERE contact.id= test.id
)
``` |
56,568,232 | I've have had a working version of mongoose instance methods working before. I'm not sure what is different about it this time around. The only thing I have done differently this time is that I separated the mongoose connection function outside of the `server.js` file into a config file that will be imported and call the `connect()` function.
I will mostly use this instance method in passport with the local strategy to log in the user. When I go to call my instance method on the user instance that was found by the previous `UserModel.findOne({ email })` the `verify(password)` instance method is not called and does not throw any errors.
For testing purposes, I've tried to hard code a `UserModel.findOne()` right into connection field and I do get a user back. I then decided to call my instance method right off of the returned user instance named `verify()`.
I have also attempted changing the name of the method to `comparePassword`, I've tried testing with statics to check if it is even called at all (which it wasn't), I've also tried to research other ways to import my schemas and models, and that does not seem to work. I have experimented with Async/Await hasn't changed the output
---
**File: `mongo.db.js`**
```
const connect = () => {
return new Promise((resolve, reject) => {
mongoose.connect(
config.get('DB.STRING'),
{ useCreateIndex: true, useNewUrlParser: true },
async (err) => {
if (err) reject(err)
resolve()
// TESTING INSTANCE METHODS
await mongoose.connection
.collection('users')
// HARD CODED TEST EMAIL
.findOne({ email: 'braden_feeney@hotmail.com' }, (err, result) => {
if (err) reject(err)
console.log(result)
console.log(result.verify('test1234'))
})
},
)
})
}
const close = () => {
return mongoose.disconnect()
}
export default { connect, close }
```
---
**File: `passport.config.js`**
```
passport.use(
new LocalStrategy(
{
usernameField: 'email',
passwordField: 'password',
},
async (email, password, done) => {
try {
// Find the user given the email
const user = await User.findOne({ email })
// If not found
if (!user) return done(null, false)
// Check if the password is correct
const isValididated = await user.verify(password)
// If not matched
if (!isValididated) return done(null, false)
// Return the user
done(null, user)
} catch (error) {
done(error, false)
}
},
),
)
```
---
**File: `users.model.js`**
```
const UserSchema = new Schema(
// HIDDEN FOR SECURITY
{ ... },
{ versionKey: false, timestamps: true },
)
// HIDDEN FOR SECURITY - PRE SAVE WORKS AS EXPECTED
UserSchema.pre('save', async function(next) { ... })
// THIS IS THE METHOD THAT SHOWS AS 'Not a Function'
UserSchema.methods.verify = function(password) {
bcrypt.compare(password, this.password, (err, res) => {
if (err) return new Error(err)
return res
})
}
export default model('User', UserSchema)
```
When I call `user.verify(password)` I expect to see a Boolean value either get returned from the function.
The actual result is an Error thrown stating
`TypeError: user.verify is not a function` | 2019/06/12 | [
"https://Stackoverflow.com/questions/56568232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4567394/"
] | Technically, it doesn't work with any of them.
From [[dcl.constexr]](http://eel.is/c++draft/dcl.constexpr#5):
>
> For a constexpr function or constexpr constructor that is neither defaulted nor a template, if no argument values exist such that an invocation of the function or constructor could be an evaluated subexpression of a core constant expression, or, for a constructor, a constant initializer for some object ([basic.start.static]), **the program is ill-formed, no diagnostic required**.
>
>
>
`f()` and `g()` are never constant expressions (neither `std::cout << x` nor `printf()` are constexpr functions), so the `constexpr` declaration is ill-formed. But the compiler isn't *required* to diagnose this (in this case, it may be easy, but in the general case... not so much). What you're seeing is that your compiler was able to diagnose one problem but not the other.
But they're both wrong. | It doesn't. You need to use it to force a compile time error.
```
constexpr int a = f(), 0; // fails
constexpr int b = g(), 0; // fails
```
`constexpr` functions that never produce a constant expression are ill-formed; no diagnostic required. This means that compilers do a best effort check to see if that is the case, but your program already has an error either way. Seems like gcc can't see that `printf` is not a constant expression. [clang errors at the definition](https://godbolt.org/z/unRcDe). |
43,490,938 | I'm currently searching how to write correctly a regex for this application :
1 - A number without "." with a length of 1 to 5 digits
=> `/^(\d{1,5})$/`
2 - A number with "." with a length of 1 to 5 digits before the "." and 1 to 4 digits after the "." or a number starting with "." with a length of 1 to 4 digits after the "."
=> `/^(\d{1,5})?\.?(\d{1,4})?$/`
I tried to use a or operator "|", but it doesn't work ;(
=> `/^(\d{1,5})?\.?(\d{1,4})?$|^(\d{1,5})$/`
I do not understand why, it's my first java script regex and i'm not sure to use well the "|" operator.
Following the answers I would like to obtain with **1** regex :
```
123 => ok
12345 => ok
123456 => not ok
12345.2156 => ok
123456.12 => not ok
12345.12345 => not ok
```
Thank you very much for your help.
Have a nice day.
Etienne | 2017/04/19 | [
"https://Stackoverflow.com/questions/43490938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7888406/"
] | You could check the second part as optional.
```js
function check(v) {
return /^(?=.)\d{0,5}(\.\d{1,4})?$/.test(v);
}
console.log(['', '.123', 123, 12345, 12345.2156, 123456, 123456.12, 12345.12345].map(check));
``` | `^(\d{1,5}|\d{1,5}\.\d{1,4}|\.\d{1,4})$` with a double | works just fine here <https://regex101.com/r/jTVW2Z/1> |
2,719,279 | I have mapped a simple entity, let's say an invoice using Fluent NHibernate, everything works fine... after a while it turns out that very frequently i need to process 'sent invoices' (by sent invoices we mean all entities that fulfill invoice.sent==true condition)... is there a way to easily abstract 'sent invoices' in terms of my data access layer? I dont like the idea of having aforementioned condition repeated in half of my repository methods.
I thought that using a simple filtering view would be optimal, but how could it be done?
Maybe I am doing it terribly wrong and someone would help me realize it :)? | 2010/04/27 | [
"https://Stackoverflow.com/questions/2719279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/309588/"
] | I just found this one:
<http://web.archive.org/web/20141001063046/http://elliottjorgensen.com/nhibernate-api-ref/index.html>
It doesn't seem to be official, but at least it *looks* like an API reference... unlike the official reference, which mostly describes concepts and mappings without any information about classes and members. | If you're on Windows, get [ILSpy](http://wiki.sharpdevelop.net/ILSpy.ashx) and point it at NHibernate.dll. It's not quite the same as real API documentation, but it's not half bad. |
29,819,947 | I am trying to implement a custom directive for a **counter** widget.
I have been able to implement it, but there are many things i need some light to be thrown on.
* Can this directive be written in a better way ?
* How do i use the `scope:`(isolate scope) in a better way ?
* on click of any reset button i want all the `startnumber` to be reset to "1" ?
* Where does the `scope` inherit from?Does it inherit from the element being called from?
**HTML** snippet
```
<body>
<counter-widget startnumber=1 ></counter-widget>
<counter-widget startnumber=1 ></counter-widget>
<counter-widget startnumber=1 ></counter-widget>
</body>
```
**JS** snippet
```
angular.module("myApp",[])
.directive("counterWidget",function(){
return{
restrict:"E",
scope:{
},
link:function(scope,elem,attr){
scope.f = attr.startnumber;
scope.add = function(){
scope.f = Number(scope.f) + 1;
}
scope.remove = function(){
scope.f =Number(scope.f) - 1;
}
scope.reset = function(){
scope.f = 1;
}
},
template:"<button ng-click='add()'>more</button>"+
"{{f}}"+
"<button ng-click='remove()'>less</button> "+
"<button ng-click='reset()'>reset</button><br><br>"
}
})
```
Thanks in advance for the help. | 2015/04/23 | [
"https://Stackoverflow.com/questions/29819947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4112077/"
] | First, pass in your startnumber attribute, so we can reset to that number instead of having to hard code in a number.
You want to isolate the scope if you are going to have multiple counters.
But here is how you can implement a global reset:
```
app.directive("counterWidget",function(){
return{
restrict:"E",
scope:{
startnumber: '=',
resetter: '='
},
link:function(scope,elem,attr){
scope.f = attr.startnumber;
scope.add = function(){
scope.f++
}
scope.remove = function(){
scope.f--
}
scope.reset = function(){
scope.f = attr.startnumber
scope.$parent.triggerReset()
}
scope.$watch(function(attr) {
return attr.resetter
},
function(newVal) {
if (newVal === true) {
scope.f = attr.startnumber;
}
})
},
template:"<button ng-click='add()'>more</button>"+
"{{f}}"+
"<button ng-click='remove()'>less</button> "+
"<button ng-click='reset()'>reset</button><br><br>"
}
})
```
And in the controller you just add a small reset function that each directives is watching:
```
$scope.triggerReset = function () {
$scope.reset = true;
console.log('reset')
$timeout(function() {
$scope.reset = false;
},100)
}
```
I wouldn't overcomplicate the decrement and increment functions. ++ and -- should be fine.
We create the global reset function by adding an attribute and passing it in to the directive. We then watch that attribute for a true value. Whenever we click reset we trigger a function in the $parent scope (the triggerReset() function). That function toggles the $scope.reset value quickly. Any directive which has that binding in it's resetter attribute will be reset to whatever is in the startnumber attribute.
Another nice thing is that the reset will only affect counters you want it to. You could even create multiple groups of counters that only reset counters in it's own group. You just need to add a trigger function and variable for each group you want to have it's own reset.
Here is the demo:
**[Plunker](http://plnkr.co/edit/cmOHvLCRpRVwd5Z48gGm?p=preview)**
**EDIT:**
So the question came up in comments - can the $watch function 'miss' the toggle?
I did a little testing and the best answer I have so far is, on plunker if I set it to 1ms or even remove the time argument completely, the $watch still triggers.
I have also asked this question to the community here: [Can $watch 'miss'?](https://stackoverflow.com/questions/29824224/can-watch-miss) | You can use ng-repeat in your html.you can define count = 3
```
<body>
<div ng-repeat="index in count">
<counter-widget startnumber=1 ></counter-widget></div>
</body>
```
Also follow the link .They have explained scope inheritance in a better way
<http://www.sitepoint.com/practical-guide-angularjs-directives-part-two/>
**Parent Scope (scope: false)** – This is the default case. If your directive does not manipulate the parent scope properties you might not need a new scope. In this case, using the parent scope is okay.
**Child Scope (scope:true)** – This creates a new child scope for a directive which prototypically inherits from the parent scope. If the properties and functions you set on the scope are not relevant to other directives and the parent, you should probably create a new child scope. With this you also have all the scope properties and functions defined by the parent.
**Isolated Scope (scope:{})** – This is like a sandbox! You need this if the directive you are going to build is self contained and reusable. Your directive might be creating many scope properties and functions which are meant for internal use, and should never be seen by the outside world. If this is the case, it’s better to have an isolated scope. The isolated scope, as expected, does not inherit the parent scope. |
4,428,048 | I am writing code to use a library called SCIP (solves optimisation problems). The library itself can be compiled in two ways: create a set of .a files, then the binary, OR create a set of shared objects. In both cases, SCIP is compiled with it's own, rather large, Makefile.
I have two implementations, one which compiles with the .a files (I'll call this program 1), the other links with the shared objects (I'll call this program 2). Program 1 is compiled using a SCIP-provided makefile, whereas program 2 is compiled using my own, much simpler makefile.
The behaviour I'm encountering occurs in the SCIP code, not in code that I wrote. The code extract is as follows:
```
void* BMSallocMemory_call(size_t size)
{
void* ptr;
size = MAX(size, 1);
ptr = malloc(size);
// This is where I call gdb print statements.
if( ptr == NULL )
{
printf("ERROR - unable to allocate memory for a SCIP*.\n");
}
return ptr;
}
void SCIPcreate(SCIP** A)
{
*A = (SCIP*)BMSallocMemory_call(sizeof(**(A)))
.
.
.
}
```
If I debug this code in gdb, and step through `BMSallocMemory_call()` in order to see what's happening, and view the contents of `*((SCIP*)(ptr))`, I get the following output:
Program 1 gdb output:
```
289 size = MAX(size, 1);
(gdb) step
284 {
(gdb)
289 size = MAX(size, 1);
(gdb)
290 ptr = malloc(size);
(gdb) print ptr
$1 = <value optimised out>
(gdb) step
292 if( ptr == NULL )
(gdb) print ptr
$2 = <value optimised out>
(gdb) step
290 ptr = malloc(size);
(gdb) print ptr
$3 = (void *) 0x8338448
(gdb) print *((SCIP*)(ptr))
$4 = {mem = 0x0, set = 0x0, interrupt = 0x0, dialoghdlr = 0x0, totaltime = 0x0, stat = 0x0, origprob = 0x0, eventfilter = 0x0, eventqueue = 0x0, branchcand = 0x0, lp = 0x0, nlp = 0x0, relaxation = 0x0, primal = 0x0, tree = 0x0, conflict = 0x0, cliquetable = 0x0, transprob = 0x0, pricestore = 0x0, sepastore = 0x0, cutpool = 0x0}
```
Program 2 gdb output:
```
289 size = MAX(size, 1);
(gdb) step
290 ptr = malloc(size);
(gdb) print ptr
$1 = (void *) 0xb7fe450c
(gdb) print *((SCIP*)(ptr))
$2 = {mem = 0x1, set = 0x8232360, interrupt = 0x1, dialoghdlr = 0xb7faa6f8, totaltime = 0x0, stat = 0xb7fe45a0, origprob = 0xb7fe4480, eventfilter = 0xfffffffd, eventqueue = 0x1, branchcand = 0x826e6a0, lp = 0x8229c20, nlp = 0xb7fdde80, relaxation = 0x822a0d0, primal = 0xb7f77d20, tree = 0xb7fd0f20, conflict = 0xfffffffd, cliquetable = 0x1, transprob = 0x8232360, pricestore = 0x1, sepastore = 0x822e0b8, cutpool = 0x0}
```
The only reason I can think of is that in either program 1's or SCIP's makefile, there is some sort of option that forces malloc to initialise memory it allocates. I simply must learn why the structure is initialised in the compiled implementation, and is not in the shared object implementation. | 2010/12/13 | [
"https://Stackoverflow.com/questions/4428048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/532441/"
] | I doubt the difference has to do with how the two programs are built.
`malloc` does not initialize the memory it allocates. It may so happen by chance that the memory you get back is filled with zeroes. For example, a program that's just started is more likely to get zero-filled memory from `malloc` than a program that's been running for a while and allocating/deallocating memory.
**edit** You may find the following past questions of interest:
* [malloc zeroing out memory?](https://stackoverflow.com/questions/1622196/malloc-zeroing-out-memory)
* [Create a wrapper function for malloc and free in C](https://stackoverflow.com/questions/262439/create-a-wrapper-function-for-malloc-and-free-in-c)
* [When and why will an OS initialise memory to 0xCD, 0xDD, etc. on malloc/free/new/delete?](https://stackoverflow.com/questions/370195/when-and-why-will-an-os-initialise-memory-to-0xcd-0xdd-etc-on-malloc-free-new) | On Linux, according to [this thread](http://www.linuxquestions.org/questions/linux-general-1/in-linux-malloc-initializes-to-zero-843577/), memory will be zero-filled when first handed to the application. Thus, if your call to `malloc()` caused the program's heap to grow, the "new" memory will be zero-filled.
One way to verify is of course to just step *into* `malloc()` from your routine, that should make it pretty clear whether or not it contains code to initialize the memory, directly. |
5,146,621 | For several reasons I prefer to configure my editor to insert spaces when `TAB` is pressed.
But recently I discovered that tabs should remain as tabs in make files.
How do I insert tab (`\t`, not `" "`) without reconfiguring editors each time I need to write make files?
I use the following editors:
[Emacs](http://en.wikipedia.org/wiki/Emacs), [Kate](https://en.wikipedia.org/wiki/Kate_%28text_editor%29), [gedit](http://en.wikipedia.org/wiki/Gedit), and the [Visual Studio](http://en.wikipedia.org/wiki/Microsoft_Visual_Studio) editor. | 2011/02/28 | [
"https://Stackoverflow.com/questions/5146621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/638231/"
] | To manually insert a tab in Emacs, use ctrl-Q TAB. control-Q causes the next key to be inserted rather than interpreted as a possible command. | Emacs' Makefile mode takes care of where to insert tabs and spaces as long as you press the right keys at the right places. Either that, or I missed some details in the question. |
55,017,122 | So I know how to get the selected value using the ionChange event, but how do I get the selected index. For example if i was to select the 3rd value down in a dropdown how can I get the selected index (2) rather than the value selected? | 2019/03/06 | [
"https://Stackoverflow.com/questions/55017122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4372290/"
] | You can do something like ths:-
```
<ion-select placeholder="Select One">
<ion-select-option value="id1">Value1</ion-select-option>
<ion-select-option value="id2">Value2</ion-select-option>
</ion-select>
```
By this when you will select any particular option, then on its change event you will get that object's id instead of the value in the controller.
I hope it helps. | This is what you can do to get the id. Add a local variable to your ion-select *#selectedIndex*. After add your value like this ***[value]=[prices.w, id]***
```
<ion-select slot="end" (ionChange)="changePrice($event)" #selectIndex>
<ion-select-option text-uppercase [value]="[prices.w, id]" *ngFor="let prices of prodData?.prices; let id = index" >{{prices.w}}</ion-select-option>
</ion-select>
```
In your ts. Import ViewChild
```
import { Component, OnInit, ViewChild } from '@angular/core';
```
After reference your local variable
```
@ViewChild('selectIndex') selectedId: ElementRef;
```
then declare your *ionChange()* function **changePrice(event)** and add the following code
```
public changePrice(event) {
const childCount = this.selectedId['el']['childElementCount'];
this.selectedId['el']['childNodes'][`${childCount}`]['defaultValue'] = event.detail.value[0];
this.selectedId['el']['shadowRoot']['children'][1]['innerHTML'] = event.detail.value[0];
this.selectedId['el']['shadowRoot']['children'][1]['innerText'] = event.detail.value[0];
console.log(event.detail.value[1]);
}
```
logs your index
```
console.log(event.detail.value[1]);
```
Hope it works fine |
31,852,339 | The array
```
Array ( [0] =>
CLG
0%
[1] =>
TSM
0%
[2] =>
7sway
10%
[3] =>
Nostalgie
90%
[4] =>
K1CK.pt
9%
[5] =>
E-Frag
91%
[6] =>
HR
86%
```
So I want to print the elements of this array into the same div by using the for loop. I want to print 2 array parts into the same element
The imageined output
```
<div>
CLG
0%
TSM
0%
</div>
<div>
7sway
10%
Nostalgie
90%
</div>
``` | 2015/08/06 | [
"https://Stackoverflow.com/questions/31852339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5197523/"
] | As a temporarily solution, I would introduce an extension method:
```
public static class ZipFileExtensions
{
public static Task SaveAsync(this ZipFile zipFile, string filePath)
{
zipFile.Save(filePath);
return Task.FromResult(true);
}
}
```
Then the usage would be:
```
public static async Task<bool> ZipAndSaveFileAsync(string fileToPack, string archiveName, string outputDirectory)
{
var archiveNameAndPath = Path.Combine(outputDirectory, archiveName);
using (var zip = new ZipFile())
{
...
await zip.SaveAsync(archiveNameAndPath).ConfugureAwait(false);
}
return true;
}
```
1. Implementing synchronous tasks does not violate anything (talking about Task.FromResult)
2. Submit a request to <https://github.com/jstedfast/Ionic.Zlib> asking for an async support in the library due to IO operations
3. Hope that's done eventually, and then you can upgrade the Ionic.Zlib in your app, delete the `ZipFileExtensions`, and continue using async version of the Save method (this time built into the library).
4. Alternatively, you can clone the repo from GitHub, and add SaveAsync by yourself, the submit a pull request back.
5. It's just not possible to 'convert' a sync method to an async if a library does not support it.
From performance standpoint, this might not be the best solution, but from management point of view, you can decouple stories "Convert everything to async" and "Improve app performance by having Ionic.Zlib async", what makes your backlog more granular. | Some of the answers suggest that zipping a file is not a process that you should do asynchronously. I don't agree with this.
I can imagine that zipping files is a process that might take some time. During this time you want to keep your UI responsive or you want to zip several files simultaneously, or you want to upload a zipped file while zipping the next one/
The code you show is the proper way to make your function asynchronous. You question whether it is useful to create such a small method. Why not let the users call Task.Run instead of call your async function?
The reason for this is called information hiding. By creating the async function you're hiding **how** you zip asynchronously, thus relieving others from knowing how to do this.
Besides, information hiding gives you the freedom to change the internals of the procedure as long as you don't change the pre- and postcondition.
One of the answers said that your function still is not asynchronous. That is not true. Callers of your function may call your async function without awaiting for it. While the task is zipping, the caller may do other things. As soon as it needs the boolean result of the task if can await for the task.
Example of usage:
```
private async Task DoSomethingSimultaneously()
{
var taskZipFileA = ZipAndSaveFileAsync(fileA, ...)
// while this task is zipping do other things,
// for instance start zipping file B:
var taskZipFileB = ZipAndSaveFileAsync(fileB, ...)
// while both tasks are zipping do other things
// after a while you want to wait until both files are finished:
await Task.WhenAll(new Task[] {taskZipFileA, taskZipFileB});
// after the await, the results are known:
if (taskZipFileA.Result)
{
// process the boolean result of taskZipFile A
}
```
Note the difference between **Task.WaitAll** and **Task.WhenAll**
In async - await you use Task.WhenAll. The return is a Task, so you can
```
await Task.WhenAll (...)
```
For proper async-await, all functions that call any async function need to be async themselves and return a Task (instead of void) or Task`<TResult`> instead of TResult. There is one exception: the event handler may return void.
```
private async void OnButton1_clicked(object sender, ...)
{
bool zipResult = await SaveAndZipFileAsync(...);
ProcessZipResult(zipResult);
}
```
Using this method your UI keeps responsive. You don't have to call Task.Run
If you have a non-async function and want to start zipping while doing something else, your non-async function has to call Task.Run. As the function is not async it can't use await. When it needs the result of task.Run it needs to use Task.Wait, or Task.WaitAll
```
private void NonAsyncZipper()
{
var taskZipFileA = Task.Run ( () => ZipAndSaveFileAsync(...);
// while zipping do other things
// after a while when the result is needed:
taskZipFileA.Wait();
ProcesZipResult(taskZipFileA.Result);
}
``` |
10,856,545 | Is the locking object used for synchronization arbitrary or is there reasoning behind choosing a specific object? | 2012/06/01 | [
"https://Stackoverflow.com/questions/10856545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/925922/"
] | You'd be better off using one of the more modern locking techniques where much of the complexity and pitfalls have been removed/smoothed over. [Package](http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/locks/package-summary.html) `java.util.concurrent.locks` would be a good start. | The locking object needs to represent the exclusive part.
if you lock the whole object meaning using it exclusively by an thread, you may use the object "this" to lock. This is the way "synchronize" work on methods work.
```
public class A
{
public synchronized void do1 ()
{
...
}
public synchronized void do2 ()
{
...
}
}
```
if your object just has some set of members which should be used exclusively, you need separate (explicit) locking objects
```
public class B
{
private X x;
private Y y;
private Object lockXY = new Object ();
private R r;
private S s;
private Object lockRS = new Object ();
public void do1 ()
{
synchronize (lockXY) {
}
...
}
public void do2 ()
{
synchronize (lockRS) {
}
}
}
```
Beware to make locking to complex, you may run into dead locks |
59,449,692 | I have written the following code to simulate an unbiased random walk on Z^2. With probability 1/4, the "destination" is supposed to move one unit up, left, right, or down. So I made "destination" a matrix with two columns, one for the x-coordinate and one for the y-coordinate, and increment/decrement the appropriate coordinate as according to the value of `runif(1)`.
```
N_trials <- 10
N_steps <- 10
destination <- matrix(0,N_trials,2)
for(n in 1:N_steps) {
p <- runif(1)
if(p < 1/4) {
destination[n,1] <- destination[n,1] - 1
}
else if(p < 1/2) {
destination[n,1] <- destination[n,1] + 1
}
else if(p < 3/4) {
destination[n,2] <- destination[n,2] + 1
}
else if(p < 1) {
destination[n,2] <- destination[n,2] - 1
}
}
```
However, the process never seems to move out of the set {(0,0),(1,0),(-1,0),(0,1),(0,-1)}. Why is this? Is there an error in the logic of my code? | 2019/12/23 | [
"https://Stackoverflow.com/questions/59449692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3457277/"
] | Use a dictionary instead of having 2 separate list for ids and names of includes
The code below creates a dictionary with include id as keys and the corresponding include's name as the value. later this dict is used to print file name
In case you want to save each include as separate file,First isolate the include using "Or"(API) then we have an API for each deck in ANSA to do save files(make sure to enable optional argument 'save visible').for example for NASTRAN it is OutputNastran you can search it in the API search tab in the script editor window
```
dict={}
for include in includes:
ret=base.GetEntityCardValues(deck, include, 'NAME', 'ID')
ids=str(ret['ID'])
setname=ret['NAME']
if setname.endswith('.dat'):
dict[ids]=setname
for k, v in dict.items():
test=base.GetEntity(deck,'INCLUDE',int(k))
file_path_name=directory+"/"+v
print(file_path_name)
```
Hope this helps | Assuming ids is actually just the elements in hugo:
```
a=[id for id in hugo]
print(a)
```
Or
```
a=hugo.copy()
print(a)
```
Or
```
print(hugo)
```
Or
```
a=hugo
print(a)
```
Or
```
string = "["
for elem in hugo:
string.append(elem + ",")
print(string[:-1] + "]")
```
Edit: Added more amazing answers. The last is my personal favourite.
Edit 2:
Answer for your edited question:
This part
```
for a in ishow:
test=base.GetEntity(deck,'INCLUDE',int(a))
print(a)
file_path_name=directory+"/"+iname
print(file_path_name)
```
Needs to be changed to
```
for i in range(len(ishow)):
test=base.GetEntity(deck,'INCLUDE',int(ishow[i]))
file_path_name=directory+"/"+iname[i]
```
The print statements can be left if you wish.
When you are trying to refer to the same index in multiple lists, it is better to use `for i in range(len(a))`so that you can access the same index in both. |
6,179,617 | I happened to fail to set character encoding in Python terminal on Windows. According to official guide, it's a piece of cake:
```
# -*- coding: utf-8 -*-
```
Ok, now testing:
```
print 'Русский'
```
Produces piece of mojibake. What am doing wrong?
**P.S.** IDE is Visual Studio 2010, if it matters | 2011/05/30 | [
"https://Stackoverflow.com/questions/6179617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/476756/"
] | Update: See [J.F. Sebastian's answer](https://stackoverflow.com/a/29352343/252687) for a better explanation and a better solution.
`# -*- coding: utf-8 -*-` sets the source file's encoding, not the output encoding.
You have to encode the string just before printing it with the exact same encoding that your terminal is using. In your case, I'm guessing that your code page is Cyrillic (cp866). Therefore,
```
print 'Русский'.encode("cp866")
``` | In case anyone else gets this page when searching
easiest is to set the windows terminal code page
```
CHCP 65001
```
or for power shell start it with
```
powershell.exe -NoExit /c "chcp.com 65001"
```
from [Is there a Windows command shell that will display Unicode characters?](https://stackoverflow.com/questions/379240/is-there-a-windows-command-shell-that-will-display-unicode-characters?lq=1) |
4,889,336 | I am decoding a base64string I need to show the decoded contents in a window.
But when i print that i am getting only the bytearrayObject and not the data.
How to get the data?
```
private function copyByteArray(content:String):void{
try{
byteData = new ByteArray();
//byteData.writeUTFBytes(contents);
var dec:Base64Decoder = new Base64Decoder();
dec.decode(content);
byteData.writeBytes(dec.toByteArray());
Alert.show("byte Array " + byteData+" :: " +contents.length + "::");
}
catch (ex: ErrorEvent){
Alert.show("error");
}
```
} | 2011/02/03 | [
"https://Stackoverflow.com/questions/4889336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/358435/"
] | I tried it and got a string in Alert, not byteArray object. By the way, you should use a variable of class Error (or inherited classes), not any Events. | Try something like this:
```
var bytes:ByteArray = new ByteArray();
var bDecoder : Base64Decoder = new Base64Decoder();
bDecoder.decode(urlModifiedString);
bytes = bDecoder.toByteArray() ;
bytes.position = 0;
var returnObj : * = bytes.readObject();
```
---
after posting i just saw someone else's readUTFBytes... if you want to serialize and deserialize any type of object... roll with the above. |
29,674,656 | Hi I have child ul and parent li which is being targeted by jquery which toggles class "shown" on click event within it. The problem I face is that for some reason when I click child ul li elements it also triggers that event. How to prevent that?
Here is my code.
```
<script>
$(document).ready(function() {
$('.dropdown').click(function(e) {
e.stopPropagation();
$(this).toggleClass('shown');
e.preventDefault();
})
})
</script>
<li class="dropdown"><a title="Installation" href="#">Installation <span class="caret"></span></a>
<ul role="menu" class="dropdown-menu">
<li>
<a title="Wood Floor Installation" href="">Wood Floor Installation</a></li>
<li>
<a title="Sub Floor Preparation" href="">Sub Floor Preparation</a></li>
<li>
<a title="Type of your subfloor" href="">Type of your subfloor</a></li>
<li>
<a title="Wood Floor Fitting Method" href="">Wood Floor Fitting Method</a>
</li>
</ul>
</li>
``` | 2015/04/16 | [
"https://Stackoverflow.com/questions/29674656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4061068/"
] | What you're experiencing is called [event bubbling](http://javascript.info/tutorial/bubbling-and-capturing). Events triggered on elements deeper in the hierarchy will "bubble" up towards the root of the DOM tree, hence the parent `<li>` element receives click events instantiated by the child elements.
The easiest way to fix this is to check which element triggered the original event by checking `event.target`:
```
<script>
jQuery(document).ready(function($) {
$('.dropdown').click(function(e) {
if (!$(e.target).is('.dropdown-toggle'))
return;
$(this).toggleClass('shown');
e.preventDefault();
})
})
</script>
<li class="dropdown"><a title="Installation" href="#" data-toggle="dropdown" class="dropdown-toggle">Installation <span class="caret"></span></a>
<ul role="menu" class=" dropdown-menu">
<li>
<a title="Wood Floor Installation" href="">Wood Floor Installation</a></li>
<li>
<a title="Sub Floor Preparation" href="">Sub Floor Preparation</a></li>
<li>
<a title="Type of your subfloor" href="">Type of your subfloor</a></li>
<li>
<a title="Wood Floor Fitting Method" href="">Wood Floor Fitting Method</a>
</li>
</ul>
</li>
``` | Try [stopImmediatePropagation()](http://api.jquery.com/event.stopimmediatepropagation/) like this:
```
$(document).on('click', '#child_element', function(event) {
event.stopImmediatePropagation();
})
``` |
8,320,993 | What happens if I annotate a constructor parameter using `@JsonProperty` but the Json doesn't specify that property. What value does the constructor get?
How do I differentiate between a property having a null value versus a property that is not present in the JSON? | 2011/11/30 | [
"https://Stackoverflow.com/questions/8320993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14731/"
] | Summarizing excellent answers by [Programmer Bruce](https://stackoverflow.com/a/8321074/14731) and [StaxMan](https://stackoverflow.com/a/8321255/14731):
1. Missing properties referenced by the constructor are assigned a default value [as defined by Java](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html).
2. You can use setter methods to differentiate between properties that are implicitly or explicitly set. Setter methods are only invoked for properties with explicit values. Setter methods can keep track of whether a property was explicitly set using a boolean flag (e.g. `isValueSet`). | In addition to constructor behavior explained in @Programmer\_Bruce's answer, one way to differentiate between null value and missing value is to define a setter: setter is only called with explicit null value.
Custom setter can then set a private boolean flag ("isValueSet" or whatever) if you want to keep track of values set.
Setters have precedence over fields, in case both field and setter exist, so you can "override" behavior this way as well. |
25,463,744 | I'm tearing my hair out over this one. I'm trying to pass an image URL from my `TableViewController` to my `DetailViewController` (`FullArticleViewController`) so that I can set the `UIImageView`, and nothing I try seems to be working. See my code below:
**`MyTableViewController.h`**
```
@interface MyTableViewController : UIViewController <UISearchBarDelegate>{
IBOutlet UITableView *DoctorsTableView;
NSArray *Doctors;
NSMutableData *data;
NSArray *searchResults;
}
@property (strong, nonatomic) NSString *cellImageLink;
@property (strong, nonatomic) UINavigationBar *navigationBar;
```
**`MyTableViewController.m`**
```
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *DoctorsTableIdentifier = @"DoctorsCell";
DoctorsCell *cell = (DoctorsCell *)[tableView dequeueReusableCellWithIdentifier:DoctorsTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"DoctorsCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
if (tableView == self.searchDisplayController.searchResultsTableView) {
NSLog(@"Using the search results");
cell.firstnameLabel.text = [[searchResults objectAtIndex:indexPath.row] objectForKey:@"node_title"];
cell.descriptionLabel.text = [[searchResults objectAtIndex:indexPath.row] objectForKey:@"Opening Paragraph"];
NSString *firstLink = [[NSString alloc] init];
firstLink = [[[searchResults objectAtIndex:indexPath.row] objectForKey:@"Image"] objectForKey:@"filename"];
NSString *secondLink = [[NSString alloc] init];
secondLink = [NSString stringWithFormat:@"URL HERE%@",firstLink];
NSLog(@"second link is %@", secondLink);
cellImageLink = secondLink;
[cell.featureImage sd_setImageWithURL:[NSURL URLWithString:secondLink]];
} else {
NSLog(@"Using the Full List!");
cell.firstnameLabel.text = [[Doctors objectAtIndex:indexPath.row] objectForKey:@"node_title"];
cell.descriptionLabel.text = [[Doctors objectAtIndex:indexPath.row] objectForKey:@"Opening Paragraph"];
NSString *firstLink = [[NSString alloc] init];
firstLink = [[[Doctors objectAtIndex:indexPath.row] objectForKey:@"Image"] objectForKey:@"filename"];
NSString *secondLink = [[NSString alloc] init];
secondLink = [NSString stringWithFormat:@"URL HERE%@",firstLink];
NSLog(@"second link is %@", secondLink);
cellImageLink = secondLink;
[cell.featureImage sd_setImageWithURL:[NSURL URLWithString:secondLink]];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
FullArticleViewController *detailViewController = [[FullArticleViewController alloc]
initWithNibName:@"FullArticleViewController" bundle:nil];
if ([searchResults count]) {
detailViewController.title = [[searchResults objectAtIndex:indexPath.row] objectForKey:@"node_title"];
detailViewController.articleDetail = [searchResults objectAtIndex:indexPath.row];
} else {
detailViewController.title = [[Doctors objectAtIndex:indexPath.row] objectForKey:@"node_title"];
detailViewController.articleDetail = [Doctors objectAtIndex:indexPath.row];
NSLog(@"%@", Doctors);
}
FullArticleViewController *viewController = [[FullArticleViewController alloc]
initWithNibName:@"DetailViewController"
bundle:nil];
viewController.featureImage = searchResults[indexPath.row][@"Image"][@"filename"];
[self.navigationController pushViewController:detailViewController animated:YES];
}
```
**FullArticleViewController.h** (detailview)
```
@interface FullArticleViewController : UIViewController
{
IBOutlet UIScrollView *scroller;
IBOutlet UILabel *firstnameLabel;
IBOutlet UILabel *descriptionLabel;
IBOutlet UILabel *bodyLabel;
}
@property (nonatomic, copy) NSDictionary *articleDetail;
@property (strong, nonatomic) IBOutlet UIImageView *featureImage;
-(IBAction)goBack:(id)sender;
```
**FullArticleViewController.m** (detailview)
```
#import "SDWebImage/UIImageView+WebCache.h"
#import "FullArticleViewController.h"
#import "DoctorsCell.h"
#import "MyTableViewController.h"
@interface FullArticleViewController ()
@end
@implementation FullArticleViewController
@synthesize articleDetail;
@synthesize featureImage;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
featureImage = [[UIImageView alloc] init];
[scroller setScrollEnabled:YES];
[scroller setContentSize:CGSizeMake(320, 5000)];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
firstnameLabel.text = [articleDetail objectForKey:@"node_title"];
descriptionLabel.text = [articleDetail objectForKey:@"Opening Paragraph"];
bodyLabel.text = [articleDetail objectForKey:@"Body"];
}
``` | 2014/08/23 | [
"https://Stackoverflow.com/questions/25463744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3030060/"
] | If you check the types:
```
>>> type(df.groupby('Date').groups)
<class 'dict'>
```
therefore, as a dictionary, `df.groupby('Date').groups` does not provide any *order guarantee* when you access items or keys; in your example `grouped.groups.keys()`; So you will lose consistency and correspondence between `dates` and `avg` when you pull them out of `groupby` separately.
If you want to work with `datetime` objects and simple numpy arrays (as opposed to the pandas series), you may do as below, in order to have the orders consistent:
```
>>> ts = df.groupby('Date')['Score'].mean()
>>> avg, dates = ts.values, ts.index.map(pd.Timestamp.date)
```
so you will have:
```
>>> avg
array([-0.0825, 0.1125, 0.175 , -0.0625, -0.1325, 0.0375])
>>> dates
array([datetime.date(2014, 8, 15), datetime.date(2014, 8, 16), datetime.date(2014, 8, 17), datetime.date(2014, 8, 18),
datetime.date(2014, 8, 19), datetime.date(2014, 8, 20)], dtype=object)
```
Note that [`groupby`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html#pandas.DataFrame.groupby) has a default parameter `sort=True`, so the output is already sorted by index:
```
>>> df.groupby('Date')['Score'].mean()
Date
2014-08-15 -0.082
2014-08-16 0.112
2014-08-17 0.175
2014-08-18 -0.062
2014-08-19 -0.133
2014-08-20 0.038
Name: Score, dtype: float64
``` | The `avg` series will have the timestamps in the right order as the index, and can be passed directly to the bokeh plotting functions, like this.
```
line(avg.index, avg, line_color="grey", line_width=8, line_join="round")
asterisk(avg.index, avg, line_color="black", size=15)
``` |
78,713 | I'm confused by my books treatment of the Schrödinger equation. In steado f listing my questions at the end of my post, I'll add them as questions in parentheses after the line in question.
For a free particle:
$$i \hbar \left| \dot{\Psi} \right \rangle = H\left| \Psi \right \rangle = \frac{P^2}{2m}\left| \Psi \right \rangle$$ (where did the potential go?)
The normal mode solutions are of the form: $\left| \Psi \right \rangle = \left| E \right \rangle e^{-iEt/ \hbar}$
Feeding this into the equation above (the schrödinger equation written above), we get the time-independent equation for $\left| E \right \rangle$ :
$$H \left| E \right \rangle = \frac{P^2}{2m}\left| E \right \rangle = E \left| E \right \rangle$$
(this follows from the eigen-equation, where the eigenvalue must be equal to $E$?)
This problem can be solved without going into any basis. First note that any eigenstateof $P$ is also an eigenstate of $P^2$. So we feed the trial solution for $\left| p \right \rangle$ into the equation (the equation directly above).
$$\frac{P^2}{2m}\left| p \right \rangle = E\left| p \right \rangle $$
(why are we all of a sudden talking about the ket $p$?
Which means that $\left| p \right \rangle = \pm \sqrt{2mE}$
This gives us two eigenkets of $E$, which span an eigenspace.
The next steps are to set up the propagator (which I have questions about, but understanding the previous steps may help me clear them up myself). | 2013/09/27 | [
"https://physics.stackexchange.com/questions/78713",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/23094/"
] | >
> (where did the potential go?)
>
>
>
A potential implies a force and a *free* particle is not under the influence of a force (else it wouldn't be *free from force*).
>
> this follows from the eigen-equation, where the eigenvalue must be
> equal to E?
>
>
>
It is not uncommon, *when the context is appropriate*, to denote a state by its eigenvalue, e.g. the context is states of definite energy.
>
> (why are we all of a sudden talking about the ket p?)
>
>
>
Because, *for a free particle*, the Hamiltonian and momentum operators *commute*, i.e., states of definite energy are also states of definite momentum. Thus, *in this context*, an eigenstate can carry the energy eigenvalue label or the momentum eigenvalue label. | To answer your question: I assume your book is talking about the free particle and not the more general problem. The free particle itself (eg wavepackets spreading, or just simple time evolution of free partiles initial condition) is an interesting problem in itself. In this case, the potential is constant---and we can pick any constant, so V=0 works best and makes the reading and typesetting easiest and best to look at.
I also wanted to point out an error later in the post
>
> $ \left| p \right \rangle = \pm \sqrt{2mE} $
>
>
>
This is not true, what you probably mean to say, is that the P operator has the effect of scaling any "eigen vector of P\_op" or eigenstate |p> by $\pm \sqrt{2mE}$ |
34,440,333 | I want to share the following class between at least two wpf windows:
```
namespace WPF
{
class dd_internals
{
public int current_process_index;
public class process_class
{
public string process_name;
public List<string> parm_list;
public List<string> var_list;
public List<string> statements;
}
public List<process_class> process_list = new List<process_class>();
}
}
```
How would I share a single instance of this class between multiple windows?
Ok code showing `dd_internals` being passed into the constructor of `window1`, but not usable directly in a member function of `window1`.
```
namespace posting2
{
public partial class Window1 : Window
{
public void Member()
{
int y = Data.current_process_index;
// Error: the name 'Data' does not exist in the current context
}
public Window1(dd_internals data)
{
int x = data.current_process_index;
// ok, it works here.
InitializeComponent();
}
}
}
``` | 2015/12/23 | [
"https://Stackoverflow.com/questions/34440333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | There are several options, for example:
1. As I can guess one window can open another window, so you can just pass an instance of this object to the second window before opening it.
2. You can store it in Application.Properties
Application.Current.Properties["Key"] = myobject;
3. The best option for bigger application is to use some dependency container (there are many implementations of it) and store shared object in such a container
4. I really don't like the singleton pattern because it is not actually a pattern, but you can use it too. | I think you would need to make the class public or internal before sharing it anywhere. |
64,809,597 | I'm trying to compute the combined potential between the first and and last `SuperHero` instance of the `_superHeroes` array, and display the result. I created a method in the `SuperHero` class that computed the combined potential between two instances of a class. When I try to perform this method I get the following error:
```
TestSuperHero.java:20: error: cannot find symbol
double n = _superHeroes.combinedPotential(_superHeroes[0], _superHeroes[2]);
^
symbol: method combinedPotential(SuperHero,SuperHero)
location: variable _superHeroes of type SuperHero[]
1 error
```
I would deeply appreciate some help! Thank you!
```
import java.util.*;
public class TestSuperHero
{
public static void main(String[] args)
{
//Welcome Message
System.out.println("***** Welcome to the SuperHero Program ******\n");
//Define Array of Three SuperHeros
SuperHero [] _superHeroes = new SuperHero[3];
//Initialize SuperHero Elements
_superHeroes[0] = new SuperHero ("Poodle", 1000);
_superHeroes[1] = new SuperHero ("HangNail", 200);
_superHeroes[2] = new SuperHero ("WetSlipper", 50);
//Create a Double Variable that will compute combinedPotential on
//_superHeroes[0] and _superHeroes[2]
double n = _superHeroes.combinedPotential(_superHeroes[0], _superHeroes[2]);
}
class SuperHero
{
//Private Data Members
private String _name;
private double _kineticForce;
//Constructor
public SuperHero(String name, double kineticForce)
{
_name = name;
_kineticForce = kineticForce;
}
/* Methods */
//getName Accessor
public String getName()
{
return _name;
}
//getKineticForce Accessor
public double getKineticForce()
{
return _kineticForce;
}
//setKineticForce Mutator
public void setKineticForce(double kineticForce)
{
_kineticForce = kineticForce;
}
public double damagePotential()
{
final double PI = 3.14159;
double damagePotential = ((7.0/3.0) * PI) * (Math.pow(getKineticForce() / 2 , 5));
return damagePotential;
}
public double combinedPotential(SuperHero superHeroOne, SuperHero superHeroTwo)
{
double combinedPotential;
double numerator = Math.pow(3 * superHeroOne.getKineticForce(), 2)
- Math.pow(3 * superHeroTwo.getKineticForce(), 2);
double denominator = superHeroOne.getKineticForce() - superHeroTwo.getKineticForce();
combinedPotential = numerator / denominator;
return combinedPotential;
}
public String toString()
{
String superHero = "Name of SuperHero: " + getName();
String kineticForce = "Kinetic Force of " + getName() + ": " + getKineticForce();
return superHero + "\n" + kineticForce;
}
}
``` | 2020/11/12 | [
"https://Stackoverflow.com/questions/64809597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13295595/"
] | To understand the problem: `_superHeroes` is an array of `SuperHero` and you are trying to call a method of that class on the array. But the array does not inherrit the methods of the class. Instead you need to call the method on an instance that is stored inside of the array.
```
_superHeroes[0].combinedPotential(_superHeroes[0], _superHeroes[2]);
```
Better solution: As the method is not using any fields of the class for calculations, you can also declare the method `static` and call the static method without the need for an instance:
```
public static double combinedPotential(SuperHero superHeroOne, SuperHero superHeroTwo) {
...
}
...
SuperHero.combinedPotential(_superHeroes[0], _superHeroes[2]);
``` | This should be a `static` method:
```
public static double combinedPotential(...) { ... }
```
which you then call as
```
SuperHero.combinedPotential(_superHeroes[0], _superHeroes[2]);
``` |
8,836,276 | Hy,
I have this jquery code , what it does is saving in database (through ajax) the position of div in a database ,
but i don`t know how to get the id of div dragged , on the drop event
```
$().ready(function () {
$('.dragDiv').Drags({
handler: '.handler',
onMove: function (e) {
//$('.content').html('Div Position:(Left:' + e.pageX + ' ,Top:' + e.pageY + ')');
//$('.content').html(done);
},
onDrop: function (e) {
//$('.content').html('dropped!' + e.pageX);
$.ajax({
url: 'includes/scripts/data.php',
data: "top=" + e.pageX + "&left=" + e.pageY + ""
});
}
});
$('.dragDiv2').Drags({
handler: '.handler2',
zIndex: 200,
opacity: .9
});
});
``` | 2012/01/12 | [
"https://Stackoverflow.com/questions/8836276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1069937/"
] | Use this:
```
$('.dragDiv').attr("id");
```
---
**EDIT**
If you would like to try this, you can try getting the id in the onDrag function using:
```
var id = $(this).attr('id');
```
Verify that this is the correct id for the div, and if it is, this would be the recommended methodology.
---
**EDIT**
Good point 'Shadow Wizard'
```
var id = this.id;
```
---
**EDIT**
If all the previous methods have failed, use the jQuery event target:
```
var $target = $(e.target);
var id = null;
if($target.hasClass('dragDiv')) {
id = $target[0].id;
} else {
id = $target.parents('.dragDiv').first()[0].id;
}
```
This should go into your `onDrag` method. | I think you can just use the "this" keyword to get the object that is being dragged.
So that would mean you could write `$(this).attr("id")` |
650,555 | I have been a VB.net developer for a long time and changed recently to C#.
When I was using VB.net, to call user settings, I just need to create a new setting using the designer and then call it from code with the My namespace.
Here's the code
`My.settings.anysetting`
I can change or get data from it.
However in C# the My keyword doesn't work, so what can I do to call settings?? | 2009/03/16 | [
"https://Stackoverflow.com/questions/650555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12637/"
] | `Settings` are stored under the `Application` folder and as such, use that as their namespace.
```
int myInt = Properties.Settings.Default.myVariable;
Properties.Settings.Default.myVariable = 12;
Properties.Settings.Default.Save();
```
[Using Settings in C#](http://msdn.microsoft.com/en-us/library/aa730869.aspx) | ```
// Retrieving connection string from Web.config.
String connStringMSQL = WebConfigurationManager.ConnectionStrings["andi_msql"].ToString();
```
In my case this was for my connectionStrings setting but depending on what node your setting is in you can change this accordingly.
Hope this helps |
1,897,181 | When showing a secondary form from the main form and from the second form showing a third form and then closing both forms will cause the main form to lose focus.
Using Delphi 2009 with XP SP3
Here are my steps for reproducing the problem:
1. Create a new VCL forms applications
2. Drag a button onto the created form
3. In the click handler create a new TForm1 and show it
Run the program. Click the button to show a second form. Click the button on the second form to create a third form. When closing both new forms the main form will lose its focus.
This is my code in the button click event handler:
```
// Using Self does not change the results
with TForm1.Create(nil) do
show;
```
Is there any way to stop my main form from losing focus? | 2009/12/13 | [
"https://Stackoverflow.com/questions/1897181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40007/"
] | I don't see how what you describe creates a "child" Form.
But anyway, I just tried with exactly what you described in your steps and could not reproduce it in D2009 (updates 3 & 4), whether I create the 2nd "child" from the main Form or from the 1st "child", and whatever the order in which I close them.
So, there must be something else you did not tell... | Try the following (and avoid the with):
```
with TForm1.Create(nil) do begin
show;
activate;
bringtofront;
end;
``` |
781,357 | I think my Webapplication gets shut down after a while.
It returns a new session if I haven't used the application in maybe 5 minutes. The session timeout is set to 720 minutes so that can't be the issue.
Is it maybe a setting in the Application Pool or something like that? I figure it is some sort of resource management. I use IIS 7.0 | 2009/04/23 | [
"https://Stackoverflow.com/questions/781357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/70283/"
] | IIS has a feature in properties where you can stop recycle your IIS on intervals
1. Go to your "IIS Manager"
2. Select "Application Pool" the instance you want to manage.
3. Select "Advanced settings" action
4. Under "Recycling" and set "Regular Time Interval" to 0, which means the application pool does not recycle. | After failed at configuring IIS pool. I come out with this simple windows service.
[github code](https://github.com/ChinhPLQ/Windows-Service)
It can save some minutes of you. |
98,455 | I am writing a science fiction novel where dead humans are turned into diamonds by compacting cremated remains. What size of diamond would the amount of carbon in a human body form? I know that the size would vary somewhat depending on the weight of the person.
Specifically, would the diamond be small enough to be worn as an earring, or able to be worn as a necklace? Or would it be too large to practically be worn at all and be set as decoration? | 2017/11/21 | [
"https://worldbuilding.stackexchange.com/questions/98455",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/44959/"
] | Prior Art
=========
First it's worth noting that there is at least one company that actually does this. LifeGem creates diamonds from carbon extracted from cremated remains.
Per wikipedia:
>
> The company can extract enough purified carbon from a single cremated human body to synthesize up to 50 gems weighing one carat (200 mg) each, or up to 100 diamonds of smaller size, while sending remaining ashes to the family.
>
>
>
This is about ten grams of gem. I think that's too heavy for an earring, but I don't wear earrings. It probably wouldn't hurt in a necklace.
Is this the limit?
==================
The question literally asks
>
> What size of diamond would the amount of carbon in a human body form?
>
>
>
According to [wikipedia](https://en.wikipedia.org/wiki/Composition_of_the_human_body) the human body is about 18% carbon by mass. This means that a 70 kilo person contains about 12.6 kilos of carbon.
If we made a diamond from *all* the carbon in a human body, we'd have a 12.6 kilo gem which is frankly a bit excessive. This is 63000 carats, and would be a record-size diamond. I don't think anyone would wear that.
However, cremation removes a significant portion of this carbon (as carbon dioxide gas). Wikipedia [states](https://en.wikipedia.org/wiki/Cremation#Ash_weight_and_composition) that a typical cremation leaves 1.8-2.7 kilograms of ash, mostly calcium salts from the bones.
From that same article:
>
> Cremated remains are mostly dry calcium phosphates with some minor minerals, such as salts of sodium and potassium. Sulfur and most carbon are driven off as oxidized gases during the process, although a relatively small amount of carbon may remain as carbonate.
>
>
>
I assume that's why LifeGem doesn't produce 12 kilo monster gems. | According to [wikipedia](https://en.wikipedia.org/wiki/Composition_of_the_human_body), humans are 18% carbon by mass.
So a 70 kg human is made up of roughly 16 kg carbon.
The density of a [diamond](https://en.wikipedia.org/wiki/Diamond) is roughly 3.5 g/cm^3
Assuming a lossless process where every atom of carbon is used in the resulting diamond this would result with a 4500 cm^3 diamond.
In the real world nothing is a lossless conversion. [Memorial diamonds](https://en.wikipedia.org/wiki/Memorial_diamond) are being created by either using the cremated remains, or carbonized hair as the carbon source to create a lab grown diamond. |
15,472,814 | I have problem with .lib files not found. I would like to check linker properties. However, in Project->Properties, I cannot find linker tab. What am i missing here ? Actually, I fear that I am not looking at project properties, but at properties for solution or whatever. What is a project exactly (which icon in VS for instance), or where can I look at project properties ?
Thanks !! | 2013/03/18 | [
"https://Stackoverflow.com/questions/15472814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | If there is no linker options, it is possible that the project is set to build a \*.lib.
In this case you will be able to select 'Librarian' on the left of the project options. You can modify what the project is configured to build by going to General and then changing the Configuration type.
To get to the Project properties, right click on the project in the solution explorer window and click on properties. | For clarification of the concept of "Projects" in Visual Studio:
The topmost node you see in the Solution Explorer (The panel which is (I believe) by default on the left of your window) is called the **Solution**. You can imagine it as a big bag to put everything related to solving a problem into.
This "everything" I'm talking about is put together using **Projects**. A project is essentially a bunch of code that is to be compiled into one distinct output file (a DLL/LIB, an application).
For instance, if you yourself were to write a library, you would create a solution encompassing all of it. Into the solution, you'd put the code of your library's components in separate projects. For testing, you'd add even more projects, each building an executable that is linking to your libraries.
For example:
```
---- MyLibrary (Solution)
|
+--- MyLibraryMath (Project)
|
+--- MyLibraryNetwork (Project)
|
+--- TestMath (Project, linking to MyLibraryMath)
|
+--- TestNetwork (Project, linking to MyLybraryNetwork)
``` |
8,675,206 | Is there any difference between `:key => "value"` (hashrocket) and `key: "value"` (Ruby 1.9) notations?
If not, then I would like to use `key: "value"` notation. Is there a gem that helps me to convert from `:x =>` to `x:` notations? | 2011/12/30 | [
"https://Stackoverflow.com/questions/8675206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/927667/"
] | Yes, there is a difference. These are legal:
```
h = { :$in => array }
h = { :'a.b' => 'c' }
h[:s] = 42
```
but these are not:
```
h = { $in: array }
h = { 'a.b': 'c' } # but this is okay in Ruby2.2+
h[s:] = 42
```
You can also use anything as a key with `=>` so you can do this:
```
h = { C.new => 11 }
h = { 23 => 'pancakes house?' }
```
but you can't do this:
```
h = { C.new: 11 }
h = { 23: 'pancakes house?' }
```
The JavaScript style (`key: value`) is only useful if all of your Hash keys are "simple" symbols (more or less something that matches `/\A[a-z_]\w*\z/i`, AFAIK the parser uses its label pattern for these keys).
The `:$in` style symbols show up a fair bit when using MongoDB so you'll end up mixing Hash styles if you use MongoDB. And, if you ever work with specific keys of Hashes (`h[:k]`) rather than just whole hashes (`h = { ... }`), you'll still have to use the colon-first style for symbols; you'll also have to use the leading-colon style for symbols that you use outside of Hashes. I prefer to be consistent so I don't bother with the JavaScript style at all.
Some of the problems with the JavaScript-style have been fixed in Ruby 2.2. You can now use quotes if you have symbols that aren't valid labels, for example:
```
h = { 'where is': 'pancakes house?', '$set': { a: 11 } }
```
But you still need the hashrocket if your keys are not symbols. | Ruby hash-keys assigned by hash-rockets can facilitate strings for key-value pairs (*e.g*. `'s' => x`) whereas key assignment via **symbols** (*e.g.* `key: "value"` or `:key => "value"`) *cannot be assigned with strings.* Although hash-rockets provide freedom and functionality for hash-tables, *specifically allowing strings as keys*, application performance may be slower than if the hash-tables were to be constructed with symbols as hash-keys. The following resources may be able to clarify any differences between hashrockets and symbols:
* [Ryan Sobol's Symbols in Ruby](https://gist.github.com/ryansobol/9b0b6995a7ae806cd008)
* [Ruby Hashes Exaplained by Erik Trautman](http://www.eriktrautman.com/posts/ruby-explained-hashes) |
26,070,464 | I have created a new "Database" project in Visual Studio 2013. I have set the Target platform to "Windows Azure SQL Database". The project is nearly empty, with the exception of one .sql file to create a Schema.
When I try to publish the project, it takes several minutes and ends with:
Creating publish preview...
Failed to import target model [database\_name]. Detailed message Unable to reconnect to database: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
I have tested the connection string, and it works.
What do I need to do to publish to Azure? Thanks. | 2014/09/27 | [
"https://Stackoverflow.com/questions/26070464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2503327/"
] | Like Hesham mentioned in the comments, I also had this issue with the new Basic tier of Azure SQL Database. Switching the tier to Standard S0 size fixed the issue. So if you're having issues with the Basic tier, try scaling up to publish, then scale back down when you're finished. | Check this answer from MSDN forum, worked with me perfectly!
>
> In order to change the command timeouts used in Visual Studio 2013 you
> will need to change the following registry setting:
>
>
> HKEY\_CURRENT\_USER\Software\Microsoft\VisualStudio\12.0\SQLDB\Database\QueryTimeoutSeconds
>
>
>
Source:
<http://social.msdn.microsoft.com/Forums/sqlserver/en-US/7e869f10-529b-41af-b54f-709a420308f6/publish-database-to-a-new-basic-scale-db-from-vs2013-times-out?forum=ssdsgetstarted> |
49,169,802 | I need to create a string like this to make works the mapserver request:
`filterobj = "POLYGON((507343.9 182730.8, 507560.2 182725.19999999998, 507568.60000000003 182541.1, 507307.5 182563.5, 507343.9 182730.8))";`
Where the numbers are map coordinates `x` `y` of a polygon, the problem is with Javascript and OpenLayer what I have back is an array of numbers, How can I remove just the ODD commas (first, third, fifth...)?
At the moment I've created the string in this way:
```
filterobj = "POLYGON((" +
Dsource.getFeatures()[0].getGeometry().getCoordinates() + " ))";
```
And the result is:
`POLYGON((507343.9, 182730.8,507560.2, 182725.19999999998, 507568.60000000003, 182541.1, 507307.5, 182563.5,507343.9, 182730.8));`
It's almost what I need but, I need to remove the ODD commas from the `Dsource.getFeatures()[0].getGeometry().getCoordinates()` array to make the request work, how can I do that? | 2018/03/08 | [
"https://Stackoverflow.com/questions/49169802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6447610/"
] | Look at code snippet :
Help method : setCharAt ,
Take all commas ,
take all odds commas with i % 2 == 0
```js
// I need to start from somewhere
function setCharAt(str,index,chr) {
if(index > str.length-1) return str;
return str.substr(0,index) + chr + str.substr(index+1);
}
var POLYGON = [507343.9, 182730.8,507560.2, 182725.19999999998, 507568.60000000003, 182541.1, 507307.5, 182563.5,507343.9, 182730.8];
var REZ = "";
REZ = POLYGON.toString();
var all_comma = [];
for(var i=0; i<REZ.length;i++) {
if (REZ[i] === ",") all_comma.push(i);
}
for(var i=0; i<all_comma.length;i++) {
if (i % 2 == 0 ) {
REZ = setCharAt(REZ,all_comma[i],' ');
}
}
console.log(REZ);
// let return nee element intro POLYGON
// reset
POLYGON = REZ.split(',');
console.log(POLYGON);
``` | One approach would be using `Array.reduce()`:
```
var input = '1.0, 2.0, 3.0, 4.0, 5.0, 6.0';
var output = input
.split(',')
.reduce((arr, num, idx) => {
arr.push(idx % 2 ? arr.pop() + ' ' + num : num);
return arr;
}, [])
.join(',');
// output = '1.0 2.0, 3.0 4.0, 5.0 6.0'
``` |
15,552,581 | I'm currently developing an OpenGL framework for video games. This framework contains a specific program that loads shaders. In the class of said program I have these three functions:
```
InitShaderProgram(...);
CreateShader(...);
CreateProgram(...);
```
The InitShaderProgram calls CreateShader and CreateProgram in such way:
```
bool ShaderLoader::InitShaderProgram(GLuint &Program)
{
std::vector<GLuint> ShaderList;
ShaderList.push_back(ShaderLoader::CreateShader(GL_VERTEX_SHADER, VertexShader));
ShaderList.push_back(ShaderLoader::CreateShader(GL_FRAGMENT_SHADER, FragmentShader));
Program = ShaderLoader::CreateProgram(ShaderList);
std::for_each(ShaderList.begin(), ShaderList.end(), glDeleteShader);
return GL_TRUE;
}
```
However, whenever I try to compile this code, it gives me two "unresolved external symbol" errors:
```
Error 4 error LNK2019: unresolved external symbol "public: virtual unsigned int __thiscall ShaderLoader::CreateProgram(class std::vector<unsigned int,class std::allocator<unsigned int> > const &)" (?CreateProgram@ShaderLoader@@UAEIABV?$vector@IV?$allocator@I@std@@@std@@@Z) referenced in function "public: bool __thiscall ShaderLoader::InitShaderProgram(unsigned int &)" (?InitShaderProgram@ShaderLoader@@QAE_NAAI@Z)
Error 3 error LNK2019: unresolved external symbol "public: virtual unsigned int __thiscall ShaderLoader::CreateShader(unsigned int,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)" (?CreateShader@ShaderLoader@@UAEIIABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) referenced in function "public: bool __thiscall ShaderLoader::InitShaderProgram(unsigned int &)" (?InitShaderProgram@ShaderLoader@@QAE_NAAI@Z)
```
In my header file, I define these three functions as such:
```
bool InitShaderProgram(GLuint&);
GLuint CreateShader(GLenum, const std::string&);
GLuint CreateProgram(const std::vector<GLuint>&);
```
If I get this right (I most likely don't), the compiler does not understand where these functions come from. Can anyone help me out here? | 2013/03/21 | [
"https://Stackoverflow.com/questions/15552581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1849415/"
] | Unresolved External Symbol means the compiler has looked at the code you have written and has generated all code in the source file you are compiling and a set of symbols it needs for the linker to look up. The linker takes all of the object code files and maps all of the defined symbols from one [translation unit](http://en.wikipedia.org/wiki/Translation_unit_%28programming%29) (think source file and its headers) to all of the symbols. When it can't find a implemented symbol it emits an Unresolved External Symbol.
In general this is because you have failed to include the library object file in the linkers list of object files. The other likly cause if you have declared a function and not defined it.
Emits an undefined Symbol
main.cpp
```
int foo();
int main(int argc, char ** argv)
{
return foo();
}
```
This will complain because I have not defined foo. | >
> If I get this right (I most likely don't), the compiler does not understand where these functions come from.
>
>
>
Unfortunally no. The error is not from compiler but from linker.
Do you have already implemented this two functions: ShaderLoader::CreateShader and ShaderLoader::CreateProgram? Or just declarated in a header? How do you link? |
1,450,623 | I am using VB.net code and SQL server 2005.
I am havng below code for sending email in my vb.net code.
```
Protected Sub ibtnSendInvites_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ibtnSendInvites.Click
Try
Dim emailList As New List(Of String)
For Each curRow As GridViewRow In GridView1.Rows
Dim chkSelect As CheckBox = CType(curRow.Cells(1).FindControl("chkSelect"), CheckBox)
Dim emailLabel As Label = CType(curRow.Cells(1).FindControl("lblEmailAddress"), Label)
If chkSelect.Checked Then
emailList.Add(emailLabel.Text)
End If
Next
For Each email As String In emailList
Dim SelectDelegateMessage As String = "Please confirm your booking for this course"
Dim SelectDelegateSubject As String = "User-Point Course Booking Invitation Email"
Dim SelectDelegateFrom As String = WebConfigurationManager.AppSettings("UserPointEmailFromAddress").ToString()
SendEmail.SendMessage(SelectDelegateSubject, SelectDelegateMessage, SelectDelegateFrom, email, "")
Next
GridView1.DataBind()
Catch ex As Exception
'Throw New Exception("Cannot Insert Duplicate Record", ex)
End Try
End Sub
```
Now my problem is that some time if emailaddress is not valid or SMTP server is responding my application get hangs. I want to log my errors generated by my SMTP server in table or any log file it would be good if I can send back email to admin with the details of error occured.
Please suggest!
Thanks.
Best Regards,
MS | 2009/09/20 | [
"https://Stackoverflow.com/questions/1450623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30394/"
] | There's no one answer. Depends on the business situation. I do agile/XP development, and get the software in a stable and usable state as early as possible.
I encourage our clients to get it out there to start getting feedback. This is great, as it always affects how you view the software you are building. And it definitely makes sense if you have the ability to digest the feedback and react to it.
But there are marketing situations where you need to hold back. It's naive to think that there's only one way to release software in the modern world. There are risks inherent in releasing early, as you have to be careful to set expectations carefully with your audience, and you simply may not have the ability or inclination to do so. It may be easier to stick with more traditional release cycles.
I still believe strongly in early releases, even if they are password protected. They reduce project risk and stress. We know there are no hidden problems with releasing to production, since we've been doing it since day one. And it also helps keep developers out of the hot-seat, since we always have something up and running. Demos and PR moments aren't as stressful as they are just a regular part of the process.
So from a software development standpoint I recommend it. From a marketing standpoint... well this is SO and we shouldn't get into that here. :-> | **No Software is ever fully-functional.**
Use cases evolve as users come along and find new and interesting uses for your product.
You'd be far better off designing the site to be easy to update and with minimal downtime during update then trying to guess who your users will be and how they will use it. |
6,031,468 | Can I use preg\_match to validate phone number in jQuery? Here is my code which does not work:
```
if (!preg_match("/^[0-9]{3}-|\s[0-9]{3}-|\s[0-9]{4}$/", phone.val() )) {
phone.addClass("needsfilled");
phone.val(phonerror);
}
```
HTML
`<input id="phone" type="text" value="" name="phone" />` | 2011/05/17 | [
"https://Stackoverflow.com/questions/6031468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/756928/"
] | Javascript includes a regular expression engine, which is accessed via the `string.match()`, `string.replace()` and `string.split()` functions.
For example:
```
var mystring = "this is a sentence";
mystring = mystring.replace(/sentence/,'string');
var matches = mystring.match(/\b\w+\b/);
```
That should provide you with essentially the same functionality as `preg_match()`.
So to do the same validation as the preg\_match in your question:
```
if(!phone.val().match(/^[0-9]{3}-|\s[0-9]{3}-|\s[0-9]{4}$/)) {
phone.addClass("needsfilled");
phone.val(phonerror);
}
```
If you absolutely insist on having a function called `preg_match()` which works exactly like the PHP version, there is a project called [PHPJS](http://phpjs.org/), which aims to implement PHP functions in Javascript. A quick look at their site shows that although they don't currently have a fully working `preg_match()` implementation, they have an [unfinished implementation](https://github.com/kvz/phpjs/blob/master/_workbench/pcre/preg_match.js) which you may want to look at. But frankly, the built-in Javascript `.match()` function should be more than sufficient. | Instead of using `preg_match`, which is a PHP function, you should use the String object's `match` function. See the [Mozilla docs](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/match) for information on using the match function. |
448,271 | What is [`__init__.py`](https://docs.python.org/3/tutorial/modules.html#packages) for in a Python source directory? | 2009/01/15 | [
"https://Stackoverflow.com/questions/448271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42974/"
] | `__init__.py` will treat the directory it is in as a loadable module.
For people who prefer reading code, I put [Two-Bit Alchemist's](https://stackoverflow.com/users/2588818/two-bit-alchemist) comment here.
```
$ find /tmp/mydir/
/tmp/mydir/
/tmp/mydir//spam
/tmp/mydir//spam/__init__.py
/tmp/mydir//spam/module.py
$ cd ~
$ python
>>> import sys
>>> sys.path.insert(0, '/tmp/mydir')
>>> from spam import module
>>> module.myfun(3)
9
>>> exit()
$
$ rm /tmp/mydir/spam/__init__.py*
$
$ python
>>> import sys
>>> sys.path.insert(0, '/tmp/mydir')
>>> from spam import module
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named spam
>>>
``` | One thing \_\_init\_\_.py allows is converting a module to a package without breaking the API or creating extraneous nested namespaces or private modules\*. This helps when I want to extend a namespace.
If I have a file util.py containing
```
def foo():
...
```
then users will access `foo` with
```
from util import foo
```
If I then want to add utility functions for database interaction, and I want them to have their own namespace under `util`, I'll need a new directory\*\*, and to keep API compatibility (so that `from util import foo` still works), I'll call it util/. I *could* move util.py into util/ like so,
```none
util/
__init__.py
util.py
db.py
```
and in util/\_\_init\_\_.py do
```
from util import *
```
but this is redundant. Instead of having a util/util.py file, we can just put the util.py contents in \_\_init\_\_.py and the user can now
```
from util import foo
from util.db import check_schema
```
I think this nicely highlights how a `util` package's \_\_init\_\_.py acts in a similar way to a `util` module
\* this is hinted at in the other answers, but I want to highlight it here
\*\* short of employing import gymnastics. Note it won't work to create a new package with the same name as the file, see [this](https://stackoverflow.com/q/6393861/5986907) |
19,324,397 | What's the difference between the declaring an uninitialized final variable and setting a final variable to null?
```
void A(String pizza) {
String retVal = null;
if (StringUtils.isBlank(pizza)) {
retVal = "blank"
} else {
retVal = computeString(pizza);
}
}
void A(String pizza) {
final String retVal;
if(StringUtils.isBlank(pizza)) {
retVal = "blank"
} else {
retVal = computeString(pizza);
}
}
``` | 2013/10/11 | [
"https://Stackoverflow.com/questions/19324397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/973391/"
] | Maybe I didn't understand, but in your second example, you won't be able to reassign `retVal` after your `if-else` block. [A `final` variable](http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.4)
>
> may only be assigned to once. Declaring a variable final can serve as
> useful documentation that its value will not change and can help avoid
> programming errors.
>
>
>
If you had set your `final` variable to `null`, you would not be able to reassign it in the `if` block. | The difference is that a final variable can never be changed to have another value. |
39,686,844 | ```
select p.ProduitNom,v.VonduDate,p.ProduitPrix from Produits p,Vondus v
where p.ProduitId = v.ProduitId and p.CentreId=1
```
How to do this request in entity framework ? | 2016/09/25 | [
"https://Stackoverflow.com/questions/39686844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5296683/"
] | Yes, it's because Google has been blocked in Iran since 2012.
You can use a proxy app like Shadowsocks to change your country.
After activating your proxy app, in Android Studio go to
file->setting->Appearance & Behavior->System Setting->HTTP Proxy
active 'Manual proxy configuration'
and set:
* host name:127.0.0.1 (for example)
* port name:1080 (for example)
and reset Android Studio. When Android Studio resets, activate the HTTPS proxy and sync your Gradle and it will work. ;) | Put this info in your Android Studio **proxy settings**:
```
address: fodev.org
port:8118
```
Put these lines on **gradle.properties** file in your project:
```
systemProp.http.proxyHost=fodev.org
systemProp.http.proxyPort=8118
systemProp.https.proxyHost=fodev.org
systemProp.https.proxyPort=8118
```
[](https://i.stack.imgur.com/timjn.png)
For more information see this **repository**: <https://github.com/freedomofdevelopers/fod> |
15,055,073 | I have just downloaded and installed the new opencv version. The fact that it natively supports java is quite exiting. However I am having some trouble porting my javacv code over. I can no longer seem to use IplImage as it can not be resolved, even though I have imported org.opencv.core.\*; Switching to Mat does not seem ideal as many of the opencv functions that I use require an IplImage.
Example:
```
public static IplImage getAbsDifference (IplImage source1, IplImage source2){
IplImage result = cvCreateImage(new CvSize(source1.width(),source1.height()),source1.depth(),3);
cvAbsDiff(source1, source2, result);
return result;
}
```
So what kind of changes do I need to make to my old code for it to work with the new version of opencv for java?
Sorry if this is a noobish question, still new to the image processing field. | 2013/02/24 | [
"https://Stackoverflow.com/questions/15055073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2041427/"
] | First, some preliminaries:
Using `O_NONBLOCK` and `poll()` is common practice -- not the other way around. To work successfully, you need to be sure to handle all `poll()` and `read()` return states correctly:
* `read()` return value of `0` means EOF -- the other side has closed its connection. This corresponds (usually, but not on all OSes) to `poll()` returning a `POLLHUP` revent. You may want to check for `POLLHUP` before attempting `read()`, but it is not absolutely necessary since `read()` is guaranteed to return `0` after the writing side has closed.
* If you call `read()` before a writer has connected, and you have `O_RDONLY | O_NONBLOCK`, you will get EOF (`read()` returning `0`) repeatedly, as you've noticed. However, if you use `poll()` to wait for a `POLLIN` event before calling `read()`, it will wait for the writer to connect, and not produce the EOFs.
* `read()` return value `-1` usually means error. However, if `errno == EAGAIN`, this simply means there is no more data available right now and you're not blocking, so you can go back to `poll()` in case other devices need handling. If `errno == EINTR`, then `read()` was interrupted before reading any data, and you can either go back to `poll()` or simply call `read()` again immediately.
Now, for Linux:
* If you open on the reading side with `O_RDONLY`, then:
+ The `open()` will block until there is a corresponding writer open.
+ `poll()` will give a `POLLIN` revent when data is ready to be read, or EOF occurs.
+ `read()` will block until either the requested number of bytes is read, the connection is closed (returns 0), it is interrupted by a signal, or some fatal IO error occurs. This blocking sort of defeats the purpose of using `poll()`, which is why `poll()` almost always is used with `O_NONBLOCK`. You could use an `alarm()` to wake up out of `read()` after a timeout, but that's overly complicated.
+ If the writer closes, then the reader will receive a `poll()` `POLLHUP` revent and `read()` will return `0` indefinitely afterwards. At this point, the reader must close its filehandle and reopen it.
* If you open on the reading side with `O_RDONLY | O_NONBLOCK`, then:
+ The `open()` will not block.
+ `poll()` will give a `POLLIN` revent when data is ready to be read, or EOF occurs. `poll()` will also block until a writer is available, if none is present.
+ After all currently available data is read, `read()` will either return -1 and set `errno == EAGAIN` if the connection is still open, or it will return `0` if the connection is closed (EOF) *or not yet opened by a writer*. When `errno == EAGAIN`, this means it's time to return to `poll()`, since the connection is open but there is no more data. When `errno == EINTR`, `read()` has read no bytes yet and was interrupted by a signal, so it can be restarted.
+ If the writer closes, then the reader will receive a `poll()` `POLLHUP` revent, and `read()` will return `0` indefinitely afterwards. At this point the reader must close its filehandle and reopen it.
* (Linux-specific:) If you open on the reading side with `O_RDWR`, then:
+ The `open()` will not block.
+ `poll()` will give a `POLLIN` revent when data is ready to be read. However, for named pipes, EOF will not cause `POLLIN` or `POLLHUP` revents.
+ `read()` will block until the requested number of bytes is read, it is interrupted by a signal, or some other fatal IO error occurs. For named pipes, it will not return `errno == EAGAIN`, nor will it even return `0` on EOF. It will just sit there until the exact number of bytes requested is read, or until it receives a signal (in which case it will return the number of bytes read so far, or return -1 and set `errno == EINTR` if no bytes were read so far).
+ If the writer closes, the reader will not lose the ability to read the named pipe later if another writer opens the named pipe, but the reader will not receive any notification either.
* (Linux-specific:) If you open on the reading side with `O_RDWR | O_NONBLOCK`, then:
+ The `open()` will not block.
+ `poll()` will give a `POLLIN` revent when data is ready to be read. However, EOF will not cause `POLLIN` or `POLLHUP` revents on named pipes.
+ After all currently available data is read, `read()` will return `-1` and set `errno == EAGAIN`. This is the time to return to `poll()` to wait for more data, possibly from other streams.
+ If the writer closes, the reader will not lose the ability to read the named pipe later if another writer opens the named pipe. The connection is persistent.
As you are rightly concerned, using `O_RDWR` with pipes is not standard, POSIX or elsewhere.
However, since this question seems to come up often, the best way on Linux to make "resilient named pipes" which stay alive even when one side closes, and which don't cause `POLLHUP` revents or return `0` for `read()`, is to use `O_RDWR | O_NONBLOCK`.
I see three main ways of handling named pipes on Linux:
1. (Portable.) Without `poll()`, and with a single pipe:
* `open(pipe, O_RDONLY);`
* Main loop:
+ `read()` as much data as needed, possibly looping on `read()` calls.
- If `read() == -1` and `errno == EINTR`, `read()` all over again.
- If `read() == 0`, the connection is closed, and all data has been received.
2. (Portable.) With `poll()`, and with the expectation that pipes, even named ones, are only opened once, and that once they are closed, must be reopened by both reader and writer, setting up a new pipeline:
* `open(pipe, O_RDONLY | O_NONBLOCK);`
* Main loop:
+ `poll()` for `POLLIN` events, possibly on multiple pipes at once. (Note: This prevents `read()` from getting multiple EOFs before a writer has connected.)
+ `read()` as much data as needed, possibly looping on `read()` calls.
- If `read() == -1` and `errno == EAGAIN`, go back to `poll()` step.
- If `read() == -1` and `errno == EINTR`, `read()` all over again.
- If `read() == 0`, the connection is closed, and you must terminate, or close and reopen the pipe.
3. (Non-portable, Linux-specific.) With `poll()`, and with the expectation that named pipes never terminate, and may be connected and disconnected multiple times:
* `open(pipe, O_RDWR | O_NONBLOCK);`
* Main loop:
+ `poll()` for `POLLIN` events, possibly on multiple pipes at once.
+ `read()` as much data as needed, possibly looping on `read()` calls.
- If `read() == -1` and `errno == EAGAIN`, go back to `poll()` step.
- If `read() == -1` and `errno == EINTR`, `read()` all over again.
- If `read() == 0`, something is wrong -- it shouldn't happen with `O_RDWR` on named pipes, but only with `O_RDONLY` or unnamed pipes; it indicates a closed pipe which must be closed and re-opened. If you mix named and unnamed pipes in the same `poll()` event-handling loop, this case may still need to be handled. | Just keep an open O\_WRONLY file descriptor in the reading process alongside the O\_RDONLY one. This will achieve the same effect, ensuring that read() never returns end-of-file and that poll() and select() will block.
And it's 100% POSIX |
34,409,780 | ```
<tr id="Any_22" class="value-table list-row-even">
<td class="selection-column">
<input id="Checkbox_1_1" type="checkbox" onclick="doCheck( this, 'value-table-selected', 'value-table' )" name="Checkbox_1_1">
</td>
<td id="columnValues_19" class="first-selection" onmouseover="sCC(this)">
<span>
<table id="container_7" class="vo-label" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td class="skinImage">
<img border="0" src="/images/icons/small/pawn_glass_white.gif">
</td>
<td id="Any_23" class="remainder"> I_am_here </td>
</tr>
</tbody>
</table>
</span>
</td>
</tr>
```
How can I click the check box if I know only "I\_am\_Here" txt.
I have tried `//td[normalize-space(text())='192.168.9.2']`. But it doesn't worked for me. | 2015/12/22 | [
"https://Stackoverflow.com/questions/34409780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3622632/"
] | This is one possible XPath that works for the HTML snippet posted :
```
//tr[td[normalize-space()='I_am_here']]/td/input[@type='checkbox']
```
**`[`xpathtester demo`](http://www.xpathtester.com/xpath/e70ace1299a95ff28fd747baef57cab1)`**
**brief explanation :**
* `//tr[td[normalize-space()='I_am_here']]` : find `tr` where `td` child element has inner text equals `"I_am_here"`
* `/td` : from such `tr`, find child element `td`
* `/input[@type='checkbox']` : from such `td`, return `input` element where `type` attribute value equals `"checkbox"`
**output :**
```
<input id="Checkbox_1_1" name="Checkbox_1_1" onclick="doCheck( this, 'value-table-selected', 'value-table' )" type="checkbox"/>
``` | Because you didn't provide any code, the answer will be also conceptual.
So, you should get the nodes tree by known text (`I_am_Here`) and then find nearest node with name `input` and type `checkbox`.
The nodes tree can be obtained by traveling through `parents` and `siblings` of found node. |
17,305,437 | Im trying to get the following script to work, but Im having some issues:
```
g++ -g -c $1
DWARF=echo $1 | sed -e `s/(^.+)\.cpp$/\1/`
```
and Im getting -
```
./dcompile: line 3: test3.cpp: command not found
./dcompile: command substitution: line 3: syntax error near unexpected token `^.+'
./dcompile: command substitution: line 3: `s/(^.+)\.cpp$/\1/'
sed: option requires an argument -- 'e'
```
and then bunch of stuff on sed usage. What I want to do is pass in a cpp file and then extract the file name without the .cpp and put it into the variable DWARF. I would also like to later use the variable DWARF to do the following -
`readelf --debug-dump=info $DWARF+".o" > $DWARF+".txt"`
But Im not sure how to actually do on the fly string concats, so please help with both those issues. | 2013/06/25 | [
"https://Stackoverflow.com/questions/17305437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1305516/"
] | You actually need to execute the command:
```
DWARF=$(echo $1 | sed -e 's/(^.+)\.cpp$/\1/')
```
The error message is a shell error because your original statement
```
DWARF=echo $1 | sed -e `s/(^.+)\.cpp$/\1/`
```
is actually parsed like this
```
run s/(^.+)\.cpp$/\1/
set DWARF=echo
run the command $1 | ...
```
So when it says `test3.cpp: command not found` I assume that you are running with argument `test3.cpp` and it's literally trying to execute that file
You also need to wrap the sed script in single quotes, not backticks | You can use `awk` for this:
```
$ var="testing.cpp"
$ DWARF=$(awk -F. '{print $1}' <<< $var)
$ echo "$DWARF"
testing
``` |
37,977 | I have two lists, say `a` and `b`, both of length `n`. I'd like to compute the following:
* minimum of $a[i]/b[i]$ where $i=1, 2, ...n$ and $b[i]>0$
I'd also like to know the index of the element where the min occurs. | 2013/11/28 | [
"https://mathematica.stackexchange.com/questions/37977",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/10831/"
] | One way to enforce the positivity condition on `b` is to locate the positions of all the positive elements of `b` and use those to index into the division of `a` by `b`.
```
a = RandomReal[{-10, 10}, 10];
b = RandomReal[{-10, 10}, 10];
pos = Flatten[Position[b, _?(0 < # &)]]
Min[a[[pos]]/b[[pos]]]
``` | ```
a = RandomReal[{1, 10}, 10];
b = RandomReal[{1, 10}, 10];
lst = a/b;
Min[lst]
(*0.442821447015283*)
Position[lst, Min[lst]]
(* {{4}} *)
```
**Update to answer comment below**
`How can I implement the b[i]>0 condition`
One way can be to use [MapThread](http://reference.wolfram.com/mathematica/ref/MapThread.html) to make the list by checking for the condition
```
a = {2, 9, 5, 3, 0, 4, 9, 1};
b = {0, -4, 2, 0, 10, 4, 0, 10};
lst = MapThread[If[#2 > 0, #1/#2, Sequence @@ {}] &, {a, b}]
(*{5/2, 0, 1, 1/10}*)
Min[lst]
(* 0 *)
Position[lst, %]
{{2}}
```
**Updated to return position of min in original list not filtered list**
remember the index while filtering to use it to go back.
```
a = {2, 9, 5, 3, 0, 4, 9};
b = {0, -4, 2, 0, 10, 4, 0};
i = 0;
lst = MapThread[(i++; If[#2 > 0, {i, #1/#2}, Sequence @@ {}]) &, {a,b}]
(* {{3, 5/2}, {5, 0}, {6, 1}, {8, 1/10}} *)
min = Min[lst[[All, 2]]]
(* 0 *)
p = Flatten@Position[lst[[All, 2]], min];
lst[[p, 1]]
(* {5} *)
```
A short hand version is
```
i = 0;
p = Flatten@
Position[lst[[All,2]],Min@MapThread[(i++;If[#2>0,{i,#1/#2},Sequence@@{}])&,{a,b}][[All,2]]]
lst[[p, 1]]
``` |
407,987 | I'm interested in implementing a Forth system, just so I can get some experience building a simple VM and runtime.
When starting in Forth, one typically learns about the stack and its operators (DROP, DUP, SWAP, etc.) first, so it's natural to think of these as being among the primitive operators. But they're not. Each of them can be broken down into operators that directly manipulate memory and the stack pointers. Later one learns about store (!) and fetch (@) which can be used to implement DUP, SWAP, and so forth (ha!).
So what are the primitive operators? Which ones must be implemented directly in the runtime environment from which all others can be built? I'm not interested in high-performance; I want something that I (and others) can learn from. Operator optimization can come later.
(Yes, I'm aware that I can start with a Turing machine and go from there. That's a bit extreme.)
Edit:
What I'm aiming for is akin to bootstrapping an operating system or a new compiler. What do I need do implement, at minimum, so that I can construct the rest of the system out of those primitive building blocks? I won't implement this on bare hardware; as an educational exercise, I'd write my own minimal VM. | 2009/01/02 | [
"https://Stackoverflow.com/questions/407987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17312/"
] | This post at comp.lang.forth lists a few "minimal Forths".
<http://groups.google.com/group/comp.lang.forth/msg/10872cb68edcb526>
Why do I know this? My brother, Mikael, wrote #3 and he also wrote a [paper](http://libris.kb.se/bib/879246) about making a "minimal Forth" (in Swedish, though). If I remember correctly he wanted to get a minimal set of operators that could be built in silicon. | You might also want to take a look at Hans Bezemer's [4tH compiler](http://www.xs4all.nl/~thebeez/4tH/). |
2,910,587 | what is the difference between deleting a pointer, setting it to null, and freeing it.
```
delete ptr;
```
vs.
```
ptr=NULL;
```
vs.
```
free(ptr);
``` | 2010/05/26 | [
"https://Stackoverflow.com/questions/2910587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/350593/"
] | Your question suggests that you come from a language that has garbage collection. **C++ does not have garbage collection.**
If you set a pointer to NULL, this does not cause the memory to return to the pool of available memory. If no other pointers point to this block of memory, you now simply have an "orphaned" block of memory that remains allocated but is now unreachable -- a **leak**. Leaks only cause a program to crash if they build up to a point where no memory is left to allocate.
There's also the converse situation, where you `delete` a block of memory using a pointer, and later try to access that memory as though it was still allocated. This is possible because calling `delete` on a pointer does not set the pointer to NULL -- it still points to the address of memory that previously was allocated. A pointer to memory that is no longer allocated is called a **dangling pointer** and accessing it will usually cause strange program behaviour and crashes, since its contents are probably not what you expect -- that piece of memory may have since been reallocated for some other purpose.
**[EDIT]** As stinky472 mentions, another difference between `delete` and `free()` is that only the former calls the object's destructor. (Remember that you must call `delete` on an object allocated with `new`, and `free()` for memory allocated with `malloc()` -- they can't be mixed.) In C++, it's always best to use static allocation if possible, but if not, then prefer `new` to `malloc()`. | When you create an object using new, you need to use delete to release its memory back to the system. The memory will then be available for others to reuse.
```
int* a = new int;
delete a;
```
NULL is just a pre-defined macro that can be assigned a pointer to mean that it does not point to anything.
```
int* a = new int;
a = NULL;
```
In the above case, after allocating storage for a, you are assigning NULL to it. However, the memory previously allocated for a was not released and cannot be reused by the system. This is what we call memory leak. |
45,117,470 | I have following select drop-down which is dynamically created,which does not have select id but have name.
I have JavaScript array like
var t=[125,43,89].
I want to remove above array values from below drop-down.
```
<select name="UF_DEPT">
<option value="">no</option>
<option value="125"> . Volkswagen</option>
<option value="43" selected=""> . . AMC / INS / EW</option>
<option value="66"> . . CPU</option>
<option value="89"> . . New York Office</option>
<option value="107"> . . Paris Office</option>
</select>
``` | 2017/07/15 | [
"https://Stackoverflow.com/questions/45117470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7461933/"
] | ```js
var t = [125, 43, 89];
t.forEach(function(item) {
$("select[name='UF_DEPT'] option[value='" + item + "']").remove();
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="UF_DEPT">
<option value="">no</option>
<option value="125"> . Volkswagen</option>
<option value="43" selected=""> . . AMC / INS / EW</option>
<option value="66"> . . CPU</option>
<option value="89"> . . New York Office</option>
<option value="107"> . . Paris Office</option>
</select>
``` | ```
var child=$("select [name='UF-DEPT']").children();
foreach(child as sub-child){
if($.inArray(sub-child.val(),array){
subchild.remove();
}
}
``` |
4,675,241 | Using [Joda Time's pattern syntax](http://www.joda.org/joda-time/apidocs/org/joda/time/format/DateTimeFormat.html) below, this input string:
```
Sunday, January 09, 2011 6:15:00 PM
```
becomes this datetime:
```
2011-01-09T06:15:00.000Z
```
Code:
```
String start = "Sunday, January 09, 2011 6:15:00 PM";
DateTimeFormatter parser1 =
DateTimeFormat.forPattern("EEEE, MMMM dd, yyyy H:mm:ss aa");
DateTime startTime = parser1.parseDateTime(start);
```
Is this format pattern incorrect? If not, what are the `T` and `Z` doing inside the DateTime output?
```
2011-01-09T06:15:00.000Z
``` | 2011/01/12 | [
"https://Stackoverflow.com/questions/4675241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/559894/"
] | You've only shown the *parsing* code - not how you've converted the `DateTime` value back to a `String`.
I strongly suspect you're just calling `toString()`, which use the default `DateTime` ISO8601 format.
Don't forget that a `DateTime` value represents an instant in time in a particular time zone and calendar system - it has no concept of format patterns. The "T" and "Z" aren't in the `DateTime` value - they're just in the default *representation* of the value. It's like when you convert an `int` to a string - it happens to use decimal, but the number itself is just a number.
If you want to format a `DateTime` in a specific way, you should use
```
String text = formatter.print(startTime);
``` | T: Denotes start of "time part" of the string.
Zone: 'Z' outputs offset. I suppose in thise case is GMT.
Source:<http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html>
I always use this format string: `yyyy-MM-dd'T'HH:mm:ss.SSSZ`
And, yes, they are not incorrect, if they are present in your string. |
120,894 | <https://stackoverflow.com/questions/9086369/how-does-a-browser-render-a-page-using-the-dom-model-constructed-from-html>
One of the comments is that it is not programming related.
Possible answers to the question in question might be code snippets or links to a specific implementation i.e. IE and that wouldn't be off topic would it? | 2012/01/31 | [
"https://meta.stackexchange.com/questions/120894",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/177768/"
] | Hmm. No, I agree with the off-topic voters. This kind of behaviour is how a piece of software works in the general sense, which is more like [HowStuffWorks](http://www.howstuffworks.com/) (i.e. probably a question for [Super User](https://superuser.com/)). If you were asking how a specific part of the code *within* a browser works, then that sounds like a Stack Overflow question, because someone is running through code and explaining that, but top-level functionality is more of a power user question than a software developer's question. | This question falls foul of this paragraph of [What kind of questions should I *not* ask here?](https://stackoverflow.com/faq#dontask):
>
> Your questions should be reasonably scoped. If you can imagine an
> *entire book* that answers your question, you’re asking too much.
>
>
>
Given that there exist both the Dragon book ('create your own compiler from scratch') and [WebKit for Dummies](http://rads.stackoverflow.com/amzn/click/111812720X), it's surely possible to imagine a 'create your own browser from scratch' book. |
1,432 | I understand that in order to get a visa to visit Russia you need an invitation before you can get a visa.
If you don't have family or friends that you are visiting and you aren't part of an organised tour, how can you obtain an invitation? | 2011/08/05 | [
"https://travel.stackexchange.com/questions/1432",
"https://travel.stackexchange.com",
"https://travel.stackexchange.com/users/155/"
] | Well, everything is for sale. There are companies out there that will provide you with an official invitation for set prices. (try Google)
I've bought a (single entry) business invitation some years ago, and everything worked out fine. I've met several travellers (in Russia) who bought tourist visa invitations.
Some gotchas:
* The invitation will not be provided more than 45 days in advance.
* There are quite some options to choose from. Transit, Tourist and Business visa invitations are the more useful options for travellers.
* There are different visa durations for the Tourist and Business visa, some allow for multiple entries, some (the most common) are single entry only.
Make sure you leave the country one day ahead of the expiration date as to avoid trouble when, for example, your train is delayed. | Hotels can sponsor you if you spend the first nights with them. |
27,056,876 | I have initialized a JSON document in my code like this:
```
var json = [];
```
I use the '.push()' method to add elements to this document like this:
```
json.push({title: "abc", link: "xxx"});
```
In the end I get a JSON document that looks like this:
```
[
{
"title": "abc",
"link": "xxx"
}
{
"title": "asd",
"link": "zzz"
}
...
]
```
This is not entirely bad, but I wanted it to look like this:
```
{
"links":
[
{
"title": "abc",
"link": "xxx"
}
{
"title": "asd",
"link": "zzz"
}
...
]
}
```
Any ideas how I can make it so? | 2014/11/21 | [
"https://Stackoverflow.com/questions/27056876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2679979/"
] | By doing
```
var json = [];
```
You initialize an array, not an object.
To have an object you can do:
```
var json = {};
```
Then to add a field:
```
json.links = [];
```
then push to you links object:
```
json.links.push({title: "abc", link: "xxx"});
``` | ```
var json = {
links: []
};
json.links.push({title: "abc", link: "xxx"});
``` |
23,375,740 | When I attempt to run "rake test" on a local postgres database, it throws the above exception.
Here is my pg\_hba.conf file:
# Database administrative login by Unix domain socket
local all postgres peer
```
# TYPE DATABASE USER ADDRESS METHOD
# "local" is for Unix domain socket connections only
local all username peer
local myapp_dev myapp md5
local myapp_test myapp md5
local myapp_prod myapp md5
#local all all peer
# IPv4 local connections:
host all all 127.0.0.1/32 md5
# IPv6 local connections:
host all all ::1/128 md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
#local replication postgres peer
#host replication postgres 127.0.0.1/32 md5
#host replication postgres ::1/128 md5
```
and here is the relevant section from my database.yml
```
test:
adapter: postgresql
database: myapp_test
pool: 5
timeout: 5000
host: localhost
username: username
password:
```
In the real database.yml, 'username' is replaced with my actual user name that I am logged in as. Since the authentication method is defined as 'peer', no password should be required.
I have also taken care to restart Postgres
```
sudo -u postgres pg_ctlcluster 9.3 main restart
```
What else am I missing here? | 2014/04/29 | [
"https://Stackoverflow.com/questions/23375740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/270511/"
] | If your hb\_conf has already been modified to force passwords, then make sure your rails app's database configuration includes a password in both development and test environments.
```
default: &default
adapter: postgresql
encoding: unicode
pool: 5
host: localhost
username: your_user
password: your_password
development:
<<: *default
database: your_db_development
test:
<<: *default
database: your_db_test
production:
url: <%= ENV['DATABASE_URL'] %>
```
I was getting this error when I failed to supply a password for the test database. | **initialize dot environment in your project**
```
# dot gem
gem 'dotenv-rails', groups: [:development, :test]
```
than `bundle install`
and than make a .env file in your project and add the following line
```
POSTGRES_HOST=localhost
POSTGRES_USER= user_name
POSTGRES_PASSWORD= your_password
RAILS_MAX_THREADS=5
``` |
5,127,401 | I am a newbie in python programming, what I understand is that a process can be a daemon, but a thread in a daemon mode, I couldn't understand the usecase of this, I would request the python gurus to help me in understanding this. | 2011/02/26 | [
"https://Stackoverflow.com/questions/5127401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/571105/"
] | #### In simple words...
### What is a Daemon thread?
* **daemon threads** can *shut down any time* in between their flow ***whereas*** **non-daemon** (i.e. user threads) *execute completely*.
* **daemon threads** run *intermittently in the background* as long as other **non-daemon threads** are running.
* When all of the **non-daemon threads** are complete, **daemon threads** terminate automatically *(no matter whether they got fully executed or not)*.
* **daemon threads** are *service providers* for **user threads** running in the same process.
* *python does not care* about **daemon threads** to complete when in **running state**, NOT EVEN the finally block **but** python **does give** preference to **non-daemon threads** that are created by us.
* **daemon threads** act as services in operating systems.
* **python** stops the **daemon threads** when all **user threads** (in contrast to the **daemon threads**) are terminated. Hence **daemon threads** can be used to implement, for example, a monitoring functionality as the thread is stopped by the **python** as soon as all **user threads** have stopped.
### In a nutshell
If you do something like this
```
thread = Thread(target=worker_method, daemon=True)
```
there is ***NO guarantee*** that `worker_method` will get executed completely.
### Where does this behaviour be useful?
Consider two threads `t1` *(parent thread)* and `t2` *(child thread)*. Let `t2` be **daemon**. Now, you want to analyze the working of `t1` while it is in running state; you can write the code to do this in `t2`.
Reference:
* [StackOverflow - What is a daemon thread in Java?](https://stackoverflow.com/a/31603321/10204932)
* [GeeksForGeeks - Python daemon threads](https://www.geeksforgeeks.org/python-daemon-threads/)
* [TutotrialsPoint - Concurrency in Python - Threads](https://www.tutorialspoint.com/concurrency_in_python/concurrency_in_python_threads.htm)
* [Official Python Documentation](https://docs.python.org/3/library/threading.html#threading.Thread.daemon) | I've adapted @unutbu's answer for python 3. Make sure that you run this script from the command line and not some interactive environment like jupyter notebook.
```py
import queue
import threading
def basic_worker(q):
while True:
item = q.get()
# do_work(item)
print(item)
q.task_done()
def basic():
q = queue.Queue()
for item in range(4):
q.put(item)
for i in range(3):
t = threading.Thread(target=basic_worker,args=(q,))
t.daemon = True
t.start()
q.join() # block until all tasks are done
print('got here')
basic()
```
So when you comment out the daemon line, you'll notice that the program does not finish, you'll have to interrupt it manually.
Setting the threads to daemon threads makes sure that they are killed once they have finished.
Note: you could achieve the same thing here without daemon threads, if you would replace the infinite while loop with another condition:
```py
def basic_worker(q):
while not q.empty():
item = q.get()
# do_work(item)
print(item)
q.task_done()
``` |
69,465 | >
> How many different combinations of $X$ sweaters can we buy if we have
> $Y$ colors to choose from?
>
>
>
According to my teacher the right way to think about this problem is to think of partitioning $X$ identical objects (sweaters) into $Y$ different categories (colors).
Well,this idea however yields the right answer but I just couldn't convince my self about this way to thinking,to be precise I couldn't link the wording of the problem to this approach,could any body throw some more light on this? | 2011/10/03 | [
"https://math.stackexchange.com/questions/69465",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/2109/"
] | There are many general approaches. One of the simplest and best is Newton's Method, which you will find in any calculus text, or by searching the web.
By the way, I think your first formula should be $f(x)=(1/2)(x+(3/x))$, no? | The link below shows to some extent the rationale behind the formula you have provided as well as others - See in particular the "Babylonian method"
[Approximating square roots](http://en.wikipedia.org/wiki/Methods_of_computing_square_roots) |
54,625,221 | I want to extract a specific portion from a text file.
**example** -
```
PASSED: 1 GETFILE /root/test/misc/ptolemy/erase_flash.csv
PASSED: 4 MegaSCU -cfgclr -a0
PASSED: 8 MegaSCU -adphwdevice -read devicetype 5 bus 1 slaveaddr 82 start 0 sz 256 -f SK83100192.vpd -a0
PASSED: 28 VALUECHECK PACKAGE= 24.0.2-0013 in tty.log for 1 occurances!
```
From the above text I want to extract "GETFILE" , "MegaSCU", "VALUECHECK" as my output.
The file is huge and this texts are stored as column.
I am searching for any option which will help me to extract the word after "PASSED: X" in the text
Kindly help. | 2019/02/11 | [
"https://Stackoverflow.com/questions/54625221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9447298/"
] | ```
class Test
end
obj = Test.new
```
Here are some ways to create the hash, other than
```
class << obj
def greet
...
end
end
```
and (as mentioned in another answer)
```
def obj.greet
...
end
```
**#1**
```
obj.singleton_class.class_eval do
def greet1
'Welcome'
end
end
obj.greet1 #=> "Welcome"
```
**#2**
```
obj.singleton_class.class_eval "def greet2
'Get lost'
end"
obj.greet2 #=> "Get lost"
```
This form can be useful when creating singleton methods dynamically.
**#3**
```
obj.singleton_class.instance_eval do
define_method(:greet3) { 'yo' }
end
obj.greet3 #=> "yo"
```
**#4**
```
obj.singleton_class.
public_send(:define_method, :greet4) { 'yo-yo' }
obj.greet4 #=> "yo-yo"
```
**#5**
```
obj.define_singleton_method(:greet5) { 'yo who?' }
obj.greet5 #=> "ho who?"
```
**#6**
```
module M
def greet6
'hi ya'
end
end
obj.extend M
obj.greet6 #=> "hi ya"
```
**#7**
```
module M
def greet7
'hi you'
end
end
obj.singleton_class.include M
obj.greet7 #=> "hi you"
```
```
obj.methods(false)
#=> [:greet3, :greet4, :greet1, :greet2, :greet5]
obj.methods.grep /greet/
#=> [:greet3, :greet4, :greet1, :greet2, :greet5,
# :greet6, :greet7]
```
The practical use of creating singleton methods is obvious for modules (including classes), but calls for an opinion as it concerns other objects. | As per @mu\_is\_too\_short comment, another way is,
```
class Test; end
obj1 = Test.new
def obj1.pancakes
p 'Where is pancakes house?'
end
obj1.pancakes # "Where is pancakes house?"
obj2 = Test.new
obj2.pancakes
Traceback (most recent call last) :
NoMethodError
(undefined method `pancakes' for #<Test:0x0000564fb35ca310>)
``` |
66,212,883 | every time I try to display my data out of my MySQL database on a `html` page it will only show the first column of the record or only the name of the column itself.
For example:
MyDatabase
db
```
id names
1 Harry
2 Snape
```
main.py
```
@app.route("/db", methodes = ["POST", "GET"])
def db():
if request.method == "POST":
cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cur.execute("SELECT names FROM db WHERE id = 1")
output = cur.fetchone()
cur. close
return render_template("db.html", data = output)
else:
return render_template("db.html")
```
db.html
```
{% extends "base.html" %}
{% block title %}db{% endblock %}
{% block content %}
<form method="POST">
<input type="submit" value="show data">
</form>
<!-- Output 1 -->
<p>{{data}}</p>
<!-- Output 2 -->
{% for i in data %}
<p>{{i}}</p>
{% endfor %}
<!-- Output 3 -->
{% for i in data %}
<p>{{i[0]}}</p>
{% endfor %}
{% endblock %}
```
Output 1 = {'names': 'Harry'}
Output 2 = names
Output 3 = n
I just want to get the records, not the column name, how can I do this (*Output = Harry*)
I am new to all this, I would be happy about a short explanation :) | 2021/02/15 | [
"https://Stackoverflow.com/questions/66212883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13472449/"
] | you can search for Dictionary in Python .
here is some changes in your db.html code :
```
{% extends "base.html" %}
{% block title %}db{% endblock %}
{% block content %}
<form method="POST">
<input type="submit" value="show data">
</form>
<!-- Output 1 -->
<p>{{data['names']}}</p>
<!-- Output 2 -->
{% for key, value in data.items() %}
<p>{{value}}</p>
{% endfor %}
{% endblock %}
``` | This fixed it for me
db.html
```
<p>{{data.names}}</p>
```
main.py
```
else:
return render_template("db.html", data = "")
```
This is to avoid getting the error that "data" is undefined when restarting the server. |
40,574,177 | Is there a way that I for example use my website called `www.mywebsite.com` and in address bar to show `www.wikipedia.com`?
And of course to load my contents from `mywebsite.com`? | 2016/11/13 | [
"https://Stackoverflow.com/questions/40574177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7152893/"
] | In my case it was a file not found, I typed the path to the javascript file incorrectly. | After searching for a while I realized that this error in my Windows 10 64 bits was related to JavaScript. In order to see this go to your browser DevTools and confirm that first. In my case it shows an error like "MIME type ('application/javascript') is not executable".
If that is the case I've found a solution. Here's the deal:
1. Borrowing user "ilango100" on <https://github.com/jupyterlab/jupyterlab/issues/6098>:
>
> I had the exact same issue a while ago. I think this issue is specific to Windows. It is due to the wrong MIME type being set in Windows registry for javascript files. I solved the issue by editing the Windows registry with correct content type:
>
>
>
>
> regedit -> HKEY\_LOCAL\_MACHINE\Software\Classes -> You will see lot of folders for each file extension -> Just scroll down to ".js" registry and select it -> On the right, if the "Content Type" value is other than application/javascript, then this is causing the problem. Right click on Content Type and change the value to application/javascript
>
>
>
>
> [enter image description here](https://i.stack.imgur.com/WNWKa.jpg)
>
>
>
>
> Try again in the browser."
>
>
>
After that I've realized that the error changes. It doesn't even open automatically in the browser anymore. PGAdmin, however, will be open on the side bar (close to the calendar/clock). By trying to open in the browser directly ("New PGAdmin 4 window...") it doesn't work either.
FINAL SOLUTION: click on "Copy server URL" and paste it on your browser. It worked for me!
EDIT: Copying server URL might not be necessary, as explained by Eric Mutta in the comment below. |
35,843,696 | I am trying to set the x and y limits on a subplot but am having difficultly. I suspect that the difficultly stems from my fundamental lack of understanding of how figures and subplots work. I have read these two questions:
[question 1](https://stackoverflow.com/questions/3777861/setting-y-axis-limit-in-matplotlib)
[question 2](https://stackoverflow.com/questions/15858192/how-to-set-xlim-and-ylim-for-a-subplot-in-matplotlib)
I tried to use that approach, but neither had any effect on the x and y limits. Here's my code:
```
fig = plt.figure(figsize=(9,6))
ax = plt.subplot(111)
ax.hist(sub_dict['b'], bins=30, color='r', alpha=0.3)
ax.set_ylim=([0,200])
ax.set_xlim=([0,100])
plt.xlabel('x')
plt.ylabel('y')
plt.title('title')
plt.show()
```
I am confused as whether to apply commands to fig or ax? For instance .xlabel and .title don't seem to be available for ax. Thanks | 2016/03/07 | [
"https://Stackoverflow.com/questions/35843696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5255941/"
] | You probably misunderstood the comment. It means that
```
for my $t (qw( housecats house )) {
my ($m) = $t =~ /house(cat|)/;
print "[$m]\n";
}
```
will print
```
[cat]
[]
```
i.e. the regex will match both `housecat` and `house`. If the pattern didn't match at all then `$m` would be `undef` | ```
my $t = "housecats";
my ($m) = $t=~m/house(cat|)/gn;
print $m;
``` |
14,525 | How do you target a radio telescope on the precise object you wish to observe? You can point it in the general direction but how do you get the information from the exact point in the sky that you are investigating?
This seems self evident with an optical telescope but not with a radio telescope. | 2016/04/13 | [
"https://astronomy.stackexchange.com/questions/14525",
"https://astronomy.stackexchange.com",
"https://astronomy.stackexchange.com/users/11542/"
] | Large radio telescope have pretty good pointing accuracy:
* the individual dishes of the [VLA are accurate](https://science.nrao.edu/facilities/vla/docs/manuals/oss/performance/sensitivity) to about 10 arcsec.
* the giant [Lovell telescope](http://www.jodrellbank.net/visit/whats-here/lovell-telescope/) at Jodrell Bank has a similar accuracy.
The second critical parameter is the [beam width](http://www.cv.nrao.edu/course/astr534/Interferometers1.html). Beam width depends highly on frequency:
beamwidth = wave length/dish diameter
When you use several dishes in an interferometer, you can increase their effective accuracy and [decrease their collective beam width](https://science.nrao.edu/facilities/vla/docs/manuals/oss/performance/resolution).
A bit more info on the mechanics of the Lovell telescope:
>
> A control computer calculates the required drive rates to follow each radio source. The drive motors are servo-controlled, so there is a continuous check that the correct rate has been achieved. The position of the telescope is constantly monitored and fed back to control computer to ensure that the telescope is pointing correctly.
>
>
> For good tracking the pointing accuracy should be about a twentieth of the resolution. Since the resolution is proportional to the wavelength being received (see below), it follows that the pointing accuracy is more critical at shorter wavelengths. The control computer is able to correct for pointing errors caused by the telescope bowl sagging under its own weight as it moves up and down. In this way the pointing errors can be kept to about 10 arcsec.
>
>
>
So, [servo motors](https://en.wikipedia.org/wiki/Ward_Leonard_control) and presumably, calibration are what enables this accuracy.
The Lovell telescope has 2 elevation drive motors with gearboxes on each side of the dish. These can be driven so that one motor pulls the dish, and the dish drags along the second motor. This eliminates gear backlash in the system: the two gear trains are "wound up" in opposite directions. This means they can make adjustments without gear backlash interfering. (source: a video presentation that runs in the visitor center at Jodrell Bank)
Further reading: [the story of Jodrell Bank](https://archive.org/stream/TheStoryOfJodrellBank/Piper-theStoryOfJodrellBank_djvu.txt), and a [Radio Electronics article](http://www.rfcafe.com/references/radio-electronics/jodrell-bank-radio-telescope-february-1958-radio-electronics.htm). | This is a complicated question with a number of good answers already posted. It's complicated since there are (broadly) two kinds of radio telescopes -- single dishes and interferometers -- and (even more broadly) two kinds of observation -- imaging, and spectroscopy/photometry.
The most important thing to remember is that to a good first approximation "all" you need to do is get the source in the telescope's beam and avoid any conflicting sources. As @Hobbes noted, the beamwidth (in radians) is the wavelength/dish diameter. (Specifically, it's 1.2\*wavelength/diameter -- see [Wikipedia](https://en.wikipedia.org/wiki/Angular_resolution).) Even for big dishes this can be large: multiple degrees, though it gets down into the arc minute range for higher radio frequencies.
Individual dishes are steered by moving something: usually the dish, but in the case of one like Arecibo, by moving the feed horn. There's no real need to steer more accurately than a fraction -- a quarter, say -- of the beam width.
Even a big dish like Green Bank's isn't used much for imaging (its images would have a resolution of many arc minutes at best), but to measure the source's time variation at a variety of wavelengths. And for this it just needs the source to be somewhere near the center of the beam.
So, for this kind of telescope, you need pointing accuracy ranging from several degrees down to maybe ten arc minutes. Somewhere in the system, there's a gearbox and motors which drive the dish, and there are indicators which show position. Once this is calibrated -- probably by making accurate measurements of the dish's actual position as a function of the gearbox readings -- this accuracy of pointing can be done by driving the dish to the desired position.
If you are doing interferometry, things are much more complicated! The VLA works in centimeter wavelengths with 25-meter dishes, so the beam width of an individual dish is about a minute of arc. Aiming an individual dish is done in the same way as any other individual dish, though the mechanisms are typically more precise.
But the resolution of an array like the VLA is *much* better than the resolution of the individual dishes. (The [Wikipedia article](https://en.wikipedia.org/wiki/Astronomical_interferometer) on the subject is mediocre, but tracing down some of its references will help a lot.) Basically, a single very large dish is constructed mathematically by combining together the signals received at each individual dish (both intensity and time) and the *precise* location of each dish (but not so much where each was pointed!).
The ultra-precise pointing that's possible from an interferometer comes from the mathematical processing of the data, not from the mechanics of the pointing of the individual dishes. (In fact, there are a number of useful interferometers -- [LOFAR](https://en.wikipedia.org/wiki/LOFAR) in the Netherlands is a good example -- which don't point at all,, but basically are comprised of omnidirectional antennas.)
Bottom line: Individual dishes point using mechanics; Interferometric arrays point using mathematics. |
3,782,217 | I am using c# on a windows mobile 6.1 device. compact framework 3.5.
I am getting a OutofMemoryException when loading in a large string of XML.
The handset has limited memory, but should be more than enough to handle the size of the xml string. The string of xml contains the base64 contents of a 2 MB file. The code will work when the xml string contains files of up to 1.8 MB.
I am completely puzzled as to what to do. Not sure how to change any memory settings.
I have included a condensed copy of the code below. Any help is appreciated.
```
Stream newStream = myRequest.GetRequestStream();
// Send the data.
newStream.Write(data, 0, data.Length);
//close the write stream
newStream.Close();
// Get the response.
HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse();
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
//Process the return
//Set the buffer
byte[] server_response_buffer = new byte[8192];
int response_count = -1;
string tempString = null;
StringBuilder response_sb = new StringBuilder();
//Loop through the stream until it is all written
do
{
// Read content into a buffer
response_count = dataStream.Read(server_response_buffer, 0, server_response_buffer.Length);
// Translate from bytes to ASCII text
tempString = Encoding.ASCII.GetString(server_response_buffer, 0, response_count);
// Write content to a file from buffer
response_sb.Append(tempString);
}
while (response_count != 0);
responseFromServer = response_sb.ToString();
// Cleanup the streams and the response.
dataStream.Close();
response.Close();
}
catch {
MessageBox.Show("There was an error with the communication.");
comm_error = true;
}
if(comm_error == false){
//Load the xml file into an XML object
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(responseFromServer);
}
```
The error occurs on the xdoc.LoadXML line. I have tried writing the stream to a file and then loading the file directly into the xmldocument but it was no better.
Completely stumped at this point. | 2010/09/23 | [
"https://Stackoverflow.com/questions/3782217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/961042/"
] | I would recommend that you use the XmlTextReader class instead of the XmlDocument class. I am not sure what your requirements are for reading of the xml, but XmlDocument is very memory intensive as it creates numerous objects and attempts to load the entire xml string. The XmlTextReader class on the other hand simply scans through the xml as you read from it.
Assuming you have the string, this means you would do something like the following
```
String xml = "<someXml />";
using(StringReader textReader = new StringReader(xml)) {
using(XmlTextReader xmlReader = new XmlTextReader(textReader)) {
xmlReader.MoveToContent();
xmlReader.Read();
// the reader is now pointed at the first element in the document...
}
}
``` | I'm unsure why you are reading the xml in the way you are, but it could be very memory inefficient. If the garbage collector hasn't kicked in you could have 3+ copies of the document in memory: in the string builder, in the string and in the XmlDocument.
Much better to do something like:
```
XmlDocument xDoc = new XmlDocument();
Stream dataStream;
try {
dataStream = response.GetResponseStream();
xDoc.Load(dataStream);
} catch {
MessageBox.Show("There was an error with the communication.");
} finally {
if(dataStream != null)
dataStream.Dispose();
}
``` |
48,509,134 | If I created an entity with this JSON with `options=keyValues`:
```
{
"id": "waterqualityobserved:Sevilla:D3",
"type": "WaterQualityObserved",
"location": "41.3763726, 2.186447514"
}
```
Then request: `localhost:1026/v2/entities/waterqualityobserved:Sevilla:D3`
```
{
"id": "waterqualityobserved:Sevilla:D3",
"type": "WaterQualityObserved",
"location": {
"type": "Text",
"value": "41.3763726, 2.186447514",
"metadata": {}
}
}
```
Orion is able to execute geographical queries?
How else to define the location property? | 2018/01/29 | [
"https://Stackoverflow.com/questions/48509134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8539530/"
] | I had been experiencing this issue on emulated devices running 7.0 and 8.0 and consistently the location callback was not being triggered when the screen was off (cmd+P). I was finally able to get my hands on a real 7.0 device (Galaxy S7) and I was not able to replicate the issue. Sorry if I wasted anyone's time, apparently it is an emulator issue. | one solution might be this :
check if location is not received in 2 minutes stop/start whole start location update again . although foreground service must have solve the problem |
772 | The website I'm working on has different sections and each section different types of entries. I would like the types of entries to be shown in the URL. I have followed [this tutorial to do so](http://buildwithcraft.com/help/entry-type-urls).
In a site example.com where we have:
* A Section called: My Section
* With Entry Types: Example Entry Type, Another Entry type.
Utilizing the model from the tutorial, we could structure the URL for *My Section* as follows:
/my-section/{type}/{slug}
Which would give us URLs like these:
* example.com/my-section/**exampleEntryType**/new-entry-1
* example.com/my-section/**exampleEntryType**/new-entry-2
* example.com/my-section/**anotherEntryType**/new-entry-3
* example.com/my-section/**anotherEntryType**/new-entry-4
Notice that the **entry types** are the only part of the URL camelCased. This is because Entry Types can only be configured to have a Name, and a Handle; and handles can NOT have dashes. This interferes with keeping URLs consistent as the rest of the site uses dashes instead of spaces
The problem I am trying to solve is: how do we get the Entry Types to stay consistent with the rest of the site?
Does anyone have any suggestion on how to deal with this? Is this a problem that should be addressed in Craft? Should I be taking another approach for this?
I had considered using categories but the way the system is setup, entry types seem more appropriate. | 2014/07/06 | [
"https://craftcms.stackexchange.com/questions/772",
"https://craftcms.stackexchange.com",
"https://craftcms.stackexchange.com/users/47/"
] | You could just set your "Entry URL Format" to:
```
my-section/{type.name}/{slug}
```
Your entry type names couldn't be as clean when composing entries in the CP as you'd need to set them to something like "example-entry-type", but it would work.
---
Now for the really clean way:
Install the [Low Regex for Craft](https://github.com/low/low_regex/) plugin.
Set "Entry URL Format" to:
```
my-section/{type.handle|regex('/(^|[a-z])([A-Z])/e', 'strtolower(strlen("\\1") ? "\\1-\\2" : "\\2")',(type.handle))}/{slug}
```
This will convert the entry type handle from camelCase to all lowercase with dashes as word delimiters. Set the entry type handles to be like "exampleEntryType" and they will become "example-entry-type" when in a slug. | You can use twig filters in url structures as mentioned by RhealPoirier in a comment above, no need for a plugin:
```
my-section/{type.handle|replace('/(^|[a-z])([A-Z])/', '\\1-\\2')|lower}/{slug}
```
or
```
my-section/{type.name|kebab}/{slug}
``` |
26,446,684 | I'm trying to delete an object that I created in an ArrayList:
```
turtles.add(new Turtle());
```
I want to get rid of the last turtle in the ArrayList, something like this:
```
turtles.get(turtles.size() - 1) = null;
```
Any ideas? Simply removing from the list doesn't work, and Java won't let me nullify in the above way. I'm pretty sure there is only be a single reference to a given Turtle object, as they are only ever created in this way.
P.S: The Turtle class is a thread, in case that matters. | 2014/10/19 | [
"https://Stackoverflow.com/questions/26446684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2558418/"
] | In JAVA, only creation of objects is in our hands, destroying them is at the discretion of Garbage Collector (GC).
When you execute the line **turtles.add(new Turtle())**, the JVM creates a new Turtle object in the java HEAP and adds the corresponding reference to list.
Similarly, when you execute **turtles.get(turtles.size() - 1) == null**, you are essentially getting the reference to that object and making the reference null. You are not actually deleting the object. Only GC takes care of deleting the object.
Note that GC is a lower priority thread, and we do not have any control to make it kick in. But we can request for GC to kick in using System.gc(). | If you are trying to destroy an object in Java you just have to set it `null`:
```
object = null;
``` |
61,236,082 | Usually the multiple dispatch in julia is straightforward if one of the parameters in a function changes data type, for example `Float64` vs `Complex{Float64}`. How can I implement multiple dispatch if the parameter is an integer, and I want two functions, one for even and other for odd values? | 2020/04/15 | [
"https://Stackoverflow.com/questions/61236082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2820579/"
] | You may be able to solve this with a `@generated` function: <https://docs.julialang.org/en/v1/manual/metaprogramming/#Generated-functions-1>
But the simplest solution is to use an ordinary branch in your code:
```
function foo(x::MyType{N}) where {N}
if isodd(N)
return _oddfoo(x)
else
return _evenfoo(x)
end
end
```
This may seem as a defeat for the type system, but if `N` is known at compile-time, the compiler will actually select *only* the correct branch, and you will get static dispatch to the correct function, without loss of performance.
This is idiomatic, and as far as I know the recommended solution in most cases. | As @logankilpatrick pointed out the dispatch system is type based. What you are dispatching on, though, is well established pattern known as a trait.
Essentially your code looks like
```
myfunc(num) = iseven(num) ? _even_func(num) : _odd_func(num)
``` |
14,946,472 | So, I have a vast quantity of `NSString`s and my problem is I need to cut them into smaller strings at a specific point. This may sound complicated but what I need basically is this:
```
NSString *test =" blah blah blah - goo goo goo.";
NSString *str1 = "blah blah blah ";
NSString *str2 = "goo goo goo";
```
How do I code for when there's a hyphen for the string to just cut off there. Is there a way to do this? I found ways to cut of the string after a certain amount of letters but I need it at the hyphen every time. | 2013/02/18 | [
"https://Stackoverflow.com/questions/14946472",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2069876/"
] | You could do this many ways. Two answers above show a few approaches. Many Objective-C solutions will include NSRange usage. You could also do more flexible things with NSScanner or NSRegularExpression.
There is not going to be one right answer. | ```
NSString *cutString = [text substringFromIndex:3];
cutString = [text substringToIndex:5];
cutString = [text substringWithRange:NSMakeRange(3, 5)];
``` |
22,910,327 | I'm currently writing a simple painting app in Java using the Swing libraries. Everything seems to be working fine -- mousePressed and mouseDragged both get called -- but the program does not paint anything on the drawing board. I'd be very happy if somebody could tell me why nothing ever gets drawn here.
**Code:**
```
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PaintGUI extends JComponent {
private static final long serialVersionUID = 1L;
JButton red, green, blue, clear;
Image img;
Graphics2D gfx;
JFrame drawFrame;
JPanel drawPan;
Container cont;
MyListener ml;
Action act;
int x, y, prevX, prevY;
public PaintGUI(){
//Initialisering av panel, frame og content
drawFrame = new JFrame("IFIPaint");
drawPan = new JPanel();
cont = drawFrame.getContentPane();
cont.setLayout(new BorderLayout());
cont.add(BorderLayout.SOUTH, drawPan);
//Setter størrelser
drawPan.setPreferredSize(new Dimension(30, 60));
drawPan.setMinimumSize(new Dimension(30, 60));
drawPan.setMaximumSize(new Dimension(30, 60));
//Ordner knappene
red = new JButton("Rød");
green = new JButton("Grønn");
blue = new JButton("Blå");
clear = new JButton("Slett alt");
//Putter knappene på panelet
drawPan.add(red);
drawPan.add(green);
drawPan.add(blue);
drawPan.add(clear);
//Legger på action listeners
act = new Action();
red.addActionListener(act);
green.addActionListener(act);
blue.addActionListener(act);
clear.addActionListener(act);
//Fullfører vindu og setter synlighet
drawPan.setVisible(true);
drawFrame.setSize(500, 500);
drawFrame.setVisible(true);
drawFrame.add(this);
this.setSize(500, 500);
this.paintComponent(gfx);
this.setVisible(true);
drawFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
draw();
}
public void draw() {
ml = new MyListener();
this.addMouseListener(ml);
this.addMouseMotionListener(ml);
}
public void paintComponent(Graphics g) {
if (img == null) {
img = createImage(drawFrame.getWidth(),drawFrame.getHeight());
gfx = (Graphics2D) img.getGraphics();
gfx.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
gfx.setPaint(Color.WHITE);
gfx.fillRect(0, 0, this.getSize().width, this.getSize().height);
gfx.setPaint(Color.RED);
repaint();
}
gfx.drawImage(img, 0, 0, null);
}
class Action implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == red){
gfx.setPaint(Color.RED);
repaint();
} else if (e.getSource() == green){
gfx.setPaint(Color.GREEN);
repaint();
} else if (e.getSource() == blue) {
gfx.setPaint(Color.BLUE);
repaint();
} else if (e.getSource() == clear) {
gfx.clearRect(0, 0, drawFrame.getWidth(), drawFrame.getHeight());
repaint();
}
}
}
class MyListener extends MouseAdapter {
public void mousePressed(MouseEvent e) {
prevX = e.getX();
prevY = e.getY();
}
public void mouseDragged(MouseEvent e) {
x = e.getX();
y = e.getY();
gfx.drawLine(prevX, prevY, x, y);
repaint();
prevX = x;
prevY = y;
}
}
}
``` | 2014/04/07 | [
"https://Stackoverflow.com/questions/22910327",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1790803/"
] | Don't call `repaint` directly or indirectly within any paint method, doing so will cause a new paint event to be scheduled onto the event queue over and over again, quickly consuming your CPU.
You're not actually painting to the screen device, in order to do that, you need to paint to the supplied `Graphics` context
```
protected void paintComponent(Graphics g) {
if (img == null) {
img = createImage(drawFrame.getWidth(),drawFrame.getHeight());
gfx = (Graphics2D) img.getGraphics();
gfx.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
gfx.setPaint(Color.WHITE);
gfx.fillRect(0, 0, this.getSize().width, this.getSize().height);
gfx.setPaint(Color.RED);
// If you create it you should dispose of it...
gfx.dispose();
}
g.drawImage(img, 0, 0, this);
}
```
Because use `JComponent` is transparent by default, it is even more important that you call `super.paintComponent`, you'll end up with all sorts of nasty paint artifacts if you don't
The fact that are adding components onto the same drawing surface means that you could be obscuring what is getting painted. Remember, not all components are transparent, `JPanel` is opaque by default.
A better solution would be to create a dedicated drawing panel which did nothing but painted what you want, they way you want. This would then be added to another container along with the controls. You would then use setters to change how the painting occurred, such as using color for example
You seem to be trying to do double buffered approach. It might be easier to separate the painting of the buffer from the painting of the component, this would allow you to modify the buffer any way you want to and then call repaint which would simply draw the image to the components `Graphics` context | It seems that the `drawPan` is obstructing you from seeing the image.
Remove its creation and addition to the content pane. |
46,599,757 | This is the code I have so far:
```
questions = ["What is 1 + 1","What is Batman's real name"]
answer_choices = ["1)1\n2)2\n3)3\n4)4\n5)5\n:","1)Peter Parker\n2)Tony Stark\n3)Bruce Wayne\n4)Thomas Wayne\n5)Clark Kent\n:"]
correct_choices = ["2","3",]
answers = ["1 + 1 is 2","Bruce Wayne is Batman"]
score = 0
answer_choices = [c.split()[:3] for c in answer_choices]
for question, choices, correct_choice, answer in zip(questions,answer_choices, correct_choices, answers):
print(question)
user_answer = str(input(choices))
if user_answer in correct_choice:
print("Correct")
score += 1
else:
print("Incorrect", answer)
print(score, "out of", len(questions), "that is", float(score /len(questions)) * 100, "%")
```
My code runs but the answer\_choices (so the question options) don't display on a new line for each list element. How can I do this? An explanation would also be nice | 2017/10/06 | [
"https://Stackoverflow.com/questions/46599757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8291259/"
] | You should get rid of this line in order for your code to work:
```
answer_choices = [c.split()[:3] for c in answer_choices
```
Notice that you don't have to split `answer_choices` since you don't treat the answers of each question as an array.
Moreover, you have more bugs in your code, like the scoring at the end. Here's a formatted and fixed version of your code:
```
questions = [
"What is 1 + 1?",
"What is Batman's real name?"]
answer_choices = [
"1) 1\n2) 2\n3) 3\n4) 4\n5) 5\n\nYour answer: ",
"1) Peter Parker\n2) Tony Stark\n3) Bruce Wayne\n4) Thomas Wayne\n5) Clark Kent\n\nYour answer: "]
correct_choices = ["2","3",]
answers = [
"1 + 1 is 2",
"Bruce Wayne is Batman"]
score = 0
for question, choices, correct_choice, answer in zip(
questions,answer_choices, correct_choices, answers):
print(question)
user_answer = str(input(choices))
if user_answer in correct_choice:
print("Correct!\n")
score += 1
else:
print("Incorrect! " + answer + "\n")
print score, "out of", len(questions), "that is", int(float(score)/len(questions)*100), "%"
``` | If you remove/comment the line
```
answer_choices = [c.split()[:3] for c in answer_choices]
```
you'll get the output as you expect.
Since answer\_choices is already a String array, in for loop you are accessing each array element of answer\_choices. Also, since each string in answer\_choices are in the format you need them to appear, you don't need to split. |
9,950,827 | I'm creating a list of class "Task" in a way such as this.
```
List<Task> toDoList = new List<Task>;
```
Task is a base class and have designed it as such:
```
public class Task : IDetail
{
string _taskName; //Task title.
string _taskDescription; //Task description.
public Task(string tn, string td) //Constructor.
{
_taskName = tn;
_taskDescription = td;
}
// Method set or return _taskName.
public string taskName
{
get
{
return _taskName;
}
set
{
_taskName = value;
}
}
//Method to set or return _taskDescription.
public string taskDescription
{
get
{
return _taskDescription;
}
set
{
_taskDescription = value;
}
}
public virtual void editList()
{
Creator editCreator = new Creator();
editCreator.Show();
}
}
```
What i've been trying todo is call methods that exists within the inherited class like one the one i have designate "Note" and have defined it as follows.
```
class Note : Task, IDetail
{
string _noteDescription;
public Note(string nd, string tn, string td) //Constructor.
: base(tn, td)
{
_noteDescription = nd;
}
//Method to set or return _noteDescription.
public string noteDescription
{
get
{
return _noteDescription;
}
set
{
_noteDescription = value;
}
}
public override void editList()
{
noteBuilder editNote = new noteBuilder();
editNote.Show();
}
}
```
However when i try to call a method of the inherited task on the list i get an error. I am trying to access the method as such:
```
toDoList.ElementAt(x).noteDescription;
```
My question is how do i prevent an error from occurring?
the error states
'toDoList.Task' does not contain a definition for 'noteDescription' and no extension method etc etc.
Should i perhaps be declaring the base class as Abstract? or is there something else i am missing?
Many thanks in advance | 2012/03/30 | [
"https://Stackoverflow.com/questions/9950827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1300895/"
] | Filter the list and convert them to notes, like:
```
var noteList = toDoList.Where(x => x is Note)
.Select(x => (Note)x)
.ToList();
```
then write
```
noteList.ElementAt(x).noteDescription;
``` | `toDoList` contains `Task` elements, not `Note` elements. Now a `Note` element is a type of `Task` element, sure, but polymorphism only works in one direction: you can treat a subclass like its superclass, but you can't treat a superclass like a subclass without casting it first.
If you think about it, you'll realize that it has to be that way. What if you had a second subclass of `Task` called `Foo`: you can put both of those types in `toDoList`...if you tried to access `noteDescription` on an object that is of type `Foo`, you'd be in trouble.
However, there is a way to do what you want, it just requires a cast:
```
var note = toDoList.ElementAt(x) as Note;
var noteDescription = note==null ? "<not a note>" : note.noteDescription;
```
The other way to do it, of course, would be to move `noteDescription` into `Todo`, where it would be accessible from any subclass of `Todo`, but that's probably not what you want since the name implies that it belongs to `Note`. |
50,747,048 | I have a variable that is defined like as an Error and this is what it looks like when I print it:
```
Optional(Error Domain=com.apple.LocalAuthentication Code=-2 "Canceled by user." UserInfo={NSLocalizedDescription=Canceled by user.})
```
What I am trying to do is get that Code of -2...how would I do that? | 2018/06/07 | [
"https://Stackoverflow.com/questions/50747048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/979331/"
] | You can unwrap the optional `error` first and compare the `-2` case.
```
if let error = error {
switch error._code {
case LAError.userCancel.rawValue: // or -2 if you want
// do something
default:
break
}
}
``` | I'm pretty sure you want use the `code` property on `NSError`:
```
var e = NSError(domain: "Pizza", code: 31, userInfo: nil)
e.code // 31
``` |
28,806,763 | I have a .net MVC project which works with Code first approach, I need to add a new table and the migration folder already exists and contains a lot of migrations files that have been made before; when I run `Add-Migration`:
>
> Unable to generate an explicit migration because the following
> explicit migrations are pending:
> [201304230714010\_InformationalMessage, 201305231312259\_Remove
> hardcoded currencies ]. Apply the pending explicit migrations before
> attempting to generate a new explicit migration.
>
>
>
So I run `Update-Database –Verbose` it gives me error:
>
> There is already an object named 'InformationalMessage' in the
> database.
>
>
>
which seems that it goes to execute the migrations files again and it is normal to give me that error as it already exist.
Can anyone help me to how to update this code with my new table? | 2015/03/02 | [
"https://Stackoverflow.com/questions/28806763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2153930/"
] | The error message is probably misleading. It will be linked to the extended data type with table relation.
Try following
1) Check if the EDT you are using is in the 2012 style or 2009 style (2009 has relations). If it is in the old style try to use new style datatype with table reference instead of relation.
2) Add relation to the table level.
3) "Table1 -> Field1,Field12
Index1 -> Field1 having AlternateKey set to "Yes".
Table1 -> properties->PrimaryIndex set to "Index1".
Table2 -> create a foreign key relation (Foreign key -> Primary key based)
then automatically a reation Table2.Table1 ==Table1.Field1 is created.
In this way you can easily create a relation on any field other than RecId. and also the BP error Only foreign key constraints are allowed on this table will remove."
<http://dynamicsuser.net/forums/p/54753/288954.aspx>
4) Try to export table into .XPO. Then change EnforceFKRelation property in file and import .XPO back to axapta.
<https://erpcoder.wordpress.com/2014/08/04/get-rid-of-bp839-only-foreign-key-constraints-are-allowed-on-this-table/>
5) You can find more about this error here <http://microsoft-dynamics-ax-erp.blogspot.cz/2012/12/debug-bp-errors-in-dynamics-ax-2012.html>
"For those of you who were wondering the reason for this BP error, it is because we should create a new Foreign key based relation instead of a normal relation.
Simply put, when you drag and drop the ItemID EDT on the table, it will ask for your confirmation to add the relation on the EDT.
Press Yes and a Foreign key based relation will be created. If you press No and want to create the relation manually, make sure you create a Foreign key based relation and not a normal relation.
Both the normal and foreign key relation looks the same and it is visually difficult to differnetiate between them. So, if you ever encounter the above mentioned BP and have a relation defined, delete and recreate a new foreign key relation." | You have to delete existing relation and add new relation to the same table. Then add relation fields and select `New -> ForeignKey -> PrimaryKey based`. AX will create all three fields. |
21,765,647 | I'm trying to compute the difference in pixel values of two images, but I'm running into memory problems because the images I have are quite large. Is there way in python that I can read an image lets say in 10x10 chunks at a time rather than try to read in the whole image? I was hoping to solve the memory problem by reading an image in small chunks, assigning those chunks to numpy arrays and then saving those numpy arrays using pytables for further processing. Any advice would be greatly appreciated.
Regards,
Berk | 2014/02/13 | [
"https://Stackoverflow.com/questions/21765647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1272809/"
] | You can use numpy.memmap and let the operating system decide which parts of the image file to page in or out of RAM. If you use 64-bit Python the virtual memory space is astronomic compared to the available RAM. | If you have time to preprocess the images you can convert them to bitmap files (which will be large, not compressed) and then read particular sections of the file via offset as detailed here:
[Load just part of an image in python](https://stackoverflow.com/questions/19695249/load-just-part-of-an-image-in-python)
Conversion from any file type to bitmap can be done in Python with this code:
```
from PIL import Image
file_in = "inputCompressedImage.png"
img = Image.open(file_in)
file_out = "largeOutputFile.bmp"
img.save(file_out)
``` |
9,761,804 | When I use:
```
include "../common/common_functions.php";
include "../common/functions.php";
include '../../common/global_functions.php';
```
my browser gives me a lot of warnings, but when i use:
```
@include "../common/common_functions.php";
@include "../common/functions.php";
@include '../../common/global_functions.php';
```
it's working. I know what is the difference between them, but is there any other explanation because files are there and its working with `@` but I know that it's not good to be used! Any suggestion what might be other reason?
It gives me this errors :
```
Warning: include(../../common/constants.php) [function.include]: failed to open stream: No such file or directory in /var/www/ebelejnik/trunk/src/www/root/teadmin/common/common_functions.php on line 4
Warning: include() [function.include]: Failed opening '../../common/constants.php' for inclusion (include_path='.:/usr/share/php:/usr/share/pear') in /var/www/ebelejnik/trunk/src/www/root/teadmin/common/common_functions.php on line 4
```
I understand why it gives me these errors. Because I make a `subdir` and my file system looks like this:
```
/root /common /teadmin /common /admin_pages
```
And when I call a file in `/teadmin/common` from `/teadmin/admin_pages`, it starts to execute it but it calls several files from `/root/common` and can't find them because i use a path like this:
```
include '../common/constants.php';
```
When I do it like this:
```
include '../../common/constants.php';
```
This is from file `common_functions.php` which is in `/root/teadmin/common/`. It's working in a second way from `/root/teadmin/admin_pages/` but gives me an error in `/root/teadmin/` when i call it. Is there a problem with doing it like this:
```
include '../common/constants.php';
@include '../../common/constants.php';
``` | 2012/03/18 | [
"https://Stackoverflow.com/questions/9761804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/710592/"
] | @ is the error suppresion operator in php
<http://php.net/manual/en/language.operators.errorcontrol.php>
Errors are good, it's php's way of communicating with you. They might be worth looking into. Perhaps you are using deprecated functionality, you should post your errors too. | If in doubt how relative paths work and how PHP sets the working directory to the invoked script, then make all paths absolute:
```
include "$_SERVER[DOCUMENT_ROOT]/common/constants.php";
include "$_SERVER[DOCUMENT_ROOT]/common/functions.php";
```
They are absolute in relation to the "web server root directory". (Note that absent array key quotes are valid in double quote context, and only there.) |
2,590 | In a book I'm typesetting, I want the tabular environment to be in footnote size and the other body of the book to be in normalsize font. To do this, I've tried something like the following:
```
\renewenvironment{tabular}[1][t]{\footnotesize
\begin{tabular}
[#1]}{\end{tabular}\normalsize}
```
But I get the following error:
```
! TeX capacity exceeded, sorry [save size=50000].
<to be read again>
\relax
l.72 \centering\begin{tabular}{
cccccc}
```
By the way, I'm using the tabular as below:
```
\begin{table}[t]
\caption{Title}\label{tab1}
\centering\begin{tabular}{cccccc}
....
\end{tabular}
\end{table}
```
Have I done something wrong here?
Edit on December 28th (another question):
-----------------------------------------
In the following code, if I want also to add a `\centering` command, where should I put it? I have put it before and after the `\footnotesize` but it doesn't work!
```
\let\oldtabular\tabular
\let\endoldtabular\endtabular
\renewenvironment{tabular}{\bgroup\footnotesize\oldtabular}%
{\endoldtabular\egroup}
``` | 2010/08/31 | [
"https://tex.stackexchange.com/questions/2590",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/885/"
] | A better approach is to define a new tabular environment with your own customizations
```
\newenvironment{smalltabular}{\footnotesize\tabular}{\endtabular}
```
And then use `smalltabular` instead of `tabular`. A few things to note:
* In the definition of a new environment, instead of `\begin{tabular}` and `\end{tabular}` it's enough to say `\tabular` and `\endtabular`.
* You don't need to register any arguments for `smalltabular`, because the last command in it's definition (i.e. `\tabular`) will already look for and process any arguments appropriately.
If for some reason you *really* want to redefine the tabular environment, you first need to save its old definition and then redefine it. For example:
```
\let\oldtabular\tabular
\let\endoldtabular\endtabular
\renewenvironment{tabular}{\footnotesize\oldtabular}{\endoldtabular}
``` | Using the `\tabular` macro inside a redefinition of the same macro will produce an infinite loop. Try the following:
```
\makeatletter
\renewcommand{\tabular}{\let\@halignto\@empty\footnotesize\@tabular}
\makeatother
``` |
113,151 | If you are a financially responsible person, you know how a credit card works, you pay back the loans in full before the due date, you don't take out money form the ATM or otherwise do something that gets taxed, etc.
Are there any ways that you could still end up paying interest, fees, penalties, or whatever?
I guess stuff like human weakness like forgetting to make the payments when due, or getting addicted to shopping, etc. Having an emergency is another. But if you are disciplined and you have an emergency basket saved up, is there any other way that "banks can get you", so to speak? | 2019/08/31 | [
"https://money.stackexchange.com/questions/113151",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/81192/"
] | Some credit cards will charge an annual fee. If you qualify for a card with no annual fee, don't get cash advances, and pay in full each month, you won't be charged any interest. I think I've been charged a month's interest twice in the last five years, both times because I spaced out and missed the billing due date. The main things are to really know how much income you'll have each month, not buying things you can't afford, have money saved to pay for emergency expenses, and to stay on top of your record keeping. | One way banks/credit cards can get you is by being having terms that are subtly different from the norm.
**An example**:
On every credit card I had ever had, if you paid the balance in full in the previous statement period then you would have a grace period where purchases in the current statement wouldn’t be assessed interest.
One time, I missed a payment on a particular card — it fell through the cracks when I moved to a new checking account — and so I was charged interest the following month. That’s fine, my fault, so I promptly paid the full balance due. To my surprise, the following month I again got a bill with interest assessed on my purchases. As it turned out, on this card the grace period didn’t reset for *two!* billing periods, instead of the traditional *one*.
It was a deviation from boilerplate that I had never considered, so that’s how they got me. Yes, when I looked at the terms they were as the bank had described, but by subtly modifying an industry-standard perk, they were able to extract an unexpected fee. |
37,337,477 | I need some advices on how to mock a rest api. My application is in MVP architecture.
My interface for API:
```
public interface MyAPI {
@GET("{cmd}/{userName}/{password}")
Observable<Response> login(
@Path("cmd") String cmd,
@Path("userName") String userName,
@Path("password") String password
);
```
My service:
```
public class MyService implements IService {
private static MyService mInstance = new MyService();
private MyAPI mApi;
public static MyService getInstance() {
return mInstance;
}
private MyService() {
OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
httpClientBuilder.connectTimeout(Config.DEFAULT_TIMEOUT, TimeUnit.SECONDS);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Config.kBaseUrl)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(httpClientBuilder.build())
.build();
this.mApi = retrofit.create(MyAPI.class);
}
public void login(
Subscriber<Response> subscriber,
String userName,
String password) {
mApi.login(Config.kLoginCmd,userName,password)
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(subscriber);
}
```
My presenter class:
```
public class LoginPresenter implements LoginContract.Presenter {
LoginContract.View mView;
IService mService;
ISession mSession;
public LoginPresenter(LoginContract.View loginView, IService service, ISession session) {
mView = loginView;
mService = service;
mSession = session;
}
@Override
public void login(String email, String password) {
Subscriber<Response> subscriber = new Subscriber<Response>() {
@Override
public void onCompleted() {
mView.showLoading(false);
}
@Override
public void onError(Throwable e) {
mView.showError(e.getLocalizedMessage());
}
@Override
public void onNext(Response response) {
if (response.getResults().getStatus().equalsIgnoreCase(Config.kResultCodeOK)) {
mView.loginSuccess();
} else {
mView.showError(response.getResults().getStatus().getErrmsg());
}
}
};
mView.showLoading(true);
mService.login(
subscriber,
email,
password);
}
```
There is another way to test my presenter by writing a Mock service. But I don't like that so much and I think Mockito could help.
Here is my test class:
```
public class LoginPresenterMockTest {
private LoginPresenter mLoginPresenter;
@Mock
LoginContract.View view;
@Mock
IService service;
@Mock
ISession session;
@Before
public void setup() throws Exception {
MockitoAnnotations.initMocks(this);
mLoginPresenter = new LoginPresenter(view, service, session);
}
@Test
public void testLoginWithCorrectUserNameAndPassword() throws Exception {
mLoginPresenter.login("user@email.com","password");
verify(view).loginSuccess();
}
}
```
What I want to do is I mock the response data call loginSuccess() when the response is correct.
Of course my current test will not work. I need some advices on how to mock this? Any idea? Thanks. | 2016/05/20 | [
"https://Stackoverflow.com/questions/37337477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/118562/"
] | You can do it in next way:
```
@Test
public void testLoginWithCorrectUserNameAndPassword() throws Exception {
// create or mock response object
when(service.login(anyString(), anyString(), anyString).thenReturn(Observable.just(response));
mLoginPresenter.login("user@email.com","password");
verify(view).loginSuccess();
}
@Test
public void testLoginWithIncorrectUserNameAndPassword() throws Exception {
// create or mock response object
when(service.login(anyString(), anyString(), anyString).thenReturn(Observable.<Response>error(new IOException()));
mLoginPresenter.login("user@email.com","password");
verify(view).showError(anyString);
}
``` | Thanks for **@Ilya Tretyakov**, I came out this solution:
```
private ArgumentCaptor<Subscriber<Response>> subscriberArgumentCaptor;
@Test
public void testLoginWithCorrectUserNameAndPassword() throws Exception {
mLoginPresenter.login("user@email.com","password");
// create the mock Response object
Response response = ......
verify(service, times(1)).login(
subscriberArgumentCaptor.capture(),
stringUserNameCaptor.capture(),
stringPasswordCaptor.capture()
);
subscriberArgumentCaptor.getValue().onNext(response);
verify(view).loginSuccess();
}
``` |
53,712 | In what cases it is correct to say "in the school"? Are there any situations, in which that combination of words placed in the end of a sentence would be correct? | 2015/03/28 | [
"https://ell.stackexchange.com/questions/53712",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/650/"
] | In school vs in the school.
When you talk about activities other than school actvities, you use the phrase "in the school". Otherwise, you use "in school" about school/educational activities. look at the following sentences to distinguish between these phrases:
My kids are still in/at school.
Some visitors are in the school.
There is a canteen in the school.
The carpenter is repairing chairs in the school. | Not really, 'in the school' is perhaps more common American English while 'at school' is more British but both are equally 'correct'. Similarly an American would probably say 'in college' while a Brit would say 'at university'.
In tends to be used for institutions, so your are 'in hospital' or rather than 'at hospital' but 'at home' not 'in home' - although you might be put 'in a home'
It's just one of those things!
there is perhaps a slight subtle difference that 'in school' means they attend school - as opposed to having finished school, while 'at school' means they are there now.
So "are your children in school" = are they under 16 or 18 ? But "are your children at school" = are they at school today or are they at home.
(but that's from a BE perspective) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.