I faced the issue with my web application based on Spring 3 and deployed on Weblogic 10.3 on Oracle Linux 6. The solution mentioned at the link did not work for me.
I had to take the following steps - 1. Copy the Arial*.ttf font files to JROCKIT_JAVA_HOME/jre/lib/fonts directory 2. Make entries of the fonts in fontconfig.properties.src 3. Restart the cluster from Weblogic console
filename.Arial=Arial.ttf
filename.Arial_Bold=Arial_Bold.ttf
filename.Arial_Italic=Arial_Italic.ttf
filename.Arial_Bold_Italic=Arial_Bold_Italic.ttf
The strncpy()
function was designed with a very particular problem in mind: manipulating strings stored in the manner of original UNIX directory entries. These used a fixed sized array, and a nul-terminator was only used if the filename was shorter than the array.
That's what's behind the two oddities of strncpy()
:
For a "safer strcpy()
", you are better off using strncat()
like so:
if (dest_size > 0)
{
dest[0] = '\0';
strncat(dest, source, dest_size - 1);
}
That will always nul-terminate the result, and won't copy more than necessary.
I should be like this:
$.post(submitAddress, { 'yourArrayName' : javaScriptArrayToSubmitToServer },
function(response, status, xhr) {
alert("POST returned: \n" + response + "\n\n");
})
Suppose your screen id has a pattern. Then you can use the following code to kill all the attached screen at once.
result=$(screen -ls | grep 'pattern_of_screen_id' -o)
for i in $result;
do
`screen -X -S $i quit`;
done
Try this:
String yourVal = "20.5";
float a = (Float.valueOf(yourVal)).floatValue();
System.out.println(a);
You can also use the |
operator to concatenate two sets (union in set theory):
>>> my_set = {1}
>>> my_set = my_set | {2}
>>> my_set
{1, 2}
Or a shorter form using |=
:
>>> my_set = {1}
>>> my_set |= {2}
>>> my_set
{1, 2}
Note: In versions prior to Python 2.7, use set([...])
instead of {...}
.
As of others have explained how to do it using str_replace
, you can also use regex to achieve this.
$name = preg_replace('/\s+/', '_', $name);
Personally, I prefer to use empty collections instead of null
and have the algorithms work in a way that for the algorithm it does not matter if the collection is empty or not.
If you don't want to use any additional package, you can call the following function before creating your file:
var path = require('path'),
fs = require('fs');
function ensureDirectoryExistence(filePath) {
var dirname = path.dirname(filePath);
if (fs.existsSync(dirname)) {
return true;
}
ensureDirectoryExistence(dirname);
fs.mkdirSync(dirname);
}
To check if packagename
was installed, type:
dpkg -s <packagename>
You can also use dpkg-query
that has a neater output for your purpose, and accepts wild cards, too.
dpkg-query -l <packagename>
To find what package owns the command
, try:
dpkg -S `which <command>`
For further details, see article Find out if package is installed in Linux and dpkg cheat sheet.
Better late than never i suppose... you get the option to set the MASTERPAGE only of you are developing a WEB SITE (FILE>NEW>WEBSITE)... but not when you create an ASP.NET project (FILE>NEW>PROJECT) - there you have to set the Masterpage using the properties of the newly created webform and it's up to you to modify the ASPX source to make it master page compliant (ie, removing the stock HTML, etc...)
Use this to limit the depth to 2:
Get-ChildItem \*\*\*,\*\*,\*
The way it works is that it returns the children at each depth 2,1 and 0.
Explanation:
This command
Get-ChildItem \*\*\*
returns all items with a depth of two subfolders. Adding \* adds an additional subfolder to search in.
In line with the OP question, to limit a recursive search using get-childitem you are required to specify all the depths that can be searched.
I’ve built a function I use all the time for password validation and to create passwords, e.g. to store them in a MySQL database. It uses a randomly generated salt which is way more secure than using a static salt.
function secure_password($user_pwd, $multi) {
/*
secure_password ( string $user_pwd, boolean/string $multi )
*** Description:
This function verifies a password against a (database-) stored password's hash or
returns $hash for a given password if $multi is set to either true or false
*** Examples:
// To check a password against its hash
if(secure_password($user_password, $row['user_password'])) {
login_function();
}
// To create a password-hash
$my_password = 'uber_sEcUrE_pass';
$hash = secure_password($my_password, true);
echo $hash;
*/
// Set options for encryption and build unique random hash
$crypt_options = ['cost' => 11, 'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM)];
$hash = password_hash($user_pwd, PASSWORD_BCRYPT, $crypt_options);
// If $multi is not boolean check password and return validation state true/false
if($multi!==true && $multi!==false) {
if (password_verify($user_pwd, $table_pwd = $multi)) {
return true; // valid password
} else {
return false; // invalid password
}
// If $multi is boolean return $hash
} else return $hash;
}
I would say that one should omit the __init__.py
only if one wants to have the implicit namespace package. If you don't know what it means, you probably don't want it and therefore you should continue to use the __init__.py
even in Python 3.
According to "Hans Vonn" replies.
Adding the following line before making the call resolved the issue:
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
After adding Security protocol and working fine but I have to add before every API call which is not healthy. I just upgrade .net framework version at least 4.6 and working as expected do not require to adding before every API call.
Set the listview adapter to "simple_list_item_multiple_choice"
ArrayAdapter<String> adapter;
List<String> values; // put values in this
//Put in listview
adapter = new ArrayAdapter<UserProfile>(
this,
android.R.layout.simple_list_item_multiple_choice,
values);
setListAdapter(adapter);
You will have to use something like below
#menu ul{_x000D_
list-style: none;_x000D_
}_x000D_
#menu li{_x000D_
display: inline;_x000D_
}_x000D_
_x000D_
<div id="menu">_x000D_
<ul>_x000D_
<li>First menu item</li>_x000D_
<li>Second menu item</li>_x000D_
<li>Third menu item</li>_x000D_
</ul>_x000D_
</div>
_x000D_
For me it was missing MySQL PDO, I recompiled my PHP with the --with-pdo-mysql
option, installed it and restarted apache and it was all working
This image explains normal script tag, async and defer
Async scripts are executed as soon as the script is loaded, so it doesn't guarantee the order of execution (a script you included at the end may execute before the first script file )
Defer scripts guarantees the order of execution in which they appear in the page.
Ref this link : http://www.growingwiththeweb.com/2014/02/async-vs-defer-attributes.html
I found this to be small and complete https://github.com/auth0/java-jwt
To update a layout constraint you only need to update the constant property and call layoutIfNeeded after.
myConstraint.constant = newValue
myView.layoutIfNeeded()
It's simple. On the sender side, use Intent.putExtra
:
Intent myIntent = new Intent(A.this, B.class);
myIntent.putExtra("intVariableName", intValue);
startActivity(myIntent);
On the receiver side, use Intent.getIntExtra
:
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("intVariableName", 0);
Try this.
x = "1"
x is a string because it has quotes around it, but it has a number in it.
x = int(x)
Since x has the number 1 in it, I can turn it in to a integer.
To see if a string is a number, you can do this.
def is_number(var):
try:
if var == int(var):
return True
except Exception:
return False
x = "1"
y = "test"
x_test = is_number(x)
print(x_test)
It should print to IDLE True because x is a number.
y_test = is_number(y)
print(y_test)
It should print to IDLE False because y in not a number.
To chip in a pandas-based solution I use:
import pandas as pd
import numpy as np
def random_date(start, end, position=None):
start, end = pd.Timestamp(start), pd.Timestamp(end)
delta = (end - start).total_seconds()
if position is None:
offset = np.random.uniform(0., delta)
else:
offset = position * delta
offset = pd.offsets.Second(offset)
t = start + offset
return t
I like it, because of the nice pd.Timestamp
features that allow me to throw different stuff and formats at it. Consider the following few examples...
Your signature.
>>> random_date(start="1/1/2008 1:30 PM", end="1/1/2009 4:50 AM", position=0.34)
Timestamp('2008-05-04 21:06:48', tz=None)
Random position.
>>> random_date(start="1/1/2008 1:30 PM", end="1/1/2009 4:50 AM")
Timestamp('2008-10-21 05:30:10', tz=None)
Different format.
>>> random_date('2008-01-01 13:30', '2009-01-01 4:50')
Timestamp('2008-11-18 17:20:19', tz=None)
Passing pandas/datetime objects directly.
>>> random_date(pd.datetime.now(), pd.datetime.now() + pd.offsets.Hour(3))
Timestamp('2014-03-06 14:51:16.035965', tz=None)
$files = scandir('folder/');
foreach($files as $file) {
//do your work here
}
or glob may be even better for your needs:
$files = glob('folder/*.{jpg,png,gif}', GLOB_BRACE);
foreach($files as $file) {
//do your work here
}
The entry point for Java programs is the method:
public static void main(String[] args) {
//Code
}
If you do not have this, your program will not run.
Reviving an old question because it seems to appear at the top of search results.
I wanted to retain transition effects while still being able to style the actionlink so I came up with this solution.
<div class="parent-style-one"> @Html.ActionLink("Homepage", "Home", "Home") </div>
.parent-style-one { /* your styles here */ }
.parent-style-one a { text-decoration: none; }
.parent-style-one a:hover { text-decoration: underline; -webkit-transition-duration: 1.1s; /* Safari */ transition-duration: 1.1s; }
This way I only target the child elements of the div in this case the action link and still be able to apply transition effects.
i find no reason to do this $scope.value = $rootScope.test;
$scope is already prototype inheritance from $rootScope.
Please see this example
var app = angular.module('app',[]).run(function($rootScope){
$rootScope.userName = "Rezaul Hasan";
});
now you can bind this scope variable in anywhere in app tag.
while(in.hasNextLine()) {
lines++;
String line = in.nextLine();
for(int i=0;i<line.length();i++)
{
if(line.charAt(i)!=' ' && line.charAt(i)!='\n')
chars ++;
}
words += new StringTokenizer(line, " ,;:.").countTokens();
}
Googled "Permission denied (publickey). fatal: The remote end hung up unexpectedly", first result an exact SO dupe:
GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly which links here in the accepted answer (from the original poster, no less): http://help.github.com/linux-set-up-git/
If the answers that involve tables or setting line-height don't work for you, you can experiment with wrapping the p element in a div and style its positioning relative to the height of the parent div.
.parent-div{_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background-color: blue;_x000D_
}_x000D_
_x000D_
.text-div{_x000D_
position: relative;_x000D_
top: 50%;_x000D_
transform: translateY(-50%);_x000D_
}_x000D_
_x000D_
p.event_desc{_x000D_
font: bold 12px "Helvetica Neue", Helvetica, Arial, sans-serif;_x000D_
color: white;_x000D_
text-align: center;_x000D_
}
_x000D_
<div class="parent-div">_x000D_
<div class="text-div">_x000D_
<p class="event_desc">_x000D_
MY TEXT_x000D_
</p>_x000D_
</div>_x000D_
</div>
_x000D_
Judging from my own experience, asmcrypto.js provides the fastest AES implementation in JavaScript (especially in Firefox since it can fully leverage asm.js there).
From the readme:
Chrome/31.0 SHA256: 51 MiB/s (9 times faster than SJCL and CryptoJS) AES-CBC: 47 MiB/s (13 times faster than CryptoJS and 20 times faster than SJCL) Firefox/26.0 SHA256: 144 MiB/s (5 times faster than CryptoJS and 20 times faster than SJCL) AES-CBC: 81 MiB/s (3 times faster than CryptoJS and 8 times faster than SJCL)
Edit: The Web Cryptography API is now implemented in most browsers and should be used as the primary solution if you care about performance. Be aware that IE11 implemented an earlier draft version of the standard which did not use promises.
Some examples can be found here:
I might suggest 2 things.
1) If your query takes a lot of time because it´s using several tables that might involve locks, a quite fast solution is to run your queries with the "NoLock" hint.
Simply add Select * from YourTable WITH (NOLOCK)
in all your table references an that will prevent your query to block for concurrent transactions.
2) if you want to be sure that all of your queries runs in (let´s say) less than 5 seconds, then you could add what @talha proposed, that worked sweet for me
Just add at the top of your execution
SET LOCK_TIMEOUT 5000; --5 seconds.
And that will cause that your query takes less than 5 or fail. Then you should catch the exception and rollback if needed.
Hope it helps.
You can create enums to deal with errors :)
enum RikhError: Error {
case unknownError
case connectionError
case invalidCredentials
case invalidRequest
case notFound
case invalidResponse
case serverError
case serverUnavailable
case timeOut
case unsuppotedURL
}
and then create a method inside enum to receive the http response code and return the corresponding error in return :)
static func checkErrorCode(_ errorCode: Int) -> RikhError {
switch errorCode {
case 400:
return .invalidRequest
case 401:
return .invalidCredentials
case 404:
return .notFound
//bla bla bla
default:
return .unknownError
}
}
Finally update your failure block to accept single parameter of type RikhError :)
I have a detailed tutorial on how to restructure traditional Objective - C based Object Oriented network model to modern Protocol Oriented model using Swift3 here https://learnwithmehere.blogspot.in Have a look :)
Hope it helps :)
If you don't mind picking the same item again at some other time:
$items[rand(0, count($items) - 1)];
Either use window.onload
this way
<script>
window.onload = function() {
// ...
}
</script>
or alternatively
<script>
window.onload = functionName;
</script>
(yes, without the parentheses)
Or just put the script at the very bottom of page, right before </body>
. At that point, all HTML DOM elements are ready to be accessed by document
functions.
<body>
...
<script>
functionName();
</script>
</body>
On ubuntu you can add this PPA Repository and use it to install python 3.7: https://launchpad.net/~jonathonf/+archive/ubuntu/python-3.7
Or a different PPA that provides several Python versions is Deadsnakes: https://launchpad.net/~deadsnakes/+archive/ubuntu/ppa
See also here: https://askubuntu.com/questions/865554/how-do-i-install-python-3-6-using-apt-get (I know it says 3.6 in the url, but the deadsnakes ppa also contains 3.7 so you can use it for 3.7 just the same)
If you want "official" you'd have to install it from the sources from the site, get the code (which you already downloaded) and do this:
tar -xf Python-3.7.0.tar.xz
cd Python-3.7.0
./configure
make
sudo make install <-- sudo is required.
This might take a while
I created a function to generate a form, based on url, target and an object as the POST
/GET
data and submit method. It supports nested and mixed types within that object, so it can fully replicate any structure you feed it: PHP automatically parses it and returns it as a nested array.
However, there is a single restriction: the brackets [
and ]
must not be part of any key in the object (like {"this [key] is problematic" : "hello world"}
). If someone knows how to escape it properly, please do tell!
Without further ado, here is the source:
function getForm(url, target, values, method) {_x000D_
function grabValues(x) {_x000D_
var path = [];_x000D_
var depth = 0;_x000D_
var results = [];_x000D_
_x000D_
function iterate(x) {_x000D_
switch (typeof x) {_x000D_
case 'function':_x000D_
case 'undefined':_x000D_
case 'null':_x000D_
break;_x000D_
case 'object':_x000D_
if (Array.isArray(x))_x000D_
for (var i = 0; i < x.length; i++) {_x000D_
path[depth++] = i;_x000D_
iterate(x[i]);_x000D_
}_x000D_
else_x000D_
for (var i in x) {_x000D_
path[depth++] = i;_x000D_
iterate(x[i]);_x000D_
}_x000D_
break;_x000D_
default:_x000D_
results.push({_x000D_
path: path.slice(0),_x000D_
value: x_x000D_
})_x000D_
break;_x000D_
}_x000D_
path.splice(--depth);_x000D_
}_x000D_
iterate(x);_x000D_
return results;_x000D_
}_x000D_
var form = document.createElement("form");_x000D_
form.method = method;_x000D_
form.action = url;_x000D_
form.target = target;_x000D_
_x000D_
var values = grabValues(values);_x000D_
_x000D_
for (var j = 0; j < values.length; j++) {_x000D_
var input = document.createElement("input");_x000D_
input.type = "hidden";_x000D_
input.value = values[j].value;_x000D_
input.name = values[j].path[0];_x000D_
for (var k = 1; k < values[j].path.length; k++) {_x000D_
input.name += "[" + values[j].path[k] + "]";_x000D_
}_x000D_
form.appendChild(input);_x000D_
}_x000D_
return form;_x000D_
}
_x000D_
Usage example:
document.body.onclick = function() {_x000D_
var obj = {_x000D_
"a": [1, 2, [3, 4]],_x000D_
"b": "a",_x000D_
"c": {_x000D_
"x": [1],_x000D_
"y": [2, 3],_x000D_
"z": [{_x000D_
"a": "Hello",_x000D_
"b": "World"_x000D_
}, {_x000D_
"a": "Hallo",_x000D_
"b": "Welt"_x000D_
}]_x000D_
}_x000D_
};_x000D_
_x000D_
var form = getForm("http://example.com", "_blank", obj, "post");_x000D_
_x000D_
document.body.appendChild(form);_x000D_
form.submit();_x000D_
form.parentNode.removeChild(form);_x000D_
}
_x000D_
Just a little addition. If you've only selected 1 row then the code below will select the value of a column (index of 4, but 5th column) for the selected row:
me.lstIssues.Column(4)
This saves having to use the ItemsSelected property.
Kristian
function Person(firstname, lastname) {
this.firstname = firstname;
this.lastname = lastname;
this.getfullname = function () {
return `${this.firstname} ${this.lastname}`;
};
let that = this;
this.sayHi = function() {
console.log(`i am this , ${this.firstname}`);
console.log(`i am that , ${that.firstname}`);
};
}
let thisss = new Person('thatbetty', 'thatzhao');
let thatt = {firstname: 'thisbetty', lastname: 'thiszhao'};
thisss.sayHi.call(thatt);
It only seems to because that is what it is printing out. But actually, you shouldn't write the logic this way. This is equivalent:
insert into errortable (dateupdated, table1id)
values (sysdate, 1083);
It seems silly to convert the system date to a string just to convert it back to a date.
If you want to see the full date, then you can do:
select TO_CHAR(dateupdated, 'YYYY-MM-DD HH24:MI:SS'), table1id
from errortable;
After a brief review of the YAML cookbook cited in the question and some testing, here's my interpretation:
10
but you want it to return a String and not a Fixnum, write '10'
or "10"
.:
, {
, }
, [
, ]
, ,
, &
, *
, #
, ?
, |
, -
, <
, >
, =
, !
, %
, @
, \
).'\n'
would be returned as the string \n
."\n"
would be returned as a line feed character.!ruby/sym
to return a Ruby symbol.Seems to me that the best approach would be to not use quotes unless you have to, and then to use single quotes unless you specifically want to process escape codes.
Update
"Yes" and "No" should be enclosed in quotes (single or double) or else they will be interpreted as TrueClass and FalseClass values:
en:
yesno:
'yes': 'Yes'
'no': 'No'
5 different ways to refresh a webpage using Selenium Webdriver
There is no special extra coding. I have just used the existing functions in different ways to get it work. Here they are :
Using sendKeys.Keys method
driver.get("https://accounts.google.com/SignUp");
driver.findElement(By.id("firstname-placeholder")).sendKeys(Keys.F5);
Using navigate.refresh() method
driver.get("https://accounts.google.com/SignUp");
driver.navigate().refresh();
Using navigate.to() method
driver.get("https://accounts.google.com/SignUp");
driver.navigate().to(driver.getCurrentUrl());
Using get() method
driver.get("https://accounts.google.com/SignUp");
driver.get(driver.getCurrentUrl());
Using sendKeys() method
driver.get("https://accounts.google.com/SignUp");
driver.findElement(By.id("firstname-placeholder")).sendKeys("\uE035");
I wanted to implement myself this, i ended up reading the Wikipedia page on Great-circle distance formula, because no code was readable enough for me to use as basis.
C# example
/// <summary>
/// Calculates the distance between two locations using the Great Circle Distance algorithm
/// <see cref="https://en.wikipedia.org/wiki/Great-circle_distance"/>
/// </summary>
/// <param name="first"></param>
/// <param name="second"></param>
/// <returns></returns>
private static double DistanceBetween(GeoLocation first, GeoLocation second)
{
double longitudeDifferenceInRadians = Math.Abs(ToRadians(first.Longitude) - ToRadians(second.Longitude));
double centralAngleBetweenLocationsInRadians = Math.Acos(
Math.Sin(ToRadians(first.Latitude)) * Math.Sin(ToRadians(second.Latitude)) +
Math.Cos(ToRadians(first.Latitude)) * Math.Cos(ToRadians(second.Latitude)) *
Math.Cos(longitudeDifferenceInRadians));
const double earthRadiusInMeters = 6357 * 1000;
return earthRadiusInMeters * centralAngleBetweenLocationsInRadians;
}
private static double ToRadians(double degrees)
{
return degrees * Math.PI / 180;
}
From the RFC 4648:
Base encoding of data is used in many situations to store or transfer data in environments that, perhaps for legacy reasons, are restricted to US-ASCII data.
So it depends on the purpose of usage of the encoded data if the data should be considered as dangerous.
But if you’re just looking for a regular expression to match Base64 encoded words, you can use the following:
^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$
oninput
event is very useful to track input fields changes.
However it is not supported in IE version < 9. But older IE versions has its own proprietary event onpropertychange
that does the same as oninput
.
So you can use it this way:
$(':input').on('input propertychange');
To have a full crossbrowser support.
Since the propertychange can be triggered for ANY property change, for example, the disabled property is changed, then you want to do include this:
$(':input').on('propertychange input', function (e) {
var valueChanged = false;
if (e.type=='propertychange') {
valueChanged = e.originalEvent.propertyName=='value';
} else {
valueChanged = true;
}
if (valueChanged) {
/* Code goes here */
}
});
Dictionary<string, List<string>> dictionary = new Dictionary<string,List<string>>();
foreach(string key in keys) {
if(!dictionary.ContainsKey(key)) {
//add
dictionary.Add(key, new List<string>());
}
dictionary[key].Add("theString");
}
If the key doesn't exist, a new List
is added (inside if). Else the key exists, so just add a new value to the List
under that key.
I use this code:
<?php
{
//foreach (glob("images/*.jpg") as $large)
foreach (glob("*.xml") as $filename) {
//echo "$filename\n";
//echo str_replace("","","$filename\n");
echo str_replace("","","<a href='$filename'>$filename</a>\n");
}
}
?>
MySQL documentation covers this topic.
Here is a synopsis. When using join
or inner join
, the on
condition is optional. This is different from the ANSI standard and different from almost any other database. The effect is a cross join
. Similarly, you can use an on
clause with cross join
, which also differs from standard SQL.
A cross join creates a Cartesian product -- that is, every possible combination of 1 row from the first table and 1 row from the second. The cross join for a table with three rows ('a', 'b', and 'c') and a table with four rows (say 1, 2, 3, 4) would have 12 rows.
In practice, if you want to do a cross join, then use cross join
:
from A cross join B
is much better than:
from A, B
and:
from A join B -- with no on clause
The on
clause is required for a right or left outer join, so the discussion is not relevant for them.
If you need to understand the different types of joins, then you need to do some studying on relational databases. Stackoverflow is not an appropriate place for that level of discussion.
select
(select count(*) from foo) as foo
, (select count(*) from bar) as bar
, ...
I am using Visual Studio 2012. After installing the Visual Studio 2013 web express, when I want to run or open any project in Visual Studio 2012 it shows me the following error:
"no exports were found that match the constraint contract name".
I also tried the above solution for clearing the ComponentModelCache, but I did not find the folder. I solves my problem just by: Repair Visual Studio 2012
For the Express versions of the software, the folder you need is in a slightly different place(s): For Express 2012 for Web it is C:\Users\XXXXXXXX\AppData\Local\Microsoft\VWDExpress
- not in the Visual Studio folder.
If you have fresh installation / update of Xcode, it is possible that your git binary can't be executed (I had mine under /usr/bin/git
). To fix this problem just run the Xcode and "Accept" license conditions and try again, it should work.
You can also use the "timestamp" data type where it just needs "dd-mm-yyyy"
Like:
insert into emp values('12-12-2012');
considering there is just one column in the table... You can adjust the insertion values according to your table.
You can move to desired activity on button click. just add
android:onClick="timerApp"this line.
xml:
<Button
android:id="@+id/timer_app"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="timerApp"
android:text="Click To run Timer Activity" />
In your main activity just add this method:
public void timerApp(View view){
Intent intent= new Intent(MainActivity.this,TimerActivity.class);
startActivity(intent);
}
OR in onCreate() method add below code
Button btn =findViewById(R.id.timer_app);//Don't need to type casting in android studio 3
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, TimerActivity.class);
startActivity(intent);
}
});
Depends how you implement the RMI, you can set the registry port (registry is a "unique point of services"). If you don't set a explicit port, the registry will assume the port 1099 by default. In some cases, you have a firewall, and the firewall don't allow your rmi-client to see the stubs and objects behind the registry, because this things are running in randomically port, a different port that the registry use, and this port is blocked by firewall - of course.
If you use RmiServiceExporter
to configure your RmiServer, you can use the method rmiServiceExporter.setServicePort(port)
to fixed the rmi port, and open this port in the firewall.
Edit: I resolve this issue with this post: http://www.mscharhag.com/java/java-rmi-things-to-remember
This is the most simple, and it worked for me:
In the values-21:
<resources>
<style name="AppTheme" parent="AppTheme.Base">
...
<item name="android:windowTranslucentStatus">true</item>
</style>
<dimen name="topMargin">25dp</dimen>
</resources>
In the values:
<resources>
<dimen name="topMargin">0dp</dimen>
</resources>
And set to your toolbar
android:layout_marginTop="@dimen/topMargin"
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.
$ irb --simple-prompt
class TestClass
def method1
end
def method2
end
def method3
end
end
tc_list = TestClass.instance_methods(false)
#[:method1, :method2, :method3]
puts tc_list
#method1
#method2
#method3
If you know the width of the span you could just stuff in a left margin.
Try this:
.center { text-align: center}
div.center span { display: table; }
Add the "center: class to your .
If you want some spans centered, but not others, replace the "div.center span" in your style sheet to a class (e.g "center-span") and add that class to the span.
How about a function that jumps to the week before that week number and then steps through the next few days until the week number changes (max 7 steps), returning the new date?
CREATE FUNCTION dbo.fnGetDateFromWeekNo
(@weekNo int , @yearNo int)
RETURNS smalldatetime
AS
BEGIN
DECLARE @tmpDate smalldatetime
set @tmpdate= cast(cast (@yearNo as varchar) + '-01-01' as smalldatetime)
-- jump forward x-1 weeks to save counting through the whole year
set @tmpdate=dateadd(wk,@weekno-1,@tmpdate)
-- make sure weekno is not out of range
if @WeekNo <= datepart(wk,cast(cast (@yearNo as varchar) + '-12-31' as smalldatetime))
BEGIN
WHILE (datepart(wk,@tmpdate)<@WeekNo)
BEGIN
set @tmpdate=dateadd(dd,1,@tmpdate)
END
END
ELSE
BEGIN
-- invalid weeknumber given
set @tmpdate=null
END
RETURN @tmpDate
END
If using sqlplus you can define a variable thus:
define <varname>=<varvalue>
And you can display the value by:
define <varname>
And then use it in a query as, for example:
select *
from tab1
where col1 = '&varname';
Yup, often called a 'cookie jar' Google should provide many examples:
http://devzone.zend.com/16/php-101-part-10-a-session-in-the-cookie-jar/
http://curl.haxx.se/libcurl/php/examples/cookiejar.html <- good example IMHO
Copying that last one here so it does not go away...
Login to on one page and then get another page passing all cookies from the first page along Written by Mitchell
<?php
/*
This script is an example of using curl in php to log into on one page and
then get another page passing all cookies from the first page along with you.
If this script was a bit more advanced it might trick the server into
thinking its netscape and even pass a fake referer, yo look like it surfed
from a local page.
*/
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/cookieFileName");
curl_setopt($ch, CURLOPT_URL,"http://www.myterminal.com/checkpwd.asp");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "UserID=username&password=passwd");
ob_start(); // prevent any output
curl_exec ($ch); // execute the curl command
ob_end_clean(); // stop preventing output
curl_close ($ch);
unset($ch);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_COOKIEFILE, "/tmp/cookieFileName");
curl_setopt($ch, CURLOPT_URL,"http://www.myterminal.com/list.asp");
$buf2 = curl_exec ($ch);
curl_close ($ch);
echo "<PRE>".htmlentities($buf2);
?>
You can also try to use a Polyfill like Fixed-Sticky. Especially when you are using Bootstrap4 the affix
component is no longer included:
Dropped the Affix jQuery plugin. We recommend using a position: sticky polyfill instead.
You can also use .map() as:
var list=[];
response.data.message.map(function(value, key) {
list.push(value);
});
It is a xml error for some reason may be because of deleting a view or string in another view or may be for missing " or /> ..... etc
But here I am using a good technique to figure out where is the problem exactly :-
I know it is not the solution of the main problem but it will make you find where is the error quickly and save you time.
Update
There is another way you can find out easily, as Bennik2000 write in comment, you can look at the right scrollbar for red lines, they also indicate errors.
Update
I found a very simple way to get where is the error exactly if it is in resource file or even java file.
1- Go to Project Window.
2- Open the file that has the error.
3- Click F2 to go to the nearest error appears (it will go to the correct line)
Yes. Internally it is implemented as open hashing based on a primitive polynomial over Z/2 (source).
Position the cursor inside the class, then press ALT + Ins and select Getters and Setters
from the contextual menu.
Unless your application has specially needs, I think you have 2 approaches:
Session is not only thread-safe but also state-safe, in a way that you know that until the current request is completed, every session variable wont change from another active request. In order for this to happen you must ensure that session WILL BE LOCKED until the current request have completed.
You can create a session like behavior by many ways, but if it does not lock the current session, it wont be 'session'.
For the specific problems you mentioned I think you should check HttpContext.Current.Response.IsClientConnected. This can be useful to to prevent unnecessary executions and waits on the client, although it cannot solve this problem entirely, as this can be used only by a pooling way and not async.
Ctrl + F2 works for me in Windows 10.
Ctrl + Shift + L starts performance logging
You can use replace
instead of gsub
.
"hello _there_".replace(/_(.*?)_/g, "<div>\$1</div>")
Simple Example:
protocol Work: class {
func doSomething()
}
class Manager {
weak var delegate: Work?
func passAlong() {
delegate?.doSomething()
}
}
class Employee: Work {
func doSomething() {
print("Working on it")
}
}
let manager = Manager()
let developer = Employee()
manager.delegate = developer
manager.passAlong() // PRINTS: Working on it
You can try this:
var theValue = document.getElementById("demo").getAttribute("value");
This worked for me
pip install django-csvimport --upgrade
I timed all the methods in the current answers along with one extra.
With an input string of abc&def#ghi
and replacing & -> \& and # -> \#, the fastest way was to chain together the replacements like this: text.replace('&', '\&').replace('#', '\#')
.
Timings for each function:
Here are the functions:
def a(text):
chars = "&#"
for c in chars:
text = text.replace(c, "\\" + c)
def b(text):
for ch in ['&','#']:
if ch in text:
text = text.replace(ch,"\\"+ch)
import re
def c(text):
rx = re.compile('([&#])')
text = rx.sub(r'\\\1', text)
RX = re.compile('([&#])')
def d(text):
text = RX.sub(r'\\\1', text)
def mk_esc(esc_chars):
return lambda s: ''.join(['\\' + c if c in esc_chars else c for c in s])
esc = mk_esc('&#')
def e(text):
esc(text)
def f(text):
text = text.replace('&', '\&').replace('#', '\#')
def g(text):
replacements = {"&": "\&", "#": "\#"}
text = "".join([replacements.get(c, c) for c in text])
def h(text):
text = text.replace('&', r'\&')
text = text.replace('#', r'\#')
def i(text):
text = text.replace('&', r'\&').replace('#', r'\#')
Timed like this:
python -mtimeit -s"import time_functions" "time_functions.a('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.b('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.c('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.d('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.e('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.f('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.g('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.h('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.i('abc&def#ghi')"
Here's similar code to do the same but with more characters to escape (\`*_{}>#+-.!$):
def a(text):
chars = "\\`*_{}[]()>#+-.!$"
for c in chars:
text = text.replace(c, "\\" + c)
def b(text):
for ch in ['\\','`','*','_','{','}','[',']','(',')','>','#','+','-','.','!','$','\'']:
if ch in text:
text = text.replace(ch,"\\"+ch)
import re
def c(text):
rx = re.compile('([&#])')
text = rx.sub(r'\\\1', text)
RX = re.compile('([\\`*_{}[]()>#+-.!$])')
def d(text):
text = RX.sub(r'\\\1', text)
def mk_esc(esc_chars):
return lambda s: ''.join(['\\' + c if c in esc_chars else c for c in s])
esc = mk_esc('\\`*_{}[]()>#+-.!$')
def e(text):
esc(text)
def f(text):
text = text.replace('\\', '\\\\').replace('`', '\`').replace('*', '\*').replace('_', '\_').replace('{', '\{').replace('}', '\}').replace('[', '\[').replace(']', '\]').replace('(', '\(').replace(')', '\)').replace('>', '\>').replace('#', '\#').replace('+', '\+').replace('-', '\-').replace('.', '\.').replace('!', '\!').replace('$', '\$')
def g(text):
replacements = {
"\\": "\\\\",
"`": "\`",
"*": "\*",
"_": "\_",
"{": "\{",
"}": "\}",
"[": "\[",
"]": "\]",
"(": "\(",
")": "\)",
">": "\>",
"#": "\#",
"+": "\+",
"-": "\-",
".": "\.",
"!": "\!",
"$": "\$",
}
text = "".join([replacements.get(c, c) for c in text])
def h(text):
text = text.replace('\\', r'\\')
text = text.replace('`', r'\`')
text = text.replace('*', r'\*')
text = text.replace('_', r'\_')
text = text.replace('{', r'\{')
text = text.replace('}', r'\}')
text = text.replace('[', r'\[')
text = text.replace(']', r'\]')
text = text.replace('(', r'\(')
text = text.replace(')', r'\)')
text = text.replace('>', r'\>')
text = text.replace('#', r'\#')
text = text.replace('+', r'\+')
text = text.replace('-', r'\-')
text = text.replace('.', r'\.')
text = text.replace('!', r'\!')
text = text.replace('$', r'\$')
def i(text):
text = text.replace('\\', r'\\').replace('`', r'\`').replace('*', r'\*').replace('_', r'\_').replace('{', r'\{').replace('}', r'\}').replace('[', r'\[').replace(']', r'\]').replace('(', r'\(').replace(')', r'\)').replace('>', r'\>').replace('#', r'\#').replace('+', r'\+').replace('-', r'\-').replace('.', r'\.').replace('!', r'\!').replace('$', r'\$')
Here's the results for the same input string abc&def#ghi
:
And with a longer input string (## *Something* and [another] thing in a longer sentence with {more} things to replace$
):
Adding a couple of variants:
def ab(text):
for ch in ['\\','`','*','_','{','}','[',']','(',')','>','#','+','-','.','!','$','\'']:
text = text.replace(ch,"\\"+ch)
def ba(text):
chars = "\\`*_{}[]()>#+-.!$"
for c in chars:
if c in text:
text = text.replace(c, "\\" + c)
With the shorter input:
With the longer input:
So I'm going to use ba
for readability and speed.
Prompted by haccks in the comments, one difference between ab
and ba
is the if c in text:
check. Let's test them against two more variants:
def ab_with_check(text):
for ch in ['\\','`','*','_','{','}','[',']','(',')','>','#','+','-','.','!','$','\'']:
if ch in text:
text = text.replace(ch,"\\"+ch)
def ba_without_check(text):
chars = "\\`*_{}[]()>#+-.!$"
for c in chars:
text = text.replace(c, "\\" + c)
Times in µs per loop on Python 2.7.14 and 3.6.3, and on a different machine from the earlier set, so cannot be compared directly.
?-------------------------------------------------------------?
¦ Py, input ¦ ab ¦ ab_with_check ¦ ba ¦ ba_without_check ¦
¦------------+------+---------------+------+------------------¦
¦ Py2, short ¦ 8.81 ¦ 4.22 ¦ 3.45 ¦ 8.01 ¦
¦ Py3, short ¦ 5.54 ¦ 1.34 ¦ 1.46 ¦ 5.34 ¦
+------------+------+---------------+------+------------------¦
¦ Py2, long ¦ 9.3 ¦ 7.15 ¦ 6.85 ¦ 8.55 ¦
¦ Py3, long ¦ 7.43 ¦ 4.38 ¦ 4.41 ¦ 7.02 ¦
+-------------------------------------------------------------+
We can conclude that:
Those with the check are up to 4x faster than those without the check
ab_with_check
is slightly in the lead on Python 3, but ba
(with check) has a greater lead on Python 2
However, the biggest lesson here is Python 3 is up to 3x faster than Python 2! There's not a huge difference between the slowest on Python 3 and fastest on Python 2!
I have a solution that's similar to ironhacker's except that I use logging.exception in some of my code and found that I needed to format the exception before passing it back over the Queue since tracebacks aren't pickle'able:
class QueueHandler(logging.Handler):
def __init__(self, queue):
logging.Handler.__init__(self)
self.queue = queue
def emit(self, record):
if record.exc_info:
# can't pass exc_info across processes so just format now
record.exc_text = self.formatException(record.exc_info)
record.exc_info = None
self.queue.put(record)
def formatException(self, ei):
sio = cStringIO.StringIO()
traceback.print_exception(ei[0], ei[1], ei[2], None, sio)
s = sio.getvalue()
sio.close()
if s[-1] == "\n":
s = s[:-1]
return s
I think, this could be done without IIS URL Rewrite module. <httpRedirect>
supports wildcards, so you can configure it this way:
<system.webServer>
<httpRedirect enabled="true">
<add wildcard="/" destination="/menu_1/MainScreen.aspx" />
</httpRedirect>
</system.webServer>
Note that you need to have the "HTTP Redirection" feature enabled on IIS - see HTTP Redirects
Please use a <pre>
tag
demo : http://jsfiddle.net/K83cK/
var data = {_x000D_
"data": {_x000D_
"x": "1",_x000D_
"y": "1",_x000D_
"url": "http://url.com"_x000D_
},_x000D_
"event": "start",_x000D_
"show": 1,_x000D_
"id": 50_x000D_
}_x000D_
_x000D_
_x000D_
document.getElementById("json").textContent = JSON.stringify(data, undefined, 2);
_x000D_
<pre id="json"></pre>
_x000D_
As stated in Date and Time Literals:
MySQL recognizes
DATE
values in these formats:
As a string in either
'YYYY-MM-DD'
or'YY-MM-DD'
format. A “relaxed” syntax is permitted: Any punctuation character may be used as the delimiter between date parts. For example,'2012-12-31'
,'2012/12/31'
,'2012^12^31'
, and'2012@12@31'
are equivalent.As a string with no delimiters in either
'YYYYMMDD'
or'YYMMDD'
format, provided that the string makes sense as a date. For example,'20070523'
and'070523'
are interpreted as'2007-05-23'
, but'071332'
is illegal (it has nonsensical month and day parts) and becomes'0000-00-00'
.As a number in either
YYYYMMDD
orYYMMDD
format, provided that the number makes sense as a date. For example,19830905
and830905
are interpreted as'1983-09-05'
.
Therefore, the string '08/25/2012'
is not a valid MySQL date literal. You have four options (in some vague order of preference, without any further information of your requirements):
Configure Datepicker to provide dates in a supported format using an altField
together with its altFormat
option:
<input type="hidden" id="actualDate" name="actualDate"/>
$( "selector" ).datepicker({
altField : "#actualDate"
altFormat: "yyyy-mm-dd"
});
Or, if you're happy for users to see the date in YYYY-MM-DD
format, simply set the dateFormat
option instead:
$( "selector" ).datepicker({
dateFormat: "yyyy-mm-dd"
});
Use MySQL's STR_TO_DATE()
function to convert the string:
INSERT INTO user_date VALUES ('', '$name', STR_TO_DATE('$date', '%m/%d/%Y'))
Convert the string received from jQuery into something that PHP understands as a date, such as a DateTime
object:
$dt = \DateTime::createFromFormat('m/d/Y', $_POST['date']);
and then either:
obtain a suitable formatted string:
$date = $dt->format('Y-m-d');
obtain the UNIX timestamp:
$timestamp = $dt->getTimestamp();
which is then passed directly to MySQL's FROM_UNIXTIME()
function:
INSERT INTO user_date VALUES ('', '$name', FROM_UNIXTIME($timestamp))
Manually manipulate the string into a valid literal:
$parts = explode('/', $_POST['date']);
$date = "$parts[2]-$parts[0]-$parts[1]";
Your code is vulnerable to SQL injection. You really should be using prepared statements, into which you pass your variables as parameters that do not get evaluated for SQL. If you don't know what I'm talking about, or how to fix it, read the story of Bobby Tables.
Also, as stated in the introduction to the PHP manual chapter on the mysql_*
functions:
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
You appear to be using either a DATETIME
or TIMESTAMP
column for holding a date value; I recommend you consider using MySQL's DATE
type instead. As explained in The DATE
, DATETIME
, and TIMESTAMP
Types:
The
DATE
type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in'YYYY-MM-DD'
format. The supported range is'1000-01-01'
to'9999-12-31'
.The
DATETIME
type is used for values that contain both date and time parts. MySQL retrieves and displaysDATETIME
values in'YYYY-MM-DD HH:MM:SS'
format. The supported range is'1000-01-01 00:00:00'
to'9999-12-31 23:59:59'
.The
TIMESTAMP
data type is used for values that contain both date and time parts.TIMESTAMP
has a range of'1970-01-01 00:00:01'
UTC to'2038-01-19 03:14:07'
UTC.
I think what you want is MySQL's information_schema view(s): http://dev.mysql.com/doc/refman/5.0/en/tables-table.html
If you want treeview like explorer, you can go with LightExplorer
Download dll from here and paste it inside plugins folder in notepad++ installed directory. Restart notepad++ and then in menubar goto Plugins ->Light Explorer -> Light Explorer
if you want php you can count the array and just make an if statement like
if((int)count($_FILES['i_dont_know_whats_coming_next'] > 2)
echo "error message";
Its better to access the count with the laravels count method
$count = Model::where('status','=','1')->count();
or
$count = Model::count();
First of all - prerequisite for downcast is that object you are casting is of the type you are casting to. Casting with dynamic_cast will check this condition in runtime (provided that casted object has some virtual functions) and throw bad_cast
or return NULL
pointer on failure. Compile-time casts will not check anything and will just lead tu undefined behaviour if this prerequisite does not hold.
Now analyzing your code:
DerivedType m_derivedType = m_baseType;
Here there is no casting. You are creating a new object of type DerivedType
and try to initialize it with value of m_baseType variable.
Next line is not much better:
DerivedType m_derivedType = (DerivedType)m_baseType;
Here you are creating a temporary of DerivedType
type initialized with m_baseType
value.
The last line
DerivedType * m_derivedType = (DerivedType*) & m_baseType;
should compile provided that BaseType
is a direct or indirect public base class of DerivedType
. It has two flaws anyway:
static_cast<DerivedType *>(&m_baseType)
BaseType m_baseType;
so any use of m_derivedType
pointer will result in undefined behaviour.You sure can.
The easiest way to see how you might do this is to browse to the aspx page you want to post to. Then save the source of that page as HTML. Change the action of the form on your new html page to point back to the aspx page you originally copied it from.
Add value tags to your form fields and put the data you want in there, then open the page and hit the submit button.
You may also indicate the path to the gemfile in the same command e.g.
BUNDLE_GEMFILE="MyProject/Gemfile.ios" bundle install
$("#divParentClip").find("#subclip_checkbox")[0].checked=true;
Find will return array , so use [0] to get even if there is only one item
if you don't use find then
$("#subclip_checkbox").checked=true;
this worked fine in Mozilla Firefox for me
Call System.Reflection.MethodBase.GetCurrentMethod().Name
from within the method.
NumPy's arrays are more compact than Python lists -- a list of lists as you describe, in Python, would take at least 20 MB or so, while a NumPy 3D array with single-precision floats in the cells would fit in 4 MB. Access in reading and writing items is also faster with NumPy.
Maybe you don't care that much for just a million cells, but you definitely would for a billion cells -- neither approach would fit in a 32-bit architecture, but with 64-bit builds NumPy would get away with 4 GB or so, Python alone would need at least about 12 GB (lots of pointers which double in size) -- a much costlier piece of hardware!
The difference is mostly due to "indirectness" -- a Python list is an array of pointers to Python objects, at least 4 bytes per pointer plus 16 bytes for even the smallest Python object (4 for type pointer, 4 for reference count, 4 for value -- and the memory allocators rounds up to 16). A NumPy array is an array of uniform values -- single-precision numbers takes 4 bytes each, double-precision ones, 8 bytes. Less flexible, but you pay substantially for the flexibility of standard Python lists!
you should change the owner of the server
by chown
command
from home you can run this command
sudo chown {userName} -R ../../opt
If it does not work yet, run this command
sudo chmod 777 -R ../../opt
It should work now.
To avoid check on every digest cycle, we can change the height of the div when the window height gets changed.
http://jsfiddle.net/zbjLh/709/
<div ng-app="miniapp" resize>
Testing
</div>
.
var app = angular.module('miniapp', []);
app.directive('resize', function ($window) {
return function (scope, element) {
var w = angular.element($window);
var changeHeight = function() {element.css('height', (w.height() -20) + 'px' );};
w.bind('resize', function () {
changeHeight(); // when window size gets changed
});
changeHeight(); // when page loads
}
})
This gives you the needed results:
string time = "16:23:01";
var result = Convert.ToDateTime(time);
string test = result.ToString("hh:mm:ss tt", CultureInfo.CurrentCulture);
//This gives you "04:23:01 PM" string
You could also use CultureInfo.CreateSpecificCulture("en-US")
as not all cultures will display AM/PM.
just like user hcpl said but if you want to not worry about the version of the library you can do this:
dependencies {
compile(name:'mylibrary', ext:'aar')
}
as its kind of annoying to have to update the version everytime. Also it makes the not worrying about the name space easier this way.
The simple solution would be to use a ItemListener
. When the state changes, you would simply check the currently selected item and set the text accordingly
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestComboBox06 {
public static void main(String[] args) {
new TestComboBox06();
}
public TestComboBox06() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JComboBox cb;
private JTextField field;
public TestPane() {
cb = new JComboBox(new String[]{"Item 1", "Item 2"});
field = new JTextField(12);
add(cb);
add(field);
cb.setSelectedItem(null);
cb.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
Object item = cb.getSelectedItem();
if ("Item 1".equals(item)) {
field.setText("20");
} else if ("Item 2".equals(item)) {
field.setText("30");
}
}
});
}
}
}
A better solution would be to create a custom object that represents the value to be displayed and the value associated with it...
Updated
Now I no longer have a 10 month chewing on my ankles, I updated the example to use a ListCellRenderer
which is a more correct approach then been lazy and overriding toString
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestComboBox06 {
public static void main(String[] args) {
new TestComboBox06();
}
public TestComboBox06() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JComboBox cb;
private JTextField field;
public TestPane() {
cb = new JComboBox(new Item[]{
new Item("Item 1", "20"),
new Item("Item 2", "30")});
cb.setRenderer(new ItemCelLRenderer());
field = new JTextField(12);
add(cb);
add(field);
cb.setSelectedItem(null);
cb.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
Item item = (Item)cb.getSelectedItem();
field.setText(item.getValue());
}
});
}
}
public class Item {
private String value;
private String text;
public Item(String text, String value) {
this.text = text;
this.value = value;
}
public String getText() {
return text;
}
public String getValue() {
return value;
}
}
public class ItemCelLRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); //To change body of generated methods, choose Tools | Templates.
if (value instanceof Item) {
setText(((Item)value).getText());
}
return this;
}
}
}
C (not simplified)
seq 1 10 | tcc -run <(cat << EOF
#include <stdio.h>
int main(int argc, char** argv) {
int sum = 0;
int i = 0;
while(scanf("%d", &i) == 1) {
sum = sum + i;
}
printf("%d\n", sum);
return 0;
}
EOF)
Re: craigts's response, for anyone having trouble with using either False or None parameters for index_col, such as in cases where you're trying to get rid of a range index, you can instead use an integer to specify the column you want to use as the index. For example:
df = pd.read_csv('file.csv', index_col=0)
The above will set the first column as the index (and not add a range index in my "common case").
Given the popularity of this answer, I thought i'd add some context/ a demo:
# Setting up the dummy data
In [1]: df = pd.DataFrame({"A":[1, 2, 3], "B":[4, 5, 6]})
In [2]: df
Out[2]:
A B
0 1 4
1 2 5
2 3 6
In [3]: df.to_csv('file.csv', index=None)
File[3]:
A B
1 4
2 5
3 6
Reading without index_col or with None/False will all result in a range index:
In [4]: pd.read_csv('file.csv')
Out[4]:
A B
0 1 4
1 2 5
2 3 6
# Note that this is the default behavior, so the same as In [4]
In [5]: pd.read_csv('file.csv', index_col=None)
Out[5]:
A B
0 1 4
1 2 5
2 3 6
In [6]: pd.read_csv('file.csv', index_col=False)
Out[6]:
A B
0 1 4
1 2 5
2 3 6
However, if we specify that "A" (the 0th column) is actually the index, we can avoid the range index:
In [7]: pd.read_csv('file.csv', index_col=0)
Out[7]:
B
A
1 4
2 5
3 6
yet another solution uses tr
:
echo $testVar | tr -d '\r'
cat myscript | tr -d '\r'
the option -d
stands for delete
.
You can use following formulas.
For Excel 2007 or later:
=IFERROR(VLOOKUP(D3,List!A:C,3,FALSE),"No Match")
For Excel 2003:
=IF(ISERROR(MATCH(D3,List!A:A, 0)), "No Match", VLOOKUP(D3,List!A:C,3,FALSE))
Note, that
List!A:C
in VLOOKUP
and returns value from column ? 3
VLOOKUP
equals to FALSE
, in that case VLOOKUP
will only find an exact match, and the values in the first column of List!A:C
do not need to be sorted (opposite to case when you're using TRUE
).The command that sold me on git personally was bisect. I don't think that this feature is available in any other version control system as of now.
That being said, if people are used to a GUI client for source control they are not going to be impressed with git. Right now the only full-featured client is command-line.
IMPORTANT EDIT: It is now possible to achieve this with DATETIME fields since MySQL 5.6.5, take a look at the other post below...
Previous versions can't do that with DATETIME...
But you can do it with TIMESTAMP:
mysql> create table test (str varchar(32), ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
Query OK, 0 rows affected (0.00 sec)
mysql> desc test;
+-------+-------------+------+-----+-------------------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+-------------------+-------+
| str | varchar(32) | YES | | NULL | |
| ts | timestamp | NO | | CURRENT_TIMESTAMP | |
+-------+-------------+------+-----+-------------------+-------+
2 rows in set (0.00 sec)
mysql> insert into test (str) values ("demo");
Query OK, 1 row affected (0.00 sec)
mysql> select * from test;
+------+---------------------+
| str | ts |
+------+---------------------+
| demo | 2008-10-03 22:59:52 |
+------+---------------------+
1 row in set (0.00 sec)
mysql>
CAVEAT: IF you define a column with CURRENT_TIMESTAMP ON as default, you will need to ALWAYS specify a value for this column or the value will automatically reset itself to "now()" on update. This means that if you do not want the value to change, your UPDATE statement must contain "[your column name] = [your column name]" (or some other value) or the value will become "now()". Weird, but true. I hope this helps. I am using 5.5.56-MariaDB
The flatMap
method on Stream
can certainly flatten those lists for you, but it must create Stream
objects for element, then a Stream
for the result.
You don't need all those Stream
objects. Here is the simple, concise code to perform the task.
// listOfLists is a List<List<Object>>.
List<Object> result = new ArrayList<>();
listOfLists.forEach(result::addAll);
Because a List
is Iterable
, this code calls the forEach
method (Java 8 feature), which is inherited from Iterable
.
Performs the given action for each element of the
Iterable
until all elements have been processed or the action throws an exception. Actions are performed in the order of iteration, if that order is specified.
And a List
's Iterator
returns items in sequential order.
For the Consumer
, this code passes in a method reference (Java 8 feature) to the pre-Java 8 method List.addAll
to add the inner list elements sequentially.
Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator (optional operation).
The ACTION_SEND
will only give you options for sending using GMail, YahooMail... etc(Any application installed on your phone, that can perform ACTION_SEND
). If you want to share on Facebook or Twitter you will need to place custom buttons for each and use their own SDK such as Facebook SDK or Twitter4J .
First off, you have to specify you wish to use Document Literal style:
$client = new SoapClient(NULL, array(
'location' => 'https://example.com/path/to/service',
'uri' => 'http://example.com/wsdl',
'trace' => 1,
'use' => SOAP_LITERAL)
);
Then, you need to transform your data into a SoapVar; I've written a simple transform function:
function soapify(array $data)
{
foreach ($data as &$value) {
if (is_array($value)) {
$value = soapify($value);
}
}
return new SoapVar($data, SOAP_ENC_OBJECT);
}
Then, you apply this transform function onto your data:
$data = soapify(array(
'Acquirer' => array(
'Id' => 'MyId',
'UserId' => 'MyUserId',
'Password' => 'MyPassword',
),
));
Finally, you call the service passing the Data parameter:
$method = 'Echo';
$result = $client->$method(new SoapParam($data, 'Data'));
I am late to this question, but I think the best way to handle JDK versions on MacOS is by using the script described at: http://www.jayway.com/2014/01/15/how-to-switch-jdk-version-on-mac-os-x-maverick/
Solved!
$a['index'] = [];
$a['index'][] = 'another value';
$a['index'][] = 'another value';
$a['index'][] = 'another value';
$a['index'][] = 'another value';
Want to center an image? Very easy, Bootstrap comes with two classes, .center-block
and text-center
.
Use the former in the case of your image being a BLOCK
element, for example, adding img-responsive
class to your img
makes the img
a block element. You should know this if you know how to navigate in the web console and see applied styles to an element.
Don't want to use a class? No problem, here is the CSS bootstrap uses. You can make a custom class or write a CSS rule for the element to match the Bootstrap class.
// In case you're dealing with a block element apply this to the element itself
.center-block {
margin-left:auto;
margin-right:auto;
display:block;
}
// In case you're dealing with a inline element apply this to the parent
.text-center {
text-align:center
}
You may not have permission to dba_sequences. So you can always just do:
select * from user_sequences;
On *nix check nm. On windows use the program Dependency Walker
You can compare two date by this method also
switch ([currenttimestr compare:endtimestr])
{
case NSOrderedAscending:
// dateOne is earlier in time than dateTwo
break;
case NSOrderedSame:
// The dates are the same
break;
case NSOrderedDescending:
// dateOne is later in time than dateTwo
break;
}
For those who want isoWeek
to be the default you can modify moment's behaviour as such:
const moment = require('moment');
const proto = Object.getPrototypeOf(moment());
const {startOf, endOf} = proto;
proto.startOf = function(period) {
if (period === 'week') {
period = 'isoWeek';
}
return startOf.call(this, period);
};
proto.endOf = function(period) {
if (period === 'week') {
period = 'isoWeek';
}
return endOf.call(this, period);
};
Now you can simply use someDate.startOf('week')
without worrying you'll get sunday or having to think about whether to use isoweek
or isoWeek
etc.
Plus you can store this in a variable like const period = 'week'
and use it safely in subtract()
or add()
operations, e.g. moment().subtract(1, period).startOf(period);
. This won't work with period being isoWeek
.
For properties for which css transition will affect, can use transitionend event, example for z-index:
$(".observed-element").on("webkitTransitionEnd transitionend", function(e) {_x000D_
console.log("end", e);_x000D_
alert("z-index changed");_x000D_
});_x000D_
_x000D_
$(".changeButton").on("click", function() {_x000D_
console.log("click");_x000D_
document.querySelector(".observed-element").style.zIndex = (Math.random() * 1000) | 0;_x000D_
});
_x000D_
.observed-element {_x000D_
transition: z-index 1ms;_x000D_
-webkit-transition: z-index 1ms;_x000D_
}_x000D_
div {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
border: 1px solid;_x000D_
position: absolute;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button class="changeButton">change z-index</button>_x000D_
<div class="observed-element"></div>
_x000D_
I had the same problem. I want a 100% transparent background color. Just use this code; it's worked great for me:
rgba(54, 25, 25, .00004);
You can see examples on the left side on this web page (the contact form area).
In my xml file, the header looked like this:
<?xml version="1.0" encoding="utf-16"? />
In a test file, I was reading the file bytes and decoding the data as UTF-8 (not realizing the header in this file was utf-16) to create a string.
byte[] data = Files.readAllBytes(Paths.get(path));
String dataString = new String(data, "UTF-8");
When I tried to deserialize this string into an object, I was seeing the same error:
javax.xml.stream.XMLStreamException: ParseError at [row,col]:[1,1]
Message: Content is not allowed in prolog.
When I updated the second line to
String dataString = new String(data, "UTF-16");
I was able to deserialize the object just fine. So as Romain had noted above, the encodings need to match.
I did it by putting
export JAVA_HOME=`/usr/libexec/java_home`
(backtics) in my .bashrc. See my comment on Adrian's answer.
Run dos2unix or similar utility on it to remove the carriage returns (^M).
This message indicates that your file has dos-style lineendings:
-bash: /backup/backup.sh: /bin/bash^M: bad interpreter: No such file or directory
Utilities like dos2unix
will fix it:
dos2unix <backup.bash >improved-backup.sh
Or, if no such utility is installed, you can accomplish the same thing with translate:
tr -d "\015\032" <backup.bash >improved-backup.sh
As for how those characters got there in the first place, @MadPhysicist had some good comments.
You can't get value when calling getJSON
, only after response.
var myjson;
$.getJSON("http://127.0.0.1:8080/horizon-update", function(json){
myjson = json;
});
Adding this answer partially because it fixed my problem of the same issue and so I can bookmark this question myself.
I was able to fix it by doing the following:
sudo apt-get install gcc-multilib g++-multilib
If you've installed a version of gcc
/ g++
that doesn't ship by default (such as g++-4.8
on lucid) you'll want to match the version as well:
sudo apt-get install gcc-4.8-multilib g++-4.8-multilib
CROSS APPLY
to the rescue:
SELECT Orders.OrderNumber, topline.Quantity, topline.Description
FROM Orders
cross apply
(
select top 1 Description,Quantity
from LineItems
where Orders.OrderID = LineItems.OrderID
)topline
You can also add the order by
of your choice.
Alternatively, you may also use the CSS3 Flexible Box Model. It's a great way to create flexible layouts that can also be applied to center content like so:
#parent {
-webkit-box-align:center;
-webkit-box-pack:center;
display:-webkit-box;
}
See the (quite) recent answer on the matplotlib repository, in which the following solution is suggested:
If you want to set the xticklabels:
ax.set_xticks([1,4,5])
ax.set_xticklabels([1,4,5], fontsize=12)
If you want to only increase the fontsize of the xticklabels, using the default values and locations (which is something I personally often need and find very handy):
ax.tick_params(axis="x", labelsize=12)
To do it all at once:
plt.setp(ax.get_xticklabels(), fontsize=12, fontweight="bold",
horizontalalignment="left")`
You can use backticks
.
$ echo myfilename-"`date +"%d-%m-%Y"`"
Yields:
myfilename-25-11-2009
It happens because the component is rendered before the async data arrived, you should control before to render.
I resolved it in this way:
render() {
let partners = this.props && this.props.partners.length > 0 ?
this.props.partners.map(p=>
<li className = "partners" key={p.id}>
<img src={p.img} alt={p.name}/> {p.name} </li>
) : <span></span>;
return (
<div>
<ul>{partners}</ul>
</div>
);
}
this.props && this.props.partners.length > 0 ?
Why use a dropdown at all? The only way the user will see your explanatory text is by blindly hovering over one of the options.
I think it would be preferable to use a radio button group, and next to each item, put a tooltip icon indicating additional information, as well as displaying it after selection (like you currently have it).
I realize this doesn't exactly solve your problem, but I don't see the point in struggling with an html element that's notorious for its inflexibility when you could just use one that's better suited in the first place.
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA
.COLUMNS
WHERE TABLE_SCHEMA
='bodb'
AND TABLE_NAME
='abc';
works for getting all column names
Or alternatively, you could use this:
WHERE CHARINDEX(N'Apples', someColumn) = 0
Not sure which one performs better - you gotta test it! :-)
Marc
UPDATE: the performance seems to be pretty much on a par with the other solution (WHERE someColumn NOT LIKE '%Apples%') - so it's really just a question of your personal preference.
If you know the viewport angle of the camera, you can use the height in pixels to determine the angle from the top to bottom of the object. Then, using the distance and arctangent calculate the height:
height = arctan(angle) * distance
To find the viewport angle, point the camera at something which is of known height, and make it exactly fill the screen. For example, point it at a ruler, and make it just far enough away that you can only barely see the ends of the ruler. Measure the distance from the camera, and then your total viewport angle is
viewportAngle = tan(ruler_length / distance)
Then, suppose your camera is 480px tall (cheap webcam), and the view angle is 20°. If you have an object onscreen which is 240px tall, then its angle is 10°. If you know it's 2 feet away, you would say 2 feet * arctan(10°) = ~4.1 inches
tall. (I think... it's 2am so this may be a little off)
I think you've got your understanding of the two properties off a little. Border affects the outside edge of the element, making the element different in size. Outline will not change the size or position of the element (takes up no space) and goes outside the border. From your description you want to use the border property.
Look at the simple example below in your browser:
<div style="height: 100px; width: 100px; background: black; color: white; outline: thick solid #00ff00">SOME TEXT HERE</div>_x000D_
_x000D_
<div style="height: 100px; width: 100px; background: black; color: white; border-left: thick solid #00ff00">SOME TEXT HERE</div>
_x000D_
Notice how the border pushes the bottom div over, but the outline doesn't move the top div and the outline actually overlaps the bottom div.
Try this:
return Redirect("http://www.website.com");
If you like to call an activity method from within a custom layout class(non-Activity Class).You should create a delegate using interface.
It is untested and i coded it right . but i am conveying a way to achieve what you want.
First of all create and Interface
interface TaskCompleteListener<T> {
public void onProfileClicked(T result);
}
public class ProfileView extends LinearLayout
{
private TaskCompleteListener<String> callback;
TextView profileTitleTextView;
ImageView profileScreenImageButton;
boolean isEmpty;
ProfileData data;
String name;
public ProfileView(Context context, AttributeSet attrs, String name, final ProfileData profileData)
{
super(context, attrs);
......
......
}
public setCallBack( TaskCompleteListener<String> cb)
{
this.callback = cb;
}
//Heres where things get complicated
public void onClick(View v)
{
callback.onProfileClicked("Pass your result or any type");
}
}
And implement this to any Activity.
and call it like
ProfileView pv = new ProfileView(actvitiyContext, null, temp, tempPd);
pv.setCallBack(new TaskCompleteListener
{
public void onProfileClicked(String resultStringFromProfileView){}
});
I also had same problem but i have solved by adding 'Content-Type' : 'application/x-font-ttf' in response header for all .ttf files
A shorter version of converting List to Array of specific type (for example Long):
Long[] myArray = myList.toArray(Long[]::new);
This is the effect that we're trying to achieve:
The classes that need to be applied changed with the release of Bootstrap 3.1.0 and again with the release of Bootstrap 4. If one of the below solutions doesn't seem to be working double check the version number of Bootstrap that you're importing and try a different one.
You can use the pull-right
class to line the right hand side of the menu up with the caret:
<li class="dropdown">
<a class="dropdown-toggle" href="#">Link</a>
<ul class="dropdown-menu pull-right">
<li>...</li>
</ul>
</li>
Fiddle: http://jsfiddle.net/joeczucha/ewzafdju/
As of v3.1.0, we've deprecated .pull-right on dropdown menus. To right-align a menu, use .dropdown-menu-right. Right-aligned nav components in the navbar use a mixin version of this class to automatically align the menu. To override it, use .dropdown-menu-left.
You can use the dropdown-right
class to line the right hand side of the menu up with the caret:
<li class="dropdown">
<a class="dropdown-toggle" href="#">Link</a>
<ul class="dropdown-menu dropdown-menu-right">
<li>...</li>
</ul>
</li>
Fiddle: http://jsfiddle.net/joeczucha/1nrLafxc/
The class for Bootstrap 4 are the same as Bootstrap > 3.1.0, just watch out as the rest of the surrounding markup has changed a little:
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#">
Link
</a>
<div class="dropdown-menu dropdown-menu-right">
<a class="dropdown-item" href="#">...</a>
</div>
</li>
Yes you can.
You need to add in the first controller:
YourController controller = loader.getController();
controller.setclient(client);
Then in the second one declare a client, then at the bottom of your controller:
public void setclien(Client c) {
this.client = c;
}
If you look at your original connection string:
<property name="url" value="jdbc:hsqldb:hsql://localhost"/>
The Hypersonic docs suggest that you're missing an alias after localhost:
I had the same problem when I was running the plotting commands in separate cells in Jupyter:
In [1]: %matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
In [2]: x = np.array([1, 3, 4])
y = np.array([1, 5, 3])
In [3]: fig = plt.figure()
<Figure size 432x288 with 0 Axes> #this might be the problem
In [4]: ax = fig.add_subplot(1, 1, 1)
In [5]: ax.scatter(x, y)
Out[5]: <matplotlib.collections.PathCollection at 0x12341234> # CAN'T SEE ANY PLOT :(
In [6]: plt.show() # STILL CAN'T SEE IT :(
The problem was solved by merging the plotting commands into a single cell:
In [1]: %matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
In [2]: x = np.array([1, 3, 4])
y = np.array([1, 5, 3])
In [3]: fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.scatter(x, y)
Out[3]: <matplotlib.collections.PathCollection at 0x12341234>
# AND HERE APPEARS THE PLOT AS DESIRED :)
If you're using C++11, you can use std::normal_distribution
:
#include <random>
std::default_random_engine generator;
std::normal_distribution<double> distribution(/*mean=*/0.0, /*stddev=*/1.0);
double randomNumber = distribution(generator);
There are many other distributions you can use to transform the output of the random number engine.
For me, other answers didn't work. I had to go to open Files
and do Invalidate caches and restart
on Intellij. After that, everything worked fine again.
The best way to get number of rows from resultset is using count function query for database access and then rs.getInt(1) method to get number of rows. from my code look it:
String query = "SELECT COUNT() FROM table";
ResultSet rs = new DatabaseConnection().selectData(query);
rs.getInt(1);
this will return int value number of rows fetched from database. Here DatabaseConnection().selectData() is my code for accessing database. I was also stuck here but then solved...
An article on Testing Private Methods lays out some approaches to testing private code. using reflection puts extra burden on the programmer to remember if refactoring is done, the strings aren't automatically changed, but I think it's the cleanest approach.
Above solutions did not work for me as the issue with open JDK 13 version https://github.com/spotify/dockerfile-maven/issues/163 So I degraded to open JDK8 and it works for me
You use this code in your button click event
// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
Visual Studio 2015 (v.14.....) - same problem here
Cause: Different versions of NUnit and NUnit Test Adapter In my case I had the latest versions of both NUnit (3.5) and NUnit Test Adapter but the Test Adapter was not the right one. For NUnit 3 and higher there is a NUnit3TestAdapter that must be used
Solution: Uninstalled the "faulty" NUnint Test Adapter and installed the UNit3TestAdapter v.3.5.0 (the latest now is 3.6.0 but didn't use it in order to keep it same as NUnit)
After Rebuild of the Solution Tests poped up :)
<button style="position: absolute; left: 20%; right: 20%; bottom: 5%;"> Button </button>
Note: This is not a duplicate, because the OP is aware that the image from cv2.imread
is in BGR format (unlike the suggested duplicate question that assumed it was RGB hence the provided answers only address that issue)
To illustrate, I've opened up this same color JPEG image:
once using the conversion
img = cv2.imread(path)
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
and another by loading it in gray scale mode
img_gray_mode = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
Like you've documented, the diff between the two images is not perfectly 0, I can see diff pixels in towards the left and the bottom
I've summed up the diff too to see
import numpy as np
np.sum(diff)
# I got 6143, on a 494 x 750 image
I tried all cv2.imread()
modes
Among all the IMREAD_
modes for cv2.imread()
, only IMREAD_COLOR
and IMREAD_ANYCOLOR
can be converted using COLOR_BGR2GRAY
, and both of them gave me the same diff against the image opened in IMREAD_GRAYSCALE
The difference doesn't seem that big. My guess is comes from the differences in the numeric calculations in the two methods (loading grayscale vs conversion to grayscale)
Naturally what you want to avoid is fine tuning your code on a particular version of the image just to find out it was suboptimal for images coming from a different source.
In brief, let's not mix the versions and types in the processing pipeline.
So I'd keep the image sources homogenous, e.g. if you have capturing the image from a video camera in BGR, then I'd use BGR as the source, and do the BGR to grayscale conversion cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Vice versa if my ultimate source is grayscale then I'd open the files and the video capture in gray scale cv2.imread(path, cv2.IMREAD_GRAYSCALE)
pandoc
with browser
works well for me.
Usage: cat README.md | pandoc -f markdown_github | browser
Installation (Assuming you are using Mac OSX):
$ brew install pandoc
$ brew install browser
Or on Debian/Ubuntu: apt-get install pandoc browser
Use Python:
#!/bin/bash
# home/victoria/test.sh
START=$(date +"%s") ## seconds since Epoch
for i in $(seq 1 10)
do
sleep 1.5
END=$(date +"%s") ## integer
TIME=$((END - START)) ## integer
AVG_TIME=$(python -c "print(float($TIME/$i))") ## int to float
printf 'i: %i | elapsed time: %0.1f sec | avg. time: %0.3f\n' $i $TIME $AVG_TIME
((i++)) ## increment $i
done
Output
$ ./test.sh
i: 1 | elapsed time: 1.0 sec | avg. time: 1.000
i: 2 | elapsed time: 3.0 sec | avg. time: 1.500
i: 3 | elapsed time: 5.0 sec | avg. time: 1.667
i: 4 | elapsed time: 6.0 sec | avg. time: 1.500
i: 5 | elapsed time: 8.0 sec | avg. time: 1.600
i: 6 | elapsed time: 9.0 sec | avg. time: 1.500
i: 7 | elapsed time: 11.0 sec | avg. time: 1.571
i: 8 | elapsed time: 12.0 sec | avg. time: 1.500
i: 9 | elapsed time: 14.0 sec | avg. time: 1.556
i: 10 | elapsed time: 15.0 sec | avg. time: 1.500
$
You can change the port in the console by running the following on Windows:
SET PORT=8000
For Mac, Linux or Windows WSL use the following:
export PORT=8000
The export sets the environment variable for the current shell and all child processes like npm that might use it.
If you want the environment variable to be set just for the npm process, precede the command with the environment variable like this (on Mac and Linux and Windows WSL):
PORT=8000 npm run start
You can use a regular expression: window.location.href.match(/^[^\#\?]+/)[0]
You can also install simplejson.
If you have pip (see https://pypi.python.org/pypi/pip) as your Python package manager you can install simplejson with:
pip install simplejson
This is similar to the comment of installing with easy_install, but I prefer pip to easy_install as you can easily uninstall in pip with "pip uninstall package".
Here's a cool ASP.NET Web control called Multi-Select List Field at http://www.xnodesystems.com/. It's capable of:
(1) Multi-select; (2) Auto-complete; (3) Validation.
I faced the same issue. I had missed the forms module import tag in the app.module.ts
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [BrowserModule,
FormsModule
],
You can do something like:
function ChckbxsCtrl($scope, $filter) {
$scope.chkbxs = [{
label: "Led Zeppelin",
val: false
}, {
label: "Electric Light Orchestra",
val: false
}, {
label: "Mark Almond",
val: false
}];
$scope.$watch("chkbxs", function(n, o) {
var trues = $filter("filter")(n, {
val: true
});
$scope.flag = trues.length;
}, true);
}
And a template:
<div ng-controller="ChckbxsCtrl">
<div ng-repeat="chk in chkbxs">
<input type="checkbox" ng-model="chk.val" />
<label>{{chk.label}}</label>
</div>
<div ng-show="flag">I'm ON when band choosed</div>
</div>
Working: http://jsfiddle.net/cherniv/JBwmA/
UPDATE: Or you can go little bit different way , without using $scope
's $watch()
method, like:
$scope.bandChoosed = function() {
var trues = $filter("filter")($scope.chkbxs, {
val: true
});
return trues.length;
}
And in a template do:
<div ng-show="bandChoosed()">I'm ON when band choosed</div>
Fiddle: http://jsfiddle.net/uzs4sgnp/
Another example
FOR %I in (file1.txt) do @ECHO %~zI
The existing answers are good but don't cover what to do when a smart pointer is not the (complete) answer to the problem you are trying to solve.
Among other things (explained well in other answers) using a smart pointer is a possible solution to How do we use a abstract class as a function return type? which has been marked as a duplicate of this question. However, the first question to ask if tempted to specify an abstract (or in fact, any) base class as a return type in C++ is "what do you really mean?". There is a good discussion (with further references) of idiomatic object oriented programming in C++ (and how this is different to other languages) in the documentation of the boost pointer container library. In summary, in C++ you have to think about ownership. Which smart pointers help you with, but are not the only solution, or always a complete solution (they don't give you polymorphic copy) and are not always a solution you want to expose in your interface (and a function return sounds an awful lot like an interface). It might be sufficient to return a reference, for example. But in all of these cases (smart pointer, pointer container or simply returning a reference) you have changed the return from a value to some form of reference. If you really needed copy you may need to add more boilerplate "idiom" or move beyond idiomatic (or otherwise) OOP in C++ to more generic polymorphism using libraries like Adobe Poly or Boost.TypeErasure.
It happened to me as Iam behind a firewall. The dependencies doesn't get downloaded sometimes when you are running in Eclipse IDE. Make sure you use mvn clean install -U
to resolve the problem. You would see the dependencies download after this.
Here is my entry, simple and clean..
function array2xml($array, $xml = false){
if($xml === false){
$xml = new SimpleXMLElement('<root/>');
}
foreach($array as $key => $value){
if(is_array($value)){
array2xml($value, $xml->addChild($key));
}else{
$xml->addChild($key, $value);
}
}
return $xml->asXML();
}
header('Content-type: text/xml');
print array2xml($array);
Nice short method:
public static String escapeHTML(String s) {
StringBuilder out = new StringBuilder(Math.max(16, s.length()));
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c > 127 || c == '"' || c == '\'' || c == '<' || c == '>' || c == '&') {
out.append("&#");
out.append((int) c);
out.append(';');
} else {
out.append(c);
}
}
return out.toString();
}
Based on https://stackoverflow.com/a/8838023/1199155 (the amp is missing there). The four characters checked in the if clause are the only ones below 128, according to http://www.w3.org/TR/html4/sgml/entities.html
You can replace '<' with <
and '>' with >
. For example:
echo "<div>";
The output will be visible <div>
.
For longer strings, make a function, for example
function example($input) {
$output = str_replace('>', '>', str_replace('<', '<', $html));
return $output;
}
echo example($your_html);
Don't forget to put backslashes href=\"#\"
or do it with single quotes href='#'
or change it in a function too with str_replace.
I guess something like this would do the job.
var option = document.createElement("option");
option.text = "Text";
option.value = "myvalue";
var select = document.getElementById("daySelect");
select.appendChild(option);
Your src property is an object because you are setting the src element to be the entire image you created in JavaScript.
Try
document["pic1"].src = searchPic.src;
Are you aware that the Access 2007 runtime can be downloaded for free?
Links for newer versions:
I had the same problem, the WebBrowser was using an old version of IE, with some googling I came across the following code that makes a change into registry and makes the WebBrowser to use the lastest IE version possible:
public enum BrowserEmulationVersion
{
Default = 0,
Version7 = 7000,
Version8 = 8000,
Version8Standards = 8888,
Version9 = 9000,
Version9Standards = 9999,
Version10 = 10000,
Version10Standards = 10001,
Version11 = 11000,
Version11Edge = 11001
}
public static class WBEmulator
{
private const string InternetExplorerRootKey = @"Software\Microsoft\Internet Explorer";
public static int GetInternetExplorerMajorVersion()
{
int result;
result = 0;
try
{
RegistryKey key;
key = Registry.LocalMachine.OpenSubKey(InternetExplorerRootKey);
if (key != null)
{
object value;
value = key.GetValue("svcVersion", null) ?? key.GetValue("Version", null);
if (value != null)
{
string version;
int separator;
version = value.ToString();
separator = version.IndexOf('.');
if (separator != -1)
{
int.TryParse(version.Substring(0, separator), out result);
}
}
}
}
catch (SecurityException)
{
// The user does not have the permissions required to read from the registry key.
}
catch (UnauthorizedAccessException)
{
// The user does not have the necessary registry rights.
}
return result;
}
private const string BrowserEmulationKey = InternetExplorerRootKey + @"\Main\FeatureControl\FEATURE_BROWSER_EMULATION";
public static BrowserEmulationVersion GetBrowserEmulationVersion()
{
BrowserEmulationVersion result;
result = BrowserEmulationVersion.Default;
try
{
RegistryKey key;
key = Registry.CurrentUser.OpenSubKey(BrowserEmulationKey, true);
if (key != null)
{
string programName;
object value;
programName = Path.GetFileName(Environment.GetCommandLineArgs()[0]);
value = key.GetValue(programName, null);
if (value != null)
{
result = (BrowserEmulationVersion)Convert.ToInt32(value);
}
}
}
catch (SecurityException)
{
// The user does not have the permissions required to read from the registry key.
}
catch (UnauthorizedAccessException)
{
// The user does not have the necessary registry rights.
}
return result;
}
public static bool SetBrowserEmulationVersion(BrowserEmulationVersion browserEmulationVersion)
{
bool result;
result = false;
try
{
RegistryKey key;
key = Registry.CurrentUser.OpenSubKey(BrowserEmulationKey, true);
if (key != null)
{
string programName;
programName = Path.GetFileName(Environment.GetCommandLineArgs()[0]);
if (browserEmulationVersion != BrowserEmulationVersion.Default)
{
// if it's a valid value, update or create the value
key.SetValue(programName, (int)browserEmulationVersion, RegistryValueKind.DWord);
}
else
{
// otherwise, remove the existing value
key.DeleteValue(programName, false);
}
result = true;
}
}
catch (SecurityException)
{
// The user does not have the permissions required to read from the registry key.
}
catch (UnauthorizedAccessException)
{
// The user does not have the necessary registry rights.
}
return result;
}
public static bool SetBrowserEmulationVersion()
{
int ieVersion;
BrowserEmulationVersion emulationCode;
ieVersion = GetInternetExplorerMajorVersion();
if (ieVersion >= 11)
{
emulationCode = BrowserEmulationVersion.Version11;
}
else
{
switch (ieVersion)
{
case 10:
emulationCode = BrowserEmulationVersion.Version10;
break;
case 9:
emulationCode = BrowserEmulationVersion.Version9;
break;
case 8:
emulationCode = BrowserEmulationVersion.Version8;
break;
default:
emulationCode = BrowserEmulationVersion.Version7;
break;
}
}
return SetBrowserEmulationVersion(emulationCode);
}
public static bool IsBrowserEmulationSet()
{
return GetBrowserEmulationVersion() != BrowserEmulationVersion.Default;
}
}
You just need to create a class and put this code in it, then run the following code when the program starts:
if (!WBEmulator.IsBrowserEmulationSet())
{
WBEmulator.SetBrowserEmulationVersion();
}
VB.NET:
Imports Microsoft.Win32
Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Linq
Imports System.Security
Imports System.Text
Imports System.Threading.Tasks
Public Enum BrowserEmulationVersion
[Default] = 0
Version7 = 7000
Version8 = 8000
Version8Standards = 8888
Version9 = 9000
Version9Standards = 9999
Version10 = 10000
Version10Standards = 10001
Version11 = 11000
Version11Edge = 11001
End Enum
Public Class WBEmulator
Private Const InternetExplorerRootKey As String = "Software\Microsoft\Internet Explorer"
Public Shared Function GetInternetExplorerMajorVersion() As Integer
Dim result As Integer
result = 0
Try
Dim key As RegistryKey
key = Registry.LocalMachine.OpenSubKey(InternetExplorerRootKey)
If key IsNot Nothing Then
Dim value As Object = If(key.GetValue("svcVersion", Nothing), key.GetValue("Version", Nothing))
Dim Version As String
Dim separator As Integer
Version = value.ToString()
separator = Version.IndexOf(".")
If separator <> -1 Then
Integer.TryParse(Version.Substring(0, separator), result)
End If
End If
Catch ex As SecurityException
'The user does Not have the permissions required to read from the registry key.
Catch ex As UnauthorizedAccessException
'The user does Not have the necessary registry rights.
Catch
End Try
GetInternetExplorerMajorVersion = result
End Function
Private Const BrowserEmulationKey = InternetExplorerRootKey + "\Main\FeatureControl\FEATURE_BROWSER_EMULATION"
Public Shared Function GetBrowserEmulationVersion() As BrowserEmulationVersion
Dim result As BrowserEmulationVersion
result = BrowserEmulationVersion.Default
Try
Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey(BrowserEmulationKey, True)
If key IsNot Nothing Then
Dim programName As String
Dim value As Object
programName = Path.GetFileName(Environment.GetCommandLineArgs()(0))
value = key.GetValue(programName, Nothing)
If value IsNot Nothing Then
result = CType(Convert.ToInt32(value), BrowserEmulationVersion)
End If
End If
Catch ex As SecurityException
'The user does Not have the permissions required to read from the registry key.
Catch ex As UnauthorizedAccessException
'The user does Not have the necessary registry rights.
Catch
End Try
GetBrowserEmulationVersion = result
End Function
Public Shared Function SetBrowserEmulationVersion(BEVersion As BrowserEmulationVersion) As Boolean
Dim result As Boolean = False
Try
Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey(BrowserEmulationKey, True)
If key IsNot Nothing Then
Dim programName As String = Path.GetFileName(Environment.GetCommandLineArgs()(0))
If BEVersion <> BrowserEmulationVersion.Default Then
'if it's a valid value, update or create the value
key.SetValue(programName, CType(BEVersion, Integer), RegistryValueKind.DWord)
Else
'otherwise, remove the existing value
key.DeleteValue(programName, False)
End If
result = True
End If
Catch ex As SecurityException
' The user does Not have the permissions required to read from the registry key.
Catch ex As UnauthorizedAccessException
' The user does Not have the necessary registry rights.
End Try
SetBrowserEmulationVersion = result
End Function
Public Shared Function SetBrowserEmulationVersion() As Boolean
Dim ieVersion As Integer
Dim emulationCode As BrowserEmulationVersion
ieVersion = GetInternetExplorerMajorVersion()
If ieVersion >= 11 Then
emulationCode = BrowserEmulationVersion.Version11
Else
Select Case ieVersion
Case 10
emulationCode = BrowserEmulationVersion.Version10
Case 9
emulationCode = BrowserEmulationVersion.Version9
Case 8
emulationCode = BrowserEmulationVersion.Version8
Case Else
emulationCode = BrowserEmulationVersion.Version7
End Select
End If
SetBrowserEmulationVersion = SetBrowserEmulationVersion(emulationCode)
End Function
Public Shared Function IsBrowserEmulationSet() As Boolean
IsBrowserEmulationSet = GetBrowserEmulationVersion() <> BrowserEmulationVersion.Default
End Function
End Class
You may use it like:
If Not WBEmulator.IsBrowserEmulationSet() Then
WBEmulator.SetBrowserEmulationVersion()
End If
I had the same problem.
I already had a g++ compiler installed thru MinGW (the package mingw32-gcc-g++) but I needed a C compiler so I ran mingw-get-setup.exe where I was able to have it install the mingw32-base package, the one with the C compiler.
Alas! I had this error when I use gcc to compile:
gcc: error: createprocess: no such file or directory
What I did was, still using the MinGW Installation Manager, I removed the C and C++ compiler packages, namely mingw32-base and mingw32-gcc-g++ and ALSO deleted the C:\MinGW directory itself. Then I reran mingw-get-setup.exe, installed mingw32-base, and voila, it worked :)
You also can use some HTML5 attributes, some browsers might already take advantage of them (type="number" min="0"
).
Whatever you do, remember to re-check your inputs on the server side: you can never assume the client-side validation has been performed.
The error you gave is due to the fact that in python, dictionary keys must be immutable types (if key can change, there will be problems), and list is a mutable type.
Your error says that you try to use a list as dictionary key, you'll have to change your list into tuples if you want to put them as keys in your dictionary.
According to the python doc :
The only types of values not acceptable as keys are values containing lists or dictionaries or other mutable types that are compared by value rather than by object identity, the reason being that the efficient implementation of dictionaries requires a key’s hash value to remain constant
I was Forming some Programming Logic Used CHAR(34) for Quotes at Excel : A small Part of same I am posting which can be helpfull ,Hopefully
1 Customers
2 Invoices
Formula Used :
=CONCATENATE("listEvents.Add(",D4,",",CHAR(34),E4,CHAR(34),");")
Result :
listEvents.Add(1,"Customers");
listEvents.Add(2,"Invoices");
If you want to go even further than @tetra with ES6 you can use the Object spread syntax and do something like this:
let john = {
firstName: "John",
lastName: "Doe",
};
let people = new Array(10).fill().map((e, i) => {(...john, id: i});
if (StartDate>=EndDate)
{
throw new InvalidOperationException("Ack! StartDate is not before EndDate!");
}
echo date('d/m/Y', strtotime('+7 days'));
public void getDatabaseMetaData()
{
try {
DatabaseMetaData dbmd = conn.getMetaData();
String[] types = {"TABLE"};
ResultSet rs = dbmd.getTables(null, null, "%", types);
while (rs.next()) {
System.out.println(rs.getString("TABLE_NAME"));
}
}
catch (SQLException e) {
e.printStackTrace();
}
}
There are many ways to do what you're asking for:
float
property: <div style="width: 100%; overflow: hidden;">
<div style="width: 600px; float: left;"> Left </div>
<div style="margin-left: 620px;"> Right </div>
</div>
_x000D_
display
property - which can be used to make div
s act like a table
:<div style="width: 100%; display: table;">
<div style="display: table-row">
<div style="width: 600px; display: table-cell;"> Left </div>
<div style="display: table-cell;"> Right </div>
</div>
</div>
_x000D_
There are more methods, but those two are the most popular.
This is jQuery Email Validation using Regex Expression. you can also use the same concept for AngularJS if you have idea of AngularJS.
var expression = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
class MyClass {}
const instance = new MyClass();
console.log(instance.constructor.name); // MyClass
console.log(MyClass.name); // MyClass
However: beware that the name will likely be different when using minified code.
Putting a <br clear="all" />
after the last floated div worked the best for me. Thanks to Brent Fiare & Paul Waite for the info that floated divs will not expand the height of the parent div! This has been driving me nuts! ;-}
If I remember correctly the delphi IDE did a default indent of two spaces. Most of the legacy code for the company had three spaces and was written by the VP IT and the CEO. One day, all the programmers were talking about what we should do to make our lives easier and a contractor who knew Delphi pretty well said, "Hey the ide defaults to two spaces does anyone have a problem with us doing this going forward for new code?" All of us looked at each other, and pretty much thought it was a no brainer and said that we agreed.
Two days later the VP and CEO found out we were going to make such a dangerous change that could "cause problems" and instructed us that we would be using three indents for everything until the two of them could accurately evaluate the impact of such a change. Now I am all for following standards, but these are the same people who thought oo programming was creating an object with one function that had all of the logic necessary to perform an action, and that source control was moving the code files to a different directory.
In swift 3 use this -
object?.addTarget(objectWhichHasMethod, action: #selector(classWhichHasMethod.yourMethod), for: someUIControlEvents)
For example(from my code) -
self.datePicker?.addTarget(self, action:#selector(InfoTableViewCell.datePickerValueChanged), for: .valueChanged)
Just give a :
after method name if you want the sender as parameter.
I was having the same issue and tried all of the solutions on this page but none of them did the trick.
What finally worked was adding the universe
repo to my repo list. To do that run the following command
sudo add-apt-repository universe
After running the above command I was able to run
sudo apt install openjdk-8-jre
without an issue and the package was installed.
Hope this helps someone.
html
<input type="hidden" #fondovalor value="valores">
<button (click)="getFotoFondo()">Obtener</button>
ts
@ViewChild('fondovalor') fondovalor:ElementRef;
getFotoFondo(){
const valueInput = this.fondovalor.nativeElement.value
}
x <- c(1:10)
# empty data frame with variables ----
df <- data.frame(x1=character(),
y1=character())
for (i in x) {
a1 <- c(x1 == paste0("The number is ",x[i]),y1 == paste0("This is another number ", x[i]))
df <- rbind(df,a1)
}
names(df) <- c("st_column","nd_column")
View(df)
that might be a good way to do so....
The new Android Design Support Library adds TabLayout, providing a tab implementation that matches the material design guidelines for tabs. A complete walkthrough of how to implement Tabs and ViewPager
can be found in this video
Now deprecated: The PagerTabStrip is part of the support library (and has been for some time) and serves as a direct replacement. If you prefer the newer Google Play style tabs, you can use the PagerSlidingTabStrip library or modify either of the Google provided examples SlidingTabsBasic or SlidingTabsColors as explained in this Dev Bytes video.
To save the Log cat content to the file, you need to redirect to the android sdk's platform tools folder and hit the below command
adb logcat > logcat.txt
In Android Studio, version 3.6RC1, file will be created of the name "logcat.txt" in respective project folder. you can change the name according to your interest. enjoy
If FName and LName contain NULL values, then you will need special handling to avoid unnecessary extra preceeding, trailing, and middle spaces. Also, if Address1 contains NULL values, then you need to have special handling to prevent adding unnecessary ', ' at the beginning of your address string.
If you are using SQL Server 2012, then you can use CONCAT (NULLs are automatically treated as empty strings) and IIF:
INSERT INTO TblStuff (FullName, Address, City, Zip)
SELECT FullName = REPLACE(RTRIM(LTRIM(CONCAT(FName, ' ', Middle, ' ', LName))), ' ', ' ')
, Address = CONCAT(Address1, IIF(Address2 IS NOT NULL, CONCAT(', ', Address2), ''))
, City
, Zip
FROM tblImport (NOLOCK);
Otherwise, this will work:
INSERT INTO TblStuff (FullName, Address, City, Zip)
SELECT FullName = REPLACE(RTRIM(LTRIM(ISNULL(FName, '') + ' ' + ISNULL(Middle, '') + ' ' + ISNULL(LName, ''))), ' ', ' ')
, Address = ISNULL(Address1, '') + CASE
WHEN Address2 IS NOT NULL THEN ', ' + Address2
ELSE '' END
, City
, Zip
FROM tblImport (NOLOCK);
SlickEdit is very cool, and does support something like intellisense. At my current company I now use Visual Studio, and I've mostly gotten used to it - but there are still some SlickEdit features I miss.
This is a good one: apps-for-android
Here my demo: https://stackblitz.com/edit/react-dgz1ee?file=styles.css
I am using useEffect
to call the children component's methods. I have tried with Proxy and Setter_Getter
but sor far useEffect
seems to be the more convenient way to call a child method from parent. To use Proxy and Setter_Getter
it seems there is some subtlety to overcome first, because the element firstly rendered is an objectLike's element through the ref.current return => <div/>
's specificity.
Concerning useEffect
, you can also leverage on this approach to set the parent's state depending on what you want to do with the children.
In the demo's link I have provided, you will find my full ReactJS' code with my draftwork inside's so you can appreciate the workflow of my solution.
Here I am providing you my ReactJS' snippet with the relevant code only. :
import React, {
Component,
createRef,
forwardRef,
useState,
useEffect
} from "react";
{...}
// Child component
// I am defining here a forwardRef's element to get the Child's methods from the parent
// through the ref's element.
let Child = forwardRef((props, ref) => {
// I am fetching the parent's method here
// that allows me to connect the parent and the child's components
let { validateChildren } = props;
// I am initializing the state of the children
// good if we can even leverage on the functional children's state
let initialState = {
one: "hello world",
two: () => {
console.log("I am accessing child method from parent :].");
return "child method achieve";
}
};
// useState initialization
const [componentState, setComponentState] = useState(initialState);
// useEffect will allow me to communicate with the parent
// through a lifecycle data flow
useEffect(() => {
ref.current = { componentState };
validateChildren(ref.current.componentState.two);
});
{...}
});
{...}
// Parent component
class App extends Component {
// initialize the ref inside the constructor element
constructor(props) {
super(props);
this.childRef = createRef();
}
// I am implementing a parent's method
// in child useEffect's method
validateChildren = childrenMethod => {
// access children method from parent
childrenMethod();
// or signaling children is ready
console.log("children active");
};
{...}
render(){
return (
{
// I am referencing the children
// also I am implementing the parent logic connector's function
// in the child, here => this.validateChildren's function
}
<Child ref={this.childRef} validateChildren={this.validateChildren} />
</div>
)
}
Use the built in date_sub and date_add functions to math with dates. (See http://php.net/manual/en/datetime.sub.php)
Similar to Sazzad's answer, but in procedural style PHP,
$date = date_create('2008-12-02');
date_sub($date, date_interval_create_from_date_string('5 days'));
echo date_format($date, 'Y-m-d'); //outputs 2008-11-27
I have another solution that works fine if you have a local copy of the repository on the machine where you would like to create the export. In this case move to this repository directory, and enter this command:
GIT_WORK_TREE=outputdirectory git checkout -f
This is particularly useful if you manage a website with a git repository and would like to checkout a clean version in /var/www/
. In this case, add thiscommand in a .git/hooks/post-receive
script (hooks/post-receive
on a bare repository, which is more suitable in this situation)
If you use the matplotlib object-oriented approach, this is a simple task using ax.set_xticklabels()
and ax.set_yticklabels()
:
import matplotlib.pyplot as plt
# Create Figure and Axes instances
fig,ax = plt.subplots(1)
# Make your plot, set your axes labels
ax.plot(sim_1['t'],sim_1['V'],'k')
ax.set_ylabel('V')
ax.set_xlabel('t')
# Turn off tick labels
ax.set_yticklabels([])
ax.set_xticklabels([])
plt.show()
For Xamarin Android align to the left of an object
int dp24 = (int)TypedValue.ApplyDimension( ComplexUnitType.Dip, 24, Resources.System.DisplayMetrics );
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams( dp24, dp24 );
lp.AddRule( LayoutRules.CenterInParent, 1 );
lp.AddRule( LayoutRules.LeftOf, //Id of the field Eg m_Button.Id );
m_Button.LayoutParameters = lp;
Non-reflective solution for Java 8, without using a series of if's, would be to stream all fields and check for nullness:
return Stream.of(id, name).allMatch(Objects::isNull);
This remains quite easy to maintain while avoiding the reflection hammer. This will return true for null attributes.
["1","2","3","4"].forEach( function(item) {
const optionObj = document.createElement("option");
optionObj.textContent = item;
document.getElementById("myselect").appendChild(optionObj);
});
This is VanillaJS (unmodified):
// VanillaJS v1.0
// Released into the Public Domain
// Your code goes here:
As you can see, it's not really a framework or a library. It's just a running gag for framework-loving bosses or people who think you NEED to use a JS framework. It means you just use whatever your (for you own sake: non-legacy) browser gives you (using Vanilla JS when working with legacy browsers is a bad idea).
func convertDateFormater(date: String) -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
dateFormatter.timeZone = NSTimeZone(name: "UTC")
guard let date = dateFormatter.dateFromString(date) else {
assert(false, "no date from string")
return ""
}
dateFormatter.dateFormat = "yyyy MMM EEEE HH:mm"
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let timeStamp = dateFormatter.stringFromDate(date)
return timeStamp
}
Edit for Swift 4
func convertDateFormatter(date: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"//this your string date format
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
dateFormatter.locale = Locale(identifier: "your_loc_id")
let convertedDate = dateFormatter.date(from: date)
guard dateFormatter.date(from: date) != nil else {
assert(false, "no date from string")
return ""
}
dateFormatter.dateFormat = "yyyy MMM HH:mm EEEE"///this is what you want to convert format
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
let timeStamp = dateFormatter.string(from: convertedDate!)
return timeStamp
}
Here is the full c# code to convert xml to json
public static class JSon
{
public static string XmlToJSON(string xml)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
return XmlToJSON(doc);
}
public static string XmlToJSON(XmlDocument xmlDoc)
{
StringBuilder sbJSON = new StringBuilder();
sbJSON.Append("{ ");
XmlToJSONnode(sbJSON, xmlDoc.DocumentElement, true);
sbJSON.Append("}");
return sbJSON.ToString();
}
// XmlToJSONnode: Output an XmlElement, possibly as part of a higher array
private static void XmlToJSONnode(StringBuilder sbJSON, XmlElement node, bool showNodeName)
{
if (showNodeName)
sbJSON.Append("\"" + SafeJSON(node.Name) + "\": ");
sbJSON.Append("{");
// Build a sorted list of key-value pairs
// where key is case-sensitive nodeName
// value is an ArrayList of string or XmlElement
// so that we know whether the nodeName is an array or not.
SortedList<string, object> childNodeNames = new SortedList<string, object>();
// Add in all node attributes
if (node.Attributes != null)
foreach (XmlAttribute attr in node.Attributes)
StoreChildNode(childNodeNames, attr.Name, attr.InnerText);
// Add in all nodes
foreach (XmlNode cnode in node.ChildNodes)
{
if (cnode is XmlText)
StoreChildNode(childNodeNames, "value", cnode.InnerText);
else if (cnode is XmlElement)
StoreChildNode(childNodeNames, cnode.Name, cnode);
}
// Now output all stored info
foreach (string childname in childNodeNames.Keys)
{
List<object> alChild = (List<object>)childNodeNames[childname];
if (alChild.Count == 1)
OutputNode(childname, alChild[0], sbJSON, true);
else
{
sbJSON.Append(" \"" + SafeJSON(childname) + "\": [ ");
foreach (object Child in alChild)
OutputNode(childname, Child, sbJSON, false);
sbJSON.Remove(sbJSON.Length - 2, 2);
sbJSON.Append(" ], ");
}
}
sbJSON.Remove(sbJSON.Length - 2, 2);
sbJSON.Append(" }");
}
// StoreChildNode: Store data associated with each nodeName
// so that we know whether the nodeName is an array or not.
private static void StoreChildNode(SortedList<string, object> childNodeNames, string nodeName, object nodeValue)
{
// Pre-process contraction of XmlElement-s
if (nodeValue is XmlElement)
{
// Convert <aa></aa> into "aa":null
// <aa>xx</aa> into "aa":"xx"
XmlNode cnode = (XmlNode)nodeValue;
if (cnode.Attributes.Count == 0)
{
XmlNodeList children = cnode.ChildNodes;
if (children.Count == 0)
nodeValue = null;
else if (children.Count == 1 && (children[0] is XmlText))
nodeValue = ((XmlText)(children[0])).InnerText;
}
}
// Add nodeValue to ArrayList associated with each nodeName
// If nodeName doesn't exist then add it
List<object> ValuesAL;
if (childNodeNames.ContainsKey(nodeName))
{
ValuesAL = (List<object>)childNodeNames[nodeName];
}
else
{
ValuesAL = new List<object>();
childNodeNames[nodeName] = ValuesAL;
}
ValuesAL.Add(nodeValue);
}
private static void OutputNode(string childname, object alChild, StringBuilder sbJSON, bool showNodeName)
{
if (alChild == null)
{
if (showNodeName)
sbJSON.Append("\"" + SafeJSON(childname) + "\": ");
sbJSON.Append("null");
}
else if (alChild is string)
{
if (showNodeName)
sbJSON.Append("\"" + SafeJSON(childname) + "\": ");
string sChild = (string)alChild;
sChild = sChild.Trim();
sbJSON.Append("\"" + SafeJSON(sChild) + "\"");
}
else
XmlToJSONnode(sbJSON, (XmlElement)alChild, showNodeName);
sbJSON.Append(", ");
}
// Make a string safe for JSON
private static string SafeJSON(string sIn)
{
StringBuilder sbOut = new StringBuilder(sIn.Length);
foreach (char ch in sIn)
{
if (Char.IsControl(ch) || ch == '\'')
{
int ich = (int)ch;
sbOut.Append(@"\u" + ich.ToString("x4"));
continue;
}
else if (ch == '\"' || ch == '\\' || ch == '/')
{
sbOut.Append('\\');
}
sbOut.Append(ch);
}
return sbOut.ToString();
}
}
To convert a given XML string to JSON, simply call XmlToJSON() function as below.
string xml = "<menu id=\"file\" value=\"File\"> " +
"<popup>" +
"<menuitem value=\"New\" onclick=\"CreateNewDoc()\" />" +
"<menuitem value=\"Open\" onclick=\"OpenDoc()\" />" +
"<menuitem value=\"Close\" onclick=\"CloseDoc()\" />" +
"</popup>" +
"</menu>";
string json = JSON.XmlToJSON(xml);
// json = { "menu": {"id": "file", "popup": { "menuitem": [ {"onclick": "CreateNewDoc()", "value": "New" }, {"onclick": "OpenDoc()", "value": "Open" }, {"onclick": "CloseDoc()", "value": "Close" } ] }, "value": "File" }}
create a file called mongostop.bat
save the following code in it
mongo admin --eval "db.shutdownServer()"
run the file mongostop.bat and you successfully have mongo stopped
I am not familiar with JXL and but we use POI. POI is well maintained and can handle both the binary .xls format and the new xml based format that was introduced in Office 2007.
CSV files are not excel files, they are text based files, so these libraries don't read them. You will need to parse out a CSV file yourself. I am not aware of any CSV file libraries, but I haven't looked either.
^ outside of the character class ("[a-zA-Z]") notes that it is the "begins with" operator.
^ inside of the character negates the specified class.
So, "^[a-zA-Z]" translates to "begins with character from a-z or A-Z", and "[^a-zA-Z]" translates to "is not either a-z or A-Z"
Here's a quick reference: http://www.regular-expressions.info/reference.html
For MacOS users:
Just do this and easily it will solve your problem:
brew install cocoapods
From Laravel 5.7 with Illuminate\Database\Query\Builder
you can use insertUsing method.
$query = [];
foreach($oXML->results->item->item as $oEntry){
$date = date("Y-m-d H:i:s")
$query[] = "('{$oEntry->firstname}', '{$oEntry->lastname}', '{$date}')";
}
Builder::insertUsing(['first_name', 'last_name', 'date_added'], implode(', ', $query));
Assuming you build your jar file with ant, you can just instruct ant to leave out the META-INF dir. This is a simplified version of my ant target:
<jar destfile="app.jar" basedir="${classes.dir}">
<zipfileset excludes="META-INF/**/*" src="${lib.dir}/bcprov-jdk16-145.jar"></zipfileset>
<manifest>
<attribute name="Main-Class" value="app.Main"/>
</manifest>
</jar>