update
update
ngComponentOutlet
was added to 4.0.0-beta.3
update
There is a NgComponentOutlet
work in progress that does something similar https://github.com/angular/angular/pull/11235
RC.7
// Helper component to add dynamic components
@Component({
selector: 'dcl-wrapper',
template: `<div #target></div>`
})
export class DclWrapper {
@ViewChild('target', {read: ViewContainerRef}) target: ViewContainerRef;
@Input() type: Type<Component>;
cmpRef: ComponentRef<Component>;
private isViewInitialized:boolean = false;
constructor(private componentFactoryResolver: ComponentFactoryResolver, private compiler: Compiler) {}
updateComponent() {
if(!this.isViewInitialized) {
return;
}
if(this.cmpRef) {
// when the `type` input changes we destroy a previously
// created component before creating the new one
this.cmpRef.destroy();
}
let factory = this.componentFactoryResolver.resolveComponentFactory(this.type);
this.cmpRef = this.target.createComponent(factory)
// to access the created instance use
// this.compRef.instance.someProperty = 'someValue';
// this.compRef.instance.someOutput.subscribe(val => doSomething());
}
ngOnChanges() {
this.updateComponent();
}
ngAfterViewInit() {
this.isViewInitialized = true;
this.updateComponent();
}
ngOnDestroy() {
if(this.cmpRef) {
this.cmpRef.destroy();
}
}
}
Usage example
// Use dcl-wrapper component
@Component({
selector: 'my-tabs',
template: `
<h2>Tabs</h2>
<div *ngFor="let tab of tabs">
<dcl-wrapper [type]="tab"></dcl-wrapper>
</div>
`
})
export class Tabs {
@Input() tabs;
}
@Component({
selector: 'my-app',
template: `
<h2>Hello {{name}}</h2>
<my-tabs [tabs]="types"></my-tabs>
`
})
export class App {
// The list of components to create tabs from
types = [C3, C1, C2, C3, C3, C1, C1];
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App, DclWrapper, Tabs, C1, C2, C3],
entryComponents: [C1, C2, C3],
bootstrap: [ App ]
})
export class AppModule {}
See also angular.io DYNAMIC COMPONENT LOADER
older versions xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
This changed again in Angular2 RC.5
I will update the example below but it's the last day before vacation.
This Plunker example demonstrates how to dynamically create components in RC.5
Update - use ViewContainerRef.createComponent()
Because DynamicComponentLoader
is deprecated, the approach needs to be update again.
@Component({
selector: 'dcl-wrapper',
template: `<div #target></div>`
})
export class DclWrapper {
@ViewChild('target', {read: ViewContainerRef}) target;
@Input() type;
cmpRef:ComponentRef;
private isViewInitialized:boolean = false;
constructor(private resolver: ComponentResolver) {}
updateComponent() {
if(!this.isViewInitialized) {
return;
}
if(this.cmpRef) {
this.cmpRef.destroy();
}
this.resolver.resolveComponent(this.type).then((factory:ComponentFactory<any>) => {
this.cmpRef = this.target.createComponent(factory)
// to access the created instance use
// this.compRef.instance.someProperty = 'someValue';
// this.compRef.instance.someOutput.subscribe(val => doSomething());
});
}
ngOnChanges() {
this.updateComponent();
}
ngAfterViewInit() {
this.isViewInitialized = true;
this.updateComponent();
}
ngOnDestroy() {
if(this.cmpRef) {
this.cmpRef.destroy();
}
}
}
Plunker example RC.4
Plunker example beta.17
Update - use loadNextToLocation
export class DclWrapper {
@ViewChild('target', {read: ViewContainerRef}) target;
@Input() type;
cmpRef:ComponentRef;
private isViewInitialized:boolean = false;
constructor(private dcl:DynamicComponentLoader) {}
updateComponent() {
// should be executed every time `type` changes but not before `ngAfterViewInit()` was called
// to have `target` initialized
if(!this.isViewInitialized) {
return;
}
if(this.cmpRef) {
this.cmpRef.destroy();
}
this.dcl.loadNextToLocation(this.type, this.target).then((cmpRef) => {
this.cmpRef = cmpRef;
});
}
ngOnChanges() {
this.updateComponent();
}
ngAfterViewInit() {
this.isViewInitialized = true;
this.updateComponent();
}
ngOnDestroy() {
if(this.cmpRef) {
this.cmpRef.destroy();
}
}
}
original
Not entirely sure from your question what your requirements are but I think this should do what you want.
The Tabs
component gets an array of types passed and it creates "tabs" for each item in the array.
@Component({
selector: 'dcl-wrapper',
template: `<div #target></div>`
})
export class DclWrapper {
constructor(private elRef:ElementRef, private dcl:DynamicComponentLoader) {}
@Input() type;
ngOnChanges() {
if(this.cmpRef) {
this.cmpRef.dispose();
}
this.dcl.loadIntoLocation(this.type, this.elRef, 'target').then((cmpRef) => {
this.cmpRef = cmpRef;
});
}
}
@Component({
selector: 'c1',
template: `<h2>c1</h2>`
})
export class C1 {
}
@Component({
selector: 'c2',
template: `<h2>c2</h2>`
})
export class C2 {
}
@Component({
selector: 'c3',
template: `<h2>c3</h2>`
})
export class C3 {
}
@Component({
selector: 'my-tabs',
directives: [DclWrapper],
template: `
<h2>Tabs</h2>
<div *ngFor="let tab of tabs">
<dcl-wrapper [type]="tab"></dcl-wrapper>
</div>
`
})
export class Tabs {
@Input() tabs;
}
@Component({
selector: 'my-app',
directives: [Tabs]
template: `
<h2>Hello {{name}}</h2>
<my-tabs [tabs]="types"></my-tabs>
`
})
export class App {
types = [C3, C1, C2, C3, C3, C1, C1];
}
Plunker example beta.15 (not based on your Plunker)
There is also a way to pass data along that can be passed to the dynamically created component like (someData
would need to be passed like type
)
this.dcl.loadIntoLocation(this.type, this.elRef, 'target').then((cmpRef) => {
cmpRef.instance.someProperty = someData;
this.cmpRef = cmpRef;
});
There is also some support to use dependency injection with shared services.
For more details see https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html
You've to create empty constructor because JAX-RS initializes the classes... Your constructor must have no arguments:
@XmlRootElement
public class Student implements Serializable {
public String first_name;
public String last_name;
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public Student()
{
first_name = "Fahad";
last_name = "Mullaji";
}
public Student()
{
}
}
Without explicitly providing the type as in command.Parameters.Add("@ID", SqlDbType.Int);
, it will try to implicitly convert the input to what it is expecting.
The downside of this, is that the implicit conversion may not be the most optimal of conversions and may cause a performance hit.
There is a discussion about this very topic here: http://forums.asp.net/t/1200255.aspx/1
I have just found a PHP function "strip_tags()" and its working in my case.
I tried to convert the following HTML :
<p><span style="font-family: 'Verdana','sans-serif'; color: black; font-size: 7.5pt;"> </span>Many practitioners are optimistic that the eyeglass and contact lens industry will recover from the recent economic storm. Did your practice feel its affects? Statistics show revenue notably declined in 2008 and 2009. But interestingly enough, those that monitor these trends state that despite the industry's lackluster performance during this time, revenue has grown at an average annual rate of 2.2% over the last five years, to $9.0 billion in 2010. So despite the downturn, how were we able to manage growth as an industry?</p>
After applying strip_tags() function, I have got the following output :
&nbsp;Many practitioners are optimistic that the eyeglass and contact lens industry will recover from the recent economic storm. Did your practice feel its affects?&nbsp; Statistics show revenue notably declined in 2008 and 2009. But interestingly enough, those that monitor these trends state that despite the industry's lackluster performance during this time, revenue has grown at an average annual rate&nbsp;of 2.2% over the last five years, to $9.0 billion in 2010.&nbsp; So despite the downturn, how were we able to manage growth as an industry?
Don't include header.php. You should not output HTML when you are going to redirect.
Make a new file, eg. "pre.php". Put this in it:
<?php
include('class.user.php');
include('class.Connection.php');
?>
Then in header.php, include that, in stead of including the two other files. In form.php, include pre.php in stead of header.php.
For those looking for a solution from an Angular perspective, this worked for me:
$http.post(
'url',
{},
{responseType: 'arraybuffer'}
).then(function (response) {
var headers = response.headers();
var blob = new Blob([response.data],{type:headers['content-type']});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "Filename";
link.click();
});
Place this at the top of your script. It will cause the script to prompt the user for a password. The resulting password can then be used elsewhere in your script via $pw.
Param(
[Parameter(Mandatory=$true, Position=0, HelpMessage="Password?")]
[SecureString]$password
)
$pw = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))
If you want to debug and see the value of the password you just read, use:
write-host $pw
According to this, you will need .NET 4.5 installed. For more details, visit the webpage. The gist of it is that after you have .NET 4.5 installed, your 4.0 apps will use the 4.5 System.dll. You can enable TLS 1.2 in two ways:
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319: SchUseStrongCrypto
to DWORD 1
Just had the same issue after VS crashed and Rahul's comment regarding the application pool pointed me in the right direction. In my case recycling the app pool did the trick (IIS Manager => App Pools => right click on ap in question and recycle).
Just wanted to mention react-router v4 changed radically since this question was posted/answed.
There is no <Match>
component any more! <Switch>
is to make sure only the first match is rendered. <Redirect>
well .. redirects to another route. Use or leave out exact
to either in- or exclude a partial match.
See the docs. They are great. https://reacttraining.com/react-router/
Here's an example I hope is useable to answer your question.
<Router>
<div>
<Redirect exact from='/' to='/front'/>
<Route path="/" render={() => {
return (
<div>
<h2>Home menu</h2>
<Link to="/front">front</Link>
<Link to="/back">back</Link>
</div>
);
}} />
<Route path="/front" render={() => {
return (
<div>
<h2>front menu</h2>
<Link to="/front/help">help</Link>
<Link to="/front/about">about</Link>
</div>
);
}} />
<Route exact path="/front/help" render={() => {
return <h2>front help</h2>;
}} />
<Route exact path="/front/about" render={() => {
return <h2>front about</h2>;
}} />
<Route path="/back" render={() => {
return (
<div>
<h2>back menu</h2>
<Link to="/back/help">help</Link>
<Link to="/back/about">about</Link>
</div>
);
}} />
<Route exact path="/back/help" render={() => {
return <h2>back help</h2>;
}} />
<Route exact path="/back/about" render={() => {
return <h2>back about</h2>;
}} />
</div>
</Router>
Hope it helped, let me know. If this example is not answering your question well enough, tell me and I'll see if I can modify it.
Another way to do this, is by using the .NET System.Management querying facilities:
string Query = "SELECT Capacity FROM Win32_PhysicalMemory";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(Query);
UInt64 Capacity = 0;
foreach (ManagementObject WniPART in searcher.Get())
{
Capacity += Convert.ToUInt64(WniPART.Properties["Capacity"].Value);
}
return Capacity;
You should use @input
:
<input @input="handleInput" />
@input
fires when user changes input value.
@change
fires when user changed value and unfocus input (for example clicked somewhere outside)
You can see the difference here: https://jsfiddle.net/posva/oqe9e8pb/
React Router 4 includes a withRouter HOC that gives you access to the history
object via this.props
:
import React, {Component} from 'react'
import {withRouter} from 'react-router-dom'
class Foo extends Component {
constructor(props) {
super(props)
this.goHome = this.goHome.bind(this)
}
goHome() {
this.props.history.push('/')
}
render() {
<div className="foo">
<button onClick={this.goHome} />
</div>
}
}
export default withRouter(Foo)
Sooooo, I had this same question. here's my answer: COUNTIFS(sheet1!$A:$A,">="&D1,sheet1!$A:$A,"<="&D2)
you don't need to specify A2:A50, unless there are dates beyond row 50 that you wish to exclude. this is cleaner in the sense that you don't have to go back and adjust the rows as more PO data comes in on sheet1.
also, the reference to D1 and D2 are start and end dates (respectively) for each month. On sheet2, you could have a hidden column that translates April to 4/1/2014, May into 5/1/2014, etc. THen, D1 would reference the cell that contains 4/1/2014, and D2 would reference the cell that contains 5/1/2014.
if you want to sum, it works the same way, except that the first argument is the sum array (column or row) and then the rest of the ranges/arrays and arguments are the same as the countifs formula.
btw-this works in excel AND google sheets. cheers
You could use:
jQuery('input[type="date"]').live('click', function(e) {e.preventDefault();}).datepicker();
For me the issue got fixed when I changed
<id name="personID" column="person_id">
<generator class="native"/>
</id>
to
<id name="personID" column="person_id">
<generator class="increment"/>
</id>
in my Person.hbm.xml
.
after that I re-encountered that same error for an another field(mobno). I tried restarting my IDE, recreating the database with previous back issue got eventually fixed when I re-create my tables using (without ENGINE=InnoDB DEFAULT CHARSET=latin1;
and removing underscores in the field name)
CREATE TABLE `tbl_customers` (
`pid` bigint(20) NOT NULL,
`title` varchar(4) NOT NULL,
`dob` varchar(10) NOT NULL,
`address` varchar(100) NOT NULL,
`country` varchar(4) DEFAULT NULL,
`hometp` int(12) NOT NULL,
`worktp` int(12) NOT NULL,
`mobno` varchar(12) NOT NULL,
`btcfrom` varchar(8) NOT NULL,
`btcto` varchar(8) NOT NULL,
`mmname` varchar(20) NOT NULL
)
instead of
CREATE TABLE `tbl_person` (
`person_id` bigint(20) NOT NULL,
`person_nic` int(10) NOT NULL,
`first_name` varchar(20) NOT NULL,
`sur_name` varchar(20) NOT NULL,
`person_email` varchar(20) NOT NULL,
`person_password` varchar(512) NOT NULL,
`mobno` varchar(10) NOT NULL DEFAULT '1',
`role` varchar(10) NOT NULL,
`verified` int(1) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
I probably think this due to using ENGINE=InnoDB DEFAULT CHARSET=latin1;
, because I once got the error org.hibernate.engine.jdbc.spi.SqlExceptionHelper - Unknown column 'mob_no' in 'field list'
even though it was my previous column name, which even do not exist in my current table. Even after backing up the database(with modified column name, using InnoDB engine) I still got that same error with old field name. This probably due to caching in that Engine.
You may also consider using line.rstrip() to remove the whitespaces at the end of your line.
Appending a single scalar could be done a bit easier as already shown (and also without converting to float) by expanding the scalar to a python-list-type:
import numpy as np
a = np.array([[1,3,4],[1,2,3],[1,2,1]])
x = 10
b = np.hstack ((a, [[x]] * len (a) ))
returns b
as:
array([[ 1, 3, 4, 10],
[ 1, 2, 3, 10],
[ 1, 2, 1, 10]])
Appending a row could be done by:
c = np.vstack ((a, [x] * len (a[0]) ))
returns c
as:
array([[ 1, 3, 4],
[ 1, 2, 3],
[ 1, 2, 1],
[10, 10, 10]])
EventHandler.GetInvocationList().Length > 0
Check out this directive: https://github.com/samu/angular-table
It automates sorting and pagination a lot and gives you enough freedom to customize your table/list however you want.
@ECHO OFF
:: %HOMEDRIVE% = C:
:: %HOMEPATH% = \Users\Ruben
:: %system32% ??
:: No spaces in paths
:: Program Files > ProgramFiles
:: cls = clear screen
:: CMD reads the system environment variables when it starts. To re-read those variables you need to restart CMD
:: Use console 2 http://sourceforge.net/projects/console/
:: Assign all Path variables
SET PHP="%HOMEDRIVE%\wamp\bin\php\php5.4.16"
SET SYSTEM32=";%HOMEDRIVE%\Windows\System32"
SET ANT=";%HOMEDRIVE%%HOMEPATH%\Downloads\apache-ant-1.9.0-bin\apache-ant-1.9.0\bin"
SET GRADLE=";%HOMEDRIVE%\tools\gradle-1.6\bin;"
SET ADT=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\eclipse\jre\bin"
SET ADTTOOLS=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\tools"
SET ADTP=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\platform-tools"
SET YII=";%HOMEDRIVE%\wamp\www\yii\framework"
SET NODEJS=";%HOMEDRIVE%\ProgramFiles\nodejs"
SET CURL=";%HOMEDRIVE%\tools\curl_734_0_ssl"
SET COMPOSER=";%HOMEDRIVE%\ProgramData\ComposerSetup\bin"
SET GIT=";%HOMEDRIVE%\Program Files\Git\cmd"
:: Set Path variable
setx PATH "%PHP%%SYSTEM32%%NODEJS%%COMPOSER%%YII%%GIT%" /m
:: Set Java variable
setx JAVA_HOME "%HOMEDRIVE%\ProgramFiles\Java\jdk1.7.0_21" /m
PAUSE
You can add a shebang line the to the top of the script:
#!/usr/bin/env python2.7
But that will only work when executing as ./my_program.py
.
If you execute as python my_program.py
, then the whatever Python version that which python
returns will be used.
In re: to virtualenv use: virtualenv -p /usr/bin/python3.2
or whatever to set it up to use that Python executable.
Bootstrap 3 dropped native support for nested collapsing menus, but there's a way to re-enable it with a 3rd party script. It's called SmartMenus. It means adding three new resources to your page, but it seamlessly supports Bootstrap 3.x with multiple levels of menus for nested <ul>/<li>
elements with class="dropdown-menu"
. It automatically displays the proper caret indicator as well.
<head>
...
<script src=".../jquery.smartmenus.min.js"></script>
<script src=".../jquery.smartmenus.bootstrap.min.js"></script>
...
<link rel="stylesheet" href=".../jquery.smartmenus.bootstrap.min.css"/>
...
</head>
Here's a demo page: http://vadikom.github.io/smartmenus/src/demo/bootstrap-navbar-fixed-top.html
As I started to update my old project to Swift 3.2, I just needed to change the method from
respondsToSelector(selector)
to:
responds(to: selector)
So what are you doing is with append and concat is almost equivalent. The difference is the empty DataFrame. For some reason this causes a big slowdown, not sure exactly why, will have to look at some point. Below is a recreation of basically what you did.
I almost always use concat (though in this case they are equivalent, except for the empty frame); if you don't use the empty frame they will be the same speed.
In [17]: df1 = pd.DataFrame(dict(A = range(10000)),index=pd.date_range('20130101',periods=10000,freq='s'))
In [18]: df1
Out[18]:
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 10000 entries, 2013-01-01 00:00:00 to 2013-01-01 02:46:39
Freq: S
Data columns (total 1 columns):
A 10000 non-null values
dtypes: int64(1)
In [19]: df4 = pd.DataFrame()
The concat
In [20]: %timeit pd.concat([df1,df2,df3])
1000 loops, best of 3: 270 us per loop
This is equavalent of your append
In [21]: %timeit pd.concat([df4,df1,df2,df3])
10 loops, best of
3: 56.8 ms per loop
You can pass your arguments using this encodeURIComponent function so you don't have to worry about passing any special characters.
data: "param1=getAccNos¶m2="+encodeURIComponent('Dolce & Gabbana')
OR
var someValue = 'Dolce & Gabbana';
data: "param1=getAccNos¶m2="+encodeURIComponent(someValue)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
I tried various approaches but all seem flawed or I have to makeup some code, that's annoying. But there's a convinient way under linux, that is simply to find every test through certain pattern and then invoke them one by one.
find . -name 'Test*py' -exec python '{}' \;
and most importantly, it definitely works.
Add the following to the top of your file # coding=utf-8
If you go to the link in the error you can seen the reason why:
Defining the Encoding
Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=
If the double is a Double
with capital D (a boxed primitive value):
Double d = 4.97542;
int i = (int) d.doubleValue();
// or directly:
int i2 = d.intValue();
If the double is already a primitive double
, then you simply cast it:
double d = 4.97542;
int i = (int) d;
As a brand new member, I was unable to simply add a comment on the post but I want to second that the solution offered by Phillip Schwartz worked for me. Hopefully people in a similar situation will try that path sooner with the emphasis. Not having page breaks was a frustrating problem for quite a while so I am grateful for the discussion above.
As Phillip Schwartz said: "You'll need to install wkhtmltopdf: [http://wkhtmltopdf.org/downloads.html][1]
and Nbconvert "
You then add a cell of the type "rawNBConvert" and include:
<p style="page-break-after:always;"></p>
That seemed to do the trick for me, and the generated PDF had the page break at the corresponding locations. You don't need to run the custom code though, as it seems the "normal" path of downloading the notebook as HTML, opening in browser, and printing to PDF works once those utilities are installed.
Maybe you can leverage the std::bitset
type available in C++11. It can be used to represent a fixed sequence of N
bits, which can be manipulated by conventional logic.
#include<iostream>
#include<bitset>
class MissileLauncher {
public:
MissileLauncher() {}
void show_bits() const {
std::cout<<m_abc[2]<<", "<<m_abc[1]<<", "<<m_abc[0]<<std::endl;
}
bool toggle_a() {
// toggles (i.e., flips) the value of `a` bit and returns the
// resulting logical value
m_abc[0].flip();
return m_abc[0];
}
bool toggle_c() {
// toggles (i.e., flips) the value of `c` bit and returns the
// resulting logical value
m_abc[2].flip();
return m_abc[2];
}
bool matches(const std::bitset<3>& mask) {
// tests whether all the bits specified in `mask` are turned on in
// this instance's bitfield
return ((m_abc & mask) == mask);
}
private:
std::bitset<3> m_abc;
};
typedef std::bitset<3> Mask;
int main() {
MissileLauncher ml;
// notice that the bitset can be "built" from a string - this masks
// can be made available as constants to test whether certain bits
// or bit combinations are "on" or "off"
Mask has_a("001"); // the zeroth bit
Mask has_b("010"); // the first bit
Mask has_c("100"); // the second bit
Mask has_a_and_c("101"); // zeroth and second bits
Mask has_all_on("111"); // all on!
Mask has_all_off("000"); // all off!
// I can even create masks using standard logic (in this case I use
// the or "|" operator)
Mask has_a_and_b = has_a | has_b;
std::cout<<"This should be 011: "<<has_a_and_b<<std::endl;
// print "true" and "false" instead of "1" and "0"
std::cout<<std::boolalpha;
std::cout<<"Bits, as created"<<std::endl;
ml.show_bits();
std::cout<<"is a turned on? "<<ml.matches(has_a)<<std::endl;
std::cout<<"I will toggle a"<<std::endl;
ml.toggle_a();
std::cout<<"Resulting bits:"<<std::endl;
ml.show_bits();
std::cout<<"is a turned on now? "<<ml.matches(has_a)<<std::endl;
std::cout<<"are both a and c on? "<<ml.matches(has_a_and_c)<<std::endl;
std::cout<<"Toggle c"<<std::endl;
ml.toggle_c();
std::cout<<"Resulting bits:"<<std::endl;
ml.show_bits();
std::cout<<"are both a and c on now? "<<ml.matches(has_a_and_c)<<std::endl;
std::cout<<"but, are all bits on? "<<ml.matches(has_all_on)<<std::endl;
return 0;
}
Compiling using gcc 4.7.2
g++ example.cpp -std=c++11
I get:
This should be 011: 011
Bits, as created
false, false, false
is a turned on? false
I will toggle a
Resulting bits:
false, false, true
is a turned on now? true
are both a and c on? false
Toggle c
Resulting bits:
true, false, true
are both a and c on now? true
but, are all bits on? false
If this is coming from SQL Server Import Wizard, try editing the definition of the column on the Data Source, it is 50 characters by default, but it can be longer.
Data Soruce -> Advanced -> Look at the column that goes in error -> change OutputColumnWidth to 200 and try again.
Use it to achieve what you want. Then decide which properties you want to return.
yourList.OrderBy(l => l.Id).GroupBy(l => new { GroupName = l.F1}).Select(r => r.Key.GroupName)
I had the same problem for different package. I was installing pyinstaller
in conda on Mac Mojave. I did
conda create --name ai37 python=3.7
conda activate ai37
I got the mentioned error when I tried to install pyinstaller using
pip install pyinstaller
I was able to install the pyinstaller with the following command
conda install -c conda-forge pyinstaller
Sometimes you need to pay attention to howw Eclipse is launched. I ever pinned Eclipse by rigk-click on the excutable and pinning it to taskbar. In this way, the Eclipse is launched to use settings under c:\User\public\public Documents\eclipse" which is not very desirable.
However, if you pin it by creating a short-cut, then it will launch to use settings in the folder of Eclipse installation. Then everything makes much more sense.
The reason that you get this error on OSX is the rvm-installed ruby.
If you run into this issue on OSX you can find a really broad explanation of it in this blog post:
http://toadle.me/2015/04/16/fixing-failing-ssl-verification-with-rvm.html
The short version is that, for some versions of Ruby, RVM downloads pre-compiled binaries, which look for certificates in the wrong location. By forcing RVM to download the source and compile on your own machine, you ensure that the configuration for the certificate location is correct.
The command to do this is:
rvm install 2.2.0 --disable-binary
if you already have the version in question, you can re-install it with:
rvm reinstall 2.2.0 --disable-binary
(obviously, substitute your ruby version as needed).
You can refer to event modifiers in vuejs to prevent form submission on enter
key.
It is a very common need to call
event.preventDefault()
orevent.stopPropagation()
inside event handlers.Although we can do this easily inside methods, it would be better if the methods can be purely about data logic rather than having to deal with DOM event details.
To address this problem, Vue provides event modifiers for
v-on
. Recall that modifiers are directive postfixes denoted by a dot.
<form v-on:submit.prevent="<method>">
...
</form>
As the documentation states, this is syntactical sugar for e.preventDefault()
and will stop the unwanted form submission on press of enter key.
Here is a working fiddle.
new Vue({_x000D_
el: '#myApp',_x000D_
data: {_x000D_
emailAddress: '',_x000D_
log: ''_x000D_
},_x000D_
methods: {_x000D_
validateEmailAddress: function(e) {_x000D_
if (e.keyCode === 13) {_x000D_
alert('Enter was pressed');_x000D_
} else if (e.keyCode === 50) {_x000D_
alert('@ was pressed');_x000D_
} _x000D_
this.log += e.key;_x000D_
},_x000D_
_x000D_
postEmailAddress: function() {_x000D_
this.log += '\n\nPosting';_x000D_
},_x000D_
noop () {_x000D_
// do nothing ?_x000D_
}_x000D_
}_x000D_
})
_x000D_
html, body, #editor {_x000D_
margin: 0;_x000D_
height: 100%;_x000D_
color: #333;_x000D_
}
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>_x000D_
<div id="myApp" style="padding:2rem; background-color:#fff;">_x000D_
<form v-on:submit.prevent="noop">_x000D_
<input type="text" v-model="emailAddress" v-on:keyup="validateEmailAddress" />_x000D_
<button type="button" v-on:click="postEmailAddress" >Subscribe</button> _x000D_
<br /><br />_x000D_
_x000D_
<textarea v-model="log" rows="4"></textarea> _x000D_
</form>_x000D_
</div>
_x000D_
You can simply use:
document.getElementById(button_id).innerText = 'Your text here';
If you want to use HTML formatting, use the innerHTML
property instead.
This is old I know, but just a pointer to anyone using this ass a reference. I have just tried this and if you are using Oracle, JOIN does not work in DELETE statements. You get a the following message:
ORA-00933: SQL command not properly ended.
There is a comand to directly do that:
Create a new kubectl rollout restart
command that does a rolling restart of a deployment.
The pull request got merged. It is part of the version 1.15
(changelog) or higher.
Here is a good article from Microsoft http://www.iis.net/learn/troubleshoot/security-issues/troubleshooting-forms-authentication that covers various cases and scenarios.
These are the two options I managed to build, not having the luxury of working with var
type, nor with additional variables on the line:
string f = "aS.".Substring(0, "aS.".IndexOf("S"));
Console.WriteLine(f);
string s = "aS.".Split("S".ToCharArray(),StringSplitOptions.RemoveEmptyEntries)[0];
Console.WriteLine(s);
This is what it gets:
Another alternative, not sure if this applies to your particular problem but to some it may be applicable is to use UnaryOperator
in java.util.function library.
where it returns same type you specify, so you put all your variables in one class and is it as a parameter:
public class FunctionsLibraryUse {
public static void main(String[] args){
UnaryOperator<People> personsBirthday = (p) ->{
System.out.println("it's " + p.getName() + " birthday!");
p.setAge(p.getAge() + 1);
return p;
};
People mel = new People();
mel.setName("mel");
mel.setAge(27);
mel = personsBirthday.apply(mel);
System.out.println("he is now : " + mel.getAge());
}
}
class People{
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
So the class you have, in this case Person
, can have numerous instance variables and won't have to change the parameter of your lambda expression.
For those interested, I've written notes on how to use java.util.function library: http://sysdotoutdotprint.com/index.php/2017/04/28/java-util-function-library/
I had this problem after changing the git access password!
I had to reset the credentials through the PowerShell console.
At the git repository folder level, the script was as follows:
git config --system --unset credential.helper
git config --system credential.helper store
git fetch
You will be prompted for the user and then the password.
The next command will no longer request authentication:
git fetch
Yes it's the exact same thing in Python 2:
d.values()
In Python 3 (where dict.values
returns a view of the dictionary’s values instead):
list(d.values())
This an old question, but I have had to explain it to someone recently and I thought recording the answer here would be helpful at least in understanding how C works.
String literals like
"a"
or
"This is a string"
are put in the text or data segments of your program.
A string in C is actually a pointer to a char, and the string is understood to be the subsequent chars in memory up until a NUL char is encountered. That is, C doesn't really know about strings.
So if I have
char *s1 = "This is a string";
then s1 is a pointer to the first byte of the string.
Now, if I have
char *s2 = "This is a string";
this is also a pointer to the same first byte of that string in the text or data segment of the program.
But if I have
char *s3 = malloc( 17 );
strcpy(s3, "This is a string");
then s3 is a pointer to another place in memory into which I copy all the bytes of the other strings.
Illustrative examples:
Although, as your compiler rightly points out, you shouldn't do this, the following will evaluate to true:
s1 == s2 // True: we are comparing two pointers that contain the same address
but the following will evaluate to false
s1 == s3 // False: Comparing two pointers that don't hold the same address.
And although it might be tempting to have something like this:
struct Vehicle{
char *type;
// other stuff
}
if( type == "Car" )
//blah1
else if( type == "Motorcycle )
//blah2
You shouldn't do it because it's not something that is guarantied to work. Even if you know that type will always be set using a string literal.
I have tested it and it works. If I do
A.type = "Car";
then blah1 gets executed and similarly for "Motorcycle". And you'd be able to do things like
if( A.type == B.type )
but this is just terrible. I'm writing about it because I think it's interesting to know why it works, and it helps understand why you shouldn't do it.
Solutions:
In your case, what you want to do is use strcmp(a,b) == 0
to replace a == b
In the case of my example, you should use an enum.
enum type {CAR = 0, MOTORCYCLE = 1}
The preceding thing with string was useful because you could print the type, so you might have an array like this
char *types[] = {"Car", "Motorcycle"};
And now that I think about it, this is error prone since one must be careful to maintain the same order in the types array.
Therefore it might be better to do
char *getTypeString(int type)
{
switch(type)
case CAR: return "Car";
case MOTORCYCLE: return "Motorcycle"
default: return NULL;
}
In swift 4.2 I used following code to show and hide code using NSNotification
@objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo? [UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
let keyboardheight = keyboardSize.height
print(keyboardheight)
}
}
The only thing which worked for me is this
fetchData()
.subscribe(
(data) => {
//Called when success
},
(error) => {
//Called when error
}
).add(() => {
//Called when operation is complete (both success and error)
});
Note: This is not unicode compliant.
"IU".split('')
results in the 4 character array["I", "?", "?", "u"]
which can lead to dangerous bugs. See answers below for safe alternatives.
Just split it by an empty string.
var output = "Hello world!".split('');_x000D_
console.log(output);
_x000D_
See the String.prototype.split()
MDN docs.
<context:component-scan base-package="" />
tells Spring to scan those packages for Annotations.
<mvc:annotation-driven>
registers a RequestMappingHanderMapping, a RequestMappingHandlerAdapter, and an ExceptionHandlerExceptionResolver to support the annotated controller methods like @RequestMapping, @ExceptionHandler, etc. that come with MVC.
This also enables a ConversionService that supports Annotation driven formatting of outputs as well as Annotation driven validation for inputs. It also enables support for @ResponseBody which you can use to return JSON data.
You can accomplish the same things using Java-based Configuration using @ComponentScan(basePackages={"...", "..."} and @EnableWebMvc in a @Configuration class.
Check out the 3.1 documentation to learn more.
http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/mvc.html#mvc-config
Just saw this now:
:nnoremap <esc> :noh<return><esc>
I found it in ViEmu Blog and I really dig this. A short explanation - It makes Esc turn off search highlight in normal mode.
The above solution for the JsonCreationConverter<T>
is all over the internet, but has a flaw that manifests itself in rare occasions. The new JsonReader created in the ReadJson method does not inherit any of the original reader's configuration values (Culture, DateParseHandling, DateTimeZoneHandling, FloatParseHandling, etc...). These values should be copied over before using the new JsonReader in serializer.Populate().
This is the best I could come up with to fix some of the problems with the above implementation, but I still think there are some things being overlooked:
Update I updated this to have a more explicit method that makes a copy of an existing reader. This just encapsulates the process of copying over individual JsonReader settings. Ideally this function would be maintained in the Newtonsoft library itself, but for now, you can use the following:
/// <summary>Creates a new reader for the specified jObject by copying the settings
/// from an existing reader.</summary>
/// <param name="reader">The reader whose settings should be copied.</param>
/// <param name="jToken">The jToken to create a new reader for.</param>
/// <returns>The new disposable reader.</returns>
public static JsonReader CopyReaderForObject(JsonReader reader, JToken jToken)
{
JsonReader jTokenReader = jToken.CreateReader();
jTokenReader.Culture = reader.Culture;
jTokenReader.DateFormatString = reader.DateFormatString;
jTokenReader.DateParseHandling = reader.DateParseHandling;
jTokenReader.DateTimeZoneHandling = reader.DateTimeZoneHandling;
jTokenReader.FloatParseHandling = reader.FloatParseHandling;
jTokenReader.MaxDepth = reader.MaxDepth;
jTokenReader.SupportMultipleContent = reader.SupportMultipleContent;
return jTokenReader;
}
This should be used as follows:
public override object ReadJson(JsonReader reader,
Type objectType,
object existingValue,
JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
// Load JObject from stream
JObject jObject = JObject.Load(reader);
// Create target object based on JObject
T target = Create(objectType, jObject);
// Populate the object properties
using (JsonReader jObjectReader = CopyReaderForObject(reader, jObject))
{
serializer.Populate(jObjectReader, target);
}
return target;
}
Older solution follows:
/// <summary>Base Generic JSON Converter that can help quickly define converters for specific types by automatically
/// generating the CanConvert, ReadJson, and WriteJson methods, requiring the implementer only to define a strongly typed Create method.</summary>
public abstract class JsonCreationConverter<T> : JsonConverter
{
/// <summary>Create an instance of objectType, based properties in the JSON object</summary>
/// <param name="objectType">type of object expected</param>
/// <param name="jObject">contents of JSON object that will be deserialized</param>
protected abstract T Create(Type objectType, JObject jObject);
/// <summary>Determines if this converted is designed to deserialization to objects of the specified type.</summary>
/// <param name="objectType">The target type for deserialization.</param>
/// <returns>True if the type is supported.</returns>
public override bool CanConvert(Type objectType)
{
// FrameWork 4.5
// return typeof(T).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo());
// Otherwise
return typeof(T).IsAssignableFrom(objectType);
}
/// <summary>Parses the json to the specified type.</summary>
/// <param name="reader">Newtonsoft.Json.JsonReader</param>
/// <param name="objectType">Target type.</param>
/// <param name="existingValue">Ignored</param>
/// <param name="serializer">Newtonsoft.Json.JsonSerializer to use.</param>
/// <returns>Deserialized Object</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
// Load JObject from stream
JObject jObject = JObject.Load(reader);
// Create target object based on JObject
T target = Create(objectType, jObject);
//Create a new reader for this jObject, and set all properties to match the original reader.
JsonReader jObjectReader = jObject.CreateReader();
jObjectReader.Culture = reader.Culture;
jObjectReader.DateParseHandling = reader.DateParseHandling;
jObjectReader.DateTimeZoneHandling = reader.DateTimeZoneHandling;
jObjectReader.FloatParseHandling = reader.FloatParseHandling;
// Populate the object properties
serializer.Populate(jObjectReader, target);
return target;
}
/// <summary>Serializes to the specified type</summary>
/// <param name="writer">Newtonsoft.Json.JsonWriter</param>
/// <param name="value">Object to serialize.</param>
/// <param name="serializer">Newtonsoft.Json.JsonSerializer to use.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, value);
}
}
\d is a digit, + is 1 or more, so a sequence of 1 or more digits
You need to set the Identity seed to that value:
CREATE TABLE orders
(
id int IDENTITY(9586,1)
)
To alter an existing table:
ALTER TABLE orders ALTER COLUMN Id INT IDENTITY (9586, 1);
More info on CREATE TABLE (Transact-SQL) IDENTITY (Property)
you need to iterate through the array's elements
float foo[] = {1, 2, 3, 10};
int i;
for (i=0;i < (sizeof (foo) /sizeof (foo[0]));i++) {
printf("%lf\n",foo[i]);
}
or create a function that returns stacked sn printf
and then prints it with
printf("%s\n",function_that_makes_pretty_output(foo))
In case a name is assigned like this:
#editForm="testForm"
... the exportAs has to be defined in the component decorator:
selector: 'test-form',
templateUrl: './test-form.component.html',
styleUrls: ['./test-form.component.scss'],
exportAs: 'testForm'
after struggling with this for a couple of hours, I've found that you can only use one db helper object per db execution. For example,
for(int x = 0; x < someMaxValue; x++)
{
db = new DBAdapter(this);
try
{
db.addRow
(
NamesStringArray[i].toString(),
StartTimeStringArray[i].toString(),
EndTimeStringArray[i].toString()
);
}
catch (Exception e)
{
Log.e("Add Error", e.toString());
e.printStackTrace();
}
db.close();
}
as apposed to:
db = new DBAdapter(this);
for(int x = 0; x < someMaxValue; x++)
{
try
{
// ask the database manager to add a row given the two strings
db.addRow
(
NamesStringArray[i].toString(),
StartTimeStringArray[i].toString(),
EndTimeStringArray[i].toString()
);
}
catch (Exception e)
{
Log.e("Add Error", e.toString());
e.printStackTrace();
}
}
db.close();
creating a new DBAdapter each time the loop iterates was the only way I could get my strings into a database through my helper class.
File myFile=new File("/tmp/myfile");
URL myUrl = myFile.toURI().toURL();
If you want to open it for a range and for a protocol
ufw allow 11200:11299/tcp
ufw allow 11200:11299/udp
Swift 3 class:
import UIKit
class CircleView: UIView {
override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else {return}
context.addEllipse(in: rect)
context.setFillColor(UIColor.blue.cgColor)
context.fillPath()
}
}
&
is a logical elementwise operator, while &&
is a logical short-circuiting operator (which can only operate on scalars).
For example (pardon my syntax).
If..
A = [True True False True]
B = False
A & B = [False False False False]
..or..
B = True
A & B = [True True False True]
For &&
, the right operand is only calculated if the left operand is true, and the result is a single boolean value.
x = (b ~= 0) && (a/b > 18.5)
Hope that's clear.
This will work, make sure your control Event is assigned to this code, it has probably been lost, I also noticed that Double click will only work if the cell is not empty. Try double clicking on a cell with content, don't mess with the designer
private void dgvReport_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
//do something
}
Here is one way of doing it.
If you HTML looks like this:
<div>Contact Details
<button type="button" class="edit_button">My Button</button>
</div>
apply the following CSS:
div {
border-bottom-width: 1px;
border-bottom-style: solid;
border-bottom-color: gray;
overflow: auto;
}
.edit_button {
float: right;
margin: 0 10px 10px 0; /* for demo only */
}
The trick is to apply overflow: auto
to the div
, which starts a new block formatting context. The result is that the floated button is enclosed within the block area defined by the div
tag.
You can then add margins to the button if needed to adjust your styling.
In the original HTML and CSS, the floated button was out of the content flow so the border of the div
would be positioned with respect to the in-flow text, which does not include any floated elements.
See demo at: http://jsfiddle.net/audetwebdesign/AGavv/
Sure you just need to setup a local web server. Check out XAMPP: http://www.apachefriends.org/en/xampp.html
That will get you up and running in about 10 minutes.
There is now a way to run php locally without installing a server: https://stackoverflow.com/a/21872484/672229
Yes but the files need to be processed. For example you can install test servers like mamp / lamp / wamp depending on your plateform.
Basically you need apache / php running.
Based on my little knowledge of Oracle... a USER and a SCHEMA are somewhat similar. But there is also a major difference. A USER can be called a SCHEMA if the "USER" owns any object, otherwise ... it will only remain a "USER". Once the USER owns at least one object then by virtue of all of your definitions above.... the USER can now be called a SCHEMA.
If you are working with google maps, then check if the lat lng are being passed into new google.maps.LatLng
are of a proper format. In my case they were being passed as undefined.
SELECT * FROM INFORMATION_SCHEMA.TABLES
That should be a good start. For more, check INFORMATION_SCHEMA Tables.
After a lot of digging around I finally ended up downloading the source code of the recovery section of Android. Turns out you can actually send commands to the recovery.
* The arguments which may be supplied in the recovery.command file:
* --send_intent=anystring - write the text out to recovery.intent
* --update_package=path - verify install an OTA package file
* --wipe_data - erase user data (and cache), then reboot
* --wipe_cache - wipe cache (but not user data), then reboot
* --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
Those are the commands you can use according to the one I found but that might be different for modded files. So using adb you can do this:
adb shell
recovery --wipe_data
Using --wipe_data seemed to do what I was looking for which was handy although I have not fully tested this as of yet.
EDIT:
For anyone still using this topic, these commands may change based on which recovery you are using. If you are using Clockword recovery, these commands should still work. You can find other commands in /cache/recovery/command
For more information please see here: https://github.com/CyanogenMod/android_bootable_recovery/blob/cm-10.2/recovery.c
If you have date as a datetime.datetime
(or a datetime.date
) instance and want to combine it via a time from a datetime.time
instance, then you can use the classmethod datetime.datetime.combine
:
import datetime
dt = datetime.datetime(2020, 7, 1)
t = datetime.time(12, 34)
combined = datetime.datetime.combine(dt.date(), t)
I had a similar question: In the manual, it describes rename as
rename [option] expression replacement file
so you can use it in this way
rename _h _half *.png
In the code: '_h' is the expression that you are looking for. '_half' is the pattern that you want to replace with. '*.png' is the range of files that you are looking for your possible target files.
Hope this can help c:
Natural Join: It is combination or combined result of all the columns in the two tables. It will return all rows of the first table with respect to the second table.
Inner Join: This join will work unless if any of the column name shall be sxame in two tables
If the function is not defined when using that function in html, such as onclick = ‘function () ', it means function is in a callback, in my case is 'DOMContentLoaded'.
In Typescript you need to set types of HTMLAttributes
and React.FunctionComponent
.
In most cases you will need will be extending it to another interface or type.
const List: React.FunctionComponent<ListProps &
React.HTMLAttributes<HTMLDivElement>> = (
props: ListProps & React.HTMLAttributes<HTMLDivElement>
) => {
return (
<div className={props.className}>
<img className="mr-3" src={props.icon} alt="" />
{props.context}
</div>
);
};
interface ListProps {
context: string;
icon: string;
}
The following helps:
Open a shell to the device
adb shell
Navigate to the temp directory where the incoming APK is first copied
cd /data/local/tmp
List the available files and delete as desired
rm * // use at your own risk, good practice to list files first
This has been reliable for me so far on an actual device.
EDIT: This turned out to be not as reliable a solution as the one above.
I tried a number of the solutions. Nothing really helped. Finally I found an app called SD Maid. That helped.
It says the functionality is limited on unrooted devices. Mine is rooted so it would be good to see hear from people effective it is in those scenarios and if it was just a fluke that it worked for me (it is an unpredictable problem anyway).
NOTE: I have nothing to do with the app. Just found it with a search.
This is based on Cmyker's update for Chart.js 2. (posted as another answer as I can't comment yet)
I had an issue with the text alignment on Chrome when the legend is displayed as the chart height does not include this so it's not aligned correctly in the middle. Fixed this by accounting for this in the calculation of fontSize and textY.
I calculated percentage inside the method rather than a set value as I have multiple of these on the page. Assumptions are that your chart only has 2 values (otherwise what is the percentage of? and that the first is the one you want to show the percentage for. I have a bunch of other charts too so I do a check for type = doughnut. I'm only using doughnuts to show percentages so it works for me.
Text color seems a bit hit and miss depending on what order things run in etc so I ran into an issue when resizing that the text would change color (between black and the primary color in one case, and secondary color and white in another) so I "save" whatever the existing fill style was, draw the text (in the color of the primary data) then restore the old fill style. (Preserving the old fill style doesn't seem needed but you never know.)
https://jsfiddle.net/g733tj8h/
Chart.pluginService.register({
beforeDraw: function(chart) {
var width = chart.chart.width,
height = chart.chart.height,
ctx = chart.chart.ctx,
type = chart.config.type;
if (type == 'doughnut')
{
var percent = Math.round((chart.config.data.datasets[0].data[0] * 100) /
(chart.config.data.datasets[0].data[0] +
chart.config.data.datasets[0].data[1]));
var oldFill = ctx.fillStyle;
var fontSize = ((height - chart.chartArea.top) / 100).toFixed(2);
ctx.restore();
ctx.font = fontSize + "em sans-serif";
ctx.textBaseline = "middle"
var text = percent + "%",
textX = Math.round((width - ctx.measureText(text).width) / 2),
textY = (height + chart.chartArea.top) / 2;
ctx.fillStyle = chart.config.data.datasets[0].backgroundColor[0];
ctx.fillText(text, textX, textY);
ctx.fillStyle = oldFill;
ctx.save();
}
}
});
var data = {_x000D_
labels: ["Red","Blue"],_x000D_
datasets: [_x000D_
{_x000D_
data: [300, 50],_x000D_
backgroundColor: ["#FF6384","#36A2EB"],_x000D_
}]_x000D_
};_x000D_
_x000D_
Chart.pluginService.register({_x000D_
beforeDraw: function(chart) {_x000D_
var width = chart.chart.width,_x000D_
height = chart.chart.height,_x000D_
ctx = chart.chart.ctx,_x000D_
type = chart.config.type;_x000D_
_x000D_
if (type == 'doughnut')_x000D_
{_x000D_
var percent = Math.round((chart.config.data.datasets[0].data[0] * 100) /_x000D_
(chart.config.data.datasets[0].data[0] +_x000D_
chart.config.data.datasets[0].data[1]));_x000D_
var oldFill = ctx.fillStyle;_x000D_
var fontSize = ((height - chart.chartArea.top) / 100).toFixed(2);_x000D_
_x000D_
ctx.restore();_x000D_
ctx.font = fontSize + "em sans-serif";_x000D_
ctx.textBaseline = "middle"_x000D_
_x000D_
var text = percent + "%",_x000D_
textX = Math.round((width - ctx.measureText(text).width) / 2),_x000D_
textY = (height + chart.chartArea.top) / 2;_x000D_
_x000D_
ctx.fillStyle = chart.config.data.datasets[0].backgroundColor[0];_x000D_
ctx.fillText(text, textX, textY);_x000D_
ctx.fillStyle = oldFill;_x000D_
ctx.save();_x000D_
}_x000D_
}_x000D_
});_x000D_
_x000D_
var myChart = new Chart(document.getElementById('myChart'), {_x000D_
type: 'doughnut',_x000D_
data: data,_x000D_
options: {_x000D_
responsive: true,_x000D_
legend: {_x000D_
display: true_x000D_
}_x000D_
}_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.6/Chart.bundle.js"></script>_x000D_
<canvas id="myChart"></canvas>
_x000D_
I have JSONObject like this: {"status":[{"Response":"success"}]}
.
If I want to convert the JSONObject value, which is a JSONArray into JSONObject automatically without using any static value, here is the code for that.
JSONArray array=new JSONArray();
JSONObject obj2=new JSONObject();
obj2.put("Response", "success");
array.put(obj2);
JSONObject obj=new JSONObject();
obj.put("status",array);
Converting the JSONArray to JSON Object:
Iterator<String> it=obj.keys();
while(it.hasNext()){
String keys=it.next();
JSONObject innerJson=new JSONObject(obj.toString());
JSONArray innerArray=innerJson.getJSONArray(keys);
for(int i=0;i<innerArray.length();i++){
JSONObject innInnerObj=innerArray.getJSONObject(i);
Iterator<String> InnerIterator=innInnerObj.keys();
while(InnerIterator.hasNext()){
System.out.println("InnInnerObject value is :"+innInnerObj.get(InnerIterator.next()));
}
}
Use the global flag:
var name = name.replace(/[^a-zA-Z ]/g, "");
^
If you don't want to remove numbers, add it to the class:
var name = name.replace(/[^a-zA-Z0-9 ]/g, "");
One problem with sockets is that they do not have a way to flush the buffer. There is something called the Nagle algorithm which collects all data and flushes it after 40ms. So if it is responsiveness and not bandwidth you might be better off with a pipe.
You can disable the Nagle with the socket option TCP_NODELAY but then the reading end will never receive two short messages in one single read call.
So test it, i ended up with none of this and implemented memory mapped based queues with pthread mutex and semaphore in shared memory, avoiding a lot of kernel system calls (but today they aren't very slow anymore).
The exec(3,3p)
functions replace the current process with another. That is, the current process stops, and another runs instead, taking over some of the resources the original program had.
In oracle an empty varchar2 and null are treated the same, and your observations show that.
when you write:
select * from table where a = '';
its the same as writing
select * from table where a = null;
and not a is null
which will never equate to true, so never return a row. same on the insert, a NOT NULL means you cant insert a null or an empty string (which is treated as a null)
If you have an empty table the Export method won't work. As a workaround. I used the Table View of Oracle SQL Developer. and clicked on Columns. Sorted by Nullable so NO was on top. And then selected these non nullable values using shift + select for the range.
This allowed me to do one base insert. So that Export could prepare a proper all columns insert.
As my experience, you can add another domain which listens different port than 7001, and use this domain in to deploy app.
Here's an example: http://st-curriculum.oracle.com/obe/fmw/wls/10g/r3/installconfig/install_wls/install_wls.htm
HTH.
Minimal code needed for this one. Create a common 'key' to cartesian merge the two:
df1['key'] = 0
df2['key'] = 0
df_cartesian = df1.merge(df2, how='outer')
The code below can solve the NullPointerException.
@Id
@GeneratedValue
@Column(name = "STOCK_ID", unique = true, nullable = false)
public Integer getStockId() {
return this.stockId;
}
public void setStockId(Integer stockId) {
this.stockId = stockId;
}
If you add @Id
, then you can declare some more like as above declared method.
A property that has only a getter is said to be readonly. Cause no setter is provided, to change the value of the property (from outside).
C# has has a keyword readonly, that can be used on fields (not properties). A field that is marked as "readonly", can only be set once during the construction of an object (in the constructor).
private string _name = "Foo"; // field for property Name;
private bool _enabled = false; // field for property Enabled;
public string Name{ // This is a readonly property.
get {
return _name;
}
}
public bool Enabled{ // This is a read- and writeable property.
get{
return _enabled;
}
set{
_enabled = value;
}
}
You wont be able to do this from the client side because of the Same Origin Policy set by the browsers. You wont be able to get much information from the iFrame other than basic properties like its width and height.
Also, google sets in its response header an 'X-Frame-Options' of SAMEORIGIN.
Even if you did an ajax call to google you wont be able to inspect the response because the browser enforcing Same Origin Policy.
So, the only option is to make the request from your server to see if you can display the site in your IFrame.
So, on your server.. your web app would make a request to www.google.com and then inspect the response to see if it has a header argument of X-Frame-Options. If it does exist then you know the IFrame will error.
If you use this way so you no need to import any third party class.
If you want concatenate String
Sample code for concate two String Array
public static String[] combineString(String[] first, String[] second){
int length = first.length + second.length;
String[] result = new String[length];
System.arraycopy(first, 0, result, 0, first.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}
If you want concatenate Int
Sample code for concate two Integer Array
public static int[] combineInt(int[] a, int[] b){
int length = a.length + b.length;
int[] result = new int[length];
System.arraycopy(a, 0, result, 0, a.length);
System.arraycopy(b, 0, result, a.length, b.length);
return result;
}
Here is Main method
public static void main(String[] args) {
String [] first = {"a", "b", "c"};
String [] second = {"d", "e"};
String [] joined = combineString(first, second);
System.out.println("concatenated String array : " + Arrays.toString(joined));
int[] array1 = {101,102,103,104};
int[] array2 = {105,106,107,108};
int[] concatenateInt = combineInt(array1, array2);
System.out.println("concatenated Int array : " + Arrays.toString(concatenateInt));
}
}
We can use this way also.
Another approach when you have many updates would be to use COALESCE:
UPDATE [DATABASE].[dbo].[TABLE_NAME]
SET
[ABC] = COALESCE(@ABC, [ABC]),
[ABCD] = COALESCE(@ABCD, [ABCD])
Assuming, we want to get image dimensions of <img id="an-img" src"...">
// Query after all the elements on the page have loaded.
// Or, use `onload` on a particular element to check if it is loaded.
document.addEventListener('DOMContentLoaded', function () {
var el = document.getElementById("an-img");
console.log({
"naturalWidth": el.naturalWidth, // Only on HTMLImageElement
"naturalHeight": el.naturalHeight, // Only on HTMLImageElement
"offsetWidth": el.offsetWidth,
"offsetHeight": el.offsetHeight
});
Natural Dimensions
el.naturalWidth
and el.naturalHeight
will get us the natural dimensions, the dimensions of the image file.
Layout Dimensions
el.offsetWidth
and el.offsetHeight
will get us the dimensions at which the element is rendered on the document.
I made it work with Vue 2.0 in single file component.
npm install moment
in folder where you have vue installed
<template>
<div v-for="meta in order.meta">
{{ getHumanDate(meta.value.date) }}
</div>
</template>
<script>
import moment from 'moment';
export default {
methods: {
getHumanDate : function (date) {
return moment(date, 'YYYY-MM-DD').format('DD/MM/YYYY');
}
}
}
</script>
As we don't know what are the names of your activities classes, let's call your current activity Activity1, and the one you wish to open - Activity2 (these are the names of the classes)
First you need to define an intent that will be sent to Activity2:
Intent launchActivity2 = new Intent(Activity1.this, Activity2.class);
Then, you can simply launch the activity by running:
startActivity(launchActivity2 );
Besides @Matt's approach, one way to change the default directory to use for notebooks permanently is to change the config files. Firstly in the cmdline, type:
$> ipython profile create
to initialize a profile with the default configuration file. Secondly, in file ipython_notebook_config.py
, uncomment and edit this line:
# c.NotebookManager.notebook_dir = 'D:\\Documents\\Desktop'
changing D:\\Documents\\Desktop
to whatever path you like.
This works for me ;)
UPDATE: There is no c.NotebookManager.notebook_dir
anymore.
Now, the line to uncomment and config is this one:
c.NotebookApp.notebook_dir = 'Z:\\username_example\folder_that_you_whant'
You need to open the connection first:
SQLConnection.Open();
If you have two lists called 'a' and 'b', you can do: [m - n for m,n in zip(a,b)]
The answer is "All of them". A java array is allocated with a fixed number of element slots. The "length" attribute will tell you how many. That number is immutable for the life of the array. For a resizable equivalent, you need one of the java.util.List classes - where you can use the size() method to find out how many elements are in use.
However, there's "In use" and then there's In Use. In an class object array, you can have element slots whose elements are null objects, so even though they count in the length attribute, but most people's definitions, they're not in use (YMMV, depending on the application). There's no builtin function for returning the null/non-null counts.
List objects have yet another definition of "In Use". To avoid excessive creation/destruction of the underlying storage structures, there's typically some padding in these classes. It's used internally, but isn't counted in the returned size() method. And if you attempt to access those items without expanding the List (via the add methods), you'll get an illegal index exception.
So for Lists, you can have "In Use" for non-null, committed elements, All committed elements (including null elements), or All elements, including the expansion space presently allocated.
I had this happen to me when my node_modules folder got screwy after installing a new package. I killed the folder rm -rf node_modules
and then did an npm install
to re-install my packages and that fixed it.
Alternatively, if using Sass, one can "extend" FA icons to display them:
.mytextwithicon:before {
@extend .fas, .fa-angle-double-right;
@extend .mr-2; // using bootstrap to add a small gap
// between the icon and the text.
}
display: block
with margin: 0
didn't work for me, neither wrapping with a text-align: center
element.
This is my solution:
img.center {
position: absolute;
transform: translateX(-50%);
left: 50%;
}
And what's the answer from the server? It should reply a 204 and then really send the GET you are requesting.
In the OPTIONS the client is checking if the server allows CORS requests. If it gives you something different than a 204 then you should configure your server to send the correct Allow-Origin headers.
The way you are adding headers is the right way to do it.
Just use the method message.setRecipients with multiple addresses separated by commas:
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected],[email protected],[email protected]"));
message.setRecipients(Message.RecipientType.CC, InternetAddress.parse("[email protected],[email protected],[email protected]"));
works fine with only one address too
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]"));
There's a difference between the raw queries and standard selects (between the DB::raw
and DB::select
methods).
You can do what you want using a DB::select
and simply dropping in the ?
placeholder much like you do with prepared statements (it's actually what it's doing).
A small example:
$results = DB::select('SELECT * FROM user WHERE username=?', ['jason']);
The second parameter is an array of values that will be used to replace the placeholders in the query from left to right.
Divide $percentage
by 100 and multiply to $totalWidth
. Simple maths.
You can execute bits of code once for a class before an object is constructed in the static blocks.
E.g.
class A {
static int var1 = 6;
static int var2 = 9;
static int var3;
static long var4;
static Date date1;
static Date date2;
static {
date1 = new Date();
for(int cnt = 0; cnt < var2; cnt++){
var3 += var1;
}
System.out.println("End first static init: " + new Date());
}
}
As mentioned by Quynh Nguyen, you don't need the '.' in the className. However - document.getElementsByClassName('col1') will return an array of objects.
This will return an "undefined" value because an array doesn't have a class. You'll still need to loop through the array elements...
function changeBGColor() {
var cols = document.getElementsByClassName('col1');
for(i = 0; i < cols.length; i++) {
cols[i].style.backgroundColor = 'blue';
}
}
Simple way in Java
public void resize(String inputImagePath,
String outputImagePath, int scaledWidth, int scaledHeight)
throws IOException {
// reads input image
File inputFile = new File(inputImagePath);
BufferedImage inputImage = ImageIO.read(inputFile);
// creates output image
BufferedImage outputImage = new BufferedImage(scaledWidth,
scaledHeight, inputImage.getType());
// scales the input image to the output image
Graphics2D g2d = outputImage.createGraphics();
g2d.drawImage(inputImage, 0, 0, scaledWidth, scaledHeight, null);
g2d.dispose();
// extracts extension of output file
String formatName = outputImagePath.substring(outputImagePath
.lastIndexOf(".") + 1);
// writes to output file
ImageIO.write(outputImage, formatName, new File(outputImagePath));
}
The assumption that one should never, ever use + for string concatenation, but instead always use ''.join may be a myth. It is true that using +
creates unnecessary temporary copies of immutable string object but the other not oft quoted fact is that calling join
in a loop would generally add the overhead of function call
. Lets take your example.
Create two lists, one from the linked SO question and another a bigger fabricated
>>> myl1 = ['A','B','C','D','E','F']
>>> myl2=[chr(random.randint(65,90)) for i in range(0,10000)]
Lets create two functions, UseJoin
and UsePlus
to use the respective join
and +
functionality.
>>> def UsePlus():
return [myl[i] + myl[i + 1] for i in range(0,len(myl), 2)]
>>> def UseJoin():
[''.join((myl[i],myl[i + 1])) for i in range(0,len(myl), 2)]
Lets run timeit with the first list
>>> myl=myl1
>>> t1=timeit.Timer("UsePlus()","from __main__ import UsePlus")
>>> t2=timeit.Timer("UseJoin()","from __main__ import UseJoin")
>>> print "%.2f usec/pass" % (1000000 * t1.timeit(number=100000)/100000)
2.48 usec/pass
>>> print "%.2f usec/pass" % (1000000 * t2.timeit(number=100000)/100000)
2.61 usec/pass
>>>
They have almost the same runtime.
Lets use cProfile
>>> myl=myl2
>>> cProfile.run("UsePlus()")
5 function calls in 0.001 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.001 0.001 0.001 0.001 <pyshell#1376>:1(UsePlus)
1 0.000 0.000 0.001 0.001 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 {len}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
1 0.000 0.000 0.000 0.000 {range}
>>> cProfile.run("UseJoin()")
5005 function calls in 0.029 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.015 0.015 0.029 0.029 <pyshell#1388>:1(UseJoin)
1 0.000 0.000 0.029 0.029 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 {len}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
5000 0.014 0.000 0.014 0.000 {method 'join' of 'str' objects}
1 0.000 0.000 0.000 0.000 {range}
And it looks that using Join, results in unnecessary function calls which could add to the overhead.
Now coming back to the question. Should one discourage the use of +
over join
in all cases?
I believe no, things should be taken into consideration
And off-course in a development pre-mature optimization is evil.
Your currently selected backend, 'agg' does not support show().
AGG
backend is for writing to file, not for rendering in a window. See the backend FAQ at the matplotlib web site.
ImportError: No module named _backend_gdk
For the second error, maybe your matplotlib distribution is not compiled with GTK support, or you miss the PyGTK package. Try to install it.
Do you call the show()
method inside a terminal or application that has access to a graphical environment?
Try other GUI backends, in this order:
TkAgg
WX
QTAgg
QT4Agg
What git-revert does is create a commit which undoes changes made in a given commit, creating a commit which is reverse (well, reciprocal) of a given commit. Therefore
git revert <SHA-1>
should and does work.
If you want to rewind back to a specified commit, and you can do this because this part of history was not yet published, you need to use git-reset, not git-revert:
git reset --hard <SHA-1>
(Note that --hard
would make you lose any non-committed changes in the working directory).
By the way, perhaps it is not obvious, but everywhere where documentation says <commit>
or <commit-ish>
(or <object>
), you can put an SHA-1 identifier (full or shortened) of commit.
Assuming this branch isn't an external or a symlink, removing the branch should be as simple as:
svn rm branches/< mybranch >
svn ci -m "message"
If you'd like to do this in the repository then update to remove it from your working copy you can do something like:
svn rm http://< myurl >/< myrepo >/branches/< mybranch >
Then run:
svn update
check this out jquery calendar to show only year and month
or something like this
$("#datepicker").datepicker( "option", "dateFormat", "yy" );?
Updated Answer (post-WWDC 2016):
iOS apps will require secure HTTPS connections by the end of 2016. Trying turn ATS off may get your app rejected in the future.
App Transport Security, or ATS, is a feature that Apple introduced in iOS 9. When ATS is enabled, it forces an app to connect to web services over an HTTPS connection rather than non secure HTTP.
However, developers can still switch ATS off and allow their apps to send data over an HTTP connection as mentioned in above answers. At the end of 2016, Apple will make ATS mandatory for all developers who hope to submit their apps to the App Store. link
$files = glob($_SERVER["DOCUMENT_ROOT"]."/myFolder/*");
One option is to use Python's slicing and indexing features to logically evaluate the places where your condition holds and overwrite the data there.
Assuming you can load your data directly into pandas
with pandas.read_csv
then the following code might be helpful for you.
import pandas
df = pandas.read_csv("test.csv")
df.loc[df.ID == 103, 'FirstName'] = "Matt"
df.loc[df.ID == 103, 'LastName'] = "Jones"
As mentioned in the comments, you can also do the assignment to both columns in one shot:
df.loc[df.ID == 103, ['FirstName', 'LastName']] = 'Matt', 'Jones'
Note that you'll need pandas
version 0.11 or newer to make use of loc
for overwrite assignment operations.
Another way to do it is to use what is called chained assignment. The behavior of this is less stable and so it is not considered the best solution (it is explicitly discouraged in the docs), but it is useful to know about:
import pandas
df = pandas.read_csv("test.csv")
df['FirstName'][df.ID == 103] = "Matt"
df['LastName'][df.ID == 103] = "Jones"
This is a very old post, but I recently encountered the problem and for me the following solved the issue by formatting the SQL as follows,
SELECT CONVERT (varchar, getdate(), 120) AS Date
If you copy the result from SQL Server and paste in Excel then Excel holds the proper formatting.
Check if any of your .php
files which printing some text, also is correctly encoding in utf-8
.
I had a similar problem. I had saved some xml in a file and when reading it into a DOM document, it failed due to special character. Then I used the following code to fix it:
String enco = new String(Files.readAllBytes(Paths.get(listPayloadPath+"/Payload.xml")), StandardCharsets.UTF_8);
Document doc = builder.parse(new ByteArrayInputStream(enco.getBytes(StandardCharsets.UTF_8)));
Let me know if it works for you.
FWIW, if you don't want to use custom function or extension, you can:
let array = [ .... ]
if let found = find(array.map({ $0.name }), "Foo") {
let obj = array[found]
}
This generates name
array first, then find
from it.
If you have huge array, you might want to do:
if let found = find(lazy(array).map({ $0.name }), "Foo") {
let obj = array[found]
}
or maybe:
if let found = find(lazy(array).map({ $0.name == "Foo" }), true) {
let obj = array[found]
}
You actually got it. Just forgot some quotes.
$(this).css({backgroundColor: 'red'});
or
$(this).css('background-color', 'red');
You don't need to pass over a map/object to set only one property. You can just put pass it as string. Note that if passing an object you cannot use a -
. All CSS properties which have such a character are mapped with capital letters.
Reference: .css()
Why not just bypass the WebClient's file handling pieces altogether. Perhaps something similar to this:
private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
e.Cancel = true;
WebClient client = new WebClient();
client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted);
client.DownloadDataAsync(e.Url);
}
void client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
string filepath = textBox1.Text;
File.WriteAllBytes(filepath, e.Result);
MessageBox.Show("File downloaded");
}
Check out the basics of regular expressions in a tutorial. All it requires is two anchors and a repeated character class:
^[a-zA-Z ._-]*$
If you use the case-insensitive modifier, you can shorten this to
^[a-z ._-]*$
Note that the space is significant (it is just a character like any other).
File>Settings...>Editor>General>
then you'll find this in the menu Mouse,
"change the font size(Zoom) with Ctrl+Mouse Wheel"
I've seen a couple cases where this error occurs:
!=
in a where
clause with a list of multiple or
valuessuch as:
where columnName !=('A'||'B')
This can be resolved by using
where columnName not in ('A','B')
if()
function:select if(col1,col1,col2);
in order to select the value in col1
if it exists and otherwise show the value in col2
...this throws the error; it can be resolved by using:
select if(col1!='',col1,col2);
I ran into this error while trying to click some element (or its overlay, I didn't care), and the other answers didn't work for me. I fixed it by using the elementFromPoint
DOM API to find the element that Selenium wanted me to click on instead:
element_i_care_about = something()
loc = element_i_care_about.location
element_to_click = driver.execute_script(
"return document.elementFromPoint(arguments[0], arguments[1]);",
loc['x'],
loc['y'])
element_to_click.click()
I've also had situations where an element was moving, for example because an element above it on the page was doing an animated expand or collapse. In that case, this Expected Condition class helped. You give it the elements that are animated, not the ones you want to click. This version only works for jQuery animations.
class elements_not_to_be_animated(object):
def __init__(self, locator):
self.locator = locator
def __call__(self, driver):
try:
elements = EC._find_elements(driver, self.locator)
# :animated is an artificial jQuery selector for things that are
# currently animated by jQuery.
return driver.execute_script(
'return !jQuery(arguments[0]).filter(":animated").length;',
elements)
except StaleElementReferenceException:
return False
http://www.eclipsezone.com/eclipse/forums/t53459.html
Basically run it with:
-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=1044
The application, at launch, will wait until you connect from another source.
You need to use a global regular expression for this. Try it this way:
str.replace(/"/g, '\\"');
Check out regex syntax and options for the replace function in Using Regular Expressions with JavaScript.
simple query would be, just set a variable to some number you want. then update the column you need by incrementing 1 from that number. for all the rows it'll update each row id by incrementing 1
SET @a = 50000835 ;
UPDATE `civicrm_contact` SET external_identifier = @a:=@a+1
WHERE external_identifier IS NULL;
That may be also interesting in context of adding INTERNET permission to your application:
Google has also given each app Internet access, effectively removing the Internet access permission. Oh, sure, Android developers still have to declare they want Internet access when putting together the app. But users can no longer see the Internet access permission when installing an app and current apps that don’t have Internet access can now gain Internet access with an automatic update without prompting you.
Bottom line is that you still have to add INTERNET permission in manifest file but application will be updated on user's devices without asking them for new permission.
I hope below solution will work for you all as I was having the same problem with my websites...
For : $json = json_decode(file_get_contents('http://...'));
Replace with below query
$Details= unserialize(file_get_contents('http://......'));
Simply you can import it using require as following code:
var _ = require('your_module_name');
This is possible to do without an iframe
specifically. jQuery is utilised since it's mentioned in the title.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Load remote content into object element</title>
</head>
<body>
<div id="siteloader"></div>?
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script>
$("#siteloader").html('<object data="http://tired.com/">');
</script>
</body>
</html>
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
// Assume x, y, and diameter are instance variables.
Ellipse2D.Double circle = new Ellipse2D.Double(x, y, diameter, diameter);
g2d.fill(circle);
...
}
Here are some docs about paintComponent (link).
You should override that method in your JPanel and do something similar to the code snippet above.
In your ActionListener you should specify x, y, diameter
and call repaint()
.
You can add a source folder to the build script and then sync. Look for sourceSets in the documentation here: http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Basic-Project
I haven't found a good way of adding test source folders. I have manually added the source to the .iml file. Of course this means it will go away everytime the build script is synched.
Simply delete that column using: del df['column_name']
Your Problem is because of getTime() . it always return following.
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
Because the max integer value is less then the return value by getTime()
that why is showing
wrong result.
These are escape characters which are used to manipulate string.
\t Insert a tab in the text at this point.
\b Insert a backspace in the text at this point.
\n Insert a newline in the text at this point.
\r Insert a carriage return in the text at this point.
\f Insert a form feed in the text at this point.
\' Insert a single quote character in the text at this point.
\" Insert a double quote character in the text at this point.
\\ Insert a backslash character in the text at this point.
Read more about them from here.
http://docs.oracle.com/javase/tutorial/java/data/characters.html
put your css in public folder, then
add this in you blade file
<link rel="stylesheet" type="text/css" href="{{ asset('mystyle.css') }}">
<RatingBar
android:id="@+id/ratingBar"
style="@style/custom_rating_bar"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:clickable="true"
android:numStars="5"
/>
Configure the number of Stars in the XML file... No need to provide it in Styles or Activity/Fragment .... IMPORTANT: Make sure you Put the WIDTH as Wrap content and weights are not enabled
In kotlin just use activity
instead of getActivity()
The accepted answer is rather complicated. Here is a more standard design:
L = LinkedList()
L.insert(1)
L.insert(1)
L.insert(2)
L.insert(4)
print L
L.clear()
print L
It is a simple LinkedList
class based on the straightforward C++ design and Chapter 17: Linked lists, as recommended by Thomas Watnedal.
class Node:
def __init__(self, value = None, next = None):
self.value = value
self.next = next
def __str__(self):
return 'Node ['+str(self.value)+']'
class LinkedList:
def __init__(self):
self.first = None
self.last = None
def insert(self, x):
if self.first == None:
self.first = Node(x, None)
self.last = self.first
elif self.last == self.first:
self.last = Node(x, None)
self.first.next = self.last
else:
current = Node(x, None)
self.last.next = current
self.last = current
def __str__(self):
if self.first != None:
current = self.first
out = 'LinkedList [\n' +str(current.value) +'\n'
while current.next != None:
current = current.next
out += str(current.value) + '\n'
return out + ']'
return 'LinkedList []'
def clear(self):
self.__init__()
First of all, are they float or Float? If one of them is a Float, you should use the equals() method. Also, probably best to use the static Float.compare method.
You can get the url without parameters by using {{request.path}} You can get the url with parameters by using {{request.get_full_path}}
Take note that if you have multiple versions of Python installed on your computer, you may have a few versions of pip associated with each.
Depending on your associations, you might need to be very cautious of what pip command you use:
pip3 list
Worked for me, where I'm running Python3.4. Simply using pip list
returned the error The program 'pip' is currently not installed. You can install it by typing: sudo apt-get install python-pip
.
There is a branch of conda (new-pypi-install) that adds better integration with pip and PyPI. In particular conda list will also show pip installed packages and conda install will first try to find a conda package and failing that will use pip to install the package.
This branch is scheduled to be merged later this week so that version 2.1 of conda will have better pip-integration with conda.
<td><b>Field Label:</b><br>
<select style='align:left; width:100%;' id='some_id' name='some_name'>
<option hidden selected>Select one...</option>
<option value='Value1'>OptLabel1</option>
<option value='Value2'>OptLabel2</option>
<option value='Value3'>OptLabel3</option></select>
</td>
_x000D_
Just put "hidden" on option you want to hide on dropdown list.
Why not this very simple method:
$i = 0; //a counter to track which element we are at
foreach($array as $index => $value) {
$i++;
if( $i == sizeof($array) ){
//we are at the last element of the array
}
}
Aside from other great responses, I just had to give NTFS permissions to the Oracle installation folder. (I gave read access)
Apache Commons has an IntegerValidator class which appears to do what you want. Java provides no in-built method for doing this.
See here for the groupid/artifactid.
pdf validation with OPEN validator:
DROID (Digital Record Object Identification) http://sourceforge.net/projects/droid/
JHOVE - JSTOR/Harvard Object Validation Environment http://hul.harvard.edu/jhove/
Open the project you want to push in Android Studio.
Click VCS -> Enable version Control Integration -> Git
There doesn't seem to be a way to add a remote through the GUI. So open Git Bash in the root of the project and do git remote add <remote_name> <remote_url>
Now when you do VCS -> Commit changes -> Commit & Push
you should see your remote and everything should work through the GUI.
If you are getting the error: fatal: remote <remote_name> already exists
that means you already added it. To see your remotes do git remote -v
and git remote rm <remote_name>
to remove.
See these pages for details:
http://www.jetbrains.com/idea/webhelp/using-git-integration.html
I think you can use db.collection.distinct(fields,query)
You will be able to get the distinct values in your case for NetworkID.
It should be something like this :
Db.collection.distinct('NetworkID')
There is a npm sync module also. which is used for synchronize the process of executing the query.
When you want to run parallel queries in synchronous way then node restrict to do that because it never wait for response. and sync module is much perfect for that kind of solution.
Sample code
/*require sync module*/
var Sync = require('sync');
app.get('/',function(req,res,next){
story.find().exec(function(err,data){
var sync_function_data = find_user.sync(null, {name: "sanjeev"});
res.send({story:data,user:sync_function_data});
});
});
/*****sync function defined here *******/
function find_user(req_json, callback) {
process.nextTick(function () {
users.find(req_json,function (err,data)
{
if (!err) {
callback(null, data);
} else {
callback(null, err);
}
});
});
}
reference link: https://www.npmjs.com/package/sync
If (when the file doesn't exist) you want to create it as empty, the simplest approach is
with open(thepath, 'a'): pass
(in Python 2.6 or better; in 2.5, this requires an "import from the future" at the top of your module).
If, on the other hand, you want to leave the file alone if it exists, but put specific non-empty contents there otherwise, then more complicated approaches based on if os.path.isfile(thepath):
/else
statement blocks are probably more suitable.
I don't know if it changes the whole app, but I have managed to change some components that couldn't otherwise be changed by doing this:
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/Lucida Sans Unicode.ttf");
Typeface.class.getField("DEFAULT").setAccessible(true);
Typeface.class.getField("DEFAULT_BOLD").setAccessible(true);
Typeface.class.getField("DEFAULT").set(null, tf);
Typeface.class.getField("DEFAULT_BOLD").set(null, tf);
This was a problem for me last time the emulator updated itself and back then disabling other network adapters fixed it. Now it's cropped up again but the only adapter that is enabled is a single wifi one so I have nothing to disable.
The issue only reappeared after I updated via a prompt the emulator tools to 26.1.1. I uninstalled and reinstalled the emulator via the SDK Tools update tab and thankfully the only option when installing again right now is to install 26.0.3 (which seems to be working okay).
Moral of the story is to be very wary of emulator updates.
To escape backslashes that cause problems for JSON data I use this function.
//escape backslash to avoid errors
var escapeJSON = function(str) {
return str.replace(/\\/g,'\\');
};
This doesn't exactly answer the question as posed, but it does create the same visual effect that you are trying to achieve.
<style>
body {
border:0;
padding:0;
margin:0;
padding-top:60px;
}
#header {
position:absolute;
top:0;
height:60px;
width:100%;
}
#wrapper {
height:100%;
width:100%;
}
</style>
Charset UTF8_CHARSET = Charset.forName("UTF-8");
String strISO = "{\"name\":\"?\"}";
System.out.println(strISO);
byte[] b = strISO.getBytes();
for (byte c: b) {
System.out.print("[" + c + "]");
}
String str = new String(b, UTF8_CHARSET);
System.out.println(str);
The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName
to be the name of the file you wish to open.
Private Const TargetWBName As String = "myworkbook.xlsx"
'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
WorkbookOpen = False
On Error GoTo WorkBookNotOpen
If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
WorkbookOpen = True
Exit Function
End If
WorkBookNotOpen:
End Function
Private Sub Workbook_Open()
'Check if our target workbook is open
If WorkbookOpen(TargetWBName) = False Then
'set calculation to manual
Application.Calculation = xlCalculationManual
Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
DoEvents
Me.Close False
End If
End Sub
Set the constant 'TargetWBName' to be the name of the workbook that you wish to open.
This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself.
*NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True
after Me.Close
The easiest way to implement this behaviour is by calling the pauseVideo
and playVideo
methods, when necessary. Inspired by the result of my previous answer, I have written a pluginless function to achieve the desired behaviour.
The only adjustments:
toggleVideo
?enablejsapi=1
to YouTube's URL, to enable the featureDemo: http://jsfiddle.net/ZcMkt/
Code:
<script>
function toggleVideo(state) {
// if state == 'hide', hide. Else: show video
var div = document.getElementById("popupVid");
var iframe = div.getElementsByTagName("iframe")[0].contentWindow;
div.style.display = state == 'hide' ? 'none' : '';
func = state == 'hide' ? 'pauseVideo' : 'playVideo';
iframe.postMessage('{"event":"command","func":"' + func + '","args":""}', '*');
}
</script>
<p><a href="javascript:;" onClick="toggleVideo();">Click here</a> to see my presenting showreel, to give you an idea of my style - usually described as authoritative, affable and and engaging.</p>
<!-- popup and contents -->
<div id="popupVid" style="position:absolute;left:0px;top:87px;width:500px;background-color:#D05F27;height:auto;display:none;z-index:200;">
<iframe width="500" height="315" src="http://www.youtube.com/embed/T39hYJAwR40?enablejsapi=1" frameborder="0" allowfullscreen></iframe>
<br /><br />
<a href="javascript:;" onClick="toggleVideo('hide');">close</a>
You can prefix the size requirement with -
to left-justify:
sys.stdout.write("%-6s %-50s %-25s\n" % (code, name, industry))
Try:
ssh -t remotehost "sudo <cmd>"
This will remove the above errors.
I had a .live("focus") event set to select() (highlight) the contents of a text input so that the user wouldn't have to select it before typing a new value.
$(formObj).select();
Because of quirks between different browsers, the select would sometimes be superseded by the click that caused it, and it would deselect the contents right after in favor of placing the cursor within the text field (worked mostly ok in FF but failed in IE)
I thought I could solve this by putting a slight delay on the select...
setTimeout(function(){$(formObj).select();},200);
This worked fine and the select would persist, but a funny problem arose.. If you tabbed from one field to the next, the focus would switch to the next field before the select took place. Since select steals focus, the focus would then go back and trigger a new "focus" event. This ended up in a cascade of input selects dancing all over the screen.
A workable solution would be to check that the field still has focus before executing the select(), but as mentioned, there's no simple way to check... I ended up just dispensing with the whole auto highlight, rather than turning what should be a single jQuery select() call into a huge function laden with subroutines...
First, use git log
to see the log, pick the commit you want, note down the sha1 hash that is used to identify the commit. Next, run git checkout hash
. After you are done, git checkout original_branch
. This has the advantage of not moving the HEAD, it simply switches the working copy to a specific commit.
It also matters the order of the dependencies. I've had the same issue. And basically I had to put first the scope test
and then scope compile
dependencies in the pom.xml
. If I put first the scope compile
and then the scope test
it will fail.
@JS5 , I also faced the same issue as you: ImageButton causing exceptions inside UpdatePanel only on production server and IE. After some research I found this:
There is an issue with ImageButtons and UpdatePanels. The update to .NET 4.5 is fixed there. It has something to do with Microsoft changed the x,y axis of a button click from Int to Double so you can tell where on the button you clicked and it's throwing a conversion error.
I'm using NetFramework 2.0 and IIS 6, so, the suggested solution was to downgrade IE compatibility adding a meta tag:
<meta http-equiv="X-UA-Compatible" content="IE=9" />
I've done this via Page_Load method only on the page I needed to:
Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim tag As HtmlMeta = New HtmlMeta()
tag.HttpEquiv = "X-UA-Compatible"
tag.Content = "IE=9"
Header.Controls.Add(tag)
End Sub
Hope this helps someone.
(update: 2018)
Note that pd.Timegrouper
is depreciated and will be removed. Use instead:
df.groupby(pd.Grouper(freq='M'))
Its should work for all version of eclipse even in Spring tool suit(STS). Here is the steps
Go to the URl Follow The link to download or click the bellow link to direct download Click Here to download
Download JD-Eclipse
.
Download and unzip the JD-Eclipse Update Site,
Launch Eclipse,
Click on "Help > Install New Software...",
Click on button "Add..." to add an new repository,
Enter "JD-Eclipse Update Site" and select the local site directory,
Select extracted folder and give any name. I have given JDA
.
and click ok.
Check "Java Decompiler Eclipse Plug-in",
Next, next, next... and restart Eclipse.
you can use group and max:
db.getCollection('kids').aggregate([
{
$group: {
_id: null,
maxQuantity: {$max: "$age"}
}
}
])
With text files, maybe the EOF is -1 when using BufferReader.read(), char by char. I made a test with BufferReader.readLine()!=null and it worked properly.
The format you've used is not recognized by strtotime(). Replace
$date = "04-15-2013";
by
$date = "04/15/2013";
Or if you want to use -
then use the following line with the year in front:
$date = "2013-04-15";
map[key] = value
is provided for easier syntax. It is easier to read and write.
The reason for which you need to have default constructor is that map[key]
is evaluated before assignment. If key wasn't present in map, new one is created (with default constructor) and reference to it is returned from operator[]
.
There is no need to use :checkbox
, also replace #activelist
with #inactivelist
:
$('#inactivelist').change(function () {
alert('changed');
});
convert_objects is deprecated.
For pandas >= 0.17.0, use pd.to_numeric
df["2nd"] = pd.to_numeric(df["2nd"])
I know it not right way. It is not break the loop. It is a Jugad
let result = true;_x000D_
[1, 2, 3].forEach(function(el) {_x000D_
if(result){_x000D_
console.log(el);_x000D_
if (el === 2){_x000D_
result = false;_x000D_
}_x000D_
}_x000D_
});
_x000D_
You can have many java versions in your system.
I think you should add the java 8 in yours JREs installed or edit.
Take a look my screen:
If you click in edit (check your java 8 path):
http://www.mrexcel.com/td0097.html
Dim WS as Worksheet
Set WS = Sheets.Add
You don't have to know where it's located, or what it's name is, you just refer to it as WS.
If you still want to do this the "old fashioned" way, try this:
Sheets.Add.Name = "Test"
edit: I guess it's now starting to be safe to use the native JSON.stringify() method, supported by most browsers (yes, even IE8+ if you're wondering).
As simple as:
JSON.stringify(yourData)
You should encode you data in JSON before sending it, you can't just send an object like this as POST data.
I recommand using the jQuery json plugin to do so. You can then use something like this in jQuery:
$.post(_saveDeviceUrl, {
data : $.toJSON(postData)
}, function(response){
//Process your response here
}
);
It's probably more than solved. Just want to contribute with another simple solution:
var text = 'uololooo';
// With ES6
[...text].forEach(c => console.log(c))
// With the `of` operator
for (const c of text) {
console.log(c)
}
// With ES5
for (var x = 0, c=''; c = text.charAt(x); x++) {
console.log(c);
}
// ES5 without the for loop:
text.split('').forEach(function(c) {
console.log(c);
});
All the open streams & connections need to be properly closed, so the next time we try to use the urlConnection object, it does not throw an error. As an example, the following code change fixed the error for me.
Before:
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
bw.write("Some text");
bw.close();
out.close();
After:
OutputStream os = urlConnection.getOutputStream();
OutputStream out = new BufferedOutputStream(os);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
bw.write("Some text");
bw.close();
out.close();
os.close(); // This is a must.
pls refer this https://stackoverflow.com/a/1972404/951045
TelephonyManager mngr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
mngr.getDeviceId();
add READ_PHONE_STATE
permission to AndroidManifest.xml
Try doing this:
int **ary = new int* [sizeY];
for (int i = 0; i < sizeY; i++)
ary[i] = new int[sizeX];
Try this:
python -m pip install -r requirements.txt
ULs don't have a name attribute, but you can reference the ul by tag name.
Try replacing line 3 in your script with this:
var sub = cat.getElementsByTagName("UL");
You can do it as simple as this using swift 2:
let alertController = UIAlertController(title: "iOScreator", message:
"Hello, world!", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Destructive,handler: { action in
self.pressed()
}))
func pressed()
{
print("you pressed")
}
**or**
let alertController = UIAlertController(title: "iOScreator", message:
"Hello, world!", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Destructive,handler: { action in
print("pressed")
}))
All the answers above are correct i am just showing another way that can be done.
Use entrySet()
to iterate through Map
and need to access value and key:
Map<String, Person> hm = new HashMap<String, Person>();
hm.put("A", new Person("p1"));
hm.put("B", new Person("p2"));
hm.put("C", new Person("p3"));
hm.put("D", new Person("p4"));
hm.put("E", new Person("p5"));
Set<Map.Entry<String, Person>> set = hm.entrySet();
for (Map.Entry<String, Person> me : set) {
System.out.println("Key :"+me.getKey() +" Name : "+ me.getValue().getName()+"Age :"+me.getValue().getAge());
}
If you want just to iterate over keys
of map you can use keySet()
for(String key: map.keySet()) {
Person value = map.get(key);
}
If you just want to iterate over values
of map you can use values()
for(Person person: map.values()) {
}
Found this thread while looking for a way to generate localized but short dates in all browsers without any extra library, just a simple call to format server generated ISO dates.
I went with a combination of holden321 and mwrf's answers. Storing the formats external to the function because it's handier that way and storing the current locale format because it's always useful.
The function can be passed anything that can be passed to a date constructor to get a valid date, and also a language or format for flexibility.
You need to set up the list of formats and a couple more things first:
var LOCALE_DATE_FORMATS = {
// as per mwrf's list
...
}
var LANG = window.navigator.userLanguage || window.navigator.language;
var LOCALE_DATE_FORMAT = LOCALE_DATE_FORMATS[LANG] || 'dd/MM/yyyy';
Then the function is:
function getLocalizedDate(o, options)
{
var res = '';
var date = new Date(o);
if(o != null && !isNaN(date) && typeof(date.getFullYear) == 'function')
{
var d = date.getDate();
var dd = d < 10 ? '0' + d : d;
var M = date.getMonth() + 1;
var MM = M < 10 ? '0' + M : M;
var yyyy = date.getFullYear();
var yy = new String(yyyy).substring(2);
var format = LOCALE_DATE_FORMAT;
if(options && options.lang)
format = LOCALE_DATE_FORMATS[options.lang];
else if(options && options.format)
format = options.format;
res = format
.replace(/dd/g, dd)
.replace(/d/g, d)
.replace(/MM/g, MM)
.replace(/M/g, M)
.replace(/yyyy/g, yyyy)
.replace(/yy/g, yy);
}
return res;
}
getLocalizedDate('2013-03-01T00:00:00', {lang:'sk-SK'})
= 1. 3. 2013
EDIT: Call with no arguments to use the user's locale, of course:
getLocalizedDate('2013-03-01T00:00:00')
= 01/03/2013
(for me)
If you are a fan of extending prototypes, the first lines of the function definition become:
Date.prototype.getLocalized = function(options)
{
var date = this;
Called of course like this:
new Date('2013-03-01T00:00:00').getLocalized({lang:'sk-SK'})
= 1. 3. 2013
EDIT: Again, call with no arguments to use the user's locale:
new Date('2013-03-01T00:00:00').getLocalized()
= 01/03/2013
(for me)
For python 3.5+ it is recommended that you use the run function from the subprocess module. This returns a CompletedProcess
object, from which you can easily obtain the output as well as return code.
from subprocess import PIPE, run
command = ['echo', 'hello']
result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True)
print(result.returncode, result.stdout, result.stderr)
Ondrasej is the "most right" here, IMO.
There are also gui-er ways to do it, without resorting to Xcode. I like TryC.
Mac OS X includes Developer Tools, a developing environment for making Macintosh applications. However, if someone wants to study programming using C, Xcode is too big and too complicated for beginners, to write a small sample program. TryC is very suitable for beginners.
You don't need to launch a huge Xcode application, or type unfamiliar commands in Terminal. Using TryC, you can write, compile and run a C, C++ and Ruby program just like TextEdit. It's only available to compile one source code file but it's enough for trying sample programs.
After countless hours of frustration I managed to get all working:
odbcinst.ini:
[FreeTDS]
Description = FreeTDS Driver v0.91
Driver = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so
Setup = /usr/lib/x86_64-linux-gnu/odbc/libtdsS.so
fileusage=1
dontdlclose=1
UsageCount=1
odbc.ini:
[test]
Driver = FreeTDS
Description = My Test Server
Trace = No
#TraceFile = /tmp/sql.log
ServerName = mssql
#Port = 1433
instance = SQLEXPRESS
Database = usedbname
TDS_Version = 4.2
FreeTDS.conf:
[mssql]
host = hostnameOrIP
instance = SQLEXPRESS
#Port = 1433
tds version = 4.2
First test connection (mssql is a section name from freetds.conf):
tsql -S mssql -U username -P password
You must see some settings but no errors and only a 1> prompt. Use quit to exit.
Then let's test DSN/FreeTDS (test is a section name from odbc.ini; -v means verbose):
isql -v test username password -v
You must see message Connected!
As DPA says, the easiest way to generate a war file of your project is through the IDE. Open the Files tab from your left hand panel, right click on the build.xml file and tell it what type of ant target you want to run.
So I found my own solution to this problem in the end.
After searching through Microsoft documentation I managed to find a new IE11 only style msTextCombineHorizontal
In my test, I check for IE10 styles and if they are a positive match, then I check for the IE11 only style. If I find it, then it's IE11+, if I don't, then it's IE10.
Code Example: Detect IE10 and IE11 by CSS Capability Testing (JSFiddle)
I will update the code example with more styles when I discover them.
NOTE: This will almost certainly identify IE12 and IE13 as "IE11", as those styles will probably carry forward. I will add further tests as new versions roll out, and hopefully be able to rely again on Modernizr.
I'm using this test for fallback behavior. The fallback behavior is just less glamorous styling, it doesn't have reduced functionality.
So to upgrade scikit-learn package, you have to follow below process
Step-1: Open your terminal(Ctrl+Alt+t)
Step-2: Now for checking currently installed packages along with the
versions installed on your
conda environment by typing conda list
Step-3: Now for upgrade type below command
conda update scikit-learn
Hope it helps!!
Method call setSelectedIndex("item_value");
doesn't work because setSelectedIndex
use sequential index.
The dot is not part of the class name. It's only used in CSS/jQuery selector notation. Try this instead:
if ($('#navigation a').hasClass('active')) {
$(this).parent().addClass('active');
}
If $(this)
refers to that anchor, you have to change it to $('#navigation a')
as well because the if condition does not have jQuery callback scope.
Here is a generic solution using a helper method. This can also handle an enum of any underlying type (byte, sbyte, uint, long, etc.)
Helper Method:
static IEnumerable<object> GetEnum<T>() {
var type = typeof(T);
var names = Enum.GetNames(type);
var values = Enum.GetValues(type);
var pairs =
Enumerable.Range(0, names.Length)
.Select(i => new {
Name = names.GetValue(i)
, Value = values.GetValue(i) })
.OrderBy(pair => pair.Name);
return pairs;
}//method
View Model:
public IEnumerable<object> EnumSearchTypes {
get {
return GetEnum<SearchTypes>();
}
}//property
ComboBox:
<ComboBox
SelectedValue ="{Binding SearchType}"
ItemsSource ="{Binding EnumSearchTypes}"
DisplayMemberPath ="Name"
SelectedValuePath ="Value"
/>
Microsoft says here
Table variables does not have distribution statistics, they will not trigger recompiles. Therefore, in many cases, the optimizer will build a query plan on the assumption that the table variable has no rows. For this reason, you should be cautious about using a table variable if you expect a larger number of rows (greater than 100). Temp tables may be a better solution in this case.
These are called "match variables". As previously mentioned they contain the text from your last regular expression match.
More information is in Essential Perl. (Ctrl + F for 'Match Variables' to find the corresponding section.)
Sometimes doing this (the top-voted answer) is not always enough:
$('body').on('click', 'a.myclass', function() {
// do something
});
This can be an issue because of the order event handlers are fired. If you find yourself doing this, but it is causing issues because of the order in which it is handled.. You can always wrap that into a function, that when called "refreshes" the listener.
For example:
function RefreshSomeEventListener() {
// Remove handler from existing elements
$("#wrapper .specific-selector").off();
// Re-add event handler for all matching elements
$("#wrapper .specific-selector").on("click", function() {
// Handle event.
}
}
Because it is a function, whenever I set up my listener this way, I typically call it on document ready:
$(document).ready(function() {
// Other ready commands / code
// Call our function to setup initial listening
RefreshSomeEventListener();
});
Then, whenever you add some dynamically added element, call that method again:
function SomeMethodThatAddsElement() {
// Some code / AJAX / whatever.. Adding element dynamically
// Refresh our listener, so the new element is taken into account
RefreshSomeEventListener();
}
Hopefully this helps!
Regards,
$request->offsetSet(key, value);
// Embarcadero C++ Builder
// convertion string to wstring
string str1 = "hello";
String str2 = str1; // typedef UnicodeString String; -> str2 contains now u"hello";
// convertion wstring to string
String str2 = u"hello";
string str1 = UTF8string(str2).c_str(); // -> str1 contains now "hello"
try
Sub save()
ActiveWorkbook.SaveAS Filename:="C:\-docs\cmat\Desktop\New folder\" & Range("C5").Text & chr(32) & Range("C8").Text &".xls", FileFormat:= _
xlNormal, Password:="", WriteResPassword:="", ReadOnlyRecommended:=False _
, CreateBackup:=False
End Sub
If you want to save the workbook with the macros use the below code
Sub save()
ActiveWorkbook.SaveAs Filename:="C:\Users\" & Environ$("username") & _
"\Desktop\" & Range("C5").Text & Chr(32) & Range("C8").Text & ".xlsm", FileFormat:= _
xlOpenXMLWorkbookMacroEnabled, Password:=vbNullString, WriteResPassword:=vbNullString, _
ReadOnlyRecommended:=False, CreateBackup:=False
End Sub
if you want to save workbook with no macros and no pop-up use this
Sub save()
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:="C:\Users\" & Environ$("username") & _
"\Desktop\" & Range("C5").Text & Chr(32) & Range("C8").Text & ".xls", _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
Application.DisplayAlerts = True
End Sub
Best and Free ( maybe only) solution for this is google sheets. i don't know whether it plots as u expected or not but certainly you can draw multiple axes.
Regards
keerthan