Use the class URLEncoder:
URLEncoder.encode(String s, String enc)
Where :
s - String to be translated.
enc - The name of a supported character encoding.
Standard charsets:
US-ASCII Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set ISO-8859-1 ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1
UTF-8 Eight-bit UCS Transformation Format
UTF-16BE Sixteen-bit UCS Transformation Format, big-endian byte order
UTF-16LE Sixteen-bit UCS Transformation Format, little-endian byte order
UTF-16 Sixteen-bit UCS Transformation Format, byte order identified by an optional byte-order mark
Example:
import java.net.URLEncoder;
String stringEncoded = URLEncoder.encode(
"This text must be encoded! aeiou áéíóú ñ, peace!", "UTF-8");
With ObsoleteAttribute
you can to show the deprecated method.
Obsolete attribute has three constructor:
[Obsolete]:
is a no parameter constructor and is a default using this attribute.[Obsolete(string message)]:
in this format you can getmessage
of why this method is deprecated.[Obsolete(string message, bool error)]:
in this format message is very explicit buterror
means, in compilation time, compiler must be showing error and cause to fail compiling or not.
// max size constraint
CGSize maximumLabelSize = CGSizeMake(184, FLT_MAX)
// font
UIFont *font = [UIFont fontWithName:TRADE_GOTHIC_REGULAR size:20.0f];
// set paragraph style
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
// dictionary of attributes
NSDictionary *attributes = @{NSFontAttributeName:font,
NSParagraphStyleAttributeName: paragraphStyle.copy};
CGRect textRect = [string boundingRectWithSize: maximumLabelSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil];
CGSize expectedLabelSize = CGSizeMake(ceil(textRect.size.width), ceil(textRect.size.height));
If you are using Hibernate 5.2 and above then you can use this:
private static StandardServiceRegistry registry;
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
try {
// Creating a registry
registry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
// Create the MetadataSources
MetadataSources sources = new MetadataSources(registry);
// Create the Metadata
Metadata metadata = sources.getMetadataBuilder().build();
// Create SessionFactory
sessionFactory = metadata.getSessionFactoryBuilder().build();
} catch (Exception e) {
e.printStackTrace();
if (registry != null) {
StandardServiceRegistryBuilder.destroy(registry);
}
}
}
return sessionFactory;
}
//To shut down
public static void shutdown() {
if (registry != null) {
StandardServiceRegistryBuilder.destroy(registry);
}
}
NSLog(@"%@",[[UIDevice currentDevice]identifierForVendor]);
We just have to use @
in front of the deprecated function. No need to change anything as mentioned in above posts. For example: if(!@session_is_registered("username")){ }
. Just put @
and problem is solved.
Deprecated in general means "don't use it".
A deprecated function may or may not work, but it is not guaranteed to work.
Yes, Google Custom Search has now replaced the old Search API, but you can still use Google Custom Search to search the entire web, although the steps are not obvious from the Custom Search setup.
To create a Google Custom Search engine that searches the entire web:
Now your custom search engine will search the entire web.
Pricing
Source: https://developers.google.com/custom-search/json-api/v1/overview#Pricing
Vector
synchronizes on each individual operation. That's almost never what you want to do.
Generally you want to synchronize a whole sequence of operations. Synchronizing individual operations is both less safe (if you iterate over a Vector
, for instance, you still need to take out a lock to avoid anyone else changing the collection at the same time, which would cause a ConcurrentModificationException
in the iterating thread) but also slower (why take out a lock repeatedly when once will be enough)?
Of course, it also has the overhead of locking even when you don't need to.
Basically, it's a very flawed approach to synchronization in most situations. As Mr Brian Henk pointed out, you can decorate a collection using the calls such as Collections.synchronizedList
- the fact that Vector
combines both the "resized array" collection implementation with the "synchronize every operation" bit is another example of poor design; the decoration approach gives cleaner separation of concerns.
As for a Stack
equivalent - I'd look at Deque
/ArrayDeque
to start with.
For python 3, just write below codes to ignore all warnings.
from warnings import filterwarnings
filterwarnings("ignore")
Why is this happening?
The entire ext/mysql
PHP extension, which provides all functions named with the prefix mysql_
, was officially deprecated in PHP v5.5.0 and removed in PHP v7.
It was originally introduced in PHP v2.0 (November 1997) for MySQL v3.20, and no new features have been added since 2006. Coupled with the lack of new features are difficulties in maintaining such old code amidst complex security vulnerabilities.
The manual has contained warnings against its use in new code since June 2011.
How can I fix it?
As the error message suggests, there are two other MySQL extensions that you can consider: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql
. Both have been in PHP core since v5.0, so if you're using a version that is throwing these deprecation errors then you can almost certainly just start using them right away—i.e. without any installation effort.
They differ slightly, but offer a number of advantages over the old extension including API support for transactions, stored procedures and prepared statements (thereby providing the best way to defeat SQL injection attacks). PHP developer Ulf Wendel has written a thorough comparison of the features.
Hashphp.org has an excellent tutorial on migrating from ext/mysql
to PDO.
I understand that it's possible to suppress deprecation errors by setting
error_reporting
inphp.ini
to excludeE_DEPRECATED
:error_reporting = E_ALL ^ E_DEPRECATED
What will happen if I do that?
Yes, it is possible to suppress such error messages and continue using the old ext/mysql
extension for the time being. But you really shouldn't do this—this is a final warning from the developers that the extension may not be bundled with future versions of PHP (indeed, as already mentioned, it has been removed from PHP v7). Instead, you should take this opportunity to migrate your application now, before it's too late.
Note also that this technique will suppress all E_DEPRECATED
messages, not just those to do with the ext/mysql
extension: therefore you may be unaware of other upcoming changes to PHP that would affect your application code. It is, of course, possible to only suppress errors that arise on the expression at issue by using PHP's error control operator—i.e. prepending the relevant line with @
—however this will suppress all errors raised by that expression, not just E_DEPRECATED
ones.
You are starting a new project.
There is absolutely no reason to use ext/mysql
—choose one of the other, more modern, extensions instead and reap the rewards of the benefits they offer.
You have (your own) legacy codebase that currently depends upon ext/mysql
.
It would be wise to perform regression testing: you really shouldn't be changing anything (especially upgrading PHP) until you have identified all of the potential areas of impact, planned around each of them and then thoroughly tested your solution in a staging environment.
Following good coding practice, your application was developed in a loosely integrated/modular fashion and the database access methods are all self-contained in one place that can easily be swapped out for one of the new extensions.
Spend half an hour rewriting this module to use one of the other, more modern, extensions; test thoroughly. You can later introduce further refinements to reap the rewards of the benefits they offer.
The database access methods are scattered all over the place and cannot easily be swapped out for one of the new extensions.
Consider whether you really need to upgrade to PHP v5.5 at this time.
You should begin planning to replace ext/mysql
with one of the other, more modern, extensions in order that you can reap the rewards of the benefits they offer; you might also use it as an opportunity to refactor your database access methods into a more modular structure.
However, if you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.
You are using a third party project that depends upon ext/mysql
.
Consider whether you really need to upgrade to PHP v5.5 at this time.
Check whether the developer has released any fixes, workarounds or guidance in relation to this specific issue; or, if not, pressure them to do so by bringing this matter to their attention. If you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.
It is absolutely essential to perform regression testing.
This method was
deprecatedin API level 24.
You should use FROM_HTML_MODE_LEGACY
Separate block-level elements with blank lines (two newline characters) in between. This is the legacy behavior prior to N.
Code
if (Build.VERSION.SDK_INT >= 24)
{
etOBJ.setText(Html.fromHtml("Intellij \n Amiyo",Html.FROM_HTML_MODE_LEGACY));
}
else
{
etOBJ.setText(Html.fromHtml("Intellij \n Amiyo"));
}
For Kotlin
fun setTextHTML(html: String): Spanned
{
val result: Spanned = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY)
} else {
Html.fromHtml(html)
}
return result
}
Call
txt_OBJ.text = setTextHTML("IIT Amiyo")
I tend not to use the .on() syntax, if not necessary. For example you can migrate easier like this:
old:
$('.myButton').live('click', function);
new:
$('.myButton').click(function)
Here is a list of valid event handlers: https://api.jquery.com/category/forms/
Implement both deprecated and non-deprecated methods like below. First one is to handle API level 21 and higher, second one is handle lower than API level 21
webViewClient = object : WebViewClient() {
.
.
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
parseUri(request?.url)
return true
}
@SuppressWarnings("deprecation")
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
parseUri(Uri.parse(url))
return true
}
}
Take a look at the @Deprecated
annotation.
You need to use ContextCompat.getColor(), which is part of the Support V4 Library (so it will work for all the previous API).
ContextCompat.getColor(context, R.color.my_color)
As specified in the documentation, "Starting in M, the returned color will be styled for the specified Context's theme". SO no need to worry about it.
You can add the Support V4 library by adding the following to the dependencies array inside your app build.gradle:
compile 'com.android.support:support-v4:23.0.1'
new GregorianCalendar(1985, Calendar.JANUARY, 1).getTime();
(the pre-Java-8 way)
I have used
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Firebase Push Notification")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
android developers documentation says : "Updated the AppCompatActivity as the base class for activities that use the support library action bar features. This class replaces the deprecated ActionBarActivity."
checkout changes for Android Support Library, revision 22.1.0 (April 2015)
Here is more information regarding replacing ereg_replace with preg_replace
This warning is displayed because a new extension has appeared. It suppouse that you still can use the old one but in some cases it´s impossible.
I show you how I do the connection with database. You need just change the values of the variables.
My connection file: connection.php
<?php
$host='IP or Server Name (usually "localhost") ';
$user='Database user';
$password='Database password';
$db='Database name';
//PHP 5.4 o earlier (DEPRECATED)
$con = mysql_connect($host,$user,$password) or exit("Connection Error");
$connection = mysql_select_db($db, $con);
//PHP 5.5 (New method)
$connection = mysqli_connect($host,$user,$password,$db);
?>
The extension changes too when performing a query.
Query File: "example.php"
<?php
//First I call for the connection
require("connection.php");
// ... Here code if you need do something ...
$query = "Here the query you are going to perform";
//QUERY PHP 5.4 o earlier (DEPRECATED)
$result = mysql_query ($query) or exit("The query could not be performed");
//QUERY PHP 5.5 (NEW EXTENSION)
$result = mysqli_query ($query) or exit("The query could not be performed");
?>
This way is using MySQL Improved Extension, but you can use PDO (PHP Data Objects).
First method can be used only with MySQL databases, but PDO can manage different types of databases.
I'm going to put an example but it´s necessary to say that I only use the first one, so please correct me if there is any error.
My PDO connection file: "PDOconnection.php"
<?php
$hostDb='mysql:host= "Here IP or Server Name";dbname="Database name" ';
$user='Database user';
$password='Database password';
$connection = new PDO($hostDb, $user, $password);
?>
Query File (PDO): "example.php"
<?php
$query = "Here the query you are going to perform";
$result=$connection->$query;
?>
To finish just say that of course you can hide the warning but it´s not a good idea because can help you in future save time if an error happens (all of us knows the theory but if you work a lot of hours sometimes... brain is not there ^^ ).
This error sometimes occurs in a situation like this:
#ifndef NAN
#include <stdlib.h>
#define NAN (strtod("NAN",NULL))
#endif
static void init_random(uint32_t initseed=0)
{
if (initseed==0)
{
struct timeval tv;
gettimeofday(&tv, NULL);
seed=(uint32_t) (4223517*getpid()*tv.tv_sec*tv.tv_usec);
}
else
seed=initseed;
#if !defined(CYGWIN) && !defined(__INTERIX)
//seed=42
//SG_SPRINT("initializing random number generator with %d (seed size %d)\n", seed, RNG_SEED_SIZE)
initstate(seed, CMath::rand_state, RNG_SEED_SIZE);
#endif
}
If the following code lines not run in the run-time:
#ifndef NAN
#include <stdlib.h>
#define NAN (strtod("NAN",NULL))
#endif
you will face with an error in your code like something as follows; because initstate is placed in the stdlib.h file and it's not included:
In file included from ../../shogun/features/SubsetStack.h:14:0,
from ../../shogun/features/Features.h:21,
from ../../shogun/ui/SGInterface.h:7,
from MatlabInterface.h:15,
from matlabInterface.cpp:7:
../../shogun/mathematics/Math.h: In static member function 'static void shogun::CMath::init_random(uint32_t)':
../../shogun/mathematics/Math.h:459:52: error: 'initstate' was not declared in this scope
If you code is intended for a different OS (like Mac OS X, Linux) you may use following:
#ifdef _WIN32
#define _CRT_SECURE_NO_DEPRECATE
#endif
I used FPDF v. 1.53 and didn't want to upgrade because of possible side effects. I used the following code according to Yacoby:
Line 1164:
if (version_compare(PHP_VERSION, '5.3.0', '<')) {
$mqr=get_magic_quotes_runtime();
set_magic_quotes_runtime(0);
}
Line 1203:
if (version_compare(PHP_VERSION, '5.3.0', '<')) {
set_magic_quotes_runtime($mqr);
}
Food for thought: what would a text-to-speech synthesizer do with <center>
?
127.0.0.1 restricts access on every interface on port 8000 except development computer. change it to 0.0.0.0:8000 this will allow connection from curl.
My preference, and I have no idea why this isn't already in jQuery:
$.fn.orElse = function(elseFunction) {
if (!this.length) {
elseFunction();
}
};
Used like this:
$('#notAnElement').each(function () {
alert("Wrong, it is an element")
}).orElse(function() {
alert("Yup, it's not an element")
});
Or, as it looks in CoffeeScript:
$('#notAnElement').each ->
alert "Wrong, it is an element"; return
.orElse ->
alert "Yup, it's not an element"
It is possible to define a function from inside another function. the inner function does not exist until the outer function gets executed.
echo function_exists("y") ? 'y is defined\n' : 'y is not defined \n';
$x=x(2);
echo function_exists("y") ? 'y is defined\n' : 'y is not defined \n';
Output
y is not defined
y is defined
Simple thing you can not call function y before executed x
A factory approach is certainly viable. Another approach is to use inheritance to create individual interfaces that inherit from IService, implement the inherited interfaces in your IService implementations, and register the inherited interfaces rather than the base. Whether adding an inheritance hierarchy or factories is the "right" pattern all depends on who you speak to. I often have to use this pattern when dealing with multiple database providers in the same application that uses a generic, such as IRepository<T>
, as the foundation for data access.
Example interfaces and implementations:
public interface IService
{
}
public interface IServiceA: IService
{}
public interface IServiceB: IService
{}
public IServiceC: IService
{}
public class ServiceA: IServiceA
{}
public class ServiceB: IServiceB
{}
public class ServiceC: IServiceC
{}
Container:
container.Register<IServiceA, ServiceA>();
container.Register<IServiceB, ServiceB>();
container.Register<IServiceC, ServiceC>();
Processes are like two people using two different computers, who use the network to share data when necessary. Threads are like two people using the same computer, who don't have to share data explicitly but must carefully take turns.
Conceptually, threads are just multiple worker bees buzzing around in the same address space. Each thread has its own stack, its own program counter, etc., but all threads in a process share the same memory. Imagine two programs running at the same time, but they both can access the same objects.
Contrast this with processes. Processes each have their own address space, meaning a pointer in one process cannot be used to refer to an object in another (unless you use shared memory).
I guess the key things to understand are:
In your activity, the following function getIpAddress(context)
returns the phone's IP address:
public static String getIpAddress(Context context) {
WifiManager wifiManager = (WifiManager) context.getApplicationContext()
.getSystemService(WIFI_SERVICE);
String ipAddress = intToInetAddress(wifiManager.getDhcpInfo().ipAddress).toString();
ipAddress = ipAddress.substring(1);
return ipAddress;
}
public static InetAddress intToInetAddress(int hostAddress) {
byte[] addressBytes = { (byte)(0xff & hostAddress),
(byte)(0xff & (hostAddress >> 8)),
(byte)(0xff & (hostAddress >> 16)),
(byte)(0xff & (hostAddress >> 24)) };
try {
return InetAddress.getByAddress(addressBytes);
} catch (UnknownHostException e) {
throw new AssertionError();
}
}
If you're using an implementation of System.Collections.IEnumerable
you can do like following to convert it to a List
. The following uses Enumerable.Cast method to convert IEnumberable
to a Generic List
.
//ArrayList Implements IEnumerable interface
ArrayList _provinces = new System.Collections.ArrayList();
_provinces.Add("Western");
_provinces.Add("Eastern");
List<string> provinces = _provinces.Cast<string>().ToList();
If you're using Generic version IEnumerable<T>
, The conversion is straight forward. Since both are generics, you can do like below,
IEnumerable<int> values = Enumerable.Range(1, 10);
List<int> valueList = values.ToList();
But if the IEnumerable
is null, when you try to convert it to a List
, you'll get
ArgumentNullException
saying Value cannot be null.
IEnumerable<int> values2 = null;
List<int> valueList2 = values2.ToList();
Therefore as mentioned in the other answer, remember to do a null
check before converting it to a List
.
You are right. If you want to delete the User and all associated objects -> destroy_all
However, if you just want to delete the User without suppressing all associated objects -> delete_all
According to this post : Rails :dependent => :destroy VS :dependent => :delete_all
destroy
/ destroy_all
: The associated objects are destroyed alongside this object by calling their destroy methoddelete
/ delete_all
: All associated objects are destroyed immediately without calling their :destroy methodI was having the same error under Windows using emacs 24.5.1 to connect to some company servers through /ssh:user@host. What solved my problem was setting the "tramp-default-method" variable to "plink" and whenever I connect to a server I ommit the ssh protocol. You need to have PuTTY's plink.exe installed for this to work.
Solution
I created .pfx file from .key and .pem files.
Like this openssl pkcs12 -inkey rootCA.key -in rootCA.pem -export -out rootCA.pfx
That's not the direct answer but still maybe it helps out someone else.
@Limp, your answer is right, just use .nextLine() while reading the input. Sample code:
do {
try {
System.out.println("Enter first num: ");
n1 = Integer.parseInt(input.nextLine());
System.out.println("Enter second num: ");
n2 = Integer.parseInt(input.nextLine());
nQuotient = n1 / n2;
bError = false;
} catch (Exception e) {
System.out.println("Error!");
}
} while (bError);
System.out.printf("%d/%d = %d", n1, n2, nQuotient);
Read the description of why this problem was caused in the link below. Look for the answer I posted for the detail in this thread. Java Homework user input issue
Ok, I will briefly describe it. When you read input using nextInt(), you just read the number part but the ENDLINE character was still on the stream. That was the main cause. Now look at the code above, all I did is read the whole line and parse it , it still throws the exception and work the way you were expecting it to work. Rest of your code works fine.
The Code part :
Image imProfile = new Image(getClass().getResourceAsStream("/img/profile128.png"));
ImageView profileImage=new ImageView(imProfile);
in a javafx maven:
Be careful, you can not modify the preflight. In addition, the browser (at least chrome) removes the "authorization" header ... this results in some problems that may arise according to the route design. For example, a preflight will never enter the passport route sheet since it does not have the header with the token.
In case you are designing a file with an implementation of the options method, you must define in the route file web.php one (or more than one) "trap" route so that the preflght (without header authorization) can resolve the request and Obtain the corresponding CORS headers. Because they can not return in a middleware 200 by default, they must add the headers on the original request.
If you use ECMAScript 6, you can simply write like this.
// First, create a wrap object.
const wrap = {
[variableName]: true
}
// Then, use it
<SomeComponent {...{wrap}} />
Python 3.x makes a clear distinction between the types:
str
= '...'
literals = a sequence of Unicode characters (Latin-1, UCS-2 or UCS-4, depending on the widest character in the string)bytes
= b'...'
literals = a sequence of octets (integers between 0 and 255)If you're familiar with:
str
as String
and bytes
as byte[]
;str
as NVARCHAR
and bytes
as BINARY
or BLOB
;str
as REG_SZ
and bytes
as REG_BINARY
.If you're familiar with C(++), then forget everything you've learned about char
and strings, because a character is not a byte. That idea is long obsolete.
You use str
when you want to represent text.
print('???? ????')
You use bytes
when you want to represent low-level binary data like structs.
NaN = struct.unpack('>d', b'\xff\xf8\x00\x00\x00\x00\x00\x00')[0]
You can encode a str
to a bytes
object.
>>> '\uFEFF'.encode('UTF-8')
b'\xef\xbb\xbf'
And you can decode a bytes
into a str
.
>>> b'\xE2\x82\xAC'.decode('UTF-8')
'€'
But you can't freely mix the two types.
>>> b'\xEF\xBB\xBF' + 'Text with a UTF-8 BOM'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't concat bytes to str
The b'...'
notation is somewhat confusing in that it allows the bytes 0x01-0x7F to be specified with ASCII characters instead of hex numbers.
>>> b'A' == b'\x41'
True
But I must emphasize, a character is not a byte.
>>> 'A' == b'A'
False
Pre-3.0 versions of Python lacked this kind of distinction between text and binary data. Instead, there was:
unicode
= u'...'
literals = sequence of Unicode characters = 3.x str
str
= '...'
literals = sequences of confounded bytes/characters
struct.pack
output.In order to ease the 2.x-to-3.x transition, the b'...'
literal syntax was backported to Python 2.6, in order to allow distinguishing binary strings (which should be bytes
in 3.x) from text strings (which should be str
in 3.x). The b
prefix does nothing in 2.x, but tells the 2to3
script not to convert it to a Unicode string in 3.x.
So yes, b'...'
literals in Python have the same purpose that they do in PHP.
Also, just out of curiosity, are there more symbols than the b and u that do other things?
The r
prefix creates a raw string (e.g., r'\t'
is a backslash + t
instead of a tab), and triple quotes '''...'''
or """..."""
allow multi-line string literals.
You could just create an array of the correct size up-front and fill it:
frames = np.empty((480, 640, 3, 100))
for k in xrange(nframes):
frames[:,:,:,k] = cv2.imread('frame_{}.jpg'.format(k))
if the frames were individual jpg file that were named in some particular way (in the example, frame_0.jpg, frame_1.jpg, etc).
Just a note, you might consider using a (nframes, 480,640,3)
shaped array, instead.
Technically, the char*
is not an array, but a pointer to a char
.
Similarly, char**
is a pointer to a char*
. Making it a pointer to a pointer to a char
.
C and C++ both define arrays behind-the-scenes as pointer types, so yes, this structure, in all likelihood, is array of arrays of char
s, or an array of strings.
Adding your favicon simply into to the public
folder should do. Make sure the favicon is named as favicon.ico
.
If your driver is JDBC 4 compliant, there is no need for a dedicated query to test connections. Instead, there is Connection.isValid to test the connection.
JDBC 4 is part of Java 6 from 2006 and you driver should support this by now!
Famous connection pools, like HikariCP, still have a config parameter for specifying a test query but strongly discourage to use it:
connectionTestQuery
If your driver supports JDBC4 we strongly recommend not setting this property. This is for "legacy" databases that do not support the JDBC4 Connection.isValid() API. This is the query that will be executed just before a connection is given to you from the pool to validate that the connection to the database is still alive. Again, try running the pool without this property, HikariCP will log an error if your driver is not JDBC4 compliant to let you know. Default: none
Use given lines in OnActionExecuting for Action and Controller name.
string actionName = this.ControllerContext.RouteData.Values["action"].ToString();
string controllerName = this.ControllerContext.RouteData.Values["controller"].ToString();
Here's a solution:
dates <- c("14.01.2013", "26.03.2014")
# Date format:
dates2 <- strptime(dates, format = "%d.%m.%Y")
dif <- diff(as.numeric(dates2)) # difference in seconds
dif/(60 * 60 * 24 * 7) # weeks
[1] 62.28571
dif/(60 * 60 * 24 * 30) # months
[1] 14.53333
dif/(60 * 60 * 24 * 30 * 3) # quartes
[1] 4.844444
dif/(60 * 60 * 24 * 365) # years
[1] 1.194521
Jon's disassemblies show, that the difference between the two versions is that the fast version uses a pair of registers (esi,edi
) to store one of the local variables where the slow version doesn't.
The JIT compiler makes different assumptions regarding register use for code that contains a try-catch block vs. code which doesn't. This causes it to make different register allocation choices. In this case, this favors the code with the try-catch block. Different code may lead to the opposite effect, so I would not count this as a general-purpose speed-up technique.
In the end, it's very hard to tell which code will end up running the fastest. Something like register allocation and the factors that influence it are such low-level implementation details that I don't see how any specific technique could reliably produce faster code.
For example, consider the following two methods. They were adapted from a real-life example:
interface IIndexed { int this[int index] { get; set; } }
struct StructArray : IIndexed {
public int[] Array;
public int this[int index] {
get { return Array[index]; }
set { Array[index] = value; }
}
}
static int Generic<T>(int length, T a, T b) where T : IIndexed {
int sum = 0;
for (int i = 0; i < length; i++)
sum += a[i] * b[i];
return sum;
}
static int Specialized(int length, StructArray a, StructArray b) {
int sum = 0;
for (int i = 0; i < length; i++)
sum += a[i] * b[i];
return sum;
}
One is a generic version of the other. Replacing the generic type with StructArray
would make the methods identical. Because StructArray
is a value type, it gets its own compiled version of the generic method. Yet the actual running time is significantly longer than the specialized method's, but only for x86. For x64, the timings are pretty much identical. In other cases, I've observed differences for x64 as well.
This happens when you have previously changed your icon or the ic_launcher; and when that ic_launcher no longer exists in your base folder.
Try adding a png image and giving the same name and then copy it to your drawable folder.Now re build the project.
Define "much faster". Asymptotically they're about the same. The differences lie in how they make use of secondary storage. The Wikipedia articles on B-trees and B+trees look pretty trustworthy.
I fixed the same issue by deleting ComponentModelCache folder
%APPDATA%/..
and press enterC:\Users\\AppData
Local\Microsoft\VisualStudio\<version>
where is 12.0 for Visual Studio 2013.From here: http://withmartin.net/how-visual-studios-component-model-cache-can-be-a-pain/
I had the same issue, but I wanted a solution that didn't use locks.
Problem: I have at most one thread consuming from a queue. Multiple producer threads are constantly inserting into the queue and need to notify the consumer if it's waiting. The queue is lock-free so using locks for notification causes unnecessary blocking in producer threads. Each producer thread needs to acquire the lock before it can notify the waiting consumer. I believe I came up with a lock-free solution using LockSupport
and AtomicReferenceFieldUpdater
. If a lock-free barrier exists within the JDK, I couldn't find it. Both CyclicBarrier
and CoundDownLatch
use locks internally from what I could find.
This is my slightly abbreviated code. Just to be clear, this code will only allow one thread to wait at a time. It could be modified to allow for multiple awaiters/consumers by using some type of atomic collection to store multiple owner (a ConcurrentMap
may work).
I have used this code and it seems to work. I have not tested it extensively. I suggest you read the documentation for LockSupport
before use.
/* I release this code into the public domain.
* http://unlicense.org/UNLICENSE
*/
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.util.concurrent.locks.LockSupport;
/**
* A simple barrier for awaiting a signal.
* Only one thread at a time may await the signal.
*/
public class SignalBarrier {
/**
* The Thread that is currently awaiting the signal.
* !!! Don't call this directly !!!
*/
@SuppressWarnings("unused")
private volatile Thread _owner;
/** Used to update the owner atomically */
private static final AtomicReferenceFieldUpdater<SignalBarrier, Thread> ownerAccess =
AtomicReferenceFieldUpdater.newUpdater(SignalBarrier.class, Thread.class, "_owner");
/** Create a new SignalBarrier without an owner. */
public SignalBarrier() {
_owner = null;
}
/**
* Signal the owner that the barrier is ready.
* This has no effect if the SignalBarrer is unowned.
*/
public void signal() {
// Remove the current owner of this barrier.
Thread t = ownerAccess.getAndSet(this, null);
// If the owner wasn't null, unpark it.
if (t != null) {
LockSupport.unpark(t);
}
}
/**
* Claim the SignalBarrier and block until signaled.
*
* @throws IllegalStateException If the SignalBarrier already has an owner.
* @throws InterruptedException If the thread is interrupted while waiting.
*/
public void await() throws InterruptedException {
// Get the thread that would like to await the signal.
Thread t = Thread.currentThread();
// If a thread is attempting to await, the current owner should be null.
if (!ownerAccess.compareAndSet(this, null, t)) {
throw new IllegalStateException("A second thread tried to acquire a signal barrier that is already owned.");
}
// The current thread has taken ownership of this barrier.
// Park the current thread until the signal. Record this
// signal barrier as the 'blocker'.
LockSupport.park(this);
// If a thread has called #signal() the owner should already be null.
// However the documentation for LockSupport.unpark makes it clear that
// threads can wake up for absolutely no reason. Do a compare and set
// to make sure we don't wipe out a new owner, keeping in mind that only
// thread should be awaiting at any given moment!
ownerAccess.compareAndSet(this, t, null);
// Check to see if we've been unparked because of a thread interrupt.
if (t.isInterrupted())
throw new InterruptedException();
}
/**
* Claim the SignalBarrier and block until signaled or the timeout expires.
*
* @throws IllegalStateException If the SignalBarrier already has an owner.
* @throws InterruptedException If the thread is interrupted while waiting.
*
* @param timeout The timeout duration in nanoseconds.
* @return The timeout minus the number of nanoseconds that passed while waiting.
*/
public long awaitNanos(long timeout) throws InterruptedException {
if (timeout <= 0)
return 0;
// Get the thread that would like to await the signal.
Thread t = Thread.currentThread();
// If a thread is attempting to await, the current owner should be null.
if (!ownerAccess.compareAndSet(this, null, t)) {
throw new IllegalStateException("A second thread tried to acquire a signal barrier is already owned.");
}
// The current thread owns this barrier.
// Park the current thread until the signal. Record this
// signal barrier as the 'blocker'.
// Time the park.
long start = System.nanoTime();
LockSupport.parkNanos(this, timeout);
ownerAccess.compareAndSet(this, t, null);
long stop = System.nanoTime();
// Check to see if we've been unparked because of a thread interrupt.
if (t.isInterrupted())
throw new InterruptedException();
// Return the number of nanoseconds left in the timeout after what we
// just waited.
return Math.max(timeout - stop + start, 0L);
}
}
To give a vague example of usage, I'll adopt james large's example:
SignalBarrier barrier = new SignalBarrier();
Consumer thread (singular, not plural!):
try {
while(!conditionIsTrue()) {
barrier.await();
}
doSomethingThatRequiresConditionToBeTrue();
} catch (InterruptedException e) {
handleInterruption();
}
Producer thread(s):
doSomethingThatMakesConditionTrue();
barrier.signal();
Do you have access to the command prompt ?
Method 1 : Command Prompt
The specifics of the Java installed on the system can be determined by executing the following command java -version
Method 2 : Folder Structure
In case you do not have access to command prompt then determining the folder where Java.
32 Bit : C:\Program Files (x86)\Java\jdk1.6.0_30
64 Bit : C:\Program Files\Java\jdk1.6.0_25
However during the installation it is possible that the user might change the installation folder.
Method 3 : Registry
You can also see the version installed in registry editor.
Go to registry editor
Edit -> Find
Search for Java. You will get the registry entries for Java.
In the entry with name : DisplayName
& DisplayVersion
, the installed java version is displayed
For OP's terminal Cmder
there is an integration guide, also hinted in the VS Code docs.
If you want to use VS Code tasks and encounter problems after switch to Cmder
, there is an update to @khernand's answer. Copy this into your settings.json
file:
"terminal.integrated.shell.windows": "cmd.exe",
"terminal.integrated.env.windows": {
"CMDER_ROOT": "[cmder_root]" // replace [cmder_root] with your cmder path
},
"terminal.integrated.shellArgs.windows": [
"/k",
"%CMDER_ROOT%\\vendor\\bin\\vscode_init.cmd" // <-- this is the relevant change
// OLD: "%CMDER_ROOT%\\vendor\\init.bat"
],
The invoked file will open Cmder
as integrated terminal and switch to cmd
for tasks - have a look at the source here. So you can omit configuring a separate terminal in tasks.json
to make tasks work.
Starting with VS Code 1.38, there is also "terminal.integrated.automationShell.windows"
setting, which lets you set your terminal for tasks globally and avoids issues with Cmder
.
"terminal.integrated.automationShell.windows": "cmd.exe"
At line 5 there is a /
missing.
There is a good answer on the differences between ;
and /
here.
Basically, when running a CREATE
block via script, you need to use /
to let SQLPlus know when the block ends, since a PL/SQL block can contain many instances of ;
.
The itertools.iter_except
recipes encapsulates this idea of "calling a function repeatedly until an exception is raised". It is similar to the accepted answer, but the recipe gives an iterator instead.
From the recipes:
def iter_except(func, exception, first=None):
""" Call a function repeatedly until an exception is raised."""
try:
if first is not None:
yield first() # For database APIs needing an initial cast to db.first()
while True:
yield func()
except exception:
pass
You can certainly implement the latter code directly. For convenience, I use a separate library, more_itertools
, that implements this recipe for us (optional).
Code
import more_itertools as mit
list(mit.iter_except([0, 1, 2].pop, IndexError))
# [2, 1, 0]
Details
Here the pop
method (or given function) is called for every iteration of the list object until an IndexError
is raised.
For your case, given some connect_function
and expected error, you can make an iterator that calls the function repeatedly until an exception is raised, e.g.
mit.iter_except(connect_function, ConnectionError)
At this point, treat it as any other iterator by looping over it or calling next()
.
Try this in your batch file:
@echo off
start /d "C:\Program Files\Internet Explorer" IEXPLORE.EXE www.google.com
start /d "C:\Program Files\Internet Explorer" IEXPLORE.EXE www.yahoo.com
Jon Tan has done this with his site - http://jontangerine.com/ Everything including images has been declared in ems. Everything. This is how the desired effect is achieved. Text zoom and screen zoom yield almost the exact same result.
Firebug is great, but Safari provides its own built-in development tools.
If you haven't already tried Safari's development kit, go to Safari-->Preferences-->Advanced, and check the box next to "Show Develop menu in menu bar".
Once you have the Develop menu enabled, you can use the Web Inspector to get a lot of the same functionality that Firebug provides.
If you want to only update on rows that are not currently uppercase (instead of all rows), you'd need to identify the difference using COLLATE
like this:
UPDATE MyTable
SET MyColumn = UPPER(MyColumn)
WHERE MyColumn != UPPER(MyColumn) COLLATE Latin1_General_CS_AS
Cases sensitivity is based on your collation settings, and is typically case insensitive by default.
Collation can be set at the Server, Database, Column, or Query Level:
-- Server
SELECT SERVERPROPERTY('COLLATION')
-- Database
SELECT name, collation_name FROM sys.databases
-- Column
SELECT COLUMN_NAME, COLLATION_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE CHARACTER_SET_NAME IS NOT NULL
Collation Names specify how a string should be encoded and read, for example:
Latin1_General_CI_AS
? Case InsensitiveLatin1_General_CS_AS
? Case SensitiveHere is a nice, tidy Python solution. I made no attempt to be terse here.
This modifies the file in-place, rather than making a copy of the file and stripping the newline from the last line of the copy. If the file is large, this will be much faster than the Perl solution that was chosen as the best answer.
It truncates a file by two bytes if the last two bytes are CR/LF, or by one byte if the last byte is LF. It does not attempt to modify the file if the last byte(s) are not (CR)LF. It handles errors. Tested in Python 2.6.
Put this in a file called "striplast" and chmod +x striplast
.
#!/usr/bin/python
# strip newline from last line of a file
import sys
def trunc(filename, new_len):
try:
# open with mode "append" so we have permission to modify
# cannot open with mode "write" because that clobbers the file!
f = open(filename, "ab")
f.truncate(new_len)
f.close()
except IOError:
print "cannot write to file:", filename
sys.exit(2)
# get input argument
if len(sys.argv) == 2:
filename = sys.argv[1]
else:
filename = "--help" # wrong number of arguments so print help
if filename == "--help" or filename == "-h" or filename == "/?":
print "Usage: %s <filename>" % sys.argv[0]
print "Strips a newline off the last line of a file."
sys.exit(1)
try:
# must have mode "b" (binary) to allow f.seek() with negative offset
f = open(filename, "rb")
except IOError:
print "file does not exist:", filename
sys.exit(2)
SEEK_EOF = 2
f.seek(-2, SEEK_EOF) # seek to two bytes before end of file
end_pos = f.tell()
line = f.read()
f.close()
if line.endswith("\r\n"):
trunc(filename, end_pos)
elif line.endswith("\n"):
trunc(filename, end_pos + 1)
P.S. In the spirit of "Perl golf", here's my shortest Python solution. It slurps the whole file from standard input into memory, strips all newlines off the end, and writes the result to standard output. Not as terse as the Perl; you just can't beat Perl for little tricky fast stuff like this.
Remove the "\n" from the call to .rstrip()
and it will strip all white space from the end of the file, including multiple blank lines.
Put this into "slurp_and_chomp.py" and then run python slurp_and_chomp.py < inputfile > outputfile
.
import sys
sys.stdout.write(sys.stdin.read().rstrip("\n"))
You can use this library: https://github.com/vadamsky/csvworker
Code for example:
#include <iostream>
#include "csvworker.h"
using namespace std;
int main()
{
//
CsvWorker csv;
csv.loadFromFile("example.csv");
cout << csv.getRowsNumber() << " " << csv.getColumnsNumber() << endl;
csv.getFieldRef(0, 2) = "0";
csv.getFieldRef(1, 1) = "0";
csv.getFieldRef(1, 3) = "0";
csv.getFieldRef(2, 0) = "0";
csv.getFieldRef(2, 4) = "0";
csv.getFieldRef(3, 1) = "0";
csv.getFieldRef(3, 3) = "0";
csv.getFieldRef(4, 2) = "0";
for(unsigned int i=0;i<csv.getRowsNumber();++i)
{
//cout << csv.getRow(i) << endl;
for(unsigned int j=0;j<csv.getColumnsNumber();++j)
{
cout << csv.getField(i, j) << ".";
}
cout << endl;
}
csv.saveToFile("test.csv");
//
CsvWorker csv2(4,4);
csv2.getFieldRef(0, 0) = "a";
csv2.getFieldRef(0, 1) = "b";
csv2.getFieldRef(0, 2) = "r";
csv2.getFieldRef(0, 3) = "a";
csv2.getFieldRef(1, 0) = "c";
csv2.getFieldRef(1, 1) = "a";
csv2.getFieldRef(1, 2) = "d";
csv2.getFieldRef(2, 0) = "a";
csv2.getFieldRef(2, 1) = "b";
csv2.getFieldRef(2, 2) = "r";
csv2.getFieldRef(2, 3) = "a";
csv2.saveToFile("test2.csv");
return 0;
}
bool (*FuncPtr)()
FuncPtr = A;
FuncPtr();
If you want to call one of those functions conditionally, you should consider using an array of function pointers. In this case you'd have 3 elements pointing to A, B, and C and you call one depending on the index to the array, such as funcArray0 for A.
This would do it.
public static void main(String[] args) {
double d = 12.349678;
int r = (int) Math.round(d*100);
double f = r / 100.0;
System.out.println(f);
}
You can short this method, it's easy to understand that's why I have written like this.
Release 3.2 of commons-lang
will have FastDateParser
class that is a thread-safe substitute of SimpleDateFormat
for Gregorian calendar. See LANG-909
for more information.
You can't use a LinearLayout for this, but you can use a FrameLayout
. In a FrameLayout
, the z-index is defined by the order in which the items are added, for example:
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/my_drawable"
android:scaleType="fitCenter"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center"
android:padding="5dp"
android:text="My Label"
/>
</FrameLayout>
In this instance, the TextView would be drawn on top of the ImageView, along the bottom center of the image.
When we create a customer directive, the scope of the directive could be in Isolated scope, It means the directive does not share a scope with the controller; both directive and controller have their own scope. However, data can be passed to the directive scope in three possible ways.
@
string literal, pass string value, one way binding.=
string literal, pass object, 2 ways binding.&
string literal, calls external function, can pass data from directive to controller.SQL Server Express editions are limited in some ways - one way is that they don't have the SQL Agent that allows you to schedule jobs.
There are a few third-party extensions that provide that capability - check out e.g.:
A simple way is:
while (<FILE>) { $document .= $_ }
Another way is to change the input record separator "$/". You can do it locally in a bare block to avoid changing the global record separator.
{
open(F, "filename");
local $/ = undef;
$d = <F>;
}
You will need to add the values in the array one at a time.
var parameters = new string[items.Length];
var cmd = new SqlCommand();
for (int i = 0; i < items.Length; i++)
{
parameters[i] = string.Format("@Age{0}", i);
cmd.Parameters.AddWithValue(parameters[i], items[i]);
}
cmd.CommandText = string.Format("SELECT * from TableA WHERE Age IN ({0})", string.Join(", ", parameters));
cmd.Connection = new SqlConnection(connStr);
UPDATE: Here is an extended and reusable solution that uses Adam's answer along with his suggested edit. I improved it a bit and made it an extension method to make it even easier to call.
public static class SqlCommandExt
{
/// <summary>
/// This will add an array of parameters to a SqlCommand. This is used for an IN statement.
/// Use the returned value for the IN part of your SQL call. (i.e. SELECT * FROM table WHERE field IN ({paramNameRoot}))
/// </summary>
/// <param name="cmd">The SqlCommand object to add parameters to.</param>
/// <param name="paramNameRoot">What the parameter should be named followed by a unique value for each value. This value surrounded by {} in the CommandText will be replaced.</param>
/// <param name="values">The array of strings that need to be added as parameters.</param>
/// <param name="dbType">One of the System.Data.SqlDbType values. If null, determines type based on T.</param>
/// <param name="size">The maximum size, in bytes, of the data within the column. The default value is inferred from the parameter value.</param>
public static SqlParameter[] AddArrayParameters<T>(this SqlCommand cmd, string paramNameRoot, IEnumerable<T> values, SqlDbType? dbType = null, int? size = null)
{
/* An array cannot be simply added as a parameter to a SqlCommand so we need to loop through things and add it manually.
* Each item in the array will end up being it's own SqlParameter so the return value for this must be used as part of the
* IN statement in the CommandText.
*/
var parameters = new List<SqlParameter>();
var parameterNames = new List<string>();
var paramNbr = 1;
foreach (var value in values)
{
var paramName = string.Format("@{0}{1}", paramNameRoot, paramNbr++);
parameterNames.Add(paramName);
SqlParameter p = new SqlParameter(paramName, value);
if (dbType.HasValue)
p.SqlDbType = dbType.Value;
if (size.HasValue)
p.Size = size.Value;
cmd.Parameters.Add(p);
parameters.Add(p);
}
cmd.CommandText = cmd.CommandText.Replace("{" + paramNameRoot + "}", string.Join(",", parameterNames));
return parameters.ToArray();
}
}
It is called like this...
var cmd = new SqlCommand("SELECT * FROM TableA WHERE Age IN ({Age})");
cmd.AddArrayParameters("Age", new int[] { 1, 2, 3 });
Notice the "{Age}" in the sql statement is the same as the parameter name we are sending to AddArrayParameters. AddArrayParameters will replace the value with the correct parameters.
With the use of the bootstrap 4 utilities you could horizontally center an element itself by setting the horizontal margins to 'auto'.
To set the horizontal margins to auto you can use mx-auto
. The m
refers to margin and the x
will refer to the x-axis (left+right) and auto
will refer to the setting. So this will set the left margin and the right margin to the 'auto' setting. Browsers will calculate the margin equally and center the element. The setting will only work on block elements so the display:block needs to be added and with the bootstrap utilities this is done by d-block
.
<button type="submit" class="btn btn-primary mx-auto d-block">Submit</button>
You can consider all browsers to fully support auto margin settings according to this answer Browser support for margin: auto so it's safe to use.
The bootstrap 4 class text-center
is also a very good solution, however it needs a parent wrapper element. The benefit of using auto margin is that it can be done directly on the button element itself.
pop
mutates the dictionary.
>>> lol = {"hello": "gdbye"}
>>> lol.pop("hello")
'gdbye'
>>> lol
{}
If you want to keep the original you could just copy it.
You'll want to change the extension of your css file from .css.scss
to .css.scss.erb
and do:
background-image:url(<%=asset_path "admin/logo.png"%>);
You may need to do a "hard refresh" to see changes. CMD+SHIFT+R on OSX browsers.
In production, make sure
rm -rf public/assets
bundle exec rake assets:precompile RAILS_ENV=production
happens upon deployment.
All versions of Git since v1.7.8 understand git fetch
with a refspec, whereas since v1.9.0 the --tags
option overrides the --prune
option. For a general purpose solution, try this:
$ git --version
git version 2.1.3
$ git fetch --prune origin "+refs/tags/*:refs/tags/*"
From ssh://xxx
x [deleted] (none) -> rel_test
For further reading on how the "--tags" with "--prune" behavior changed in Git v1.9.0, see: https://github.com/git/git/commit/e66ef7ae6f31f246dead62f574cc2acb75fd001c
Yes, with a lexical cast. Use a stringstream and the << operator, or use Boost, they've already implemented it.
Your own version could look like:
template<typename to, typename from>to lexical_cast(from const &x) {
std::stringstream os;
to ret;
os << x;
os >> ret;
return ret;
}
After reading John's answer, I discovered the following seemed to work for us (did not require specifying width):
<style>
.row {
float:left;
border: 1px solid yellow;
overflow: visible;
white-space: nowrap;
}
.cell {
display: inline-block;
border: 1px solid red;
height: 100px;
}
</style>
<div class="row">
<div class="cell">hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello </div>
<div class="cell">hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello </div>
<div class="cell">hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello </div>
</div>
50 - List1[0][0] + List[0][1] - List[0][2]
List[0]
gives you the first list in the list (try out print List[0]
). Then, you index into it again to get the items of that list. Think of it this way: (List1[0])[0]
.
Check out the pack URI syntax. You want something like this:
<ResourceDictionary Source="pack://application:,,,/YourAssembly;component/Subfolder/YourResourceFile.xaml"/>
If you're sharing code between C and C++, remember to add the following to the shared.h
file:
#ifdef __cplusplus
extern "C" {
#endif
extern int my_global;
/* other extern declarations ... */
#ifdef __cplusplus
}
#endif
Interpreted languages like Python and JavaScript benefit greatly from linting, as these languages don’t have a compiling phase to display errors before execution.
Linters are also useful for code formatting and/or adhering to language specific best practices.
Lately I have been using ESLint for JS/React and will occasionally use it with an airbnb-config file.
You can adjust the plot margins with plot.margin
in theme()
and then move your axis labels and title with the vjust
argument of element_text()
. For example :
library(ggplot2)
library(grid)
qplot(rnorm(100)) +
ggtitle("Title") +
theme(axis.title.x=element_text(vjust=-2)) +
theme(axis.title.y=element_text(angle=90, vjust=-0.5)) +
theme(plot.title=element_text(size=15, vjust=3)) +
theme(plot.margin = unit(c(1,1,1,1), "cm"))
will give you something like this :
If you want more informations about the different theme()
parameters and their arguments, you can just enter ?theme
at the R prompt.
Also you can
use it lowercase
under below
let uuid = NSUUID().UUIDString.lowercaseString
print(uuid)
Output
68b696d7-320b-4402-a412-d9cee10fc6a3
Thank you !
Following solution is working fine.
HTML:
<table>
<tr>
<td>
<input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this);">
</td>
</tr>
<tr>
<td>
<input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this);">
</td>
</tr>
<tr>
<td>
<input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this);">
</td>
</tr>
</table>
JQuery:
function SomeDeleteRowFunction(btndel) {
if (typeof(btndel) == "object") {
$(btndel).closest("tr").remove();
} else {
return false;
}
}
I have done bins on http://codebins.com/bin/4ldqpa9
what you need exactly is
def fun():
raise Exception()
f = lambda x:print x if x==2 else fun()
now call the function the way you need
f(2)
f(3)
One minor difference is what they convert of undefined
or null
,
Number() Or Number(null) // returns 0
while
parseInt() Or parseInt(null) // returns NaN
Yes you can do that.
Materials you need:
1. First set the internet permissions in your manifest file
<uses-permission android:name="android.permission.INTERNET" />
2. Make a class to make an HTTPRequest from the server (i am using json parisng to get the values)
for eg:
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
3. In your MainActivity
Make an object of the class JsonFunctions
and pass the url as an argument from where you want to get the data
eg:
JSONObject jsonobject;
jsonobject = JSONfunctions.getJSONfromURL("http://YOUR_DATABASE_URL");
4. And then finally read the jsontags and store the values in an arraylist and later show it in listview if you want
and if you have any problem you can follow this blog he gives excellent android tutorials AndroidHive
Since the above answer i wrote was long back and now HttpClient
, HttpPost
,HttpEntity
have been removed in Api 23. You can use the below code in the build.gradle(app-level) to still continue using org.apache.http
in your project.
android {
useLibrary 'org.apache.http.legacy'
signingConfigs {}
buildTypes {}
}
or You can use HttpURLConnection
like below to get your response from server
public String getJSON(String url, int timeout) {
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
return null;
}
or You can use 3rd party Library like Volley
, Retrofit
to call the webservice api and get the response and later parse it with using FasterXML-jackson
, google-gson
.
Pragma
is the HTTP/1.0 implementation and cache-control
is the HTTP/1.1 implementation of the same concept. They both are meant to prevent the client from caching the response. Older clients may not support HTTP/1.1 which is why that header is still in use.
go to apple icon on the top left corn and click "System Preference"
find "Mysql" at the bottom and click it
"start Mysql server"
ReactJS: Maximum update depth exceeded error
inputDigit(digit){
this.setState({
displayValue: String(digit)
})
<button type="button"onClick={this.inputDigit(0)}>
why that?
<button type="button"onClick={() => this.inputDigit(1)}>1</button>
The function onDigit sets the state, which causes a rerender, which causes onDigit to fire because that’s the value you’re setting as onClick which causes the state to be set which causes a rerender, which causes onDigit to fire because that’s the value you’re… Etc
Let me provide answers to both possible questions. Note that your existing title (and original post) ask a question different than what you seek in your edit and subsequent comment.
To position an element "fixed" relative to a parent element, you want position:absolute
on the child element, and any position mode other than the default or static on your parent element.
For example:
#parentDiv { position:relative; }
#childDiv { position:absolute; left:50px; top:20px; }
This will position childDiv
element 50 pixels left and 20 pixels down relative to parentDiv's position.
To position an element "fixed" relative to the window, you want position:fixed
, and can use top:
, left:
, right:
, and bottom:
to position as you see fit.
For example:
#yourDiv { position:fixed; bottom:40px; right:40px; }
This will position yourDiv
fixed relative to the web browser window, 40 pixels from the bottom edge and 40 pixels from the right edge.
You need to take out the $ signs before the row numbers in the formula....and the row number used in the formula should correspond to the first row of data, so if you are applying this to the ("applies to") range $B$2:$B$5 it must be this formula
=$B2>$C2
by using that "relative" version rather than your "absolute" one Excel (implicitly) adjusts the formula for each row in the range, as if you were copying the formula down
I’m surprised no-one answered with this code:
for(var child=elt.firstChild;
child;
child=child.nextSibling){
do_thing(child);
}
Or, if you only want children which are elements, this code:
for(var child=elt.firstElementChild;
child;
child=child.nextElementSibling){
do_thing(child);
}
To H2oRider -- does your application access the Oracle dll in the GAC? What I recommend you do is this: Add the dll to your project and set the build action to "content" and set "copy to output directory" to "copy always".
Then delete your reference(s) to the dll in the GAC. Re-add the reference, but this time drill down to the one you just added to your project.
Now publish it. The application will look for the dll locally, and the dll is included in the deployment so it will find it.
If this doesn't work, then it might be that you can not use that dll if included locally rather than in the GAC. This is true of some assemblies, like the Office PIAs. In that case, the only way to deploy it is to wrap it in a setup & deployment package and use the Bootstrapper Manifest Generator to turn it into a prerequisite you can publish with ClickOnce deployment.
In each html template I just add the following meta tags at the top:
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
In my understanding each template is free standing therefore it does not inherit meta no caching rules setup in the index.html file.
A UDF will only return a value it won't allow you to change the properties of a cell/sheet/workbook. Move your code to a Worksheet_Change event or similar to change properties.
Eg
Private Sub worksheet_change(ByVal target As Range)
target.Font.Bold = True
End Sub
if you have to pass the value you should enter url like this
localhost/yoururl/index.php/products_controller/delete_controller/70
and in controller function you can read like this
function delete_controller( $product_id = NULL ) {
echo $product_id;
}
Use dataType:"json"
for json
data
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
dataType:'json', // add json datatype to get json
data: ({name: 145}),
success: function(data){
console.log(data);
}
});
Read Docs http://api.jquery.com/jQuery.ajax/
Also in PHP
<?php
$userAnswer = $_POST['name'];
$sql="SELECT * FROM <tablename> where color='".$userAnswer."'" ;
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
// for first row only and suppose table having data
echo json_encode($row); // pass array in json_encode
?>
You could have two separate TextViews and you could align them accordingly in your layout if needed:
Text1.setText(
Html.fromHtml(
"<a href=\"http://www.google.com\">google</a> "));
Text1.setMovementMethod(LinkMovementMethod.getInstance());
Text2.setText(
Html.fromHtml(
"<a href=\"http://www.stackoverflow.com\">stackoverflow</a> "));
Text2.setMovementMethod(LinkMovementMethod.getInstance());
Then if you want to strip the "link underline". Create a class:
public class URLSpanNoUnderline extends URLSpan {
public URLSpanNoUnderline(String url) {
super(url);
}
@Override public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setUnderlineText(false);
}
}
Then add this method in your main Activity class where you have the TextViews
private void stripUnderlines(TextView textView) {
Spannable s = new SpannableString(textView.getText());
URLSpan[] spans = s.getSpans(0, s.length(), URLSpan.class);
for (URLSpan span: spans) {
int start = s.getSpanStart(span);
int end = s.getSpanEnd(span);
s.removeSpan(span);
span = new URLSpanNoUnderline(span.getURL());
s.setSpan(span, start, end, 0);
}
textView.setText(s);
}
And then just call this after you initialised the TextViews (in your onCreate):
stripUnderlines(Text1);
stripUnderlines(Text2);
I will reproduce a good tutorial here, because I lost this article and take some time to find it again!
Adding syntax highlighting for new languages to Eclipse with the Colorer library
Say you have an HRC file containing the syntax and lexical structure of some programming language Eclipse does not support (for example D / Iptables or any other script language).
Using the EclipseColorer plugin, you can easily add support for it.
Go to Help -> Install New Software and click Add.. In the Name field write Colorer and in the Location field write http://colorer.sf.net/eclipsecolorer/
Select the entry you’ve just added in the work with: combo box, wait for the component list to populate and click Select All
Click Next and follow the instructions
Once the plugin is installed, close Eclipse.
Copy your HRC file to [EclipseFolder]\plugins\net.sf.colorer_0.9.9\colorer\hrc\auto\types
[EclipseFolder] = /home/myusername/.eclipse
Use your favorite text editor to open
[EclipseFolder]\plugins\net.sf.colorer_0.9.9\colorer\hrc\auto\empty.hrc
Add the appropriate prototype element. For example, if your HRC file is d.hrc, empty.hrc will look like this:
<?xml version="1.0" encoding='Windows-1251'?>
<!DOCTYPE hrc PUBLIC
"-//Cail Lomecb//DTD Colorer HRC take5//EN"
"http://colorer.sf.net/2003/hrc.dtd"
>
<hrc version="take5" xmlns="http://colorer.sf.net/2003/hrc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://colorer.sf.net/2003/hrc http://colorer.sf.net/2003/hrc.xsd"
><annotation><documentation>
'auto' is a place for include
to colorer your own HRCs
</documentation></annotation>
<prototype name="d" group="main" description="D">
<location link="types/d.hrc"/>
<filename>/\.(d)$/i</filename>
</prototype>
</hrc>
Save the changes and close the text editor
Open Eclipse and go to Window -> Preferences -> General -> Editors -> File Associations
In the file types section, click Add.. and fill in the appropriate filetype (for example .d)
Click OK and click your newly added entry in the list
In the associated editors section, click Add.., select Colorer Editor and press OK
ok, the hard part is you must learn about HCR syntax.
You can look in
[EclipseFolder]/net.sf.colorer_0.9.9/colorer/hrc/common.jar
to learn how do it and explore many other hcr's files. At this moment I didn't find any documentation.
My gift is a basic and incomplete iptables syntax highlight. If you improve please share with me.
<?xml version="1.0" encoding="Windows-1251"?>
<!DOCTYPE hrc PUBLIC "-//Cail Lomecb//DTD Colorer HRC take5//EN" "http://colorer.sf.net/2003/hrc.dtd">
<hrc version="take5" xmlns="http://colorer.sf.net/2003/hrc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://colorer.sf.net/2003/hrc http://colorer.sf.net/2003/hrc.xsd">
<type name="iptables">
<annotation>
<develby> Mario Moura - moura.mario gmail.com</develby>
<documentation>Support iptables EQL language</documentation>
<appinfo>
<prototype name="iptables" group="database" description="iptables">
<location link="iptables.hrc"/>
<filename>/\.epl$/i</filename>
</prototype>
</appinfo>
</annotation>
<region name="iptablesTable" parent="def:Keyword"/>
<region name="iptablesChainFilter" parent="def:Symbol"/>
<region name="iptablesChainNatMangle" parent="def:NumberDec"/>
<region name="iptablesCustomDefaultChains" parent="def:Keyword"/>
<region name="iptablesOptions" parent="def:String"/>
<region name="iptablesParameters" parent="def:Operator"/>
<region name="iptablesOtherOptions" parent="def:Comment"/>
<region name="iptablesMatchExtensions" parent="def:ParameterStrong"/>
<region name="iptablesTargetExtensions" parent="def:FunctionKeyword"/>
<region name="pyComment" parent="def:Comment"/>
<region name="pyOperator" parent="def:Operator"/>
<region name="pyDelimiter" parent="def:Symbol"/>
<scheme name="iptablesTable">
<keywords ignorecase="no" region="iptablesTable">
<word name="mangle"/>
<word name="filter"/>
<word name="nat"/>
<word name="as"/>
<word name="at"/>
<word name="asc"/>
<word name="avedev"/>
<word name="avg"/>
<word name="between"/>
<word name="by"/>
</keywords>
</scheme>
<scheme name="iptablesChainFilter">
<keywords ignorecase="no" region="iptablesChainFilter">
<word name="FORWARD"/>
<word name="INPUT"/>
<word name="OUTPUT"/>
</keywords>
</scheme>
<scheme name="iptablesChainNatMangle">
<keywords ignorecase="no" region="iptablesChainNatMangle">
<word name="PREROUTING"/>
<word name="POSTROUTING"/>
<word name="OUTPUT"/>
</keywords>
</scheme>
<scheme name="iptablesCustomDefaultChains">
<keywords ignorecase="no" region="iptablesCustomDefaultChains">
<word name="CHTTP"/>
<word name="CHTTPS"/>
<word name="CSSH"/>
<word name="CDNS"/>
<word name="CFTP"/>
<word name="CGERAL"/>
<word name="CICMP"/>
</keywords>
</scheme>
<scheme name="iptablesOptions">
<keywords ignorecase="no" region="iptablesOptions">
<word name="-A"/>
<word name="--append"/>
<word name="-D"/>
<word name="--delete"/>
<word name="-I"/>
<word name="--insert"/>
<word name="-R"/>
<word name="--replace"/>
<word name="-L"/>
<word name="--list"/>
<word name="-F"/>
<word name="--flush"/>
<word name="-Z"/>
<word name="--zero"/>
<word name="-N"/>
<word name="--new-chain"/>
<word name="-X"/>
<word name="--delete-chain"/>
<word name="-P"/>
<word name="--policy"/>
<word name="-E"/>
<word name="--rename-chain"/>
</keywords>
</scheme>
<scheme name="iptablesParameters">
<keywords ignorecase="no" region="iptablesParameters">
<word name="-p"/>
<word name="--protocol"/>
<word name="-s"/>
<word name="--source"/>
<word name="-d"/>
<word name="--destination"/>
<word name="-j"/>
<word name="--jump"/>
<word name="-g"/>
<word name="--goto"/>
<word name="-i"/>
<word name="--in-interface"/>
<word name="-o"/>
<word name="--out-interface"/>
<word name="-f"/>
<word name="--fragment"/>
<word name="-c"/>
<word name="--set-counters"/>
</keywords>
</scheme>
<scheme name="iptablesOtherOptions">
<keywords ignorecase="no" region="iptablesOtherOptions">
<word name="-v"/>
<word name="--verbose"/>
<word name="-n"/>
<word name="--numeric"/>
<word name="-x"/>
<word name="--exact"/>
<word name="--line-numbers"/>
<word name="--modprobe"/>
</keywords>
</scheme>
<scheme name="iptablesMatchExtensions">
<keywords ignorecase="no" region="iptablesMatchExtensions">
<word name="account"/>
<word name="addrtype"/>
<word name="childlevel"/>
<word name="comment"/>
<word name="connbytes"/>
<word name="connlimit"/>
<word name="connmark"/>
<word name="connrate"/>
<word name="conntrack"/>
<word name="dccp"/>
<word name="dscp"/>
<word name="dstlimit"/>
<word name="ecn"/>
<word name="esp"/>
<word name="hashlimit"/>
<word name="helper"/>
<word name="icmp"/>
<word name="ipv4options"/>
<word name="length"/>
<word name="limit"/>
<word name="mac"/>
<word name="mark"/>
<word name="mport"/>
<word name="multiport"/>
<word name="nth"/>
<word name="osf"/>
<word name="owner"/>
<word name="physdev"/>
<word name="pkttype"/>
<word name="policy"/>
<word name="psd"/>
<word name="quota"/>
<word name="realm"/>
<word name="recent"/>
<word name="sctp"/>
<word name="set"/>
<word name="state"/>
<word name="string"/>
<word name="tcp"/>
<word name="tcpmss"/>
<word name="tos"/>
<word name="u32"/>
<word name="udp"/>
</keywords>
</scheme>
<scheme name="iptablesTargetExtensions">
<keywords ignorecase="no" region="iptablesTargetExtensions">
<word name="BALANCE"/>
<word name="CLASSIFY"/>
<word name="CLUSTERIP"/>
<word name="CONNMARK"/>
<word name="DNAT"/>
<word name="DSCP"/>
<word name="ECN"/>
<word name="IPMARK"/>
<word name="IPV4OPTSSTRIP"/>
<word name="LOG"/>
<word name="MARK"/>
<word name="MASQUERADE"/>
<word name="MIRROR"/>
<word name="NETMAP"/>
<word name="NFQUEUE"/>
<word name="NOTRACK"/>
<word name="REDIRECT"/>
<word name="REJECT"/>
<word name="SAME"/>
<word name="SET"/>
<word name="SNAT"/>
<word name="TARPIT"/>
<word name="TCPMSS"/>
<word name="TOS"/>
<word name="TRACE"/>
<word name="TTL"/>
<word name="ULOG"/>
<word name="XOR"/>
</keywords>
</scheme>
<scheme name="iptables">
<inherit scheme="iptablesTable"/>
<inherit scheme="iptablesChainFilter"/>
<inherit scheme="iptablesChainNatMangle"/>
<inherit scheme="iptablesCustomDefaultChains"/>
<inherit scheme="iptablesOptions"/>
<inherit scheme="iptablesParameters"/>
<inherit scheme="iptablesOtherOptions"/>
<inherit scheme="iptablesMatchExtensions"/>
<inherit scheme="iptablesTargetExtensions"/>
<!-- python operators : http://docs.python.org/ref/keywords.html -->
<keywords region="pyOperator">
<symb name="+"/>
<symb name="-"/>
<symb name="*"/>
<symb name="**"/>
<symb name="/"/>
<symb name="//"/>
<symb name="%"/>
<symb name="<<"/>
<symb name=">>"/>
<symb name="&"/>
<symb name="|"/>
<symb name="^"/>
<symb name="~"/>
<symb name="<"/>
<symb name=">"/>
<symb name="<="/>
<symb name=">="/>
<symb name="=="/>
<symb name="!="/>
<symb name="<>"/>
</keywords>
<!-- basic python comment - consider it everything after # till the end of line -->
<block start="/#/" end="/$/" region="pyComment" scheme="def:Comment"/>
<block start="/(u|U)?(r|R)?("{3}|'{3})/" end="/\y3/"
region00="def:PairStart" region10="def:PairEnd"
scheme="def:Comment" region="pyComment" />
<!-- TODO: better scheme for multiline comments/docstrings -->
<!-- scheme="StringCommon" region="pyString" /> -->
<!-- python delimiters : http://docs.python.org/ref/delimiters.html -->
<keywords region="pyDelimiter">
<symb name="+"/>
<symb name="("/>
<symb name=")"/>
<symb name="["/>
<symb name="]"/>
<symb name="{"/>
<symb name="}"/>
<symb name="@"/>
<symb name=","/>
<symb name=":"/>
<symb name="."/>
<symb name="`"/>
<symb name="="/>
<symb name=";"/>
<symb name="+="/>
<symb name="-="/>
<symb name="*="/>
<symb name="/="/>
<symb name="//="/>
<symb name="%="/>
<symb name="&="/>
<symb name="|="/>
<symb name="^="/>
<symb name=">>="/>
<symb name="<<="/>
<symb name="**="/>
</keywords>
</scheme>
</type>
After this you must save the file as iptables.hcr and add inside the jar:
[EclipseFolder]/net.sf.colorer_0.9.9/colorer/hrc/common.jar
Ok, here is a better way to deal with Currency formats, delete-backward keystroke. The code is based on @androidcurious' code above... But, deals with some problems related to backwards-deletion and some parse exceptions: http://miguelt.blogspot.ca/2013/01/textwatcher-for-currency-masksformatting.html [UPDATE] The previous solution had some problems... This is a better solutoin: http://miguelt.blogspot.ca/2013/02/update-textwatcher-for-currency.html And... here are the details:
This approach is better since it uses the conventional Android mechanisms. The idea is to format values after the user exists the View.
Define an InputFilter to restrict the numeric values – this is required in most cases because the screen is not large enough to accommodate long EditText views. This can be a static inner class or just another plain class:
/** Numeric range Filter. */
class NumericRangeFilter implements InputFilter {
/** Maximum value. */
private final double maximum;
/** Minimum value. */
private final double minimum;
/** Creates a new filter between 0.00 and 999,999.99. */
NumericRangeFilter() {
this(0.00, 999999.99);
}
/** Creates a new filter.
* @param p_min Minimum value.
* @param p_max Maximum value.
*/
NumericRangeFilter(double p_min, double p_max) {
maximum = p_max;
minimum = p_min;
}
@Override
public CharSequence filter(
CharSequence p_source, int p_start,
int p_end, Spanned p_dest, int p_dstart, int p_dend
) {
try {
String v_valueStr = p_dest.toString().concat(p_source.toString());
double v_value = Double.parseDouble(v_valueStr);
if (v_value<=maximum && v_value>=minimum) {
// Returning null will make the EditText to accept more values.
return null;
}
} catch (NumberFormatException p_ex) {
// do nothing
}
// Value is out of range - return empty string.
return "";
}
}
Define a class (inner static or just a class) that will implement View.OnFocusChangeListener. Note that I'm using an Utils class - the implementation can be found at "Amounts, Taxes".
/** Used to format the amount views. */
class AmountOnFocusChangeListener implements View.OnFocusChangeListener {
@Override
public void onFocusChange(View p_view, boolean p_hasFocus) {
// This listener will be attached to any view containing amounts.
EditText v_amountView = (EditText)p_view;
if (p_hasFocus) {
// v_value is using a currency mask - transfor over to cents.
String v_value = v_amountView.getText().toString();
int v_cents = Utils.parseAmountToCents(v_value);
// Now, format cents to an amount (without currency mask)
v_value = Utils.formatCentsToAmount(v_cents);
v_amountView.setText(v_value);
// Select all so the user can overwrite the entire amount in one shot.
v_amountView.selectAll();
} else {
// v_value is not using a currency mask - transfor over to cents.
String v_value = v_amountView.getText().toString();
int v_cents = Utils.parseAmountToCents(v_value);
// Now, format cents to an amount (with currency mask)
v_value = Utils.formatCentsToCurrency(v_cents);
v_amountView.setText(v_value);
}
}
}
This class will remove the currency format when editing - relying on standard mechanisms. When the user exits, the currency format is re-applied.
It's better to define some static variables to minimize the number of instances:
static final InputFilter[] FILTERS = new InputFilter[] {new NumericRangeFilter()};
static final View.OnFocusChangeListener ON_FOCUS = new AmountOnFocusChangeListener();
Finally, within the onCreateView(...):
EditText mAmountView = ....
mAmountView.setFilters(FILTERS);
mAmountView.setOnFocusChangeListener(ON_FOCUS);
You can reuse FILTERS and ON_FOCUS on any number of EditText views.
Here is the Utils class:
public class Utils {
private static final NumberFormat FORMAT_CURRENCY = NumberFormat.getCurrencyInstance();
/** Parses an amount into cents.
* @param p_value Amount formatted using the default currency.
* @return Value as cents.
*/
public static int parseAmountToCents(String p_value) {
try {
Number v_value = FORMAT_CURRENCY.parse(p_value);
BigDecimal v_bigDec = new BigDecimal(v_value.doubleValue());
v_bigDec = v_bigDec.setScale(2, BigDecimal.ROUND_HALF_UP);
return v_bigDec.movePointRight(2).intValue();
} catch (ParseException p_ex) {
try {
// p_value doesn't have a currency format.
BigDecimal v_bigDec = new BigDecimal(p_value);
v_bigDec = v_bigDec.setScale(2, BigDecimal.ROUND_HALF_UP);
return v_bigDec.movePointRight(2).intValue();
} catch (NumberFormatException p_ex1) {
return -1;
}
}
}
/** Formats cents into a valid amount using the default currency.
* @param p_value Value as cents
* @return Amount formatted using a currency.
*/
public static String formatCentsToAmount(int p_value) {
BigDecimal v_bigDec = new BigDecimal(p_value);
v_bigDec = v_bigDec.setScale(2, BigDecimal.ROUND_HALF_UP);
v_bigDec = v_bigDec.movePointLeft(2);
String v_currency = FORMAT_CURRENCY.format(v_bigDec.doubleValue());
return v_currency.replace(FORMAT_CURRENCY.getCurrency().getSymbol(), "").replace(",", "");
}
/** Formats cents into a valid amount using the default currency.
* @param p_value Value as cents
* @return Amount formatted using a currency.
*/
public static String formatCentsToCurrency(int p_value) {
BigDecimal v_bigDec = new BigDecimal(p_value);
v_bigDec = v_bigDec.setScale(2, BigDecimal.ROUND_HALF_UP);
v_bigDec = v_bigDec.movePointLeft(2);
return FORMAT_CURRENCY.format(v_bigDec.doubleValue());
}
}
As User Mr. Brownstone
suggested you can use a stored procedure; to make it easy for all i created a minimalist example. First create a stored procedure:
Create PROCEDURE MultipleOutParameter
@Input int,
@Out1 int OUTPUT,
@Out2 int OUTPUT
AS
BEGIN
Select @Out1 = @Input + 1
Select @Out2 = @Input + 2
Select 'this returns your normal Select-Statement' as Foo
, 'amazing is it not?' as Bar
-- Return can be used to get even more (afaik only int) values
Return(@Out1+@Out2+@Input)
END
To execute the stored procedure a few local variables are needed to receive the value:
DECLARE @GetReturnResult int, @GetOut1 int, @GetOut2 int
EXEC @GetReturnResult = MultipleOutParameter
@Input = 1,
@Out1 = @GetOut1 OUTPUT,
@Out2 = @GetOut2 OUTPUT
To see the values content you can do the following
Select @GetReturnResult as ReturnResult, @GetOut1 as Out_1, @GetOut2 as Out_2
This will be the result:
brew switch libfoo mycopy
You can use brew switch
to switch between versions of the same package, if it's installed as versioned subdirectories under Cellar/<packagename>/
This will list versions installed ( for example I had Cellar/sdl2/2.0.3
, I've compiled into Cellar/sdl2/2.0.4
)
brew info sdl2
Then to switch between them
brew switch sdl2 2.0.4
brew info
Info now shows *
next to the 2.0.4
To install under Cellar/<packagename>/<version>
from source you can do for example
cd ~/somewhere/src/foo-2.0.4
./configure --prefix $(brew --Cellar)/foo/2.0.4
make
check where it gets installed with
make install -n
if all looks correct
make install
Then from cd $(brew --Cellar)
do the switch between version.
I'm using brew version 0.9.5
Add a Console.Read();
at the end of your program. It'll keep the application from closing, and you can see its output that way.
This is a console application I just dug up that stops after processing but before exiting:
class Program
{
static void Main(string[] args)
{
DummyObjectList dol = new DummyObjectList(2);
dol.Add(new DummyObject("test1", (Decimal)25.36));
dol.Add(new DummyObject("test2", (Decimal)0.698));
XmlSerializer dolxs = new XmlSerializer(typeof(DummyObjectList));
dolxs.Serialize(Console.Out, dol);
Console.WriteLine(string.Empty);
Console.WriteLine(string.Empty);
List<DummyObject> dolist = new List<DummyObject>(2);
dolist.Add(new DummyObject("test1", (Decimal)25.36));
dolist.Add(new DummyObject("test2", (Decimal)0.698));
XmlSerializer dolistxs = new XmlSerializer(typeof(List<DummyObject>));
dolistxs.Serialize(Console.Out, dolist);
Console.Read(); // <--- Right here
}
}
Alternatively, you can simply add a breakpoint on the last line.
A list is considered to be False
if it has no elements, so you can do something like this:
{% if mylist %}
<p>I have a list!</p>
{% else %}
<p>I don't have a list!</p>
{% endif %}
First, don't use update panels. They are the second most evil thing that Microsoft has ever created for the web developer.
Second, if you must use update panels, try setting the UpdateMode property to Conditional. Then add a trigger to an Asp:Hidden control that you add to the page. Assign the change event as the trigger. In your dragstop event, change the value of the hidden control.
This is untested, but the theory seems sound... If this does not work, you could try the same thing with an asp:button, just set the display:none style on it and use the click event instead of the change event.
As of 2020, using ContentResult
is still the right approach as proposed above, but the usage is as follows:
return new System.Web.Mvc.ContentResult
{
Content = "Hi there! ?",
ContentType = "text/plain; charset=utf-8"
}
You can use DistinctBy() for getting Distinct records by an object property. Just add the following statement before using it:
using Microsoft.Ajax.Utilities;
and then use it like following:
var listToReturn = responseList.DistinctBy(x => x.Index).ToList();
where 'Index' is the property on which i want the data to be distinct.
I'm posting this answer because the one with the most votes led me astray. To redirect from a servlet, you simply do this:
response.sendRedirect("simpleList.do")
In this particular question, I think @M-D is correctly explaining why the asker is having his problem, but since this is the first result on google when you search for "Redirect from Servlet" I think it's important to have an answer that helps most people, not just the original asker.
Just becuase your class object has no variables does not mean that it is nothing. Declaring and object and creating an object are two different things. Look and see if you are setting/creating the object.
Take for instance the dictionary object - just because it contains no variables does not mean it has not been created.
Sub test()
Dim dict As Object
Set dict = CreateObject("scripting.dictionary")
If Not dict Is Nothing Then
MsgBox "Dict is something!" '<--- This shows
Else
MsgBox "Dict is nothing!"
End If
End Sub
However if you declare an object but never create it, it's nothing.
Sub test()
Dim temp As Object
If Not temp Is Nothing Then
MsgBox "Temp is something!"
Else
MsgBox "Temp is nothing!" '<---- This shows
End If
End Sub
Above solutions did not work for me as the issue with open JDK 13 version https://github.com/spotify/dockerfile-maven/issues/163 So I degraded to open JDK8 and it works for me
Possibly the problem is your two constructor overloads, one that sets the border, the other that doesn't:
public GoBoard(){
this.linien = 9;
this.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
}
public GoBoard(int pLinien){
this.linien = pLinien;
}
If you create a GoBoard object with the second constructor and pass an int parameter, the empty border will not be created. To fix this, consider changing this so both constructors set the border:
// default constructor
public GoBoard(){
this(9); // calls other constructor
}
public GoBoard(int pLinien){
this.linien = pLinien;
this.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
}
edit 1: The border you've added is more for controlling how components are added to your JPanel. If you want to draw in your one JPanel but have a border around the drawing, consider placing this JPanel into another JPanel, a holding JPanel that has the border. For e.g.,
class GoTest {
private static final int JB_WIDTH = 400;
private static final int JB_HEIGHT = JB_WIDTH;
private static void initGui() {
JFrame frame = new JFrame("GoBoard");
GoBoard jboard = new GoBoard();
jboard.setLayout(new BorderLayout(10, 10));
JPanel holdingPanel = new JPanel(new BorderLayout());
int eb = 20;
holdingPanel.setBorder(BorderFactory.createEmptyBorder(0, eb, eb, eb));
holdingPanel.add(jboard, BorderLayout.CENTER);
frame.add(holdingPanel, BorderLayout.CENTER);
jboard.setPreferredSize(new Dimension(JB_WIDTH, JB_HEIGHT));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//!! frame.setSize(400, 400);
frame.pack();
frame.setVisible(true);
}
// .... etc....
SELECT * from TABLE
WHERE 1 = CASE when TABLE.col = 100 then 1
when TABLE.col = 200 then 2 else 3 END
and TABLE.col2 = 'myname';
Use in this way.
As an addition to @C??? answer, make sure the title of the tooltip has not already been set manually in the HTML element. In my case, the span class for the tooltip already had a fixed tittle text, because of this my JQuery function $('[data-toggle="tooltip"]').prop('title', 'your new title');
did not work.
When I removed the title attribute in the HTML span class, the jQuery was working.
So:
<span class="showTooltip" data-target="#showTooltip" data-id="showTooltip">
<span id="MyTooltip" class="fas fa-info-circle" data-toggle="tooltip" data-placement="top" title="this is my pre-set title text"></span>
</span>
Should becode:
<span class="showTooltip" data-target="#showTooltip" data-id="showTooltip">
<span id="MyTooltip" class="fas fa-info-circle" data-toggle="tooltip" data-placement="top"></span>
</span>
changing:
collection.fetch({ data: { page: 1} });
to:
collection.fetch({ data: $.param({ page: 1}) });
So with out over doing it, this is called with your {data: {page:1}}
object as options
Backbone.sync = function(method, model, options) {
var type = methodMap[method];
// Default JSON-request options.
var params = _.extend({
type: type,
dataType: 'json',
processData: false
}, options);
// Ensure that we have a URL.
if (!params.url) {
params.url = getUrl(model) || urlError();
}
// Ensure that we have the appropriate request data.
if (!params.data && model && (method == 'create' || method == 'update')) {
params.contentType = 'application/json';
params.data = JSON.stringify(model.toJSON());
}
// For older servers, emulate JSON by encoding the request into an HTML-form.
if (Backbone.emulateJSON) {
params.contentType = 'application/x-www-form-urlencoded';
params.processData = true;
params.data = params.data ? {model : params.data} : {};
}
// For older servers, emulate HTTP by mimicking the HTTP method with `_method`
// And an `X-HTTP-Method-Override` header.
if (Backbone.emulateHTTP) {
if (type === 'PUT' || type === 'DELETE') {
if (Backbone.emulateJSON) params.data._method = type;
params.type = 'POST';
params.beforeSend = function(xhr) {
xhr.setRequestHeader('X-HTTP-Method-Override', type);
};
}
}
// Make the request.
return $.ajax(params);
};
So it sends the 'data' to jQuery.ajax which will do its best to append whatever params.data
is to the URL.
here's another solution for Python3:
import csv
with open(filename, "r") as csvfile:
datareader = csv.reader(csvfile)
count = 0
for row in datareader:
if row[3] in ("column header", criterion):
doSomething(row)
count += 1
elif count > 2:
break
here datareader
is a generator function.
To help with this I created a function to make this more easy to achieve it.
public static <T> void forEachCurrent(List<T> list, Consumer<T> action) {
final int size = list.size();
for (int i = 0; i < size; i++) {
action.accept(list.get(i));
}
}
Example
List<String> l = new ArrayList<>();
l.add("1");
l.add("2");
l.add("3");
forEachCurrent(l, e -> {
l.add(e + "A");
l.add(e + "B");
l.add(e + "C");
});
l.forEach(System.out::println);
In Express 4.x you can use req.hostname
, which returns the domain name, without port. i.e.:
// Host: "example.com:3000"
req.hostname
// => "example.com"
You can also use DBMS_METADATA:
select dbms_metadata.get_ddl('FUNCTION', 'FGETALGOGROUPKEY', 'PADCAMPAIGN')
from dual
This simple method will work for most cases, but would trip up over something like "u005Cu005C" which should decode to the string "\u0048" but would actually decode "H" as the first pass produces "\u0048" as the working string which then gets processed again by the while loop.
static final String decode(final String in)
{
String working = in;
int index;
index = working.indexOf("\\u");
while(index > -1)
{
int length = working.length();
if(index > (length-6))break;
int numStart = index + 2;
int numFinish = numStart + 4;
String substring = working.substring(numStart, numFinish);
int number = Integer.parseInt(substring,16);
String stringStart = working.substring(0, index);
String stringEnd = working.substring(numFinish);
working = stringStart + ((char)number) + stringEnd;
index = working.indexOf("\\u");
}
return working;
}
How about this? Here, pElement
refers to the element you want this div
inside (to be a child of! :).
$("pElement").append("<div></div");
You can easily add anything more to that div
in the string - Attributes, Content, you name it. Do note, for attribute values, you need to use the right quotation marks.
make sure your css reads:
margin: 0 auto;
Even though you're saying you have the left and right set to auto, you may be placing an error. Of course we wouldn't know though because you did not show us any code.
In C/C++ Build -> Builder Settings, select Internal builder (instead of External builder).
It works for me.
No there isn't. Instead use a while
loop such as:
while 1:
...statements...
if cond:
break
I viewed the Eclipse ADT documentation and found out the way to get around this issue. I was able to Update My SDK Tool to 22.0.4 (Latest Version).
Solution is: First Update ADT to 22.0.4 and then Update SDK Tool to 22.0.4
The above link says,
ADT 22.0.4 is designed for use with SDK Tools r22.0.4. If you haven't already installed SDK Tools r22.0.4 into your SDK, use the Android SDK Manager to do so
What I had to do was update my ADT to 22.0.4 (Latest Version) and then I was able to update SDK tool to 22.0.4. I thought only SDK Tool has been updated not ADT, so I was updating the SDK Tool with Older ADT Version (22.0.1).
How to Update your ADT to Latest Version
In Eclipse go to Help
Install New Software
---> Add
inside Add Repository write the Name: ADT
(or whatever you want)
Location: https://dl-ssl.google.com/android/eclipse/
after loading you should get Developer Tools and NDK Plugins
check both if you want to use the Native Developer Kit (NDK) in the future or check
Developer Tool only
click Next
Finish
You probably want an extra wrapper. use a div for the background and position it below your content..
http://jsfiddle.net/pixelass/42F2j/
HTML
<div id="background-image"></div>
<div id="content">
Here is the content at opacity 1
<img src="http://lorempixel.com/100/50/fashion/1/">
</div>
CSS
#background-image {
background-image: url(http://lorempixel.com/400/200/sports/1/);
opacity:0.4;
position:absolute;
top:0;
left:0;
height:200px;
width:400px;
z-index:0;
}
#content {
z-index:1;
position:relative;
}
Check host file which like this
##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting. Do not change this entry.
##
127.0.0.1 localhost
255.255.255.255 broadcasthost
The property pDoc.parentElement
or pDoc.parentNode
will get you the parent element.
The first important thing is the meaning of GET versus POST :
After that, a couple of things that can be noted :
Anyway, I don't think we could "live" without GET : think of how many URLs you are using with parameters in the query string, every day -- without GET, all those wouldn't work ;-)
You can use the following to get where the registry thinks it's installed:
(string)Registry.LocalMachine.GetValue(@"SOFTWARE\MyApplication\AppPath",
"Installed", null);
Or you can use the following to find out where the application is actually being launched from:
System.Windows.Forms.Application.StartupPath
The latter is more reliable than the former if you're trying to use the .exe
location as a relative path to find related files. The user could easily move things around after the install and still have the app work fine because .NET apps aren't so dependent upon the registry.
Using StartupPath
, you could even do something clever like have your app update the registry entries at run time instead of crashing miserably due to missing/wrong/corrupted entries.
And be sure to look at the app settings functionality as storage for values rather than the registry (Properties.Settings.Default.mySettingEtc
). You can read/write settings for the app and/or the user levels that get saved as simple MyApp.exe.config
files in standard locations. A nice blast from the past (good old Win 3.1/DOS days) to have the application install/delete be a simple copy/delete of a folder structure or two rather than some convoluted, arcane install/uninstall routine that leaves all kinds of garbage in the registry and sprinkled all over the hard drive.
Use it:
function validate_Date($mydate,$format = 'DD-MM-YYYY') {
if ($format == 'YYYY-MM-DD') list($year, $month, $day) = explode('-', $mydate);
if ($format == 'YYYY/MM/DD') list($year, $month, $day) = explode('/', $mydate);
if ($format == 'YYYY.MM.DD') list($year, $month, $day) = explode('.', $mydate);
if ($format == 'DD-MM-YYYY') list($day, $month, $year) = explode('-', $mydate);
if ($format == 'DD/MM/YYYY') list($day, $month, $year) = explode('/', $mydate);
if ($format == 'DD.MM.YYYY') list($day, $month, $year) = explode('.', $mydate);
if ($format == 'MM-DD-YYYY') list($month, $day, $year) = explode('-', $mydate);
if ($format == 'MM/DD/YYYY') list($month, $day, $year) = explode('/', $mydate);
if ($format == 'MM.DD.YYYY') list($month, $day, $year) = explode('.', $mydate);
if (is_numeric($year) && is_numeric($month) && is_numeric($day))
return checkdate($month,$day,$year);
return false;
}
$scope.$watch('myVar', function (newValue, oldValue) {
if (typeof (newValue) !== 'undefined') {
$scope.someothervar= newValue;
//or get some data
getData();
}
}, true);
Variable initializes after controller so you need to watch over it and when it't initialized the use it.
I keep this function handy for whenever I need it, and change the column names and classes to suit the use case:
make_df <- function() { data.frame(name=character(),
profile=character(),
sector=character(),
type=character(),
year_range=character(),
link=character(),
stringsAsFactors = F)
}
make_df()
[1] name profile sector type year_range link
<0 rows> (or 0-length row.names)
Check your project's build settings under 'Apple LLVM - Preprocessing', 'Preprocessor Macros' for debug to ensure that DEBUG
is being set - do this by selecting the project and clicking on the build settings tab. Search for DEBUG
and look to see if indeed DEBUG
is being set.
Pay attention though. You may see DEBUG changed to another variable name such as DEBUG_MODE.
then conditionally code for DEBUG in your source files
#ifdef DEBUG
// Something to log your sensitive data here
#else
//
#endif
I use withRouter
to get the location
prop. When the component is updated because of a new route, I check if the value changed:
@withRouter
class App extends React.Component {
static propTypes = {
location: React.PropTypes.object.isRequired
}
// ...
componentDidUpdate(prevProps) {
if (this.props.location !== prevProps.location) {
this.onRouteChanged();
}
}
onRouteChanged() {
console.log("ROUTE CHANGED");
}
// ...
render(){
return <Switch>
<Route path="/" exact component={HomePage} />
<Route path="/checkout" component={CheckoutPage} />
<Route path="/success" component={SuccessPage} />
// ...
<Route component={NotFound} />
</Switch>
}
}
Hope it helps
Using post jquery instead helped me to solve this problem
$.post('url', data, function(response) {
console.log(response);
});
This is resolved. The problem was elsewhere. Another code in cron job was truncating XML to 0 length file. I have taken care of that.
This answer from askubuntu is what worked for me. Seems simpler than other options an less error-prone, since it uses package libgtest-dev
to get the sources and builds from there: https://askubuntu.com/questions/145887/why-no-library-files-installed-for-google-test?answertab=votes#tab-top
Please refer to that answer, but just as a shortcut I provide the steps here as well:
sudo apt-get install -y libgtest-dev
sudo apt-get install -y cmake
cd /usr/src/gtest
sudo cmake .
sudo make
sudo mv libg* /usr/lib/
After that, I could build my project which depends on gtest
with no issues.
The preferred way to get the length of any python object is to pass it as an argument to the len
function. Internally, python will then try to call the special __len__
method of the object that was passed.
I use numbers tables for primarily dummying up reports in BIRT without having to fiddle around with dynamic creation of recordsets.
I do the same with dates, having a table spanning from 10 years in the past to 10 years in the future (and hours of the day for more detailed reporting). It's a neat trick to be able to get values for all dates even if your 'real' data tables don't have data for them.
I have a script which I use to create these, something like (this is from memory):
drop table numbers; commit;
create table numbers (n integer primary key); commit;
insert into numbers values (0); commit;
insert into numbers select n+1 from numbers; commit;
insert into numbers select n+2 from numbers; commit;
insert into numbers select n+4 from numbers; commit;
insert into numbers select n+8 from numbers; commit;
insert into numbers select n+16 from numbers; commit;
insert into numbers select n+32 from numbers; commit;
insert into numbers select n+64 from numbers; commit;
The number of rows doubles with each line so it doesn't take a lot to produce truly huge tables.
I'm not sure I agree with you that it's important to be created fast since you only create it once. The cost of that is amortized over all the accesses to it, rendering that time fairly insignificant.
At least in .NET 4.5+ you can also do:
var uri = new System.Uri("C:\\foo", UriKind.Absolute);
I just got this error while trying to push stuff into a new repository on GitHub. I had created the Git repository locally, plus I had created the repository on GitHub using the Web GUI (including a LICENSE file).
The problem went away after I pulled the LICENSE file from the otherwise empty GitHub repository into my local repository. After that, I could push with no problems.
Luckily git stash pop
does not change the stash in the case of a conflict!
So nothing, to worry about, just clean up your code and try it again.
Say your codebase was clean before, you could go back to that state with: git checkout -f
Then do the stuff you forgot, e.g. git merge missing-branch
After that just fire git stash pop
again and you get the same stash, that conflicted before.
Keep in mind: The stash is safe, however, uncommitted changes in the working directory are of course not. They can get messed up.
Yes,
You can download Xcode with/without Paid (Premium) Apple Developer Account from below links.
Xcode 11
Xcode 11.3
- (Command Line Tool (Xcode 11.3) - for macOS 10.14)Xcode 11.2.1
- (Command Line Tool (Xcode 11.2 beta 2) - for macOS 10.14)Xcode 10
Xcode 10.2.1
- (Command Line Tool (Xcode 10.2.1) - for macOS 10.14)Xcode 10.2
- (Command Line Tool (Xcode 10.2) - for macOS 10.14)Xcode 10.1
- (Command Line Tool (Xcode 10.1) - for macOS 10.14)
- (Command Line Tool (Xcode 10.1) - for macOS 10.13)Xcode 10
- (Command Line Tool (Xcode 10) - for macOS 10.14)
- (Command Line Tool (Xcode 10) - for macOS 10.13)
For non-premium account/apple id: (Download Xcode 10 without Paid (Premium) Apple Developer Account from below link)
Look at here: How to install & set command line tool
See here for older versions of Xcode (Which may need to authenticate your apple account):
Just thought I'd post yet another way of doing the same thing.
function guid() {
var chars = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];
var str = "";
for(var i=0;i<36;i++) {
var str = str + ((i == 8 || i == 13 || i == 18 || i == 23) ? "-" : chars[Math.floor(Math.random()*chars.length)]);
};
return str;
}
There is no easy way to emulate fork() on Windows.
I suggest you to use threads instead.
The result is not a String
but a String[]
. That's why you get this unsuspected printout.
[Ljava.lang.String
is a signature of an array of String
:
System.out.println(new String[]{});
Working with just one selector:
select {
width: 268px;
padding: 5px;
font-size: 16px;
line-height: 1;
border: 0;
border-radius: 5px;
height: 34px;
background: url(http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png) no-repeat right #ddd;
-webkit-appearance: none;
background-position-x: 244px;
}
First of all we will get source and destination points between which we have to draw route. Then we will pass these attribute to below function.
public String makeURL (double sourcelat, double sourcelog, double destlat, double destlog ){
StringBuilder urlString = new StringBuilder();
urlString.append("http://maps.googleapis.com/maps/api/directions/json");
urlString.append("?origin=");// from
urlString.append(Double.toString(sourcelat));
urlString.append(",");
urlString.append(Double.toString( sourcelog));
urlString.append("&destination=");// to
urlString.append(Double.toString( destlat));
urlString.append(",");
urlString.append(Double.toString( destlog));
urlString.append("&sensor=false&mode=driving&alternatives=true");
urlString.append("&key=YOUR_API_KEY");
return urlString.toString();
}
This function will make the url that we will send to get Direction API response. Then we will parse that response . The parser class is
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public String getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
json = sb.toString();
is.close();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return json;
}
}
This parser will return us string. We will call it like that.
JSONParser jParser = new JSONParser();
String json = jParser.getJSONFromUrl(url);
Now we will send this string to our drawpath function. The drawpath function is
public void drawPath(String result) {
try {
//Tranform the string into a json object
final JSONObject json = new JSONObject(result);
JSONArray routeArray = json.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
List<LatLng> list = decodePoly(encodedString);
Polyline line = mMap.addPolyline(new PolylineOptions()
.addAll(list)
.width(12)
.color(Color.parseColor("#05b1fb"))//Google maps blue color
.geodesic(true)
);
/*
for(int z = 0; z<list.size()-1;z++){
LatLng src= list.get(z);
LatLng dest= list.get(z+1);
Polyline line = mMap.addPolyline(new PolylineOptions()
.add(new LatLng(src.latitude, src.longitude), new LatLng(dest.latitude, dest.longitude))
.width(2)
.color(Color.BLUE).geodesic(true));
}
*/
}
catch (JSONException e) {
}
}
Above code will draw the path on mMap. The code of decodePoly is
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng( (((double) lat / 1E5)),
(((double) lng / 1E5) ));
poly.add(p);
}
return poly;
}
As direction call may take time so we will do all this in Asynchronous task. My Asynchronous task was
private class connectAsyncTask extends AsyncTask<Void, Void, String>{
private ProgressDialog progressDialog;
String url;
connectAsyncTask(String urlPass){
url = urlPass;
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Fetching route, Please wait...");
progressDialog.setIndeterminate(true);
progressDialog.show();
}
@Override
protected String doInBackground(Void... params) {
JSONParser jParser = new JSONParser();
String json = jParser.getJSONFromUrl(url);
return json;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.hide();
if(result!=null){
drawPath(result);
}
}
}
I hope it will help.
If you do not have Administrator access to the MySQL Server configuration (i.e. you are using a hosting service), then there are 2 options to get this to work:
1) Request that the old_passwords option be set to false on the MySQL server
2) Downgrade PHP to 5.2.2 until option 1 occurs.
From what I've been able to find, the issue seems to be with how the MySQL account passwords are stored and if the 'old_passwords' setting is set to true. This causes a compatibility issue between MySQL and newer versions of PHP (5.3+) where PHP attempts to connect using a 41-character hash but the MySQL server is still storing account passwords using a 16-character hash.
This incompatibility was brought about by the changing of the hashing method used in MySQL 4.1 which allows for both short and long hash lengths (Scenario 2 on this page from the MySQL site: http://dev.mysql.com/doc/refman/5.5/en/password-hashing.html) and the inclusion of the MySQL Native Driver in PHP 5.3 (backwards compatibility issue documented on bullet 7 of this page from the PHP documentation: http://www.php.net/manual/en/migration53.incompatible.php).
I am trying to do something similar to this. As commented above, I think you would want to build a new image with a custom Dockerfile (using the image you pulled as a base image), ADD
your certificate, then RUN update-ca-certificates
. This way you will have a consistent state each time you start a container from this new image.
# Dockerfile
FROM some-base-image:0.1
ADD you_certificate.crt:/container/cert/path
RUN update-ca-certificates
Let's say a docker build
against that Dockerfile produced IMAGE_ID. On the next docker run -d [any other options] IMAGE_ID
, the container started by that command will have your certificate info. Simple and reproducible.
if (!$(row).hasClass("changed")) {
// do your stuff
}
For a StopWatch helper class, here is my solution which gives you precision on output and also access to the raw start time:
class StopWatch:
def __init__(self):
self.start()
def start(self):
self._startTime = time.time()
def getStartTime(self):
return self._startTime
def elapsed(self, prec=3):
prec = 3 if prec is None or not isinstance(prec, (int, long)) else prec
diff= time.time() - self._startTime
return round(diff, prec)
def round(n, p=0):
m = 10 ** p
return math.floor(n * m + 0.5) / m
You can start with Instant.ofEpochMilli(long):
LocalDate date =
Instant.ofEpochMilli(startDateLong)
.atZone(ZoneId.systemDefault())
.toLocalDate();
I believe you are trying to compare two strings representing values, the function you are looking for is:
int atoi(const char *nptr);
or
long int strtol(const char *nptr, char **endptr, int base);
these functions will allow you to convert a string to an int/long int:
int val = strtol("555", NULL, 10);
and compare it to another value.
int main (int argc, char *argv[])
{
long int val = 0;
if (argc < 2)
{
fprintf(stderr, "Usage: %s number\n", argv[0]);
exit(EXIT_FAILURE);
}
val = strtol(argv[1], NULL, 10);
printf("%d is %s than 555\n", val, val > 555 ? "bigger" : "smaller");
return 0;
}
One good way to further your Python knowledge is to dig into the source code of the libraries, platforms, and frameworks you use already.
For example if you're building a site on Django, many questions that might stump you can be answered by looking at how Django implements the feature in question.
This way you'll continue to pick up new idioms, coding styles, and Python tricks. (Some will be good and some will be bad.)
And when you see something Pythony that you don't understand in the source, hop over to the #python IRC channel and you'll find plenty of "language lawyers" happy to explain.
An accumulation of these little clarifications over years leads to a much deeper understanding of the language and all of its ins and outs.
Do this:
if (denominator == 0) throw new ArithmeticException("denominator == 0");
ArithmeticException is the exception which is normally thrown when you divide by 0.
If you are parsing string data from the console or similar, the best way is to use regular expressions. Read more on that here: http://java.sun.com/developer/technicalArticles/releases/1.4regex/
Otherwise, to parse an int from a string, try Integer.parseInt(string). If the string is not a number, you will get an exception. Otherise you can then perform your checks on that value to make sure it is not negative.
String input;
int number;
try
{
number = Integer.parseInt(input);
if(number > 0)
{
System.out.println("You positive number is " + number);
}
} catch (NumberFormatException ex)
{
System.out.println("That is not a positive number!");
}
To get a character-only string, you would probably be better of looping over each character checking for digits, using for instance Character.isLetter(char).
String input
for(int i = 0; i<input.length(); i++)
{
if(!Character.isLetter(input.charAt(i)))
{
System.out.println("This string does not contain only letters!");
break;
}
}
Good luck!
In your public View getView
method change return null;
to return convertView;
.
Adding display: inline-block;
to the p
styling should take of it:
#container p{
background-color: green;
display: inline-block;
}
In addition to what's already been said, don't use ToString()
on the exception object for displaying to the user. Just the Message
property should suffice, or a higher level custom message.
In terms of logging purposes, definitely use ToString()
on the Exception, not just the Message
property, as in most scenarios, you will be left scratching your head where specifically this exception occurred, and what the call stack was. The stacktrace would have told you all that.
Try to create script with ADD
command and specification of working directory
Like this("script" is the name of script and /root/script.sh
is where you want it in the container, it can be different path:
ADD script.sh /root/script.sh
In this case ADD
has to come before CMD
, if you have one
BTW it's cool way to import scripts to any location in container from host machine
In CMD
place [./script]
It should automatically execute your script
You can also specify WORKDIR
as /root
, then you'l be automatically placed in root, upon starting a container
You need to leverage the @ViewChild
decorator to reference the child component from the parent one by injection:
import { Component, ViewChild } from 'angular2/core';
(...)
@Component({
selector: 'my-app',
template: `
<h1>My First Angular 2 App</h1>
<child></child>
<button (click)="submit()">Submit</button>
`,
directives:[App]
})
export class AppComponent {
@ViewChild(Child) child:Child;
(...)
someOtherMethod() {
this.searchBar.someMethod();
}
}
Here is the updated plunkr: http://plnkr.co/edit/mrVK2j3hJQ04n8vlXLXt?p=preview.
You can notice that the @Query
parameter decorator could also be used:
export class AppComponent {
constructor(@Query(Child) children:QueryList<Child>) {
this.childcmp = children.first();
}
(...)
}
The PHP manual explains both quite well:
http://php.net/manual/en/reserved.variables.server.php # REQUEST_URI
http://php.net/manual/en/reserved.variables.get.php # for the $_GET["q"] variable
You can connect two iPhones and transfer data via Bluetooth using either the high-level GameKit framework or the lower-level (but still easy to work with) Bonjour discovery mechanisms. Bonjour also works transparently between Bluetooth and WiFi on the iPhone under 3.0, so it's a good choice if you would like to support iPhone-to-iPhone data transfers on those two types of networks.
For more information, you can also look at the responses to these questions:
How about something based on Douglas Crockford idea:
function Shape(){}
Shape.prototype.name = 'Shape';
Shape.prototype.toString = function(){
return this.constructor.parent
? this.constructor.parent.toString() + ',' + this.name
: this.name;
};
function TwoDShape(){}
var F = function(){};
F.prototype = Shape.prototype;
TwoDShape.prototype = new F();
TwoDShape.prototype.constructor = TwoDShape;
TwoDShape.parent = Shape.prototype;
TwoDShape.prototype.name = '2D Shape';
var my = new TwoDShape();
console.log(my.toString()); ===> Shape,2D Shape
If you want to keep it open when you are debugging, but still let it close normally when not debugging, you can do something like this:
if (System.Diagnostics.Debugger.IsAttached) Console.ReadLine();
Like other answers have stated, the call to Console.ReadLine()
will keep the window open until enter is pressed, but Console.ReadLine()
will only be called if the debugger is attached.
To disable a specific rule for the file:
/* eslint-disable no-use-before-define */
Note there is a bug in eslint where single line comment will not work -
// eslint-disable max-classes-per-file
// This fails!
eduffy had a good idea. He just got it backwards in his code example. Either in JavaScript or in SQLite you can replace the apostrophe with the accent symbol.
He (accidentally I am sure) placed the accent symbol as the delimiter for the string instead of replacing the apostrophe in O'Brian. This is in fact a terrifically simple solution for most cases.
But for any future bypassers you could mention that df = df[df.line_race != 0]
doesn't do anything when trying to filter for None
/missing values.
Does work:
df = df[df.line_race != 0]
Doesn't do anything:
df = df[df.line_race != None]
Does work:
df = df[df.line_race.notnull()]
If you do not want to include that your code script (as advised by others above), then simply you may do the following after generating the figure window:
Go to "Edit" in the figure window
Go to "Figure Properties"
At the bottom, you can type the name you want in "Figure Name" field. You can uncheck "Show Figure Number".
That's all.
Good luck.
For mysqli on Docker's official php containers:
Tagged php versions that support mysqli may still not come with mysqli configured out of the box, You can install it with the docker-php-ext-install
utility (see comment by Konstantin). This is built-in, but also available from the docker-php-extension-installer project.
They can be used to add mysqli either in a Dockerfile, for example:
FROM php:5.6.5-apache
COPY ./php.ini /usr/local/etc/php/
RUN docker-php-ext-install mysqli
or in a compose file that uses a generic php container and then injects mysqli installation as a setup step into command
:
web:
image: php:5.6.5-apache
volumes:
- app:/var/www/html/
ports:
- "80:80"
command: >
sh -c "docker-php-ext-install mysqli &&
apache2-foreground"
This worked for me on iOS 5.0 simulator.
Run the app on the simulator.
Go to the path where you can see something like this:
/Users/arshad/Library/Application\ Support/iPhone\ Simulator/5.0/Applications/34BC3FDC-7398-42D4-9114-D5FEFC737512/…
Copy all the package contents including the app, lib, temp and Documents.
Clear all the applications installed on the simulator so that it is easier to see what is happening.
Run a pre-existing app you have on your simulator.
Look for the same package content for that application as in step 3 and delete all.
Paste the package contents that you have previously copied.
Close the simulator and start it again. The new app icon of the intended app will replace the old one.
/Applications/MAMP/tmp/mysql/
which holds the mysql.pid
and mysql.sock.lock
filesThe first part:
.Cells(.Rows.Count,"A")
Sends you to the bottom row of column A, which you knew already.
The End function starts at a cell and then, depending on the direction you tell it, goes that direction until it reaches the edge of a group of cells that have text. Meaning, if you have text in cells C4:E4 and you type:
Sheet1.Cells(4,"C").End(xlToRight).Select
The program will select E4, the rightmost cell with text in it.
In your case, the code is spitting out the row of the very last cell with text in it in column A. Does that help?
I modified mine to return a string rather than use a ref variable like below.
public static string Serialize<T>(this T value)
{
if (value == null)
{
return string.Empty;
}
try
{
var xmlserializer = new XmlSerializer(typeof(T));
var stringWriter = new StringWriter();
using (var writer = XmlWriter.Create(stringWriter))
{
xmlserializer.Serialize(writer, value);
return stringWriter.ToString();
}
}
catch (Exception ex)
{
throw new Exception("An error occurred", ex);
}
}
Its usage would be like this:
var xmlString = obj.Serialize();
You can also download swagger ui from: https://github.com/swagger-api/swagger-ui, take the dist folder, modify index.html: change the constructor
const ui = SwaggerUIBundle({
url: ...,
into
const ui = SwaggerUIBundle({
spec: YOUR_JSON,
now the dist folder contains all what you need and can be distributed as is
To loop from current record to the end:
While Me.CurrentRecord < Me.Recordset.RecordCount
' ... do something to current record
' ...
DoCmd.GoToRecord Record:=acNext
Wend
To check if it is possible to go to next record:
If Me.CurrentRecord < Me.Recordset.RecordCount Then
' ...
End If
You can use the "User-Defined Language" option available at the notepad++. You do not need to do the xml-based hacks, where the formatting would be available only in the searched window, with the formatting rules.
Sample for your reference here.
To plot just a selection of your columns you can select the columns of interest by passing a list to the subscript operator:
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
What you tried was df['V1','V2']
this will raise a KeyError
as correctly no column exists with that label, although it looks funny at first you have to consider that your are passing a list hence the double square brackets [[]]
.
import matplotlib.pyplot as plt
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
ax.set_xlabel("Hour", fontsize=12)
ax.set_ylabel("V", fontsize=12)
plt.show()
For the numeric wrapper types.
e.g Double.POSITVE_INFINITY
Hope this might help you.
The following code shows how to read values from an HTML form. As @pimvdb said you need to use the request.on('data'...) to capture the contents of the body.
const http = require('http')
const server = http.createServer(function(request, response) {
console.dir(request.param)
if (request.method == 'POST') {
console.log('POST')
var body = ''
request.on('data', function(data) {
body += data
console.log('Partial body: ' + body)
})
request.on('end', function() {
console.log('Body: ' + body)
response.writeHead(200, {'Content-Type': 'text/html'})
response.end('post received')
})
} else {
console.log('GET')
var html = `
<html>
<body>
<form method="post" action="http://localhost:3000">Name:
<input type="text" name="name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>`
response.writeHead(200, {'Content-Type': 'text/html'})
response.end(html)
}
})
const port = 3000
const host = '127.0.0.1'
server.listen(port, host)
console.log(`Listening at http://${host}:${port}`)
If you use something like Express.js and Bodyparser then it would look like this since Express will handle the request.body concatenation
var express = require('express')
var fs = require('fs')
var app = express()
app.use(express.bodyParser())
app.get('/', function(request, response) {
console.log('GET /')
var html = `
<html>
<body>
<form method="post" action="http://localhost:3000">Name:
<input type="text" name="name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>`
response.writeHead(200, {'Content-Type': 'text/html'})
response.end(html)
})
app.post('/', function(request, response) {
console.log('POST /')
console.dir(request.body)
response.writeHead(200, {'Content-Type': 'text/html'})
response.end('thanks')
})
port = 3000
app.listen(port)
console.log(`Listening at http://localhost:${port}`)
My installer copied a log.txt file which had been generated on an XP computer. I was looking at that log file thinking it was generated on Vista. Once I fixed my log4net configuration to be "Vista Compatible". Environment.GetFolderPath was returning the expected results. Therefore, I'm closing this post.
The following SpecialFolder path reference might be useful:
Output On Windows Server 2003:
SpecialFolder.ApplicationData: C:\Documents and Settings\blake\Application Data SpecialFolder.CommonApplicationData: C:\Documents and Settings\All Users\Application Data SpecialFolder.ProgramFiles: C:\Program Files SpecialFolder.CommonProgramFiles: C:\Program Files\Common Files SpecialFolder.DesktopDirectory: C:\Documents and Settings\blake\Desktop SpecialFolder.LocalApplicationData: C:\Documents and Settings\blake\Local Settings\Application Data SpecialFolder.MyDocuments: C:\Documents and Settings\blake\My Documents SpecialFolder.System: C:\WINDOWS\system32`
Output on Vista:
SpecialFolder.ApplicationData: C:\Users\blake\AppData\Roaming SpecialFolder.CommonApplicationData: C:\ProgramData SpecialFolder.ProgramFiles: C:\Program Files SpecialFolder.CommonProgramFiles: C:\Program Files\Common Files SpecialFolder.DesktopDirectory: C:\Users\blake\Desktop SpecialFolder.LocalApplicationData: C:\Users\blake\AppData\Local SpecialFolder.MyDocuments: C:\Users\blake\Documents SpecialFolder.System: C:\Windows\system32
I had success after using ade.exe as explained above, plus using the latest version of Chrome Canary. Apparently your desktop version of Chrome has to be higher than the version running on your Android device.
Since IGrouping<TKey, TElement>
implements IEnumerable<TElement>
, you can use SelectMany
to put all the IEnumerables
back into one IEnumerable
all together:
List<smth> list = new List<smth>();
IEnumerable<IGrouping<int, smth>> groups = list.GroupBy(x => x.id);
IEnumerable<smth> smths = groups.SelectMany(group => group);
List<smth> newList = smths.ToList();
Here's an example that builds/runs: https://dotnetfiddle.net/DyuaaP
Video commentary of this solution: https://youtu.be/6BsU1n1KTdo
In order to add the file to the email as an attachment, it will need to be stored on the server briefly. It's trivial, though, to place it in a tmp location then delete it after you're done with it.
As for emailing, Zend Mail has a very easy to use interface for dealing with email attachments. We run with the whole Zend Framework installed, but I'm pretty sure you could just install the Zend_Mail library without needing any other modules for dependencies.
With Zend_Mail, sending an email with an attachment is as simple as:
$mail = new Zend_Mail();
$mail->setSubject("My Email with Attachment");
$mail->addTo("[email protected]");
$mail->setBodyText("Look at the attachment");
$attachment = $mail->createAttachment(file_get_contents('/path/to/file'));
$mail->send();
If you're looking for a one-file-package to do the whole form/email/attachment thing, I haven't seen one. But the individual components are certainly available and easy to assemble. Trickiest thing of the whole bunch is the email attachment, which the above recommendation makes very simple.
Loius answer is correct, I just want to add an example:
listOne.add("A");
listOne.add("B");
listOne.add("C");
listTwo.add("D");
listTwo.add("E");
listTwo.add("F");
boolean noElementsInCommon = Collections.disjoint(listOne, listTwo); // true
This has worked for me in both SQL Server 2005 and 2008:
SELECT * from TABLE
WHERE FIELDNAME > {ts '2013-02-01 15:00:00.001'}
AND FIELDNAME < {ts '2013-08-05 00:00:00.000'}
You want to simulate n-nested for loops.
Iterating through n-dimmensional array can be seen as increasing the n-digit number.
At each dimmension we have as many digits as the lenght of the dimmension.
Example:
Suppose we had array(matrix)
int[][][] T=new int[3][4][5];
in "for notation" we have:
for(int x=0;x<3;x++)
for(int y=0;y<4;y++)
for(int z=0;z<5;z++)
T[x][y][z]=...
to simulate this you would have to use the "n-digit number notation"
We have 3 digit number, with 3 digits for first, 4 for second and five for third digit
We have to increase the number, so we would get the sequence
0 0 0
0 0 1
0 0 2
0 0 3
0 0 4
0 1 0
0 1 1
0 1 2
0 1 3
0 1 4
0 2 0
0 2 1
0 2 2
0 2 3
0 2 4
0 3 0
0 3 1
0 3 2
0 3 3
0 3 4
and so on
So you can write the code for increasing such n-digit number. You can do it in such way that you can start with any value of the number and increase/decrease the digits by any numbers. That way you can simulate nested for loops that begin somewhere in the table and finish not at the end.
This is not an easy task though. I can't help with the matlab notation unfortunaly.
Check out how Haar Wavelets are implemented by isk-daemon. You could use it's imgdb C++ code to calculate the difference between images on-the-fly:
isk-daemon is an open source database server capable of adding content-based (visual) image searching to any image related website or software.
This technology allows users of any image-related website or software to sketch on a widget which image they want to find and have the website reply to them the most similar images or simply request for more similar photos at each image detail page.
install Local DB from following link https://www.microsoft.com/en-us/download/details.aspx?id=42299 then connect to the local db using windows authentication. (localdb)\MSSQLLocalDB
I got the same issue while adding dynamic url in Image tag in Angular 7. I searched a lot and found this solution.
First, write below code in the component file.
constructor(private sanitizer: DomSanitizer) {}
public getSantizeUrl(url : string) {
return this.sanitizer.bypassSecurityTrustUrl(url);
}
Now in your html image tag, you can write like this.
<img class="image-holder" [src]=getSantizeUrl(item.imageUrl) />
You can write as per your requirement instead of item.imageUrl
I got a reference from this site.dynamic urls. Hope this solution will help you :)
It allocates that much space according to the value of n and pointer will point to the array i.e the 1st element of array
int *array = new int[n];
curl -u username:password http://
curl -u username http://
From the documentation page:
-u, --user <user:password>
Specify the user name and password to use for server authentication. Overrides -n, --netrc and --netrc-optional.
If you simply specify the user name, curl will prompt for a password.
The user name and passwords are split up on the first colon, which makes it impossible to use a colon in the user name with this option. The password can, still.
When using Kerberos V5 with a Windows based server you should include the Windows domain name in the user name, in order for the server to succesfully obtain a Kerberos Ticket. If you don't then the initial authentication handshake may fail.
When using NTLM, the user name can be specified simply as the user name, without the domain, if there is a single domain and forest in your setup for example.
To specify the domain name use either Down-Level Logon Name or UPN (User Principal Name) formats. For example, EXAMPLE\user and [email protected] respectively.
If you use a Windows SSPI-enabled curl binary and perform Kerberos V5, Negotiate, NTLM or Digest authentication then you can tell curl to select the user name and password from your environment by specifying a single colon with this option: "-u :".
If this option is used several times, the last one will be used.
http://curl.haxx.se/docs/manpage.html#-u
Note that you do not need --basic
flag as it is the default.
There is a DateTime constructor that takes a long.
DateTime today = new DateTime(t); // where t represents long format of dateTime
Not sure why no one has mentioned two Base R functions specifically to do this: str2lang()
and str2expression()
. These are variants of parse()
, but seem to return the expression more cleanly:
eval(str2lang("5+5"))
# > 10
eval(str2expression("5+5"))
# > 10
Also want to push back against the posters saying that anyone trying to do this is wrong. I'm reading in R expressions stored as text in a file and trying to evaluate them. These functions are perfect for this use case.
I realize that this question is over 10 years old, but it appears to me that not only has the most obvious answer not been addressed, but that maybe its not really clear from the question a good understanding of what goes on under the covers. In addition, there are other questions about late binding and what that means with regards to delegates and lambdas (more on that later).
First to address the 800 lb elephant/gorilla in the room, when to choose event
vs Action<T>
/Func<T>
:
event
when you
want more of a pub/sub model with multiple
statements/lambdas/functions that will execute (this is a major
difference right off the bat).As an example of an event, lets wire up a simple and 'standard' set of events using a small console application as follows:
public delegate void FireEvent(int num);
public delegate void FireNiceEvent(object sender, SomeStandardArgs args);
public class SomeStandardArgs : EventArgs
{
public SomeStandardArgs(string id)
{
ID = id;
}
public string ID { get; set; }
}
class Program
{
public static event FireEvent OnFireEvent;
public static event FireNiceEvent OnFireNiceEvent;
static void Main(string[] args)
{
OnFireEvent += SomeSimpleEvent1;
OnFireEvent += SomeSimpleEvent2;
OnFireNiceEvent += SomeStandardEvent1;
OnFireNiceEvent += SomeStandardEvent2;
Console.WriteLine("Firing events.....");
OnFireEvent?.Invoke(3);
OnFireNiceEvent?.Invoke(null, new SomeStandardArgs("Fred"));
//Console.WriteLine($"{HeightSensorTypes.Keyence_IL030}:{(int)HeightSensorTypes.Keyence_IL030}");
Console.ReadLine();
}
private static void SomeSimpleEvent1(int num)
{
Console.WriteLine($"{nameof(SomeSimpleEvent1)}:{num}");
}
private static void SomeSimpleEvent2(int num)
{
Console.WriteLine($"{nameof(SomeSimpleEvent2)}:{num}");
}
private static void SomeStandardEvent1(object sender, SomeStandardArgs args)
{
Console.WriteLine($"{nameof(SomeStandardEvent1)}:{args.ID}");
}
private static void SomeStandardEvent2(object sender, SomeStandardArgs args)
{
Console.WriteLine($"{nameof(SomeStandardEvent2)}:{args.ID}");
}
}
The output will look as follows:
If you did the same with Action<int>
or Action<object, SomeStandardArgs>
, you would only see SomeSimpleEvent2
and SomeStandardEvent2
.
So whats going on inside of event
?
If we expand out FireNiceEvent
, the compiler is actually generating the following (I have omitted some details with respect to thread synchronization that isn't relevant to this discussion):
private EventHandler<SomeStandardArgs> _OnFireNiceEvent;
public void add_OnFireNiceEvent(EventHandler<SomeStandardArgs> handler)
{
Delegate.Combine(_OnFireNiceEvent, handler);
}
public void remove_OnFireNiceEvent(EventHandler<SomeStandardArgs> handler)
{
Delegate.Remove(_OnFireNiceEvent, handler);
}
public event EventHandler<SomeStandardArgs> OnFireNiceEvent
{
add
{
add_OnFireNiceEvent(value)
}
remove
{
remove_OnFireNiceEvent(value)
}
}
The compiler generates a private delegate variable which is not visible to the class namespace in which it is generated. That delegate is what is used for subscription management and late binding participation, and the public facing interface is the familiar +=
and -=
operators we have all come to know and love : )
You can customize the code for the add/remove handlers by changing the scope of the FireNiceEvent
delegate to protected. This now allows developers to add custom hooks to the hooks, such as logging or security hooks. This really makes for some very powerful features that now allows for customized accessibility to subscription based on user roles, etc. Can you do that with lambdas? (Actually you can by custom compiling expression trees, but that's beyond the scope of this response).
To address a couple of points from some of the responses here:
There really is no difference in the 'brittleness' between changing
the args list in Action<T>
and changing the properties in a class
derived from EventArgs
. Either will not only require a compile
change, they will both change a public interface and will require
versioning. No difference.
With respect to which is an industry standard, that depends on where
this is being used and why. Action<T>
and such is often used in IoC
and DI, and event
is often used in message routing such as GUI and
MQ type frameworks. Note that I said often, not always.
Delegates have different lifetimes than lambdas. One also has to be aware of capture... not just with closure, but also with the notion of 'look what the cat dragged in'. This does affect memory footprint/lifetime as well as management a.k.a. leaks.
One more thing, something I referenced earlier... the notion of late binding. You will often see this when using framework like LINQ, regarding when a lambda becomes 'live'. That is very different than late binding of a delegate, which can happen more than once (i.e. the lambda is always there, but binding occurs on demand as often as is needed), as opposed to a lambda, which once it occurs, its done -- the magic is gone, and the method(s)/property(ies) will always bind. Something to keep in mind.
If you need just file names like:
dir/subdir/file1.txt
dir/subdir2/file2.sql
dir2/subdir3/file6.php
(which I use as a source for tar command) you will also need to filter out commit messages.
In order to do this I use following command:
git log --name-only --oneline | grep -v '.{7} '
Grep command excludes (-v
param) every line which starts with seven symbols (which is the length of my git hash for git log
command) followed by space. So it filters out every git hash message
line and leave only lines with file names.
One useful improvement is to append uniq
to remove duplicate lines so it will looks as follow:
git log --name-only --oneline | grep -v '.{7} ' | uniq
white-space: pre-wrap
is what worked for me for <span>
and <div>
.
just disable "world wide web publishing service" , it solve my problem.
An easier way is to use the heredoc syntax of PHP. An example:
<?php
echo <<<EOF
<script type="text/javascript">
document.write("Hello World!");
</script>
EOF;
?>
You can use this for 24 hour to 12 hour:
echo date("h:i", strtotime($time));
And for vice versa:
echo date("H:i", strtotime($time));
When using Python 3 the empty lines can be avoid by using the codecs module. As stated in the documentation, files are opened in binary mode so no change of the newline kwarg is necessary. I was running into the same issue recently and that worked for me:
with codecs.open( csv_file, mode='w', encoding='utf-8') as out_csv:
csv_out_file = csv.DictWriter(out_csv)
https://github.com/cognitom/paper-css seems to solve all my needs.
Front-end printing solution - previewable and live-reloadable!
It seems you can provide just the local image name, assuming it is in the same folder...
It suffices like:
background-image: url("img1.png")
Use curl
instead of file_get_contents
:
$address = "India+Panchkula";
$url = "http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false®ion=India";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
$response_a = json_decode($response);
echo $lat = $response_a->results[0]->geometry->location->lat;
echo "<br />";
echo $long = $response_a->results[0]->geometry->location->lng;
Run apt-get install build-essential
on your system.
This package depends on other packages considered to be essential for builds and will install them. If you find you have to build packages, this can be helpful to avoid piecemeal resolution of dependencies.
See this page for more info.
//
// creates 'clone' method on context object
//
// var
// clon = Object.clone( anyValue );
//
!((function (propertyName, definition) {
this[propertyName] = definition();
}).call(
Object,
"clone",
function () {
function isfn(fn) {
return typeof fn === "function";
}
function isobj(o) {
return o === Object(o);
}
function isarray(o) {
return Object.prototype.toString.call(o) === "[object Array]";
}
function fnclon(fn) {
return function () {
fn.apply(this, arguments);
};
}
function owns(obj, p) {
return obj.hasOwnProperty(p);
}
function isemptyobj(obj) {
for (var p in obj) {
return false;
}
return true;
}
function isObject(o) {
return Object.prototype.toString.call(o) === "[object Object]";
}
return function (input) {
if (isfn(input)) {
return fnclon(input);
} else if (isobj(input)) {
var cloned = {};
for (var p in input) {
owns(Object.prototype, p)
|| (
isfn(input[p])
&& ( cloned[p] = function () { return input[p].apply(input, arguments); } )
|| ( cloned[p] = input[p] )
);
}
if (isarray(input)) {
cloned.length = input.length;
"concat every filter forEach indexOf join lastIndexOf map pop push reduce reduceRight reverse shift slice some sort splice toLocaleString toString unshift"
.split(" ")
.forEach(
function (methodName) {
isfn( Array.prototype[methodName] )
&& (
cloned[methodName] =
function () {
return Array.prototype[methodName].apply(cloned, arguments);
}
);
}
);
}
return isemptyobj(cloned)
? (
isObject(input)
? cloned
: input
)
: cloned;
} else {
return input;
}
};
}
));
//
Other answers already provide information for iOS 7 and older, however UIAlertView
is deprecated in iOS 8.
In iOS 8+ you should use UIAlertController
. It is a replacement for both UIAlertView
and UIActionSheet
. Documentation: UIAlertController Class Reference. And a nice article on NSHipster.
To create a simple Alert View you can do the following:
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Title"
message:@"Message"
preferredStyle:UIAlertControllerStyleAlert];
//We add buttons to the alert controller by creating UIAlertActions:
UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Ok"
style:UIAlertActionStyleDefault
handler:nil]; //You can use a block here to handle a press on this button
[alertController addAction:actionOk];
[self presentViewController:alertController animated:YES completion:nil];
Swift 3 / 4 / 5:
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)
//We add buttons to the alert controller by creating UIAlertActions:
let actionOk = UIAlertAction(title: "OK",
style: .default,
handler: nil) //You can use a block here to handle a press on this button
alertController.addAction(actionOk)
self.present(alertController, animated: true, completion: nil)
Note, that, since it was added in iOS 8, this code won't work on iOS 7 and older. So, sadly, for now we have to use version checks like so:
NSString *alertTitle = @"Title";
NSString *alertMessage = @"Message";
NSString *alertOkButtonText = @"Ok";
if (@available(iOS 8, *)) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:alertTitle
message:alertMessage
delegate:nil
cancelButtonTitle:nil
otherButtonTitles:alertOkButtonText, nil];
[alertView show];
}
else {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:alertTitle
message:alertMessage
preferredStyle:UIAlertControllerStyleAlert];
//We add buttons to the alert controller by creating UIAlertActions:
UIAlertAction *actionOk = [UIAlertAction actionWithTitle:alertOkButtonText
style:UIAlertActionStyleDefault
handler:nil]; //You can use a block here to handle a press on this button
[alertController addAction:actionOk];
[self presentViewController:alertController animated:YES completion:nil];
}
Swift 3 / 4 / 5:
let alertTitle = "Title"
let alertMessage = "Message"
let alertOkButtonText = "Ok"
if #available(iOS 8, *) {
let alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert)
//We add buttons to the alert controller by creating UIAlertActions:
let actionOk = UIAlertAction(title: alertOkButtonText,
style: .default,
handler: nil) //You can use a block here to handle a press on this button
alertController.addAction(actionOk)
self.present(alertController, animated: true, completion: nil)
}
else {
let alertView = UIAlertView(title: alertTitle, message: alertMessage, delegate: nil, cancelButtonTitle: nil, otherButtonTitles: alertOkButtonText)
alertView.show()
}
UPD: updated for Swift 5. Replaced outdated class presence check with availability check in Obj-C.
Yes, there is a way to emulate max-width
using a table, thus giving you both responsive and Outlook-friendly layout. What's more, this solution doesn't require conditional comments.
Suppose you want the equivalent of a centered div
with max-width
of 350px
. You create a table, set the width to 100%
. The table has three cells in a row. Set the width of the center TD
to 350
(using the HTML width
attribute, not CSS), and there you go.
If you want your content aligned left instead of centered, just leave out the first empty cell.
Example:
<table border="0" cellspacing="0" width="100%">
<tr>
<td></td>
<td width="350">The width of this cell should be a maximum of
350 pixels, but shrink to widths less than 350 pixels.
</td>
<td></td>
</tr>
</table>
In the jsfiddle I give the table a border so you can see what's going on, but obviously you wouldn't want one in real life:
Try the Apache POI HSSF. Here's an example on how to read an excel file:
try {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row;
HSSFCell cell;
int rows; // No of rows
rows = sheet.getPhysicalNumberOfRows();
int cols = 0; // No of columns
int tmp = 0;
// This trick ensures that we get the data properly even if it doesn't start from first few rows
for(int i = 0; i < 10 || i < rows; i++) {
row = sheet.getRow(i);
if(row != null) {
tmp = sheet.getRow(i).getPhysicalNumberOfCells();
if(tmp > cols) cols = tmp;
}
}
for(int r = 0; r < rows; r++) {
row = sheet.getRow(r);
if(row != null) {
for(int c = 0; c < cols; c++) {
cell = row.getCell((short)c);
if(cell != null) {
// Your code here
}
}
}
}
} catch(Exception ioe) {
ioe.printStackTrace();
}
On the documentation page you also have examples of how to write to excel files.
Using hbm.xml
<composite-id>
<!--<key-many-to-one name="productId" class="databaselayer.users.UserDB" column="user_name"/>-->
<key-property name="productId" column="PRODUCT_Product_ID" type="int"/>
<key-property name="categoryId" column="categories_id" type="int" />
</composite-id>
Using Annotation
Composite Key Class
public class PK implements Serializable{
private int PRODUCT_Product_ID ;
private int categories_id ;
public PK(int productId, int categoryId) {
this.PRODUCT_Product_ID = productId;
this.categories_id = categoryId;
}
public int getPRODUCT_Product_ID() {
return PRODUCT_Product_ID;
}
public void setPRODUCT_Product_ID(int PRODUCT_Product_ID) {
this.PRODUCT_Product_ID = PRODUCT_Product_ID;
}
public int getCategories_id() {
return categories_id;
}
public void setCategories_id(int categories_id) {
this.categories_id = categories_id;
}
private PK() { }
@Override
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( o == null || getClass() != o.getClass() ) {
return false;
}
PK pk = (PK) o;
return Objects.equals(PRODUCT_Product_ID, pk.PRODUCT_Product_ID ) &&
Objects.equals(categories_id, pk.categories_id );
}
@Override
public int hashCode() {
return Objects.hash(PRODUCT_Product_ID, categories_id );
}
}
Entity Class
@Entity(name = "product_category")
@IdClass( PK.class )
public class ProductCategory implements Serializable {
@Id
private int PRODUCT_Product_ID ;
@Id
private int categories_id ;
public ProductCategory(int productId, int categoryId) {
this.PRODUCT_Product_ID = productId ;
this.categories_id = categoryId;
}
public ProductCategory() { }
public int getPRODUCT_Product_ID() {
return PRODUCT_Product_ID;
}
public void setPRODUCT_Product_ID(int PRODUCT_Product_ID) {
this.PRODUCT_Product_ID = PRODUCT_Product_ID;
}
public int getCategories_id() {
return categories_id;
}
public void setCategories_id(int categories_id) {
this.categories_id = categories_id;
}
public void setId(PK id) {
this.PRODUCT_Product_ID = id.getPRODUCT_Product_ID();
this.categories_id = id.getCategories_id();
}
public PK getId() {
return new PK(
PRODUCT_Product_ID,
categories_id
);
}
}
You can now use the npm package sequelize-auto-migrations to automatically generate a migrations file. https://www.npmjs.com/package/sequelize-auto-migrations
Using sequelize-cli, initialize your project with
sequelize init
Create your models and put them in your models folder.
Install sequelize-auto-migrations:
npm install sequelize-auto-migrations
Create an initial migration file with
node ./node_modules/sequelize-auto-migrations/bin/makemigration --name <initial_migration_name>
Run your migration:
node ./node_modules/sequelize-auto-migrations/bin/runmigration
You can also automatically generate your models from an existing database, but that is beyond the scope of the question.
You need some form of iteration here, as val
(except when called with a function) only works on the first element:
$("input[placeholder]").val($("input[placeholder]").attr("placeholder"));
should be:
$("input[placeholder]").each( function () {
$(this).val( $(this).attr("placeholder") );
});
or
$("input[placeholder]").val(function() {
return $(this).attr("placeholder");
});
// Java 8 with lambda & stream, if param is directory
static boolean delRecursive(File dir) {
return Arrays.stream(dir.listFiles()).allMatch((f) -> f.isDirectory() ? delRecursive(f) : f.delete()) && dir.delete();
}
// if param is file or directory
static boolean delRecursive(File fileOrDir) {
return fileOrDir.isDirectory() ? Arrays.stream(fileOrDir.listFiles()).allMatch((f) -> delRecursive(f)) && fileOrDir.delete() : fileOrDir.delete();
}
"#if one" means that if "#define one" has been written "#if one" is executed otherwise "#ifndef one" is executed.
This is just the C Pre-Processor (CPP) Directive equivalent of the if, then, else branch statements in the C language.
i.e. if {#define one} then printf("one evaluates to a truth "); else printf("one is not defined "); so if there was no #define one statement then the else branch of the statement would be executed.
Try this:
your_command 2>stderr.log 1>stdout.log
The numerals 0
through 9
are file descriptors in bash.
0
stands for standard input, 1
stands for standard output, 2
stands for standard error. 3
through 9
are spare for any other temporary usage.
Any file descriptor can be redirected to a file or to another file descriptor using the operator >
. You can instead use the operator >>
to appends to a file instead of creating an empty one.
Usage:
file_descriptor > filename
file_descriptor > &file_descriptor
Please refer to Advanced Bash-Scripting Guide: Chapter 20. I/O Redirection.
Why do you need to get this root url ? Can't you generate directly absolute URL's ?
{{ url('_demo_hello', { 'name': 'Thomas' }) }}
This Twig code will generate the full http:// url to the _demo_hello route.
In fact, getting the base url of the website is only getting the full url of the homepage route :
{{ url('homepage') }}
(homepage, or whatever you call it in your routing file).
You could use the TIMEDIFF()
and the TIME_TO_SEC()
functions as follows:
SELECT TIME_TO_SEC(TIMEDIFF('2010-08-20 12:01:00', '2010-08-20 12:00:00')) diff;
+------+
| diff |
+------+
| 60 |
+------+
1 row in set (0.00 sec)
You could also use the UNIX_TIMESTAMP()
function as @Amber suggested in an other answer:
SELECT UNIX_TIMESTAMP('2010-08-20 12:01:00') -
UNIX_TIMESTAMP('2010-08-20 12:00:00') diff;
+------+
| diff |
+------+
| 60 |
+------+
1 row in set (0.00 sec)
If you are using the TIMESTAMP
data type, I guess that the UNIX_TIMESTAMP()
solution would be slightly faster, since TIMESTAMP
values are already stored as an integer representing the number of seconds since the epoch (Source). Quoting the docs:
When
UNIX_TIMESTAMP()
is used on aTIMESTAMP
column, the function returns the internal timestamp value directly, with no implicit “string-to-Unix-timestamp” conversion.Keep in mind that
TIMEDIFF()
return data type ofTIME
.TIME
values may range from '-838:59:59' to '838:59:59' (roughly 34.96 days)
I was getting the same error about the SSL certificate when Maven tried to download the necessary modules automatically.
As a remedy, I was attempting to implement Luke's answer above, but found that the DigiCert Global Root CA certificate is already in Java's trusted keystore.
What helped me was adding %JAVA_HOME%\bin
to the Path variable (I am running Windows). And %JAVA_HOME%
is a JDK location, not just a JRE location, since Maven needs a JDK.
I am not certain why it helped, but it did. I am absolutely sure that this was the only thing I changed.
You are using improper syntax. If you read the docs mysqli_query() you will find that it needs two parameter.
mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )
mysql $link
generally means, the resource object of the established mysqli connection to query the database.
So there are two ways of solving this problem
mysqli_query();
$myConnection= mysqli_connect("$db_host","$db_username","$db_pass", "mrmagicadam") or die ("could not connect to mysql");
$sqlCommand="SELECT id, linklabel FROM pages ORDER BY pageorder ASC";
$query=mysqli_query($myConnection, $sqlCommand) or die(mysqli_error($myConnection));
Or, Using mysql_query()
(This is now obselete)
$myConnection= mysql_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql");
mysql_select_db("mrmagicadam") or die ("no database");
$sqlCommand="SELECT id, linklabel FROM pages ORDER BY pageorder ASC";
$query=mysql_query($sqlCommand) or die(mysql_error());
As pointed out in the comments, be aware of using die to just get the error. It might inadvertently give the viewer some sensitive information .
What worked for me was this:
$("#testButton").hasClass('ui-state-disabled')
But I like tomwadley's answer a lot more.
Nevertheless, the is(':disabled') code does also not work for me which should be the best version. Don't know, why it does not work. :-(
You can use AES to encrypt your string with a password. Though, you'll want to chose a strong enough password so people can't easily guess what it is (sorry I can't help it. I'm a wannabe security weenie).
AES is strong with a good key size, but it's also easy to use with PyCrypto.
Here's my flavor without the loss of hover. I personally like it better than the standard bootstrap transitioning.
.btn-primary,_x000D_
.btn-primary:active,_x000D_
.btn-primary:visited {_x000D_
background-color: #8064A2 !important;_x000D_
}_x000D_
_x000D_
.btn-primary:hover {_x000D_
background-color: #594671 !important;_x000D_
transition: all 1s ease;_x000D_
-webkit-transition: all 1s ease;_x000D_
-moz-transition: all 1s ease;_x000D_
-o-transition: all 1s ease;_x000D_
-ms-transition: all 1s ease;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<button class="btn btn-primary">Hover me!</button>
_x000D_
if you have integrated firebase messaging push notification then,
Add new/update firebase messaging dependencies for android O (Android 8.0), due to Background Execution Limits.
compile 'com.google.firebase:firebase-messaging:11.4.0'
upgrade google play services and google repositories if needed.
Update:
compile 'com.google.firebase:firebase-messaging:11.4.2'