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:
I've filled my ComboBox with een DataTable filled from a database. Then I've set the DisplayMember and the ValueMember. And I use this code to set the selected item.
foreach (DataRowView Row in ComboBox1.Items)
{
if (Row["ColumnName"].ToString() == "Value") ComboBox1.SelectedItem = Row;
}
Put this .gitignore
into the folder, then git add .gitignore
.
*
*/
!.gitignore
The *
line tells git to ignore all files in the folder, but !.gitignore
tells git to still include the .gitignore
file. This way, your local repository and any other clones of the repository all get both the empty folder and the .gitignore
it needs.
Edit: May be obvious but also add */
to the .gitignore
to also ignore subfolders.
I had the same problem when I was working on asp.net Mvc webApi because cors was not enabled. I solved this by enabling cors inside register method of webApiconfig
First install cors from here then
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
config.EnableCors();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
with zxing this is my code for create QR
QRCodeWriter writer = new QRCodeWriter();
try {
BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, 512, 512);
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
bmp.setPixel(x, y, bitMatrix.get(x, y) ? Color.BLACK : Color.WHITE);
}
}
((ImageView) findViewById(R.id.img_result_qr)).setImageBitmap(bmp);
} catch (WriterException e) {
e.printStackTrace();
}
Actually the @Ian Robinson answer works well but Chrome will continue complain with that message : "Resource interpreted as Font but transferred with MIME type application/x-woff"
If you get that, you can change from
application/x-woff
to
application/x-font-woff
and you will not have any Chrome console errors anymore !
(tested on Chrome 17)
A "download" is simply an HTTP header change.
See http://docs.djangoproject.com/en/dev/ref/request-response/#telling-the-browser-to-treat-the-response-as-a-file-attachment for how to respond with a download.
You only need one URL definition for "/download"
.
The request's GET
or POST
dictionary will have the "f=somefile.txt"
information.
Your view function will simply merge the base path with the "f
" value, open the file, create and return a response object. It should be less than 12 lines of code.
Use
code -n
when launching the program. This "Opens a new session of Visual Studio Code instead of restoring the previous session." (from here).
The way I used this was by modifying my "Code" shortcut to include the -n
parameter:
If it does not work, restart VSCode
sns.boxplot() function returns Axes(matplotlib.axes.Axes) object. please refer the documentation you can add title using 'set' method as below:
sns.boxplot('Day', 'Count', data=gg).set(title='lalala')
you can also add other parameters like xlabel, ylabel to the set method.
sns.boxplot('Day', 'Count', data=gg).set(title='lalala', xlabel='its x_label', ylabel='its y_label')
There are some other methods as mentioned in the matplotlib.axes.Axes documentaion to add tile, legend and labels.
As Ciro Santilli notes using command substitutions will drop trailing newlines. Their workaround adding trailing characters is great, but after using it for quite some time I decided I needed a solution that didn't use command substitution at all.
My approach now uses read
along with the printf
builtin's -v
flag in order to read the contents of stdin directly into a variable.
# Reads stdin into a variable, accounting for trailing newlines. Avoids
# needing a subshell or command substitution.
# Note that NUL bytes are still unsupported, as Bash variables don't allow NULs.
# See https://stackoverflow.com/a/22607352/113632
read_input() {
# Use unusual variable names to avoid colliding with a variable name
# the user might pass in (notably "contents")
: "${1:?Must provide a variable to read into}"
if [[ "$1" == '_line' || "$1" == '_contents' ]]; then
echo "Cannot store contents to $1, use a different name." >&2
return 1
fi
local _line _contents=()
while IFS='' read -r _line; do
_contents+=("$_line"$'\n')
done
# include $_line once more to capture any content after the last newline
printf -v "$1" '%s' "${_contents[@]}" "$_line"
}
This supports inputs with or without trailing newlines.
Example usage:
$ read_input file_contents < /tmp/file
# $file_contents now contains the contents of /tmp/file
SELECT IF((
SELECT count(*) FROM gdata_calendars
WHERE `group` = ? AND id = ?)
,1,0);
For Detail explanation you can visit here
I think what you are looking for is
.style1 {
background: url('http://localhost/msite/images/12.PNG');
background-repeat: no-repeat;
background-position: center;
-webkit-background-size: contain;
-moz-background-size: contain;
-o-background-size: contain;
background-size: contain;
}
I dont understand why nobody mention the easiest way....just split the large file with http://www.rusiczki.net/2007/01/24/sql-dump-file-splitter/ and after just execute vie mySQL admin the seperated generated files starting from the one with Structure
After fixing a performance issue related to the use of .is(":visible"), I would recommend against the above answers and instead use jQuery's code for deciding whether a single element is visible:
$.expr.filters.visible($("#singleElementID")[0]);
What .is does is check whether a set of elements is within another set of elements. So you will looking for your element within the entire set of visible elements on your page. Having 100 elements is pretty normal and might take a few milliseconds to search through the array of visible elements. If you're building a web app you probably have hundreds or possibly thousands. Our app was sometimes taking 100ms for $("#selector").is(":visible") since it was checking if an element was in an array of 5000 other elements.
That is interesting subject.
You can play around with two lifecycle hooks to figure out how it works: ngOnChanges
and ngOnInit
.
Basically when you set default value to Input
that's mean it will be used only in case there will be no value coming on that component.
And the interesting part it will be changed before component will be initialized.
Let's say we have such components with two lifecycle hooks and one property coming from input
.
@Component({
selector: 'cmp',
})
export class Login implements OnChanges, OnInit {
@Input() property: string = 'default';
ngOnChanges(changes) {
console.log('Changed', changes.property.currentValue, changes.property.previousValue);
}
ngOnInit() {
console.log('Init', this.property);
}
}
Situation 1
Component included in html without defined property
value
As result we will see in console:
Init default
That's mean onChange
was not triggered. Init was triggered and property
value is default
as expected.
Situation 2
Component included in html with setted property <cmp [property]="'new value'"></cmp>
As result we will see in console:
Changed
new value
Object {}
Init
new value
And this one is interesting. Firstly was triggered onChange
hook, which setted property
to new value
, and previous value was empty object! And only after that onInit
hook was triggered with new value of property
.
First create a class to represent your json data.
public class MyFlightDto
{
public string err_code { get; set; }
public string org { get; set; }
public string flight_date { get; set; }
// Fill the missing properties for your data
}
Using Newtonsoft JSON serializer to Deserialize a json string to it's corresponding class object.
var jsonInput = "{ org:'myOrg',des:'hello'}";
MyFlightDto flight = Newtonsoft.Json.JsonConvert.DeserializeObject<MyFlightDto>(jsonInput);
Or Use JavaScriptSerializer
to convert it to a class(not recommended as the newtonsoft json serializer seems to perform better).
string jsonInput="have your valid json input here"; //
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
Customer objCustomer = jsonSerializer.Deserialize<Customer >(jsonInput)
Assuming you want to convert it to a Customer
classe's instance. Your class should looks similar to the JSON
structure (Properties)
Because the original question was never answered, and I had to run into this same problem, the solution for the MD5 problem is that S3 doesn't want the Hex encoded MD5 string we normally think about.
Instead, I had to do this.
// content is a passed in InputStream
byte[] resultByte = DigestUtils.md5(content);
String streamMD5 = new String(Base64.encodeBase64(resultByte));
metaData.setContentMD5(streamMD5);
Essentially what they want for the MD5 value is the Base64 encoded raw MD5 byte-array, not the Hex string. When I switched to this it started working great for me.
I would write :
var handleData = function (data) {
alert(data);
//do some stuff
}
function getData() {
$.ajax({
url : 'example.com',
type: 'GET',
success : handleData
})
}
Also useful is Object.toSource() for debugging purposes, where you want to show the object and its properties for debugging purposes. This is a generic Javascript (not jQuery) function, however it only works in "modern" browsers.
The seek
function expect's an offset in bytes.
So if you have a text file with the following content:
simple.txt
abc
You can jump 1 byte to skip over the first character as following:
fp = open('simple.txt', 'r')
fp.seek(1)
print fp.readline()
>>> bc
fp = open('afile.png', 'rb')
fp.seek(16)
print 'width: {0}'.format(struct.unpack('>i', fp.read(4))[0])
print 'height: ', struct.unpack('>i', fp.read(4))[0]
Note: Once you call
read
you are changing the position of the read-head, which act's likeseek
.
Implement onFocusChange
of setOnFocusChangeListener
and there's a boolean parameter for hasFocus. When this is false, you've lost focus to another control.
EditText txtEdit = (EditText) findViewById(R.id.edittxt);
txtEdit.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
// code to execute when EditText loses focus
}
}
});
var newElementsAppended = $(newHtml).appendTo("#myDiv");
newElementsAppended.effects("highlight", {}, 2000);
My solution to this was to write the script block dynamically with [scriptblock]:Create
:
# Or build a complex local script with MARKERS here, and do substitutions
# I was sending install scripts to the remote along with MSI packages
# ...for things like Backup and AV protection etc.
$p1 = "good stuff"; $p2 = "better stuff"; $p3 = "best stuff"; $etc = "!"
$script = [scriptblock]::Create("MyScriptOnRemoteServer.ps1 $p1 $p2 $etc")
#strings get interpolated/expanded while a direct scriptblock does not
# the $parms are now expanded in the script block itself
# ...so just call it:
$result = invoke-command $computer -script $script
Passing arguments was very frustrating, trying various methods, e.g.,
-arguments
, $using:p1
, etc. and this just worked as desired with no problems.
Since I control the contents and variable expansion of the string which creates the [scriptblock]
(or script file) this way, there is no real issue with the "invoke-command" incantation.
(It shouldn't be that hard. :) )
I just wanted to mention that one can get the detailed GC log with the
-XX:+PrintGCDetails
parameter. Then you see the PSYoungGen or PSPermGen output like in the answer.
Also -Xloggc:gc.log
seems to generate the same output like -verbose:gc
but you can specify an output file in the first.
Example usage:
java -Xloggc:./memory.log -XX:+PrintGCDetails Memory
To visualize the data better you can try gcviewer (a more recent version can be found on github).
Take care to write the parameters correctly, I forgot the "+" and my JBoss would not start up, without any error message!
How can we read data from a text file and store in a String Variable?
Err, read data from the file and store it in a String variable. It's just code. Not a real question so far.
Is it possible to pass the filename in a method and it would return the String which is the text from the file.
Yes it's possible. It's also a very bad idea. You should deal with the file a part at a time, for example a line at a time. Reading the entire file into memory before you process any of it adds latency; wastes memory; and assumes that the entire file will fit into memory. One day it won't. You don't want to do it this way.
Please note: There is a difference between using String[] to StringBuilder[].
In String - if you change the String, the other arrays we have copied (by CopyTo or Clone) that points to the same string will not change, but the original String array will point to a new String, however, if we use a StringBuilder in an array, the String pointer will not change, therefore, it will affect all the copies we have made for this array. For instance:
public void test()
{
StringBuilder[] sArrOr = new StringBuilder[1];
sArrOr[0] = new StringBuilder();
sArrOr[0].Append("hello");
StringBuilder[] sArrClone = (StringBuilder[])sArrOr.Clone();
StringBuilder[] sArrCopyTo = new StringBuilder[1];
sArrOr.CopyTo(sArrCopyTo,0);
sArrOr[0].Append(" world");
Console.WriteLine(sArrOr[0] + " " + sArrClone[0] + " " + sArrCopyTo[0]);
//Outputs: hello world hello world hello world
//Same result in int[] as using String[]
int[] iArrOr = new int[2];
iArrOr[0] = 0;
iArrOr[1] = 1;
int[] iArrCopyTo = new int[2];
iArrOr.CopyTo(iArrCopyTo,0);
int[] iArrClone = (int[])iArrOr.Clone();
iArrOr[0]++;
Console.WriteLine(iArrOr[0] + " " + iArrClone[0] + " " + iArrCopyTo[0]);
// Output: 1 0 0
}
You can use column indices (letters) like this:
import pandas as pd
import numpy as np
file_loc = "path.xlsx"
df = pd.read_excel(file_loc, index_col=None, na_values=['NA'], usecols = "A,C:AA")
print(df)
[Corresponding documentation][1]:
usecolsint, str, list-like, or callable default None
- If None, then parse all columns.
- If str, then indicates comma separated list of Excel column letters and column ranges (e.g. “A:E” or “A,C,E:F”). Ranges are inclusive of both sides.
- If list of int, then indicates list of column numbers to be parsed.
If list of string, then indicates list of column names to be parsed.
New in version 0.24.0.
If callable, then evaluate each column name against it and parse the column if the callable returns True.
Returns a subset of the columns according to behavior above.
New in version 0.24.0.
If min = 5
, and max = 10
, and Math.random()
returns (almost) 1.0, the generated number will be (almost) 15, which is clearly more than the chosen max
.
Relatedly, this is why every random number API should let you specify min and max explicitly. You shouldn't have to write error-prone maths that are tangential to your problem domain.
Take the following folder structure
notice:
Now in the index.html.en
file you'll want to put the following markup
<p>
<span>src="check_mark.png"</span>
<img src="check_mark.png" />
<span>I'm purple because I'm referenced from this current directory</span>
</p>
<p>
<span>src="/check_mark.png"</span>
<img src="/check_mark.png" />
<span>I'm green because I'm referenced from the ROOT directory</span>
</p>
<p>
<span>src="subfolder/check_mark.png"</span>
<img src="subfolder/check_mark.png" />
<span>I'm yellow because I'm referenced from the child of this current directory</span>
</p>
<p>
<span>src="/subfolder/check_mark.png"</span>
<img src="/subfolder/check_mark.png" />
<span>I'm orange because I'm referenced from the child of the ROOT directory</span>
</p>
<p>
<span>src="../subfolder/check_mark.png"</span>
<img src="../subfolder/check_mark.png" />
<span>I'm purple because I'm referenced from the parent of this current directory</span>
</p>
<p>
<span>src="subfolder/subfolder/check_mark.png"</span>
<img src="subfolder/subfolder/check_mark.png" />
<span>I'm [broken] because there is no subfolder two children down from this current directory</span>
</p>
<p>
<span>src="/subfolder/subfolder/check_mark.png"</span>
<img src="/subfolder/subfolder/check_mark.png" />
<span>I'm purple because I'm referenced two children down from the ROOT directory</span>
</p>
Now if you load up the index.html.en
file located in the second subfolder
http://example.com/subfolder/subfolder/
This will be your output
To get the content of a directory you can use
$files = Get-ChildItem "C:\Users\gerhardl\Documents\My Received Files\"
Then you can loop over this variable as well:
for ($i=0; $i -lt $files.Count; $i++) {
$outfile = $files[$i].FullName + "out"
Get-Content $files[$i].FullName | Where-Object { ($_ -match 'step4' -or $_ -match 'step9') } | Set-Content $outfile
}
An even easier way to put this is the foreach
loop (thanks to @Soapy and @MarkSchultheiss):
foreach ($f in $files){
$outfile = $f.FullName + "out"
Get-Content $f.FullName | Where-Object { ($_ -match 'step4' -or $_ -match 'step9') } | Set-Content $outfile
}
os.listdir()
to see the list of files in the current working directoryos.getcwd()
(if you launch your code from an IDE, you may well be in a different directory)os.chdir(dir)
, dir
being the folder where the file is
located, then open the file with just its name like you were doing.open
call.dir = r'C:\Python32'
'C:\\User\\Bob\\...'
'C:/Python32'
and do not need to be escaped.Let me clarify how Python finds files:
working directory
. You can view Python's current working directory by calling os.getcwd()
. If you try to do open('sortedLists.yaml')
, Python will see that you are passing it a relative path, so it will search for the file inside the current working directory. Calling os.chdir
will change the current working directory.
Example: Let's say file.txt
is found in C:\Folder
.
To open it, you can do:
os.chdir(r'C:\Folder')
open('file.txt') #relative path, looks inside the current working directory
or
open(r'C:\Folder\file.txt') #full path
¦ What is an attribute?
– A variable that belongs to an object.Attributes is same term used alternatively for properties or fields or data members or class members
¦ How else can it be called?
– field or instance variable
¦ How do you create one? What is the syntax?
– You need to declare attributes at the beginning of the class definition, outside of any method. The syntax is the following: ;
In macOS for those who are using the express version 4.x.x
and using the DOTENV
plugin, need to use like this:
After installing the plugin import like the following in the file where you init the application:
require('dotenv').config({path: path.resolve(__dirname+'/.env')});
In the root directory create a file '.env' and add the varaiable like:
NODE_ENV=development
or
NODE_ENV = development
For those looking for an answer in Oracle:
SELECT column_name FROM user_tab_columns WHERE table_name = 'TABLENAME'
Use replace()
s = s.replace("'", "\\'");
output:
You\'ll be totally awesome, I\'m really terrible
Here's how you could set a custom cookie value for the request:
var baseAddress = new Uri("http://example.com");
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
{
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("foo", "bar"),
new KeyValuePair<string, string>("baz", "bazinga"),
});
cookieContainer.Add(baseAddress, new Cookie("CookieName", "cookie_value"));
var result = await client.PostAsync("/test", content);
result.EnsureSuccessStatusCode();
}
You can also use the following code :
package com.agileinfotech.bsviewer.ldap;
import java.util.Hashtable;
import java.util.ResourceBundle;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
public class LDAPLoginAuthentication {
public LDAPLoginAuthentication() {
// TODO Auto-generated constructor
}
ResourceBundle resBundle = ResourceBundle.getBundle("settings");
@SuppressWarnings("unchecked")
public String authenticateUser(String username, String password) {
String strUrl = "success";
Hashtable env = new Hashtable(11);
boolean b = false;
String Securityprinciple = "cn=" + username + "," + resBundle.getString("UserSearch");
env.put(Context.INITIAL_CONTEXT_FACTORY, resBundle.getString("InitialContextFactory"));
env.put(Context.PROVIDER_URL, resBundle.getString("Provider_url"));
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, Securityprinciple);
env.put(Context.SECURITY_CREDENTIALS, password);
try {
// Create initial context
DirContext ctx = new InitialDirContext(env);
// Close the context when we're done
b = true;
ctx.close();
} catch (NamingException e) {
b = false;
} finally {
if (b) {
strUrl = "success";
} else {
strUrl = "failer";
}
}
return strUrl;
}
}
Hi,
Well, I have tried the methods mentioned above! it's working yes, but not exactly the way I wanted. I wanted to redirect the default page extension to the main domain with our further action.
Here how I do that...
# Accesible Index Page
<IfModule dir_module>
DirectoryIndex index.php index.html
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.(html|htm|php|php3|php5|shtml|phtml) [NC]
RewriteRule ^index\.html|htm|php|php3|php5|shtml|phtml$ / [R=301,L]
</IfModule>
The above code simply captures any index.* and redirect it to the main domain.
Thank you
\n - simple newline character insertion works:
# Here's the test example - string with newline char:
In [36]: test_line = "Hi!!!\n testing first line.. \n testing second line.. \n and third line....."
# Output:
In [37]: print(test_line)
Hi!!!
testing first line..
testing second line..
and third line.....
Swift extension based on the answer by maz
extension AVPlayer {
var isPlaying: Bool {
return ((rate != 0) && (error == nil))
}
}
I found the answer, you need to set the environment variable ANSIBLE_HOST_KEY_CHECKING
to False
. For example:
ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook ...
Its very simple actually. Try this:
str1="a b c d"
splitStr1 = str1.split()
print splitStr1
This Answer is Published in 2020, Fix this Error in 3 steps:
First step: I changed the value of expo
in package.json
file to the latest supported version, according to expo documents(visit here).
Second step: I changed the value of sdkVersion
in app.json
file to the same value of expo
in package.json
.( equal number to last step).
Third step : I changed the value of react-native
in package.json
file to the same value of React Native Version
, according to expo documents(visit here).
now your ready to go.
use npm install
to install specified version of dependencies and then npm start
to run the project
It's compiling because printf
isn't type safe, since it uses variable arguments in the C sense1. printf
has no option for std::string
, only a C-style string. Using something else in place of what it expects definitely won't give you the results you want. It's actually undefined behaviour, so anything at all could happen.
The easiest way to fix this, since you're using C++, is printing it normally with std::cout
, since std::string
supports that through operator overloading:
std::cout << "Follow this command: " << myString;
If, for some reason, you need to extract the C-style string, you can use the c_str()
method of std::string
to get a const char *
that is null-terminated. Using your example:
#include <iostream>
#include <string>
#include <stdio.h>
int main()
{
using namespace std;
string myString = "Press ENTER to quit program!";
cout << "Come up and C++ me some time." << endl;
printf("Follow this command: %s", myString.c_str()); //note the use of c_str
cin.get();
return 0;
}
If you want a function that is like printf
, but type safe, look into variadic templates (C++11, supported on all major compilers as of MSVC12). You can find an example of one here. There's nothing I know of implemented like that in the standard library, but there might be in Boost, specifically boost::format
.
[1]: This means that you can pass any number of arguments, but the function relies on you to tell it the number and types of those arguments. In the case of printf
, that means a string with encoded type information like %d
meaning int
. If you lie about the type or number, the function has no standard way of knowing, although some compilers have the ability to check and give warnings when you lie.
Since and
has lower precedence than =
you can use it in condition assignment:
if ($var = true && false) // Compare true with false and assign to $var
if ($var = true and false) // Assign true to $var and compare $var to false
What you want is called an associative array. In python these are called dictionaries.
Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys.
myDict = {}
myDict["john"] = "johns value"
myDict["jeff"] = "jeffs value"
Alternative way to create the above dict:
myDict = {"john": "johns value", "jeff": "jeffs value"}
Accessing values:
print(myDict["jeff"]) # => "jeffs value"
Getting the keys (in Python v2):
print(myDict.keys()) # => ["john", "jeff"]
In Python 3, you'll get a dict_keys
, which is a view and a bit more efficient (see views docs and PEP 3106 for details).
print(myDict.keys()) # => dict_keys(['john', 'jeff'])
If you want to learn about python dictionary internals, I recommend this ~25 min video presentation: https://www.youtube.com/watch?v=C4Kc8xzcA68. It's called the "The Mighty Dictionary".
The reason it is only a suggestion is that you could quite easily write a print function that ignored the options value. The built-in printing and formatting functions do use the options
value as a default.
As to the second question, since R uses finite precision arithmetic, your answers aren't accurate beyond 15 or 16 decimal places, so in general, more aren't required. The gmp and rcdd packages deal with multiple precision arithmetic (via an interace to the gmp library), but this is mostly related to big integers rather than more decimal places for your doubles.
Mathematica or Maple will allow you to give as many decimal places as your heart desires.
EDIT:
It might be useful to think about the difference between decimal places and significant figures. If you are doing statistical tests that rely on differences beyond the 15th significant figure, then your analysis is almost certainly junk.
On the other hand, if you are just dealing with very small numbers, that is less of a problem, since R can handle number as small as .Machine$double.xmin
(usually 2e-308).
Compare these two analyses.
x1 <- rnorm(50, 1, 1e-15)
y1 <- rnorm(50, 1 + 1e-15, 1e-15)
t.test(x1, y1) #Should throw an error
x2 <- rnorm(50, 0, 1e-15)
y2 <- rnorm(50, 1e-15, 1e-15)
t.test(x2, y2) #ok
In the first case, differences between numbers only occur after many significant figures, so the data are "nearly constant". In the second case, Although the size of the differences between numbers are the same, compared to the magnitude of the numbers themselves they are large.
As mentioned by e3bo, you can use multiple-precision floating point numbers using the Rmpfr
package.
mpfr("3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825")
These are slower and more memory intensive to use than regular (double precision) numeric
vectors, but can be useful if you have a poorly conditioned problem or unstable algorithm.
A trick I often use when I just need "a little" shadow (read: contour must not be super-precise) is placing a DIV with a radial fill 100%-black-to-100%-transparent under the image. The CSS for the DIV looks something like:
.shadow320x320{
background: -moz-radial-gradient(center, ellipse cover, rgba(0,0,0,0.58) 0%, rgba(0,0,0,0.58) 1%, rgba(0,0,0,0) 43%, rgba(0,0,0,0) 100%); /* FF3.6+ */
background: -webkit-gradient(radial, center center, 0px, center center, 100%, color-stop(0%,rgba(0,0,0,0.58)), color-stop(1%,rgba(0,0,0,0.58)), color-stop(43%,rgba(0,0,0,0)), color-stop(100%,rgba(0,0,0,0))); /* Chrome,Safari4+ */
background: -webkit-radial-gradient(center, ellipse cover, rgba(0,0,0,0.58) 0%,rgba(0,0,0,0.58) 1%,rgba(0,0,0,0) 43%,rgba(0,0,0,0) 100%); /* Chrome10+,Safari5.1+ */
background: -o-radial-gradient(center, ellipse cover, rgba(0,0,0,0.58) 0%,rgba(0,0,0,0.58) 1%,rgba(0,0,0,0) 43%,rgba(0,0,0,0) 100%); /* Opera 12+ */
background: -ms-radial-gradient(center, ellipse cover, rgba(0,0,0,0.58) 0%,rgba(0,0,0,0.58) 1%,rgba(0,0,0,0) 43%,rgba(0,0,0,0) 100%); /* IE10+ */
background: radial-gradient(ellipse at center, rgba(0,0,0,0.58) 0%,rgba(0,0,0,0.58) 1%,rgba(0,0,0,0) 43%,rgba(0,0,0,0) 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#94000000', endColorstr='#00000000',GradientType=1 ); /* IE6-9 fallback on horizontal gradient */
}
This will create a circular black faded-out 'dot' on a 320x320 DIV. If you scale the height or width of the DIV you get a corresponding oval. Very nice to create eg shadows under bottles or other cylinder-like shapes.
There is an absolute incredible, super-excellent tool to create CSS gradients here:
http://www.colorzilla.com/gradient-editor/
ps: Do a courtesy ad-click when you use it. (And, no,I'm not affiliated with it. But courtesy clicking should become a bit of a habit, especially for tool you use often... just sayin... since we're all working on the net...)
Check out the link given it has Apache HTTP Server 2.4.2 x86 and x64 Windows Installers http://www.anindya.com/apache-http-server-2-4-2-x86-and-x64-windows-installers/
.find_all()
returns list of all found elements, so:
input_tag = soup.find_all(attrs={"name" : "stainfo"})
input_tag
is a list (probably containing only one element). Depending on what you want exactly you either should do:
output = input_tag[0]['value']
or use .find()
method which returns only one (first) found element:
input_tag = soup.find(attrs={"name": "stainfo"})
output = input_tag['value']
If you want to use a function form a package or module in python you have to import and reference them. For example normally you do the following to draw 5 points( [1,5],[2,4],[3,3],[4,2],[5,1]) in the space:
import matplotlib.pyplot
matplotlib.pyplot.plot([1,2,3,4,5],[5,4,3,2,1],"bx")
matplotlib.pyplot.show()
In your solution
from matplotlib import*
This imports the package matplotlib and "plot is not defined" means there is no plot function in matplotlib you can access directly, but instead if you import as
from matplotlib.pyplot import *
plot([1,2,3,4,5],[5,4,3,2,1],"bx")
show()
Now you can use any function in matplotlib.pyplot without referencing them with matplotlib.pyplot.
I would recommend you to name imports you have, in this case you can prevent disambiguation and future problems with the same function names. The last and clean version of above example looks like:
import matplotlib.pyplot as plt
plt.plot([1,2,3,4,5],[5,4,3,2,1],"bx")
plt.show()
DOM is a logical model that can be implemented in any convenient manner.It is based on an object structure that closely resembles the structure of the documents it models.
For More Information on DOM : Click Here
The following will just print out the content of the file:
cat $Path/FileName.txt
while read line;
do
echo $line
done
The example below is an adaptation and simplification of a longer post from We ? Swift. This is what it will look like:
It can be just the usual Single View Application.
Replace the ViewController.swift code with the following:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// Data model: These strings will be the data for the table view cells
let animals: [String] = ["Horse", "Cow", "Camel", "Sheep", "Goat"]
// cell reuse id (cells that scroll out of view can be reused)
let cellReuseIdentifier = "cell"
// don't forget to hook this up from the storyboard
@IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Register the table view cell class and its reuse id
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
// (optional) include this line if you want to remove the extra empty cell divider lines
// self.tableView.tableFooterView = UIView()
// This view controller itself will provide the delegate methods and row data for the table view.
tableView.delegate = self
tableView.dataSource = self
}
// number of rows in table view
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.animals.count
}
// create a cell for each table view row
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// create a new cell if needed or reuse an old one
let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!
// set the text from the data model
cell.textLabel?.text = self.animals[indexPath.row]
return cell
}
// method to run when table view cell is tapped
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("You tapped cell number \(indexPath.row).")
}
}
Read the in-code comments to see what is happening. The highlights are
UITableViewDelegate
and UITableViewDataSource
protocols.numberOfRowsInSection
method determines how many rows there will be in the table view.cellForRowAtIndexPath
method sets up each row.didSelectRowAtIndexPath
method is called every time a row is tapped.Drag a UITableView
onto your View Controller. Use auto layout to pin the four sides.
Control drag from the Table View in IB to the tableView
outlet in the code.
That's all. You should be able run your app now.
This answer was tested with Xcode 9 and Swift 4
Row Deletion
You only have to add a single method to the basic project above if you want to enable users to delete rows. See this basic example to learn how.
Row Spacing
If you would like to have spacing between your rows, see this supplemental example.
Custom cells
The default layout for the table view cells may not be what you need. Check out this example to help get you started making your own custom cells.
Dynamic Cell Height
Sometimes you don't want every cell to be the same height. Starting with iOS 8 it is easy to automatically set the height depending on the cell content. See this example for everything you need to get you started.
You can remove the "not null" property from your column in mysql table if not necessary. when you remove "not null" property no need for "0000-00-00 00:00:00" conversion and problem is gone.
At least worked for me.
If you target android 5.0 and above. You could use:
Activity.startLockTask()
I would like to share my way, first of all i had Huawei ascend p7 and my touch screen stopped handling touch, so none of the above solutions helped me to be unlock the phone, i have found a better clever way to do it since i can see the screen on thus i thought that my display is 1080 x 1920 px thus i had to simulate a drawing on my photoshop with keypad with (x,y) so i can try instead with input mouse tap
command.
Since i have pin lock as you can see in the picture, i have got all the (x,y) for all the numbers on the screen to simulate touch and unlock my screen and have to backup my data, thus if my password is 123 i did all the following commands
adb shell input mouse tap 100 1150
adb shell input mouse tap 500 1150
adb shell input mouse tap 900 1150
And then my phone just got unlocked, i hope it was helpful.
I had this same problem and this link provided the solution for me:
http://www.holovaty.com/writing/cors-ie-cloudfront/
The short version of it is:
Your cloudfront distribution will update, which takes about 10 minutes. After that, all should be well, you can verify by checking that the CORS related error messages are gone from the browser.
To get this running in Eclipse, as well as in a Maven build, you should add the addDefaultImplementationEntries
and addDefaultSpecificationEntries
pom entries as described in other replies, then use the following code:
public synchronized static final String getVersion() {
// Try to get version number from pom.xml (available in Eclipse)
try {
String className = getClass().getName();
String classfileName = "/" + className.replace('.', '/') + ".class";
URL classfileResource = getClass().getResource(classfileName);
if (classfileResource != null) {
Path absolutePackagePath = Paths.get(classfileResource.toURI())
.getParent();
int packagePathSegments = className.length()
- className.replace(".", "").length();
// Remove package segments from path, plus two more levels
// for "target/classes", which is the standard location for
// classes in Eclipse.
Path path = absolutePackagePath;
for (int i = 0, segmentsToRemove = packagePathSegments + 2;
i < segmentsToRemove; i++) {
path = path.getParent();
}
Path pom = path.resolve("pom.xml");
try (InputStream is = Files.newInputStream(pom)) {
Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(is);
doc.getDocumentElement().normalize();
String version = (String) XPathFactory.newInstance()
.newXPath().compile("/project/version")
.evaluate(doc, XPathConstants.STRING);
if (version != null) {
version = version.trim();
if (!version.isEmpty()) {
return version;
}
}
}
}
} catch (Exception e) {
// Ignore
}
// Try to get version number from maven properties in jar's META-INF
try (InputStream is = getClass()
.getResourceAsStream("/META-INF/maven/" + MAVEN_PACKAGE + "/"
+ MAVEN_ARTIFACT + "/pom.properties")) {
if (is != null) {
Properties p = new Properties();
p.load(is);
String version = p.getProperty("version", "").trim();
if (!version.isEmpty()) {
return version;
}
}
} catch (Exception e) {
// Ignore
}
// Fallback to using Java API to get version from MANIFEST.MF
String version = null;
Package pkg = getClass().getPackage();
if (pkg != null) {
version = pkg.getImplementationVersion();
if (version == null) {
version = pkg.getSpecificationVersion();
}
}
version = version == null ? "" : version.trim();
return version.isEmpty() ? "unknown" : version;
}
If your Java build puts target classes somewhere other than "target/classes", then you may need to adjust the value of segmentsToRemove.
[Joke mode="on"]
public enum Evenness
{
Unknown = 0,
Even = 1,
Odd = 2
}
public static Evenness AnalyzeEvenness(object o)
{
if (o == null)
return Evenness.Unknown;
string foo = o.ToString();
if (String.IsNullOrEmpty(foo))
return Evenness.Unknown;
char bar = foo[foo.Length - 1];
switch (bar)
{
case '0':
case '2':
case '4':
case '6':
case '8':
return Evenness.Even;
case '1':
case '3':
case '5':
case '7':
case '9':
return Evenness.Odd;
default:
return Evenness.Unknown;
}
}
[Joke mode="off"]
EDIT: Added confusing values to the enum.
Upon investigation, it's also worth noting that when you want to start using docker in a new terminal window, the correct command is:
$(boot2docker shellinit)
I had tested these commands:
>> docker info
Get http:///var/run/docker.sock/v1.15/info: dial unix /var/run/docker.sock: no such file or directory
>> boot2docker shellinit
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/ca.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/cert.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/key.pem
export DOCKER_HOST=tcp://192.168.59.103:2376
export DOCKER_CERT_PATH=/Users/ddavison/.boot2docker/certs/boot2docker-vm
export DOCKER_TLS_VERIFY=1
>> docker info
Get http:///var/run/docker.sock/v1.15/info: dial unix /var/run/docker.sock: no such file or directory
Notice that docker info returned that same error. however.. when using $(boot2docker shellinit)
...
>> $(boot2docker init)
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/ca.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/cert.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/key.pem
>> docker info
Containers: 3
...
Since I felt like these answers just touched the surface, I attempted to dig a bit deeper.
So what we would really want to do is something that doesn't compile, say:
// Won't compile... damn
public static void Main()
{
try
{
throw new ArgumentOutOfRangeException();
}
catch (ArgumentOutOfRangeException)
catch (IndexOutOfRangeException)
{
// ... handle
}
The reason we want this is because we don't want the exception handler to catch things that we need later on in the process. Sure, we can catch an Exception and check with an 'if' what to do, but let's be honest, we don't really want that. (FxCop, debugger issues, uglyness)
So why won't this code compile - and how can we hack it in such a way that it will?
If we look at the code, what we really would like to do is forward the call. However, according to the MS Partition II, IL exception handler blocks won't work like this, which in this case makes sense because that would imply that the 'exception' object can have different types.
Or to write it in code, we ask the compiler to do something like this (well it's not entirely correct, but it's the closest possible thing I guess):
// Won't compile... damn
try
{
throw new ArgumentOutOfRangeException();
}
catch (ArgumentOutOfRangeException e) {
goto theOtherHandler;
}
catch (IndexOutOfRangeException e) {
theOtherHandler:
Console.WriteLine("Handle!");
}
The reason that this won't compile is quite obvious: what type and value would the '$exception' object have (which are here stored in the variables 'e')? The way we want the compiler to handle this is to note that the common base type of both exceptions is 'Exception', use that for a variable to contain both exceptions, and then handle only the two exceptions that are caught. The way this is implemented in IL is as 'filter', which is available in VB.Net.
To make it work in C#, we need a temporary variable with the correct 'Exception' base type. To control the flow of the code, we can add some branches. Here goes:
Exception ex;
try
{
throw new ArgumentException(); // for demo purposes; won't be caught.
goto noCatch;
}
catch (ArgumentOutOfRangeException e) {
ex = e;
}
catch (IndexOutOfRangeException e) {
ex = e;
}
Console.WriteLine("Handle the exception 'ex' here :-)");
// throw ex ?
noCatch:
Console.WriteLine("We're done with the exception handling.");
The obvious disadvantages for this are that we cannot re-throw properly, and -well let's be honest- that it's quite the ugly solution. The uglyness can be fixed a bit by performing branch elimination, which makes the solution slightly better:
Exception ex = null;
try
{
throw new ArgumentException();
}
catch (ArgumentOutOfRangeException e)
{
ex = e;
}
catch (IndexOutOfRangeException e)
{
ex = e;
}
if (ex != null)
{
Console.WriteLine("Handle the exception here :-)");
}
That leaves just the 're-throw'. For this to work, we need to be able to perform the handling inside the 'catch' block - and the only way to make this work is by an catching 'Exception' object.
At this point, we can add a separate function that handles the different types of Exceptions using overload resolution, or to handle the Exception. Both have disadvantages. To start, here's the way to do it with a helper function:
private static bool Handle(Exception e)
{
Console.WriteLine("Handle the exception here :-)");
return true; // false will re-throw;
}
public static void Main()
{
try
{
throw new OutOfMemoryException();
}
catch (ArgumentException e)
{
if (!Handle(e)) { throw; }
}
catch (IndexOutOfRangeException e)
{
if (!Handle(e)) { throw; }
}
Console.WriteLine("We're done with the exception handling.");
And the other solution is to catch the Exception object and handle it accordingly. The most literal translation for this, based on the context above is this:
try
{
throw new ArgumentException();
}
catch (Exception e)
{
Exception ex = (Exception)(e as ArgumentException) ?? (e as IndexOutOfRangeException);
if (ex != null)
{
Console.WriteLine("Handle the exception here :-)");
// throw ?
}
else
{
throw;
}
}
So to conclude:
Following code from here is a useful solution. No keystores etc. Just call method SSLUtilities.trustAllHttpsCertificates() before initializing the service and port (in SOAP).
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
* This class provide various static methods that relax X509 certificate and
* hostname verification while using the SSL over the HTTP protocol.
*
* @author Jiramot.info
*/
public final class SSLUtilities {
/**
* Hostname verifier for the Sun's deprecated API.
*
* @deprecated see {@link #_hostnameVerifier}.
*/
private static com.sun.net.ssl.HostnameVerifier __hostnameVerifier;
/**
* Thrust managers for the Sun's deprecated API.
*
* @deprecated see {@link #_trustManagers}.
*/
private static com.sun.net.ssl.TrustManager[] __trustManagers;
/**
* Hostname verifier.
*/
private static HostnameVerifier _hostnameVerifier;
/**
* Thrust managers.
*/
private static TrustManager[] _trustManagers;
/**
* Set the default Hostname Verifier to an instance of a fake class that
* trust all hostnames. This method uses the old deprecated API from the
* com.sun.ssl package.
*
* @deprecated see {@link #_trustAllHostnames()}.
*/
private static void __trustAllHostnames() {
// Create a trust manager that does not validate certificate chains
if (__hostnameVerifier == null) {
__hostnameVerifier = new SSLUtilities._FakeHostnameVerifier();
} // if
// Install the all-trusting host name verifier
com.sun.net.ssl.HttpsURLConnection
.setDefaultHostnameVerifier(__hostnameVerifier);
} // __trustAllHttpsCertificates
/**
* Set the default X509 Trust Manager to an instance of a fake class that
* trust all certificates, even the self-signed ones. This method uses the
* old deprecated API from the com.sun.ssl package.
*
* @deprecated see {@link #_trustAllHttpsCertificates()}.
*/
private static void __trustAllHttpsCertificates() {
com.sun.net.ssl.SSLContext context;
// Create a trust manager that does not validate certificate chains
if (__trustManagers == null) {
__trustManagers = new com.sun.net.ssl.TrustManager[]{new SSLUtilities._FakeX509TrustManager()};
} // if
// Install the all-trusting trust manager
try {
context = com.sun.net.ssl.SSLContext.getInstance("SSL");
context.init(null, __trustManagers, new SecureRandom());
} catch (GeneralSecurityException gse) {
throw new IllegalStateException(gse.getMessage());
} // catch
com.sun.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(context
.getSocketFactory());
} // __trustAllHttpsCertificates
/**
* Return true if the protocol handler property java. protocol.handler.pkgs
* is set to the Sun's com.sun.net.ssl. internal.www.protocol deprecated
* one, false otherwise.
*
* @return true if the protocol handler property is set to the Sun's
* deprecated one, false otherwise.
*/
private static boolean isDeprecatedSSLProtocol() {
return ("com.sun.net.ssl.internal.www.protocol".equals(System
.getProperty("java.protocol.handler.pkgs")));
} // isDeprecatedSSLProtocol
/**
* Set the default Hostname Verifier to an instance of a fake class that
* trust all hostnames.
*/
private static void _trustAllHostnames() {
// Create a trust manager that does not validate certificate chains
if (_hostnameVerifier == null) {
_hostnameVerifier = new SSLUtilities.FakeHostnameVerifier();
} // if
// Install the all-trusting host name verifier:
HttpsURLConnection.setDefaultHostnameVerifier(_hostnameVerifier);
} // _trustAllHttpsCertificates
/**
* Set the default X509 Trust Manager to an instance of a fake class that
* trust all certificates, even the self-signed ones.
*/
private static void _trustAllHttpsCertificates() {
SSLContext context;
// Create a trust manager that does not validate certificate chains
if (_trustManagers == null) {
_trustManagers = new TrustManager[]{new SSLUtilities.FakeX509TrustManager()};
} // if
// Install the all-trusting trust manager:
try {
context = SSLContext.getInstance("SSL");
context.init(null, _trustManagers, new SecureRandom());
} catch (GeneralSecurityException gse) {
throw new IllegalStateException(gse.getMessage());
} // catch
HttpsURLConnection.setDefaultSSLSocketFactory(context
.getSocketFactory());
} // _trustAllHttpsCertificates
/**
* Set the default Hostname Verifier to an instance of a fake class that
* trust all hostnames.
*/
public static void trustAllHostnames() {
// Is the deprecated protocol setted?
if (isDeprecatedSSLProtocol()) {
__trustAllHostnames();
} else {
_trustAllHostnames();
} // else
} // trustAllHostnames
/**
* Set the default X509 Trust Manager to an instance of a fake class that
* trust all certificates, even the self-signed ones.
*/
public static void trustAllHttpsCertificates() {
// Is the deprecated protocol setted?
if (isDeprecatedSSLProtocol()) {
__trustAllHttpsCertificates();
} else {
_trustAllHttpsCertificates();
} // else
} // trustAllHttpsCertificates
/**
* This class implements a fake hostname verificator, trusting any host
* name. This class uses the old deprecated API from the com.sun. ssl
* package.
*
* @author Jiramot.info
*
* @deprecated see {@link SSLUtilities.FakeHostnameVerifier}.
*/
public static class _FakeHostnameVerifier implements
com.sun.net.ssl.HostnameVerifier {
/**
* Always return true, indicating that the host name is an acceptable
* match with the server's authentication scheme.
*
* @param hostname the host name.
* @param session the SSL session used on the connection to host.
* @return the true boolean value indicating the host name is trusted.
*/
public boolean verify(String hostname, String session) {
return (true);
} // verify
} // _FakeHostnameVerifier
/**
* This class allow any X509 certificates to be used to authenticate the
* remote side of a secure socket, including self-signed certificates. This
* class uses the old deprecated API from the com.sun.ssl package.
*
* @author Jiramot.info
*
* @deprecated see {@link SSLUtilities.FakeX509TrustManager}.
*/
public static class _FakeX509TrustManager implements
com.sun.net.ssl.X509TrustManager {
/**
* Empty array of certificate authority certificates.
*/
private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[]{};
/**
* Always return true, trusting for client SSL chain peer certificate
* chain.
*
* @param chain the peer certificate chain.
* @return the true boolean value indicating the chain is trusted.
*/
public boolean isClientTrusted(X509Certificate[] chain) {
return (true);
} // checkClientTrusted
/**
* Always return true, trusting for server SSL chain peer certificate
* chain.
*
* @param chain the peer certificate chain.
* @return the true boolean value indicating the chain is trusted.
*/
public boolean isServerTrusted(X509Certificate[] chain) {
return (true);
} // checkServerTrusted
/**
* Return an empty array of certificate authority certificates which are
* trusted for authenticating peers.
*
* @return a empty array of issuer certificates.
*/
public X509Certificate[] getAcceptedIssuers() {
return (_AcceptedIssuers);
} // getAcceptedIssuers
} // _FakeX509TrustManager
/**
* This class implements a fake hostname verificator, trusting any host
* name.
*
* @author Jiramot.info
*/
public static class FakeHostnameVerifier implements HostnameVerifier {
/**
* Always return true, indicating that the host name is an acceptable
* match with the server's authentication scheme.
*
* @param hostname the host name.
* @param session the SSL session used on the connection to host.
* @return the true boolean value indicating the host name is trusted.
*/
public boolean verify(String hostname, javax.net.ssl.SSLSession session) {
return (true);
} // verify
} // FakeHostnameVerifier
/**
* This class allow any X509 certificates to be used to authenticate the
* remote side of a secure socket, including self-signed certificates.
*
* @author Jiramot.info
*/
public static class FakeX509TrustManager implements X509TrustManager {
/**
* Empty array of certificate authority certificates.
*/
private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[]{};
/**
* Always trust for client SSL chain peer certificate chain with any
* authType authentication types.
*
* @param chain the peer certificate chain.
* @param authType the authentication type based on the client
* certificate.
*/
public void checkClientTrusted(X509Certificate[] chain, String authType) {
} // checkClientTrusted
/**
* Always trust for server SSL chain peer certificate chain with any
* authType exchange algorithm types.
*
* @param chain the peer certificate chain.
* @param authType the key exchange algorithm used.
*/
public void checkServerTrusted(X509Certificate[] chain, String authType) {
} // checkServerTrusted
/**
* Return an empty array of certificate authority certificates which are
* trusted for authenticating peers.
*
* @return a empty array of issuer certificates.
*/
public X509Certificate[] getAcceptedIssuers() {
return (_AcceptedIssuers);
} // getAcceptedIssuers
} // FakeX509TrustManager
} // SSLUtilities
document.getElementById('Id').value='new value';
https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById
you need to register it in index.android.js / index.ios.js
like this:
'use strict';
import {
AppRegistry
} from 'react-native';
import app from "./app";
AppRegistry.registerComponent('test', () => app);
you put resource-ref in the description tag in web.xml
You can also do this
[Flags]
public enum MyEnum
{
None = 0,
First = 1 << 0,
Second = 1 << 1,
Third = 1 << 2,
Fourth = 1 << 3
}
I find the bit-shifting easier than typing 4,8,16,32 and so on. It has no impact on your code because it's all done at compile time
HTML:
<a href="#" class="delete" data-confirm="Are you sure to delete this item?">Delete</a>
Using jQuery:
$('.delete').on("click", function (e) {
e.preventDefault();
var choice = confirm($(this).attr('data-confirm'));
if (choice) {
window.location.href = $(this).attr('href');
}
});
I have seen people use Throwable to catch some errors that might happen due to infra failure/ non availability.
If you know the width of the span you could just stuff in a left margin.
Try this:
.center { text-align: center}
div.center span { display: table; }
Add the "center: class to your .
If you want some spans centered, but not others, replace the "div.center span" in your style sheet to a class (e.g "center-span") and add that class to the span.
X - TRUNC(X), works for negatives too.
It would give you the decimal part of the number, as a double, not an integer.
It is varchar
and not var_char
CREATE DATABASE IF NOT EXISTS courses;
USE courses;
CREATE TABLE IF NOT EXISTS teachers(
id INT(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
addr VARCHAR(255) NOT NULL,
phone INT NOT NULL
);
You should use a SQL tool to visualize possbile errors like MySQL Workbench.
Just pass it as parameters as follows:
php test.php one two three
And inside file test.php:
<?php
if(isset($argv))
{
foreach ($argv as $arg)
{
echo $arg;
echo "\r\n";
}
}
?>
Apple mail has also been known to make an encoding error on text and csv attachments outbound. In essence it replaces line terminators with soft line breaks on each line, which look like =0D in the encoding. If the attachment is emailed to Outlook, Outlook sees the soft line breaks, removes the = then appends real line breaks i.e. 0D0A so you get 0D0D0A (cr cr lf) at the end of each line. The encoding should be =0D= if it is a mac format file (or any other flavour of unix) or =0D0A= if it is a windows format file.
If you are emailing out from apple mail (in at least mavericks or yosemite), making the attachment not a text or csv file is an acceptable workaround e.g. compress it.
The bug also exists if you are running a windows VM under parallels and email a txt file from there using apple mail. It is the email encoding. Form previous comments here, it looks like netscape had the same issue.
In the case of the well voted solution posted by @Bikesh M Annur (here) doesn't work to you, try using:
<TextView
...
android:background="?android:attr/selectableItemBackgroundBorderless"
android:clickable="true" />
<ImageView
...
android:background="?android:attr/selectableItemBackgroundBorderless"
android:clickable="true" />
Also, when using android:clickable="true"
add android:focusable="true"
because:
"A widget that is declared to be clickable but not declared to be focusable is not accessible via the keyboard."
While you are working with Laravel you must be in root of laravel directory structure. There are App, route, public etc folders is root directory.
Just follow below step to fix issue.
check composer status using : composer -v
First, download the Laravel installer using Composer:
composer global require "laravel/installer"
Please check with below command:
php artisan serve
still not work then create new project with existing code. using LINK
.md
extension stands for Markdown, which Github uses, among others, to format those files.
Read about Markdown:
http://daringfireball.net/projects/markdown/
http://en.wikipedia.org/wiki/Markdown
Also:
The MultiModelForm from django-betterforms
is a convenient wrapper to do what is described in Gnudiff's answer. It wraps regular ModelForm
s in a single class which is transparently (at least for basic usage) used as a single form. I've copied an example from their docs below.
# forms.py
from django import forms
from django.contrib.auth import get_user_model
from betterforms.multiform import MultiModelForm
from .models import UserProfile
User = get_user_model()
class UserEditForm(forms.ModelForm):
class Meta:
fields = ('email',)
class UserProfileForm(forms.ModelForm):
class Meta:
fields = ('favorite_color',)
class UserEditMultiForm(MultiModelForm):
form_classes = {
'user': UserEditForm,
'profile': UserProfileForm,
}
# views.py
from django.views.generic import UpdateView
from django.core.urlresolvers import reverse_lazy
from django.shortcuts import redirect
from django.contrib.auth import get_user_model
from .forms import UserEditMultiForm
User = get_user_model()
class UserSignupView(UpdateView):
model = User
form_class = UserEditMultiForm
success_url = reverse_lazy('home')
def get_form_kwargs(self):
kwargs = super(UserSignupView, self).get_form_kwargs()
kwargs.update(instance={
'user': self.object,
'profile': self.object.profile,
})
return kwargs
No, you can simply use com.fasterxml.jackson.databind.ObjectMapper
.
Most likely you forgot to fix your import
-statements, delete all references to codehaus and you're golden.
Those are just version designations (just like windows xp, vista or windows 7) which they are using to name their major releases, instead of using version numbers. so you'll want to use the newest eclipse version available, which is helios (or 3.6 which is the corresponding version number).
You shouldn't change the npm registry using .bat
files.
Instead try to use modify the .npmrc
file which is the configuration for npm
.
The correct command for changing registry is
npm config set registry <registry url>
you can find more information with npm help config
command, also check for privileges when and if you are running .bat
files this way.
Typical usage might look like:
i=0
echo -e "hello1\nhello2\nhello3" | while read str ; do
echo "$((++i)): $str"
done
and output
1: hello1
2: hello2
3: hello3
Reason and solution-
Everything happens for a reason :)
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:3.1.0:clean (default-clean) on project
Solution- 1) Check the war and jar (also check jar if any running in background), terminate it.
2) if u have opened command prompt (cmd), and are using that path to execute the jar, close it or change the path in cmd. This was the reason in my case. Do check this.
Once u do this , u would be able to delete the contents of the target folder and and can also perform maven clean and maven install.
If you want to redirect the output to a log file to look for errors or something. You can do something like this.
sqlplus -s <<EOF>> LOG_FILE_NAME user/passwd@host/db
#Your SQL code
EOF
A status code of 0 in an NSHTTPURLResponse
object generally means there was no response, and can occur for various reasons. The server will never return a status of 0 as this is not a valid HTTP status code.
In your case, you are appearing to get a status code of 0 because the request is timing out and 0 is just the default value for the property. The timeout itself could be for various reasons, such as the server simply not responding in time, being blocked by a firewall, or your entire network connection being down. Usually in the case of the latter though the phone is smart enough to know it doesn't have a network connection and will fail immediately. However, it will still fail with an apparent status code of 0.
Note that in cases where the status code is 0, the real error is captured in the returned NSError
object, not the NSHTTPURLResponse
.
HTTP status 408
is pretty uncommon in my experience. I've never encountered one myself. But it is apparently used in cases where the client needs to maintain an active socket connection to the server, and the server is waiting on the client to send more data over the open socket, but it doesn't in a given amount of time and the server ends the connection with a 408
status code, essentially telling the client "you took too long".
One of the easiest ways to fix this is to use the $
which is the search all.
Here is a plunker that shows it working. I have changed the checkboxes to radio ( because I thought they should be complementary )..
http://plnkr.co/edit/dHzvm6hR5P8G4wPuTxoi?p=preview
If you want a very specific way of doing this ( instead of doing a generic search ) you need work with functions in the search.
The documentation is here
Minor nit: static functions are visible to a translation unit, which for most practical cases is the file the function is defined in. The error you are getting is commonly referred to as violation of the One Definition Rule.
The standard probably says something like:
"Every program shall contain exactly one definition of every noninline function or object that is used in that program; no diagnostic required."
That is the C way of looking at static functions. This is deprecated in C++ however.
In C++, additionally, you can declare member functions static. These are mostly metafunctions i.e. they do not describe/modify a particular object's behavior/state but act on the whole class itself. Also, this means that you do not need to create an object to call a static member function. Further, this also means, you only get access to static member variables from within such a function.
I'd add to Parrot's example the Singleton pattern which is based on this sort of a static member function to get/use a single object throughout the lifetime of a program.
Using the arrow package:
>>> import arrow
>>> arrow.get(2010, 12, 31).timestamp
1293753600
>>> time.gmtime(1293753600)
time.struct_time(tm_year=2010, tm_mon=12, tm_mday=31,
tm_hour=0, tm_min=0, tm_sec=0,
tm_wday=4, tm_yday=365, tm_isdst=0)
Here's an approach using generators:
function* square(n) {
for (var i = 0; i < n; i++ ) yield i*i;
}
Then you can write
console.log(...square(7));
Another idea is:
[...Array(5)].map((_, i) => i*i)
Array(5)
creates an unfilled five-element array. That's how Array
works when given a single argument. We use the spread operator to create an array with five undefined elements. That we can then map. See http://ariya.ofilabs.com/2013/07/sequences-using-javascript-array.html.
Alternatively, we could write
Array.from(Array(5)).map((_, i) => i*i)
or, we could take advantage of the second argument to Array#from
to skip the map
and write
Array.from(Array(5), (_, i) => i*i)
A horrible hack which I saw recently, which I do not recommend you use, is
[...1e4+''].map((_, i) => i*i)
You can also try what is suggested here: https://www.stkent.com/2017/08/10/update-your-path-for-the-new-android-emulator-location.html
For short, run the emulator from the sdk/emulator
folder
FOR XML PATH might not work on Microsoft Azure Synapse Serve. A possible alternative, following @Taryn dynamic generated cols approach, same results is obtained by using STRING_AGG.
DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX)
SELECT @cols = STRING_AGG(QUOTENAME(c.phaseid),', ')
/*OPTIONAL: within group (order by cast(t1.[FLOW_SP_SLPM] as INT) asc)*/
FROM (SELECT phaseid FROM temp
GROUP BY phaseid) c
set @query = 'SELECT elementid,' + @cols + ' from
(
select elementid,
phaseid,
effort
from temp
) x
PIVOT
(
max(effort)
for phaseid in (' + @cols + ')
) p '
execute(@query)
Go to the Ant website and download. This way, you have a copy of Ant outside of Eclipse. I recommend to put it under the C:\ant
directory. This way, it doesn't have any spaces in the directory names. In your System Control Panel, set the Environment Variable ANT_HOME
to this directory, then pre-pend to the System PATH
variable, %ANT_HOME%\bin
. This way, you don't have to put in the whole directory name.
Assuming you did the above, try this:
C:\> cd \Silk4J\Automation\iControlSilk4J
C:\Silk4J\Automation\iControlSilk4J> ant -d build
This will do several things:
build.xml
in the directory where it exists, you don't end up with the possibility that your Ant build can't locate a particular directory.The -d
will print out a lot of output, so you might want to capture it, or set your terminal buffer to something like 99999
, and run cls
first to clear out the buffer. This way, you'll capture all of the output from the beginning in the terminal buffer.
Let's see how Ant should be executing. You didn't specify any targets to execute, so Ant should be taking the default build
target. Here it is:
<target depends="build-subprojects,build-project" name="build"/>
The build
target does nothing itself. However, it depends upon two other targets, so these will be called first:
The first target is build-subprojects
:
<target name="build-subprojects"/>
This does nothing at all. It doesn't even have a dependency.
The next target specified is build-project
does have code:
<target depends="init" name="build-project">
This target does contain tasks, and some dependent targets. Before build-project
executes, it will first run the init
target:
<target name="init">
<mkdir dir="bin"/>
<copy includeemptydirs="false" todir="bin">
<fileset dir="src">
<exclude name="**/*.java"/>
</fileset>
</copy>
</target>
This target creates a directory called bin
, then copies all files under the src
tree with the suffix *.java
over to the bin
directory. The includeemptydirs
mean that directories without non-java code will not be created.
Ant uses a scheme to do minimal work. For example, if the bin
directory is created, the <mkdir/>
task is not executed. Also, if a file was previously copied, or there are no non-Java files in your src
directory tree, the <copy/>
task won't run. However, the init
target will still be executed.
Next, we go back to our previous build-project
target:
<target depends="init" name="build-project">
<echo message="${ant.project.name}: ${ant.file}"/>
<javac debug="true" debuglevel="${debuglevel}" destdir="bin" source="${source}" target="${target}">
<src path="src"/>
<classpath refid="iControlSilk4J.classpath"/>
</javac>
</target>
Look at this line:
<echo message="${ant.project.name}: ${ant.file}"/>
That should have always executed. Did your output print:
[echo] iControlSilk4J: C:\Silk4J\Automation\iControlSilk4J\build.xml
Maybe you didn't realize that was from your build.
After that, it runs the <javac/>
task. That is, if there's any files to actually compile. Again, Ant tries to avoid work it doesn't have to do. If all of the *.java
files have previously been compiled, the <javac/>
task won't execute.
And, that's the end of the build. Your build might not have done anything simply because there was nothing to do. You can try running the clean
task, and then build
:
C:\Silk4J\Automation\iControlSilk4J> ant -d clean build
However, Ant usually prints the target being executed. You should have seen this:
init:
build-subprojects:
build-projects:
[echo] iControlSilk4J: C:\Silk4J\Automation\iControlSilk4J\build.xml
build:
Build Successful
Note that the targets are all printed out in order they're executed, and the tasks are printed out as they are executed. However, if there's nothing to compile, or nothing to copy, then you won't see these tasks being executed. Does this look like your output? If so, it could be there's nothing to do.
bin
directory already exists, <mkdir/>
isn't going to execute.src
, or they have already been copied into bin
, the <copy/>
task won't execute.src
directory, or they have already been compiled, the <java/>
task won't run.If you look at the output from the -d
debug, you'll see Ant looking at a task, then explaining why a particular task wasn't executed. Plus, the debug option will explain how Ant decides what tasks to execute.
See if that helps.
Just go to https://github.com/new/import .
In the section "Your old repository's clone URL" paste the repo URL you want and in "Privacy" select Private
.
I use some css like this (based on css tricks):
@media screen and (min-width: 320px) and (max-width: 767px) and (orientation: portrait) {
html {
transform: rotate(-90deg);
transform-origin: left top;
width: 100vh;
height: 100vw;
overflow-x: hidden;
position: absolute;
top: 100%;
left: 0;
}
}
For Ubuntu:
add extension=php_curl.so
to php.ini to enable, if necessary. Then sudo service apache2 restart
this is generally taken care of automatically, but there are situations - eg, in shared development environments - where it can become necessary to re-enable manually.
The thumbprint will match all three of these conditions:
Problem was to select columns of on dataframe after joining with other dataframe.
I tried below and select the columns of salaryDf from the joined dataframe.
Hope this will help
val empDf=spark.read.option("header","true").csv("/data/tech.txt")
val salaryDf=spark.read.option("header","true").csv("/data/salary.txt")
val joinData= empDf.join(salaryDf,empDf.col("first") === salaryDf.col("first") and empDf.col("last") === salaryDf.col("last"))
//**below will select the colums of salaryDf only**
val finalDF=joinData.select(salaryDf.columns map salaryDf.col:_*)
//same way we can select the columns of empDf
joinData.select(empDf.columns map empDf.col:_*)
For an example data in your table such as combinations of
''
, null
and as well as actual value
than if you want to only actual value
and replace to ''
and null
value by #
symbol than execute this query
SELECT Column_Name = (CASE WHEN (Column_Name IS NULL OR Column_Name = '') THEN '#' ELSE Column_Name END) FROM Table_Name
and another way you can use it but this is little bit lengthy and instead of this you can also use IsNull
function but here only i am mentioning IIF
function
SELECT IIF(Column_Name IS NULL, '#', Column_Name) FROM Table_Name
SELECT IIF(Column_Name = '', '#', Column_Name) FROM Table_Name
-- and syntax of this query
SELECT IIF(Column_Name IS NULL, 'True Value', 'False Value') FROM Table_Name
I could not get any of these solutions working when using a TableLayout>TableRow>TextView
. I then found TableLayout.shrinkColumns="*"
. The only other solution that worked was forcing the TextView to layout_width:250px
etc but i don't like forcing widths like that.
Try something like this if working with tables.
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:shrinkColumns="*">
Note you need shrinkColumns="*"
This is obviously within a <LinearLayout>
. So something like <LinearLayout> <TableLayout> <TableRow> <TextView>
references:
http://code.google.com/p/android/issues/detail?id=4000
Hope that helps someone.
You can try this. It is very simple
<connectionStrings>
<add name="conString" connectionString="Data Source=SQLServerAddress;Initial Catalog=YourDatabaseName; User Id=SQLServerLoginId; Password=SQLServerPassword"/>
</connectionStrings>
Recursive convert object to array
function is_object(mixed_var) {
if (mixed_var instanceof Array) {
return false;
} else {
return (mixed_var !== null) && (typeof( mixed_var ) == 'object');
}
}
function objectToArray(obj) {
var array = [], tempObject;
for (var key in obj) {
tempObject = obj[key];
if (is_object(obj[key])) {
tempObject = objectToArray(obj[key]);
}
array[key] = tempObject;
}
return array;
}
sometimes mysql_upgrade -u root -p --force
is not realy enough,
please refer to this question : Table 'performance_schema.session_variables' doesn't exist
according to it:
cd [installation_path]\eds-binaries\dbserver\mysql5711x86x160420141510\bin
mysql_upgrade -u root -p --force
In sandbox , you need to go for /apps/hive/warehouse/ and normal cluster /user/hive/warehouse
Try to use it
-moz-transition: background .2s linear;
-webkit-transition: background .2s linear;
-o-transition: background .2s linear;
transition: background .2s linear;
I found the below snippet helpful. Taken from: http://jeromeblog-jerome.blogspot.com/2007/10/how-to-unlock-record-on-oracle.html
select
owner||'.'||object_name obj ,
oracle_username||' ('||s.status||')' oruser ,
os_user_name osuser ,
machine computer ,
l.process unix ,
s.sid||','||s.serial# ss ,
r.name rs ,
to_char(s.logon_time,'yyyy/mm/dd hh24:mi:ss') time
from v$locked_object l ,
dba_objects o ,
v$session s ,
v$transaction t ,
v$rollname r
where l.object_id = o.object_id
and s.sid=l.session_id
and s.taddr=t.addr
and t.xidusn=r.usn
order by osuser, ss, obj
;
Then ran:
Alter System Kill Session '<value from ss above>'
;
To kill individual sessions.
Yes, you can do almost that:
SELECT dbo.GetBusinessDays(a.opendate,a.closedate) as BusinessDays
FROM account a
WHERE...
Try initializing your variables and use them in your connection object:
$username ="root";
$password = "password";
$host = "localhost";
$table = "shop";
$conn = new mysqli("$host", "$username", "$password", "$table");
I had this problem even with plenty of internal memory and SD memory. This solution is only for apps that won't update, or have previously been installed on the phone and won't install.
It appears that in some cases there are directories left over from a previous install and the new app cannot remove or overwrite these.
The first thing to do is try uninstalling the app first and try again. In my case this worked for a couple of apps.
For the next step you need root access on your phone:
With a file manager go to /data/app-lib and find the directory (or directories) associated with the app. For example for kindle it is com.amazon.kindle. Delete these. Also go to /data/data and do the same.
Then goto play store and re-install the app. This worked for all apps in my case.
I wasn't having codec issues or dimension issues as the answers above. Instead, my issue was because my output frames were in greyscale.
I had to create a VideoWriter with the parameter isColor=False
out = cv2.VideoWriter(output_path,
cv2.VideoWriter_fourcc(*'mp4v'),
30,
(INPUT_VIDEO_WIDTH,INPUT_VIDEO_HEIGHT),
isColor=False
)
In the API Docs, it wrongly says that the flag is currently supported on Windows only. I have tested on Ubuntu 20.04, with opencv-python==4.2.0.34, and it finally writes out to file correctly.
This might work a little better this way
<embed src= "MyHome.pdf" width= "500" height= "375">
NSData *data = [strChangetoJSON dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
For example you have a NSString
with special characters in NSString
strChangetoJSON.
Then you can convert that string to JSON response using above code.
If you want to see the default browser errors being displayed, for example, those triggered by HTML attributes (showing up before any client-code JS treatment):
<input name="o" required="required" aria-required="true" type="text">
You should use the submit
event instead of the click
event. In this case a popup will be automatically displayed requesting "Please fill out this field". Even with preventDefault
:
$('form').on('submit', function(event) {
event.preventDefault();
my_form_treatment(this, event);
}); // -> this will show up a "Please fill out this field" pop-up before my_form_treatment
As someone mentioned previously, return false
would stop propagation (i.e. if there are more handlers attached to the form submission, they would not be executed), but, in this case, the action triggered by the browser will always execute first. Even with a return false
at the end.
So if you want to get rid of these default pop-ups, use the click
event on the submit button:
$('form input[type=submit]').on('click', function(event) {
event.preventDefault();
my_form_treatment(this, event);
}); // -> this will NOT show any popups related to HTML attributes
Remember, you can only add a cookie for the current domain.
If you want to add a cookie for your Google account, do
browser.get('http://google.com')
for cookie in cookies:
browser.add_cookie(cookie)
import java.util.HashMap;
import java.util.Scanner;
public class HashMapDemo {
public static void main(String[] args) {
//Create HashMap object to Store Element as Key and Value
HashMap<Character,Integer> hm= new HashMap<Character,Integer>();
//Enter Your String From Console
System.out.println("Enter an String:");
//Create Scanner Class Object From Retrive the element from console to our java application
Scanner sc = new Scanner(System.in);
//Store Data in an string format
String s1=sc.nextLine();
//find the length of an string and check that hashmap object contain the character or not by using
//containskey() if that map object contain element only one than count that value as one or if it contain more than one than increment value
for(int i=0;i<s1.length();i++){
if(!hm.containsKey(s1.charAt(i))){
hm.put(s1.charAt(i),(Integer)1);
}//if
else{
hm.put(s1.charAt(i),hm.get(s1.charAt(i))+1);
}//else
}//for
System.out.println("The Charecters are:"+hm);
}//main
}//HashMapDemo
Go to
C:\Program Files\MySQL\MySQL Server 5.2\bin
then Open MySQLInstanceConfig file
then complete the wizard.
Click finish
Solve the problem
I think this is the best way to change the port number also.
It works for me
If you need this code in several places then I'd suggest that you add a short function to keep your code simpler and easier to test.
function add_days( $days, $from_date = null ) {
if ( is_numeric( $from_date ) ) {
$new_date = $from_date;
} else {
$new_date = time();
}
// Timestamp is the number of seconds since an event in the past
// To increate the value by one day we have to add 86400 seconds to the value
// 86400 = 24h * 60m * 60s
$new_date += $days * 86400;
return $new_date;
}
Then you can use it anywhere like this:
$today = add_days( 0 );
$tomorrow = add_days( 1 );
$yesterday = add_days( -1 );
$in_36_hours = add_days( 1.5 );
$first_reminder = add_days( 10 );
$second_reminder = add_days( 5, $first_reminder );
$last_reminder = add_days( 3, $second_reminder );
Just to top this up to the new Java 8 API:
DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendPattern("MMMM dd, yyyy").toFormatter();
TemporalAccessor ta = formatter.parse("June 27, 2007");
Instant instant = LocalDate.from(ta).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
Date d = Date.from(instant);
assertThat(d.getYear(), is(107));
assertThat(d.getMonth(), is(5));
A bit more verbose but you also see that the methods of Date used are deprecated ;-) Time to move on.
try to ad the following in your CSS:
body, html{
padding:0;
margin:0;
}
Here is my script to do the process described by sje397:
#!/bin/sh
# Needed if running on Windows
FIND="/usr/bin/find"
DIFF="diff -r"
# Extract the jar (war or ear)
JAR_FILE1=$1
JAR_FILE2=$2
JAR_DIR=${PWD} # to assign to a variable
TEMP_DIR=$(mktemp -d)
echo "Extracting jars in $TEMP_DIR"
EXT_DIR1="${TEMP_DIR}/${JAR_FILE1%.*}"
EXT_DIR2="${TEMP_DIR}/${JAR_FILE2%.*}"
mkdir ${EXT_DIR1}
cd ${EXT_DIR1}
jar xf ${JAR_DIR}/${JAR_FILE1}
jad -d . -o -t2 -safe -space -b -ff -s java -r **/*.class
cd ..
mkdir ${EXT_DIR2}
cd ${EXT_DIR2}
jar xf ${JAR_DIR}/${JAR_FILE2}
jad -d . -o -t2 -safe -space -b -ff -s java -r **/*.class
cd ..
# remove class files so the diff is clean
${FIND} ${TEMP_DIR} -name '*.class' | xargs rm
# diff recursively
${DIFF} ${EXT_DIR1} ${EXT_DIR2}
I can run it on Windows using GIT for Windows. Just open a command prompt. Run bash and then execute the script from there.
If primary key is not already defined on parent table then this issue may arise. Please try to define the primary key on existing table. For eg:
ALTER TABLE table_name
ADD PRIMARY KEY (the_column_which_is_primary_key);
As Rasmus states in his article "The difference between UTF-8 and Unicode?":
If asked the question, "What is the difference between UTF-8 and Unicode?", would you confidently reply with a short and precise answer? In these days of internationalization all developers should be able to do that. I suspect many of us do not understand these concepts as well as we should. If you feel you belong to this group, you should read this ultra short introduction to character sets and encodings.
Actually, comparing UTF-8 and Unicode is like comparing apples and oranges:
UTF-8 is an encoding - Unicode is a character set
A character set is a list of characters with unique numbers (these numbers are sometimes referred to as "code points"). For example, in the Unicode character set, the number for A is 41.
An encoding on the other hand, is an algorithm that translates a list of numbers to binary so it can be stored on disk. For example UTF-8 would translate the number sequence 1, 2, 3, 4 like this:
00000001 00000010 00000011 00000100
Our data is now translated into binary and can now be saved to disk.
All together now
Say an application reads the following from the disk:
1101000 1100101 1101100 1101100 1101111
The app knows this data represent a Unicode string encoded with UTF-8 and must show this as text to the user. First step, is to convert the binary data to numbers. The app uses the UTF-8 algorithm to decode the data. In this case, the decoder returns this:
104 101 108 108 111
Since the app knows this is a Unicode string, it can assume each number represents a character. We use the Unicode character set to translate each number to a corresponding character. The resulting string is "hello".
Conclusion
So when somebody asks you "What is the difference between UTF-8 and Unicode?", you can now confidently answer short and precise:
UTF-8 (Unicode Transformation Format) and Unicode cannot be compared. UTF-8 is an encoding used to translate numbers into binary data. Unicode is a character set used to translate characters into numbers.
This command line tool is the business! https://wkhtmltopdf.org/
It uses webkit rendering engine(used in safari and KDE), I tested it on some complex sites and it was by far better than any other tool.
So I take it you want 2 options default selected, and then get the value of it? If so:
<div class="divright">
<select id="drp_Books_Ill_Illustrations" class="leaderMultiSelctdropdown Books_Illustrations" name="drp_Books_Ill_Illustrations" multiple="">
<option value=" ">No illustrations</option>
<option value="a" selected>Illustrations</option>
<option value="b">Maps</option>
<option value="c" selected>selectedPortraits</option>
</select>
</div>
And to get value:
alert($(".leaderMultiSelctdropdown").val());
To set the value:
$(".leaderMultiSelctdropdown").val(["a", "c"]);
You can also use an array to set the values:
var selectedValues = new Array();
selectedValues[0] = "a";
selectedValues[1] = "c";
$(".Books_Illustrations").val(selectedValues);
I found the answer is very very simple...
// It is in java, but it should be same in pyspark
Column col = ds.col("colName"); //the column object
String theNameOftheCol = col.toString();
The variable "theNameOftheCol" is "colName"
Here's a very simple way to do it;
int main()
{
int s=7,l=1;
vector <bool> v;
v.clear();
while (l <= 4)
{
v.push_back(s%2);
s /= 2;
l++;
}
for (l=(v.size()-1); l >= 0; l--)
{
cout<<v[l]<<" ";
}
return 0;
}
You can always use something like
"string".sub!(/.{X}$/,'')
Where X
is the number of characters to remove.
Or with assigning/using the result:
myvar = "string"[0..-X]
where X
is the number of characters plus one to remove.
public static string Serialize(object dataToSerialize)
{
if(dataToSerialize==null) return null;
using (StringWriter stringwriter = new System.IO.StringWriter())
{
var serializer = new XmlSerializer(dataToSerialize.GetType());
serializer.Serialize(stringwriter, dataToSerialize);
return stringwriter.ToString();
}
}
public static T Deserialize<T>(string xmlText)
{
if(String.IsNullOrWhiteSpace(xmlText)) return default(T);
using (StringReader stringReader = new System.IO.StringReader(xmlText))
{
var serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(stringReader);
}
}
substr(PHONE_NUMBERS, length(PHONE_NUMBERS) - 3, 4)
If you are not root user then, use following commands:
There are two ways to do it -
1.
sudo vi path_to_file/file_name
Press Esc and then type below respectively
:wq //save and exit :q! //exit without saving
When using nano: after you finish editing press ctrl+x then it will ask save Y/N.
If you want to save press Y, if not press N. And press enter to exit the editor.
How to convert string to lowercase in Python?
Is there any way to convert an entire user inputted string from uppercase, or even part uppercase to lowercase?
E.g. Kilometers --> kilometers
The canonical Pythonic way of doing this is
>>> 'Kilometers'.lower()
'kilometers'
However, if the purpose is to do case insensitive matching, you should use case-folding:
>>> 'Kilometers'.casefold()
'kilometers'
Here's why:
>>> "Maße".casefold()
'masse'
>>> "Maße".lower()
'maße'
>>> "MASSE" == "Maße"
False
>>> "MASSE".lower() == "Maße".lower()
False
>>> "MASSE".casefold() == "Maße".casefold()
True
This is a str method in Python 3, but in Python 2, you'll want to look at the PyICU or py2casefold - several answers address this here.
Python 3 handles plain string literals as unicode:
>>> string = '????????'
>>> string
'????????'
>>> string.lower()
'????????'
In Python 2, the below, pasted into a shell, encodes the literal as a string of bytes, using utf-8
.
And lower
doesn't map any changes that bytes would be aware of, so we get the same string.
>>> string = '????????'
>>> string
'\xd0\x9a\xd0\xb8\xd0\xbb\xd0\xbe\xd0\xbc\xd0\xb5\xd1\x82\xd1\x80'
>>> string.lower()
'\xd0\x9a\xd0\xb8\xd0\xbb\xd0\xbe\xd0\xbc\xd0\xb5\xd1\x82\xd1\x80'
>>> print string.lower()
????????
In scripts, Python will object to non-ascii (as of Python 2.5, and warning in Python 2.4) bytes being in a string with no encoding given, since the intended coding would be ambiguous. For more on that, see the Unicode how-to in the docs and PEP 263
str
literalsSo we need a unicode
string to handle this conversion, accomplished easily with a unicode string literal, which disambiguates with a u
prefix (and note the u
prefix also works in Python 3):
>>> unicode_literal = u'????????'
>>> print(unicode_literal.lower())
????????
Note that the bytes are completely different from the str
bytes - the escape character is '\u'
followed by the 2-byte width, or 16 bit representation of these unicode
letters:
>>> unicode_literal
u'\u041a\u0438\u043b\u043e\u043c\u0435\u0442\u0440'
>>> unicode_literal.lower()
u'\u043a\u0438\u043b\u043e\u043c\u0435\u0442\u0440'
Now if we only have it in the form of a str
, we need to convert it to unicode
. Python's Unicode type is a universal encoding format that has many advantages relative to most other encodings. We can either use the unicode
constructor or str.decode
method with the codec to convert the str
to unicode
:
>>> unicode_from_string = unicode(string, 'utf-8') # "encoding" unicode from string
>>> print(unicode_from_string.lower())
????????
>>> string_to_unicode = string.decode('utf-8')
>>> print(string_to_unicode.lower())
????????
>>> unicode_from_string == string_to_unicode == unicode_literal
True
Both methods convert to the unicode type - and same as the unicode_literal.
It is recommended that you always work with text in Unicode.
Software should only work with Unicode strings internally, converting to a particular encoding on output.
However, to get the lowercase back in type str
, encode the python string to utf-8
again:
>>> print string
????????
>>> string
'\xd0\x9a\xd0\xb8\xd0\xbb\xd0\xbe\xd0\xbc\xd0\xb5\xd1\x82\xd1\x80'
>>> string.decode('utf-8')
u'\u041a\u0438\u043b\u043e\u043c\u0435\u0442\u0440'
>>> string.decode('utf-8').lower()
u'\u043a\u0438\u043b\u043e\u043c\u0435\u0442\u0440'
>>> string.decode('utf-8').lower().encode('utf-8')
'\xd0\xba\xd0\xb8\xd0\xbb\xd0\xbe\xd0\xbc\xd0\xb5\xd1\x82\xd1\x80'
>>> print string.decode('utf-8').lower().encode('utf-8')
????????
So in Python 2, Unicode can encode into Python strings, and Python strings can decode into the Unicode type.
I just cleaned up a large set of obsolete local/remote branches today.
Below is how I did it:
1. list all branch names to a text file:
git branch -a >> BranchNames.txt
2. append the branches I want to delete to command "git branch -D -r":
git branch -D -r origin/dirA/branch01 origin/dirB/branch02 origin/dirC/branch03 (... append whatever branch names)
3. execute the cmd
And this one works so much faster and reliable than "git push origin --delete".
This may not be the most smart way as listed in other answers, but this one is pretty straight forward, and easy to use.
Modern ES6 way (async/await)
const toBase64 = file => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
async function Main() {
const file = document.querySelector('#myfile').files[0];
console.log(await toBase64(file));
}
Main();
UPD:
If you want to catch errors
async function Main() {
const file = document.querySelector('#myfile').files[0];
const result = await toBase64(file).catch(e => Error(e));
if(result instanceof Error) {
console.log('Error: ', result.message);
return;
}
//...
}
Maybe this is helpful, too.
for (var i = countries.length - 1; i--;) {
if (countries[i]['id'] === 'AF' || countries[i]['name'] === 'Algeria'{
countries.splice(i, 1);
}
}
Supported by SQL Server 2005 and later versions
SELECT CONVERT(VARCHAR(10), GETDATE(), 101)
+ ' ' + CONVERT(VARCHAR(8), GETDATE(), 108)
* See Microsoft's documentation to understand what the 101
and 108
style codes above mean.
Supported by SQL Server 2012 and later versions
SELECT FORMAT(GETDATE() , 'MM/dd/yyyy HH:mm:ss')
Result
Both of the above methods will return:
10/16/2013 17:00:20
Map<String, String> map = new HashMap<String, String>();
map.put("key1", "value1");
map.put("key2", "value2");
Object[][] twoDarray = new Object[map.size()][2];
Object[] keys = map.keySet().toArray();
Object[] values = map.values().toArray();
for (int row = 0; row < twoDarray.length; row++) {
twoDarray[row][0] = keys[row];
twoDarray[row][1] = values[row];
}
// Print out the new 2D array
for (int i = 0; i < twoDarray.length; i++) {
for (int j = 0; j < twoDarray[i].length; j++) {
System.out.println(twoDarray[i][j]);
}
}
I had to downgrade OpenSSL in this way:
brew uninstall --ignore-dependencies openssl
brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/30fd2b68feb458656c2da2b91e577960b11c42f4/Formula/openssl.rb
It was the only solution that worked for me.
just export the table with data .. then copy its sql like
CREATE TABLE IF NOT EXISTS `employees` (
`emp_badgenumber` int(20) NOT NULL AUTO_INCREMENT,
`emp_fullname` varchar(100) NOT NULL,
`emp_father_name` varchar(30) NOT NULL,
`emp_mobile` varchar(20) DEFAULT NULL,
`emp_cnic` varchar(20) DEFAULT NULL,
`emp_gender` varchar(10) NOT NULL,
`emp_is_deleted` tinyint(4) DEFAULT '0',
`emp_registration_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`emp_overtime_allowed` tinyint(4) DEFAULT '1',
PRIMARY KEY (`emp_badgenumber`),
UNIQUE KEY `bagdenumber` (`emp_badgenumber`),
KEY `emp_badgenumber` (`emp_badgenumber`),
KEY `emp_badgenumber_2` (`emp_badgenumber`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=111121326 ;
now change auto increment value and execute sql.
You can check in windows services if tomcat is installed it will be listed in windows services.
To check the windows service list of services installed on windows machine use
WINDOWS KEY + R and type services.msc
There you can find all the services related with Jasperreport server like Tomcat and MySQL with name starting Jasperreport server Tomcat and MySQL only if these services are installed and its need to be started by selecting the option.Then you can access it through browser using this link :-
http://localhost:8080
default port for tomcat is 8080.
This seems a very old question, but I am providing an answer, so that it might help others. You can specify the variables in the second screen in the form section, as shown below or in the RAW format by appending the variables as shown in the second image.
If your variable and variable values are valid, you should see a successful response in the response section.
as others have said new line char will give you a new line in a text file in windows. try the following:
using System;
using System.IO;
static class Program
{
static void Main()
{
WriteToFile
(
@"C:\test.txt",
"fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@",
"@"
);
/*
output in test.txt in windows =
fkdfdsfdflkdkfk@
dfsdfjk72388389@
kdkfkdfkkl@
jkdjkfjd@
jjjk@
*/
}
public static void WriteToFile(string filename, string text, string newLineDelim)
{
bool equal = Environment.NewLine == "\r\n";
//Environment.NewLine == \r\n = True
Console.WriteLine("Environment.NewLine == \\r\\n = {0}", equal);
//replace newLineDelim with newLineDelim + a new line
//trim to get rid of any new lines chars at the end of the file
string filetext = text.Replace(newLineDelim, newLineDelim + Environment.NewLine).Trim();
using (StreamWriter sw = new StreamWriter(File.OpenWrite(filename)))
{
sw.Write(filetext);
}
}
}
I tried to add the following options in the /etc/docker/daemon.json. (I used CentOS7)
"add-registry": ["192.168.100.100:5001"],
"block-registry": ["docker.io"],
after that, restarted docker daemon. And it's working without docker.io. I hope this someone will be helpful.
document.getElementById("tblBlah").rows[i].columns[j].innerHTML;
Should be:
document.getElementById("tblBlah").rows[i].cells[j].innerHTML;
But I get the distinct impression that the row/cell you need is the one clicked by the user. If so, the simplest way to achieve this would be attaching an event to the cells in your table:
function alertInnerHTML(e)
{
e = e || window.event;//IE
alert(this.innerHTML);
}
var theTbl = document.getElementById('tblBlah');
for(var i=0;i<theTbl.length;i++)
{
for(var j=0;j<theTbl.rows[i].cells.length;j++)
{
theTbl.rows[i].cells[j].onclick = alertInnerHTML;
}
}
That makes all table cells clickable, and alert it's innerHTML. The event object will be passed to the alertInnerHTML
function, in which the this
object will be a reference to the cell that was clicked. The event object offers you tons of neat tricks on how you want the click event to behave if, say, there's a link in the cell that was clicked, but I suggest checking the MDN and MSDN (for the window.event object)
200 (cache) means Firefox is simply using the locally cached version. This is the fastest because no request to the Web server is made.
304 means Firefox is sending a "If-Modified-Since" conditional request to the Web server. If the file has not been updated since the date sent by the browser, the Web server returns a 304 response which essentially tells Firefox to use its cached version. It is not as fast as 200 (cache) because the request is still sent to the Web server, but the server doesn't have to send the contents of the file.
To your last question, I don't know why the two JavaScript files in the same directory are returning different results.
After extensive googling I found a working solution, which consists of two steps.
The first step is to set system wide environment variable ASPNET_ENV to Production and Restart the Windows Server. After this, all web apps are getting the value 'Production' as EnvironmentName.
The second step (to enable value 'Staging' for staging web) was rather more difficult to get to work correctly, but here it is:
Now the Staging web should have the EnvironmentName set to 'Staging'.
Update: In Windows 7+ there is a command that can set environment variables from CMD prompt also for a specified user. This outputs help plus samples:
>setx /?
Here is a jQuery handler that can be used to stop enter submits, and also stop backspace key -> back. The (keyCode: selectorString) pairs in the "keyStop" object are used to match nodes that shouldn't fire their default action.
Remember that the web should be an accessible place, and this is breaking keyboard users' expectations. That said, in my case the web application I am working on doesn't like the back button anyway, so disabling its key shortcut is OK. The "should enter -> submit" discussion is important, but not related to the actual question asked.
Here is the code, up to you to think about accessibility and why you would actually want to do this!
$(function(){
var keyStop = {
8: ":not(input:text, textarea, input:file, input:password)", // stop backspace = back
13: "input:text, input:password", // stop enter = submit
end: null
};
$(document).bind("keydown", function(event){
var selector = keyStop[event.which];
if(selector !== undefined && $(event.target).is(selector)) {
event.preventDefault(); //stop event
}
return true;
});
});
you can use this command for particular branch clone :
git clone <url of repo> -b <branch name to be cloned>
Eg: git clone https://www.github.com/Repo/FirstRepo -b master
You can change style directly for scene using .root
class:
.root {
-fx-background-image: url("https://www.google.com/images/srpr/logo3w.png");
}
Add this to CSS and load it as "Uluk Biy" described in his answer.
If you run the browser in the server and test your url of the project with the local ip you have received all errors of that project without a generally error page(for example 500 error page).
Map is a part of the enumerable module. Very similar to "collect" For Example:
Class Car
attr_accessor :name, :model, :year
Def initialize (make, model, year)
@make, @model, @year = make, model, year
end
end
list = []
list << Car.new("Honda", "Accord", 2016)
list << Car.new("Toyota", "Camry", 2015)
list << Car.new("Nissan", "Altima", 2014)
p list.map {|p| p.model}
Map provides values iterating through an array that are returned by the block parameters.
You may use this:
Intent intent = new Intent(getApplicationContext(), ClassName.class);
If you can't use rgba
due to browser support, and you don't want to include a semi-transparent white PNG, you will have to create two positioned elements. One for the white box, with opacity, and one for the overlaid text, solid.
body { background: red; }_x000D_
_x000D_
.box { position: relative; z-index: 1; }_x000D_
.box .back {_x000D_
position: absolute; z-index: 1;_x000D_
top: 0; left: 0; width: 100%; height: 100%;_x000D_
background: white; opacity: 0.75;_x000D_
}_x000D_
.box .text { position: relative; z-index: 2; }_x000D_
_x000D_
body.browser-ie8 .box .back { filter: alpha(opacity=75); }
_x000D_
<!--[if lt IE 9]><body class="browser-ie8"><![endif]-->_x000D_
<!--[if gte IE 9]><!--><body><!--<![endif]-->_x000D_
<div class="box">_x000D_
<div class="back"></div>_x000D_
<div class="text">_x000D_
Lorem ipsum dolor sit amet blah blah boogley woogley oo._x000D_
</div>_x000D_
</div>_x000D_
</body>
_x000D_
You can try something like this. Special Characters range for alphabets starts from 192, so you can avoid such characters in the result.
String name = "A função";
StringBuilder result = new StringBuilder();
for(char val : name.toCharArray()) {
if(val < 192) result.append(val);
}
System.out.println("Result "+result.toString());
Restarting Visual Studio 2019 - that did it.
Shouldn't that be
validates_length_of :title, :in => 6..255, :on => :create
so it only works during create?
If you need the difference in days accounting up to the second:
SELECT TIMESTAMPDIFF(SECOND,'2010-09-21 21:40:36','2010-10-08 18:23:13')/86400 AS diff
It will return
diff
16.8629
You need to set the password for root@localhost
to be blank. There are two ways:
The MySQL SET PASSWORD
command:
SET PASSWORD FOR root@localhost=PASSWORD('');
Using the command-line mysqladmin
tool:
mysqladmin -u root -pType_in_your_current_password_here password ''
If you want to get any element that has part of a URL in their href attribute you could use:
$( 'a[href*="google.com"]' );
This will select all elements with a href that contains google.com, for example:
As stated by @BalusC in the comments below, it will also match elements that have google.com
at any position in the href, like blahgoogle.com
.
For single css property
ng-style="1==1 && {'color':'red'}"
For multiple css properties below can be referred
ng-style="1==1 && {'color':'red','font-style': 'italic'}"
Replace 1==1 with your condition expression
So the issue here actually has nothing to do with Swift but just how status bar appearance is handled as of iOS 7.
By Default, view controllers individually control the appearance of the status bar when they are on the screen. If you want to use this method of controlling the status bar, you can override the following methods for whatever view controllers you'd like to modify the appearance for:
prefersStatusBarHidden
,
preferredStatusBarStyle
,
preferredStatusBarAnimation
,
In your case, you would just implement prefersStatusBarHidden
and return true
.
The other way would be to control the status bar appearance at the application level. This seems to be what you're actually trying to do (by setting application.statusBarHidden
).
In order to make this work, you need to open up your app's Info.plist
file and add the key UIViewControllerBasedStatusBarAppearance
, and give it a value of NO
.
In my version of Git [1], every Git submodule has a name
and a path
. They don't necessarily have to be the same [2]. Getting both in a reliable way, without checking out the submodules first (git update --init
), is a tricky bit of shell wizardry.
names
I didn't find a way how to achieve this using git config
or any other git
command. Therefore we are back to regex on .gitmodules
(super ugly). But it seems to be somewhat safe since git
limits the possible code space allowed for submodule names
. In addition, since you probably want to use this list for further shell processing, the solution below separate entries with NULL
-bytes (\0
).
$ sed -nre \
's/^\[submodule \"(.*)\"]$/\1\x0/p' \
"$(git rev-parse --show-toplevel)/.gitmodules" \
| tr -d '\n' \
| xargs -0 -n1 printf "%b\0"
And in your script:
#!/usr/bin/env bash
while IFS= read -rd '' submodule_name; do
echo submodule name: "${submodule_name}"
done < <(
sed -nre \
's/^\[submodule \"(.*)\"]$/\1\x0/p' \
"$(git rev-parse --show-toplevel)/.gitmodules" \
| tr -d '\n' \
| xargs -0 -n1 printf "%b\0"
)
Note: read -rd ''
requires bash
and won't work with sh
.
paths
In my approach I try not to process the output from git config --get-regexp
with awk
, tr
, sed
, ... but instead pass it a zero byte separated back to git config --get
. This is to avoid problems with newlines, spaces and other special characters (e.g. Unicode) in the submodule paths
. In addition, since you probably want to use this list for further shell processing, the solution below separate entries with NULL
-bytes (\0
).
$ git config --null --file .gitmodules --name-only --get-regexp '\.path$' \
| xargs -0 -n1 git config --null --file .gitmodules --get
For example, in a Bash script you could then:
#!/usr/bin/env bash
while IFS= read -rd '' submodule_path; do
echo submodule path: "${submodule_path}"
done < <(
git config --null --file .gitmodules --name-only --get-regexp '\.path$' \
| xargs -0 -n1 git config --null --file .gitmodules --get
)
Note: read -rd ''
requires bash
and won't work with sh
.
$ git --version
git version 2.22.0
name
and path
Set up test repository:
$ git init test-name-path
$ cd test-name-path/
$ git checkout -b master
$ git commit --allow-empty -m 'test'
$ git submodule add ./ submodule-name
Cloning into '/tmp/test-name-path/submodule-name'...
done.
$ ls
submodule-name
$ cat .gitmodules
[submodule "submodule-name"]
path = submodule-name
url = ./
Move submodule to make name
and path
diverge:
$ git mv submodule-name/ submodule-path
$ ls
submodule-path
$ cat .gitmodules
[submodule "submodule-name"]
path = submodule-path
url = ./
$ git config --file .gitmodules --get-regexp '\.path$'
submodule.submodule-name.path submodule-path
Set up test repository:
$ git init test
$ cd test/
$ git checkout -b master
$ git commit --allow-empty -m 'test'
$
$ git submodule add ./ simplename
Cloning into '/tmp/test/simplename'...
done.
$
$ git submodule add ./ 'name with spaces'
Cloning into '/tmp/test/name with spaces'...
done.
$
$ git submodule add ./ 'future-name-with-newlines'
Cloning into '/tmp/test/future-name-with-newlines'...
done.
$ git mv future-name-with-newlines/ 'name
> with
> newlines'
$
$ git submodule add ./ 'name-with-unicode-'
Cloning into '/tmp/test/name-with-unicode-'...
done.
$
$ git submodule add ./ sub/folder/submodule
Cloning into '/tmp/test/sub/folder/submodule'...
done.
$
$ git submodule add ./ name.with.dots
Cloning into '/tmp/test/name.with.dots'...
done.
$
$ git submodule add ./ 'name"with"double"quotes'
Cloning into '/tmp/test/name"with"double"quotes'...
done.
$
$ git submodule add ./ "name'with'single'quotes"
Cloning into '/tmp/test/name'with'single'quotes''...
done.
$ git submodule add ./ 'name]with[brackets'
Cloning into '/tmp/test/name]with[brackets'...
done.
$ git submodule add ./ 'name-with-.path'
Cloning into '/tmp/test/name-with-.path'...
done.
.gitmodules
:
[submodule "simplename"]
path = simplename
url = ./
[submodule "name with spaces"]
path = name with spaces
url = ./
[submodule "future-name-with-newlines"]
path = name\nwith\nnewlines
url = ./
[submodule "name-with-unicode-"]
path = name-with-unicode-
url = ./
[submodule "sub/folder/submodule"]
path = sub/folder/submodule
url = ./
[submodule "name.with.dots"]
path = name.with.dots
url = ./
[submodule "name\"with\"double\"quotes"]
path = name\"with\"double\"quotes
url = ./
[submodule "name'with'single'quotes"]
path = name'with'single'quotes
url = ./
[submodule "name]with[brackets"]
path = name]with[brackets
url = ./
[submodule "name-with-.path"]
path = name-with-.path
url = ./
names
$ sed -nre \
's/^\[submodule \"(.*)\"]$/\1\x0/p' \
"$(git rev-parse --show-toplevel)/.gitmodules" \
| tr -d '\n' \
| xargs -0 -n1 printf "%b\0" \
| xargs -0 -n1 echo submodule name:
submodule name: simplename
submodule name: name with spaces
submodule name: future-name-with-newlines
submodule name: name-with-unicode-
submodule name: sub/folder/submodule
submodule name: name.with.dots
submodule name: name"with"double"quotes
submodule name: name'with'single'quotes
submodule name: name]with[brackets
submodule name: name-with-.path
paths
$ git config --null --file .gitmodules --name-only --get-regexp '\.path$' \
| xargs -0 -n1 git config --null --file .gitmodules --get \
| xargs -0 -n1 echo submodule path:
submodule path: simplename
submodule path: name with spaces
submodule path: name
with
newlines
submodule path: name-with-unicode-
submodule path: sub/folder/submodule
submodule path: name.with.dots
submodule path: name"with"double"quotes
submodule path: name'with'single'quotes
submodule path: name]with[brackets
submodule path: name-with-.path
ioutil.ReadDir
is a good find, but if you click and look at the source you see that it calls the method Readdir of os.File. If you are okay with the directory order and don't need the list sorted, then this Readdir method is all you need.
substring()
Methodpublic static String capitalize(String str) {
if(str== null || str.isEmpty()) {
return str;
}
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
Now just call the capitalize()
method to convert the first letter of a string to uppercase:
System.out.println(capitalize("stackoverflow")); // Stackoverflow
System.out.println(capitalize("heLLo")); // HeLLo
System.out.println(capitalize(null)); // null
The StringUtils
class from Commons Lang provides the capitalize()
method that can also be used for this purpose:
System.out.println(StringUtils.capitalize("apache commons")); // Apache commons
System.out.println(StringUtils.capitalize("heLLO")); // HeLLO
System.out.println(StringUtils.uncapitalize(null)); // null
Add the following dependency to your pom.xml
file (for Maven only):
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
Here is an article that explains these two approaches in detail.
In my case i was returning string value from my api eg: "35" and in my HTML i was using
<mat-select placeholder="State*" formControlName="states" [(ngModel)]="selectedState" (ngModelChange)="getDistricts()">
<mat-option *ngFor="let state of formInputs.states" [value]="state.stateId">
{{ state.stateName }}
</mat-option>
</mat-select>
Like others mentioned in the comment value will only accept integer values i guess. So what I did is I converted my string value to integer in my component class like below
var x = user.state;
var y: number = +x;
and then assigned it like
this.EditProfileForm.get('states').setValue(y);
Now the correct values is getting setting by default.
How about alert(JSON.stringify(object))
with a modern browser?
In case of TypeError: Converting circular structure to JSON
, here are more options: How to serialize DOM node to JSON even if there are circular references?
The documentation: JSON.stringify()
provides info on formatting or prettifying the output.
delete react node_modules
rm -r node_modules
yarn or npm install
yarn start or npm start
if error occurs use this method again
Depends what you want to do.
If what you want is to retrieve the bytes that are remaining (between position and limit), then what you have will work. You could also just do:
ByteBuffer bb =..
byte[] b = new byte[bb.remaining()];
bb.get(b);
which is equivalent as per the ByteBuffer javadocs.
With jQuery UI just do this!
$( "#draggable" ).draggable({
start: function() {
},
drag: function() {
},
stop: function() {
}
});
The same way Steven Schmatz did it but using Swift 3.0 :
//max Length
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool
{
let maxLength = 4
let currentString: NSString = textField.text! as NSString
let newString: NSString = currentString.replacingCharacters(in: range, with: string) as NSString
return newString.length <= maxLength
}
Open the SQL Server Configuration Manager.... 2.Check wheather TCP and UDP are running or not.... 3.If not running , Please enable them and also check the SQL Server Browser is running or not.If not running turn it on.....
Next you have to check which ports TCP and UDP is using. You have to open those ports from your windows firewall.....
5.Click here to see the steps to open a specific port in windows firewall....
Now SQL Server is ready to access over LAN.......
If you wan to access it remotely (over internet) , you have to do another job that is 'Port Forwarding'. You have open the ports TCP and UDP is using in SQL Server on your router. Now the configuration of routers are different. If you give me the details of your router (i. e name of the company and version ) , I can show you the steps how to forward a specific port.
As noted in the comments, there are some things to try: gc.collect
(@EdChum) may clear stuff, for example. At least from my experience, these things sometimes work and often don't.
There is one thing that always works, however, because it is done at the OS, not language, level.
Suppose you have a function that creates an intermediate huge DataFrame, and returns a smaller result (which might also be a DataFrame):
def huge_intermediate_calc(something):
...
huge_df = pd.DataFrame(...)
...
return some_aggregate
Then if you do something like
import multiprocessing
result = multiprocessing.Pool(1).map(huge_intermediate_calc, [something_])[0]
Then the function is executed at a different process. When that process completes, the OS retakes all the resources it used. There's really nothing Python, pandas, the garbage collector, could do to stop that.
You can use a converter or create new property in your ViewModel like that:
public bool CanDoIt
{
get
{
return !string.IsNullOrEmpty(SomeField);
}
}
and use it:
<DataTrigger Binding="{Binding SomeField}" Value="{Binding CanDoIt}">
You can use strtotime
, which is great in this kind of situations :
$timestamp = strtotime('-1 month');
var_dump(date('Y-m', $timestamp));
Will get you :
string '2009-11' (length=7)
res_list = [x[0] for x in rows]
c.f. http://docs.python.org/3/tutorial/datastructures.html#list-comprehensions
For a discussion on why to prefer comprehensions over higher-order functions such as map
, go to http://www.artima.com/weblogs/viewpost.jsp?thread=98196.
An update to @sourcesimian 's and @kunal-b's answer which dynamically sets the username and password if configured in the system properties.
The following sets the username and password if provided or just adds the host and port if no username and password is set.
task setHttpProxyFromEnv {
def map = ['HTTP_PROXY': 'http', 'HTTPS_PROXY': 'https']
for (e in System.getenv()) {
def key = e.key.toUpperCase()
if (key in map) {
def base = map[key]
//Get proxyHost,port, username, and password from http system properties
// in the format http://username:password@proxyhost:proxyport
def (val1,val2) = e.value.tokenize( '@' )
def (val3,val4) = val1.tokenize( '//' )
def(userName, password) = val4.tokenize(':')
def url = e.value.toURL()
//println " - systemProp.${base}.proxy=${url.host}:${url.port}"
System.setProperty("${base}.proxyHost", url.host.toString())
System.setProperty("${base}.proxyPort", url.port.toString())
System.setProperty("${base}.proxyUser", userName.toString())
System.setProperty("${base}.proxyPassword", password.toString())
}
}
}
%j
works for only Node.js. %j
converts a value to a JSON string and inserts it.
console.log('%j new messages for', 7, 'john')
// 7 new messages for john
You're trying to open each file twice! First you do:
infile=open('110331_HS1A_1_rtTA.result','r')
and then you pass infile
(which is a file object) to the open
function again:
with open (infile, mode='r', buffering=-1)
open
is of course expecting its first argument to be a file name, not an opened file!
Open the file once only and you should be fine.
public static void main(String[] args) {
DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
.withZone(ZoneId.systemDefault());
System.out.println(DATE_TIME_FORMATTER.format(new Date().toInstant()));
}
array_values does the job :
$myArray = array_values($myArray);
Also some other php function do not preserve the keys, i.e. reset the index.
In case you want to store it to a file, you solve it using bbox_inches="tight"
argument:
plt.savefig('myfile.png', bbox_inches = "tight")
Do you mean something like this?
In [39]: df2.pivot_table(values='X', rows='Y', cols='Z',
aggfunc=lambda x: len(x.unique()))
Out[39]:
Z Z1 Z2 Z3
Y
Y1 1 1 NaN
Y2 NaN NaN 1
Note that using len
assumes you don't have NA
s in your DataFrame. You can do x.value_counts().count()
or len(x.dropna().unique())
otherwise.
cout
is in std namespace, you shall use std::cout
in your code.
And you shall not add using namespace std;
in your header file, it's bad to mix your code with std namespace, especially don't add it in header file.
If you are really interested in a good, in-depth explanation of move semantics, I'd highly recommend reading the original paper on them, "A Proposal to Add Move Semantics Support to the C++ Language."
It's very accessible and easy to read and it makes an excellent case for the benefits that they offer. There are other more recent and up to date papers about move semantics available on the WG21 website, but this one is probably the most straightforward since it approaches things from a top-level view and doesn't get very much into the gritty language details.
<div style="border: 2px solid #D5CC5A; overflow: hidden; margin: 15px auto; max-width: 575px;">
I use the following technique. It makes it easy to keep the column names in sync with the content:
var cursor = db.getCollection('Employees.Details').find({})
var header = []
var rows = []
var firstRow = true
cursor.forEach((doc) =>
{
var cells = []
if (firstRow) header.push("employee_number")
cells.push(doc.EmpNum.valueOf())
if (firstRow) header.push("name")
cells.push(doc.FullName.valueOf())
if (firstRow) header.push("dob")
cells.push(doc.DateOfBirth.valueOf())
row = cells.join(',')
rows.push(row)
firstRow = false
})
print(header.join(','))
print(rows.join('\n'))
https://isocpp.org/wiki/faq/const-correctness#const-member-fns
What is a "
const
member function"?A member function that inspects (rather than mutates) its object.
A
const
member function is indicated by aconst
suffix just after the member function’s parameter list. Member functions with aconst
suffix are called “const member functions” or “inspectors.” Member functions without aconst
suffix are called “non-const member functions” or “mutators.”class Fred { public: void inspect() const; // This member promises NOT to change *this void mutate(); // This member function might change *this }; void userCode(Fred& changeable, const Fred& unchangeable) { changeable.inspect(); // Okay: doesn't change a changeable object changeable.mutate(); // Okay: changes a changeable object unchangeable.inspect(); // Okay: doesn't change an unchangeable object unchangeable.mutate(); // ERROR: attempt to change unchangeable object }
The attempt to call
unchangeable.mutate()
is an error caught at compile time. There is no runtime space or speed penalty forconst
, and you don’t need to write test-cases to check it at runtime.The trailing
const
oninspect()
member function should be used to mean the method won’t change the object’s abstract (client-visible) state. That is slightly different from saying the method won’t change the “raw bits” of the object’s struct. C++ compilers aren’t allowed to take the “bitwise” interpretation unless they can solve the aliasing problem, which normally can’t be solved (i.e., a non-const alias could exist which could modify the state of the object). Another (important) insight from this aliasing issue: pointing at an object with a pointer-to-const doesn’t guarantee that the object won’t change; it merely promises that the object won’t change via that pointer.
from pandas import DataFrame
import pandas as pd
d = {'one':[2,3,1,4,5],
'two':[5,4,3,2,1],
'letter':['a','a','b','b','c']}
df = DataFrame(d)
test = df.sort_values(['one'], ascending=False)
test
Now you can configure Visual Studio Code (version 0.10.2, check for older versions) to use existing git installation.
Just add the path to the git executable in your Visual Studio Code settings (File -> Preferences -> Settings) like this:
{
// Is git enabled
"git.enabled": true,
// Path to the git executable
"git.path": "C:\\path\\to\\git.exe"
// other settings
}
Use ToString("X4")
.
The 4 means that the string will be 4 digits long.
Reference: The Hexadecimal ("X") Format Specifier on MSDN.
If you have only aar
or jar
file itself, or just don't want to use plugins - I've created a simple shell script. You can achieve the same with it - publishing your artifacts to Github and use it as public Maven repo.
IN HTML 5 action=""
IS NOT SUPPORTED SO DON'T DO THIS. BAD PRACTICE.
If instead you completely negate action altogether it will submit to the same page by default, I believe this is the best practice:
<form>This will submit to the current page</form>
If you are sumbitting the form using php you may want to consider the following. read more about it here.
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Alternatively you could use #
bear in mind though that this will act like an anchor and scroll to the top of the page.
<form action="#">
Yes, use the jQuery contains
selector.
for me , in sql server 2016, I do it like this
*To rename column Column1 to column2
EXEC sp_rename 'dbo.T_Table1.Column1', 'Column2', 'COLUMN'
*To modify column Type from string to int:( Please be sure that data are in the correct format)
ALTER TABLE dbo.T_Table1 ALTER COLUMN Column2 int;
Try this:
static double Evaluate(string expression) {
var loDataTable = new DataTable();
var loDataColumn = new DataColumn("Eval", typeof (double), expression);
loDataTable.Columns.Add(loDataColumn);
loDataTable.Rows.Add(0);
return (double) (loDataTable.Rows[0]["Eval"]);
}
In package specs you can do all you mentioned but not sure about INDEX BY BINARY_INTEGER;
In package body:
initialize the table in declarations:
exch_rt exch_tbl := exch_tbl();
in order to add record to the local collection, in begin - end block you can do:
exch_rt.extend;
one_row.exch_rt_usd := 2;
one_row.exch_rt_eur := 1;
one_row.currency_cd := 'dollar';
exch_rt(1) := one_row; -- 1 - number of row in the table - you can put a variable which will be incremented inside a loop
in order to get data from this table , inside package body you can use:
select exch_rt_usd, exch_rt_eur, currency_cd from table(exch_rt)
enjoy!
P.S. sorry for a late answer :D
Use the Apache XMLSerializer
here's an example: http://www.informit.com/articles/article.asp?p=31349&seqNum=3&rl=1
you can check this as well
Try this command for Version <= Marshmallow,
adb devices
List of devices attached 38ccdc87 device
adb tcpip 5555
restarting in TCP mode port: 5555
adb shell ip addr show wlan0
24: wlan0: mtu 1500 qdisc mq state UP qlen 1000 link/ether ac:c1:ee:6b:22:f1 brd ff:ff:ff:ff:ff:ff inet 192.168.0.18/24 brd 192.168.0.255 scope global wlan0 valid_lft forever preferred_lft forever inet6 fd01::1d45:6b7a:a3b:5f4d/64 scope global temporary dynamic valid_lft 287sec preferred_lft 287sec inet6 fd01::aec1:eeff:fe6b:22f1/64 scope global dynamic valid_lft 287sec preferred_lft 287sec inet6 fe80::aec1:eeff:fe6b:22f1/64 scope link valid_lft forever preferred_lft forever
To connect to your device run this
adb connect 192.168.0.18
connected to 192.168.0.18:5555
Make sure you have adb inside this location android-sdk\platform-tools
Try this using uniqid and hexdec,
echo hexdec(uniqid());
I think there could be a more consolidated effort in an answer to better explain the relationship between Python's datetime module, numpy's datetime64/timedelta64 and pandas' Timestamp/Timedelta objects.
The datetime standard library has four main objects
>>> import datetime
>>> datetime.time(hour=4, minute=3, second=10, microsecond=7199)
datetime.time(4, 3, 10, 7199)
>>> datetime.date(year=2017, month=10, day=24)
datetime.date(2017, 10, 24)
>>> datetime.datetime(year=2017, month=10, day=24, hour=4, minute=3, second=10, microsecond=7199)
datetime.datetime(2017, 10, 24, 4, 3, 10, 7199)
>>> datetime.timedelta(days=3, minutes = 55)
datetime.timedelta(3, 3300)
>>> # add timedelta to datetime
>>> datetime.timedelta(days=3, minutes = 55) + \
datetime.datetime(year=2017, month=10, day=24, hour=4, minute=3, second=10, microsecond=7199)
datetime.datetime(2017, 10, 27, 4, 58, 10, 7199)
NumPy has no separate date and time objects, just a single datetime64 object to represent a single moment in time. The datetime module's datetime object has microsecond precision (one-millionth of a second). NumPy's datetime64 object allows you to set its precision from hours all the way to attoseconds (10 ^ -18). It's constructor is more flexible and can take a variety of inputs.
Pass an integer with a string for the units. See all units here. It gets converted to that many units after the UNIX epoch: Jan 1, 1970
>>> np.datetime64(5, 'ns')
numpy.datetime64('1970-01-01T00:00:00.000000005')
>>> np.datetime64(1508887504, 's')
numpy.datetime64('2017-10-24T23:25:04')
You can also use strings as long as they are in ISO 8601 format.
>>> np.datetime64('2017-10-24')
numpy.datetime64('2017-10-24')
Timedeltas have a single unit
>>> np.timedelta64(5, 'D') # 5 days
>>> np.timedelta64(10, 'h') 10 hours
Can also create them by subtracting two datetime64 objects
>>> np.datetime64('2017-10-24T05:30:45.67') - np.datetime64('2017-10-22T12:35:40.123')
numpy.timedelta64(147305547,'ms')
A pandas Timestamp is a moment in time very similar to a datetime but with much more functionality. You can construct them with either pd.Timestamp
or pd.to_datetime
.
>>> pd.Timestamp(1239.1238934) #defautls to nanoseconds
Timestamp('1970-01-01 00:00:00.000001239')
>>> pd.Timestamp(1239.1238934, unit='D') # change units
Timestamp('1973-05-24 02:58:24.355200')
>>> pd.Timestamp('2017-10-24 05') # partial strings work
Timestamp('2017-10-24 05:00:00')
pd.to_datetime
works very similarly (with a few more options) and can convert a list of strings into Timestamps.
>>> pd.to_datetime('2017-10-24 05')
Timestamp('2017-10-24 05:00:00')
>>> pd.to_datetime(['2017-1-1', '2017-1-2'])
DatetimeIndex(['2017-01-01', '2017-01-02'], dtype='datetime64[ns]', freq=None)
>>> dt = datetime.datetime(year=2017, month=10, day=24, hour=4,
minute=3, second=10, microsecond=7199)
>>> np.datetime64(dt)
numpy.datetime64('2017-10-24T04:03:10.007199')
>>> pd.Timestamp(dt) # or pd.to_datetime(dt)
Timestamp('2017-10-24 04:03:10.007199')
>>> dt64 = np.datetime64('2017-10-24 05:34:20.123456')
>>> unix_epoch = np.datetime64(0, 's')
>>> one_second = np.timedelta64(1, 's')
>>> seconds_since_epoch = (dt64 - unix_epoch) / one_second
>>> seconds_since_epoch
1508823260.123456
>>> datetime.datetime.utcfromtimestamp(seconds_since_epoch)
>>> datetime.datetime(2017, 10, 24, 5, 34, 20, 123456)
Convert to Timestamp
>>> pd.Timestamp(dt64)
Timestamp('2017-10-24 05:34:20.123456')
This is quite easy as pandas timestamps are very powerful
>>> ts = pd.Timestamp('2017-10-24 04:24:33.654321')
>>> ts.to_pydatetime() # Python's datetime
datetime.datetime(2017, 10, 24, 4, 24, 33, 654321)
>>> ts.to_datetime64()
numpy.datetime64('2017-10-24T04:24:33.654321000')
I would do it like this:
Worksheets("EmployeeCosts").Range("B" & var1a).Formula = _
Replace("=SUM(H5:H{SOME_VAR})","{SOME_VAR}",var1a)
In case you have some more complex formula it will be handy