qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
84,827 | There are characteristic chord progressions taught in music theory, for example, the *cadential 6-4*, which is **Ic - V - I**. Then there's **Ib - ii7b - V - I**, & so on. I want to know if these cadences have to be written as is, or they can be modified by writing one or more chords in them in an inversion?
Also, from a previous question asked by me ([double the third or the fifth of a chord](https://music.stackexchange.com/questions/84381/should-one-double-the-thirds-or-the-fifth-in-chords)), I learnt that notes other than the root are also doubled. I want to know if this is ok to do in the cadences I mentioned above (& other examples of such characteristic cadences). For example, is it ok to *double the third instead of the root* in chord **Ib** of the **Ib - ii7b - V - I** progression? | 2019/05/13 | [
"https://music.stackexchange.com/questions/84827",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/59054/"
] | Two leading music scholars of our generation, Jim Hepokoski and Warren Darcy, formulated what they call [Sonata Theory](https://en.wikipedia.org/wiki/Sonata_theory) (note the capital S and T!) to better understand the sonata process.
They list five types of sonatas. The Type 3 Sonata is the sonata that you describe, with exposition, development, and recapitulation. The **Type 1 Sonata**, however, is a sonata without development, which therefore only includes two of your three sections.
In my experience, the development is the only one of these three sections that is optional. It seems to me the exposition is mandatory, because without it nothing can be developed. And the recapitulation seems mandatory because without it the music will not return to tonic.
Lastly, the term "sonatina" is also used to discuss a sonata without a development, but the term isn't used consistently; sometimes a composer uses "sonatina" to just mean "easy sonata." | The term Sonata can be used for any instrumental piece.
The *Sonata* that you're thinking of is the classical *Sonatensatz* and needs to have these 3 section to be called as such.
The classical Sonata includes apart of the Sonata-Satz form a Menuet or Scherzo and other forms like Adagio-Satz, Lied-Satz, (AB: a form made up of two contrasting sections, each of which may or may not be repeated) and a Rondo.
A smaller Sonata that also may fit to what your meaning (only 2 sections) is called *Sonatina.*
The *Sonataform* (1. or 4. section in a "Sonata") includes the 3:
exposition,
development, and
recapitulation. |
84,827 | There are characteristic chord progressions taught in music theory, for example, the *cadential 6-4*, which is **Ic - V - I**. Then there's **Ib - ii7b - V - I**, & so on. I want to know if these cadences have to be written as is, or they can be modified by writing one or more chords in them in an inversion?
Also, from a previous question asked by me ([double the third or the fifth of a chord](https://music.stackexchange.com/questions/84381/should-one-double-the-thirds-or-the-fifth-in-chords)), I learnt that notes other than the root are also doubled. I want to know if this is ok to do in the cadences I mentioned above (& other examples of such characteristic cadences). For example, is it ok to *double the third instead of the root* in chord **Ib** of the **Ib - ii7b - V - I** progression? | 2019/05/13 | [
"https://music.stackexchange.com/questions/84827",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/59054/"
] | Two leading music scholars of our generation, Jim Hepokoski and Warren Darcy, formulated what they call [Sonata Theory](https://en.wikipedia.org/wiki/Sonata_theory) (note the capital S and T!) to better understand the sonata process.
They list five types of sonatas. The Type 3 Sonata is the sonata that you describe, with exposition, development, and recapitulation. The **Type 1 Sonata**, however, is a sonata without development, which therefore only includes two of your three sections.
In my experience, the development is the only one of these three sections that is optional. It seems to me the exposition is mandatory, because without it nothing can be developed. And the recapitulation seems mandatory because without it the music will not return to tonic.
Lastly, the term "sonatina" is also used to discuss a sonata without a development, but the term isn't used consistently; sometimes a composer uses "sonatina" to just mean "easy sonata." | A sonata that has only the exposition and the recapitulation or only a very short development section can be called a *sonatina.*
Early sonata forms from the transition between the Baroque and Classical periods can be based on a two part form. Essentially the material of the first half will move from the tonic key to the dominant key. Then the second half restates the material but with the key areas reversed, the second half starts in the dominant key and transitions to the tonic key. These movements may not necessarily be titled "sonata." In a suite of movements an *allemande*, *courante*, *gigue*, etc. may use the early sonata form. You could also look for examples in Scarlatti's shorter sonatas for harpsichord.
Examples of simple two part sonatinas can be found in many sources. They often are titled "sonatina" which makes them easy to find. You can also find examples in the Mozart *Nannerl Notebook*, but none of those are titled as "sonata" or "sonatina."
In these sonata forms the order of thematic material change between the initial presentation in the exposition and its second appearance in the recapitulation. The placement of the thematic material isn't what determines the form but instead the movement form tonic to dominant and back to the tonic. You could abstract the essential harmonic aspect of the form to...
`||: I (V7/V) V :||: V(7) I :||`
Very important is the sense that the dominant *becomes a new tonic* at the close of the first half. Then in the second half the dominant returns to its original function as the dominant of the opening tonic.
As a side note: you may want to read up on the distinction of sonata as a two part or three part form. The three part idea of course is: exposition, development, and recapitulation. But in terms of form and harmony it's more of a two part form. The traditional division of a sonata movement into two halves with a double bar repeat underscores the two part, binary aspect.
The ideas aren't mutually exclusive. Think about both when you assess any particular sonata. You can think of the third section as the *development* which may be optionally omitted, just a brief segue into the recapitulation which doesn't really constitute a formal section, or a long excursion to various keys which can be considered a bona-fide, formal section. |
28,734,847 | I am running the Thin server for my Rails app locally. Every time I start it I receive the following message:
```
Warning: Running `gem pristine --all` to regenerate your installed gemspecs (and deleting then reinstalling your bundle if you use bundle --path) will improve the startup performance of Spring.
```
Even after I run the command 'gem pristine -all' it takes a long time for the server to restart, and the message then appears again. Why so? | 2015/02/26 | [
"https://Stackoverflow.com/questions/28734847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1545308/"
] | `gem update --system` to get rid of the message works for me. | I had the same problem. Looking through the output from `gem pristine --all` I saw that several gems were being skipped with a message like
```
Skipped bigdecimal-1.1.0, it is bundled with old Ruby
```
I reinstalled those gems manually to get rid of the message
```
gem uninstall bigdecimal
gem install bigdecimal
``` |
70,849,002 | Assume I have the following situation:
```
interface Base {
a: string;
}
interface Derived extends Base {
b: string;
}
const x: Derived = {
a: "a",
b: "b",
};
```
Is it possible to have the linter and/or compiler to complain about the following line:
```
const y : Base = x;
```
The purpose would be to discover that there are additional properties being assigned to `y` that do not exist in the Base class. | 2022/01/25 | [
"https://Stackoverflow.com/questions/70849002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/665794/"
] | [This comment](https://stackoverflow.com/questions/70849002/disallow-properties-from-derived-class-on-assignment#comment125249375_70849002) is correct: TypeScript is [structurally-typed](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-func.html#structural-typing).
This means that as long as you extend `Derived` from `Base`, then you cannot exclude `Base`'s properties from `Derived`.
However, you can use structural typing to create an additional type which is compatible with `Base` and excludes the "excess" properties of `Derived` by typing them as [optional properties](https://www.typescriptlang.org/docs/handbook/2/objects.html#optional-properties) of type [`never`](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#the-never-type) (via the help of some [type utilites](https://www.typescriptlang.org/docs/handbook/utility-types.html)), like this:
[TS Playground](https://www.typescriptlang.org/play?noUncheckedIndexedAccess=true&target=99&useUnknownInCatchVariables=true&exactOptionalPropertyTypes=true#code/JYOwLgpgTgZghgYwgAgEJwM4oN4FgBQyycAXMhmFKAOYDcBAvgQaJLIigCLTABuEAE2QQAHpBACMaTDgJEARmQpUQdRs3wIA9iArIRZblX5CAvMjyFiZAERwbAGjnJFyG-MeN6+AmACeAA4oAApQEPzgAKJiEBKCoVoBGAA86FgOyEZ8gsIxElJpEAB8yOaFyABkyMFwUGDAcAA2yQBKENpQAsnRCI0ArgIQyQDWEH5aMJk8Jhmj45OFRRkg4dBFRd6+gSiFAHJaYFkmpdVhEWDR4oMCCUmpMhlHghsaAPSvyACSukEIYMhgAAWKH8QQA5FIAlBEtB6hAMCQCINerUUNpdP9XHsDk8BN55AA6ODId7kSg0AiE+Qkj59OIwUCCN4fACaWj6UFycAAtgFGihMBhgNQQNzYmBEZodHo-GRsYdpjlzCJaCSAFTOIhEAB6BAAKttkGDcWDkMApCADsQMEKRXB5PyAVoAYawfKTQTnAagkaTWaLVbBcKQPbHWBnaCUGCanUGs02h0uu5HMgVvwoOswZ6rERvfDkBNkFCYXU-Eb5KbUWaQNpeXB6g6INmtVq80blDRTebU4GbcHQyCI6609AswAKABMAGYJxOAJTINWvAhAA)
```ts
interface Base {
a: string;
}
interface Derived extends Base {
b: string;
}
const x: Derived = {
a: "a",
b: "b",
};
type PreventExtendedProps<Base, Derived extends Base> = Base & Partial<Record<Exclude<keyof Derived, keyof Base>, never>>;
type BaseNotDerived = PreventExtendedProps<Base, Derived>;
// Inspect the type's properties:
declare const b: BaseNotDerived;
b.a // string
b.b // undefined
// Your example assignment:
const y: BaseNotDerived = x; /*
^
Type 'Derived' is not assignable to type 'BaseNotDerived'.
Type 'Derived' is not assignable to type 'Partial<Record<"b", never>>'.
Types of property 'b' are incompatible.
Type 'string' is not assignable to type 'never'.(2322) */
``` | How about this...
```
type A = {
a: string;
};
type B = {
b: string;
};
type Derived = A | B;
const x: Derived = {
a: "a",
b: "b",
};
const a: A = { a: "123" };
const b: B = { b: "234" };
const d: Derived = x;
const b1: B = x; // <---- Error
const a1: A = x; // <---- Error
```
**Surely, with interface(s) alone, that won't be possible** |
14,761,777 | I'm new to node/pdf js. I just install node and run pdf.js.
Now I want know how can I open pdf files using pdf js by passing pdf file url as parameter in query string? | 2013/02/07 | [
"https://Stackoverflow.com/questions/14761777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/523864/"
] | Try adding `?file=document.pdf` to the viewer url. See also <https://github.com/mozilla/pdf.js/issues/2496> | It will require some changes in the `viewer.js`:
* Move `parseQueryString: function pdfViewParseQueryString(query)` outside `var PDFView` so it's a standalone function: `function pdfViewParseQueryString(query)`
* Replace all occurences of `PDFView.parseQueryString(..)` to `pdfViewParseQueryString(..)`
* Change `var DEFAULT_URL = ''` to `var urlParm = pdfViewParseQueryString(document.location.search.substring(1)); var DEFAULT_URL = urlParm.url;`
* You should now be able to call the viewer with somethin like `$("actualViewer").src = 'pdfViewer?url=' + encodeURIComponent(pathToFile);` |
14,761,777 | I'm new to node/pdf js. I just install node and run pdf.js.
Now I want know how can I open pdf files using pdf js by passing pdf file url as parameter in query string? | 2013/02/07 | [
"https://Stackoverflow.com/questions/14761777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/523864/"
] | It will require some changes in the `viewer.js`:
* Move `parseQueryString: function pdfViewParseQueryString(query)` outside `var PDFView` so it's a standalone function: `function pdfViewParseQueryString(query)`
* Replace all occurences of `PDFView.parseQueryString(..)` to `pdfViewParseQueryString(..)`
* Change `var DEFAULT_URL = ''` to `var urlParm = pdfViewParseQueryString(document.location.search.substring(1)); var DEFAULT_URL = urlParm.url;`
* You should now be able to call the viewer with somethin like `$("actualViewer").src = 'pdfViewer?url=' + encodeURIComponent(pathToFile);` | On a further note, it is important to know that the file=document.pdf argument must come before the hash sign:
<http://myserver.com/web/viewer.html?file=test.pdf#page=6&zoom=page-fit,0,540>
HTH |
14,761,777 | I'm new to node/pdf js. I just install node and run pdf.js.
Now I want know how can I open pdf files using pdf js by passing pdf file url as parameter in query string? | 2013/02/07 | [
"https://Stackoverflow.com/questions/14761777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/523864/"
] | Try adding `?file=document.pdf` to the viewer url. See also <https://github.com/mozilla/pdf.js/issues/2496> | On a further note, it is important to know that the file=document.pdf argument must come before the hash sign:
<http://myserver.com/web/viewer.html?file=test.pdf#page=6&zoom=page-fit,0,540>
HTH |
48,250,698 | I have table with more than 25 Fields in it. It has some column with huge data (`nvarchar(MAX)`). It has **User** table like :
```
ID // Primary key
Name
Mail
Contact
RegFees
.
.
. // about 25 Fields
Narration // Nvarchar(Max) may have upto 10000 chars
Tag // Nvarchar(Max) may have upto 15000 chars
```
Now i have to update only *Name,Mail,Contact* fields in it.
I have gone through several so posts like [update 1 field](https://stackoverflow.com/questions/3642371/how-to-update-only-one-field-using-entity-framework), [update multiple fields](https://stackoverflow.com/questions/35617864/update-multiple-columns-in-entity-framework).
But these require data to be loaded for that specific user ID and then Update it like :
```
var u = dc.Users.Where(a =>a.ID.Equals(i.ID)).FirstOrDefault();
if (u != null)
{
// Note : ALL the data of 25+ columns is loaded including nvarchar(Max)
// it will decrease performance as Whole Data is loaded first.
u.Name = i.Name;
u.Mail = i.Mail;
u.Contact = i.Contact;
}
```
is there any better way that does not require to load entire data ? | 2018/01/14 | [
"https://Stackoverflow.com/questions/48250698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6479082/"
] | You can follow the below approach for updating few fields in a table.
```
dc.Database.ExecuteSqlCommand("Update [User] Set Name = @Name, Mail = @Mail, Contact = @Contact Where ID = @ID", new SqlParameter("@Name", "YourName"), new SqlParameter("@Mail", "newMail"), new SqlParameter("@Contact", "newContact"), new SqlParameter("@ID", 1));
``` | Add a stored procedure to the database for updating the few fields in the table. You can use the entity framework to call a stored procedure which updates the fields in the database
One of these articles should help
<http://www.entityframeworktutorial.net/stored-procedure-in-entity-framework.aspx>
<https://www.mikesdotnetting.com/article/299/entity-framework-code-first-and-stored-procedures> |
48,250,698 | I have table with more than 25 Fields in it. It has some column with huge data (`nvarchar(MAX)`). It has **User** table like :
```
ID // Primary key
Name
Mail
Contact
RegFees
.
.
. // about 25 Fields
Narration // Nvarchar(Max) may have upto 10000 chars
Tag // Nvarchar(Max) may have upto 15000 chars
```
Now i have to update only *Name,Mail,Contact* fields in it.
I have gone through several so posts like [update 1 field](https://stackoverflow.com/questions/3642371/how-to-update-only-one-field-using-entity-framework), [update multiple fields](https://stackoverflow.com/questions/35617864/update-multiple-columns-in-entity-framework).
But these require data to be loaded for that specific user ID and then Update it like :
```
var u = dc.Users.Where(a =>a.ID.Equals(i.ID)).FirstOrDefault();
if (u != null)
{
// Note : ALL the data of 25+ columns is loaded including nvarchar(Max)
// it will decrease performance as Whole Data is loaded first.
u.Name = i.Name;
u.Mail = i.Mail;
u.Contact = i.Contact;
}
```
is there any better way that does not require to load entire data ? | 2018/01/14 | [
"https://Stackoverflow.com/questions/48250698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6479082/"
] | If you want a EFish approach (no SQL statement) you can treat your `UPDATE` as a batch statement using [Entity Framework Extensions](https://github.com/zzzprojects/EntityFramework.Extended/wiki/Batch-Update-and-Delete), now re-branded [Entity Framework plus](http://entityframework-plus.net/?z=ef-extended).
I have used the old version, but the one seems to work similarly. For your particular case:
```
dc.Users.Where(u =>
u.ID = userID)
.Update(x => new User()
{
Name = name,
Mail = mail,
Contact = contact
});
```
AFAIK, this will directly issue an `UPDATE` against the database (it is not included in the transaction by default). However, a custom transaction (i.e. TransactionScope`) can be used when needed. | Add a stored procedure to the database for updating the few fields in the table. You can use the entity framework to call a stored procedure which updates the fields in the database
One of these articles should help
<http://www.entityframeworktutorial.net/stored-procedure-in-entity-framework.aspx>
<https://www.mikesdotnetting.com/article/299/entity-framework-code-first-and-stored-procedures> |
98,609 | I'm new to options and I was on the robinhood options chain for selling VSAT puts with expiration data AUG 17 and noticed that the stock was trading at $63.79 with premiums $0.08 and $2.40 for respective strikes of $60 and $50/$40.
I am wondering why this is the case? Wouldn't a writer prefer the $40 strike with premium $2.30 to the strike of $60 with premium $0.08? | 2018/08/15 | [
"https://money.stackexchange.com/questions/98609",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/74023/"
] | Helpful first post suggestions: When you describe an option position, you need to specify all of the details. In this case, are these puts or calls? Are you quoting the bid, the ask or the last trade? The details are apparent when I look at an option chain but the reader shouldn't have to look up the quotes.
Now, some answers. These are illiquid options. The $40 put has an Open Interest (OI) of zero. That means that there are no contracts in existence. This illiquidity is also reflected by a closing bid of $0.00, a closing ask of $4.80 and a last trade of $2.40 which occurred who knows how long ago and at what price of VSAT? Although the ask price and last trade are slightly different for the $45 and $50 put, it's the same zero OI. There's no valid basis for comparison for any of these options.
Another tip off that this is bad data is that the last trade in all three of these strike prices ($40, $45, and $50) was $2.30 to $2.40 and yet the $60 put is $0.05 x $0.10 with a last trade of $0.10. The further out-of-the-money options are, the less they are worth. And yet the $40, $45 and $50 puts are worth 23 times the $60 put, based on the last trade? All of these puts are near worthless and this is just garbage quote time. | OP,
1. The prices (both history, and current bid/ask) you are seeing are literally **totally meaningless.**
2. The fundamental issue is, it looks like you have not yet got the idea that "prices" **are, quite simply, meaningless** in very thin markets.
The important point to understand is that, because we often talk about "the price" of common everyday stocks (Coke, Apple, etc) ...
* with those instruments, there is an incredibly high trading volume measured literally in as much as millions of trades per hour (!!), and at every second (!) of the day there are tens of thousands of bids/asks sitting,
* this gives folks a completely distorted view that instruments "have" a price
* once you trade thin instruments, you will be quickly disabused of this notion :)
As in the example at hand.
The "myth of price."
====================
The *"myth of price"* is caused by our day-to-day familiarity with incredibly liquid instruments (the common well-known stocks of our day). It is completely common to talk about "the price" of Apple, etc. This is simply as wrong as it is common. Once you trade thin instruments, you will be quickly disabused of the "myth of price".
An analogy which can help is, consider a house for sale on your street. When you think of a "single item" like that it's more obvious that there is no "price". It could be nobody whatsoever is making an offer on it, it could be it just sold a few days ago, or it may not have sold for 20 years, or there may be a dozen offers on it. |
5,494,811 | Hey everyone,
A friend of a friend has asked me for help to setup a website. I haven’t really created a website on my own. Although I know HTML, CSS, and Javascript my background has primarily been in Java, Flex, and ActionScript. I don’t mind doing this friend a favor but my time is valuable (New York City is expensive to live in).
**A.** How much should I charge for my valuable time but lack of experience? I was thinking $30/hr or $500 total.
The website would be a static site with 5-10 pages. I’m not sure if the friend (client?) has all the assets (images, layout, styles). I’m just trying to prepare before the meeting in a few days.
**B.** What are my options?
1. Squarespace and similar sites. The client could then figure it out and
update it without me once the primary project is complete. (I would have to convince the client to leave godaddy though)
2. Setup wordpress with a premium template, customize it (I don’t know
PHP) and that way the client could
use the CMS/backend to make future
revisions. All I’d need are the
assets.
3. Write it all from scratch? (Could be very time consuming not to mention
ugly as I’m not a designer)
4. Fourth option?
All opinions are welcome. Thanks for the advice! | 2011/03/31 | [
"https://Stackoverflow.com/questions/5494811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/554327/"
] | I totally see where you're coming from. You're charging for your time, and your time includes CUSTOMISING WordPress. Some people think it's easy. But if you're going into deep-level programming and making more efficient code, then you're really using your expertise in programming and scripting, PHP or otherwise.
I've so much to say in response to Blender, but I guess it's better saving my bytes.
I found myself here cos I'm starting out freelancing now too and I've got a request to create a site, and can quote for a static site's price or to do it on Wordpress. The client already has a design in mind, and I've to go study the Wordpress ins and outs to figure out how to use Wordpress and creating his design as a template. I can use a ready made template that looks similar, but I still will have to spend my time and use my experience as a "purist" HTML/CSS coder with basic Java/ASP knowledge and tweak that template to suit ME.
I am considering $500-$800 for basic setup, and $100-$150 per drill down page. That may sound steep to some, but we find ourselves spending time cleaning up bad logos and cropping photos, as well as doing page layout most of the time. If a work looks too good and simple it means some effort has been put in to make it look effortless. That's what I think anyway when it comes to a clean website, both visually and code-wise.
My prices are in Singapore Dollars, but I guess you can translate the same price to NY, or even more since NY is more expensive!
The point is if your time is worth $30, whether doing dishes or doing programming, then stick to it, cos you know you have to spend time setting up, explaining, discussing and commuting, all factored in. If someone is willing to pay that amount for quality and trust, then no one else should complain. | WP based site with 5-10 static pages and simple design is something around 150-200$ at least we charge somewhere around that. |
13,446,807 | I wonder if there is a command to straight away copy a character or a word above the cursor and paste it at the current position?
Example:
```
sig1 : in std_logic;
sig2 : in std_logic;
sig3 : ^
```
Consider the situation above, and my cursor is at the `^` position, I would like to duplicate the `in std_logic;` and paste it at current position. A way that I know of that can work is:
```
1. Move cursor up
2. Go into visual mode and highlight
3. Yank
4. Move cursor down
5. Paste
```
Is there any easier way to do so? Or I'm left with the only option of writing a mapping in vimrc that execute the whole sequence for me?
Edit:
I found a mapping on the internet:
```
imap <F1> @<Esc>kyWjPA<BS>
nmap <F1> @<Esc>kyWjPA<BS>
imap <F2> @<Esc>kvyjPA<BS>
nmap <F2> @<Esc>kvyjPA<BS>
```
but it seems that Greg's solution is easier! | 2012/11/19 | [
"https://Stackoverflow.com/questions/13446807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/75579/"
] | In insert mode, you can use `Ctrl+Y` to copy characters from the corresponding character position on the previous line. Just hold down the key and wait for the keyboard repeat to get you to the end of the line. | Although Greg's answer is spot on I have modified my `ctrl`+`y` to copy word-wise as I find it more helpful in my workflows. I have the following in my `~/.vimrc` file:
```
inoremap <expr> <c-y> pumvisible() ? "\<c-y>" : matchstr(getline(line('.')-1), '\%' . virtcol('.') . 'v\%(\k\+\\|.\)')
```
Basically this expression mapping copies the a word from the line above by if the insert completion menu (see `:h ins-completion-menu`) is not visible. Checking for this case allows for accepting of the current completion and leave completion mode (See `:h complete_CTRL-Y`).
If the insert completion menu is not visible then the following occurs:
* `getline(line('.')-1)` returns the previous line
* `virtual('.')` the current positions column position
* `'\%' . virtcol('.') . 'v\%(\k\+\\|.\)'` match a word from the cursors position or any character
* `matchstr()` returns the matching portion of the previous line that matches the pattern.
For more help see:
```
:h :map-<expr>
:h pumvisible(
:h matchstr(
:h getline(
:h line(
:h virtcol(
:h /\%v
:h /\k
``` |
24,290,331 | I am working on a hybrid application using IBM worklight and Dojo toolkit. On IOS8, only the button clicks are working. Rest all the elements do not respond to any click. Has anyone tried using Dojo toolkit 1.9 with IOS8? Does this version of Dojo supports IOS8.
Thanks. | 2014/06/18 | [
"https://Stackoverflow.com/questions/24290331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3731989/"
] | >
> if there are any concerns or gotchas I need to be aware
>
>
>
No. Just use the same folder for `SVNParentPath` in Apache and for `-r` of svnserve (for simplicity - same hotname, only protocol will differ) | Accessing a repository using different protocols will work, but in my experience using mod\_dav\_svn for all user access has many advantages:
* no user account for SVN access required, use LDAP, and/or "basic" authentication instead,
* easy tool integration through HTTP(S) transport
* powerful Apache integration (mod\_rewrite, mod\_proxy\_http...)
* supports modeling project roles, individually, or with groups, and if necessary on a directory basis,
* audit friendly access rule storage *in* a repository (file: method), or in *the* repository (^ method).
Using multiple blocks for the same repository parent directory will work, too. |
10,698,706 | How can the following produce an "invalid cast exception" ???
```
foreach (KeyValuePair<String,Object> entry in HttpRuntime.Cache)
{
if (entry.Value.GetType() == typeof(MyClass))
{
MyClass mc = (MyClass)entry.Value; // ===> Invalid Cast Exception !!!
```
(To those who are asking why I want to do this : I randomly add and remove a few different objects in/from the cache so the need for this kind of test. I was planning to create some sort of container object that would hold my various objects; I would push only this object in the cache but the question remains : would it solve the cast exception ?) | 2012/05/22 | [
"https://Stackoverflow.com/questions/10698706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1409737/"
] | Are you in an environment that does dynamic (re-)compilation? ASP.NET Websites, for example, recompile pages at runtime if the code file changes. They will compile that page to an assembly and load that assembly. Even if the runtime unloads the old assembly at some point, this still gives you a new type that is not compatible with the old one.
I don't know, if you can work around this with some kind of versioning or strong naming.
But since the change occured, it seems unlikely, you'd want the old type around. | No idea why your code fails, but you can try this with a 'softcast':
```
foreach (KeyValuePair<String,Object> entry in HttpRuntime.Cache)
{
MyClass mc = entry.Value as MyClass;
if (mc != null)
{
//Do your stuff
``` |
10,698,706 | How can the following produce an "invalid cast exception" ???
```
foreach (KeyValuePair<String,Object> entry in HttpRuntime.Cache)
{
if (entry.Value.GetType() == typeof(MyClass))
{
MyClass mc = (MyClass)entry.Value; // ===> Invalid Cast Exception !!!
```
(To those who are asking why I want to do this : I randomly add and remove a few different objects in/from the cache so the need for this kind of test. I was planning to create some sort of container object that would hold my various objects; I would push only this object in the cache but the question remains : would it solve the cast exception ?) | 2012/05/22 | [
"https://Stackoverflow.com/questions/10698706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1409737/"
] | OK I finally made it.
First of all, my apologies, I was erroneously reading my log file. The exception did not come form
```
MyClass mc = (MyClass)entry.Value;
```
but from
```
foreach (KeyValuePair<String,Object> entry in HttpRuntime.Cache)
```
It appears the Cache can't be iterated with a KeyValuePair (a code I had found on the internet...). Once again, sorry for wasting your time searching in a wrong direction... Thanks for your help anyway !
And now for the code that works :
```
IDictionaryEnumerator CacheEnum = HttpRuntime.Cache.GetEnumerator();
while (CacheEnum.MoveNext()) {
MyClass mc = ((DictionaryEntry)CacheEnum.Current).Value as MyClass;
if (mc != null) {
// Doing stuff...
``` | No idea why your code fails, but you can try this with a 'softcast':
```
foreach (KeyValuePair<String,Object> entry in HttpRuntime.Cache)
{
MyClass mc = entry.Value as MyClass;
if (mc != null)
{
//Do your stuff
``` |
9,632,521 | Is there any best practice in handling "support tables" in Django?
I dislike `Field.choices`, as it doesn't really enforce integrity (it doesn't even create check constraints), so I prefer creating a full-blown model (and often, I find myself adding additional fields in the support table).
Now, if I use a full model, I suppose the right way to go is to create an initial data fixture for the table content, but is there a "right way" to have named instances of the row, say...
```
class State(models.Model):
name = model.TextField()
STATES = dict(
NEW=State.objects.get(pk=0),
IN_PROGRESS=State.objects.get(pk=1),
)
```
... or something like that.
What do *you* use? | 2012/03/09 | [
"https://Stackoverflow.com/questions/9632521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26787/"
] | Django ORM checks integrity if you specify choices attribute (when you insert/update data via user forms).
You also can set validation logic to database level and use database ENUM field if you db support this.
**UPD**:
```
class EnumField(models.Field):
def __init__(self, *args, **kwargs):
super(EnumField, self).__init__(*args, **kwargs)
if not self.choices:
raise AttributeError('EnumField requires `choices` attribute.')
def db_type(self):
return "enum(%s)" % ','.join("'%s'" % k for (k, _) in self.choices)
GENDER_MALE = 'm'
GENDER_FEMALE = 'f'
GENDER_CHOICES = (
(GENDER_MALE, 'Male'),
(GENDER_FEMALE, 'Female'),
)
class Person(models.Model):
name = models.CharField(max_length=50)
gender = EnumField(choices=GENDER_CHOICES)
``` | I have also a use case for database-backed Enum models. I came up with a solution that uses Python descriptors to implement [django choices](https://docs.djangoproject.com/en/2.2/ref/models/fields/#choices)-like interface to the enum values:
```
from django.db import models
class ModelInstance:
"""Descriptor that uses predefined value fields to access model instances."""
def __init__(self, **kwargs):
self._instance_attributes = kwargs
self._instance = None
def __get__(self, instance, instance_type):
if not self._instance:
self._instance = instance_type.objects.get(**self._instance_attributes)
return self._instance
class EnumModel(models.Model):
name = models.CharField(max_length=100)
JOHN = ModelInstance(name='John')
FRED = ModelInstance(name='Fred')
```
`JOHN` and `FRED` are lazily evaluated model instances obtained for specific query params (`name=value`). I assume that the queries evaluate to unique rows in the table.
To use it, you first need to add rows to the database for John and Fred:
```
In [1]: EnumModel.objects.create(name="Fred")
In [2]: EnumModel.objects.create(name="John")
```
Then you can then access the model instances using the class attributes:
```
In [3]: EnumModel.JOHN
Out[3]: <EnumModel: EnumModel object (1)>
In [4]: EnumModel.FRED
Out[4]: <EnumModel: EnumModel object (2)>
``` |
17,382,613 | Is there a way to view the raw http request that a jquery ajax request is sending to the server?
I am seeing different behaviors on some different devices with regards to an ajax request. If I can view the raw http request I might be able to diagnose the issue...This is mostly related to mobile devices so normal tools (fiddler,fire bug, chrome dev tools) are not available.
Thanks | 2013/06/29 | [
"https://Stackoverflow.com/questions/17382613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/223823/"
] | Well, first I would say you're probably safer to refuse the order and tell the user to come back, because you should be doing things like checking stock, price, etc. in your product table before verifying a purchase.
Anyway, this should solve your immediate problem:
```
INSERT IGNORE INTO products (id, name, isDummy) VALUES (10, "TBD", 1); // does nothing if product id 10 already exists
INSERT INTO purchases (fk_productid, buyerName) VALUES (10, "Andreas");
``` | I decided to go with this solution:
>
> INSERT INTO purchases (fk\_productid, buyerName) VALUES ((SELECT id FROM product WHERE id=10 LIMIT 1), "Andreas");
>
>
>
I agree that in production this case should never happen - don't worry, it won't. This was more of a simple description of a larger problem I had. ;-)
Thanks for your ideas before! |
31,668,905 | I'm beginner in android and want show something with this plan:
[](https://i.stack.imgur.com/Fx7bk.png)
and my xml file is this:
```
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout android:id="@+id/container" android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="@+id/ExplainImage"
android:layout_gravity="center"
android:layout_width="fill_parent"
android:layout_height="78dp"
android:src="@drawable/abc_btn_check_material" />
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/MAINLABEL"
android:layout_gravity="center" />
</ScrollView>
</FrameLayout>
</android.support.v4.widget.DrawerLayout>
```
but when run my app,i see like this:
[](https://i.stack.imgur.com/OtE2O.png)
How can i solve that problem?thanks.
i change XML file but so not work!,my complete xml file after change:
```
<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout android:id="@+id/container" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="3" >
<ImageView
android:id="@+id/ExplainImage"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:src="@drawable/abc_btn_check_material" />
<ScrollView
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="2">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/MAINLABEL" />
</ScrollView>
</LinearLayout>
<ListView
android:id="@+id/myLIST"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<fragment android:id="@+id/navigation_drawer"
android:layout_width="@dimen/navigation_drawer_width" android:layout_height="match_parent"
android:layout_gravity="start"
android:name="com.example.nothing.myapplication.NavigationDrawerFragment"
tools:layout="@layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
``` | 2015/07/28 | [
"https://Stackoverflow.com/questions/31668905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4923413/"
] | The 1st figure is your requirement. So i will first answer what would be the best way to achieve your desired result. Using `LinearLayout` instead of `FrameLayout` would be recommended in this case. Then you should use `layout_weight` attribute for your `ImageView` and `TextView` along with `layout_height="0dp"`. Note that `TextView` automatically scrolls vertically so you don't really need `ScrollView`.
Do something like this.
```
<ImageView
android:id="@+id/ExplainImage"
android:layout_gravity="center"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="0.3"
android:src="@drawable/abc_btn_check_material" />
<TextView
android:layout_width="wrap_content"
android:layout_height="0dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/MAINLABEL"
android:layout_weight="0.7"
android:layout_gravity="center" />
```
Refer [this answer](https://stackoverflow.com/a/7220491/2319542) for a better understanding.
So finally you do something like this
```
<LinearLayout
android:id="@+id/lin_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="4"
android:orientation="vertical" >
<ImageView
android:id="@+id/ExplainImage"
android:layout_gravity="center"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:src="@drawable/abc_btn_check_material">
</ImageView>
<TextView
android:layout_width="wrap_content"
android:layout_height="0dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/MAINLABEL"
android:layout_weight="3"
android:layout_gravity="center" />
</LinearLayout>
```
However if your `TextView` doesn't scroll automatically , use `ScrollView` as mentioned in other answers by setting `layout_weight` and `layout_height` attributes. | Replace xml file with this:
```
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent">
<ImageView
android:id="@+id/ExplainImage"
android:layout_gravity="center"
background="color_code"
android:layout_weight="0.3"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:src="@drawable/abc_btn_check_material" />
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="0.7">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/MAINLABEL"
android:layout_gravity="center" />
</ScrollView>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
``` |
31,668,905 | I'm beginner in android and want show something with this plan:
[](https://i.stack.imgur.com/Fx7bk.png)
and my xml file is this:
```
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout android:id="@+id/container" android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="@+id/ExplainImage"
android:layout_gravity="center"
android:layout_width="fill_parent"
android:layout_height="78dp"
android:src="@drawable/abc_btn_check_material" />
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/MAINLABEL"
android:layout_gravity="center" />
</ScrollView>
</FrameLayout>
</android.support.v4.widget.DrawerLayout>
```
but when run my app,i see like this:
[](https://i.stack.imgur.com/OtE2O.png)
How can i solve that problem?thanks.
i change XML file but so not work!,my complete xml file after change:
```
<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout android:id="@+id/container" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="3" >
<ImageView
android:id="@+id/ExplainImage"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:src="@drawable/abc_btn_check_material" />
<ScrollView
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="2">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/MAINLABEL" />
</ScrollView>
</LinearLayout>
<ListView
android:id="@+id/myLIST"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<fragment android:id="@+id/navigation_drawer"
android:layout_width="@dimen/navigation_drawer_width" android:layout_height="match_parent"
android:layout_gravity="start"
android:name="com.example.nothing.myapplication.NavigationDrawerFragment"
tools:layout="@layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
``` | 2015/07/28 | [
"https://Stackoverflow.com/questions/31668905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4923413/"
] | The 1st figure is your requirement. So i will first answer what would be the best way to achieve your desired result. Using `LinearLayout` instead of `FrameLayout` would be recommended in this case. Then you should use `layout_weight` attribute for your `ImageView` and `TextView` along with `layout_height="0dp"`. Note that `TextView` automatically scrolls vertically so you don't really need `ScrollView`.
Do something like this.
```
<ImageView
android:id="@+id/ExplainImage"
android:layout_gravity="center"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="0.3"
android:src="@drawable/abc_btn_check_material" />
<TextView
android:layout_width="wrap_content"
android:layout_height="0dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/MAINLABEL"
android:layout_weight="0.7"
android:layout_gravity="center" />
```
Refer [this answer](https://stackoverflow.com/a/7220491/2319542) for a better understanding.
So finally you do something like this
```
<LinearLayout
android:id="@+id/lin_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="4"
android:orientation="vertical" >
<ImageView
android:id="@+id/ExplainImage"
android:layout_gravity="center"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:src="@drawable/abc_btn_check_material">
</ImageView>
<TextView
android:layout_width="wrap_content"
android:layout_height="0dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/MAINLABEL"
android:layout_weight="3"
android:layout_gravity="center" />
</LinearLayout>
```
However if your `TextView` doesn't scroll automatically , use `ScrollView` as mentioned in other answers by setting `layout_weight` and `layout_height` attributes. | You can use a LinearLayout with weights:
```
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout android:id="@+id/container" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="3" >
<ImageView
android:id="@+id/ExplainImage"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:src="@drawable/abc_btn_check_material" />
<ScrollView
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="2">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/MAINLABEL" />
</ScrollView>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
``` |
31,668,905 | I'm beginner in android and want show something with this plan:
[](https://i.stack.imgur.com/Fx7bk.png)
and my xml file is this:
```
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout android:id="@+id/container" android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="@+id/ExplainImage"
android:layout_gravity="center"
android:layout_width="fill_parent"
android:layout_height="78dp"
android:src="@drawable/abc_btn_check_material" />
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/MAINLABEL"
android:layout_gravity="center" />
</ScrollView>
</FrameLayout>
</android.support.v4.widget.DrawerLayout>
```
but when run my app,i see like this:
[](https://i.stack.imgur.com/OtE2O.png)
How can i solve that problem?thanks.
i change XML file but so not work!,my complete xml file after change:
```
<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout android:id="@+id/container" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="3" >
<ImageView
android:id="@+id/ExplainImage"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:src="@drawable/abc_btn_check_material" />
<ScrollView
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="2">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/MAINLABEL" />
</ScrollView>
</LinearLayout>
<ListView
android:id="@+id/myLIST"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<fragment android:id="@+id/navigation_drawer"
android:layout_width="@dimen/navigation_drawer_width" android:layout_height="match_parent"
android:layout_gravity="start"
android:name="com.example.nothing.myapplication.NavigationDrawerFragment"
tools:layout="@layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
``` | 2015/07/28 | [
"https://Stackoverflow.com/questions/31668905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4923413/"
] | The 1st figure is your requirement. So i will first answer what would be the best way to achieve your desired result. Using `LinearLayout` instead of `FrameLayout` would be recommended in this case. Then you should use `layout_weight` attribute for your `ImageView` and `TextView` along with `layout_height="0dp"`. Note that `TextView` automatically scrolls vertically so you don't really need `ScrollView`.
Do something like this.
```
<ImageView
android:id="@+id/ExplainImage"
android:layout_gravity="center"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="0.3"
android:src="@drawable/abc_btn_check_material" />
<TextView
android:layout_width="wrap_content"
android:layout_height="0dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/MAINLABEL"
android:layout_weight="0.7"
android:layout_gravity="center" />
```
Refer [this answer](https://stackoverflow.com/a/7220491/2319542) for a better understanding.
So finally you do something like this
```
<LinearLayout
android:id="@+id/lin_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="4"
android:orientation="vertical" >
<ImageView
android:id="@+id/ExplainImage"
android:layout_gravity="center"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:src="@drawable/abc_btn_check_material">
</ImageView>
<TextView
android:layout_width="wrap_content"
android:layout_height="0dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/MAINLABEL"
android:layout_weight="3"
android:layout_gravity="center" />
</LinearLayout>
```
However if your `TextView` doesn't scroll automatically , use `ScrollView` as mentioned in other answers by setting `layout_weight` and `layout_height` attributes. | Try this :
```
<LinearLayout
android:id="@+id/ll"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="5"
android:orientation="vertical" >
<ImageView
android:layout_height="0dp"
android:layout_width="fill_parent"
android:layout_weight="1.5">
</ImageView>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="3.5"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/MAINLABEL"
android:layout_gravity="center" />
</ScrollView>
</LinearLayout>
```
[](https://i.stack.imgur.com/JCe9R.png) |
31,668,905 | I'm beginner in android and want show something with this plan:
[](https://i.stack.imgur.com/Fx7bk.png)
and my xml file is this:
```
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout android:id="@+id/container" android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="@+id/ExplainImage"
android:layout_gravity="center"
android:layout_width="fill_parent"
android:layout_height="78dp"
android:src="@drawable/abc_btn_check_material" />
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/MAINLABEL"
android:layout_gravity="center" />
</ScrollView>
</FrameLayout>
</android.support.v4.widget.DrawerLayout>
```
but when run my app,i see like this:
[](https://i.stack.imgur.com/OtE2O.png)
How can i solve that problem?thanks.
i change XML file but so not work!,my complete xml file after change:
```
<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout android:id="@+id/container" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="3" >
<ImageView
android:id="@+id/ExplainImage"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:src="@drawable/abc_btn_check_material" />
<ScrollView
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="2">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/MAINLABEL" />
</ScrollView>
</LinearLayout>
<ListView
android:id="@+id/myLIST"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<fragment android:id="@+id/navigation_drawer"
android:layout_width="@dimen/navigation_drawer_width" android:layout_height="match_parent"
android:layout_gravity="start"
android:name="com.example.nothing.myapplication.NavigationDrawerFragment"
tools:layout="@layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
``` | 2015/07/28 | [
"https://Stackoverflow.com/questions/31668905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4923413/"
] | The 1st figure is your requirement. So i will first answer what would be the best way to achieve your desired result. Using `LinearLayout` instead of `FrameLayout` would be recommended in this case. Then you should use `layout_weight` attribute for your `ImageView` and `TextView` along with `layout_height="0dp"`. Note that `TextView` automatically scrolls vertically so you don't really need `ScrollView`.
Do something like this.
```
<ImageView
android:id="@+id/ExplainImage"
android:layout_gravity="center"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="0.3"
android:src="@drawable/abc_btn_check_material" />
<TextView
android:layout_width="wrap_content"
android:layout_height="0dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/MAINLABEL"
android:layout_weight="0.7"
android:layout_gravity="center" />
```
Refer [this answer](https://stackoverflow.com/a/7220491/2319542) for a better understanding.
So finally you do something like this
```
<LinearLayout
android:id="@+id/lin_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="4"
android:orientation="vertical" >
<ImageView
android:id="@+id/ExplainImage"
android:layout_gravity="center"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:src="@drawable/abc_btn_check_material">
</ImageView>
<TextView
android:layout_width="wrap_content"
android:layout_height="0dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/MAINLABEL"
android:layout_weight="3"
android:layout_gravity="center" />
</LinearLayout>
```
However if your `TextView` doesn't scroll automatically , use `ScrollView` as mentioned in other answers by setting `layout_weight` and `layout_height` attributes. | You can try this one as I am able to get proper output as you needed.
```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:weightSum="1">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.3"
android:background="@color/blue">
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="@drawable/ic_launcher" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.7"
android:background="@color/orange">
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:text="TestView" />
</LinearLayout>
``` |
8,052,663 | We're attempting to upgrade our site from framework 3.5 to 4.0. Everything appears to be fine server side - My only problem so far is the IDs of a handful of custom controls.
The Controls deceleration looks like:
```
<div runat="server" id="gglSelectedItemsImage" class="gplSelectedItemsText">None selected</div>
```
When rendered in 3.5 the control looks like:
```
<div id="gplCategories_gglSelectedItemsImage" class="gplSelectedItemsText">Some Content</div>
```
And in 4.0 Like:
```
<div id="ctl00_ctl00_ctl00_ContentPlaceHolder1_Content_gplCategories_gglSelectedItemsImage" class="gplSelectedItemsText">Some Content</div>
```
This is causing some of our older JavaScript/JQuery to fail.
I've set `<pages clientIDMode="AutoID" controlRenderingCompatibilityVersion="3.5" />` in the web.config so 99.9% of the IDs are correct. The weirdest thing is the 3.5 control looks like it rendering with `clientIDMode="Predictable"` rather than the standard 3.5 auto IDs?
Furthermore if I access the controls clientID Server side in 4.0 it appears correct:
```
Me.gglSelectedItemsImage.ClientID = "gplCategories_gglSelectedItemsImage"
```
This is the main problem, any values inserted into the JavaScript ect are actually the wrong values.
Our site is unfortunately to large to just fix this one error so I need to work out why the control is rendering its ID differently and implement it across the site.
Any idea's you guys have will be very much appreciated. | 2011/11/08 | [
"https://Stackoverflow.com/questions/8052663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/693342/"
] | Try this
```
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
``` | You should access the client id's like this in your .ASPX file:
```
<%=gglSelectedItemsImage.ClientID%>
``` |
8,052,663 | We're attempting to upgrade our site from framework 3.5 to 4.0. Everything appears to be fine server side - My only problem so far is the IDs of a handful of custom controls.
The Controls deceleration looks like:
```
<div runat="server" id="gglSelectedItemsImage" class="gplSelectedItemsText">None selected</div>
```
When rendered in 3.5 the control looks like:
```
<div id="gplCategories_gglSelectedItemsImage" class="gplSelectedItemsText">Some Content</div>
```
And in 4.0 Like:
```
<div id="ctl00_ctl00_ctl00_ContentPlaceHolder1_Content_gplCategories_gglSelectedItemsImage" class="gplSelectedItemsText">Some Content</div>
```
This is causing some of our older JavaScript/JQuery to fail.
I've set `<pages clientIDMode="AutoID" controlRenderingCompatibilityVersion="3.5" />` in the web.config so 99.9% of the IDs are correct. The weirdest thing is the 3.5 control looks like it rendering with `clientIDMode="Predictable"` rather than the standard 3.5 auto IDs?
Furthermore if I access the controls clientID Server side in 4.0 it appears correct:
```
Me.gglSelectedItemsImage.ClientID = "gplCategories_gglSelectedItemsImage"
```
This is the main problem, any values inserted into the JavaScript ect are actually the wrong values.
Our site is unfortunately to large to just fix this one error so I need to work out why the control is rendering its ID differently and implement it across the site.
Any idea's you guys have will be very much appreciated. | 2011/11/08 | [
"https://Stackoverflow.com/questions/8052663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/693342/"
] | In the second example you're using a master page, which explains why the `ClientID` is different. It shouldn't make a difference though if you're referencing the control by `ClientID`:
```
var ctrl = $("#<%=gglSelectedItemsImage.ClientID%>");
``` | You should access the client id's like this in your .ASPX file:
```
<%=gglSelectedItemsImage.ClientID%>
``` |
55,727,212 | 1. How i can undo a command in jupyter notebook, let suppose in the provided code i treated outliers in my `data['age']` column by replacing them by a value 72 for all the outliers which lies beyond 72 (as shown in the below code). But after few more finding i thought it would be appropriate if i replace values which is beyond 75 not 72 in 'age' column. how can i retrieve my data back as i have already ran few more commands after this line?
2. if accidentally i deleted a column in my data and saved it as in the same variable data(as shown in below code for column 'customer ID'), then how can i get it back? as i have already ran many commands after deleting the column.
```
#1
data[(data['age']>72)]==72
```
```
#2
data=data.drop(columns='customer ID',axis=1)
``` | 2019/04/17 | [
"https://Stackoverflow.com/questions/55727212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11373628/"
] | You simply can't.
If you overwrite your variable then there is no way to go to a previous state unless you reload your data, run your script up to the point you wish to modify and then run a different command.
In your two examples, you will have to reload `data`. | A very good question, but it seems there isn't anyway to undo an executed command since the machine has already learned the command which you mistakenly executed.
```
Wished if there was a way like erasing the events in memory, as in the move men in black!!
The only way around for now is to reload the data back to machine, making it learning the data again.
``` |
62,900,752 | I'm trying to check if my forEach loop is not at the last index so I can separate the numbers with commas. Currently it still uses a comma on the last number which I don't want.
```
const repeatNums = function(data) {
let ans = '';
data.forEach(function(item, index, arrsy) {
ans += item[0].toString().repeat(item[1]);
if (index !== -1) {
ans += ', '
}
});
return ans;
};
``` | 2020/07/14 | [
"https://Stackoverflow.com/questions/62900752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6775809/"
] | You should use `map` and then `join` instead, which handles that for you.
```
return data.map(([first,second])=>first.toString().repeat(second)).join(', ');
```
Your current code is wrong because the index can never be negative; the last index of the array is one less than its length, as arrays are zero-indexed.
```
data.forEach(function(item, index, array){
ans += item[0].toString().repeat(item[1]);
if(index !== array.length - 1){
ans += ', '
}
});
``` | You can just check the `index` argument in the loop to see if it is one less than `arrsy.length`.
Or, you could just use [`Array.join()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join):
```js
let ary = ["A","B","C","D"];
console.log(ary.join(","));
``` |
62,900,752 | I'm trying to check if my forEach loop is not at the last index so I can separate the numbers with commas. Currently it still uses a comma on the last number which I don't want.
```
const repeatNums = function(data) {
let ans = '';
data.forEach(function(item, index, arrsy) {
ans += item[0].toString().repeat(item[1]);
if (index !== -1) {
ans += ', '
}
});
return ans;
};
``` | 2020/07/14 | [
"https://Stackoverflow.com/questions/62900752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6775809/"
] | You should use `map` and then `join` instead, which handles that for you.
```
return data.map(([first,second])=>first.toString().repeat(second)).join(', ');
```
Your current code is wrong because the index can never be negative; the last index of the array is one less than its length, as arrays are zero-indexed.
```
data.forEach(function(item, index, array){
ans += item[0].toString().repeat(item[1]);
if(index !== array.length - 1){
ans += ', '
}
});
``` | Maybe this helps
```js
let arr = [1, 2, 3];
let joined = arr.join(', ');
console.log(joined);
``` |
62,900,752 | I'm trying to check if my forEach loop is not at the last index so I can separate the numbers with commas. Currently it still uses a comma on the last number which I don't want.
```
const repeatNums = function(data) {
let ans = '';
data.forEach(function(item, index, arrsy) {
ans += item[0].toString().repeat(item[1]);
if (index !== -1) {
ans += ', '
}
});
return ans;
};
``` | 2020/07/14 | [
"https://Stackoverflow.com/questions/62900752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6775809/"
] | You should use `map` and then `join` instead, which handles that for you.
```
return data.map(([first,second])=>first.toString().repeat(second)).join(', ');
```
Your current code is wrong because the index can never be negative; the last index of the array is one less than its length, as arrays are zero-indexed.
```
data.forEach(function(item, index, array){
ans += item[0].toString().repeat(item[1]);
if(index !== array.length - 1){
ans += ', '
}
});
``` | Just modify your function like this:
```
const repeatNums = function(data) {
let ans = '';
data.forEach(function(item, index, arrsy) {
ans += item[0].toString().repeat(item[1]);
if (index !== arrsy.length -1) {
ans += ', '
}
});
return ans;
};
``` |
16,452,394 | I have a quicktime object i am reading with av foundation.
I can see it's tracks and I would like to be able to read the 'tmcd' track (timecode) and get it's output as a string i can use in an NSTextView.
With an NSLog and a [track formatDescriptions] i see:
{\n\tmediaType:'tmcd' \n\tmediaSubType:'tmcd' \n\tmediaSpecific: {\n\t\tframeDuration: {1001/24000 = 0.042}\t\tframes/sec: 24\t\ttcFlags: 0 \n\t} \n\textensions: {{type = immutable dict, count = 1,\nentries =>\n\t1 : {contents = \"VerbatimSampleDescription\"} = {length = 38, capacity = 38, bytes = 0x00000026746d63640000000000000001 ... 03e918d400000000}\n}\n}\n}"
)
I can can see there is a lot of information in there, but I wonder how I can use this.
Is this something I can pull apart with other AV Foundation tools or do I need to break it apart somehow?
Basically I would like to end up with a format such as "00:12:23:12"
Thanks!
Adam | 2013/05/09 | [
"https://Stackoverflow.com/questions/16452394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/668846/"
] | Try using [avfprobe](https://github.com/mself/avfprobe). It will decode all of the track info for you, including the `CMFormatDescription` that you mentioned in your question. You'll see something like this:
```
formatDescriptions = [
{
mediaType = kCMMediaType_TimeCode; // = 'tmcd'
mediaSubType = 'tmcd';
extensions = {
VerbatimSampleDescription = <00000022 746d6364 00000000 00000001 00000000 00000002 0000ea60 000003e9 3c00>;
};
},
];
```
However, this is just info about the timecode track -- not the contents of the track. I also don't have any more information about the contents of the `VerbatimSampleDescription` property. | You could try this:
```
NSArray* arrFormat = [tTrack formatDescriptions];
NSInteger nCountArr = [arrFormat count];
CMTimeCodeFormatDescriptionRef refCmFormat = (__bridge CMTimeCodeFormatDescriptionRef)(arrFormat[0]);
NSDictionary* dictFormat = (__bridge NSDictionary *)(refCmFormat);
NSLog(@"format[%ld] = %@", nCountArr, dictFormat);
```
In **dictFormat** you get keys and values for your not well readable **formatDescriptions** string abobe. Then have a look, what keys/values you need... |
65,057,140 | I have been doing a course on intermediate machine learning from Kaggle. In the explanation, in order to label categorical data they have used `LabelEncoder` library from sklearn.preprocessing.

Here, for training dataset they have used fit\_transform and for validadtion dataset they have used only transform, why is it so?
Also, while dealing with null values, in training dataset they have used fit\_transform and for validation dataset they have used transform.

So what is the difference between fit\_transform and transform and what circumstances they can be used? | 2020/11/29 | [
"https://Stackoverflow.com/questions/65057140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10304159/"
] | fit\_transform both fits the transformer to the dataset and also transforms the given data.
Transform just transforms the given dataset.
Generally you use fit\_transform on the training dataset to both fit the transformer to the dataset and transform your dataset.
On your testing and validation dataset you only want to transform your dataset. This is because you want to avoid any possible data leakage. You want your testing set to have never been seen by the model you are creating in any form. One form would be influencing on how you are prepossessing the dataset.
The default replace for simple inputer which is what is used in the example is to replace with the mean. By fitting to only the train dataset you avoid any possibility that dataset from the test set influences the mean of the inputer and leaks information. | We use fit in creating machine learning models,but fit\_transform is used whenever we want
to fit the data as well as transforming those values.
For ex - In case of Label Encoding and Feature Scaling we want to change or scale our values. So whenever we want to transform the values we use fit\_transform.
But We don't use fit\_transform for validation data because of two problems:
```
1)Data Leakage,
2)Overfitting
```
We can explain those two with an simple example-
It is like a leakage of question paper.If we seen the question paper then there is no
point of having exams.Likely If we fit test data, then entire data is known by the model
i.e "Data Leakage" which may leads to "Overfitting" that means we can do well incase of
leaked question paper but what happens if principal changes question paper then we fail
in test. |
693,765 | I am new to the Ubuntu. I tried to install `pycharm-community-5.0.tar.gz` with following command:
```
tar -xzf pycharm-community-5.0.tar.gz
cd pycharm-community-5.0
./configure
```
it says
```
./configure: No such file or directory
``` | 2015/11/04 | [
"https://askubuntu.com/questions/693765",
"https://askubuntu.com",
"https://askubuntu.com/users/461499/"
] | Use the below two options for installing pycharm in Ubuntu:
1. ```
sudo add-apt-repository ppa:mystic-mirage/pycharm
sudo apt-get update
sudo apt-get install pycharm
```
2. Follow the steps mentioned in this [link](http://exponential.io/blog/2015/02/10/install-pycharm-on-ubuntu-linux/) | The archive `pycharm-community-5.0.tar.gz` doesn't contain a `configure`. Extract the archive and run PyCharm
```
sudo tar xf pycharm-community-5.0.tar.gz -C /opt
/opt/pycharm-community-5.0/bin/pycharm.sh
```
For a better integration in your desktop, create a desktop file:
```
nano ~/.local/share/applications/pycharm.desktop
```
and add the configuration below
```
[Desktop Entry]
Version=1.0
Name=PyCharm
Exec=/opt/bin/pycharm.sh
Icon=/opt/bin/pycharm.png
Terminal=false
Type=Application
Categories=Application;Development;
Keywords=ide;python;charm;
``` |
582,918 | I am trying to use StructureMap and have essentially 3 levels of abstraction. I have a service a repository and database interface. So the IService depends on IRepo and IRepo depends on IDatabase. My issue is that my IDatabase concrete type takes in db connection information. I am going to create these on the fly, trying to use ObjectFactory.Configure().
So I have a user and the user is linked to a company and the I lookup the company connection information and I want to create the proper IDatabase concrete type based on this information. I have the concrete type configured in my startup code. I only want to use the IService object from outside...so I want to create a named IService object named with the company Name. Having issues with trying to create these types on the fly. ANY information would be helpfull...
I basically want to be able to create a named instance and either set properties or pass specific args to a constructor at runtime, without knowing the concrete type. I have the concrete type setup in the config file. I have tried to use the ObjectFactory.GetInstance and tried to set properties inside the Configure method, but got StackOverflow exception...HOW IRONIC | 2009/02/24 | [
"https://Stackoverflow.com/questions/582918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11907/"
] | The old adage is this.
>
> When you use a spreadsheet to solve a problem, you now have two problems.
>
>
>
Database is for records of the business. Long-lasting. Permanent.
Other configuration files are for other configuration information -- not long-lasting business records. Current settings and what-not are not enduring business records, they're part of a specific software configuration that processes the business records.
Spreadsheets are -- well -- they are what they are. Too complex to be a simple, configuration file. Too simple to be a real database.
Since they're (almost) impossible to control, you need one standard, correct, idempotent result in the database. You should be able to rebuild spreadsheets from that controlled source.
Similarly, if you accept a spreadsheet for upload, you have to extract the data, and never refer back to the (almost uncontrollable) source document again. | For me, I want all of the core data to be stored in a database. Two reasons:
* to allow adhoc reporting access to the data
* to allow applications to share data.
Databases should contain all of the domain data, and occasionally some on-the-fly data (user preferences for example). Relational databases are most popular, but for some apps there are other options.
The config file on the other hand should contain all of the 'parameters' you want to change in the system; the ones that are not changed rapidly (on-the-fly). Config items are flexible, but not easily, and usually not from the interface. If it's a param that you only want the coder to possibly change, that should be right in the code (so no one else has access).
If you want to fiddle with data mining, provide some generic mechanism to download a CSV file with the results of a SQL query, directly into Excel. That way people can fiddle with pivot tables, without having to alter the application's schema. |
582,918 | I am trying to use StructureMap and have essentially 3 levels of abstraction. I have a service a repository and database interface. So the IService depends on IRepo and IRepo depends on IDatabase. My issue is that my IDatabase concrete type takes in db connection information. I am going to create these on the fly, trying to use ObjectFactory.Configure().
So I have a user and the user is linked to a company and the I lookup the company connection information and I want to create the proper IDatabase concrete type based on this information. I have the concrete type configured in my startup code. I only want to use the IService object from outside...so I want to create a named IService object named with the company Name. Having issues with trying to create these types on the fly. ANY information would be helpfull...
I basically want to be able to create a named instance and either set properties or pass specific args to a constructor at runtime, without knowing the concrete type. I have the concrete type setup in the config file. I have tried to use the ObjectFactory.GetInstance and tried to set properties inside the Configure method, but got StackOverflow exception...HOW IRONIC | 2009/02/24 | [
"https://Stackoverflow.com/questions/582918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11907/"
] | The old adage is this.
>
> When you use a spreadsheet to solve a problem, you now have two problems.
>
>
>
Database is for records of the business. Long-lasting. Permanent.
Other configuration files are for other configuration information -- not long-lasting business records. Current settings and what-not are not enduring business records, they're part of a specific software configuration that processes the business records.
Spreadsheets are -- well -- they are what they are. Too complex to be a simple, configuration file. Too simple to be a real database.
Since they're (almost) impossible to control, you need one standard, correct, idempotent result in the database. You should be able to rebuild spreadsheets from that controlled source.
Similarly, if you accept a spreadsheet for upload, you have to extract the data, and never refer back to the (almost uncontrollable) source document again. | Spreadsheets are documents, databases are repositories for information, configuration files store rules for how a specific instance of an application should behave. If you think of it that way, it's usually not hard to make a call. |
2,346,606 | I am trying to build an iPhone application that has a Tab bar as the root controller and several navigation bars. My doubt is, shall I create one NavigationBarController class for each navigation bar that I want to put in the application? Or is it possible to create only a single navigation controller that manages all the navigation bar controllers that exist in the application?
In the case that multiple navigation controllers exist in the application, can I use the "self" to access the correct navigation controller that pushes/pops the view? Or should I use the delegate of the Application delegate to access each navigation bar controllers?
(I am assuming that all navigation bar controllers are declared in the application delegate, is this approach correct or is there a more elegant approach?)
Thanks a lot in advance | 2010/02/27 | [
"https://Stackoverflow.com/questions/2346606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/236650/"
] | The common way to achieve this is to create a Tab Bar application and then change each item in the tab bar to be a UINavigationController. If you do this, you can definitely use self to access the navigationController - specifically you can use `self.navigationController`. | Insert a unique `UINavigationController` for each tab.
You can't have a single controller manage across multiple tabs, since a navigation controller can only have a single linear stack of view controllers. Each tab should have it's own navigation controller with a different root controller in each one. |
2,346,606 | I am trying to build an iPhone application that has a Tab bar as the root controller and several navigation bars. My doubt is, shall I create one NavigationBarController class for each navigation bar that I want to put in the application? Or is it possible to create only a single navigation controller that manages all the navigation bar controllers that exist in the application?
In the case that multiple navigation controllers exist in the application, can I use the "self" to access the correct navigation controller that pushes/pops the view? Or should I use the delegate of the Application delegate to access each navigation bar controllers?
(I am assuming that all navigation bar controllers are declared in the application delegate, is this approach correct or is there a more elegant approach?)
Thanks a lot in advance | 2010/02/27 | [
"https://Stackoverflow.com/questions/2346606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/236650/"
] | The common way to achieve this is to create a Tab Bar application and then change each item in the tab bar to be a UINavigationController. If you do this, you can definitely use self to access the navigationController - specifically you can use `self.navigationController`. | Watch out for possible leak in this part of the above code:
```
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:tools];
```
You could use this instead:
```
UIBarButtonItem* rightButtonBar = [[UIBarButtonItem alloc] initWithCustomView:tools];
self.navigationItem.rightBarButtonItem = rightButtonBar;
[rightButtonBar release];
```
;) ... or use autorelease |
2,346,606 | I am trying to build an iPhone application that has a Tab bar as the root controller and several navigation bars. My doubt is, shall I create one NavigationBarController class for each navigation bar that I want to put in the application? Or is it possible to create only a single navigation controller that manages all the navigation bar controllers that exist in the application?
In the case that multiple navigation controllers exist in the application, can I use the "self" to access the correct navigation controller that pushes/pops the view? Or should I use the delegate of the Application delegate to access each navigation bar controllers?
(I am assuming that all navigation bar controllers are declared in the application delegate, is this approach correct or is there a more elegant approach?)
Thanks a lot in advance | 2010/02/27 | [
"https://Stackoverflow.com/questions/2346606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/236650/"
] | The common way to achieve this is to create a Tab Bar application and then change each item in the tab bar to be a UINavigationController. If you do this, you can definitely use self to access the navigationController - specifically you can use `self.navigationController`. | >
> The common way to achieve this is to create a Tab Bar application and
> then change each item in the tab bar to be a UINavigationController.
>
>
>
This is THE way of achieving this. I have loaded 5 navigation controllers into a tab bar controllor. The key tip is to plan the navigations of the App, as every navController should take place where a new navigation tree starts. |
2,346,606 | I am trying to build an iPhone application that has a Tab bar as the root controller and several navigation bars. My doubt is, shall I create one NavigationBarController class for each navigation bar that I want to put in the application? Or is it possible to create only a single navigation controller that manages all the navigation bar controllers that exist in the application?
In the case that multiple navigation controllers exist in the application, can I use the "self" to access the correct navigation controller that pushes/pops the view? Or should I use the delegate of the Application delegate to access each navigation bar controllers?
(I am assuming that all navigation bar controllers are declared in the application delegate, is this approach correct or is there a more elegant approach?)
Thanks a lot in advance | 2010/02/27 | [
"https://Stackoverflow.com/questions/2346606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/236650/"
] | Watch out for possible leak in this part of the above code:
```
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:tools];
```
You could use this instead:
```
UIBarButtonItem* rightButtonBar = [[UIBarButtonItem alloc] initWithCustomView:tools];
self.navigationItem.rightBarButtonItem = rightButtonBar;
[rightButtonBar release];
```
;) ... or use autorelease | Insert a unique `UINavigationController` for each tab.
You can't have a single controller manage across multiple tabs, since a navigation controller can only have a single linear stack of view controllers. Each tab should have it's own navigation controller with a different root controller in each one. |
2,346,606 | I am trying to build an iPhone application that has a Tab bar as the root controller and several navigation bars. My doubt is, shall I create one NavigationBarController class for each navigation bar that I want to put in the application? Or is it possible to create only a single navigation controller that manages all the navigation bar controllers that exist in the application?
In the case that multiple navigation controllers exist in the application, can I use the "self" to access the correct navigation controller that pushes/pops the view? Or should I use the delegate of the Application delegate to access each navigation bar controllers?
(I am assuming that all navigation bar controllers are declared in the application delegate, is this approach correct or is there a more elegant approach?)
Thanks a lot in advance | 2010/02/27 | [
"https://Stackoverflow.com/questions/2346606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/236650/"
] | Watch out for possible leak in this part of the above code:
```
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:tools];
```
You could use this instead:
```
UIBarButtonItem* rightButtonBar = [[UIBarButtonItem alloc] initWithCustomView:tools];
self.navigationItem.rightBarButtonItem = rightButtonBar;
[rightButtonBar release];
```
;) ... or use autorelease | >
> The common way to achieve this is to create a Tab Bar application and
> then change each item in the tab bar to be a UINavigationController.
>
>
>
This is THE way of achieving this. I have loaded 5 navigation controllers into a tab bar controllor. The key tip is to plan the navigations of the App, as every navController should take place where a new navigation tree starts. |
116,883 | I think I need some help as I run out of ideas.
In my database I have a simple table like this:
```
CREATE TABLE dbo.Invoices
(
CashDiscounts MONEY,
Cost MONEY
)
GO
```
and a stored procedure that uses this table in SELECT context:
```
CREATE PROCEDURE Reporting.pLoadTest
AS
BEGIN
CREATE TABLE #t ( Test INT );
SELECT
Invoice.[CashDiscounts] AS [CashDiscounts]
, Invoice.[Cost] AS [Cost]
FROM dbo.Invoices AS Invoice
LEFT OUTER JOIN #t -- if you remove this join, dm_sql_referenced_entities should return also CashDiscounts and Cost attributes
ON 1=1
END
GO
```
Now, the problem I got is following: I am using system function **sys.dm\_sql\_referenced\_entities** to get list of columns used by *Reporting.pLoadTest.*
```
SELECT *
FROM sys.dm_sql_referenced_entities ('Reporting.pLoadTest', 'OBJECT')
```
I expect the results of this function to be:
1. dbo.Invoices
2. dbo.Invoices.CashDiscounts
3. dbo.Invoices.Cost
However, when I do a join to temp #t table function **sys.dm\_sql\_referenced\_entities** returns only
1. dbo.Invoices
Everything in this case works fine if I use table variable instead of temp table. I tried to fiddle with permissions for tempdb as written in documentation
>
> Requires SELECT permission on sys.dm\_sql\_referenced\_entities and VIEW
> DEFINITION permission on the referencing entity.
>
>
>
but with no positive result.
What should I do to get correct results of columns being used by a stored procedure that do a select and a join to temp table? | 2015/10/03 | [
"https://dba.stackexchange.com/questions/116883",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/77399/"
] | This is a bug in SQL Server and here is a Connect item to vote for if you want a change.
[dm\_sql\_referenced\_entities does not shows columnes when temporary tables are used in statement](https://connect.microsoft.com/SQLServer/feedback/details/489390/dm-sql-referenced-entities-does-not-shows-columnes-when-temporary-tables-are-used-in-statement)
Current status:
>
> We believe it is unlikely that we will address this suggestion, and so
> we are closing it as “won’t fix”.
>
>
> | Thanks for the answer. Just before I posted a question here I did a search Microsoft Connect bug list however nothing came up here and I used dm\_sql\_referenced\_entities as keyword. I've posted the same bug and that's available at <https://connect.microsoft.com/SQLServer/feedback/details/1859356>.
Let's say I understand Microsoft policy about that. I wonder however if there is a way to modify and maybe fix sys.dm\_sql\_referenced\_entities function at least on my local instance of SQL Server? |
6,393,157 | I have a class called Regions and another class I will call Area. In the main class Area, I need to have an array of Region class objects.
Here is my region class:
```
class Region
{
public:
// Constructor
Region();
// Get/set functions
bool getPoly() {return poly;}
bool setPoly(bool value) {poly = value;}
long getMesh() {return mesh;}
void setMesh(long value) {mesh = value;}
long getVisibleNum() {return visibleNum;}
void setVisibleNum(long value) {visibleNum = value;}
// Visibility vector
void reserveSpace();
long addVisibleRegion(int region);
long getSize(){return visibility.size();}
friend class Area;
private:
bool poly; // Does the region have polygons?
long mesh; // The reference to a 0x36 mesh
long visibleNum; // The number of visible regions
};
```
Now in my area class, I am trying to declare something like this
:
```
class Area
{
public: // Some public class functions
private:
Region* regionArray; // this should be pointers to an array of class objects
}
```
In the Area class constructor, I will allocate the number of class objects I want.
I am getting this error:
```
error C2143: syntax error : missing ';' before '*'
error C4430: missing type specifier - int assumed.
Note: C++ does not support default-int
```
So I assume I am not setting it up correctly. It worked perfectly when Region was a struct but now that it is a class, I assume I am doing something wrong. | 2011/06/18 | [
"https://Stackoverflow.com/questions/6393157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/804132/"
] | Yes it is possible - do you have the classes defined in the same file? It sounds like they might be in separate files and you haven't included the header file for `Region` in the `Area` file.
Edit: Also, you have getter functions for the data in `Region`, so there is no need to make `Area` a friend of `Region`. I would also replace `Region* regionArray` with `std::vector<Region> regionArray`, so the memory is all managed for me. | Other common problem is the `friend class Area;` declaration inside the class without a forward declaration first (I'm almost sure this is the case, are you using GCC?)
In Region.h
```
class Area; // <- this is a forward declaration
clasee Region {
...
friend class Area;
};
```
Regards |
6,393,157 | I have a class called Regions and another class I will call Area. In the main class Area, I need to have an array of Region class objects.
Here is my region class:
```
class Region
{
public:
// Constructor
Region();
// Get/set functions
bool getPoly() {return poly;}
bool setPoly(bool value) {poly = value;}
long getMesh() {return mesh;}
void setMesh(long value) {mesh = value;}
long getVisibleNum() {return visibleNum;}
void setVisibleNum(long value) {visibleNum = value;}
// Visibility vector
void reserveSpace();
long addVisibleRegion(int region);
long getSize(){return visibility.size();}
friend class Area;
private:
bool poly; // Does the region have polygons?
long mesh; // The reference to a 0x36 mesh
long visibleNum; // The number of visible regions
};
```
Now in my area class, I am trying to declare something like this
:
```
class Area
{
public: // Some public class functions
private:
Region* regionArray; // this should be pointers to an array of class objects
}
```
In the Area class constructor, I will allocate the number of class objects I want.
I am getting this error:
```
error C2143: syntax error : missing ';' before '*'
error C4430: missing type specifier - int assumed.
Note: C++ does not support default-int
```
So I assume I am not setting it up correctly. It worked perfectly when Region was a struct but now that it is a class, I assume I am doing something wrong. | 2011/06/18 | [
"https://Stackoverflow.com/questions/6393157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/804132/"
] | It seems to me that the problem is that you are referring to a class you have not yet defined. That is the: `Region* regionArray;` line in the `Area` class.
If this is the case you have to remember to include the header containing the `Region` class in the header file containing the `Area` class. Or add `class Region;` above the `Area` class. | Other common problem is the `friend class Area;` declaration inside the class without a forward declaration first (I'm almost sure this is the case, are you using GCC?)
In Region.h
```
class Area; // <- this is a forward declaration
clasee Region {
...
friend class Area;
};
```
Regards |
6,393,157 | I have a class called Regions and another class I will call Area. In the main class Area, I need to have an array of Region class objects.
Here is my region class:
```
class Region
{
public:
// Constructor
Region();
// Get/set functions
bool getPoly() {return poly;}
bool setPoly(bool value) {poly = value;}
long getMesh() {return mesh;}
void setMesh(long value) {mesh = value;}
long getVisibleNum() {return visibleNum;}
void setVisibleNum(long value) {visibleNum = value;}
// Visibility vector
void reserveSpace();
long addVisibleRegion(int region);
long getSize(){return visibility.size();}
friend class Area;
private:
bool poly; // Does the region have polygons?
long mesh; // The reference to a 0x36 mesh
long visibleNum; // The number of visible regions
};
```
Now in my area class, I am trying to declare something like this
:
```
class Area
{
public: // Some public class functions
private:
Region* regionArray; // this should be pointers to an array of class objects
}
```
In the Area class constructor, I will allocate the number of class objects I want.
I am getting this error:
```
error C2143: syntax error : missing ';' before '*'
error C4430: missing type specifier - int assumed.
Note: C++ does not support default-int
```
So I assume I am not setting it up correctly. It worked perfectly when Region was a struct but now that it is a class, I assume I am doing something wrong. | 2011/06/18 | [
"https://Stackoverflow.com/questions/6393157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/804132/"
] | Yes, that is possible. In your case, the problem isn't array. but (most likely) you've not included some header files in some other files.
By the way, you can use `std::vector` as well, which in my opinion would be a better choice, in comparison to raw pointer.
```
#include <vector>
#include "Region.h" //must include these two
class Area
{
public: // Some public class functions
private:
std::vector<Region> regions; //better than raw pointer
};
```
Read about RAII Idiom : [Resource Acquisition Is Initialization](http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization) | Other common problem is the `friend class Area;` declaration inside the class without a forward declaration first (I'm almost sure this is the case, are you using GCC?)
In Region.h
```
class Area; // <- this is a forward declaration
clasee Region {
...
friend class Area;
};
```
Regards |
26,664,602 | I'd like to have the application at example.com use In Proc. And all other applications (example.com/app1, example.com/other\_app, etc) use SQL state. Is this possible? I have created distinct application pools for each application. | 2014/10/30 | [
"https://Stackoverflow.com/questions/26664602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3435345/"
] | I added a `<location>` element to all of my web.configs:
```
<location path="." inheritInChildApplications="false" allowOverride="false">
<system.web>
<sessionState />
</system.web>
</location>
```
This seems to keep everything separate now. I can now use "In Proc" in my parent app and "SQL session" in child apps and not lose any session data. (A complex object was lost in the parent app because (I think) it was somehow inheriting the session state from children web.configs.) | Should just work with multiple applications. This setting is per application.
Haven't you tried this? |
17,604,826 | I am trying to do a lesson, learning javascript objects and so forth... I am having a problem with this for in loop and I suppose the object literal itself
```
var darkness = {
add: function(a,b) {
for(var title in b) {
alert(a+ " is the "+ b.title );
alert(a+ " holds many of"+b.dream);
}
}
};
darkness.add('darkness',{
title :'feelings',
dream:'dreams'
});
```
This alerts twice? test <http://jsbin.com/ogunor/1/edit>
Can someone help me learn these a little better | 2013/07/11 | [
"https://Stackoverflow.com/questions/17604826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1760670/"
] | The clause `WHERE spyypp BETWEEN 201305 AND 201305` has the consequence of coercing your join into an INNER JOIN, as it is performed **after** the join is completed.
In order to achieve the effect you desire you must move this clause into the ON condition like this so that the clause is applied **before** the join is:
```
WITH lastYear AS (
SELECT
spsku "sku",
spstor "store",
sum(spales) "sales_ly"
FROM SALES
WHERE spyypp BETWEEN 201205 AND 201205
GROUP BY spstor, spsku
)
SELECT
Sales_report.spstor "store",
sum(spales) "bom_retail",
sum(LY."sales_ly") "sales_ly"
FROM SALES Sales_report
FULL OUTER JOIN lastYear LY
ON LY."sku" = spsku
AND LY."store" = spstor
AND spyypp BETWEEN 201305 AND 201305
GROUP BY spstor
```
Alternatively, which provides clearer code in some circumstance, make both LAST\_YEAR and THIS\_YEAR common table expressions like this:
```
WITH
lastYear AS (
SELECT
spsku "sku",
spstor "store",
sum(spales) "sales_ly"
FROM SALES
WHERE spyypp BETWEEN 201205 AND 201205
GROUP BY spstor, spsku
),
this year as (
SELECT
spsku "sku",
spstor "store",
sum(spales) "sales_ly"
FROM SALES
WHERE spyypp BETWEEN 201305 AND 201305
GROUP BY spstor, spsku
)
SELECT
TY.spstor "store",
sum(TY.spales) "bom_retail",
sum(LY."sales_ly") "sales_ly"
FROM this year TY
FULL OUTER JOIN lastYear LY
ON LY."sku" = TY.sku
AND LY."store" = TY.stor
``` | There seems to be multiple problems. This predicate:
```
WHERE spyypp BETWEEN 201305 AND 201305
```
is probably eliminating some of the "outer joined" rows. Those rows are going to have a NULL for spyypp. (The grouping by spsku is a bit odd, but that may actually not be a problem, you're just going to get separate rows... one total where there were matching spsku, and another row where they weren't, but those are all going to get collapsed buy the GROUP BY, so I don't see the point.
If you want to use common table expressions, I think you want to use two, and do the full outer join on those resultsets. I'd use a function that picks up the non-NULL value for non-matches, the ISNULL function is handy for this.
```
WITH lastYear AS
(
SELECT
spsku,
spstor,
sum(spales) AS sales_ly
FROM SALES
WHERE spyypp BETWEEN 201205 AND 201205
GROUP BY spstor, spsku
)
, thisYear AS (
SELECT
spsku,
spstor,
SUM(spales) AS sales_ty
FROM SALES
WHERE spyypp BETWEEN 201305 AND 201305
GROUP BY spstor, spsku
)
SELECT ISNULL(thisYear.spstor,lastYear.spstor) AS "store"
, SUM(TY.sales_ty) AS "bom_retail"
, SUM(LY.sales_ly) AS "sales_ly"
FROM thisYear TY
FULL
OUTER
JOIN lastYear LY
ON LY.spsku = TY.spsku
AND LY.store = TY.store
GROUP
BY ISNULL(thisYear.spstor,lastYear.spstor)
```
---
If that's the resultset you're after, that seems like a whole lot of unnecessary noise. If you aren't concerned with the spsku being returned, and its a full outer join, then this query would return an equivalent resultset:
```
SELECT r.spstor AS "store"
, SUM(CASE WHEN r.spyypp BETWEEN 201305 AND 201305 THEN r.spsales END) AS "bom_retail"
, SUM(CASE WHEN r.spyypp BETWEEN 201205 AND 201205 THEN r.spsales END) AS "sales_ly"
FROM SALES r
WHERE r.spyypp BETWEEN 201305 AND 201305
OR r.spyypp BETWEEN 201205 AND 201205
GROUP
BY r.spstor
```
The "trick" here is using a conditional test, to determine whether an spsales amount should be included in the SUM or not.
---
If this is actually for MySQL (and not SQL Server), then I'd write it like this:
```
SELECT r.spstor AS `store`
, SUM(IF(r.spyypp BETWEEN 201305 AND 201305,r.spsales,NULL)) AS `bom_retail`
, SUM(IF(r.spyypp BETWEEN 201205 AND 201205,r.spsales,NULL)) AS `sales_ly`
FROM SALES r
WHERE r.spyypp BETWEEN 201305 AND 201305
OR r.spyypp BETWEEN 201205 AND 201205
GROUP
BY r.spstor
``` |
17,604,826 | I am trying to do a lesson, learning javascript objects and so forth... I am having a problem with this for in loop and I suppose the object literal itself
```
var darkness = {
add: function(a,b) {
for(var title in b) {
alert(a+ " is the "+ b.title );
alert(a+ " holds many of"+b.dream);
}
}
};
darkness.add('darkness',{
title :'feelings',
dream:'dreams'
});
```
This alerts twice? test <http://jsbin.com/ogunor/1/edit>
Can someone help me learn these a little better | 2013/07/11 | [
"https://Stackoverflow.com/questions/17604826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1760670/"
] | The clause `WHERE spyypp BETWEEN 201305 AND 201305` has the consequence of coercing your join into an INNER JOIN, as it is performed **after** the join is completed.
In order to achieve the effect you desire you must move this clause into the ON condition like this so that the clause is applied **before** the join is:
```
WITH lastYear AS (
SELECT
spsku "sku",
spstor "store",
sum(spales) "sales_ly"
FROM SALES
WHERE spyypp BETWEEN 201205 AND 201205
GROUP BY spstor, spsku
)
SELECT
Sales_report.spstor "store",
sum(spales) "bom_retail",
sum(LY."sales_ly") "sales_ly"
FROM SALES Sales_report
FULL OUTER JOIN lastYear LY
ON LY."sku" = spsku
AND LY."store" = spstor
AND spyypp BETWEEN 201305 AND 201305
GROUP BY spstor
```
Alternatively, which provides clearer code in some circumstance, make both LAST\_YEAR and THIS\_YEAR common table expressions like this:
```
WITH
lastYear AS (
SELECT
spsku "sku",
spstor "store",
sum(spales) "sales_ly"
FROM SALES
WHERE spyypp BETWEEN 201205 AND 201205
GROUP BY spstor, spsku
),
this year as (
SELECT
spsku "sku",
spstor "store",
sum(spales) "sales_ly"
FROM SALES
WHERE spyypp BETWEEN 201305 AND 201305
GROUP BY spstor, spsku
)
SELECT
TY.spstor "store",
sum(TY.spales) "bom_retail",
sum(LY."sales_ly") "sales_ly"
FROM this year TY
FULL OUTER JOIN lastYear LY
ON LY."sku" = TY.sku
AND LY."store" = TY.stor
``` | Thank you all for you suggestions. I did restructure the SQL to have both this year and last year nested inside a with clause. The fatal flaw I was over looking is sku's that existed only in the Last Year dataset were not being included unless I selected/grouped by sku in the main clause.
To solve the issue, I used the following code below. I separately built the data-sets with placeholders for TY/LY sales. I then performed a UNION to combine tables (TY/LY being stored in different columns, and different rows). I stuffed all that in a sub-query. Because I was summing the data (grouping by non-summed fields), this would collapse all rows so it would properly reflect in the desired format.
```
WITH lastYear AS (
SELECT sku, store, sum(sales) "sales_ly"
FROM DWHLIB.SLSSUMPD
WHERE spyypp BETWEEN 201205 AND 201205
GROUP BY store, sku
),
thisYear AS (
SELECT spsku sku, store, sum(sales) "sales"
FROM DWHLIB.SLSSUMPD
WHERE spyypp BETWEEN 201305 AND 201305
GROUP BY store, sku
)
SELECT sum(AY."sales"), sum(AY."sales_ly"), AY."store"
FROM (
SELECT sum(TY."sales") "sales", 0 "sales_ly", TY."store"
FROM thisYear TY GROUP BY TY."store"
UNION ALL
SELECT 0 "sales", sum(LY."sales_ly") "sales_ly", LY."store"
FROM lastYear LY
GROUP BY LY."store"
) AY
GROUP BY "store"
``` |
5,888,124 | I need to be able to replace all occurrences of the word "and" ONLY when it occurs between single quotes. For example replacing "and" with "XXX" in the string:
`This and that 'with you and me and others' and not 'her and him'`
Results in:
`This and that 'with you XXX me XXX others' and not 'her XXX him'`
I have been able to come up with regular expressions which nearly gets every case, but I'm failing with the "and" between the two sets of quoted text.
My code:
```
String str = "This and that 'with you and me and others' and not 'her and him'";
String patternStr = ".*?\\'.*?(?i:and).*?\\'.*";
Pattern pattern= Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(str);
System.out.println(matcher.matches());
while(matcher.matches()) {
System.out.println("in matcher");
str = str.replaceAll("(?:\\')(.*?)(?i:and)(.*?)(?:\\')", "'$1XXX$2'");
matcher = pattern.matcher(str);
}
System.out.println(str);
``` | 2011/05/04 | [
"https://Stackoverflow.com/questions/5888124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/193278/"
] | Try this code:
```
str = "This and that 'with you and me and others' and not 'her and him'";
Matcher matcher = Pattern.compile("('[^']*?')").matcher(str);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, matcher.group(1).replaceAll("and", "XXX"));
}
matcher.appendTail(sb);
System.out.println("Output: " + sb);
```
### OUTPUT
```
Output: This and that 'with you XXX me XXX others' and not 'her XXX him'
``` | ```
String str = "This and that 'with you and me and others' and not 'her and him'";
Pattern p = Pattern.compile("(\\s+)and(\\s+)(?=[^']*'(?:[^']*+'[^']*+')*+[^']*+$)");
System.out.println(p.matcher(str).replaceAll("$1XXX$2"));
```
The idea is, each time you find the complete word `and`, you you scan from the current match position to the end of the string, looking for an odd number of single-quotes. If the lookahead succeeds, the matched word must be between a pair of quotes.
Of course, this assumes quotes always come in matched pairs, and that quotes can't be escaped. Quotes escaped with backslashes can be dealt with, but it makes the regex much longer.
I'm also assuming the target word never appears at the beginning or end of a quoted sequence, which seems reasonable for the word `and`. If you want to allow for target words that are *not* surrounded by whitespace, you could use something like `"\\band\\b"` instead, but be aware of Java's problems in the area of [word characters vs word boundaries](https://stackoverflow.com/q/4304928/20938). |
332,328 | Which of the following two is more correct? And why? And what is the difference? Both produce identical outputs.
Also, what is the correct place for a `\newcommand` - before `\begin{document}` or after?
Here is the MWE:
```
\documentclass{article}
\newcommand{\Variable}{World}
\begin{document}
Hello \Variable{}! Welcome!!
Hello \Variable! Welcome!!
\end{document}
``` | 2016/10/03 | [
"https://tex.stackexchange.com/questions/332328",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/18495/"
] | A macro -- more specifically, a control word that consists of one or more *letters* -- usually gobbles any space to its right (The exception are the macros with a single non-letter character). This allows the macro to take the next characters as first argument, so `\fbox abc` does the same as `\fbox{a}bc`. Unfortunately, macros without argument also do this, so when you start with LaTeX, sooner or later you realize that `\LaTeX abc` is the same as `\LaTeX{}abc`.
Thus, you must use "`\Variable{}`" or "`\Variable\`" (note the space after the second backslash) to avoid that. If there is no space after the macro but, say, a comma, you can simply write "`\Variable,`". Another option is to use the `xspace` package and include `\xspace` at the end of the macro definition, such that `\Variable` works well in most cases.
The `\newcommand` can be used in the body of the document, in the preamble o even before (above `\documentclass`), but the right place is the preamble as usually you do not want mix format and contents. Moreover, if the macro definition in the middle of text, it is easier to make the mistake of use the macro before of its definition. | Both uses are sufficient in the context you show, since they produce the same result:
[](https://i.stack.imgur.com/OuBVo.png)
However, in a slightly different context - removing the punctuation `!` immediately following the macro use, the results are noticeably different:
[](https://i.stack.imgur.com/oB22V.png)
```
\documentclass{article}
\newcommand{\Variable}{World}
\begin{document}
Hello \Variable{} Welcome!!
Hello \Variable Welcome!!
\end{document}
```
With `{}` the inter-word space is preserved, while it is gobbled when using `\Variable` without `{}`. This is due to the way TeX reads the input stream to identify where a macro ends.
Which is "more correct"? It depends on the context as you can use it - the ending braces `{}` - in some places, but it's not always necessary.
Relevant contents to read:
* [Space after LaTeX commands](https://tex.stackexchange.com/q/31091/5764)
* [Drawbacks of xspace](https://tex.stackexchange.com/q/86565/5764)
---
Technically you can place your `\newcommand` wherever you want. It is better practice to separate document structure from content. Therefore, it is customary to include all command definitions and document formatting content as part of the preamble - between `\documentclass` and `\begin{document}`.
This remains, however, purely a suggestion and depends on the end user. Some people may feel more inclined to keep definitions together with their usage (if the document provides that "flow"), others roll the more conventional way. |
44,218,914 | I have created a simple list getter from rest api:
```
def list: Future[Iterable[ProductResource]] = {
ProductService.listAllProducts.map { postDataList =>
postDataList.map(postData => createProductResource(postData))
}
}
```
It convert product objects into json with this writer:
```
object ProductResource {
implicit val implicitWrites = new Writes[Product] {
def writes(product: Product): JsValue = {
Json.obj(
"id" -> product.id,
"name" -> product.name,
"description" -> product.description,
"price" -> product.price,
"amount" -> product.amount
)
}
}
}
```
but when I compile project I get: `play.sbt.PlayExceptions$CompilationException: Compilation error[Cannot use a method returning scala.concurrent.Future[Iterable[controllers.ProductController.ProductResource]] as a Handler for requests]` which I do not understand how to fix it.
I looked on this tutorial <https://developer.lightbend.com/guides/play-rest-api/part-1/index.html>
and there is similar list function.
**EDIT:**
I updated this function and add an Action:
```
def list: Action[AnyContent] = {
Action.async { implicit request =>
find.map { products =>
Ok(Json.toJson(products))
}
}
}
def find: Future[Iterable[ProductResource]] = {
ProductService.listAllProducts.map { postDataList =>
postDataList.map(postData => createProductResource(postData))
}
}
```
Now I get `No Json serializer found for type Iterable[controllers.ProductController.ProductResource]. Try to implement an implicit Writes or Format for this type.`, but I created a writes. | 2017/05/27 | [
"https://Stackoverflow.com/questions/44218914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4541597/"
] | your controller must return a Future of JsValue (`Future[JsValue]`).
But your are returning Iterable of ProductResource (`Iterable[ProductResource]`).
to convert your Iterable[ProductResource] to JsValue.
* convert each individual ProductResource objects to JsObject
* do a `foldLeft` action to convert the sequence of JsObjects to JsArray.
* make your the implicit JsonWriter that converts `ProductResource` type to JsValue is imported and available in scope. *(The implicitWrites shown in the Question converts Product to a Json. The controller is expecting a JsonWriter for type ProductResource)*
This can be done like the below.
```
import ProductResource.implicitWrites
import play.api.libs.json._
def list: Action[AnyContent] = Action.async {
find
.map(x => Json.toJson(x))
.map(x => x.foldLeft(JsArray())({case (acc, json) => acc :+ json}))
.map(x => Ok(x))
}
``` | Problem fixed my change in `ProdcutResource` object
```
case class ProductResource(id: Option[Long], name: String, description: String, price: BigDecimal, amount: Int)
object ProductResource {
implicit val implicitWrites = new Writes[ProductResource] {
def writes(product: ProductResource): JsValue = {
Json.obj(
"id" -> product.id,
"name" -> product.name,
"description" -> product.description,
"price" -> product.price,
"amount" -> product.amount
)
}
}
}
```
and no errors connected to json appear. |
9,721,790 | As a simplified example, consider a `ListView` that can contain both sub-categories and book titles. If a book title is clicked, a new activity should start that shows the cover image. If a sub-category is clicked, a new list of books and categories is displayed.
A `Row` interface is defined as follows.
```
interface Row {
void onClick();
void draw(View v);
}
```
I would like to know how to prevent a dependency from the `ListView`'s `ArrayAdapter` as well as from the implementer of `onItemClickListener` on the `Row` implementers (e.g.,`Book` and `Category`).
One of the forces driving this requirement is the "don't repeat yourself" (DRY) principle: the `ArrayAdapter` implementation does not need to change when new row types are introduced. | 2012/03/15 | [
"https://Stackoverflow.com/questions/9721790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/403455/"
] | Forgive my chicken-scratched "UML" below, but here's how I do it.
```
class ListAdapter extends ArrayAdapter<Row<?>> {
...
public View getView(int position, View convertView, ViewGroup parent) {
View view = listViewRowViewRecycler.getView(convertView);
rowProvider.get().getRow(position).draw(view);
return view;
}
}
```
The implementer of `OnItemClickListener` has a method like this:
```
void onItemClick(AdapterView<?> adapterView, View view, int rowIndex, long rowId)
{
rowProvider.onItemClick(rowIndex);
}
```
Then `RowProvider` has a method like this:
```
void onItemClick(int rowIndex) {
rowList.get(rowIndex).onClick();
}
```
Then the `Row` interface has a method with signature `void onClick()` and there are `Category` and `Book` implementations of `Row` that provide the necessary behavior.
 | Another possibility is to use the setTag/getTag methods on each item's View in the list - this allows you to attach the 'Book' or 'Category' to its appropriate row.
For this to work each of the 'listed' items should implement a common interface that has an appropriate method to be called when it is clicked.
For instance:
```
interface Selectable {
void onSelected(); // Add parameters if necessary...
}
```
In your list adapter:
```
public View getView(int position, View convertView, ViewGroup parent) {
View itemView; // Logic to get the appropriate view for this row.
Selectable theObjectBeingRepresented;
//
// Logic to assign a Book/Category, etc to theObjectBeingRepresented.
// In this example assume there is a magic Book being represented by
// this row.
//
Book aMagicBook = new Book();
theObjectBeingRepresented = aMagicBook;
// If all objects that will be contained in your list implement the
// 'Selectable' interface then you can simply call setTag(...) with
// the object you are working with (otherwise you may need some conditional logic)
//
itemView.setTag( SELECTABLE_ITEM_KEY, theObjectBeingRepresented );
}
```
Then when an item is clicked:
```
void onItemClick(AdapterView<?> adapterView, View view, int rowIndex, long rowId)
{
Selectable item = (Selectable)view.getTag( SELECTABLE_ITEM_KEY );
// Depending on how you are populating the list, you may need to check for null
// before operating on the item..
if( null != item ) {
item.onClick(); // Appropriate implementation called...
}
}
```
A bit more detail on the setTag method:
[setTag documentation](http://developer.android.com/reference/android/view/View.html#setTag%28int,%20java.lang.Object%29)
Hope this helps... |
3,127,154 | I need to find $\lim\_{n \rightarrow \infty} \left[\int\_{ 0}^{ 1} \frac {(1+x+...+x^{n})^2}{1+x+...+x^{n+1}}dx - \ln (n)\right]$ and my idea is that after using some simplification the integral is equal to $\int\_{0}^{1} \frac{x^{2(n+1)}-2x^{(n+1)}+1}{(x-1)(x^{(n+2)}-1)}dx$ which, because $x$ is smaller than 1, is bigger than $\int\_{0}^{1} 1+x+...+x^{n+1}dx$, which gives $1+\frac{1}{2}+\frac{1}{3}+...+\frac{1}{n+1}$, a sum converging to $\ln(n)$, so I suppose the initial integral converges to $0$ | 2019/02/26 | [
"https://math.stackexchange.com/questions/3127154",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/-1/"
] | Write $f\_n(x) = 1 + x + \cdots + x^n$. Denoting the expression inside the limit by $a\_n$, we find that
$$ a\_n = \int\_{0}^{1} \frac{f\_n(x)^2}{f\_n(x) + x^{n+1}} \, \mathrm{d}x - \log n. $$
We first examine the expression where $\log n$ is replaced by $\int\_{0}^{1} f\_n(x) \mathrm{d}x$. Then
$$ \left| \int\_{0}^{1} \frac{f\_n(x)^2}{f\_n(x) + x^{n+1}} \, \mathrm{d}x - \int\_{0}^{1} f\_n(x) \mathrm{d}x \right|
= \left| - \int\_{0}^{1} \frac{x^{n+1} f\_n(x)}{f\_n(x) + x^{n+1}} \, \mathrm{d}x \right|
\leq \int\_{0}^{1} x^{n+1} \, \mathrm{d}x = \frac{1}{n+2}. $$
Together with $\int\_{0}^{1} f\_n(x) \mathrm{d}x = \sum\_{k=1}^{n+1} \frac{1}{k}$ and $\gamma := \lim\_{n\to\infty} \left( \sum\_{k=1}^{n} \frac{1}{k} - \log n \right) \approx 0.5772\cdots$, we have
$$ a\_n = \int\_{0}^{1} f\_n(x) \mathrm{d}x - \log n + \mathcal{O}(n^{-1}) = \gamma + \mathcal{O}(n^{-1}), $$
which converges to $\gamma$ as $n\to\infty$. | $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
\newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
\newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
\newcommand{\dd}{\mathrm{d}}
\newcommand{\ds}[1]{\displaystyle{#1}}
\newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
\newcommand{\ic}{\mathrm{i}}
\newcommand{\mc}[1]{\mathcal{#1}}
\newcommand{\mrm}[1]{\mathrm{#1}}
\newcommand{\pars}[1]{\left(\,{#1}\,\right)}
\newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
\newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
\newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
\newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
&\bbox[10px,#ffd]{\lim\_{n \to \infty}\bracks{\int\_{0}^{1}
{\pars{1 + x + \cdots + x^{n}}^{\, 2} \over
1 + x + \cdots + x^{n + 1}}\,\dd x - \ln\pars{n}}}
\\[5mm] = &\
\lim\_{n \to \infty}\bracks{\int\_{0}^{1}
{\pars{\sum\_{k = 0}^{n + 1}x^{k} - x^{n +1}}^{\, 2} \over
\sum\_{k = 0}^{n + 1}x^{k}}\,\dd x - \ln\pars{n}}
\\[5mm] = &\
\lim\_{n \to \infty}\bracks{\int\_{0}^{1}
\sum\_{k = 0}^{n + 1}x^{k}\,\dd x - 2\int\_{0}^{1}x^{n +1}\,\dd x +
\int\_{0}^{1}{x^{2n + 2} \over \sum\_{k = 0}^{n + 1}x^{k}}\,\dd x - \ln\pars{n}}
\\[5mm] = &\
\lim\_{n \to \infty}\bracks{H\_{n + 2} - {2 \over n + 2} +
\int\_{0}^{1}{x^{2n + 2} \over \sum\_{k = 0}^{n + 1}x^{k}}\,\dd x - \ln\pars{n}}
\\[2mm] &\ \pars{~H\_{z}\ \mbox{is the}\ Harmonic\ Number~}
\\[5mm] = &\
\lim\_{n \to \infty}\bracks{H\_{n} +
{1 \over \pars{n + 1}\pars{n + 2}} +
\int\_{0}^{1}{x^{2n + 2} \over \sum\_{k = 0}^{n + 1}x^{k}}\,\dd x - \ln\pars{n}}
\\[5mm] = &\
\gamma +
\lim\_{n \to \infty}\int\_{0}^{1}{x^{2n + 2} \over
\sum\_{k = 0}^{n + 1}x^{k}}\,\dd x.\quad
\pars{~\mbox{Note that}\
\gamma = \lim\_{n \to \infty}\bracks{H\_{n} - \ln\pars{n}}~}
\label{1}\tag{1}
\end{align}
>
> $\ds{\gamma}$ is the *Euler-Mascheroni Constant*. Note that
>
>
>
\begin{align}
&\bbox[10px,#ffd]{\int\_{0}^{1}{x^{2n + 2} \over
\sum\_{k = 0}^{n + 1}x^{k}}\,\dd x} =
\int\_{0}^{1}{x^{2n + 2} - x^{2n + 3} \over
1 - x^{n + 2}}\,\dd x =
{1 \over n + 2}\int\_{0}^{1}
{x^{\pars{n + 1}/\pars{n + 2}} - x \over 1 - x}\,\dd x
\\[5mm] = &\
{1 \over n + 2}\bracks{\int\_{0}^{1}\dd x -
\int\_{0}^{1}{1 - x^{\pars{n + 1}/\pars{n + 2}} \over 1 - x}\,\dd x}
\\[5mm] = &\
{1 - H\_{\pars{n +1}/\pars{n + 2}} \over n + 2}
\,\,\,\stackrel{\mrm{as}\ n\ \to\ \infty}{\to}\,\,\,
\color{red}{\large 0}
\end{align}
>
> \eqref{1} becomes
>
>
>
$$
\bbx{\bbox[10px,#ffd]{\lim\_{n \to \infty}\bracks{\int\_{0}^{1}
{\pars{1 + x + \cdots + x^{n}}^{\, 2} \over
1 + x + \cdots + x^{n + 1}}\,\dd x - \ln\pars{n}}} = \gamma}
$$ |
2,550,748 | Is it possible to capture full screen in visual studio (VC++), so that user don't have to press ATL+Enter. Kindly guide me how I can make it possible. | 2010/03/31 | [
"https://Stackoverflow.com/questions/2550748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/67381/"
] | If you need to enter fullscreen mode in OpenGL per default, check out NeHe Productions, for instance his [second lesson](http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=02)
If you download his example at the bottom of the screen and check out the:
`BOOL CreateGLWindow(char* title, int width, int height, int bits, bool **fullscreenflag**)`
.. you will see how it can be made in OpenGL | It depends. If you are using `Direct3D` alt-enter enters full screen mode by default.
If your application is "normal" (ie, not a 3d application) then there is no actual full-screen mode. You can however create the illusion of it by maximizing the window and removing things like the top menu bar. |
39,332,625 | I've been stuck with this compiler error for a while now, my project is a UWP Universal Windows Platform, with Xamarin.Forms 4.1, along with a set of nuget packages, and for some time when enabled the .NET Native tool chain option I get the following error:
>
> C:\Program Files
> (x86)\MSBuild\Microsoft.NetNative\x86\ilc\IlcInternals.targets(936,5):
> error : Internal compiler error: MCG0024:UnresolvableTypeReference
> Unresolvable type reference 'System.Runtime.InteropServices.HandleRef'
> in 'Assembly(Name=mscorlib, Version=4.0.0.0, Culture=neutral,
> PublicKeyToken=b77a5c561934e089)' found. Please check the references
> in your build system. A reference is either missing or an assembly is
> missing an expected type.
>
>
>
I've tried a set of solutions, updating Visual Studio to Update 3, UWP Developer Tools 1.4 with no success, the error remains the same... the only way to get rid of this error is compiling without the .NET Native options, but that's not an a option since we need to need to pass the Windows Certification thing...
Any clues? | 2016/09/05 | [
"https://Stackoverflow.com/questions/39332625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/499989/"
] | The feedback from opencv github seems clear: you compiled with OpenCV 3.x but use OpenCV 2.4.8 at runtime. Since they are not binary compatible, it does not free properly the `cv::Mat`. Let export your `LD_LIBRARY_PATH` to the `OCV_DIST/lib` of OpenCV 3.x used to compile.
Note that if you `delete` the pointer you don't even need to `release()` before. | Quoted the following from the documentation page: (<http://docs.opencv.org/2.4.9/modules/core/doc/basic_structures.html#mat-release>):
*void Mat::release()
The method decrements the reference counter associated with the matrix data. When the reference counter reaches 0, the matrix data is deallocated and the data and the reference counter pointers are set to NULL’s.*
The above means that when you do "delete matrx;" you are trying to delete a memory zone that already points to NULL, which generates a run-time error. |
35,630,237 | My code will show the menu's submenu on hover, now I don't want to run this code if my button is clicked. How can I do this? Both ' subMenuDropDown.preventDefault(); ' and subMenuDropDown.stopPropagation(); don't do the trick.
**JsFiddle**: <https://jsfiddle.net/k4ftf4tx/>
```
$('.menu ul li ul').hide();
$('.menu ul li').hover(function(subMenuDropDown) {
$(this).find("ul").first().stop(true, true).delay(60).slideDown('slow');
}, function() {
$(this).find("ul").first().stop(true, true).delay(60).slideUp('fast');
});
$('.mobileMenuButton').click(function() {
$('.menu').toggle();
subMenuDropDown.preventDefault();
});
```
As you can see on click it will toggle the menu, but on hover it will still slideDown the submenu. | 2016/02/25 | [
"https://Stackoverflow.com/questions/35630237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5804430/"
] | ```js
// Make submenu dropdown on hover
$('.menu ul li ul').hide();
$('.menu ul li').hover(function(subMenuDropDown) {
$(this).find("ul").first().stop(true, true).delay(60).slideDown('slow');
}, function() {
$(this).find("ul").first().stop(true, true).delay(60).slideUp('fast');
});
$('.mobileMenuButton').click(function() {
$('.menu').toggle();
$('.menu ul li').off('mouseenter').off('mouseleave');
});
```
```css
.menu {
display: none;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mobileMenuButton" role="button">
<p>
Menu
</p>
</div>
<div class="menu">
<ul>
<li><a href="">Something</a>
<ul>
<li>Something else</li>
</ul>
</li>
</ul>
</div>
```
<http://api.jquery.com/off/>
As I was too fast: [How do I unbind "hover" in jQuery?](https://stackoverflow.com/questions/805133/how-do-i-unbind-hover-in-jquery) | To hover on desktop sites, but us the click on mobile sites you'd need to check to see if its a mobile device and implement your hover accordingly. If you're using a framework like Bootstrap, lots of that work is already done for you.
If not, you can check for mobile devices using something like this: [Detecting a mobile browser](https://stackoverflow.com/questions/11381673/detecting-a-mobile-browser)
Implemented in your code, you'd first detect the device type. If its desktop, add a class and bind your hover event to that menu and class. The end result is that you get the hover on desktop, but mobile devices must use the click.
Something like this would work:
```
window.mobilecheck = function() {
var check = false;
(function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))check = true})(navigator.userAgent||navigator.vendor||window.opera);
return check;
}
if(!window.mobilecheck()) {
$('.menu').addClass('isDesktop');
}
// Make submenu dropdown on hover
// Make submenu dropdown on hover
$('.menu.isDesktop ul li ul').hide();
$('.menu.isDesktop ul li').hover(function(subMenuDropDown) {
$(this).find("ul").first().stop(true, true).delay(60).slideDown('slow');
}, function() {
$(this).find("ul").first().stop(true, true).delay(60).slideUp('fast');
});
$('.mobileMenuButton').click(function() {
$('.menu').toggle();
});
```
You can see it working in this JS Fiddle: <https://jsfiddle.net/igor_9000/k4ftf4tx/3/>
Hope that helps! |
8,822,359 | I need to show label background color which is attached in following code. It's multiline label.
Here is code snippet.
```
self._coverTittle =[[FontLabel alloc] initWithFrame:CGRectMake(100, 650, 400, 200) fontName:@"futurlig-webfont" pointSize:48.0f];
self._coverTittle.backgroundColor = [UIColor colorWithRed:0 green: 0 blue:0 alpha:0.4];
_coverTittle.numberOfLines = 5;
_coverTittle.textColor = [UIColor whiteColor];
self._coverTittle.tag=5;
[self._coverTittle sizeToFit];
``` | 2012/01/11 | [
"https://Stackoverflow.com/questions/8822359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/289036/"
] | You should be fine.
Check the properties of your web app (and any other referenced projects you compile).
```
Properties -> Build -> Platform: should be set to: Any CPU.
```
This is the default, so unless you have changed it, you will be ok.
AnyCPU assembly's will be JITed to 32 or 64 bit code depending on the process they are running in.
You typically only need to mess with this if you are referencing unmanaged dll's. | As Visual Studio is a 32-bit application, ASP.NET development is usually performed in a 32-bit environment. You won't be able to develop using any 64 bit assemblies (like the Azure assemblies, for example), but unless you need to do that it probably won't make any difference. |
8,822,359 | I need to show label background color which is attached in following code. It's multiline label.
Here is code snippet.
```
self._coverTittle =[[FontLabel alloc] initWithFrame:CGRectMake(100, 650, 400, 200) fontName:@"futurlig-webfont" pointSize:48.0f];
self._coverTittle.backgroundColor = [UIColor colorWithRed:0 green: 0 blue:0 alpha:0.4];
_coverTittle.numberOfLines = 5;
_coverTittle.textColor = [UIColor whiteColor];
self._coverTittle.tag=5;
[self._coverTittle sizeToFit];
``` | 2012/01/11 | [
"https://Stackoverflow.com/questions/8822359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/289036/"
] | No problem. Just make sure you build your app for Any CPU. If you use [MySQL Connector for .Net](http://dev.mysql.com/downloads/connector/net/), which is a 32-bits DLL, your Application Pool must be enabled to run 32-bits applications, which you can configure on IIS. | As Visual Studio is a 32-bit application, ASP.NET development is usually performed in a 32-bit environment. You won't be able to develop using any 64 bit assemblies (like the Azure assemblies, for example), but unless you need to do that it probably won't make any difference. |
5,660,338 | Has anybody gotten this ruby warning before? "warning: redundant nested repeat operator"
What does it mean?
I get it when I start Webrick
This is how my trace looks like:
```
c:/Ruby192/lib/ruby/gems/1.9.1/gems/rack-mount-0.6.13/lib/rack/mount/strexp.rb:4
1: warning: redundant nested repeat operator
c:/Ruby192/lib/ruby/gems/1.9.1/gems/actionpack-3.0.5/lib/action_dispatch/routing
/route.rb:25: warning: redundant nested repeat operator
c:/Ruby192/lib/ruby/gems/1.9.1/gems/rack-mount-0.6.13/lib/rack/mount/route.rb:46
```
I'm using Rails 3.0.5 and Ruby 1.9.2 p180 | 2011/04/14 | [
"https://Stackoverflow.com/questions/5660338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/226255/"
] | This happens when you have a regular expression with two repeat operators on a single atom. E.g.,
```
ruby-1.9.2-p180 :001 > re = /\w**/
~/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/1.9.1/irb/workspace.rb:80:
warning: redundant nested repeat operator: /\w**/
=> /\w**/
```
Given that the backtrace has what looks like routing libraries (I've not personally used the rack-mount gem), I'd guess one of your routes either has a redundant repeat operator in it, or is being reduced down to a regex which has one. | @michael's response got me to find the real problem:
If you have the following in your routes.rb,
```
match "/foo(/bar(/something)))" => "controller#action"
```
You get the warning mentioned above. It exists to warn you that `/foo` works, so does `/foo/bar` and so does `/foo/bar/something` |
447,030 | My goal is to write a `\unitvector` command which produces bold upright symbols with a bold circumflex accent. Here's my MWE:
```
\documentclass{article}
\usepackage{amsmath}
\usepackage{unicode-math}
\setmainfont{TeX Gyre Bonum}
\setmathfont{texgyrebonum-math.otf}
\newcommand\unitvectorA[1]{\symbfup{\hat{#1}}}
\newcommand\unitvectorB[1]{\text{\textbf{\^{#1}}}}
\begin{document}
% Text versions for reference.
\textbf{\^{x}}
\textbf{\^{ρ}}
% First attempt: circumflex accent is not bold.
$\unitvectorA{x}$
$\unitvectorA{\rho}$
% Second attempt: missing \rho.
$\unitvectorB{x}$
$\unitvectorB{\rho}$
\end{document}
```
Here's the output:
[](https://i.stack.imgur.com/QZdPZ.png)
There are other questions here which are similar to this one, but as far as I can tell, they either do not use `unicode-math`, or they do not provide a bold circumflex accent. (If I'm wrong about that, I'd love to know.)
I believe I understand why `\symbfup` doesn't do the "right" thing: Unicode does not define a "mathematical bold circumflex accent" (which seems like an oversight to me). I also do not have the luxury of using a math font which has a corresponding bold math font (such as XITS Math), which I believe would also provide a solution. Hence the attempted workaround using `\text` which, unfortunately, is not a workaround at all as it does not work.
I attempted to use the `range` feature of `unicode-math` to switch out fonts in some clever way, but I failed to find an incantation which worked.
**Update:**
I modified [Marcel Krüger's](https://tex.stackexchange.com/users/80496/marcel-kr%C3%BCger) answer by replacing XITS Math Bold with TeX Gyre Bonum Bold and obtained this:
[](https://i.stack.imgur.com/0yJIu.png)
It seems that there should be a way to nudge the accents over, but I don't understand yet how `\Umathaccent` works. | 2018/08/21 | [
"https://tex.stackexchange.com/questions/447030",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/33233/"
] | You can just skip `unicode-math` and load `XITS Math Bold` as a LaTeX Symbol font:
```
\documentclass{article}
\usepackage{amsmath}
\usepackage{unicode-math}
\setmainfont{TeX Gyre Bonum}
\setmathfont{texgyrebonum-math.otf}
% We could use fontspec to load these but I am not a big fontspec fan:
\DeclareFontFamily{TU}{xitsmath}{}
\DeclareFontShape{TU}{xitsmath}{bx}{n}
{<-> \UnicodeFontName{XITS Math Bold}{mode=base;script=math;language=DFLT}}{}
% Declare \symboldaccent:
\DeclareSymbolFont{boldaccents}{TU}{xitsmath}{bx}{n}
% Now we just need a nice name for the accent: (If you prefer a `\widehat`, just omit `fixed`)
\newcommand\boldhat{\Umathaccent fixed 7\symboldaccents"0302\relax}
\newcommand\unitvector[1]{\symbfup{\boldhat{#1}}}
% If we are using LuaTeX, we can also modify our text font to include the placement information for math accents:
\directlua{
fonts.constructors.features.otf.register{
name = 'mathcircumflex',
description = 'Add math accent treatment to circumflex',
manipulators = {
base = function(tfm, v)
tfm.nomath = false
tfm.characters[0x2C6].top_accent = tfm.characters[0x2C6].width/2
end
}
}
}
\DeclareFontFamily{TU}{bonumsemimath}{}
\DeclareFontShape{TU}{bonumsemimath}{bx}{n}
{<-> \UnicodeFontName{TeX Gyre Bonum Bold}{mode=base;+mathcircumflex;script=DFLT;language=DFLT}}{}
\DeclareSymbolFont{boldtextaccents}{TU}{bonumsemimath}{bx}{n}
\newcommand\boldtexthat{\Umathaccent fixed 7\symboldtextaccents"02C6\relax}
\newcommand\unitvectorB[1]{\symbfup{\boldtexthat{#1}}}
\begin{document}
% Text versions for reference.
\textbf{\^{x}}
\textbf{\^{ρ}}
$\unitvector{x}$
$\unitvector{\rho}$
$\unitvectorB{x}$
$\unitvectorB{\rho}$
\end{document}
```
[](https://i.stack.imgur.com/RxxHQ.png) | Works only with `lualatex`. For `xelatex` you can use the `FakeBold` option.
```
\documentclass{article}
\usepackage{amsmath}
\usepackage{unicode-math}
\setmainfont{TeX Gyre Bonum}
\setmathfont{texgyrebonum-math.otf}
\usepackage[bold=0.8]{xfakebold}
\newcommand\unitvectorA[1]{\setBold\ensuremath{\hat{#1}}\unsetBold}
\begin{document}
\unitvectorA{x} $\hat{x}$
\unitvectorA{\rho}$\hat{\rho}$
\end{document}
```
[](https://i.stack.imgur.com/tkn3p.png) |
28,161,281 | Say I have the following...
```
double d = 1.6;
int q = ( ( int ) d );
```
Will this always drop the just decimal point according to the Java standard, or could it round up or down ***according to the standard*** (Which more or less exists)? | 2015/01/27 | [
"https://Stackoverflow.com/questions/28161281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4496759/"
] | Yes, it will drop the decimal point. That means it will round *towards zero*, so it will round down if it is positive, but it will round up if it is negative.
See [§5.1.3](http://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.1.3) in the JLS:
>
> Otherwise, if the floating-point number is not an infinity, the floating-point value is rounded to an integer value V, rounding toward zero using IEEE 754 round-toward-zero mode ([§4.2.3](http://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.2.3)).
>
>
> | Casting a `double` to an `int` always floors the value to greatest integer less than it, but try this:
```
int q = (int) Math.round(d); // rounded instead of floored
``` |
36,190,294 | I'm trying to import a flat file into SQL Server and I'm having some issues. The column delimiter is `;~` and the row delimiter is `|~`. I'm using the SQL Server Import and Export Wizard but keep getting errors. Have any of you every had a similar issue? I think I'm doing it wrong from the start of the wizard. Can any of you talk me through the steps. Thanks.
Here is the import error:
[](https://i.stack.imgur.com/4FB8x.jpg) | 2016/03/23 | [
"https://Stackoverflow.com/questions/36190294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | The best way to do this is:
`gsutil -m acl ch -u 'AllUsers:R' gs://your-bucket/**`
will update ACLs for each existing object in the bucket.
If you want newly created objects in this bucket to also be public, you should also run:
`gsutil defacl ch -u 'AllUsers:R' gs://your-bucket`
This question was also asked [here](https://stackoverflow.com/questions/14371376/how-do-you-make-many-files-public-in-google-cloud-storage) but the answer recommends using `acl set public-read` which has the downside of potentially altering your existing ACLs. | ```
$> gsutil acl ch -g All:R -r gs://bucketName
```
gsutil is the command-line utility for GCS.
"acl ch" means "Modify an ACL."
"-g All:R" means "include read permissions for all users."
"-r" means "recursively"
and the rest is the path.
If you have a whole lot of files and you want MORE SPEED, you can use -m to mean "and also do this multithreaded!", like so:
```
$> gsutil -m acl ch -g All:R -r gs://bucketName
``` |
27,730,848 | Yes, the question has been asked so many times, but this one is a bit more specific. I need JavaScript code that shows/hides all elements of a certain `class`. The code must be compatible with the older browsers and Internet Explorer, and it must have an extremely small footprint. So, please don't post jQuery solutions, since this task will use 0.01% of the code from the library. So far I've come up with this:
```
var flip = document.getElementsByTagName(_tag);
if (trigger)
for (var i = 0; i < flip.length; i++)
if (flip[i].className == _class) flip[i].style.visibility = 'visible';
else
for (var i = 0; i < flip.length; i++)
if (flip[i].className == _class) flip[i].style.visibility = 'hidden';
```
Since `getElementsByclassName` does not work in IE, and most common solutions are too bulky for me. Is this code optimal for the task, or could it be streamlined even more? (as a reference, the previous solution used a `cgi` to add `<style>.myclass {visibility:visible}</class>` to the page) | 2015/01/01 | [
"https://Stackoverflow.com/questions/27730848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3664780/"
] | You need to use a shim or iterate through the dom and get elements with your class. See no other solutions. | I agree with Luba, here's a shim: [getElementsByClassName.polyfill.js](https://gist.github.com/eikes/2299607)
As commented by Hemang, link only answers are invalid due to link change so here's the code from the link. The link is a shim for the deficit of getElementsByClassName in pre-ie9. Initially the shim tests the lack of getElementsByClassName then tests for the presence of querySelectorAll, if this is not available (i.e. pre-ie8) then evaluate is used.
```
// Add a getElementsByClassName function if the browser doesn't have one
// Limitation: only works with one class name
// Copyright: Eike Send http://eike.se/nd
// License: MIT License
if (!document.getElementsByClassName) {
document.getElementsByClassName = function(search) {
var d = document, elements, pattern, i, results = [];
if (d.querySelectorAll) { // IE8
return d.querySelectorAll("." + search);
}
if (d.evaluate) { // IE6, IE7
pattern = ".//*[contains(concat(' ', @class, ' '), ' " + search + " ')]";
elements = d.evaluate(pattern, d, null, 0, null);
while ((i = elements.iterateNext())) {
results.push(i);
}
} else {
elements = d.getElementsByTagName("*");
pattern = new RegExp("(^|\\s)" + search + "(\\s|$)");
for (i = 0; i < elements.length; i++) {
if ( pattern.test(elements[i].className) ) {
results.push(elements[i]);
}
}
}
return results;
}
}
``` |
27,730,848 | Yes, the question has been asked so many times, but this one is a bit more specific. I need JavaScript code that shows/hides all elements of a certain `class`. The code must be compatible with the older browsers and Internet Explorer, and it must have an extremely small footprint. So, please don't post jQuery solutions, since this task will use 0.01% of the code from the library. So far I've come up with this:
```
var flip = document.getElementsByTagName(_tag);
if (trigger)
for (var i = 0; i < flip.length; i++)
if (flip[i].className == _class) flip[i].style.visibility = 'visible';
else
for (var i = 0; i < flip.length; i++)
if (flip[i].className == _class) flip[i].style.visibility = 'hidden';
```
Since `getElementsByclassName` does not work in IE, and most common solutions are too bulky for me. Is this code optimal for the task, or could it be streamlined even more? (as a reference, the previous solution used a `cgi` to add `<style>.myclass {visibility:visible}</class>` to the page) | 2015/01/01 | [
"https://Stackoverflow.com/questions/27730848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3664780/"
] | Don't use the same iterator (var i) in an inner for loop because it collides with your current loop. Remove the second inner one and check if class x is set, then set your property, do a "continue" and vice versa:
```
var flip = document.getElementsByTagName(_tag);
if (trigger) {
for (var i = 0; i < flip.length; i++) {
var state = flip[i].style.visibility;
if (flip[i].className == _class && state == 'hidden') {
flip[i].style.visibility = 'visible';
continue;
}
if (flip[i].className == _class && state == 'visible') {
flip[i].style.visibility = 'hidden';
}
}
}
``` | I agree with Luba, here's a shim: [getElementsByClassName.polyfill.js](https://gist.github.com/eikes/2299607)
As commented by Hemang, link only answers are invalid due to link change so here's the code from the link. The link is a shim for the deficit of getElementsByClassName in pre-ie9. Initially the shim tests the lack of getElementsByClassName then tests for the presence of querySelectorAll, if this is not available (i.e. pre-ie8) then evaluate is used.
```
// Add a getElementsByClassName function if the browser doesn't have one
// Limitation: only works with one class name
// Copyright: Eike Send http://eike.se/nd
// License: MIT License
if (!document.getElementsByClassName) {
document.getElementsByClassName = function(search) {
var d = document, elements, pattern, i, results = [];
if (d.querySelectorAll) { // IE8
return d.querySelectorAll("." + search);
}
if (d.evaluate) { // IE6, IE7
pattern = ".//*[contains(concat(' ', @class, ' '), ' " + search + " ')]";
elements = d.evaluate(pattern, d, null, 0, null);
while ((i = elements.iterateNext())) {
results.push(i);
}
} else {
elements = d.getElementsByTagName("*");
pattern = new RegExp("(^|\\s)" + search + "(\\s|$)");
for (i = 0; i < elements.length; i++) {
if ( pattern.test(elements[i].className) ) {
results.push(elements[i]);
}
}
}
return results;
}
}
``` |
27,730,848 | Yes, the question has been asked so many times, but this one is a bit more specific. I need JavaScript code that shows/hides all elements of a certain `class`. The code must be compatible with the older browsers and Internet Explorer, and it must have an extremely small footprint. So, please don't post jQuery solutions, since this task will use 0.01% of the code from the library. So far I've come up with this:
```
var flip = document.getElementsByTagName(_tag);
if (trigger)
for (var i = 0; i < flip.length; i++)
if (flip[i].className == _class) flip[i].style.visibility = 'visible';
else
for (var i = 0; i < flip.length; i++)
if (flip[i].className == _class) flip[i].style.visibility = 'hidden';
```
Since `getElementsByclassName` does not work in IE, and most common solutions are too bulky for me. Is this code optimal for the task, or could it be streamlined even more? (as a reference, the previous solution used a `cgi` to add `<style>.myclass {visibility:visible}</class>` to the page) | 2015/01/01 | [
"https://Stackoverflow.com/questions/27730848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3664780/"
] | Here's a mockup of a classname-switcher, would that be an idea? If you use IE < 8, use `document.getElementsByTagName` instead of `document.querySelectorAll`.
```js
(function() {
document.querySelector('button').addEventListener('click', toggledivshidden);
function toggledivshidden() {
return toggle('div', 'hidden');
}
function toggle(tag, clssname) {
var flips = document.querySelectorAll(tag);
for (var i = 0; i< flips.length; i+=1) {
var classExists = RegExp(clssname, 'i').test(flips[i].className);
classEdit(flips[i], clssname, classExists);
}
}
// add or remove a classname, without destroying other classnames
function classEdit(el, clname, remove) {
var re = RegExp(clname, 'g'),
current = el.className;
el.className = ( remove ? current.replace(re, '')
: re.test(current)
? current
: current +' '+clname )
.replace(/\s+/g, ' ') // remove redundant spaces
.replace(/^\s+|\s+$/,''); // trim
return true;
}
}())
```
```css
.hidden {
visibility: collapse;
height: 0;
}
div:after {
content: ' - className: "'attr(class)'"';
color: #c0c0c0;
}
```
```html
<div class="hidden some">originally hidden</div>
<div class="some hidden foo bar">originally hidden</div>
<div class="some more etc">originally visible</div>
<div class="some">originally visible</div>
<button>toggle</button>
``` | I agree with Luba, here's a shim: [getElementsByClassName.polyfill.js](https://gist.github.com/eikes/2299607)
As commented by Hemang, link only answers are invalid due to link change so here's the code from the link. The link is a shim for the deficit of getElementsByClassName in pre-ie9. Initially the shim tests the lack of getElementsByClassName then tests for the presence of querySelectorAll, if this is not available (i.e. pre-ie8) then evaluate is used.
```
// Add a getElementsByClassName function if the browser doesn't have one
// Limitation: only works with one class name
// Copyright: Eike Send http://eike.se/nd
// License: MIT License
if (!document.getElementsByClassName) {
document.getElementsByClassName = function(search) {
var d = document, elements, pattern, i, results = [];
if (d.querySelectorAll) { // IE8
return d.querySelectorAll("." + search);
}
if (d.evaluate) { // IE6, IE7
pattern = ".//*[contains(concat(' ', @class, ' '), ' " + search + " ')]";
elements = d.evaluate(pattern, d, null, 0, null);
while ((i = elements.iterateNext())) {
results.push(i);
}
} else {
elements = d.getElementsByTagName("*");
pattern = new RegExp("(^|\\s)" + search + "(\\s|$)");
for (i = 0; i < elements.length; i++) {
if ( pattern.test(elements[i].className) ) {
results.push(elements[i]);
}
}
}
return results;
}
}
``` |
72,513,468 | I'm trying to detect and differentiate the login of the normals users and admin. The user only shows "welcome user" and when an admin log-in's it shows all the users. I've tried if else but the statement is wrong it dosent work.
**LoginValidator.php**
```
<?php
session_start();
$users = array(
array("User" => "admin", "Password" => "admin"),
array("User" => "administrator", "Password" => "administrator"),
);
$mergedUsers = array_merge($users, $_SESSION['newUsers']);
$userName = $_POST['username'];
$msg = "";
$codeinput = $_POST['code'];
foreach ($mergedUsers as $value) {
if ($userName == $value['User'] && $_POST['password'] == $value['Password']) {
if ($codeinput == $_SESSION['captcha']) {
echo "Captcha valid";
echo "<p>Login successful<3</p>";
if ($value['User'] == $users) {
echo "Welcome admin!";
echo print_r($mergedUsers);
echo print_r($users);
echo '<pre>' . print_r($_SESSION, TRUE) . '</pre>';
} else
echo "Welcome user!";
} else {
echo "Captcha NOT valid";
}
} else if ($userName == $value["User"] and $_POST['password'] != $value["Password"]) {
//$msg = "<p>Wrong Password</p>";
echo "Wrong password";
}
}
?>
```
**Login.php**
```
<form action="LoginValidator.php" method="POST">
<div class="login">
<h3>Login Here</h3>
<label for="username">Username</label>
<input type="text" placeholder="User name" id="username" name="username" required>
<label for="password">Password</label>
<input type="password" placeholder="Password" id="password" name="password" required>
<p>Enter this number: <?php echo $_SESSION['captcha']; ?></p>
<p><input type="text" name="code" required />
<button>Log In</button>
<p> Don't have any account yet? <br> <a href="registration.php"> Register Here </a> </p>
</div>
</div>
</form>
``` | 2022/06/06 | [
"https://Stackoverflow.com/questions/72513468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13831923/"
] | I found problem in the if condition where you are checking for the admin.
```
if ($value['User'] == $users) {
```
Here, you are comparing a value with an array, which will not work.
This problem could be solved by comparing an array with an array.
For that, you just have to change above if condition to:
```
if (in_array($value, $users)) {
```
The `in_array()` method will check whether `$value` array is present in `$user` array and will then return true if present, false if not.
I hope this will resolve your problem. | You may try to type the value instead
```
if ($value['User'] == "ADMIN") {
echo "Welcome admin!";
echo print_r($mergedUsers);
echo print_r($users);
echo '<pre>' . print_r($_SESSION, TRUE) . '</pre>';
} else
echo "Welcome user!";
``` |
926,517 | I only register (make an account/login stuff) on [HTTPS](http://en.wikipedia.org/wiki/HTTP_Secure) webpages. However, a webpage I wanted to register right now doesn't use HTTPS. I am wondering if I am connected to my company VPN, is it safe to register on a webpage that uses just [HTTP](http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol)? | 2015/06/11 | [
"https://superuser.com/questions/926517",
"https://superuser.com",
"https://superuser.com/users/311621/"
] | Your company VPN will NOT encrypt data from your computer to the website you want to register yourself, only the data from your computer to your company's VPN-server.
HTTPS (if used correctly) makes sure data from your machine to the website is safe and that you are not the victim of a [man-in-the-middle attack](https://en.wikipedia.org/wiki/Man-in-the-middle_attack).
So. Is it safe? "Maybe" (but has nothing to do with your VPN), you could always get your account / password information stolen on the way from your VPN-server to the website. | I guess you're worried about the details you enter onto the page being sent unencrypted.
The company VPN will secure the connection between you and the VPN server. The VPN server will still have to open an unencrypted connection between itself and the HTTP page/server, instead of your computer opening the connection itself.
Maybe it's ever so slightly safer, since a corporate Internet connection is secured better than a consumer one, but your information is still bring sent unencrypted and is still subject to [man-in-the-middle'ing](https://en.wikipedia.org/wiki/Man-in-the-middle_attack). |
926,517 | I only register (make an account/login stuff) on [HTTPS](http://en.wikipedia.org/wiki/HTTP_Secure) webpages. However, a webpage I wanted to register right now doesn't use HTTPS. I am wondering if I am connected to my company VPN, is it safe to register on a webpage that uses just [HTTP](http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol)? | 2015/06/11 | [
"https://superuser.com/questions/926517",
"https://superuser.com",
"https://superuser.com/users/311621/"
] | Your company VPN will NOT encrypt data from your computer to the website you want to register yourself, only the data from your computer to your company's VPN-server.
HTTPS (if used correctly) makes sure data from your machine to the website is safe and that you are not the victim of a [man-in-the-middle attack](https://en.wikipedia.org/wiki/Man-in-the-middle_attack).
So. Is it safe? "Maybe" (but has nothing to do with your VPN), you could always get your account / password information stolen on the way from your VPN-server to the website. | No, using a VPN does not make VPN traffic safe. When going out of the VPN tunnel (between the VPN server and the HTTP server) the traffic is (in general) not encrypted:
```
Unencrypted HTTP here
|
v
[ HTTP ]<--------------->[ HTTP ]
[ TCP ]<--------------->[ TCP ]
[ IP ]<->[ IP ]<->[ IP ]
[ OpenVPN ]<->[ OpenVPN ]
[ TCP ]<->[ TCP ]
[ IP ]<->[ IP ]
Client VPN server HTTP server
```
So it's only safe, if you assume that the path between the VPN server and the HTTP server is "safe" for some reason (it is the same host, it uses a VPN…). |
926,517 | I only register (make an account/login stuff) on [HTTPS](http://en.wikipedia.org/wiki/HTTP_Secure) webpages. However, a webpage I wanted to register right now doesn't use HTTPS. I am wondering if I am connected to my company VPN, is it safe to register on a webpage that uses just [HTTP](http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol)? | 2015/06/11 | [
"https://superuser.com/questions/926517",
"https://superuser.com",
"https://superuser.com/users/311621/"
] | Your company VPN will NOT encrypt data from your computer to the website you want to register yourself, only the data from your computer to your company's VPN-server.
HTTPS (if used correctly) makes sure data from your machine to the website is safe and that you are not the victim of a [man-in-the-middle attack](https://en.wikipedia.org/wiki/Man-in-the-middle_attack).
So. Is it safe? "Maybe" (but has nothing to do with your VPN), you could always get your account / password information stolen on the way from your VPN-server to the website. | Seeing as my comments on other answers are getting pretty long I figured I'd separate it out:
**It is impossible to answer if a corporate VPN connection offers equivalent security compared to SSL to a web server without knowing the exact specifics of the connection in question, which the OP hasn't specified.**
However as a general reference there are two main scenarios to look at:
**1)** IF a user is using a VPN connection to a corporate network in order to connect to **unencrypted public websites outside the corporate network**, then the security offered is equivalent to directly accessing the same unencrypted website from the corporate network.
It will prevent interception of communications between your device and your corporate network but will not protect against interception between your corporate network and the public webserver. How secure it is depends on how much you trust your corporate network's connection to the public webserver.
In any case it will be **less secure than a properly configured HTTPS connection direct to the public webserver** from your client device.
However this mechanism will protect against eavesdropping on your local connection if for example you are using an unencrypted public hotspot or other untrusted ISP.
**2)** IF a user is using a VPN connection to a corporate network in order to connect to unencrypted **resources on the corporate network** behind the VPN server, or on the VPN server itself, then it is protecting the connection all the way to the target network itself.
**This offers protection is roughly equivalent to HTTPS to the webserver in question.**
ysdx's answer illustrates the first point well, except it misses out everything after the HTTP server.
**A fully encrypted HTTPS connection to a webserver does not guarantee a completely secure to the source of the web page any more than a corporate VPN would in scenario 2.**
HTTPS provides a security guarantee between two TCP endpoints. VPN provides a security guarantee between two TCP endpoints. In both cases, the endpoints are your PC, and a server at the edge of the other server's corporate/internal network. What happens after that edge is NOT secured by either method.
Many people forget that the HTTPS webserver you connect to during an HTTPS session is, in the case of many large websites, NOT the server the web page you are viewing comes from. The many reasons this happens include:
1) Load balancers, which will often have unencrypted network connection via a corporate LAN to various content servers that actually serve the content on the webpage.
2) Reverse proxies, NATs, and so forth that forward your connection - again, unencrypted, to arbitrary servers on the corporate LAN or even other public websites.
3) Caching servers or DDoS protection services such as CloudFlare, some of which operate on the public internet but forward your connection to a different company's server to actually serve the content - usually via a second encrypted connection or VPN.
4) Databases or NAS/SAN backends, where the web server uses an unencrypted connection to another server over the corporate LNA to retrieve the content for the website.
**In all of these cases, the security of your web session relies on the security of the corporate LAN behind the HTTPS "gateway", in exactly the same way connecting to a corporate server behind a corporate VPN does.** |
926,517 | I only register (make an account/login stuff) on [HTTPS](http://en.wikipedia.org/wiki/HTTP_Secure) webpages. However, a webpage I wanted to register right now doesn't use HTTPS. I am wondering if I am connected to my company VPN, is it safe to register on a webpage that uses just [HTTP](http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol)? | 2015/06/11 | [
"https://superuser.com/questions/926517",
"https://superuser.com",
"https://superuser.com/users/311621/"
] | I guess you're worried about the details you enter onto the page being sent unencrypted.
The company VPN will secure the connection between you and the VPN server. The VPN server will still have to open an unencrypted connection between itself and the HTTP page/server, instead of your computer opening the connection itself.
Maybe it's ever so slightly safer, since a corporate Internet connection is secured better than a consumer one, but your information is still bring sent unencrypted and is still subject to [man-in-the-middle'ing](https://en.wikipedia.org/wiki/Man-in-the-middle_attack). | No, using a VPN does not make VPN traffic safe. When going out of the VPN tunnel (between the VPN server and the HTTP server) the traffic is (in general) not encrypted:
```
Unencrypted HTTP here
|
v
[ HTTP ]<--------------->[ HTTP ]
[ TCP ]<--------------->[ TCP ]
[ IP ]<->[ IP ]<->[ IP ]
[ OpenVPN ]<->[ OpenVPN ]
[ TCP ]<->[ TCP ]
[ IP ]<->[ IP ]
Client VPN server HTTP server
```
So it's only safe, if you assume that the path between the VPN server and the HTTP server is "safe" for some reason (it is the same host, it uses a VPN…). |
926,517 | I only register (make an account/login stuff) on [HTTPS](http://en.wikipedia.org/wiki/HTTP_Secure) webpages. However, a webpage I wanted to register right now doesn't use HTTPS. I am wondering if I am connected to my company VPN, is it safe to register on a webpage that uses just [HTTP](http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol)? | 2015/06/11 | [
"https://superuser.com/questions/926517",
"https://superuser.com",
"https://superuser.com/users/311621/"
] | I guess you're worried about the details you enter onto the page being sent unencrypted.
The company VPN will secure the connection between you and the VPN server. The VPN server will still have to open an unencrypted connection between itself and the HTTP page/server, instead of your computer opening the connection itself.
Maybe it's ever so slightly safer, since a corporate Internet connection is secured better than a consumer one, but your information is still bring sent unencrypted and is still subject to [man-in-the-middle'ing](https://en.wikipedia.org/wiki/Man-in-the-middle_attack). | Seeing as my comments on other answers are getting pretty long I figured I'd separate it out:
**It is impossible to answer if a corporate VPN connection offers equivalent security compared to SSL to a web server without knowing the exact specifics of the connection in question, which the OP hasn't specified.**
However as a general reference there are two main scenarios to look at:
**1)** IF a user is using a VPN connection to a corporate network in order to connect to **unencrypted public websites outside the corporate network**, then the security offered is equivalent to directly accessing the same unencrypted website from the corporate network.
It will prevent interception of communications between your device and your corporate network but will not protect against interception between your corporate network and the public webserver. How secure it is depends on how much you trust your corporate network's connection to the public webserver.
In any case it will be **less secure than a properly configured HTTPS connection direct to the public webserver** from your client device.
However this mechanism will protect against eavesdropping on your local connection if for example you are using an unencrypted public hotspot or other untrusted ISP.
**2)** IF a user is using a VPN connection to a corporate network in order to connect to unencrypted **resources on the corporate network** behind the VPN server, or on the VPN server itself, then it is protecting the connection all the way to the target network itself.
**This offers protection is roughly equivalent to HTTPS to the webserver in question.**
ysdx's answer illustrates the first point well, except it misses out everything after the HTTP server.
**A fully encrypted HTTPS connection to a webserver does not guarantee a completely secure to the source of the web page any more than a corporate VPN would in scenario 2.**
HTTPS provides a security guarantee between two TCP endpoints. VPN provides a security guarantee between two TCP endpoints. In both cases, the endpoints are your PC, and a server at the edge of the other server's corporate/internal network. What happens after that edge is NOT secured by either method.
Many people forget that the HTTPS webserver you connect to during an HTTPS session is, in the case of many large websites, NOT the server the web page you are viewing comes from. The many reasons this happens include:
1) Load balancers, which will often have unencrypted network connection via a corporate LAN to various content servers that actually serve the content on the webpage.
2) Reverse proxies, NATs, and so forth that forward your connection - again, unencrypted, to arbitrary servers on the corporate LAN or even other public websites.
3) Caching servers or DDoS protection services such as CloudFlare, some of which operate on the public internet but forward your connection to a different company's server to actually serve the content - usually via a second encrypted connection or VPN.
4) Databases or NAS/SAN backends, where the web server uses an unencrypted connection to another server over the corporate LNA to retrieve the content for the website.
**In all of these cases, the security of your web session relies on the security of the corporate LAN behind the HTTPS "gateway", in exactly the same way connecting to a corporate server behind a corporate VPN does.** |
926,517 | I only register (make an account/login stuff) on [HTTPS](http://en.wikipedia.org/wiki/HTTP_Secure) webpages. However, a webpage I wanted to register right now doesn't use HTTPS. I am wondering if I am connected to my company VPN, is it safe to register on a webpage that uses just [HTTP](http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol)? | 2015/06/11 | [
"https://superuser.com/questions/926517",
"https://superuser.com",
"https://superuser.com/users/311621/"
] | Seeing as my comments on other answers are getting pretty long I figured I'd separate it out:
**It is impossible to answer if a corporate VPN connection offers equivalent security compared to SSL to a web server without knowing the exact specifics of the connection in question, which the OP hasn't specified.**
However as a general reference there are two main scenarios to look at:
**1)** IF a user is using a VPN connection to a corporate network in order to connect to **unencrypted public websites outside the corporate network**, then the security offered is equivalent to directly accessing the same unencrypted website from the corporate network.
It will prevent interception of communications between your device and your corporate network but will not protect against interception between your corporate network and the public webserver. How secure it is depends on how much you trust your corporate network's connection to the public webserver.
In any case it will be **less secure than a properly configured HTTPS connection direct to the public webserver** from your client device.
However this mechanism will protect against eavesdropping on your local connection if for example you are using an unencrypted public hotspot or other untrusted ISP.
**2)** IF a user is using a VPN connection to a corporate network in order to connect to unencrypted **resources on the corporate network** behind the VPN server, or on the VPN server itself, then it is protecting the connection all the way to the target network itself.
**This offers protection is roughly equivalent to HTTPS to the webserver in question.**
ysdx's answer illustrates the first point well, except it misses out everything after the HTTP server.
**A fully encrypted HTTPS connection to a webserver does not guarantee a completely secure to the source of the web page any more than a corporate VPN would in scenario 2.**
HTTPS provides a security guarantee between two TCP endpoints. VPN provides a security guarantee between two TCP endpoints. In both cases, the endpoints are your PC, and a server at the edge of the other server's corporate/internal network. What happens after that edge is NOT secured by either method.
Many people forget that the HTTPS webserver you connect to during an HTTPS session is, in the case of many large websites, NOT the server the web page you are viewing comes from. The many reasons this happens include:
1) Load balancers, which will often have unencrypted network connection via a corporate LAN to various content servers that actually serve the content on the webpage.
2) Reverse proxies, NATs, and so forth that forward your connection - again, unencrypted, to arbitrary servers on the corporate LAN or even other public websites.
3) Caching servers or DDoS protection services such as CloudFlare, some of which operate on the public internet but forward your connection to a different company's server to actually serve the content - usually via a second encrypted connection or VPN.
4) Databases or NAS/SAN backends, where the web server uses an unencrypted connection to another server over the corporate LNA to retrieve the content for the website.
**In all of these cases, the security of your web session relies on the security of the corporate LAN behind the HTTPS "gateway", in exactly the same way connecting to a corporate server behind a corporate VPN does.** | No, using a VPN does not make VPN traffic safe. When going out of the VPN tunnel (between the VPN server and the HTTP server) the traffic is (in general) not encrypted:
```
Unencrypted HTTP here
|
v
[ HTTP ]<--------------->[ HTTP ]
[ TCP ]<--------------->[ TCP ]
[ IP ]<->[ IP ]<->[ IP ]
[ OpenVPN ]<->[ OpenVPN ]
[ TCP ]<->[ TCP ]
[ IP ]<->[ IP ]
Client VPN server HTTP server
```
So it's only safe, if you assume that the path between the VPN server and the HTTP server is "safe" for some reason (it is the same host, it uses a VPN…). |
9,202 | I have a Sam Coupé and the last time I turn it on, i noticed a smell of components overheating.
After opening the power supply I came to the conclusion that is the resistance R1 (50ºc with IR thermometer).
I took the power supply to two technicians who measured the values in the components and the final output. Both said that everything was fine and that the resistance in question was made to warm up. However I'm worried about the situation because I had never noticed this smell before.
Is this heating really normal?
Can someone with a Sam confirm?
Thanks for the help.
[](https://i.stack.imgur.com/Tb0zi.jpg) | 2019/02/15 | [
"https://retrocomputing.stackexchange.com/questions/9202",
"https://retrocomputing.stackexchange.com",
"https://retrocomputing.stackexchange.com/users/11959/"
] | 50 ºC is nothing for a 4 W power resistor, so the 'overheating' smell was probably coming from something else.
As this power supply has a single-sided pcb (tracks on the bottom side only) I would examine all the joints and resolder any that look cracked or burnt. You might also consider testing the electrolytic capacitors for ESR and capacitance value, or just replace them anyway as a precaution. | The "overheating" smell might emerge from the dust accreted on the heating components, if the device was off for a long time. So you could try to clean the dust off the PCB and components to get rid of the smell. |
44,666,553 | If I start a new project in .net 4.5 and hit manage nuget packages, search for ajax, then hit install for ajax unobtrusive. I can then go into my cshtml file and type @Ajax.\_\_\_ e.g. @Ajax.beginForm
If I create a new project with Dot Net Core... I cannot, where instead it gives me the useless error:
"The name 'Ajax' does not exist in the current context"
I've searched the web, found nothing...
Basically I want to make a Form with an Ajax call as you could do in .net
Such as:
"`@using (Ajax.BeginForm("EmployeeMaster", "Home", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "divEmp" })) {`"
Anyone know what else I can try?
In the above, I can see that Ajax is a object of type AjaxHelper which comes from System.web.mvc.webviewpage... so maybe its never meant to be available for .net core | 2017/06/21 | [
"https://Stackoverflow.com/questions/44666553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/297201/"
] | While the `Ajax.BeginForm()` methods do not work, the actual unobtrusive Ajax html does. The C# methods just help generate the Html form tags. Forgive me in thse syntax is wrong, this is from memory, but you get the idea
```
@using (Ajax.BeginForm("EmployeeMaster", "Home", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "divEmp" }))
{
//form content
}
```
becomes
```
<form asp-action="EmployeeMaster" asp-controller="Home" method="POST" data-ajax="true" data-ajax-update="divEmp">
<!-- form content-->
</form>
```
**NOTE:** The above HTML STILL needs the unobtrusive ajax js files for it to wire up these data-\* attributes correctly. This is not a part of ASP.NET Core MVC | What is the equlivalent of OnSuccess
```
@using (Ajax.BeginForm("EmployeeMaster", "Home", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "divEmp", OnSuccess="ShowMessage" }))
{
//form content
}
``` |
130,233 | I started using subversion for one of my projects and it would be absolutely amazing if I could just export the latest version from the repository on my production server by for example running a php or perl script.
The production site is hosted with a shared hosting provider who doesn't allow shell access or for example the php [`exec()`](http://www.php.net/manual/en/function.exec.php) function. (I don't know much about perl; I only know that my hoster allows perl and custom cgi scripts).
Is it possible to perform a SVN export in this environment? | 2008/09/24 | [
"https://Stackoverflow.com/questions/130233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5005/"
] | As far as I know there is no SVN client fully written in PHP or Perl. SO without exec you're out of luck.
Workarounds:
* Depending on your own OS and what methods you have to access your web space you might be able to mount the web space in your local file system and just use your system's SVN client for checking out/updating.
* Again depending on your access methods (I'm guessing ftp or sftp) you might update a local checkout and sync any changes up onto the web space. | SVN supports access over WebDAV (i.e. HTTPS). This means for simple read access you don't actually need an SVN client to access an SVN repository. You can even use a web browser, or in your case any PHP function that accepts a URL as its argument. SVN has to be set up on the server side to work with apache, for more info check out the [svn red book](http://svnbook.red-bean.com/en/1.5/svn.serverconfig.html) |
130,233 | I started using subversion for one of my projects and it would be absolutely amazing if I could just export the latest version from the repository on my production server by for example running a php or perl script.
The production site is hosted with a shared hosting provider who doesn't allow shell access or for example the php [`exec()`](http://www.php.net/manual/en/function.exec.php) function. (I don't know much about perl; I only know that my hoster allows perl and custom cgi scripts).
Is it possible to perform a SVN export in this environment? | 2008/09/24 | [
"https://Stackoverflow.com/questions/130233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5005/"
] | As far as I know there is no SVN client fully written in PHP or Perl. SO without exec you're out of luck.
Workarounds:
* Depending on your own OS and what methods you have to access your web space you might be able to mount the web space in your local file system and just use your system's SVN client for checking out/updating.
* Again depending on your access methods (I'm guessing ftp or sftp) you might update a local checkout and sync any changes up onto the web space. | Have a look on this:
<http://www.randomsequence.com/articles/svn-backup-script/>
Of course, you still need exec for that, but as said it won't be difficult to code something in PHP that runs an http call to your svn server.
Or else, something like:
palaniraja.wordpress.com/2008/09/20/svn-export-only-updated-files-between-2-revisions/
Cheers! |
57,262,974 | How can I track a yellow object in python using opencv? And, if possible, how can I get the position of the object?
I've tried using the following method but i can't figure out how to lower and upper ranges work.
```
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while True:
screen = np.array(ImageGrab.grab())
ret, img = cap.read()
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
#Help
lower = np.array([])
upper = np.array([])
mask = cv2.inRange(hsv, lower, upper)
cv2.imshow('screen', mask)
if cv2.waitKey(25) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
```
It should find yellow objects and possibly get their position. | 2019/07/30 | [
"https://Stackoverflow.com/questions/57262974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11731680/"
] | You can convert the image to HSV then use color thresholding. Using this example image
[](https://i.stack.imgur.com/NecuP.jpg)
With lower/upper ranges of
```
lower = np.array([22, 93, 0])
upper = np.array([45, 255, 255])
```
We can isolate yellow
[](https://i.stack.imgur.com/VrYLU.png)
To get the position of the object (I'm assuming you want a bounding box), you can find contours on the resulting mask
[](https://i.stack.imgur.com/JhHfD.png)
```
import numpy as np
import cv2
image = cv2.imread('yellow.jpg')
original = image.copy()
image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
lower = np.array([22, 93, 0], dtype="uint8")
upper = np.array([45, 255, 255], dtype="uint8")
mask = cv2.inRange(image, lower, upper)
cnts = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
x,y,w,h = cv2.boundingRect(c)
cv2.rectangle(original, (x, y), (x + w, y + h), (36,255,12), 2)
cv2.imshow('mask', mask)
cv2.imshow('original', original)
cv2.waitKey()
```
You can use this script to find the color threshold ranges
```
import cv2
import sys
import numpy as np
def nothing(x):
pass
useCamera=False
# Check if filename is passed
if (len(sys.argv) <= 1) :
print("'Usage: python hsvThresholder.py <ImageFilePath>' to ignore camera and use a local image.")
useCamera = True
# Create a window
cv2.namedWindow('image')
# create trackbars for color change
cv2.createTrackbar('HMin','image',0,179,nothing) # Hue is from 0-179 for Opencv
cv2.createTrackbar('SMin','image',0,255,nothing)
cv2.createTrackbar('VMin','image',0,255,nothing)
cv2.createTrackbar('HMax','image',0,179,nothing)
cv2.createTrackbar('SMax','image',0,255,nothing)
cv2.createTrackbar('VMax','image',0,255,nothing)
# Set default value for MAX HSV trackbars.
cv2.setTrackbarPos('HMax', 'image', 179)
cv2.setTrackbarPos('SMax', 'image', 255)
cv2.setTrackbarPos('VMax', 'image', 255)
# Initialize to check if HSV min/max value changes
hMin = sMin = vMin = hMax = sMax = vMax = 0
phMin = psMin = pvMin = phMax = psMax = pvMax = 0
# Output Image to display
if useCamera:
cap = cv2.VideoCapture(0)
# Wait longer to prevent freeze for videos.
waitTime = 330
else:
img = cv2.imread(sys.argv[1])
output = img
waitTime = 33
while(1):
if useCamera:
# Capture frame-by-frame
ret, img = cap.read()
output = img
# get current positions of all trackbars
hMin = cv2.getTrackbarPos('HMin','image')
sMin = cv2.getTrackbarPos('SMin','image')
vMin = cv2.getTrackbarPos('VMin','image')
hMax = cv2.getTrackbarPos('HMax','image')
sMax = cv2.getTrackbarPos('SMax','image')
vMax = cv2.getTrackbarPos('VMax','image')
# Set minimum and max HSV values to display
lower = np.array([hMin, sMin, vMin])
upper = np.array([hMax, sMax, vMax])
# Create HSV Image and threshold into a range.
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, lower, upper)
output = cv2.bitwise_and(img,img, mask= mask)
# Print if there is a change in HSV value
if( (phMin != hMin) | (psMin != sMin) | (pvMin != vMin) | (phMax != hMax) | (psMax != sMax) | (pvMax != vMax) ):
print("(hMin = %d , sMin = %d, vMin = %d), (hMax = %d , sMax = %d, vMax = %d)" % (hMin , sMin , vMin, hMax, sMax , vMax))
phMin = hMin
psMin = sMin
pvMin = vMin
phMax = hMax
psMax = sMax
pvMax = vMax
# Display output image
cv2.imshow('image',output)
# Wait longer to prevent freeze for videos.
if cv2.waitKey(waitTime) & 0xFF == ord('q'):
break
# Release resources
if useCamera:
cap.release()
cv2.destroyAllWindows()
``` | The lower and upper value is always depends on the range you want to choose. There is no hard and fast rule that it should be in this range for a particular color. because it might vary even because of the lighting conditions.
With respect to your tracking, I would recommend you to follow this tutorial.
<https://www.pyimagesearch.com/2015/09/14/ball-tracking-with-opencv/>
It gives explanation about masking, segmentation, tracking. |
5,382,438 | I need a login to let 10 students to view educational material. Simple is good.
Perhaps it just redirects to a page if student logs in correctly. **Can you send me a link or example, or best tutorial?**
I was told JavaScript alone doesn't work, so the next simplest thing is preferred.
If there's an example where I don't have to rename all of my pages 'php', that would be better.
Thanks, | 2011/03/21 | [
"https://Stackoverflow.com/questions/5382438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/643573/"
] | I used this when I was learning to do secure logon using PHP.
<http://www.devshed.com/c/a/PHP/Creating-a-Secure-PHP-Login-Script/1/>
Found it quite helpful. | It depends on exactly what you're trying to do. If you want a pure-JS login system, you could do something fairly simple like XOR'ing a redirect page with a password, storing that in the page and then XOR'ing it again when they type in a password.
If you want an actual login-system, you need a back-end running some server (perhaps Node.js if you're trying to learn JavaScript), some type of database (e.g. MySQL), users stored in that database.
The front-end javascript might be responsible for validating the login via ajax. Using jQuery, something like:
```
function validateLogin(user, pass, successCallback, errorCallback){
$.get('/login', {user: user, pass:pass}, function(data){
if(data.status == 'success'){
successCallback();
}else{
errorCallback();
}
}
}
``` |
5,382,438 | I need a login to let 10 students to view educational material. Simple is good.
Perhaps it just redirects to a page if student logs in correctly. **Can you send me a link or example, or best tutorial?**
I was told JavaScript alone doesn't work, so the next simplest thing is preferred.
If there's an example where I don't have to rename all of my pages 'php', that would be better.
Thanks, | 2011/03/21 | [
"https://Stackoverflow.com/questions/5382438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/643573/"
] | You could possibly "do" it with JavaScript if you did some kind of AJAX function which called a php page, and then returned your value. This could work, and it's how a lot of sites do their logins actually. So, your client wouldn't have to rename their site, and you could just set up an array of logins on the php page.
This would NOT be secure at all, but it would work just fine.
I guess you would do something like this (I'm going to use [jQuery](http://jquery.com/) because it's easier to do Ajax with it. It's really easy to use, and if you're going to learn Javascript, it's probably better nowadays to know the basics and then use a framework library like jQuery)
```
$(document).ready(function(){
$("#NAME-OF-SUBMIT-BUTTON").submit(function(){
var username = $(this).find("#username");
var password = $(this).find("#password");
$("NAME-OF-DIV-FOR-RETURN").load('login.php', {['parameters']:,[username,password]},function(responseText){
if(responseText == 'SUCCESSFUL-RESPONSE-TEXT'){
$("#NAME-OF-FORM").html("Login Successful");
}
});
});
});
```
and of course you're going to want to set a session variable or cookie or something on your php page to indicate the user has logged in. Again, this is not very secure, but it's what I would do if it were like a homework assignment or just SUPER temporary. Of course, I would suggest making hard-coded usernames and passwords in an array on your original page in PHP with a postback to itself if you were going to go that temporary. Using Javascript and Ajax for this just seems like a bit much.
But, you requested it! | It depends on exactly what you're trying to do. If you want a pure-JS login system, you could do something fairly simple like XOR'ing a redirect page with a password, storing that in the page and then XOR'ing it again when they type in a password.
If you want an actual login-system, you need a back-end running some server (perhaps Node.js if you're trying to learn JavaScript), some type of database (e.g. MySQL), users stored in that database.
The front-end javascript might be responsible for validating the login via ajax. Using jQuery, something like:
```
function validateLogin(user, pass, successCallback, errorCallback){
$.get('/login', {user: user, pass:pass}, function(data){
if(data.status == 'success'){
successCallback();
}else{
errorCallback();
}
}
}
``` |
5,382,438 | I need a login to let 10 students to view educational material. Simple is good.
Perhaps it just redirects to a page if student logs in correctly. **Can you send me a link or example, or best tutorial?**
I was told JavaScript alone doesn't work, so the next simplest thing is preferred.
If there's an example where I don't have to rename all of my pages 'php', that would be better.
Thanks, | 2011/03/21 | [
"https://Stackoverflow.com/questions/5382438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/643573/"
] | Simple...
Create a file called functions and insert the following:
```
session_start();
$_GLOBALS['users'] = array(
//'username' => 'password'
'robert' => 'my_pass'
);
function isAuthed()
{
if(empty($_SESSION['logged_in']))
{
if(!empty($_REQUEST['username']) || !empty($_REQUEST['password']))
{
if(isset($_GLOBALS['users']) && is_array($_GLOBALS['users']))
{
if(isset($_GLOBALS['users'][$_REQUEST['username']]) && $_GLOBALS['users'][$_REQUEST['username']] === $_REQUEST['password'])
{
$_SESSION['logged_in'] = true;
return true;
}
}
}
}else
{
return true;
}
return false;
}
```
and then in your secured pages just do:
```
if(!isAuthed())
{
die("You're not authorized to see this page");
}
```
and on your login page just create a form that sends the username, password to the an area of your site that your authorizing
Note: This is not copy and past'able code, this is for example purposes only. | It depends on exactly what you're trying to do. If you want a pure-JS login system, you could do something fairly simple like XOR'ing a redirect page with a password, storing that in the page and then XOR'ing it again when they type in a password.
If you want an actual login-system, you need a back-end running some server (perhaps Node.js if you're trying to learn JavaScript), some type of database (e.g. MySQL), users stored in that database.
The front-end javascript might be responsible for validating the login via ajax. Using jQuery, something like:
```
function validateLogin(user, pass, successCallback, errorCallback){
$.get('/login', {user: user, pass:pass}, function(data){
if(data.status == 'success'){
successCallback();
}else{
errorCallback();
}
}
}
``` |
61,816,693 | I am new to c++
I tried to create a simple calculator.
I am not sure why but when I run this code, it prints weird results, for example: 15 \* 5 = 753
```
int a;
int b;
char param;
printf("Enter Two numbers:\n");
scanf_s("%d %d", &a, &b);
printf("%d %d\n", a, b);
printf("Enter mathematical operator *-/+\n");
int result;
scanf_s(" %c", ¶m);
switch (param)
{
case ('+'):
result = a + b;
printf("%d", result);
case ('-'):
result = a - b;
printf("%d", result);
case ('*'):
result = a * b;
printf("%d", result);
case ('/'):
result = a / b;
printf("%d", result);
}
``` | 2020/05/15 | [
"https://Stackoverflow.com/questions/61816693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13353615/"
] | There is no break between cases which explain that your example enter in case '\*' print 75 (15 \* 5) as there is no break continue to '/' and print 3 (15 / 5). And that's what you got 753.
```
switch (param)
{
case ('+'):
result = a + b;
printf("%d", result);
break;
case ('-'):
result = a - b;
printf("%d", result);
break;
case ('*'):
result = a * b;
printf("%d", result);
break;
case ('/'):
result = a / b;
printf("%d", result);
break;
}
``` | Remember to [include `break;` statement](https://beginnersbook.com/2017/08/cpp-switch-case/) after each `case`
```
int a;
int b;
char param;
printf("Enter Two numbers:\n");
scanf_s("%d %d", &a, &b);
printf("%d %d\n", a, b);
printf("Enter mathematical operator *-/+\n");
int result;
scanf_s(" %c", ¶m);
switch (param)
{
case ('+'):
result = a + b;
printf("%d", result);
break;
case ('-'):
result = a - b;
printf("%d", result);
break;
case ('*'):
result = a * b;
printf("%d", result);
break;
case ('/'):
result = a / b;
printf("%d\n", result);
break;
}
```
---
[Working code](https://ideone.com/QIZkBq) |
12,293,503 | I was just thinking that in a large web application where tens of connections are made to database for every client using the application, there is a possibility that very few of the connections are gone unclosed. *Though it is strictly up to us that we must close all connections explicitly* but, you know, there may be mistakes. If this happens then after some days we may find that our connection pool has reached its maximum size and the application is not running being unable to get a connection.
Actually I am facing this problem for one of my projects and whenever the connection pool reaches its maximum size I just restart the server which is not good.
I am curious to know how to handle this issue in a better manner and I want to know that is there such a thing that I can close all the unused active connections in my connection pool explicitly in a regular interval e.g every 72 hours using java code ?
I am talking about Java/J2ee technologies and my server is Glassfish Application Server2.1.
**EDIT:** I am using the connection pool that Glassfish Application server provides within, not any third party connection pool and using this pool using JNDI DataSource.
need your suggestions........
Thanks | 2012/09/06 | [
"https://Stackoverflow.com/questions/12293503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343275/"
] | You have quite a number of options:
**cygwin**
Install [cygwin](http://www.cygwin.com/). It will give you a bash.
**mingw**
The [minimal GNU for windows](http://www.mingw.org/). Comes with set of commands, compilers. This came with my Git on Windows and now the default shell for small scripts
**VM, such as VirtualBox**
There are tons on VMs, VirtualBox being easy to use(it powers the [Boot2Docker](https://github.com/boot2docker/boot2docker)). You can do development and test on real Linux distros.
**Ubuntu on Windows 10**
There is new kid on the block. This allows you to run User Space Ubuntu using Windows Subsystem for Linux (WSL). see more on it at [Microsoft blog](https://blogs.windows.com/buildingapps/2016/03/30/run-bash-on-ubuntu-on-windows/)
**Other notes/IDE support**
Shell scripts should be small, requires less IDE etc. I use VIM with syntax highligthing. But it seems [ShellED](http://sourceforge.net/projects/shelled/) may be useful in your case. I got the link from answer for this question - [Bash script plugin for Eclipse?](https://stackoverflow.com/questions/1356827/bash-script-plugin-for-eclipse)
IntelliJ has couple of [plugins](https://plugins.jetbrains.com/plugin/4230?pr=idea) too for Bash.. | There is cygwin , that's a linux console for windows.. so you can execute all the linux command with it. |
12,293,503 | I was just thinking that in a large web application where tens of connections are made to database for every client using the application, there is a possibility that very few of the connections are gone unclosed. *Though it is strictly up to us that we must close all connections explicitly* but, you know, there may be mistakes. If this happens then after some days we may find that our connection pool has reached its maximum size and the application is not running being unable to get a connection.
Actually I am facing this problem for one of my projects and whenever the connection pool reaches its maximum size I just restart the server which is not good.
I am curious to know how to handle this issue in a better manner and I want to know that is there such a thing that I can close all the unused active connections in my connection pool explicitly in a regular interval e.g every 72 hours using java code ?
I am talking about Java/J2ee technologies and my server is Glassfish Application Server2.1.
**EDIT:** I am using the connection pool that Glassfish Application server provides within, not any third party connection pool and using this pool using JNDI DataSource.
need your suggestions........
Thanks | 2012/09/06 | [
"https://Stackoverflow.com/questions/12293503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343275/"
] | Install Cygwin to execute the commands. However you can use NotePad++ as editor which has native windows binaries.
<http://www.cygwin.com/>
<http://notepad-plus-plus.org/> | I had a similar problem.
I like both Linux and Windows, and I am working on both systems, but for programming (and generally, for text editing) I use Windows, for different reasons. For example, I write C/C++ code on Windows, using the Windows DevC++ IDE, then I can compile this project on Linux, by sharing the files on LAN. Now I have to write long scripts, and I would like to do it in a similar way. Ok, maybe its a special request, but maybe I am not the only one who works in such a mixed environment.
First, I tried notepad++ (it is suggested by others as well), but does it support syntax highlight for Linux scripts? I didn't found this feature...
Then I tried gedit compiled for Windows. It requires the GTK library installed (actually it was already on my Windows). Gedit has syntax highlight for scripts!
So I suggest using gedit for Windows for this case. The edited script can not directly be started/tested with it, but for editing, it is fine! |
12,293,503 | I was just thinking that in a large web application where tens of connections are made to database for every client using the application, there is a possibility that very few of the connections are gone unclosed. *Though it is strictly up to us that we must close all connections explicitly* but, you know, there may be mistakes. If this happens then after some days we may find that our connection pool has reached its maximum size and the application is not running being unable to get a connection.
Actually I am facing this problem for one of my projects and whenever the connection pool reaches its maximum size I just restart the server which is not good.
I am curious to know how to handle this issue in a better manner and I want to know that is there such a thing that I can close all the unused active connections in my connection pool explicitly in a regular interval e.g every 72 hours using java code ?
I am talking about Java/J2ee technologies and my server is Glassfish Application Server2.1.
**EDIT:** I am using the connection pool that Glassfish Application server provides within, not any third party connection pool and using this pool using JNDI DataSource.
need your suggestions........
Thanks | 2012/09/06 | [
"https://Stackoverflow.com/questions/12293503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343275/"
] | You have quite a number of options:
**cygwin**
Install [cygwin](http://www.cygwin.com/). It will give you a bash.
**mingw**
The [minimal GNU for windows](http://www.mingw.org/). Comes with set of commands, compilers. This came with my Git on Windows and now the default shell for small scripts
**VM, such as VirtualBox**
There are tons on VMs, VirtualBox being easy to use(it powers the [Boot2Docker](https://github.com/boot2docker/boot2docker)). You can do development and test on real Linux distros.
**Ubuntu on Windows 10**
There is new kid on the block. This allows you to run User Space Ubuntu using Windows Subsystem for Linux (WSL). see more on it at [Microsoft blog](https://blogs.windows.com/buildingapps/2016/03/30/run-bash-on-ubuntu-on-windows/)
**Other notes/IDE support**
Shell scripts should be small, requires less IDE etc. I use VIM with syntax highligthing. But it seems [ShellED](http://sourceforge.net/projects/shelled/) may be useful in your case. I got the link from answer for this question - [Bash script plugin for Eclipse?](https://stackoverflow.com/questions/1356827/bash-script-plugin-for-eclipse)
IntelliJ has couple of [plugins](https://plugins.jetbrains.com/plugin/4230?pr=idea) too for Bash.. | Install Cygwin to execute the commands. However you can use NotePad++ as editor which has native windows binaries.
<http://www.cygwin.com/>
<http://notepad-plus-plus.org/> |
12,293,503 | I was just thinking that in a large web application where tens of connections are made to database for every client using the application, there is a possibility that very few of the connections are gone unclosed. *Though it is strictly up to us that we must close all connections explicitly* but, you know, there may be mistakes. If this happens then after some days we may find that our connection pool has reached its maximum size and the application is not running being unable to get a connection.
Actually I am facing this problem for one of my projects and whenever the connection pool reaches its maximum size I just restart the server which is not good.
I am curious to know how to handle this issue in a better manner and I want to know that is there such a thing that I can close all the unused active connections in my connection pool explicitly in a regular interval e.g every 72 hours using java code ?
I am talking about Java/J2ee technologies and my server is Glassfish Application Server2.1.
**EDIT:** I am using the connection pool that Glassfish Application server provides within, not any third party connection pool and using this pool using JNDI DataSource.
need your suggestions........
Thanks | 2012/09/06 | [
"https://Stackoverflow.com/questions/12293503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343275/"
] | If you want to use a simple environment emulating all Linux environment as alternative to cygwin (more lightweight) you can try [mingw](http://www.mingw.org/) and you can use notepad++ or emacs or vim to provide some syntax highlight on sh scripts. | Install Cygwin to execute the commands. However you can use NotePad++ as editor which has native windows binaries.
<http://www.cygwin.com/>
<http://notepad-plus-plus.org/> |
12,293,503 | I was just thinking that in a large web application where tens of connections are made to database for every client using the application, there is a possibility that very few of the connections are gone unclosed. *Though it is strictly up to us that we must close all connections explicitly* but, you know, there may be mistakes. If this happens then after some days we may find that our connection pool has reached its maximum size and the application is not running being unable to get a connection.
Actually I am facing this problem for one of my projects and whenever the connection pool reaches its maximum size I just restart the server which is not good.
I am curious to know how to handle this issue in a better manner and I want to know that is there such a thing that I can close all the unused active connections in my connection pool explicitly in a regular interval e.g every 72 hours using java code ?
I am talking about Java/J2ee technologies and my server is Glassfish Application Server2.1.
**EDIT:** I am using the connection pool that Glassfish Application server provides within, not any third party connection pool and using this pool using JNDI DataSource.
need your suggestions........
Thanks | 2012/09/06 | [
"https://Stackoverflow.com/questions/12293503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343275/"
] | I prefer [Gow](https://github.com/bmatzelle/gow/wiki) (Gnu on Windows) over Cygwin. Both will give you bash on Windows, but Cygwin has unnatural conventions for filesystem access (`/cygdive/c/some/path` instead of `c:\some\path`).
The native windows command terminal is pretty lame, take a look at [Conemu](https://conemu.github.io/).
I'm not aware of any bash IDE, but there are a plethora of windows text editors with decent syntax highlight for bash scripts. I like [Notepad++](http://notepad-plus-plus.org/) and [Sublime text](http://www.sublimetext.com/) (the multiple cursor feature from Sublime rocks!). I don't recommend bash for anything with more than 30 lines, if you ever feel the need for an IDE, perhaps the task is more suited for Python, Ruby or Perl (IMHO Python is more maintainable). | Install Cygwin to execute the commands. However you can use NotePad++ as editor which has native windows binaries.
<http://www.cygwin.com/>
<http://notepad-plus-plus.org/> |
12,293,503 | I was just thinking that in a large web application where tens of connections are made to database for every client using the application, there is a possibility that very few of the connections are gone unclosed. *Though it is strictly up to us that we must close all connections explicitly* but, you know, there may be mistakes. If this happens then after some days we may find that our connection pool has reached its maximum size and the application is not running being unable to get a connection.
Actually I am facing this problem for one of my projects and whenever the connection pool reaches its maximum size I just restart the server which is not good.
I am curious to know how to handle this issue in a better manner and I want to know that is there such a thing that I can close all the unused active connections in my connection pool explicitly in a regular interval e.g every 72 hours using java code ?
I am talking about Java/J2ee technologies and my server is Glassfish Application Server2.1.
**EDIT:** I am using the connection pool that Glassfish Application server provides within, not any third party connection pool and using this pool using JNDI DataSource.
need your suggestions........
Thanks | 2012/09/06 | [
"https://Stackoverflow.com/questions/12293503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343275/"
] | You have quite a number of options:
**cygwin**
Install [cygwin](http://www.cygwin.com/). It will give you a bash.
**mingw**
The [minimal GNU for windows](http://www.mingw.org/). Comes with set of commands, compilers. This came with my Git on Windows and now the default shell for small scripts
**VM, such as VirtualBox**
There are tons on VMs, VirtualBox being easy to use(it powers the [Boot2Docker](https://github.com/boot2docker/boot2docker)). You can do development and test on real Linux distros.
**Ubuntu on Windows 10**
There is new kid on the block. This allows you to run User Space Ubuntu using Windows Subsystem for Linux (WSL). see more on it at [Microsoft blog](https://blogs.windows.com/buildingapps/2016/03/30/run-bash-on-ubuntu-on-windows/)
**Other notes/IDE support**
Shell scripts should be small, requires less IDE etc. I use VIM with syntax highligthing. But it seems [ShellED](http://sourceforge.net/projects/shelled/) may be useful in your case. I got the link from answer for this question - [Bash script plugin for Eclipse?](https://stackoverflow.com/questions/1356827/bash-script-plugin-for-eclipse)
IntelliJ has couple of [plugins](https://plugins.jetbrains.com/plugin/4230?pr=idea) too for Bash.. | If you want to use a simple environment emulating all Linux environment as alternative to cygwin (more lightweight) you can try [mingw](http://www.mingw.org/) and you can use notepad++ or emacs or vim to provide some syntax highlight on sh scripts. |
12,293,503 | I was just thinking that in a large web application where tens of connections are made to database for every client using the application, there is a possibility that very few of the connections are gone unclosed. *Though it is strictly up to us that we must close all connections explicitly* but, you know, there may be mistakes. If this happens then after some days we may find that our connection pool has reached its maximum size and the application is not running being unable to get a connection.
Actually I am facing this problem for one of my projects and whenever the connection pool reaches its maximum size I just restart the server which is not good.
I am curious to know how to handle this issue in a better manner and I want to know that is there such a thing that I can close all the unused active connections in my connection pool explicitly in a regular interval e.g every 72 hours using java code ?
I am talking about Java/J2ee technologies and my server is Glassfish Application Server2.1.
**EDIT:** I am using the connection pool that Glassfish Application server provides within, not any third party connection pool and using this pool using JNDI DataSource.
need your suggestions........
Thanks | 2012/09/06 | [
"https://Stackoverflow.com/questions/12293503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343275/"
] | You have quite a number of options:
**cygwin**
Install [cygwin](http://www.cygwin.com/). It will give you a bash.
**mingw**
The [minimal GNU for windows](http://www.mingw.org/). Comes with set of commands, compilers. This came with my Git on Windows and now the default shell for small scripts
**VM, such as VirtualBox**
There are tons on VMs, VirtualBox being easy to use(it powers the [Boot2Docker](https://github.com/boot2docker/boot2docker)). You can do development and test on real Linux distros.
**Ubuntu on Windows 10**
There is new kid on the block. This allows you to run User Space Ubuntu using Windows Subsystem for Linux (WSL). see more on it at [Microsoft blog](https://blogs.windows.com/buildingapps/2016/03/30/run-bash-on-ubuntu-on-windows/)
**Other notes/IDE support**
Shell scripts should be small, requires less IDE etc. I use VIM with syntax highligthing. But it seems [ShellED](http://sourceforge.net/projects/shelled/) may be useful in your case. I got the link from answer for this question - [Bash script plugin for Eclipse?](https://stackoverflow.com/questions/1356827/bash-script-plugin-for-eclipse)
IntelliJ has couple of [plugins](https://plugins.jetbrains.com/plugin/4230?pr=idea) too for Bash.. | Everyone has said to go full Linux or use various mocks.
Cloud9.io is a good option if you don't need that much.
You can set up a "workspace" which can be accessed online, lets you write in literally any language similar to np++, but the best part is, it's an online Linux, so you have a terminal, with all your shell commands - no mock up, no dual boot.
The downside to this is that the free users aren't given that much power, so if you wanted to execute some high-level maths or output a large image, it will crash as you will be using too much memory. But it is still really worth getting into, it's only ever crashed once on me, and I do some pretty memory-intensive things. |
12,293,503 | I was just thinking that in a large web application where tens of connections are made to database for every client using the application, there is a possibility that very few of the connections are gone unclosed. *Though it is strictly up to us that we must close all connections explicitly* but, you know, there may be mistakes. If this happens then after some days we may find that our connection pool has reached its maximum size and the application is not running being unable to get a connection.
Actually I am facing this problem for one of my projects and whenever the connection pool reaches its maximum size I just restart the server which is not good.
I am curious to know how to handle this issue in a better manner and I want to know that is there such a thing that I can close all the unused active connections in my connection pool explicitly in a regular interval e.g every 72 hours using java code ?
I am talking about Java/J2ee technologies and my server is Glassfish Application Server2.1.
**EDIT:** I am using the connection pool that Glassfish Application server provides within, not any third party connection pool and using this pool using JNDI DataSource.
need your suggestions........
Thanks | 2012/09/06 | [
"https://Stackoverflow.com/questions/12293503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343275/"
] | The Bash shell is coming to Windows 10 in the upcoming Anniversary Update (Redstone).
The Bash shell is coming to Windows. Yes, the real Bash is coming to Windows, said Microsoft's Kevin Gallo at Build 2016 keynote. This is not a VM [Virtual Machine]. This is not cross-compiled tools. This is native."
Here's the steps to run Bash on Windows 10 OS:
----------------------------------------------
1. Open the Windows Start menu
2. Type "bash" [hit enter]
3. Which opens a console running Ubuntu's `/bin/bash` with full access to all of Ubuntu user space
Yes, you are right, that means `apt`, `set`, `ssh`, `rsync`, `find`, `ls`, `grep`, `awk`, `sed`, `sort`, `xargs`, `md5sum`, `gpg`, `curl`, `wget`, `apache`, `mysql`, `python`, `perl`, `ruby`, `ruby gem`, `php`, `gcc`, `tar`, `vim`, `emacs`, `diff`, `patch`, nano...and most of the tens of thousands binary packages available in the Ubuntu archives!


Reference
---------
1. [Step-vise Guide to Enable Windows 10’s Ubuntu Bash Shell (Windows Subsystem for Linux)](http://www.developerinsider.in/step-vise-guide-to-enable-windows-10s-ubuntu-bash-shell-windows-subsystem-for-linux/)
2. [The Bash shell is coming to Windows 10 in the upcoming Anniversary Update (Redstone).](http://www.developerinsider.in/2016/04/07/the-bash-shell-is-coming-to-windows-10-in-the-upcoming-anniversary-update-redstone/)
3. [Run native Bash on Ubuntu on Windows](https://blogs.windows.com/buildingapps/2016/03/30/run-bash-on-ubuntu-on-windows/) | There is cygwin , that's a linux console for windows.. so you can execute all the linux command with it. |
12,293,503 | I was just thinking that in a large web application where tens of connections are made to database for every client using the application, there is a possibility that very few of the connections are gone unclosed. *Though it is strictly up to us that we must close all connections explicitly* but, you know, there may be mistakes. If this happens then after some days we may find that our connection pool has reached its maximum size and the application is not running being unable to get a connection.
Actually I am facing this problem for one of my projects and whenever the connection pool reaches its maximum size I just restart the server which is not good.
I am curious to know how to handle this issue in a better manner and I want to know that is there such a thing that I can close all the unused active connections in my connection pool explicitly in a regular interval e.g every 72 hours using java code ?
I am talking about Java/J2ee technologies and my server is Glassfish Application Server2.1.
**EDIT:** I am using the connection pool that Glassfish Application server provides within, not any third party connection pool and using this pool using JNDI DataSource.
need your suggestions........
Thanks | 2012/09/06 | [
"https://Stackoverflow.com/questions/12293503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343275/"
] | For Eclipse Luna Should use this one old version fails on UI error
```
Help > Install New Software… > Add…
```
Name: ShellEd
Location: <http://sourceforge.net/projects/shelled/files/shelled/update/> | I had a similar problem.
I like both Linux and Windows, and I am working on both systems, but for programming (and generally, for text editing) I use Windows, for different reasons. For example, I write C/C++ code on Windows, using the Windows DevC++ IDE, then I can compile this project on Linux, by sharing the files on LAN. Now I have to write long scripts, and I would like to do it in a similar way. Ok, maybe its a special request, but maybe I am not the only one who works in such a mixed environment.
First, I tried notepad++ (it is suggested by others as well), but does it support syntax highlight for Linux scripts? I didn't found this feature...
Then I tried gedit compiled for Windows. It requires the GTK library installed (actually it was already on my Windows). Gedit has syntax highlight for scripts!
So I suggest using gedit for Windows for this case. The edited script can not directly be started/tested with it, but for editing, it is fine! |
12,293,503 | I was just thinking that in a large web application where tens of connections are made to database for every client using the application, there is a possibility that very few of the connections are gone unclosed. *Though it is strictly up to us that we must close all connections explicitly* but, you know, there may be mistakes. If this happens then after some days we may find that our connection pool has reached its maximum size and the application is not running being unable to get a connection.
Actually I am facing this problem for one of my projects and whenever the connection pool reaches its maximum size I just restart the server which is not good.
I am curious to know how to handle this issue in a better manner and I want to know that is there such a thing that I can close all the unused active connections in my connection pool explicitly in a regular interval e.g every 72 hours using java code ?
I am talking about Java/J2ee technologies and my server is Glassfish Application Server2.1.
**EDIT:** I am using the connection pool that Glassfish Application server provides within, not any third party connection pool and using this pool using JNDI DataSource.
need your suggestions........
Thanks | 2012/09/06 | [
"https://Stackoverflow.com/questions/12293503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343275/"
] | Since you need to write linux shell scripts, you are learning Linux. So you should install Linux on your machine (preferably on its own partition and boot from it, otherwise in a VM).
Using `cygwin` or whatever imitation of Linux shell is not using Linux. You'll learn a lot more by installing and using Linux (and by developing on it with an editor like `emacs` or `gedit` or `gvim` ....). Also, take advantage that Linux is almost entirely [free software](http://www.fsf.org/), so you can study its source code and improve it.
Not installing Linux is not doing yourself a favor.
I believe `cygwin` is for those who love Linux but have to use Windows. It cannot give you the entire Linux feeling (e.g. you won't be able to write shell scripts looking into `/proc` which does not exist in Windows, even with cygwin). | There is cygwin , that's a linux console for windows.. so you can execute all the linux command with it. |
21,182,948 | I have a php/apache page that takes a long time to load. Basically, it looks like this:
```
<?php
doHeavyStuff_1();
doHeavyStuff_2();
doHeavyStuff_3();
printResults();
?>
```
It happens from time to time that the client disconnects in the middle of the processing, say, between step1 and step2. Is there a way in php to check if the client is still connected and to stop further processing if it isn't? I'd like my code to be like this:
```
<?php
doHeavyStuff_1();
if(<clientDisconnected>) die;
doHeavyStuff_2();
if(<clientDisconnected>) die;
doHeavyStuff_3();
if(<clientDisconnected>) die;
printResults();
?>
``` | 2014/01/17 | [
"https://Stackoverflow.com/questions/21182948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/989121/"
] | Look into using the [connection\_aborted](http://php.net/manual/en/function.connection-aborted.php) function. | Normally PHP (as an apache module) should stop automatically if the user disconnects. No work is necessary.
Just if you are interested: if you want PHP to continue processing there is the function [`ignore_user_abort()`](http://www.php.net/manual/en/function.ignore-user-abort.php). You should start to read the manual page and especially the comments to see how it can be used and which problems can occur. |
53,136,376 | I am trying to make some buttons to control some things in my canvas. I want them to appear in the right side of canvas, so i use css to style and move them. I also made a timer which stars when pressing the green button START and stops when pressing FINISH. My problem is that the first buttons do not work or pressed when i moved then in the right position. Do you have any idea why this happens?? Here is the part of my code that does what i am saying. Thank you in advance!!!
```js
document.body.style.backgroundColor = "#FAFAD2";
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
window.requestAnimFrame = (function(callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
var startTime = Date.now();
var t;
var timer_is_on = 0;
function timedCount() {
var elapsedTime = Date.now() - startTime;
document.getElementById("timer").innerHTML = (elapsedTime / 1000).toFixed(3);
t = setTimeout("timedCount()", 100);
}
function doTimer() {
if (!timer_is_on) {
timer_is_on = 1;
timedCount();
}
}
function stopCount() {
clearTimeout(t);
timer_is_on = 0;
}
$('#start').on('click', function() {
doTimer();
});
$('#finish').on('click', function() {
stopCount();
});
```
```css
.timer {
position: absolute;
bottom: 55px;
left: 600px;
}
.both,
.one,
.two,
.timer {
display: block;
padding: 30px;
position: absolute;
left: 600px;
}
.both button {
background-color: #4CAF50;
border: 1px solid black;
margin-left: 50px;
color: white;
padding: 15px 10px;
text-align: center;
font-size: 16px;
font-weight: bold;
cursor: pointer;
width: 100px;
display: block;
position: relative;
bottom: 20px;
}
.one button {
border: 1px solid black;
color: white;
padding: 15px 5px;
text-align: center;
font-size: 16px;
font-weight: bold;
cursor: pointer;
width: 200px;
display: block;
position: relative;
top: 100px;
}
.two button {
border: 1px solid black;
color: white;
padding: 15px 5px;
text-align: center;
font-size: 16px;
font-weight: bold;
cursor: pointer;
width: 200px;
display: block;
position: relative;
top: 300px;
}
.timer button {
background-color: #696969;
border: 1px solid black;
color: white;
padding: 12px 8px;
text-align: center;
font-size: 15px;
font-weight: bold;
cursor: pointer;
width: 80px;
}
```
```html
<!DOCTYPE html>
<html>
<head>
<title> Simulation </title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class='both'>
<button type='button' id='start'>START</button>
<button type='button' id='stop'>STOP</button>
</div>
<div class='one'>
<button type='button' id='start1' style='background-color:#B22222;'>START 1</button>
<button type='button' id='stop1' style='background-color:#B22222;'>STOP 1</button>
<button type='button' id='position1' style='background-color:#B22222;'>POSITION 1</button>
</div>
<div class='two'>
<button type='button' id='start2' style='background-color:#FFD700;'>START 2</button>
<button type='button' id='stop2' style='background-color:#FFD700;'>STOP 2</button>
<button type='button' id='position2' style='background-color:#FFD700;'>POSITION 2</button>
</div>
<div class='timer'>
<span id="timer"></span> sec
<button type='button' id='finish'>FINISH</button>
</div>
<br>
<canvas id="myCanvas" width="455" height="650" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
</body>
</html>
``` | 2018/11/03 | [
"https://Stackoverflow.com/questions/53136376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9958802/"
] | try adding z-index to button wrapper and a position relative for canvas
`.both {z-index:99;}
canvas{position:relative;z-index:10;}` | Your code isn't working because you're trying to set a timeout on a string, not a function:
```
function timedCount() {
var elapsedTime = Date.now() - startTime;
document.getElementById("timer").innerHTML = (elapsedTime / 1000).toFixed(3);
t = setTimeout("timedCount()", 100);
}
```
Change this line:
```
t = setTimeout(timedCount, 100);
```
And it should work. |
14,775,587 | I have a number of projects which are joined into a solution. Every project has it's own directory structure, and csproj files are located on diferrent level of folder structure.
Every csproj has OutputPath property specified. OutputPath - is a relative path and it varies from project to project in such a way so all projects have the same output dir.
It is work OK if I build a separate project. But everything changes if I try to build solution file. In this case every project output folder differs (depends on a number of '..\' in that project's OutputPath).
I do know, that before some moment all was working fine. Nobody changed build.cmd neither any sln or csproj files. But now I have situation described above.
So my question is - what affects how relative path is evaluated? I mean how can I force relative OutputPath to be evaluated starting from folder where csproj file of that particular project is located. Not from folder where .sln file is.
```
Let's assume I have following directory structure:
dir1
a.sln
dir2
a.csproj
dir21
dir3
b.csproj
```
a.csproj has output path set to '../../\_bin' which is just above dir1 if counted from a.csproj folder
b.csproj has output path set to '../../../\_bin' which is same - just about dir1 if counted from b.csproj
a.sln contains both - a.csproj and b.csproj.
When I run msbuild I get a project build to 'dir1/../../\_bin' and b project to 'dir1/../../../\_bin' - both relative paths of projects files are counted from solution file location, not project files. | 2013/02/08 | [
"https://Stackoverflow.com/questions/14775587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/354554/"
] | Well, I was able to find out what was causing this. That was custom .targets file, which was inferring SolutionDir property at the start of any msbuild.
I did find out that by using MSBuild Explorer. The tool proved to be very useful in my case - I was not aware of third party .target files on my system. | From [Msbuild Import Element description](http://msdn.microsoft.com/en-us/library/92x05xfs.aspx)
>
> Relative paths in imported projects are interpreted relative to the
> directory of the importing project. Therefore, if a project file is
> imported into several project files in different locations, the
> relative paths in the imported project file will be interpreted
> differently for each imported project.
>
>
> All MSBuild reserved properties that relate to the project file, for example, MSBuildProjectDirectory
> and MSBuildProjectFile, that are referenced in an imported project are
> assigned values based on the importing project file.
>
>
>
If you add more details or few samples to your question - it will be easier to understand exact problem.
Edit:
Okay, lets try to pinpoint that mystery. First of all - OutputPath could be affected by Environment variables.
2nd - during build sln file transformed into msbuild project file format and stored in temp file. You can get that temporary file if you execute in cmd "set msbuildemitsolution=1" and then trigger build via command line. There you can check that file and see how your individual projects called. But I suppose you will see multiple .csproj /> entries. And global msbuild properties inherited by that calls.
So I suspect if everything was fine before some point and no changes were made - you are missing OutputPath environment variable or some other variable that contributed to construction of OutputPath.
BTW - I think if you want to fix your issue with forcing relative dir - you also can use $(MSBuildProjectDirectory). This is one of msbuild reserved properties (from [here](http://msdn.microsoft.com/en-us/library/vstudio/ms164309.aspx)), but this will require yo adjust your OutputPath in each csproj file. What i, personally, prefer to avoid, because it could affect some other targets and introduce subtle issues. |
20,819,876 | I have a MVC application and inject my repositories to my controller what works properly.
Additionally I have a Webservice in my solution which uses exactly the same repositories but when my Webservice is called my repository properties are null.
I register my repositories the following way:
```
container.Register(Classes.FromAssembly(Assembly.GetAssembly(typeof(HdtRepository))).InSameNamespaceAs<HdtRepository>().WithService.DefaultInterfaces().LifestyleTransient());
```
my repository properties look like:
```
public IUserRepository _userRepo { get; set; }
public IHdtRepository _hdtRepo { get; set; }
public ITimeRecordRepository _timeRepo { get; set; }
```
Can someone tell me why the repositories are not injected to my webservice?
For now I added the following to the constructor of my webservice:
```
public MyWebservice()
{
_userRepo = MvcApplication.container.Resolve<IUserRepository>();
_hdtRepo = MvcApplication.container.Resolve<IHdtRepository>();
_timeRepo = MvcApplication.container.Resolve<ITimeRecordRepository>();
_locationRepo = MvcApplication.container.Resolve<ILocationRepository>();
_wayRepo = MvcApplication.container.Resolve<IWayPointRepository>();
_wayDataRepo = MvcApplication.container.Resolve<IWayDataRepository>();
}
```
but as far as I know this is actually a antipattern.
I'm new to all that IoC stuff so could someone please tell me where the problem is.
Cheers,
Stefan | 2013/12/28 | [
"https://Stackoverflow.com/questions/20819876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1845959/"
] | The backbutton text is set in the navigation view before displaying the detailed view.
```
Ext.define('mimo.view.PostPanel', {
extend: 'Ext.NavigationView',
```
`xtype: 'postPanel',
requires: [
'mimo.view.post.PostList'
],
config: {
title: 'Blog',
iconCls: 'home',
// set the back button text here
defaultBackButtonText: 'Volver',
items:[{
title: 'Las entradas de blog',
xtype: 'postlist'
}]
}
});
</pre>` | You are extending Ext.Panel. Ext.Panel does not accept the navigationBar configuration, you probably want to use Ext.navigation.View. Then on that view you can pass the defaultBackButtonText property. Otherwise if you want to customize the button further, inside of navigationBar object you want to specify a button object with button properties. |
56,352,970 | I am using a 3rd-party library it will hide iOS status bar when calling. After that, I can't show the status bar back on screen.
I can control status bar by `StatusBar` component in React Native normally.
However, I tried to call a iOS library <https://www.dynamsoft.com/Products/dynamsoft-webcam-sdk.aspx> it will hide the status bar when showing it's screen.
After it hide the status bar, I can't show it up again using `StatusBar.setHidden(false)`.
It don't prompt any error, just simply no effect.
Anyone knows what's going on and how can I show the status bar back in this situation? | 2019/05/29 | [
"https://Stackoverflow.com/questions/56352970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7897319/"
] | Use [`np.isin`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.isin.html) -
```
In [8]: b[np.isin(b[:,0],a)]
Out[8]:
array([[ 10, 8, 52, 30, 15],
[ 11, 81, 152, 54, 112],
[ 13, 82, 84, 63, 24]])
```
With sorted `a`, we can also use [`np.searchsorted`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.searchsorted.html) -
```
idx = np.searchsorted(a,b[:,0])
idx[idx==len(a)] = 0
out = b[a[idx] == b[:,0]]
```
If you have an array with different number of elements per row, which is essentially array of lists, you need to modify the slicing part. So, in that case, get the first off elements -
```
b0 = [bi[0] for bi in b]
```
Then, use `b0` to replace all instances of `b[:,0]` in earlier posted methods. | Use list comprehension:
```
c = [l for l in b if l[0] in a]
```
Output:
```
[[10, 8, 52, 30, 15], [11, 81, 152, 54, 112], [13, 82, 84, 63, 24]]
```
If your `list` or `array`s are considerably large, using `numpy.isin` can be significantly faster:
```
b[np.isin(b[:, 0], a), :]
```
Benchmark:
```
a = [10, 11, 12, 13, 14]
b = [[9, 23, 45, 67, 56], [10, 8, 52, 30, 15], [11, 81, 152, 54, 112],
[13, 82, 84, 63, 24], [18, 182, 25, 63, 96]]
list_comp, np_isin = [], []
for i in range(1,100):
a_test = a * i
b_test = b * i
list_comp.append(timeit.timeit('[l for l in b_test if l[0] in a_test]', number=10, globals=globals()))
a_arr = np.array(a_test)
b_arr = np.array(b_test)
np_isin.append(timeit.timeit('b_arr[np.isin(b_arr[:, 0], a_arr), :]', number=10, globals=globals()))
```
[](https://i.stack.imgur.com/QLnn1.png)
While it is not clear and concise, I would recommend using `list` comprehension if the `b` is shorter than 100. Otherwise, `numpy` is your way to go. |
56,352,970 | I am using a 3rd-party library it will hide iOS status bar when calling. After that, I can't show the status bar back on screen.
I can control status bar by `StatusBar` component in React Native normally.
However, I tried to call a iOS library <https://www.dynamsoft.com/Products/dynamsoft-webcam-sdk.aspx> it will hide the status bar when showing it's screen.
After it hide the status bar, I can't show it up again using `StatusBar.setHidden(false)`.
It don't prompt any error, just simply no effect.
Anyone knows what's going on and how can I show the status bar back in this situation? | 2019/05/29 | [
"https://Stackoverflow.com/questions/56352970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7897319/"
] | Use list comprehension:
```
c = [l for l in b if l[0] in a]
```
Output:
```
[[10, 8, 52, 30, 15], [11, 81, 152, 54, 112], [13, 82, 84, 63, 24]]
```
If your `list` or `array`s are considerably large, using `numpy.isin` can be significantly faster:
```
b[np.isin(b[:, 0], a), :]
```
Benchmark:
```
a = [10, 11, 12, 13, 14]
b = [[9, 23, 45, 67, 56], [10, 8, 52, 30, 15], [11, 81, 152, 54, 112],
[13, 82, 84, 63, 24], [18, 182, 25, 63, 96]]
list_comp, np_isin = [], []
for i in range(1,100):
a_test = a * i
b_test = b * i
list_comp.append(timeit.timeit('[l for l in b_test if l[0] in a_test]', number=10, globals=globals()))
a_arr = np.array(a_test)
b_arr = np.array(b_test)
np_isin.append(timeit.timeit('b_arr[np.isin(b_arr[:, 0], a_arr), :]', number=10, globals=globals()))
```
[](https://i.stack.imgur.com/QLnn1.png)
While it is not clear and concise, I would recommend using `list` comprehension if the `b` is shorter than 100. Otherwise, `numpy` is your way to go. | You are doing it reverse. It is better to loop through the elements of b array and check if it is present in a. If yes then print that element of b. See the answer below.
```
a = [10, 11, 12, 13, 14]
b = [[9, 23, 45, 67, 56, 23, 54], [10, 8, 52, 30, 15, 47, 109], [11, 81, 152, 54, 112, 78, 167], [13, 82, 84, 63, 24, 26, 78], [18, 182, 25, 63, 96, 104, 74]]
for bb in b: # if you want to check only the first element of b is in a
if bb[0] in a:
print(bb)
for bb in b: # if you want to check if any element of b is in a
for bbb in bb:
if bbb in a:
print(bb)
```
Output:
```
[10, 8, 52, 30, 15, 47, 109]
[11, 81, 152, 54, 112, 78, 167]
[13, 82, 84, 63, 24, 26, 78]
``` |
56,352,970 | I am using a 3rd-party library it will hide iOS status bar when calling. After that, I can't show the status bar back on screen.
I can control status bar by `StatusBar` component in React Native normally.
However, I tried to call a iOS library <https://www.dynamsoft.com/Products/dynamsoft-webcam-sdk.aspx> it will hide the status bar when showing it's screen.
After it hide the status bar, I can't show it up again using `StatusBar.setHidden(false)`.
It don't prompt any error, just simply no effect.
Anyone knows what's going on and how can I show the status bar back in this situation? | 2019/05/29 | [
"https://Stackoverflow.com/questions/56352970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7897319/"
] | Use [`np.isin`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.isin.html) -
```
In [8]: b[np.isin(b[:,0],a)]
Out[8]:
array([[ 10, 8, 52, 30, 15],
[ 11, 81, 152, 54, 112],
[ 13, 82, 84, 63, 24]])
```
With sorted `a`, we can also use [`np.searchsorted`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.searchsorted.html) -
```
idx = np.searchsorted(a,b[:,0])
idx[idx==len(a)] = 0
out = b[a[idx] == b[:,0]]
```
If you have an array with different number of elements per row, which is essentially array of lists, you need to modify the slicing part. So, in that case, get the first off elements -
```
b0 = [bi[0] for bi in b]
```
Then, use `b0` to replace all instances of `b[:,0]` in earlier posted methods. | You are doing it reverse. It is better to loop through the elements of b array and check if it is present in a. If yes then print that element of b. See the answer below.
```
a = [10, 11, 12, 13, 14]
b = [[9, 23, 45, 67, 56, 23, 54], [10, 8, 52, 30, 15, 47, 109], [11, 81, 152, 54, 112, 78, 167], [13, 82, 84, 63, 24, 26, 78], [18, 182, 25, 63, 96, 104, 74]]
for bb in b: # if you want to check only the first element of b is in a
if bb[0] in a:
print(bb)
for bb in b: # if you want to check if any element of b is in a
for bbb in bb:
if bbb in a:
print(bb)
```
Output:
```
[10, 8, 52, 30, 15, 47, 109]
[11, 81, 152, 54, 112, 78, 167]
[13, 82, 84, 63, 24, 26, 78]
``` |
9,291,411 | Is it possible for a User control to receive an update whenever a user control changes value? I have a form with a save button and I want to activate it as soon as a value changes.
Currently I am ding this using my View but I have to add a call to every property when it changes. This is OK but for edit boxes it means the user has to tab away before the save button becomes active. | 2012/02/15 | [
"https://Stackoverflow.com/questions/9291411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1145533/"
] | There is no such thing as this working reliably with a single script: You have little control over buffering on the server side - `flush()` might or might not work as expected, depending on wether you use `mod_php`, `CGI`, `FCGI` or whatever, and you have absolutely no control over buffering at the client (IE is notorious here).
Been there, done that, did it with AJAX. | Will something like the following not work?
```
$output = shell_exec($theScript);
file_put_contents($someFile, $output, FILE_APPEND);
```
Or have I got the wrong end of the stick? |
1,888 | Hydrogen is the lightest element, so it's cable of lifting the most weight in out atmosphere (probably not the best terminology there, but you get the picture)
Would hot hydrogen (in the same sense as hot air) be able to lift even more mass?
Would a higher or lower density of hydrogen in a ballon lift more?
If you could have a balloon which had nothing in it (it was a vacuum inside) would that lift more than a hydrogen balloon?
Basically what are the physics to balloons and lifting?
(really not sure what to tag this, so if someone else could that'd be great) | 2010/12/13 | [
"https://physics.stackexchange.com/questions/1888",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/4/"
] | >
> Would hot hydrogen (in the same sense as hot air) be able to lift even more mass?
>
>
>
Yes. Though I suppose the fire danger goes up, and you certainly can't use a propane burner to warm it...
>
> Would a higher or lower density of hydrogen in a ballon lift more?
>
>
>
Lower density always means higher buoyancy.
>
> If you could have a balloon which had nothing in it (it was a vacuum inside) would that lift more than a hydrogen balloon?
>
>
>
Yes, and this has been proposed in various ways in science fiction literature. The engineering challenge is finding a away to confine the vacuum that is as light as a gas bag so that you don't loose the advantage to extra weight.
In general a volume $V$ of material of density $\rho$ immersed in a fluid of density $\rho\_f$ experiences a buoyant force of
$$ F\_b = gV\rho\_f $$
and a weight of
$$W = -gV\rho $$
so the available lifting force is
$$ F\_l = gV(\rho\_f - \rho) .$$
Where the object is floating at the surface of a liquid the buoyant force is modified to reflect the volume of liquid displaced $F\_b = g V\_d \rho\_f$ where $V\_d$ is enough to cover the weight of the floating object. | [dmckee's answer](https://physics.stackexchange.com/questions/1888/balloons-and-lifting-gases/1889#1889) is a great not-too-technical description of buoyancy. Read that first. But in case you're interested, I thought I would go into some more detail.
The buoyant force on a submerged object (e.g. a balloon submerged in air) is equal to the weight of the displaced fluid,
$$F\_b = \rho\_f g V$$
as dmckee said. The physical origin of this force is actually the pressure difference between the top and bottom surfaces of the floating object. Pressure in a fluid at a certain height is related to the depth of the fluid above that height by
$$P(z\_2) - P(z\_1) = \rho\_f g (z\_2 - z\_1)$$
that is, density of fluid times gravitational acceleration times height difference. If you have a rectangular box whose top and bottom surfaces are flat, then it's pretty easy to calculate the buoyant force as the pressure differential times the area of those surfaces,
$$F\_b = (\Delta P)(A) = \rho\_f g \Delta z A = \rho\_f g V$$
For an irregular shape, you'll have to do an integral of some sort. For example, I once wrote a [blog post](http://www.ellipsix.net/blog/2009/11/buoyancy-part-1.html) which discusses, in part, deriving the buoyant force (and weight) from the minimization of potential energy, and that method can be easier to apply to irregular objects. (There are also a couple of interesting applications, even if you don't care about the math.)
You can also take into account variations in density (or gravitational acceleration) over the size of the balloon by doing an integral. But, according to the [US standard atmosphere model](http://en.wikipedia.org/wiki/File:Us_standard_atmosphere_model.png), the density of the atmosphere takes about $20\ \mathrm{km}$ to drop off to near zero, which corresponds to a fraction of a percent change over the height of a typical hot air balloon (a few tens of meters). That fraction of a percent is generally negligible, so you're pretty safe just using a single value for the density.
However, you can't neglect differences in density between vastly different altitudes. Remember that the buoyant force on the balloon is equal to the weight of the amount of fluid displaced. As you go higher, the density of the air drops, which means the balloon displaces a lower mass of air. Therefore, as the balloon rises, the buoyant force drops. Eventually it reaches a height at which the buoyant force exactly balances out the weight of the balloon (and basket), and the balloon levitates at that level. As has been said in the comments, for a controlled balloon, the operator can adjust the level by either heating the gas inside the balloon (thus making it expand and displace more air) or by letting some gas out (thus making the balloon contract and displace less air). |
1,888 | Hydrogen is the lightest element, so it's cable of lifting the most weight in out atmosphere (probably not the best terminology there, but you get the picture)
Would hot hydrogen (in the same sense as hot air) be able to lift even more mass?
Would a higher or lower density of hydrogen in a ballon lift more?
If you could have a balloon which had nothing in it (it was a vacuum inside) would that lift more than a hydrogen balloon?
Basically what are the physics to balloons and lifting?
(really not sure what to tag this, so if someone else could that'd be great) | 2010/12/13 | [
"https://physics.stackexchange.com/questions/1888",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/4/"
] | >
> Would hot hydrogen (in the same sense as hot air) be able to lift even more mass?
>
>
>
Yes. Though I suppose the fire danger goes up, and you certainly can't use a propane burner to warm it...
>
> Would a higher or lower density of hydrogen in a ballon lift more?
>
>
>
Lower density always means higher buoyancy.
>
> If you could have a balloon which had nothing in it (it was a vacuum inside) would that lift more than a hydrogen balloon?
>
>
>
Yes, and this has been proposed in various ways in science fiction literature. The engineering challenge is finding a away to confine the vacuum that is as light as a gas bag so that you don't loose the advantage to extra weight.
In general a volume $V$ of material of density $\rho$ immersed in a fluid of density $\rho\_f$ experiences a buoyant force of
$$ F\_b = gV\rho\_f $$
and a weight of
$$W = -gV\rho $$
so the available lifting force is
$$ F\_l = gV(\rho\_f - \rho) .$$
Where the object is floating at the surface of a liquid the buoyant force is modified to reflect the volume of liquid displaced $F\_b = g V\_d \rho\_f$ where $V\_d$ is enough to cover the weight of the floating object. | Approximate mean atomic mass of air: 29
Approximate mean atomic mass of hydrogen: 2
So with both gases at the same temperature and pressure, you are getting $\frac{27}{29}=93\%$ of the theoretical lifting capacity.
You would have to heat the hydrogen to about 200 C in order to get to 95% efficiency. It would be much better to work on making the surrounding/supporting structure lighter than to heat the hydrogen - the apparatus plus fuel for the heating is likely to weigh much more than you gain in lift. |
1,888 | Hydrogen is the lightest element, so it's cable of lifting the most weight in out atmosphere (probably not the best terminology there, but you get the picture)
Would hot hydrogen (in the same sense as hot air) be able to lift even more mass?
Would a higher or lower density of hydrogen in a ballon lift more?
If you could have a balloon which had nothing in it (it was a vacuum inside) would that lift more than a hydrogen balloon?
Basically what are the physics to balloons and lifting?
(really not sure what to tag this, so if someone else could that'd be great) | 2010/12/13 | [
"https://physics.stackexchange.com/questions/1888",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/4/"
] | >
> Would hot hydrogen (in the same sense as hot air) be able to lift even more mass?
>
>
>
Yes. Though I suppose the fire danger goes up, and you certainly can't use a propane burner to warm it...
>
> Would a higher or lower density of hydrogen in a ballon lift more?
>
>
>
Lower density always means higher buoyancy.
>
> If you could have a balloon which had nothing in it (it was a vacuum inside) would that lift more than a hydrogen balloon?
>
>
>
Yes, and this has been proposed in various ways in science fiction literature. The engineering challenge is finding a away to confine the vacuum that is as light as a gas bag so that you don't loose the advantage to extra weight.
In general a volume $V$ of material of density $\rho$ immersed in a fluid of density $\rho\_f$ experiences a buoyant force of
$$ F\_b = gV\rho\_f $$
and a weight of
$$W = -gV\rho $$
so the available lifting force is
$$ F\_l = gV(\rho\_f - \rho) .$$
Where the object is floating at the surface of a liquid the buoyant force is modified to reflect the volume of liquid displaced $F\_b = g V\_d \rho\_f$ where $V\_d$ is enough to cover the weight of the floating object. | A vacuum balloon is a possibility, but I doubt it can provide more lift than a hydrogen balloon: you need a rigid shell to prevent implosion of the vacuum balloon, and my feeling is the shell will be too heavy. However, while vacuum balloons cannot compete on lift, they can have better altitude control: you can bleed air in to lose altitude and pump out air to gain altitude.
Together with my coauthor, I proposed some designs of vacuum balloons made of commercially available materials, such as boron carbide and aluminum honeycombs (US patent application 20070001053 (11/517915), or <http://akhmeteli.org/wp-content/uploads/2011/08/vacuum_balloons_cip.pdf> ). The main problem is so-called buckling (loss of stability). It is possible, but difficult, so nobody has built a vacuum balloon so far, as far as I know, although the idea of vacuum balloon is centuries old. |
1,888 | Hydrogen is the lightest element, so it's cable of lifting the most weight in out atmosphere (probably not the best terminology there, but you get the picture)
Would hot hydrogen (in the same sense as hot air) be able to lift even more mass?
Would a higher or lower density of hydrogen in a ballon lift more?
If you could have a balloon which had nothing in it (it was a vacuum inside) would that lift more than a hydrogen balloon?
Basically what are the physics to balloons and lifting?
(really not sure what to tag this, so if someone else could that'd be great) | 2010/12/13 | [
"https://physics.stackexchange.com/questions/1888",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/4/"
] | [dmckee's answer](https://physics.stackexchange.com/questions/1888/balloons-and-lifting-gases/1889#1889) is a great not-too-technical description of buoyancy. Read that first. But in case you're interested, I thought I would go into some more detail.
The buoyant force on a submerged object (e.g. a balloon submerged in air) is equal to the weight of the displaced fluid,
$$F\_b = \rho\_f g V$$
as dmckee said. The physical origin of this force is actually the pressure difference between the top and bottom surfaces of the floating object. Pressure in a fluid at a certain height is related to the depth of the fluid above that height by
$$P(z\_2) - P(z\_1) = \rho\_f g (z\_2 - z\_1)$$
that is, density of fluid times gravitational acceleration times height difference. If you have a rectangular box whose top and bottom surfaces are flat, then it's pretty easy to calculate the buoyant force as the pressure differential times the area of those surfaces,
$$F\_b = (\Delta P)(A) = \rho\_f g \Delta z A = \rho\_f g V$$
For an irregular shape, you'll have to do an integral of some sort. For example, I once wrote a [blog post](http://www.ellipsix.net/blog/2009/11/buoyancy-part-1.html) which discusses, in part, deriving the buoyant force (and weight) from the minimization of potential energy, and that method can be easier to apply to irregular objects. (There are also a couple of interesting applications, even if you don't care about the math.)
You can also take into account variations in density (or gravitational acceleration) over the size of the balloon by doing an integral. But, according to the [US standard atmosphere model](http://en.wikipedia.org/wiki/File:Us_standard_atmosphere_model.png), the density of the atmosphere takes about $20\ \mathrm{km}$ to drop off to near zero, which corresponds to a fraction of a percent change over the height of a typical hot air balloon (a few tens of meters). That fraction of a percent is generally negligible, so you're pretty safe just using a single value for the density.
However, you can't neglect differences in density between vastly different altitudes. Remember that the buoyant force on the balloon is equal to the weight of the amount of fluid displaced. As you go higher, the density of the air drops, which means the balloon displaces a lower mass of air. Therefore, as the balloon rises, the buoyant force drops. Eventually it reaches a height at which the buoyant force exactly balances out the weight of the balloon (and basket), and the balloon levitates at that level. As has been said in the comments, for a controlled balloon, the operator can adjust the level by either heating the gas inside the balloon (thus making it expand and displace more air) or by letting some gas out (thus making the balloon contract and displace less air). | Approximate mean atomic mass of air: 29
Approximate mean atomic mass of hydrogen: 2
So with both gases at the same temperature and pressure, you are getting $\frac{27}{29}=93\%$ of the theoretical lifting capacity.
You would have to heat the hydrogen to about 200 C in order to get to 95% efficiency. It would be much better to work on making the surrounding/supporting structure lighter than to heat the hydrogen - the apparatus plus fuel for the heating is likely to weigh much more than you gain in lift. |
1,888 | Hydrogen is the lightest element, so it's cable of lifting the most weight in out atmosphere (probably not the best terminology there, but you get the picture)
Would hot hydrogen (in the same sense as hot air) be able to lift even more mass?
Would a higher or lower density of hydrogen in a ballon lift more?
If you could have a balloon which had nothing in it (it was a vacuum inside) would that lift more than a hydrogen balloon?
Basically what are the physics to balloons and lifting?
(really not sure what to tag this, so if someone else could that'd be great) | 2010/12/13 | [
"https://physics.stackexchange.com/questions/1888",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/4/"
] | [dmckee's answer](https://physics.stackexchange.com/questions/1888/balloons-and-lifting-gases/1889#1889) is a great not-too-technical description of buoyancy. Read that first. But in case you're interested, I thought I would go into some more detail.
The buoyant force on a submerged object (e.g. a balloon submerged in air) is equal to the weight of the displaced fluid,
$$F\_b = \rho\_f g V$$
as dmckee said. The physical origin of this force is actually the pressure difference between the top and bottom surfaces of the floating object. Pressure in a fluid at a certain height is related to the depth of the fluid above that height by
$$P(z\_2) - P(z\_1) = \rho\_f g (z\_2 - z\_1)$$
that is, density of fluid times gravitational acceleration times height difference. If you have a rectangular box whose top and bottom surfaces are flat, then it's pretty easy to calculate the buoyant force as the pressure differential times the area of those surfaces,
$$F\_b = (\Delta P)(A) = \rho\_f g \Delta z A = \rho\_f g V$$
For an irregular shape, you'll have to do an integral of some sort. For example, I once wrote a [blog post](http://www.ellipsix.net/blog/2009/11/buoyancy-part-1.html) which discusses, in part, deriving the buoyant force (and weight) from the minimization of potential energy, and that method can be easier to apply to irregular objects. (There are also a couple of interesting applications, even if you don't care about the math.)
You can also take into account variations in density (or gravitational acceleration) over the size of the balloon by doing an integral. But, according to the [US standard atmosphere model](http://en.wikipedia.org/wiki/File:Us_standard_atmosphere_model.png), the density of the atmosphere takes about $20\ \mathrm{km}$ to drop off to near zero, which corresponds to a fraction of a percent change over the height of a typical hot air balloon (a few tens of meters). That fraction of a percent is generally negligible, so you're pretty safe just using a single value for the density.
However, you can't neglect differences in density between vastly different altitudes. Remember that the buoyant force on the balloon is equal to the weight of the amount of fluid displaced. As you go higher, the density of the air drops, which means the balloon displaces a lower mass of air. Therefore, as the balloon rises, the buoyant force drops. Eventually it reaches a height at which the buoyant force exactly balances out the weight of the balloon (and basket), and the balloon levitates at that level. As has been said in the comments, for a controlled balloon, the operator can adjust the level by either heating the gas inside the balloon (thus making it expand and displace more air) or by letting some gas out (thus making the balloon contract and displace less air). | A vacuum balloon is a possibility, but I doubt it can provide more lift than a hydrogen balloon: you need a rigid shell to prevent implosion of the vacuum balloon, and my feeling is the shell will be too heavy. However, while vacuum balloons cannot compete on lift, they can have better altitude control: you can bleed air in to lose altitude and pump out air to gain altitude.
Together with my coauthor, I proposed some designs of vacuum balloons made of commercially available materials, such as boron carbide and aluminum honeycombs (US patent application 20070001053 (11/517915), or <http://akhmeteli.org/wp-content/uploads/2011/08/vacuum_balloons_cip.pdf> ). The main problem is so-called buckling (loss of stability). It is possible, but difficult, so nobody has built a vacuum balloon so far, as far as I know, although the idea of vacuum balloon is centuries old. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.