You're missing semi-colons after your javascript lines. Also, window.location
should have .href
or .replace
etc to redirect - See this post for more information.
echo '<script type="text/javascript">';
echo 'alert("review your answer");';
echo 'window.location.href = "index.php";';
echo '</script>';
For clarity, try leaving PHP tags for this:
?>
<script type="text/javascript">
alert("review your answer");
window.location.href = "index.php";
</script>
<?php
NOTE: semi colons on seperate lines are optional, but encouraged - however as in the comments below, PHP won't break lines in the first example here but will in the second, so semi-colons are required in the first example.
Here is another nice and easy solution:
$maxDim = 800;
$file_name = $_FILES['myFile']['tmp_name'];
list($width, $height, $type, $attr) = getimagesize( $file_name );
if ( $width > $maxDim || $height > $maxDim ) {
$target_filename = $file_name;
$ratio = $width/$height;
if( $ratio > 1) {
$new_width = $maxDim;
$new_height = $maxDim/$ratio;
} else {
$new_width = $maxDim*$ratio;
$new_height = $maxDim;
}
$src = imagecreatefromstring( file_get_contents( $file_name ) );
$dst = imagecreatetruecolor( $new_width, $new_height );
imagecopyresampled( $dst, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
imagedestroy( $src );
imagepng( $dst, $target_filename ); // adjust format as needed
imagedestroy( $dst );
}
Reference: PHP resize image proportionally with max width or weight
Edit: Cleaned up and simplified the code a bit. Thanks @jan-mirus for your comment.
Since the behavior is kind of strange, I have done some testing on the behavior, and here's my result:
If you are:
form
, andonclick="xxx()"
on an elementid="xxx"
or name="xxx"
to that element
Here's are some test and their result:
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<form onsubmit="return false;">
<button onclick="totalbandwidth()">SUCCESS</button>
</form>
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<form onsubmit="return false;">
<button id="totalbandwidth" onclick="totalbandwidth()">FAILED</button>
</form>
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<form onsubmit="return false;">
<button name="totalbandwidth" onclick="totalbandwidth()">FAILED</button>
</form>
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<form onsubmit="return false;">
<input type="button" value="totalbandwidth" onclick="totalbandwidth()" />SUCCESS
</form>
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<button id="totalbandwidth" onclick="totalbandwidth()">SUCCESS</button>
_x000D_
function totalbandwidth(){ alert("The answer is no, the span will not affect button"); }
_x000D_
<form onsubmit="return false;">
<span name="totalbandwidth" >Will this span affect button? </span>
<button onclick="totalbandwidth()">SUCCESS</button>
</form>
_x000D_
After installing php5-gd
apache restart is needed.
The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:
ffmpeg -i input.mov -qscale 0 output.mp4
Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0
):
ffmpeg -i input.mov -q:v 0 output.mp4
Use:
git reset --mixed
instead of git reset --hard
. You will not lose any changes.
Never mind,
I am converting my audio files to mp2 by using the command:
ffmpeg -i input.wav -f mp2 output.mp3
This command works perfectly.
I know that this actually converts the files to mp2 format, but then the resulting file sizes are the same..
php 5.5 has an imagecrop function http://php.net/manual/en/function.imagecrop.php
I just do it like this:
CvCapture *capture = cvCreateFileCapture("rtsp://camera-address");
Also make sure this dll is available at runtime else cvCreateFileCapture will return NULL
opencv_ffmpeg200d.dll
The camera needs to allow unauthenticated access too, usually set via its web interface. MJPEG format worked via rtsp but MPEG4 didn't.
hth
Si
From Which comparator, test, bracket, or double bracket, is fastest? (http://bashcurescancer.com)
The double bracket is a “compound command” where as test and the single bracket are shell built-ins (and in actuality are the same command). Thus, the single bracket and double bracket execute different code.
The test and single bracket are the most portable as they exist as separate and external commands. However, if your using any remotely modern version of BASH, the double bracket is supported.
strict-ssl=false
proxy = http://ip_address_of_proxy:8088 https-proxy = https://ip_address_of_proxy:8088
registry = http://registry.npmjs.org/
If you are looking to do an exact match, use the following syntax:
(param)?
.
Eg.
<Route path={`my/(exact)?/path`} component={MyComponent} />
The nice thing about this is that you'll have props.match
to play with, and you don't need to worry about checking the value of the optional parameter:
{ props: { match: { "0": "exact" } } }
To address the question more generally...
Keep in mind that using synchronized on methods is really just shorthand (assume class is SomeClass):
synchronized static void foo() {
...
}
is the same as
static void foo() {
synchronized(SomeClass.class) {
...
}
}
and
synchronized void foo() {
...
}
is the same as
void foo() {
synchronized(this) {
...
}
}
You can use any object as the lock. If you want to lock subsets of static methods, you can
class SomeClass {
private static final Object LOCK_1 = new Object() {};
private static final Object LOCK_2 = new Object() {};
static void foo() {
synchronized(LOCK_1) {...}
}
static void fee() {
synchronized(LOCK_1) {...}
}
static void fie() {
synchronized(LOCK_2) {...}
}
static void fo() {
synchronized(LOCK_2) {...}
}
}
(for non-static methods, you would want to make the locks be non-static fields)
You can simply use the #define
directive as follows:
#define TRUE 1
#define FALSE 0
#define NOT(arg) (arg == TRUE)? FALSE : TRUE
typedef int bool;
And use as follows:
bool isVisible = FALSE;
bool isWorking = TRUE;
isVisible = NOT(isVisible);
and so on
This is entirely dependent on the encoding of the incoming data.
To get the position of click relative to current clicked element
Use this code
$("#specialElement").click(function(e){
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
});
adb reboot
should not reboot your linux box.
But in any case, you can redirect the command to a specific adb device using adb -s <device_id> command
, where
Device ID can be obtained from the command adb devices
command in this case is reboot
I see you have a problem. Try building your app as Release and then check out your source codes build folder. It may be called Release-iphonesimulator. Inside here will be the app. Then go to (home folder)/Library/Application Support/iPhone Simulator (if you can't find it, try pressing Command - J and choosing arrange by name). Go to an OS that has apps in it in the iPhone sim, like 4.1. In that folder there should be an Applications folder. Open that, and there should be folders with random lettering. Pick any one, and replace it with the app you have. Make sure to delete anything in the little folders!
If it doesn't work, then I'm dumbfounded.
I do not know why there is no answer directly addressing the problem. When you
want to compile C++ program, it is best to use clang++
. For example, the
following works for me:
clang++ -Wall -std=c++11 test.cc -o test
If compiled correctly, it will produce the executable file test
, and you can
run the file by using ./test
.
Or you can just use clang++ test.cc
to compile the program. It will produce a
default executable file named a.out
. Use ./a.out
to run the file.
The whole process is a lot like g++ if you are familiar with g++. See this
post to check which warnings are included with -Wall
option. This
page shows a list of diagnostic flags supported by Clang.
A note on using clang -x c++
: Kim Gräsman says that you can also use
clang -x c++
to compile cpp programs, but that may not be true. For example,
I am having a simple program below:
#include <iostream>
#include <vector>
int main() {
/* std::vector<int> v = {1, 2, 3, 4, 5}; */
std::vector<int> v(10, 5);
int sum = 0;
for (int i = 0; i < v.size(); i++){
sum += v[i]*2;
}
std::cout << "sum is " << sum << std::endl;
return 0;
}
clang++ test.cc -o test
will compile successfully, but clang -x c++
will
not, showing a lot undefined references errors. So I guess they are not exactly
equivalent. It is best to use clang++
instead of clang -x c++
when
compiling c++ programs to avoid extra troubles.
The select statement in the cost part of your select is returning more than one value. You need to add more where clauses, or use an aggregation.
At no point in the history of computing has it ever been possible to prevent reverse-engineering of software when you give a working copy of it to your attacker. Also, in most likelihood, it never will be possible.
With that understood, there is an obvious solution: don't give your secrets to your attacker. While you can't protect the contents of your APK, what you can protect is anything you don't distribute. Typically this is server-side software used for things like activation, payments, rule-enforcement, and other juicy bits of code. You can protect valuable assets by not distributing them in your APK. Instead, set up a server that responds to requests from your app, "uses" the assets (whatever that might mean) and then sends the result back to the app. If this model doesn't work for the assets you have in mind, then you may want to re-think your strategy.
Also, if your primary goal is to prevent app piracy: don't even bother. You've already burned more time and money on this problem than any anti-piracy measure could possibly ever hope to save you. The return on investment for solving this problem is so low that it doesn't make sense to even think about it.
Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.
Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .
if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .
if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .
after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).
if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.
If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.
If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.
If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property.
if you further face any difficulty then you need to provide more information about your web site and sql server .
The problem with putting using namespace
in the header files of your classes is that it forces anyone who wants to use your classes (by including your header files) to also be 'using' (i.e. seeing everything in) those other namespaces.
However, you may feel free to put a using statement in your (private) *.cpp files.
Beware that some people disagree with my saying "feel free" like this -- because although a using
statement in a cpp file is better than in a header (because it doesn't affect people who include your header file), they think it's still not good (because depending on the code it could make the implementation of the class more difficult to maintain). This C++ Super-FAQ entry says,
The using-directive exists for legacy C++ code and to ease the transition to namespaces, but you probably shouldn’t use it on a regular basis, at least not in your new C++ code.
The FAQ suggests two alternatives:
A using-declaration:
using std::cout; // a using-declaration lets you use cout without qualification
cout << "Values:";
Just typing std::
std::cout << "Values:";
Aside from working 3-liners and just for reference: If you want the full blown information - there is a little project on Microsoft Dev Center:
https://code.msdn.microsoft.com/windowsapps/How-to-know-the-process-704839f4
From the Introduction:
The C# sample code developed in .NET Framework 4.0 would help in finding out which is the process that is having a lock on a file. RmStartSession function which is included in rstrtmgr.dll has been used to create a restart manager session and according to the return result a new instance of Win32Exception object is created. After registering the resources to a Restart Manager session via RmRegisterRescources function, RmGetList function is invoked to check what are the applications are using a particular file by enumerating the RM_PROCESS_INFO array.
It works by connecting to the "Restart Manager Session".
The Restart Manager uses the list of resources registered with the session to determine which applications and services must be shut down and restarted. Resources can be identified by filenames, service short names, or RM_UNIQUE_PROCESS structures that describe running applications.
It might be a little overengineered for your particular needs... But if that is what you want, go ahead and grab the vs-project.
Try this :
//i have a
List<string> g_list = new List<string>();
//i put manually the values... (for this example)
g_list.Add("aaa");
g_list.Add("bbb");
g_list.Add("ccc");
//for each string add a row in dataGridView and put the l_str value...
foreach (string l_str in g_list)
{
dataGridView1.Rows.Add(l_str);
}
I just learned the comm command from this thread, but wanted to add something extra: if the files are not sorted, and you don't want to touch the original files, you can pipe the outptut of the sort command. This leaves the original files intact. Works in bash, I can't say about other shells.
comm -1 -2 <(sort file1) <(sort file2)
This can be extended to compare command output, instead of files:
comm -1 -2 <(ls /dir1 | sort) <(ls /dir2 | sort)
Like @benvie said, its more efficient to change a style sheet rather than using jQuery.css (which will loop through all of the elements in the set). It is also important not to add a new style to the head every time the function is called because it will create a memory leak and thousands of CSS rules that have to be individually applied by the browser. I would do something like this:
//Add the stylesheet once and store a cached jQuery object
var $style = $("<style type='text/css'>").appendTo('head');
function onResize() {
var css = "\
.someClass {\
left: "+leftVal+";\
width: "+widthVal+";\
height: "+heightVal+";\
}";
$style.html(css);
}
This solution will change your styles by modifying the DOM only once per resize. Note that for effective js minification and compression, you probably don't want to pretty-print the css, but I did for clarity.
Depends on the Keymap selected.
Keymap: Mac OS X ? + Left Right Arrow Keys
Keymap: Mac OS X 10.5+ ? + [ / ]
I was facing similar problems in Pycharm. To resolve change your Keymap in Preferences.
There are many simple ways to find the mode of a list in Python such as:
import statistics
statistics.mode([1,2,3,3])
>>> 3
Or, you could find the max by its count
max(array, key = array.count)
The problem with those two methods are that they don't work with multiple modes. The first returns an error, while the second returns the first mode.
In order to find the modes of a set, you could use this function:
def mode(array):
most = max(list(map(array.count, array)))
return list(set(filter(lambda x: array.count(x) == most, array)))
In case that you have Ubuntu in your machine, the following steps will help you:
Open your terminal and paste: sudo apt-get install php-soap.
Restart your apache2 server in terminal : service apache2 restart.
To check use your php test file again to be seems like mine in step 1.
The other option for using PHP scripts sans extension is
Options +MultiViews
Or even just following in the directories .htaccess
:
DefaultType application/x-httpd-php
The latter allows having all filenames without extension script
being treated as PHP scripts. While MultiViews makes the webserver look for alternatives, when just the basename is provided (there's a performance hit with that however).
High-Level Design (HLD) involves decomposing a system into modules, and representing the interfaces & invocation relationships among modules. An HLD is referred to as software architecture.
LLD, also known as a detailed design, is used to design internals of the individual modules identified during HLD i.e. data structures and algorithms of the modules are designed and documented.
Now, HLD and LLD are actually used in traditional Approach (Function-Oriented Software Design) whereas, in OOAD, the system is seen as a set of objects interacting with each other.
As per the above definitions, a high-level design document will usually include a high-level architecture diagram depicting the components, interfaces, and networks that need to be further specified or developed. The document may also depict or otherwise refer to work flows and/or data flows between component systems.
Class diagrams with all the methods and relations between classes come under LLD. Program specs are covered under LLD. LLD describes each and every module in an elaborate manner so that the programmer can directly code the program based on it. There will be at least 1 document for each module. The LLD will contain - a detailed functional logic of the module in pseudo code - database tables with all elements including their type and size - all interface details with complete API references(both requests and responses) - all dependency issues - error message listings - complete inputs and outputs for a module.
Following code from here is a useful solution. No keystores etc. Just call method SSLUtilities.trustAllHttpsCertificates() before initializing the service and port (in SOAP).
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
* This class provide various static methods that relax X509 certificate and
* hostname verification while using the SSL over the HTTP protocol.
*
* @author Jiramot.info
*/
public final class SSLUtilities {
/**
* Hostname verifier for the Sun's deprecated API.
*
* @deprecated see {@link #_hostnameVerifier}.
*/
private static com.sun.net.ssl.HostnameVerifier __hostnameVerifier;
/**
* Thrust managers for the Sun's deprecated API.
*
* @deprecated see {@link #_trustManagers}.
*/
private static com.sun.net.ssl.TrustManager[] __trustManagers;
/**
* Hostname verifier.
*/
private static HostnameVerifier _hostnameVerifier;
/**
* Thrust managers.
*/
private static TrustManager[] _trustManagers;
/**
* Set the default Hostname Verifier to an instance of a fake class that
* trust all hostnames. This method uses the old deprecated API from the
* com.sun.ssl package.
*
* @deprecated see {@link #_trustAllHostnames()}.
*/
private static void __trustAllHostnames() {
// Create a trust manager that does not validate certificate chains
if (__hostnameVerifier == null) {
__hostnameVerifier = new SSLUtilities._FakeHostnameVerifier();
} // if
// Install the all-trusting host name verifier
com.sun.net.ssl.HttpsURLConnection
.setDefaultHostnameVerifier(__hostnameVerifier);
} // __trustAllHttpsCertificates
/**
* Set the default X509 Trust Manager to an instance of a fake class that
* trust all certificates, even the self-signed ones. This method uses the
* old deprecated API from the com.sun.ssl package.
*
* @deprecated see {@link #_trustAllHttpsCertificates()}.
*/
private static void __trustAllHttpsCertificates() {
com.sun.net.ssl.SSLContext context;
// Create a trust manager that does not validate certificate chains
if (__trustManagers == null) {
__trustManagers = new com.sun.net.ssl.TrustManager[]{new SSLUtilities._FakeX509TrustManager()};
} // if
// Install the all-trusting trust manager
try {
context = com.sun.net.ssl.SSLContext.getInstance("SSL");
context.init(null, __trustManagers, new SecureRandom());
} catch (GeneralSecurityException gse) {
throw new IllegalStateException(gse.getMessage());
} // catch
com.sun.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(context
.getSocketFactory());
} // __trustAllHttpsCertificates
/**
* Return true if the protocol handler property java. protocol.handler.pkgs
* is set to the Sun's com.sun.net.ssl. internal.www.protocol deprecated
* one, false otherwise.
*
* @return true if the protocol handler property is set to the Sun's
* deprecated one, false otherwise.
*/
private static boolean isDeprecatedSSLProtocol() {
return ("com.sun.net.ssl.internal.www.protocol".equals(System
.getProperty("java.protocol.handler.pkgs")));
} // isDeprecatedSSLProtocol
/**
* Set the default Hostname Verifier to an instance of a fake class that
* trust all hostnames.
*/
private static void _trustAllHostnames() {
// Create a trust manager that does not validate certificate chains
if (_hostnameVerifier == null) {
_hostnameVerifier = new SSLUtilities.FakeHostnameVerifier();
} // if
// Install the all-trusting host name verifier:
HttpsURLConnection.setDefaultHostnameVerifier(_hostnameVerifier);
} // _trustAllHttpsCertificates
/**
* Set the default X509 Trust Manager to an instance of a fake class that
* trust all certificates, even the self-signed ones.
*/
private static void _trustAllHttpsCertificates() {
SSLContext context;
// Create a trust manager that does not validate certificate chains
if (_trustManagers == null) {
_trustManagers = new TrustManager[]{new SSLUtilities.FakeX509TrustManager()};
} // if
// Install the all-trusting trust manager:
try {
context = SSLContext.getInstance("SSL");
context.init(null, _trustManagers, new SecureRandom());
} catch (GeneralSecurityException gse) {
throw new IllegalStateException(gse.getMessage());
} // catch
HttpsURLConnection.setDefaultSSLSocketFactory(context
.getSocketFactory());
} // _trustAllHttpsCertificates
/**
* Set the default Hostname Verifier to an instance of a fake class that
* trust all hostnames.
*/
public static void trustAllHostnames() {
// Is the deprecated protocol setted?
if (isDeprecatedSSLProtocol()) {
__trustAllHostnames();
} else {
_trustAllHostnames();
} // else
} // trustAllHostnames
/**
* Set the default X509 Trust Manager to an instance of a fake class that
* trust all certificates, even the self-signed ones.
*/
public static void trustAllHttpsCertificates() {
// Is the deprecated protocol setted?
if (isDeprecatedSSLProtocol()) {
__trustAllHttpsCertificates();
} else {
_trustAllHttpsCertificates();
} // else
} // trustAllHttpsCertificates
/**
* This class implements a fake hostname verificator, trusting any host
* name. This class uses the old deprecated API from the com.sun. ssl
* package.
*
* @author Jiramot.info
*
* @deprecated see {@link SSLUtilities.FakeHostnameVerifier}.
*/
public static class _FakeHostnameVerifier implements
com.sun.net.ssl.HostnameVerifier {
/**
* Always return true, indicating that the host name is an acceptable
* match with the server's authentication scheme.
*
* @param hostname the host name.
* @param session the SSL session used on the connection to host.
* @return the true boolean value indicating the host name is trusted.
*/
public boolean verify(String hostname, String session) {
return (true);
} // verify
} // _FakeHostnameVerifier
/**
* This class allow any X509 certificates to be used to authenticate the
* remote side of a secure socket, including self-signed certificates. This
* class uses the old deprecated API from the com.sun.ssl package.
*
* @author Jiramot.info
*
* @deprecated see {@link SSLUtilities.FakeX509TrustManager}.
*/
public static class _FakeX509TrustManager implements
com.sun.net.ssl.X509TrustManager {
/**
* Empty array of certificate authority certificates.
*/
private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[]{};
/**
* Always return true, trusting for client SSL chain peer certificate
* chain.
*
* @param chain the peer certificate chain.
* @return the true boolean value indicating the chain is trusted.
*/
public boolean isClientTrusted(X509Certificate[] chain) {
return (true);
} // checkClientTrusted
/**
* Always return true, trusting for server SSL chain peer certificate
* chain.
*
* @param chain the peer certificate chain.
* @return the true boolean value indicating the chain is trusted.
*/
public boolean isServerTrusted(X509Certificate[] chain) {
return (true);
} // checkServerTrusted
/**
* Return an empty array of certificate authority certificates which are
* trusted for authenticating peers.
*
* @return a empty array of issuer certificates.
*/
public X509Certificate[] getAcceptedIssuers() {
return (_AcceptedIssuers);
} // getAcceptedIssuers
} // _FakeX509TrustManager
/**
* This class implements a fake hostname verificator, trusting any host
* name.
*
* @author Jiramot.info
*/
public static class FakeHostnameVerifier implements HostnameVerifier {
/**
* Always return true, indicating that the host name is an acceptable
* match with the server's authentication scheme.
*
* @param hostname the host name.
* @param session the SSL session used on the connection to host.
* @return the true boolean value indicating the host name is trusted.
*/
public boolean verify(String hostname, javax.net.ssl.SSLSession session) {
return (true);
} // verify
} // FakeHostnameVerifier
/**
* This class allow any X509 certificates to be used to authenticate the
* remote side of a secure socket, including self-signed certificates.
*
* @author Jiramot.info
*/
public static class FakeX509TrustManager implements X509TrustManager {
/**
* Empty array of certificate authority certificates.
*/
private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[]{};
/**
* Always trust for client SSL chain peer certificate chain with any
* authType authentication types.
*
* @param chain the peer certificate chain.
* @param authType the authentication type based on the client
* certificate.
*/
public void checkClientTrusted(X509Certificate[] chain, String authType) {
} // checkClientTrusted
/**
* Always trust for server SSL chain peer certificate chain with any
* authType exchange algorithm types.
*
* @param chain the peer certificate chain.
* @param authType the key exchange algorithm used.
*/
public void checkServerTrusted(X509Certificate[] chain, String authType) {
} // checkServerTrusted
/**
* Return an empty array of certificate authority certificates which are
* trusted for authenticating peers.
*
* @return a empty array of issuer certificates.
*/
public X509Certificate[] getAcceptedIssuers() {
return (_AcceptedIssuers);
} // getAcceptedIssuers
} // FakeX509TrustManager
} // SSLUtilities
Another Solution : you get the marker by its title
public class MarkerDemoActivity extends android.support.v4.app.FragmentActivity implements OnMarkerClickListener
{
private Marker myMarker;
private void setUpMap()
{
.......
googleMap.setOnMarkerClickListener(this);
myMarker = googleMap.addMarker(new MarkerOptions()
.position(latLng)
.title("My Spot")
.snippet("This is my spot!")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
......
}
@Override
public boolean onMarkerClick(final Marker marker)
{
String name= marker.getTitle();
if (name.equalsIgnoreCase("My Spot"))
{
//write your code here
}
}
}
Try this:
List<int> list = new List<int>();
list.Add(1);
list.Add(5);
list.Add(4);
list.Add(3);
list.Add(2);
foreach (var item in list.OrderByDescending(x => x))
{
Console.WriteLine(item);
}
I made my own version, based in the code presented above by @Tats_innit . The difference is the pause function. Works a little better in that aspect.
(function ($) {
var timeVar, width=0;
$.fn.textWidth = function () {
var calc = '<span style="display:none">' + $(this).text() + '</span>';
$('body').append(calc);
var width = $('body').find('span:last').width();
$('body').find('span:last').remove();
return width;
};
$.fn.marquee = function (args) {
var that = $(this);
if (width == 0) { width = that.width(); };
var textWidth = that.textWidth(), offset = that.width(), i = 0, stop = textWidth * -1, dfd = $.Deferred(),
css = {
'text-indent': that.css('text-indent'),
'overflow': that.css('overflow'),
'white-space': that.css('white-space')
},
marqueeCss = {
'text-indent': width,
'overflow': 'hidden',
'white-space': 'nowrap'
},
args = $.extend(true, { count: -1, speed: 1e1, leftToRight: false, pause: false }, args);
function go() {
if (!that.length) return dfd.reject();
if (width <= stop) {
i++;
if (i <= args.count) {
that.css(css);
return dfd.resolve();
}
if (args.leftToRight) {
width = textWidth * -1;
} else {
width = offset;
}
}
that.css('text-indent', width + 'px');
if (args.leftToRight) {
width++;
} else {
width=width-2;
}
if (args.pause == false) { timeVar = setTimeout(function () { go() }, args.speed); };
if (args.pause == true) { clearTimeout(timeVar); };
};
if (args.leftToRight) {
width = textWidth * -1;
width++;
stop = offset;
} else {
width--;
}
that.css(marqueeCss);
timeVar = setTimeout(function () { go() }, 100);
return dfd.promise();
};
})(jQuery);
usage:
for start: $('#Text1').marquee()
pause: $('#Text1').marquee({ pause: true })
resume: $('#Text1').marquee({ pause: false })
math.log
is the natural logarithm:
math.log(x[, base]) With one argument, return the natural logarithm of x (to base e).
Your equation is therefore:
n = math.log((1 + (FV * r) / p) / math.log(1 + r)))
Note that in your code you convert n to a str
twice which is unnecessary
This will return TRUE
for #VALUE!
errors (ERROR.TYPE = 3) and FALSE
for anything else.
=IF(ISERROR(A1),ERROR.TYPE(A1)=3)
If you only have a single newline in the input, just doing
std::cin.ignore();
will work fine. It reads and discards the next character from the input.
But if you have anything else still in the input, besides the newline (for example, you read one word but the user entered two words), then you have to do
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
See e.g. this reference of the ignore
function.
To be even more safe, do the second alternative above in a loop until gcount
returns zero.
You can now use Modern ECMAScript syntax thanks to V8 Runtime.
You can use includes():
var grade = itemResponse.getResponse();
if(grade.includes("9th")){do something}
Generally I handle this by setting up an HTML formatted SMTP message, with IMG tags pointing to a content server. Just make sure you have both text and HTML versions since some email clients cannot support HTML emails.
an ajax call to your domain is the easiest way to detect if you are offline
$.ajax({
type: "HEAD",
url: document.location.pathname + "?param=" + new Date(),
error: function() { return false; },
success: function() { return true; }
});
this is just to give you the concept, it should be improved.
E.g. error=404 should still mean that you online
Here we have two possible cases given below
from __future__ import division
print(4/100)
print(4//100)
#if !defined(MANUF) || !defined(SERIAL) || !defined(MODEL)
I am not sure what the difference is with the retail NCover, but there is also an NCover project on SourceForge that is of course open source and free.
For Oracle use:
Select * from v$version;
For SQL server use:
Select @@VERSION as Version
and for MySQL use:
Show variables LIKE "%version%";
A functor is pretty much just a class which defines the operator(). That lets you create objects which "look like" a function:
// this is a functor
struct add_x {
add_x(int val) : x(val) {} // Constructor
int operator()(int y) const { return x + y; }
private:
int x;
};
// Now you can use it like this:
add_x add42(42); // create an instance of the functor class
int i = add42(8); // and "call" it
assert(i == 50); // and it added 42 to its argument
std::vector<int> in; // assume this contains a bunch of values)
std::vector<int> out(in.size());
// Pass a functor to std::transform, which calls the functor on every element
// in the input sequence, and stores the result to the output sequence
std::transform(in.begin(), in.end(), out.begin(), add_x(1));
assert(out[i] == in[i] + 1); // for all i
There are a couple of nice things about functors. One is that unlike regular functions, they can contain state. The above example creates a function which adds 42 to whatever you give it. But that value 42 is not hardcoded, it was specified as a constructor argument when we created our functor instance. I could create another adder, which added 27, just by calling the constructor with a different value. This makes them nicely customizable.
As the last lines show, you often pass functors as arguments to other functions such as std::transform or the other standard library algorithms. You could do the same with a regular function pointer except, as I said above, functors can be "customized" because they contain state, making them more flexible (If I wanted to use a function pointer, I'd have to write a function which added exactly 1 to its argument. The functor is general, and adds whatever you initialized it with), and they are also potentially more efficient. In the above example, the compiler knows exactly which function std::transform
should call. It should call add_x::operator()
. That means it can inline that function call. And that makes it just as efficient as if I had manually called the function on each value of the vector.
If I had passed a function pointer instead, the compiler couldn't immediately see which function it points to, so unless it performs some fairly complex global optimizations, it'd have to dereference the pointer at runtime, and then make the call.
A slightly simpler solution:
>>> "7061756c".decode("hex")
'paul'
Try This... It's very simple just use confirm dialog box for alert with YES|NO.
if(confirm("Do you want to upgrade?")){ Your code }
Your condition says if X is greater than 57 AND smaller than 48
. X
cannot be both greater than 57 and smaller than 48 at the same time.
if(tmp[j] > 57 && tmp[j] < 48)
It should be if X is greater than 57 OR smaller than 48
:
if(tmp[j] > 57 || tmp[j] < 48)
To Read from Keyboard (Standard Input) You can use Scanner is a class in java.util
package.
Scanner
package used for obtaining the input of the primitive types like int, double
etc. and strings
. It is the easiest way to read input in a Java program, though not very efficient.
object
of Scanner
class, we usually pass the
predefined object System.in
, which represents the standard input
stream (Keyboard).For example, this code allows a user to read a number from System.in:
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
Some Public methods in Scanner
class.
hasNext()
Returns true if this scanner has another token in its
input.nextInt()
Scans the next token of the input as an int.nextFloat()
Scans the next token of the input as a float.nextLine()
Advances this scanner past the current line and returns the input that was skipped. nextDouble()
Scans the next token of the input as a double.close()
Closes this scanner.For more details of Public methods in Scanner class.
Example:-
import java.util.Scanner; //importing class
class ScannerTest {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in); // Scanner object
System.out.println("Enter your rollno");
int rollno = sc.nextInt();
System.out.println("Enter your name");
String name = sc.next();
System.out.println("Enter your fee");
double fee = sc.nextDouble();
System.out.println("Rollno:" + rollno + " name:" + name + " fee:" + fee);
sc.close(); // closing object
}
}
Somewhere, you need to tell Apache that people are allowed to see contents of this directory.
<Directory "F:/bar/public">
Order Allow,Deny
Allow from All
# Any other directory-specific stuff
</Directory>
Basically I use Fiddler or Postman for testing API's.
In fiddler, in request header you need to specify instead of xml, html you need to change it to json.
Eg: Accept: application/json
. That should do the job.
To remove black background only add background-color: white; to the style of
The USAGE-privilege in mysql simply means that there are no privileges for the user 'phpadmin'@'localhost' defined on global level *.*
. Additionally the same user has ALL-privilege on database phpmyadmin phpadmin.*
.
So if you want to remove all the privileges and start totally from scratch do the following:
Revoke all privileges on database level:
REVOKE ALL PRIVILEGES ON phpmyadmin.* FROM 'phpmyadmin'@'localhost';
Drop the user 'phpmyadmin'@'localhost'
DROP USER 'phpmyadmin'@'localhost';
Above procedure will entirely remove the user from your instance, this means you can recreate him from scratch.
To give you a bit background on what described above: as soon as you create a user the mysql.user
table will be populated. If you look on a record in it, you will see the user and all privileges set to 'N'
. If you do a show grants for 'phpmyadmin'@'localhost';
you will see, the allready familliar, output above. Simply translated to "no privileges on global level for the user". Now your grant ALL
to this user on database level, this will be stored in the table mysql.db
. If you do a SELECT * FROM mysql.db WHERE db = 'nameofdb';
you will see a 'Y'
on every priv.
Above described shows the scenario you have on your db at the present. So having a user that only has USAGE
privilege means, that this user can connect, but besides of SHOW GLOBAL VARIABLES; SHOW GLOBAL STATUS;
he has no other privileges.
Just to update all, after some deliberations, I have decided to use Async Http Client instead to solve my earlier problem. The library allows a cleaner approach (to me) to manipulate HTTP responses especially in cases where JSON objects are returned in all scenarios/HTTP statuses.
protected void getLogin() {
EditText username = (EditText) findViewById(R.id.username);
EditText password = (EditText) findViewById(R.id.password);
RequestParams params = new RequestParams();
params.put("username", username.getText().toString());
params.put("password", password.getText().toString());
RestClient.post(getHost() + "api/v1/auth/login", params,
new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
JSONObject response) {
try {
//process JSONObject obj
Log.w("myapp","success status code..." + statusCode);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onFailure(int statusCode, Header[] headers,
Throwable throwable, JSONObject errorResponse) {
Log.w("myapp", "failure status code..." + statusCode);
try {
//process JSONObject obj
Log.w("myapp", "error ..." + errorResponse.getString("message").toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
There are many ways to wait in Unity. It is really simple but I think it's worth covering most ways to do these:
1.With a coroutine and WaitForSeconds
.
The is by far the simplest way. Put all the code that you need to wait for some time in a coroutine function then you can wait with WaitForSeconds
. Note that in coroutine function, you call the function with StartCoroutine(yourFunction)
.
Example below will rotate 90 deg, wait for 4 seconds, rotate 40 deg and wait for 2 seconds, and then finally rotate rotate 20 deg.
void Start()
{
StartCoroutine(waiter());
}
IEnumerator waiter()
{
//Rotate 90 deg
transform.Rotate(new Vector3(90, 0, 0), Space.World);
//Wait for 4 seconds
yield return new WaitForSeconds(4);
//Rotate 40 deg
transform.Rotate(new Vector3(40, 0, 0), Space.World);
//Wait for 2 seconds
yield return new WaitForSeconds(2);
//Rotate 20 deg
transform.Rotate(new Vector3(20, 0, 0), Space.World);
}
2.With a coroutine and WaitForSecondsRealtime
.
The only difference between WaitForSeconds
and WaitForSecondsRealtime
is that WaitForSecondsRealtime
is using unscaled time to wait which means that when pausing a game with Time.timeScale
, the WaitForSecondsRealtime
function would not be affected but WaitForSeconds
would.
void Start()
{
StartCoroutine(waiter());
}
IEnumerator waiter()
{
//Rotate 90 deg
transform.Rotate(new Vector3(90, 0, 0), Space.World);
//Wait for 4 seconds
yield return new WaitForSecondsRealtime(4);
//Rotate 40 deg
transform.Rotate(new Vector3(40, 0, 0), Space.World);
//Wait for 2 seconds
yield return new WaitForSecondsRealtime(2);
//Rotate 20 deg
transform.Rotate(new Vector3(20, 0, 0), Space.World);
}
Wait and still be able to see how long you have waited:
3.With a coroutine and incrementing a variable every frame with Time.deltaTime
.
A good example of this is when you need the timer to display on the screen how much time it has waited. Basically like a timer.
It's also good when you want to interrupt the wait/sleep with a boolean
variable when it is true. This is where yield break;
can be used.
bool quit = false;
void Start()
{
StartCoroutine(waiter());
}
IEnumerator waiter()
{
float counter = 0;
//Rotate 90 deg
transform.Rotate(new Vector3(90, 0, 0), Space.World);
//Wait for 4 seconds
float waitTime = 4;
while (counter < waitTime)
{
//Increment Timer until counter >= waitTime
counter += Time.deltaTime;
Debug.Log("We have waited for: " + counter + " seconds");
//Wait for a frame so that Unity doesn't freeze
//Check if we want to quit this function
if (quit)
{
//Quit function
yield break;
}
yield return null;
}
//Rotate 40 deg
transform.Rotate(new Vector3(40, 0, 0), Space.World);
//Wait for 2 seconds
waitTime = 2;
//Reset counter
counter = 0;
while (counter < waitTime)
{
//Increment Timer until counter >= waitTime
counter += Time.deltaTime;
Debug.Log("We have waited for: " + counter + " seconds");
//Check if we want to quit this function
if (quit)
{
//Quit function
yield break;
}
//Wait for a frame so that Unity doesn't freeze
yield return null;
}
//Rotate 20 deg
transform.Rotate(new Vector3(20, 0, 0), Space.World);
}
You can still simplify this by moving the while
loop into another coroutine function and yielding it and also still be able to see it counting and even interrupt the counter.
bool quit = false;
void Start()
{
StartCoroutine(waiter());
}
IEnumerator waiter()
{
//Rotate 90 deg
transform.Rotate(new Vector3(90, 0, 0), Space.World);
//Wait for 4 seconds
float waitTime = 4;
yield return wait(waitTime);
//Rotate 40 deg
transform.Rotate(new Vector3(40, 0, 0), Space.World);
//Wait for 2 seconds
waitTime = 2;
yield return wait(waitTime);
//Rotate 20 deg
transform.Rotate(new Vector3(20, 0, 0), Space.World);
}
IEnumerator wait(float waitTime)
{
float counter = 0;
while (counter < waitTime)
{
//Increment Timer until counter >= waitTime
counter += Time.deltaTime;
Debug.Log("We have waited for: " + counter + " seconds");
if (quit)
{
//Quit function
yield break;
}
//Wait for a frame so that Unity doesn't freeze
yield return null;
}
}
Wait/Sleep until variable changes or equals to another value:
4.With a coroutine and the WaitUntil
function:
Wait until a condition becomes true
. An example is a function that waits for player's score to be 100
then loads the next level.
float playerScore = 0;
int nextScene = 0;
void Start()
{
StartCoroutine(sceneLoader());
}
IEnumerator sceneLoader()
{
Debug.Log("Waiting for Player score to be >=100 ");
yield return new WaitUntil(() => playerScore >= 10);
Debug.Log("Player score is >=100. Loading next Leve");
//Increment and Load next scene
nextScene++;
SceneManager.LoadScene(nextScene);
}
5.With a coroutine and the WaitWhile
function.
Wait while a condition is true
. An example is when you want to exit app when the escape key is pressed.
void Start()
{
StartCoroutine(inputWaiter());
}
IEnumerator inputWaiter()
{
Debug.Log("Waiting for the Exit button to be pressed");
yield return new WaitWhile(() => !Input.GetKeyDown(KeyCode.Escape));
Debug.Log("Exit button has been pressed. Leaving Application");
//Exit program
Quit();
}
void Quit()
{
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}
6.With the Invoke
function:
You can call tell Unity to call function in the future. When you call the Invoke
function, you can pass in the time to wait before calling that function to its second parameter. The example below will call the feedDog()
function after 5
seconds the Invoke
is called.
void Start()
{
Invoke("feedDog", 5);
Debug.Log("Will feed dog after 5 seconds");
}
void feedDog()
{
Debug.Log("Now feeding Dog");
}
7.With the Update()
function and Time.deltaTime
.
It's just like #3 except that it does not use coroutine. It uses the Update
function.
The problem with this is that it requires so many variables so that it won't run every time but just once when the timer is over after the wait.
float timer = 0;
bool timerReached = false;
void Update()
{
if (!timerReached)
timer += Time.deltaTime;
if (!timerReached && timer > 5)
{
Debug.Log("Done waiting");
feedDog();
//Set to false so that We don't run this again
timerReached = true;
}
}
void feedDog()
{
Debug.Log("Now feeding Dog");
}
There are still other ways to wait in Unity but you should definitely know the ones mentioned above as that makes it easier to make games in Unity. When to use each one depends on the circumstances.
For your particular issue, this is the solution:
IEnumerator showTextFuntion()
{
TextUI.text = "Welcome to Number Wizard!";
yield return new WaitForSeconds(3f);
TextUI.text = ("The highest number you can pick is " + max);
yield return new WaitForSeconds(3f);
TextUI.text = ("The lowest number you can pick is " + min);
}
And to call/start the coroutine function from your start or Update function, you call it with
StartCoroutine (showTextFuntion());
Probably because both SQL Server and Sybase (to name two I am familiar with) used to have a 255 character maximum in the number of characters in a VARCHAR
column. For SQL Server, this changed in version 7 in 1996/1997 or so... but old habits sometimes die hard.
As of today, there is no support on this function. However, I found a little hack on this one.
imageView.setImageResource(R.drawable.ic_star_black_48dp);
imageView.setTag(R.drawable.ic_star_black_48dp);
So if you want to get the ID of the view, just get it's tag.
if (imageView.getTag() != null) {
int resourceID = (int) imageView.getTag();
//
// drawable id.
//
}
Try the following:
SELECT *, (FieldA + FieldB) AS Sum
FROM Table
try using -U
(aka --update-snapshots
) when you run maven
And make sure the dependency definition is correct
This also works:
...
WHERE
(FirstName IS NULL OR FirstName = ISNULL(@FirstName, FirstName)) AND
(LastName IS NULL OR LastName = ISNULL(@LastName, LastName)) AND
(Title IS NULL OR Title = ISNULL(@Title, Title))
The Best and Simple way is using Float
val = Float "234" rescue nil
Float "234" rescue nil #=> 234.0
Float "abc" rescue nil #=> nil
Float "234abc" rescue nil #=> nil
Float nil rescue nil #=> nil
Float "" rescue nil #=> nil
Integer
is also good but it will return 0
for Integer nil
You usually see it in the ternary assignment operator;
Syntax
variable = `condition ? result 1 : result 2;`
example:
boolean isNegative = number > 0 ? false : true;
which is "equivalent" in nature to the if else
if(number > 0){
isNegative = false;
}
else{
isNegative = true;
}
Other than examples given by different posters,
you can also use : to signify a label for a block which you can use in conjunction with continue and break..
for example:
public void someFunction(){
//an infinite loop
goBackHere: { //label
for(int i = 0; i < 10 ;i++){
if(i == 9 ) continue goBackHere;
}
}
}
You can use method getDate():
$('#calendar').datepicker({
dateFormat: 'yy-m-d',
inline: true,
onSelect: function(dateText, inst) {
var date = $(this).datepicker('getDate'),
day = date.getDate(),
month = date.getMonth() + 1,
year = date.getFullYear();
alert(day + '-' + month + '-' + year);
}
});
That's because Bootstrap by default sets the width of the legend
element to 100%. You can fix this by changing your legend.scheduler-border
to also use:
legend.scheduler-border {
width:inherit; /* Or auto */
padding:0 10px; /* To give a bit of padding on the left and right */
border-bottom:none;
}
You'll also need to ensure your custom stylesheet is being added after Bootstrap to prevent Bootstrap overriding your styling - although your styles here should have higher specificity.
You may also want to add margin-bottom:0;
to it as well to reduce the gap between the legend and the divider.
Put ALTER COLUMN
statement inside a bracket, it should work.
ALTER TABLE tblcommodityOHLC alter ( column
CC_CommodityContractID NUMERIC(18,0),
CM_CommodityID NUMERIC(18,0) )
The light bulb started to come on. Unfortunately, I have not discovered a uniform way to correct the problem, as described below.
I believe that my whole problem centers on my autoresizingMasks. And the reason I have concluded that is the same symptoms exist, with or without a UIWebView. And that symptom is that everything is peachy for Portrait. For Landscape, the bottom-most UIButton pops down behind the TabBar.
For example, on one UIView, I have, from top to bottom:
UIView – both springs set (default case) and no struts
UIScrollView - If I set the two springs, and clear everything else (like the UIView), then the UIButton intrudes on the object immediately above it. If I clear everything, then UIButton is OK, but the stuff at the very top hides behind the StatusBar Setting only the top strut, the UIButton pops down behind the Tab Bar.
UILabel and UIImage next vertically – top strut set, flexible everywhere else
Just to complete the picture for the few that have a UIWebView:
UIWebView - Struts: top, left, right Springs: both
UIButton – nothing set, i.e., flexible everywhere
Although my light bulb is dim, there appears to be hope.
This might give the increased relevance to the head part that you want. It won't double it, but it might possibly good enough for your sake:
SELECT pages.*,
MATCH (head, body) AGAINST ('some words') AS relevance,
MATCH (head) AGAINST ('some words') AS title_relevance
FROM pages
WHERE MATCH (head, body) AGAINST ('some words')
ORDER BY title_relevance DESC, relevance DESC
-- alternatively:
ORDER BY title_relevance + relevance DESC
An alternative that you also want to investigate, if you've the flexibility to switch DB engine, is Postgres. It allows to set the weight of operators and to play around with the ranking.
Link to oficial API documentation is http://instagram.com/developer/authentication/
Longstory short - two steps:
Get CODE
Open https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code with information from http://instagram.com/developer/clients/manage/
Get access token
curl \-F 'client_id=CLIENT-ID' \
-F 'client_secret=CLIENT-SECRET' \
-F 'grant_type=authorization_code' \
-F 'redirect_uri=YOUR-REDIRECT-URI' \
-F 'code=CODE' \
https://api.instagram.com/oauth/access_token
You can also use simple_format(@str)
which removes malicious code. Read more here: http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-simple_format
By catching Throwable
it includes things that subclass Error
. You should generally not do that, except perhaps at the very highest "catch all" level of a thread where you want to log or otherwise handle absolutely everything that can go wrong. It would be more typical in a framework type application (for example an application server or a testing framework) where it can be running unknown code and should not be affected by anything that goes wrong with that code, as much as possible.
def gcd(a,b):
if b > a:
return gcd(b,a)
r = a%b
if r == 0:
return b
return gcd(r,b)
$(window).load()
will work only the first time the page is loaded. If you are doing dynamic stuff (example: click button, wait for some new images to load), this won't work. To achieve that, you can use my plugin:
/**
* Plugin which is applied on a list of img objects and calls
* the specified callback function, only when all of them are loaded (or errored).
* @author: H. Yankov (hristo.yankov at gmail dot com)
* @version: 1.0.0 (Feb/22/2010)
* http://yankov.us
*/
(function($) {
$.fn.batchImageLoad = function(options) {
var images = $(this);
var originalTotalImagesCount = images.size();
var totalImagesCount = originalTotalImagesCount;
var elementsLoaded = 0;
// Init
$.fn.batchImageLoad.defaults = {
loadingCompleteCallback: null,
imageLoadedCallback: null
}
var opts = $.extend({}, $.fn.batchImageLoad.defaults, options);
// Start
images.each(function() {
// The image has already been loaded (cached)
if ($(this)[0].complete) {
totalImagesCount--;
if (opts.imageLoadedCallback) opts.imageLoadedCallback(elementsLoaded, originalTotalImagesCount);
// The image is loading, so attach the listener
} else {
$(this).load(function() {
elementsLoaded++;
if (opts.imageLoadedCallback) opts.imageLoadedCallback(elementsLoaded, originalTotalImagesCount);
// An image has been loaded
if (elementsLoaded >= totalImagesCount)
if (opts.loadingCompleteCallback) opts.loadingCompleteCallback();
});
$(this).error(function() {
elementsLoaded++;
if (opts.imageLoadedCallback) opts.imageLoadedCallback(elementsLoaded, originalTotalImagesCount);
// The image has errored
if (elementsLoaded >= totalImagesCount)
if (opts.loadingCompleteCallback) opts.loadingCompleteCallback();
});
}
});
// There are no unloaded images
if (totalImagesCount <= 0)
if (opts.loadingCompleteCallback) opts.loadingCompleteCallback();
};
})(jQuery);
You almost never have to write your own loops in C++. Here, you can use std::find.
const int toFind = 42;
int* found = std::find (myArray, std::end (myArray), toFind);
if (found != std::end (myArray))
{
std::cout << "Found.\n"
}
else
{
std::cout << "Not found.\n";
}
std::end
requires C++11. Without it, you can find the number of elements in the array with:
const size_t numElements = sizeof (myArray) / sizeof (myArray[0]);
...and the end with:
int* end = myArray + numElements;
AStyle can be customized in great detail for C++ and Java (and others too)
This is a source code formatting tool.
clang-format is a powerful command line tool bundled with the clang compiler which handles even the most obscure language constructs in a coherent way.
It can be integrated with Visual Studio, Emacs, Vim (and others) and can format just the selected lines (or with git/svn to format some diff).
It can be configured with a variety of options listed here.
When using config files (named .clang-format
) styles can be per directory - the closest such file in parent directories shall be used for a particular file.
Styles can be inherited from a preset (say LLVM or Google) and can later override different options
It is used by Google and others and is production ready.
Also look at the project UniversalIndentGUI. You can experiment with several indenters using it: AStyle, Uncrustify, GreatCode, ... and select the best for you. Any of them can be run later from a command line.
Uncrustify has a lot of configurable options. You'll probably need Universal Indent GUI (in Konstantin's reply) as well to configure it.
As stated, all objects in sharepoint contain some sort of unique identifier (often an integer based counter for list items, and GUIDs for lists).
That said, there is also a feature available at http://www.codeplex.com/features called "Unique Column Policy", designed to add an other column with a unique value. A complete writeup is available at http://scothillier.spaces.live.com/blog/cns!8F5DEA8AEA9E6FBB!293.entry
$float = -abs($float);
The code that you have shown will do what you want iff those properties equal "" when they are not filled in. If they equal $null when not filled in for example, then they will not equal "". Here is an example to prove the point that what you have will work for "":
$foo = 1
$bar = 1
$foo -eq 1 -and $bar -eq 1
True
$foo -eq 1 -and $bar -eq 2
False
Considering unicode. Code checked in python3.
from unicodedata import category
text = 'hi, how are you?'
text_without_punc = ''.join(ch for ch in text if not category(ch).startswith('P'))
To expand upon dreamlax's example... If you want to send data along with the notification
In posting code:
NSDictionary *userInfo =
[NSDictionary dictionaryWithObject:myObject forKey:@"someKey"];
[[NSNotificationCenter defaultCenter] postNotificationName:
@"TestNotification" object:nil userInfo:userInfo];
In observing code:
- (void) receiveTestNotification:(NSNotification *) notification {
NSDictionary *userInfo = notification.userInfo;
MyObject *myObject = [userInfo objectForKey:@"someKey"];
}
It is a syntax. In the function arguments int (&myArray)[100]
parenthesis that enclose the &myArray
are necessary. if you don't use them, you will be passing an array of references
and that is because the subscript operator []
has higher precedence over the & operator
.
E.g. int &myArray[100] // array of references
So, by using type construction ()
you tell the compiler that you want a reference to an array of 100 integers.
E.g int (&myArray)[100] // reference of an array of 100 ints
They are not. They're exactly the same.
However, some people say that parameters are placeholders in method signatures:
public void doMethod(String s, int i) {
..
}
String s and int i are sometimes said to be parameters. The arguments are the actual values/references:
myClassReference.doMethod("someString", 25);
"someString" and 25 are sometimes said to be the arguments.
This solution is deprecated. Use the top voted solution.
The hide
class is useful to keep the content hidden on page load.
My solution to this is during initialization, switch to jquery's hide:
$('.targets').hide().removeClass('hide');
Then show()
and hide()
should function as normal.
Since Http service in angular2 returns an Observable type, From your Angular2 installation directory('node_modules' in my case),We need to import map function of the Observable in your component using http service,as:
import 'rxjs/add/operator/map';
You'll want to use the GetExtensionName method on the FileSystemObject object.
Set x = CreateObject("scripting.filesystemobject")
WScript.Echo x.GetExtensionName("foo.pdf")
In your example, try using this
For Each objFile in colFiles
If UCase(objFSO.GetExtensionName(objFile.name)) = "PDF" Then
Wscript.Echo objFile.Name
End If
Next
I think you could get away with using relative positioning and then set the top/left positioning of the second DIV until you have it in the position desired.
Ah its unfortunate. Since you add them essentially client side asp.net blows up. It is also unfortunate you'd have to turn off EventValidation as there are some important protections that helps (for instance evil injection into drop down boxes). The other alternative is to make your own composite control, which of course here seems a bit more than the effort involved. I'd prob turn off event validation too but be very careful that you don't trust any values from the page that could be used in a bad manner by simply changing them - like hidden keys, sql injection through combo boxes, etc.
Greetings if i get you right you need a JavaScript function that doing it
function report(v) {
//To Do
switch(v) {
case "daily":
//Do something
break;
case "monthly":
//Do somthing
break;
}
}
Regards
Here's a link to marketplace for extension. Extension "compareit" helps to compare two files wich you can choose from your current project and other directory on your computer or clipboard.
TL;DR:
A DTO describes the pattern of state transfer. A POCO doesn't describe anything. It's another way of saying "object" in OOP. It comes from POJO (Java), coined by Martin Fowler who literally just describes it as a fancier name for 'object' because 'object' isn't very sexy.
A DTO is an object pattern used to transfer state between layers of concern. They can have behavior (i.e. can technically be a poco) so long as that behavior doesn't mutate the state. For example, it may have a method that serializes itself.
A POCO is a plain object, but what is meant by 'plain' is that it is not special. It just means it's a CLR object with no implied pattern to it. A generic term. It isn't made to work with some other framework. So if your POCO has [JsonProperty]
or EF decorations all over it's properties, for example, then it I'd argue that it isn't a POCO.
Here some examples of different kinds of object patterns to compare:
These are all just objects, but notice that most of them are generally tied to a pattern. So you could call them "objects" or you could be more specific about its intent and call it by what it is. This is also why we have design patterns; to describe complex concepts in a few works. DTO is a pattern. Aggregate root is a pattern, View Model is a pattern (e.g. MVC & MVVM). POCO is not a pattern.
A POCO doesn't describe a pattern. It is just a different way of referring to classes/objects in OOP. Think of it as an abstract concept; they can be referring to anything. IMO, there's a one-way relationship though because once an object reaches the point where it can only serve one purpose cleanly, it is no longer a POCO. For example, once you mark up your class with decorations to make it work with some framework, it is no longer a POCO. Therefore:
The point in making a distinction between the two is about keeping patterns clear and consistent in effort to not cross concerns and lead to tight coupling. For example if you have a business object that has methods to mutate state, but is also decorated to hell with EF decorations for saving to SQL Server AND JsonProperty so that it can be sent back over an API endpoint. That object would be intolerant to change, and would likely be littered with variants of properties (e.g. UserId, UserPk, UserKey, UserGuid, where some of them are marked up to not be saved to the DB and others marked up to not be serialized to JSON at the API endpoint).
So if you were to tell me something was a DTO, then I'd probably make sure it was never used for anything other than moving state around. If you told me something was a view model, then I'd probably make sure it wasn't getting saved to a database. If you told me something was a Domain Model, then I'd probably make sure it had no dependencies on anything outside of the domain. But if you told me something was a POCO, you wouldn't really be telling me much at all.
I had the same issue, ended up using the much more convenient Guava Resources:
Resources.getResource("my.file")
I find that if you use a lot of spaces, the browser will wrap it properly. Don't worry about using an exact number of spaces, just throw a lot in there, and the browser should properly wrap to the first non space character on the next line.
<textarea name="address" placeholder="1313 Mockingbird Ln Saginaw, MI 45100"></textarea>
That's a very complex question for a simple answer.
You may want to take a look at existing API frameworks, like Swagger Specification (OpenAPI), and services like apiary.io and apiblueprint.org.
Also, here's an example of the same REST API described, organized and even styled in three different ways. It may be a good start for you to learn from existing common ways.
At the very top level I think quality REST API docs require at least the following:
Also there are a lot of JSON/XML-based doc frameworks which can parse your API definition or schema and generate a convenient set of docs for you. But the choice for a doc generation system depends on your project, language, development environment and many other things.
This answer comes a little bit late, but I just was in a similar need.
Observing the comments written by @ganaraj in the question, One use case I was in the need of is, passing a classname via a directive attribute to be added to a ng-repeat li tag in the template.
For example, use the directive like this:
<my-directive class2add="special-class" />
And get the following html:
<div>
<ul>
<li class="special-class">Item 1</li>
<li class="special-class">Item 2</li>
</ul>
</div>
The solution found here applied with templateUrl, would be:
app.directive("myDirective", function() {
return {
template: function(element, attrs){
return '<div><ul><li ng-repeat="item in items" class="'+attrs.class2add+'"></ul></div>';
},
link: function(scope, element, attrs) {
var list = element.find("ul");
}
}
});
Just tried it successfully with AngularJS 1.4.9.
Hope it helps.
Use npm to uninstall. Just running sudo npm uninstall npm -g
removes all the files.
To get rid of the extraneous stuff like bash pathnames run this (from nicerobot's answer):
sudo rm -rf /usr/local/lib/node \
/usr/local/lib/node_modules \
/var/db/receipts/org.nodejs.*
I test examples in js. Simplest solution - just add word u need inside / /:
var reg = /cat/;
reg.test('some cat here');//1 test
true // result
reg.test('acatb');//2 test
true // result
Now if u need this specific word with boundaries, not inside any other signs-letters. We use b marker:
var reg = /\bcat\b/
reg.test('acatb');//1 test
false // result
reg.test('have cat here');//2 test
true // result
We have also exec() method in js, whichone returns object-result. It helps f.g. to get info about place/index of our word.
var matchResult = /\bcat\b/.exec("good cat good");
console.log(matchResult.index); // 5
If we need get all matched words in string/sentence/text, we can use g modifier (global match):
"cat good cat good cat".match(/\bcat\b/g).length
// 3
Now the last one - i need not 1 specific word, but some of them. We use | sign, it means choice/or.
"bad dog bad".match(/\bcat|dog\b/g).length
// 1
Why not store it as an array of prices instead of object?
prices = []
$(allProducts).each(function () {
var price = parseFloat($(this).data('price'));
prices.push(price);
});
prices.sort(function(a, b) { return a - b }); //this is the magic line which sort the array
That way you can just
prices[0]; // cheapest
prices[prices.length - 1]; // most expensive
Note that you can do shift()
and pop()
to get min and max price respectively, but it will take off the price from the array.
Even better alternative is to use Sergei solution below, by using Math.max
and min
respectively.
EDIT:
I realized that this would be wrong if you have something like [11.5, 3.1, 3.5, 3.7]
as 11.5
is treated as a string, and would come before the 3.x
in dictionary order, you need to pass in custom sort function to make sure they are indeed treated as float:
prices.sort(function(a, b) { return a - b });
Swift 4+
NotificationCenter.default.addObserver(forName: UIApplication.userDidTakeScreenshotNotification, object: nil, queue: OperationQueue.main) { notification in
//you can do anything you want here.
}
by using this observer you can find out when user takes a screenshot, but you can not prevent him.
Some frameworks are using this header to detect xhr requests e.g. grails spring security is using this header to identify xhr request and give either a json response or html response as response.
Most Ajax libraries (Prototype, JQuery, and Dojo as of v2.1) include an X-Requested-With header that indicates that the request was made by XMLHttpRequest instead of being triggered by clicking a regular hyperlink or form submit button.
Source: http://grails-plugins.github.io/grails-spring-security-core/guide/helperClasses.html
You can simply make the start_date required using
<input type="submit" value="Submit" required />
You don't even need the checkform() then.
Thanks
I'm assuming you figured this out already but:
Technical Reference for Log Files in Configuration Manager
That's a list of client-side logs and what they do. They are located in Windows\CCM\Logs
AppEnforce.log
will show you the actual command-line executed and the resulting exit code for each Deployment Type (only for the new style ConfigMgr Applications)
This is my go-to for troubleshooting apps. Haven't really found any other logs that are exceedingly useful.
Yes Java allows vargs
in method parameter .
public class Varargs
{
public int add(int... numbers)
{
int result = 1;
for(int number: numbers)
{
result= result+number;
} return result;
}
}
You can specify the family of JRE to be used. http://www.oracle.com/technetwork/java/javase/family-clsid-140615.html
Comparing various suggestions (as well as comparing in the context of single-character replacements with various sizes and positions of the target).
In this particular case, splitting on the targets and joining on the replacements (in this case, empty string) is the fastest by at least a factor of 3. Ultimately, performance is different depending on the number of replacements, where the replacements are in the source, and the size of the source. #ymmv
(full results here)
| Test | Compare | Elapsed |
|---------------------------|---------|--------------------------------------------------------------------|
| SplitJoin | 1.00x | 29023 ticks elapsed (2.9023 ms) [in 10K reps, 0.00029023 ms per] |
| Replace | 2.77x | 80295 ticks elapsed (8.0295 ms) [in 10K reps, 0.00080295 ms per] |
| RegexCompiled | 5.27x | 152869 ticks elapsed (15.2869 ms) [in 10K reps, 0.00152869 ms per] |
| LinqSplit | 5.43x | 157580 ticks elapsed (15.758 ms) [in 10K reps, 0.0015758 ms per] |
| Regex, Uncompiled | 5.85x | 169667 ticks elapsed (16.9667 ms) [in 10K reps, 0.00169667 ms per] |
| Regex | 6.81x | 197551 ticks elapsed (19.7551 ms) [in 10K reps, 0.00197551 ms per] |
| RegexCompiled Insensitive | 7.33x | 212789 ticks elapsed (21.2789 ms) [in 10K reps, 0.00212789 ms per] |
| Regex Insentive | 7.52x | 218164 ticks elapsed (21.8164 ms) [in 10K reps, 0.00218164 ms per] |
(note: the Perf
and Vs
are timing extensions I wrote)
void test(string title, string sample, string target, string replacement) {
var targets = target.ToCharArray();
var tox = "[" + target + "]";
var x = new Regex(tox);
var xc = new Regex(tox, RegexOptions.Compiled);
var xci = new Regex(tox, RegexOptions.Compiled | RegexOptions.IgnoreCase);
// no, don't dump the results
var p = new Perf/*<string>*/();
p.Add(string.Join(" ", title, "Replace"), n => targets.Aggregate(sample, (res, curr) => res.Replace(new string(curr, 1), replacement)));
p.Add(string.Join(" ", title, "SplitJoin"), n => String.Join(replacement, sample.Split(targets)));
p.Add(string.Join(" ", title, "LinqSplit"), n => String.Concat(sample.Select(c => targets.Contains(c) ? replacement : new string(c, 1))));
p.Add(string.Join(" ", title, "Regex"), n => Regex.Replace(sample, tox, replacement));
p.Add(string.Join(" ", title, "Regex Insentive"), n => Regex.Replace(sample, tox, replacement, RegexOptions.IgnoreCase));
p.Add(string.Join(" ", title, "Regex, Uncompiled"), n => x.Replace(sample, replacement));
p.Add(string.Join(" ", title, "RegexCompiled"), n => xc.Replace(sample, replacement));
p.Add(string.Join(" ", title, "RegexCompiled Insensitive"), n => xci.Replace(sample, replacement));
var trunc = 40;
var header = sample.Length > trunc ? sample.Substring(0, trunc) + "..." : sample;
p.Vs(header);
}
void Main()
{
// also see https://stackoverflow.com/questions/7411438/remove-characters-from-c-sharp-string
"Control".Perf(n => { var s = "*"; });
var text = "My name @is ,Wan.;'; Wan";
var clean = new[] { '@', ',', '.', ';', '\'' };
test("stackoverflow", text, string.Concat(clean), string.Empty);
var target = "o";
var f = "x";
var replacement = "1";
var fillers = new Dictionary<string, string> {
{ "short", new String(f[0], 10) },
{ "med", new String(f[0], 300) },
{ "long", new String(f[0], 1000) },
{ "huge", new String(f[0], 10000) }
};
var formats = new Dictionary<string, string> {
{ "start", "{0}{1}{1}" },
{ "middle", "{1}{0}{1}" },
{ "end", "{1}{1}{0}" }
};
foreach(var filler in fillers)
foreach(var format in formats) {
var title = string.Join("-", filler.Key, format.Key);
var sample = string.Format(format.Value, target, filler.Value);
test(title, sample, target, replacement);
}
}
Suggest replacing this:
char str[1024];
char tmp = '.';
strcat(str, tmp);
with this:
char str[1024] = {'\0'}; // set array to initial all NUL bytes
char tmp[] = "."; // create a string for the call to strcat()
strcat(str, tmp); //
Your can do it like this in short hands.
int[,] values=new int[2,3]{{2,4,5},{4,5,2}};
for (int i = 0; i < values.GetLength(0); i++)
{
for (int k = 0; k < values.GetLength(1); k++) {
Console.Write(values[i,k]);
}
Console.WriteLine();
}
This setting needs to be set:
SET SERVEROUTPUT ON
Additional data (in case you have more questions):
FOO: {
for my $i ( @listone ){
for my $j ( @listtwo ){
if ( cond( $i,$j ) ){
last FOO; # --->
# |
} # |
} # |
} # |
} # <-------------------------------
You can try:
\bcat\b.*\bmat\b
\b
is an anchor and matches a word boundary. It will look for words cat and mat anywhere in the string with mat following cat. It will not match:
Therez caterpillar on the mat
.
but will match
The cat slept on the mat in front of the fire
If you want to match strings which have letters cat followed by mat, you can try:
cat.*mat
This will match both the above example strings.
Or if you use the six library
from six.moves import reduce
The second option really isn't the same as the others - if the string is "///foo" it will become "foo" instead of "//foo".
The first option needs a bit more work to understand than the third - I would view the Substring
option as the most common and readable.
(Obviously each of them as an individual statement won't do anything useful - you'll need to assign the result to a variable, possibly data
itself.)
I wouldn't take performance into consideration here unless it was actually becoming a problem for you - in which case the only way you'd know would be to have test cases, and then it's easy to just run those test cases for each option and compare the results. I'd expect Substring
to probably be the fastest here, simply because Substring
always ends up creating a string from a single chunk of the original input, whereas Remove
has to at least potentially glue together a start chunk and an end chunk.
"my, tags are, in here".split(/[ ,]+/)
the result is :
["my", "tags", "are", "in", "here"]
Like this:
int main()
{
int arr[2][5] =
{
{1,8,12,20,25},
{5,9,13,24,26}
};
}
This should be covered by your C++ textbook: which one are you using?
Anyway, better, consider using std::vector
or some ready-made matrix class e.g. from Boost.
I was facing the same problem, I googled and tried suggestions I found but none of them worked for me. I changed my workspace and it worked, but before changing your workspace try other workarounds you have. Any one of them might work for you.
A simple json POST request example for those that need it even simpler than what Tom is linking to:
require 'net/http'
uri = URI.parse("http://www.example.com/search.json")
response = Net::HTTP.post_form(uri, {"search" => "Berlin"})
I do not see http://wordlist.sourceforge.net/ mentioned here, but that is where I would start if I were looking for something like this (and I was, when I stumbled over this question).
If you cannot find what you want there, and what you want is a list of english words, then you should probably spend some extra time describing how to recognize what it is that you want.
This is a maven specific problem I think. Maven does not copy the files form /src/main/resources
to the target-test folder. You will have to do this yourself by configuring the resources plugin, if you absolutely want to go this way.
An easier way is to instead put a test specific context definition in the /src/test/resources
directory and load via:
@ContextConfiguration(locations = { "classpath:mycontext.xml" })
If someone finds this question like me, here are my performance tests of proposed methods:
Python 2.7.8
In [1]: %timeit ([1]*1000000).insert(0, 0)
100 loops, best of 3: 4.62 ms per loop
In [2]: %timeit ([1]*1000000)[0:0] = [0]
100 loops, best of 3: 4.55 ms per loop
In [3]: %timeit [0] + [1]*1000000
100 loops, best of 3: 8.04 ms per loop
As you can see, insert
and slice assignment are as almost twice as fast than explicit adding and are very close in results. As Raymond Hettinger noted insert
is more common option and I, personally prefer this way to prepend to list.
In the Eclipse download folder make the entries in the eclipse.ini
file :
--launcher.XXMaxPermSize
512M
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms512m
-Xmx1024m
or what ever values you want.
jQuery lib has to be loaded first. In my case, i was loading bootstrap lib first, also tried tag with target and firing a click trigger. But the main issue was - jquery has to be loaded first.
Another option:
"My name is Milan, people know me as Milan Vasic"
.replaceAll("Milan Vasic|Milan", "Milan Vasic"))
@hop5 and @RnMss suggested to use C++11 lambdas, but if you deal with pointers, you can use them directly:
#include <thread>
#include <iostream>
class CFoo {
public:
int m_i = 0;
void bar() {
++m_i;
}
};
int main() {
CFoo foo;
std::thread t1(&CFoo::bar, &foo);
t1.join();
std::thread t2(&CFoo::bar, &foo);
t2.join();
std::cout << foo.m_i << std::endl;
return 0;
}
outputs
2
Rewritten sample from this answer would be then:
#include <thread>
#include <iostream>
class Wrapper {
public:
void member1() {
std::cout << "i am member1" << std::endl;
}
void member2(const char *arg1, unsigned arg2) {
std::cout << "i am member2 and my first arg is (" << arg1 << ") and second arg is (" << arg2 << ")" << std::endl;
}
std::thread member1Thread() {
return std::thread(&Wrapper::member1, this);
}
std::thread member2Thread(const char *arg1, unsigned arg2) {
return std::thread(&Wrapper::member2, this, arg1, arg2);
}
};
int main() {
Wrapper *w = new Wrapper();
std::thread tw1 = w->member1Thread();
tw1.join();
std::thread tw2 = w->member2Thread("hello", 100);
tw2.join();
return 0;
}
//objects
var array = [{id:'12', name:'Smith', value:1},{id:'13', name:'Jones', value:2}];
array.sort(function(a, b){
var a1= a.name.toLower(), b1= b.name.toLower();
if(a1== b1) return 0;
return a1> b1? 1: -1;
});
//arrays
var array =[ ['12', ,'Smith',1],['13', 'Jones',2]];
array.sort(function(a, b){
var a1= a[1], b1= b[1];
if(a1== b1) return 0;
return a1> b1? 1: -1;
});
On OS X, use pbcopy
; pbpaste
goes in the opposite direction.
pbcopy < .ssh/id_rsa.pub
You can select every column from that sub-query by aliasing it and adding the alias before the *
:
SELECT t.*, a+b AS total_sum
FROM
(
SELECT SUM(column1) AS a, SUM(column2) AS b
FROM table
) t
I was looking for the same but couldn't find it, so I make a small script in PHP, you can find it at: http://tequilaphp.wordpress.com/2010/07/05/searching-strings-in-a-database-and-files/
Good luck! (I remove some private code, let me know if I didn't break it in the process :D)
If you want to do it by ClassName you could do:
<script type="text/javascript">
function hideTd(className){
var elements;
if (document.getElementsByClassName)
{
elements = document.getElementsByClassName(className);
}
else
{
var elArray = [];
var tmp = document.getElementsByTagName(elements);
var regex = new RegExp("(^|\\s)" + className+ "(\\s|$)");
for ( var i = 0; i < tmp.length; i++ ) {
if ( regex.test(tmp[i].className) ) {
elArray.push(tmp[i]);
}
}
elements = elArray;
}
for(var i = 0, i < elements.length; i++) {
if( elements[i].textContent == ''){
elements[i].style.display = 'none';
}
}
}
</script>
In the Manifest, you can set the screenOrientation to landscape. It would look something like this in the XML:
<activity android:name="MyActivity"
android:screenOrientation="landscape"
android:configChanges="keyboardHidden|orientation|screenSize">
...
</activity>
Where MyActivity
is the one you want to stay in landscape.
The android:configChanges=...
line prevents onResume()
, onPause()
from being called when the screen is rotated. Without this line, the rotation will stay as you requested but the calls will still be made.
Note: keyboardHidden
and orientation
are required for < Android 3.2 (API level 13), and all three options are required 3.2 or above, not just orientation
.
Maximum element value in priceValues[] is maxPriceValues :
double[] priceValues = new double[3];
priceValues [0] = 1;
priceValues [1] = 2;
priceValues [2] = 3;
double maxPriceValues = priceValues.Max();
Here's an example in VB.NET
Public Function ShowtheDialog(caption As String, text As String, selStr As String) As String
Dim prompt As New Form()
prompt.Width = 280
prompt.Height = 160
prompt.Text = caption
Dim textLabel As New Label() With { _
.Left = 16, _
.Top = 20, _
.Width = 240, _
.Text = text _
}
Dim textBox As New TextBox() With { _
.Left = 16, _
.Top = 40, _
.Width = 240, _
.TabIndex = 0, _
.TabStop = True _
}
Dim selLabel As New Label() With { _
.Left = 16, _
.Top = 66, _
.Width = 88, _
.Text = selStr _
}
Dim cmbx As New ComboBox() With { _
.Left = 112, _
.Top = 64, _
.Width = 144 _
}
cmbx.Items.Add("Dark Grey")
cmbx.Items.Add("Orange")
cmbx.Items.Add("None")
cmbx.SelectedIndex = 0
Dim confirmation As New Button() With { _
.Text = "In Ordnung!", _
.Left = 16, _
.Width = 80, _
.Top = 88, _
.TabIndex = 1, _
.TabStop = True _
}
AddHandler confirmation.Click, Sub(sender, e) prompt.Close()
prompt.Controls.Add(textLabel)
prompt.Controls.Add(textBox)
prompt.Controls.Add(selLabel)
prompt.Controls.Add(cmbx)
prompt.Controls.Add(confirmation)
prompt.AcceptButton = confirmation
prompt.StartPosition = FormStartPosition.CenterScreen
prompt.ShowDialog()
Return String.Format("{0};{1}", textBox.Text, cmbx.SelectedItem.ToString())
End Function
Sounds like you might want a light box,and since you didnt tag your question with jQuery included is a pure JS example of how to make one.
JS
var opener = document.getElementById("opener");
opener.onclick = function(){
var lightbox = document.getElementById("lightbox"),
dimmer = document.createElement("div");
dimmer.style.width = window.innerWidth + 'px';
dimmer.style.height = window.innerHeight + 'px';
dimmer.className = 'dimmer';
dimmer.onclick = function(){
document.body.removeChild(this);
lightbox.style.visibility = 'hidden';
}
document.body.appendChild(dimmer);
lightbox.style.visibility = 'visible';
lightbox.style.top = window.innerHeight/2 - 50 + 'px';
lightbox.style.left = window.innerWidth/2 - 100 + 'px';
return false;
}
Markup
<div id="lightbox">Testing out the lightbox</div>
<a href="#" id="opener">Click me</a>
CSS
#lightbox{
visibility:hidden;
position:absolute;
background:red;
border:2px solid #3c3c3c;
color:white;
z-index:100;
width: 200px;
height:100px;
padding:20px;
}
.dimmer{
background: #000;
position: absolute;
opacity: .5;
top: 0;
z-index:99;
}
Get fields where a timestamp is greater than date in postgresql:
SELECT * from yourtable
WHERE your_timestamp_field > to_date('05 Dec 2000', 'DD Mon YYYY');
Subtract minutes from timestamp in postgresql:
SELECT * from yourtable
WHERE your_timestamp_field > current_timestamp - interval '5 minutes'
Subtract hours from timestamp in postgresql:
SELECT * from yourtable
WHERE your_timestamp_field > current_timestamp - interval '5 hours'
I fork @Ludwig code and remove necessity of swfobject
.
I just use swfobject code for detect flash version.
/**
* JavaScript Client Detection
* (C) viazenetti GmbH (Christian Ludwig)
*/
(function (window) {
{
var unknown = '-';
// screen
var screenSize = '';
if (screen.width) {
width = (screen.width) ? screen.width : '';
height = (screen.height) ? screen.height : '';
screenSize += '' + width + " x " + height;
}
//browser
var nVer = navigator.appVersion;
var nAgt = navigator.userAgent;
var browser = navigator.appName;
var version = '' + parseFloat(navigator.appVersion);
var majorVersion = parseInt(navigator.appVersion, 10);
var nameOffset, verOffset, ix;
// Opera
if ((verOffset = nAgt.indexOf('Opera')) != -1) {
browser = 'Opera';
version = nAgt.substring(verOffset + 6);
if ((verOffset = nAgt.indexOf('Version')) != -1) {
version = nAgt.substring(verOffset + 8);
}
}
// MSIE
else if ((verOffset = nAgt.indexOf('MSIE')) != -1) {
browser = 'Microsoft Internet Explorer';
version = nAgt.substring(verOffset + 5);
}
// Chrome
else if ((verOffset = nAgt.indexOf('Chrome')) != -1) {
browser = 'Chrome';
version = nAgt.substring(verOffset + 7);
}
// Safari
else if ((verOffset = nAgt.indexOf('Safari')) != -1) {
browser = 'Safari';
version = nAgt.substring(verOffset + 7);
if ((verOffset = nAgt.indexOf('Version')) != -1) {
version = nAgt.substring(verOffset + 8);
}
}
// Firefox
else if ((verOffset = nAgt.indexOf('Firefox')) != -1) {
browser = 'Firefox';
version = nAgt.substring(verOffset + 8);
}
// MSIE 11+
else if (nAgt.indexOf('Trident/') != -1) {
browser = 'Microsoft Internet Explorer';
version = nAgt.substring(nAgt.indexOf('rv:') + 3);
}
// Other browsers
else if ((nameOffset = nAgt.lastIndexOf(' ') + 1) < (verOffset = nAgt.lastIndexOf('/'))) {
browser = nAgt.substring(nameOffset, verOffset);
version = nAgt.substring(verOffset + 1);
if (browser.toLowerCase() == browser.toUpperCase()) {
browser = navigator.appName;
}
}
// trim the version string
if ((ix = version.indexOf(';')) != -1) version = version.substring(0, ix);
if ((ix = version.indexOf(' ')) != -1) version = version.substring(0, ix);
if ((ix = version.indexOf(')')) != -1) version = version.substring(0, ix);
majorVersion = parseInt('' + version, 10);
if (isNaN(majorVersion)) {
version = '' + parseFloat(navigator.appVersion);
majorVersion = parseInt(navigator.appVersion, 10);
}
// mobile version
var mobile = /Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(nVer);
// cookie
var cookieEnabled = (navigator.cookieEnabled) ? true : false;
if (typeof navigator.cookieEnabled == 'undefined' && !cookieEnabled) {
document.cookie = 'testcookie';
cookieEnabled = (document.cookie.indexOf('testcookie') != -1) ? true : false;
}
// system
var os = unknown;
var clientStrings = [
{s:'Windows 10', r:/(Windows 10.0|Windows NT 10.0)/},
{s:'Windows 8.1', r:/(Windows 8.1|Windows NT 6.3)/},
{s:'Windows 8', r:/(Windows 8|Windows NT 6.2)/},
{s:'Windows 7', r:/(Windows 7|Windows NT 6.1)/},
{s:'Windows Vista', r:/Windows NT 6.0/},
{s:'Windows Server 2003', r:/Windows NT 5.2/},
{s:'Windows XP', r:/(Windows NT 5.1|Windows XP)/},
{s:'Windows 2000', r:/(Windows NT 5.0|Windows 2000)/},
{s:'Windows ME', r:/(Win 9x 4.90|Windows ME)/},
{s:'Windows 98', r:/(Windows 98|Win98)/},
{s:'Windows 95', r:/(Windows 95|Win95|Windows_95)/},
{s:'Windows NT 4.0', r:/(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/},
{s:'Windows CE', r:/Windows CE/},
{s:'Windows 3.11', r:/Win16/},
{s:'Android', r:/Android/},
{s:'Open BSD', r:/OpenBSD/},
{s:'Sun OS', r:/SunOS/},
{s:'Linux', r:/(Linux|X11)/},
{s:'iOS', r:/(iPhone|iPad|iPod)/},
{s:'Mac OS X', r:/Mac OS X/},
{s:'Mac OS', r:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh)/},
{s:'QNX', r:/QNX/},
{s:'UNIX', r:/UNIX/},
{s:'BeOS', r:/BeOS/},
{s:'OS/2', r:/OS\/2/},
{s:'Search Bot', r:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/}
];
for (var id in clientStrings) {
var cs = clientStrings[id];
if (cs.r.test(nAgt)) {
os = cs.s;
break;
}
}
var osVersion = unknown;
if (/Windows/.test(os)) {
osVersion = /Windows (.*)/.exec(os)[1];
os = 'Windows';
}
switch (os) {
case 'Mac OS X':
osVersion = /Mac OS X (10[\.\_\d]+)/.exec(nAgt)[1];
break;
case 'Android':
osVersion = /Android ([\.\_\d]+)/.exec(nAgt)[1];
break;
case 'iOS':
osVersion = /OS (\d+)_(\d+)_?(\d+)?/.exec(nVer);
osVersion = osVersion[1] + '.' + osVersion[2] + '.' + (osVersion[3] | 0);
break;
}
var flashVersion = 'no check', d, fv = [];
if (typeof navigator.plugins !== 'undefined' && typeof navigator.plugins["Shockwave Flash"] === "object") {
d = navigator.plugins["Shockwave Flash"].description;
if (d && !(typeof navigator.mimeTypes !== 'undefined' && navigator.mimeTypes["application/x-shockwave-flash"] && !navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin)) { // navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin indicates whether plug-ins are enabled or disabled in Safari 3+
d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1");
fv[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10);
fv[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10);
fv[2] = /[a-zA-Z]/.test(d) ? parseInt(d.replace(/^.*[a-zA-Z]+(.*)$/, "$1"), 10) : 0;
}
} else if (typeof window.ActiveXObject !== 'undefined') {
try {
var a = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
if (a) { // a will return null when ActiveX is disabled
d = a.GetVariable("$version");
if (d) {
d = d.split(" ")[1].split(",");
fv = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
}
}
catch(e) {}
}
if (fv.length) {
flashVersion = fv[0] + '.' + fv[1] + ' r' + fv[2];
}
}
window.jscd = {
screen: screenSize,
browser: browser,
browserVersion: version,
mobile: mobile,
os: os,
osVersion: osVersion,
cookies: cookieEnabled,
flashVersion: flashVersion
};
}(this));
alert(
'OS: ' + jscd.os +' '+ jscd.osVersion + '\n'+
'Browser: ' + jscd.browser +' '+ jscd.browserVersion + '\n' +
'Mobile: ' + jscd.mobile + '\n' +
'Flash: ' + jscd.flashVersion + '\n' +
'Cookies: ' + jscd.cookies + '\n' +
'Screen Size: ' + jscd.screen + '\n\n' +
'Full User Agent: ' + navigator.userAgent
);
The query should be:
(&(objectCategory=user)(memberOf=CN=Distribution Groups,OU=Mybusiness,DC=mydomain.local,DC=com))
You missed & and ()
Adding to unwinds post:
You can send multiple key-value args too.
def myfunc(**kwargs):
# kwargs is a dictionary.
for k,v in kwargs.iteritems():
print "%s = %s" % (k, v)
myfunc(abc=123, efh=456)
# abc = 123
# efh = 456
And you can mix the two:
def myfunc2(*args, **kwargs):
for a in args:
print a
for k,v in kwargs.iteritems():
print "%s = %s" % (k, v)
myfunc2(1, 2, 3, banan=123)
# 1
# 2
# 3
# banan = 123
They must be both declared and called in that order, that is the function signature needs to be *args, **kwargs, and called in that order.
Assuming alphanumeric words, you can use:
Search = ^([A-Za-z0-9]+)$
Replace = able:"\1"
Or, if you just want to highlight the lines and use "Replace All" & "In Selection" (with the same replace):
Search = ^(.+)$
^
points to the start of the line.
$
points to the end of the line.
\1
will be the source match within the parentheses.
i use this code for navbar on bootstrap 3.2.0, the image should be at most 50px high, or else it will bleed the standard bs navbar.
Notice that i purposely do not use the class='navbar-brand' as that introduces padding on the image
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="" href="/"><img src='img/anyWidthx50.png'/></a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Active Link</a></li>
<li><a href="#">More Links</a></li>
</ul>
</div><!-- /.navbar-collapse -->
</div>
</div>
The following adds elements to a list in a loop.
l<-c()
i=1
while(i<100) {
b<-i
l<-c(l,b)
i=i+1
}
The easiest way to get the correct number of hours between two dates (datetimes), even across daylight saving time changes, is to use the difference in Unix timestamps. Unix timestamps are seconds elapsed since 1970-01-01T00:00:00 UTC, ignoring leap seconds (this is OK because you probably don't need this precision, and because it's quite difficult to take leap seconds into account).
The most flexible way to convert a datetime string with optional timezone information into a Unix timestamp is to construct a DateTime object (optionally with a DateTimeZone as a second argument in the constructor), and then call its getTimestamp method.
$str1 = '2006-04-12 12:30:00';
$str2 = '2006-04-14 11:30:00';
$tz1 = new DateTimeZone('Pacific/Apia');
$tz2 = $tz1;
$d1 = new DateTime($str1, $tz1); // tz is optional,
$d2 = new DateTime($str2, $tz2); // and ignored if str contains tz offset
$delta_h = ($d2->getTimestamp() - $d1->getTimestamp()) / 3600;
if ($rounded_result) {
$delta_h = round ($delta_h);
} else if ($truncated_result) {
$delta_h = intval($delta_h);
}
echo "?h: $delta_h\n";
jminix is an embedded web based JMX console. Not sure if it's maintained any longer, but still.
Regarding 3rd definition:
var foo = function foo() { return 5; }
Heres an example which shows how to use possibility of recursive call:
a = function b(i) {
if (i>10) {
return i;
}
else {
return b(++i);
}
}
console.log(a(5)); // outputs 11
console.log(a(10)); // outputs 11
console.log(a(11)); // outputs 11
console.log(a(15)); // outputs 15
Edit: more interesting example with closures:
a = function(c) {
return function b(i){
if (i>c) {
return i;
}
return b(++i);
}
}
d = a(5);
console.log(d(3)); // outputs 6
console.log(d(8)); // outputs 8
You can not directly send an email with a HTML form. You can however send the form to your web server and then generate the email with a server side program written in e.g. PHP.
The other solution is to create a link as you did with the "mailto:". This will open the local email program from the user. And he/she can then send the pre-populated email.
When you decided how you wanted to do it you can ask another (more specific) question on this site. (Or you can search for a solution somewhere on the internet.)
At the end of foo()
, create a Timer
which calls foo()
itself after 10 seconds.
Because, Timer
create a new thread
to call foo()
.
You can do other stuff without being blocked.
import time, threading
def foo():
print(time.ctime())
threading.Timer(10, foo).start()
foo()
#output:
#Thu Dec 22 14:46:08 2011
#Thu Dec 22 14:46:18 2011
#Thu Dec 22 14:46:28 2011
#Thu Dec 22 14:46:38 2011
Strtr
replaces single characters instead of strings, so it's a good solution for this example. Supposedly strtr
is faster than str_replace
(but for this use case they're both immeasurably fast).
echo strtr('Alex Newton',' ','_');
//outputs: Alex_Newton
For long long (or __int64) using MSVS, you should use %I64d:
__int64 a;
time_t b;
...
fprintf(outFile,"%I64d,%I64d\n",a,b); //I is capital i
For a more general solution, for JAXB-XML serialization of any top level list , which only requires 1 new class to be written, check out the solution given in this question:
Is it possible to programmatically configure JAXB?
public class Wrapper<T> {
private List<T> items = new ArrayList<T>();
@XmlAnyElement(lax=true)
public List<T> getItems() {
return items;
}
}
//JAXBContext is thread safe and so create it in constructor or
//setter or wherever:
...
JAXBContext jc = JAXBContext.newInstance(Wrapper.class, clazz);
...
public String marshal(List<T> things, Class clazz) {
//configure JAXB and marshaller
Marshaller m = jc.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
//Create wrapper based on generic list of objects
Wrapper<T> wrapper = new Wrapper<T>(things);
JAXBElement<Wrapper> wrapperJAXBElement = new JAXBElement<Wrapper>(new QName(clazz.getSimpleName().toLowerCase()+"s"), Wrapper.class, wrapper);
StringWriter result = new StringWriter();
//marshal!
m.marshal(wrapperJAXBElement, result);
return result.toString();
}
The solution was to add these flags to JVM command line when Tomcat is started:
-XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled
You can do that by shutting down the tomcat service, then going into the Tomcat/bin directory and running tomcat6w.exe. Under the "Java" tab, add the arguments to the "Java Options" box. Click "OK" and then restart the service.
If you get an error the specified service does not exist as an installed service you should run:
tomcat6w //ES//servicename
where servicename is the name of the server as viewed in services.msc
Source: orx's comment on Eric's Agile Answers.
I've had this problem when I use multiple proyects, the start proyect with web.config and app.config for EntityFramework project.
for avoid this problem you must:
Instead of using ellipsis to solve the problem of overflowing text, I found that a disabled and styled input looked better and still allows the user to view and select the entire string if they need to.
<input disabled='disabled' style="border: 0; padding: 0; margin: 0" />
It looks like a text field but is highlight-able so more user friendly
You need to do deep search if you use groups in options:
options={[
{ value: 'all', label: 'All' },
{
label: 'Specific',
options: [
{ value: 'one', label: 'One' },
{ value: 'two', label: 'Two' },
{ value: 'three', label: 'Three' },
],
},
]}
const deepSearch = (options, value, tempObj = {}) => {
if (options && value != null) {
options.find((node) => {
if (node.value === value) {
tempObj.found = node;
return node;
}
return deepSearch(node.options, value, tempObj);
});
if (tempObj.found) {
return tempObj.found;
}
}
return undefined;
};
Map default.aspx as HttpHandler route and redirect to CreateThings.aspx from within the HttpHandler.
<add verb="GET" path="default.aspx" type="RedirectHandler"/>
Make sure Default.aspx does not exists physically at your application root. If it exists physically the HttpHandler will not be given any chance to execute. Physical file overrides HttpHandler mapping.
Moreover you can re-use this for pages other than default.aspx.
<add verb="GET" path="index.aspx" type="RedirectHandler"/>
//RedirectHandler.cs in your App_Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for RedirectHandler
/// </summary>
public class RedirectHandler : IHttpHandler
{
public RedirectHandler()
{
//
// TODO: Add constructor logic here
//
}
#region IHttpHandler Members
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
context.Response.Redirect("CreateThings.aspx");
context.Response.End();
}
#endregion
}
When using instanceof
, you need to know the class of B
at compile time. When using isAssignableFrom()
it can be dynamic and change during runtime.
Use the ieee.numeric_std
library, and the appropriate vector type for the numbers you are working on (unsigned
or signed
).
Then the operators are sla
/sra
for arithmetic shifts (ie fill with sign bit on right shifts and lsb on left shifts) and sll
/srl
for logical shifts (ie fill with '0's).
You pass a parameter to the operator to define the number of bits to shift:
A <= B srl 2; -- logical shift right 2 bits
I have no idea what I was writing above (thanks to Val for pointing that out!)
Of course the correct way to shift signed
and unsigned
types is with the shift_left
and shift_right
functions defined in ieee.numeric_std
.
The shift and rotate operators sll
, ror
etc are for vectors of boolean
, bit
or std_ulogic
, and can have interestingly unexpected behaviour in that the arithmetic shifts duplicate the end-bit even when shifting left.
And much more history can be found here:
http://jdebp.eu./FGA/bit-shifts-in-vhdl.html
However, the answer to the original question is still
sig <= tmp sll number_of_bits;
If the imagestr was bitmap data (which we now know it isn't) you could use this
imagestr
is the base64 encoded string
width
is the width of the image
height
is the height of the image
from PIL import Image
from base64 import decodestring
image = Image.fromstring('RGB',(width,height),decodestring(imagestr))
image.save("foo.png")
Since the imagestr is just the encoded png data
from base64 import decodestring
with open("foo.png","wb") as f:
f.write(decodestring(imagestr))
Are you looking for something like this?
SELECT CASE WHEN LEFT(created_ts, 1) LIKE '[0-9]'
THEN CONVERT(VARCHAR(10), CONVERT(datetime, created_ts, 1), 101)
ELSE CONVERT(VARCHAR(10), CONVERT(datetime, created_ts, 109), 101)
END created_ts
FROM table1
Output:
| CREATED_TS | |------------| | 02/20/2012 | | 11/29/2012 | | 02/20/2012 | | 11/29/2012 | | 02/20/2012 | | 11/29/2012 | | 11/16/2011 | | 02/20/2012 | | 11/29/2012 |
Here is SQLFiddle demo
You can use inline css :
<td style = "text-align: center;">
If it's a DNS problem, you could try:
If this doesn't fix it, you could try editing the hosts file located here:
C:\Windows\System32\drivers\etc\hosts
And ensure that this line (and no other line referencing localhost) is in there:
127.0.0.1 localhost
I was also getting this issue in springboot project and added @Transactional in my class and it is working.
import org.springframework.transaction.annotation.Transactional;
@Transactional
public class SearchRepo {
---
}
read-host -assecurestring | convertfrom-securestring | out-file C:\securestring.txt
$pass = cat C:\securestring.txt | convertto-securestring
$mycred = new-object -typename System.Management.Automation.PSCredential -argumentlist "test",$pass
$mycred.GetNetworkCredential().Password
Be very careful with storing passwords this way... it's not as secure as ...
um responsive is simple
display:table-cell
max-width:700px
do {display:block; width:100%; clear:both}
and that's it no absolute divs ever; divs needs to be 100% then max-width: - desired width -
for inner framming. A true responsive sites has less than 9 lines of css anything passed that you are in a world of shit and over complicated things.
PS : reset.css
style sheets are what makes css blinds there was a logical reason why they gave default styles in the first place.
CREATE PROCEDURE sp_generate_insertscripts
(
@TABLENAME VARCHAR(MAX),
@FILTER_CONDITION VARCHAR(MAX)='' -- where TableId = 5 or some value
)
AS
BEGIN
SET NOCOUNT ON
DECLARE @TABLE_NAME VARCHAR(MAX),
@CSV_COLUMN VARCHAR(MAX),
@QUOTED_DATA VARCHAR(MAX),
@TEXT VARCHAR(MAX),
@FILTER VARCHAR(MAX)
SET @TABLE_NAME=@TABLENAME
SELECT @FILTER=@FILTER_CONDITION
SELECT @CSV_COLUMN=STUFF
(
(
SELECT ',['+ NAME +']' FROM sys.all_columns
WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND
is_identity!=1 FOR XML PATH('')
),1,1,''
)
SELECT @QUOTED_DATA=STUFF
(
(
SELECT ' ISNULL(QUOTENAME('+NAME+','+QUOTENAME('''','''''')+'),'+'''NULL'''+')+'','''+'+' FROM sys.all_columns
WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND
is_identity!=1 FOR XML PATH('')
),1,1,''
)
SELECT @TEXT='SELECT ''INSERT INTO '+@TABLE_NAME+'('+@CSV_COLUMN+')VALUES('''+'+'+SUBSTRING(@QUOTED_DATA,1,LEN(@QUOTED_DATA)-5)+'+'+''')'''+' Insert_Scripts FROM '+@TABLE_NAME + @FILTER
--SELECT @CSV_COLUMN AS CSV_COLUMN,@QUOTED_DATA AS QUOTED_DATA,@TEXT TEXT
EXECUTE (@TEXT)
SET NOCOUNT OFF
END
The difference is that you can't have a reference to an immutable collection which allows changes. Unmodifiable collections are unmodifiable through that reference, but some other object may point to the same data through which it can be changed.
e.g.
List<String> strings = new ArrayList<String>();
List<String> unmodifiable = Collections.unmodifiableList(strings);
unmodifiable.add("New string"); // will fail at runtime
strings.add("Aha!"); // will succeed
System.out.println(unmodifiable);
/appointments?users=1d1,1d2..
is fine. It's pretty much your only sensible option since you can't pass in a body with a GET.
DECLARE @TABLE TABLE
(RowNo INT,ScripName VARCHAR(10),ScripCode VARCHAR(10)
,Price VARCHAR(10))
INSERT INTO @TABLE VALUES
(1,'20 MICRONS ','533022','39')
SELECT ColumnName,ColumnValue from @Table
Unpivot(ColumnValue For ColumnName IN (ScripName,ScripCode,Price)) AS H
For executeUpdate statements against a DB2 for z/OS server, the value that is returned depends on the type of SQL statement that is being executed:
For an SQL statement that can have an update count, such as an INSERT, UPDATE, or DELETE statement, the returned value is the number of affected rows. It can be:
A positive number, if a positive number of rows are affected by the operation, and the operation is not a mass delete on a segmented table space.
0, if no rows are affected by the operation.
-1, if the operation is a mass delete on a segmented table space.
For a DB2 CALL statement, a value of -1 is returned, because the DB2 database server cannot determine the number of affected rows. Calls to getUpdateCount or getMoreResults for a CALL statement also return -1. For any other SQL statement, a value of -1 is returned.
You do not need to keep the system images unless you want to use the emulator on your desktop. Along with it you can remove other unwanted stuff to clear disk space.
Adding as an answer to my own question as I've had to narrate this to people in my team more than a few times. Hence this answer as a reference to share with other curious ones.
In the last few weeks there were several colleagues who asked me how to safely get rid of the unwanted stuff to release disk space (most of them were beginners). I redirected them to this question but they came back to me for steps. So for android beginners here is a step by step guide to safely remove unwanted stuff.
Note
First, be sure you are not going to use emulators and will always do you development on a physical device. In case you are going to need emulators, note down the API Levels and type of emulators you'll need. Do not remove those. For the rest follow the below steps:
Steps to safely clear up unwanted stuff from Android SDK folder on the disk
- Open the Stand Alone Android SDK Manager. To open do one of the following:
.
- Uncheck all items ending with "System Image". Each API Level will have more than a few. In case you need some and have figured the list already leave them checked to avoid losing them and having to re-download.
.
- Optional (may help save a marginally more amount of disk space): To free up some more space, you can also entirely uncheck unrequired API levels. Be careful again to avoid re-downloading something you are actually using in other projects.
.
- In the end make sure you have at least the following (check image below) for the remaining API levels to be able to seamlessly work with your physical device.
In the end the clean android sdk installed components should look something like this in the SDK manager.
I wrote a blog post about it: http://blogs.msdn.com/kirillosenkov/archive/2009/01/31/foreach.aspx
You can vote here if you'd like to see this method in .NET 4.0: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=279093
I have tried a few of the answers above and note that some of them are version dependent and do not work in version 3.7.
I also note that since 3.6 all dictionaries are ordered by the sequence in which items are inserted.
Despite dictionaries being ordered since 3.6 some of the statements you expect to work with ordered structures don't seem to work.
The answer to the OP question that worked best for me.
itr = iter(dic.items())
lst = [next(itr) for i in range(3)]
On Ubuntu you should be able to install the necessary PDO parts from apt using sudo apt-get install php5-mysql
There is no limitation between using PDO and mysql_ simultaneously. You will however need to create two connections to your DB, one with mysql_ and one using PDO.
The only easy way to do this is to use snprintf
to print to a buffer that's long enough to hold the entire, exact value, then truncate it as a string. Something like:
char buf[2*(DBL_MANT_DIG + DBL_MAX_EXP)];
snprintf(buf, sizeof buf, "%.*f", (int)sizeof buf, x);
char *p = strchr(buf, '.'); // beware locale-specific radix char, though!
p[2+1] = 0;
puts(buf);
When you say
(a['x']==1) and (a['y']==10)
You are implicitly asking Python to convert (a['x']==1)
and (a['y']==10)
to boolean values.
NumPy arrays (of length greater than 1) and Pandas objects such as Series do not have a boolean value -- in other words, they raise
ValueError: The truth value of an array is ambiguous. Use a.empty, a.any() or a.all().
when used as a boolean value. That's because its unclear when it should be True or False. Some users might assume they are True if they have non-zero length, like a Python list. Others might desire for it to be True only if all its elements are True. Others might want it to be True if any of its elements are True.
Because there are so many conflicting expectations, the designers of NumPy and Pandas refuse to guess, and instead raise a ValueError.
Instead, you must be explicit, by calling the empty()
, all()
or any()
method to indicate which behavior you desire.
In this case, however, it looks like you do not want boolean evaluation, you want element-wise logical-and. That is what the &
binary operator performs:
(a['x']==1) & (a['y']==10)
returns a boolean array.
By the way, as alexpmil notes,
the parentheses are mandatory since &
has a higher operator precedence than ==
.
Without the parentheses, a['x']==1 & a['y']==10
would be evaluated as a['x'] == (1 & a['y']) == 10
which would in turn be equivalent to the chained comparison (a['x'] == (1 & a['y'])) and ((1 & a['y']) == 10)
. That is an expression of the form Series and Series
.
The use of and
with two Series would again trigger the same ValueError
as above. That's why the parentheses are mandatory.
From the Mongo documentation:
The mongoexport utility takes a collection and exports to either JSON or CSV. You can specify a filter for the query, or a list of fields to output
Read more here: http://www.mongodb.org/display/DOCS/mongoexport
Try to use the <font>
tag
?<table>
<thead>
<tr>
<th><font color="#FFF">Header 1</font></th>
<th><font color="#FFF">Header 1</font></th>
<th><font color="#FFF">Header 1</font></th>
</tr>
</thead>
<tbody>
<tr>
<td>blah blah</td>
<td>blah blah</td>
<td>blah blah</td>
</tr>
</tbody>
</table>
But I think this should work, too:
?<table>
<thead>
<tr>
<th color="#FFF">Header 1</th>
<th color="#FFF">Header 1</th>
<th color="#FFF">Header 1</th>
</tr>
</thead>
<tbody>
<tr>
<td>blah blah</td>
<td>blah blah</td>
<td>blah blah</td>
</tr>
</tbody>
</table>
EDIT:
Crossbrowser solution:
use capitals in HEX-color.
<th bgcolor="#5D7B9D" color="#FFFFFF"><font color="#FFFFFF">Header 1</font></th>
Using Erik's answer, as a starting point. I found a simpler solution that worked for me.
In my ng-click function I have:
var the_string = 'lifeMeaning';
if ($scope[the_string] === undefined) {
//Valid in my application for first usage
$scope[the_string] = true;
} else {
$scope[the_string] = !$scope[the_string];
}
//$scope.$apply
I've tested it with and without $scope.$apply. Works correctly without it!
Use this to list Grantee too and remove (PG_monitor and Public) for Postgres PaaS Azure.
SELECT grantee,table_catalog, table_schema, table_name, privilege_type
FROM information_schema.table_privileges
WHERE grantee not in ('pg_monitor','PUBLIC');
Loads of answers here, but haven't seen the one I use:
input[type="text"]:read-only { color: blue; }
Note the dash in the pseudo selector. If the input is readonly="false"
it'll catch that too since this selector catches the presence of readonly regardless of the value. Technically false
is invalid according to specs, but the internet is not a perfect world. If you need to cover that case, you can do this:
input[type="text"]:read-only:not([read-only="false"]) { color: blue; }
textarea
works the same way:
textarea:read-only:not([read-only="false"]) { color: blue; }
Keep in mind that html now supports not only type="text"
, but a slew of other textual types such a number
, tel
, email
, date
, time
, url
, etc. Each would need to be added to the selector.
In front-end JavaScript/HTML, you can load a binary file as an image, you do not have to convert to base64:
<img src="http://engci.nabisco.com/artifactory/repo/folder/my-image">
my-image is a binary image file. This will load just fine.
Unfortunately, np.polynomial.polynomial.polyfit
returns the coefficients in the opposite order of that for np.polyfit
and np.polyval
(or, as you used np.poly1d
). To illustrate:
In [40]: np.polynomial.polynomial.polyfit(x, y, 4)
Out[40]:
array([ 84.29340848, -100.53595376, 44.83281408, -8.85931101,
0.65459882])
In [41]: np.polyfit(x, y, 4)
Out[41]:
array([ 0.65459882, -8.859311 , 44.83281407, -100.53595375,
84.29340846])
In general: np.polynomial.polynomial.polyfit
returns coefficients [A, B, C]
to A + Bx + Cx^2 + ...
, while np.polyfit
returns: ... + Ax^2 + Bx + C
.
So if you want to use this combination of functions, you must reverse the order of coefficients, as in:
ffit = np.polyval(coefs[::-1], x_new)
However, the documentation states clearly to avoid np.polyfit
, np.polyval
, and np.poly1d
, and instead to use only the new(er) package.
You're safest to use only the polynomial package:
import numpy.polynomial.polynomial as poly
coefs = poly.polyfit(x, y, 4)
ffit = poly.polyval(x_new, coefs)
plt.plot(x_new, ffit)
Or, to create the polynomial function:
ffit = poly.Polynomial(coefs) # instead of np.poly1d
plt.plot(x_new, ffit(x_new))
Try absolute positioning:
<div style="position:relative;width:100%;">
<div id="help" style="
position:absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index:1;">
<img src="/portfolio/space_1_header.png" border="0" style="width:100%;">
</div>
</div>
I wrote a simple node script for deleting messages from public/private channels and chats. You can modify and use it.
https://gist.github.com/firatkucuk/ee898bc919021da621689f5e47e7abac
First, modify your token in the scripts configuration section then run the script:
node ./delete-slack-messages CHANNEL_ID
Also, the channel ID can be seen in the browser URL when you open slack in the browser. e.g.
https://mycompany.slack.com/messages/MY_CHANNEL_ID/
or
https://app.slack.com/client/WORKSPACE_ID/MY_CHANNEL_ID
Note: You can play back the audio data only to the standard output device.
Currently, that is the mobile device speaker or a Bluetooth headset. You
cannot play sound files in the conversation audio during a call.
See official link
http://developer.android.com/guide/topics/media/mediaplayer.html
Well its a sequential process. The Request first treat by FrontController and then moves towards our own customize controller with @Controller annotation.
but our controller method is binding bean using modelattribute and we are also performing few validations on bean values.
so instead of moving the request to our controller class, FrontController moves it towards one interceptor which creates the temp object of our bean and the validate the values. if validation successful then bind the temp obj values with our actual bean which is stored in @ModelAttribute otherwise if validation fails it does not bind and moves the resp towards error page or wherever u want.
Buffers are always of fixed size, there is no built in way to resize them dynamically, so your approach of copying it to a larger Buffer is the only way.
However, to be more efficient, you could make the Buffer larger than the original contents, so it contains some "free" space where you can add data without reallocating the Buffer. That way you don't need to create a new Buffer and copy the contents on each append operation.
Revisiting this page and I have more information to share with others.
Debugging environment (using Visual Studio)
1a) Stephen Walter's link to set the startup page on MVC using the project properties is only applicable when you are debugging your MVC application.
1b) Right mouse click on the .aspx page in Solution Explorer and select the "Set As Start Page" behaves the same.
Note: in both the above cases, the startup page setting is only recognised by your Visual Studio Development Server. It is not recognised by your deployed server.
Deployed environment
2a) To set the startup page, assuming that you have not change any of the default routings, change the content of /Views/Home/Index.aspx to do a "Server.Transfer" or a "Response.Redirect" to your desired page.
2b) Change your default routing in your global.asax.cs to your desired page.
Are there any other options that the readers are aware of? Which of the above (including your own option) would be your preferred solution (and please share with us why)?
Ok so this is the combination that worked for me when I had this problem on one of my websites:
html {
height: 100%;
}
body {
overflow-x: hidden;
}
Dim x as date
x = dr("appdate")
appdate = x.tostring("dd/MM/yyyy")
dr is the variable of datareader
You can use d6tstack which creates the table for you and is faster than pd.to_sql() because it uses native DB import commands. It supports Postgres as well as MYSQL and MS SQL.
import pandas as pd
df = pd.read_csv('table.csv')
uri_psql = 'postgresql+psycopg2://usr:pwd@localhost/db'
d6tstack.utils.pd_to_psql(df, uri_psql, 'table')
It is also useful for importing multiple CSVs, solving data schema changes and/or preprocess with pandas (eg for dates) before writing to db, see further down in examples notebook
d6tstack.combine_csv.CombinerCSV(glob.glob('*.csv'),
apply_after_read=apply_fun).to_psql_combine(uri_psql, 'table')
Your execution plan should make this clear; the JOIN takes precedence, after which the results are filtered.
Look at the filter
function.
If you just need a 1-pole low-pass filter, it's
xfilt = filter(a, [1 a-1], x);
where a = T/τ, T = the time between samples, and τ (tau) is the filter time constant.
Here's the corresponding high-pass filter:
xfilt = filter([1-a a-1],[1 a-1], x);
If you need to design a filter, and have a license for the Signal Processing Toolbox, there's a bunch of functions, look at fvtool and fdatool.
Transparency can be coded in the color argument as well. It is just two more hex numbers coding a transparency between 0 (fully transparent) and 255 (fully visible). I once wrote this function to add transparency to a color vector, maybe it is usefull here?
addTrans <- function(color,trans)
{
# This function adds transparancy to a color.
# Define transparancy with an integer between 0 and 255
# 0 being fully transparant and 255 being fully visable
# Works with either color and trans a vector of equal length,
# or one of the two of length 1.
if (length(color)!=length(trans)&!any(c(length(color),length(trans))==1)) stop("Vector lengths not correct")
if (length(color)==1 & length(trans)>1) color <- rep(color,length(trans))
if (length(trans)==1 & length(color)>1) trans <- rep(trans,length(color))
num2hex <- function(x)
{
hex <- unlist(strsplit("0123456789ABCDEF",split=""))
return(paste(hex[(x-x%%16)/16+1],hex[x%%16+1],sep=""))
}
rgb <- rbind(col2rgb(color),trans)
res <- paste("#",apply(apply(rgb,2,num2hex),2,paste,collapse=""),sep="")
return(res)
}
Some examples:
cols <- sample(c("red","green","pink"),100,TRUE)
# Fully visable:
plot(rnorm(100),rnorm(100),col=cols,pch=16,cex=4)
# Somewhat transparant:
plot(rnorm(100),rnorm(100),col=addTrans(cols,200),pch=16,cex=4)
# Very transparant:
plot(rnorm(100),rnorm(100),col=addTrans(cols,100),pch=16,cex=4)
See from How to Replace String in File works in a simple way and is an answer that works with replace
fin = open("data.txt", "rt")
fout = open("out.txt", "wt")
for line in fin:
fout.write(line.replace('pyton', 'python'))
fin.close()
fout.close()
We can use this:
DELETE FROM table_name WHERE date_column <
CAST(CONVERT(char(8), (DATEADD(day,-30,GETDATE())), 112) AS datetime)
But a better option is to use:
DELETE FROM table_name WHERE DATEDIFF(dd, date_column, GETDATE()) > 30
The former is not sargable (i.e. functions on the right side of the expression so it can’t use index) and takes 30 seconds, the latter is sargable and takes less than a second.
This is not mentioned in you post but I suspect you are initiating an SSL connection from the browser to Apache, where VirtualHosts are configured, and Apache does a revese proxy to your Tomcat.
There is a serious bug in (some versions ?) of IE that sends the 'wrong' host information in an SSL connection (see EDIT below) and confuses the Apache VirtualHosts. In short the server name presented is the one of the reverse DNS resolution of the IP, not the one in the URL.
The workaround is to have one IP address per SSL virtual hosts/server name. Is short, you must end up with something like
1 server name == 1 IP address == 1 certificate == 1 Apache Virtual Host
EDIT
Though the conclusion is correct, the identification of the problem is better described here http://en.wikipedia.org/wiki/Server_Name_Indication
Validate the INPUT.
$time = strtotime($_POST['dateFrom']);
if ($time) {
$new_date = date('Y-m-d', $time);
echo $new_date;
} else {
echo 'Invalid Date: ' . $_POST['dateFrom'];
// fix it.
}
This is more efficient as it does not run "cp" multiple times:
find -name '*FooBar*' -print0 | xargs -0 cp -t ~/foo/bar
Just took a look over the mustache docs and they support "inverted sections" in which they state
they (inverted sections) will be rendered if the key doesn't exist, is false, or is an empty list
http://mustache.github.io/mustache.5.html#Inverted-Sections
{{#value}}
value is true
{{/value}}
{{^value}}
value is false
{{/value}}
That should work if the dates you saved in the DB are without time (just year, month, day).
Chances are that the dates you saved were new Date()
, which includes the time components. To query those times you need to create a date range that includes all moments in a day.
db.posts.find({ //query today up to tonight
created_on: {
$gte: new Date(2012, 7, 14),
$lt: new Date(2012, 7, 15)
}
})
For Chrome/Safari/Firefox you could add a display: block
and use a negative margin to compensate the offset, like:
a[name] {
display: block;
padding-top: 90px;
margin-top: -90px;
}
See example http://codepen.io/swed/pen/RrZBJo
Problem is that while runtime generic type is erased so new E[10]
would be equivalent to new Object[10]
.
This would be dangerous because it would be possible to put in array other data than of E
type. That is why you need to explicitly say that type you want by either
E[]
array, or componentType
argiment.$animals = array('--Select Animal--', 'Cat', 'Dog', 'Cow');
$selected_key = $_POST['animal'];
$selected_val = $animals[$_POST['animal']];
Use your $animals list to generate your dropdown list; you now can get the key & the value of that key.
Just use the &&
operator like you would with any other statement that you need to do boolean logic.
if (useAdditionalClauses)
{
results = results.Where(
o => o.OrderStatus == OrderStatus.Open
&& o.CustomerID == customerID)
}
I assume that you want them sorted by something else also, to get a consistent ordering between all items where AVC is the same. For example by name:
var sortedList = list.OrderBy(x => c.AVC).ThenBy(x => x.Name).ToList();
For small files and using only python built-ins, you can use the following one-liner:
with open(source, 'rb') as src, open(dest, 'wb') as dst: dst.write(src.read())
As @maxschlepzig mentioned in the comments below, this is not optimal way for applications where the file is too large or when memory is critical, thus Swati's answer should be preferred.
I know the question is for JUnit4, but if you happen to be stuck at JUnit3, you could create a short utility function like that:
private void assertArrayEquals(Object[] esperado, Object[] real) {
assertEquals(Arrays.asList(esperado), Arrays.asList(real));
}
In JUnit3, this is better than directly comparing the arrays, since it will detail exactly which elements are different.
If you want to open it for a range and for a protocol
ufw allow 11200:11299/tcp
ufw allow 11200:11299/udp