Swift 4/3
You can use this solution beneath. It works on UIBezierPaths which are lighter than layers, causing quick startup times. It is easy to use, see instructions beneath.
class ResizeBorderView: UIView {
var color = UIColor.white
var lineWidth: CGFloat = 1
var edges = [UIRectEdge](){
didSet {
setNeedsDisplay()
}
}
override func draw(_ rect: CGRect) {
if edges.contains(.top) || edges.contains(.all){
let path = UIBezierPath()
path.lineWidth = lineWidth
color.setStroke()
UIColor.blue.setFill()
path.move(to: CGPoint(x: 0, y: 0 + lineWidth / 2))
path.addLine(to: CGPoint(x: self.bounds.width, y: 0 + lineWidth / 2))
path.stroke()
}
if edges.contains(.bottom) || edges.contains(.all){
let path = UIBezierPath()
path.lineWidth = lineWidth
color.setStroke()
UIColor.blue.setFill()
path.move(to: CGPoint(x: 0, y: self.bounds.height - lineWidth / 2))
path.addLine(to: CGPoint(x: self.bounds.width, y: self.bounds.height - lineWidth / 2))
path.stroke()
}
if edges.contains(.left) || edges.contains(.all){
let path = UIBezierPath()
path.lineWidth = lineWidth
color.setStroke()
UIColor.blue.setFill()
path.move(to: CGPoint(x: 0 + lineWidth / 2, y: 0))
path.addLine(to: CGPoint(x: 0 + lineWidth / 2, y: self.bounds.height))
path.stroke()
}
if edges.contains(.right) || edges.contains(.all){
let path = UIBezierPath()
path.lineWidth = lineWidth
color.setStroke()
UIColor.blue.setFill()
path.move(to: CGPoint(x: self.bounds.width - lineWidth / 2, y: 0))
path.addLine(to: CGPoint(x: self.bounds.width - lineWidth / 2, y: self.bounds.height))
path.stroke()
}
}
}
For a similar post a long time ago there seems to be issues with making table visibility hidden.
You have two options, one is to use the display:none
attribute.
Or two wrap the table in a div and make the div hidden.
<div id="wrapper" style="visibility:hidden">
<table>
<tr>
<td>
Content
</td>
</tr>
</table>
</div>
I 'tripped' across my solution after 2 days...XCODE 4.0
I've just upgraded to XCode 4.0 and this code signing issue has been a stunning frustrastion. And I've been doing this for over a year various versions...so if you are having problems, you are not alone.
I have recertified, reprovisioned, drag and dropped, manually edit the project file, deleted PROVISIIONING paths, stopped/started XCODE, stopped started keychain, checked spelling, checked bundle ID's, check my birth certificate, the phase of the moon, and taught my dog morse code...none of it worked!!!!
--bottom line---
If the Debug mode was not the same, it failed the Distribution mode as well...go figure. Hope that helps someone...
Figure: This shows how to find the relevant settings in XCode 4.5.
One way to do it is list the log for your branch and count the lines.
git log <branch_name> --oneline | wc -l
As drew_w said, you can find a good example here.
HTML
<div id="wrapper">
<div id="sidebar-wrapper">
<ul class="sidebar-nav">
<li class="sidebar-brand"><a href="#">Home</a></li>
<li><a href="#">Another link</a></li>
<li><a href="#">Next link</a></li>
<li><a href="#">Last link</a></li>
</ul>
</div>
<div id="page-content-wrapper">
<div class="page-content">
<div class="container">
<div class="row">
<div class="col-md-12">
<!-- content of page -->
</div>
</div>
</div>
</div>
</div>
</div>
CSS
#wrapper {
padding-left: 250px;
transition: all 0.4s ease 0s;
}
#sidebar-wrapper {
margin-left: -250px;
left: 250px;
width: 250px;
background: #CCC;
position: fixed;
height: 100%;
overflow-y: auto;
z-index: 1000;
transition: all 0.4s ease 0s;
}
#page-content-wrapper {
width: 100%;
}
.sidebar-nav {
position: absolute;
top: 0;
width: 250px;
list-style: none;
margin: 0;
padding: 0;
}
@media (max-width:767px) {
#wrapper {
padding-left: 0;
}
#sidebar-wrapper {
left: 0;
}
#wrapper.active {
position: relative;
left: 250px;
}
#wrapper.active #sidebar-wrapper {
left: 250px;
width: 250px;
transition: all 0.4s ease 0s;
}
}
'O' stands for object.
#Loading a csv file as a dataframe
import pandas as pd
train_df = pd.read_csv('train.csv')
col_name = 'Name of Employee'
#Checking the datatype of column name
train_df[col_name].dtype
#Instead try printing the same thing
print train_df[col_name].dtype
The first line returns: dtype('O')
The line with the print statement returns the following: object
one way is to convert it to list
>>> b=list(mytuple)
>>> b.append("something")
>>> a=tuple(b)
I found this https://typescriptbcl.codeplex.com/SourceControl/latest
here is the Guid version they have in case the link does not work later.
module System {
export class Guid {
constructor (public guid: string) {
this._guid = guid;
}
private _guid: string;
public ToString(): string {
return this.guid;
}
// Static member
static MakeNew(): Guid {
var result: string;
var i: string;
var j: number;
result = "";
for (j = 0; j < 32; j++) {
if (j == 8 || j == 12 || j == 16 || j == 20)
result = result + '-';
i = Math.floor(Math.random() * 16).toString(16).toUpperCase();
result = result + i;
}
return new Guid(result);
}
}
}
you can simply do like that in the html part:
<span>Heading Text</span>
and in the css you can make it as an h1 block using display:
span{
display:block;
font-size:20px;
}
you will get it as a h1 without bold ,
if you want it bold just add this to the css:
font-weight:bold;
Xcode 10
cross-project references
[About] Explicit dependency
[About] //Xcode 10
Build Phases -> Target Dependencies -> + Add items
//Xcode 11
Build Phases -> Dependencies -> + Add items
In Choose items to add:
dialog you will see only targets from your project and the sub-project
MySQL unique and primary keys serve to identify rows. There can be only one Primary key in a table but one or more unique keys. Key is just index.
for more details you can check http://www.geeksww.com/tutorials/database_management_systems/mysql/tips_and_tricks/mysql_primary_key_vs_unique_key_constraints.php
to convert mysql to mssql try this and see http://gathadams.com/2008/02/07/convert-mysql-to-ms-sql-server/
Ross, you can use Arrays.copyof() or Arrays.copyOfRange() too.
Integer[] integerArray = Arrays.copyOf(a, a.length, Integer[].class);
Integer[] integerArray = Arrays.copyOfRange(a, 0, a.length, Integer[].class);
Here the reason to hitting an ClassCastException
is you can't treat an array of Integer
as an array of Object
. Integer[]
is a subtype of Object[]
but Object[]
is not a Integer[]
.
And the following also will not give an ClassCastException
.
Object[] a = new Integer[1];
Integer b=1;
a[0]=b;
Integer[] c = (Integer[]) a;
Check out JSON2HTML http://json2html.com/ plugin for jQuery. It allows you to specify a transform that would convert your JSON object to HTML template. Use builder on http://json2html.com/ to get json transform object for any desired html template. In your case, it would be a table with row having following transform.
Example:
var transform = {"tag":"table", "children":[
{"tag":"tbody","children":[
{"tag":"tr","children":[
{"tag":"td","html":"${name}"},
{"tag":"td","html":"${age}"}
]}
]}
]};
var data = [
{'name':'Bob','age':40},
{'name':'Frank','age':15},
{'name':'Bill','age':65},
{'name':'Robert','age':24}
];
$('#target_div').html(json2html.transform(data,transform));
$('#column-left form').hide();
$('.show-search').click(function() {
$('#column-left form').stop(true, true).slideToggle(300); //this will slide but not hide that's why
$('#column-left form').hide();
if(!($('#column-left form').is(":visible"))) {
$("#offers").show();
} else {
$('#offers').hide();
}
});
You can pass via GET. So if you want to pass the value foobar
from PageA.php
to PageB.php
, call it as PageB.php?value=foobar
.
In PageB.php, you can access it this way:
$value = $_GET['value'];
you can try this way
One way to speed things up is to explicitly perform multiple inserts or copy's within a transaction (say 1000). Postgres's default behavior is to commit after each statement, so by batching the commits, you can avoid some overhead. As the guide in Daniel's answer says, you may have to disable autocommit for this to work. Also note the comment at the bottom that suggests increasing the size of the wal_buffers to 16 MB may also help.
//JS_x000D_
//First Solution_x000D_
moment(myDate)_x000D_
_x000D_
//Second Solution_x000D_
moment(myDate).format('YYYY-MM-DD HH:mm:ss')_x000D_
//or_x000D_
moment(myDate).format('YYYY-MM-DD')_x000D_
_x000D_
//Third Solution_x000D_
myDate = $filter('date')(myDate, "dd/MM/yyyy");
_x000D_
<!--HTML-->_x000D_
<!-- First Solution -->_x000D_
{{myDate | date:'M/d/yyyy HH:mm:ss'}}_x000D_
<!-- or -->_x000D_
{{myDate | date:'medium'}}_x000D_
_x000D_
<!-- Second Solution -->_x000D_
{{myDate}}_x000D_
_x000D_
<!-- Third Solution -->_x000D_
{{myDate}}
_x000D_
If you know that certain characters are not used, you can translate "\t" into something else. cat my_file | tr "\t" "," | sed "s/(.*)/,\1/"
Vue.set(object, prop, value)
For vuex you will want to do Vue.set(state.object, key, value)
So just for others who come to this question. It appears at some point in Vue 2.* they removed this.items.$set(index, val)
in favor of this.$set(this.items, index, val)
.
Splice is still available and here is a link to array mutation methods available in vue link.
In raw Javascript, the best that you can do is using the few asynchronous calls (xmlhttprequest), but that's not really threading and very limited. Google Gears adds a number of APIs to the browser, some of which can be used for threading support.
Just set an onload function on the body:
<body onload="init()">
Then do something like this in javascript:
function init() {
var someimage = 'changableBackgroudImage';
document.body.style.background = 'url(img/'+someimage+'.png) no-repeat center center'
}
You can change the 'someimage' variable to whatever you want depending on some conditions, such as the time of day or something, and that image will be set as the background image.
You have at least two issues in your code:
ng-change="getScoreData(Score)
Angular doesn't see getScoreData
method that refers to defined service
getScoreData: function (Score, callback)
We don't need to use callback since GET
returns promise. Use then
instead.
Here is a working example (I used random address only for simulation):
HTML
<select ng-model="score"
ng-change="getScoreData(score)"
ng-options="score as score.name for score in scores"></select>
<pre>{{ScoreData|json}}</pre>
JS
var fessmodule = angular.module('myModule', ['ngResource']);
fessmodule.controller('fessCntrl', function($scope, ScoreDataService) {
$scope.scores = [{
name: 'Bukit Batok Street 1',
URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, 153 Bukit Batok Street 1&sensor=true'
}, {
name: 'London 8',
URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, London 8&sensor=true'
}];
$scope.getScoreData = function(score) {
ScoreDataService.getScoreData(score).then(function(result) {
$scope.ScoreData = result;
}, function(result) {
alert("Error: No data returned");
});
};
});
fessmodule.$inject = ['$scope', 'ScoreDataService'];
fessmodule.factory('ScoreDataService', ['$http', '$q', function($http) {
var factory = {
getScoreData: function(score) {
console.log(score);
var data = $http({
method: 'GET',
url: score.URL
});
return data;
}
}
return factory;
}]);
Demo Fiddle
You're missing your database name:
$sql = "SELECT ID, ListStID, ListEmail, Title FROM ".$entry_database." WHERE ID = ". $ReqBookID .";
And make sure that $entry_database isn't null or empty:
var_dump($entry_database);
Also notice that you don't need to have $ReqBookID in '' as if it's an Int.
On Ubuntu, early 2018, there is no python3.6-tk
on ubuntu's (xenial/16.04) normal distributions, so even if you have earlier versions of python-tk
this won't work.
My solution was to use set everything up with python 3.5
:
sudo apt install python3.5-tk
virtualenv --python=`which python3.5` python-env
source python-env/bin/activate
pip install -r requirements.txt
And now matplotlib
can find tkinter
.
EDIT:
I just needed 3.6 afterall, and the trick was to:
sudo apt install tk-dev
and then rebuild python3.6, after tk-dev
, eg:
./configure
make
make install
$ string="hello-world"
$ prefix="hell"
$ suffix="ld"
$ #remove "hell" from "hello-world" if "hell" is found at the beginning.
$ prefix_removed_string=${string/#$prefix}
$ #remove "ld" from "o-world" if "ld" is found at the end.
$ suffix_removed_String=${prefix_removed_string/%$suffix}
$ echo $suffix_removed_String
o-wor
#$prefix : adding # makes sure that substring "hell" is removed only if it is found in beginning. %$suffix : adding % makes sure that substring "ld" is removed only if it is found in end.
Without these, the substrings "hell" and "ld" will get removed everywhere, even it is found in the middle.
use php implode()
or serialize()
You can have multiple <context:property-placeholder />
elements instead of explicitly declaring multiple PropertiesPlaceholderConfigurer beans.
If you'd like to use dynamic mapping, and don't want to clutter up your model with attributes, this approach worked for me
Usage:
var settings = new JsonSerializerSettings();
settings.DateFormatString = "YYYY-MM-DD";
settings.ContractResolver = new CustomContractResolver();
this.DataContext = JsonConvert.DeserializeObject<CountResponse>(jsonString, settings);
Logic:
public class CustomContractResolver : DefaultContractResolver
{
private Dictionary<string, string> PropertyMappings { get; set; }
public CustomContractResolver()
{
this.PropertyMappings = new Dictionary<string, string>
{
{"Meta", "meta"},
{"LastUpdated", "last_updated"},
{"Disclaimer", "disclaimer"},
{"License", "license"},
{"CountResults", "results"},
{"Term", "term"},
{"Count", "count"},
};
}
protected override string ResolvePropertyName(string propertyName)
{
string resolvedName = null;
var resolved = this.PropertyMappings.TryGetValue(propertyName, out resolvedName);
return (resolved) ? resolvedName : base.ResolvePropertyName(propertyName);
}
}
I had a similar issue, where I had one div holding the image, and one div holding the text. The reason mine wasn't working, was that the div holding the image had display: inline-block
while the div holding the text had display: inline
.
I changed it to both be display: inline
and it worked.
Here's a solution for a basic header section with a logo, title and tagline:
HTML
<div class="site-branding">
<div class="site-branding-logo">
<img src="add/Your/URI/Here" alt="what Is The Image About?" />
</div>
</div>
<div class="site-branding-text">
<h1 id="site-title">Site Title</h1>
<h2 id="site-tagline">Site Tagline</h2>
</div>
CSS
div.site-branding { /* Position Logo and Text */
display: inline-block;
vertical-align: middle;
}
div.site-branding-logo { /* Position logo within site-branding */
display: inline;
vertical-align: middle;
}
div.site-branding-text { /* Position text within site-branding */
display: inline;
width: 350px;
margin: auto 0;
vertical-align: middle;
}
div.site-branding-title { /* Position title within text */
display: inline;
}
div.site-branding-tagline { /* Position tagline within text */
display: block;
}
Why not do string suppression with triple quotes:
>>> s = """my string with "some" double quotes"""
>>> print s
my string with "some" double quotes
Here is a working example: http://jsfiddle.net/rVBzt/ (using jQuery)
<img id="tiger" src="https://twimg0-a.akamaihd.net/profile_images/2642324404/46d743534606515238a9a12cfb4b264a.jpeg">
<a id="toggle">click to toggle</a>
img {display: none;}
a {cursor: pointer; color: blue;}
$('#toggle').click(function() {
$('#tiger').toggle();
});
Why for
? What do you want to iterate? Try this.
call :cpy pc-name-1
call :cpy pc-name-2
...
:cpy
net use \\%1\{destfolder} {password} /user:{username}
copy {file} \\%1\{destfolder}
goto :EOF
First Create Bitmap Image
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.image);
now set bitmap in Notification Builder Icon....
Notification.Builder.setLargeIcon(bmp);
Looks like you have a bad practice here but not where you think.
Catching an IllegalArgumentException
to rethrow another RuntimeException
with a clearer message might look like a good idea but it is not. Because it means you care about messages in your exceptions.
If you care about messages in your exceptions, then it means that your user is somehow seeing your exceptions. This is bad.
If you want to provide an explicit error message to your user, you should check the validity of the enum value when parsing user input and send the appropriate error message in the response if user input is incorrect.
Something like:
// This code uses pure fantasy, you are warned!
class MyApi
{
// Return the 24-hour from a 12-hour and AM/PM
void getHour24(Request request, Response response)
{
// validate user input
int nTime12 = 1;
try
{
nTime12 = Integer.parseInt(request.getParam("hour12"));
if( nTime12 <= 0 || nTime12 > 12 )
{
throw new NumberFormatException();
}
}
catch( NumberFormatException e )
{
response.setCode(400); // Bad request
response.setContent("time12 must be an integer between 1 and 12");
return;
}
AMPM pm = null;
try
{
pm = AMPM.lookup(request.getParam("pm"));
}
catch( IllegalArgumentException e )
{
response.setCode(400); // Bad request
response.setContent("pm must be one of " + AMPM.values());
return;
}
response.setCode(200);
switch( pm )
{
case AM:
response.setContent(nTime12);
break;
case PM:
response.setContent(nTime12 + 12);
break;
}
return;
}
}
Yes, it is possible to write and call a function nested in another function.
Try this:
function A(){
B(); //call should be B();
function B(){
}
}
Most people do not read the comments so to summarize (Thanks to @Industrial-antidepressant and @wrecker):
As suggested in a bug ticket you should try the following:
android-studio/plugins/gradle/lib
gradle-*-1.8
filesIt should work. Make sure to star the above bug ticket to get informed.
Little tip: Try the new compile setting Settings -> Compiler -> Gradle and activate the third in-process build for a speed up. Depending on your project setting you might want to select the first one as well. With that my project build time reduced to 2-4 seconds (before 20+ seconds).
The difference between
import java.util.*;
and
import java.util.*;
import java.util.List;
import java.util.Arrays;
becomes apparent when the code refers to some other List
or Arrays
(for example, in the same package, or also imported generally). In the first case, the compiler will assume that the Arrays
declared in the same package is the one to use, in the latter, since it is declared specifically, the more specific java.util.Arrays
will be used.
In that case you should use ListBox
control instead of dropdown and Set the SelectionMode
property to Multiple
<asp:ListBox runat="server" SelectionMode="Multiple" >
<asp:ListItem Text="test1"></asp:ListItem>
<asp:ListItem Text="test2"></asp:ListItem>
<asp:ListItem Text="test3"></asp:ListItem>
</asp:ListBox>
MODERN REVISION: you also now need to fix it by changing the little known ''security.limit_extensions' in php-fpm doing this. You will probably already know the well documented mechanism of changing apache to AddHandler/AddType I will not go into that here.
YOU MUST find out where php-fpm/conf is in your set up. I did it by doing this
# grep -rnw '/etc/' -e 'security.limit_extensions'
I got this back
'/etc/php-fpm.d/www.conf:387:;security.limit_extensions = .php .php3 .php4 .php5 .php7'
go to this file, edit it and MAKE SURE YOU REALISE IT IS COMMENTED OUT
EG: change it from ';security.limit_extensions = .php .php3 .php4 .php5 .php7'
<- NB: note the ";"
- this line is actually DISABLED by default - and you do not need all the nonsense extensions, in fact they are probably dangerous.. change it to 'security.limit_extensions = .php .htm'
<- note the semi colon is now removed. then restart apache/(or nginx) and restart php-fpm # service php-fpm restart
# service httpd restart
gem uninstall pg
On OS X with Homebrew:
gem install pg -- --with-pg-config=/usr/local/bin/pg_config
Truely platform-indpendent would be also this R-onliner
readlink(){ RScript -e "cat(normalizePath(commandArgs(T)[1]))" "$1";}
To actually mimic readlink -f <path>
, $2 instead of $1 would need to be used.
This worked for me
HTML CODE
<span class="number-count">841</span>
jQuery Code
$('.number-count').each(function () {
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
See http://adamalbrecht.com/2013/12/12/creating-a-simple-modal-dialog-directive-in-angular-js/ for a simple way of doing modal dialog with Angular and without needing bootstrap
Edit: I've since been using ng-dialog from http://likeastore.github.io/ngDialog which is flexible and doesn't have any dependencies.
KISS Answer:
document.getElementById('element').style.background = '#DD00DD';
I only had to change one line of the file config.inc.php
located in C:\wamp\apps\phpmyadmin4.1.14
.
Put the right password here ...
$cfg['Servers'][$i]['password'] = 'Put_Password_Here';
Getting first and last elements in an array in Java
int[] a = new int[]{1, 8, 5, 9, 4};
First Element: a[0]
Last Element: a[a.length-1]
You need to Open the SQL Developer first and then click on File option and browse to the location where your .sql is placed. Once you are at the location where file is placed double click on it, this will get the file open in SQL Developer. Now select all of the content of file (CTRL + A) and press F9 key. Just make sure there is a commit statement at the end of the .sql script so that the changes are persisted in the database
Here is what a Microsoft support page says about this: https://support.microsoft.com/en-us/help/944886/error-message-when-you-use-the-response-binarywrite-method-in-iis-6-an.
But it’s easier in the GUI:
Or about the best module I have found http://pypi.python.org/pypi/colorama
i agree with you about alternative solutions which you mentioned above
1. Use POST instead of GET;
2. Transform the List into a JSON string and pass it to the service.
and its true that you can't add List
to MultiValuedMap
because of its impl class MultivaluedMapImpl
have capability to accept String Key and String Value. which is shown in following figure
still you want to do that things than try following code.
Controller Class
package net.yogesh.test;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import com.google.gson.Gson;
@Path("test")
public class TestController {
@Path("testMethod")
@GET
@Produces("application/text")
public String save(
@QueryParam("list") List<String> list) {
return new Gson().toJson(list) ;
}
}
Client Class
package net.yogesh.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.ws.rs.core.MultivaluedMap;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.core.util.MultivaluedMapImpl;
public class Client {
public static void main(String[] args) {
String op = doGet("http://localhost:8080/JerseyTest/rest/test/testMethod");
System.out.println(op);
}
private static String doGet(String url){
List<String> list = new ArrayList<String>();
list = Arrays.asList(new String[]{"string1,string2,string3"});
MultivaluedMap<String, String> params = new MultivaluedMapImpl();
String lst = (list.toString()).substring(1, list.toString().length()-1);
params.add("list", lst);
ClientConfig config = new DefaultClientConfig();
com.sun.jersey.api.client.Client client = com.sun.jersey.api.client.Client.create(config);
WebResource resource = client.resource(url);
ClientResponse response = resource.queryParams(params).type("application/x-www-form-urlencoded").get(ClientResponse.class);
String en = response.getEntity(String.class);
return en;
}
}
hope this'll help you.
-webkit-padding-start: 0;
will remove padding added by webkit engine
Find below a simple example illustrating how to get class and method names.
public static void main(String args[])
{
callMe();
}
void callMe()
{
try
{
throw new Exception("Who called me?");
}
catch( Exception e )
{
System.out.println( "I was called by " +
e.getStackTrace()[1].getClassName() +
"." +
e.getStackTrace()[1].getMethodName() +
"()!" );
}
}
e has getClassName()
, getFileName()
, getLineNumber()
and getMethodName()
...
This worked for me: brew uninstall openssl; brew uninstall openssl; brew install https://github.com/tebelorg/Tump/releases/download/v1.0.0/openssl.rb
Suggested in this post: https://github.com/kelaberetiv/TagUI/issues/635#issuecomment-560139279
"How to: Pad a Number with Leading Zeros" http://msdn.microsoft.com/en-us/library/dd260048.aspx
Firstly run this query
SHOW VARIABLES LIKE '%char%';
You have character_set_server='latin1'
If so,go into your config file,my.cnf and add or uncomment these lines:
character-set-server = utf8
collation-server = utf8_unicode_ci
Restart the server. Yes late to the party,just encountered the same issue.
Found the simple official way after wading through the walls of text above that would make you think there is none.
Create a complete bundle with:
$ git bundle create <filename> --all
Restore it with:
$ git clone <filename> <folder>
This operation is atomic AFAIK. Check official docs for the gritty details.
Regarding "zip": git bundles are compressed and surprisingly small compared to the .git folder size.
This should work...
var displayDate = new Date().toLocaleDateString();
alert(displayDate);
But I suspect you are trying it on something else, for example:
var displayDate = Date.now.toLocaleDateString(); // No!
alert(displayDate);
UPDATE:
You'll also want to goto Security -> Server Roles
, and for public
check the permissions for TSQL Default TCP/TSQL Default VIA/TSQL Local Machine/TSQL Named Pipes
and remove the connect
permission
To iterate through all elements
XDocument xdoc = XDocument.Load("input.xml");
foreach (XElement element in xdoc.Descendants())
{
Console.WriteLine(element.Name);
}
PRN solution works only for simple data in the cells, for me it cuts only first 6 signs from 200 characters cell.
These are the main file formats in Excel 2007-2016, Note: In Excel for the Mac the values are +1
51 = xlOpenXMLWorkbook (without macro's in 2007-2016, xlsx)
52 = xlOpenXMLWorkbookMacroEnabled (with or without macro's in 2007-2016, xlsm)
50 = xlExcel12 (Excel Binary Workbook in 2007-2016 with or without macro's, xlsb)
56 = xlExcel8 (97-2003 format in Excel 2007-2016, xls)
From XlFileFormat FileFormat Property
Keep in mind others FileFormatNumbers for SaveAs method:
FileExtStr = ".csv": FileFormatNum = 6
FileExtStr = ".txt": FileFormatNum = -4158
FileExtStr = ".prn": FileFormatNum = 36
A more "precise" calculation. That is, the number of week/month/quarter/year for a non-complete week/month/quarter/year is the fraction of calendar days in that week/month/quarter/year. For example, the number of months between 2016-02-22 and 2016-03-31 is 8/29 + 31/31 = 1.27586
explanation inline with code
#' Calculate precise number of periods between 2 dates
#'
#' @details The number of week/month/quarter/year for a non-complete week/month/quarter/year
#' is the fraction of calendar days in that week/month/quarter/year.
#' For example, the number of months between 2016-02-22 and 2016-03-31
#' is 8/29 + 31/31 = 1.27586
#'
#' @param startdate start Date of the interval
#' @param enddate end Date of the interval
#' @param period character. It must be one of 'day', 'week', 'month', 'quarter' and 'year'
#'
#' @examples
#' identical(numPeriods(as.Date("2016-02-15"), as.Date("2016-03-31"), "month"), 15/29 + 1)
#' identical(numPeriods(as.Date("2016-02-15"), as.Date("2016-03-31"), "quarter"), (15 + 31)/(31 + 29 + 31))
#' identical(numPeriods(as.Date("2016-02-15"), as.Date("2016-03-31"), "year"), (15 + 31)/366)
#'
#' @return exact number of periods between
#'
numPeriods <- function(startdate, enddate, period) {
numdays <- as.numeric(enddate - startdate) + 1
if (grepl("day", period, ignore.case=TRUE)) {
return(numdays)
} else if (grepl("week", period, ignore.case=TRUE)) {
return(numdays / 7)
}
#create a sequence of dates between start and end dates
effDaysinBins <- cut(seq(startdate, enddate, by="1 day"), period)
#use the earliest start date of the previous bins and create a breaks of periodic dates with
#user's period interval
intervals <- seq(from=as.Date(min(levels(effDaysinBins)), "%Y-%m-%d"),
by=paste("1",period),
length.out=length(levels(effDaysinBins))+1)
#create a sequence of dates between the earliest interval date and last date of the interval
#that contains the enddate
allDays <- seq(from=intervals[1],
to=intervals[intervals > enddate][1] - 1,
by="1 day")
#bin all days in the whole period using previous breaks
allDaysInBins <- cut(allDays, intervals)
#calculate ratio of effective days to all days in whole period
sum( tabulate(effDaysinBins) / tabulate(allDaysInBins) )
} #numPeriods
Please let me know if you find more boundary cases where the above solution does not work.
I personally like the solution using the parser
module, which is the second Answer to this question and is beautiful, as you don't have to construct any string literals to get it working. BUT, one downside is that it is 90% slower than the accepted answer with strptime
.
from dateutil import parser
from datetime import datetime
import timeit
def dt():
dt = parser.parse("Jun 1 2005 1:33PM")
def strptime():
datetime_object = datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p')
print(timeit.timeit(stmt=dt, number=10**5))
print(timeit.timeit(stmt=strptime, number=10**5))
>10.70296801342902
>1.3627995655316933
As long as you are not doing this a million times over and over again, I still think the parser
method is more convenient and will handle most of the time formats automatically.
Following is my proposed solution.
A) Following is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="schneider.carouseladventure.MainActivity">
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/viewpager"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<RelativeLayout
android:id="@+id/viewPagerIndicator"
android:layout_width="match_parent"
android:layout_height="55dp"
android:layout_alignParentBottom="true"
android:layout_marginTop="5dp"
android:gravity="center">
<LinearLayout
android:id="@+id/viewPagerCountDots"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:gravity="center"
android:orientation="horizontal" />
</RelativeLayout>
</RelativeLayout>
B) pager_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/imageView" />
</LinearLayout>
C) MainActivity.java
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener, View.OnClickListener {
int[] mResources = {R.drawable.nature1, R.drawable.nature2, R.drawable.nature3, R.drawable.nature4,
R.drawable.nature5, R.drawable.nature6
};
ViewPager mViewPager;
private CustomPagerAdapter mAdapter;
private LinearLayout pager_indicator;
private int dotsCount;
private ImageView[] dots;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.viewpager);
pager_indicator = (LinearLayout) findViewById(R.id.viewPagerCountDots);
mAdapter = new CustomPagerAdapter(this, mResources);
mViewPager.setAdapter(mAdapter);
mViewPager.setCurrentItem(0);
mViewPager.setOnPageChangeListener(this);
setPageViewIndicator();
}
private void setPageViewIndicator() {
Log.d("###setPageViewIndicator", " : called");
dotsCount = mAdapter.getCount();
dots = new ImageView[dotsCount];
for (int i = 0; i < dotsCount; i++) {
dots[i] = new ImageView(this);
dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
params.setMargins(4, 0, 4, 0);
final int presentPosition = i;
dots[presentPosition].setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
mViewPager.setCurrentItem(presentPosition);
return true;
}
});
pager_indicator.addView(dots[i], params);
}
dots[0].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
}
@Override
public void onClick(View v) {
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
Log.d("###onPageSelected, pos ", String.valueOf(position));
for (int i = 0; i < dotsCount; i++) {
dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
}
dots[position].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
if (position + 1 == dotsCount) {
} else {
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
}
D) CustomPagerAdapter.java
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class CustomPagerAdapter extends PagerAdapter {
private Context mContext;
LayoutInflater mLayoutInflater;
private int[] mResources;
public CustomPagerAdapter(Context context, int[] resources) {
mContext = context;
mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mResources = resources;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
View itemView = mLayoutInflater.inflate(R.layout.pager_item,container,false);
ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView);
imageView.setImageResource(mResources[position]);
/* LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(950, 950);
imageView.setLayoutParams(layoutParams);*/
container.addView(itemView);
return itemView;
}
@Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
@Override
public int getCount() {
return mResources.length;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
E) selecteditem_dot.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval" android:useLevel="true"
android:dither="true">
<size android:height="12dip" android:width="12dip"/>
<solid android:color="#7e7e7e"/>
</shape>
F) nonselecteditem_dot.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval" android:useLevel="true"
android:dither="true">
<size android:height="12dip" android:width="12dip"/>
<solid android:color="#d3d3d3"/>
</shape>
Easy steps to Integrate ckeditor with php pages
step 1 : download the ckeditor.zip file
step 2 : paste ckeditor.zip file on root directory of the site or you can paste it where the files are (i did this one )
step 3 : extract the ckeditor.zip file
step 4 : open the desired php page you want to integrate with here page1.php
step 5 : add some javascript first below, this is to call elements of ckeditor and styling and css without this you will only a blank textarea
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
And if you are using in other sites, then use relative links for that here is one below
<script type="text/javascript" src="somedirectory/ckeditor/ckeditor.js"></script>
step 6 : now!, you need to call the work code of ckeditor on your page page1.php below is how you call it
<?php
// Make sure you are using a correct path here.
include_once 'ckeditor/ckeditor.php';
$ckeditor = new CKEditor();
$ckeditor->basePath = '/ckeditor/';
$ckeditor->config['filebrowserBrowseUrl'] = '/ckfinder/ckfinder.html';
$ckeditor->config['filebrowserImageBrowseUrl'] = '/ckfinder/ckfinder.html?type=Images';
$ckeditor->config['filebrowserFlashBrowseUrl'] = '/ckfinder/ckfinder.html?type=Flash';
$ckeditor->config['filebrowserUploadUrl'] = '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files';
$ckeditor->config['filebrowserImageUploadUrl'] = '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images';
$ckeditor->config['filebrowserFlashUploadUrl'] = '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash';
$ckeditor->editor('CKEditor1');
?>
step 7 : what ever you name you want, you can name to it ckeditor by changing the step 6 code last line
$ckeditor->editor('mycustomname');
step 8 : Open-up the page1.php, see it, use it, share it and Enjoy because we all love Open Source.
Thanks
You can use this Function if you have some variable in the SSIS.
Package pkg;
Microsoft.SqlServer.Dts.Runtime.Application app;
DTSExecResult pkgResults;
Variables vars;
app = new Microsoft.SqlServer.Dts.Runtime.Application();
pkg = app.LoadPackage(" Location of your SSIS package", null);
vars = pkg.Variables;
// your variables
vars["somevariable1"].Value = "yourvariable1";
vars["somevariable2"].Value = "yourvariable2";
pkgResults = pkg.Execute(null, vars, null, null, null);
if (pkgResults == DTSExecResult.Success)
{
Console.WriteLine("Package ran successfully");
}
else
{
Console.WriteLine("Package failed");
}
I did a small experiment of running a method "1,000,000,000 (one billion)" times with "Parallel.For" and one with "Task" objects.
I measured the processor time and found Parallel more efficient. Parallel.For divides your task in to small work items and executes them on all the cores parallely in a optimal way. While creating lot of task objects ( FYI TPL will use thread pooling internally) will move every execution on each task creating more stress in the box which is evident from the experiment below.
I have also created a small video which explains basic TPL and also demonstrated how Parallel.For utilizes your core more efficiently http://www.youtube.com/watch?v=No7QqSc5cl8 as compared to normal tasks and threads.
Experiment 1
Parallel.For(0, 1000000000, x => Method1());
Experiment 2
for (int i = 0; i < 1000000000; i++)
{
Task o = new Task(Method1);
o.Start();
}
javac (.exe on Windows) binary path must be added into global PATH env. variable.
javac MyProgram.java
or with java (.exe on Windows)
java MyProgram.jar
I have implemented a tiny benchmark (please find the code on Gist) to evaluate the pandas' concat
and append
. I updated the code snippet and the results after the comment by ssk08
- thanks alot!
The benchmark ran on a Mac OS X 10.13 system with Python 3.6.2 and pandas 0.20.3.
+--------+---------------------------------+---------------------------------+ | | ignore_index=False | ignore_index=True | +--------+---------------------------------+---------------------------------+ | size | append | concat | append/concat | append | concat | append/concat | +--------+--------+--------+---------------+--------+--------+---------------+ | small | 0.4635 | 0.4891 | 94.77 % | 0.4056 | 0.3314 | 122.39 % | +--------+--------+--------+---------------+--------+--------+---------------+ | medium | 0.5532 | 0.6617 | 83.60 % | 0.3605 | 0.3521 | 102.37 % | +--------+--------+--------+---------------+--------+--------+---------------+ | large | 0.9558 | 0.9442 | 101.22 % | 0.6670 | 0.6749 | 98.84 % | +--------+--------+--------+---------------+--------+--------+---------------+
Using ignore_index=False
append
is slightly faster, with ignore_index=True
concat
is slightly faster.
tl;dr
No significant difference between concat
and append
.
At its simplest, the app.config is an XML file with many predefined configuration sections available and support for custom configuration sections. A "configuration section" is a snippet of XML with a schema meant to store some type of information.
Settings can be configured using built-in configuration sections such as connectionStrings
or appSettings
. You can add your own custom configuration sections; this is an advanced topic, but very powerful for building strongly-typed configuration files.
Web applications typically have a web.config, while Windows GUI/service applications have an app.config file.
Application-level config files inherit settings from global configuration files, e.g. the machine.config.
Connection strings have a predefined schema that you can use. Note that this small snippet is actually a valid app.config (or web.config) file:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="MyKey"
connectionString="Data Source=localhost;Initial Catalog=ABC;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
Once you have defined your app.config, you can read it in code using the ConfigurationManager class. Don't be intimidated by the verbose MSDN examples; it's actually quite simple.
string connectionString = ConfigurationManager.ConnectionStrings["MyKey"].ConnectionString;
Frequently changing the *.config files is usually not a good idea, but it sounds like you only want to perform one-time setup.
See: Change connection string & reload app.config at run time which describes how to update the connectionStrings
section of the *.config file at runtime.
Note that ideally you would perform such configuration changes from a simple installer.
Q: Suppose I manually change some <value>
in app.config, save it and then close it. Now when I go to my bin folder and launch the .exe file from here, why doesn't it reflect the applied changes?
A: When you compile an application, its app.config is copied to the bin directory1 with a name that matches your exe. For example, if your exe was named "test.exe", there should be a "text.exe.config" in your bin directory. You can change the configuration without a recompile, but you will need to edit the config file that was created at compile time, not the original app.config.
1: Note that web.config files are not moved, but instead stay in the same location at compile and deployment time. One exception to this is when a web.config is transformed.
New configuration options were introduced with .NET Core. The way that *.config files works does not appear to have changed, but developers are free to choose new, more flexible configuration paradigms.
In the action you can call:
this.Request.PhysicalPath
that returns the physical path in reference to the current controller. If you only need the root path call:
this.Request.PhysicalApplicationPath
AssertionError is an Unchecked Exception which rises explicitly by programmer or by API Developer to indicate that assert statement fails.
assert(x>10);
Output:
AssertionError
If x is not greater than 10 then you will get runtime exception saying AssertionError.
In a business application, i use the Open Source project on codeproject.com, CSVReader.
It works well, and has good performance. There is some benchmarking on the link i provided.
A simple example, copied from the project page:
using (CsvReader csv = new CsvReader(new StreamReader("data.csv"), true))
{
int fieldCount = csv.FieldCount;
string[] headers = csv.GetFieldHeaders();
while (csv.ReadNextRecord())
{
for (int i = 0; i < fieldCount; i++)
Console.Write(string.Format("{0} = {1};", headers[i], csv[i]));
Console.WriteLine();
}
}
As you can see, it's very easy to work with.
I have another solution:- Generating a signing key You can generate a private signing key using keytool. On Windows keytool must be run from C:\Program Files\Java\jdkx.x.x_x\bin.
$ keytool -genkey -v -keystore my-release-key.keystore -alias my-key-alias -keyalg RSA -keysize 2048 -validity 10000
Place the my-release-key.keystore file under the android/app directory in your project folder.
Edit the file android/app/build.gradle in your project folder and add the signing config,
android {
....
signingConfigs {
release {
storeFile file('my-release-key.keystore')
storePassword 'yourpassword'
keyAlias 'my-key-alias'
keyPassword 'yourpassword'
}
}}}
buildTypes {release {signingConfig signingConfigs.release}}
and run
gradlew assembleRelease
This will give you two files at android\app\build\outputs\apk app-release.apk and app-release-unsigned.apk now install the app-release.apk in your android device.
with GNU-grep you could just say
grep --context=10 ...
Once I have detected Android in the user agent, this is how I differentiate between tablet and smartphone browsers (this is using Python, but is similarly simple for other programming languages):
if ("Android" in agent):
if ("Mobile" in agent):
deviceType = "Phone"
else:
deviceType = "Tablet"
UPDATED: to reflect use of Chrome on Android, as per comments below.
If you really have issues related to efficiency of returning an integer from a process, you should probably avoid to call that process so many times that this return value becomes an issue.
If you are doing this (call a process so many times), you should find a way to put your logic directly inside the caller, or in a DLL file, without allocate a specific process for each call; the multiple process allocations bring you the relevant efficiency problem in this case.
In detail, if you only want to know if returning 0 is more or less efficient than returning 1, it could depend from the compiler in some cases, but generically, assuming they are read from the same source (local, field, constant, embedded in the code, function result, etc.) it requires exactly the same number of clock cycles.
Imagine you are developing a web-application and you decide to decouple the functionality from the presentation of the application, because it affords greater freedom.
You create an API and let others implement their own front-ends over it as well. What you just did here is implement an SOA methodology, i.e. using web-services.
Web services make functional building-blocks accessible over standard Internet protocols independent of platforms and programming languages.
So, you design an interchange mechanism between the back-end (web-service) that does the processing and generation of something useful, and the front-end (which consumes the data), which could be anything. (A web, mobile, or desktop application, or another web-service). The only limitation here is that the front-end and back-end must "speak" the same "language".
That's where SOAP and REST come in. They are standard ways you'd pick communicate with the web-service.
SOAP:
SOAP internally uses XML to send data back and forth. SOAP messages have rigid structure and the response XML then needs to be parsed. WSDL is a specification of what requests can be made, with which parameters, and what they will return. It is a complete specification of your API.
REST:
REST is a design concept.
The World Wide Web represents the largest implementation of a system conforming to the REST architectural style.
It isn't as rigid as SOAP. RESTful web-services use standard URIs and methods to make calls to the webservice. When you request a URI, it returns the representation of an object, that you can then perform operations upon (e.g. GET, PUT, POST, DELETE). You are not limited to picking XML to represent data, you could pick anything really (JSON included)
Flickr's REST API goes further and lets you return images as well.
JSON and XML, are functionally equivalent, and common choices. There are also RPC-based frameworks like GRPC based on Protobufs, and Apache Thrift that can be used for communication between the API producers and consumers. The most common format used by web APIs is JSON because of it is easy to use and parse in every language.
Like Andrew said /exclude
parameter of xcopy should be existing file that has list of excludes.
Documentation of xcopy says:
Using /exclude
List each string in a separate line in each file. If any of the listed strings match any part of the absolute path of the file to be copied, that file is then excluded from the copying process. For example, if you specify the string "\Obj\", you exclude all files underneath the Obj directory. If you specify the string ".obj", you exclude all files with the .obj extension.
Example:
xcopy c:\t1 c:\t2 /EXCLUDE:list-of-excluded-files.txt
and list-of-excluded-files.txt
should exist in current folder (otherwise pass full path), with listing of files/folders to exclude - one file/folder per line. In your case that would be:
exclusion.txt
The other answers did not help me as I only had client attached (the previous one that started the session was already detached).
To fix it I followed the answer here (I was not using xterm).
Which simply said:
resize
linux commandA lot of overly-complicated answers here, perhaps because this is not easy to find in the iOS documentation. JosephH had it right above:
[[view window] endEditing:YES];
create a package protected (assumes test class in same package) method in the sub class that calls the super class method and then call that method in your overridden sub class method. you can then set expectations on this method in your test through the use of the spy pattern. not pretty but certainly better than having to deal with all the expectation setting for the super method in your test
If you have reason to avoid the use of the datetime module, then this function will work.
Note: The change from the Julian to the Gregorian calendar is assumed to have occurred in 1582. If this is not true for your calendar of interest then change the line if year > 1582: accordingly.
def dow(year,month,day):
""" day of week, Sunday = 1, Saturday = 7
http://en.wikipedia.org/wiki/Zeller%27s_congruence """
m, q = month, day
if m == 1:
m = 13
year -= 1
elif m == 2:
m = 14
year -= 1
K = year % 100
J = year // 100
f = (q + int(13*(m + 1)/5.0) + K + int(K/4.0))
fg = f + int(J/4.0) - 2 * J
fj = f + 5 - J
if year > 1582:
h = fg % 7
else:
h = fj % 7
if h == 0:
h = 7
return h
Polymorphism is the ability of a class instance to behave as if it were an instance of another class in its inheritance tree, most often one of its ancestor classes. For example, in Java all classes inherit from Object. Therefore, you can create a variable of type Object and assign to it an instance of any class.
An override is a type of function which occurs in a class which inherits from another class. An override function "replaces" a function inherited from the base class, but does so in such a way that it is called even when an instance of its class is pretending to be a different type through polymorphism. Referring to the previous example, you could define your own class and override the toString() function. Because this function is inherited from Object, it will still be available if you copy an instance of this class into an Object-type variable. Normally, if you call toString() on your class while it is pretending to be an Object, the version of toString which will actually fire is the one defined on Object itself. However, because the function is an override, the definition of toString() from your class is used even when the class instance's true type is hidden behind polymorphism.
Overloading is the action of defining multiple methods with the same name, but with different parameters. It is unrelated to either overriding or polymorphism.
Here's a solution that also includes High(er)DPI (MDPI) devices > ~160 dots per inch like quite a few non-iOS Devices (f.e.: Google Nexus 7 2012):
.box {
background: url( 'img/box-bg.png' ) no-repeat top left;
width: 200px;
height: 200px;
}
@media only screen and ( -webkit-min-device-pixel-ratio: 1.3 ),
only screen and ( min--moz-device-pixel-ratio: 1.3 ),
only screen and ( -o-min-device-pixel-ratio: 2.6/2 ), /* returns 1.3, see Dev.Opera */
only screen and ( min-device-pixel-ratio: 1.3 ),
only screen and ( min-resolution: 124.8dpi ),
only screen and ( min-resolution: 1.3dppx ) {
.box {
background: url( 'img/[email protected]' ) no-repeat top left / 200px 200px;
}
}
As @3rror404 included in his edit after receiving feedback from the comments, there's a world beyond Webkit/iPhone. One thing that bugs me with most solutions around so far like the one referenced as source above at CSS-Tricks, is that this isn't taken fully into account.
The original source went already further.
As an example the Nexus 7 (2012) screen is a TVDPI screen with a weird device-pixel-ratio
of 1.325
. When loading the images with normal resolution they are upscaled via interpolation and therefore blurry. For me applying this rule in the media query to include those devices succeeded in best customer feedback.
ANSI compliant, without cursor
DECLARE @SQL national character varying(MAX)
SET @SQL= ''
SELECT @SQL= @SQL+ N'DROP PROCEDURE "' + REPLACE(SPECIFIC_SCHEMA, N'"', N'""') + N'"."' + REPLACE(SPECIFIC_NAME, N'"', N'""') + N'"; '
FROM INFORMATION_SCHEMA.ROUTINES
WHERE (1=1)
AND ROUTINE_TYPE = 'PROCEDURE'
AND ROUTINE_NAME NOT IN
(
'dt_adduserobject'
,'dt_droppropertiesbyid'
,'dt_dropuserobjectbyid'
,'dt_generateansiname'
,'dt_getobjwithprop'
,'dt_getobjwithprop_u'
,'dt_getpropertiesbyid'
,'dt_getpropertiesbyid_u'
,'dt_setpropertybyid'
,'dt_setpropertybyid_u'
,'dt_verstamp006'
,'dt_verstamp007'
,'sp_helpdiagrams'
,'sp_creatediagram'
,'sp_alterdiagram'
,'sp_renamediagram'
,'sp_dropdiagram'
,'sp_helpdiagramdefinition'
,'fn_diagramobjects'
,'sp_upgraddiagrams'
)
ORDER BY SPECIFIC_NAME
-- PRINT @SQL
EXEC(@SQL)
Without cursor, non-ansi compliant:
DECLARE @sql NVARCHAR(MAX) = N''
, @lineFeed NVARCHAR(2) = CHAR(13) + CHAR(10) ;
SELECT @sql = @sql + N'DROP PROCEDURE ' + QUOTENAME(SPECIFIC_SCHEMA) + N'.' + QUOTENAME(SPECIFIC_NAME) + N';' + @lineFeed
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE = 'PROCEDURE'
-- AND SPECIFIC_NAME LIKE 'sp[_]RPT[_]%'
AND ROUTINE_NAME NOT IN
(
SELECT name FROM sys.procedures WHERE is_ms_shipped <> 0
)
ORDER BY SPECIFIC_NAME
-- PRINT @sql
EXECUTE(@sql)
The easiest way to stream video via IP Camera !
I just edit your example. You must replace your IP and add /video
on your link. And go ahead with your project
import cv2
cap = cv2.VideoCapture('http://192.168.18.37:8090/video')
while(True):
ret, frame = cap.read()
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
It seems to me to be a bug in PHP. The error
'Fatal error: Uncaught Error: Using $this when not in object context in'
appears in the function using $this
, but the error is that the calling function is using non-static function as a static. I.e:
Class_Name
{
function foo()
{
$this->do_something(); // The error appears there.
}
function do_something()
{
///
}
}
While the error is here:
Class_Name::foo();
Please note on iPad Safari, NoviceCoding's solution won't work if you have -webkit-overflow-scrolling: touch;
somewhere in your CSS.
The solution is either removing all the occurrences of -webkit-overflow-scrolling: touch;
or putting -webkit-overflow-scrolling: auto;
with
NoviceCoding's solution.
REM kill all existing instance of chrome
taskkill /F /IM chrome.exe /T
REM directory path where chrome.exe is located
set chromeLocation="C:\Program Files (x86)\Google\Chrome\Application"
cd %chromeLocation%
cd c:
start chrome.exe --allow-file-access-from-files
change chromeLocation path with yours.
save above as .bat file.
drag drop you file on the batch file you created. (chrome does give restore pages option though so if you have pages open just hit restore and it will work).
A callback
is a function passed as an parameter to a Higher Order Function
(wikipedia). A simple implementation of a callback would be:
const func = callback => callback('Hello World!');
To call the function, simple pass another function as argument to the function defined.
func(string => console.log(string));
The solution that worked for me is:
suptitle()
for the actual titletitle()
for the subtitle and adjust it using the optional parameter y
: import matplotlib.pyplot as plt
"""
some code here
"""
plt.title('My subtitle',fontsize=16)
plt.suptitle('My title',fontsize=24, y=1)
plt.show()
There can be some nasty overlap between the two pieces of text. You can fix this by fiddling with the value of y
until you get it right.
Apart from the rest of the answers, I would like to show one difference in React.
If I throw a new Error()
and I am in development mode, I will get an error screen and a console log. If I throw a string literal, I will only see it in the console and possibly miss it, if I am not watching the console log.
Throwing an error logs into the console and shows an error screen while in development mode (the screen won't be visible in production).
throw new Error("The application could not authenticate.");
Whereas the following code only logs into the console:
throw "The application could not authenticate.";
I had a similar issues fresh install and same error surprising. Finally I figured out it was a problem with browser cookies...
Try cleaning your browser cookies and see it helps to resolve this issue, before even trying any configuration changes.
Try using XAMPP Control panel "Admin" button instead of usual http://localhost
or http://localhost/phpmyadmin
Try direct link: http://localhost/phpmyadmin/main.php
or http://127.0.0.1/phpmyadmin/main.php
Finally try this: http://localhost/phpmyadmin/index.php?db=phpmyadmin&server=1&target=db_structure.php
Somehow if you have old installation and you upgraded to new version it keeps track of your old settings through cookies.
If this solution helped let me know.
It's called a middle dot: ·
HTML entities:
·
·
·
In CSS:
\00B7
The best practice is to explicitly list the columns:
Insert Into TableName(col1, col2,col2) Values(?, ?, ?)
Otherwise, your original insert will break if you add another column to your table.
You need to use cv.LoadImageM instead of cv.LoadImage:
In [1]: import cv
In [2]: import numpy as np
In [3]: x = cv.LoadImageM('im.tif')
In [4]: im = np.asarray(x)
In [5]: im.shape
Out[5]: (487, 650, 3)
You'll need to send the image back base64 encoded, look at this: http://php.net/manual/en/function.base64-encode.php
Then in your ajax call change the success function to this:
$('.div_imagetranscrits').html('<img src="data:image/png;base64,' + data + '" />');
These two classes can work together to schedule a periodic task:
import java.util.TimerTask;
import java.util.Date;
// Create a class extending TimerTask
public class ScheduledTask extends TimerTask {
Date now;
public void run() {
// Write code here that you want to execute periodically.
now = new Date(); // initialize date
System.out.println("Time is :" + now); // Display current time
}
}
import java.util.Timer;
public class SchedulerMain {
public static void main(String args[]) throws InterruptedException {
Timer time = new Timer(); // Instantiate Timer Object
ScheduledTask st = new ScheduledTask(); // Instantiate SheduledTask class
time.schedule(st, 0, 1000); // Create task repeating every 1 sec
//for demo only.
for (int i = 0; i <= 5; i++) {
System.out.println("Execution in Main Thread...." + i);
Thread.sleep(2000);
if (i == 5) {
System.out.println("Application Terminates");
System.exit(0);
}
}
}
}
Reference https://www.mkyong.com/java/how-to-run-a-task-periodically-in-java/
Sometimes, the easiest way to edit a commandline is using a mouse. Some previous answers give a command to open your current line in your $EDITOR. For me (zhs with grml config) that combination is Alt+e
. If you enable mouse in your editor, you can make use of it.
To enable mouse in Vim, add this to your ~/.vimrc
set mouse=a
set ttymouse=xterm2
If you then want to do a text selection in terminal (instead of passing the mouseclick to vim), hold Shift when you click; this is terminal specific, of course.
Sysadmins should not be afraid of the mouse.
Keyword parameters allow you to pass variables from one function to another. In this way you can use the key of a dictionary as a variable name (which can be populated in your while
loop). The dictionary name just needs to be preceded by **
when it is called.
# create a dictionary
>>> kwargs = {}
# add a key of name and assign it a value, later we'll use this key as a variable
>>> kwargs['name'] = 'python'
# an example function to use the variable
>>> def print_name(name):
... print name
# call the example function
>>> print_name(**kwargs)
python
Without **
, kwargs
is just a dictionary:
>>> print_name(kwargs)
{'name': 'python'}
putExtra() : This method sends the data to another activity and in parameter, we have to pass key-value pair.
Syntax: intent.putExtra("key", value);
Eg: intent.putExtra("full_name", "Vishnu Sivan");
Intent intent=getIntent()
: It gets the Intent from the previous activity.
fullname = intent.getStringExtra(“full_name”)
: This line gets the string form previous activity and in parameter, we have to pass the key which we have mentioned in previous activity.
Sample Code:
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("firstName", "Vishnu");
intent.putExtra("lastName", "Sivan");
startActivity(intent);
Why not use an ImageButton control?
If you do not want to include the brackets in the match, here's the regex: (?<=\[).*?(?=\])
The .
matches any character except for line terminators. The ?=
is a positive lookahead. A positive lookahead finds a string when a certain string comes after it. The ?<=
is a positive lookbehind. A positive lookbehind finds a string when a certain string precedes it. To quote this,
Look ahead positive (?=)
Find expression A where expression B follows:
A(?=B)
Look behind positive (?<=)
Find expression A where expression B precedes:
(?<=B)A
If your regex engine does not support lookaheads and lookbehinds, then you can use the regex \[(.*?)\]
to capture the innards of the brackets in a group and then you can manipulate the group as necessary.
The parentheses capture the characters in a group. The .*?
gets all of the characters between the brackets (except for line terminators, unless you have the s
flag enabled) in a way that is not greedy.
If you wish to get the individual NSDateComponents from NSDate, you would definitely need the solution suggested by Itai Ferber. But if you want to go from NSDate directly to an NSString, you can use NSDateFormatter.
For Sql Server 2017 and later you can use the new STRING_AGG
function
https://docs.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql
The following example replaces null values with 'N/A' and returns the names separated by commas in a single result cell.
SELECT STRING_AGG ( ISNULL(FirstName,'N/A'), ',') AS csv FROM Person.Person;
Here is the result set.
John,N/A,Mike,Peter,N/A,N/A,Alice,Bob
Perhaps a more common use case is to group together and then aggregate, just like you would with SUM
, COUNT
or AVG
.
SELECT a.articleId, title, STRING_AGG (tag, ',') AS tags
FROM dbo.Article AS a
LEFT JOIN dbo.ArticleTag AS t
ON a.ArticleId = t.ArticleId
GROUP BY a.articleId, title;
You can use from pkg.components.core import GameLoopEvents
, for example I use pycharm, the below is my project structure image, I just import from the root package, then it works:
This will work for the EditText:
android:inputType="text"
Then I would set a max length for the input text:
android:maxLines="1"
Those are the 2 that are needed now.
Simplified example (with counter):
With Me.lstbox
.ColumnCount = 2
.ColumnWidths = "60;60"
.AddItem
.List(i, 0) = Company_ID
.List(i, 1) = Company_name
i = i + 1
end with
Make sure to start the counter with 0, not 1 to fill up a listbox.
"Am i doing it right?Is there better/smarter way to achieve the output this code gave me?"
Generally speaking, yes, you're doing it right. Tkinter has no native scrollable container other than the canvas. As you can see, it's really not that difficult to set up. As your example shows, it only takes 5 or 6 lines of code to make it work -- depending on how you count lines.
"Why must i use grid method?(i tried place method, but none of the labels appear on the canvas?)"
You ask about why you must use grid. There is no requirement to use grid. Place, grid and pack can all be used. It's simply that some are more naturally suited to particular types of problems. In this case it looks like you're creating an actual grid -- rows and columns of labels -- so grid is the natural choice.
"What so special about using anchor='nw' when creating window on canvas?"
The anchor tells you what part of the window is positioned at the coordinates you give. By default, the center of the window will be placed at the coordinate. In the case of your code above, you want the upper left ("northwest") corner to be at the coordinate.
You have to define a PersistentVolume providing disc space to be consumed by the PersistentVolumeClaim.
When using storageClass
Kubernetes is going to enable "Dynamic Volume Provisioning" which is not working with the local file system.
storageClass
-line from the PersistentVolumeClaimAt creation of the deployment state-description it is usually known which kind (amount, speed, ...) of storage that application will need.
To make a deployment versatile you'd like to avoid a hard dependency on storage. Kubernetes' volume-abstraction allows you to provide and consume storage in a standardized way.
The PersistentVolumeClaim is used to provide a storage-constraint alongside the deployment of an application.
The PersistentVolume offers cluster-wide volume-instances ready to be consumed ("bound
"). One PersistentVolume will be bound to one claim. But since multiple instances of that claim may be run on multiple nodes, that volume may be accessed by multiple nodes.
A PersistentVolume without StorageClass is considered to be static.
"Dynamic Volume Provisioning" alongside with a StorageClass allows the cluster to provision PersistentVolumes on demand. In order to make that work, the given storage provider must support provisioning - this allows the cluster to request the provisioning of a "new" PersistentVolume when an unsatisfied PersistentVolumeClaim pops up.
In order to find how to specify things you're best advised to take a look at the API for your Kubernetes version, so the following example is build from the API-Reference of K8S 1.17:
apiVersion: v1
kind: PersistentVolume
metadata:
name: ckan-pv-home
labels:
type: local
spec:
capacity:
storage: 100Mi
hostPath:
path: "/mnt/data/ckan"
The PersistentVolumeSpec allows us to define multiple attributes.
I chose a hostPath
volume which maps a local directory as content for the volume. The capacity allows the resource scheduler to recognize this volume as applicable in terms of resource needs.
It's actually not really clearly stated in the standard (RFC 3986) whether a percent-encoded version of .
or ..
is supposed to have the same this-folder/up-a-folder meaning as the unescaped version. Section 3.3 only talks about “The path segments .
and ..
”, without clarifying whether they match .
and ..
before or after pct-encoding.
Personally I find Firefox's interpretation that %2E
does not mean .
most practical, but unfortunately all the other browsers disagree. This would mean that you can't have a path component containing only .
or ..
.
I think the only possible suggestion is “don't do that”! There are other path components that are troublesome too, typically due to server limitations: %2F
, %00
and %5C
sequences in paths may also be blocked by some web servers, and the empty path segment can also cause problems. So in general it's not possible to fit all possible byte sequences into a path component.
You could consider using an external tool like ffmpeg to merge the images into a movie (see answer here) or you could try to use OpenCv to combine the images into a movie like the example here.
I'm attaching below a code snipped I used to combine all png files from a folder called "images" into a video.
import cv2
import os
image_folder = 'images'
video_name = 'video.avi'
images = [img for img in os.listdir(image_folder) if img.endswith(".png")]
frame = cv2.imread(os.path.join(image_folder, images[0]))
height, width, layers = frame.shape
video = cv2.VideoWriter(video_name, 0, 1, (width,height))
for image in images:
video.write(cv2.imread(os.path.join(image_folder, image)))
cv2.destroyAllWindows()
video.release()
For anyone else having the same problem, I figured it out myself.
<html>_x000D_
<body>_x000D_
<form target="_blank" action="https://website.com/action.php" method="POST">_x000D_
<input type="hidden" name="fullname" value="Sam" />_x000D_
<input type="hidden" name="city" value="Dubai " />_x000D_
<input onclick="window.location.href = 'https://website.com/my-account';" type="submit" value="Submit request" />_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
All I had to do was add the target="_blank" attribute to inline on form to open the response in a new page and redirect the other page using onclick on the submit button.
I am using Cent OS 6.6 with Apache and for me error log files are in
/usr/local/apache/log
After visiting this question and noting the initial concerns of the chosen solution, I figured I'd contribute this one for those not using Java 7 which uses FileUtils instead of IOUtils from Apache Commons. The advantage here is that the readFileToString and the writeStringToFile handle the issue of closing the files for you automatically. (writeStringToFile doesn't document it but you can read the source). Hopefully this recipe simplifies things for anyone new coming to this problem.
try {
String content = FileUtils.readFileToString(new File("InputFile"), "UTF-8");
content = content.replaceAll("toReplace", "replacementString");
File tempFile = new File("OutputFile");
FileUtils.writeStringToFile(tempFile, content, "UTF-8");
} catch (IOException e) {
//Simple exception handling, replace with what's necessary for your use case!
throw new RuntimeException("Generating file failed", e);
}
I'm on Windows and have used 4 methods: SFTP, WinSCP, Unison and Sublime Text on Linux with X11 forwarding over SSH to Windows (yes you can do this without messy configs and using a free tool).
The fourth way is the best if you can install software on your Linux machine.
The fourth way:
MobaXterm
subl
Note: When invoking subl if it complains for a certain library - ensure you install them to successfully invoke sublimetext from mobaxterm.
If you can't install software on your Linux box, the best is Unison. Why?
SFTP
Setup: Install the SFTP Sublime Text package. This package requires a license.
In the sftp-config, I usually set:
"upload_on_save": true,
"sync_down_on_open": true,
This, in addition to an SSH terminal to the machine gives me a fairly seamless remote editing experience.
WinSCP
From then on, WinSCP will keep your changes synchronized.
Work in the local folder using SublimeText. Just make sure that Sublime Text is set to guess the line endings from the file that is being edited.
Unison
I have found that if source tree is massive (around a few hundred MB with a deep hierarchy), then the WinSCP method described above might be a bit slow. You can get much better performance using Unison. The down side is that Unison is not automatic (you need to trigger it with a keypress) and requires a server component to be running on your linux machine. The up side is that the transfers are incredibly fast, it is very reliable and ignoring files, folders and extensions are incredibly easy to setup.
There is no such functionality in jQuery. Use JSON.stringify
or alternatively any jQuery plugin with similar functionality (e.g jquery-json).
After many struggles and to achive a general, flexible and more readable solution, in my case I ended up saving the ORs results into ENV variables and doing the ANDs of those variables.
# RESULT_ONE = A OR B
RewriteRule ^ - [E=RESULT_ONE:False]
RewriteCond ...A... [OR]
RewriteCond ...B...
RewriteRule ^ - [E=RESULT_ONE:True]
# RESULT_TWO = C OR D
RewriteRule ^ - [E=RESULT_TWO:False]
RewriteCond ...C... [OR]
RewriteCond ...D...
RewriteRule ^ - [E=RESULT_TWO:True]
# if ( RESULT_ONE AND RESULT_TWO ) then ( RewriteRule ...something... )
RewriteCond %{ENV:RESULT_ONE} =True
RewriteCond %{ENV:RESULT_TWO} =True
RewriteRule ...something...
Requirements:
Try this with Swift 4
buttonSection.addTarget(self, action: #selector(actionWithParam(_:)), for: .touchUpInside)
@objc func actionWithParam(sender: UIButton){
//...
}
buttonSection.addTarget(self, action: #selector(actionWithoutParam), for: .touchUpInside)
@objc func actionWithoutParam(){
//...
}
you can use this way...
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
String main = listView.getSelectedItem().toString();
}
});
Suppose you have 2 lists
A = [1,2,3,4]
B = [3,4,5,6]
so you can find A
Union B
as follow
union = set(A).union(set(B))
also if you want to find intersection and non-intersection you do that as follow
intersection = set(A).intersection(set(B))
non_intersection = union - intersection
There is a lot of ways to achieve this. In regards to the way you are asking, with a hidden form element.
create this form element inside your form:
<input type="hidden" name="total" value="">
So your form like this:
<form id="sampleForm" name="sampleForm" method="post" action="phpscript.php">
<input type="hidden" name="total" id="total" value="">
<a href="#" onclick="setValue();">Click to submit</a>
</form>
Then your javascript something like this:
<script>
function setValue(){
document.sampleForm.total.value = 100;
document.forms["sampleForm"].submit();
}
</script>
You could use random.sample
to generate the list with one call:
import random
my_randoms = random.sample(range(100), 10)
That generates numbers in the (inclusive) range from 0 to 99. If you want 1 to 100, you could use this (thanks to @martineau for pointing out my convoluted solution):
my_randoms = random.sample(range(1, 101), 10)
instanceof is a keyword that can be used to test if an object is of a specified type.
Example :
public class MainClass {
public static void main(String[] a) {
String s = "Hello";
int i = 0;
String g;
if (s instanceof java.lang.String) {
// This is going to be printed
System.out.println("s is a String");
}
if (i instanceof Integer) {
// This is going to be printed as autoboxing will happen (int -> Integer)
System.out.println("i is an Integer");
}
if (g instanceof java.lang.String) {
// This case is not going to happen because g is not initialized and
// therefore is null and instanceof returns false for null.
System.out.println("g is a String");
}
}
Here is my source.
Just to add something to what @Fionnuala Said, The below functions can be used. These even work for leap years.
'If you pass #2016/20/01# you get #2016/31/01#
Public Function GetLastDate(tempDate As Date) As Date
GetLastDate = DateSerial(Year(tempDate), Month(tempDate) + 1, 0)
End Function
'If you pass #2016/20/01# you get 31
Public Function GetLastDay(tempDate As Date) As Integer
GetLastDay = Day(DateSerial(Year(tempDate), Month(tempDate) + 1, 0))
End Function
Tell the correlation to ignore the NAs with use
argument, e.g.:
cor(data$price, data$exprice, use = "complete.obs")
Just give any name to the DataTable Like:
DataTable dt = new DataTable();
dt = SecondDataTable.Copy();
dt .TableName = "New Name";
DataSet.Tables.Add(dt );
CREATE LOGIN [IIS APPPOOL\MyAppPool] FROM WINDOWS;
CREATE USER MyAppPoolUser FOR LOGIN [IIS APPPOOL\MyAppPool];
To clear all SharedPreferences centrally from any class:
public static SharedPreferences.Editor getEditor(Context context) {
return getPreferences(context).edit();
}
And then from any class: (commit returns a Boolean where you can check whether your Preferences cleared or not)
Navigation.getEditor(this).clear().commit();
Or you can use apply; it returns void
Navigation.getEditor(this).clear().apply();
First thing is
DataFrame
was evolved fromSchemaRDD
.
Yes.. conversion between Dataframe
and RDD
is absolutely possible.
Below are some sample code snippets.
df.rdd
is RDD[Row]
Below are some of options to create dataframe.
1) yourrddOffrow.toDF
converts to DataFrame
.
2) Using createDataFrame
of sql context
val df = spark.createDataFrame(rddOfRow, schema)
where schema can be from some of below options as described by nice SO post..
From scala case class and scala reflection apiimport org.apache.spark.sql.catalyst.ScalaReflection val schema = ScalaReflection.schemaFor[YourScalacaseClass].dataType.asInstanceOf[StructType]
OR using
Encoders
import org.apache.spark.sql.Encoders val mySchema = Encoders.product[MyCaseClass].schema
as described by Schema can also be created using
StructType
andStructField
val schema = new StructType() .add(StructField("id", StringType, true)) .add(StructField("col1", DoubleType, true)) .add(StructField("col2", DoubleType, true)) etc...
In fact there Are Now 3 Apache Spark APIs..
RDD
API :The
RDD
(Resilient Distributed Dataset) API has been in Spark since the 1.0 release.The
RDD
API provides many transformation methods, such asmap
(),filter
(), andreduce
() for performing computations on the data. Each of these methods results in a newRDD
representing the transformed data. However, these methods are just defining the operations to be performed and the transformations are not performed until an action method is called. Examples of action methods arecollect
() andsaveAsObjectFile
().
RDD Example:
rdd.filter(_.age > 21) // transformation
.map(_.last)// transformation
.saveAsObjectFile("under21.bin") // action
Example: Filter by attribute with RDD
rdd.filter(_.age > 21)
DataFrame
APISpark 1.3 introduced a new
DataFrame
API as part of the Project Tungsten initiative which seeks to improve the performance and scalability of Spark. TheDataFrame
API introduces the concept of a schema to describe the data, allowing Spark to manage the schema and only pass data between nodes, in a much more efficient way than using Java serialization.The
DataFrame
API is radically different from theRDD
API because it is an API for building a relational query plan that Spark’s Catalyst optimizer can then execute. The API is natural for developers who are familiar with building query plans
Example SQL style :
df.filter("age > 21");
Limitations : Because the code is referring to data attributes by name, it is not possible for the compiler to catch any errors. If attribute names are incorrect then the error will only detected at runtime, when the query plan is created.
Another downside with the DataFrame
API is that it is very scala-centric and while it does support Java, the support is limited.
For example, when creating a DataFrame
from an existing RDD
of Java objects, Spark’s Catalyst optimizer cannot infer the schema and assumes that any objects in the DataFrame implement the scala.Product
interface. Scala case class
works out the box because they implement this interface.
Dataset
APIThe
Dataset
API, released as an API preview in Spark 1.6, aims to provide the best of both worlds; the familiar object-oriented programming style and compile-time type-safety of theRDD
API but with the performance benefits of the Catalyst query optimizer. Datasets also use the same efficient off-heap storage mechanism as theDataFrame
API.When it comes to serializing data, the
Dataset
API has the concept of encoders which translate between JVM representations (objects) and Spark’s internal binary format. Spark has built-in encoders which are very advanced in that they generate byte code to interact with off-heap data and provide on-demand access to individual attributes without having to de-serialize an entire object. Spark does not yet provide an API for implementing custom encoders, but that is planned for a future release.Additionally, the
Dataset
API is designed to work equally well with both Java and Scala. When working with Java objects, it is important that they are fully bean-compliant.
Example Dataset
API SQL style :
dataset.filter(_.age < 21);
Evaluations diff. between DataFrame
& DataSet
:
Catalist level flow..(Demystifying DataFrame and Dataset presentation from spark summit)
Further reading... databricks article - A Tale of Three Apache Spark APIs: RDDs vs DataFrames and Datasets
Rather than worry about dealing with the keyboard, why not just accept any input, lowercase or uppercase and convert the string to uppercase?
The following code should help:
EditText edit = (EditText)findViewById(R.id.myEditText);
String input;
....
input = edit.getText();
input = input.toUpperCase(); //converts the string to uppercase
This is user-friendly since it is unnecessary for the user to know that you need the string in uppercase. Hope this helps.
Go into task manager and see if you have any Microsoft Excel Processes running in the background. I closed my excel background processes and my code worked again.
@weekly work better for me!
example,add the fellowing crontab -e ,it will work in every sunday 0:00 AM
@weekly /root/fd/databasebackup/week.sh >> ~/test.txt
To get a type that implements io.Reader
from a []byte
slice, you can use bytes.NewReader
in the bytes
package:
r := bytes.NewReader(byteData)
This will return a value of type bytes.Reader
which implements the io.Reader
(and io.ReadSeeker
) interface.
Don't worry about them not being the same "type". io.Reader
is an interface and can be implemented by many different types. To learn a little bit more about interfaces in Go, read Effective Go: Interfaces and Types.
Both patterns come for the same necessity: Hide from some client code the construction logic of a complex object. But what makes "complex" (or, sometimes, complicate) an object? Mainly, it's due to dependencies, or rather the state of an object composed by more partial states. You can inject dependencies by constructor to set the initial object state, but an object may require a lot of them, some will be in a default initial state (just because we should have learned that set a default dependency to null is not the cleanest way) and some other set to a state driven by some condition. Moreover, there are object properties that are some kind of "oblivious dependencies" but also they can assume optional states.
there are two well known ways to dominate that complexity:
Composition/aggregation: Construct an object, construct its dependent objects, then wire together. Here, a builder can make transparent and flexible the process that determines the rules that lead the construction of component.
Polymorphism: Construction rules are declared directly into subtype definition, so you have a set of rules for each subtype and some condition decides which one among these set of rules apply to construct the object. A factory fits perfectly in this scenario.
Nothing prevents to mix these two approaches. A family of product could abstract object creation done with a builder, a builder could use factories to determine which component object instantiate.
Please check that the function you are importing and the one that you have declared in the same file do not have the same name.
I will give you an example for this error. In express JS (using ES6), consider the following scenario:
import {getAllCall} from '../../services/calls';
let getAllCall = () => {
return getAllCall().then(res => {
//do something here
})
}
module.exports = {
getAllCall
}
The above scenario will cause infamous RangeError: Maximum call stack size exceeded error because the function keeps calling itself so many times that it runs out of maximum call stack.
Most of the times the error is in code (like the one above). Other way of resolving is manually increasing the call stack. Well, this works for certain extreme cases, but it is not recommended.
Hope my answer helped you.
Example code (without exception-handling):
XMLGregorianCalendar xgc =
DatatypeFactory // Data-type converter.
.newInstance() // Instantiate a converter object.
.newXMLGregorianCalendar( // Converter going from `GregorianCalendar` to `XMLGregorianCalendar`.
GregorianCalendar.from( // Convert from modern `ZonedDateTime` class to legacy `GregorianCalendar` class.
LocalDate // Modern class for representing a date-only, without time-of-day and without time zone.
.parse( "2014-01-07" ) // Parsing strings in standard ISO 8601 format is handled by default, with no need for custom formatting pattern.
.atStartOfDay( ZoneOffset.UTC ) // Determine the first moment of the day as seen in UTC. Returns a `ZonedDateTime` object.
) // Returns a `GregorianCalendar` object.
) // Returns a `XMLGregorianCalendar` object.
;
XMLGregorianCalendar
classAvoid the terrible legacy date-time classes whenever possible, such as XMLGregorianCalendar
, GregorianCalendar
, Calendar
, and Date
. Use only modern java.time classes.
When presented with a string such as "2014-01-07"
, parse as a LocalDate
.
LocalDate.parse( "2014-01-07" )
To get a date with time-of-day, assuming you want the first moment of the day, specify a time zone. Let java.time determine the first moment of the day, as it is not always 00:00:00.0 in some zones on some dates.
LocalDate.parse( "2014-01-07" )
.atStartOfDay( ZoneId.of( "America/Montreal" ) )
This returns a ZonedDateTime
object.
ZonedDateTime zdt =
LocalDate
.parse( "2014-01-07" )
.atStartOfDay( ZoneId.of( "America/Montreal" ) )
;
zdt.toString() = 2014-01-07T00:00-05:00[America/Montreal]
But apparently, you want the start-of-day as seen in UTC (an offset of zero hours-minutes-seconds). So we specify ZoneOffset.UTC
constant as our ZoneId
argument.
ZonedDateTime zdt =
LocalDate
.parse( "2014-01-07" )
.atStartOfDay( ZoneOffset.UTC )
;
zdt.toString() = 2014-01-07T00:00Z
The Z
on the end means UTC (an offset of zero), and is pronounced “Zulu”.
If you must work with legacy classes, convert to GregorianCalendar
, a subclass of Calendar
.
GregorianCalendar gc = GregorianCalendar.from( zdt ) ;
gc.toString() = java.util.GregorianCalendar[time=1389052800000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="UTC",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2014,MONTH=0,WEEK_OF_YEAR=2,WEEK_OF_MONTH=2,DAY_OF_MONTH=7,DAY_OF_YEAR=7,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=0,DST_OFFSET=0]
Apparently, you really need an object of the legacy class XMLGregorianCalendar
. If the calling code cannot be updated to use java.time, convert.
XMLGregorianCalendar xgc =
DatatypeFactory
.newInstance()
.newXMLGregorianCalendar( gc )
;
Actually, that code requires a try-catch.
try
{
XMLGregorianCalendar xgc =
DatatypeFactory
.newInstance()
.newXMLGregorianCalendar( gc );
}
catch ( DatatypeConfigurationException e )
{
e.printStackTrace();
}
xgc = 2014-01-07T00:00:00.000Z
Putting that all together, with appropriate exception-handling.
// Given an input string such as "2014-01-07", return a `XMLGregorianCalendar` object
// representing first moment of the day on that date as seen in UTC.
static public XMLGregorianCalendar getXMLGregorianCalendar ( String input )
{
Objects.requireNonNull( input );
if( input.isBlank() ) { throw new IllegalArgumentException( "Received empty/blank input string for date argument. Message # 11818896-7412-49ba-8f8f-9b3053690c5d." ) ; }
XMLGregorianCalendar xgc = null;
ZonedDateTime zdt = null;
try
{
zdt =
LocalDate
.parse( input )
.atStartOfDay( ZoneOffset.UTC );
}
catch ( DateTimeParseException e )
{
throw new IllegalArgumentException( "Faulty input string for date does not comply with standard ISO 8601 format. Message # 568db0ef-d6bf-41c9-8228-cc3516558e68." );
}
GregorianCalendar gc = GregorianCalendar.from( zdt );
try
{
xgc =
DatatypeFactory
.newInstance()
.newXMLGregorianCalendar( gc );
}
catch ( DatatypeConfigurationException e )
{
e.printStackTrace();
}
Objects.requireNonNull( xgc );
return xgc ;
}
Usage.
String input = "2014-01-07";
XMLGregorianCalendar xgc = App.getXMLGregorianCalendar( input );
Dump to console.
System.out.println( "xgc = " + xgc );
xgc = 2014-01-07T00:00:00.000Z
Do not conflate a date-time value with its textual representation. We parse strings to get a date-time object, and we ask the date-time object to generate a string to represent its value. The date-time object has no ‘format’, only strings have a format.
So shift your thinking into two separate modes: model and presentation. Determine the date-value you have in mind, applying appropriate time zone, as the model. When you need to display that value, generate a string in a particular format as expected by the user.
The Question and other Answers all use old troublesome date-time classes now supplanted by the java.time classes.
Your input string "2014-01-07"
is in standard ISO 8601 format.
The T
in the middle separates date portion from time portion.
The Z
on the end is short for Zulu and means UTC.
Fortunately, the java.time classes use the ISO 8601 formats by default when parsing/generating strings. So no need to specify a formatting pattern.
LocalDate
The LocalDate
class represents a date-only value without time-of-day and without time zone.
LocalDate ld = LocalDate.parse( "2014-01-07" ) ;
ld.toString(): 2014-01-07
ZonedDateTime
If you want to see the first moment of that day, specify a ZoneId
time zone to get a moment on the timeline, a ZonedDateTime
. The time zone is crucial because the date varies around the globe by zone. A few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
Never assume the day begins at 00:00:00. Anomalies such as Daylight Saving Time (DST) means the day may begin at another time-of-day such as 01:00:00. Let java.time determine the first moment.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ld.atStartOfDay( z ) ;
zdt.toString(): 2014-01-07T00:00:00Z
For your desired format, generate a string using the predefined formatter DateTimeFormatter.ISO_LOCAL_DATE_TIME
and then replace the T
in the middle with a SPACE.
String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " ) ;
2014-01-07 00:00:00
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
I had a similar problem and none of the solutions above worked, so I went with an old standby that always works:
That almost always works if you've spent 10 minutes at it and can't get it.
Note that for similar problems with older versions (2008, 2005) you can usually get away with just changing the version in the .csproj and either changing the version in the .sln or discarding it, but this doesn't seem to work for 2013.
Seems everyone has difference experiences from this and therfore solutions as well :) This is my "story".
My thing came from a validate.php file fetched with ajax. The output was meant to be :
$response['status'] = $status;
$response['message'] = $message;
$response['param'] = $param;
echo json_encode($response);
And the error that cause the "Unexpected token <" error was simply that in some cases $message hadn't been declared (but only $status and $param). So, added this in the beginning of the code.
$message = ''; // Default value, in case it doesn't get set later on.
So I guess, those "little things" may in this scenario big of quite importance. So be sure to really check your code and making it bulletproof.
You can try using open-cv to save the file since it helps with image type conversions internally. The sample code:
import cv2
import numpy as np
def save(encoded_data, filename):
nparr = np.fromstring(encoded_data.decode('base64'), np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_ANYCOLOR)
return cv2.imwrite(filename, img)
Then somewhere in your code you can use it like this:
save(base_64_string, 'testfile.png');
save(base_64_string, 'testfile.jpg');
save(base_64_string, 'testfile.bmp');
I had the same problem, and I found the solution in this post of Sam Goddard,
The solution if to defined the call to the font twice. First as it is recommended, to be used for all the browsers, and after a particular call only for Chrome with a special media query:
@font-face {
font-family: 'chunk-webfont';
src: url('../../includes/fonts/chunk-webfont.eot');
src: url('../../includes/fonts/chunk-webfont.eot?#iefix') format('eot'),
url('../../includes/fonts/chunk-webfont.woff') format('woff'),
url('../../includes/fonts/chunk-webfont.ttf') format('truetype'),
url('../../includes/fonts/chunk-webfont.svg') format('svg');
font-weight: normal;
font-style: normal;
}
@media screen and (-webkit-min-device-pixel-ratio:0) {
@font-face {
font-family: 'chunk-webfont';
src: url('../../includes/fonts/chunk-webfont.svg') format('svg');
}
}
With this method the font will render good in all browsers. The only negative point that I found is that the font file is also downloaded twice.
You can find an spanish version of this article in my page
I usually sort the data by the field I need to do the distinct count of then use IF(A2=A1,0,1); you get then get a 1 in the top row of each group of IDs. Simple and doesn't take any time to calculate on large datasets.
set -e
stops the execution of a script if a command or pipeline has an error - which is the opposite of the default shell behaviour, which is to ignore errors in scripts. Type help set
in a terminal to see the documentation for this built-in command.
You could try this
$('#myFieldID').focus(function(){
$(this).val('');
});
Try this one, I assure you that it will work perfectly.
import scipy.optimize as opt
from numpy import exp
import timeit
st1 = timeit.default_timer()
def f(variables) :
(x,y) = variables
first_eq = x + y**2 -4
second_eq = exp(x) + x*y - 3
return [first_eq, second_eq]
solution = opt.fsolve(f, (0.1,1) )
print(solution)
st2 = timeit.default_timer()
print("RUN TIME : {0}".format(st2-st1))
->
[ 0.62034452 1.83838393]
RUN TIME : 0.0009331008900937708
FYI. as mentioned above, you can also use 'Broyden's approximation' by replacing 'fsolve' with 'broyden1'. It works. I did it.
I don't know exactly how Broyden's approximation works, but it took 0.02 s.
And I recommend you do not use Sympy's functions <- convenient indeed, but in terms of speed, it's quite slow. You will see.
As I continue to recieve upvotes on this, I think it is reasonable to remember that this answer is 4 years old. Web has grown in a really fast pace, so please be mindful about this answer.
I had the same issue recently and researched about the subject.
The solution given is called long polling, and to correctly use it you must be sure that your AJAX request has a "large" timeout and to always make this request after the current ends (timeout, error or success).
Here, to keep code short, I will use jQuery:
function pollTask() {
$.ajax({
url: '/api/Polling',
async: true, // by default, it's async, but...
dataType: 'json', // or the dataType you are working with
timeout: 10000, // IMPORTANT! this is a 10 seconds timeout
cache: false
}).done(function (eventList) {
// Handle your data here
var data;
for (var eventName in eventList) {
data = eventList[eventName];
dispatcher.handle(eventName, data); // handle the `eventName` with `data`
}
}).always(pollTask);
}
It is important to remember that (from jQuery docs):
In jQuery 1.4.x and below, the XMLHttpRequest object will be in an invalid state if the request times out; accessing any object members may throw an exception. In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period.
It is not in any specific language, but it would be something like this:
function handleRequest () {
while (!anythingHappened() || hasTimedOut()) { sleep(2); }
return events();
}
Here, hasTimedOut
will make sure your code does not wait forever, and anythingHappened
, will check if any event happend. The sleep
is for releasing your thread to do other stuff while nothing happens. The events
will return a dictionary of events (or any other data structure you may prefer) in JSON format (or any other you prefer).
It surely solves the problem, but, if you are concerned about scalability and perfomance as I was when researching, you might consider another solution I found.
Use sockets!
On client side, to avoid any compatibility issues, use socket.io. It tries to use socket directly, and have fallbacks to other solutions when sockets are not available.
On server side, create a server using NodeJS (example here). The client will subscribe to this channel (observer) created with the server. Whenever a notification has to be sent, it is published in this channel and the subscriptor (client) gets notified.
If you don't like this solution, try APE (Ajax Push Engine).
Hope I helped.
You can use margin. See the example:
li{
margin: 10px 0;
}
(1) Is it possible to pass a JSON object to the url like in Ex.2?
No, because http://localhost:8080/api/v1/mno/objectKey/{"id":1, "name":"Saif"}
is not a valid URL.
If you want to do it the RESTful way, use http://localhost:8080/api/v1/mno/objectKey/1/Saif
, and defined your method like this:
@RequestMapping(path = "/mno/objectKey/{id}/{name}", method = RequestMethod.GET)
public Book getBook(@PathVariable int id, @PathVariable String name) {
// code here
}
(2) How can we pass and parse the parameters in Ex.1?
Just add two request parameters, and give the correct path.
@RequestMapping(path = "/mno/objectKey", method = RequestMethod.GET)
public Book getBook(@RequestParam int id, @RequestParam String name) {
// code here
}
UPDATE (from comment)
What if we have a complicated parameter structure ?
"A": [ { "B": 37181, "timestamp": 1160100436, "categories": [ { "categoryID": 2653, "timestamp": 1158555774 }, { "categoryID": 4453, "timestamp": 1158555774 } ] } ]
Send that as a POST
with the JSON data in the request body, not in the URL, and specify a content type of application/json
.
@RequestMapping(path = "/mno/objectKey", method = RequestMethod.POST, consumes = "application/json")
public Book getBook(@RequestBody ObjectKey objectKey) {
// code here
}
In java based regular expression you can use [\s\S]
Laravel 4
When the validation fails return back with the validation errors.
if($validator->fails()) {
return Redirect::back()->withErrors($validator);
}
You can catch the error on your view using
@if($errors->any())
{{ implode('', $errors->all('<div>:message</div>')) }}
@endif
UPDATE
To display error under each field you can do like this.
<input type="text" name="firstname">
@if($errors->has('firstname'))
<div class="error">{{ $errors->first('firstname') }}</div>
@endif
For better display style with css.
You can refer to the docs here.
UPDATE 2
To display all errors at once
@if($errors->any())
{!! implode('', $errors->all('<div>:message</div>')) !!}
@endif
To display error under each field.
@error('firstname')
<div class="error">{{ $message }}</div>
@enderror
I tried using the 'WHERE' statement above, I thought its correct since nobody corrected it but I was wrong; after some searches I found out that this is the right formula for the WHERE statement so the code becomes like this:
SELECT COUNT(id)
FROM stats
WHERE YEAR(record_date) = 2009
GROUP BY MONTH(record_date)
GCD is very easy to use - if you want to do something in the background, all you need to do is write the code and dispatch it on a background queue. Doing the same thing with NSOperation is a lot of additional work.
The advantage of NSOperation is that (a) you have a real object that you can send messages to, and (b) that you can cancel an NSOperation. That's not trivial. You need to subclass NSOperation, you have to write your code correctly so that cancellation and correctly finishing a task both work correctly. So for simple things you use GCD, and for more complicated things you create a subclass of NSOperation. (There are subclasses NSInvocationOperation and NSBlockOperation, but everything they do is easier done with GCD, so there is no good reason to use them).
To Run Nodejs Server over Network
const port = process.env.PORT || 3000;
const server = http.createServer(
server.listen(port, '0.0.0.0', () => console.log(`Server started on port ${port}`)
));
run http://yournetworkipaddress:3000 to access your application over local area network (LAN)
Steps to find your network ip.
MacOS
I am not sure why you cannot use "lat" but, if you must you can rename the columns in a derived table.
select a.latitude from (SELECT lat AS latitude FROM poi_table) a where latitude < 500
Here is the jsFiddle
#backdrop{
border: 2px solid red;
width: 400px;
height: 200px;
position: absolute;
}
#curtain {
border: 1px solid blue;
width: 400px;
height: 200px;
position: absolute;
}
Use Z-index to move the one you want on top.
The asterisk (*) means "zero or more of the previous item".
If you want to match any single character use
sed -i 's/string-./string-0/g' file.txt
If you want to match any string (i.e. any single character zero or more times) use
sed -i 's/string-.*/string-0/g' file.txt
To avoid syntax errors, be sure to always put BEGIN
and END
after an IF
clause, eg:
IF (@A!= @SA)
BEGIN
--do stuff
END
IF (@C!= @SC)
BEGIN
--do stuff
END
... and so on. This should work as expected. Imagine BEGIN
and END
keyword as the opening and closing bracket, respectively.
**Check by executing this**
git config --list
**Change user email**
git config --global user.email "[email protected]"
**Change user name**
git config --global user.name "user"
**Change user credential name**
git config --global credential.username "new_username"
**After this a window popup asking password.
Enter password and proceed.**
You can get some limited memory information from the Runtime class. It really isn't exactly what you are looking for, but I thought I would provide it for the sake of completeness. Here is a small example. Edit: You can also get disk usage information from the java.io.File class. The disk space usage stuff requires Java 1.6 or higher.
public class Main {
public static void main(String[] args) {
/* Total number of processors or cores available to the JVM */
System.out.println("Available processors (cores): " +
Runtime.getRuntime().availableProcessors());
/* Total amount of free memory available to the JVM */
System.out.println("Free memory (bytes): " +
Runtime.getRuntime().freeMemory());
/* This will return Long.MAX_VALUE if there is no preset limit */
long maxMemory = Runtime.getRuntime().maxMemory();
/* Maximum amount of memory the JVM will attempt to use */
System.out.println("Maximum memory (bytes): " +
(maxMemory == Long.MAX_VALUE ? "no limit" : maxMemory));
/* Total memory currently available to the JVM */
System.out.println("Total memory available to JVM (bytes): " +
Runtime.getRuntime().totalMemory());
/* Get a list of all filesystem roots on this system */
File[] roots = File.listRoots();
/* For each filesystem root, print some info */
for (File root : roots) {
System.out.println("File system root: " + root.getAbsolutePath());
System.out.println("Total space (bytes): " + root.getTotalSpace());
System.out.println("Free space (bytes): " + root.getFreeSpace());
System.out.println("Usable space (bytes): " + root.getUsableSpace());
}
}
}
Try This
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysqli_query('SELECT * FROM Users WHERE UserName LIKE $username');
if($result){
while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'];
}
}
It didn't feel like folks were answering the issue here which is: being on the latest version of beta Chrome/Chromium and not seeing the matching chromedriver version
For example, currently as of writing this, Chromium for Mac is Version 86.0.4190.0 (Developer Build) (64-bit) however the latest chromedriver versions listed are
Current stable release: ChromeDriver 83.0.4103.39
Current beta release: ChromeDriver 84.0.4147.30
If you go to https://chromedriver.chromium.org/downloads/version-selection, they provide some pointers on getting a compatible version. One of the last lines near the end mentions trying the ChromeDriver Canary build which leads to how to get it from Chromium browser snapshots.
Of course this goes without saying that using the latest experimental version is likely to have bugs
There is a limit on the number of half-open connections, but afaik not for active connections. Although it appears to depend on the type of Windows 2008 server, at least according to this MSFT employee:
It depends on the edition, Web and Foundation editions have connection limits while Standard, Enterprise, and Datacenter do not.
And if you want to retain any of the aggregation info from the second level of the multiindex you can try this:
In [1]: new_cols = [''.join(t) for t in df.columns]
Out[1]:
['USAF',
'WBAN',
'day',
'month',
's_CDsum',
's_CLsum',
's_CNTsum',
's_PCsum',
'tempfamax',
'tempfamin',
'year']
In [2]: df.columns = new_cols
You'll need to be more specific. What do you mean by 'update the URL'? It could mean automatically navigating to a different page, which is certainly possible.
If you want to just update the contents of the address bar without reloading the page, see Modify the URL without reloading the page
You could use display: table-row-group
for your div.
<table>
<div style="display: table-row-group">
<tr><td></td></tr>
</div>
<div style="display: table-row-group">
<tr><td></td></tr>
</div>
</table>
[]
is replaced by %5B%5D
at URL encoding time.
In JavaScript when you create any object through a constructor call like below
step 1 : create a function say Person..
function Person(name){
this.name=name;
}
person.prototype.print=function(){
console.log(this.name);
}
step 2 : create an instance for this function..
var obj=new Person('venkat')
//above line will instantiate this function(Person) and return a brand new object called Person {name:'venkat'}
if you don't want to instantiate this function and call at same time.we can also do like below..
var Person = {
init: function(name){
this.name=name;
},
print: function(){
console.log(this.name);
}
};
var obj=Object.create(Person);
obj.init('venkat');
obj.print();
in the above method init will help in instantiating the object properties. basically init is like a constructor call on your class.
Simple and clear (may be).
Might not be a fancy solution, but this worked me and saved my day.
Worked for Server version: 5.6.38 MySQL Community Server (GPL)
Steps I followed:
1. generate drop query using concat and group_concat.
2. use database
3. disable key constraint check
4. copy the query generated from step 1
5. enable key constraint check
6. run show table
MySQL shell
mysql> SYSTEM CLEAR;
mysql> SELECT CONCAT('DROP TABLE IF EXISTS `', GROUP_CONCAT(table_name SEPARATOR '`, `'), '`;') AS dropquery FROM information_schema.tables WHERE table_schema = 'emall_duplicate';
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| dropquery |
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| DROP TABLE IF EXISTS `admin`, `app`, `app_meta_settings`, `commission`, `commission_history`, `coupon`, `email_templates`, `infopages`, `invoice`, `m_pc_xref`, `member`, `merchant`, `message_templates`, `mnotification`, `mshipping_address`, `notification`, `order`, `orderdetail`, `pattributes`, `pbrand`, `pcategory`, `permissions`, `pfeatures`, `pimage`, `preport`, `product`, `product_review`, `pspecification`, `ptechnical_specification`, `pwishlist`, `role_perms`, `roles`, `settings`, `test`, `testanother`, `user_perms`, `user_roles`, `users`, `wishlist`; |
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
mysql> USE emall_duplicate;
Database changed
mysql> SET FOREIGN_KEY_CHECKS = 0; Query OK, 0 rows affected (0.00 sec)
// copy and paste generated query from step 1
mysql> DROP TABLE IF EXISTS `admin`, `app`, `app_meta_settings`, `commission`, `commission_history`, `coupon`, `email_templates`, `infopages`, `invoice`, `m_pc_xref`, `member`, `merchant`, `message_templates`, `mnotification`, `mshipping_address`, `notification`, `order`, `orderdetail`, `pattributes`, `pbrand`, `pcategory`, `permissions`, `pfeatures`, `pimage`, `preport`, `product`, `product_review`, `pspecification`, `ptechnical_specification`, `pwishlist`, `role_perms`, `roles`, `settings`, `test`, `testanother`, `user_perms`, `user_roles`, `users`, `wishlist`;
Query OK, 0 rows affected (0.18 sec)
mysql> SET FOREIGN_KEY_CHECKS = 1;
Query OK, 0 rows affected (0.00 sec)
mysql> SHOW tables;
Empty set (0.01 sec)
mysql>
The short answer is "yes". A sample ldapsearch
command to query an Active Directory server is:
ldapsearch \
-x -h ldapserver.mydomain.com \
-D "[email protected]" \
-W \
-b "cn=users,dc=mydomain,dc=com" \
-s sub "(cn=*)" cn mail sn
This would connect to an AD server at hostname ldapserver.mydomain.com
as user [email protected]
, prompt for the password on the command line and show name and email details for users in the cn=users,dc=mydomain,dc=com
subtree.
See Managing LDAP from the Command Line on Linux for more samples. See LDAP Query Basics for Microsoft Exchange documentation for samples using LDAP queries with Active Directory.
Simply speaking Unicode
is a standard which assigned one number (called code point) to all characters of the world (Its still work in progress).
Now you need to represent this code points using bytes, thats called character encoding
. UTF-8, UTF-16, UTF-6
are ways of representing those characters.
UTF-8
is multibyte character encoding. Characters can have 1 to 6 bytes (some of them may be not required right now).
UTF-32
each characters have 4 bytes a characters.
UTF-16
uses 16 bits for each character and it represents only part of Unicode characters called BMP (for all practical purposes its enough). Java uses this encoding in its strings.
In Angular 6, you can do this:
In your service file:
function_name(data) {
const url = `the_URL`;
let input = new FormData();
input.append('url', data); // "url" as the key and "data" as value
return this.http.post(url, input).pipe(map((resp: any) => resp));
}
In component.ts file: in any function say xyz,
xyz(){
this.Your_service_alias.function_name(data).subscribe(d => { // "data" can be your file or image in base64 or other encoding
console.log(d);
});
}
You need to set option CURLOPT_PROXYTYPE
to CURLPROXY_SOCKS5_HOSTNAME
, which sadly wasn't defined in old PHP versions, circa pre-5.6; if you have earlier in but you can explicitly use its value, which is equal to 7
:
curl_setopt($ch, CURLOPT_PROXYTYPE, 7);
You could easily create your own control inheriting from TextBox and reuse it throughout your project.
Something similar to this should work:
public class SubmitTextBox : TextBox
{
public SubmitTextBox()
: base()
{
PreviewKeyDown += new KeyEventHandler(SubmitTextBox_PreviewKeyDown);
}
void SubmitTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
BindingExpression be = GetBindingExpression(TextBox.TextProperty);
if (be != null)
{
be.UpdateSource();
}
}
}
}
There may be a way to get around this step, but otherwise you should bind like this (using Explicit):
<custom:SubmitTextBox
Text="{Binding Path=BoundProperty, UpdateSourceTrigger=Explicit}" />
You can save your array as a json.
there is documentation for json data type: https://dev.mysql.com/doc/refman/5.7/en/json.html
I think this is the best solution, and will help you maintain your code more readable by avoiding crazy functions.
I expect this is helpful for you.
Set Label
's AutoSize
property to False
, TextAlign
property to MiddleCenter
and Dock
property to Fill
.
There is no format specifier for bool
types. However, since any integral type shorter than int
is promoted to int
when passed down to printf()
's variadic arguments, you can use %d
:
bool x = true;
printf("%d\n", x); // prints 1
But why not:
printf(x ? "true" : "false");
or, better:
printf("%s", x ? "true" : "false");
or, even better:
fputs(x ? "true" : "false", stdout);
instead?
Take an input float as left. Then take the button and float it right. You can clearfix class when you take more than one to distance.
<input style="width:65%;float:left"class="btn btn-primary" type="text" name="name">
<div style="width:8%;float:left"> </div>
<button class="btn btn-default" type="button">Go!</button>
<div class="clearfix" style="margin-bottom:10px"> </div>
You can make extension to just change one color component
static class ColorExtension
{
public static Color ChangeG(Color this color,byte g)
{
return Color.FromArgb(color.A,color.R,g,color.B);
}
}
then you can use this:
yourColor = yourColor.ChangeG(100);
Well, timing to the rescue again. It seems switch
is generally faster than if
statements.
So that, and the fact that the code is shorter/neater with a switch
statement leans in favor of switch
:
# Simplified to only measure the overhead of switch vs if
test1 <- function(type) {
switch(type,
mean = 1,
median = 2,
trimmed = 3)
}
test2 <- function(type) {
if (type == "mean") 1
else if (type == "median") 2
else if (type == "trimmed") 3
}
system.time( for(i in 1:1e6) test1('mean') ) # 0.89 secs
system.time( for(i in 1:1e6) test2('mean') ) # 1.13 secs
system.time( for(i in 1:1e6) test1('trimmed') ) # 0.89 secs
system.time( for(i in 1:1e6) test2('trimmed') ) # 2.28 secs
Update With Joshua's comment in mind, I tried other ways to benchmark. The microbenchmark seems the best. ...and it shows similar timings:
> library(microbenchmark)
> microbenchmark(test1('mean'), test2('mean'), times=1e6)
Unit: nanoseconds
expr min lq median uq max
1 test1("mean") 709 771 864 951 16122411
2 test2("mean") 1007 1073 1147 1223 8012202
> microbenchmark(test1('trimmed'), test2('trimmed'), times=1e6)
Unit: nanoseconds
expr min lq median uq max
1 test1("trimmed") 733 792 843 944 60440833
2 test2("trimmed") 2022 2133 2203 2309 60814430
Final Update Here's showing how versatile switch
is:
switch(type, case1=1, case2=, case3=2.5, 99)
This maps case2
and case3
to 2.5
and the (unnamed) default to 99
. For more information, try ?switch
I found w3schools.com howto, their try me page is at the following.
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_trigger_button_enter
This worked in my regular browser but did not work in my php app which uses the built in php browser.
After toying a bit I came up with the following pure JavaScript alternative that works for my situation and should work in every other situation:
function checkForEnterKey(){
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("myBtn").click();
}
}
function buttonClickEvent()
{
alert('The button has been clicked!');
}
HTML Press the enter key inside the textbox to activate the button.
<br />
<input id="myInput" onkeyup="checkForEnterKey(this.value)">
<br />
<button id="myBtn" onclick="buttonClickEvent()">Button</button>
I know it's an old question, but I just had to find solution for multiple rows update where multiple records had to updated with different values based on their IDs and I found that I can use a a scalar-subselect:
UPDATE PROJECT
SET DEPTNO =
(SELECT WORKDEPT FROM EMPLOYEE
WHERE PROJECT.RESPEMP = EMPLOYEE.EMPNO)
WHERE RESPEMP='000030'
(with WHERE optional, of course)
Also, I found that it is critical to specify that no NULL values would not be used in this update (in case not all records in first table have corresponding record in the second one), this way:
UPDATE PROJECT
SET DEPTNO =
(SELECT WORKDEPT FROM EMPLOYEE
WHERE PROJECT.RESPEMP = EMPLOYEE.EMPNO)
WHERE RESPEMP IN (SELECT EMPNO FROM EMPLOYEE)
Source: https://www.ibm.com/support/knowledgecenter/ssw_i5_54/sqlp/rbafyupdatesub.htm
You have to create __init__.py
on the Models
subfolder. The file may be empty. It defines a package.
Then you can do:
from Models.user import User
Read all about it in python tutorial, here.
There is also a good article about file organization of python projects here.
Yes but it depends what you want to execute:
E.g.
try {
a();
b();
}
catch(Exception $e){
}
c();
c()
will always be executed. But if a()
throws an exception, b()
is not executed.
Only put the stuff in to the try
block that is depended on each other. E.g. b
depends on some result of a
it makes no sense to put b
after the try-catch
block.
If I want to create JavaScript Object from string generated by for loop then I would JSON to Object approach. I would generate JSON string by iterating for loop and then use any popular JavaScript Framework to evaluate JSON to Object.
I have used Prototype JavaScript Framework. I have two array with keys and values. I iterate through for loop and generate valid JSON string. I use evalJSON() function to convert JSON string to JavaScript object.
Here is example code. Tryout on your FireBug Console
var key = ["color", "size", "fabric"];
var value = ["Black", "XL", "Cotton"];
var json = "{ ";
for(var i = 0; i < key.length; i++) {
(i + 1) == key.length ? json += "\"" + key[i] + "\" : \"" + value[i] + "\"" : json += "\"" + key[i] + "\" : \"" + value[i] + "\",";
}
json += " }";
var obj = json.evalJSON(true);
console.log(obj);
I would heartily recommend relative URLs for pointing bits of the same site to other bits of the same site.
Don't forget that a change to HTTPS - even if in the same site - is going to need an absolute URL.
I am using this in my code.Try this
var x=$("#checkbox").is(":checked");
If the checkbox is checked x
will be true otherwise it will be false.
Specify paths
--app
--one
one.module.ts
--services
--two
two.module.ts
--services
Create Service with new folder in module ONE
ng g service one/services/myNewServiceFolderName/serviceOne --module one/one
--one
one.module.ts // service imported and added to providers.
--services
--myNewServiceFolderName
serviceOne.service.ts
serviceOne.service.spec.ts
This problem was solved for me by repairing vmware
with the run installer which fixed the services correctly.
Here is one way you could do it...
find . -type f -name "*_peaks.bed" | egrep -v "^(./tmp/|./scripts/)"
DateTimeFormat
, introduced in java 8:The idea is to define two formats: one for the input format, and one for the output format. Parse with the input formatter, then format with the output formatter.
Your input format looks quite standard, except the trailing Z
. Anyway, let's deal with this: "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
. The trailing 'Z'
is the interesting part. Usually there's time zone data here, like -0700
. So the pattern would be ...Z
, i.e. without apostrophes.
The output format is way more simple: "dd-MM-yyyy"
. Mind the small y
-s.
Here is the example code:
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyy", Locale.ENGLISH);
LocalDate date = LocalDate.parse("2018-04-10T04:00:00.000Z", inputFormatter);
String formattedDate = outputFormatter.format(date);
System.out.println(formattedDate); // prints 10-04-2018
SimpleDateFormat
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
SimpleDateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = inputFormat.parse("2018-04-10T04:00:00.000Z");
String formattedDate = outputFormat.format(date);
System.out.println(formattedDate); // prints 10-04-2018
std::sort(object.begin(), object.end(), pred());
where, pred()
is a function object defining the order on objects of myclass
. Alternatively, you can define myclass::operator<
.
For example, you can pass a lambda:
std::sort(object.begin(), object.end(),
[] (myclass const& a, myclass const& b) { return a.v < b.v; });
Or if you're stuck with C++03, the function object approach (v
is the member on which you want to sort):
struct pred {
bool operator()(myclass const & a, myclass const & b) const {
return a.v < b.v;
}
};
You can use this simple code:
<a href="" onclick="return false;">add new action</a><br>
Use request.args
to get parsed contents of query string:
from flask import request
@app.route(...)
def login():
username = request.args.get('username')
password = request.args.get('password')
If you have jQuery UI (needed for the datepicker), this would do the trick:
$.datepicker.formatDate('yy/mm/dd', new Date());
That doesn't work because, judging by the rest of the code, the initial value of the text input is "Default text" - which is more than one character, and so your if
condition is always true.
The simplest way to make it work, it seems to me, is to account for this case:
var value = $(this).val();
if ( value.length > 0 && value != "Default text" ) ...
Swift 5.3, I believe.
The normal array wasvar myArray = ["Steve", "Bill", "Linus", "Bret"]
and you want to add "Tim"
to the array, then you can use myArray.insert("Tim", at=*index*)
so if you want to add it at the back of the array, then you can use myArray.append("Tim", at: 3)
1,new Long(intValue);
2,Long.valueOf(intValue);