qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
31,157,803 | I am working on spring web app using maven. I am trying to make localhost a secure connection.I am using tomcat server. I used this [link](http://docs.oracle.com/cd/E19798-01/821-1841/bnbyb/index.html) for creating my own CA and added it to JVM.
This is what I added in pom.xml.
```
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>/security</path>
<Connector port="8443" protocol="org.apache.coyote.http11.Http11Protocol" SSLEnabled="true" maxThreads="200" scheme="https" secure="true" keystoreFile="/usr/lib/jvm/java-1.7.0-openjdk-1.7.0.71.x86_64/jre/lib/security/cacerts.jks" keystorePass="security"
clientAuth="false" sslProtocol="TLS" />
</configuration>
</plugin>
```
I went to the link:<https://localhost:8443> . But no app is running on that port. Could someone please help? | 2015/07/01 | [
"https://Stackoverflow.com/questions/31157803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2213010/"
] | Go to sever.xml and add following xml
```
<Connector port="443" protocol="org.apache.coyote.http11.Http11NioProtocol"
maxThreads="150" SSLEnabled="true" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS" keystoreFile="{path}/mycer.cert" keystorePass="{password}"/>
<!-- Define an AJP 1.3 Connector on port 8009 -->
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443"/>
```
1. first you want to create one CA certificate
2. you can use java key tool for certificate creation
3. store that certificate on your server .
4. add connector config with in your tomcat server.xml
5. you should provide certificate path and password that given
6. restart server
if any problem for restarting comment stack trace
<http://www.mkyong.com/tomcat/how-to-configure-tomcat-to-support-ssl-or-https/> | You need to add a connector in `servlet.xml` file.
```
<Connector
protocol="org.apache.coyote.http11.Http11Protocol"
port="8443" maxThreads="200"
scheme="https" secure="true" SSLEnabled="true"
keystoreFile="${user.home}/.keystore" keystorePass="changeit"
clientAuth="false" sslProtocol="TLS"/>
```
Replace the keystore file path and the password with the ones you have.
Refer <https://tomcat.apache.org/tomcat-6.0-doc/ssl-howto.html>. |
26,957,743 | Suppose one has a java project which consists of several packages, subpackages etc, all existing in a folder "source". Is there a direct way to copy the structure of the folders in "source" to a "classes" folder and then recursively compile all the .java files, placing the .class files in the correct locations in "classes"? | 2014/11/16 | [
"https://Stackoverflow.com/questions/26957743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1333200/"
] | For larger projects a recommend using a build tool like [Maven](http://maven.apache.org) or the newer and faster [Gradle](http://gradle.org). Once you've configured one of them for your needs, it's very easy to do the job by calling `mvn build` or `gradle build`.
If these tools seem to heavy for your purpose, you may have a look at [Ant](http://ant.apache.org). A simple ant example:
```
<project default="compile">
<target name="compile">
<mkdir dir="bin"/>
<javac srcdir="source" destdir="bin"/>
</target>
</project>
```
and then run `ant` from the command line. See [this thread for further information](https://stackoverflow.com/questions/6623161/javac-option-to-compile-recursively). | * There are no "bin files" in Java, this language only compiles
bytecode
* [Compiling multiple packages using the command line in Java](https://stackoverflow.com/questions/3512603/compiling-multiple-packages-using-the-command-line-in-java)
* Eclipse : <https://stackoverflow.com/a/7218929/351861>
* via console : `javac folder1/*.java folder2/*.java folder3/*.java` |
37,686,247 | I'm trying to convert the following curl post to a Python request:
```
curl -k -i -H "Content-Type: multipart/mixed" -X POST --form
'session.id=e7a29776-5783-49d7-afa0-b0e688096b5e' --form 'ajax=upload'
--form '[email protected];type=application/zip' --form 'project=MyProject;type/plain' https://localhost:8443/manager
```
I used [curl.trillworks.com](http://curl.trillworks.com) to make an auto conversion but it didn't work. I also tried the following:
```
sessionID = e7a29776-5783-49d7-afa0-b0e688096b5e
project = 'file.zip'
metadata = json.dumps({"documentType":"multipart/mixed"})
files = {
'meta' : ('', metadata , 'application/zip'),
'data':(project, 'multipart/mixed', 'application/octet-stream')}
data = {'ajax':'upload','project':'test','session.id':sessionId}
cookie = {'azkaban.browser.session.id':sessionId}
response=requests.post('https://'+azkabanURL+'/manager',
data=data,verify=False,files=files)
print response.text
```
I got the following error:
```
<p>Problem accessing /manager. Reason:
<pre> INTERNAL_SERVER_ERROR</pre></p><h3>Caused by:</h3><pre>java.lang.NullPointerException
at azkaban.webapp.servlet.ProjectManagerServlet.ajaxHandleUpload(ProjectManagerServlet.java:1664)
at azkaban.webapp.servlet.ProjectManagerServlet.handleMultiformPost(ProjectManagerServlet.java:183)
at azkaban.webapp.servlet.LoginAbstractAzkabanServlet.doPost(LoginAbstractAzkabanServlet.java:276)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:401)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:766)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:326)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:945)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:756)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:218)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
at org.mortbay.jetty.bio.SocketConnector$Connection.run(SocketConnector.java:228)
at org.mortbay.jetty.security.SslSocketConnector$SslConnection.run(SslSocketConnector.java:713)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)
```
Can't figure out what I'm missing here?? | 2016/06/07 | [
"https://Stackoverflow.com/questions/37686247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1762447/"
] | I found the answer after trying out some of the examples from [requests](http://docs.python-requests.org/en/master/user/quickstart/#make-a-request) site and finally it worked.
```
data = {'ajax':'upload','project':'test','session.id':sessionId}
files = {'file':('projects.zip',open('projects.zip','rb'),'application/zip')}
response=requests.post('https://'+azkabanURL+'/manager',data=data,verify=False,files=files)
print response.text
print response.status_code
``` | For the future reference I recommend you to check this online tool:
<http://curl.trillworks.com/>
it converts curl to python requests, node and php.
It has helped my multiple times. |
66,628 | My employer offers an ESPP with the following details:
* 15% discount
* Max contribution is 15% of base salary
* Purchase transaction occurs on the last business day of the month
* Transaction settles 3 days after purchase
* No obligation to hold the stock for minimum duration
* No restrictions on sell timing (except during earnings lock-out period)
* Brokerage fees
+ $0.05 per share sold (approximately 0.08% of the stock price today)
+ $0 per share bought
Given these parameters...
What is the safest way to play the ESPP?
What is (likely) the most lucrative way to play the ESPP?
Assume I contribute the maximum amount allowable.
Assume I can hold the stock for up to you year before I may need to cash it out. | 2016/06/26 | [
"https://money.stackexchange.com/questions/66628",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/22298/"
] | Short answer is to put the max 15% contribution into your ESPP.
Long answer is that since you want to be saving as much as you can anyway, this is a great way to force you to do it, and pick up at least a 15% return every six months (or however often your plan makes a purchase). I say at least because sometimes an ESPP will give you the lower of the beginning or end period stock price, and then a 15% discount off of that (but check the details of your plan). If you feel like your company's stock is a good long term investment, then hold onto the shares when purchased. Otherwise sell as soon as you get them, and bank that 15% return. | A 15% discount does not necessarily mean it is a good investment.
The stock price can go down at any point. 15% discount might mean you
are getting a little better deal than the average cat. |
66,628 | My employer offers an ESPP with the following details:
* 15% discount
* Max contribution is 15% of base salary
* Purchase transaction occurs on the last business day of the month
* Transaction settles 3 days after purchase
* No obligation to hold the stock for minimum duration
* No restrictions on sell timing (except during earnings lock-out period)
* Brokerage fees
+ $0.05 per share sold (approximately 0.08% of the stock price today)
+ $0 per share bought
Given these parameters...
What is the safest way to play the ESPP?
What is (likely) the most lucrative way to play the ESPP?
Assume I contribute the maximum amount allowable.
Assume I can hold the stock for up to you year before I may need to cash it out. | 2016/06/26 | [
"https://money.stackexchange.com/questions/66628",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/22298/"
] | A 15% discount is a 17.6% return. (100/85 = 1.176). For a holding period that's an average 15.5 days, a half month. It would be silly to compound this over a year as the numbers are limited.
The safest way to do this is to sell the day you are permitted. In effect, you are betting, 12 times a year, that the stock won't drop 15% in 3 days. You can pull data going back decades, or as long as your company has been public, and run a spreadsheet to see how many times, if at all, the stock has seen this kind of volatility over 3 day periods. Even for volatile stocks, a 15% move is pretty large, you're likely to find your stock doing this less than once per year. It's also safest to not accumulate too many shares of your company for multiple reasons, having to do with risk spreading, diversification, etc.
2 additional points -
the Brexit just caused the S&P to drop 4% over the last 3 days trading. This was a major world event, but, on average we are down 4%. One would have to be very unlucky to have their stock drop 15% over the specific 3 days we are discussing.
The dollars at risk are minimal. Say you make $120K/yr. $10K/month. 15% of this is $1500 and you are buying $1765 worth of stock. The gains, on average are expected to be $265/mo. Doesn't seem like too much, but it's $3180 over a years' time. $3180 in profit for a maximum $1500 at risk at any month's cycle. | Short answer is to put the max 15% contribution into your ESPP.
Long answer is that since you want to be saving as much as you can anyway, this is a great way to force you to do it, and pick up at least a 15% return every six months (or however often your plan makes a purchase). I say at least because sometimes an ESPP will give you the lower of the beginning or end period stock price, and then a 15% discount off of that (but check the details of your plan). If you feel like your company's stock is a good long term investment, then hold onto the shares when purchased. Otherwise sell as soon as you get them, and bank that 15% return. |
66,628 | My employer offers an ESPP with the following details:
* 15% discount
* Max contribution is 15% of base salary
* Purchase transaction occurs on the last business day of the month
* Transaction settles 3 days after purchase
* No obligation to hold the stock for minimum duration
* No restrictions on sell timing (except during earnings lock-out period)
* Brokerage fees
+ $0.05 per share sold (approximately 0.08% of the stock price today)
+ $0 per share bought
Given these parameters...
What is the safest way to play the ESPP?
What is (likely) the most lucrative way to play the ESPP?
Assume I contribute the maximum amount allowable.
Assume I can hold the stock for up to you year before I may need to cash it out. | 2016/06/26 | [
"https://money.stackexchange.com/questions/66628",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/22298/"
] | A 15% discount is a 17.6% return. (100/85 = 1.176). For a holding period that's an average 15.5 days, a half month. It would be silly to compound this over a year as the numbers are limited.
The safest way to do this is to sell the day you are permitted. In effect, you are betting, 12 times a year, that the stock won't drop 15% in 3 days. You can pull data going back decades, or as long as your company has been public, and run a spreadsheet to see how many times, if at all, the stock has seen this kind of volatility over 3 day periods. Even for volatile stocks, a 15% move is pretty large, you're likely to find your stock doing this less than once per year. It's also safest to not accumulate too many shares of your company for multiple reasons, having to do with risk spreading, diversification, etc.
2 additional points -
the Brexit just caused the S&P to drop 4% over the last 3 days trading. This was a major world event, but, on average we are down 4%. One would have to be very unlucky to have their stock drop 15% over the specific 3 days we are discussing.
The dollars at risk are minimal. Say you make $120K/yr. $10K/month. 15% of this is $1500 and you are buying $1765 worth of stock. The gains, on average are expected to be $265/mo. Doesn't seem like too much, but it's $3180 over a years' time. $3180 in profit for a maximum $1500 at risk at any month's cycle. | A 15% discount does not necessarily mean it is a good investment.
The stock price can go down at any point. 15% discount might mean you
are getting a little better deal than the average cat. |
11,324 | I need to annotate a text file, so I would like to add a `|` pipe character to the end of each line to put my annotations relatively close to the original text. Each line is *up to* 72 characters in length. How might I move to the 74th character of the line, even if the line itself is shorter (i.e. add spaces if needed)?
My current solution is to simply add 72 spaces to the line, then to move to position 74 and delete the remaining spaces. Is there not a more elegant method in VIM?
My current (inelegant) macro:
```
qq$74a<space><esc>74|i|<esc>lDjq
```
I'm currently using VIM 8.0.133 on CentOS 7.3. | 2017/02/09 | [
"https://vi.stackexchange.com/questions/11324",
"https://vi.stackexchange.com",
"https://vi.stackexchange.com/users/989/"
] | You could also enable `'virtualedit'` option and directly jump to the column you're interested in.
A very similar question as been asked lately on SO: <https://stackoverflow.com/questions/41964261/how-do-i-put-the-character-in-6th-column-and-80th-column-in-vi/41964372#41964372> | Here's one way to do it without having to edit and restore `'virtualedit'`:
```
:execute "normal " . string(73 - strwidth(getline('.'))) . "A " | normal A|
```
This runs two commands:
1. The part *before* the bar `|` calculates the number of spaces required (`73 - strwidth(getline('.'))`) and then uses that as a count to a normal mode command that appends a single space, thus appending the correct number of spaces,.
2. The part *after* the bar simply appends a pipe character `|`. |
105,982 | My barbarian will be level 3 soon, and I'm looking forward to choosing the Path of the Totem Warrior. | 2017/08/26 | [
"https://rpg.stackexchange.com/questions/105982",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/34635/"
] | The most thematically appropriate option would be for your Barbarian to hunt the relevant animal of your choice.
The PHB of 50 states
>
> ...
>
>
> You must make or acquire a physical totem object -an amulet or similar adornment—that incorporates fur or feathers, claws, teeth, or bones of the totem animal.
>
>
> ...
>
>
>
Your choice of totem animal is Bear, Eagle or Wolf.
In order to facilitate this I would speak to your DM and set out what type of totem you wish to get, and ask if they could facilitate a hunt scenario for this particular animal into your campaign. | You need to acquire the item:
>
> You must make or acquire a physical totem object -an amulet or similar adornment—that incorporates fur or feathers, claws, teeth, or bones of the totem animal.
>
>
>
From [Merriam-Webster](https://www.merriam-webster.com/dictionary/acquire):
>
> **acquire:** to come into possession or control of often by unspecified means - *acquire* property - The team *acquired* three new players this year.
>
>
>
And by *unspecified means* it can include **buying one**. In any sufficient large city there should be a shop of trinkets, oddities[,](https://www.grammarly.com/blog/what-is-the-oxford-comma-and-why-do-people-care-so-much-about-it/) or magic components that can sell either the amulet or the required animal parts. |
16,368,230 | I am looking at the Webapi Help Page to generated docmentation but all the tutorials I see leave me wondering.
Q1.
How do I populate the sample data myself? From my understanding it looks at the data type and makes some data based on the datatype. Some of my data has specific requirements(ie length can't be more than 5 characters).
How do I write my own sample data for each method?
Q2
How can I hide warning messages.
I get this message
>
> Failed to generate the sample for media type
> 'application/x-www-form-urlencoded'. Cannot use formatter
> 'JQueryMvcFormUrlEncodedFormatter' to write type 'ProductDM'.
>
>
>
I am not really sure what "x-www-form-urlencoded" is but say if I don't support that how can I just hide that message or say "not supported"?
Q3 How can I write a description for each parameter. In most cases it is clear what they are but in some cases maybe not. Also it would be nice if it automatically took the annotations and put that beside them as well to show that maybe parameter A is option while parameter B is not. | 2013/05/03 | [
"https://Stackoverflow.com/questions/16368230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/130015/"
] | Q1: Have you taken a look at "Areas\HelpPage\App\_Start\HelpPageConfig.cs" file. You should see a bunch of commented out with examples how you could define your own samples.
Example:
```
public static class HelpPageConfig
{
public static void Register(HttpConfiguration config)
{
//// Uncomment the following to use the documentation from XML documentation file.
//config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml")));
//// Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type.
//// Also, the string arrays will be used for IEnumerable<string>. The sample objects will be serialized into different media type
//// formats by the available formatters.
//config.SetSampleObjects(new Dictionary<Type, object>
//{
// {typeof(string), "sample string"},
// {typeof(IEnumerable<string>), new string[]{"sample 1", "sample 2"}}
//});
```
Q2: You are seeing the error for "application/x-www-form-urlencoded" mediatype because the formatter which we use for it can only deserialize or read the data and cannot write. Here the error is to indicate that it only cannot write the sample, but if you infact are sending data in this media type, it could be deserialized correctly. Instead of hiding this section, you could provide an explicit sample for this media type. The HelpPageConfig.cs has examples for this:
```
//// Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format
//// and have IEnumerable<string> as the body parameter or return type.
//config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable<string>));
```
Q3: For documentation about parameters of an action, you can always use the regular comments(summary, param etc) and generate the documentation file and point it like the following:
```
//// Uncomment the following to use the documentation from XML documentation file.
//config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml")));
```
We currently do not have support for generating documentation out of Data Annotations, we currently have an issue tracing it: <http://aspnetwebstack.codeplex.com/workitem/877> | Regarding Q2 "How can I hide warning messages", in Areas/HelpPage/Views/Help/DisplayTemplates/Samples.chtml, you can add an if statement in the code:
```
@foreach (var mediaType in mediaTypes)
{
if (mediaType != "application/x-www-form-urlencoded") { /// <--- line added here
<h4 class="sample-header">@mediaType</h4>
<div class="sample-content">
<span><b>Sample:</b></span>
@{
var sample = samples[mediaType];
if (sample == null)
{
<p>Sample not available.</p>
}
else
{
@Html.DisplayFor(s => sample);
}
}
</div>
} /// <----- closing parenthesis
}
```
In my case I was already displaying the POST data structure so the "x-www-form-urlencoded" section was not needed. The helpPageConfig also displays a query string by default whereas my methods only accepted objects. |
17,298,631 | In an effort to learn C programming, I'm attempting to translate some Lua Code into C. I know C is not considered a "functional" language in the same vein as Lua, but I want to know how/if it's possible.
Lua Code:
```
function Increment(a)
a = a + 1
if a == 100 then return 0
else return Increment(a) end end
```
In this code, Lua cleverly exits the function after calling it again to avoid creating a huge stack of nested functions.
Is there a method for this sort of recursion in C that exits a function before calling it again, to avoid forming a large group of nested functions?
I understand functions can be used in this way to avoid side effects; How can I write this in C to avoid them as well? | 2013/06/25 | [
"https://Stackoverflow.com/questions/17298631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2395058/"
] | Try this code if you want a global, but there is side effect :
```
int a;
int increment()
{
a = a + 1;
if (a == 100)
return 0;
else
return increment();
}
```
Prefer to use if you don't want side effect, and this solution DO NOT stack lot of function, because you call your function at the last statement.
```
int increment(int a)
{
if (a == 100)
return a;
else
return increment(a + 1);
}
```
For example this one create stack of function :
```
int increment(int a)
{
if (a == 100)
return a;
else
{
a = increment(a);
return (a + 1);
}
}
``` | As Shar has pointed out above, the straight-forward translation of the lua code to C is:
```
int increment(int a)
{
if (a == 100)
return a;
else
return increment(a + 1);
}
```
For going up to 100, stack usage is not going to be a problem unless you are on a very small embedded system. However, there is no guarantee in C that a C compiler will do *tail call optimization* (which is, as you put it, the fact that "Lua cleverly exits the function after calling it again to avoid creating a huge stack of nested function").
For a simple example such as this, many compilers will actually do the tail call optimization, but it is a bad idea to use `if(a == 1000000000)` and rely on it. If you do that, you will probably have a program that works in "Release" optimized builds, but crashes in "Debug" builds.
So, if you know that there will be a lot of recursion, you can do the optimization yourself:
```
int increment(int a)
{
for(;;)
{
if(a == 100)
return a;
else
a = a + 1;
}
}
// and then "clean it up":
int increment(int a)
{
while (a != 100)
{
a = a + 1;
}
return a;
}
``` |
26,093,827 | I need to find a value wherever present in database.
Consider I need to find value "Fish" from Database.
Output I need is
```
Table Name | Column Name
--------------------------
Table 1 | columnName
Table 12 | columnName
```
and so on.. | 2014/09/29 | [
"https://Stackoverflow.com/questions/26093827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3540786/"
] | First, download the source version of Thrift. I would strongly recommend using a newer version if possible. There are several ways to include the Thrift Java library (may have to change slightly for your Thrift version):
If you are using maven, you can add the maven coordinates to your pom.xml:
```
<dependency>
<groupId>org.apache.thrift</groupId>
<artifactId>libthrift</artifactId>
<version>0.9.1</version>
</dependency>
```
Alternatively you can just download the JAR and add it your project:
<http://central.maven.org/maven2/org/apache/thrift/libthrift/0.9.1/libthrift-0.9.1.jar>
If you are using a version that has not been published to the central maven repositories, you can download the source tarball and navigate to the lib/java directory and build it with Apache Ant by typing:
```
ant
```
The library JAR will be in the lib/java/build directory. Optionally you can add the freshly built JAR to your local Maven repository:
```
mvn install:install-file -DartifactId=libthrift -DgroupId=org.apache.thrift -Dvers
```
For the PHP library, navigate to the `lib/php/src` directory and copy the PHP files into your project. You can then use the Thrift\ClassLoader\ThriftClassLoader class or the autoload.php script to include the Thrift PHP library. No build necessary unless you are trying to use the native PHP extension that implements the thrift protocol. | * for Java: you can download .jar library, javadoc here <http://repo1.maven.org/maven2/org/apache/thrift/libthrift/0.9.1/>
* for PHP: copy [thrift-source]/lib/php/lib to your project and use it. This is a example to use: <https://thrift.apache.org/tutorial/php>
P/s: i want to use .dll PHP extension rather than PHP source files. Anyone care it, we can discuss at here [How can write or find a PHP extension for Apache Thrift](https://stackoverflow.com/questions/26623610/how-can-write-or-find-a-php-extension-for-apache-thrift) |
58,526,031 | I would like to check myself whether I understand correctly the following quote below from the C++ 20 Standard (English is not my native language).
Section 9.7.1 Namespace definition:
>
> 2 In a named-namespace-definition, the identifier is the name of the
> namespace. If the identifier, when looked up (6.4.1), refers to a
> namespace-name (but not a namespace-alias) that was introduced in the
> namespace in which the named-namespace-definition appears or that was
> introduced in a member of the inline namespace set of that namespace,
> the namespace-definition extends the previously-declared namespace.
> Otherwise, the identifier is introduced as a namespace-name into the
> declarative region in which the named-namespacedefinition appears.
>
>
>
That is may a namespace be defined in a namespace and then extended in one of its inline namespace? Or vice versa. May a namespace be defined in an inline namespace and then be extended in its enclosing namespace?
Here is a demonstrative program.
```
#include <iostream>
inline namespace N1
{
inline namespace N2
{
namespace N3
{
void f( int ) { std::cout << "f( int )\n"; }
}
}
namespace N3
{
void f( char ) { std::cout << "f( char )\n"; }
}
}
int main()
{
N3::f( 10 );
N3::f( 'A' );
}
```
The program output is
```
f( int )
f( char )
```
However for this program the compiler issues an error saying that reference to 'N3' is ambiguous.
```
#include <iostream>
inline namespace N1
{
namespace N3
{
void f( int ) { std::cout << "f( int )\n"; }
}
inline namespace N2
{
namespace N3
{
void f( char ) { std::cout << "f( char )\n"; }
}
}
}
int main()
{
N3::f( 10 );
N3::f( 'A' );
}
``` | 2019/10/23 | [
"https://Stackoverflow.com/questions/58526031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2877241/"
] | There in no variable named `good` or `wrong` in your main module. However you passed them to this function:
```
selected_function.randomfunction(good, wrong)
``` | thnx for youre answers!
I managed to get what i wan't by doing this:
```
import random
class functions:
def jammer():
print("jammer")
def goedzo():
print("goedzo")
def uuh():
print("uuh")
def tsjing():
print("tsjing")
#random functonlist
ls_good = [goedzo, tsjing]
ls_wrong = [jammer, uuh]
#method to select different functions
def randomfunction(self, test, good = random.choice(ls_good), wrong = random.choice(ls_wrong)):
self.good = good
self.wrong = wrong
self.test = test
if self.test == 1:
good()
else:
wrong()
#create object from class playsound
sf = functions()
sf.randomfunction(test=1)
``` |
21,355,784 | I need to be able to rotate whole layouts on the fly (on the click of a button).
I am able to rotate the layouts using, eg. `layout.setRotation(270.0f)`. **The problem is, after the rotation, the layout `height` and `width` are not matching its parent's**.
I have tried inverting `height` and `width` like so,
```
RelativeLayout layout = (RelativeLayout)findViewById(R.id.rootLayout);
LayoutParams layoutParams = layout.getLayoutParams();
int height = layout.getHeight();
int width = layout.getWidth();
layoutParams.height = width;
layoutParams.width = height;
```
Which does nothing at all.
I am working with `sdk 14`.
The first image below is the app as it starts. The second one, after a rotation. I wish to fill the black "space". Any help would be appreciated.
The images below show only a button in the layout. However, in reality, the layout are a lot more complex. What I am trying to achieve is "faking" a landscape view.


**Edit:** Changed images and added descriptions. | 2014/01/25 | [
"https://Stackoverflow.com/questions/21355784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/845253/"
] | Try this code:
```
btnRotate.setOnClickListener(new OnClickListener()
{
@SuppressLint("NewApi")
@Override
public void onClick(View v)
{
int orientation = getResources().getConfiguration().orientation;
switch(orientation)
{
case Configuration.ORIENTATION_LANDSCAPE:
llparent.setRotation(270.0f);
RelativeLayout.LayoutParams layoutParams_LandsScape =
new RelativeLayout.LayoutParams(
rlRoot.getHeight(), rlRoot.getWidth());
layoutParams_LandsScape.setMargins(
rlRoot.getTop(), rlRoot.getRight(),
rlRoot.getBottom(), rlRoot.getLeft());
layoutParams_LandsScape.addRule(RelativeLayout.CENTER_IN_PARENT);
llparent.setLayoutParams(layoutParams_LandsScape);
break;
case Configuration.ORIENTATION_PORTRAIT:
llparent.setRotation(270.0f);
RelativeLayout.LayoutParams layoutParams_Portrait =
new RelativeLayout.LayoutParams(
rlRoot.getHeight(), rlRoot.getWidth());
layoutParams_Portrait.setMargins(
0, 0, rlRoot.getBottom(), rlRoot.getLeft());
layoutParams_Portrait.addRule(RelativeLayout.CENTER_IN_PARENT);
llparent.setLayoutParams(layoutParams_Portrait);
break;
}
}
});
}
```
And XML:
```
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".RotateAnim">
<RelativeLayout
android:id="@+id/rlroot"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#090">
<LinearLayout
android:id="@+id/llParent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#900"
android:gravity="center"
android:orientation="vertical">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="Button"/>
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
``` | Try this code:
(RelativeLayoutOuterFrame) it is the name of your layout.which you want to rotate.
Actually, we are not rotate the layout.we just change height an width value.
```
int w = RelativeLayoutOuterFrame.getWidth();
int h = RelativeLayoutOuterFrame.getHeight();
ViewGroup.LayoutParams lp = (ViewGroup.LayoutParams) RelativeLayoutOuterFrame.getLayoutParams();
lp.height = w;
lp.width = h;
RelativeLayoutOuterFrame.setGravity(RelativeLayout.CENTER_IN_PARENT);
RelativeLayoutOuterFrame.setGravity(RelativeLayout.CENTER_HORIZONTAL);
RelativeLayoutOuterFrame.requestLayout();
``` |
21,355,784 | I need to be able to rotate whole layouts on the fly (on the click of a button).
I am able to rotate the layouts using, eg. `layout.setRotation(270.0f)`. **The problem is, after the rotation, the layout `height` and `width` are not matching its parent's**.
I have tried inverting `height` and `width` like so,
```
RelativeLayout layout = (RelativeLayout)findViewById(R.id.rootLayout);
LayoutParams layoutParams = layout.getLayoutParams();
int height = layout.getHeight();
int width = layout.getWidth();
layoutParams.height = width;
layoutParams.width = height;
```
Which does nothing at all.
I am working with `sdk 14`.
The first image below is the app as it starts. The second one, after a rotation. I wish to fill the black "space". Any help would be appreciated.
The images below show only a button in the layout. However, in reality, the layout are a lot more complex. What I am trying to achieve is "faking" a landscape view.


**Edit:** Changed images and added descriptions. | 2014/01/25 | [
"https://Stackoverflow.com/questions/21355784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/845253/"
] | If you want to literally rotate the screen, you can [force a screen orientation](https://stackoverflow.com/questions/14587085/how-can-i-globally-force-screen-orientation-in-android).
Otherwise there's no easy way to do what you are trying to do as `View.setRotation(float)` will always render the `View` in its "real" bounds and **then** rotate it! What I suggest is careful consideration of what elements of the layout should be rotated and then to rotate those specifically.
The only true "automatic" way of achieving it would be to create a custom layout that essentially measures, layouts and draws children rotated... Honestly I would only go there if I really, **really** needed to and it's probably more trouble than it's worth! | i'll suggest you rotate only button rather than rotating the whole layout like
```
btn_rotate.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v)
{
rotation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.rotate);
rotation.setFillAfter(true);
btn_rotate.startAnimation(rotation);
}
});
```
rotate.xml
----------
```
<set>
<rotate
xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="0"
android:fromDegrees="270"
android:pivotX="50%"
android:pivotY="50%"
android:startOffset="0"
android:toDegrees="270" />
</set>
``` |
21,355,784 | I need to be able to rotate whole layouts on the fly (on the click of a button).
I am able to rotate the layouts using, eg. `layout.setRotation(270.0f)`. **The problem is, after the rotation, the layout `height` and `width` are not matching its parent's**.
I have tried inverting `height` and `width` like so,
```
RelativeLayout layout = (RelativeLayout)findViewById(R.id.rootLayout);
LayoutParams layoutParams = layout.getLayoutParams();
int height = layout.getHeight();
int width = layout.getWidth();
layoutParams.height = width;
layoutParams.width = height;
```
Which does nothing at all.
I am working with `sdk 14`.
The first image below is the app as it starts. The second one, after a rotation. I wish to fill the black "space". Any help would be appreciated.
The images below show only a button in the layout. However, in reality, the layout are a lot more complex. What I am trying to achieve is "faking" a landscape view.


**Edit:** Changed images and added descriptions. | 2014/01/25 | [
"https://Stackoverflow.com/questions/21355784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/845253/"
] | Simple and tricky way to make screen orientation along the button click.. with an example..
Here,I'm using the sharedPreference(Im setting an boolean value based on orientation )
Method for button onClick.
```
public void rotate(View v) {
edt = prefs.edit();
if (!prefs.getBoolean("screen_protrait", true)) {
edt.putBoolean("screen_protrait", true);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else {
edt.putBoolean("screen_protrait", false);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
edt.commit();
}
```
In xml, set an onClick method for rotate button
```
<Button
android:id="@+id/bt_rotate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:onClick="rotate"
android:text="Rotate" />
```
Last one, is in onCreate of Activity you want to set the Prefernce from Application..as
```
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
```
Keep coding.. You can achieve your goal...Let me know,if it's working with your scenario. | [Android: alternate layout xml for landscape mode](https://stackoverflow.com/questions/4858026/android-alternate-layout-xml-for-landscape-modes)
As I can remember, you should define a new layout for the horizontal view. I think this link can help you |
21,355,784 | I need to be able to rotate whole layouts on the fly (on the click of a button).
I am able to rotate the layouts using, eg. `layout.setRotation(270.0f)`. **The problem is, after the rotation, the layout `height` and `width` are not matching its parent's**.
I have tried inverting `height` and `width` like so,
```
RelativeLayout layout = (RelativeLayout)findViewById(R.id.rootLayout);
LayoutParams layoutParams = layout.getLayoutParams();
int height = layout.getHeight();
int width = layout.getWidth();
layoutParams.height = width;
layoutParams.width = height;
```
Which does nothing at all.
I am working with `sdk 14`.
The first image below is the app as it starts. The second one, after a rotation. I wish to fill the black "space". Any help would be appreciated.
The images below show only a button in the layout. However, in reality, the layout are a lot more complex. What I am trying to achieve is "faking" a landscape view.


**Edit:** Changed images and added descriptions. | 2014/01/25 | [
"https://Stackoverflow.com/questions/21355784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/845253/"
] | ```
// get root layout from activity's XML
LinearLayout mParentLayout = (LinearLayout) findViewById(R.id.activity_main);
// get screen size from DisplayMetrics if you need to rotate before the screen is shown
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels;
// if you are rotating after the view was shown
// acquire width and height from the layout's parent's LayoutParams
// calculate offset to move the view into correct position
int offset = (width - height) / 2;
// rotate the layout
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(height, width);
mParentLayout.setLayoutParams(lp);
// 90° clockwise
mParentLayout.setRotation(90.0f);
mParentLayout.setTranslationX(offset);
mParentLayout.setTranslationY(-offset);
```
It may look like the suggested answer, but this displays how to get dimensions from DisplayMetrics and the calculating the offset for the translation is a little different because that's the only way it worked properly. | i'll suggest you rotate only button rather than rotating the whole layout like
```
btn_rotate.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v)
{
rotation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.rotate);
rotation.setFillAfter(true);
btn_rotate.startAnimation(rotation);
}
});
```
rotate.xml
----------
```
<set>
<rotate
xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="0"
android:fromDegrees="270"
android:pivotX="50%"
android:pivotY="50%"
android:startOffset="0"
android:toDegrees="270" />
</set>
``` |
21,355,784 | I need to be able to rotate whole layouts on the fly (on the click of a button).
I am able to rotate the layouts using, eg. `layout.setRotation(270.0f)`. **The problem is, after the rotation, the layout `height` and `width` are not matching its parent's**.
I have tried inverting `height` and `width` like so,
```
RelativeLayout layout = (RelativeLayout)findViewById(R.id.rootLayout);
LayoutParams layoutParams = layout.getLayoutParams();
int height = layout.getHeight();
int width = layout.getWidth();
layoutParams.height = width;
layoutParams.width = height;
```
Which does nothing at all.
I am working with `sdk 14`.
The first image below is the app as it starts. The second one, after a rotation. I wish to fill the black "space". Any help would be appreciated.
The images below show only a button in the layout. However, in reality, the layout are a lot more complex. What I am trying to achieve is "faking" a landscape view.


**Edit:** Changed images and added descriptions. | 2014/01/25 | [
"https://Stackoverflow.com/questions/21355784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/845253/"
] | Try this code:
```
btnRotate.setOnClickListener(new OnClickListener()
{
@SuppressLint("NewApi")
@Override
public void onClick(View v)
{
int orientation = getResources().getConfiguration().orientation;
switch(orientation)
{
case Configuration.ORIENTATION_LANDSCAPE:
llparent.setRotation(270.0f);
RelativeLayout.LayoutParams layoutParams_LandsScape =
new RelativeLayout.LayoutParams(
rlRoot.getHeight(), rlRoot.getWidth());
layoutParams_LandsScape.setMargins(
rlRoot.getTop(), rlRoot.getRight(),
rlRoot.getBottom(), rlRoot.getLeft());
layoutParams_LandsScape.addRule(RelativeLayout.CENTER_IN_PARENT);
llparent.setLayoutParams(layoutParams_LandsScape);
break;
case Configuration.ORIENTATION_PORTRAIT:
llparent.setRotation(270.0f);
RelativeLayout.LayoutParams layoutParams_Portrait =
new RelativeLayout.LayoutParams(
rlRoot.getHeight(), rlRoot.getWidth());
layoutParams_Portrait.setMargins(
0, 0, rlRoot.getBottom(), rlRoot.getLeft());
layoutParams_Portrait.addRule(RelativeLayout.CENTER_IN_PARENT);
llparent.setLayoutParams(layoutParams_Portrait);
break;
}
}
});
}
```
And XML:
```
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".RotateAnim">
<RelativeLayout
android:id="@+id/rlroot"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#090">
<LinearLayout
android:id="@+id/llParent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#900"
android:gravity="center"
android:orientation="vertical">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="Button"/>
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
``` | Simple and tricky way to make screen orientation along the button click.. with an example..
Here,I'm using the sharedPreference(Im setting an boolean value based on orientation )
Method for button onClick.
```
public void rotate(View v) {
edt = prefs.edit();
if (!prefs.getBoolean("screen_protrait", true)) {
edt.putBoolean("screen_protrait", true);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else {
edt.putBoolean("screen_protrait", false);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
edt.commit();
}
```
In xml, set an onClick method for rotate button
```
<Button
android:id="@+id/bt_rotate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:onClick="rotate"
android:text="Rotate" />
```
Last one, is in onCreate of Activity you want to set the Prefernce from Application..as
```
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
```
Keep coding.. You can achieve your goal...Let me know,if it's working with your scenario. |
21,355,784 | I need to be able to rotate whole layouts on the fly (on the click of a button).
I am able to rotate the layouts using, eg. `layout.setRotation(270.0f)`. **The problem is, after the rotation, the layout `height` and `width` are not matching its parent's**.
I have tried inverting `height` and `width` like so,
```
RelativeLayout layout = (RelativeLayout)findViewById(R.id.rootLayout);
LayoutParams layoutParams = layout.getLayoutParams();
int height = layout.getHeight();
int width = layout.getWidth();
layoutParams.height = width;
layoutParams.width = height;
```
Which does nothing at all.
I am working with `sdk 14`.
The first image below is the app as it starts. The second one, after a rotation. I wish to fill the black "space". Any help would be appreciated.
The images below show only a button in the layout. However, in reality, the layout are a lot more complex. What I am trying to achieve is "faking" a landscape view.


**Edit:** Changed images and added descriptions. | 2014/01/25 | [
"https://Stackoverflow.com/questions/21355784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/845253/"
] | Not sure why this is useful, but it's a nice puzzle. Here is something that works for me:
On rotate click, do this:
```
RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.main);
int w = mainLayout.getWidth();
int h = mainLayout.getHeight();
mainLayout.setRotation(270.0f);
mainLayout.setTranslationX((w - h) / 2);
mainLayout.setTranslationY((h - w) / 2);
ViewGroup.LayoutParams lp = (ViewGroup.LayoutParams) mainLayout.getLayoutParams();
lp.height = w;
lp.width = h;
mainLayout.requestLayout();
```
And the layout:
```
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="@+id/main"
android:layout_height="match_parent"
android:background="#ffcc88"
tools:context=".TestRotateActivity" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
/>
<Button
android:id="@+id/rotate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Rotate"
android:layout_centerInParent="true"
/>
</RelativeLayout>
``` | try set your layout params to match\_parent after rotation:
```
layout.setRotation(270.0f)
```
and then
```
RelativeLayout layout = (RelativeLayout) findViewById(R.id.rootLayout);
layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
```
EDIT: get the parentView `View parent = layout.getParent();` and set the width and height of the parent view to your layout as you need - in width to height and vice versa. |
21,355,784 | I need to be able to rotate whole layouts on the fly (on the click of a button).
I am able to rotate the layouts using, eg. `layout.setRotation(270.0f)`. **The problem is, after the rotation, the layout `height` and `width` are not matching its parent's**.
I have tried inverting `height` and `width` like so,
```
RelativeLayout layout = (RelativeLayout)findViewById(R.id.rootLayout);
LayoutParams layoutParams = layout.getLayoutParams();
int height = layout.getHeight();
int width = layout.getWidth();
layoutParams.height = width;
layoutParams.width = height;
```
Which does nothing at all.
I am working with `sdk 14`.
The first image below is the app as it starts. The second one, after a rotation. I wish to fill the black "space". Any help would be appreciated.
The images below show only a button in the layout. However, in reality, the layout are a lot more complex. What I am trying to achieve is "faking" a landscape view.


**Edit:** Changed images and added descriptions. | 2014/01/25 | [
"https://Stackoverflow.com/questions/21355784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/845253/"
] | Simple and tricky way to make screen orientation along the button click.. with an example..
Here,I'm using the sharedPreference(Im setting an boolean value based on orientation )
Method for button onClick.
```
public void rotate(View v) {
edt = prefs.edit();
if (!prefs.getBoolean("screen_protrait", true)) {
edt.putBoolean("screen_protrait", true);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else {
edt.putBoolean("screen_protrait", false);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
edt.commit();
}
```
In xml, set an onClick method for rotate button
```
<Button
android:id="@+id/bt_rotate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:onClick="rotate"
android:text="Rotate" />
```
Last one, is in onCreate of Activity you want to set the Prefernce from Application..as
```
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
```
Keep coding.. You can achieve your goal...Let me know,if it's working with your scenario. | Try this code:
(RelativeLayoutOuterFrame) it is the name of your layout.which you want to rotate.
Actually, we are not rotate the layout.we just change height an width value.
```
int w = RelativeLayoutOuterFrame.getWidth();
int h = RelativeLayoutOuterFrame.getHeight();
ViewGroup.LayoutParams lp = (ViewGroup.LayoutParams) RelativeLayoutOuterFrame.getLayoutParams();
lp.height = w;
lp.width = h;
RelativeLayoutOuterFrame.setGravity(RelativeLayout.CENTER_IN_PARENT);
RelativeLayoutOuterFrame.setGravity(RelativeLayout.CENTER_HORIZONTAL);
RelativeLayoutOuterFrame.requestLayout();
``` |
21,355,784 | I need to be able to rotate whole layouts on the fly (on the click of a button).
I am able to rotate the layouts using, eg. `layout.setRotation(270.0f)`. **The problem is, after the rotation, the layout `height` and `width` are not matching its parent's**.
I have tried inverting `height` and `width` like so,
```
RelativeLayout layout = (RelativeLayout)findViewById(R.id.rootLayout);
LayoutParams layoutParams = layout.getLayoutParams();
int height = layout.getHeight();
int width = layout.getWidth();
layoutParams.height = width;
layoutParams.width = height;
```
Which does nothing at all.
I am working with `sdk 14`.
The first image below is the app as it starts. The second one, after a rotation. I wish to fill the black "space". Any help would be appreciated.
The images below show only a button in the layout. However, in reality, the layout are a lot more complex. What I am trying to achieve is "faking" a landscape view.


**Edit:** Changed images and added descriptions. | 2014/01/25 | [
"https://Stackoverflow.com/questions/21355784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/845253/"
] | Simple and tricky way to make screen orientation along the button click.. with an example..
Here,I'm using the sharedPreference(Im setting an boolean value based on orientation )
Method for button onClick.
```
public void rotate(View v) {
edt = prefs.edit();
if (!prefs.getBoolean("screen_protrait", true)) {
edt.putBoolean("screen_protrait", true);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else {
edt.putBoolean("screen_protrait", false);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
edt.commit();
}
```
In xml, set an onClick method for rotate button
```
<Button
android:id="@+id/bt_rotate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:onClick="rotate"
android:text="Rotate" />
```
Last one, is in onCreate of Activity you want to set the Prefernce from Application..as
```
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
```
Keep coding.. You can achieve your goal...Let me know,if it's working with your scenario. | i'll suggest you rotate only button rather than rotating the whole layout like
```
btn_rotate.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v)
{
rotation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.rotate);
rotation.setFillAfter(true);
btn_rotate.startAnimation(rotation);
}
});
```
rotate.xml
----------
```
<set>
<rotate
xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="0"
android:fromDegrees="270"
android:pivotX="50%"
android:pivotY="50%"
android:startOffset="0"
android:toDegrees="270" />
</set>
``` |
21,355,784 | I need to be able to rotate whole layouts on the fly (on the click of a button).
I am able to rotate the layouts using, eg. `layout.setRotation(270.0f)`. **The problem is, after the rotation, the layout `height` and `width` are not matching its parent's**.
I have tried inverting `height` and `width` like so,
```
RelativeLayout layout = (RelativeLayout)findViewById(R.id.rootLayout);
LayoutParams layoutParams = layout.getLayoutParams();
int height = layout.getHeight();
int width = layout.getWidth();
layoutParams.height = width;
layoutParams.width = height;
```
Which does nothing at all.
I am working with `sdk 14`.
The first image below is the app as it starts. The second one, after a rotation. I wish to fill the black "space". Any help would be appreciated.
The images below show only a button in the layout. However, in reality, the layout are a lot more complex. What I am trying to achieve is "faking" a landscape view.


**Edit:** Changed images and added descriptions. | 2014/01/25 | [
"https://Stackoverflow.com/questions/21355784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/845253/"
] | ```
// get root layout from activity's XML
LinearLayout mParentLayout = (LinearLayout) findViewById(R.id.activity_main);
// get screen size from DisplayMetrics if you need to rotate before the screen is shown
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels;
// if you are rotating after the view was shown
// acquire width and height from the layout's parent's LayoutParams
// calculate offset to move the view into correct position
int offset = (width - height) / 2;
// rotate the layout
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(height, width);
mParentLayout.setLayoutParams(lp);
// 90° clockwise
mParentLayout.setRotation(90.0f);
mParentLayout.setTranslationX(offset);
mParentLayout.setTranslationY(-offset);
```
It may look like the suggested answer, but this displays how to get dimensions from DisplayMetrics and the calculating the offset for the translation is a little different because that's the only way it worked properly. | [Android: alternate layout xml for landscape mode](https://stackoverflow.com/questions/4858026/android-alternate-layout-xml-for-landscape-modes)
As I can remember, you should define a new layout for the horizontal view. I think this link can help you |
21,355,784 | I need to be able to rotate whole layouts on the fly (on the click of a button).
I am able to rotate the layouts using, eg. `layout.setRotation(270.0f)`. **The problem is, after the rotation, the layout `height` and `width` are not matching its parent's**.
I have tried inverting `height` and `width` like so,
```
RelativeLayout layout = (RelativeLayout)findViewById(R.id.rootLayout);
LayoutParams layoutParams = layout.getLayoutParams();
int height = layout.getHeight();
int width = layout.getWidth();
layoutParams.height = width;
layoutParams.width = height;
```
Which does nothing at all.
I am working with `sdk 14`.
The first image below is the app as it starts. The second one, after a rotation. I wish to fill the black "space". Any help would be appreciated.
The images below show only a button in the layout. However, in reality, the layout are a lot more complex. What I am trying to achieve is "faking" a landscape view.


**Edit:** Changed images and added descriptions. | 2014/01/25 | [
"https://Stackoverflow.com/questions/21355784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/845253/"
] | Not sure why this is useful, but it's a nice puzzle. Here is something that works for me:
On rotate click, do this:
```
RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.main);
int w = mainLayout.getWidth();
int h = mainLayout.getHeight();
mainLayout.setRotation(270.0f);
mainLayout.setTranslationX((w - h) / 2);
mainLayout.setTranslationY((h - w) / 2);
ViewGroup.LayoutParams lp = (ViewGroup.LayoutParams) mainLayout.getLayoutParams();
lp.height = w;
lp.width = h;
mainLayout.requestLayout();
```
And the layout:
```
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="@+id/main"
android:layout_height="match_parent"
android:background="#ffcc88"
tools:context=".TestRotateActivity" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
/>
<Button
android:id="@+id/rotate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Rotate"
android:layout_centerInParent="true"
/>
</RelativeLayout>
``` | Try this code:
```
btnRotate.setOnClickListener(new OnClickListener()
{
@SuppressLint("NewApi")
@Override
public void onClick(View v)
{
int orientation = getResources().getConfiguration().orientation;
switch(orientation)
{
case Configuration.ORIENTATION_LANDSCAPE:
llparent.setRotation(270.0f);
RelativeLayout.LayoutParams layoutParams_LandsScape =
new RelativeLayout.LayoutParams(
rlRoot.getHeight(), rlRoot.getWidth());
layoutParams_LandsScape.setMargins(
rlRoot.getTop(), rlRoot.getRight(),
rlRoot.getBottom(), rlRoot.getLeft());
layoutParams_LandsScape.addRule(RelativeLayout.CENTER_IN_PARENT);
llparent.setLayoutParams(layoutParams_LandsScape);
break;
case Configuration.ORIENTATION_PORTRAIT:
llparent.setRotation(270.0f);
RelativeLayout.LayoutParams layoutParams_Portrait =
new RelativeLayout.LayoutParams(
rlRoot.getHeight(), rlRoot.getWidth());
layoutParams_Portrait.setMargins(
0, 0, rlRoot.getBottom(), rlRoot.getLeft());
layoutParams_Portrait.addRule(RelativeLayout.CENTER_IN_PARENT);
llparent.setLayoutParams(layoutParams_Portrait);
break;
}
}
});
}
```
And XML:
```
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".RotateAnim">
<RelativeLayout
android:id="@+id/rlroot"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#090">
<LinearLayout
android:id="@+id/llParent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#900"
android:gravity="center"
android:orientation="vertical">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="Button"/>
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
``` |
42,087,917 | When i search results, my data takes some time to show,So i want a progress bar should show after click on search button.It takes 5-8 second to show data.If i add below div after [div class="k-grid-content] div in inspect element then loading bar work well but not hide after data load.How can i add below code before data load and remove after load. Thanks !!
```
<div class="k-loading-mask" style="width: 100%; height: 100%; top: 0px; left: 0px;">
<span class="k-loading-text">Loading...</span>
<div class="k-loading-image"></div>
<div class="k-loading-color"></div>
</div>
``` | 2017/02/07 | [
"https://Stackoverflow.com/questions/42087917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7218492/"
] | If you are interested in Sql Server you can use something like this:
```
using System.Data;
using System.Data.Sql;
var instances = SqlDataSourceEnumerator.Instance.GetDataSources();
foreach (DataRow instance in instances.AsEnumerable())
{
Console.WriteLine($"ServerName: {instance["ServerName"]}; "+
" Instance: {instance["InstanceName"]}");
}
```
More information about the `SqlDataSourceEnumerator` class you can find on [MSDN](https://msdn.microsoft.com/en-us/library/system.data.sql.sqldatasourceenumerator(v=vs.110).aspx).
Note:
-----
This class will look into the local network for servers, if your network is large then there might be a delay in acquiring the response. Also for the empty string instance name, that should be the default instance for that SQL Server.
You can get this information using the SMO too, if you want. | Similar to the accepted answer but for those who have a SqlClient.SqlConnection already opened, you can retrieve the instance name from
```
Dim c As New SqlClient.SqlConnection(sConnectionString)
' Get the database name and server
SourceDatabase = c.Database
SourceServer = c.DataSource
```
Sorry for the VB ;) |
55,879,345 | ```
var request: [String: Any] = [
"Token": "Token",
"Request": [
"CityID": "CityID",
"Filters": [
"IsRecommendedOnly": "0",
"IsShowRooms": "0"
]
]
]
//
print(request)
```
Console output:
```
["Token": "Token", "Request": ["CityID": "CityID", "Filters": ["IsRecommendedOnly": "0", "IsShowRooms": "0"]]]
```
Here I want to update value of **"IsShowRooms"** key from value **"0"** to value **"1"**, I was tried different steps but I am unable to do so, can anyone help me out in this? | 2019/04/27 | [
"https://Stackoverflow.com/questions/55879345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6511607/"
] | You can get the value by typecasting Any to its type and store its value back
```
if var requestVal = request["Request"] as? [String: Any], var filters = requestVal["Filters"] as? [String: String] {
filters["IsShowRooms"] = "1"
requestVal["Filters"] = filters
request["Request"] = requestVal
}
```
Output
>
> ["Token": "Token", "Request": ["CityID": "CityID", "Filters": ["IsRecommendedOnly": "0", "IsShowRooms": "1"]]]
>
>
>
OR
Instead of storing values in Dictionary create a struct. It will be easier to update its properties | You can do this following way.(**Dictionary in swift is treated as value type**)
```
if var reqObj = request["Request"] as? [String: Any] {
if var obj = reqObj["Filters"] as? [String: Any] {
obj["IsShowRooms"] = "1"
reqObj["Filters"] = obj
}
request["Request"] = reqObj
}
print(request)
```
**OUTPUT**
```
["Request": ["CityID": "CityID", "Filters": ["IsShowRooms": "1", "IsRecommendedOnly": "0"]], "Token": "Token"]
``` |
10,414,489 | I'm evaluating Knockout to use with JayData to create a standalone web application.
Following this tutorial (http://jaydata.org/tutorials/creating-a-stand-alone-web-application) it seems that I will be able to store my data on iPhone, Android and in HTML5 browsers...
I'm not sure how can I use JavaScript Query Language with Knockout. I've seen they will have some support it, but I probably you have an idea how can I do it myself.
I'm not sure if Knockout is the appropriate UI library for hybrid applications, hopefully you can share some know-how.
Thank you! | 2012/05/02 | [
"https://Stackoverflow.com/questions/10414489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | **UPDATE**:
From version 1.1.0 JayData has knockoutjs integration module. Include "jaydatamodules/knockout.js" in your html page, and have JayData provide Knockout observables with entity.asKoObservable(). With this module queryable.toArray() accepts ko.ObservableArrays as targets populating it with kendo observable entities.
Custom Bindings is just the way for the integration you are after. You have to connect the knockoutjs way of interacting with the JavaScript objects with the JayData entity metadata functions and its `propertyChanged / propertyChanging` events.
It shouldn't be difficult a task to do, as JayData supports simple property notation (`object.property`) and async property accessor pattern (get\_property(cb), set\_property(cb)) as well. | You can integrate Knockout with jQuery by way of [Custom Bindings](http://knockoutjs.com/documentation/custom-bindings.html). That answers your question about integration. Custom bindings allow you to integrate with any JavaScript UI library, not just jQuery.
In regards to your second question... Knockout really isn't a UI library. It's more of a framework to facilitate data-binding between DOM objects and JavaScript objects. It is used to design web applications following the [MVVM](http://en.wikipedia.org/wiki/Model_View_ViewModel) design paradigm. |
10,414,489 | I'm evaluating Knockout to use with JayData to create a standalone web application.
Following this tutorial (http://jaydata.org/tutorials/creating-a-stand-alone-web-application) it seems that I will be able to store my data on iPhone, Android and in HTML5 browsers...
I'm not sure how can I use JavaScript Query Language with Knockout. I've seen they will have some support it, but I probably you have an idea how can I do it myself.
I'm not sure if Knockout is the appropriate UI library for hybrid applications, hopefully you can share some know-how.
Thank you! | 2012/05/02 | [
"https://Stackoverflow.com/questions/10414489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | **UPDATE**:
From version 1.1.0 JayData has knockoutjs integration module. Include "jaydatamodules/knockout.js" in your html page, and have JayData provide Knockout observables with entity.asKoObservable(). With this module queryable.toArray() accepts ko.ObservableArrays as targets populating it with kendo observable entities.
Custom Bindings is just the way for the integration you are after. You have to connect the knockoutjs way of interacting with the JavaScript objects with the JayData entity metadata functions and its `propertyChanged / propertyChanging` events.
It shouldn't be difficult a task to do, as JayData supports simple property notation (`object.property`) and async property accessor pattern (get\_property(cb), set\_property(cb)) as well. | Here is an [example](http://jaydata.org/examples/Knockoutjs/Northwind.html) It is integrated in recent release probably |
126,060 | i wanted to remove "billing agreement" "recurring profile" "customer token" "My Downloadable Products" in account navigation.
Magento ver. 1.9.2.4
please help me . | 2016/07/17 | [
"https://magento.stackexchange.com/questions/126060",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/37698/"
] | Billing Agreements :
copy this file
`app/design/frontend/base/default/layout/sales/billing_agreement.xml`
in your current theme and remove below lines
```
<reference name="customer_account_navigation" >
<action method="addLink" translate="label"><name>billing_agreements</name><path>sales/billing_agreement/</path><label>Billing Agreements</label></action>
</reference>
```
Recurring Profiles :
copy this file
`app/design/frontend/base/default/layout/sales/recurring_profile.xml`
in your current theme and remove below lines
```
<reference name="customer_account_navigation" >
<action method="addLink" translate="label"><name>recurring_profiles</name><path>sales/recurring_profile/</path><label>Recurring Profiles</label></action>
</reference>
```
My Downloadable Products :
copy this file
`app/design/frontend/base/default/layout/downloadable.xml`
in your current theme and remove below lines
```
<reference name="customer_account_navigation">
<action method="addLink" translate="label" module="downloadable"><name>downloadable_products</name><path>downloadable/customer/products</path><label>My Downloadable Products</label></action>
</reference>
``` | This can be done using following code in your theme local.xml
```
<customer_account>
<reference name="left">
<!--Remove the whole block -->
<action
method="unsetChild"><name>customer_account_navigation</name></action>
<!-- if you don't want to add any link just skip below part -->
<block type="customer/account_navigation"
name="customer_account_navigation" before="-"
template="customer/account/navigation.phtml">
<action method="addLink" translate="label"
module="customer"><name>account</name><path>customer/account/</path><label>Account
Dashboard</label></action>
</block>
</reference>
</customer_account>
```
Using the above code in your local.xml file will remove the links to your account navigation. |
4,523,604 | I have a problem with fitting all my annotations to the screen... sometimes it shows all annotations, but some other times the app is zooming in between the two annotations so that none of them are visible...
I want the app to always fit the region to the annotations and not to zoom in between them... what do I do wrong?
```
if ([mapView.annotations count] == 2) {
CLLocationCoordinate2D SouthWest = location;
CLLocationCoordinate2D NorthEast = savedPosition;
NorthEast.latitude = MAX(NorthEast.latitude, savedPosition.latitude);
NorthEast.longitude = MAX(NorthEast.longitude, savedPosition.longitude);
SouthWest.latitude = MIN(SouthWest.latitude, location.latitude);
SouthWest.longitude = MIN(SouthWest.longitude, location.longitude);
CLLocation *locSouthWest = [[CLLocation alloc] initWithLatitude:SouthWest.latitude longitude:SouthWest.longitude];
CLLocation *locNorthEast = [[CLLocation alloc] initWithLatitude:NorthEast.latitude longitude:NorthEast.longitude];
CLLocationDistance meter = [locSouthWest distanceFromLocation:locNorthEast];
MKCoordinateRegion region;
region.span.latitudeDelta = meter / 111319.5;
region.span.longitudeDelta = 0.0;
region.center.latitude = (SouthWest.latitude + NorthEast.latitude) / 2.0;
region.center.longitude = (SouthWest.longitude + NorthEast.longitude) / 2.0;
region = [mapView regionThatFits:region];
[mapView setRegion:region animated:YES];
[locSouthWest release];
[locNorthEast release];
}
```
Any ideas?
Thanks!! | 2010/12/24 | [
"https://Stackoverflow.com/questions/4523604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/543570/"
] | Use the following code
```
-(void)zoomToFitMapAnnotations:(MKMapView*)mapView{
if([mapView.annotations count] == 0)
return;
CLLocationCoordinate2D topLeftCoord;
topLeftCoord.latitude = -90;
topLeftCoord.longitude = 180;
CLLocationCoordinate2D bottomRightCoord;
bottomRightCoord.latitude = 90;
bottomRightCoord.longitude = -180;
for(FSMapAnnotation* annotation in mapView.annotations)
{
topLeftCoord.longitude = fmin(topLeftCoord.longitude, annotation.coordinate.longitude);
topLeftCoord.latitude = fmax(topLeftCoord.latitude, annotation.coordinate.latitude);
bottomRightCoord.longitude = fmax(bottomRightCoord.longitude, annotation.coordinate.longitude);
bottomRightCoord.latitude = fmin(bottomRightCoord.latitude, annotation.coordinate.latitude);
}
MKCoordinateRegion region;
region.center.latitude = topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5;
region.center.longitude = topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5;
region.span.latitudeDelta = fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.1; // Add a little extra space on the sides
region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.1; // Add a little extra space on the sides
region = [mapView regionThatFits:region];
[mapView setRegion:region animated:YES];
}
``` | Instead of:
```
region.span.latitudeDelta = meter / 111319.5;
region.span.longitudeDelta = 0.0;
region.center.latitude = (SouthWest.latitude + NorthEast.latitude) / 2.0;
region.center.longitude = (SouthWest.longitude + NorthEast.longitude) / 2.0;
```
Try adding:
```
region.span.latitudeDelta = fabs(NorthEast.latitude - SouthWest.latitude) * 1.2;
region.span.longitudeDelta = fabs(SouthWest.longitude - NorthEast.longitude) * 1.2;
region.center.latitude = NorthEast.latitude - (NorthEast.latitude - SouthWest.latitude) * 0.5;
region.center.longitude = NorthEast.longitude + (SouthWest.longitude - NorthEast.longitude) * 0.5;
```
And removing:
```
CLLocationDistance meter = [locSouthWest distanceFromLocation:locNorthEast];
``` |
14,565,365 | As from the jquery api page
<http://api.jquery.com/jQuery.getScript/>
>
> Success Callback
> ----------------
>
>
> The callback is fired once the script has been loaded but not necessarily executed.
>
>
>
> ```
> $.getScript("test.js", function() {
> foo();
> });
>
> ```
>
>
if the `foo()` function depend on test.js, it cannot be execute successfully.
I saw similar thing with google map api but in that case you can specify the callback function in the ajax script url. But in general is there an obvious way to wait until the ajax script executed to do the callback? | 2013/01/28 | [
"https://Stackoverflow.com/questions/14565365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2018232/"
] | `$.getScript(...)` + `setInterval(...)` worked for me:
======================================================
```
$.getScript('https://www.google.com/recaptcha/api.js')
.done(function() {
var setIntervalID = setInterval(function() {
if (window.grecaptcha) {
clearInterval(setIntervalID);
console.log(window.grecaptcha);
letsWorkWithWindowDotGreptcha();
};
}, 300);
});
function letsWorkWithWindowDotGreptcha() {
// window.greptcha is available here....
}
```
Once the `variable` we are looking for is defined (in my case `window.grecaptcha`, i can call a `closure function` which can be `abstracted out`.
Good Luck... | As mentioned `then`, `done` and the `$.getScript` callback fire when the script was loaded and not executed wich may be to early … intervals may be a way of tackling this but in my opinion it seems not very elegant.
My solution is triggering an event inside the async loaded script like:
```
jQuery( document ).trigger( 'loadedeventsjs' );
```
And inside my main script i could bind to that event like:
```
jQuery( document ).on( 'loadedeventsjs', function() {
jQuery( '#mainmenu_wrapper' ).on( 'swiperight', menuout );
} );
``` |
14,565,365 | As from the jquery api page
<http://api.jquery.com/jQuery.getScript/>
>
> Success Callback
> ----------------
>
>
> The callback is fired once the script has been loaded but not necessarily executed.
>
>
>
> ```
> $.getScript("test.js", function() {
> foo();
> });
>
> ```
>
>
if the `foo()` function depend on test.js, it cannot be execute successfully.
I saw similar thing with google map api but in that case you can specify the callback function in the ajax script url. But in general is there an obvious way to wait until the ajax script executed to do the callback? | 2013/01/28 | [
"https://Stackoverflow.com/questions/14565365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2018232/"
] | I know it is an old question but i think both answers containing "done" are not explained by their owners and they are in fact the best answers.
The most up-voted answer calls for using "async:false" which will in turn create a sync call which is not optimal. on the other hand promises and promise handlers were introduced to jquery since version 1.5 (maybe earlier?) in this case we are trying to load a script asynchronously and wait for it to finish running.
The callback by definition [getScript documentation](https://api.jquery.com/jquery.getscript/)
>
> The callback is fired once the script has been loaded but not necessarily executed.
>
>
>
what you need to look for instead is how promises act. In this case as you are looking for a script to load asynchronously you can use either "then" or "done"
have a look at [this thread](https://stackoverflow.com/questions/5436327/jquery-deferreds-and-promises-then-vs-done) which explains the difference nicely.
Basically done will be called only when a promise is resolved. in our case when the script was loaded successfully and finished running. So basically in your code it would mean:
```
$.getScript("test.js", function() {
foo();
});
```
should be changed to:
```
$.getScript("test.js").done(function(script, textStatus) {
console.log("finished loading and running test.js. with a status of" + textStatus);
});
``` | ```
$.getScript( "ajaxFile/myjs.js" )
.done(function( s, Status ) {
console.warn( Status );
})
.fail(function( jqxhr, settings, exception ) {
console.warn( "Something went wrong"+exception );
});
``` |
14,565,365 | As from the jquery api page
<http://api.jquery.com/jQuery.getScript/>
>
> Success Callback
> ----------------
>
>
> The callback is fired once the script has been loaded but not necessarily executed.
>
>
>
> ```
> $.getScript("test.js", function() {
> foo();
> });
>
> ```
>
>
if the `foo()` function depend on test.js, it cannot be execute successfully.
I saw similar thing with google map api but in that case you can specify the callback function in the ajax script url. But in general is there an obvious way to wait until the ajax script executed to do the callback? | 2013/01/28 | [
"https://Stackoverflow.com/questions/14565365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2018232/"
] | I know it is an old question but i think both answers containing "done" are not explained by their owners and they are in fact the best answers.
The most up-voted answer calls for using "async:false" which will in turn create a sync call which is not optimal. on the other hand promises and promise handlers were introduced to jquery since version 1.5 (maybe earlier?) in this case we are trying to load a script asynchronously and wait for it to finish running.
The callback by definition [getScript documentation](https://api.jquery.com/jquery.getscript/)
>
> The callback is fired once the script has been loaded but not necessarily executed.
>
>
>
what you need to look for instead is how promises act. In this case as you are looking for a script to load asynchronously you can use either "then" or "done"
have a look at [this thread](https://stackoverflow.com/questions/5436327/jquery-deferreds-and-promises-then-vs-done) which explains the difference nicely.
Basically done will be called only when a promise is resolved. in our case when the script was loaded successfully and finished running. So basically in your code it would mean:
```
$.getScript("test.js", function() {
foo();
});
```
should be changed to:
```
$.getScript("test.js").done(function(script, textStatus) {
console.log("finished loading and running test.js. with a status of" + textStatus);
});
``` | As mentioned `then`, `done` and the `$.getScript` callback fire when the script was loaded and not executed wich may be to early … intervals may be a way of tackling this but in my opinion it seems not very elegant.
My solution is triggering an event inside the async loaded script like:
```
jQuery( document ).trigger( 'loadedeventsjs' );
```
And inside my main script i could bind to that event like:
```
jQuery( document ).on( 'loadedeventsjs', function() {
jQuery( '#mainmenu_wrapper' ).on( 'swiperight', menuout );
} );
``` |
14,565,365 | As from the jquery api page
<http://api.jquery.com/jQuery.getScript/>
>
> Success Callback
> ----------------
>
>
> The callback is fired once the script has been loaded but not necessarily executed.
>
>
>
> ```
> $.getScript("test.js", function() {
> foo();
> });
>
> ```
>
>
if the `foo()` function depend on test.js, it cannot be execute successfully.
I saw similar thing with google map api but in that case you can specify the callback function in the ajax script url. But in general is there an obvious way to wait until the ajax script executed to do the callback? | 2013/01/28 | [
"https://Stackoverflow.com/questions/14565365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2018232/"
] | `$.getScript(...)` + `setInterval(...)` worked for me:
======================================================
```
$.getScript('https://www.google.com/recaptcha/api.js')
.done(function() {
var setIntervalID = setInterval(function() {
if (window.grecaptcha) {
clearInterval(setIntervalID);
console.log(window.grecaptcha);
letsWorkWithWindowDotGreptcha();
};
}, 300);
});
function letsWorkWithWindowDotGreptcha() {
// window.greptcha is available here....
}
```
Once the `variable` we are looking for is defined (in my case `window.grecaptcha`, i can call a `closure function` which can be `abstracted out`.
Good Luck... | ```
$.getScript( "ajaxFile/myjs.js" )
.done(function( s, Status ) {
console.warn( Status );
})
.fail(function( jqxhr, settings, exception ) {
console.warn( "Something went wrong"+exception );
});
``` |
14,565,365 | As from the jquery api page
<http://api.jquery.com/jQuery.getScript/>
>
> Success Callback
> ----------------
>
>
> The callback is fired once the script has been loaded but not necessarily executed.
>
>
>
> ```
> $.getScript("test.js", function() {
> foo();
> });
>
> ```
>
>
if the `foo()` function depend on test.js, it cannot be execute successfully.
I saw similar thing with google map api but in that case you can specify the callback function in the ajax script url. But in general is there an obvious way to wait until the ajax script executed to do the callback? | 2013/01/28 | [
"https://Stackoverflow.com/questions/14565365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2018232/"
] | I know it is an old question but i think both answers containing "done" are not explained by their owners and they are in fact the best answers.
The most up-voted answer calls for using "async:false" which will in turn create a sync call which is not optimal. on the other hand promises and promise handlers were introduced to jquery since version 1.5 (maybe earlier?) in this case we are trying to load a script asynchronously and wait for it to finish running.
The callback by definition [getScript documentation](https://api.jquery.com/jquery.getscript/)
>
> The callback is fired once the script has been loaded but not necessarily executed.
>
>
>
what you need to look for instead is how promises act. In this case as you are looking for a script to load asynchronously you can use either "then" or "done"
have a look at [this thread](https://stackoverflow.com/questions/5436327/jquery-deferreds-and-promises-then-vs-done) which explains the difference nicely.
Basically done will be called only when a promise is resolved. in our case when the script was loaded successfully and finished running. So basically in your code it would mean:
```
$.getScript("test.js", function() {
foo();
});
```
should be changed to:
```
$.getScript("test.js").done(function(script, textStatus) {
console.log("finished loading and running test.js. with a status of" + textStatus);
});
``` | I was facing the same issue today and came up with a solution based on promises and a interval timer:
```
$.getScript("test.js", function() {
var $def = $.Deferred();
if (typeof foo === 'undefined') { // "foo" isn't available
var attempts = 0;
// create an interval
// that will check each 100ms if the "foo" function
// was loaded
var interval = setInterval(function() {
if (typeof foo !== 'undefined') { // loaded
window.clearInterval(interval);
$def.resolve();
}
// after X unsuccessfull attempts, abort the operation
else if (attempts >= 100) {
window.clearInterval(interval);
$def.reject('Something went wrong');
}
attempts++;
}, 100);
}
else { // "foo" is available
$def.resolve();
}
return $def.promise();
}).then(function() {
// at this point "foo()" is definitely available.
}).fail(function() {
// deal with the failure
});
```
The ideia is that you load a given script that will expose some variable (the `foo` function in your question example) that still doesn't exist, so after the script is loaded by `getScript` you check if this variable exists, if not you create an interval that will continuously check if the variable is available, and only when this condition is satisfied you resolve the promise. |
14,565,365 | As from the jquery api page
<http://api.jquery.com/jQuery.getScript/>
>
> Success Callback
> ----------------
>
>
> The callback is fired once the script has been loaded but not necessarily executed.
>
>
>
> ```
> $.getScript("test.js", function() {
> foo();
> });
>
> ```
>
>
if the `foo()` function depend on test.js, it cannot be execute successfully.
I saw similar thing with google map api but in that case you can specify the callback function in the ajax script url. But in general is there an obvious way to wait until the ajax script executed to do the callback? | 2013/01/28 | [
"https://Stackoverflow.com/questions/14565365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2018232/"
] | As mentioned `then`, `done` and the `$.getScript` callback fire when the script was loaded and not executed wich may be to early … intervals may be a way of tackling this but in my opinion it seems not very elegant.
My solution is triggering an event inside the async loaded script like:
```
jQuery( document ).trigger( 'loadedeventsjs' );
```
And inside my main script i could bind to that event like:
```
jQuery( document ).on( 'loadedeventsjs', function() {
jQuery( '#mainmenu_wrapper' ).on( 'swiperight', menuout );
} );
``` | $getScript use like this
```
$.getScript( "js/jquery.raty.min.js" )
.done(function( script, textStatus ) {
console.log( textStatus );
}
});
```
this is working fine for me |
14,565,365 | As from the jquery api page
<http://api.jquery.com/jQuery.getScript/>
>
> Success Callback
> ----------------
>
>
> The callback is fired once the script has been loaded but not necessarily executed.
>
>
>
> ```
> $.getScript("test.js", function() {
> foo();
> });
>
> ```
>
>
if the `foo()` function depend on test.js, it cannot be execute successfully.
I saw similar thing with google map api but in that case you can specify the callback function in the ajax script url. But in general is there an obvious way to wait until the ajax script executed to do the callback? | 2013/01/28 | [
"https://Stackoverflow.com/questions/14565365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2018232/"
] | I know it is an old question but i think both answers containing "done" are not explained by their owners and they are in fact the best answers.
The most up-voted answer calls for using "async:false" which will in turn create a sync call which is not optimal. on the other hand promises and promise handlers were introduced to jquery since version 1.5 (maybe earlier?) in this case we are trying to load a script asynchronously and wait for it to finish running.
The callback by definition [getScript documentation](https://api.jquery.com/jquery.getscript/)
>
> The callback is fired once the script has been loaded but not necessarily executed.
>
>
>
what you need to look for instead is how promises act. In this case as you are looking for a script to load asynchronously you can use either "then" or "done"
have a look at [this thread](https://stackoverflow.com/questions/5436327/jquery-deferreds-and-promises-then-vs-done) which explains the difference nicely.
Basically done will be called only when a promise is resolved. in our case when the script was loaded successfully and finished running. So basically in your code it would mean:
```
$.getScript("test.js", function() {
foo();
});
```
should be changed to:
```
$.getScript("test.js").done(function(script, textStatus) {
console.log("finished loading and running test.js. with a status of" + textStatus);
});
``` | $getScript use like this
```
$.getScript( "js/jquery.raty.min.js" )
.done(function( script, textStatus ) {
console.log( textStatus );
}
});
```
this is working fine for me |
14,565,365 | As from the jquery api page
<http://api.jquery.com/jQuery.getScript/>
>
> Success Callback
> ----------------
>
>
> The callback is fired once the script has been loaded but not necessarily executed.
>
>
>
> ```
> $.getScript("test.js", function() {
> foo();
> });
>
> ```
>
>
if the `foo()` function depend on test.js, it cannot be execute successfully.
I saw similar thing with google map api but in that case you can specify the callback function in the ajax script url. But in general is there an obvious way to wait until the ajax script executed to do the callback? | 2013/01/28 | [
"https://Stackoverflow.com/questions/14565365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2018232/"
] | `$.getScript(...)` + `setInterval(...)` worked for me:
======================================================
```
$.getScript('https://www.google.com/recaptcha/api.js')
.done(function() {
var setIntervalID = setInterval(function() {
if (window.grecaptcha) {
clearInterval(setIntervalID);
console.log(window.grecaptcha);
letsWorkWithWindowDotGreptcha();
};
}, 300);
});
function letsWorkWithWindowDotGreptcha() {
// window.greptcha is available here....
}
```
Once the `variable` we are looking for is defined (in my case `window.grecaptcha`, i can call a `closure function` which can be `abstracted out`.
Good Luck... | I'm afraid the solution requires polling for the dependency. Alternatively the script needs to be wrapped in a pre-defined callback like AMD. |
14,565,365 | As from the jquery api page
<http://api.jquery.com/jQuery.getScript/>
>
> Success Callback
> ----------------
>
>
> The callback is fired once the script has been loaded but not necessarily executed.
>
>
>
> ```
> $.getScript("test.js", function() {
> foo();
> });
>
> ```
>
>
if the `foo()` function depend on test.js, it cannot be execute successfully.
I saw similar thing with google map api but in that case you can specify the callback function in the ajax script url. But in general is there an obvious way to wait until the ajax script executed to do the callback? | 2013/01/28 | [
"https://Stackoverflow.com/questions/14565365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2018232/"
] | I was facing the same issue today and came up with a solution based on promises and a interval timer:
```
$.getScript("test.js", function() {
var $def = $.Deferred();
if (typeof foo === 'undefined') { // "foo" isn't available
var attempts = 0;
// create an interval
// that will check each 100ms if the "foo" function
// was loaded
var interval = setInterval(function() {
if (typeof foo !== 'undefined') { // loaded
window.clearInterval(interval);
$def.resolve();
}
// after X unsuccessfull attempts, abort the operation
else if (attempts >= 100) {
window.clearInterval(interval);
$def.reject('Something went wrong');
}
attempts++;
}, 100);
}
else { // "foo" is available
$def.resolve();
}
return $def.promise();
}).then(function() {
// at this point "foo()" is definitely available.
}).fail(function() {
// deal with the failure
});
```
The ideia is that you load a given script that will expose some variable (the `foo` function in your question example) that still doesn't exist, so after the script is loaded by `getScript` you check if this variable exists, if not you create an interval that will continuously check if the variable is available, and only when this condition is satisfied you resolve the promise. | I'm afraid the solution requires polling for the dependency. Alternatively the script needs to be wrapped in a pre-defined callback like AMD. |
14,565,365 | As from the jquery api page
<http://api.jquery.com/jQuery.getScript/>
>
> Success Callback
> ----------------
>
>
> The callback is fired once the script has been loaded but not necessarily executed.
>
>
>
> ```
> $.getScript("test.js", function() {
> foo();
> });
>
> ```
>
>
if the `foo()` function depend on test.js, it cannot be execute successfully.
I saw similar thing with google map api but in that case you can specify the callback function in the ajax script url. But in general is there an obvious way to wait until the ajax script executed to do the callback? | 2013/01/28 | [
"https://Stackoverflow.com/questions/14565365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2018232/"
] | `$.getScript(...)` + `setInterval(...)` worked for me:
======================================================
```
$.getScript('https://www.google.com/recaptcha/api.js')
.done(function() {
var setIntervalID = setInterval(function() {
if (window.grecaptcha) {
clearInterval(setIntervalID);
console.log(window.grecaptcha);
letsWorkWithWindowDotGreptcha();
};
}, 300);
});
function letsWorkWithWindowDotGreptcha() {
// window.greptcha is available here....
}
```
Once the `variable` we are looking for is defined (in my case `window.grecaptcha`, i can call a `closure function` which can be `abstracted out`.
Good Luck... | I was facing the same issue today and came up with a solution based on promises and a interval timer:
```
$.getScript("test.js", function() {
var $def = $.Deferred();
if (typeof foo === 'undefined') { // "foo" isn't available
var attempts = 0;
// create an interval
// that will check each 100ms if the "foo" function
// was loaded
var interval = setInterval(function() {
if (typeof foo !== 'undefined') { // loaded
window.clearInterval(interval);
$def.resolve();
}
// after X unsuccessfull attempts, abort the operation
else if (attempts >= 100) {
window.clearInterval(interval);
$def.reject('Something went wrong');
}
attempts++;
}, 100);
}
else { // "foo" is available
$def.resolve();
}
return $def.promise();
}).then(function() {
// at this point "foo()" is definitely available.
}).fail(function() {
// deal with the failure
});
```
The ideia is that you load a given script that will expose some variable (the `foo` function in your question example) that still doesn't exist, so after the script is loaded by `getScript` you check if this variable exists, if not you create an interval that will continuously check if the variable is available, and only when this condition is satisfied you resolve the promise. |
42,756,655 | I have this function that finds the preorder of a binary tree. I'm a bit unsure how I can edit this to store the traversal instead of printing it. I want to store it in an array possibly so I can compare it to another traversal, but creating an array within this function will be an issue since I implemented it recursively. Any ideas?
I was thinking of passing it an empty array, but how I can't seem to picture how I'd increment through the array due to the function being recursive.
```
void preorder(node *node)
{
if(node == NULL)
return;
printf("%d", node->data);
preorder(node->left);
preorder(node->right);
}
``` | 2017/03/13 | [
"https://Stackoverflow.com/questions/42756655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7608519/"
] | You are on the right track. Yes, pass in an array that is initially empty. Also pass an index initialized to 0 to keep track of how much of the array you have filled in. `*index` represents the next array index available for filling in data. You increment the index only when you fill data in the array. The recursive cases will be handled naturally. Each invocation of `inorder` will increment the index by 1.
```
void inorder(node *node, int *array, int *index)
{
if (node == NULL)
return;
inorder(node->left, array, index);
array[(*index)++] = node->data;
inorder(node->right, array, index);
}
``` | You just have to modify your preorder traversal code a bit and keep storing the values in an array using the `index` variable.
```
int arr[10]; // Change it to the number of nodes in your tree
int index = 0;
void store(struct node *root)
{
if (root != NULL)
{
printf("%d \n", root->key);
arr[index++] = root->key;
store(root->left);
store(root->right);
}
}
``` |
238,782 | CONTEXT : I'm building a website where users can upload many files. [WEB SERVER, no gpu]
WHAT I WANT : that an uploaded .obj => render an image preview as a .png
WHY : to manage a library of multiple files so the image is to have a preview, imagine a multimedia library like google photo, but with videos, audios, photos, 3d files (with their thumbnail), ETC.
I CAN : with aasimp : I can easily convert from .obj, .fbx..... to .glb or .gltf [but aasimp have no solution to render an image from a 3d file]
I ALSO CAN : render 1 frame to png (( but only from a .blend ))
SEE HOW I SUCCESSFULLY INSTALLED BLEND + RENDER .blend TO .PNG ON LINUX : <https://almalinux.discourse.group/t/how-to-install-blender-3d-withtout-snap-and-without-a-desktop/526>
**QUESTION** : is it possible to invoke from the command line (linux web server without a desktop...) to create a new .blend and import a .obj or .fbx into that new .blend and than I can do my render?
WHY THE QUESTION : the command "--render-frame" accepts only .blend so the only "missing" stuff I need is to convert a .obj or .fbx from the command line (shell or python script) to convert to .blend
when I TRY this
```
xvfb-run -a --server-args="-screen 0, 1280x720x24" /opt/blender293/blender pathtoOBJ.obj --render-frame 1 -F PNG -b
```
I get this
```
Error: File format is not supported in file 'pathtoOBJ.obj'
```
---
when I do the same command with a .blend it's working fine see this. This image was generated from a .blend via a linux COMMAND LINE (shell) without GPU, without desktop
[](https://i.stack.imgur.com/4AV2U.png) | 2021/09/22 | [
"https://blender.stackexchange.com/questions/238782",
"https://blender.stackexchange.com",
"https://blender.stackexchange.com/users/132680/"
] | Assuming you have this animation:
[](https://i.stack.imgur.com/2iKxG.png)
[](https://i.stack.imgur.com/1IfRm.gif)
and now you want the same animation on another y-value you can do this:
select your animation, press SHIFT-D to copy all keyframes, move it with your mouse where you want to have it and you get something like this:
[](https://i.stack.imgur.com/UwH8N.png)
Now go to frame 1 and keyframe delta transform - location:
[](https://i.stack.imgur.com/M2cgg.png)
Then go 1 frame before your first copied keyframe and keyframe again:
[](https://i.stack.imgur.com/GTjwB.png)
then it looks like this:
[](https://i.stack.imgur.com/Q41Xb.png)
Then change your timeline +1 frame and change the y-value (or other values as you need) and keyframe the delta again.
done.
result:
[](https://i.stack.imgur.com/Foh8H.gif) | The only thing I can think of at this moment would be to make your duplicate, open up the Graph Editor, select the keyframes you wish to move, and `G`+`Y` to change their value (not time). You may need to hide whatever you don't want to edit or don't want to edit in the same way. Like if you want to move the `X` very far, the `Y` not so far, and the `Z` not at all, you would hide everything but `X`, select and move, deselect, then hide `X` and unhide `Y` and select and move. |
238,782 | CONTEXT : I'm building a website where users can upload many files. [WEB SERVER, no gpu]
WHAT I WANT : that an uploaded .obj => render an image preview as a .png
WHY : to manage a library of multiple files so the image is to have a preview, imagine a multimedia library like google photo, but with videos, audios, photos, 3d files (with their thumbnail), ETC.
I CAN : with aasimp : I can easily convert from .obj, .fbx..... to .glb or .gltf [but aasimp have no solution to render an image from a 3d file]
I ALSO CAN : render 1 frame to png (( but only from a .blend ))
SEE HOW I SUCCESSFULLY INSTALLED BLEND + RENDER .blend TO .PNG ON LINUX : <https://almalinux.discourse.group/t/how-to-install-blender-3d-withtout-snap-and-without-a-desktop/526>
**QUESTION** : is it possible to invoke from the command line (linux web server without a desktop...) to create a new .blend and import a .obj or .fbx into that new .blend and than I can do my render?
WHY THE QUESTION : the command "--render-frame" accepts only .blend so the only "missing" stuff I need is to convert a .obj or .fbx from the command line (shell or python script) to convert to .blend
when I TRY this
```
xvfb-run -a --server-args="-screen 0, 1280x720x24" /opt/blender293/blender pathtoOBJ.obj --render-frame 1 -F PNG -b
```
I get this
```
Error: File format is not supported in file 'pathtoOBJ.obj'
```
---
when I do the same command with a .blend it's working fine see this. This image was generated from a .blend via a linux COMMAND LINE (shell) without GPU, without desktop
[](https://i.stack.imgur.com/4AV2U.png) | 2021/09/22 | [
"https://blender.stackexchange.com/questions/238782",
"https://blender.stackexchange.com",
"https://blender.stackexchange.com/users/132680/"
] | The simplest way to offset an animation is to sandwich in a new parent:
[](https://i.stack.imgur.com/z3Ykh.jpg)
Here, I started with an object with a single location keyframe, animated by an f-curve modifier. Then I duplicated the object and parented it to an empty. Finally, I moved that empty to create the offset that I wanted.
This can be done for location, rotation, or scale offsets.
If the object is already parented to an object, you should sandwich in the new parent: parent the object to the empty, then parent the empty to the original parent of the object.
This doesn't require any kind of fiddliness or math, and can be done to eye as easily as numerically, just by controlling the new parent's transform. There are similar techniques involving delta transforms, but deltas are a weird, out-of-date, not-quite-there solution to the problem, and so I avoid deltas whenever possible. | The only thing I can think of at this moment would be to make your duplicate, open up the Graph Editor, select the keyframes you wish to move, and `G`+`Y` to change their value (not time). You may need to hide whatever you don't want to edit or don't want to edit in the same way. Like if you want to move the `X` very far, the `Y` not so far, and the `Z` not at all, you would hide everything but `X`, select and move, deselect, then hide `X` and unhide `Y` and select and move. |
72,495,735 | I have the following two common table expressions:
```
WITH cte_1 AS (
SELECT
u.id AS users,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o
ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
),
cte_2 AS (
SELECT
u.id AS users,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o
ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
HAVING COUNT(o.id) > 0
)
```
Notice that both CTEs are exactly the same (with the exception of `HAVING COUNT(o.id) > 0` clause in `cte_2`).
If I independently run the query inside of `cte_1`, I get a value of 200. If I independently run the query inside of `cte_2`, I get a value of 75. I'm trying to run a single query using these CTEs to get the following counts:
```
foo bar
200 75
```
I tried the following (which is syntactically incorrect):
```
WITH cte_1 AS (
SELECT
u.id AS users,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o
ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
),
cte_2 AS (
SELECT
u.id AS users,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o
ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
HAVING COUNT(o.id) > 0
)
SELECT count(users) as foo
FROM cte_1
SELECT count(order_count) as bar
from cte2
```
Any assistance you can give this SQL newbie would be greatly appreciated! Thanks! | 2022/06/03 | [
"https://Stackoverflow.com/questions/72495735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18908491/"
] | ```
WITH
cte as (
SELECT
u.id AS userid,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY
u.id
)
SELECT
count(userid) as foo,
sum(case when order_count > 0 then 1 else 0 end) as bar
FROM
cte
``` | ```
with summary as (
SELECT u.id AS userid, count(o.id) AS order_count
FROM users u LEFT JOIN orders o ON u.id = o.user_id
WHERE u.created_at BETWEEN '2019-07-01 00:00:00.000000'
AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
)
select count(userid), count(case when order_count > 0 then 1 end)
from summary;
``` |
72,495,735 | I have the following two common table expressions:
```
WITH cte_1 AS (
SELECT
u.id AS users,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o
ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
),
cte_2 AS (
SELECT
u.id AS users,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o
ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
HAVING COUNT(o.id) > 0
)
```
Notice that both CTEs are exactly the same (with the exception of `HAVING COUNT(o.id) > 0` clause in `cte_2`).
If I independently run the query inside of `cte_1`, I get a value of 200. If I independently run the query inside of `cte_2`, I get a value of 75. I'm trying to run a single query using these CTEs to get the following counts:
```
foo bar
200 75
```
I tried the following (which is syntactically incorrect):
```
WITH cte_1 AS (
SELECT
u.id AS users,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o
ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
),
cte_2 AS (
SELECT
u.id AS users,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o
ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
HAVING COUNT(o.id) > 0
)
SELECT count(users) as foo
FROM cte_1
SELECT count(order_count) as bar
from cte2
```
Any assistance you can give this SQL newbie would be greatly appreciated! Thanks! | 2022/06/03 | [
"https://Stackoverflow.com/questions/72495735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18908491/"
] | ```
with summary as (
SELECT u.id AS userid, count(o.id) AS order_count
FROM users u LEFT JOIN orders o ON u.id = o.user_id
WHERE u.created_at BETWEEN '2019-07-01 00:00:00.000000'
AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
)
select count(userid), count(case when order_count > 0 then 1 end)
from summary;
``` | Assuming that you must use these CTEs, and this is not a [XY problem](https://en.wikipedia.org/wiki/XY_problem), you could use a CROSS JOIN to join these results like so:
```
SELECT foo_q.foo, bar_q.bar
FROM
(SELECT count(users) as foo
FROM cte_1) as foo_q
CROSS JOIN
(SELECT count(order_count) as bar
FROM cte_2) as bar_q
``` |
72,495,735 | I have the following two common table expressions:
```
WITH cte_1 AS (
SELECT
u.id AS users,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o
ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
),
cte_2 AS (
SELECT
u.id AS users,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o
ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
HAVING COUNT(o.id) > 0
)
```
Notice that both CTEs are exactly the same (with the exception of `HAVING COUNT(o.id) > 0` clause in `cte_2`).
If I independently run the query inside of `cte_1`, I get a value of 200. If I independently run the query inside of `cte_2`, I get a value of 75. I'm trying to run a single query using these CTEs to get the following counts:
```
foo bar
200 75
```
I tried the following (which is syntactically incorrect):
```
WITH cte_1 AS (
SELECT
u.id AS users,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o
ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
),
cte_2 AS (
SELECT
u.id AS users,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o
ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
HAVING COUNT(o.id) > 0
)
SELECT count(users) as foo
FROM cte_1
SELECT count(order_count) as bar
from cte2
```
Any assistance you can give this SQL newbie would be greatly appreciated! Thanks! | 2022/06/03 | [
"https://Stackoverflow.com/questions/72495735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18908491/"
] | ```
with summary as (
SELECT u.id AS userid, count(o.id) AS order_count
FROM users u LEFT JOIN orders o ON u.id = o.user_id
WHERE u.created_at BETWEEN '2019-07-01 00:00:00.000000'
AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
)
select count(userid), count(case when order_count > 0 then 1 end)
from summary;
``` | ```sql
WITH ...
SELECT (
SELECT count(users) as foo
FROM cte_1
) foo,
(
SELECT count(order_count) as bar
from cte2
) bar
``` |
72,495,735 | I have the following two common table expressions:
```
WITH cte_1 AS (
SELECT
u.id AS users,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o
ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
),
cte_2 AS (
SELECT
u.id AS users,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o
ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
HAVING COUNT(o.id) > 0
)
```
Notice that both CTEs are exactly the same (with the exception of `HAVING COUNT(o.id) > 0` clause in `cte_2`).
If I independently run the query inside of `cte_1`, I get a value of 200. If I independently run the query inside of `cte_2`, I get a value of 75. I'm trying to run a single query using these CTEs to get the following counts:
```
foo bar
200 75
```
I tried the following (which is syntactically incorrect):
```
WITH cte_1 AS (
SELECT
u.id AS users,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o
ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
),
cte_2 AS (
SELECT
u.id AS users,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o
ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
HAVING COUNT(o.id) > 0
)
SELECT count(users) as foo
FROM cte_1
SELECT count(order_count) as bar
from cte2
```
Any assistance you can give this SQL newbie would be greatly appreciated! Thanks! | 2022/06/03 | [
"https://Stackoverflow.com/questions/72495735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18908491/"
] | ```
WITH
cte as (
SELECT
u.id AS userid,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY
u.id
)
SELECT
count(userid) as foo,
sum(case when order_count > 0 then 1 else 0 end) as bar
FROM
cte
``` | Assuming that you must use these CTEs, and this is not a [XY problem](https://en.wikipedia.org/wiki/XY_problem), you could use a CROSS JOIN to join these results like so:
```
SELECT foo_q.foo, bar_q.bar
FROM
(SELECT count(users) as foo
FROM cte_1) as foo_q
CROSS JOIN
(SELECT count(order_count) as bar
FROM cte_2) as bar_q
``` |
72,495,735 | I have the following two common table expressions:
```
WITH cte_1 AS (
SELECT
u.id AS users,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o
ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
),
cte_2 AS (
SELECT
u.id AS users,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o
ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
HAVING COUNT(o.id) > 0
)
```
Notice that both CTEs are exactly the same (with the exception of `HAVING COUNT(o.id) > 0` clause in `cte_2`).
If I independently run the query inside of `cte_1`, I get a value of 200. If I independently run the query inside of `cte_2`, I get a value of 75. I'm trying to run a single query using these CTEs to get the following counts:
```
foo bar
200 75
```
I tried the following (which is syntactically incorrect):
```
WITH cte_1 AS (
SELECT
u.id AS users,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o
ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
),
cte_2 AS (
SELECT
u.id AS users,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o
ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
HAVING COUNT(o.id) > 0
)
SELECT count(users) as foo
FROM cte_1
SELECT count(order_count) as bar
from cte2
```
Any assistance you can give this SQL newbie would be greatly appreciated! Thanks! | 2022/06/03 | [
"https://Stackoverflow.com/questions/72495735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18908491/"
] | ```
WITH
cte as (
SELECT
u.id AS userid,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY
u.id
)
SELECT
count(userid) as foo,
sum(case when order_count > 0 then 1 else 0 end) as bar
FROM
cte
``` | ```sql
WITH ...
SELECT (
SELECT count(users) as foo
FROM cte_1
) foo,
(
SELECT count(order_count) as bar
from cte2
) bar
``` |
72,495,735 | I have the following two common table expressions:
```
WITH cte_1 AS (
SELECT
u.id AS users,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o
ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
),
cte_2 AS (
SELECT
u.id AS users,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o
ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
HAVING COUNT(o.id) > 0
)
```
Notice that both CTEs are exactly the same (with the exception of `HAVING COUNT(o.id) > 0` clause in `cte_2`).
If I independently run the query inside of `cte_1`, I get a value of 200. If I independently run the query inside of `cte_2`, I get a value of 75. I'm trying to run a single query using these CTEs to get the following counts:
```
foo bar
200 75
```
I tried the following (which is syntactically incorrect):
```
WITH cte_1 AS (
SELECT
u.id AS users,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o
ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
),
cte_2 AS (
SELECT
u.id AS users,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o
ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
HAVING COUNT(o.id) > 0
)
SELECT count(users) as foo
FROM cte_1
SELECT count(order_count) as bar
from cte2
```
Any assistance you can give this SQL newbie would be greatly appreciated! Thanks! | 2022/06/03 | [
"https://Stackoverflow.com/questions/72495735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18908491/"
] | ```
WITH
cte as (
SELECT
u.id AS userid,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY
u.id
)
SELECT
count(userid) as foo,
sum(case when order_count > 0 then 1 else 0 end) as bar
FROM
cte
``` | Both shawnt00 and Kurt have fine answers.
There's another slightly simpler approach to obtain that result.
While it's not a direct response to the question about using those CTE terms, it might be interesting to the new SQL user, and it's standard SQL:
[Test case with PG](https://dbfiddle.uk/?rdbms=postgres_14&fiddle=6a8740dd0b0a93fc9f175f81a81c419c)
```
SELECT COUNT(DISTINCT u.id) AS foo
, COUNT(DISTINCT u.id) FILTER (WHERE o.id IS NOT NULL) AS bar
FROM users u LEFT JOIN orders o ON u.id = o.user_id
WHERE u.created_at BETWEEN '2019-07-01 00:00:00.000000'
AND '2019-09-30 23:59:59.999999'
;
``` |
72,495,735 | I have the following two common table expressions:
```
WITH cte_1 AS (
SELECT
u.id AS users,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o
ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
),
cte_2 AS (
SELECT
u.id AS users,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o
ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
HAVING COUNT(o.id) > 0
)
```
Notice that both CTEs are exactly the same (with the exception of `HAVING COUNT(o.id) > 0` clause in `cte_2`).
If I independently run the query inside of `cte_1`, I get a value of 200. If I independently run the query inside of `cte_2`, I get a value of 75. I'm trying to run a single query using these CTEs to get the following counts:
```
foo bar
200 75
```
I tried the following (which is syntactically incorrect):
```
WITH cte_1 AS (
SELECT
u.id AS users,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o
ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
),
cte_2 AS (
SELECT
u.id AS users,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o
ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
HAVING COUNT(o.id) > 0
)
SELECT count(users) as foo
FROM cte_1
SELECT count(order_count) as bar
from cte2
```
Any assistance you can give this SQL newbie would be greatly appreciated! Thanks! | 2022/06/03 | [
"https://Stackoverflow.com/questions/72495735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18908491/"
] | Both shawnt00 and Kurt have fine answers.
There's another slightly simpler approach to obtain that result.
While it's not a direct response to the question about using those CTE terms, it might be interesting to the new SQL user, and it's standard SQL:
[Test case with PG](https://dbfiddle.uk/?rdbms=postgres_14&fiddle=6a8740dd0b0a93fc9f175f81a81c419c)
```
SELECT COUNT(DISTINCT u.id) AS foo
, COUNT(DISTINCT u.id) FILTER (WHERE o.id IS NOT NULL) AS bar
FROM users u LEFT JOIN orders o ON u.id = o.user_id
WHERE u.created_at BETWEEN '2019-07-01 00:00:00.000000'
AND '2019-09-30 23:59:59.999999'
;
``` | Assuming that you must use these CTEs, and this is not a [XY problem](https://en.wikipedia.org/wiki/XY_problem), you could use a CROSS JOIN to join these results like so:
```
SELECT foo_q.foo, bar_q.bar
FROM
(SELECT count(users) as foo
FROM cte_1) as foo_q
CROSS JOIN
(SELECT count(order_count) as bar
FROM cte_2) as bar_q
``` |
72,495,735 | I have the following two common table expressions:
```
WITH cte_1 AS (
SELECT
u.id AS users,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o
ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
),
cte_2 AS (
SELECT
u.id AS users,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o
ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
HAVING COUNT(o.id) > 0
)
```
Notice that both CTEs are exactly the same (with the exception of `HAVING COUNT(o.id) > 0` clause in `cte_2`).
If I independently run the query inside of `cte_1`, I get a value of 200. If I independently run the query inside of `cte_2`, I get a value of 75. I'm trying to run a single query using these CTEs to get the following counts:
```
foo bar
200 75
```
I tried the following (which is syntactically incorrect):
```
WITH cte_1 AS (
SELECT
u.id AS users,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o
ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
),
cte_2 AS (
SELECT
u.id AS users,
count(o.id) AS order_count
FROM
users u
LEFT JOIN
orders o
ON u.id = o.user_id
WHERE
u.created_at BETWEEN '2019-07-01 00:00:00.000000' AND '2019-09-30 23:59:59.999999'
GROUP BY u.id
HAVING COUNT(o.id) > 0
)
SELECT count(users) as foo
FROM cte_1
SELECT count(order_count) as bar
from cte2
```
Any assistance you can give this SQL newbie would be greatly appreciated! Thanks! | 2022/06/03 | [
"https://Stackoverflow.com/questions/72495735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18908491/"
] | Both shawnt00 and Kurt have fine answers.
There's another slightly simpler approach to obtain that result.
While it's not a direct response to the question about using those CTE terms, it might be interesting to the new SQL user, and it's standard SQL:
[Test case with PG](https://dbfiddle.uk/?rdbms=postgres_14&fiddle=6a8740dd0b0a93fc9f175f81a81c419c)
```
SELECT COUNT(DISTINCT u.id) AS foo
, COUNT(DISTINCT u.id) FILTER (WHERE o.id IS NOT NULL) AS bar
FROM users u LEFT JOIN orders o ON u.id = o.user_id
WHERE u.created_at BETWEEN '2019-07-01 00:00:00.000000'
AND '2019-09-30 23:59:59.999999'
;
``` | ```sql
WITH ...
SELECT (
SELECT count(users) as foo
FROM cte_1
) foo,
(
SELECT count(order_count) as bar
from cte2
) bar
``` |
2,592,292 | Let's say I have a standalone windows service running in a windows server machine. How to make sure it is highly available?
1). What are all the design level guidelines that you can propose?
2). How to make it highly available like primary/secondary, eg., the clustering solutions currently available in the market
3). How to deal with cross-cutting concerns in case any fail-over scenarios
If any other you can think of please add it here ..
**Note:**
The question is only related to windows and windows services, please try to obey this rule :) | 2010/04/07 | [
"https://Stackoverflow.com/questions/2592292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/125904/"
] | To keep the service at least running you can arrange for the Windows Service Manager to automatically restart the service if it crashes (see the Recovery tab on the service properties.) More details are available here, including a batch script to set these properties - [Restart a windows service if it crashes](https://serverfault.com/questions/48600/how-can-i-automatically-restart-a-windows-service-if-it-crashes)
High availability is more than just keeping the service up from the outside - the service itself needs to be built with high-availabiity in mind (i.e. use good programming practices throughout, appropriate datastructures, pairs resource aquire and release), and the whole stress-tested to ensure that it will stay up under expected loads.
For idempotent commands, tolerating intermittent failures (such as locked resources) can be achieved by re-invoking the command a certain number of times. This allows the service to shield the client from the failure (up to a point.) The client should also be coded to anticipate failure. The client can handle service failure in several ways - logging, prompting the user, retrying X times, logging a fatal error and exiting are all possible handlers - which one is right for you depends upon your requirements. If the service has "conversation state", when service fails hard (i.e. process is restarted), the client should be aware of and handle ths situation, as it usually means current conversation state has been lost.
A single machine is going to be vulnerable to hardware failure, so if you are going to use a single machine, then ensure it has redundant components. HDDs are particularly prone to failure, so have at least mirrored drives, or a RAID array. PSUs are the next weak point, so redundant PSU is also worthwhile, as is a UPS.
As to clustering, Windows supports service clustering, and manages services using a Network Name, rather than individual Computer names. This allows your client to connect to any machine running the service and not a hard-coded name. But unless you take additional measures, this is Resource failover - directing requests from one instance of the service to another. Converstaion state is usually lost. If your services are writing to a database, then that should also be clustered to also ensure reliabiity and ensure changes are available to the entire cluster, and not just the local node.
This is really just the tip of the iceberg, but I hope it gives you ideas to get started on further research.
[Microsoft Clustering Service (MSCS)](http://msdn.microsoft.com/en-us/library/ms952401.aspx) | If you break down the problems you are trying to solve, I think you'll probably come up with a few answers yourself. As Justin mentioned in the comment, there is no one answer. It completely depends on what your service does and how clients use it. You also don't specify any details about the client-server interactivity. HTTP? TCP? UDP? Other?
Here are some things to think about to get you started.
1) What do you do if the service or server goes down?
* How about run more than one instance of your service on separate servers?
2) Ok, but now how do the clients know about the multiple services?
* You can hard code the list into each client(not recommended)
* You can use DNS round-robin to bounce requests across all of them.
* You can use a load-balancing device.
* You can have a separate service that knows about all of the other services and can direct clients to available services.
3) So what if one service goes down?
* Do the client applications know what to do if the service they are connected to goes down? If not, then they need to be updated to handle that situation.
That should get you started with the basic idea of how to get started with high-availability. If you provide specific details about your architecture, you will probably get a much better response. |
2,592,292 | Let's say I have a standalone windows service running in a windows server machine. How to make sure it is highly available?
1). What are all the design level guidelines that you can propose?
2). How to make it highly available like primary/secondary, eg., the clustering solutions currently available in the market
3). How to deal with cross-cutting concerns in case any fail-over scenarios
If any other you can think of please add it here ..
**Note:**
The question is only related to windows and windows services, please try to obey this rule :) | 2010/04/07 | [
"https://Stackoverflow.com/questions/2592292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/125904/"
] | To keep the service at least running you can arrange for the Windows Service Manager to automatically restart the service if it crashes (see the Recovery tab on the service properties.) More details are available here, including a batch script to set these properties - [Restart a windows service if it crashes](https://serverfault.com/questions/48600/how-can-i-automatically-restart-a-windows-service-if-it-crashes)
High availability is more than just keeping the service up from the outside - the service itself needs to be built with high-availabiity in mind (i.e. use good programming practices throughout, appropriate datastructures, pairs resource aquire and release), and the whole stress-tested to ensure that it will stay up under expected loads.
For idempotent commands, tolerating intermittent failures (such as locked resources) can be achieved by re-invoking the command a certain number of times. This allows the service to shield the client from the failure (up to a point.) The client should also be coded to anticipate failure. The client can handle service failure in several ways - logging, prompting the user, retrying X times, logging a fatal error and exiting are all possible handlers - which one is right for you depends upon your requirements. If the service has "conversation state", when service fails hard (i.e. process is restarted), the client should be aware of and handle ths situation, as it usually means current conversation state has been lost.
A single machine is going to be vulnerable to hardware failure, so if you are going to use a single machine, then ensure it has redundant components. HDDs are particularly prone to failure, so have at least mirrored drives, or a RAID array. PSUs are the next weak point, so redundant PSU is also worthwhile, as is a UPS.
As to clustering, Windows supports service clustering, and manages services using a Network Name, rather than individual Computer names. This allows your client to connect to any machine running the service and not a hard-coded name. But unless you take additional measures, this is Resource failover - directing requests from one instance of the service to another. Converstaion state is usually lost. If your services are writing to a database, then that should also be clustered to also ensure reliabiity and ensure changes are available to the entire cluster, and not just the local node.
This is really just the tip of the iceberg, but I hope it gives you ideas to get started on further research.
[Microsoft Clustering Service (MSCS)](http://msdn.microsoft.com/en-us/library/ms952401.aspx) | If the service doesn’t expose any interface for client connectivity you could:
* Broadcast or expose an “I’m alive” message or signal a database/registry/tcp/whatever that you are alive
* Have a second service (monitor) that checks for these “I’m alive” signals and try to restart the service in case it is down
But if you have a client connecting to this service through namedpipes/tcp/etc, the client would have to check the address of the machine with the service running in a database, or have something fancier like an intelligent switch to redirect traffic. |
4,648,533 | I am using a jQuery UI Tabs widget that exists within an iframe on the page. From the parent document, I need to be able to access the tabs object and use its methods (the 'select' method in particular). I am using the following code currently:
```
var iframe = $('#mainFrame').contents().get(0);
$('#tabs', iframe).tabs('select', 1);
```
The code does not throw any errors/warnings in the console and the jquery object for $('#tabs', iframe) does seem to be selecting the correct elements from the DOM of the iframe, however nothing happens when this is executed. | 2011/01/10 | [
"https://Stackoverflow.com/questions/4648533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192694/"
] | You're turning the jQuery object reference into a `DOM node` by calling `.get(0)`. Try instead:
```
var iframe = $('#mainFrame').contents();
iframe.find('#tabs').tabs('select', 1);
```
ref.: [.find()](http://api.jquery.com/find/) | You could try (untested):
```
$('#mainFrame').contents().find('#tabs').tabs('select', 1);
``` |
2,943,502 | The system in question is:
$$
x' = y\\
y' = \mu x+x^2
$$
This has a fixed point at $x=0,-\mu$ and $y=0$ and after computing the Jacobian I find eigenvalues of
$$
\lambda = \pm \sqrt{\mu}
$$
for the $x=0 ,y=0$ solution. This is a saddle point for $\mu>0$ but becomes completely imaginary for $\mu<0.$ I am not sure how to determine the stability for $\mu<0$ | 2018/10/05 | [
"https://math.stackexchange.com/questions/2943502",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/146286/"
] | You cannot conclude anything about the stability of a fixed point through linearization whenever the Jacobian has at least one purely imaginary eigenvalue.
However, what you can do, is to express the system as a second-order system by letting $\ddot{x} = \dot{y}$:
$$\ddot{x}-\mu x - x^2 = 0$$
We can interpret this system as a generalized harmonic oscillator with an amended potential. To see this, recall that the equation for a harmonic oscillator is $\ddot{x}+x=0$, where the spring constant is 1 and the potential is given by $\int\_0^x y \ dy = x^2/2$. So in our case, we have a negative spring constant when $\mu>0$ and a negative spring constant when $\mu<0$. The potential in our case is given by:
$$\int\_0^x (-\mu y -y^2) \ dy = -\mu x^2/2 - x^3/3$$
Furthermore, you can have more fun by writing down the Hamiltonian for your system:
$$H = T + V = \dot{x}^2/2 - \mu x - x^2 = p^2/2 - \mu x - x^2$$
So now you can draw the potential and use it to sketch the phase portrait of your system, from which you can infer the stability of the equilibrium points.
Here is an example of what this looks like for a different system with a different potential:
[](https://i.stack.imgur.com/1czIw.png)
So basically, for your system, you can look at the potential and say that the quadratic term dominates over the cubic when $x$ is close to 0, which means that for $\mu<0$ the potential will have a valley at $x=0$ and, therefore, solutions that start around it on a sufficiently low energy level, will get trapped (i.e., the equilibrium point $x=0,y=0$ is a center).
Hope this helps! | Note that this system has the symmetry ($x \to x, y \to -y, t \to -t$). Thus a trajectory that starts out on the $x$ axis and returns to the $x$ axis is reflected across that axis to make a closed loop.
The fixed point is a centre: stable but not asymptotically stable. |
29,600,941 | I want to add data in drop down list,I am able to add the data and view it but for that i have to refresh the page again, I want to do that in jQuery without refreshing the page. | 2015/04/13 | [
"https://Stackoverflow.com/questions/29600941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4781955/"
] | The problem is
* Caused by: java.lang.UnsupportedOperationException: Can't convert to color: type=0x2 at android.content.res.TypedArray.getColor(TypedArray.java:326)
The code or id of the color is invalid. | I actually get it! The problem was with the custom theme i was trying to use. I think the main reason for that error came from trying to extend Material Light and that was incompatible with android version on my phone! :)
If someone can confirm that i'll be gratefull! |
16,108,745 | I have Radmenu placed in master page and if I click any item ,page will get post back so its difficult to maintain item selected focused with the color.I tried placing an ajaxpanel,still its getting post backed.
```
<telerik:RadAjaxPanel ID="RadAjaxPanel1" runat="server">
<telerik:RadMenu ID="Menu1" runat="server" Skin="Office2010Silver"
Width="100%" Font-Bold="true"
Visible ="false">
<Items>
< <telerik:RadMenuItem runat="server" NavigateUrl="~/Home.aspx" Text="Home">
</telerik:RadMenuItem>
</Items>
</telerik:RadMenu>
```
Any suggestions will be of great help.
Thanks | 2013/04/19 | [
"https://Stackoverflow.com/questions/16108745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1046415/"
] | If you create a new windows forms application for C# in Visual Studio it will get you working with a single form, and then you can add more forms in your main form. As a bonus, you will get a designer for your main form where you can drag and drop controls. | Hope your `Program.cs` looks like:
```
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
```
and try this inside `Form1`:
```
private void Form1_Load(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.Show();
}
``` |
16,108,745 | I have Radmenu placed in master page and if I click any item ,page will get post back so its difficult to maintain item selected focused with the color.I tried placing an ajaxpanel,still its getting post backed.
```
<telerik:RadAjaxPanel ID="RadAjaxPanel1" runat="server">
<telerik:RadMenu ID="Menu1" runat="server" Skin="Office2010Silver"
Width="100%" Font-Bold="true"
Visible ="false">
<Items>
< <telerik:RadMenuItem runat="server" NavigateUrl="~/Home.aspx" Text="Home">
</telerik:RadMenuItem>
</Items>
</telerik:RadMenu>
```
Any suggestions will be of great help.
Thanks | 2013/04/19 | [
"https://Stackoverflow.com/questions/16108745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1046415/"
] | You can create a new `ApplicationContext` to represent multiple forms:
```
public class MultiFormContext : ApplicationContext
{
private int openForms;
public MultiFormContext(params Form[] forms)
{
openForms = forms.Length;
foreach (var form in forms)
{
form.FormClosed += (s, args) =>
{
//When we have closed the last of the "starting" forms,
//end the program.
if (Interlocked.Decrement(ref openForms) == 0)
ExitThread();
};
form.Show();
}
}
}
```
Using that you can now write:
```
Application.Run(new MultiFormContext(new Form1(), new Form2()));
``` | Hope your `Program.cs` looks like:
```
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
```
and try this inside `Form1`:
```
private void Form1_Load(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.Show();
}
``` |
16,108,745 | I have Radmenu placed in master page and if I click any item ,page will get post back so its difficult to maintain item selected focused with the color.I tried placing an ajaxpanel,still its getting post backed.
```
<telerik:RadAjaxPanel ID="RadAjaxPanel1" runat="server">
<telerik:RadMenu ID="Menu1" runat="server" Skin="Office2010Silver"
Width="100%" Font-Bold="true"
Visible ="false">
<Items>
< <telerik:RadMenuItem runat="server" NavigateUrl="~/Home.aspx" Text="Home">
</telerik:RadMenuItem>
</Items>
</telerik:RadMenu>
```
Any suggestions will be of great help.
Thanks | 2013/04/19 | [
"https://Stackoverflow.com/questions/16108745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1046415/"
] | You can create a new `ApplicationContext` to represent multiple forms:
```
public class MultiFormContext : ApplicationContext
{
private int openForms;
public MultiFormContext(params Form[] forms)
{
openForms = forms.Length;
foreach (var form in forms)
{
form.FormClosed += (s, args) =>
{
//When we have closed the last of the "starting" forms,
//end the program.
if (Interlocked.Decrement(ref openForms) == 0)
ExitThread();
};
form.Show();
}
}
}
```
Using that you can now write:
```
Application.Run(new MultiFormContext(new Form1(), new Form2()));
``` | If you create a new windows forms application for C# in Visual Studio it will get you working with a single form, and then you can add more forms in your main form. As a bonus, you will get a designer for your main form where you can drag and drop controls. |
55,859,542 | ```
var state = Vue.observable({
selectedTab: ''
});
Vue.component('block-ui-tab', {
props: ['name', 'handle', 'icon'],
template: '<li :handle="handle" :class="{ active: state.selectedTab === handle }"><i :class="icon"></i>{{ name }}</li>'
});
var app = new Vue({
el: '#app',
data: {},
methods: {},
computed: {},
watch:{},
mounted: function(){},
});
```
This doesn't work, so I'm wondering how to use the observable in the component and the vue root instance? Pass it as a prop, or? | 2019/04/26 | [
"https://Stackoverflow.com/questions/55859542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172637/"
] | First, I think you can use any serializer to convert your objects to the format you want.
```
var serialized = JsonConvert.SerializeObject(data)
```
Second, back to your question, here is the code. However, you need to add " around your variables and get rid of string concatenation I added for readability. Also, this code is so specific to your problem and for more generic solution go for the first approach.
```
var mainData = string.Join(',', data.Select(x => $" {{ {nameof(x.Id)} : {x.Id}, " +
$"{nameof(User)}s: " +
$"[ {string.Join(',', x.Users.Select(y => $"{{ {nameof(User.T_Id)} : {y.T_Id} }}"))}]" +
$"}}"));
var result = $"[{mainData}]" ;
```
As you changed the question, I updated my answer. So, you need to first join someView and user to get them together and then group by someView.id. Here is the code
```
var someViewsUsersJoin = someViews.Join(users, l => l.t_id, r => r.t_id, (someView, user) => new {someView, user});
var result = someViewsUsersJoin.GroupBy(x => x.someView.id).Select(x => new SomeViewModel()
{
Id = x.Key,
Users = x.Select(y => y.user).ToList()
});
``` | Finally Resolved it this way -
```
public class SomeView
{
public int Id {get; private set;}
public int T_Id { get; private set; }
}
public class User
{
public int T_Id { get; set; }
public string fname {get; set;}
public string lname{get; set;}
}
public class SomeViewModel
{
public int Id { get; set; }
public List<User> Users{get; set;}
}
from t in SomeView
join u in User on v.T_Id equals u.T_Id
group new {t, u} by t.Id into grp
select new SomeViewModel{
Id = grp.Key,
Users = grp.Select(x => x.u).ToList()
}
```
That was easy :) |
25,772 | A stranger walks up to you on the street. They say they lost their phone and need to make a phone call (has happened to me twice, and maybe to you). What's the worst a phone call could do?
Let's assume they don't run, don't plug any devices into the phone, they just dial a number and do whatever, and hang up. | 2012/12/21 | [
"https://security.stackexchange.com/questions/25772",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/17662/"
] | A few scams I've seen making the rounds:
* Use it to dial a premium rate number owned by the group. In the UK, 09xx numbers can cost up to £1.50 per minute, and most 09xx providers charge around 33%, so a five minute call syphons £5 into the group's hands. If you're a good social engineer, you might only have a 10 minute gap between calls as you wander around a busy high-street, so that's £15 an hour (tax free!) - almost triple minimum wage.
* Use it to send premium rate texts. The regulations on there are tighter, but if you can get a premium rate SMS number set up, you can charge up to £10 per text. A scammer would typically see between £5 and £7 of that, after the provider takes a cut. It's also possible to set up a recurring cost, where the provider sends you messages every day and charges you up to £2.50 for each one. By law the service provider must automatically cancel it if they send a text sayin STOP, but every extra message you send gains you money.
* Set up an app in the app store, then buy it on peoples' phones. This can be very expensive for the victim, since apps can be priced very high - some up to £80. In-app purchases also work. This is precisely why you should be prompted for your password on *every* app purchase and in-app purchase, but not all phones do so!
* Install a malicious app, such as the mobile Zeus trojan. This can then be used to steal banking credentials and email accounts. This seems to be gaining popularity on Android phones. | Some mobile networks in the world allow users to transfer prepaid balances from one account to another. Alternatively, they might send some sort of incriminating SMS from your phone which may cause you issues with law enforcement officer. |
25,772 | A stranger walks up to you on the street. They say they lost their phone and need to make a phone call (has happened to me twice, and maybe to you). What's the worst a phone call could do?
Let's assume they don't run, don't plug any devices into the phone, they just dial a number and do whatever, and hang up. | 2012/12/21 | [
"https://security.stackexchange.com/questions/25772",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/17662/"
] | They could use it to send the detonation signal to that nuclear weapon they've secreted in a warehouse in Manhattan. That's pretty much the worst-case scenario. | While detonating a bomb or EMP would be the most harmful, I think the following scenarios are much more likely to happen.
If you have a smartphone, it's very likely you have some kind of weather widget on the homescreen which tells the attacker what is your hometown.
Also, I yet have to see a smartphone without news widget, which again, tells the attacker what kind of person you are. Are you following a finance news? Sport? IT? The very same thing can be done by just looking at your installed apps. Do you have any games? Which ones? Do you have any kind of booking apps? Does this kind of app keeps any sort of history? Well, in short, within just few second attacker can make pretty reliable profile of you.
Do you have anykind of notebook app? What have you written in it?
The second threat is... Well, most likely you just gave him full access to all of your e-mail accounts and with a few presses on the screen, he could forward all of your mails to his account.
The last thing which I can remember are pranks. While this doesn't sound like anything danger, it can be really unpleasantly. The attacker could send to a random contact of opposite sex SMS - "Hey, I'm thinking about you...". Just imagine if this random contact is your wife's friend (now, the scenario of detonating nuclear weapon is not so scary, isn't it?). Or even more explicit message to a contact saved as your family member (e.g. Mother).
He could also update your Facebook status, leave a message on a Twitter or upload some of your private photos to a public service. |
25,772 | A stranger walks up to you on the street. They say they lost their phone and need to make a phone call (has happened to me twice, and maybe to you). What's the worst a phone call could do?
Let's assume they don't run, don't plug any devices into the phone, they just dial a number and do whatever, and hang up. | 2012/12/21 | [
"https://security.stackexchange.com/questions/25772",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/17662/"
] | They could use it to send the detonation signal to that nuclear weapon they've secreted in a warehouse in Manhattan. That's pretty much the worst-case scenario. | Rule 3: [If a bad guy has unrestricted physical access to your computer, it's not your computer anymore.](http://technet.microsoft.com/library/cc722487.aspx#EIAA) |
25,772 | A stranger walks up to you on the street. They say they lost their phone and need to make a phone call (has happened to me twice, and maybe to you). What's the worst a phone call could do?
Let's assume they don't run, don't plug any devices into the phone, they just dial a number and do whatever, and hang up. | 2012/12/21 | [
"https://security.stackexchange.com/questions/25772",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/17662/"
] | with a USB rubber on android the pin password could be hacked (brute forced)
<http://hakshop.myshopify.com/products/usb-rubber-ducky>
they could then create a backup of your device, they could analyse already created backups, they could download all of your saved data, media etc and use this to further penetrate other areas of interest.
<https://santoku-linux.com>
they could run the phone through a smartphone pentest framework, and infect it for botnet purposes.
<http://georgiaweidman.com/wordpress/>
they could hawk it for cash
<http://www.cashamerica.com/>
**on a side note, if your lucky they could;**
1. correct any duplicate contacts you have
2. organize your mobile media
3. finishing posting your facebook post you left open
4. beat that hard level on Angry birds for you
5. Call your most called numbers to return your phone
6. Call the carrier to report it lost/stolen
7. etc | With some phones it is possible to call system commands or even to lock the SIM card, just by visiting a prepared website. There was an article some time ago on [Heise security](http://www.h-online.com/security/news/item/Android-smartphones-USSD-calls-can-kill-SIM-cards-1719230.html) about this problem. |
25,772 | A stranger walks up to you on the street. They say they lost their phone and need to make a phone call (has happened to me twice, and maybe to you). What's the worst a phone call could do?
Let's assume they don't run, don't plug any devices into the phone, they just dial a number and do whatever, and hang up. | 2012/12/21 | [
"https://security.stackexchange.com/questions/25772",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/17662/"
] | They could use it to send the detonation signal to that nuclear weapon they've secreted in a warehouse in Manhattan. That's pretty much the worst-case scenario. | With some phones it is possible to call system commands or even to lock the SIM card, just by visiting a prepared website. There was an article some time ago on [Heise security](http://www.h-online.com/security/news/item/Android-smartphones-USSD-calls-can-kill-SIM-cards-1719230.html) about this problem. |
25,772 | A stranger walks up to you on the street. They say they lost their phone and need to make a phone call (has happened to me twice, and maybe to you). What's the worst a phone call could do?
Let's assume they don't run, don't plug any devices into the phone, they just dial a number and do whatever, and hang up. | 2012/12/21 | [
"https://security.stackexchange.com/questions/25772",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/17662/"
] | While detonating a bomb or EMP would be the most harmful, I think the following scenarios are much more likely to happen.
If you have a smartphone, it's very likely you have some kind of weather widget on the homescreen which tells the attacker what is your hometown.
Also, I yet have to see a smartphone without news widget, which again, tells the attacker what kind of person you are. Are you following a finance news? Sport? IT? The very same thing can be done by just looking at your installed apps. Do you have any games? Which ones? Do you have any kind of booking apps? Does this kind of app keeps any sort of history? Well, in short, within just few second attacker can make pretty reliable profile of you.
Do you have anykind of notebook app? What have you written in it?
The second threat is... Well, most likely you just gave him full access to all of your e-mail accounts and with a few presses on the screen, he could forward all of your mails to his account.
The last thing which I can remember are pranks. While this doesn't sound like anything danger, it can be really unpleasantly. The attacker could send to a random contact of opposite sex SMS - "Hey, I'm thinking about you...". Just imagine if this random contact is your wife's friend (now, the scenario of detonating nuclear weapon is not so scary, isn't it?). Or even more explicit message to a contact saved as your family member (e.g. Mother).
He could also update your Facebook status, leave a message on a Twitter or upload some of your private photos to a public service. | Did not see these: adding another sync account, forwarding your calls, automated pin code retrieval (boostmobile), calling drug dealers, making threats over your phone. |
25,772 | A stranger walks up to you on the street. They say they lost their phone and need to make a phone call (has happened to me twice, and maybe to you). What's the worst a phone call could do?
Let's assume they don't run, don't plug any devices into the phone, they just dial a number and do whatever, and hang up. | 2012/12/21 | [
"https://security.stackexchange.com/questions/25772",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/17662/"
] | They could dial their own number to get yours (assuming your number isn't private.)
I think I just invented a new, somewhat forceful and creepy, pick-up move. | They could dial a [USSD](http://en.wikipedia.org/wiki/Unstructured_Supplementary_Service_Data) to get supplimental information about you or your device. Some UUSD codes have been documented to have the capability of doing a factory reset on your phone. [Source](http://www.engadget.com/2012/09/25/dirty-ussd-code-samsung-hack-wipe/) |
25,772 | A stranger walks up to you on the street. They say they lost their phone and need to make a phone call (has happened to me twice, and maybe to you). What's the worst a phone call could do?
Let's assume they don't run, don't plug any devices into the phone, they just dial a number and do whatever, and hang up. | 2012/12/21 | [
"https://security.stackexchange.com/questions/25772",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/17662/"
] | While detonating a bomb or EMP would be the most harmful, I think the following scenarios are much more likely to happen.
If you have a smartphone, it's very likely you have some kind of weather widget on the homescreen which tells the attacker what is your hometown.
Also, I yet have to see a smartphone without news widget, which again, tells the attacker what kind of person you are. Are you following a finance news? Sport? IT? The very same thing can be done by just looking at your installed apps. Do you have any games? Which ones? Do you have any kind of booking apps? Does this kind of app keeps any sort of history? Well, in short, within just few second attacker can make pretty reliable profile of you.
Do you have anykind of notebook app? What have you written in it?
The second threat is... Well, most likely you just gave him full access to all of your e-mail accounts and with a few presses on the screen, he could forward all of your mails to his account.
The last thing which I can remember are pranks. While this doesn't sound like anything danger, it can be really unpleasantly. The attacker could send to a random contact of opposite sex SMS - "Hey, I'm thinking about you...". Just imagine if this random contact is your wife's friend (now, the scenario of detonating nuclear weapon is not so scary, isn't it?). Or even more explicit message to a contact saved as your family member (e.g. Mother).
He could also update your Facebook status, leave a message on a Twitter or upload some of your private photos to a public service. | Rule 3: [If a bad guy has unrestricted physical access to your computer, it's not your computer anymore.](http://technet.microsoft.com/library/cc722487.aspx#EIAA) |
25,772 | A stranger walks up to you on the street. They say they lost their phone and need to make a phone call (has happened to me twice, and maybe to you). What's the worst a phone call could do?
Let's assume they don't run, don't plug any devices into the phone, they just dial a number and do whatever, and hang up. | 2012/12/21 | [
"https://security.stackexchange.com/questions/25772",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/17662/"
] | A few scams I've seen making the rounds:
* Use it to dial a premium rate number owned by the group. In the UK, 09xx numbers can cost up to £1.50 per minute, and most 09xx providers charge around 33%, so a five minute call syphons £5 into the group's hands. If you're a good social engineer, you might only have a 10 minute gap between calls as you wander around a busy high-street, so that's £15 an hour (tax free!) - almost triple minimum wage.
* Use it to send premium rate texts. The regulations on there are tighter, but if you can get a premium rate SMS number set up, you can charge up to £10 per text. A scammer would typically see between £5 and £7 of that, after the provider takes a cut. It's also possible to set up a recurring cost, where the provider sends you messages every day and charges you up to £2.50 for each one. By law the service provider must automatically cancel it if they send a text sayin STOP, but every extra message you send gains you money.
* Set up an app in the app store, then buy it on peoples' phones. This can be very expensive for the victim, since apps can be priced very high - some up to £80. In-app purchases also work. This is precisely why you should be prompted for your password on *every* app purchase and in-app purchase, but not all phones do so!
* Install a malicious app, such as the mobile Zeus trojan. This can then be used to steal banking credentials and email accounts. This seems to be gaining popularity on Android phones. | With some phones it is possible to call system commands or even to lock the SIM card, just by visiting a prepared website. There was an article some time ago on [Heise security](http://www.h-online.com/security/news/item/Android-smartphones-USSD-calls-can-kill-SIM-cards-1719230.html) about this problem. |
25,772 | A stranger walks up to you on the street. They say they lost their phone and need to make a phone call (has happened to me twice, and maybe to you). What's the worst a phone call could do?
Let's assume they don't run, don't plug any devices into the phone, they just dial a number and do whatever, and hang up. | 2012/12/21 | [
"https://security.stackexchange.com/questions/25772",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/17662/"
] | They could dial their own number to get yours (assuming your number isn't private.)
I think I just invented a new, somewhat forceful and creepy, pick-up move. | While detonating a bomb or EMP would be the most harmful, I think the following scenarios are much more likely to happen.
If you have a smartphone, it's very likely you have some kind of weather widget on the homescreen which tells the attacker what is your hometown.
Also, I yet have to see a smartphone without news widget, which again, tells the attacker what kind of person you are. Are you following a finance news? Sport? IT? The very same thing can be done by just looking at your installed apps. Do you have any games? Which ones? Do you have any kind of booking apps? Does this kind of app keeps any sort of history? Well, in short, within just few second attacker can make pretty reliable profile of you.
Do you have anykind of notebook app? What have you written in it?
The second threat is... Well, most likely you just gave him full access to all of your e-mail accounts and with a few presses on the screen, he could forward all of your mails to his account.
The last thing which I can remember are pranks. While this doesn't sound like anything danger, it can be really unpleasantly. The attacker could send to a random contact of opposite sex SMS - "Hey, I'm thinking about you...". Just imagine if this random contact is your wife's friend (now, the scenario of detonating nuclear weapon is not so scary, isn't it?). Or even more explicit message to a contact saved as your family member (e.g. Mother).
He could also update your Facebook status, leave a message on a Twitter or upload some of your private photos to a public service. |
6,659,360 | I connected with VPN to setup the inventory API to get product list and it works fine. Once I get the result from the web-service and i bind to UI. And also I integrated PayPal with my application for make Express checkout when I make a call for payment I'm facing this error. I use servlet for back-end process. Can any one say how to fix this issue?
```
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException:
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException:
unable to find valid certification path to requested target
``` | 2011/07/12 | [
"https://Stackoverflow.com/questions/6659360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/504130/"
] | First, you need to obtain the public certificate from the server you're trying to connect to. That can be done in a variety of ways, such as contacting the server admin and asking for it, [using OpenSSL to download it](http://www.madboa.com/geek/openssl/#cert-retrieve), or, since this appears to be an HTTP server, connecting to it with any browser, viewing the page's security info, and saving a copy of the certificate. (Google should be able to tell you exactly what to do for your specific browser.)
Now that you have the certificate saved in a file, you need to add it to your JVM's trust store. At `$JAVA_HOME/jre/lib/security/` for JREs or `$JAVA_HOME/lib/security` for JDKs, there's a file named `cacerts`, which comes with Java and contains the public certificates of the well-known Certifying Authorities. To import the new cert, run keytool as a user who has permission to write to cacerts:
```
keytool -import -file <the cert file> -alias <some meaningful name> -keystore <path to cacerts file>
```
It will most likely ask you for a password. The default password as shipped with Java is `changeit`. Almost nobody changes it. After you complete these relatively simple steps, you'll be communicating securely and with the assurance that you're talking to the right server and only the right server (as long as they don't lose their private key). | I believe that you are trying to connect to a something using SSL but that something is providing a certificate which is not verified by root certification authorities such as verisign.. In essence by default secure connections can only be established if the person trying to connect knows the counterparties keys or some other verndor such as verisign can step in and say that the public key being provided is indeed right..
ALL OS's trust a handful of certification authorities and smaller certificate issuers need to be certified by one of the large certifiers making a chain of certifiers if you get what I mean...
Anyways coming back to the point.. I had a similiar problem when programming a java applet and a java server ( Hopefully some day I will write a complete blogpost about how I got all the security to work :) )
In essence what I had to do was to extract the public keys from the server and store it in a keystore inside my applet and when I connected to the server I used this key store to create a trust factory and that trust factory to create the ssl connection. There are alterante procedures as well such as adding the key to the JVM's trusted host and modifying the default trust store on start up..
I did this around two months back and dont have source code on me right now.. use google and you should be able to solve this problem. If you cant message me back and I can provide you the relevent source code for the project .. Dont know if this solves your problem since you havent provided the code which causes these exceptions. Furthermore I was working wiht applets thought I cant see why it wont work on Serverlets...
P.S I cant get source code before the weekend since external SSH is disabled in my office :( |
6,659,360 | I connected with VPN to setup the inventory API to get product list and it works fine. Once I get the result from the web-service and i bind to UI. And also I integrated PayPal with my application for make Express checkout when I make a call for payment I'm facing this error. I use servlet for back-end process. Can any one say how to fix this issue?
```
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException:
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException:
unable to find valid certification path to requested target
``` | 2011/07/12 | [
"https://Stackoverflow.com/questions/6659360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/504130/"
] | Whenever we are trying to connect to URL,
if server at the other site is running on https protocol and is mandating that we should communicate via information provided in certificate then
we have following option:
1) ask for the certificate(download the certificate), import this certificate in trustore. Default trustore java uses can be found in \Java\jdk1.6.0\_29\jre\lib\security\cacerts, then if we retry to connect to the URL connection would be accepted.
2) In normal business cases, we might be connecting to internal URLS in organizations and we know that they are correct.
In such cases, you trust that it is the correct URL, In such cases above, code can be used which will not mandate to store the certificate to connect to particular URL.
**for the point no 2 we have to follow below steps :**
1) write below method which sets HostnameVerifier for HttpsURLConnection which returns true for all cases meaning we are trusting the trustStore.
```
// trusting all certificate
public void doTrustToCertificates() throws Exception {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
return;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
return;
}
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
if (!urlHostName.equalsIgnoreCase(session.getPeerHost())) {
System.out.println("Warning: URL host '" + urlHostName + "' is different to SSLSession host '" + session.getPeerHost() + "'.");
}
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(hv);
}
```
2) write below method, which calls doTrustToCertificates before trying to connect to URL
```
// connecting to URL
public void connectToUrl(){
doTrustToCertificates();//
URL url = new URL("https://www.example.com");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
System.out.println("ResponseCode ="+conn.getResponseCode());
}
```
This call will return response code = 200 means connection is successful.
For more detail and sample example you can refer to [URL](http://blog.hexican.com/2010/12/sending-soap-messages-through-https-using-saaj/). | I believe that you are trying to connect to a something using SSL but that something is providing a certificate which is not verified by root certification authorities such as verisign.. In essence by default secure connections can only be established if the person trying to connect knows the counterparties keys or some other verndor such as verisign can step in and say that the public key being provided is indeed right..
ALL OS's trust a handful of certification authorities and smaller certificate issuers need to be certified by one of the large certifiers making a chain of certifiers if you get what I mean...
Anyways coming back to the point.. I had a similiar problem when programming a java applet and a java server ( Hopefully some day I will write a complete blogpost about how I got all the security to work :) )
In essence what I had to do was to extract the public keys from the server and store it in a keystore inside my applet and when I connected to the server I used this key store to create a trust factory and that trust factory to create the ssl connection. There are alterante procedures as well such as adding the key to the JVM's trusted host and modifying the default trust store on start up..
I did this around two months back and dont have source code on me right now.. use google and you should be able to solve this problem. If you cant message me back and I can provide you the relevent source code for the project .. Dont know if this solves your problem since you havent provided the code which causes these exceptions. Furthermore I was working wiht applets thought I cant see why it wont work on Serverlets...
P.S I cant get source code before the weekend since external SSH is disabled in my office :( |
6,659,360 | I connected with VPN to setup the inventory API to get product list and it works fine. Once I get the result from the web-service and i bind to UI. And also I integrated PayPal with my application for make Express checkout when I make a call for payment I'm facing this error. I use servlet for back-end process. Can any one say how to fix this issue?
```
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException:
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException:
unable to find valid certification path to requested target
``` | 2011/07/12 | [
"https://Stackoverflow.com/questions/6659360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/504130/"
] | First, you need to obtain the public certificate from the server you're trying to connect to. That can be done in a variety of ways, such as contacting the server admin and asking for it, [using OpenSSL to download it](http://www.madboa.com/geek/openssl/#cert-retrieve), or, since this appears to be an HTTP server, connecting to it with any browser, viewing the page's security info, and saving a copy of the certificate. (Google should be able to tell you exactly what to do for your specific browser.)
Now that you have the certificate saved in a file, you need to add it to your JVM's trust store. At `$JAVA_HOME/jre/lib/security/` for JREs or `$JAVA_HOME/lib/security` for JDKs, there's a file named `cacerts`, which comes with Java and contains the public certificates of the well-known Certifying Authorities. To import the new cert, run keytool as a user who has permission to write to cacerts:
```
keytool -import -file <the cert file> -alias <some meaningful name> -keystore <path to cacerts file>
```
It will most likely ask you for a password. The default password as shipped with Java is `changeit`. Almost nobody changes it. After you complete these relatively simple steps, you'll be communicating securely and with the assurance that you're talking to the right server and only the right server (as long as they don't lose their private key). | Whenever we are trying to connect to URL,
if server at the other site is running on https protocol and is mandating that we should communicate via information provided in certificate then
we have following option:
1) ask for the certificate(download the certificate), import this certificate in trustore. Default trustore java uses can be found in \Java\jdk1.6.0\_29\jre\lib\security\cacerts, then if we retry to connect to the URL connection would be accepted.
2) In normal business cases, we might be connecting to internal URLS in organizations and we know that they are correct.
In such cases, you trust that it is the correct URL, In such cases above, code can be used which will not mandate to store the certificate to connect to particular URL.
**for the point no 2 we have to follow below steps :**
1) write below method which sets HostnameVerifier for HttpsURLConnection which returns true for all cases meaning we are trusting the trustStore.
```
// trusting all certificate
public void doTrustToCertificates() throws Exception {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
return;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
return;
}
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
if (!urlHostName.equalsIgnoreCase(session.getPeerHost())) {
System.out.println("Warning: URL host '" + urlHostName + "' is different to SSLSession host '" + session.getPeerHost() + "'.");
}
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(hv);
}
```
2) write below method, which calls doTrustToCertificates before trying to connect to URL
```
// connecting to URL
public void connectToUrl(){
doTrustToCertificates();//
URL url = new URL("https://www.example.com");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
System.out.println("ResponseCode ="+conn.getResponseCode());
}
```
This call will return response code = 200 means connection is successful.
For more detail and sample example you can refer to [URL](http://blog.hexican.com/2010/12/sending-soap-messages-through-https-using-saaj/). |
6,659,360 | I connected with VPN to setup the inventory API to get product list and it works fine. Once I get the result from the web-service and i bind to UI. And also I integrated PayPal with my application for make Express checkout when I make a call for payment I'm facing this error. I use servlet for back-end process. Can any one say how to fix this issue?
```
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException:
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException:
unable to find valid certification path to requested target
``` | 2011/07/12 | [
"https://Stackoverflow.com/questions/6659360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/504130/"
] | First, you need to obtain the public certificate from the server you're trying to connect to. That can be done in a variety of ways, such as contacting the server admin and asking for it, [using OpenSSL to download it](http://www.madboa.com/geek/openssl/#cert-retrieve), or, since this appears to be an HTTP server, connecting to it with any browser, viewing the page's security info, and saving a copy of the certificate. (Google should be able to tell you exactly what to do for your specific browser.)
Now that you have the certificate saved in a file, you need to add it to your JVM's trust store. At `$JAVA_HOME/jre/lib/security/` for JREs or `$JAVA_HOME/lib/security` for JDKs, there's a file named `cacerts`, which comes with Java and contains the public certificates of the well-known Certifying Authorities. To import the new cert, run keytool as a user who has permission to write to cacerts:
```
keytool -import -file <the cert file> -alias <some meaningful name> -keystore <path to cacerts file>
```
It will most likely ask you for a password. The default password as shipped with Java is `changeit`. Almost nobody changes it. After you complete these relatively simple steps, you'll be communicating securely and with the assurance that you're talking to the right server and only the right server (as long as they don't lose their private key). | SSLHandshakeException can be resolved 2 ways.
1. Incorporating SSL
* Get the SSL (by asking the source system administrator, can also
be downloaded by openssl command, or any browsers downloads the
certificates)
* Add the certificate into truststore (cacerts) located at
JRE/lib/security
* provide the truststore location in vm arguments as
"-Djavax.net.ssl.trustStore="
2. Ignoring SSL
For this #2, please visit my other answer on another stackoverflow website:
[How to ingore SSL verification](https://stackoverflow.com/questions/12060250/ignore-ssl-certificate-errors-with-java/42823950#42823950) [Ignore SSL Certificate Errors with Java](https://stackoverflow.com/questions/12060250/ignore-ssl-certificate-errors-with-java/42823950#42823950) |
6,659,360 | I connected with VPN to setup the inventory API to get product list and it works fine. Once I get the result from the web-service and i bind to UI. And also I integrated PayPal with my application for make Express checkout when I make a call for payment I'm facing this error. I use servlet for back-end process. Can any one say how to fix this issue?
```
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException:
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException:
unable to find valid certification path to requested target
``` | 2011/07/12 | [
"https://Stackoverflow.com/questions/6659360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/504130/"
] | First, you need to obtain the public certificate from the server you're trying to connect to. That can be done in a variety of ways, such as contacting the server admin and asking for it, [using OpenSSL to download it](http://www.madboa.com/geek/openssl/#cert-retrieve), or, since this appears to be an HTTP server, connecting to it with any browser, viewing the page's security info, and saving a copy of the certificate. (Google should be able to tell you exactly what to do for your specific browser.)
Now that you have the certificate saved in a file, you need to add it to your JVM's trust store. At `$JAVA_HOME/jre/lib/security/` for JREs or `$JAVA_HOME/lib/security` for JDKs, there's a file named `cacerts`, which comes with Java and contains the public certificates of the well-known Certifying Authorities. To import the new cert, run keytool as a user who has permission to write to cacerts:
```
keytool -import -file <the cert file> -alias <some meaningful name> -keystore <path to cacerts file>
```
It will most likely ask you for a password. The default password as shipped with Java is `changeit`. Almost nobody changes it. After you complete these relatively simple steps, you'll be communicating securely and with the assurance that you're talking to the right server and only the right server (as long as they don't lose their private key). | This is what I did to POST a JSON to a URL with insecure/invalid SSL certs using latest JDK 11 HttpClient:
```
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
try {
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Creat HttpClient with new SSLContext.
HttpClient httpClient = HttpClient.newBuilder()
.connectTimeout(Duration.ofMillis(3 * 1000))
.sslContext(sc) // SSL context 'sc' initialised as earlier
.build();
// Create request.
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(<URL>))
.timeout(Duration.ofMinutes(1))
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(<PAYLOAD JSON STRING>))
.build();
//Send Request
HttpResponse<String> response =
httpClient.send(request, HttpResponse.BodyHandlers.ofString());
//Access response JSON
String responseJson = response.body();
} catch (Exception e) {
throw new Exception(e);
}
``` |
6,659,360 | I connected with VPN to setup the inventory API to get product list and it works fine. Once I get the result from the web-service and i bind to UI. And also I integrated PayPal with my application for make Express checkout when I make a call for payment I'm facing this error. I use servlet for back-end process. Can any one say how to fix this issue?
```
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException:
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException:
unable to find valid certification path to requested target
``` | 2011/07/12 | [
"https://Stackoverflow.com/questions/6659360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/504130/"
] | Whenever we are trying to connect to URL,
if server at the other site is running on https protocol and is mandating that we should communicate via information provided in certificate then
we have following option:
1) ask for the certificate(download the certificate), import this certificate in trustore. Default trustore java uses can be found in \Java\jdk1.6.0\_29\jre\lib\security\cacerts, then if we retry to connect to the URL connection would be accepted.
2) In normal business cases, we might be connecting to internal URLS in organizations and we know that they are correct.
In such cases, you trust that it is the correct URL, In such cases above, code can be used which will not mandate to store the certificate to connect to particular URL.
**for the point no 2 we have to follow below steps :**
1) write below method which sets HostnameVerifier for HttpsURLConnection which returns true for all cases meaning we are trusting the trustStore.
```
// trusting all certificate
public void doTrustToCertificates() throws Exception {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
return;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
return;
}
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
if (!urlHostName.equalsIgnoreCase(session.getPeerHost())) {
System.out.println("Warning: URL host '" + urlHostName + "' is different to SSLSession host '" + session.getPeerHost() + "'.");
}
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(hv);
}
```
2) write below method, which calls doTrustToCertificates before trying to connect to URL
```
// connecting to URL
public void connectToUrl(){
doTrustToCertificates();//
URL url = new URL("https://www.example.com");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
System.out.println("ResponseCode ="+conn.getResponseCode());
}
```
This call will return response code = 200 means connection is successful.
For more detail and sample example you can refer to [URL](http://blog.hexican.com/2010/12/sending-soap-messages-through-https-using-saaj/). | SSLHandshakeException can be resolved 2 ways.
1. Incorporating SSL
* Get the SSL (by asking the source system administrator, can also
be downloaded by openssl command, or any browsers downloads the
certificates)
* Add the certificate into truststore (cacerts) located at
JRE/lib/security
* provide the truststore location in vm arguments as
"-Djavax.net.ssl.trustStore="
2. Ignoring SSL
For this #2, please visit my other answer on another stackoverflow website:
[How to ingore SSL verification](https://stackoverflow.com/questions/12060250/ignore-ssl-certificate-errors-with-java/42823950#42823950) [Ignore SSL Certificate Errors with Java](https://stackoverflow.com/questions/12060250/ignore-ssl-certificate-errors-with-java/42823950#42823950) |
6,659,360 | I connected with VPN to setup the inventory API to get product list and it works fine. Once I get the result from the web-service and i bind to UI. And also I integrated PayPal with my application for make Express checkout when I make a call for payment I'm facing this error. I use servlet for back-end process. Can any one say how to fix this issue?
```
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException:
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException:
unable to find valid certification path to requested target
``` | 2011/07/12 | [
"https://Stackoverflow.com/questions/6659360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/504130/"
] | Whenever we are trying to connect to URL,
if server at the other site is running on https protocol and is mandating that we should communicate via information provided in certificate then
we have following option:
1) ask for the certificate(download the certificate), import this certificate in trustore. Default trustore java uses can be found in \Java\jdk1.6.0\_29\jre\lib\security\cacerts, then if we retry to connect to the URL connection would be accepted.
2) In normal business cases, we might be connecting to internal URLS in organizations and we know that they are correct.
In such cases, you trust that it is the correct URL, In such cases above, code can be used which will not mandate to store the certificate to connect to particular URL.
**for the point no 2 we have to follow below steps :**
1) write below method which sets HostnameVerifier for HttpsURLConnection which returns true for all cases meaning we are trusting the trustStore.
```
// trusting all certificate
public void doTrustToCertificates() throws Exception {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
return;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
return;
}
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
if (!urlHostName.equalsIgnoreCase(session.getPeerHost())) {
System.out.println("Warning: URL host '" + urlHostName + "' is different to SSLSession host '" + session.getPeerHost() + "'.");
}
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(hv);
}
```
2) write below method, which calls doTrustToCertificates before trying to connect to URL
```
// connecting to URL
public void connectToUrl(){
doTrustToCertificates();//
URL url = new URL("https://www.example.com");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
System.out.println("ResponseCode ="+conn.getResponseCode());
}
```
This call will return response code = 200 means connection is successful.
For more detail and sample example you can refer to [URL](http://blog.hexican.com/2010/12/sending-soap-messages-through-https-using-saaj/). | This is what I did to POST a JSON to a URL with insecure/invalid SSL certs using latest JDK 11 HttpClient:
```
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
try {
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Creat HttpClient with new SSLContext.
HttpClient httpClient = HttpClient.newBuilder()
.connectTimeout(Duration.ofMillis(3 * 1000))
.sslContext(sc) // SSL context 'sc' initialised as earlier
.build();
// Create request.
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(<URL>))
.timeout(Duration.ofMinutes(1))
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(<PAYLOAD JSON STRING>))
.build();
//Send Request
HttpResponse<String> response =
httpClient.send(request, HttpResponse.BodyHandlers.ofString());
//Access response JSON
String responseJson = response.body();
} catch (Exception e) {
throw new Exception(e);
}
``` |
858,161 | The question regards the Poisson distribution function as given by:
$$\frac{x^k e^{-x}}{k!}$$
The distribution's domain (x) goes from 0 to $\infty$, and $k \in \mathbb{N\_0}$
I tried the distribution as the following function:
$$\frac{x^r e^{-x}}{\Gamma(r + 1)}$$
To my surprise, the integral
$$\int\_0^\infty \frac{x^{r}e^{-x}}{\Gamma(r + 1)} dx = 1$$
At least, that's what I deduce from my tests of 0.5, 1.5, 1.2, and 7.9. I have done so non-algebraically, only numerically.
So my question is; is this a valid form of distribution? And should we perhaps replace the one currently on wikipedia stating the requirement of k to be a natural number? | 2014/07/06 | [
"https://math.stackexchange.com/questions/858161",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/132716/"
] | "The distribution's domain" is a phrase I would not have understood if you hadn't provided some context. The distribution's **support** is the set of values the random variable can take, ~~or in the case of continuous distributions, the closure of that set.~~[Later edit: see **PS** below.] For the Poisson distribution whose probability mass function is
$$
k\mapsto\frac{x^k e^{-x}}{k!}
$$
the support is given by
$$
k\in\{0,1,2,3,\ldots\},
$$
the set of non-negative integers.
The set of possible values of $x$ is $[0,\infty)=\{x : x\ge 0\}$. That is the **parameter space**, not for a distribution, but for a family of distributions.
You leave us to infer, rather than explicitly saying, that $0.5$, $1.5$, $1.2$, and $7.9$ are values of $r$ rather than of $x$.
The fact that
$$
\int\_0^\infty \frac{x^r e^{-x}}{\Gamma(r + 1)} dx = 1
$$
is often taken to be the definition of the Gamma function, although the form in which it is most often stated is
$$
\Gamma(s) = \int\_0^\infty x^{s-1} e^{-x}\,dx,
$$
so the $s$ here is $r+1$. A continuous distribution called the Gamma distribution has probability density function
$$
x\mapsto\frac{x^{s-1} e^{-x}}{\Gamma(s)} \text{ for }x>0,
$$
and if one rescales it, putting $x/\lambda$ in place of $x$, one has the density
$$
x\mapsto\frac{(x/\lambda)^{s-1} e^{-x/\lambda}}{\Gamma(s)}\cdot\frac 1 \lambda \text{ for } x>0
$$
and that is also considered a "Gamma distribution". The extra $1/\lambda$ at the end comes from the chain rule. I like to write it is
$$
\frac{(x/\lambda)^{s-1} e^{-x/\lambda}}{\Gamma(s)}\cdot\frac {dx} \lambda\text{ for }x>0.\tag 1
$$
A connection between the Gamma distribution and the Poisson distribution is this: suppose the number of "occurrences" during a particular time interval has a Poisson distribution whose expected value is $\lambda$ times the amount of time, and that the numbers of "occurrences" in different time intervals are independent if the time intervals don't overlap. In that case, the time you wait until the $s$th occurence has the Gamma distribution $(1)$.
**PS:** I was not too precise about what "support" means". For distributions for which the set of values is topologically discrete, the support is indeed the set of values that can be attained. Thus for the Poisson distribution it is $\{0,1,2,3,\ldots\}$. But technically a "discrete distribution" is one for which all the probability is in point masses, and that need not be discrete in the topological sense: it could, for example, be the set of all rational numbers. So here's a **definition:** The support of a distribution is the smallest closed set whose complement has probability $0$. For the Poisson distribution, the set of possible values is $\{0,1,2,3,\ldots\}$, and that's *already* a closed set, so we don't need to take its closure and we get no complications or subtleties. | You have discovered the [Gamma Distribution,](http://en.wikipedia.org/wiki/Gamma_distribution) actually an inessentially special case of it. The distribution has many uses. |
31,594,880 | I am a complete beginner with the [D language](http://dlang.org/).
How to get, as an `uint` unsigned 32 bits integer in the D language, some hash of a string...
I need a quick and dirty hash code (I don't care much about the "randomness" or the "lack of collision", I care slightly more about performance).
```
import std.digest.crc;
uint string_hash(string s) {
return crc320f(s);
}
```
is not good...
(using `gdc-5` on Linux/x86-64 with phobos-2) | 2015/07/23 | [
"https://Stackoverflow.com/questions/31594880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/841108/"
] | A really quick thing could just be this:
```
uint string_hash(string s) {
import std.digest.crc;
auto r = crc32Of(s);
return *(cast(uint*) r.ptr);
}
```
Since `crc32Of` returns a `ubyte[4]` instead of the `uint` you want, a conversion is necessary, but since `ubyte[4]` and `uint` are the same thing to the machine, we can just do a reinterpret cast with the pointer trick seen there to convert types for free at runtime. | While Adams answer does exactly what you're looking for, you can also use a union to do the casting.
This is a pretty useful trick so may as well put it here:
```
/**
* Returns a crc32Of hash of a string
* Uses a union to store the ubyte[]
* And then simply reads that memory as a uint
*/
uint string_hash(string s){
import std.digest.crc;
union hashUnion{
ubyte[4] hashArray;
uint hashNumber;
}
hashUnion x;
x.hashArray = crc32Of(s); // stores the result of crc32Of into the array.
return x.hashNumber; // reads the exact same memory as the hashArray
// but reads it as a uint.
}
``` |
6,183,063 | I am going to use on of the tooltip plugins listed in this question: [jquery tooltip, but on click instead of hover](https://stackoverflow.com/questions/1313321/jquery-tooltip-but-on-click-instead-of-hover)
How would I also setup a tooltip that randomized the text shown. For instance if you click a link you could be shown one of three possible messages:
Message 1
Message 2
Message 3
ideas? | 2011/05/31 | [
"https://Stackoverflow.com/questions/6183063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/282789/"
] | You usually have an array of messages and then generate a random index onclick.
something like
```
var messageArray = ["message 1", "message 2", "message 3"];
var randomNum = Math.floor(Math.random()*messageArray.size);
var myMessage = messageArray[randomNum];
```
or something like that. refactor to use ajax/your db if you need to | Using a very small function from PHP.js: <http://phpjs.org/functions/rand:498>
I do it like so:
```
var messages = [
'Message 1',
'Message 2',
'Message 3'
];
var random_number = rand(0, messages.length);
$("#tooltip").text(messages[random_number]);
// PHP.js rand() function.
// http://kevin.vanzonneveld.net
// + original by: Leslie Hoare
// + bugfixed by: Onno Marsman
function rand (min, max) {
var argc = arguments.length;
if (argc === 0) {
min = 0;
max = 2147483647;
} else if (argc === 1) {
throw new Error('Warning: rand() expects exactly 2 parameters, 1 given');
}
return Math.floor(Math.random() * (max - min + 1)) + min;
}
``` |
6,183,063 | I am going to use on of the tooltip plugins listed in this question: [jquery tooltip, but on click instead of hover](https://stackoverflow.com/questions/1313321/jquery-tooltip-but-on-click-instead-of-hover)
How would I also setup a tooltip that randomized the text shown. For instance if you click a link you could be shown one of three possible messages:
Message 1
Message 2
Message 3
ideas? | 2011/05/31 | [
"https://Stackoverflow.com/questions/6183063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/282789/"
] | You usually have an array of messages and then generate a random index onclick.
something like
```
var messageArray = ["message 1", "message 2", "message 3"];
var randomNum = Math.floor(Math.random()*messageArray.size);
var myMessage = messageArray[randomNum];
```
or something like that. refactor to use ajax/your db if you need to | ```
var messages = ['Message 1', 'Message 2', 'Message 3'];
$('.withTooltip').click(function(){
$("#tooltip").text(messages[Math.round(Math.random() * 3)]).show();
});
``` |
43,971,329 | I have this query on mySQL
```
SELECT updated_at
FROM products
WHERE updated_at >= DATE_ADD(NOW(), INTERVAL -7 DAY)
GROUP BY day(updated_at)
ORDER BY updated_at desc
```
and I try to apply it on Laravel like this
```
$date = Products::select('updated_at')
->where('updated_at', '>=', 'DATE_ADD(NOW(), INTERVAL -7 DAY)')
->groupBy('updated_at')
->orderBy('updated_at', 'desc')
->get()
```
and the results on Laravel is show all data in updated\_at column, not just 6 days before now. Is there anything wrong with my query on Laravel, thank you | 2017/05/15 | [
"https://Stackoverflow.com/questions/43971329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7882004/"
] | You have to use `whereRaw` instead:
```
$date = Products::select('updated_at')
->whereRaw('updated_at >= DATE_ADD(NOW(), INTERVAL -7 DAY)')
->groupBy('updated_at')
->orderBy('updated_at', 'desc')
->get()
``` | Another use case is when you need to actually add an interval to a date column and compare that to now(), like comparing 2 days after start\_date to now().
You would have to do exactly like this (laravel 5.7):
* where 'start\_date' is the column name,
* keywords 'interval' & 'day' must be lowercase (or any other similar needed keywords)
* and brackets surrounding comparison date
```
->whereRaw('start_date + interval 2 day >= ?', [now()]);
```
I found the working answer here: <https://laracasts.com/discuss/channels/eloquent/adding-days-to-a-date-in-a-where-query> |
71,630 | My question originates from the book of Silverman "The Aritmetic of Elliptic Curves", 2nd edition (call it [S]). On p. 273 of [S] the author is considering an elliptic curve $E/K$ defined over a number field $K$ and he introduces the notion of a $v$-adic distance from $P$ to $Q$. This is done as follows:
Firstly, let's fix an absolute value (archimedean or not) $v$ of $K$ and a point $Q\in E(K\_v)$ (here $K\_v$ is the completion of $K$ at $v$). Next let's pick a function $t\_Q \in K\_v(E)$ defined over $K\_v$ which vanishes at $Q$ to the order $e$ but has no other zeroes. Now the $v$-adic distance from $P \in E(K\_v)$ to $Q$ is defined to be $d\_v(P, Q) := \min (|t\_Q(P)|\_v^{1/e}, 1)$. We will say that $P$ goes to $Q$, written $P~\xrightarrow{v}~ Q$, if $d\_v(P, Q) \rightarrow 0$. Later in the text (among other places in the proof of IX.2.2) the author considers a function $\phi\in K\_v(E)$ which is regular at $Q$ and claims that this means that $|\phi(P)|\_v$ is bounded away from $0$ and $\infty$ if $P~\xrightarrow{v}~ Q$.
I have a couple of questions about this:
1. How does one choose a $t\_Q$ that works? In the footnote in [S] it is demonstrated how one could use Riemann-Roch to pick a $t\_Q$ that has a zero only at $Q$. It seems to me however that such a procedure will not make sure that $t\_Q$ is defined over $K\_v$ since $K\_v$ is not algebraically closed.
2. For $\phi$ as above which does not vanish nor has a pole at $Q$, how does one see that $|\phi(P)|\_v$ is bounded away from $0$ and $\infty$ as $P~\xrightarrow{v}~ Q$?
3. Do these $d\_v$ have anything to do with defining a topology on $E(K\_v)$? I assume not, since I don't see how to make sense of it; but then on the other hand they are called "distance functions"... | 2011/07/30 | [
"https://mathoverflow.net/questions/71630",
"https://mathoverflow.net",
"https://mathoverflow.net/users/5498/"
] | * You can choose $t\_Q$ to be defined over $K\_v$, since the divisor $n(Q\_v)$ is defined over $K\_v$, and for large enough $n$ there will be a global section. Note that Riemann-Roch works over non-algebraically closed fields this way. Or you can choose a basis defined over some finite Galois extension of $K\_v$, and then taking appropriate linear combinations of the Galois conjugates, get a function defined over $K\_v$. See Proposition II.5.8 in [S].
* The function defined in the text is only a reasonable "distance function" in the sense that it measures the distance from $P$ to the fixed point $Q$. For the purposes of this proof, that's fine. If you want to define the $v$-adic topology, you need to be a little more careful. Locally around $Q$ you could use $$d\_v(P\_1,P\_2)=min(|t\_Q(P\_1)-t\_Q(P\_2)|^{1/e},1)$$, but that still only works in a neighborhood of $Q$, i.e., in a set $$\{P : d\_v(P,Q)<\epsilon\}$$ for a sufficiently small $\epsilon$. Using local height functions, more precisely the local height relative to the diagonal in $E(K\_v)\times E(K\_v)$, one gets a "good" distance function that is defined everywhere. See for example Lang's *Fundamentals of Diophantine Geometry* or the book *Diophantine Geometry* that Hindry and I wrote for the general construction of local height functions. | Some complement to Joe Silverman's answer. Any algebraic variety over $K\_v$ (or any topological field) has a canonical topology induced by that of the base field. This topology can be defined by a distance (far from to be unique). Over $\mathbb{P}^n\_{K\_v}$, a distance can be given (once a system de coordinates is fixed) by
$$ d((x\_0,\dots, x\_n), \ (y\_0, \dots, x\_n))= \dfrac{\max\_{i, j} \lbrace |x\_iy\_j-x\_jy\_i|\_v \rbrace}{(\max\_i\lbrace |x\_i|\_v\rbrace\max\_j\lbrace |y\_j|\_v \rbrace)}
$$
This is a non-archimedean distance. Concretely, one can see that if there exists an index $r$ such that $|x\_i|\_v\le |x\_r|\_v$ and $|y\_j|\_v\le |y\_r|\_v$ for all $i, j$, then
$$d(x,y)=\max\_i \lbrace |x\_i/x\_r - y\_i/y\_r|\_v \rbrace. $$
Otherwise $d(x,y)=1$.
One can describe this distance as following: there is a canonical reduction map $\pi: \mathbb P^n(K\_v) \to \mathbb P^n(\mathbb k\_v)$ where $k\_v$ is the residue field of $K\_v$. This map consists, after dividing by a coordinate of maximal absolute value, in reducing the coordinates mod $m\_v$.
The fiber $\pi^{-1}(P)$ of a rational point $P\in \mathbb P^n(\mathbb k\_v)$ is just an open unit polydisk. Now if $\pi(x)=\pi(y)$, then $d(x,y)$ is the usual distance in the unit polydisk (maximum of the $|x\_i-y\_i|\_v$), and $d(x,y)=1$ otherwise.
For any quasi-projective variety $X$ over $K\_v$, the embedding in some projective space induces a distance on $X$ with the above distance on projective spaces.
If $X$ has a smooth quasi-projective model $\mathcal X$ such that canonical map $\mathcal X(O\_v)\to X(K\_v)$ is surjective (hence bijective), one can define a distance using the reduction map $\pi: X(K\_v)\simeq \mathcal X(O\_v)\to \mathcal X(k\_v)$ similarly to the projective space (the fibers of $\pi$ are analytically isomorphic to a polydisk). If we embedd $\mathcal X$ into a projective space $\mathbb P^n\_{O\_v}$, then this distance is induced by the above distance on $\mathbb P^n$.
This applies to abelian varieties with their Néron models and the distance is canonical (compatible with homomorphisms of abelian varieties). I don't have access to the books of Lang and of Hindry-Silverman at home, I guess the distance described here has something to do with the good distance function that Joe alludes to. |
17,296,097 | What is wrong in this error ?
>
> alter table INFO add constraint chk\_app check
> (CASE WHEN app IS NULL THEN app = 'A');
>
>
>
>
If its because *app = 'A'* I am calling it twice then how to have a check constraint to check if app is null then it should have value A | 2013/06/25 | [
"https://Stackoverflow.com/questions/17296097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2291869/"
] | @FreefallGeek,
What do you mean by you can't filter AppointmentDate if you remove it from SELECT? Report Builder allows you do dataset filtering based on the user assigned parameter in run time with query like this,
```
SELECT DISTINCT PaientID, InsuranceCarrier
FROM Encounters
WHERE
AppointmentDate >= @beginningofdaterange
AND AppointmentDate <= @endofdaterange
```
With @beginningofdaterange and @endofdaterange as your report parameter. This should work unless you need to do additional filtering that require to return AppointmentDate as result.
If you really need to return the Appointment date as result or for additional filtering, then the next question is what should be the AppointmentDate when there are multiple visit with same patient and insurance carrier? The first visit or the last visit within the date range? If that is the case, you could use group by like this for first visit,
```
SELECT Min(AppointmentDate) AS FirstAppointmentDate, PaientID, InsuranceCarrier
FROM Encounters
WHERE
AppointmentDate >= @beginningofdaterange
AND AppointmentDate <= @endofdaterange
GROUP BY PaientID, InsuranceCarrier
ORDER BY AppointmentDate
```
However, from your description, it appears that you only need the distinct patient and insurance carrier with the capability to filter the date. If that understanding is correct, you could just filter the appointment with user input parameter in the WHERE clause without the SELECT. | In this particular case, I would take into account all visits per the entire day. And instead of displaying multiple encounters per patient per day, I would go to display for the report as AppointmentDate only the day part of the AppointmentDate itself. As the filtering might not need the exact moment of the visit, but only the fact that it took place. The resulting set would be then filtered by the report.
Your particular select would look like the following:
```
-- small modification (take encounters by entire day):
SELECT DISTINCT
CAST(e.AppointmentDate as Date) as AppointmentDateDay, -- the day of the visit
e.PatientID,
e.InsuranceCarrier,
COUNT(e.Id) as CntVisits -- display them if you'd like
FROM Encounters as e
WHERE AppointmentDate >= '20130624 10:00:00'
AND AppointmentDate <= '20130625 18:00:00'
GROUP BY PatientID, InsuranceCarrier, CAST(e.AppointmentDate as Date)
ORDER BY PatientId;
```
Example [Fiddle](http://sqlfiddle.com/#!3/893d6/2) - see both result sets.
If you really need to show the entire AppointmentDate to the user, I admit I don't have an idea now. |
42,001,511 | I have got a Microsoft Access database in the resource folder of my Java application.
When the user clicks a button, this database is copied to the temp directory of the PC. Then I make a temporary VBS file in the same directory and execute it.
(This VBS file calls a VBA macro within the database, that deletes some records.)
However, as the macro attempts to delete the records an error is thrown stating that the database is read only.
Why does this happen?
Here is my code:
When the user clicks the button, some variables are set and then the following code is executed:
```java
private void moveAccess() throws IOException {
String dbName = "sys_cl_imp.accdb";
String tempDbPath = System.getenv("TEMP").replace('\\', '/') + "/" + dbName;
InputStream in = ConscriptioLegere.class.getResourceAsStream("res/" + dbName);
File f = new File(tempDbPath);
Files.copy(in, f.toPath(), StandardCopyOption.REPLACE_EXISTING);
this.dbFilePath = tempDbPath;
System.out.println("access in temp");
f = null;
}
```
Then a connection is made to the database to update some data;
with
```
Connection con = DriverManager.getConnection("jdbc:ucanaccess://" + dbFilePath);
Statement sql = con.createStatement();
...
sql.close();
con.close();
```
Afterwards this is executed:
```java
public boolean startImport() {
File vbsFile = new File(vbsFilePath);
PrintWriter pw;
try {
updateAccess();
} catch (IOException e) {
e.printStackTrace();
return false;
}
try{
pw = new PrintWriter(vbsFile);
pw.println("Set accessApp = CreateObject(\"Access.Application\")");
pw.println("accessApp.OpenCurrentDatabase (\"" + dbFilePath + "\")");
pw.println("accessApp.Run \"sys_cl_imp.importData\", \"" + saveLoc + "\"");
pw.println("accessApp.CloseCurrentDatabase");
pw.close();
Process p = Runtime.getRuntime().exec("cscript /nologo \"" + vbsFilePath + "\"");
```
While the process is running, the error occurres.
I don't understand why the database is open as ReadOnly.
I tried setting f to null after the copying of the db, but it proved not to work that way. | 2017/02/02 | [
"https://Stackoverflow.com/questions/42001511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4440871/"
] | Based on [this dicussion](https://sourceforge.net/p/ucanaccess/discussion/help/thread/4539a56c/).
The solution is adding `;singleconnection=true` to JDBC url. `UCanAccess` will close the file after JDBC connection closed.
```
Connection con = DriverManager.getConnection("jdbc:ucanaccess://" + dbFilePath +";singleconnection=true");
``` | Thank you for your solution beckyang.
I managed to get it working with it, but there was a second mistake:
I deleted the contents of a table with java then closed the connection and run the vba procedure.
In the VBA I was attempting to delete the data again; but as there were none, this didn't work out.
After deleting the SQL from the VBA, the project worked :) |
31,974,011 | I'm currently working on the following website:
<http://hmdesign.alpheca.uberspace.de/>
As you can see, I already managed to create a list of div.project-item elements. Due to the use of inline-blocks, it also reduces the number of columns when you resize the window. What I want to accomplish now is, when you resize the window, that the elements scale up/down in a certain range (between min-width and max-width) until it reaches the maximum/minimum and that it THEN removes/creates a column. The problem now is that there is a huge empty gap after removing a column. It would be much smarter to still show lets say 3 smaller columns in that situation instead of 2 big ones.
I already tried to use a flexbox which didn't really help and also to use block elements instead of inline-block and float them to the left. Then the resizing works but I also want the whole thing to be centered (like now), which I didn't found a way yet to do with floated elements.
Relevant code below:
HTML:
```
<div class="content-wrapper">
<div class="project-list">
<div class="project-item">
<a href="#">
<img class="project-image" src="res/img/Placeholder.jpg">
<div class="project-overlay">
<div class="project-desc">
<span class="project-title"></span>
<span class="project-text"></span>
</div>
</div>
</a>
</div>
<div class="project-item"...
```
CSS:
```
/* Wrapper */
div.nav-wrapper, div.content-wrapper {
max-width: 1280px;
padding: 0 25px;
position: relative;
margin: 0 auto;
height: 100%;
}
/* Portfolio Projektliste */
div.project-list {
padding-top: 150px;
max-width: 1300px;
margin: 0 10px;
text-align: center;
font-size: 0;
}
/* Projekt Item */
div.project-item {
display: inline-block;
position: relative;
width: 400px;
height: auto;
margin: 10px;
overflow: hidden;
}
div.project-item:after {
padding-top: 56.25%;
/* 16:9 ratio */
display: block;
content: '';
}
img.project-image {
position: absolute;
left: 50%;
top: 50%;
transform: translateY(-50%) translateX(-50%);
-webkit-transform: translateY(-50%) translateX(-50%);
-moz-transform: translateY(-50%) translateX(-50%);
max-width: 100%;
}
div.project-overlay {
position: absolute;
width: 100%;
height: 100%;
z-index: 10;
background-color: black;
opacity: 0;
}
``` | 2015/08/12 | [
"https://Stackoverflow.com/questions/31974011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2738393/"
] | Take a look at the "Gang of Four" *composite* pattern:
======================================================
The Child classes should not be derived from the Parent class.
Instead, Child and Parent classes should implement the same Interface,
let's call it `IAlgorithm`.
This Interface should have a pure `virtual` method `start()`...
Here is an example (using C++11 `auto` and Range-based for loop):
```
#include <iostream>
#include <vector>
/* parents and children implement this interface*/
class IAlgorithm {
public:
virtual int start() = 0;
};
class Parent : public IAlgorithm {
private:
std::vector<IAlgorithm*> children;
public:
void addChild(IAlgorithm* child) {
children.push_back(child);
}
int start() {
std::cout << "parent" << std::endl;
for (auto child: children)
child->start();
return 0;
}
};
class Child1 : public IAlgorithm {
public:
int start() {
std::cout << "child 1" << std::endl;
return 1;
}
};
class Child2 : public IAlgorithm {
public:
int start() {
std::cout << "child 2" << std::endl;
return 2;
}
};
class Child3 : public IAlgorithm {
public:
int start() {
std::cout << "child 3" << std::endl;
return 3;
}
};
int main()
{
Parent parent;
Child1 child_1;
Child2 child_2;
Child3 child_3;
parent.addChild(&child_1);
parent.addChild(&child_2);
parent.addChild(&child_3);
parent.start();
return 0;
}
```
The output:
```
parent
child1
child2
child3
``` | A parent can not call child methods, generally. In this case you've created the class as the parent type, so it would be pretty dangerous to call something in a child since a child may assume member methods or variables exist that aren't in the parent. |
12,070,394 | In my Events table I have a column called Pos1, which contains IDs from A to E. I need to count how many times 'E' appears in the column and where it ranks alongside the other numbers.
For example in this table 'E' occurs **1** time and is ranked **4** (D=3, A=2, C=2, E=1, B=0).
```
Pos1
E
C
D
C
D
D
A
A
```
I'm a complete SQL amateur so the closest I've got is an array printing the count of each ID, but I need this to be limited to counting a single ID *and* printing the rank.
```
$query = "SELECT Pos1, COUNT(Pos1) FROM Events GROUP BY Pos1";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['COUNT(Pos1)'] ."<br />";
}
``` | 2012/08/22 | [
"https://Stackoverflow.com/questions/12070394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/310174/"
] | try this:
```
SELECT Pos1, a.cnt, rank
FROM(
SELECT a.Pos1, a.cnt, (@rank := @rank + 1) AS rank
FROM(
SELECT Pos1, COUNT(Pos1) cnt
FROM Events
GROUP BY Pos1
) a, (SELECT @rank := 0) b
ORDER BY a.cnt DESC
)a
WHERE a.pos1 = 'E';
```
[SQLFIDDLE DEMO HERE](http://sqlfiddle.com/#!2/a1e4e/2)
EDIT: php code
```
$query = "SELECT Pos1, a.cnt, rank
FROM(
SELECT a.Pos1, a.cnt, (@rank := @rank + 1) AS rank
FROM(
SELECT Pos1, COUNT(Pos1) cnt
FROM Events
GROUP BY Pos1
) a, (SELECT @rank := 0) b
ORDER BY a.cnt DESC
)a
WHERE a.pos1 = '$pos1'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_row($result);
echo $row['Pos1']." ".$row['cnt']." ".$row['rank']."<br />";
``` | alternatively do rank within PHP:
```
$query = "SELECT Pos1, COUNT(Pos1) AS qty FROM Events GROUP BY Pos1 ORDER BY qty DESC";
$result = mysql_query($query) or die(mysql_error());
$rank=1;
while($row = mysql_fetch_array($result))
{
echo $rank.": ".$row['Pos1']."(".$row['qty'].")<br />";
$rank++;
}
``` |
18,109,625 | I sometimes need to write the whole alphabet `abcd…z` and I hate typing it letter by letter in Vim's insert mode. Does there exist any method to do this more efficiently?
I know about the `ga` command which gives me the ascii code of the character where the cursor is … but don't know anything about how to mix it with my standard solution to type numbers from 1 to (for example) 5000: `a1ESCqqyyp^Aq4998@q` … | 2013/08/07 | [
"https://Stackoverflow.com/questions/18109625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2282982/"
] | How about this command:
```
:put =join(map(range(char2nr('a'),char2nr('z')),'nr2char(v:val)'),'')
```
Collect the ASCII values of the characters in the range from `a` to `z`, then map them over the `nr2char()` function and insert the result into the current buffer with `:put =`.
When you leave out the enclosing `join(` … `,'')` you get the characters on a separate line each.
See
* [`:h nr2char()`](http://vimdoc.sourceforge.net/htmldoc/eval.html#nr2char%28%29),
* [`:h char2nr()`](http://vimdoc.sourceforge.net/htmldoc/eval.html#char2nr%28%29),
* [`:h :put`](http://vimdoc.sourceforge.net/htmldoc/change.html#%3aput),
* and look up `range()`, `map()`, `join()` and friends in the [`list-functions`](http://vimdoc.sourceforge.net/htmldoc/usr_41.html#list-functions) table. | You might try using [Vim abbreviations](http://vim.wikia.com/wiki/Using_abbreviations) or a full-fledged snippet manager plugin like [UltiSnips](https://github.com/SirVer/ultisnips). It might take a few moments to set up, and you'd have to type that alphabet one more time to define it as an abbreviation or snippet, but after that you'd be able to insert the alphabet or any other common chunk of text much more easily. |
18,109,625 | I sometimes need to write the whole alphabet `abcd…z` and I hate typing it letter by letter in Vim's insert mode. Does there exist any method to do this more efficiently?
I know about the `ga` command which gives me the ascii code of the character where the cursor is … but don't know anything about how to mix it with my standard solution to type numbers from 1 to (for example) 5000: `a1ESCqqyyp^Aq4998@q` … | 2013/08/07 | [
"https://Stackoverflow.com/questions/18109625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2282982/"
] | Using `set nrformats+=alpha`:
```
ia<Esc>qqylp<C-a>q24@q
```
Step by step:
```
ia<Esc> " Start with 'a'
qqylp<C-a>q " @q will duplicate the last character and increment it
24@q " Append c..z
``` | First, `set nrformats+=alpha`.
Then:
```
ia<ESC>Y25p<CTRL-V>}g<CTRL-A>k26gJ
```
Which means:
* `ia` insert the initial `a`
* `Y25p` yank the `a` and duplicate it on 25 lines
* `<CTRL-V>` go into visual block mode
* `}` go to the last character at the end of the current paragraph
* `g<CTRL-A>` incrementally increase each alphabetic character (see `help v_g_CTRL-A`)
* `k` go up one line
* `26gJ` join 26 lines without inserting or removing any spaces
Which leads to:
```
abcdefghijklmnopqrstuvwxyz
``` |
18,109,625 | I sometimes need to write the whole alphabet `abcd…z` and I hate typing it letter by letter in Vim's insert mode. Does there exist any method to do this more efficiently?
I know about the `ga` command which gives me the ascii code of the character where the cursor is … but don't know anything about how to mix it with my standard solution to type numbers from 1 to (for example) 5000: `a1ESCqqyyp^Aq4998@q` … | 2013/08/07 | [
"https://Stackoverflow.com/questions/18109625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2282982/"
] | First, `set nrformats+=alpha`.
Then:
```
ia<ESC>Y25p<CTRL-V>}g<CTRL-A>k26gJ
```
Which means:
* `ia` insert the initial `a`
* `Y25p` yank the `a` and duplicate it on 25 lines
* `<CTRL-V>` go into visual block mode
* `}` go to the last character at the end of the current paragraph
* `g<CTRL-A>` incrementally increase each alphabetic character (see `help v_g_CTRL-A`)
* `k` go up one line
* `26gJ` join 26 lines without inserting or removing any spaces
Which leads to:
```
abcdefghijklmnopqrstuvwxyz
``` | You might try using [Vim abbreviations](http://vim.wikia.com/wiki/Using_abbreviations) or a full-fledged snippet manager plugin like [UltiSnips](https://github.com/SirVer/ultisnips). It might take a few moments to set up, and you'd have to type that alphabet one more time to define it as an abbreviation or snippet, but after that you'd be able to insert the alphabet or any other common chunk of text much more easily. |
18,109,625 | I sometimes need to write the whole alphabet `abcd…z` and I hate typing it letter by letter in Vim's insert mode. Does there exist any method to do this more efficiently?
I know about the `ga` command which gives me the ascii code of the character where the cursor is … but don't know anything about how to mix it with my standard solution to type numbers from 1 to (for example) 5000: `a1ESCqqyyp^Aq4998@q` … | 2013/08/07 | [
"https://Stackoverflow.com/questions/18109625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2282982/"
] | If your shell does brace expansion this is a pretty elegant solution:
```
:r !printf '\%s' {a..z}
```
[`:read!`](http://vimdoc.sourceforge.net/htmldoc/insert.html#:read!) reads the output of an external command into the current buffer. In this case, it reads the output of the shell's `printf` applied to `{a..z}` after it's been expanded by the shell. | First, `set nrformats+=alpha`.
Then:
```
ia<ESC>Y25p<CTRL-V>}g<CTRL-A>k26gJ
```
Which means:
* `ia` insert the initial `a`
* `Y25p` yank the `a` and duplicate it on 25 lines
* `<CTRL-V>` go into visual block mode
* `}` go to the last character at the end of the current paragraph
* `g<CTRL-A>` incrementally increase each alphabetic character (see `help v_g_CTRL-A`)
* `k` go up one line
* `26gJ` join 26 lines without inserting or removing any spaces
Which leads to:
```
abcdefghijklmnopqrstuvwxyz
``` |
18,109,625 | I sometimes need to write the whole alphabet `abcd…z` and I hate typing it letter by letter in Vim's insert mode. Does there exist any method to do this more efficiently?
I know about the `ga` command which gives me the ascii code of the character where the cursor is … but don't know anything about how to mix it with my standard solution to type numbers from 1 to (for example) 5000: `a1ESCqqyyp^Aq4998@q` … | 2013/08/07 | [
"https://Stackoverflow.com/questions/18109625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2282982/"
] | If your shell does brace expansion this is a pretty elegant solution:
```
:r !printf '\%s' {a..z}
```
[`:read!`](http://vimdoc.sourceforge.net/htmldoc/insert.html#:read!) reads the output of an external command into the current buffer. In this case, it reads the output of the shell's `printf` applied to `{a..z}` after it's been expanded by the shell. | I have found a shorter solution (you don't need to change nrformats beforehand) while solving <http://www.vimgolf.com/challenges/5ebe8a63d8085e000c2f5bd5>
```
iabcdefghijklm<Esc>yiwg??P
```
which means:
* `iabcdefghijklm<Esc>` insert first half of the alphabet
* `yiw` copy it
* `g??` ROT13 encode (shift by 13 letters) to get the second half
* `P` paste the first half |
18,109,625 | I sometimes need to write the whole alphabet `abcd…z` and I hate typing it letter by letter in Vim's insert mode. Does there exist any method to do this more efficiently?
I know about the `ga` command which gives me the ascii code of the character where the cursor is … but don't know anything about how to mix it with my standard solution to type numbers from 1 to (for example) 5000: `a1ESCqqyyp^Aq4998@q` … | 2013/08/07 | [
"https://Stackoverflow.com/questions/18109625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2282982/"
] | How about this command:
```
:put =join(map(range(char2nr('a'),char2nr('z')),'nr2char(v:val)'),'')
```
Collect the ASCII values of the characters in the range from `a` to `z`, then map them over the `nr2char()` function and insert the result into the current buffer with `:put =`.
When you leave out the enclosing `join(` … `,'')` you get the characters on a separate line each.
See
* [`:h nr2char()`](http://vimdoc.sourceforge.net/htmldoc/eval.html#nr2char%28%29),
* [`:h char2nr()`](http://vimdoc.sourceforge.net/htmldoc/eval.html#char2nr%28%29),
* [`:h :put`](http://vimdoc.sourceforge.net/htmldoc/change.html#%3aput),
* and look up `range()`, `map()`, `join()` and friends in the [`list-functions`](http://vimdoc.sourceforge.net/htmldoc/usr_41.html#list-functions) table. | First, `set nrformats+=alpha`.
Then:
```
ia<ESC>Y25p<CTRL-V>}g<CTRL-A>k26gJ
```
Which means:
* `ia` insert the initial `a`
* `Y25p` yank the `a` and duplicate it on 25 lines
* `<CTRL-V>` go into visual block mode
* `}` go to the last character at the end of the current paragraph
* `g<CTRL-A>` incrementally increase each alphabetic character (see `help v_g_CTRL-A`)
* `k` go up one line
* `26gJ` join 26 lines without inserting or removing any spaces
Which leads to:
```
abcdefghijklmnopqrstuvwxyz
``` |
18,109,625 | I sometimes need to write the whole alphabet `abcd…z` and I hate typing it letter by letter in Vim's insert mode. Does there exist any method to do this more efficiently?
I know about the `ga` command which gives me the ascii code of the character where the cursor is … but don't know anything about how to mix it with my standard solution to type numbers from 1 to (for example) 5000: `a1ESCqqyyp^Aq4998@q` … | 2013/08/07 | [
"https://Stackoverflow.com/questions/18109625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2282982/"
] | I have found a shorter solution (you don't need to change nrformats beforehand) while solving <http://www.vimgolf.com/challenges/5ebe8a63d8085e000c2f5bd5>
```
iabcdefghijklm<Esc>yiwg??P
```
which means:
* `iabcdefghijklm<Esc>` insert first half of the alphabet
* `yiw` copy it
* `g??` ROT13 encode (shift by 13 letters) to get the second half
* `P` paste the first half | You might try using [Vim abbreviations](http://vim.wikia.com/wiki/Using_abbreviations) or a full-fledged snippet manager plugin like [UltiSnips](https://github.com/SirVer/ultisnips). It might take a few moments to set up, and you'd have to type that alphabet one more time to define it as an abbreviation or snippet, but after that you'd be able to insert the alphabet or any other common chunk of text much more easily. |
18,109,625 | I sometimes need to write the whole alphabet `abcd…z` and I hate typing it letter by letter in Vim's insert mode. Does there exist any method to do this more efficiently?
I know about the `ga` command which gives me the ascii code of the character where the cursor is … but don't know anything about how to mix it with my standard solution to type numbers from 1 to (for example) 5000: `a1ESCqqyyp^Aq4998@q` … | 2013/08/07 | [
"https://Stackoverflow.com/questions/18109625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2282982/"
] | If your shell does brace expansion this is a pretty elegant solution:
```
:r !printf '\%s' {a..z}
```
[`:read!`](http://vimdoc.sourceforge.net/htmldoc/insert.html#:read!) reads the output of an external command into the current buffer. In this case, it reads the output of the shell's `printf` applied to `{a..z}` after it's been expanded by the shell. | How about this command:
```
:put =join(map(range(char2nr('a'),char2nr('z')),'nr2char(v:val)'),'')
```
Collect the ASCII values of the characters in the range from `a` to `z`, then map them over the `nr2char()` function and insert the result into the current buffer with `:put =`.
When you leave out the enclosing `join(` … `,'')` you get the characters on a separate line each.
See
* [`:h nr2char()`](http://vimdoc.sourceforge.net/htmldoc/eval.html#nr2char%28%29),
* [`:h char2nr()`](http://vimdoc.sourceforge.net/htmldoc/eval.html#char2nr%28%29),
* [`:h :put`](http://vimdoc.sourceforge.net/htmldoc/change.html#%3aput),
* and look up `range()`, `map()`, `join()` and friends in the [`list-functions`](http://vimdoc.sourceforge.net/htmldoc/usr_41.html#list-functions) table. |
18,109,625 | I sometimes need to write the whole alphabet `abcd…z` and I hate typing it letter by letter in Vim's insert mode. Does there exist any method to do this more efficiently?
I know about the `ga` command which gives me the ascii code of the character where the cursor is … but don't know anything about how to mix it with my standard solution to type numbers from 1 to (for example) 5000: `a1ESCqqyyp^Aq4998@q` … | 2013/08/07 | [
"https://Stackoverflow.com/questions/18109625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2282982/"
] | Using `set nrformats+=alpha`:
```
ia<Esc>qqylp<C-a>q24@q
```
Step by step:
```
ia<Esc> " Start with 'a'
qqylp<C-a>q " @q will duplicate the last character and increment it
24@q " Append c..z
``` | How about this command:
```
:put =join(map(range(char2nr('a'),char2nr('z')),'nr2char(v:val)'),'')
```
Collect the ASCII values of the characters in the range from `a` to `z`, then map them over the `nr2char()` function and insert the result into the current buffer with `:put =`.
When you leave out the enclosing `join(` … `,'')` you get the characters on a separate line each.
See
* [`:h nr2char()`](http://vimdoc.sourceforge.net/htmldoc/eval.html#nr2char%28%29),
* [`:h char2nr()`](http://vimdoc.sourceforge.net/htmldoc/eval.html#char2nr%28%29),
* [`:h :put`](http://vimdoc.sourceforge.net/htmldoc/change.html#%3aput),
* and look up `range()`, `map()`, `join()` and friends in the [`list-functions`](http://vimdoc.sourceforge.net/htmldoc/usr_41.html#list-functions) table. |
18,109,625 | I sometimes need to write the whole alphabet `abcd…z` and I hate typing it letter by letter in Vim's insert mode. Does there exist any method to do this more efficiently?
I know about the `ga` command which gives me the ascii code of the character where the cursor is … but don't know anything about how to mix it with my standard solution to type numbers from 1 to (for example) 5000: `a1ESCqqyyp^Aq4998@q` … | 2013/08/07 | [
"https://Stackoverflow.com/questions/18109625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2282982/"
] | Using `set nrformats+=alpha`:
```
ia<Esc>qqylp<C-a>q24@q
```
Step by step:
```
ia<Esc> " Start with 'a'
qqylp<C-a>q " @q will duplicate the last character and increment it
24@q " Append c..z
``` | I have found a shorter solution (you don't need to change nrformats beforehand) while solving <http://www.vimgolf.com/challenges/5ebe8a63d8085e000c2f5bd5>
```
iabcdefghijklm<Esc>yiwg??P
```
which means:
* `iabcdefghijklm<Esc>` insert first half of the alphabet
* `yiw` copy it
* `g??` ROT13 encode (shift by 13 letters) to get the second half
* `P` paste the first half |
48,270,808 | Not exactly sure what I am doing wrong here, I have looked at other forum post and this is what they say to do to re-auth a user. But I am getting an error of:
`TypeError: Cannot read property 'credential' of undefined` on this line here:
`const credentials = fire.auth.EmailAuthProvider.credential(currentUser.email, user.currentPass);`
Here is the code:
```
const currentUser = fire.auth().currentUser;
const credentials = fire.auth.EmailAuthProvider.credential(currentUser.email, user.currentPass);
currentUser
.reauthenticateWithCredential(credentials)
.then(() => {
alert('Success');
})
.catch(err => {
alert(err);
});
``` | 2018/01/15 | [
"https://Stackoverflow.com/questions/48270808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8551819/"
] | Like @bojeil answered, it's a namespace so, for instance and if you're using typescript and you used `firebase.initializeApp(config);` in another class, just add again the import in the class where you user the credential method with `import * as Firebase from 'firebase/app';`
As u can see in the doc `credential` it's a static method in a static class that's why you need the namespace. | You've imported firebase in the wrong way. [Here](https://firebase.google.com/docs/reference/js/firebase.auth.EmailAuthProvider#.credential) is what it says in the document.
[Official Document](https://i.stack.imgur.com/ymcZI.png)
```
const firebase = require('firebase');
const cred = firebase.auth.EmailAuthProvider.credential(
email,
password
);
``` |
48,270,808 | Not exactly sure what I am doing wrong here, I have looked at other forum post and this is what they say to do to re-auth a user. But I am getting an error of:
`TypeError: Cannot read property 'credential' of undefined` on this line here:
`const credentials = fire.auth.EmailAuthProvider.credential(currentUser.email, user.currentPass);`
Here is the code:
```
const currentUser = fire.auth().currentUser;
const credentials = fire.auth.EmailAuthProvider.credential(currentUser.email, user.currentPass);
currentUser
.reauthenticateWithCredential(credentials)
.then(() => {
alert('Success');
})
.catch(err => {
alert(err);
});
``` | 2018/01/15 | [
"https://Stackoverflow.com/questions/48270808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8551819/"
] | You've imported firebase in the wrong way. [Here](https://firebase.google.com/docs/reference/js/firebase.auth.EmailAuthProvider#.credential) is what it says in the document.
[Official Document](https://i.stack.imgur.com/ymcZI.png)
```
const firebase = require('firebase');
const cred = firebase.auth.EmailAuthProvider.credential(
email,
password
);
``` | I had the same issue as you and none of these answers helped me.
This worked for me:
```
const cred = fire.firebase_.auth.EmailAuthProvider.credential(email, password);
```
I'm not entirely sure why, but I just tried all the options available on `fire` in the dev tools until I came across firebase\_ which had the option of `EmailAuthProvider`. Maybe someone else here knows why. |
48,270,808 | Not exactly sure what I am doing wrong here, I have looked at other forum post and this is what they say to do to re-auth a user. But I am getting an error of:
`TypeError: Cannot read property 'credential' of undefined` on this line here:
`const credentials = fire.auth.EmailAuthProvider.credential(currentUser.email, user.currentPass);`
Here is the code:
```
const currentUser = fire.auth().currentUser;
const credentials = fire.auth.EmailAuthProvider.credential(currentUser.email, user.currentPass);
currentUser
.reauthenticateWithCredential(credentials)
.then(() => {
alert('Success');
})
.catch(err => {
alert(err);
});
``` | 2018/01/15 | [
"https://Stackoverflow.com/questions/48270808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8551819/"
] | Like @bojeil answered, it's a namespace so, for instance and if you're using typescript and you used `firebase.initializeApp(config);` in another class, just add again the import in the class where you user the credential method with `import * as Firebase from 'firebase/app';`
As u can see in the doc `credential` it's a static method in a static class that's why you need the namespace. | I had the same issue as you and none of these answers helped me.
This worked for me:
```
const cred = fire.firebase_.auth.EmailAuthProvider.credential(email, password);
```
I'm not entirely sure why, but I just tried all the options available on `fire` in the dev tools until I came across firebase\_ which had the option of `EmailAuthProvider`. Maybe someone else here knows why. |
148,103 | [](https://i.stack.imgur.com/VlYZM.png)
I have a fictional world, consisting of a federation of 17 provinces (in blue on the map extract). Currently, it is in the late 1920's. The Dzevogurski and Quidthovitse provinces are on the brink of war. Historically, the province of Ladies Beach was part of Dzevogurski but split away peacefully several years ago for admisitrative reasons. The mountain range running NW-SE formed a natural boundry.
In the region concerned, there are two major railway lines involved in trans-continental transport. The Fyonas River - Kandice Beach line runs through two districts of Dzevogurski. To Quidthovice, this is a major point of 'pain': Their tracks run through their 'rivals' territory.
Also, in the 1890's Quidthovice managed to convince the Kimberley-district government to deny the builders of the Vaenesston-Tannith Beach line access to the 'easy' pass between Kimberley and St. Marias Stone, where the Quidthovice-based railroad company had its tracks laid already. To avoid conflict, the Dzevogurski-Ladies Beach government (sitting in Vaenesston) let this slide.
Now, Quidthovice is trying to 'persuade' the two districts of Kimberley and Murrayville (in red/pink) to join their province. Their current 'parent' (the Dzevogurski province) naturally resists. This time, the Dzevogurski government will fight.
If Kimberley and Murrayville do flip, this will [exclave](https://en.wikipedia.org/wiki/Enclave_and_exclave) Yadzor.
The districts of Kimberley, Murrayville, Yadzor are mainly cattle ranches, with some fruit (in the mountains) and dairy production. The population is being influeced by both sides.
The question which I'm asking is this: Can two provinces in a federation have a war between themselves, with everybody else staying neutral?
Can you still call it a 'civil war'?
I know that opinion-based questions are frowned upon in this forum, hence this is an optional question: How would this conflict be resolved? | 2019/05/31 | [
"https://worldbuilding.stackexchange.com/questions/148103",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/6500/"
] | **It depends**
I would say that if the question is purely about semantics, we do not have an internationally accepted definition of civil war. I think that the conflict between two provinces in a federation is not a civil war. Presumably, there is some sort of a federal government, and it's not taking part in it in the situation you describe. Nor is either of the two sides trying to overthrow the federal government.
It can be called 'civil war' in quotes later, if the conflict was especially long or bloody, and the description may stick. Or it may be treated as a big [range war](https://en.wikipedia.org/wiki/Range_war).
Most of other parts of your question depend on the strength of the federal government, the acceptable policies in your world. Will other provinces join in the war - depends on what they stand to win by participating and whether that's an acceptable part of their political culture. They may be content to solve some conflicts by proxy, supplying the combating provinces, but not risking their troops. Or they may treat it as a humanitarian catastrophe and declare strict policy of non-intervention in order to reap some political capital from it.
As for the ways to solve it - again, it severely depends on the structure of the federation and the strength of the federal government. It may be a literal intervention by federal troops that stops the silliness. Or, maybe, federal government is severely decentralized and has a huge latency - all other provinces need to summon a temporary Council in order to figure out what to do next. It also depends on the international conditions - what are the neighbors of your country like and what will they do when the shooting starts? | **Yes**
A civil war is when members of the same country fight against each other for some reason. The people of these provinces presumably think of themselves as part of the same country, and they are fighting, therefore this is a civil war regardless of whether or not some provinces do not fight. There’s a long history of this too: Both Greek and Italian City-states fought each other either directly or through mercenary proxies while still thinking of themselves as part of the same country (for a given value of country).
Where I’d question it is the point of public image and definition. If the government of one province or the other calls it ‘civil unrest that needs to be quelled’ instead of ‘civil war’ then at the time of the conflict there may be confusion over the nature of the conflict, and as history is written by the winners even a brutal fight between two provinces could be massaged into ‘inter-region dispute’ with a careful PR campaign. On the other hand if one region declares itself to be independent from the country (even if the country doesn’t recognise it, like Spain and Catalan), then this stops being a civil war (depending on whose definition of the country you accept). In the world of inter-state politics definition of what is and isn’t is crucial. Did Russia invade Crimea or liberate it’s people? It did both depending on who you ask.
So yeah. Calling it a ‘partial civil war’ is fine, though some governing bodies in your world may disagree.
As for how the conflict is resolved, surely that’s up to you to decide? |
148,103 | [](https://i.stack.imgur.com/VlYZM.png)
I have a fictional world, consisting of a federation of 17 provinces (in blue on the map extract). Currently, it is in the late 1920's. The Dzevogurski and Quidthovitse provinces are on the brink of war. Historically, the province of Ladies Beach was part of Dzevogurski but split away peacefully several years ago for admisitrative reasons. The mountain range running NW-SE formed a natural boundry.
In the region concerned, there are two major railway lines involved in trans-continental transport. The Fyonas River - Kandice Beach line runs through two districts of Dzevogurski. To Quidthovice, this is a major point of 'pain': Their tracks run through their 'rivals' territory.
Also, in the 1890's Quidthovice managed to convince the Kimberley-district government to deny the builders of the Vaenesston-Tannith Beach line access to the 'easy' pass between Kimberley and St. Marias Stone, where the Quidthovice-based railroad company had its tracks laid already. To avoid conflict, the Dzevogurski-Ladies Beach government (sitting in Vaenesston) let this slide.
Now, Quidthovice is trying to 'persuade' the two districts of Kimberley and Murrayville (in red/pink) to join their province. Their current 'parent' (the Dzevogurski province) naturally resists. This time, the Dzevogurski government will fight.
If Kimberley and Murrayville do flip, this will [exclave](https://en.wikipedia.org/wiki/Enclave_and_exclave) Yadzor.
The districts of Kimberley, Murrayville, Yadzor are mainly cattle ranches, with some fruit (in the mountains) and dairy production. The population is being influeced by both sides.
The question which I'm asking is this: Can two provinces in a federation have a war between themselves, with everybody else staying neutral?
Can you still call it a 'civil war'?
I know that opinion-based questions are frowned upon in this forum, hence this is an optional question: How would this conflict be resolved? | 2019/05/31 | [
"https://worldbuilding.stackexchange.com/questions/148103",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/6500/"
] | **Yes**
A civil war is when members of the same country fight against each other for some reason. The people of these provinces presumably think of themselves as part of the same country, and they are fighting, therefore this is a civil war regardless of whether or not some provinces do not fight. There’s a long history of this too: Both Greek and Italian City-states fought each other either directly or through mercenary proxies while still thinking of themselves as part of the same country (for a given value of country).
Where I’d question it is the point of public image and definition. If the government of one province or the other calls it ‘civil unrest that needs to be quelled’ instead of ‘civil war’ then at the time of the conflict there may be confusion over the nature of the conflict, and as history is written by the winners even a brutal fight between two provinces could be massaged into ‘inter-region dispute’ with a careful PR campaign. On the other hand if one region declares itself to be independent from the country (even if the country doesn’t recognise it, like Spain and Catalan), then this stops being a civil war (depending on whose definition of the country you accept). In the world of inter-state politics definition of what is and isn’t is crucial. Did Russia invade Crimea or liberate it’s people? It did both depending on who you ask.
So yeah. Calling it a ‘partial civil war’ is fine, though some governing bodies in your world may disagree.
As for how the conflict is resolved, surely that’s up to you to decide? | Yes, it is not only possible to have neutral parties in internal conflicts, it has happened historically.
This would probably classified as a [Low Intensity Conflicts](https://en.wikipedia.org/wiki/Low_intensity_conflict) due to the localized nature and limited scale of fighting. While "Low Intensity" might not seem to be "Not really a war", low intensity refers to the infrequency of fighting. Low intensity actually conflicts have very higher casualty rates, due to the use of poorly trained soldiers, guerrilla tactics, and terrorism.
Some examples of civil low intensity conflicts with neutral parties:
[The Troubles](https://en.wikipedia.org/wiki/The_Troubles#Overview) - 30 year conflict between Irish nationalists and the United Kingdom over Northern Ireland. While the number of fighters was relatively small, many civilians were killed, even though most citizens of Northern Ireland remained neutral. (Give Ireland back to the Irish)
[Sudanese Civil Wars](https://en.wikipedia.org/wiki/Sudanese_Civil_War) - For most of these wars the Sudanese government participated in "Annual Dry Season Offensives" against the South Sudanese. The rough climate and poor transportation infrastructure of Sudan made it very difficult to hold territory during parts of the year. So almost every year since 1955 The Sudanese Army has invaded the south during the dry season, attempting to take as much land as possible. However, due to the logistical difficulty of holding the land The Sudanese Army retreats every rainy season.
[Myanmar Civil War](https://en.wikipedia.org/wiki/Internal_conflict_in_Myanmar) - Since around 1948, for very complex historical reasons, Myanmar has been in constant civil war. The conflict is the world's longest ongoing civil war and shows no signs of stopping. None of the many sides have made significant progress due to not being able to capture highly defensible terrain (mostly mountains and jungle) this has lead to all sides transforming into self-ruling militaristic states |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.