Take a look at this short article.
Solution paraphrased here:
Create your table:
CREATE TABLE zip_codes
(ZIP char(5), LATITUDE double precision, LONGITUDE double precision,
CITY varchar, STATE char(2), COUNTY varchar, ZIP_CLASS varchar);
Copy data from your CSV file to the table:
COPY zip_codes FROM '/path/to/csv/ZIP_CODES.txt' WITH (FORMAT csv);
You can use array.slice(0,1) // First index is removed and array is returned.
When doing;
a_file = open('E:\Python Win7-64-AMD 3.3\Test', encoding='utf-8')
...you're trying to open a directory as a file, which may (and on most non UNIX file systems will) fail.
Your other example though;
a_file = open('E:\Python Win7-64-AMD 3.3\Test\a.txt', encoding='utf-8')
should work well if you just have the permission on a.txt
. You may want to use a raw (r
-prefixed) string though, to make sure your path does not contain any escape characters like \n
that will be translated to special characters.
a_file = open(r'E:\Python Win7-64-AMD 3.3\Test\a.txt', encoding='utf-8')
An easy way of doing this:
SELECT ('[' || to_json('Some "text"'::TEXT) || ']')::json ->> 0;
Just convert the json string into a json list
Convert a JSON string into an object in C#. Using below test case.. its worked for me. Here "MenuInfo" is my C# class object.
JsonTextReader reader = null;
try
{
WebClient webClient = new WebClient();
JObject result = JObject.Parse(webClient.DownloadString("YOUR URL"));
reader = new JsonTextReader(new System.IO.StringReader(result.ToString()));
reader.SupportMultipleContent = true;
}
catch(Exception)
{}
JsonSerializer serializer = new JsonSerializer();
MenuInfo menuInfo = serializer.Deserialize<MenuInfo>(reader);
Try this:
df <- df[,colSums(is.na(df))<nrow(df)]
If you just want to insert a value at a certain position in a string, you can use the String.Insert
method:
public string Insert(int startIndex, string value)
Example:
"abc".Insert(2, "XYZ") == "abXYZc"
I am assuming you want to display this as part of the player.
This site breaks down how to get both the current and total time regardless of how you want to display it though using jQuery:
http://dev.opera.com/articles/view/custom-html5-video-player-with-css3-and-jquery/
This will also cover how to set it to a specific div. As philip has already mentioned, .currentTime will give you where you are in the video.
With Jquery... You can add class to html elements like this:
$(".divclass").find("p,h1,h2,h3,figure,span,a").addClass('nameclassorid');
nameclassorid no point or # at the beginning
As @Roko mentioned you can do this in multiple ways.
1.Using the jQuery first-child selector - SnoopCode
$(document).ready(function(){
$(".alldivs onediv:first-child").css("background-color","yellow");
}
Using jQuery eq Selector - SnoopCode
$( "body" ).find( "onediv" ).eq(1).addClass( "red" );
Using jQuery Id Selector - SnoopCode
$(document).ready(function(){
$("#div1").css("background-color: red;");
});
Download Optillect SQL Azure Backup - it has 15-day trial, so it will be enough to move your database :)
Here is an extension method doing that:
public static IEnumerable<KeyValuePair<TLeft, TRight>> FullOuterJoin<TLeft, TRight>(this IEnumerable<TLeft> leftItems, Func<TLeft, object> leftIdSelector, IEnumerable<TRight> rightItems, Func<TRight, object> rightIdSelector)
{
var leftOuterJoin = from left in leftItems
join right in rightItems on leftIdSelector(left) equals rightIdSelector(right) into temp
from right in temp.DefaultIfEmpty()
select new { left, right };
var rightOuterJoin = from right in rightItems
join left in leftItems on rightIdSelector(right) equals leftIdSelector(left) into temp
from left in temp.DefaultIfEmpty()
select new { left, right };
var fullOuterJoin = leftOuterJoin.Union(rightOuterJoin);
return fullOuterJoin.Select(x => new KeyValuePair<TLeft, TRight>(x.left, x.right));
}
Spark – Overwrite the output directory:
Spark by default doesn’t overwrite the output directory on S3, HDFS, and any other file systems, when you try to write the DataFrame contents to an existing directory, Spark returns runtime error hence. To overcome this Spark provides an enumeration org.apache.spark.sql.SaveMode.Overwrite to overwrite the existing folder.
We need to use this Overwrite as an argument to mode() function of the DataFrameWrite class, for example.
df. write.mode(SaveMode.Overwrite).csv("/tmp/out/foldername")
or you can use the overwrite string.
df.write.mode("overwrite").csv("/tmp/out/foldername")
Besides Overwrite, SaveMode also offers other modes like SaveMode.Append, SaveMode.ErrorIfExists and SaveMode.Ignore
For older versions of Spark, you can use the following to overwrite the output directory with the RDD contents.
sparkConf.set("spark.hadoop.validateOutputSpecs", "false") val sparkContext = SparkContext(sparkConf)
Alternative to @Peter Monks.
If the number in the 'in' statement is small and fixed.
DECLARE @var1 varchar(30), @var2 varchar(30), @var3 varchar(30);
SET @var1 = 'james';
SET @var2 = 'same';
SET @var3 = 'dogcat';
Select * FROM Database Where x in (@var1,@var2,@var3);
It sounds like it's just a compiler warning.
Usage of scanf_s
prevents possible buffer overflow.
See: http://code.wikia.com/wiki/Scanf_s
Good explanation as to why scanf
can be dangerous: Disadvantages of scanf
So as suggested, you can try replacing scanf
with scanf_s
or disable the compiler warning.
The major cornerstone knowledge must be the quoted one,
When an object reference is passed to a method, the reference itself is passed by use of call-by-value. However, since the value being passed refers to an object, the copy of that value will still refer to the same object referred to by its corresponding argument.
Java: A Beginner's Guide, Sixth Edition, Herbert Schildt
string sTable="static class BinaryTable\r\n{";
string stemp = "";
for (int i = 0; i < 256; i++)
{
stemp = System.Convert.ToString(i, 2);
while(stemp.Length<8) stemp = "0" + stemp;
sTable += "\tconst char nb" + stemp + "=" + i.ToString() + ";\r\n";
}
sTable += "}";
Clipboard.Clear();
Clipboard.SetText ( sTable);
MessageBox.Show(sTable);
Using this, for 8bit binary, I use this to make a static class and it puts it into the clipboard.. Then it gets pasted into the project and added to the Using section, so anything with nb001010 is taken out of a table, at least static, but still... I use C# for a lot of PIC graphics coding and use 0b101010 a lot in Hi-Tech C
--sample from code outpt--
static class BinaryTable
{ const char nb00000000=0;
const char nb00000001=1;
const char nb00000010=2;
const char nb00000011=3;
const char nb00000100=4;
//etc, etc, etc, etc, etc, etc, etc,
}
:-) NEAL
How about maybe something like this?
var condCheck1 = new string[]{"a","b","c"};
var condCheck2 = new string[]{"a","b","c","A2"}
if(!condCheck1.Contains(columnName) && !checkbox.checked)
//statement 1
else if (!condCheck2.Contains(columnName))
//statment 2
var consolidatedChildren =
from c in children
group c by new
{
c.School,
c.Friend,
c.FavoriteColor,
} into gcs
select new ConsolidatedChild()
{
School = gcs.Key.School,
Friend = gcs.Key.Friend,
FavoriteColor = gcs.Key.FavoriteColor,
Children = gcs.ToList(),
};
var consolidatedChildren =
children
.GroupBy(c => new
{
c.School,
c.Friend,
c.FavoriteColor,
})
.Select(gcs => new ConsolidatedChild()
{
School = gcs.Key.School,
Friend = gcs.Key.Friend,
FavoriteColor = gcs.Key.FavoriteColor,
Children = gcs.ToList(),
});
I didn't get the second question, maybe you can elaborate...but for your first query.
String content = edtEditText.getText().toString(); //gets you the contents of edit text
tvTextView.setText(content); //displays it in a textview..
Same issue i was getting , but When we open our eclipse software then automatically we can see eclipse version and workspace location like these pic below
I ran into the same issue, for whatever reason Visual Studio did not update the web config when I first added the service. I found that updating the Service Reference also fixed this issue.
Steps:
For Me adding few below line in WebApi.config works as after updating the new nuget package did not works out
var setting = config.Formatters.JsonFormatter.SerializerSettings;
setting.ContractResolver = new CamelCasePropertyNamesContractResolver();
setting.Formatting = Formatting.Indented;
Don't forget to add namespace:
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
Another way that is never talked about is Create a view in MSSQL with all the data you want to present. Then use LINQ to SQL or whatever to map it. In your controller return it to the view. Done.
Other option that work is ..,
If you change de indentity in application pool, you can run the code, the idea is change the aplication pool execution account for one account with more privileges,
For more details use this blog
A function is just a class with a __call__
method, so you can do
hasattr(obj, '__call__')
For example:
>>> hasattr(x, '__call__')
True
>>> x = 2
>>> hasattr(x, '__call__')
False
That is the "best" way of doing it, but depending on why you need to know if it's callable or note, you could just put it in a try/execpt block:
try:
x()
except TypeError:
print "was not callable"
It's arguable if try/except is more Python'y than doing if hasattr(x, '__call__'): x()
.. I would say hasattr
is more accurate, since you wont accidently catch the wrong TypeError, for example:
>>> def x():
... raise TypeError
...
>>> hasattr(x, '__call__')
True # Correct
>>> try:
... x()
... except TypeError:
... print "x was not callable"
...
x was not callable # Wrong!
Possibly the fastest solution is to operate in plain Python:
Series(
map(
'_'.join,
df.values.tolist()
# when non-string columns are present:
# df.values.astype(str).tolist()
),
index=df.index
)
Comparison against @MaxU answer (using the big
data frame which has both numeric and string columns):
%timeit big['bar'].astype(str) + '_' + big['foo'] + '_' + big['new']
# 29.4 ms ± 1.08 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit Series(map('_'.join, big.values.astype(str).tolist()), index=big.index)
# 27.4 ms ± 2.36 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
Comparison against @derchambers answer (using their df
data frame where all columns are strings):
from functools import reduce
def reduce_join(df, columns):
slist = [df[x] for x in columns]
return reduce(lambda x, y: x + '_' + y, slist[1:], slist[0])
def list_map(df, columns):
return Series(
map(
'_'.join,
df[columns].values.tolist()
),
index=df.index
)
%timeit df1 = reduce_join(df, list('1234'))
# 602 ms ± 39 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit df2 = list_map(df, list('1234'))
# 351 ms ± 12.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
??????Dialog
?Acticity.onConfigurationChanged
?????
If you just deal with the problem of Dialog
in Activity.onConfigurationChanged
//?`AndroidManifest.xml`??????`android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize"`????????
//If `android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize"` has been configured in `AndroidManifest.xml`, you do not need to set this item
Acticity/Context.registerComponentCallbacks(object : ComponentCallbacks {
override fun onConfigurationChanged(newConfig: Configuration) {
dialog?.dismiss()
}
override fun onLowMemory() {
}
})
?onDestroy
???????
It is safer to destroy in on Destroy
override fun onDestroy() {
super.onDestroy()
DialogManager.dismiss()
}
Maybe this is useful for you https://github.com/javakam/DialogManager
Do a chmod 400 yourkeyfile.pem If your instance is Amazon linux then use ssh -i yourkeyfile.pem ec2-user@ip for ubuntu ssh -i yourkeyfile.pem ubuntu@ip for centos ssh -i yourkeyfile.pem centos@ip
if you are trying to check that in spring frame work then isEmpty method in objectUtils class helps,
public static boolean isEmpty(@Nullable Object[] array) {
return (array == null || array.length == 0);
}
In Windows Vista and later the HTTP WCF service stuff would cause the exception you mentioned because a restricted account does not have right for that. That is the reason why it worked when you ran it as administrator.
Every sensible developer must use a RESTRICTED account rather than as an Administrator, yet many people go the wrong way and that is precisely why there are so many applications out there that DEMAND admin permissions when they are not really required. Working the lazy way results in lazy solutions. I hope you still work in a restricted account (my congratulations).
There is a tool out there (from 2008 or so) called NamespaceManagerTool if I remember correctly that is supposed to grant the restricted user permissions on these service URLs that you define for WCF. I haven't used that though...
You'll definitely want to check out this positioning article from 'A List Apart'. Helped demystify CSS positioning (which seemed insane to me, prior to this article).
This gives you the first few digits of the hash and they are unique enough to use as say a version number.
git rev-parse --short HEAD
Use this instead:
string objTextBox = t.Text;
The object t
is the TextBox
. The object you call objTextBox
is assigned the ID
property of the TextBox
.
So better code would be:
TextBox objTextBox = (TextBox)sender;
string theText = objTextBox.Text;
If you cannot find the .exe file, rebuild your solution and in your "Output" from Visual Studio the path to the file will be shown.
Getting the last character is easy, as you can treat strings as an array:
var lastChar = id[id.length - 1];
To get a section of a string, you can use the substr function or the substring function:
id.substr(id.length - 1); //get the last character
id.substr(2); //get the characters from the 3rd character on
id.substr(2, 1); //get the 3rd character
id.substr(2, 2); //get the 3rd and 4th characters
The difference between substr
and substring
is how the second (optional) parameter is treated. In substr
, it's the amount of characters from the index (the first parameter). In substring
, it's the index of where the character slicing should end.
I'm not quite sure what you're attempting to use the div for, but this is an example with some random text.
Mr_Green gave the correct instructions when he said to add overflow-y: auto
as that restricts it to vertical scrolling. This is a JSFiddle example:
Writing record arrays as CSV files with headers requires a bit more work.
This example reads from a CSV file ('example.csv'
) and writes its contents to another CSV file (out.csv
).
import numpy as np
# Write an example CSV file with headers on first line
with open('example.csv', 'w') as fp:
fp.write('''\
col1,col2,col3
1,100.1,string1
2,222.2,second string
''')
# Read it as a Numpy record array
ar = np.recfromcsv('example.csv')
print(repr(ar))
# rec.array([(1, 100.1, 'string1'), (2, 222.2, 'second string')],
# dtype=[('col1', '<i4'), ('col2', '<f8'), ('col3', 'S13')])
# Write as a CSV file with headers on first line
with open('out.csv', 'w') as fp:
fp.write(','.join(ar.dtype.names) + '\n')
np.savetxt(fp, ar, '%s', ',')
Note that the above example cannot handle values which are strings with commas. To always enclose non-numeric values within quotes, use the csv
package:
import csv
with open('out2.csv', 'wb') as fp:
writer = csv.writer(fp, quoting=csv.QUOTE_NONNUMERIC)
writer.writerow(ar.dtype.names)
writer.writerows(ar.tolist())
To find the version of the java in the classfiles I used:
javap -verbose <classname>
which announces the version at the start as
minor version: 0
major version: 49
which corresponds to Java 1.5
Add javax.servlet dependency in pom.xml. Your problem will be resolved.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
select top (@TakeCount) * --FETCH NEXT
from(
Select ROW_NUMBER() OVER (order by StartDate) AS rowid,*
From YourTable
)A
where Rowid>@SkipCount --OFFSET
You can run conda install --file requirements.txt
instead of the loop, but there is no target directory in conda install. conda install
installs a list of packages into a specified conda environment.
You want in page A to know the URL of page B?
Or to know in page B the URL of page A?
In Page B: document.referrer if set. As already shown here: How to get the previous URL in JavaScript?
In page A you would need to read a cookie or local/sessionStorage you set in page B, assuming the same domains
Since Laravel 5.2 you can use File Responses
Basically you can call it like this:
return response()->file($pathToFile);
and it will display files as PDF and images inline in the browser.
You may be forgetting something. Before #include <iostream>
, write #include <stdafx.h>
and maybe that will help. Then, when you are done writing, click test, than click output from build, then when it is done processing/compiling, press Ctrl+F5 to open the Command Prompt and it should have the output and "press any key to continue."
Try making your changes in:
- (void) viewWillLayoutSubviews {}
The code will run at every orientation change as the subviews get laid out again.
client.user.setStatus('dnd', 'Made by KwinkyWolf')
And change 'dnd' to whatever status you want it to have. And then the next field 'Made by KwinkyWolf' is where you change the game. Hope this helped :)
List of status':
Not sure if they're still the same, or if there's more but hope that helped too :)
public enum myEnum
{
ThisNameWorks,
This_Name_can_be_used_instead,
}
Open preferences, in macOS ?; or in Windows/Linux Ctrl + Alt + S.
Go to Editor -> Code Style -> Python, and if you want to follow PEP-8, choose Tab size: 4, Indent: 4, and Continuation indent: 8 as shown below:
Apply the changes, and click on OK.
Option 1: You can choose in the navigation bar: Edit -> Convert Indent -> To Spaces. (see image below)
Option 2: You can execute "To Spaces" action by running the Find Action shortcut: ??A on macOS or ctrl?A on Windows/Linux. Then type "To Spaces", and run the action as shown in the image below.
BH's answer of installing Java 6u45 was very close... still got the popup on reboot...BUT after uninstalling Java 6u45, rebooted, no warning! Thank you BH! Then installed the latest version, 8u151-i586, rebooted no warning.
I added lines in PATH as above, didn't do anything.
My system: Windows 7, 64 bit. Warning was for No JVM, 32 bit Java not found. Yes, I could have installed the 64 bit version, but 32bit is more compatible with all programs.
I found this is the most easiest way:
pipeline {
agent {
node {
label 'master'
}
}
stages {
stage('hello world') {
steps {
sh 'env'
}
}
}
}
In the event that anyone would be interested. Here's a quick shell script that will remove all local branches that aren't tracked remotely. A word of caution: This will get rid of any branch that isn't tracked remotely regardless of whether it was merged or not.
If you guys see any issues with this please let me know and I'll fix it (etc. etc.)
Save it in a file called git-rm-ntb
(call it whatever) on PATH
and run:
git-rm-ntb <remote1:optional> <remote2:optional> ...
clean()
{
REMOTES="$@";
if [ -z "$REMOTES" ]; then
REMOTES=$(git remote);
fi
REMOTES=$(echo "$REMOTES" | xargs -n1 echo)
RBRANCHES=()
while read REMOTE; do
CURRBRANCHES=($(git ls-remote $REMOTE | awk '{print $2}' | grep 'refs/heads/' | sed 's:refs/heads/::'))
RBRANCHES=("${CURRBRANCHES[@]}" "${RBRANCHES[@]}")
done < <(echo "$REMOTES" )
[[ $RBRANCHES ]] || exit
LBRANCHES=($(git branch | sed 's:\*::' | awk '{print $1}'))
for i in "${LBRANCHES[@]}"; do
skip=
for j in "${RBRANCHES[@]}"; do
[[ $i == $j ]] && { skip=1; echo -e "\033[32m Keeping $i \033[0m"; break; }
done
[[ -n $skip ]] || { echo -e "\033[31m $(git branch -D $i) \033[0m"; }
done
}
clean $@
If you want to generate a backtrace, you are looking for debug_backtrace
and/or debug_print_backtrace
.
The first one will, for instance, get you an array like this one (quoting the manual) :
array(2) {
[0]=>
array(4) {
["file"] => string(10) "/tmp/a.php"
["line"] => int(10)
["function"] => string(6) "a_test"
["args"]=>
array(1) {
[0] => &string(6) "friend"
}
}
[1]=>
array(4) {
["file"] => string(10) "/tmp/b.php"
["line"] => int(2)
["args"] =>
array(1) {
[0] => string(10) "/tmp/a.php"
}
["function"] => string(12) "include_once"
}
}
They will apparently not flush the I/O buffer, but you can do that yourself, with flush
and/or ob_flush
.
(see the manual page of the first one to find out why the "and/or" ;-) )
[project properties dialog]
For development using VisualStudio 2017 and a NetCore API-project:
1) In Cmd-Box: ipconfig /all to determine IP-address
2a) Enter the retrieved IP-address in Project properties-> Debug Tab
2b) Select a Port and attach that to the IP-address from step 2a.
3) Add an allow rule in the firewall to allow incoming TCP-traffic on the selected Port (my firewall triggered with a dialog: "Block or add rule to firewall"). Add will in that case do the trick.
Disadvantage of the solution above:
1) If you use a dynamic IP-address you need to redo the steps above in case another IP-address has been assigned.
2) You server has now an open Port which you might forget, but this open port remains an invitation for unwanted guests.
I too had the same problem, but solved after disabling the compiler and again reinstalling the extension. Disable of the compiler can be done by system-> configration-> tools-> compilation.. Here Disable the process... Good Luck
I think you should need to check for isset and not empty value, like form was submitted without input data so isset will be true This will prevent you to have any error or notice.
if((isset($_POST['name'])) && !empty($_POST['name']))
{
$name = $_POST['name']; //note i used $_POST since you have a post form **method='post'**
echo $name;
}
if you want to hold the arguments from Terminal, try the following code:
A = ARGV[0].to_i
B = ARGV[1].to_i
puts "#{A} + #{B} = #{A + B}"
patrick dw's answer is right on.
For kicks and giggles I thought I would post a simple way to return an array of all the IDs.
var arrayOfIds = $.map($(".myClassName"), function(n, i){
return n.id;
});
alert(arrayOfIds);
You are right - you declared a new use defined type (Name_pairs) and you need variable of that type to use it.
The code should go like this:
Name_pairs np;
np.read_names()
CommandArgument='<%#Eval("ScrapId").Tostring()+ Eval("UserId")%>
//added the comment function
You can use .length
after the selector to see if it matched any elements, like this:
if($("#" + name).length == 0) {
//it doesn't exist
}
The full version:
$("li.friend").live('click', function(){
name = $(this).text();
if($("#" + name).length == 0) {
$("div#chatbar").append("<div class='labels'><div id='" + name + "' style='display:none;'></div>" + name + "</div>");
} else {
alert('this record already exists');
}
});
Or, the non-jQuery version for this part (since it's an ID):
$("li.friend").live('click', function(){
name = $(this).text();
if(document.getElementById(name) == null) {
$("div#chatbar").append("<div class='labels'><div id='" + name + "' style='display:none;'></div>" + name + "</div>");
} else {
alert('this record already exists');
}
});
bcrypt
is a hashing algorithm which is scalable with hardware (via a configurable number of rounds). Its slowness and multiple rounds ensures that an attacker must deploy massive funds and hardware to be able to crack your passwords. Add to that per-password salts (bcrypt
REQUIRES salts) and you can be sure that an attack is virtually unfeasible without either ludicrous amount of funds or hardware.
bcrypt
uses the Eksblowfish algorithm to hash passwords. While the encryption phase of Eksblowfish and Blowfish are exactly the same, the key schedule phase of Eksblowfish ensures that any subsequent state depends on both salt and key (user password), and no state can be precomputed without the knowledge of both. Because of this key difference, bcrypt
is a one-way hashing algorithm. You cannot retrieve the plain text password without already knowing the salt, rounds and key (password). [Source]
Password hashing functions have now been built directly into PHP >= 5.5. You may now use password_hash()
to create a bcrypt
hash of any password:
<?php
// Usage 1:
echo password_hash('rasmuslerdorf', PASSWORD_DEFAULT)."\n";
// $2y$10$xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// For example:
// $2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a
// Usage 2:
$options = [
'cost' => 11
];
echo password_hash('rasmuslerdorf', PASSWORD_BCRYPT, $options)."\n";
// $2y$11$6DP.V0nO7YI3iSki4qog6OQI5eiO6Jnjsqg7vdnb.JgGIsxniOn4C
To verify a user provided password against an existing hash, you may use the password_verify()
as such:
<?php
// See the password_hash() example to see where this came from.
$hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';
if (password_verify('rasmuslerdorf', $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
There is a compatibility library on GitHub created based on the source code of the above functions originally written in C, which provides the same functionality. Once the compatibility library is installed, usage is the same as above (minus the shorthand array notation if you are still on the 5.3.x branch).
You can use crypt()
function to generate bcrypt hashes of input strings. This class can automatically generate salts and verify existing hashes against an input. If you are using a version of PHP higher or equal to 5.3.7, it is highly recommended you use the built-in function or the compat library. This alternative is provided only for historical purposes.
class Bcrypt{
private $rounds;
public function __construct($rounds = 12) {
if (CRYPT_BLOWFISH != 1) {
throw new Exception("bcrypt not supported in this installation. See http://php.net/crypt");
}
$this->rounds = $rounds;
}
public function hash($input){
$hash = crypt($input, $this->getSalt());
if (strlen($hash) > 13)
return $hash;
return false;
}
public function verify($input, $existingHash){
$hash = crypt($input, $existingHash);
return $hash === $existingHash;
}
private function getSalt(){
$salt = sprintf('$2a$%02d$', $this->rounds);
$bytes = $this->getRandomBytes(16);
$salt .= $this->encodeBytes($bytes);
return $salt;
}
private $randomState;
private function getRandomBytes($count){
$bytes = '';
if (function_exists('openssl_random_pseudo_bytes') &&
(strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')) { // OpenSSL is slow on Windows
$bytes = openssl_random_pseudo_bytes($count);
}
if ($bytes === '' && is_readable('/dev/urandom') &&
($hRand = @fopen('/dev/urandom', 'rb')) !== FALSE) {
$bytes = fread($hRand, $count);
fclose($hRand);
}
if (strlen($bytes) < $count) {
$bytes = '';
if ($this->randomState === null) {
$this->randomState = microtime();
if (function_exists('getmypid')) {
$this->randomState .= getmypid();
}
}
for ($i = 0; $i < $count; $i += 16) {
$this->randomState = md5(microtime() . $this->randomState);
if (PHP_VERSION >= '5') {
$bytes .= md5($this->randomState, true);
} else {
$bytes .= pack('H*', md5($this->randomState));
}
}
$bytes = substr($bytes, 0, $count);
}
return $bytes;
}
private function encodeBytes($input){
// The following is code from the PHP Password Hashing Framework
$itoa64 = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$output = '';
$i = 0;
do {
$c1 = ord($input[$i++]);
$output .= $itoa64[$c1 >> 2];
$c1 = ($c1 & 0x03) << 4;
if ($i >= 16) {
$output .= $itoa64[$c1];
break;
}
$c2 = ord($input[$i++]);
$c1 |= $c2 >> 4;
$output .= $itoa64[$c1];
$c1 = ($c2 & 0x0f) << 2;
$c2 = ord($input[$i++]);
$c1 |= $c2 >> 6;
$output .= $itoa64[$c1];
$output .= $itoa64[$c2 & 0x3f];
} while (true);
return $output;
}
}
You can use this code like this:
$bcrypt = new Bcrypt(15);
$hash = $bcrypt->hash('password');
$isGood = $bcrypt->verify('password', $hash);
Alternatively, you may also use the Portable PHP Hashing Framework.
I disagree!
Why would you ignore the built-in functionality of a for loop to make your own? You do not need to reinvent the wheel.
I think it makes more sense to have your checks at the top of your for loop like so
for(int i = 0; i < myCollection.Length && myCollection[i].SomeValue != "Break Condition"; i++)
{
//loop body
}
or if you need to process the row first
for(int i = 0; i < myCollection.Length && (i == 0 ? true : myCollection[i-1].SomeValue != "Break Condition"); i++)
{
//loop body
}
This way you can write a function to perform everything and make much cleaner code.
for(int i = 0; i < myCollection.Length && (i == 0 ? true : myCollection[i-1].SomeValue != "Break Condition"); i++)
{
DoAllThatCrazyStuff(myCollection[i]);
}
Or if your condition is complicated you can move that code out too!
for(int i = 0; i < myCollection.Length && BreakFunctionCheck(i, myCollection); i++)
{
DoAllThatCrazyStuff(myCollection[i]);
}
"Professional Code" that is riddled with breaks doesn't really sound like professional code to me. It sounds like lazy coding ;)
Error in datanode.log file
$ more /usr/local/hadoop/logs/hadoop-hduser-datanode-ubuntu.log
Shows:
java.io.IOException: Incompatible clusterIDs in /usr/local/hadoop_tmp/hdfs/datanode: namenode clusterID = CID-e4c3fed0-c2ce-4d8b-8bf3-c6388689eb82; datanode clusterID = CID-2fcfefc7-c931-4cda-8f89-1a67346a9b7c
Solution: Stop your cluster and issue the below command & then start your cluster again.
sudo rm -rf /usr/local/hadoop_tmp/hdfs/datanode/*
You can use an enum of months:
public enum Month
{
January,
February,
// (...)
December,
}
public Month ToInt(Month Input)
{
return (int)Enum.Parse(typeof(Month), Input, true));
}
I am not 100% certain on the syntax for enum.Parse(), though.
The rule is as following :
A B
B as a descendant of A
A > B
B as a child of A
So
div.dropdown *
and not
div.dropdown > *
There is none. Use script tags to link to google's version (or download it yourself and link to your copy if you really want to).
If you don't know how to do that, learn HTML and Javascript first before attempting to learn jQuery.
pandas provides high level data manipulation tools built on top of NumPy. NumPy by itself is a fairly low-level tool, similar to MATLAB. pandas on the other hand provides rich time series functionality, data alignment, NA-friendly statistics, groupby, merge and join methods, and lots of other conveniences. It has become very popular in recent years in financial applications. I will have a chapter dedicated to financial data analysis using pandas in my upcoming book.
Why not make use of the meaningful data already there, instead of adding arbitrary data?
i.e. use <a href="/articles/5/page-title" class="article-link">
, and then you can programmatically get all article links on the page (via the classname) and the article ID (matching the regex /articles\/(\d+)/
against this.href
).
Create a custom Switch and override setChecked to change color:
public class SwitchPlus extends Switch {
public SwitchPlus(Context context) {
super(context);
}
public SwitchPlus(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SwitchPlus(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public void setChecked(boolean checked) {
super.setChecked(checked);
changeColor(checked);
}
private void changeColor(boolean isChecked) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
int thumbColor;
int trackColor;
if(isChecked) {
thumbColor = Color.argb(255, 253, 153, 0);
trackColor = thumbColor;
} else {
thumbColor = Color.argb(255, 236, 236, 236);
trackColor = Color.argb(255, 0, 0, 0);
}
try {
getThumbDrawable().setColorFilter(thumbColor, PorterDuff.Mode.MULTIPLY);
getTrackDrawable().setColorFilter(trackColor, PorterDuff.Mode.MULTIPLY);
}
catch (NullPointerException e) {
e.printStackTrace();
}
}
}
}
for a solution that works without bash or certain features from read
you can use stty
to disable echo
stty_orig=$(stty -g)
stty -echo
read password
stty $stty_orig
select convert(varchar, Max(Time) - Min(Time) , 108) from logTable where id=...
You can also take a look at LineNumberReader, subclass of BufferedReader. Along with the readline method, it also has setter/getter methods to access line number. Very useful to keep track of the number of lines read, while reading data from file.
@bhamby is correct. By leaving the microseconds off of your timestamp value, your query would only match on a usagetime of 2012-09-03 08:03:06.000000
If you don't have the complete timestamp value captured from a previous query, you can specify a ranged predicate that will match on any microsecond value for that time:
...WHERE id = 1 AND usagetime BETWEEN '2012-09-03 08:03:06' AND '2012-09-03 08:03:07'
or
...WHERE id = 1 AND usagetime >= '2012-09-03 08:03:06'
AND usagetime < '2012-09-03 08:03:07'
You can also use npmlog by issacs, recommended in https://npmjs.org/doc/coding-style.html.
You can find this module here https://github.com/isaacs/npmlog
For me the reason I was getting NPE is that I was using Mockito.any()
when mocking primitives. I found that by switching to using the correct variant from mockito gets rid of the errors.
For example, to mock a function that takes a primitive long
as parameter, instead of using any()
, you should be more specific and replace that with any(Long.class)
or Mockito.anyLong()
.
Hope that helps someone.
final Properties properties = new Properties();
try (final InputStream stream =
this.getClass().getResourceAsStream("foo.properties")) {
properties.load(stream);
/* or properties.loadFromXML(...) */
}
You could use the bootstrap grid system :
<div class="col-md-6 form-group">
<label for="textbox1">Label1</label>
<input class="form-control" id="textbox1" type="text"/>
</div>
<div class="col-md-6 form-group">
<label for="textbox2">Label2</label>
<input class="form-control" id="textbox2" type="text"/>
</div>
<span class="clearfix">
http://getbootstrap.com/css/#grid
Is that what you want to achieve?
Running a simple test, I thought I'd document what works and what doesn't. Often I see people checking to see if the object's class is a member of the other class or is equal to the other class.
For the line below, we have some poorly formed data that can be an NSArray
, an NSDictionary
or (null)
.
NSArray *hits = [[[myXML objectForKey: @"Answer"] objectForKey: @"hits"] objectForKey: @"Hit"];
These are the tests that were performed:
NSLog(@"%@", [hits class]);
if ([hits isMemberOfClass:[NSMutableArray class]]) {
NSLog(@"%@", [hits class]);
}
if ([hits isMemberOfClass:[NSMutableDictionary class]]) {
NSLog(@"%@", [hits class]);
}
if ([hits isMemberOfClass:[NSArray class]]) {
NSLog(@"%@", [hits class]);
}
if ([hits isMemberOfClass:[NSDictionary class]]) {
NSLog(@"%@", [hits class]);
}
if ([hits isKindOfClass:[NSMutableDictionary class]]) {
NSLog(@"%@", [hits class]);
}
if ([hits isKindOfClass:[NSDictionary class]]) {
NSLog(@"%@", [hits class]);
}
if ([hits isKindOfClass:[NSArray class]]) {
NSLog(@"%@", [hits class]);
}
if ([hits isKindOfClass:[NSMutableArray class]]) {
NSLog(@"%@", [hits class]);
}
isKindOfClass
worked rather well while isMemberOfClass
didn't.
This might be what you are after, although depending on how many style_id's there are, it would be tricky to implement (not sure if those style_id's are static or not). If this is the case, then it is not really possible what you are wanting as the WHERE clause works on a row to row basis.
WITH cte as (
SELECT
image_id,
max(decode(style_id,24,style_value)) AS style_colour,
max(decode(style_id,25,style_value)) AS style_size,
max(decode(style_id,27,style_value)) AS style_shape
FROM
list
GROUP BY
image_id
)
SELECT
image_id
FROM
cte
WHERE
style_colour = 'red'
and style_size = 'big'
and style_shape = 'round'
Using dummies::dummy():
library(dummies)
# example data
df1 <- data.frame(id = 1:4, year = 1991:1994)
df1 <- cbind(df1, dummy(df1$year, sep = "_"))
df1
# id year df1_1991 df1_1992 df1_1993 df1_1994
# 1 1 1991 1 0 0 0
# 2 2 1992 0 1 0 0
# 3 3 1993 0 0 1 0
# 4 4 1994 0 0 0 1
ListViewItem.IsSelected = true;
ListViewItem.Focus();
The first line moves the cursor to the last non-empty row in the column. The second line prints that columns row.
Selection.End(xlDown).Select
MsgBox(ActiveCell.Row)
Cookies and local storage serve different purposes. Cookies are primarily for reading server-side, local storage can only be read by the client-side. So the question is, in your app, who needs this data — the client or the server?
If it's your client (your JavaScript), then by all means switch. You're wasting bandwidth by sending all the data in each HTTP header.
If it's your server, local storage isn't so useful because you'd have to forward the data along somehow (with Ajax or hidden form fields or something). This might be okay if the server only needs a small subset of the total data for each request.
You'll want to leave your session cookie as a cookie either way though.
As per the technical difference, and also my understanding:
Apart from being an old way of saving data, Cookies give you a limit of 4096 bytes (4095, actually) — it's per cookie. Local Storage is as big as 5MB per domain — SO Question also mentions it.
localStorage
is an implementation of the Storage
Interface. It stores data with no expiration date, and gets cleared only through JavaScript, or clearing the Browser Cache / Locally Stored Data — unlike cookie expiry.
This creates another array without those columns:
b = a.compress(logical_not(z), axis=1)
var format = /[`!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/;
// ^ ^
document.write(format.test("My @string-with(some%text)") + "<br/>");
document.write(format.test("My string with spaces") + "<br/>");
document.write(format.test("My StringContainingNoSpecialChars"));
_x000D_
You can use the very flexible solution flexbox to your Bootstrap.
justify-content: center;
can center your column.
Check out flex.
I agree with those who question why vim needs all this 'disaster recovery' stuff when no other text editors bother with it. I don't want vim creating ANY extra files in the edited file's directory when I'm editing it, thank you very much. To that end, I have this in my _vimrc
to disable swap files, and move irritating 'backup' files to the Temp dir:
" Uncomment below to prevent 'tilde backup files' (eg. myfile.txt~) from being created
"set nobackup
" Uncomment below to cause 'tilde backup files' to be created in a different dir so as not to clutter up the current file's directory (probably a better idea than disabling them altogether)
set backupdir=C:\Windows\Temp
" Uncomment below to disable 'swap files' (eg. .myfile.txt.swp) from being created
set noswapfile
Use
res.sendFile()
instead of
res.render()
.
What your trying to do is send a whole file.
This worked for me.
FIRST OF ALL KNOW THE REASON WHY ECLIPSE IS DOING SO.
Date has only one constructor Date(long date) which asks for date in long data type.
The constructor you are using
Date(String s) Deprecated. As of JDK version 1.1, replaced by DateFormat.parse(String s).
Thats why eclipse tells that this function is not good.
See this official docs
http://docs.oracle.com/javase/6/docs/api/java/util/Date.html
Deprecated methods from your context -- Source -- http://www.coderanch.com/t/378728/java/java/Deprecated-methods
There are a number of reasons why a method or class may become deprecated. An API may not be easily extensible without breaking backwards compatibility, and thus be superseded by a more powerful API (e.g., java.util.Date has been deprecated in favor of Calendar, or the Java 1.0 event model). It may also simply not work or produce incorrect results under certain circumstances (e.g., some of the java.io stream classes do not work properly with some encodings). Sometimes an API is just ill-conceived (SingleThreadModel in the servlet API), and gets replaced by nothing. And some of the early calls have been replaced by "Java Bean"-compatible methods (size by getSize, bounds by getBounds etc.)
SEVRAL SOLUTIONS ARE THERE JUST GOOGLE IT--
You can use date(long date) By converting your date String into long milliseconds and stackoverflow has so many post for that purpose.
You need to read about Java Image API and mouse-related API, maybe somewhere under the java.awt.event package
.
For a start, you need to be able to load and display the image to the screen, maybe you'll use a JPanel
.
Then from there, you will try implement a mouse motion listener interface and other related interfaces. Maybe you'll get tied on the mouseDragged
method...
For a mousedragged
action, you will get the coordinate of the rectangle form by the drag...
Then from these coordinates, you will get the subimage from the image you have and you sort of redraw it anew....
And then display the cropped image... I don't know if this will work, just a product of my imagination... just a thought!
I have found the solution even though it might be a little difficult for some to carry out.
1st step (for python3 and linux):
pip3 install pip-autoremove
2nd step:
cd /home/usernamegoeshere/.local/bin/
3rd step:
gedit /home/usernamegoeshere/.local/lib/python3.8/site-packages/pip_autoremove.py
and change all pip(s) to pip3
4th step:
./pip-autoremove packagenamegoeshere
At least, this was what worked for me ...
If you use random
instead of * random
your code not give any error
I have the same issue. My solution was delete one of the oracle path in environment variable. I also changed the inventory.xml and point to the oracle home version which is in my environment path variable.
Ok, instead of identifying players by name track with sockets through which they have connected. You can have a implementation like
var allClients = [];
io.sockets.on('connection', function(socket) {
allClients.push(socket);
socket.on('disconnect', function() {
console.log('Got disconnect!');
var i = allClients.indexOf(socket);
allClients.splice(i, 1);
});
});
Hope this will help you to think in another way
You might find this Wikipedia article on salting worthwhile. The idea is to add a set bit of data to randomize your hash value; this will protect your passwords from dictionary attacks if someone gets unauthorized access to the password hashes.
This question is old, but I'm surprised why no one mentioned boost::format
:
cout << (boost::format("%x") % 1234).str(); // output is: 4d2
If you want to GUARANTEE your application will NOT function in February, 2038, use TIMESTAMP. Refer to your REFMAN for the RANGE of dates supported.
Sass supports @if
statements. (See the documentation.)
You could write your mixin like this:
@mixin box-shadow($top, $left, $blur, $color, $inset:"") {
@if $inset != "" {
-webkit-box-shadow:$top $left $blur $color $inset;
-moz-box-shadow:$top $left $blur $color $inset;
box-shadow:$top $left $blur $color $inset;
}
}
Hope it helps!
package join;
public class ThreadJoinApp {
Thread th = new Thread("Thread 1") {
public void run() {
System.out.println("Current thread execution - " + Thread.currentThread().getName());
for (int i = 0; i < 10; i++) {
System.out.println("Current thread execution - " + Thread.currentThread().getName() + " at index - " + i);
}
}
};
Thread th2 = new Thread("Thread 2") {
public void run() {
System.out.println("Current thread execution - " + Thread.currentThread().getName());
//Thread 2 waits until the thread 1 successfully completes.
try {
th.join();
} catch( InterruptedException ex) {
System.out.println("Exception has been caught");
}
for (int i = 0; i < 10; i++) {
System.out.println("Current thread execution - " + Thread.currentThread().getName() + " at index - " + i);
}
}
};
public static void main(String[] args) {
ThreadJoinApp threadJoinApp = new ThreadJoinApp();
threadJoinApp.th.start();
threadJoinApp.th2.start();
}
//Happy coding -- Parthasarathy S
}
This is a shorter and hopefully clearer answer... Yes, the endpoint is the URL where your service can be accessed by a client application. The same web service can have multiple endpoints, for example in order to make it available using different protocols.
I had the same issue. I came up with a simple solution. Use fragment .replace
instead of fragment .add
. Replacing fragment doing the same thing as adding fragment and then removing it manually.
getFragmentManager().beginTransaction().replace(fragment).commit();
instead of
getFragmentManager().beginTransaction().add(fragment).commit();
Actually you have three steps because the local branch has a duplicate on the server so we have one step for local on two steps on the server:
git branch -m <old-branch-name> <new-branch-name>
git push <remote-name[origin by default]> :<old-branch-name>
git push -u <new-branch-name>
Just my two cents to this very old question. I would highly recommend taking a look at ElasticSearch.
Elasticsearch is a search server based on Lucene. It provides a distributed, multitenant-capable full-text search engine with a RESTful web interface and schema-free JSON documents. Elasticsearch is developed in Java and is released as open source under the terms of the Apache License.
The advantages over other FTS (full text search) Engines are:
We are using this search engine at our project and very happy with it.
If you are helpless like me, try this:
List all Sub-Modules of "Serial" (or whatever package you are having trouble with) with the method described here: List all the modules that are part of a python package
In my case, the problems solved one after the other.
...looks like a bug to me...
include math.h and compile with gcc test.c -lm
For those who still might be facing issue adding jsx to test fixed it for me
test: /\.jsx?$/,
As I posted on http://thinkinginsoftware.blogspot.com/2017/12/correctly-generate-csv-that-excel-can.html:
Tell the software developer in charge of generating the CSV to correct it. As a quick workaround you can use gsed to insert the UTF-8 BOM at the beginning of the string:
gsed -i '1s/^\(\xef\xbb\xbf\)\?/\xef\xbb\xbf/' file.csv
This command inserts the UTF-4 BOM if not present. Therefore it is an idempotent command. Now you should be able to double click the file and open it in Excel.
This will prefix your files in their directory.
The ${f%/*}
is the path till the last slash /
-> the directory
The ${f##*/}
is the text without anything before last slash /
-> filename without the path
So that's how it goes:
for f in $(find /directory/ -type f); do
mv -v $f ${f%/*}/$(date +%Y%m%d)_Prefix_${f##*/}
done
Found it! Merge command has a --squash
option
git checkout master
git merge --squash WIP
at this point everything is merged, possibly conflicted, but not committed. So I can now:
git add .
git commit -m "Merged WIP"
PHP does not have permissions to write on /tmp directory. You need to use chmod
command to open /tmp permissions.
you don’t need a select … from dual
, just write:
SELECT t.*, dbms_random.value(1,9) RandomNumber
FROM myTable t
They are successive, improved versions of the same product. Anyone noticed how the names of the last three and the next release are in alphabetical order (Galileo, Helios, Indigo, Juno)? This is probably how they will go in the future, in the same way that Ubuntu release codenames increase alphabetically (note Indigo is not a moon of Jupiter!).
If you want to wait for all tasks to complete, use the shutdown
method instead of wait
. Then follow it with awaitTermination
.
Also, you can use Runtime.availableProcessors
to get the number of hardware threads so you can initialize your threadpool properly.
You can use strlen. Size is determined by the terminating null-character, so passed string should be valid.
If you want to get size of memory buffer, that contains your string, and you have pointer to it:
sizeof
to get its size.If you are confused about difference between dynamic and static arrays, check this.
Simply remove the line that rotates it one degree at a time and calls the script forever.
// Animate rotation with a recursive call
setTimeout(function() { rotate(++degree); },65);
Then pass the desired value into the function... in this example 45
for 45 degrees.
$(function() {
var $elie = $("#bkgimg");
rotate(45);
function rotate(degree) {
// For webkit browsers: e.g. Chrome
$elie.css({ WebkitTransform: 'rotate(' + degree + 'deg)'});
// For Mozilla browser: e.g. Firefox
$elie.css({ '-moz-transform': 'rotate(' + degree + 'deg)'});
}
});
Change .css()
to .animate()
in order to animate the rotation with jQuery. We also need to add a duration for the animation, 5000 for 5 seconds. And updating your original function to remove some redundancy and support more browsers...
$(function() {
var $elie = $("#bkgimg");
rotate(45);
function rotate(degree) {
$elie.animate({
'-webkit-transform': 'rotate(' + degree + 'deg)',
'-moz-transform': 'rotate(' + degree + 'deg)',
'-ms-transform': 'rotate(' + degree + 'deg)',
'-o-transform': 'rotate(' + degree + 'deg)',
'transform': 'rotate(' + degree + 'deg)',
'zoom': 1
}, 5000);
}
});
EDIT: The standard jQuery CSS animation code above is not working because apparently, jQuery .animate()
does not yet support the CSS3 transforms
.
This jQuery plugin is supposed to animate the rotation:
In my string I have Thai characters (TIS620 encoded) and German umlauts. The answer from agiles put me on the right path. Instead of .getBytes() I use now
int len = mString.length(); // Length of the string
byte[] dataset = new byte[len];
for (int i = 0; i < len; ++i) {
char c = mString.charAt(i);
dataset[i]= (byte) c;
}
You can try with Directory.GetFiles and fix your pattern
string[] files = Directory.GetFiles(@"c:\", "*.txt");
foreach (string file in files)
{
File.Copy(file, "....");
}
Or Move
foreach (string file in files)
{
File.Move(file, "....");
}
Some notes of my experience converting Mercurial to Git.
Using hg-fast-export failed and I needed --force as noted above. Next I got this error:
error: cannot lock ref 'refs/heads/stable': 'refs/heads/stable/sub-branch-name' exists; cannot create 'refs/heads/stable'
Upon completion of the hg-fast-export I ended up with an amputated repo. I think that this repo had a good few orphaned branches and that hg-fast-export needs a somewhat idealised repo. This all seemed a bit rough around the edges, so I moved on to Kiln Harmony (http://blog.fogcreek.com/announcing-kiln-harmony-the-future-of-dvcs/)
Kiln Harmony does not appear to exist on a free tier account as suggested above. I could choose between Git-only and Mercurial-only repos and there is no option to switch. I raised a support ticket and will share the result if they reply.
The Hg-Git mercurial plugin (http://hg-git.github.io/) did work for me. FYI on Mac OSX I installed hg-git via macports as follows:
.hgrc needs these lines:
[ui]
username = Name Surname <[email protected]>
[extensions]
hgext.bookmarks =
hggit =
I then had success with:
hg push git+ssh://[email protected]:myaccount/myrepo.git
All the above are blunt instruments and I only pushed ahead because it took enough time to get the team to use git properly.
Upon first pushing the project per (3) I ended up with all new changes missing. This is because this line of code must be viewed as a guide only:
$ hg bookmark -r default master # make a bookmark of master for default, so a ref gets created
The theory is that the default branch can be deemed to be master when pushing to git, and in my case I inherited a repo where they used 'stable' as the equivalent of master. Moreover, I also discovered that the tip of the repo was a hotfix not yet merged with the 'stable' branch.
Without properly understanding both Mercurial and the repo to be converted, you are probably better off not doing the conversion.
I did the following in order to get the repo ready for a second conversion attempt:
hg update -C stable
hg merge stable/hotfix-feature
hg ci -m "Merge with stable branch"
hg push git+ssh://[email protected]:myaccount/myrepo.git
After this I had a verifiably equivalent project in git, however all the orphaned branches I mentioned earlier are gone. I don't think that is too serious, but I may well live to regret this as an oversight. Therefore my final thought is to keep the original anyway.
Edit: If you just want the latest commit in git, this is simpler than the above merge:
hg book -r tip master
hg push git+ssh://[email protected]:myaccount/myrepo.git
I think that the Import-Module
is trying to find the module in the default directory C:\Windows\System32\WindowsPowerShell\v1.0\Modules
.
Try to put the full path, or copy it to C:\Windows\System32\WindowsPowerShell\v1.0\Modules
$("video").prop('muted', true); //mute
AND
$("video").prop('muted', false); //unmute
See all events here
(side note: use attr
if in jQuery < 1.6)
I get very nervous when I see people using very large rule sets (e.g., on the order of thousands of rules in a single rule set). This often happens when the rules engine is a singleton sitting in the center of the enterprise in the hope that keeping rules DRY will make them accessible to many apps that require them. I would defy anyone to tell me that a Rete rules engine with that many rules is well-understood. I'm not aware of any tools that can check to ensure that conflicts don't exist.
I think partitioning rules sets to keep them small is a better option. Aspects can be a way to share a common rule set among many objects.
I prefer a simpler, more data driven approach wherever possible.
In Java 9
you can use:
List<String> list = List.of("Hello", "World", "from", "Java");
List<Integer> list = List.of(1, 2, 3, 4, 5);
This worked for me, none of the above worked.
.modal-dialog{
position: relative;
display: table; /* This is important */
overflow-y: auto;
overflow-x: auto;
width: auto;
min-width: 300px;
}
SWIFT4 - Easy and elegant way of decoding JSON strings to Struct.
First step - encode String to Data with .utf8 encoding.
Than decode your Data to YourDataStruct.
struct YourDataStruct: Codable {
let type, id: String
init(_ json: String, using encoding: String.Encoding = .utf8) throws {
guard let data = json.data(using: encoding) else {
throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
}
try self.init(data: data)
}
init(data: Data) throws {
self = try JSONDecoder().decode(YourDataStruct.self, from: data)
}
}
do { let successResponse = try WSDeleteDialogsResponse(response) }
} catch {}
In Java 8, there is a new Date/Time API JSR 310 that is more sane. The spec lead is the same as the primary author of JodaTime and they share many similar concepts and patterns.
If you're pulling this value directly from a SQL Database and the value is null in there, it will actually be the DBNull
object rather than null. Either place a check prior to your conversion & use a default value in the event of DBNull
, or replace your null check afterwards with a check on rdrSelect[23]
for DBNull
.
Countercheck if boostrap/cache/config.php
database details are correct. That should give you an hint if they are.
If they are not, then you need to clear the cache using the following steps :
rm -fr bootstrap/cache/*
php artisan optimize
it seems that you should set your command as an String[]
,for example:
String[] command = new String[]{"rmiregistry","2020"};
Runtime.getRuntime().exec(command);
it just like the style of main(String[] args)
.
Change your And
s to AndAlso
s
A standard And
will test both expressions. If comp.Container
is Nothing
, then the second expression will raise a NullReferenceException
because you're accessing a property on a null object.
AndAlso
will short-circuit the logical evaluation. If comp.Container
is Nothing
, then the 2nd expression will not be evaluated.
We recently encountered this error, root cause turned out to be an expired SSL cert on the IIS server. The Load Balancer (infront of our web tier) found the SSL expired, and instead of handling the HTTP traffic over to one of the IIS servers, started showing this error. So basically IIS unable to server requests, for a totally different reason :)
Similar to Alexandrin's answer, but using $state rather than $route:
(From JimTheDev's SO answer here.)
$scope.reloadState = function() {
$state.go($state.current, {}, {reload: true});
}
<a ng-click="reloadState()" ...
Other have hit this one on the head:
main(int argc, char **argv)
give you direct access to the command line (after it has been mangled and tokenized by the shell)getopt()
and getopt_long()
but as you've seen the code to use them is a bit wordy, and quite idomatic. I generally push it out of view with something like:
typedef
struct options_struct {
int some_flag;
int other_flage;
char *use_file;
} opt_t;
/* Parses the command line and fills the options structure,
* returns non-zero on error */
int parse_options(opt_t *opts, int argc, char **argv);
Then first thing in main:
int main(int argc, char **argv){
opt_t opts;
if (parse_options(&opts,argc,argv)){
...
}
...
}
Or you could use one of the solutions suggested in Argument-parsing helpers for C/UNIX.
I would grab date.js or else you will need to roll your own formatting function.
#pragma comment
is a compiler directive which indicates Visual C++ to leave a comment in the generated object file. The comment can then be read by the linker when it processes object files.
#pragma comment(lib, libname)
tells the linker to add the 'libname' library to the list of library dependencies, as if you had added it in the project properties at Linker->Input->Additional dependencies
See #pragma comment on MSDN
Need to set the foreign key option as on delete cascade... in tables which contains foreign key columns.... It need to set at the time of table creation or add later using ALTER table
The only way I've seen it done is if you do this:
for /f "delims=" %a in ('ver') do @set foobar=%a
ver
is the version command for Windows and on my system it produces:
Microsoft Windows [Version 6.0.6001]
I know this question is aged, still, I would like to contribute.
Applying Range.NumberFormat = "@"
just partially solve the problem:
Applying the apostroph behave better. It sets the format to text, it align data to left and if you check the format of the value in the cell using the type formula, it will return 2 meaning text
I think this image is pretty good to understand the concept better!
for more detail understanding please go though below link:
A URL of the form https://github.com/<owner>/<project>/commit/<hash>
will show you the changes introduced in that commit. For example here's a recent bugfix I made to one of my projects on GitHub:
https://github.com/jerith666/git-graph/commit/35e32b6a00dec02ae7d7c45c6b7106779a124685
You can also shorten the hash to any unique prefix, like so:
https://github.com/jerith666/git-graph/commit/35e32b
I know you just asked about GitHub, but for completeness: If you have the repository checked out, from the command line, you can achieve basically the same thing with either of these commands (unique prefixes work here too):
git show 35e32b6a00dec02ae7d7c45c6b7106779a124685
git log -p -1 35e32b6a00dec02ae7d7c45c6b7106779a124685
Note: If you shorten the commit hash too far, the command line gives you a helpful disambiguation message, but GitHub will just return a 404.
To revert a merge commit, you need to use: git revert -m <parent number>
. So for example, to revert the recent most merge commit using the parent with number 1 you would use:
git revert -m 1 HEAD
To revert a merge commit before the last commit, you would do:
git revert -m 1 HEAD^
Use git show <merge commit SHA1>
to see the parents, the numbering is the order they appear e.g. Merge: e4c54b3 4725ad2
git merge documentation: http://schacon.github.com/git/git-merge.html
git merge discussion (confusing but very detailed): http://schacon.github.com/git/howto/revert-a-faulty-merge.txt
A parent ViewGroup into which the fragment's View is to be inserted,
A third boolean telling whether the fragment's View as inflated from the layout XML file should be inserted into the parent ViewGroup.
In this case we pass false because the View will be attached to the parent ViewGroup elsewhere, by some of the Android code we call (in other words, behind our backs). When you pass false as last parameter to inflate(), the parent ViewGroup is still used for layout calculations of the inflated View, so you cannot pass null as parent ViewGroup .
View rootView = inflater.inflate(R.layout.fragment_photos, container, false);
So, You need to call rootView
in here
ListView lv = (ListView)rootView.findViewById(R.id.lv_contact);
What database are you connecting to? I know Oracle can be picky about date formats and likes ISO 8601 format.
**Note: Oops, I just read you are on MySQL. Just format the date and try it as a separate direct SQL call to test.
In Python, you can get an ISO date like
now.isoformat()
For instance, Oracle likes dates like
insert into x values(99, '31-may-09');
Depending on your database, if it is Oracle you might need to TO_DATE it:
insert into x
values(99, to_date('2009/05/31:12:00:00AM', 'yyyy/mm/dd:hh:mi:ssam'));
The general usage of TO_DATE is:
TO_DATE(<string>, '<format>')
If using another database (I saw the cursor and thought Oracle; I could be wrong) then check their date format tools. For MySQL it is DATE_FORMAT() and SQL Server it is CONVERT.
Also using a tool like SQLAlchemy will remove differences like these and make your life easy.
I think that you should make the reference to your config file
26399:C 16 Jan 08:51:13.413 # Warning: no config file specified, using the default config. In order to specify a config file use ./redis-server /path/to/redis.conf
you can try to start your redis server like
./redis-server /path/to/redis-stable/redis.conf
The Distinct()
is going to mess up the ordering, so you'll have to the sorting after that.
var uniqueColors =
(from dbo in database.MainTable
where dbo.Property == true
select dbo.Color.Name).Distinct().OrderBy(name=>name);
I used Jessica's solution (which was edited by Josh) to get outerHTML to work on Firefox. The problem however is that my code was breaking because her solution wrapped the element into a DIV. Adding one more line of code solved that problem.
The following code gives you the outerHTML leaving the DOM tree unchanged.
$jq.fn.outerHTML = function() {
if ($jq(this).attr('outerHTML'))
return $jq(this).attr('outerHTML');
else
{
var content = $jq(this).wrap('<div></div>').parent().html();
$jq(this).unwrap();
return content;
}
}
And use it like this: $("#myDiv").outerHTML();
Hope someone finds it useful!
There's no easy way to find out the memory size of a python object. One of the problems you may find is that Python objects - like lists and dicts - may have references to other python objects (in this case, what would your size be? The size containing the size of each object or not?). There are some pointers overhead and internal structures related to object types and garbage collection. Finally, some python objects have non-obvious behaviors. For instance, lists reserve space for more objects than they have, most of the time; dicts are even more complicated since they can operate in different ways (they have a different implementation for small number of keys and sometimes they over allocate entries).
There is a big chunk of code (and an updated big chunk of code) out there to try to best approximate the size of a python object in memory.
You may also want to check some old description about PyObject (the internal C struct that represents virtually all python objects).
Open the application by name:
open -a 'Atom' FILENAME
In short, yes, the order is preserved. In long:
In general the following definitions will always apply to objects like lists:
A list is a collection of elements that can contain duplicate elements and has a defined order that generally does not change unless explicitly made to do so. stacks and queues are both types of lists that provide specific (often limited) behavior for adding and removing elements (stacks being LIFO, queues being FIFO). Lists are practical representations of, well, lists of things. A string can be thought of as a list of characters, as the order is important ("abc" != "bca"
) and duplicates in the content of the string are certainly permitted ("aaa"
can exist and != "a"
).
A set is a collection of elements that cannot contain duplicates and has a non-definite order that may or may not change over time. Sets do not represent lists of things so much as they describe the extent of a certain selection of things. The internal structure of set, how its elements are stored relative to each other, is usually not meant to convey useful information. In some implementations, sets are always internally sorted; in others the ordering is simply undefined (usually depending on a hash function).
Collection is a generic term referring to any object used to store a (usually variable) number of other objects. Both lists and sets are a type of collection. Tuples and Arrays are normally not considered to be collections. Some languages consider maps (containers that describe associations between different objects) to be a type of collection as well.
This naming scheme holds true for all programming languages that I know of, including Python, C++, Java, C#, and Lisp (in which lists not keeping their order would be particularly catastrophic). If anyone knows of any where this is not the case, please just say so and I'll edit my answer. Note that specific implementations may use other names for these objects, such as vector in C++ and flex in ALGOL 68 (both lists; flex is technically just a re-sizable array).
If there is any confusion left in your case due to the specifics of how the +
sign works here, just know that order is important for lists and unless there is very good reason to believe otherwise you can pretty much always safely assume that list operations preserve order. In this case, the +
sign behaves much like it does for strings (which are really just lists of characters anyway): it takes the content of a list and places it behind the content of another.
If we have
list1 = [0, 1, 2, 3, 4]
list2 = [5, 6, 7, 8, 9]
Then
list1 + list2
Is the same as
[0, 1, 2, 3, 4] + [5, 6, 7, 8, 9]
Which evaluates to
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Much like
"abdcde" + "fghijk"
Produces
"abdcdefghijk"
I Know this is a old question, and Pawel has given the correct answer, I just wanted to show a code example of how to do some string processing, and avoid an extra class for the list of a primitive type.
public class Test
{
public Test()
{
_strings = new List<string>
{
"test",
"test2",
"test3",
"test4"
};
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
private List<String> _strings { get; set; }
public List<string> Strings
{
get { return _strings; }
set { _strings = value; }
}
[Required]
public string StringsAsString
{
get { return String.Join(',', _strings); }
set { _strings = value.Split(',').ToList(); }
}
}
Won't running this in the background do it?
#!/bin/sh
while [ 1 ]; do
echo "Hell yeah!" &
sleep 15
done
This is about as efficient as it gets. The important part only gets executed every 15 seconds and the script sleeps the rest of the time (thus not wasting cycles).
Use the -printcert
command like this:
keytool -printcert -file certificate.pem
You can also use the Get-Counter cmdlet (PowerShell 2.0):
Get-Counter '\Memory\Available MBytes'
Get-Counter '\Processor(_Total)\% Processor Time'
To get a list of memory counters:
Get-Counter -ListSet *memory* | Select-Object -ExpandProperty Counter
The answer above is kind of correct, you can't gracefully control how much native memory a java process allocates. It depends on what your application is doing.
That said, depending on platform, you may be able to do use some mechanism, ulimit for example, to limit the size of a java or any other process.
Just don't expect it to fail gracefully if it hits that limit. Native memory allocation failures are much harder to handle than allocation failures on the java heap. There's a fairly good chance the application will crash but depending on how critical it is to the system to keep the process size down that might still suit you.
Self invoking anonymous function (SIAF)
Self-invoking functions runs instantly, even if DOM isn't completely ready.
Assume your file looks like this and is named test.txt (space delimited):
1 2
3 4
5 6
7 8
Then:
#!/usr/bin/python
import numpy as np
import matplotlib.pyplot as plt
with open("test.txt") as f:
data = f.read()
data = data.split('\n')
x = [row.split(' ')[0] for row in data]
y = [row.split(' ')[1] for row in data]
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.set_title("Plot title...")
ax1.set_xlabel('your x label..')
ax1.set_ylabel('your y label...')
ax1.plot(x,y, c='r', label='the data')
leg = ax1.legend()
plt.show()
I find that browsing the gallery of plots on the matplotlib site helpful for figuring out legends and axes labels.
SQL Server 2012 introduces the eomonth
function:
select eomonth('2013-05-31 00:00:00:000')
-->
2013-05-31
If you have UTF8, use this (actually works with SVG source), like:
btoa(unescape(encodeURIComponent(str)))
example:
var imgsrc = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(markup)));
var img = new Image(1, 1); // width, height values are optional params
img.src = imgsrc;
If you need to decode that base64, use this:
var str2 = decodeURIComponent(escape(window.atob(b64)));
console.log(str2);
Example:
var str = "äöüÄÖÜçéèñ";
var b64 = window.btoa(unescape(encodeURIComponent(str)))
console.log(b64);
var str2 = decodeURIComponent(escape(window.atob(b64)));
console.log(str2);
Note: if you need to get this to work in mobile-safari, you might need to strip all the white-space from the base64 data...
function b64_to_utf8( str ) {
str = str.replace(/\s/g, '');
return decodeURIComponent(escape(window.atob( str )));
}
2017 Update
This problem has been bugging me again.
The simple truth is, atob doesn't really handle UTF8-strings - it's ASCII only.
Also, I wouldn't use bloatware like js-base64.
But webtoolkit does have a small, nice and very maintainable implementation:
/**
*
* Base64 encode / decode
* http://www.webtoolkit.info
*
**/
var Base64 = {
// private property
_keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
// public method for encoding
, encode: function (input)
{
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = Base64._utf8_encode(input);
while (i < input.length)
{
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2))
{
enc3 = enc4 = 64;
}
else if (isNaN(chr3))
{
enc4 = 64;
}
output = output +
this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
} // Whend
return output;
} // End Function encode
// public method for decoding
,decode: function (input)
{
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < input.length)
{
enc1 = this._keyStr.indexOf(input.charAt(i++));
enc2 = this._keyStr.indexOf(input.charAt(i++));
enc3 = this._keyStr.indexOf(input.charAt(i++));
enc4 = this._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64)
{
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64)
{
output = output + String.fromCharCode(chr3);
}
} // Whend
output = Base64._utf8_decode(output);
return output;
} // End Function decode
// private method for UTF-8 encoding
,_utf8_encode: function (string)
{
var utftext = "";
string = string.replace(/\r\n/g, "\n");
for (var n = 0; n < string.length; n++)
{
var c = string.charCodeAt(n);
if (c < 128)
{
utftext += String.fromCharCode(c);
}
else if ((c > 127) && (c < 2048))
{
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else
{
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
} // Next n
return utftext;
} // End Function _utf8_encode
// private method for UTF-8 decoding
,_utf8_decode: function (utftext)
{
var string = "";
var i = 0;
var c, c1, c2, c3;
c = c1 = c2 = 0;
while (i < utftext.length)
{
c = utftext.charCodeAt(i);
if (c < 128)
{
string += String.fromCharCode(c);
i++;
}
else if ((c > 191) && (c < 224))
{
c2 = utftext.charCodeAt(i + 1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else
{
c2 = utftext.charCodeAt(i + 1);
c3 = utftext.charCodeAt(i + 2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
} // Whend
return string;
} // End Function _utf8_decode
}
https://www.fileformat.info/info/unicode/utf8.htm
For any character equal to or below 127 (hex 0x7F), the UTF-8 representation is one byte. It is just the lowest 7 bits of the full unicode value. This is also the same as the ASCII value.
For characters equal to or below 2047 (hex 0x07FF), the UTF-8 representation is spread across two bytes. The first byte will have the two high bits set and the third bit clear (i.e. 0xC2 to 0xDF). The second byte will have the top bit set and the second bit clear (i.e. 0x80 to 0xBF).
For all characters equal to or greater than 2048 but less that 65535 (0xFFFF), the UTF-8 representation is spread across three bytes.
I prefer RENAME rather than DELETE
All my branches are named in the form of
Fix/fix-<somedescription>
or Ftr/ftr-<somedescription>
or Using Tower as my git front end, it neatly organizes all the Ftr/
, Fix/
, Test/
etc. into folders.
Once I am done with a branch, I rename them to Done/...-<description>
.
That way they are still there (which can be handy to provide history) and I can always go back knowing what it was (feature, fix, test, etc.)
UPDATE: this only tested with server side rendering ( universal Javascript ) here is my boilerplate.
With only file-loader you can load images dynamically - the trick is to use ES6 template strings so that Webpack can pick it up:
This will NOT work. :
const myImg = './cute.jpg'
<img src={require(myImg)} />
To fix this, just use template strings instead :
const myImg = './cute.jpg'
<img src={require(`${myImg}`)} />
webpack.config.js :
var HtmlWebpackPlugin = require('html-webpack-plugin')
var ExtractTextWebpackPlugin = require('extract-text-webpack-plugin')
module.exports = {
entry : './src/app.js',
output : {
path : './dist',
filename : 'app.bundle.js'
},
plugins : [
new ExtractTextWebpackPlugin('app.bundle.css')],
module : {
rules : [{
test : /\.css$/,
use : ExtractTextWebpackPlugin.extract({
fallback : 'style-loader',
use: 'css-loader'
})
},{
test: /\.js$/,
exclude: /(node_modules)/,
loader: 'babel-loader',
query: {
presets: ['react','es2015']
}
},{
test : /\.jpg$/,
exclude: /(node_modules)/,
loader : 'file-loader'
}]
}
}
Hi please check the below link
https://www.postgresql.org/docs/current/xfunc-sql.html
EX:
CREATE FUNCTION sum_n_product_with_tab (x int)
RETURNS TABLE(sum int, product int) AS $$
SELECT $1 + tab.y, $1 * tab.y FROM tab;
$$ LANGUAGE SQL;
Swift 5.1
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "What ever you want"
}
You can use strcpy to populate it. You can also initialize it from another struct.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct name {
char first[20];
char last[20];
};
int main() {
struct name sara;
struct name other;
strcpy(sara.first,"Sara");
strcpy(sara.last, "Black");
other = sara;
printf("struct: %s\t%s\n", sara.first, sara.last);
printf("other struct: %s\t%s\n", other.first, other.last);
}
Java9 uses byte[] to store String.value, so you can only get about 1GB Strings in Java9. Java8 on the other hand can have 2GB Strings.
By character I mean "char"s, some character is not representable in BMP(like some of the emojis), so it will take more(currently 2) chars.
The example code is:
in main
square(width,function (data)
{
console.log(data.squareVal);
});
using the following may works
exports.square = function(width,callback)
{
var aa = new Object();
callback(aa.squareVal = width * width);
}
Just unset the node:
$str = <<<STR
<a>
<b>
<c>
</c>
</b>
</a>
STR;
$xml = simplexml_load_string($str);
unset($xml –> a –> b –> c); // this would remove node c
echo $xml –> asXML(); // xml document string without node c
This code was taken from How to delete / remove nodes in SimpleXML.
There is another way, but...
DO NOT DO THIS IF YOU DO NOT WANT YOUR PASSWORD IN THE SCRIPT FILE (It isn't a good idea to store passwords in scripts, but some of us just like to know how.)
Ok, that was the warning, here's the code:
$username = "John Doe"
$password = "ABCDEF"
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr
$cred
will have the credentials from John Doe with the password "ABCDEF".
Alternative means to get the password ready for use:
$password = convertto-securestring -String "notverysecretpassword" -AsPlainText -Force
The most elegant solution to this problem is here.
Original answer remains, but this is a messy solution:
If you want to change the PYTHONPATH
used in a virtualenv, you can add the following line to your virtualenv's bin/activate
file:
export PYTHONPATH="/the/path/you/want"
This way, the new PYTHONPATH
will be set each time you use this virtualenv.
EDIT: (to answer @RamRachum's comment)
To have it restored to its original value on deactivate
, you could add
export OLD_PYTHONPATH="$PYTHONPATH"
before the previously mentioned line, and add the following line to your bin/postdeactivate
script.
export PYTHONPATH="$OLD_PYTHONPATH"
The line in the theme style works fine, yet that replaces the animation with a white screen. Especially on a slower phone - it is really annoying. So, if you want an instant transition - you could use this in the theme style:
<item name="android:windowAnimationStyle">@null</item>
<item name="android:windowDisablePreview">true</item>
var testCheckbox = document.getElementById("checkbox");
if (!testCheckbox.checked) {
alert("Error Message!!");
}
else {
alert("Success Message!!");
}
For there to be a Smart Cast of the properties, the data type of the property must be the class that contains the method or behavior that you want to access and NOT that the property is of the type of the super class.
Be:
class MyVM : ViewModel() {
fun onClick() {}
}
Solution:
From: private lateinit var viewModel: ViewModel
To: private lateinit var viewModel: MyVM
Usage:
viewModel = ViewModelProvider(this)[MyVM::class.java]
viewModel.onClick {}
GL
I did a benchmark test to try and answer this question, then found this post so here are my findings (which differ slightly from the other answers)
Here is the benchmark code:
require 'benchmark'
h = { abc: 'hello', 'another_key' => 123, 4567 => 'third' }
a = 1..10
many = 500_000
Benchmark.bm do |b|
GC.start
b.report("hash keys collect") do
many.times do
h.keys.collect(&:to_s)
end
end
GC.start
b.report("hash keys map") do
many.times do
h.keys.map(&:to_s)
end
end
GC.start
b.report("array collect") do
many.times do
a.collect(&:to_s)
end
end
GC.start
b.report("array map") do
many.times do
a.map(&:to_s)
end
end
end
And the results I got were:
user system total real
hash keys collect 0.540000 0.000000 0.540000 ( 0.570994)
hash keys map 0.500000 0.010000 0.510000 ( 0.517126)
array collect 1.670000 0.020000 1.690000 ( 1.731233)
array map 1.680000 0.020000 1.700000 ( 1.744398)
Perhaps an alias isn't free?
You can write the query as below:
SELECT * FROM Manager
WHERE managerid LIKE '\_%' escape '\'
AND managername LIKE '%\_%' escape '\';
it will solve your problem.
Raminson has a nice answer if you are already (or don't mind) using jQuery Mobile. If you want a different solution, why not just modify your code as follows:
change that LI you're having trouble with to include an A tag and apply the class there instead of the LI
<!-- This is the main menu -->
<ul class="menu">
<li><a href="/home/">HOME</a></li>
<li><a href="#" class="publications">PUBLICATIONS & PROJECTS</a></li>
<li><a href="/about/">ABOUT</a></li>
<li><a href="/blog/">BLOG</a></li>
<li><a href="/contact/">CONTACT</a></li>
</ul>
And your javascript/jquery code... return false to stop bubbling.
$(document).ready(function(){
$('.publications').click(function() {
$('#filter_wrapper').show();
return false;
});
});
This should work for what you are trying to do.
Also, I noticed your site opens the other links in new tabs/windows, is that intentional?
I also needed the current screen dimension, specifically the Work-area, which returned the rectangle excluding the Taskbar width.
I used it in order to reposition a window, which is opened to the right and down to where the mouse is positioned. Since the window is fairly large, in many cases it got out of the screen bounds. The following code is based on @e-j answer: This will give you the current screen.... The difference is that I also show my repositioning algorithm, which I assume is actually the point.
The code:
using System.Windows;
using System.Windows.Forms;
namespace MySample
{
public class WindowPostion
{
/// <summary>
/// This method adjust the window position to avoid from it going
/// out of screen bounds.
/// </summary>
/// <param name="topLeft">The requiered possition without its offset</param>
/// <param name="maxSize">The max possible size of the window</param>
/// <param name="offset">The offset of the topLeft postion</param>
/// <param name="margin">The margin from the screen</param>
/// <returns>The adjusted position of the window</returns>
System.Drawing.Point Adjust(System.Drawing.Point topLeft, System.Drawing.Point maxSize, int offset, int margin)
{
Screen currentScreen = Screen.FromPoint(topLeft);
System.Drawing.Rectangle rect = currentScreen.WorkingArea;
// Set an offset from mouse position.
topLeft.Offset(offset, offset);
// Check if the window needs to go above the task bar,
// when the task bar shadows the HUD window.
int totalHight = topLeft.Y + maxSize.Y + margin;
if (totalHight > rect.Bottom)
{
topLeft.Y -= (totalHight - rect.Bottom);
// If the screen dimensions exceed the hight of the window
// set it just bellow the top bound.
if (topLeft.Y < rect.Top)
{
topLeft.Y = rect.Top + margin;
}
}
int totalWidth = topLeft.X + maxSize.X + margin;
// Check if the window needs to move to the left of the mouse,
// when the HUD exceeds the right window bounds.
if (totalWidth > rect.Right)
{
// Since we already set an offset remove it and add the offset
// to the other side of the mouse (2x) in addition include the
// margin.
topLeft.X -= (maxSize.X + (2 * offset + margin));
// If the screen dimensions exceed the width of the window
// don't exceed the left bound.
if (topLeft.X < rect.Left)
{
topLeft.X = rect.Left + margin;
}
}
return topLeft;
}
}
}
Some explanations:
1) topLeft - position of the top left at the desktop (works
for multi screens - with different aspect ratio).
Screen1 Screen2
- +-------------------++-------------------+ Screen3
? ¦ ¦¦ ¦+-----------------+ -
¦ ¦ ¦¦ ¦¦ ?- ¦ ?
1080 ¦ ¦ ¦¦ ¦¦ ¦ ¦
¦ ¦ ¦¦ ¦¦ ¦ ¦ 900
? ¦ ¦¦ ¦¦ ¦ ?
- +-------------------++-------------------++-----------------+ -
--------- --------- --------
¦?-----------------?¦¦?-----------------?¦¦?---------------?¦
1920 1920 1440
If the mouse is in Screen3 a possible value might be:
topLeft.X=4140 topLeft.Y=195
2) offset - the offset from the top left, one value for both
X and Y directions.
3) maxSize - the maximal size of the window - including its
size when it is expanded - from the following example
we need maxSize.X = 200, maxSize.Y = 150 - To avoid the expansion
being out of bound.
Non expanded window:
+------------------------------+ -
¦ Window Name [X]¦ ?
+------------------------------¦ ¦
¦ +-----------------+ ¦ ¦ 100
¦ Text1: ¦ ¦ ¦ ¦
¦ +-----------------+ ¦ ¦
¦ [?] ¦ ?
+------------------------------+ -
¦?----------------------------?¦
200
Expanded window:
+------------------------------+ -
¦ Window Name [X]¦ ?
+------------------------------¦ ¦
¦ +-----------------+ ¦ ¦
¦ Text1: ¦ ¦ ¦ ¦
¦ +-----------------+ ¦ ¦ 150
¦ [?] ¦ ¦
¦ +-----------------+ ¦ ¦
¦ Text2: ¦ ¦ ¦ ¦
¦ +-----------------+ ¦ ?
+------------------------------+ -
¦?----------------------------?¦
200
4) margin - The distance the window should be from the screen
work-area - Example:
+-------------------------------------------------------------+ -
¦ ¦ ? Margin
¦ ¦ -
¦ ¦
¦ ¦
¦ ¦
¦ +------------------------------+ ¦
¦ ¦ Window Name [X]¦ ¦
¦ +------------------------------¦ ¦
¦ ¦ +-----------------+ ¦ ¦
¦ ¦ Text1: ¦ ¦ ¦ ¦
¦ ¦ +-----------------+ ¦ ¦
¦ ¦ [?] ¦ ¦
¦ ¦ +-----------------+ ¦ ¦
¦ ¦ Text2: ¦ ¦ ¦ ¦
¦ ¦ +-----------------+ ¦ ¦
¦ +------------------------------+ ¦ -
¦ ¦ ? Margin
+-------------------------------------------------------------¦ -
¦[start] [?][?][?][?] ¦en¦ 12:00 ¦
+-------------------------------------------------------------+
¦?-?¦ ¦?-?¦
Margin Margin
* Note that this simple algorithm will always want to leave the cursor
out of the window, therefor the window will jumps to its left:
+---------------------------------+ +---------------------------------+
¦ ?-+--------------+ ¦ +--------------+?- ¦
¦ ¦ Window [X]¦ ¦ ¦ Window [X]¦ ¦
¦ +--------------¦ ¦ +--------------¦ ¦
¦ ¦ +---+ ¦ ¦ ¦ +---+ ¦ ¦
¦ ¦ Val: ¦ ¦ ¦ -> ¦ ¦ Val: ¦ ¦ ¦ ¦
¦ ¦ +---+ ¦ ¦ ¦ +---+ ¦ ¦
¦ +--------------+ ¦ +--------------+ ¦
¦ ¦ ¦ ¦
+---------------------------------¦ +---------------------------------¦
¦[start] [?][?][?] ¦en¦ 12:00 ¦ ¦[start] [?][?][?] ¦en¦ 12:00 ¦
+---------------------------------+ +---------------------------------+
If this is not a requirement, you can add a parameter to just use
the margin:
+---------------------------------+ +---------------------------------+
¦ ?-+--------------+ ¦ +-?------------+ ¦
¦ ¦ Window [X]¦ ¦ ¦ Window [X]¦ ¦
¦ +--------------¦ ¦ +--------------¦ ¦
¦ ¦ +---+ ¦ ¦ ¦ +---+ ¦ ¦
¦ ¦ Val: ¦ ¦ ¦ -> ¦ ¦ Val: ¦ ¦ ¦ ¦
¦ ¦ +---+ ¦ ¦ ¦ +---+ ¦ ¦
¦ +--------------+ ¦ +--------------+ ¦
¦ ¦ ¦ ¦
+---------------------------------¦ +---------------------------------¦
¦[start] [?][?][?] ¦en¦ 12:00 ¦ ¦[start] [?][?][?] ¦en¦ 12:00 ¦
+---------------------------------+ +---------------------------------+
* Supports also the following scenarios:
1) Screen over screen:
+-----------------+
¦ ¦
¦ ¦
¦ ¦
¦ ¦
+-----------------+
+-------------------+
¦ ¦
¦ ?- ¦
¦ ¦
¦ ¦
¦ ¦
+-------------------+
---------
2) Window bigger than screen hight or width
+---------------------------------+ +---------------------------------+
¦ ¦ ¦ +--------------+ ¦
¦ ¦ ¦ ¦ Window [X]¦ ¦
¦ ?-+------------¦-+ ¦ +--------------¦ ?- ¦
¦ ¦ Window [¦]¦ ¦ ¦ +---+ ¦ ¦
¦ +------------¦-¦ -> ¦ ¦ Val: ¦ ¦ ¦ ¦
¦ ¦ +---+¦ ¦ ¦ ¦ +---+ ¦ ¦
¦ ¦ Val: ¦ ¦¦ ¦ ¦ ¦ +---+ ¦ ¦
¦ ¦ +---+¦ ¦ ¦ ¦ Val: ¦ ¦ ¦ ¦
+---------------------------------¦ ¦ +---------------------------------¦
¦[start] [?][?][?] ¦en¦ 12:00 ¦ ¦ ¦[start] [?][?][?] ¦en¦ 12:00 ¦
+---------------------------------+ ¦ +---------------------------------+
¦ +---+ ¦ ¦ +---+ ¦
¦ Val: ¦ ¦ ¦ +--------------+
¦ +---+ ¦
+--------------+
+---------------------------------+ +---------------------------------+
¦ ¦ ¦ ¦
¦ ¦ ¦ +-------------------------------¦---+
¦ ?-+--------------------------¦--------+ ¦ ¦ W?-dow ¦[X]¦
¦ ¦ Window ¦ [X]¦ ¦ +-------------------------------¦---¦
¦ +--------------------------¦--------¦ ¦ ¦ +---+ +---+ +-¦-+ ¦
¦ ¦ +---+ +---+ ¦ +---+ ¦ -> ¦ ¦ Val: ¦ ¦ Val: ¦ ¦ Val: ¦ ¦ ¦ ¦
¦ ¦ Val: ¦ ¦ Val: ¦ ¦ Va¦: ¦ ¦ ¦ ¦ ¦ +---+ +---+ +-¦-+ ¦
¦ ¦ +---+ +---+ ¦ +---+ ¦ ¦ +-------------------------------¦---+
+---------------------------------¦--------+ +---------------------------------¦
¦[start] [?][?][?] ¦en¦ 12:00 ¦ ¦[start] [?][?][?] ¦en¦ 12:00 ¦
+---------------------------------+ +---------------------------------+
<remark><code>...</code></remark>
This might be of some help: http://www.webmasterworld.com/forum83/200.htm
A relevant quote:
Most attempts to accomplish this were made by assigning the property and value: div{height:100%} - this alone will not work. The reason is that without a parent defined height, the div{height:100%;} has nothing to factor 100% percent of, and will default to a value of div{height:auto;} - auto is an "as needed value" which is governed by the actual content, so that the div{height:100%} will a=only extend as far as the content demands.
The solution to the problem is found by assigning a height value to the parent container, in this case, the body element. Writing your body stlye to include height 100% supplies the needed value.
html, body { margin:0; padding:0; height:100%; }
Another method is to use HTML5's Application Cache to download all files once and keep them in the browser's cache. The above link contains much more information. The following information is from the article:
Change your <html>
tag to include a manifest
attribute:
<html manifest="http://www.example.com/example.mf">
A manifest file must be served with the mime-type text/cache-manifest
.
A simple manifest looks something like this:
CACHE MANIFEST
index.html
stylesheet.css
images/logo.png
scripts/main.js
http://cdn.example.com/scripts/main.js
Once an application is offline it remains cached until one of the following happens:
String user = request.getParameter("uname");
out.println(user);
String pass = request.getParameter("pass");
out.println(pass);
Class.forName( "com.mysql.jdbc.Driver" );
Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/rental","root","root" ) ;
out.println("hello");
Statement st = conn.createStatement();
String sql = "insert into login (user,pass) values('" + user + "','" + pass + "')";
st.executeUpdate(sql);
You need to get the time when the application starts, and compare that to the time when the application ends.
Wen the app starts:
Calendar calendar = Calendar.getInstance();
// Get start time (this needs to be a global variable).
Date startDate = calendar.getTime();
When the application ends
Calendar calendar = Calendar.getInstance();
// Get start time (this needs to be a global variable).
Date endDate = calendar.getTime();
To get the difference (in millseconds), do this:
long sumDate = endDate.getTime() - startDate.getTime();
Enable the port in your system it is for CentOS 7 flow the commands below
1.firewall-cmd --get-active-zones
2.firewall-cmd --zone=dmz --add-port=50070/tcp --permanent
3.firewall-cmd --zone=public --add-port=50070/tcp --permanent
4.firewall-cmd --zone=dmz --add-port=9000/tcp --permanent
5.firewall-cmd --zone=public --add-port=9000/tcp --permanent 6.firewall-cmd --reload
Dates in the
m/d/y
ord-m-y
formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/
), then the Americanm/d/y
is assumed; whereas if the separator is a dash (-
) or a dot (.
), then the Europeand-m-y
format is assumed. Check more here.
Use the default date function.
$var = "20/04/2012";
echo date("Y-m-d", strtotime($var) );
EDIT I just tested it, and somehow, PHP doesn't work well with dd/mm/yyyy format. Here's another solution.
$var = '20/04/2012';
$date = str_replace('/', '-', $var);
echo date('Y-m-d', strtotime($date));
Essentially, an operating system's windowing system exposes some API calls that you can perform to do jobs like create a window, or put a button on the window. Basically, you get a suite of header files and you can call functions in those imported libraries, just like you'd do with stdlib and printf
.
Each operating system comes with its own GUI toolkit, suite of header files, and API calls, and their own way of doing things. There are also cross platform toolkits like GTK, Qt, and wxWidgets that help you build programs that work anywhere. They achieve this by having the same API calls on each platform, but a different implementation for those API functions that call down to the native OS API calls.
One thing they'll all have in common, which will be different from a CLI program, is something called an event loop. The basic idea there is somewhat complicated, and difficult to compress, but in essence it means that not a hell of a lot is going in in your main class/main function, except:
There are plenty of resources about event based programming. If you have any experience with JavaScript, it's the same basic idea, except that you, the scripter have no access or control over the event loop itself, or what events there are, your only job is to write and register handlers.
You should keep in mind that GUI programming is incredibly complicated and difficult, in general. If you have the option, it's actually much easier to just integrate an embedded webserver into your program and have an HTML/web based interface. The one exception that I've encountered is Apple's Cocoa+Xcode +interface builder + tutorials that make it easily the most approachable environment for people new to GUI programming that I've seen.
window.location.href, this as saved my life in webview from Android 5.1. The page don't reload with location.reload() in this version from Android.
Exactly as arrays in all C-like languages. The indexes start from 0. So, apple is 0, banana is 1, orange is 2 etc.
Not so much an answer as a cautionary tale: this was bugging me as well - and I thought I had a solution by pre-pending a zero and using the @(...)
syntax. i.e your code would have been:
var nonID = 0@(nonProID);
var proID = 0@(proID);
Getting output like:
var nonId = 0123;
What I didn't realise was that this is how JavaScript (version 3) represents octal/base-8 numbers and is actually altering the value. Additionally, if you are using the "use strict";
command then it will break your code entirely as octal numbers have been removed.
I'm still looking for a proper solution to this.
The answers given were not totally complete if multiple sourcepath and subpackages have to be processed.
The following command line will process all the packages under com and LOR (lord of the rings) located into /home/rudy/IdeaProjects/demo/src/main/java and /home/rudy/IdeaProjects/demo/src/test/java/
Please note:
rudy@rudy-ThinkPad-T590:~$ javadoc -d /home/rudy/IdeaProjects/demo_doc
-sourcepath /home/rudy/IdeaProjects/demo/src/main/java/
:/home/rudy/IdeaProjects/demo/src/test/java/
-subpackages com:LOR
-private
rudy@rudy-ThinkPad-T590:~/IdeaProjects/demo/src/main/java$ ls -R
.: com LOR
./com: example
./com/example: demo
./com/example/demo: DemowApplication.java
./LOR: Race.java TolkienCharacter.java
rudy@rudy-ThinkPad-T590:~/IdeaProjects/demo/src/test/java$ ls -R
.: com
./com: example
./com/example: demo
./com/example/demo: AssertJTest.java DemowApplicationTests.java
The function here returns the parameter by name. With tiny changes you will be able to return base url, parameter or anchor.
function getUrlParameter(name) {
var urlOld = window.location.href.split('?');
urlOld[1] = urlOld[1] || '';
var urlBase = urlOld[0];
var urlQuery = urlOld[1].split('#');
urlQuery[1] = urlQuery[1] || '';
var parametersString = urlQuery[0].split('&');
if (parametersString.length === 1 && parametersString[0] === '') {
parametersString = [];
}
// console.log(parametersString);
var anchor = urlQuery[1] || '';
var urlParameters = {};
jQuery.each(parametersString, function (idx, parameterString) {
paramName = parameterString.split('=')[0];
paramValue = parameterString.split('=')[1];
urlParameters[paramName] = paramValue;
});
return urlParameters[name];
}
You've been shown PadLeft
and PadRight
. This will fill in the missing PadCenter
.
public static class StringUtils
{
public static string PadCenter(this string s, int width, char c)
{
if (s == null || width <= s.Length) return s;
int padding = width - s.Length;
return s.PadLeft(s.Length + padding / 2, c).PadRight(width, c);
}
}
Note to self: don't forget to update own CV: "One day, I even fixed Joel Coehoorn's code!" ;-D -Serge
You just need to declare a
as a global in thread2
, so that you aren't modifying an a
that is local to that function.
def thread2(threadname):
global a
while True:
a += 1
time.sleep(1)
In thread1
, you don't need to do anything special, as long as you don't try to modify the value of a
(which would create a local variable that shadows the global one; use global a
if you need to)>
def thread1(threadname):
#global a # Optional if you treat a as read-only
while a < 10:
print a
you need only set default value to parameters(you do not need the Route attribute):
public IHttpActionResult Get(string apc = null, string xpc = null, int? sku = null)
{ ... }
Simplest left to right swipe detector:
In your activity class add following attributes:
private float x1,x2;
static final int MIN_DISTANCE = 150;
and override onTouchEvent()
method:
@Override
public boolean onTouchEvent(MotionEvent event)
{
switch(event.getAction())
{
case MotionEvent.ACTION_DOWN:
x1 = event.getX();
break;
case MotionEvent.ACTION_UP:
x2 = event.getX();
float deltaX = x2 - x1;
if (Math.abs(deltaX) > MIN_DISTANCE)
{
Toast.makeText(this, "left2right swipe", Toast.LENGTH_SHORT).show ();
}
else
{
// consider as something else - a screen tap for example
}
break;
}
return super.onTouchEvent(event);
}
Actually Windows does have a utility that encodes and decodes base64 - CERTUTIL
I'm not sure what version of Windows introduced this command.
To encode a file:
certutil -encode inputFileName encodedOutputFileName
To decode a file:
certutil -decode encodedInputFileName decodedOutputFileName
There are a number of available verbs and options available to CERTUTIL.
To get a list of nearly all available verbs:
certutil -?
To get help on a particular verb (-encode for example):
certutil -encode -?
To get complete help for nearly all verbs:
certutil -v -?
Mysteriously, the -encodehex
verb is not listed with certutil -?
or certutil -v -?
. But it is described using certutil -encodehex -?
. It is another handy function :-)
Regarding David Morales' comment, there is a poorly documented type option to the -encodehex
verb that allows creation of base64 strings without header or footer lines.
certutil [Options] -encodehex inFile outFile [type]
A type of 1 will yield base64 without the header or footer lines.
See https://www.dostips.com/forum/viewtopic.php?f=3&t=8521#p56536 for a brief listing of the available type formats. And for a more in depth look at the available formats, see https://www.dostips.com/forum/viewtopic.php?f=3&t=8521#p57918.
Not investigated, but the -decodehex
verb also has an optional trailing type argument.
You just need to have an existing file, open the context menu on your folder , and then choose Add
=> Existing item...
If you have the file already placed within your project structure, but it is not yet included, you can do so by making them visible in the solution explorer
To me, the simplest solution is to add two keys into the plist
You can also use wget to »untar it inline«. Simply specify stdout as the output file (-O -
):
wget --no-check-certificate https://github.com/pinard/Pymacs/tarball/v0.24-beta2 -O - | tar xz
Use the chrome.runtime.id
property from the chrome.runtime API.
Add this tag to your form - onsubmit="return false;"
Then you can only submit your form with some JavaScript function.