Add the following property:
.c{
...
overflow: hidden;
}
This will force the container to respect the height of all elements within it, regardless of floating elements.
http://jsfiddle.net/gtdfY/3/
Recently, I was working on a project that required this trick, but needed to allow overflow to show, so instead, you can use a pseudo-element to clear your floats, effectively achieving the same effect while allowing overflow on all elements.
.c:after{
clear: both;
content: "";
display: block;
}
My first post... UDF I managed quickly to compile. Usage: Select 3D range as normal and enclose is into quotation marks like below...
=CountIf3D("'StartSheet:EndSheet'!G16:G878";"Criteria")
Advisably sheets to be adjacent to avoid unanticipated results.
Public Function CountIf3D(SheetstoCount As String, CriteriaToUse As Variant)
Dim sStarSheet As String, sEndSheet As String, sAddress As String
Dim lColonPos As Long, lExclaPos As Long, cnt As Long
lColonPos = InStr(SheetstoCount, ":") 'Finding ':' separating sheets
lExclaPos = InStr(SheetstoCount, "!") 'Finding '!' separating address from the sheets
sStarSheet = Mid(SheetstoCount, 2, lColonPos - 2) 'Getting first sheet's name
sEndSheet = Mid(SheetstoCount, lColonPos + 1, lExclaPos - lColonPos - 2) 'Getting last sheet's name
sAddress = Mid(SheetstoCount, lExclaPos + 1, Len(SheetstoCount) - lExclaPos) 'Getting address
cnt = 0
For i = Sheets(sStarSheet).Index To Sheets(sEndSheet).Index
cnt = cnt + Application.CountIf(Sheets(i).Range(sAddress), CriteriaToUse)
Next
CountIf3D = cnt
End Function
You can simply use replace() function,
with where clause-
update tabelName set columnName=REPLACE(columnName,'from','to') where condition;
without where clause-
update tabelName set columnName=REPLACE(columnName,'from','to');
Note: The above query if for update records directly in table, if you want on select query and the data should not be affected in table then can use the following query-
select REPLACE(columnName,'from','to') as updateRecord;
In my case I was missing "e" on the word "email" as Chad stated above but I see its not the case with you. Please hit the following command to see if everything is pulling as expected.
git config -l
Git has two types of branches: local
and remote
. To use git pull
and git push
as you'd like, you have to tell your local branch (my_test
) which remote branch it's tracking. In typical Git fashion this can be done in both the config file and with commands.
Commands
Make sure you're on your master
branch with
1)git checkout master
then create the new branch with
2)git branch --track my_test origin/my_test
and check it out with
3)git checkout my_test
.
You can then push
and pull
without specifying which local and remote.
However if you've already created the branch then you can use the -u
switch to tell git's push
and pull
you'd like to use the specified local and remote branches from now on, like so:
git pull -u my_test origin/my_test
git push -u my_test origin/my_test
Config
The commands to setup remote branch tracking are fairly straight forward but I'm listing the config way as well as I find it easier if I'm setting up a bunch of tracking branches. Using your favourite editor open up your project's .git/config
and add the following to the bottom.
[remote "origin"]
url = [email protected]:username/repo.git
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "my_test"]
remote = origin
merge = refs/heads/my_test
This specifies a remote called origin
, in this case a GitHub style one, and then tells the branch my_test
to use it as it's remote.
You can find something very similar to this in the config after running the commands above.
Some useful resources:
You can do it using the plain JavaScript:
function trimString(str, maxLen) {
if (str.length <= maxLen) {
return str;
}
var trimmed = str.substr(0, maxLen);
return trimmed.substr(0, trimmed.lastIndexOf(' ')) + '…';
}
// Let's test it
sentenceOne = "too short";
sentencetwo = "more than the max length";
console.log(trimString(sentenceOne, 15));
console.log(trimString(sentencetwo, 15));
your validation should be occur before your event suppose you are going to submit your form.
anyway if you want this on onchange, so here is code.
function valid(id)
{
var textVal=document.getElementById(id).value;
if (!textVal.match(/\S/))
{
alert("Field is blank");
return false;
}
else
{
return true;
}
}
Usually this is an error in your PHP configuration.
It's actually pretty easy to figure out what exactly is going on:
Like this:
<video width="300" height="200" autoplay="autoplay">
<source src="video/supercoolvideo.mp4" type="video/mp4" />
</video>
controls
is a boolean attribute:
Note: The values "true" and "false" are not allowed on boolean attributes. To represent a false value, the attribute has to be omitted altogether.
You've got the right idea, so here's how to go ahead: the onclick
handlers run on the client side, in the browser, so you cannot call a PHP function directly. Instead, you need to add a JavaScript function that (as you mentioned) uses AJAX to call a PHP script and retrieve the data. Using jQuery, you can do something like this:
<script type="text/javascript">
function recp(id) {
$('#myStyle').load('data.php?id=' + id);
}
</script>
<a href="#" onClick="recp('1')" > One </a>
<a href="#" onClick="recp('2')" > Two </a>
<a href="#" onClick="recp('3')" > Three </a>
<div id='myStyle'>
</div>
Then you put your PHP code into a separate file: (I've called it data.php
in the above example)
<?php
require ('myConnect.php');
$id = $_GET['id'];
$results = mysql_query("SELECT para FROM content WHERE para_ID='$id'");
if( mysql_num_rows($results) > 0 )
{
$row = mysql_fetch_array( $results );
echo $row['para'];
}
?>
Take a look at my jquery videoBG plugin
http://syddev.com/jquery.videoBG/
Make any HTML5 video a site background... has an image fallback for browsers that don't support html5
Really easy to use
Let me know if you need any help.
In my taste, it's also very concise to combine zip()
with xrange(n)
(or range(n)
in Python3), which works nice on generators as well and seems to be more flexible for changes in general.
# Option #1: taking the first n elements as a list
[x for _, x in zip(xrange(n), generator)]
# Option #2, using 'next()' and taking care for 'StopIteration'
[next(generator) for _ in xrange(n)]
# Option #3: taking the first n elements as a new generator
(x for _, x in zip(xrange(n), generator))
# Option #4: yielding them by simply preparing a function
# (but take care for 'StopIteration')
def top_n(n, generator):
for _ in xrange(n): yield next(generator)
this is the best way to solve this
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
With Java 8, the new java.time package should be used.
Objects are immutable, time zones and day light saving are taken into account.
You can create a ZonedDateTime
object from an old java.util.Date
object like this:
Date date = new Date();
ZonedDateTime zonedDateTime = date.toInstant().atZone(ZoneId.systemDefault());
You can use CFArray instead of NSArray. Here is an article explaining how.
CFMutableArrayRef ar = CFArrayCreateMutable(NULL, 0, NULL);
for (NSUInteger i = 0; i < 1000; i++)
{
CFArrayAppendValue(ar, (void*)i);
}
CFRelease(ar); /* Releasing the array */
The same applies for the CoreFoundation version of the other containers too.
Other than the answers mentioned above. This will do it. Using Angular 5 and AngularFire2. or use firebase.firestore() instead of this.afs
// say you have have the following object and
// database structure as you mentioned in your post
data = { who: "[email protected]", when: new Date() };
...othercode
addSharedWith(data) {
const postDocRef = this.afs.collection('posts').doc('docID');
postDocRef.subscribe( post => {
// Grab the existing sharedWith Array
// If post.sharedWith doesn`t exsit initiated with empty array
const foo = { 'sharedWith' : post.sharedWith || []};
// Grab the existing sharedWith Array
foo['sharedWith'].push(data);
// pass updated to fireStore
postsDocRef.update(foo);
// using .set() will overwrite everything
// .update will only update existing values,
// so we initiated sharedWith with empty array
});
}
OAuth 2.0 defines a protocol, i.e. specifies how tokens are transferred, JWT defines a token format.
OAuth 2.0 and "JWT authentication" have similar appearance when it comes to the (2nd) stage where the Client presents the token to the Resource Server: the token is passed in a header.
But "JWT authentication" is not a standard and does not specify how the Client obtains the token in the first place (the 1st stage). That is where the perceived complexity of OAuth comes from: it also defines various ways in which the Client can obtain an access token from something that is called an Authorization Server.
So the real difference is that JWT is just a token format, OAuth 2.0 is a protocol (that may use a JWT as a token format).
Simplest answer is the following.....
All members in C# always take the LEAST accessible modifier possible by default.
That is why all top level classes in an assembly are "internal" by default, which means they are public to the assembly they are in, but private or excluded from access to outside assemblies. The only other option for a top level class is public which is more accessible. For nested types its all private except for a few rare exceptions like members of enums and interfaces which can only be public. Some examples. In the case of top level classes and interfaces, the defaults are:
class Animal same as internal class Animal
interface Animal same as public interface Animal
In the case of nested classes and interfaces (inside types), the defaults are:
class Animal same as private class Animal
interface Animal same as private interface Animal
If you just assume the default is always the most private, then you do not need to use an accessors until you need to change the default. Easy.
this should work:
svn commit -m "<Your message here>" path/to/your/file
you can also add multiple files like this:
svn commit -m "<Your message here>" path/to/your/file [path/to/your/file] [path/to/your/file]
Updating the value of a field does not update its value attribute in the DOM so that's why your selector is always matching a field, even when it's not actually empty.
Instead use the invalid
pseudo-class to achieve what you want, like so:
input:required {_x000D_
border: 1px solid green;_x000D_
}_x000D_
input:required:invalid {_x000D_
border: 1px solid red;_x000D_
}
_x000D_
<input required type="text" value="">_x000D_
_x000D_
<input required type="text" value="Value">
_x000D_
Type on sqlplus
command prompt
SQL> select * from global_name;
then u will be see result on command prompt
SQL ORCL.REGRESS.RDBMS.DEV.US.ORACLE.COM
Here first one "ORCL" is database name,may be your system "XE" and other what was given on oracle downloading time.
Oracle
stores only the fractions up to second in a DATE
field.
Use TIMESTAMP
instead:
SELECT TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9')
FROM dual
, possibly casting it to a DATE
then:
SELECT CAST(TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9') AS DATE)
FROM dual
You do not need to use the while True:
loop in this case. There is a much simpler way to use the time condition directly:
import time
# timeout variable can be omitted, if you use specific value in the while condition
timeout = 300 # [seconds]
timeout_start = time.time()
while time.time() < timeout_start + timeout:
test = 0
if test == 5:
break
test -= 1
Change column position:
ALTER TABLE Employees
CHANGE empName empName VARCHAR(50) NOT NULL AFTER department;
If you need to move it to the first position you have to use term FIRST at the end of ALTER TABLE CHANGE [COLUMN] query:
ALTER TABLE UserOrder
CHANGE order_id order_id INT(11) NOT NULL FIRST;
Use
System.getProperty("java.class.path")
see http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html
You can also split it into it's elements easily
String classpath = System.getProperty("java.class.path");
String[] classpathEntries = classpath.split(File.pathSeparator);
In addition to Ishan's answer, if you want to draw programatically without user interaction, you can edit the class just a little like this.
public class DrawingCanvas extends View {
private Paint mPaint;
private Path mPath;
private boolean isUserInteractionEnabled = false;
public DrawingCanvas(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint();
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(10);
mPath = new Path();
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(mPath, mPaint);
super.onDraw(canvas);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (isUserInteractionEnabled) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mPath.moveTo(event.getX(), event.getY());
break;
case MotionEvent.ACTION_MOVE:
mPath.lineTo(event.getX(), event.getY());
invalidate();
break;
case MotionEvent.ACTION_UP:
break;
}
}
return true;
}
public void moveCursorTo(float x, float y) {
mPath.moveTo(x, y);
}
public void makeLine(float toX, float toY) {
mPath.lineTo(toX, toY);
}
public void setUserInteractionEnabled(boolean userInteractionEnabled) {
isUserInteractionEnabled = userInteractionEnabled;
}
}
And then use it like
drawingCanvas.setUserInteractionEnabled(true) // to enable user interaction
drawingCanvas.setUserInteractionEnabled(true) // to disable user interaction
To Draw programatically
drawingCanvas.moveCursorTo(70f, 70f) // Move the cursor (Define starting point)
drawingCanvas.makeLine(200f, 200f) // End point (To where you need to draw)
NextRow = Application.WorksheetFunction.CountA(Range("A:A")) + 1
I propose an alternative method using seaborn
Working code:
import pandas as pd
import seaborn as sns
data=np.random.rand(10,2)*100
df = pd.DataFrame(data, columns=['A', 'B'])
ax= sns.lineplot(data=df, markers= True)
ax.set(xlabel='xlabel', ylabel='ylabel', title='title')
#changing ylables ticks
y_value=['{:,.2f}'.format(x) + '%' for x in ax.get_yticks()]
ax.set_yticklabels(y_value)
Using environment variable is sometimes more convenient when you do not control the build scripts / process.
For C includes use C_INCLUDE_PATH
.
For C++ includes use CPLUS_INCLUDE_PATH
.
See this link for other gcc environment variables.
# `pip install` will automatically run `gcc` using parameters
# specified in the `asyncpg` package (that I do not control)
C_INCLUDE_PATH=/home/scott/.pyenv/versions/3.7.9/include/python3.7m pip install asyncpg
set C_INCLUDE_PATH="C:\Users\Scott\.pyenv\versions\3.7.9\include\python3.7m"
pip install asyncpg
# clear the environment variable so it doesn't affect other builds
set C_INCLUDE_PATH=
Android Studio 4.0.1
in my case when I press Alt + 6
it shows logcat with no problem but when I click to dismiss it will disappear again and will not be pinned at the bottom so I pressed this little button on the bottom left the screen it worked.
hope it will help somebody :)
Most OLD c++ and c functions, when deal with strings, use const char*
.
With STL and std::string
, string.c_str()
is introduced to be able to convert from std::string
to const char*
.
That means that if you promise not to change the buffer, you'll be able to use read only string contents. PROMISE = const char*
I suggest you to read the Enumeration: Traversing a Collection’s Elements part of the Collections Programming Guide for Cocoa. There is a sample code for your need.
visit this link for reference:http://codepen.io/kalaiselvan/pen/RRBzda
<script>
var app=angular.module('formvalid', ['ui.bootstrap','ui.utils']);
app.controller('validationCtrl',function($scope){
$scope.data=[
[
"Tiger Nixon",
"System Architect",
"Edinburgh",
"5421",
"2011\/04\/25",
"$320,800"
],
[
"Garrett Winters",
"Accountant",
"Tokyo",
"8422",
"2011\/07\/25",
"$170,750"
],
[
"Ashton Cox",
"Junior Technical Author",
"San Francisco",
"1562",
"2009\/01\/12",
"$86,000"
],
[
"Cedric Kelly",
"Senior Javascript Developer",
"Edinburgh",
"6224",
"2012\/03\/29",
"$433,060"
],
[
"Airi Satou",
"Accountant",
"Tokyo",
"5407",
"2008\/11\/28",
"$162,700"
],
[
"Brielle Williamson",
"Integration Specialist",
"New York",
"4804",
"2012\/12\/02",
"$372,000"
],
[
"Herrod Chandler",
"Sales Assistant",
"San Francisco",
"9608",
"2012\/08\/06",
"$137,500"
],
[
"Rhona Davidson",
"Integration Specialist",
"Tokyo",
"6200",
"2010\/10\/14",
"$327,900"
],
[
"Colleen Hurst",
"Javascript Developer",
"San Francisco",
"2360",
"2009\/09\/15",
"$205,500"
],
[
"Sonya Frost",
"Software Engineer",
"Edinburgh",
"1667",
"2008\/12\/13",
"$103,600"
],
[
"Jena Gaines",
"Office Manager",
"London",
"3814",
"2008\/12\/19",
"$90,560"
],
[
"Quinn Flynn",
"Support Lead",
"Edinburgh",
"9497",
"2013\/03\/03",
"$342,000"
],
[
"Charde Marshall",
"Regional Director",
"San Francisco",
"6741",
"2008\/10\/16",
"$470,600"
],
[
"Haley Kennedy",
"Senior Marketing Designer",
"London",
"3597",
"2012\/12\/18",
"$313,500"
],
[
"Tatyana Fitzpatrick",
"Regional Director",
"London",
"1965",
"2010\/03\/17",
"$385,750"
],
[
"Michael Silva",
"Marketing Designer",
"London",
"1581",
"2012\/11\/27",
"$198,500"
],
[
"Paul Byrd",
"Chief Financial Officer (CFO)",
"New York",
"3059",
"2010\/06\/09",
"$725,000"
],
[
"Gloria Little",
"Systems Administrator",
"New York",
"1721",
"2009\/04\/10",
"$237,500"
],
[
"Bradley Greer",
"Software Engineer",
"London",
"2558",
"2012\/10\/13",
"$132,000"
],
[
"Dai Rios",
"Personnel Lead",
"Edinburgh",
"2290",
"2012\/09\/26",
"$217,500"
],
[
"Jenette Caldwell",
"Development Lead",
"New York",
"1937",
"2011\/09\/03",
"$345,000"
],
[
"Yuri Berry",
"Chief Marketing Officer (CMO)",
"New York",
"6154",
"2009\/06\/25",
"$675,000"
],
[
"Caesar Vance",
"Pre-Sales Support",
"New York",
"8330",
"2011\/12\/12",
"$106,450"
],
[
"Doris Wilder",
"Sales Assistant",
"Sidney",
"3023",
"2010\/09\/20",
"$85,600"
],
[
"Angelica Ramos",
"Chief Executive Officer (CEO)",
"London",
"5797",
"2009\/10\/09",
"$1,200,000"
],
[
"Gavin Joyce",
"Developer",
"Edinburgh",
"8822",
"2010\/12\/22",
"$92,575"
],
[
"Jennifer Chang",
"Regional Director",
"Singapore",
"9239",
"2010\/11\/14",
"$357,650"
],
[
"Brenden Wagner",
"Software Engineer",
"San Francisco",
"1314",
"2011\/06\/07",
"$206,850"
],
[
"Fiona Green",
"Chief Operating Officer (COO)",
"San Francisco",
"2947",
"2010\/03\/11",
"$850,000"
],
[
"Shou Itou",
"Regional Marketing",
"Tokyo",
"8899",
"2011\/08\/14",
"$163,000"
],
[
"Michelle House",
"Integration Specialist",
"Sidney",
"2769",
"2011\/06\/02",
"$95,400"
],
[
"Suki Burks",
"Developer",
"London",
"6832",
"2009\/10\/22",
"$114,500"
],
[
"Prescott Bartlett",
"Technical Author",
"London",
"3606",
"2011\/05\/07",
"$145,000"
],
[
"Gavin Cortez",
"Team Leader",
"San Francisco",
"2860",
"2008\/10\/26",
"$235,500"
],
[
"Martena Mccray",
"Post-Sales support",
"Edinburgh",
"8240",
"2011\/03\/09",
"$324,050"
],
[
"Unity Butler",
"Marketing Designer",
"San Francisco",
"5384",
"2009\/12\/09",
"$85,675"
],
[
"Howard Hatfield",
"Office Manager",
"San Francisco",
"7031",
"2008\/12\/16",
"$164,500"
],
[
"Hope Fuentes",
"Secretary",
"San Francisco",
"6318",
"2010\/02\/12",
"$109,850"
],
[
"Vivian Harrell",
"Financial Controller",
"San Francisco",
"9422",
"2009\/02\/14",
"$452,500"
],
[
"Timothy Mooney",
"Office Manager",
"London",
"7580",
"2008\/12\/11",
"$136,200"
],
[
"Jackson Bradshaw",
"Director",
"New York",
"1042",
"2008\/09\/26",
"$645,750"
],
[
"Olivia Liang",
"Support Engineer",
"Singapore",
"2120",
"2011\/02\/03",
"$234,500"
],
[
"Bruno Nash",
"Software Engineer",
"London",
"6222",
"2011\/05\/03",
"$163,500"
],
[
"Sakura Yamamoto",
"Support Engineer",
"Tokyo",
"9383",
"2009\/08\/19",
"$139,575"
],
[
"Thor Walton",
"Developer",
"New York",
"8327",
"2013\/08\/11",
"$98,540"
],
[
"Finn Camacho",
"Support Engineer",
"San Francisco",
"2927",
"2009\/07\/07",
"$87,500"
],
[
"Serge Baldwin",
"Data Coordinator",
"Singapore",
"8352",
"2012\/04\/09",
"$138,575"
],
[
"Zenaida Frank",
"Software Engineer",
"New York",
"7439",
"2010\/01\/04",
"$125,250"
],
[
"Zorita Serrano",
"Software Engineer",
"San Francisco",
"4389",
"2012\/06\/01",
"$115,000"
],
[
"Jennifer Acosta",
"Junior Javascript Developer",
"Edinburgh",
"3431",
"2013\/02\/01",
"$75,650"
],
[
"Cara Stevens",
"Sales Assistant",
"New York",
"3990",
"2011\/12\/06",
"$145,600"
],
[
"Hermione Butler",
"Regional Director",
"London",
"1016",
"2011\/03\/21",
"$356,250"
],
[
"Lael Greer",
"Systems Administrator",
"London",
"6733",
"2009\/02\/27",
"$103,500"
],
[
"Jonas Alexander",
"Developer",
"San Francisco",
"8196",
"2010\/07\/14",
"$86,500"
],
[
"Shad Decker",
"Regional Director",
"Edinburgh",
"6373",
"2008\/11\/13",
"$183,000"
],
[
"Michael Bruce",
"Javascript Developer",
"Singapore",
"5384",
"2011\/06\/27",
"$183,000"
],
[
"Donna Snider",
"Customer Support",
"New York",
"4226",
"2011\/01\/25",
"$112,000"
]
]
$scope.dataTableOpt = {
//if any ajax call
};
});
</script>
<div class="container" ng-app="formvalid">
<div class="panel" data-ng-controller="validationCtrl">
<div class="panel-heading border">
<h2>Data table using jquery datatable in Angularjs </h2>
</div>
<div class="panel-body">
<table class="table table-bordered bordered table-striped table-condensed datatable" ui-jq="dataTable" ui-options="dataTableOpt">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start Date</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="n in data">
<td>{{$index+1}}</td>
<td>{{n[0]}}</td>
<td>{{n[1]}}</td>
<td>{{n[2]}}</td>
<td>{{n[3]}}</td>
<td>{{n[4] | date:'dd/MM/yyyy'}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
This should solve your problem, you should try to run the following below:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
Have you added the google maven endpoint?
Important: The support libraries are now available through Google's Maven repository. You do not need to download the support repository from the SDK Manager. For more information, see Support Library Setup.
Add the endpoint to your build.gradle file:
allprojects {
repositories {
jcenter()
maven {
url 'https://maven.google.com'
}
}
}
Which can be replaced by the shortcut google()
since Android Gradle v3:
allprojects {
repositories {
jcenter()
google()
}
}
If you already have any maven url inside repositories
, you can add the reference after them, i.e.:
allprojects {
repositories {
jcenter()
maven {
url 'https://jitpack.io'
}
maven {
url 'https://maven.google.com'
}
}
}
I think its up to you. I certainly think the .HasValue approach is more readable, especially with developers not familiar with the ?? syntax.
The other point of a nullable boolean type is that it is tristate, so you may want to do something else when it is just null, and not default to false.
in my case it was just an intermittent issues it seems, didn't work for a few tries, then looked at https://registry.npmjs.org (webpage worked fine), tried again, tried again and then it worked.
To answer the question more generaly how to redirect standard output to a variable ?
do the following :
from io import StringIO
import sys
result = StringIO()
sys.stdout = result
result_string = result.getvalue()
If you need to do that only in some function do the following :
old_stdout = sys.stdout
# your function containing the previous lines
my_function()
sys.stdout = old_stdout
You can use ListView to render a list of items. But if you don't want to use ListView, you can create a method which returns a list of Widgets (Texts in your case) like below:
var list = ["one", "two", "three", "four"];
@override
Widget build(BuildContext context) {
return new MaterialApp(
home: new Scaffold(
appBar: new AppBar(
title: new Text('List Test'),
),
body: new Center(
child: new Column( // Or Row or whatever :)
children: createChildrenTexts(),
),
),
));
}
List<Text> createChildrenTexts() {
/// Method 1
// List<Text> childrenTexts = List<Text>();
// for (String name in list) {
// childrenTexts.add(new Text(name, style: new TextStyle(color: Colors.red),));
// }
// return childrenTexts;
/// Method 2
return list.map((text) => Text(text, style: TextStyle(color: Colors.blue),)).toList();
}
Pure JS, without inline onclick, for paired classes "content - copy button". Would be more comfortable, if you have many elements)
(function(){_x000D_
_x000D_
/* Creating textarea only once, but not each time */_x000D_
let area = document.createElement('textarea');_x000D_
document.body.appendChild( area );_x000D_
area.style.display = "none";_x000D_
_x000D_
let content = document.querySelectorAll('.js-content');_x000D_
let copy = document.querySelectorAll('.js-copy');_x000D_
_x000D_
for( let i = 0; i < copy.length; i++ ){_x000D_
copy[i].addEventListener('click', function(){_x000D_
area.style.display = "block";_x000D_
/* because the classes are paired, we can use the [i] index from the clicked button,_x000D_
to get the required text block */_x000D_
area.value = content[i].innerText;_x000D_
area.select();_x000D_
document.execCommand('copy'); _x000D_
area.style.display = "none";_x000D_
_x000D_
/* decorative part */_x000D_
this.innerHTML = 'Cop<span style="color: red;">ied</span>';_x000D_
/* arrow function doesn't modify 'this', here it's still the clicked button */_x000D_
setTimeout( () => this.innerHTML = "Copy", 2000 );_x000D_
});_x000D_
}_x000D_
_x000D_
})();
_x000D_
hr { margin: 15px 0; border: none; }
_x000D_
<span class="js-content">1111</span>_x000D_
<button class="js-copy">Copy</button>_x000D_
<hr>_x000D_
<span class="js-content">2222</span>_x000D_
<button class="js-copy">Copy</button>_x000D_
<hr>_x000D_
<span class="js-content">3333</span>_x000D_
<button class="js-copy">Copy</button>
_x000D_
Older browser support:
(function(){_x000D_
_x000D_
var area = document.createElement('textarea');_x000D_
document.body.appendChild( area );_x000D_
area.style.display = "none";_x000D_
_x000D_
var content = document.querySelectorAll('.js-content');_x000D_
var copy = document.querySelectorAll('.js-copy');_x000D_
_x000D_
for( var i = 0; i < copy.length; i++ ){_x000D_
copyOnClick(i);_x000D_
}_x000D_
_x000D_
function copyOnClick(i){_x000D_
copy[i].addEventListener('click', function(){_x000D_
area.style.display = "block";_x000D_
area.value = content[i].innerText;_x000D_
area.select();_x000D_
document.execCommand('copy'); _x000D_
area.style.display = "none";_x000D_
_x000D_
var t = this;_x000D_
t.innerHTML = 'Cop<span style="color: red;">ied</span>';_x000D_
setTimeout( function(){_x000D_
t.innerHTML = "Copy"_x000D_
}, 2000 );_x000D_
});_x000D_
}_x000D_
_x000D_
})();
_x000D_
hr { margin: 15px 0; border: none; }
_x000D_
<span class="js-content">1111</span>_x000D_
<button class="js-copy">Copy</button>_x000D_
<hr>_x000D_
<span class="js-content">2222</span>_x000D_
<button class="js-copy">Copy</button>_x000D_
<hr>_x000D_
<span class="js-content">3333</span>_x000D_
<button class="js-copy">Copy</button>
_x000D_
I found that you can just do this in Chrome:
$('.onload-fadein').each(function (k, v) {
v.onload = function () {
$(this).animate({opacity: 1}, 2000);
};
v.src = v.src;
});
Setting the .src to itself will trigger the onload event.
Make sure you are on the right directory where you have package.json
By adding using System.Timers;
to your program you can use this function:
private static void delay(int Time_delay)
{
int i=0;
// ameTir = new System.Timers.Timer();
_delayTimer = new System.Timers.Timer();
_delayTimer.Interval = Time_delay;
_delayTimer.AutoReset = false; //so that it only calls the method once
_delayTimer.Elapsed += (s, args) => i = 1;
_delayTimer.Start();
while (i == 0) { };
}
Delay is a function and can be used like:
delay(5000);
In java 5 new feature added that is Scanner method who gives the chance to read input character by character in java.
for instance; for use Scanner method import java.util.Scanner; after in main method:define
Scanner myScanner = new Scanner(System.in); //for read character
char anything=myScanner.findInLine(".").charAt(0);
you anything store single character, if you want more read more character declare more object like anything1,anything2... more example for your answer please check in your hand(copy/paste)
import java.util.Scanner;
class ReverseWord {
public static void main(String args[]){
Scanner myScanner=new Scanner(System.in);
char c1,c2,c3,c4;
c1 = myScanner.findInLine(".").charAt(0);
c2 = myScanner.findInLine(".").charAt(0);
c3 = myScanner.findInLine(".").charAt(0);
c4 = myScanner.findInLine(".").charAt(0);
System.out.print(c4);
System.out.print(c3);
System.out.print(c2);
System.out.print(c1);
System.out.println();
}
}
try this one
npm cache clean --force
after that run
npm cache verify
One way is to use the lattice package and xyplot():
R> DF <- data.frame(x=1:10, y=rnorm(10)+5,
+> z=sample(letters[1:3], 10, replace=TRUE))
R> DF
x y z
1 1 3.91191 c
2 2 4.57506 a
3 3 3.16771 b
4 4 5.37539 c
5 5 4.99113 c
6 6 5.41421 a
7 7 6.68071 b
8 8 5.58991 c
9 9 5.03851 a
10 10 4.59293 b
R> with(DF, xyplot(y ~ x, group=z))
By giving explicit grouping information via variable z
, you obtain different colors. You can specify colors etc, see the lattice documentation.
Because z
here is a factor variable for which we obtain the levels (== numeric indices), you can also do
R> with(DF, plot(x, y, col=z))
but that is less transparent (to me, at least :) then xyplot()
et al.
You may want to look into Maven release plugin's release:update-versions goal. It will update the parent's version as well as all the modules under it.
Update: Please note that the above is the release plugin. If you are not releasing, you may want to use versions:set
mvn versions:set -DnewVersion=1.2.3-SNAPSHOT
The Windows API has the functions UrlEscape/UrlUnescape, exported by shlwapi.dll, for this task.
The AngularJS way of calling $http would look like:
$http({
url: "http://example.appspot.com/rest/app",
method: "POST",
data: {"foo":"bar"}
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
$scope.data = response.data;
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$scope.error = response.statusText;
});
or could be written even simpler using shortcut methods:
$http.post("http://example.appspot.com/rest/app", {"foo":"bar"})
.then(successCallback, errorCallback);
There are number of things to notice:
success
and error
respectively (also please note parameters of each callback) - Deprecated in angular v1.5then
function instead. then
usage can be found here The above is just a quick example and some pointers, be sure to check AngularJS documentation for more: http://docs.angularjs.org/api/ng.$http
Put it as a background on your holder e.g.
<div style="background:url(path/to/image/myimage.jpg) center center; width:120px; height:120px;">
</div>
This will center your image inside a 120x120 div chopping off any excess of the image
State machines can be very complex for a complex problem. They are also subject to unexpected bugs. They can turn into a nightmare if someone runs into a bug or needs to change the logic in the future. They are also difficult to follow and debug without the state diagram. Structured programming is much better (for example you would probably not use a state machine at mainline level). You can use structured programming even in interrupt context (which is where state machines are usually used). See this article "Macros to simulate multi-tasking/blocking code at interrupt level" found at codeproject.com.
date +%Y:%m:%d|awk -vFS=":" -vOFS=":" '{$3=$3-1;print}'
2009:11:9
QApplication is derived from QCoreApplication and thereby inherits quit()
which is a public slot of QCoreApplication
, so there is no difference between QApplication::quit()
and QCoreApplication::quit()
.
As we can read in the documentation of QCoreApplication::quit()
it "tells the application to exit with return code 0 (success).". If you want to exit because you discovered file corruption then you may not want to exit with return code zero which means success, so you should call QCoreApplication::exit()
because you can provide a non-zero returnCode which, by convention, indicates an error.
It is important to note that "if the event loop is not running, this function (QCoreApplication::exit()) does nothing", so in that case you should call exit(EXIT_FAILURE)
.
You could implement it like this:
@SuppressWarnings("unchecked")
public <T extends Animal> T callFriend(String name) {
return (T)friends.get(name);
}
(Yes, this is legal code; see Java Generics: Generic type defined as return type only.)
The return type will be inferred from the caller. However, note the @SuppressWarnings
annotation: that tells you that this code isn't typesafe. You have to verify it yourself, or you could get ClassCastExceptions
at runtime.
Unfortunately, the way you're using it (without assigning the return value to a temporary variable), the only way to make the compiler happy is to call it like this:
jerry.<Dog>callFriend("spike").bark();
While this may be a little nicer than casting, you are probably better off giving the Animal
class an abstract talk()
method, as David Schmitt said.
try this:
[self dismissViewControllerAnimated:true completion:nil];
In addition to Idriss answer:
In CSS we write code as depicted bellow, in full length.
body{
width: 800px;
color: #ffffff;
}
body content{
width:750px;
background:#ffffff;
}
In SCSS we can shorten this code using a @mixin
so we don’t have to write color
and width
properties again and again. We can define this through a function, similarly to PHP or other languages.
$color: #ffffff;
$width: 800px;
@mixin body{
width: $width;
color: $color;
content{
width: $width;
background:$color;
}
}
In SASS however, the whole structure is visually quicker and cleaner than SCSS.
It seems that it doesn't support inline CSS currently.
$color: #ffffff
$width: 800px
$stack: Helvetica, sans-serif
body
width: $width
color: $color
font: 100% $stack
content
width: $width
background:$color
Since you've already stashed your changes, all you need is this one-liner:
git stash branch <branchname> [<stash>]
From the docs (https://www.kernel.org/pub/software/scm/git/docs/git-stash.html):
Creates and checks out a new branch named <branchname> starting from the commit at which the <stash> was originally created, applies the changes recorded in <stash> to the new working tree and index. If that succeeds, and <stash> is a reference of the form stash@{<revision>}, it then drops the <stash>. When no <stash> is given, applies the latest one.
This is useful if the branch on which you ran git stash save has changed enough that git stash apply fails due to conflicts. Since the stash is applied on top of the commit that was HEAD at the time git stash was run, it restores the originally stashed state with no conflicts.
How about?
<?php
$queried_post = get_page_by_path('my_slug',OBJECT,'post');
?>
This can occur when Safari is in private mode browsing. While in private browsing, local storage is not available at all.
One solution is to warn the user that the app needs non-private mode to work.
UPDATE: This has been fixed in Safari 11, so the behaviour is now aligned with other browsers.
You can pass a numpy array or matrix as an argument when initializing a sparse matrix. For a CSR matrix, for example, you can do the following.
>>> import numpy as np
>>> from scipy import sparse
>>> A = np.array([[1,2,0],[0,0,3],[1,0,4]])
>>> B = np.matrix([[1,2,0],[0,0,3],[1,0,4]])
>>> A
array([[1, 2, 0],
[0, 0, 3],
[1, 0, 4]])
>>> sA = sparse.csr_matrix(A) # Here's the initialization of the sparse matrix.
>>> sB = sparse.csr_matrix(B)
>>> sA
<3x3 sparse matrix of type '<type 'numpy.int32'>'
with 5 stored elements in Compressed Sparse Row format>
>>> print sA
(0, 0) 1
(0, 1) 2
(1, 2) 3
(2, 0) 1
(2, 2) 4
Look at stat
for checking if the directory exists,
And mkdir
, to create a directory.
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
struct stat st = {0};
if (stat("/some/directory", &st) == -1) {
mkdir("/some/directory", 0700);
}
You can see the manual of these functions with the man 2 stat
and man 2 mkdir
commands.
The question is simply asked wrong. You don't make an alias that takes parameters because alias
just adds a second name for something that already exists. The functionality the OP wants is the function
command to create a new function. You do not need to alias the function as the function already has a name.
I think you want something like this :
function trash() { mv "$@" ~/.Trash; }
That's it! You can use parameters $1, $2, $3, etc, or just stuff them all with $@
Wait function using timers, no UI locks.
public void wait(int milliseconds)
{
var timer1 = new System.Windows.Forms.Timer();
if (milliseconds == 0 || milliseconds < 0) return;
// Console.WriteLine("start wait timer");
timer1.Interval = milliseconds;
timer1.Enabled = true;
timer1.Start();
timer1.Tick += (s, e) =>
{
timer1.Enabled = false;
timer1.Stop();
// Console.WriteLine("stop wait timer");
};
while (timer1.Enabled)
{
Application.DoEvents();
}
}
Usage: just placing this inside your code that needs to wait:
wait(1000); //wait one second
Serializable is a standard Java interface. You simply mark a class Serializable by implementing the interface, and Java will automatically serialize it in certain situations.
Parcelable is an Android specific interface where you implement the serialization yourself. It was created to be far more efficient that Serializable, and to get around some problems with the default Java serialization scheme.
I believe that Binder and AIDL work with Parcelable objects.
However, you can use Serializable objects in Intents.
Here is a quick fix:
All the pros will probably hate me for this answer. But I got the same error on a server: Fatal error: Uncaught Error: Call to undefined function mysql_connect() that was using PHP 7. Did not have time to rewrite all the mysql code so a quick, temporary fix if anyone needs it is in CPANEL to look for PHP Configuration and change the version for that account to something like PHP 5.4 instead of PHP 7. Then the code worked fine without the above error.
It's go to newline then add spaces to start second line at end of first line
Output
Hello
Goodbye
please note, if you use $filter like this:
$scope.failedSubjects = $filter('filter')($scope.results.subjects, {'grade':'C'});
and you happened to have another grade for, Oh I don't know, CC or AC or C+ or CCC it pulls them in to. you need to append a requirement for an exact match:
$scope.failedSubjects = $filter('filter')($scope.results.subjects, {'grade':'C'}, true);
This really killed me when I was pulling in some commission details like this:
var obj = this.$filter('filter')(this.CommissionTypes, { commission_type_id: 6}))[0];
only get called in for a bug because it was pulling in the commission ID 56 rather than 6.
Adding the true forces an exact match.
var obj = this.$filter('filter')(this.CommissionTypes, { commission_type_id: 6}, true))[0];
Yet still, I prefer this (I use typescript, hence the "Let" and =>):
let obj = this.$filter('filter')(this.CommissionTypes, (item) =>{
return item.commission_type_id === 6;
})[0];
I do that because, at some point down the road, I might want to get some more info from that filtered data, etc... having the function right in there kind of leaves the hood open.
<?php
$hostname_conn = "localhost";
$database_conn = "user_id";
$username_conn = "root";
$password_conn = "";
$conn = mysql_pconnect($hostname_conn, $username_conn, $password_conn) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_conn,$conn);
// run an endless loop
while(1) {
$randomNumber = rand(1, 999999);// generate unique random number
$query = "SELECT * FROM tbl_rand WHERE the_number='".mysql_real_escape_string ($randomNumber)."'"; // check if it exists in database
$res =mysql_query($query,$conn);
$rowCount = mysql_num_rows($res);
// if not found in the db (it is unique), then insert the unique number into data_base and break out of the loop
if($rowCount < 1) {
$con = mysql_connect ("localhost","root");
mysql_select_db("user_id", $con);
$sql = "insert into tbl_rand(the_number) values('".$randomNumber."')";
mysql_query ($sql,$con);
mysql_close ($con);
break;
}
}
echo "inserted unique number into Data_base. use it as ID";
?>
Take a look at the Java standard API doc. Right next to LinkedHashMap
, there is a LinkedHashSet
. But note that the order in those is the insertion order, not the natural order of the elements. And you can only iterate in that order, not do random access (except by counting iteration steps).
There is also an interface SortedSet
implemented by TreeSet
and ConcurrentSkipListSet
. Both allow iteration in the natural order of their elements or a Comparator
, but not random access or insertion order.
For a data structure that has both efficient access by index and can efficiently implement the set criterium, you'd need a skip list, but there is no implementation with that functionality in the Java Standard API, though I am certain it's easy to find one on the internet.
I just created this and it looks easier. You get these 2 functions:
=GetColorIndex(E5) <- returns color number for the cell
from (cell)
=CountColorIndexInRange(C7:C24,14) <- returns count of cells C7:C24 with color 14
from (range of cells, color number you want to count)
example shows percent of cells with color 14
=ROUND(CountColorIndexInRange(C7:C24,14)/18, 4 )
Create these 2 VBA functions in a Module (hit Alt-F11)
open + folders. double-click on Module1
Just paste this text below in, then close the module window (it must save it then):
Function GetColorIndex(Cell As Range)
GetColorIndex = Cell.Interior.ColorIndex
End Function
Function CountColorIndexInRange(Rng As Range, TestColor As Long)
Dim cnt
Dim cl As Range
cnt = 0
For Each cl In Rng
If GetColorIndex(cl) = TestColor Then
Rem Debug.Print ">" & TestColor & "<"
cnt = cnt + 1
End If
Next
CountColorIndexInRange = cnt
End Function
I realize this is an old post but I find myself coming back to this thread a lot as it is one of the top search results when searching for this topic. However, I always leave more confused then when I came due to the conflicting information. Ultimately I always have to perform my own tests to figure it out. So this time I will post my findings.
TL;DR Most people will want to use Exit
to terminate a running scripts. However, if your script is merely declaring functions to later be used in a shell, then you will want to use Return
in the definitions of said functions.
Exit: This will "exit" the currently running context. If you call this command from a script it will exit the script. If you call this command from the shell it will exit the shell.
If a function calls the Exit command it will exit what ever context it is running in. So if that function is only called from within a running script it will exit that script. However, if your script merely declares the function so that it can be used from the current shell and you run that function from the shell, it will exit the shell because the shell is the context in which the function contianing the Exit
command is running.
Note: By default if you right click on a script to run it in PowerShell, once the script is done running, PowerShell will close automatically. This has nothing to do with the Exit
command or anything else in your script. It is just a default PowerShell behavior for scripts being ran using this specific method of running a script. The same is true for batch files and the Command Line window.
Return: This will return to the previous call point. If you call this command from a script (outside any functions) it will return to the shell. If you call this command from the shell it will return to the shell (which is the previous call point for a single command ran from the shell). If you call this command from a function it will return to where ever the function was called from.
Execution of any commands after the call point that it is returned to will continue from that point. If a script is called from the shell and it contains the Return
command outside any functions then when it returns to the shell there are no more commands to run thus making a Return
used in this way essentially the same as Exit
.
Break: This will break out of loops and switch cases. If you call this command while not in a loop or switch case it will break out of the script. If you call Break
inside a loop that is nested inside a loop it will only break out of the loop it was called in.
There is also an interesting feature of Break
where you can prefix a loop with a label and then you can break out of that labeled loop even if the Break
command is called within several nested groups within that labeled loop.
While ($true) {
# Code here will run
:myLabel While ($true) {
# Code here will run
While ($true) {
# Code here will run
While ($true) {
# Code here will run
Break myLabel
# Code here will not run
}
# Code here will not run
}
# Code here will not run
}
# Code here will run
}
This is a new security feature of iOS 9. Watch WWDC 2015 Session 703 for more information.
Any app built with SDK 9 needs to provide a LSApplicationQueriesSchemes
entry in its plist file, declaring which schemes it attempts to query.
<key>LSApplicationQueriesSchemes</key>
<array>
<string>urlscheme</string>
<string>urlscheme2</string>
<string>urlscheme3</string>
<string>urlscheme4</string>
</array>
You can't change the color of the line (you can't specify different foreground colors for the same element, and the text and its decoration form a single element). However there are some tricks:
a:link, a:visited {text-decoration: none; color: red; border-bottom: 1px solid #006699; }
a:hover, a:active {text-decoration: none; color: red; border-bottom: 1px solid #1177FF; }
Also you can make some cool effects this way:
a:link {text-decoration: none; color: red; border-bottom: 1px dashed #006699; }
Hope it helps.
As others mentioned, it's only possible via reflection in certain circumstances.
If you really need the type, this is the usual (type-safe) workaround pattern:
public class GenericClass<T> {
private final Class<T> type;
public GenericClass(Class<T> type) {
this.type = type;
}
public Class<T> getMyType() {
return this.type;
}
}
Tray to add text with html value to textarea but it wil not works
value :
$(document).on('click', '.edit_targets_btn', function() {
$('#add_edit_targets').modal('show');
$('#add_edit_targets_form')[0].reset();
$('#targets_modal_title').text('Doel bijwerken');
$('#action').val('targets_update');
$('#targets_submit_btn').val('Opslaan');
$('#callcenter_targets_id').val($(this).attr("callcenter_targets_id"));
$('#targets_title').val($(this).attr("title"));
$("#targets_content").append($(this).attr("content"));
tinymce.init({
selector: '#targets_content',
setup: function (editor) {
editor.on('change', function () {
tinymce.triggerSave();
});
},
browser_spellcheck : true,
plugins: ['advlist autolink lists image charmap print preview anchor', 'searchreplace visualblocks code fullscreen', 'insertdatetime media table paste code help wordcount', 'autoresize'],
toolbar: 'undo redo | formatselect | ' + ' bold italic backcolor | alignleft aligncenter ' + ' alignright alignjustify | bullist numlist outdent indent |' + ' removeformat | image | help',
relative_urls : false,
remove_script_host : false,
image_list: [<?php $stmt = $db->query('SELECT * FROM images WHERE users_id = ' . $get_user_users_id); foreach ($stmt as $row) { ?>{title: '<?=$row['name']?>', value: '<?=$imgurl?>/image_uploads/<?=$row['src']?>'},<?php } ?>],
min_height: 250,
branding: false
});
});
You can take update / pull on git branch you can use below command
git pull origin <branch-name>
The above command will take an update/pull from giving branch name
If you want to take pull from another branch, you need to go to that branch.
git checkout master
Than
git pull origin development
Hope that will work for you
A simple regex that will match, but I wouldn't recommend for validation of any sort is this:
([A-Fa-f0-9]{1,4}::?){1,7}[A-Fa-f0-9]{1,4}
Note this matches compression anywhere in the address, though it won't match the loopback address ::1. I find this a reasonable compromise in order to keep the regex simple.
I successfully use this in iTerm2 smart selection rules to quad-click IPv6 addresses.
Import mplot3d whole to use "projection = '3d'".
Insert the command below in top of your script. It should run fine.
from mpl_toolkits import mplot3d
byte[] bytes = File.ReadAllBytes(filename)
or ...
var bytes = File.ReadAllBytes(filename)
In some cases related with responsive layout $(document).height()
can return wrong data that displays view port height only.
For example when some div#wrapper has height:100%, that #wrapper can be stretched by some block inside it. But it's height still will be like viewport height. In such situation you might use
$('#wrapper').get(0).scrollHeight
That represents actual size of wrapper.
Try this function : mltiple queries and multiple values insertion.
function employmentStatus($Status) {
$pdo = PDO2::getInstance();
$sql_parts = array();
for($i=0; $i<count($Status); $i++){
$sql_parts[] = "(:userID, :val$i)";
}
$requete = $pdo->dbh->prepare("DELETE FROM employment_status WHERE userid = :userID; INSERT INTO employment_status (userid, status) VALUES ".implode(",", $sql_parts));
$requete->bindParam(":userID", $_SESSION['userID'],PDO::PARAM_INT);
for($i=0; $i<count($Status); $i++){
$requete->bindParam(":val$i", $Status[$i],PDO::PARAM_STR);
}
if ($requete->execute()) {
return true;
}
return $requete->errorInfo();
}
One can also use the following class while using bootstrap modal class (v 3.3.7) ... help-inline and help-block did not work in modal.
<span class="error text-danger">Some Errors related to something</span>
Output looks like something below:
var today = new Date().toISOString().split('T')[0];
$("#datePicker").val(today);
Above code will work.
This is expected.
Refer to Javadocs for split
.
Splits this string around matches of the given regular expression.
This method works as if by invoking the two-argument split(java.lang.String,int) method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
This SQL query gives output similar to \dx
:
SELECT e.extname AS "Name", e.extversion AS "Version", n.nspname AS "Schema", c.description AS "Description"
FROM pg_catalog.pg_extension e
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = e.extnamespace
LEFT JOIN pg_catalog.pg_description c ON c.objoid = e.oid AND c.classoid = 'pg_catalog.pg_extension'::pg_catalog.regclass
ORDER BY 1;
Thanks to https://blog.dbi-services.com/listing-the-extensions-available-in-postgresql/
Slight adjustment to answers from ARobertson and Kenneth Wilson that worked for me.
Running R 3.6.0, with library(tidyverse) and library(dplyr) in my environment:
library(tidyverse)
library(dplyr)
> df %<>% mutate_if(is.character, as.numeric)
Error in df %<>% mutate_if(is.character, as.numeric) :
could not find function "%<>%"
I did some quick research and found this note in Hadley's "The tidyverse style guide".
The magrittr package provides the %<>% operator as a shortcut for modifying an object in place. Avoid this operator.
# Good x <- x %>% abs() %>% sort() # Bad x %<>% abs() %>% sort()
Solution
Based on that style guide:
df_clean <- df %>% mutate_if(is.character, as.numeric)
Working example
> df_clean <- df %>% mutate_if(is.character, as.numeric)
Warning messages:
1: NAs introduced by coercion
2: NAs introduced by coercion
3: NAs introduced by coercion
4: NAs introduced by coercion
5: NAs introduced by coercion
6: NAs introduced by coercion
7: NAs introduced by coercion
8: NAs introduced by coercion
9: NAs introduced by coercion
10: NAs introduced by coercion
> df_clean
# A tibble: 3,599 x 17
stack datetime volume BQT90 DBT90 DRT90 DLT90 FBT90 RT90 HTML90 RFT90 RLPP90 RAT90 SRVR90 SSL90 TCP90 group
<dbl> <dttm> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
I need to decrypt a password. The password is crypted with password_hash function.
$password = 'examplepassword'; $crypted = password_hash($password, PASSWORD_DEFAULT);
Its not clear to me if you need password_verify
, or you are trying to gain unauthorized access to the application or database. Other have talked about password_verify
, so here's how you could gain unauthorized access. Its what bad guys often do when they try to gain access to a system.
First, create a list of plain text passwords. A plain text list can be found in a number of places due to the massive data breaches from companies like Adobe. Sort the list and then take the top 10,000 or 100,000 or so.
Second, create a list of digested passwords. Simply encrypt or hash the password. Based on your code above, it does not look like a salt is being used (or its a fixed salt). This makes the attack very easy.
Third, for each digested password in the list, perform a select in an attempt to find a user who is using the password:
$sql_script = 'select * from USERS where password="'.$digested_password.'"'
Fourth, profit.
So, rather than picking a user and trying to reverse their password, the bad guy picks a common password and tries to find a user who is using it. Odds are on the bad guy's side...
Because the bad guy does these things, it would behove you to not let users choose common passwords. In this case, take a look at ProCheck, EnFilter or Hyppocrates (et al). They are filtering libraries that reject bad passwords. ProCheck achieves very high compression, and can digest multi-million word password lists into a 30KB data file.
Starting with Sql Server 2012: string concatenation function CONCAT
converts to string implicitly. Therefore, another option is
SELECT Id AS 'PatientId',
CONCAT(ParentId,'') AS 'ParentId'
FROM Patients
CONCAT
converts null
values to empty strings.
Some will consider this hacky, because it merely exploits a side effect of a function while the function itself isn't required for the task in hand.
The following solution worked for me...
I tried everything mentioned above but still didn't get my app running. I have react-native app running on latest version of gradle 4+ and android studio.
I had the issue where if i run react-native run-android it was failing with issue saying its not able to find MainApplication class...i.e ClassNotFoundException
I was able to resolve the issue when I updated my gradle.properties to use the compiler D8.
I added:
android.enableD8=true
to my gradle.properties
Doc Details here: https://android-developers.googleblog.com/2017/08/next-generation-dex-compiler-now-in.html
There are JDK versions available from the base CentOS repositories. Depending on your version of CentOS, and the JDK you want to install, the following as root should give you what you want:
OpenJDK Runtime Environment (Java SE 6)
yum install java-1.6.0-openjdk
OpenJDK Runtime Environment (Java SE 7)
yum install java-1.7.0-openjdk
OpenJDK Development Environment (Java SE 7)
yum install java-1.7.0-openjdk-devel
OpenJDK Development Environment (Java SE 6)
yum install java-1.6.0-openjdk-devel
Update for Java 8
In CentOS 6.6 or later, Java 8 is available. Similar to 6 and 7 above, the packages are as follows:
OpenJDK Runtime Environment (Java SE 8)
yum install java-1.8.0-openjdk
OpenJDK Development Environment (Java SE 8)
yum install java-1.8.0-openjdk-devel
There's also a 'headless' JRE package that is the same as the above JRE, except it doesn't contain audio/video support. This can be used for a slightly more minimal installation:
OpenJDK Runtime Environment - Headless (Java SE 8)
yum install java-1.8.0-openjdk-headless
The following codes should give you the fastest speed for big data as long as you have many cores on your computer:
if (!require("pacman")) install.packages("pacman")
pacman::p_load(doParallel, data.table, stringr)
# get the file name
dir() %>% str_subset("\\.csv$") -> fn
# use parallel setting
(cl <- detectCores() %>%
makeCluster()) %>%
registerDoParallel()
# read and bind all files together
system.time({
big_df <- foreach(
i = fn,
.packages = "data.table"
) %dopar%
{
fread(i, colClasses = "character")
} %>%
rbindlist(fill = TRUE)
})
# end of parallel work
stopImplicitCluster(cl)
Updated in 2020/04/16: As I find a new package available for parallel computation, an alternative solution is provided using the following codes.
if (!require("pacman")) install.packages("pacman")
pacman::p_load(future.apply, data.table, stringr)
# get the file name
dir() %>% str_subset("\\.csv$") -> fn
plan(multiprocess)
future_lapply(fn,fread,colClasses = "character") %>%
rbindlist(fill = TRUE) -> res
# res is the merged data.table
My suggestions :
For setting the values in the number, use constructors. Do not use like the methods you have used above like :
public void setNumber(double fnum, double snum){ this.fn = fnum; this.sn = snum; }
Constructors exists to initialize the objects.This is their job and they are pretty good at it.
Getters for members of Calculate class seem in place. But setters are not. Getters and setters serves as one important block in the bridge of efficient programming with java. Put setters for fnum and snum as well
In the main class, create a Calculate object using the new operator and the constructor in place.
Call the getAnswer() method with the created Calculate object.
Rest of the code looks fine to me. Be modular. You could read your program in a much better way.
Here is my modular piece of code. Two files : Main.java & Calculate.java
public class Calculate {
private double fn;
private double sn;
private char op;
public double getFn() {
return fn;
}
public void setFn(double fn) {
this.fn = fn;
}
public double getSn() {
return sn;
}
public void setSn(double sn) {
this.sn = sn;
}
public char getOp() {
return op;
}
public void setOp(char op) {
this.op = op;
}
public Calculate(double fn, double sn, char op) {
this.fn = fn;
this.sn = sn;
this.op = op;
}
public void getAnswer(){
double ans;
switch (getOp()){
case '+':
ans = add(getFn(), getSn());
ansOutput(ans);
break;
case '-':
ans = sub (getFn(), getSn());
ansOutput(ans);
break;
case '*':
ans = mul (getFn(), getSn());
ansOutput(ans);
break;
case '/':
ans = div (getFn(), getSn());
ansOutput(ans);
break;
default:
System.out.println("--------------------------");
System.out.println("Invalid choice of operator");
System.out.println("--------------------------");
}
}
public static double add(double x,double y){
return x + y;
}
public static double sub(double x, double y){
return x - y;
}
public static double mul(double x, double y){
return x * y;
}
public static double div(double x, double y){
return x / y;
}
public static void ansOutput(double x){
System.out.println("----------- -------");
System.out.printf("the answer is %.2f\n", x);
System.out.println("-------------------");
}
}
public class Main {
public static void main(String args[])
{
Calculate obj = new Calculate(1,2,'+');
obj.getAnswer();
}
}
Modern javascript controls as well as JSON requests can be handled much easily using MVC. There we can use a lot of other mechanisms to post data from one action to another action. That's why we prefer MVC over web forms. Also we can build light weight pages.
I made some fixes for @Pinhassi solution. It handles some cases:
1.you can move cursor anywhere
2.minus sign handling
3.digitsbefore = 2 and digitsafter = 4 and you enter 12.4545. Then if you want to remove ".", it will not allow.
public class DecimalDigitsInputFilter implements InputFilter {
private int mDigitsBeforeZero;
private int mDigitsAfterZero;
private Pattern mPattern;
private static final int DIGITS_BEFORE_ZERO_DEFAULT = 100;
private static final int DIGITS_AFTER_ZERO_DEFAULT = 100;
public DecimalDigitsInputFilter(Integer digitsBeforeZero, Integer digitsAfterZero) {
this.mDigitsBeforeZero = (digitsBeforeZero != null ? digitsBeforeZero : DIGITS_BEFORE_ZERO_DEFAULT);
this.mDigitsAfterZero = (digitsAfterZero != null ? digitsAfterZero : DIGITS_AFTER_ZERO_DEFAULT);
mPattern = Pattern.compile("-?[0-9]{0," + (mDigitsBeforeZero) + "}+((\\.[0-9]{0," + (mDigitsAfterZero)
+ "})?)||(\\.)?");
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
String replacement = source.subSequence(start, end).toString();
String newVal = dest.subSequence(0, dstart).toString() + replacement
+ dest.subSequence(dend, dest.length()).toString();
Matcher matcher = mPattern.matcher(newVal);
if (matcher.matches())
return null;
if (TextUtils.isEmpty(source))
return dest.subSequence(dstart, dend);
else
return "";
}
}
You must change the cmake C/CXX default FLAGS .
According to CMAKE_BUILD_TYPE={DEBUG/MINSIZEREL/RELWITHDEBINFO/RELEASE}
put in the main CMakeLists.txt
one of :
For C
set(CMAKE_C_FLAGS_DEBUG "put your flags")
set(CMAKE_C_FLAGS_MINSIZEREL "put your flags")
set(CMAKE_C_FLAGS_RELWITHDEBINFO "put your flags")
set(CMAKE_C_FLAGS_RELEASE "put your flags")
For C++
set(CMAKE_CXX_FLAGS_DEBUG "put your flags")
set(CMAKE_CXX_FLAGS_MINSIZEREL "put your flags")
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "put your flags")
set(CMAKE_CXX_FLAGS_RELEASE "put your flags")
This will override the values defined in CMakeCache.txt
You can use the strtok()
function to split a string (and specify the delimiter to use). Note that strtok()
will modify the string passed into it. If the original string is required elsewhere make a copy of it and pass the copy to strtok()
.
EDIT:
Example (note it does not handle consecutive delimiters, "JAN,,,FEB,MAR" for example):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
char** str_split(char* a_str, const char a_delim)
{
char** result = 0;
size_t count = 0;
char* tmp = a_str;
char* last_comma = 0;
char delim[2];
delim[0] = a_delim;
delim[1] = 0;
/* Count how many elements will be extracted. */
while (*tmp)
{
if (a_delim == *tmp)
{
count++;
last_comma = tmp;
}
tmp++;
}
/* Add space for trailing token. */
count += last_comma < (a_str + strlen(a_str) - 1);
/* Add space for terminating null string so caller
knows where the list of returned strings ends. */
count++;
result = malloc(sizeof(char*) * count);
if (result)
{
size_t idx = 0;
char* token = strtok(a_str, delim);
while (token)
{
assert(idx < count);
*(result + idx++) = strdup(token);
token = strtok(0, delim);
}
assert(idx == count - 1);
*(result + idx) = 0;
}
return result;
}
int main()
{
char months[] = "JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC";
char** tokens;
printf("months=[%s]\n\n", months);
tokens = str_split(months, ',');
if (tokens)
{
int i;
for (i = 0; *(tokens + i); i++)
{
printf("month=[%s]\n", *(tokens + i));
free(*(tokens + i));
}
printf("\n");
free(tokens);
}
return 0;
}
Output:
$ ./main.exe
months=[JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC]
month=[JAN]
month=[FEB]
month=[MAR]
month=[APR]
month=[MAY]
month=[JUN]
month=[JUL]
month=[AUG]
month=[SEP]
month=[OCT]
month=[NOV]
month=[DEC]
You can initialise the whole result list in the top level call to mergesort:
result = [0]*len(x) # replace 0 with a suitable default element if necessary.
# or just copy x (result = x[:])
Then for the recursive calls you can use a helper function to which you pass not sublists, but indices into x
. And the bottom level calls read their values from x
and write into result
directly.
That way you can avoid all that pop
ing and append
ing which should improve performance.
The stack already exists, so you can assume that when writing your code. The stack contains the return addresses of the functions, the local variables and the variables which are passed between functions. There are also stack registers such as BP, SP (Stack Pointer) built-in that you can use, hence the built-in commands you have mentioned. If the stack wasn't already implemented, functions couldn't run, and code flow couldn't work.
There is a really nice, easy to use, lightweight (uses native browser events for detection) plugin for both basic JavaScript and for jQuery that was released this year. It performs perfectly:
Surprised to see no one mentioned more capable, interactive and easier to use alternatives.
Just two lines and you get:
interactivity,
smooth scale,
colors based on whole dataframe instead of individual columns,
column names & row indices on axes,
zooming in,
panning,
built-in one-click ability to save it as a PNG format,
auto-scaling,
comparison on hovering,
bubbles showing values so heatmap still looks good and you can see values wherever you want:
import plotly.express as px
fig = px.imshow(df.corr())
fig.show()
All the same functionality with a tad much hassle. But still worth it if you do not want to opt-in for plotly and still want all these things:
from bokeh.plotting import figure, show, output_notebook
from bokeh.models import ColumnDataSource, LinearColorMapper
from bokeh.transform import transform
output_notebook()
colors = ['#d7191c', '#fdae61', '#ffffbf', '#a6d96a', '#1a9641']
TOOLS = "hover,save,pan,box_zoom,reset,wheel_zoom"
data = df.corr().stack().rename("value").reset_index()
p = figure(x_range=list(df.columns), y_range=list(df.index), tools=TOOLS, toolbar_location='below',
tooltips=[('Row, Column', '@level_0 x @level_1'), ('value', '@value')], height = 500, width = 500)
p.rect(x="level_1", y="level_0", width=1, height=1,
source=data,
fill_color={'field': 'value', 'transform': LinearColorMapper(palette=colors, low=data.value.min(), high=data.value.max())},
line_color=None)
color_bar = ColorBar(color_mapper=LinearColorMapper(palette=colors, low=data.value.min(), high=data.value.max()), major_label_text_font_size="7px",
ticker=BasicTicker(desired_num_ticks=len(colors)),
formatter=PrintfTickFormatter(format="%f"),
label_standoff=6, border_line_color=None, location=(0, 0))
p.add_layout(color_bar, 'right')
show(p)
Fragmentation. Char reserves space and VarChar does not. Page split can be required to accommodate update to varchar.
To improve James' excellent answer:
It's better to put BINARY
in front of the constant instead:
SELECT * FROM `table` WHERE `column` = BINARY 'value'
Putting BINARY
in front of column
will prevent the use of any index on that column.
I would consider this more of an old-school C style; it is not really good practice in JavaScript so you should avoid it.
In ascending order you can use:
sorted_data= sorted(non_sorted_data, key=lambda k: (k[1],k[0]))
or in descending order you can use:
sorted_data= sorted(non_sorted_data, key=lambda k: (k[1],k[0]),reverse=True)
I had to drop the extra quoting using msysGit on windows 7, not sure why.
git config --global merge.tool p4merge
git config --global mergetool.p4merge.cmd 'p4merge $BASE $LOCAL $REMOTE $MERGED'
HashMap<String, String> hashMap = new HashMap<>();
String[] stringValues= new String[hashMap.values().size()];
hashMap.values().toArray(stringValues);
skipUntil : ignore emitted items until another observable has emitted
last: emit last value from a sequence (i.e. wait until it completes then emit)
Note that anything emitted from the observable passed to skipUntil
will cancel the skipping, which is why we need to add last()
- to wait for the stream to complete.
main$.skipUntil(sequence2$.pipe(last()))
Official: https://rxjs-dev.firebaseapp.com/api/operators/skipUntil
Possible issue: Note that last()
by itself will error if nothing is emitted. The last()
operator does have a default
parameter but only when used in conjunction with a predicate. I think if this situation is a problem for you (if sequence2$
may complete without emitting) then one of these should work (currently untested):
main$.skipUntil(sequence2$.pipe(defaultIfEmpty(undefined), last()))
main$.skipUntil(sequence2$.pipe(last(), catchError(() => of(undefined))
Note that undefined
is a valid item to be emitted, but could actually be any value. Also note that this is the pipe attached to sequence2$
and not the main$
pipe.
df = df.merge(same.drop_duplicates(), on=['col1','col2'],
how='left', indicator=True)
save the dissimilar rows in CSV
df[df['_merge'] == 'left_only'].to_csv('output.csv')
using System.Net;
using System.Net.Mail;
using(SmtpClient smtpClient = new SmtpClient())
{
var basicCredential = new NetworkCredential("username", "password");
using(MailMessage message = new MailMessage())
{
MailAddress fromAddress = new MailAddress("[email protected]");
smtpClient.Host = "mail.mydomain.com";
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = basicCredential;
message.From = fromAddress;
message.Subject = "your subject";
// Set IsBodyHtml to true means you can send HTML email.
message.IsBodyHtml = true;
message.Body = "<h1>your message body</h1>";
message.To.Add("[email protected]");
try
{
smtpClient.Send(message);
}
catch(Exception ex)
{
//Error, could not send the message
Response.Write(ex.Message);
}
}
}
You may use the above code.
CDATA is a better general solution.
There are many methods :
CSS
<div style="width:200px;height:100px;position:absolute;left:50%;top:50%;
margin-left:-100px;margin-top:-50px;">
<!–content–>
</div>
2 . Center horizontally and vertically a single line of text
CSS
<div style="width:400px;height:200px;text-align:center;line-height:200px;">
<!–content–>
</div>
3 . Center horizontal and vertical align of an element with no specific measure
CSS
<div style="display:table;height:300px;text-align:center;">
<div style="display:table-cell;vertical-align:middle;">
<!–content–>
</div>
</div>
This happened to me while trying to copy over the PSPDFKIT demo library into my project. I followed all the instructions in the site + all the suggestions on this page.. for some reason it kept on giving the above error, the problem was that if i grepped the message in the error method.. it only appeared in the binary (obviously I have no access to the source code b/c I have to pay for it).
I noticed this in the instruction page though:
So I went to the guts of that config file and found this:
OTHER_LDFLAGS=$(inherited) -ObjC -fobjc-arc -lz -framework CoreText -framework CoreMedia -framework MediaPlayer -framework AVFoundation -framework ImageIO -framework MediaPlayer -framework MessageUI -framework CoreGraphics -framework Foundation -framework QuartzCore -framework AVFoundation -framework CFNetwork -framework MobileCoreServices -framework SystemConfiguration -weak_framework UIKit
Then I went to the sample project provided by the author of the said library.. and noticed that the previous flags where copied verbatim to the other linker flags in my build settings.. however in my project.. they were not!.. So i simply copied and pasted them into my project's build settings other linker flags and everything worked!
take away point: if you are relying on some .xcconfig file on your setup, double check with a sample code source or something and make sure that it has actually been applied.. it wasn't applied properly in my case
This looks like the kind of error that Maven generates when you don't have the compiler plugin configured correctly. Here's an example of a Java 8 compiler config.
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<!-- ... -->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<!-- ... -->
</project>
See this IEEE_754_types.h
header for the union types to extract: float
, double
and long double
, (endianness handled). Here is an extract:
/*
** - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
** Single Precision (float) -- Standard IEEE 754 Floating-point Specification
*/
# define IEEE_754_FLOAT_MANTISSA_BITS (23)
# define IEEE_754_FLOAT_EXPONENT_BITS (8)
# define IEEE_754_FLOAT_SIGN_BITS (1)
.
.
.
# if (IS_BIG_ENDIAN == 1)
typedef union {
float value;
struct {
__int8_t sign : IEEE_754_FLOAT_SIGN_BITS;
__int8_t exponent : IEEE_754_FLOAT_EXPONENT_BITS;
__uint32_t mantissa : IEEE_754_FLOAT_MANTISSA_BITS;
};
} IEEE_754_float;
# else
typedef union {
float value;
struct {
__uint32_t mantissa : IEEE_754_FLOAT_MANTISSA_BITS;
__int8_t exponent : IEEE_754_FLOAT_EXPONENT_BITS;
__int8_t sign : IEEE_754_FLOAT_SIGN_BITS;
};
} IEEE_754_float;
# endif
And see dtoa_base.c
for a demonstration of how to convert a double
value to string form.
Furthermore, check out section 1.2.1.1.4.2 - Floating-Point Type Memory Layout of the C/CPP Reference Book, it explains super well and in simple terms the memory representation/layout of all the floating-point types and how to decode them (w/ illustrations) following the actually IEEE 754 Floating-Point specification.
It also has links to really really good ressources that explain even deeper.
Internet E-mail address format (RFC 822
)
(,)
comma separated sequence of addresses
javax.mail - 1.4.7 parse( String[] )
is not allowed. So we have to give comma separated sequence of addresses into InternetAddress
objects. Addresses must follow RFC822 syntax.
String toAddress = "[email protected],[email protected]";
InternetAddress.parse( toAddress );
(;)
semi-colon separated sequence of addresses « If group of address list is provided with delimeter as ";" then convert to String array using split method to use the following function.
String[] addressList = { "[email protected]", "[email protected]" };
String toGroup = "[email protected];[email protected]";
String[] addressList2 = toGroup.split(";");
setRecipients(message, addressList);
public static void setRecipients(Message message, Object addresslist) throws AddressException, MessagingException {
if ( addresslist instanceof String ) { // CharSequence
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse( (String) addresslist ));
} else if ( addresslist instanceof String[] ) { // String[] « Array with collection of Strings/
String[] toAddressList = (String[]) addresslist;
InternetAddress[] mailAddress_TO = new InternetAddress[ toAddressList.length ];
for (int i = 0; i < toAddressList.length; i++) {
mailAddress_TO[i] = new InternetAddress( toAddressList[i] );
}
message.setRecipients(Message.RecipientType.TO, mailAddress_TO);
}
}
Full Example:
public static Properties getMailProperties( boolean addExteraProps ) {
Properties props = new Properties();
props.put("mail.transport.protocol", MAIL_TRNSPORT_PROTOCOL);
props.put("mail.smtp.host", MAIL_SERVER_NAME);
props.put("mail.smtp.port", MAIL_PORT);
// Sending Email to the GMail SMTP server requires authentication and SSL.
props.put("mail.smtp.auth", true);
if( ENCRYPTION_METHOD.equals("STARTTLS") ) {
props.put("mail.smtp.starttls.enable", true);
props.put("mail.smtp.socketFactory.port", SMTP_STARTTLS_PORT); // 587
} else {
props.put("mail.smtps.ssl.enable", true);
props.put("mail.smtp.socketFactory.port", SMTP_SSL_PORT); // 465
}
props.put("mail.smtp.socketFactory", SOCKETFACTORY_CLASS);
return props;
}
public static boolean sendMail(String subject, String contentType, String msg, Object recipients) throws Exception {
Properties props = getMailProperties( false );
Session mailSession = Session.getInstance(props, null);
mailSession.setDebug(true);
Message message = new MimeMessage( mailSession );
message.setFrom( new InternetAddress( USER_NAME ) );
setRecipients(message, recipients);
message.setSubject( subject );
String htmlData = "<h1>This is actual message embedded in HTML tags</h1>";
message.setContent( htmlData, "text/html");
Transport transport = mailSession.getTransport( MAIL_TRNSPORT_PROTOCOL );
transport.connect(MAIL_SERVER_NAME, Integer.valueOf(MAIL_PORT), USER_NAME, PASSWORD);
message.saveChanges(); // don't forget this
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
Using Appache
SimpleEmail
-commons-email-1.3.1
Example: email.addTo( addressList );
public static void sendSimpleMail() throws Exception {
Email email = new SimpleEmail();
email.setSmtpPort(587);
DefaultAuthenticator defaultAuthenticator = new DefaultAuthenticator( USER_NAME, PASSWORD );
email.setAuthenticator( defaultAuthenticator );
email.setDebug(false);
email.setHostName( MAIL_SERVER_NAME );
email.setFrom( USER_NAME );
email.setSubject("Hi");
email.setMsg("This is a test mail ... :-)");
//email.addTo( "[email protected]", "Yash" );
String[] toAddressList = { "[email protected]", "[email protected]" }
email.addTo( addressList );
email.setTLS(true);
email.setStartTLSEnabled( true );
email.send();
System.out.println("Mail sent!");
}
I am using the following
....
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<finalName>${project.groupId}/${project.artifactId}-${baseVersion}.${monthlyVersion}.${instanceVersion}</finalName>
</configuration>
</plugin>
....
This way you can define each value individually or pragmatically from Jenkins of some other system.
mvn package -DbaseVersion=1 -monthlyVersion=2 -instanceVersion=3
This will place a folder target\{group.id}\projectName-1.2.3.jar
A better way to save time might be
....
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<finalName>${project.groupId}/${project.artifactId}-${baseVersion}</finalName>
</configuration>
</plugin>
....
Like the same except I use on variable.
mvn package -DbaseVersion=0.3.4
This will place a folder target\{group.id}\projectName-1.2.3.jar
you can also use outputDirectory
inside of configuration
to specify a location you may want the package to be located.
Select the range of cells, type in the value and press Ctrl + Enter.
This, of course, is true if you want to do it manually.
There are two best contenders:
Create a 1×1 image data, set the color, and putImageData
at the location:
var id = myContext.createImageData(1,1); // only do this once per page
var d = id.data; // only do this once per page
d[0] = r;
d[1] = g;
d[2] = b;
d[3] = a;
myContext.putImageData( id, x, y );
Use fillRect()
to draw a pixel (there should be no aliasing issues):
ctx.fillStyle = "rgba("+r+","+g+","+b+","+(a/255)+")";
ctx.fillRect( x, y, 1, 1 );
You can test the speed of these here: http://jsperf.com/setting-canvas-pixel/9 or here https://www.measurethat.net/Benchmarks/Show/1664/1
I recommend testing against browsers you care about for maximum speed. As of July 2017, fillRect()
is 5-6× faster on Firefox v54 and Chrome v59 (Win7x64).
Other, sillier alternatives are:
using getImageData()/putImageData()
on the entire canvas; this is about 100× slower than other options.
creating a custom image using a data url and using drawImage()
to show it:
var img = new Image;
img.src = "data:image/png;base64," + myPNGEncoder(r,g,b,a);
// Writing the PNGEncoder is left as an exercise for the reader
creating another img or canvas filled with all the pixels you want and use drawImage()
to blit just the pixel you want across. This would probably be very fast, but has the limitation that you need to pre-calculate the pixels you need.
Note that my tests do not attempt to save and restore the canvas context fillStyle
; this would slow down the fillRect()
performance. Also note that I am not starting with a clean slate or testing the exact same set of pixels for each test.
Enclosed in {} represents an object; enclosed in [] represents an array, there can be multiple objects in the array
example object :
{
"brand": "bwm",
"price": 30000
}
{
"brand": "benz",
"price": 50000
}
example array:
[
{
"brand": "bwm",
"price": 30000
},
{
"brand": "benz",
"price": 50000
}
]
In order to use JSON more beautifully, you can go here JSON Viewer do format
int is the C# language's shortcut for System.Int32
Whilst this does mean that Microsoft could change this mapping, a post on FogCreek's discussions stated [source]
"On the 64 bit issue -- Microsoft is indeed working on a 64-bit version of the .NET Framework but I'm pretty sure int will NOT map to 64 bit on that system.
Reasons:
1. The C# ECMA standard specifically says that int is 32 bit and long is 64 bit.
2. Microsoft introduced additional properties & methods in Framework version 1.1 that return long values instead of int values, such as Array.GetLongLength in addition to Array.GetLength.
So I think it's safe to say that all built-in C# types will keep their current mapping."
You can restart the database on RDS Admin.
For those who are having a hard time finding the "merge buttons".
The little lightbulp icon with merge options only shows up if you click precisely on the "merge conflict marker"
<<<<<<<
Steps (in VS Code 1.29.x):
Add your JDK's /bin folder to the PATH
environmental variable. You can do this under System settings > Environmental variables, or via CLI:
set PATH=%PATH%;C:\Program Files\Java\jdk1.7.0_80\bin
Close and reopen your CLI window
A dictionary is not indexed, but it is in some way, ordered. The following would give you the first existing key:
list(my_dict.keys())[0]
Building on Jared's answer, I had to enable and implement the action bar back button behavior in several activities and created this helper class to reduce code duplication.
public final class ActionBarHelper {
public static void enableBackButton(AppCompatActivity context) {
if(context == null) return;
ActionBar actionBar = context.getSupportActionBar();
if (actionBar == null) return;
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
Usage in an activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
ActionBarHelper.enableBackButton(this);
}
Google Chrome now supports this (Developer Tools > Network > [XHR item in list] Preview
).
In addition, you can use a third party tool to format the json content. Here's one that presents a tree view, and here's another that merely formats the text (and does validation).
In a new ASP.Net 5 MVC project in a controller action you can still do this.Context
and this.Context.Request
It looks like on the Request there is no longer a Url property but the child properties (schema, host, etc) are all on the request object directly.
public IActionResult About()
{
ViewBag.Message = "Your application description page.";
var schema = this.Context.Request.Scheme;
return View();
}
Rather or not you want to use this.Context or inject the property is another conversation. Dependency Injection in ASP.NET vNext
how to club the 4 query's as a single query
show below query
nsc = nature of case
report is taken on 06th of every month
( monthly report will be counted from 05th previous month to 05th present of present month)
column(1)
is your friend.
$ column -t <<< '"option-y" yank-pop
> "option-z" execute-last-named-cmd
> "option-|" vi-goto-column
> "option-~" _bash_complete-word
> "option-control-?" backward-kill-word
> "control-_" undo
> "control-?" backward-delete-char
> '
"option-y" yank-pop
"option-z" execute-last-named-cmd
"option-|" vi-goto-column
"option-~" _bash_complete-word
"option-control-?" backward-kill-word
"control-_" undo
"control-?" backward-delete-char
I had this problem too. I found setting the appearance to none helped.
.class {
appearance:none;
-moz-appearance:none;
-webkit-appearance:none;
background-color: red;
}
You can also try this. Credits to the original author who has since removed the script
/mobile.class.php
<?php
/*
=====================================================
Mobile version detection
-----------------------------------------------------
compliments of http://www.buchfelder.biz/
=====================================================
*/
$mobile = "http://www.stepforth.mobi";
$text = $_SERVER['HTTP_USER_AGENT'];
$var[0] = 'Mozilla/4.';
$var[1] = 'Mozilla/3.0';
$var[2] = 'AvantGo';
$var[3] = 'ProxiNet';
$var[4] = 'Danger hiptop 1.0';
$var[5] = 'DoCoMo/';
$var[6] = 'Google CHTML Proxy/';
$var[7] = 'UP.Browser/';
$var[8] = 'SEMC-Browser/';
$var[9] = 'J-PHONE/';
$var[10] = 'PDXGW/';
$var[11] = 'ASTEL/';
$var[12] = 'Mozilla/1.22';
$var[13] = 'Handspring';
$var[14] = 'Windows CE';
$var[15] = 'PPC';
$var[16] = 'Mozilla/2.0';
$var[17] = 'Blazer/';
$var[18] = 'Palm';
$var[19] = 'WebPro/';
$var[20] = 'EPOC32-WTL/';
$var[21] = 'Tungsten';
$var[22] = 'Netfront/';
$var[23] = 'Mobile Content Viewer/';
$var[24] = 'PDA';
$var[25] = 'MMP/2.0';
$var[26] = 'Embedix/';
$var[27] = 'Qtopia/';
$var[28] = 'Xiino/';
$var[29] = 'BlackBerry';
$var[30] = 'Gecko/20031007';
$var[31] = 'MOT-';
$var[32] = 'UP.Link/';
$var[33] = 'Smartphone';
$var[34] = 'portalmmm/';
$var[35] = 'Nokia';
$var[36] = 'Symbian';
$var[37] = 'AppleWebKit/413';
$var[38] = 'UPG1 UP/';
$var[39] = 'RegKing';
$var[40] = 'STNC-WTL/';
$var[41] = 'J2ME';
$var[42] = 'Opera Mini/';
$var[43] = 'SEC-';
$var[44] = 'ReqwirelessWeb/';
$var[45] = 'AU-MIC/';
$var[46] = 'Sharp';
$var[47] = 'SIE-';
$var[48] = 'SonyEricsson';
$var[49] = 'Elaine/';
$var[50] = 'SAMSUNG-';
$var[51] = 'Panasonic';
$var[52] = 'Siemens';
$var[53] = 'Sony';
$var[54] = 'Verizon';
$var[55] = 'Cingular';
$var[56] = 'Sprint';
$var[57] = 'AT&T;';
$var[58] = 'Nextel';
$var[59] = 'Pocket PC';
$var[60] = 'T-Mobile';
$var[61] = 'Orange';
$var[62] = 'Casio';
$var[63] = 'HTC';
$var[64] = 'Motorola';
$var[65] = 'Samsung';
$var[66] = 'NEC';
$result = count($var);
for ($i=0;$i<$result;$i++)
{
$ausg = stristr($text, $var[$i]);
if(strlen($ausg)>0)
{
header("location: $mobile");
exit;
}
}
?>
Just edit the $mobile = "http://www.stepforth.mobi";
Try:
def is_array(a)
a.class == Array
end
EDIT: The other answer is much better than mine.
I think df['word'].value_counts()
should serve. By skipping the groupby machinery, you'll save some time. I'm not sure why count
should be much slower than max
. Both take some time to avoid missing values. (Compare with size
.)
In any case, value_counts has been specifically optimized to handle object type, like your words, so I doubt you'll do much better than that.
Your code looks fine, but there are a couple of things to be aware of:
Post::find($id);
acts upon the primary key, if you have set your primary key in your model to something other than id
by doing:
protected $primaryKey = 'slug';
then find
will search by that key instead.
Laravel also expects the id
to be an integer, if you are using something other than an integer (such as a string) you need to set the incrementing property on your model to false:
public $incrementing = false;
Use datetime.datetime.fromtimestamp
:
>>> import datetime
>>> s = 1236472051807 / 1000.0
>>> datetime.datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S.%f')
'2009-03-08 09:27:31.807000'
%f
directive is only supported by datetime.datetime.strftime
, not by time.strftime
.
UPDATE Alternative using %
, str.format
:
>>> import time
>>> s, ms = divmod(1236472051807, 1000) # (1236472051, 807)
>>> '%s.%03d' % (time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'
>>> '{}.{:03d}'.format(time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'
This question is old but as it comes up high on search results I will point out that scipy
has two functions for computing the binomial coefficients:
scipy.special.binom()
import scipy.special
# the two give the same results
scipy.special.binom(10, 5)
# 252.0
scipy.special.comb(10, 5)
# 252.0
scipy.special.binom(300, 150)
# 9.375970277281882e+88
scipy.special.comb(300, 150)
# 9.375970277281882e+88
# ...but with `exact == True`
scipy.special.comb(10, 5, exact=True)
# 252
scipy.special.comb(300, 150, exact=True)
# 393759702772827452793193754439064084879232655700081358920472352712975170021839591675861424
Note that scipy.special.comb(exact=True)
uses Python integers, and therefore it can handle arbitrarily large results!
Speed-wise, the three versions give somewhat different results:
num = 300
%timeit [[scipy.special.binom(n, k) for k in range(n + 1)] for n in range(num)]
# 52.9 ms ± 107 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit [[scipy.special.comb(n, k) for k in range(n + 1)] for n in range(num)]
# 183 ms ± 814 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)each)
%timeit [[scipy.special.comb(n, k, exact=True) for k in range(n + 1)] for n in range(num)]
# 180 ms ± 649 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
(and for n = 300
, the binomial coefficients are too large to be represented correctly using float64
numbers, as shown above).
var option_user_selection = document.getElementById("maincourse").options[document.getElementById("maincourse").selectedIndex ].text
I usually place commands in parentheses $(commandStr)
, if that doesn't help I find bash debug mode great, run the script as bash -x script
I'm developing an app that needs to look similar in all devices with >= API14 when it comes to actionbar and statusbar customization. I've finally found a solution and since it took a bit of my time I'll share it to save some of yours. We start by using an appcompat-21 dependency.
Transparent Actionbar:
values/styles.xml:
<style name="AppTheme" parent="Theme.AppCompat.Light">
...
</style>
<style name="AppTheme.ActionBar.Transparent" parent="AppTheme">
<item name="android:windowContentOverlay">@null</item>
<item name="windowActionBarOverlay">true</item>
<item name="colorPrimary">@android:color/transparent</item>
</style>
<style name="AppTheme.ActionBar" parent="AppTheme">
<item name="windowActionBarOverlay">false</item>
<item name="colorPrimary">@color/default_yellow</item>
</style>
values-v21/styles.xml:
<style name="AppTheme" parent="Theme.AppCompat.Light">
...
</style>
<style name="AppTheme.ActionBar.Transparent" parent="AppTheme">
<item name="colorPrimary">@android:color/transparent</item>
</style>
<style name="AppTheme.ActionBar" parent="AppTheme">
<item name="colorPrimaryDark">@color/bg_colorPrimaryDark</item>
<item name="colorPrimary">@color/default_yellow</item>
</style>
Now you can use these themes in your AndroidManifest.xml
to specify which activities will have a transparent or colored ActionBar
:
<activity
android:name=".MyTransparentActionbarActivity"
android:theme="@style/AppTheme.ActionBar.Transparent"/>
<activity
android:name=".MyColoredActionbarActivity"
android:theme="@style/AppTheme.ActionBar"/>
Note: in API>=21 to get the Actionbar
transparent you need to get the Statusbar
transparent too, otherwise will not respect your colour styles and will stay light-grey.
Transparent Statusbar (only works with API>=19):
This one it's pretty simple just use the following code:
protected void setStatusBarTranslucent(boolean makeTranslucent) {
if (makeTranslucent) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
}
But you'll notice a funky result:
This happens because when the Statusbar
is transparent the layout will use its height. To prevent this we just need to:
SOLUTION ONE:
Add this line android:fitsSystemWindows="true"
in your layout view container of whatever you want to be placed bellow the Actionbar:
...
<LinearLayout
android:fitsSystemWindows="true"
android:layout_width="match_parent"
android:layout_height="match_parent">
...
</LinearLayout>
...
SOLUTION TWO:
Add a few lines to our previous method:
protected void setStatusBarTranslucent(boolean makeTranslucent) {
View v = findViewById(R.id.bellow_actionbar);
if (v != null) {
int paddingTop = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ? MyScreenUtils.getStatusBarHeight(this) : 0;
TypedValue tv = new TypedValue();
getTheme().resolveAttribute(android.support.v7.appcompat.R.attr.actionBarSize, tv, true);
paddingTop += TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
v.setPadding(0, makeTranslucent ? paddingTop : 0, 0, 0);
}
if (makeTranslucent) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
}
Where R.id.bellow_actionbar
will be the layout container view id of whatever we want to be placed bellow the Actionbar
:
...
<LinearLayout
android:id="@+id/bellow_actionbar"
android:layout_width="match_parent"
android:layout_height="match_parent">
...
</LinearLayout>
...
So this is it, it think I'm not forgetting something.
In this example I didn't use a Toolbar
but I think it'll have the same result. This is how I customize my Actionbar
:
@Override
protected void onCreate(Bundle savedInstanceState) {
View vg = getActionBarView();
getWindow().requestFeature(vg != null ? Window.FEATURE_ACTION_BAR : Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(getContentView());
if (vg != null) {
getSupportActionBar().setCustomView(vg, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(false);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayUseLogoEnabled(false);
}
setStatusBarTranslucent(true);
}
Note: this is an abstract class
that extends ActionBarActivity
Hope it helps!
Even if the generics problems are fixed in 1.3
the great thing about this method is it works on any class that has an isEmpty()
method! Not just Collections
!
For example it will work on String
as well!
/* Matches any class that has an <code>isEmpty()</code> method
* that returns a <code>boolean</code> */
public class IsEmpty<T> extends TypeSafeMatcher<T>
{
@Factory
public static <T> Matcher<T> empty()
{
return new IsEmpty<T>();
}
@Override
protected boolean matchesSafely(@Nonnull final T item)
{
try { return (boolean) item.getClass().getMethod("isEmpty", (Class<?>[]) null).invoke(item); }
catch (final NoSuchMethodException e) { return false; }
catch (final InvocationTargetException | IllegalAccessException e) { throw new RuntimeException(e); }
}
@Override
public void describeTo(@Nonnull final Description description) { description.appendText("is empty"); }
}
if you are using maven:
mvn eclipse:eclipse -DdownloadSources=true -DdownloadJavadocs=true
It's also important to realize that simply moving the program break pointer around with brk
and sbrk
doesn't actually allocate the memory, it just sets up the address space. On Linux, for example, the memory will be "backed" by actual physical pages when that address range is accessed, which will result in a page fault, and will eventually lead to the kernel calling into the page allocator to get a backing page.
My personal favorite alias, via .gitconfig, is:
graph = log --graph --color --all --pretty=format:"%C(yellow)%H%C(green)%d%C(reset)%n%x20%cd%n%x20%cn%x20(%ce)%n%x20%s%n"
An example of Python's way of doing "ternary" expressions:
i = 5 if a > 7 else 0
translates into
if a > 7:
i = 5
else:
i = 0
This actually comes in handy when using list comprehensions, or sometimes in return statements, otherwise I'm not sure it helps that much in creating readable code.
The readability issue was discussed at length in this recent SO question better way than using if-else statement in python.
It also contains various other clever (and somewhat obfuscated) ways to accomplish the same task. It's worth a read just based on those posts.
First argument in update
method is SyntheticEvent
object that contains common properties and methods to any event
, it is not reference to React component where there is property props
.
if you need pass argument to update method you can do it like this
onClick={ (e) => this.props.onClick(e, 'home', 'Home') }
and get these arguments inside update
method
update(e, space, txt){
console.log(e.target, space, txt);
}
event.target
gives you the native DOMNode
, then you need to use the regular DOM APIs to access attributes. For instance getAttribute
or dataset
<button
data-space="home"
className="home"
data-txt="Home"
onClick={ this.props.onClick }
/>
Button
</button>
onClick(e) {
console.log(e.target.dataset.txt, e.target.dataset.space);
}
you are a PyCharm User, its good easy to install Flask First open the pycharm press Open Settings(Ctrl+Alt+s) Goto Project Interpreter
Double click pip>>
search bar (top of page) you search the flask and click install package
such Cases in which flask is not shown in pip: Open Manage Repository>> Add(+) >> Add this following url
https://www.palletsprojects.com/p/flask/
Now back to pip, it will show related packages of flask,
select flask>>
install package
We have the following benefits of using IHttpActionResult
over HttpResponseMessage
:
IHttpActionResult
we are only concentrating on the data to be send not on the status code. So here the code will be cleaner and very easy to maintain.async
and await
by default.You'd better create some class for each item instead of using anonymous objects. And in object you're serializing you should have array of those items. E.g.:
public class Item
{
public string name { get; set; }
public string index { get; set; }
public string optional { get; set; }
}
public class RootObject
{
public List<Item> items { get; set; }
}
Usage:
var objectToSerialize = new RootObject();
objectToSerialize.items = new List<Item>
{
new Item { name = "test1", index = "index1" },
new Item { name = "test2", index = "index2" }
};
And in the result you won't have to change things several times if you need to change data-structure.
p.s. Here's very nice tool for complex json
s
In my case it was because I didn't connect to databases yet when first opened solution. click connection manager tab, establish connection to every datasource in that tab, run project
The code for percent sign in NSString
format is %%
. This is also true for NSLog()
and printf()
formats.
Thats an if/else statement equilavent to
if(row % 2 == 1){
System.out.print("<");
}else{
System.out.print("\r>");
}
For deep nested object you can use my snippet for lodash > 4
const removeObjectsWithNull = (obj) => {
return _(obj)
.pickBy(_.isObject) // get only objects
.mapValues(removeObjectsWithNull) // call only for values as objects
.assign(_.omitBy(obj, _.isObject)) // save back result that is not object
.omitBy(_.isNil) // remove null and undefined from object
.value(); // get value
};
multi-dimentional frequency count, i.e. counting arrays.
>>> print(color_array )
array([[255, 128, 128],
[255, 128, 128],
[255, 128, 128],
...,
[255, 128, 128],
[255, 128, 128],
[255, 128, 128]], dtype=uint8)
>>> np.unique(color_array,return_counts=True,axis=0)
(array([[ 60, 151, 161],
[ 60, 155, 162],
[ 60, 159, 163],
[ 61, 143, 162],
[ 61, 147, 162],
[ 61, 162, 163],
[ 62, 166, 164],
[ 63, 137, 162],
[ 63, 169, 164],
array([ 1, 2, 2, 1, 4, 1, 1, 2,
3, 1, 1, 1, 2, 5, 2, 2,
898, 1, 1,
Why do you need to state both 'x' and 'y' before the ':'?
Because a lambda is (conceptually) the same as a function, just written inline. Your example is equivalent to
def f(x, y) : return x + y
just without binding it to a name like f
.
Also how do you make it return multiple arguments?
The same way like with a function. Preferably, you return a tuple:
lambda x, y: (x+y, x-y)
Or a list, or a class, or whatever.
The thing with self.entry_1.bind
should be answered by Demosthenex.
I had problems with the mentioned methods when I use an array like
var array = ['foo', 'bar', 'foobar'];
var filled = array.fill(7);
//filled should be ['foo', 'bar', 'foobar', 'foo', 'bar', 'foobar', 'foo']
To get this I'm using:
Array.prototype.fill = function(val){
var l = this.length;
if(l < val){
for(var i = val-1-l; i >= 0; i--){
this[i+l] = this[i % l];
}
}
return this;
};
We passed Json object by HttpPost method, and parse it in dynamic object. it works fine. this is sample code:
webapi:
[HttpPost]
public string DoJson2(dynamic data)
{
//whole:
var c = JsonConvert.DeserializeObject<YourObjectTypeHere>(data.ToString());
//or
var c1 = JsonConvert.DeserializeObject< ComplexObject1 >(data.c1.ToString());
var c2 = JsonConvert.DeserializeObject< ComplexObject2 >(data.c2.ToString());
string appName = data.AppName;
int appInstanceID = data.AppInstanceID;
string processGUID = data.ProcessGUID;
int userID = data.UserID;
string userName = data.UserName;
var performer = JsonConvert.DeserializeObject< NextActivityPerformers >(data.NextActivityPerformers.ToString());
...
}
The complex object type could be object, array and dictionary.
ajaxPost:
...
Content-Type: application/json,
data: {"AppName":"SamplePrice",
"AppInstanceID":"100",
"ProcessGUID":"072af8c3-482a-4b1c??-890b-685ce2fcc75d",
"UserID":"20",
"UserName":"Jack",
"NextActivityPerformers":{
"39??c71004-d822-4c15-9ff2-94ca1068d745":[{
"UserID":10,
"UserName":"Smith"
}]
}}
...
I'm going to give the short answer since everyone else gave the long one.
You'll get .select and .activate whenever you record macros and reuse them. When you .select a cell or sheet it just makes it active. From that point on whenever you use unqualified references like Range.Value
they just use the active cell and sheet. This can also be problematic if you don't watch where your code is placed or a user clicks on the workbook.
So, you can eliminate these issues by directly referencing your cells. Which goes:
'create and set a range
Dim Rng As Excel.Range
Set Rng = Workbooks("Book1").Worksheets("Sheet1").Range("A1")
'OR
Set Rng = Workbooks(1).Worksheets(1).Cells(1, 1)
Or you could
'Just deal with the cell directly rather than creating a range
'I want to put the string "Hello" in Range A1 of sheet 1
Workbooks("Book1").Worksheets("Sheet1").Range("A1").value = "Hello"
'OR
Workbooks(1).Worksheets(1).Cells(1, 1).value = "Hello"
There are various combinations of these methods, but that would be the general idea expressed as shortly as possible for impatient people like me.
While this is definitely not the optimal solution to the problem, it is another potential solution which I thought some people might find interesting:
/**
* Treat the bst as a sorted list in descending order and find the element
* in position k.
*
* Time complexity BigO ( n^2 )
*
* 2n + sum( 1 * n/2 + 2 * n/4 + ... ( 2^n-1) * n/n ) =
* 2n + sigma a=1 to n ( (2^(a-1)) * n / 2^a ) = 2n + n(n-1)/4
*
* @param t The root of the binary search tree.
* @param k The position of the element to find.
* @return The value of the element at position k.
*/
public static int kElement2( Node t, int k ) {
int treeSize = sizeOfTree( t );
return kElement2( t, k, treeSize, 0 ).intValue();
}
/**
* Find the value at position k in the bst by doing an in-order traversal
* of the tree and mapping the ascending order index to the descending order
* index.
*
*
* @param t Root of the bst to search in.
* @param k Index of the element being searched for.
* @param treeSize Size of the entire bst.
* @param count The number of node already visited.
* @return Either the value of the kth node, or Double.POSITIVE_INFINITY if
* not found in this sub-tree.
*/
private static Double kElement2( Node t, int k, int treeSize, int count ) {
// Double.POSITIVE_INFINITY is a marker value indicating that the kth
// element wasn't found in this sub-tree.
if ( t == null )
return Double.POSITIVE_INFINITY;
Double kea = kElement2( t.getLeftSon(), k, treeSize, count );
if ( kea != Double.POSITIVE_INFINITY )
return kea;
// The index of the current node.
count += 1 + sizeOfTree( t.getLeftSon() );
// Given any index from the ascending in order traversal of the bst,
// treeSize + 1 - index gives the
// corresponding index in the descending order list.
if ( ( treeSize + 1 - count ) == k )
return (double)t.getNumber();
return kElement2( t.getRightSon(), k, treeSize, count );
}
You need to publish the exposed ports by using the following options:
-P (upper case) or --publish-all that will tell Docker to use random ports from your host and map them to the exposed container's ports.
-p (lower case) or --publish=[] that will tell Docker to use ports you manually set and map them to the exposed container's ports.
The second option is preferred because you already know which ports are mapped. If you use the first option then you will need to call docker inspect demo
and check which random ports are being used from your host at the Ports section.
Just run the following command:
docker run -it -p 8080:8080 demo
After that your url will work.
I'm using get-json very simple to use:
$ npm install get-json --save
Import get-json
var getJSON = require('get-json')
To do a GET
request you would do something like:
getJSON('http://api.listenparadise.org', function(error, response){
console.log(response);
})
Here it is:
function call_func(input) {
var evaled = eval('(' + input + ')');
var newDiv = document.createElement('div');
var id = evaled.id;
var name = evaled.Student_name;
var dob = evaled.student_dob;
var html = '<b>ID:</b>';
html += '<a href="/learningyii/index.php?r=student/view& id=' + id + '">' + id + '</a>';
html += '<br/>';
html += '<b>Student Name:</b>';
html += name;
html += '<br/>';
html += '<b>Student DOB:</b>';
html += dob;
html += '<br/>';
newDiv.innerHTML = html;
newDiv.setAttribute('class', 'view');
$('#StudentGridViewId').find('.items').prepend(newDiv);
};
Even though du
usually prints disk usage and not actual data size, GNU coreutils du
can print file's "apparent size" in bytes:
du -b FILE
But it won't work under BSD, Solaris, macOS, ...
Try this code, it works perfectly.
var IDLE_TIMEOUT = 10; //seconds
var _idleSecondsCounter = 0;
document.onclick = function () {
_idleSecondsCounter = 0;
};
document.onmousemove = function () {
_idleSecondsCounter = 0;
};
document.onkeypress = function () {
_idleSecondsCounter = 0;
};
window.setInterval(CheckIdleTime, 1000);
function CheckIdleTime() {
_idleSecondsCounter++;
var oPanel = document.getElementById("SecondsUntilExpire");
if (oPanel)
oPanel.innerHTML = (IDLE_TIMEOUT - _idleSecondsCounter) + "";
if (_idleSecondsCounter >= IDLE_TIMEOUT) {
alert("Time expired!");
document.location.href = "SessionExpired.aspx";
}
}
Arguably, it is an example of syntactic sugar, since it is implemented as an array anyways (which doesn't mean it's useless) - I prefer passing an array to keep it clear, and also declare methods with arrays of given type. Rather an opinion than an answer, though.
You may find an answer with this example : errorbar_demo_features.py
"""
Demo of errorbar function with different ways of specifying error bars.
Errors can be specified as a constant value (as shown in `errorbar_demo.py`),
or as demonstrated in this example, they can be specified by an N x 1 or 2 x N,
where N is the number of data points.
N x 1:
Error varies for each point, but the error values are symmetric (i.e. the
lower and upper values are equal).
2 x N:
Error varies for each point, and the lower and upper limits (in that order)
are different (asymmetric case)
In addition, this example demonstrates how to use log scale with errorbar.
"""
import numpy as np
import matplotlib.pyplot as plt
# example data
x = np.arange(0.1, 4, 0.5)
y = np.exp(-x)
# example error bar values that vary with x-position
error = 0.1 + 0.2 * x
# error bar values w/ different -/+ errors
lower_error = 0.4 * error
upper_error = error
asymmetric_error = [lower_error, upper_error]
fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True)
ax0.errorbar(x, y, yerr=error, fmt='-o')
ax0.set_title('variable, symmetric error')
ax1.errorbar(x, y, xerr=asymmetric_error, fmt='o')
ax1.set_title('variable, asymmetric error')
ax1.set_yscale('log')
plt.show()
Which plots this:
The reason why what you want to do doesn't work is because of the logical order of operations in SQL, which, for your first query, is (simplified):
FROM MonitoringJob
SELECT Category, CreationDate
i.e. add a so called extended sort key columnORDER BY CreationDate DESC
SELECT Category
i.e. remove the extended sort key column again from the result.So, thanks to the SQL standard extended sort key column feature, it is totally possible to order by something that is not in the SELECT
clause, because it is being temporarily added to it behind the scenes.
DISTINCT
?If we add the DISTINCT
operation, it would be added between SELECT
and ORDER BY
:
FROM MonitoringJob
SELECT Category, CreationDate
DISTINCT
ORDER BY CreationDate DESC
SELECT Category
But now, with the extended sort key column CreationDate
, the semantics of the DISTINCT
operation has been changed, so the result will no longer be the same. This is not what we want, so both the SQL standard, and all reasonable databases forbid this usage.
It can be emulated with standard syntax as follows
SELECT Category
FROM (
SELECT Category, MAX(CreationDate) AS CreationDate
FROM MonitoringJob
GROUP BY Category
) t
ORDER BY CreationDate DESC
Or, just simply (in this case), as shown also by Prutswonder
SELECT Category, MAX(CreationDate) AS CreationDate
FROM MonitoringJob
GROUP BY Category
ORDER BY CreationDate DESC
I have blogged about SQL DISTINCT and ORDER BY more in detail here.
Accurate and fast will give output in seconds:
let startDate = new Date()
let endDate = new Date("yyyy-MM-dd'T'HH:mm:ssZ");
let seconds = Math.round((endDate.getTime() - startDate.getTime()) / 1000);
My Code Is Very Easy To Understand
var year = 2015;
var LeapYear = year % 4;
if (LeapYear==0) {
alert("This is Leap Year");
} else {
alert("This is not leap year");
}
For anyone using Windows 10 and nothing else working for him/her:
In my case, I had to clone the repo with https instead of ssh and a window popped-up asking for my credentials. After that everything works fine.
If you are using oc4j to deploy the ear.
Make sure you set in the project the correct path for deploy.home=
You can fiind deploy.home in common.properties file
The oc4j needs to reload the new created class in the ear so that the server class and the client class have the same serialVersionUID
For me this started happening because on a project, I was using Docker image mysql:latest (which was version 5, and which was working fine), and during a later build, the latest version was switched to version 8, and stopped working. I changed my image to mysql:5 and I was no longer getting this error.
The following should be clean (using find_package
) and work (the find module is called FindThreads
):
cmake_minimum_required (VERSION 2.6)
find_package (Threads)
add_executable (myapp main.cpp ...)
target_link_libraries (myapp ${CMAKE_THREAD_LIBS_INIT})
in my case, upgrading pip did the trick. Also, I've installed scipy with -U parameter (upgrade all packages to the last available version)
No matter what we tried we couldn't manage to get the timeout below 21 seconds when the server we were checking was down.
To work around this we combined a TcpClient check to see if the domain was alive followed by a separate check to see if the URL was active
public static bool IsUrlAlive(string aUrl, int aTimeoutSeconds)
{
try
{
//check the domain first
if (IsDomainAlive(new Uri(aUrl).Host, aTimeoutSeconds))
{
//only now check the url itself
var request = System.Net.WebRequest.Create(aUrl);
request.Method = "HEAD";
request.Timeout = aTimeoutSeconds * 1000;
var response = (HttpWebResponse)request.GetResponse();
return response.StatusCode == HttpStatusCode.OK;
}
}
catch
{
}
return false;
}
private static bool IsDomainAlive(string aDomain, int aTimeoutSeconds)
{
try
{
using (TcpClient client = new TcpClient())
{
var result = client.BeginConnect(aDomain, 80, null, null);
var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(aTimeoutSeconds));
if (!success)
{
return false;
}
// we have connected
client.EndConnect(result);
return true;
}
}
catch
{
}
return false;
}
SyntaxHighlighter is a fully functional self-contained code syntax highlighter developed in JavaScript. To get an idea of what SyntaxHighlighter is capable of, have a look at the demo page.
If you just want to access the last item in the list you can do
if(integerList.Count>0)
{
var item = integerList[integerList.Count - 1];
}
to get the total number of items in the list you can use the Count
property
var itemCount = integerList.Count;
I don't know if this has really been solved or not... but by looking at all the other answers, nothing seems quite clear. The best way I found to do this is to put the same code, that was used to populate your datagridview
into a method and pass it your form's datagridview
, as so:
public void ConnectAndPopulateDataGridView(DataGridView dataGridView)
{ }
The code within the method is the exact same as the code used to populate the datagirdview
originally, except for the datagridview
name changing to whatever you called it in your method.
Now this method is called in your parent form.
The child form is launched via a .ShowDialog()
then the method is called after so that it is called right after the child for is closed... as so:
ChildForm.ShowDialog();
ConnectAndPopulateDataGridView(dataGridView1);
Here is yet another, compact version, with the generics syntax:
public static IEnumerable<T> FindLogicalChildren<T>(DependencyObject obj) where T : DependencyObject
{
if (obj != null) {
if (obj is T)
yield return obj as T;
foreach (DependencyObject child in LogicalTreeHelper.GetChildren(obj).OfType<DependencyObject>())
foreach (T c in FindLogicalChildren<T>(child))
yield return c;
}
}
Write-Back is a more complex one and requires a complicated Cache Coherence Protocol(MOESI) but it is worth it as it makes the system fast and efficient.
The only benefit of Write-Through is that it makes the implementation extremely simple and no complicated cache coherency protocol is required.
Here are a couple of complete working examples that build on the @bendewey & @dommer examples. I needed to tweak each one a bit to get it to work, but in case another LINQ noob is looking for working examples, here you go:
//bendewey's example using data.xml from OP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
class loadXMLToLINQ1
{
static void Main( )
{
//Load xml
XDocument xdoc = XDocument.Load(@"c:\\data.xml"); //you'll have to edit your path
//Run query
var lv1s = from lv1 in xdoc.Descendants("level1")
select new
{
Header = lv1.Attribute("name").Value,
Children = lv1.Descendants("level2")
};
StringBuilder result = new StringBuilder(); //had to add this to make the result work
//Loop through results
foreach (var lv1 in lv1s)
{
result.AppendLine(" " + lv1.Header);
foreach(var lv2 in lv1.Children)
result.AppendLine(" " + lv2.Attribute("name").Value);
}
Console.WriteLine(result.ToString()); //added this so you could see the output on the console
}
}
And next:
//Dommer's example, using data.xml from OP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
class loadXMLToLINQ
{
static void Main( )
{
XElement rootElement = XElement.Load(@"c:\\data.xml"); //you'll have to edit your path
Console.WriteLine(GetOutline(0, rootElement));
}
static private string GetOutline(int indentLevel, XElement element)
{
StringBuilder result = new StringBuilder();
if (element.Attribute("name") != null)
{
result = result.AppendLine(new string(' ', indentLevel * 2) + element.Attribute("name").Value);
}
foreach (XElement childElement in element.Elements())
{
result.Append(GetOutline(indentLevel + 1, childElement));
}
return result.ToString();
}
}
These both compile & work in VS2010 using csc.exe version 4.0.30319.1 and give the exact same output. Hopefully these help someone else who's looking for working examples of code.
EDIT: added @eglasius' example as well since it became useful to me:
//@eglasius example, still using data.xml from OP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
class loadXMLToLINQ2
{
static void Main( )
{
StringBuilder result = new StringBuilder(); //needed for result below
XDocument xdoc = XDocument.Load(@"c:\\deg\\data.xml"); //you'll have to edit your path
var lv1s = xdoc.Root.Descendants("level1");
var lvs = lv1s.SelectMany(l=>
new string[]{ l.Attribute("name").Value }
.Union(
l.Descendants("level2")
.Select(l2=>" " + l2.Attribute("name").Value)
)
);
foreach (var lv in lvs)
{
result.AppendLine(lv);
}
Console.WriteLine(result);//added this so you could see the result
}
}
You could just use the bound ng-model
(answers[item.questID]
) value itself in your ng-change method to detect if it has been checked or not.
Example:-
<input type="checkbox" ng-model="answers[item.questID]"
ng-change="stateChanged(item.questID)" /> <!-- Pass the specific id -->
and
$scope.stateChanged = function (qId) {
if($scope.answers[qId]){ //If it is checked
alert('test');
}
}
On each of your buttons you could have the following;
<input type="button" name="newWin" onclick="frmSubmitSameWin();">
<input type="button" name="SameWin" onclick="frmSubmitNewWin();">
Then have a few small js functions;
<script type="text/javascript">
function frmSubmitSameWin() {
form.target = '';
form.submit();
}
function frmSubmitNewWin() {
form.target = '_blank';
form.submit();
}
</script>
That should do the trick.
I would have put this in a comment on the accepted answer, since that's where it belongs, but I can't. So, just in case anyone gets unreliable results, this could be why.
Be careful of the accepted answer, it fails if the time_point is before the epoch.
This line of code:
std::size_t fractional_seconds = ms.count() % 1000;
will yield unexpected values if ms.count() is negative (since size_t is not meant to hold negative values).
The full error message sounds:
ERROR 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a key
So add primary key
to the auto_increment
field:
CREATE TABLE book (
id INT AUTO_INCREMENT primary key NOT NULL,
accepted_terms BIT(1) NOT NULL,
accepted_privacy BIT(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
In 2015, if you still getting this confusing error, blame python default setuptools that PIP uses.
pip install -U setuptools
pip install blahblah
It will work fine.
UPDATE: It won't work fine for all libraries. I still get some error with few modules, that require lib-headers. They only thing that work flawlessly is Linux platform
File file = new File("Foo.txt");
try (PrintStream ps = new PrintStream(file)) {
ps.println("Bar");
}
response.setContentType("application/octet-stream");
response.setContentLength((int) file.length());
response.setHeader( "Content-Disposition",
String.format("attachment; filename=\"%s\"", file.getName()));
OutputStream out = response.getOutputStream();
try (FileInputStream in = new FileInputStream(file)) {
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
}
out.flush();
As Thomas says, the cin ignore is a good way. To always wait for user to press enter (even if exit is used), register a function atexit:
#include <iostream>
void pause()
{ ::std::cout<<"\nPress ENTER to exit.";
::std::cin.sync();
if(::std::cin.get()!='\n')
::std::cin.ignore(0xFFFFFFFF,'\n');
}
int main()
{
atexit(pause);
// whatever
return 0;
}
Some googling found this, where people had a discussion about this.
An unsigned char is basically a single byte. So, you would use this if you need one byte of data (for example, maybe you want to use it to set flags on and off to be passed to a function, as is often done in the Windows API).
It's a member initialization list. You should find information about it in any good C++ book.
You should, in most cases, initialize all member objects in the member initialization list (however, do note the exceptions listed at the end of the FAQ entry).
The takeaway point from the FAQ entry is that,
All other things being equal, your code will run faster if you use initialization lists rather than assignment.
You have to export
it from your NgModule
:
@NgModule({
declarations: [TaskCardComponent],
exports: [TaskCardComponent],
imports: [MdCardModule],
providers: []
})
export class TaskModule{}
package myguo;
import javax.swing.*;
public class MyGuo {
JFrame f;
JButton bt1 , bt2 ;
JTextField t1,t2;
JLabel l1,l2;
MyGuo(){
f=new JFrame("LOG IN FORM");
f.setLocation(500,300);
f.setSize(600,500);
f.setLayout(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
l1=new JLabel("NAME");
l1.setBounds(50,70,80,30);
l2=new JLabel("PASSWORD");
l2.setBounds(50,100,80,30);
t1=new JTextField();
t1.setBounds(140, 70, 200,30);
t2=new JTextField();
t2.setBounds(140, 110, 200,30);
bt1 =new JButton("LOG IN");
bt1.setBounds(150,150,80,30);
bt2 =new JButton("CLEAR");
bt2.setBounds(235,150,80,30);
f.add(l1);
f.add(l2);
f.add(t1);
f.add(t2);
f.add(bt1);
f.add(bt2);
f.setVisible(true);
}
public static void main(String[] args) {
MyGuo myGuo = new MyGuo();
}
}
Core of the static keyword that you will have only one copy at RAM of this (method /variable /class ) that's shared for all calling
Remove "SSLv2ClientHello" from the enabled protocols on the client SSLSocket or HttpsURLConnection.
This code returns a 2d array.
#include <cstdio>
// Returns a pointer to a newly created 2d array the array2D has size [height x width]
int** create2DArray(unsigned height, unsigned width)
{
int** array2D = 0;
array2D = new int*[height];
for (int h = 0; h < height; h++)
{
array2D[h] = new int[width];
for (int w = 0; w < width; w++)
{
// fill in some initial values
// (filling in zeros would be more logic, but this is just for the example)
array2D[h][w] = w + width * h;
}
}
return array2D;
}
int main()
{
printf("Creating a 2D array2D\n");
printf("\n");
int height = 15;
int width = 10;
int** my2DArray = create2DArray(height, width);
printf("Array sized [%i,%i] created.\n\n", height, width);
// print contents of the array2D
printf("Array contents: \n");
for (int h = 0; h < height; h++)
{
for (int w = 0; w < width; w++)
{
printf("%i,", my2DArray[h][w]);
}
printf("\n");
}
// important: clean up memory
printf("\n");
printf("Cleaning up memory...\n");
for ( h = 0; h < height; h++)
{
delete [] my2DArray[h];
}
delete [] my2DArray;
my2DArray = 0;
printf("Ready.\n");
return 0;
}
jQuery Version
$(function() {_x000D_
$('#bookmarkme').click(function() {_x000D_
if (window.sidebar && window.sidebar.addPanel) { // Mozilla Firefox Bookmark_x000D_
window.sidebar.addPanel(document.title, window.location.href, '');_x000D_
} else if (window.external && ('AddFavorite' in window.external)) { // IE Favorite_x000D_
window.external.AddFavorite(location.href, document.title);_x000D_
} else if (window.opera && window.print) { // Opera Hotlist_x000D_
this.title = document.title;_x000D_
return true;_x000D_
} else { // webkit - safari/chrome_x000D_
alert('Press ' + (navigator.userAgent.toLowerCase().indexOf('mac') != -1 ? 'Command/Cmd' : 'CTRL') + ' + D to bookmark this page.');_x000D_
}_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<a id="bookmarkme" href="#" rel="sidebar" title="bookmark this page">Bookmark This Page</a>
_x000D_
$image
is in your case the value of the item and not the key. Use the following syntax to get the key too:
foreach ($images as $key => $value) {
/* … */
}
Now you can delete the item with unset($images[$key])
.
Can be seen from UI as well. Go to overview tab on table, you will see item count. Hope it helps someone.