There is an open issue to only print this warning if there was actually something sanitized: https://github.com/angular/angular/pull/10272
I didn't read in detail when this warning is printed when nothing was sanitized.
EBS is simple - block level storage which can be attached to an instance from same AZ, and can survive irrespective of instance life.
However, interesting difference is between EFS and S3, and to identify proper use cases for it.
Cost: EFS is approximately 10 times costly than S3.
Usecases:
It appears that window.webkitNotifications
has already been deprecated and removed. However, there's a new API, and it appears to work in the latest version of Firefox as well.
function notifyMe() {
// Let's check if the browser supports notifications
if (!("Notification" in window)) {
alert("This browser does not support desktop notification");
}
// Let's check if the user is okay to get some notification
else if (Notification.permission === "granted") {
// If it's okay let's create a notification
var notification = new Notification("Hi there!");
}
// Otherwise, we need to ask the user for permission
// Note, Chrome does not implement the permission static property
// So we have to check for NOT 'denied' instead of 'default'
else if (Notification.permission !== 'denied') {
Notification.requestPermission(function (permission) {
// Whatever the user answers, we make sure we store the information
if(!('permission' in Notification)) {
Notification.permission = permission;
}
// If the user is okay, let's create a notification
if (permission === "granted") {
var notification = new Notification("Hi there!");
}
});
} else {
alert(`Permission is ${Notification.permission}`);
}
}
Use a list comprehension.
[x + 2 for x in [1, 2, 3]]
If you really, really, really want to use map
, give it an anonymous function as the first argument:
map(lambda x: x + 2, [1,2,3])
Copied from my answer here: https://stackoverflow.com/a/9368199/485088
Run
ldconfig
as root to update the cache - if that still doesn't help, you need to add the path to the fileld.so.conf
(just type it in on its own line) or better yet, add the entry to a new file (easier to delete) in directoryld.so.conf.d
.
Take a Look.
$(document).ready(function () {
$('#datatable').DataTable({
columns: [
{ 'data': 'ID' },
{ 'data': 'AuthorName' },
{ 'data': 'TotalBook' },
{ 'data': 'DateofBirth' },
{ 'data': 'OccupationEN' },
{ 'data': null, title: 'Action', wrap: true, "render": function (item) { return '<div class="btn-group"> <button type="button" onclick="set_value(' + item.ID + ')" value="0" class="btn btn-warning" data-toggle="modal" data-target="#myModal">View</button></div>' } },
],
bServerSide: true,
sAjaxSource: 'EmployeeDataHandler.ashx'
});
});
It works for me. See this solution - https://alvarotrigo.com/blog/firing-resize-event-only-once-when-resizing-is-finished/
var resizeId;_x000D_
$(window).resize(function() {_x000D_
clearTimeout(resizeId);_x000D_
resizeId = setTimeout(doneResizing, 500);_x000D_
});_x000D_
function doneResizing(){_x000D_
//whatever we want to do _x000D_
}
_x000D_
In Microsoft Windows, you can go through by route -f command to delete your current Gateway, check route / ? for more advance option, like add / delete etc and also can write a batch to add route on specific time as well but if you need to delete IP cache, then you have the option to use arp command.
Eg:
Datatable newTable = new DataTable();
foreach(string s1 in list)
{
if (s1 != string.Empty) {
dvProducts.RowFilter = "(CODE like '" + serachText + "*') AND (CODE <> '" + s1 + "')";
foreach(DataRow dr in dvProducts.ToTable().Rows)
{
newTable.ImportRow(dr);
}
}
}
ListView1.DataSource = newTable;
ListView1.DataBind();
Executing Linq queries can generate extra threads. When I try to execute code that uses Linq query collection in the immediate window it often refuses to run because not enough threads are available to the debugger.
As others have said, for threads to exit when they are finished is perfectly normal.
I have found that using jQuery the best solution is
$(this.form).submit()
Using this statement jquery plugins (e.g. jquery form plugin) works correctly and jquery DOM traversing overhead is minimized.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Email Validation</h2>
<input id="textEmail">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo" style="color: red;"></p>
<script>
function myFunction() {
var email;
email = document.getElementById("textEmail").value;
var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(textEmail.value) == false)
{
document.getElementById("demo").style.color = "red";
document.getElementById("demo").innerHTML ="Invalid EMail ->"+ email;
alert('Invalid Email Address ->'+email);
return false;
} else{
document.getElementById("demo").style.color = "DarkGreen";
document.getElementById("demo").innerHTML ="Valid Email ->"+email;
}
return true;
}
</script>
</body>
</html>
df['year_month']=df.datetime_column.apply(lambda x: str(x)[:7])
This worked fine for me, didn't think pandas would interpret the resultant string date as date, but when i did the plot, it knew very well my agenda and the string year_month where ordered properly... gotta love pandas!
To mark as obsolete with a warning:
[Obsolete]
private static void SomeMethod()
You get a warning when you use it:
And with IntelliSense:
If you want a message:
[Obsolete("My message")]
private static void SomeMethod()
Here's the IntelliSense tool tip:
Finally if you want the usage to be flagged as an error:
[Obsolete("My message", true)]
private static void SomeMethod()
When used this is what you get:
Note: Use the message to tell people what they should use instead, not why it is obsolete.
in jquery ajax functions, the success callback signature is:
function (data, textStatus) {
// data could be xmlDoc, jsonObj, html, text, etc...
this; // the options for this ajax request
}
depending on the data type you've asked, using the 'dataType' parameter, you'll get the 'data' argument.
from the docs:
dataType (String) Default: Intelligent Guess (xml or html). The type of data that you're expecting back from the server. If none is specified, jQuery will intelligently pass either responseXML or responseText to your success callback, based on the MIME type of the response.
The available types (and the result passed as the first argument to your success callback) are:
"xml": Returns a XML document that can be processed via jQuery.
"html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
"script": Evaluates the response as JavaScript and returns it as plain text. Disables caching unless option "cache" is used. Note: This will turn POSTs into GETs for remote-domain requests.
"json": Evaluates the response as JSON and returns a JavaScript Object.
"jsonp": Loads in a JSON block using JSONP. Will add an extra "?callback=?" to the end of your URL to specify the callback. (Added in jQuery 1.2)
"text": A plain text string.
On the basic example of Flutter you can set with backgroundColor: Colors.X
of Scaffold
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
backgroundColor: Colors.blue,
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add_circle),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
With Font Awesome you can easily use stacked icons like this:
<span class="fa-stack fa-2x">
<i class="fas fa-circle-thin fa-stack-2x"></i>
<i class="fas fa-lock fa-stack-1x fa-inverse"></i>
</span>
refer Font Awesome Stacked Icons
Update:- Fiddle for stacked icons
Simple ruby script based on this answer: registry_cleaner.
You can run it on local machine:
./registry_cleaner.rb --host=https://registry.exmpl.com --repository=name --tags_count=4
And then on the registry machine remove blobs with /bin/registry garbage-collect /etc/docker/registry/config.yml
.
Try this:
import os
root_name = next(os.walk("."))[0]
dir_names = next(os.walk("."))[1]
file_names = next(os.walk("."))[2]
Here I'm assuming your path as "." in which the root_file and other directories are there. So, Basically we are just iterating throughout the tree by using next() call, as our os.walk is only generative function. By doing this we can save all the Directory and file names in dir_names and file_names respectively.
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = view.bounds;
gradient.colors = @[(id)[UIColor whiteColor].CGColor, (id)[UIColor blackColor].CGColor];
[view.layer insertSublayer:gradient atIndex:0];
let view = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 50))
let gradient = CAGradientLayer()
gradient.frame = view.bounds
gradient.colors = [UIColor.white.cgColor, UIColor.black.cgColor]
view.layer.insertSublayer(gradient, at: 0)
Info: use startPoint and endPoint to change direction of gradient.
If there are any other views added onto this UIView
(such as a UILabel
), you may want to consider setting the background color of those UIView
’s to [UIColor clearColor]
so the gradient view is presented instead of the background color for sub views. Using clearColor
has a slight performance hit.
Just been doing that myself today... here is code I have working for me...
$data = array("a" => $a);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
$response = curl_exec($ch);
if (!$response)
{
return false;
}
src: http://www.lornajane.net/posts/2009/putting-data-fields-with-php-curl
You can also use org.apache.commons.lang.ArrayUtils.isEquals()
Name.objects.filter(alias__gt='',alias__isnull=False)
Yes it's possible to avoid options request. Options request is a preflight request when you send (post) any data to another domain. It's a browser security issue. But we can use another technology: iframe transport layer. I strongly recommend you forget about any CORS configuration and use readymade solution and it will work anywhere.
Take a look here: https://github.com/jpillora/xdomain
And working example: http://jpillora.com/xdomain/
I based this solution on the comments of @jberger.
if git checkout master &&
git fetch origin master &&
[ `git rev-list HEAD...origin/master --count` != 0 ] &&
git merge origin/master
then
echo 'Updated!'
else
echo 'Not updated.'
fi
I forget where I first saw it mentioned but you can actually embed your labels in a container elsewhere as long as you have the for=
attribute set. So, let's check out a sample on SO:
* {_x000D_
padding: 0;_x000D_
margin: 0;_x000D_
background-color: #262626;_x000D_
color: white;_x000D_
}_x000D_
_x000D_
.radio-button {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
#filter {_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
}_x000D_
_x000D_
.filter-label {_x000D_
display: inline-block;_x000D_
border: 4px solid green;_x000D_
padding: 10px 20px;_x000D_
font-size: 1.4em;_x000D_
text-align: center;_x000D_
cursor: pointer;_x000D_
}_x000D_
_x000D_
main {_x000D_
clear: left;_x000D_
}_x000D_
_x000D_
.content {_x000D_
padding: 3% 10%;_x000D_
display: none;_x000D_
}_x000D_
_x000D_
h1 {_x000D_
font-size: 2em;_x000D_
}_x000D_
_x000D_
.date {_x000D_
padding: 5px 30px;_x000D_
font-style: italic;_x000D_
}_x000D_
_x000D_
.filter-label:hover {_x000D_
background-color: #505050;_x000D_
}_x000D_
_x000D_
#featured-radio:checked~#filter .featured,_x000D_
#personal-radio:checked~#filter .personal,_x000D_
#tech-radio:checked~#filter .tech {_x000D_
background-color: green;_x000D_
}_x000D_
_x000D_
#featured-radio:checked~main .featured {_x000D_
display: block;_x000D_
}_x000D_
_x000D_
#personal-radio:checked~main .personal {_x000D_
display: block;_x000D_
}_x000D_
_x000D_
#tech-radio:checked~main .tech {_x000D_
display: block;_x000D_
}
_x000D_
<input type="radio" id="featured-radio" class="radio-button" name="content-filter" checked="checked">_x000D_
<input type="radio" id="personal-radio" class="radio-button" name="content-filter" value="Personal">_x000D_
<input type="radio" id="tech-radio" class="radio-button" name="content-filter" value="Tech">_x000D_
_x000D_
<header id="filter">_x000D_
<label for="featured-radio" class="filter-label featured" id="feature-label">Featured</label>_x000D_
<label for="personal-radio" class="filter-label personal" id="personal-label">Personal</label>_x000D_
<label for="tech-radio" class="filter-label tech" id="tech-label">Tech</label>_x000D_
</header>_x000D_
_x000D_
<main>_x000D_
<article class="content featured tech">_x000D_
<header>_x000D_
<h1>Cool Stuff</h1>_x000D_
<h3 class="date">Today</h3>_x000D_
</header>_x000D_
_x000D_
<p>_x000D_
I'm showing cool stuff in this article!_x000D_
</p>_x000D_
</article>_x000D_
_x000D_
<article class="content personal">_x000D_
<header>_x000D_
<h1>Not As Cool</h1>_x000D_
<h3 class="date">Tuesday</h3>_x000D_
</header>_x000D_
_x000D_
<p>_x000D_
This stuff isn't nearly as cool for some reason :(;_x000D_
</p>_x000D_
</article>_x000D_
_x000D_
<article class="content tech">_x000D_
<header>_x000D_
<h1>Cool Tech Article</h1>_x000D_
<h3 class="date">Last Monday</h3>_x000D_
</header>_x000D_
_x000D_
<p>_x000D_
This article has awesome stuff all over it!_x000D_
</p>_x000D_
</article>_x000D_
_x000D_
<article class="content featured personal">_x000D_
<header>_x000D_
<h1>Cool Personal Article</h1>_x000D_
<h3 class="date">Two Fridays Ago</h3>_x000D_
</header>_x000D_
_x000D_
<p>_x000D_
This article talks about how I got a job at a cool startup because I rock!_x000D_
</p>_x000D_
</article>_x000D_
</main>
_x000D_
Whew. That was a lot for a "sample" but I feel it really drives home the effect and point: we can certainly select a label for a checked input control without it being a sibling. The secret lies in keeping the input
tags a child to only what they need to be (in this case - only the body
element).
Since the label
element doesn't actually utilize the :checked
pseudo selector, it doesn't matter that the labels are stored in the header
. It does have the added benefit that since the header
is a sibling element we can use the ~
generic sibling selector to move from the input[type=radio]:checked
DOM element to the header
container and then use descendant/child selectors to access the label
s themselves, allowing the ability to style them when their respective radio boxes/checkboxes are selected.
Not only can we style the labels, but also style other content that may be descendants of a sibling container relative to all of the input
s. And now for the moment you've all been waiting for, the JSFIDDLE! Go there, play with it, make it work for you, find out why it works, break it, do what you do!
Hopefully that all makes sense and fully answers the question and possibly any follow ups that may crop up.
you can create a List[] and initialize them by for loop. it compiles without errors:
List<e>[] l;
for(int i = 0; i < l.length; i++){
l[i] = new ArrayList<e>();
}
it works with arrayList[] l as well.
Since there are so many ways to solve this, let's start by defining what we want to see in our solution.
readarray
for this purpose. Let's use it.IFS
, looping, using eval
, or adding an extra element then removing it.The readarray
command is easiest to use with newlines as the delimiter. With other delimiters it may add an extra element to the array. The cleanest approach is to first adapt our input into a form that works nicely with readarray
before passing it in.
The input in this example does not have a multicharacter delimiter. If we apply a little common sense, it's best understood as comma separated input for which each element may need to be trimmed. My solution is to split the input by comma into multiple lines, trim each element, and pass it all to readarray
.
string=' Paris,France , All of Europe '
readarray -t foo < <(tr ',' '\n' <<< "$string" |sed 's/^ *//' |sed 's/ *$//')
declare -p foo
# declare -a foo='([0]="Paris" [1]="France" [2]="All of Europe")'
I think it should be the case. To erase the character, you should use replace(".", "")
instead.
More permanent solution would be to fill the missing values, in the output shown by command: locale
Output from locale
is:
$ locale
LANG=en_US.utf8
LANGUAGE=
LC_CTYPE="en_US.utf8"
LC_NUMERIC=es_ES.utf8
LC_TIME=es_ES.utf8
LC_COLLATE="en_US.utf8"
LC_MONETARY=es_ES.utf8
LC_MESSAGES="en_US.utf8"
LC_PAPER=es_ES.utf8
LC_NAME="en_US.utf8"
LC_ADDRESS="en_US.utf8"
LC_TELEPHONE="en_US.utf8"
LC_MEASUREMENT=es_ES.utf8
LC_IDENTIFICATION="en_US.utf8"
LC_ALL=
To Fill the missing values edit ~/.bashrc :
$ vim ~/.bashrc
Add the following lines after the above command (suppose you want en_US.UTF-8 to be your language):
export LANGUAGE="en_US.UTF-8"
export LC_ALL="en_US.UTF-8"
If this file is ReadOnly you would be needing to follow the steps mentioned by The GeekyBoy. The answer given by Dr Beco in Superuser has details relating to saving readonly files.
After saving the file do:
$ source ~/.bashrc
Now you wont be facing the same problem anymore.
Use console.log
to add debugging information to your page.
Many people use alert(hasNinjas)
for this purpose but console.log(hasNinjas)
is easier to work with. Using an alert pop-ups up a modal dialog box that blocks the user interface.
Edit: I agree with Baptiste Pernet and Jan Hancic that it is a very good idea to check if window.console
is defined first so that your code doesn't break if there is no console available.
More esoteric ways:
Rails.cache.delete_matched("*")
For Redis:
Redis.new.keys.each{ |key| Rails.cache.delete(key) }
Try using this this work for me
select * from `table_name` ORDER BY STR_TO_DATE(start_date,"%d-%m-%Y") ASC
where start_date is the field name
From what you've said so far, it sounds like a problem where the MySQL driver in PHP5.3 has trouble connecting to the older MySQL version 4.1. Have a look on http://www.bitshop.com/Blogs/tabid/95/EntryId/67/PHP-mysqlnd-cannot-connect-to-MySQL-4-1-using-old-authentication.aspx
There's a similar question here with some useful answers, Cannot connect to MySQL 4.1+ using old authentication
SELECT `User`, `Host`, Length(`Password`) FROM mysql.user
This will return 16 for accounts with old passwords and 41 for accounts with new passwords (and 0 for accounts with no password at all, you might want to take care of those as well). Either use the user managements tools of the MySQL front end (if there are any) or
SET PASSWORD FOR 'User'@'Host'=PASSWORD('yourpassword');
FLUSH Privileges
$http
service returns a promise
which has two callback methods as shown below.
$http({method: 'GET', url: '/someUrl'}).
success(function(data, status, headers, config) {
var anchor = angular.element('<a/>');
anchor.attr({
href: 'data:attachment/csv;charset=utf-8,' + encodeURI(data),
target: '_blank',
download: 'filename.csv'
})[0].click();
}).
error(function(data, status, headers, config) {
// handle error
});
Messagebox is for windows only. You have to use Javascript
Alert('dd');
In case anyone else is using EPPlus. This implementation is pretty naive, but there are comments that draw attention to such. If you were to layer one more method GetWorkbookAsDataSet()
on top it would do what the OP is asking for.
/// <summary>
/// Assumption: Worksheet is in table format with no weird padding or blank column headers.
///
/// Assertion: Duplicate column names will be aliased by appending a sequence number (eg. Column, Column1, Column2)
/// </summary>
/// <param name="worksheet"></param>
/// <returns></returns>
public static DataTable GetWorksheetAsDataTable(ExcelWorksheet worksheet)
{
var dt = new DataTable(worksheet.Name);
dt.Columns.AddRange(GetDataColumns(worksheet).ToArray());
var headerOffset = 1; //have to skip header row
var width = dt.Columns.Count;
var depth = GetTableDepth(worksheet, headerOffset);
for (var i = 1; i <= depth; i++)
{
var row = dt.NewRow();
for (var j = 1; j <= width; j++)
{
var currentValue = worksheet.Cells[i + headerOffset, j].Value;
//have to decrement b/c excel is 1 based and datatable is 0 based.
row[j - 1] = currentValue == null ? null : currentValue.ToString();
}
dt.Rows.Add(row);
}
return dt;
}
/// <summary>
/// Assumption: There are no null or empty cells in the first column
/// </summary>
/// <param name="worksheet"></param>
/// <returns></returns>
private static int GetTableDepth(ExcelWorksheet worksheet, int headerOffset)
{
var i = 1;
var j = 1;
var cellValue = worksheet.Cells[i + headerOffset, j].Value;
while (cellValue != null)
{
i++;
cellValue = worksheet.Cells[i + headerOffset, j].Value;
}
return i - 1; //subtract one because we're going from rownumber (1 based) to depth (0 based)
}
private static IEnumerable<DataColumn> GetDataColumns(ExcelWorksheet worksheet)
{
return GatherColumnNames(worksheet).Select(x => new DataColumn(x));
}
private static IEnumerable<string> GatherColumnNames(ExcelWorksheet worksheet)
{
var columns = new List<string>();
var i = 1;
var j = 1;
var columnName = worksheet.Cells[i, j].Value;
while (columnName != null)
{
columns.Add(GetUniqueColumnName(columns, columnName.ToString()));
j++;
columnName = worksheet.Cells[i, j].Value;
}
return columns;
}
private static string GetUniqueColumnName(IEnumerable<string> columnNames, string columnName)
{
var colName = columnName;
var i = 1;
while (columnNames.Contains(colName))
{
colName = columnName + i.ToString();
i++;
}
return colName;
}
Here is the documentation of the modifiers supported by strftime()
in the GNU C library. (Like people said before, it might not be portable.) Of interest to you might be:
%e
instead of %d
will replace leading zero in day of month with a spaceIt works on my Python (on Linux). I don't know if it will work on yours.
Step 1
Go to Help --->
Install New Software...
Step 2 Try to find "http://download.eclipse.org/webtools/updates" under work with drop down. If you find then select and install all the available updates.
If you can not find then click on Add -> Add Repository. Name: Eclipse Webtools Location: http://download.eclipse.org/webtools/updates Select all available updates and Install them.
Visit http://download.eclipse.org/webtools/updates/ for more details.
One of the simplest ways to do this is like this
var totalWords = "my name is rahul.";_x000D_
var firstWord = totalWords.replace(/ .*/, '');_x000D_
alert(firstWord);_x000D_
console.log(firstWord);
_x000D_
You can avoid the loop and cut etc by using:
awk -F ':' '{system("ping " $1);}' config.txt
However it would be better if you post a snippet of your config.txt
I don't think you can do it in one line of code. Try opening your activities with startActivityForResult. As the result you can pass something like a CLOSE_FLAG, which will inform your parent activity that its child activity has finished.
That said, you should probably read this answer.
You don't need the class reference for the li
s. Instead of having CSS like
li.top-level-nav { color:black; }
you can write
ul#sidebar > li { color:black; }
This will apply the styling only to li
s that immediately descend from the sidebar ul
.
Reminder to self... fetch first, else the repository has not local hash (I guess).
step 1. Setup the upstream remote and above^
diffing a single file follows this pattern :
git diff localBranch uptreamBranch --spacepath/singlefile
git diff master upstream/nameofrepo -- src/index.js
RecordCount is what you want to use.
If Not temp_rst1.RecordCount > 0 ...
If you want this type of code to run in IE11 (which does not support much of ES6 at all), then you need to get a 3rd party promise library (like Bluebird), include that library and change your coding to use ES5 coding structures (no arrow functions, no let
, etc...) so you can live within the limits of what older browsers support.
Or, you can use a transpiler (like Babel) to convert your ES6 code to ES5 code that will work in older browsers.
Here's a version of your code written in ES5 syntax with the Bluebird promise library:
<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.3.4/bluebird.min.js"></script>
<script>
'use strict';
var promise = new Promise(function(resolve) {
setTimeout(function() {
resolve("result");
}, 1000);
});
promise.then(function(result) {
alert("Fulfilled: " + result);
}, function(error) {
alert("Rejected: " + error);
});
</script>
If you want to access event object as well as data passed, you have to pass event
and ticket.id
both as parameters, like following:
HTML
<input type="number" v-on:input="addToCart($event, ticket.id)" min="0" placeholder="0">
Javascript
methods: {
addToCart: function (event, id) {
// use event here as well as id
console.log('In addToCart')
console.log(id)
}
}
See working fiddle: https://jsfiddle.net/nee5nszL/
In case you are using vue-router, you may have to use $event in your v-on:input
method like following:
<input type="number" v-on:input="addToCart($event, num)" min="0" placeholder="0">
Here is working fiddle.
You can do it using javascript. Grab the value of the form field in your submit function, parse out the extension.
You can start with something like this:
<form name="someform"enctype="multipart/form-data" action="uploader.php" method="POST">
<input type=file name="file1" />
<input type=button onclick="val()" value="xxxx" />
</form>
<script>
function val() {
alert(document.someform.file1.value)
}
</script>
I agree with alexmac - do it server-side as well.
I'd create the array and then append the object literals to it.
var myColumnDefs = [];
for ( var i=0 ; i < oFullResponse.results.length; i++) {
console.log(oFullResponse.results[i].label);
myColumnDefs[myColumnDefs.length] = {key:oFullResponse.results[i].label, sortable:true, resizeable:true};
}
I think you want to use
mysql_fetch_assoc($query)
rather than
mysql_fetch_row($query)
The latter returns an normal array index by integers, whereas the former returns an associative array, index by the field names.
Try changing server name to "localhost"
pymssql.connect(server="localhost", user="myusername", password="mypwd", database="temp",port="1433")
Using the HttpClientBuilder
in HttpClient 4.5.x with a custom HttpClientConnectionManager
with the defaults of HttpClientBuilder
:
SSLConnectionSocketFactory sslConnectionSocketFactory =
new SSLConnectionSocketFactory(SSLContexts.createDefault(),
new String[] { "TLSv1.2" },
null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
PoolingHttpClientConnectionManager poolingHttpClientConnectionManager =
new PoolingHttpClientConnectionManager(
RegistryBuilder.<ConnectionSocketFactory> create()
.register("http",
PlainConnectionSocketFactory.getSocketFactory())
.register("https",
sslConnectionSocketFactory)
.build());
// Customize the connection pool
CloseableHttpClient httpClient = HttpClientBuilder.create()
.setConnectionManager(poolingHttpClientConnectionManager)
.build()
Without a custom HttpClientConnectionManager
:
SSLConnectionSocketFactory sslConnectionSocketFactory =
new SSLConnectionSocketFactory(SSLContexts.createDefault(),
new String[] { "TLSv1.2" },
null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
CloseableHttpClient httpClient = HttpClientBuilder.create()
.setSSLSocketFactory(sslConnectionSocketFactory)
.build()
In Controller
$hostname = $_ENV['IMAP_HOSTNAME_TEST']; (or) $hostname = env('IMAP_HOSTNAME_TEST');
In blade.view
{{$_ENV['IMAP_HOSTNAME_TEST']}}
You should be on you local machine to try the above scp command.
On your local machine try:
scp -i ~/Downloads/myAmazonKey.pem ~/Downloads/phpMyAdmin-3.4.5-all-languages.tar.gz [email protected]:~/.
Go to the DBMS Output window (View->DBMS Output).
You can try "ours" option in git merge,
git merge branch -X ours
This option forces conflicting hunks to be auto-resolved cleanly by favoring our version. Changes from the other tree that do not conflict with our side are reflected to the merge result. For a binary file, the entire contents are taken from our side.
This is my powershell newbie way of doing this
if ((Test-Path ".\Desktop\checkfile.txt") -ne "True") {
Write-Host "Damn it"
} else {
Write-Host "Yay"
}
If you want to set the whole new column to an initial base value (e.g. None
), you can do this: df1['e'] = None
This actually would assign "object" type to the cell. So later you're free to put complex data types, like list, into individual cells.
As of 10/22/2019, I think the best answer is simply
conda install opencv
It appears opencv
is now in the main Anaconda
channel.
To see which packages (including opencv
) are in the main Anaconda
channel go to Anaconda Package Lists and follow the link corresponding to your python version and os version.
if you have async dom changes, this function checks (with time limit in seconds) for the DOM elements, it will not be heavy for the DOM and its Promise based :)
function getElement(selector, i = 5) {
return new Promise(async (resolve, reject) => {
if(i <= 0) return reject(`${selector} not found`);
const elements = document.querySelectorAll(selector);
if(elements.length) return resolve(elements);
return setTimeout(async () => await getElement(selector, i-1), 1000);
})
}
// Now call it with your selector
try {
element = await getElement('.woohoo');
} catch(e) { // catch the e }
//OR
getElement('.woohoo', 5)
.then(element => { // do somthing with the elements })
.catch(e => { // catch the error });
One option is to put the subquery in a LEFT JOIN
:
select sum ( t.graduates ) - t1.summedGraduates
from table as t
left join
(
select sum ( graduates ) summedGraduates, id
from table
where group_code not in ('total', 'others' )
group by id
) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates
Perhaps a better option would be to use SUM
with CASE
:
select sum(case when group_code = 'total' then graduates end) -
sum(case when group_code not in ('total','others') then graduates end)
from yourtable
The difference between getHeight()
and getMeasuredHeight()
is that first method will return actual height of the View
, the second one will return summary height of View
's children. In ohter words, getHeight()
returns view height, getMeasuredHeight()
returns height which this view needs to show all it's elements
You're not looping over the items. Try this instead:
$.getJSON(url, function(data){
$.each(data.response.venue.tips.groups.items, function (index, value) {
console.log(this.text);
});
});
If you are restoring the folder don't forget to chown the files to mysql:mysql chown -R mysql:mysql /var/lib/mysql-data
otherwise you will get errors when trying to drop a database or add new column etc..
and restart MySQL
service mysql restart
Storyboard Segues are not to be created outside of the storyboard. You will need to wire it up, despite the drawbacks.
UIStoryboardSegue Reference clearly states:
You do not create segue objects directly. Instead, the storyboard runtime creates them when it must perform a segue between two view controllers. You can still initiate a segue programmatically using the performSegueWithIdentifier:sender: method of UIViewController if you want. You might do so to initiate a segue from a source that was added programmatically and therefore not available in Interface Builder.
You can still programmatically tell the storyboard to present a view controller using a segue using presentModalViewController:
or pushViewController:animated:
calls, but you'll need a storyboard instance.
You can call UIStoryboard
s class method to get a named storyboard with bundle nil for the main bundle.
storyboardWithName:bundle:
Assuming SQL Server 2000, the following StackOverflow question should address your problem.
If using SQL Server 2005/2008, you can use the following code (taken from here):
select cast(replace(cast(myntext as nvarchar(max)),'find','replace') as ntext)
from myntexttable
You can check out this post on SuperUser.
Word starts page numbering over for each new section by default.
I do it slightly differently than the post above that goes through the ribbon menus, but in both methods you have to go through the document to each section's beginning.
My method:
Format Page Numbers
Continue from Previous Section
radio button under Page numbering
I find this right-click method to be a little faster. Also, usually if I insert the page numbers first before I start making any new sections, this problem doesn't happen in the first place.
The function STR_TO_DATE(COLUMN, '%input_format') can do it, you only have to specify the input format. Example : to convert p052011
SELECT STR_TO_DATE('p052011','p%m%Y') FROM your_table;
The result : 2011-05-00
Matt Zeunert's version with use arraw function (ES6)
const nums = a.split(',').map(x => parseInt(x, 10));
Try using the -Force
parameter on Remove-Item
.
Try this
if($("input:radio[name=postage]").is(":checked")){
//Code to append goes here
}
It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:
openssl sha1 [put the full path to the file here without brackets]
For example:
openssl sha1 /Users/me/Desktop/myFile.dmg
If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.
I have two demos, one with jQuery
and one without. Neither use date functions and are about as simple as it gets.
function startTimer(duration, display) {_x000D_
var timer = duration, minutes, seconds;_x000D_
setInterval(function () {_x000D_
minutes = parseInt(timer / 60, 10);_x000D_
seconds = parseInt(timer % 60, 10);_x000D_
_x000D_
minutes = minutes < 10 ? "0" + minutes : minutes;_x000D_
seconds = seconds < 10 ? "0" + seconds : seconds;_x000D_
_x000D_
display.textContent = minutes + ":" + seconds;_x000D_
_x000D_
if (--timer < 0) {_x000D_
timer = duration;_x000D_
}_x000D_
}, 1000);_x000D_
}_x000D_
_x000D_
window.onload = function () {_x000D_
var fiveMinutes = 60 * 5,_x000D_
display = document.querySelector('#time');_x000D_
startTimer(fiveMinutes, display);_x000D_
};
_x000D_
<body>_x000D_
<div>Registration closes in <span id="time">05:00</span> minutes!</div>_x000D_
</body>
_x000D_
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.text(minutes + ":" + seconds);
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
jQuery(function ($) {
var fiveMinutes = 60 * 5,
display = $('#time');
startTimer(fiveMinutes, display);
});
However if you want a more accurate timer that is only slightly more complicated:
function startTimer(duration, display) {_x000D_
var start = Date.now(),_x000D_
diff,_x000D_
minutes,_x000D_
seconds;_x000D_
function timer() {_x000D_
// get the number of seconds that have elapsed since _x000D_
// startTimer() was called_x000D_
diff = duration - (((Date.now() - start) / 1000) | 0);_x000D_
_x000D_
// does the same job as parseInt truncates the float_x000D_
minutes = (diff / 60) | 0;_x000D_
seconds = (diff % 60) | 0;_x000D_
_x000D_
minutes = minutes < 10 ? "0" + minutes : minutes;_x000D_
seconds = seconds < 10 ? "0" + seconds : seconds;_x000D_
_x000D_
display.textContent = minutes + ":" + seconds; _x000D_
_x000D_
if (diff <= 0) {_x000D_
// add one second so that the count down starts at the full duration_x000D_
// example 05:00 not 04:59_x000D_
start = Date.now() + 1000;_x000D_
}_x000D_
};_x000D_
// we don't want to wait a full second before the timer starts_x000D_
timer();_x000D_
setInterval(timer, 1000);_x000D_
}_x000D_
_x000D_
window.onload = function () {_x000D_
var fiveMinutes = 60 * 5,_x000D_
display = document.querySelector('#time');_x000D_
startTimer(fiveMinutes, display);_x000D_
};
_x000D_
<body>_x000D_
<div>Registration closes in <span id="time"></span> minutes!</div>_x000D_
</body>
_x000D_
Now that we have made a few pretty simple timers we can start to think about re-usability and separating concerns. We can do this by asking "what should a count down timer do?"
So with these things in mind lets write a better (but still very simple) CountDownTimer
function CountDownTimer(duration, granularity) {
this.duration = duration;
this.granularity = granularity || 1000;
this.tickFtns = [];
this.running = false;
}
CountDownTimer.prototype.start = function() {
if (this.running) {
return;
}
this.running = true;
var start = Date.now(),
that = this,
diff, obj;
(function timer() {
diff = that.duration - (((Date.now() - start) / 1000) | 0);
if (diff > 0) {
setTimeout(timer, that.granularity);
} else {
diff = 0;
that.running = false;
}
obj = CountDownTimer.parse(diff);
that.tickFtns.forEach(function(ftn) {
ftn.call(this, obj.minutes, obj.seconds);
}, that);
}());
};
CountDownTimer.prototype.onTick = function(ftn) {
if (typeof ftn === 'function') {
this.tickFtns.push(ftn);
}
return this;
};
CountDownTimer.prototype.expired = function() {
return !this.running;
};
CountDownTimer.parse = function(seconds) {
return {
'minutes': (seconds / 60) | 0,
'seconds': (seconds % 60) | 0
};
};
So why is this implementation better than the others? Here are some examples of what you can do with it. Note that all but the first example can't be achieved by the startTimer
functions.
An example that displays the time in XX:XX format and restarts after reaching 00:00
An example that displays the time in two different formats
An example that has two different timers and only one restarts
An example that starts the count down timer when a button is pressed
In my case it was a table with an ENUM that accepts the days of the week as integers (0 to 6). When inserting the value 0 as an integer I got the error message "Data truncated for column ..." so to fix it I had to cast the integer to a string. So instead of:
$item->day = 0;
I had to do;
$item->day = (string) 0;
It looks silly to cast the zero like that but in my case it was in a Laravel factory, and I had to write it like this:
$factory->define(App\Schedule::class, function (Faker $faker) {
return [
'day' => (string) $faker->numberBetween(0, 6),
//
];
});
For print session data you do not need to use print_r() function every time .
If you use it then it will be non-readable format.Data will be looks very dirty.
But if you use my function all you have to do is to use p()-Funtion and pass data into it. //create new file into application/cms_helper.php and load helper cms into //autoload or on controller
/*Copy Code for p function from here and paste into cms_helper.php in application/helpers folder */
//@parram $data-array,$d-if true then die by default it is false
//@author Your name
function p($data,$d = false){
echo "<pre>";
print_r($data);
echo "</pre>";
if($d == TRUE){
die();
}
}
Just remember to load cms_helper into your project or controller using $this->load->helper('cms'); use bellow code into your controller or model it will works just GREAT.
p($this->session->all_userdata()); // it will apply pre to your sesison data and other array as well
This should work in most versions of PHP 4+. Array map using anonymous functions is not supported below 5.3.
Also the foreach examples will throw a warning when using strict PHP error handling.
Here is a small multi-dimensional key renaming function. It can also be used to process arrays to have the correct keys for integrity throughout your app. It will not throw any errors when a key does not exist.
function multi_rename_key(&$array, $old_keys, $new_keys)
{
if(!is_array($array)){
($array=="") ? $array=array() : false;
return $array;
}
foreach($array as &$arr){
if (is_array($old_keys))
{
foreach($new_keys as $k => $new_key)
{
(isset($old_keys[$k])) ? true : $old_keys[$k]=NULL;
$arr[$new_key] = (isset($arr[$old_keys[$k]]) ? $arr[$old_keys[$k]] : null);
unset($arr[$old_keys[$k]]);
}
}else{
$arr[$new_keys] = (isset($arr[$old_keys]) ? $arr[$old_keys] : null);
unset($arr[$old_keys]);
}
}
return $array;
}
Usage is simple. You can either change a single key like in your example:
multi_rename_key($tags, "url", "value");
or a more complex multikey
multi_rename_key($tags, array("url","name"), array("value","title"));
It uses similar syntax as preg_replace() where the amount of $old_keys and $new_keys should be the same. However when they are not a blank key is added. This means you can use it to add a sort if schema to your array.
Use this all the time, hope it helps!
To enable USB Debugging first you need to enable Developer Options.
Open Zenfone Settings and scroll down and tap About.
Scroll down and select Software Information.
Under Software information you will see Build Number.
Tap Build Number 7 times to enable Developer Options.
Come back to Settings and scroll down to find Developer Options.
Tap on Developer Options and it will open upto give you option to enable USB Debugging
This works for me try it out
int main(){
char c;
scanf(" %c",&c);
printf("%c",c);
return 0;
}
Resolve is also more straightforward
from django.urls import resolve
resolve('edit_project', project_id=4)
My similar issue was caused by having special characters (e.g. periods) in the selector.
The fix was to escape the special characters:
$("#dots\\.er\\.bad").val("mmmk");
IMO this is the cleanest and easiest solution:
$("#first").animate({height: $("#first").get(0).scrollHeight}, 1000 );
Explanation: The DOM already knows from its initial rendering what size the expanded div will have when set to auto height. This property is stored in the DOM node as scrollHeight
. We just have to fetch the DOM Element from the jQuery Element by calling get(0)
and then we can access the property.
Adding a callback function to set the height to auto allows for greater responsiveness once the animation is complete (credit chris-williams):
$('#first').animate({
height: $('#first').get(0).scrollHeight
}, 1000, function(){
$(this).height('auto');
});
If you are using angular-cli, there is yet another option:
Angular CLI provides environment files in src/environments
(default ones are environment.ts
(dev) and environment.prod.ts
(production)).
Note that you need to provide the config parameters in all environment.*
files, e.g.,
environment.ts:
export const environment = {
production: false,
apiEndpoint: 'http://localhost:8000/api/v1'
};
environment.prod.ts:
export const environment = {
production: true,
apiEndpoint: '__your_production_server__'
};
and use them in your service (the correct environment file is chosen automatically):
api.service.ts
// ... other imports
import { environment } from '../../environments/environment';
@Injectable()
export class ApiService {
public apiRequest(): Observable<MyObject[]> {
const path = environment.apiEndpoint + `/objects`;
// ...
}
// ...
}
Read more on application environments on Github (Angular CLI version 6) or in the official Angular guide (version 7).
From PowerShell you can use the .NET [System.Environment]::SetEnvironmentVariable()
method:
To remove a user environment variable named FOO
:
[Environment]::SetEnvironmentVariable('FOO', $null, 'User')
Note that $null
is used to better signal the intent to remove the variable, though technically it is effectively the same as passing ''
in this case.
To remove a system (machine-level) environment variable named FOO
- requires elevation (must be run as administrator):
[Environment]::SetEnvironmentVariable('FOO', $null, 'Machine')
Aside from faster execution, the advantage over the reg.exe
-based method is that other applications are notified of the change, via a WM_SETTINGCHANGE
message (though not all applications listen to that message).
git filter-branch
is the major-surgery tool.
git filter-branch --parent-filter true -- @^!
--parent-filter
gets the parents on stdin and should print the rewritten parents on stdout; unix true
exits successfully and prints nothing, so: no parents. @^!
is Git shorthand for "the head commit but not any of its parents". Then delete all the other refs and push at leisure.
For this particular case it's better to do a = None
instead of del a
. This will decrement reference count to object a
was (if any) assigned to and won't fail when a
is not defined. Note, that del
statement doesn't call destructor of an object directly, but unbind it from variable. Destructor of object is called when reference count became zero.
A little bit off topic maybe, but for modern browsers (IE9 and newer) you can use the css odd/even selectors to achieve want you want.
tr:nth-child(even) { /* your alt-row stuff */}
tr:nth-child(odd) { /* the other rows */ }
or
tr { /* all table rows */ }
tr:nth-child(even) { /* your alt-row stuff */}
To add to Alex Kucherenko solution: the issue with the cursor getting disappearing after calling setInputType(0)
is due to a framework bug on ICS (and JB).
The bug is documented here: https://code.google.com/p/android/issues/detail?id=27609.
To workaround this, call setRawInputType(InputType.TYPE_CLASS_TEXT)
right after the setInputType
call.
To stop the keyboard from appearing, just override OnTouchListener
of the EditText and return true (swallowing the touch event):
ed.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}
});
The reasons for the cursor appearing on GB devices and not on ICS+ had me tearing my hair out for a couple of hours, so I hope this saves someone's time.
Install popper.js
with spesific version number like this:
bower install popper.js@^1.16.0
Now u can find dist
folder and popper.min.js
file.
Variations on this issue can occur if you have a missing library or file. Check there aren't any missing files in your Project Explorer: they'll be written in red if Xcode can't find them.
The problem lies in your base case.
"The height of a tree is the length of the path from the root to the deepest node in the tree. A (rooted) tree with only a node (the root) has a height of zero." - Wikipedia
If there is no node, you want to return -1 not 0. This is because you are adding 1 at the end.
So if there isn't a node, you return -1 which cancels out the +1.
int findHeight(TreeNode<T> aNode) {
if (aNode == null) {
return -1;
}
int lefth = findHeight(aNode.left);
int righth = findHeight(aNode.right);
if (lefth > righth) {
return lefth + 1;
} else {
return righth + 1;
}
}
Easy with onclick-function and a javascript link:
<td onclick="location.href='yourpage.html'">go to yourpage</td>
I had window 7 (64 bit) and Python 2.7.12,
I uninstalled it by clicking the python installer from the "download" directory then I selected remove python then I clicked “ finish”.
I also removed the remaining python associated directory & files from the c: drive and also from “my documents” folder, since I created some files there.
Objective - C
NSData *myStringData = [@"My String" dataUsingEncoding:NSUTF8StringEncoding];
NSString *myStringFromData = [[NSString alloc] initWithData:myStringData encoding:NSUTF8StringEncoding];
NSLog(@"My string value: %@",myStringFromData);
Swift
//This your data containing the string
let myStringData = "My String".dataUsingEncoding(NSUTF8StringEncoding)
//Use this method to convert the data into String
let myStringFromData = String(data:myStringData!, encoding: NSUTF8StringEncoding)
print("My string value:" + myStringFromData!)
http://objectivec2swift.blogspot.in/2016/03/coverting-nsdata-to-nsstring-or-convert.html
Here's a UDF that will do the trick...
create function ProperCase(@Text as varchar(8000))
returns varchar(8000)
as
begin
declare @Reset bit;
declare @Ret varchar(8000);
declare @i int;
declare @c char(1);
if @Text is null
return null;
select @Reset = 1, @i = 1, @Ret = '';
while (@i <= len(@Text))
select @c = substring(@Text, @i, 1),
@Ret = @Ret + case when @Reset = 1 then UPPER(@c) else LOWER(@c) end,
@Reset = case when @c like '[a-zA-Z]' then 0 else 1 end,
@i = @i + 1
return @Ret
end
You will still have to use it to update your data though.
In your onCreateView
method, container
is actually a ViewPager
instance.
So, just calling
ViewPager vpViewPager = (ViewPager) container;
vpViewPager.setCurrentItem(1);
will change current fragment in your ViewPager
.
The best solution above faces a problem when using the same associative keys, array_merge() will merge array elements together when they have the same NON-NUMBER key, so it is not suitable for the following case
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("c"=>"red","d"=>"black","e"=>"green");
If you are able output your value to the keys of your arrays instead (e.g ->pluck('name', 'id')->toArray() in Eloquent), you can use the following merge method instead
array_keys(array_merge($a1, $a2))
Basically what the code does is it utilized the behavior of array_merge() to get rid of duplicated keys and return you a new array with keys as array elements, hope it helps
If you want to pass a parameter to the delayed function:
setTimeout(setTimer, 3000, param1, param2);
You should use the interface only if you need it, e.g., if your list is casted to an IList implementation other than List. This is true when, for example, you use NHibernate, which casts ILists into an NHibernate bag object when retrieving data.
If List is the only implementation that you will ever use for a certain collection, feel free to declare it as a concrete List implementation.
To make a dropdown list you need two properties:
In your case you only have a list of string which cannot be exploited to create a usable drop down list.
While for number 2. you could have the value and the text be the same you need a property to bind to. You could use a weakly typed version of the helper:
@model List<string>
@Html.DropDownList(
"Foo",
new SelectList(
Model.Select(x => new { Value = x, Text = x }),
"Value",
"Text"
)
)
where Foo
will be the name of the ddl and used by the default model binder. So the generated markup might look something like this:
<select name="Foo" id="Foo">
<option value="item 1">item 1</option>
<option value="item 2">item 2</option>
<option value="item 3">item 3</option>
...
</select>
This being said a far better view model for a drop down list is the following:
public class MyListModel
{
public string SelectedItemId { get; set; }
public IEnumerable<SelectListItem> Items { get; set; }
}
and then:
@model MyListModel
@Html.DropDownListFor(
x => x.SelectedItemId,
new SelectList(Model.Items, "Value", "Text")
)
and if you wanted to preselect some option in this list all you need to do is to set the SelectedItemId
property of this view model to the corresponding Value
of some element in the Items
collection.
Try this:
HTML
<div id="eventCheck"></div>
JAVASCRIPT
// ----------------------------------------------------//
// Todays date
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
// Add Zero if it number is between 0-9
if(dd<10) {
dd = '0'+dd;
}
if(mm<10) {
mm = '0'+mm;
}
var today = yyyy + '' + mm + '' + dd ;
// ----------------------------------------------------//
// Day of event
var endDay = 15; // day 15
var endMonth = 01; // month 01 (January)
var endYear = 2017; // year 2017
// Add Zero if it number is between 0-9
if(endDay<10) {
endDay = '0'+endDay;
}
if(endMonth<10) {
endMonth = '0'+endMonth;
}
// eventDay - date of the event
var eventDay = endYear + '/' + endMonth + '/' + endDay;
// ----------------------------------------------------//
// ----------------------------------------------------//
// check if eventDay has been or not
if ( eventDay < today ) {
document.getElementById('eventCheck').innerHTML += 'Date has passed (event is over)'; // true
} else {
document.getElementById('eventCheck').innerHTML += 'Date has not passed (upcoming event)'; // false
}
Fiddle: https://jsfiddle.net/zm75cq2a/
You can use the patch function for setting defaults with some of the values in your form group.
component.html
<form [formGroup]="countryForm">
<select id="country" formControlName="country">
<option *ngFor="let c of countries" [ngValue]="c">{{ c }}</option>
</select>
</form>
component.ts
import { FormControl, FormGroup, Validators } from '@angular/forms';
export class Component implements OnInit{
countries: string[] = ['USA', 'UK', 'Canada'];
default: string = 'UK';
countryForm: FormGroup;
constructor() {
this.countryForm.controls['country'].setValue(this.default, {onlySelf: true});
}
}
ngOnInit() {
this.countryForm = new FormGroup({
'country': new FormControl(null)
});
this.countryForm.patchValue({
'country': default
});
}
Here is the source code: you can get the text which is exactly in the URL
URL = ''
page = requests.get(URL)
soup = bs4.BeautifulSoup(page.content,'html.parser').get_text()
print(soup)
By transforming your int array into an Integer one and then using public static <T> void Arrays.sort(T[] a,
Comparator<? super T> c)
(the first step is only needed as I fear autoboxing may bot work on arrays).
Add a build task to concatenate and register your html partials in the Angular $templateCache
. (This answer is a more detailed variant of karlgold's answer.)
For grunt, use grunt-angular-templates. For gulp, use gulp-angular-templatecache.
Below are config/code snippets to illustrate.
gruntfile.js Example:
ngtemplates: {
app: {
src: ['app/partials/**.html', 'app/views/**.html'],
dest: 'app/scripts/templates.js'
},
options: {
module: 'myModule'
}
}
gulpfile.js Example:
var templateCache = require('gulp-angular-templatecache');
var paths = ['app/partials/.html', 'app/views/.html'];
gulp.task('createTemplateCache', function () {
return gulp.src(paths)
.pipe(templateCache('templates.js', { module: 'myModule', root:'app/views'}))
.pipe(gulp.dest('app/scripts'));
});
templates.js (this file is autogenerated by the build task)
$templateCache.put('app/views/main.html', "<div class=\"main\">\r"...
index.html
<script src="app/scripts/templates.js"></script>
<div ng-include ng-controller="main as vm" src="'app/views/main.html'"></div>
You can either set with ngModel either with [checked] attribute. ngModel binded property should be set to 'true':
1.
<mat-checkbox class = "example-margin" [(ngModel)] = "myModel">
<label>Printer </label>
</mat-checkbox>
2.
<mat-checkbox [checked]= "myModel" class = "example-margin" >
<label>Printer </label>
</mat-checkbox>
3.
<mat-checkbox [ngModel]="myModel" class="example-margin">
<label>Printer </label>
</mat-checkbox>
below solution worked for me, follow steps to resolve your issue:
Step 1: Cancel Running
Step 2 : open Window menu and select Devices and Simulators
Step 3 : Unpair the iPhone
Step 4 : Removed iPhone USB cable and reconnect to the system
Step 5 : Pair the iPhone when you connect then you will be asked to Trust or Don't Allow, Please click Truct on your iPhone and enter your passcode (Pin Code)
Note : I performed all the above steps they worked for me. The issue of my device debugger gone.
Below is the Screenshot of Devices and Simulators Menu
This is because, in C#, single quotes (''
) denote (or encapsulate) a single character, whereas double quotes (""
) are used for a string of characters. For example:
var myChar = '=';
var myString = "==";
The answer is right in the MYSQL manual itself.
"DELETE FROM `table_name` WHERE `time_col` < ADDDATE(NOW(), INTERVAL -1 HOUR)"
Here is a different method same thing but a little different
the difference is the content dot which is replaced with a \00A0
== whitespace
More on this http://www.jqui.net/tips-tricks/css-clearfix/
.clearfix:after { content: "\00A0"; display: block; clear: both; visibility: hidden; line-height: 0; height: 0;}
.clearfix{ display: inline-block;}
html[xmlns] .clearfix { display: block;}
* html .clearfix{ height: 1%;}
.clearfix {display: block}
Here is a compact version of it...
.clearfix:after { content: "\00A0"; display: block; clear: both; visibility: hidden; line-height: 0; height: 0;width:0;font-size: 0px}.clearfix{ display: inline-block;}html[xmlns] .clearfix { display: block;}* html .clearfix{ height: 1%;}.clearfix {display: block}
Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english
First close All the things which use ADB. (Android Studio, Eclipse, Emulator(Bluestack as well)) and then do
adb kill-server
adb start-server
In my case I just got update of Studio.
I was driving myself crazy with this exact problem. My JSON Marshaller and Unmarshaller were not populating my Go struct. Then I found the solution at https://eager.io/blog/go-and-json:
"As with all structs in Go, it’s important to remember that only fields with a capital first letter are visible to external programs like the JSON Marshaller."
After that, my Marshaller and Unmarshaller worked perfectly!
Perl Code for Unix systems:
# Capture date from shell
my $current_date = `date +"%m/%d/%Y"`;
# Remove newline character
$current_date = substr($current_date,0,-1);
print $current_date, "\n";
Just add one to the result. That turns [0, 10) into (0,10] (for integers). [0, 10) is just a more confusing way to say [0, 9], and (0,10] is [1,10] (for integers).
How about something like:
struct foo bar;
update(init_id(42, init_dont_care(&bar)));
with:
struct foo* init_dont_care(struct foo* bar) {
bar->id = dont_care;
bar->route = dont_care;
bar->backup_route = dont_care;
bar->current_route = dont_care;
return bar;
}
and:
struct foo* init_id(int id, struct foo* bar) {
bar->id = id;
return bar;
}
and correspondingly:
struct foo* init_route(int route, struct foo* bar);
struct foo* init_backup_route(int backup_route, struct foo* bar);
struct foo* init_current_route(int current_route, struct foo* bar);
In C++, a similar pattern has a name which I don't remember just now.
EDIT: It's called the Named Parameter Idiom.
SayntLewis is right. When you activate the camera with cvCaptureFromCAM, the auto white balance is not yet adjusted (it's a slow process), so you may get a mostly white or mostly black (depends on the camera and your lightning conditions) on the first frames. The same happens when there's a sudden change of the lightning of the scene. Just wait some time after opening the camera, flush the buffer and you're ready to go.
You can use one liner javascript with array reduce method and ES6 destructuring to convert array of key value pairs to object.
arr.reduce((map, { name, input }) => ({ ...map, [name]: input }), {});
// I usually do this:
x = "0" ;
if (!!+x) console.log('I am true');
else console.log('I am false');
// Essentially converting string to integer and then boolean.
Efran Cobisi's suggestion of using an Auto Mapper is a good one. I have used Auto Mapper for a while and it worked well, until I found the much faster alternative, Mapster.
Given a large list or IEnumerable, Mapster outperforms Auto Mapper. I found a benchmark somewhere that showed Mapster being 6 times as fast, but I could not find it again. You could look it up and then, if it is suits you, use Mapster.
if you want to execute tasks parallel,you need call the method executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "your task name")
after Android version of 3.0; but this method is not exist before Android 3.0 and after 1.6 because it execute parallel by itself, So I suggest you customize your own AsyncTask class in your project,to avoid throw exception in different Android version.
Here's how it's done in the Java API:
public boolean intersects(Rectangle r) {
int tw = this.width;
int th = this.height;
int rw = r.width;
int rh = r.height;
if (rw <= 0 || rh <= 0 || tw <= 0 || th <= 0) {
return false;
}
int tx = this.x;
int ty = this.y;
int rx = r.x;
int ry = r.y;
rw += rx;
rh += ry;
tw += tx;
th += ty;
// overflow || intersect
return ((rw < rx || rw > tx) &&
(rh < ry || rh > ty) &&
(tw < tx || tw > rx) &&
(th < ty || th > ry));
}
For int %d
For long int %ld
For long long int %lld
For unsigned long long int %llu
You have to load the db library first. In autoload.php
add :
$autoload['libraries'] = array('database');
Also, try renaming User model class for "User_model".
I have also seen:
if(length(obj)) {
# do this if object has length
# NULL has no length
}
I don't think it's great though. Because some vectors can be of length 0. character(0)
, logical(0)
, integer(0)
and that might be treated as a NULL instead of an error.
If you are still interested, Chris Wolf made a prototype implementation of SQLite with Stored Procedures. You can find the details at his blog post: Adding Stored Procedures to SQLite
To obtain the current stable version of the NuGet package use:
https://www.nuget.org/api/v2/package/{packageID}
If you need to chuck a literal NULL
in, then you could have some issues. Apart from that, no, I think you're probably on the right track.
The other method some people choose is taking an assoc array of variables iterating through the argument list. It looks a bit neater but I imagine it's a little (very little) bit more process/memory intensive.
function myFunction (argArray) {
var defaults = {
'arg1' : "value 1",
'arg2' : "value 2",
'arg3' : "value 3",
'arg4' : "value 4"
}
for(var i in defaults)
if(typeof argArray[i] == "undefined")
argArray[i] = defaults[i];
// ...
}
You have two options:
Install cron as a windows service, using cygrunsrv:
cygrunsrv -I cron -p /usr/sbin/cron -a -n
net start cron
Note, in (very) old versions of cron you need to use -D instead of -n
The 'non .exe' files are probably bash scripts, so you can run them via the windows scheduler by invoking bash to run the script, e.g.:
C:\cygwin\bin\bash.exe -l -c "./full-path/to/script.sh"
To help you get the desired outcome in perhaps a different way than you asked:
render: function() {
...
<a data-tag={i} style={showStyle} onClick={this.removeTag.bind(null, i)}></a>
...
},
removeTag: function(i) {
// do whatever
},
Notice the bind()
. Because this is all javascript, you can do handy things like that. We no longer need to attach data to DOM nodes in order to keep track of them.
IMO this is much cleaner than relying on DOM events.
Update April 2017: These days I would write onClick={() => this.removeTag(i)}
instead of .bind
Based on Martin Atkins' solution, here is a complete, concise pure-Angular solution:
(function() {
var initInjector = angular.injector(['ng']);
var $http = initInjector.get('$http');
$http.get('/config.json').then(
function (response) {
angular.module('config', []).constant('CONFIG', response.data);
angular.element(document).ready(function() {
angular.bootstrap(document, ['myApp']);
});
}
);
})();
This solution uses a self-executing anonymous function to get the $http service, request the config, and inject it into a constant called CONFIG when it becomes available.
Once completely, we wait until the document is ready and then bootstrap the Angular app.
This is a slight enhancement over Martin's solution, which deferred fetching the config until after the document is ready. As far as I know, there is no reason to delay the $http call for that.
Unit Testing
Note: I have discovered this solution does not work well when unit-testing when the code is included in your app.js
file. The reason for this is that the above code runs immediately when the JS file is loaded. This means the test framework (Jasmine in my case) doesn't have a chance to provide a mock implementation of $http
.
My solution, which I'm not completely satisfied with, was to move this code to our index.html
file, so the Grunt/Karma/Jasmine unit test infrastructure does not see it.
Java code:
public class MapActivity extends FragmentActivity implements LocationListener {
GoogleMap googleMap;
LatLng myPosition;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
// Getting reference to the SupportMapFragment of activity_main.xml
SupportMapFragment fm = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
googleMap = fm.getMap();
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
myPosition = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(myPosition).title("Start"));
}
}
}
activity_map.xml:
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="@+id/map"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
class="com.google.android.gms.maps.SupportMapFragment"/>
You will get your current location in a blue circle.
Here are my personal, super-condensed notes, as far as this subject pertains to me currently, for anyone who's interested:
You can also try
Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getTimeInMillis());
getTimeInMillis() - the current time as UTC milliseconds from the epoch
Non technically speaking means :
Assumption: chair = memory block , people = variable
Structure : If there are 3 people they can sit in chair of their size correspondingly .
Union : If there are 3 people only one chair will be there to sit , all need to use the same chair when they want to sit .
Technically speaking means :
The below mentioned program gives a deep dive into structure and union together .
struct MAIN_STRUCT
{
UINT64 bufferaddr;
union {
UINT32 data;
struct INNER_STRUCT{
UINT16 length;
UINT8 cso;
UINT8 cmd;
} flags;
} data1;
};
Total MAIN_STRUCT size =sizeof(UINT64) for bufferaddr + sizeof(UNIT32) for union + 32 bit for padding(depends on processor architecture) = 128 bits . For structure all the members get the memory block contiguously .
Union gets one memory block of the max size member(Here its 32 bit) . Inside union one more structure lies(INNER_STRUCT) its members get a memory block of total size 32 bits(16+8+8) . In union either INNER_STRUCT(32 bit) member or data(32 bit) can be accessed .
Just fixed this issue. import c2 or import numpy was not working. Uninstalled the most current version of numpy. Tried to install numpy==1.15.2 just like specified above, did not work. Tried numpy==1.19.3 IT worked. I guess not all versions work perfectly with all versions of python and dependencies. So keep uninstalling and install one that works.
After several tries i found htmlentities function works.
$value = htmlentities($value)
You might want to look at the RouteLink()
method.That one lets you specify everything (except the link text and route name) via a dictionary.
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,
In my case I have changed project name in pom.xml so the new target directory was generated and junit was searching classes in old directory. You need to change directory for JUnit also in Eclipse
Properties -> Java Build Path -> Source (Default output folder)
And also check because some of source folders listed in the same window may have former directory name. You need to change them too.
One another point to note down is in MaxLength attribute you can only provide max required range not a min required range. While in StringLength you can provide both.
Instead of overriding the library search path at runtime with LD_LIBRARY_PATH, you could instead bake it into the binary itself with rpath
. If you link with GCC adding -Wl,-rpath,<libdir>
should do the trick, if you link with ld it's just -rpath <libdir>
.
As Mingyu pointed out, there is a problem in formatting. Other than that, I would strongly recommend not using the Derived class's name while calling super()
since it makes your code inflexible (code maintenance and inheritance issues). In Python 3, Use super().__init__
instead. Here is the code after incorporating these changes :
class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
class ElectricCar(Car):
def __init__(self, battery_type, model, color, mpg):
self.battery_type=battery_type
super().__init__(model, color, mpg)
Thanks to Erwin Mayer for pointing out the issue in using __class__
with super()
The Concat
method will return an object which implements IEnumerable<T>
by returning an object (call it Cat) whose enumerator will attempt to use the two passed-in enumerable items (call them A and B) in sequence. If the passed-in enumerables represent sequences which will not change during the lifetime of Cat, and which can be read from without side-effects, then Cat may be used directly. Otherwise, it may be a good idea to call ToList()
on Cat
and use the resulting List<T>
(which will represent a snapshot of the contents of A and B).
Some enumerables take a snapshot when enumeration begins, and will return data from that snapshot if the collection is modified during enumeration. If B is such an enumerable, then any change to B which occurs before Cat has reached the end of A will show up in Cat's enumeration, but changes which occur after that will not. Such semantics may likely be confusing; taking a snapshot of Cat can avoid such issues.
@Deprecated
public static int toInt(Object obj)
{
if (obj instanceof String)
{
return Integer.parseInt((String) obj);
} else if (obj instanceof Number)
{
return ((Number) obj).intValue();
} else
{
String toString = obj.toString();
if (toString.matches("-?\d+"))
{
return Integer.parseInt(toString);
}
throw new IllegalArgumentException("This Object doesn't represent an int");
}
}
As you can see, this isn't a very efficient way of doing it. You simply have to be sure of what kind of object you have. Then convert it to an int the right way.
It should be a problem in your version of grep.
Your test cases are working correctly here on my machine:
$ echo "abc" | grep -io abc
abc
$ echo "ABC" | grep -io abc
ABC
And my version is:
$ grep --version
grep (GNU grep) 2.10
Warning:
mysql_*
extension is deprecated as of PHP 5.5.0, and has been removed as of PHP 7.0.0. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
Whenever possible, importing a file to MySQL should be delegated to MySQL client.
I have got another way to do this, try this
<?php
// Name of the file
$filename = 'churc.sql';
// MySQL host
$mysql_host = 'localhost';
// MySQL username
$mysql_username = 'root';
// MySQL password
$mysql_password = '';
// Database name
$mysql_database = 'dump';
// Connect to MySQL server
mysql_connect($mysql_host, $mysql_username, $mysql_password) or die('Error connecting to MySQL server: ' . mysql_error());
// Select database
mysql_select_db($mysql_database) or die('Error selecting MySQL database: ' . mysql_error());
// Temporary variable, used to store current query
$templine = '';
// Read in entire file
$lines = file($filename);
// Loop through each line
foreach ($lines as $line)
{
// Skip it if it's a comment
if (substr($line, 0, 2) == '--' || $line == '')
continue;
// Add this line to the current segment
$templine .= $line;
// If it has a semicolon at the end, it's the end of the query
if (substr(trim($line), -1, 1) == ';')
{
// Perform the query
mysql_query($templine) or print('Error performing query \'<strong>' . $templine . '\': ' . mysql_error() . '<br /><br />');
// Reset temp variable to empty
$templine = '';
}
}
echo "Tables imported successfully";
?>
This is working for me
Had the same error encountered which was due to conflicting drawable resources. I did a clean project and the error was no longer encountered.
You should seriously consider dhiller's answer:
new ArrayList(set)
(or a new LinkedList(set)
, whatever).I think that the solution you posted with the NoDuplicatesList
has some issues, mostly with the contains()
method, plus your class does not handle checking for duplicates in the Collection passed to your addAll()
method.
The embed URL for a channel's live stream is:
https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID
You can find your CHANNEL_ID at https://www.youtube.com/account_advanced
The Facebook "Graph API Rate Limiting" docs says that an error with code #4
is an app level rate limit, which is different than user level rate limits. Although it doesn't give any exact numbers, it describes their app level rate-limit as:
This rate limiting is applied globally at the app level. Ads api calls are excluded.
- Rate limiting happens real time on sliding window for past one hour.
- Stats is collected for number of calls and queries made, cpu time spent, memory used for each app.
- There is a limit for each resource multiplied by monthly active users of a given app.
- When the app uses more than its allowed resources the error is thrown.
- Error, Code: 4, Message: Application request limit reached
The docs also give recommendations for avoiding the rate limits. For app level limits, they are:
Recommendations:
- Verify the error code (4) to confirm the throttling type.
- Do not make burst of calls, spread out the calls throughout the day.
- Do smart fetching of data (important data, non duplicated data, etc).
- Real-time insights, make sure API calls are structured in a way that you can read insights for as many as Page posts as possible, with minimum number of requests.
- Don't fetch users feed twice (in the case that two App users have a specific friend in common)
- Don't fetch all user's friends feed in a row if the number of friends is more than 250. Separate the fetches over different days. As an option, fetch first the app user's news feed (me/home) in order to detect which friends are more important to the App user. Then, fetch those friends feeds first.
- Consider to limit/filter the requests by using the following parameters: "since", "until", "limit"
- For page related calls use realtime updates to subscribe to changes in data.
- Field expansion allows ton "join" multiple graph queries into a single call.
- Etags to check if the data querying has changed since the last check.
- For page management developers who does not have massive user base, have the admins of the page to accept the app to increase the number of users.
Finally, the docs give the following informational tips:
- Batching calls will not reduce the number of api calls.
- Making parallel calls will not reduce the number of api calls.
Couldn't find any definitive reference, but I see that the example code for os.walk uses os.path but only imports os
If you manually write out the query with static date values (e.g. '2009-10-29 13:13:07.440') do you get any rows?
So, you are saying that the following two queries produce correct results:
SELECT DISTINCT pat.PublicationID
FROM PubAdvTransData AS pat
INNER JOIN PubAdvertiser AS pa
ON pat.AdvTransID = pa.AdvTransID
WHERE (pat.LastAdDate > '2009-10-29 13:13:07.440') AND (pa.AdvertiserID = 12345))
DECLARE @sp_Date DATETIME
SET @sp_Date = '2009-10-29 13:13:07.440'
SELECT DISTINCT pat.PublicationID
FROM PubAdvTransData AS pat
INNER JOIN PubAdvertiser AS pa
ON pat.AdvTransID = pa.AdvTransID
WHERE (pat.LastAdDate > @sp_Date) AND (pa.AdvertiserID = 12345))
I would echo the Json.NET library, which can transform the JSON response into a XML document. With the XML document, you can easily query with XPath and extract the data you need. I find this pretty useful.
I think that coreset.o was compiled for 64-bit, and you are linking it with a 32-bit computation.o.
You can try to recompile computation.c with the '-m64' flag of gcc(1)
If you ever end up with the same problem with Scala and SBT:
Go to Project Structure. The shortcut is (CTRL + ALT + SHIFT + S)
On the far left list, choose Project Settings > Modules
On the module list right of that, select the module of your project name (without the build) and choose the sources tab
In middle, expand the folder that the root of your project for me that's /home/<username>/IdeaProjects/<projectName>
Look at the Content Root section on the right side, the red paths are directories that you haven't made. You'll want to put the properties file in a Resources directory. So I created src/main/resources
and put log4j.properties in it. I believe you can also modify the Content Root to put it wherever you want (I didn't do this).
I ran my code with a SBT configuration and it found my log4j.properties file.
its very simple
just write:
//first create table named test....
create table test (name varchar2(10),age number(5));
//when you run the above code a table will be created....
//now we have to insert a name & an age..
Make sure age will be inserted via opening a form that seeks our help to enter the value in it
insert into test values('Deepak', :age);
//now run the above code and you'll get "1 row inserted" output...
/now run the select query to see the output
select * from test;
//that's all ..Now i think no one has any queries left over accepting a user data...
Better to use wp_mkdir_p
function for it. This function will recursively create a folder with the correct permissions. Also, you can skip folder exists condition because it will be check before creating.
$path = 'path/to/directory';
if ( wp_mkdir_p( $path ) ) {
// Directory exists or was created.
}
More: https://developer.wordpress.org/reference/functions/wp_mkdir_p/
Quoting spaces inside variables such that the shell will re-interpret things properly is hard. It's this type of thing that prompts me to reach for a stronger language. Whether that's perl or python or ruby or whatever (I choose perl, but that's not always for everyone), it's just something that will allow you to bypass the shell for quoting.
It's not that I've never managed to get it right with liberal doses of eval, but just that eval gives me the eebie-jeebies (becomes a whole new headache when you want to take user input and eval it, though in this case you'd be taking stuff that you wrote and evaling that instead), and that I've gotten headaches in debugging.
With perl, as my example, I'd be able to do something like:
@tar_cmd = ( qw(tar cv), $directory );
@encrypt_cmd = ( qw(openssl des3 -salt) );
@split_cmd = ( qw(split -b 1024m -), $backup_file );
The hard part here is doing the pipes - but a bit of IO::Pipe, fork, and reopening stdout and stderr, and it's not bad. Some would say that's worse than quoting the shell properly, and I understand where they're coming from, but, for me, this is easier to read, maintain, and write. Heck, someone could take the hard work out of this and create a IO::Pipeline module and make the whole thing trivial ;-)
You can use it with your local variables, like this:
@animal = "Dog"
@action = "licks"
@second_animal = "Bird"
"The #{@animal} #{@action} the #{@second_animal}"
the output would be: "The Dog licks the Bird"
I wouldn't reference the parent directly in the child objects. In my opinion the childs shouldn't know anything about the parents. This will limits the flexibility!
I would solve this with events/handlers.
public class Meter
{
private int _powerRating = 0;
private Production _production;
public Meter()
{
_production = new Production();
_production.OnRequestPowerRating += new Func<int>(delegate { return _powerRating; });
_production.DoSomething();
}
}
public class Production
{
protected int RequestPowerRating()
{
if (OnRequestPowerRating == null)
throw new Exception("OnRequestPowerRating handler is not assigned");
return OnRequestPowerRating();
}
public void DoSomething()
{
int powerRating = RequestPowerRating();
Debug.WriteLine("The parents powerrating is :" + powerRating);
}
public Func<int> OnRequestPowerRating;
}
In this case I solved it with the Func<> generic, but can be done with 'normal' functions. This why the child(Production) is totally independent from it's parent(Meter).
But! If there are too many events/handlers or you just want to pass a parent object, i would solve it with an interface:
public interface IMeter
{
int PowerRating { get; }
}
public class Meter : IMeter
{
private int _powerRating = 0;
private Production _production;
public Meter()
{
_production = new Production(this);
_production.DoSomething();
}
public int PowerRating { get { return _powerRating; } }
}
public class Production
{
private IMeter _meter;
public Production(IMeter meter)
{
_meter = meter;
}
public void DoSomething()
{
Debug.WriteLine("The parents powerrating is :" + _meter.PowerRating);
}
}
This looks pretty much the same as the solution mentions, but the interface could be defined in another assembly and can be implemented by more than 1 class.
Regards, Jeroen van Langen.
Try renaming your 'proguard-rules.txt' file to 'proguard-android.txt' and remove the reference to 'proguard-rules.txt' in your gradle file. The getDefaultProguardFile(...)
call references a different default proguard file, one provided by Google and not that in your project. So remove this as well, so that here the gradle file reads:
buildTypes {
release {
runProguard true
proguardFile 'proguard-android.txt'
}
}
var listItems= "";
var jsonData = jsonObj.d;
for (var i = 0; i < jsonData.Table.length; i++){
listItems+= "<option value='" + jsonData.Table[i].stateid + "'>" + jsonData.Table[i].statename + "</option>";
}
$("#<%=DLState.ClientID%>").html(listItems);
Example
<html>
<head></head>
<body>
<select id="DLState">
</select>
</body>
</html>
/*javascript*/
var jsonList = {"Table" : [{"stateid" : "2","statename" : "Tamilnadu"},
{"stateid" : "3","statename" : "Karnataka"},
{"stateid" : "4","statename" : "Andaman and Nicobar"},
{"stateid" : "5","statename" : "Andhra Pradesh"},
{"stateid" : "6","statename" : "Arunachal Pradesh"}]}
$(document).ready(function(){
var listItems= "";
for (var i = 0; i < jsonList.Table.length; i++){
listItems+= "<option value='" + jsonList.Table[i].stateid + "'>" + jsonList.Table[i].statename + "</option>";
}
$("#DLState").html(listItems);
});
How do I select multiple columns by labels in pandas?
Multiple label-based range slicing is not easily supported with pandas, but position-based slicing is, so let's try that instead:
loc = df.columns.get_loc
df.iloc[:, np.r_[loc('A'):loc('C')+1, loc('E'), loc('G'):loc('I')+1]]
A B C E G H I
0 -1.666330 0.321260 -1.768185 -0.034774 0.023294 0.533451 -0.241990
1 0.911498 3.408758 0.419618 -0.462590 0.739092 1.103940 0.116119
2 1.243001 -0.867370 1.058194 0.314196 0.887469 0.471137 -1.361059
3 -0.525165 0.676371 0.325831 -1.152202 0.606079 1.002880 2.032663
4 0.706609 -0.424726 0.308808 1.994626 0.626522 -0.033057 1.725315
5 0.879802 -1.961398 0.131694 -0.931951 -0.242822 -1.056038 0.550346
6 0.199072 0.969283 0.347008 -2.611489 0.282920 -0.334618 0.243583
7 1.234059 1.000687 0.863572 0.412544 0.569687 -0.684413 -0.357968
8 -0.299185 0.566009 -0.859453 -0.564557 -0.562524 0.233489 -0.039145
9 0.937637 -2.171174 -1.940916 -1.553634 0.619965 -0.664284 -0.151388
Note that the +1
is added because when using iloc
the rightmost index is exclusive.
filter
is a nice and simple method for OP's headers, but this might not generalise well to arbitrary column names.
The "location-based" solution with loc
is a little closer to the ideal, but you cannot avoid creating intermediate DataFrames (that are eventually thrown out and garbage collected) to compute the final result range -- something that we would ideally like to avoid.
Lastly, "pick your columns directly" is good advice as long as you have a manageably small number of columns to pick. It will, however not be applicable in some cases where ranges span dozens (or possibly hundreds) of columns.
How about without using predefined function like min
or max
?
$arr = [4,5,6,7,8,2,9,1];
$val = $arr[0];
$n = count($arr);
for($i=1;$i<$n;$i++) {
if($val<$arr[$i]) {
$val = $val;
} else {
$val = $arr[$i];
}
}
print($val);
?>
I had the same problem , I used in
instead of =
, from the Northwind
database example :
Query is : Find the Companies that placed orders in 1997
Try this :
SELECT CompanyName
FROM Customers
WHERE CustomerID IN (
SELECT CustomerID
FROM Orders
WHERE YEAR(OrderDate) = '1997'
);
Instead of that :
SELECT CompanyName
FROM Customers
WHERE CustomerID =
(
SELECT CustomerID
FROM Orders
WHERE YEAR(OrderDate) = '1997'
);
Even more, you can inherit generics :)
@SuppressWarnings("unchecked")
public <T extends Something<E>, E extends Enum<E> & SomethingAware> T getSomething(Class<T> clazz) {
return (T) somethingHolderMap.get(clazz);
}
You may still want to use VARCHAR in cases where you don't always store a hash for the user (i.e. authenticating accounts/forgot login url). Once a user has authenticated/changed their login info they shouldn't be able to use the hash and should have no reason to. You could create a separate table to store temporary hash -> user associations that could be deleted but I don't think most people bother to do this.
completing the answer @Jorgesys, in my case it was exactly the same way but the export configuration was missing in the library:
Try XmlSerialization
try this
[Serializable]
public class Task
{
public string Name{get; set;}
public string Location {get; set;}
public string Arguments {get; set;}
public DateTime RunWhen {get; set;}
}
public void WriteXMl(Task task)
{
XmlSerializer serializer;
serializer = new XmlSerializer(typeof(Task));
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream, Encoding.Unicode);
serializer.Serialize(writer, task);
int count = (int)stream.Length;
byte[] arr = new byte[count];
stream.Seek(0, SeekOrigin.Begin);
stream.Read(arr, 0, count);
using (BinaryWriter binWriter=new BinaryWriter(File.Open(@"C:\Temp\Task.xml", FileMode.Create)))
{
binWriter.Write(arr);
}
}
public Task GetTask()
{
StreamReader stream = new StreamReader(@"C:\Temp\Task.xml", Encoding.Unicode);
return (Task)serializer.Deserialize(stream);
}
@Grantismo provides a great explanation on the overall. If you wish to know who people are actually doing this things i suggest you to take a look at how google did for the Google IO App of 2014 (it's always worth taking a deep look at the source code of these apps that they release. There's a lot to learn from there).
Here's a blog post about it: http://android-developers.blogspot.com.br/2014/09/conference-data-sync-gcm-google-io.html
Essentially, on the application side: GCM for signalling, Sync Adapter for data fetching and talking properly with Content Provider that will make things persistent (yeah, it isolates the DB from direct access from other parts of the app).
Also, if you wish to take a look at the 2015's code: https://github.com/google/iosched
You may have closed either the Connection
or Statement
that made the ResultSet
, which would lead to the ResultSet
being closed as well.
I think, a word was created with more than one letters. My suggestion is:
[^\s\s$]{2,}
I have a simpler solution for you:
window.onload = window.onresize = (event) => {
//Your Code Here
}
I've tested this an it works great, on the plus side it's compact and uncomplicated like the other examples here.
If your data is already in array form, it's really simple using jQuery:
$(data.msg).each(function()
{
alert(this.value);
alert(this.label);
//this refers to the current item being iterated over
var option = $('<option />');
option.attr('value', this.value).text(this.label);
$('#myDropDown').append(option);
});
.ajax()
is more flexible than .getJSON()
- for one, getJson is targeted specifically as a GET request to retrieve json; ajax() can request on any verb to get back any content type (although sometimes that's not useful). getJSON internally calls .ajax().
you can also use ranges by using:
b = df[(df['a'] > 1) & (df['a'] < 5)]
I don't know if this is new functionality, but this will plot on separate figures:
df.plot(y='korisnika')
df.plot(y='osiguranika')
while this will plot on the same figure: (just like the code in the op)
df.plot(y=['korisnika','osiguranika'])
I found this question because I was using the former method and wanted them to plot on the same figure, so your question was actually my answer.
With CSS positioning, you can place an element exactly where you want it on your page.
When you are going to use CSS positioning, the first thing you need to do is use the CSS property position to tell the browser if you're going to use absolute or relative positioning.
Both Positions are having different features. In CSS Once you set Position then you can able to use top, right, bottom, left attributes.
Absolute Position
An absolute position element is positioned relative to the first parent element that has a position other than static.
Relative Position
A relative positioned element is positioned relative to its normal position.
To position an element relatively, the property position is set as relative. The difference between absolute and relative positioning is how the position is being calculated.
And in addition to the above nice answers.
RSA stands for Ron Rivest, Adi Shamir and Leonard Adleman.
You need the *
so it says "zero or more of the previous character" and this should do it:
var reg = new RegExp('^\\d*$');
Of course, you can't fully rely on the client-side (javascript) validation, but that's not a reason to avoid it completely. With or without it, you have to do the server-side validation anyway (since the client can disable javascript). And that's just what you're left with, due to your non-javascript solution constraint.
So, after a submit, if the field value doesn't pass the server-side validation, the client should end up on the very same page, with additional error message specifying the requested value format. You also should provide the value format information beforehands, e.g. as a tool-tip hint (title
attribute).
There's most certainly no passive client-side validation mechanism existing in HTML 4 / XHTML.
On the other hand, in HTML 5 you have two options:
input of type number
:
<input type="number" min="xxx" max="yyy" title="Format: 3 digits" />
– only validates the range – if user enters a non-number, an empty value is submitted
– the field visual is enhanced with increment / decrement controls (browser dependent)
the pattern
attribute:
<input type="text" pattern="[0-9]{3}" title="Format: 3 digits" />
<input type="text" pattern="\d{3}" title="Format: 3 digits" />
– this gives you a full contorl over the format (anything you can specify by regular expression)
– no visual difference / enhancement
But here you still rely on browser capabilities, so do a server-side validation in either case.
Yes, this is possible:
List<BigDecimal> bdList = new ArrayList<>();
//populate list
BigDecimal result = bdList.stream()
.reduce(BigDecimal.ZERO, BigDecimal::add);
What it does is:
List<BigDecimal>
.Stream<BigDecimal>
Call the reduce method.
3.1. We supply an identity value for addition, namely BigDecimal.ZERO
.
3.2. We specify the BinaryOperator<BigDecimal>
, which adds two BigDecimal
's, via a method reference BigDecimal::add
.
I see that you have added new data, therefore the new answer will become:
List<Invoice> invoiceList = new ArrayList<>();
//populate
Function<Invoice, BigDecimal> totalMapper = invoice -> invoice.getUnit_price().multiply(invoice.getQuantity());
BigDecimal result = invoiceList.stream()
.map(totalMapper)
.reduce(BigDecimal.ZERO, BigDecimal::add);
It is mostly the same, except that I have added a totalMapper
variable, that has a function from Invoice
to BigDecimal
and returns the total price of that invoice.
Then I obtain a Stream<Invoice>
, map it to a Stream<BigDecimal>
and then reduce it to a BigDecimal
.
Now, from an OOP design point I would advice you to also actually use the total()
method, which you have already defined, then it even becomes easier:
List<Invoice> invoiceList = new ArrayList<>();
//populate
BigDecimal result = invoiceList.stream()
.map(Invoice::total)
.reduce(BigDecimal.ZERO, BigDecimal::add);
Here we directly use the method reference in the map
method.
You should not place an using
directive in an header file, it creates unnecessary headaches.
Also you need an include guard in your header.
EDIT: of course, after having fixed the include guard issue, you also need a complete declaration of student in the header file. As pointed out by others the forward declaration is not sufficient in your case.
my helpful code for others(just one aspx to do text area post)::
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication45.WebForm1" %>
<!DOCTYPE html>
enter code here
<html ng-app="htmldoc" xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="angular.min.js"></script>
<script src="angular-sanitize.min.js"></script>
<script>
angular.module('htmldoc', ['ngSanitize']).controller('x', function ($scope, $sce) {
//$scope.htmlContent = '<script> (function () { location = \"http://moneycontrol.com\"; } )()<\/script> In last valid content';
$scope.htmlContent = '';
$scope.withoutSanitize = function () {
return $sce.getTrustedHtml($scope.htmlContent);
};
$scope.postMessage = function () {
var ValidContent = $sce.trustAsHtml($scope.htmlContent);
//your ajax call here
};
});
</script>
</head>
<body>
<form id="form1" runat="server">
Example to show posting valid content to server with two way binding
<div ng-controller="x">
<p ng-bind-html="htmlContent"></p>
<textarea ng-model="htmlContent" ng-trim="false"></textarea>
<button ng-click="postMessage()">Send</button>
</div>
</form>
</body>
</html>
class ArchiveUtil {
private static let PeopleKey = "PeopleKey"
private static func archivePeople(people : [Human]) -> NSData {
return NSKeyedArchiver.archivedData(withRootObject: people as NSArray) as NSData
}
static func loadPeople() -> [Human]? {
if let unarchivedObject = UserDefaults.standard.object(forKey: PeopleKey) as? Data {
return NSKeyedUnarchiver.unarchiveObject(with: unarchivedObject as Data) as? [Human]
}
return nil
}
static func savePeople(people : [Human]?) {
let archivedObject = archivePeople(people: people!)
UserDefaults.standard.set(archivedObject, forKey: PeopleKey)
UserDefaults.standard.synchronize()
}
}
class Human: NSObject, NSCoding {
var name:String?
var age:Int?
required init(n:String, a:Int) {
name = n
age = a
}
required init(coder aDecoder: NSCoder) {
name = aDecoder.decodeObject(forKey: "name") as? String
age = aDecoder.decodeInteger(forKey: "age")
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(name, forKey: "name")
aCoder.encode(age, forKey: "age")
}
}
var people = [Human]()
people.append(Human(n: "Sazzad", a: 21))
people.append(Human(n: "Hissain", a: 22))
people.append(Human(n: "Khan", a: 23))
ArchiveUtil.savePeople(people: people)
let others = ArchiveUtil.loadPeople()
for human in others! {
print("name = \(human.name!), age = \(human.age!)")
}
The function is max
. To obtain the first maximum value you should do
[val, idx] = max(a);
val
is the maximum value and idx
is its index.
In Azure environment with Basic website that has 1 Instance.I tried to insert a Batch of 1000 records at a time out of 25000 records using for loop it took 11.5 min but in parallel execution it took less than a minute.So I recommend using TPL(Task Parallel Library).
var count = (you collection / 1000) + 1;
Parallel.For(0, count, x =>
{
ApplicationDbContext db1 = new ApplicationDbContext();
db1.Configuration.AutoDetectChangesEnabled = false;
var records = members.Skip(x * 1000).Take(1000).ToList();
db1.Members.AddRange(records).AsParallel();
db1.SaveChanges();
db1.Dispose();
});
$scope.items = [{name: 'a', age: 20},{ name: 'b', age: 30},{ name: 'c', age: 40}];
Case-1) label for value in array:
<div>
<p>selected item is : {{selectedItem}}</p>
<p> age of selected item is : {{selectedItem.age}} </p>
<select ng-model="selectedItem" ng-options="item.name for item in items">
</select>
</div>
Output Explanation (Assume 1st item selected):
selectedItem = {name: 'a', age: 20} // [by default, selected item is equal to the value item]
selectedItem.age = 20
Case-2) select as label for value in array:
<div>
<p>selected item is : {{selectedItem}}</p>
<select ng-model="selectedItem" ng-options="item.age as item.name for item in items">
</select>
</div>
Output Explanation (Assume 1st item selected): selectedItem = 20 // [select part is item.age]
CTRL+SHIFT+* is the de-facto standard key combination for showing/hiding whitespace characters in all Microsoft products that support this feature.
P.S: * refers to 8- * key, not to numeric keypad * key.
I think you want something along the line of:
Parent:
<Editor name={this.state.fileData} />
Editor:
var Editor = React.createClass({
displayName: 'Editor',
propTypes: {
name: React.PropTypes.string.isRequired
},
getInitialState: function() {
return {
value: this.props.name
};
},
handleChange: function(event) {
this.setState({value: event.target.value});
},
render: function() {
return (
<form id="noter-save-form" method="POST">
<textarea id="noter-text-area" name="textarea" value={this.state.value} onChange={this.handleChange} />
<input type="submit" value="Save" />
</form>
);
}
});
This is basically a direct copy of the example provided on https://facebook.github.io/react/docs/forms.html
Update for React 16.8:
import React, { useState } from 'react';
const Editor = (props) => {
const [value, setValue] = useState(props.name);
const handleChange = (event) => {
setValue(event.target.value);
};
return (
<form id="noter-save-form" method="POST">
<textarea id="noter-text-area" name="textarea" value={value} onChange={handleChange} />
<input type="submit" value="Save" />
</form>
);
}
Editor.propTypes = {
name: PropTypes.string.isRequired
};
I strongly recommend using lowercase field|column names, it will make your life easier.
Let's assume you have a table called users with the following definition and records:
id|firstname|lastname|username |password
1 |joe |doe |[email protected] |1234
2 |jane |doe |[email protected] |12345
3 |johnny |doe |[email protected]|123456
let's say you want to get all records from table users, then you do:
SELECT * FROM users;
Now let's assume you want to select all records from table users, but you're interested only in the fields id, firstname and lastname, thus ignoring username and password:
SELECT id, firstname, lastname FROM users;
Now we get at the point where you want to retrieve records based on condition(s), what you need to do is to add the WHERE clause, let's say we want to select from users only those that have username = [email protected] and password = 1234, what you do is:
SELECT * FROM users
WHERE ( ( username = '[email protected]' ) AND ( password = '1234' ) );
But what if you need only the id of a record with username = [email protected] and password = 1234? then you do:
SELECT id FROM users
WHERE ( ( username = '[email protected]' ) AND ( password = '1234' ) );
Now to get to your question, as others before me answered you can use the IN clause:
SELECT * FROM users
WHERE ( id IN (1,2,..,n) );
or, if you wish to limit to a list of records between id 20 and id 40, then you can easily write:
SELECT * FROM users
WHERE ( ( id >= 20 ) AND ( id <= 40 ) );
I hope this gives a better understanding.
Try this :
$('select[name^="salesrep"] option[value="Bruce Jones"]').attr("selected","selected");
Just replace option[value="Bruce Jones"]
by option[value=result[0]]
And before selecting a new option, you might want to "unselect" the previous :
$('select[name^="salesrep"] option:selected').attr("selected",null);
You may want to read this too : jQuery get specific option tag text
Edit: Using jQuery Mobile, this link may provide a good solution : jquery mobile - set select/option values
A BLOB
can be 65535 bytes (64 KB) maximum.
If you need more consider using:
a MEDIUMBLOB
for 16777215 bytes (16 MB)
a LONGBLOB
for 4294967295 bytes (4 GB).
See Storage Requirements for String Types for more info.
I see that the autoload functions only receive the "full" classname - with all the namespaces preceeding it - in the following two cases:
[a] $a = new The\Full\Namespace\CoolClass();
[b] use The\Full\Namespace as SomeNamespace; (at the top of your source file) followed by $a = new SomeNamespace\CoolClass();
I see that the autoload functions DO NOT receive the full classname in the following case:
[c] use The\Full\Namespace; (at the top of your source file) followed by $a = new CoolClass();
UPDATE: [c] is a mistake and isn't how namespaces work anyway. I can report that, instead of [c], the following two cases also work well:
[d] use The\Full\Namespace; (at the top of your source file) followed by $a = new Namespace\CoolClass();
[e] use The\Full\Namespace\CoolClass; (at the top of your source file) followed by $a = new CoolClass();
Hope this helps.
You can use the not
function rather than the :not
selector:
$(".content a").not(this).hide("slow")
Did you consider using Apache Commons Net ? Since 3.3, just one jar (and you can depend on it using gradle or maven) and you're done : http://blog.dahanne.net/2013/06/17/sending-a-mail-in-java-and-android-with-apache-commons-net/