file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
analytics.service.ts |
// Declare ga function as ambient
declare const ga: Function;
@Injectable()
export class AnalyticsService {
private config: Microsoft.ApplicationInsights.IConfig = {
instrumentationKey: environment.appInsights.instrumentationKey
};
constructor() {
if (!AppInsights.config) {
AppInsights.downloadAndSetup(this.config);
}
}
logPageView(name?: string,
url?: string,
properties?: any,
measurements?: any,
duration?: number) {
AppInsights.trackPageView(
name,
url,
properties,
measurements,
duration);
ga('set', 'page', url);
ga('send', 'pageview');
}
emitEvent(eventCategory: string,
eventAction: string,
eventLabel: string = null,
eventValue: number = null) {
ga(
'send',
'event',
{
eventCategory: eventCategory,
eventLabel: eventLabel,
eventAction: eventAction,
eventValue: eventValue
});
}
} | import { Injectable } from '@angular/core';
import { environment } from '../../../environments/environment';
import { AppInsights } from 'applicationinsights-js'; | random_line_split | |
analytics.service.ts | import { Injectable } from '@angular/core';
import { environment } from '../../../environments/environment';
import { AppInsights } from 'applicationinsights-js';
// Declare ga function as ambient
declare const ga: Function;
@Injectable()
export class AnalyticsService {
private config: Microsoft.ApplicationInsights.IConfig = {
instrumentationKey: environment.appInsights.instrumentationKey
};
constructor() {
if (!AppInsights.config) {
| }
logPageView(name?: string,
url?: string,
properties?: any,
measurements?: any,
duration?: number) {
AppInsights.trackPageView(
name,
url,
properties,
measurements,
duration);
ga('set', 'page', url);
ga('send', 'pageview');
}
emitEvent(eventCategory: string,
eventAction: string,
eventLabel: string = null,
eventValue: number = null) {
ga(
'send',
'event',
{
eventCategory: eventCategory,
eventLabel: eventLabel,
eventAction: eventAction,
eventValue: eventValue
});
}
}
| AppInsights.downloadAndSetup(this.config);
}
| conditional_block |
read_multifield_dataset.py | import sys
if __name__ == "__main__":
# Parse command line arguments
if len(sys.argv) < 2:
sys.exit("python {} <datasetFilename> {{<maxPoints>}}".format(sys.argv[0]))
datasetFilename = sys.argv[1]
if len(sys.argv) >= 3:
maxPoints = int(sys.argv[2])
else:
maxPoints = None
# Perform initial pass through file to determine line count (i.e. # of points)
lineCount = 0
with open(datasetFilename, "r") as f:
line = f.readline()
while line:
lineCount += 1
line = f.readline()
# Read first line and use to make assumption about the dimensionality of each point
numDimensions = 0
with open(datasetFilename, "r") as f:
firstLine = f.readline()
numDimensions = len(firstLine.split()) | # Print initial header at END of file (so we have number of points already)
if maxPoints:
numPoints = min(lineCount, maxPoints)
else:
numPoints = lineCount
print("{} {}".format(numDimensions, numPoints))
# Output dataset header which defines dimensionality of data and number of points
# Read entire file line-by-line, printing out each line as a point
with open(datasetFilename, "r") as f:
pointsRead = 0
line = f.readline()
while line:
fields = line.split()
floatFields = [ str(float(x)) for x in fields ]
print(" ".join(floatFields))
# Stop reading file is maximum number of points have been read
pointsRead += 1
if maxPoints and pointsRead >= maxPoints:
break
# Read next line of file
line = f.readline() | # If dimensionality of dataset is 0, print error message and exit
if numDimensions == 0:
sys.exit("Could not determine dimensionality of dataset")
| random_line_split |
read_multifield_dataset.py | import sys
if __name__ == "__main__":
# Parse command line arguments
if len(sys.argv) < 2:
sys.exit("python {} <datasetFilename> {{<maxPoints>}}".format(sys.argv[0]))
datasetFilename = sys.argv[1]
if len(sys.argv) >= 3:
maxPoints = int(sys.argv[2])
else:
maxPoints = None
# Perform initial pass through file to determine line count (i.e. # of points)
lineCount = 0
with open(datasetFilename, "r") as f:
line = f.readline()
while line:
lineCount += 1
line = f.readline()
# Read first line and use to make assumption about the dimensionality of each point
numDimensions = 0
with open(datasetFilename, "r") as f:
firstLine = f.readline()
numDimensions = len(firstLine.split())
# If dimensionality of dataset is 0, print error message and exit
if numDimensions == 0:
sys.exit("Could not determine dimensionality of dataset")
# Print initial header at END of file (so we have number of points already)
if maxPoints:
|
else:
numPoints = lineCount
print("{} {}".format(numDimensions, numPoints))
# Output dataset header which defines dimensionality of data and number of points
# Read entire file line-by-line, printing out each line as a point
with open(datasetFilename, "r") as f:
pointsRead = 0
line = f.readline()
while line:
fields = line.split()
floatFields = [ str(float(x)) for x in fields ]
print(" ".join(floatFields))
# Stop reading file is maximum number of points have been read
pointsRead += 1
if maxPoints and pointsRead >= maxPoints:
break
# Read next line of file
line = f.readline() | numPoints = min(lineCount, maxPoints) | conditional_block |
utils.py | from collections import OrderedDict
from purl import URL as PURL
def URL(base, path, segments=None, defaults=None):
"""
URL segment handler capable of getting and setting segments by name. The
URL is constructed by joining base, path and segments.
For each segment a property capable of getting and setting that segment is | """
# Make a copy of the Segments class
url_class = type(Segments.__name__, Segments.__bases__,
dict(Segments.__dict__))
segments = [] if segments is None else segments
defaults = [] if defaults is None else defaults
# For each segment attach a property capable of getting and setting it
for segment in segments:
setattr(url_class, segment, url_class._segment(segment))
# Instantiate the class with the actual parameters
return url_class(base, path, segments, defaults)
class Segments(object):
"""
URL segment handler, not intended for direct use. The URL is constructed by
joining base, path and segments.
"""
def __init__(self, base, path, segments, defaults):
# Preserve the base URL
self.base = PURL(base, path=path)
# Map the segments and defaults lists to an ordered dict
self.segments = OrderedDict(zip(segments, defaults))
def build(self):
# Join base segments and segments
segments = self.base.path_segments() + tuple(self.segments.values())
# Create a new URL with the segments replaced
url = self.base.path_segments(segments)
return url
def full_path(self):
full_path = self.build().as_string()
full_path = full_path.replace(self.base.host(), '')
full_path = full_path.replace(self.base.scheme(), '')
return full_path[4:]
def __str__(self):
return self.build().as_string()
def _get_segment(self, segment):
return self.segments[segment]
def _set_segment(self, segment, value):
self.segments[segment] = value
@classmethod
def _segment(cls, segment):
"""
Returns a property capable of setting and getting a segment.
"""
return property(
fget=lambda x: cls._get_segment(x, segment),
fset=lambda x, v: cls._set_segment(x, segment, v),
) | created dinamically. | random_line_split |
utils.py | from collections import OrderedDict
from purl import URL as PURL
def URL(base, path, segments=None, defaults=None):
"""
URL segment handler capable of getting and setting segments by name. The
URL is constructed by joining base, path and segments.
For each segment a property capable of getting and setting that segment is
created dinamically.
"""
# Make a copy of the Segments class
url_class = type(Segments.__name__, Segments.__bases__,
dict(Segments.__dict__))
segments = [] if segments is None else segments
defaults = [] if defaults is None else defaults
# For each segment attach a property capable of getting and setting it
for segment in segments:
setattr(url_class, segment, url_class._segment(segment))
# Instantiate the class with the actual parameters
return url_class(base, path, segments, defaults)
class Segments(object):
"""
URL segment handler, not intended for direct use. The URL is constructed by
joining base, path and segments.
"""
def __init__(self, base, path, segments, defaults):
# Preserve the base URL
self.base = PURL(base, path=path)
# Map the segments and defaults lists to an ordered dict
self.segments = OrderedDict(zip(segments, defaults))
def build(self):
# Join base segments and segments
segments = self.base.path_segments() + tuple(self.segments.values())
# Create a new URL with the segments replaced
url = self.base.path_segments(segments)
return url
def full_path(self):
full_path = self.build().as_string()
full_path = full_path.replace(self.base.host(), '')
full_path = full_path.replace(self.base.scheme(), '')
return full_path[4:]
def | (self):
return self.build().as_string()
def _get_segment(self, segment):
return self.segments[segment]
def _set_segment(self, segment, value):
self.segments[segment] = value
@classmethod
def _segment(cls, segment):
"""
Returns a property capable of setting and getting a segment.
"""
return property(
fget=lambda x: cls._get_segment(x, segment),
fset=lambda x, v: cls._set_segment(x, segment, v),
)
| __str__ | identifier_name |
utils.py | from collections import OrderedDict
from purl import URL as PURL
def URL(base, path, segments=None, defaults=None):
"""
URL segment handler capable of getting and setting segments by name. The
URL is constructed by joining base, path and segments.
For each segment a property capable of getting and setting that segment is
created dinamically.
"""
# Make a copy of the Segments class
url_class = type(Segments.__name__, Segments.__bases__,
dict(Segments.__dict__))
segments = [] if segments is None else segments
defaults = [] if defaults is None else defaults
# For each segment attach a property capable of getting and setting it
for segment in segments:
|
# Instantiate the class with the actual parameters
return url_class(base, path, segments, defaults)
class Segments(object):
"""
URL segment handler, not intended for direct use. The URL is constructed by
joining base, path and segments.
"""
def __init__(self, base, path, segments, defaults):
# Preserve the base URL
self.base = PURL(base, path=path)
# Map the segments and defaults lists to an ordered dict
self.segments = OrderedDict(zip(segments, defaults))
def build(self):
# Join base segments and segments
segments = self.base.path_segments() + tuple(self.segments.values())
# Create a new URL with the segments replaced
url = self.base.path_segments(segments)
return url
def full_path(self):
full_path = self.build().as_string()
full_path = full_path.replace(self.base.host(), '')
full_path = full_path.replace(self.base.scheme(), '')
return full_path[4:]
def __str__(self):
return self.build().as_string()
def _get_segment(self, segment):
return self.segments[segment]
def _set_segment(self, segment, value):
self.segments[segment] = value
@classmethod
def _segment(cls, segment):
"""
Returns a property capable of setting and getting a segment.
"""
return property(
fget=lambda x: cls._get_segment(x, segment),
fset=lambda x, v: cls._set_segment(x, segment, v),
)
| setattr(url_class, segment, url_class._segment(segment)) | conditional_block |
utils.py | from collections import OrderedDict
from purl import URL as PURL
def URL(base, path, segments=None, defaults=None):
"""
URL segment handler capable of getting and setting segments by name. The
URL is constructed by joining base, path and segments.
For each segment a property capable of getting and setting that segment is
created dinamically.
"""
# Make a copy of the Segments class
url_class = type(Segments.__name__, Segments.__bases__,
dict(Segments.__dict__))
segments = [] if segments is None else segments
defaults = [] if defaults is None else defaults
# For each segment attach a property capable of getting and setting it
for segment in segments:
setattr(url_class, segment, url_class._segment(segment))
# Instantiate the class with the actual parameters
return url_class(base, path, segments, defaults)
class Segments(object):
| """
URL segment handler, not intended for direct use. The URL is constructed by
joining base, path and segments.
"""
def __init__(self, base, path, segments, defaults):
# Preserve the base URL
self.base = PURL(base, path=path)
# Map the segments and defaults lists to an ordered dict
self.segments = OrderedDict(zip(segments, defaults))
def build(self):
# Join base segments and segments
segments = self.base.path_segments() + tuple(self.segments.values())
# Create a new URL with the segments replaced
url = self.base.path_segments(segments)
return url
def full_path(self):
full_path = self.build().as_string()
full_path = full_path.replace(self.base.host(), '')
full_path = full_path.replace(self.base.scheme(), '')
return full_path[4:]
def __str__(self):
return self.build().as_string()
def _get_segment(self, segment):
return self.segments[segment]
def _set_segment(self, segment, value):
self.segments[segment] = value
@classmethod
def _segment(cls, segment):
"""
Returns a property capable of setting and getting a segment.
"""
return property(
fget=lambda x: cls._get_segment(x, segment),
fset=lambda x, v: cls._set_segment(x, segment, v),
) | identifier_body | |
benchmark.ndarray_nd_singleton_dims_float64.native.js | /**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// MODULES //
var resolve = require( 'path' ).resolve;
var tryRequire = require( '@stdlib/utils/try-require' );
var bench = require( '@stdlib/bench' );
var uniform = require( '@stdlib/random/base/uniform' ).factory;
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var pow = require( '@stdlib/math/base/special/pow' );
var Float64Array = require( '@stdlib/array/float64' );
var ndarray = require( '@stdlib/ndarray/ctor' );
var pkg = require( './../package.json' ).name;
// VARIABLES //
var abs = tryRequire( resolve( __dirname, './../lib/native.js' ) );
var opts = {
'skip': ( abs instanceof Error )
};
var rand = uniform( -100.0, 100.0 );
// FUNCTIONS //
/**
* Creates a benchmark function.
*
* @private
* @param {PositiveInteger} len - array length
* @returns {Function} benchmark function
*/
function createBenchmark( len ) |
// MAIN //
/**
* Main execution sequence.
*
* @private
*/
function main() {
var len;
var min;
var max;
var f;
var i;
min = 1; // 10^min
max = 6; // 10^max
for ( i = min; i <= max; i++ ) {
len = pow( 10, i );
f = createBenchmark( len );
bench( pkg+'::native,ndarray:contiguous=false,ndims=3,singleton_dims=2,dtype=float64,len='+len, opts, f );
}
}
main();
| {
var buf;
var sh;
var st;
var x;
var i;
buf = new Float64Array( len*2 );
for ( i = 0; i < len*2; i++ ) {
buf[ i ] = rand();
}
sh = [ len, 1, 1 ];
st = [ 2, 1, 1 ];
x = ndarray( 'float64', buf, sh, st, 0, 'row-major' );
return benchmark;
/**
* Benchmark function.
*
* @private
* @param {Benchmark} b - benchmark instance
*/
function benchmark( b ) {
var y;
var i;
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
y = abs( x );
if ( isnan( y.data[ i%len ] ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnan( y.data[ i%len ] ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
}
} | identifier_body |
benchmark.ndarray_nd_singleton_dims_float64.native.js | /**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// MODULES //
var resolve = require( 'path' ).resolve;
var tryRequire = require( '@stdlib/utils/try-require' );
var bench = require( '@stdlib/bench' );
var uniform = require( '@stdlib/random/base/uniform' ).factory;
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var pow = require( '@stdlib/math/base/special/pow' );
var Float64Array = require( '@stdlib/array/float64' );
var ndarray = require( '@stdlib/ndarray/ctor' );
var pkg = require( './../package.json' ).name;
// VARIABLES //
var abs = tryRequire( resolve( __dirname, './../lib/native.js' ) );
var opts = {
'skip': ( abs instanceof Error )
};
var rand = uniform( -100.0, 100.0 );
// FUNCTIONS //
/**
* Creates a benchmark function.
*
* @private
* @param {PositiveInteger} len - array length
* @returns {Function} benchmark function
*/
function | ( len ) {
var buf;
var sh;
var st;
var x;
var i;
buf = new Float64Array( len*2 );
for ( i = 0; i < len*2; i++ ) {
buf[ i ] = rand();
}
sh = [ len, 1, 1 ];
st = [ 2, 1, 1 ];
x = ndarray( 'float64', buf, sh, st, 0, 'row-major' );
return benchmark;
/**
* Benchmark function.
*
* @private
* @param {Benchmark} b - benchmark instance
*/
function benchmark( b ) {
var y;
var i;
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
y = abs( x );
if ( isnan( y.data[ i%len ] ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnan( y.data[ i%len ] ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
}
}
// MAIN //
/**
* Main execution sequence.
*
* @private
*/
function main() {
var len;
var min;
var max;
var f;
var i;
min = 1; // 10^min
max = 6; // 10^max
for ( i = min; i <= max; i++ ) {
len = pow( 10, i );
f = createBenchmark( len );
bench( pkg+'::native,ndarray:contiguous=false,ndims=3,singleton_dims=2,dtype=float64,len='+len, opts, f );
}
}
main();
| createBenchmark | identifier_name |
benchmark.ndarray_nd_singleton_dims_float64.native.js | /**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// MODULES //
var resolve = require( 'path' ).resolve;
var tryRequire = require( '@stdlib/utils/try-require' );
var bench = require( '@stdlib/bench' ); | var isnan = require( '@stdlib/math/base/assert/is-nan' );
var pow = require( '@stdlib/math/base/special/pow' );
var Float64Array = require( '@stdlib/array/float64' );
var ndarray = require( '@stdlib/ndarray/ctor' );
var pkg = require( './../package.json' ).name;
// VARIABLES //
var abs = tryRequire( resolve( __dirname, './../lib/native.js' ) );
var opts = {
'skip': ( abs instanceof Error )
};
var rand = uniform( -100.0, 100.0 );
// FUNCTIONS //
/**
* Creates a benchmark function.
*
* @private
* @param {PositiveInteger} len - array length
* @returns {Function} benchmark function
*/
function createBenchmark( len ) {
var buf;
var sh;
var st;
var x;
var i;
buf = new Float64Array( len*2 );
for ( i = 0; i < len*2; i++ ) {
buf[ i ] = rand();
}
sh = [ len, 1, 1 ];
st = [ 2, 1, 1 ];
x = ndarray( 'float64', buf, sh, st, 0, 'row-major' );
return benchmark;
/**
* Benchmark function.
*
* @private
* @param {Benchmark} b - benchmark instance
*/
function benchmark( b ) {
var y;
var i;
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
y = abs( x );
if ( isnan( y.data[ i%len ] ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnan( y.data[ i%len ] ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
}
}
// MAIN //
/**
* Main execution sequence.
*
* @private
*/
function main() {
var len;
var min;
var max;
var f;
var i;
min = 1; // 10^min
max = 6; // 10^max
for ( i = min; i <= max; i++ ) {
len = pow( 10, i );
f = createBenchmark( len );
bench( pkg+'::native,ndarray:contiguous=false,ndims=3,singleton_dims=2,dtype=float64,len='+len, opts, f );
}
}
main(); | var uniform = require( '@stdlib/random/base/uniform' ).factory; | random_line_split |
benchmark.ndarray_nd_singleton_dims_float64.native.js | /**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// MODULES //
var resolve = require( 'path' ).resolve;
var tryRequire = require( '@stdlib/utils/try-require' );
var bench = require( '@stdlib/bench' );
var uniform = require( '@stdlib/random/base/uniform' ).factory;
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var pow = require( '@stdlib/math/base/special/pow' );
var Float64Array = require( '@stdlib/array/float64' );
var ndarray = require( '@stdlib/ndarray/ctor' );
var pkg = require( './../package.json' ).name;
// VARIABLES //
var abs = tryRequire( resolve( __dirname, './../lib/native.js' ) );
var opts = {
'skip': ( abs instanceof Error )
};
var rand = uniform( -100.0, 100.0 );
// FUNCTIONS //
/**
* Creates a benchmark function.
*
* @private
* @param {PositiveInteger} len - array length
* @returns {Function} benchmark function
*/
function createBenchmark( len ) {
var buf;
var sh;
var st;
var x;
var i;
buf = new Float64Array( len*2 );
for ( i = 0; i < len*2; i++ ) {
buf[ i ] = rand();
}
sh = [ len, 1, 1 ];
st = [ 2, 1, 1 ];
x = ndarray( 'float64', buf, sh, st, 0, 'row-major' );
return benchmark;
/**
* Benchmark function.
*
* @private
* @param {Benchmark} b - benchmark instance
*/
function benchmark( b ) {
var y;
var i;
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
y = abs( x );
if ( isnan( y.data[ i%len ] ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnan( y.data[ i%len ] ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
}
}
// MAIN //
/**
* Main execution sequence.
*
* @private
*/
function main() {
var len;
var min;
var max;
var f;
var i;
min = 1; // 10^min
max = 6; // 10^max
for ( i = min; i <= max; i++ ) |
}
main();
| {
len = pow( 10, i );
f = createBenchmark( len );
bench( pkg+'::native,ndarray:contiguous=false,ndims=3,singleton_dims=2,dtype=float64,len='+len, opts, f );
} | conditional_block |
cancel-app-deployment.spec.ts | import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import { createContext } from '../../common'; | import * as MOCK from './cancel-app-deployment.mock';
describe('app', () => {
const DEPLOY_ID = 'deploy-id';
const URL = `/apps/${MOCK.request.body.app_id}/deployments/${DEPLOY_ID}/cancel`;
const TOKEN = process.env.TEST_TOKEN as string;
const mock = new MockAdapter(axios);
mock.onPost(URL, undefined).reply(
MOCK.response.headers.status,
MOCK.response.body,
MOCK.response.headers,
);
const context = createContext({
axios,
token: TOKEN,
});
beforeEach(() => {
mock.resetHistory();
});
describe('cancel-app-deployment', () => {
it('should be a fn', () => {
expect(typeof cancelAppDeployment).toBe('function');
});
it('should return a fn', () => {
expect(typeof cancelAppDeployment(context)).toBe('function');
});
it('should return a valid response', async () => {
const _cancelAppDeployment = cancelAppDeployment(context);
const response = await _cancelAppDeployment({
app_id: MOCK.request.body.app_id,
deployment_id: DEPLOY_ID,
});
Object.assign(response, {request: mock.history.post[0]});
/// validate response schema
expect(typeof response).toBe('object');
expect(typeof response.data).toBe('object');
expect(typeof response.headers).toBe('object');
expect(typeof response.request).toBe('object');
expect(typeof response.status).toBe('number');
/// validate request
const {request} = response;
expect(request.baseURL + request.url).toBe(context.endpoint + URL);
expect(request.method).toBe('post');
expect(request.headers).toMatchObject(MOCK.request.headers);
/// validate data
expect(response.data).toBeDefined();
const {deployment} = response.data;
expect(typeof deployment.id).toBe('string');
expect(typeof deployment.spec.name).toBe('string');
/// validate headers
const {headers, status} = response;
expect(headers).toMatchObject(MOCK.response.headers);
expect(status).toBe(MOCK.response.headers.status);
});
});
}); | import {cancelAppDeployment} from './cancel-app-deployment'; | random_line_split |
issue-7563.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms. | fn do_nothing(&self);
}
struct A { a: int }
struct B<'a> { b: int, pa: &'a A }
impl IDummy for A {
fn do_nothing(&self) {
println!("A::do_nothing() is called");
}
}
impl<'a> B<'a> {
fn get_pa(&self) -> &'a IDummy { self.pa as &'a IDummy }
}
pub fn main() {
let sa = A { a: 100 };
let sb = B { b: 200, pa: &sa };
println!("sa is {:?}", sa);
println!("sb is {:?}", sb);
println!("sb.pa is {:?}", sb.get_pa());
} |
extern crate debug;
trait IDummy { | random_line_split |
issue-7563.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern crate debug;
trait IDummy {
fn do_nothing(&self);
}
struct A { a: int }
struct | <'a> { b: int, pa: &'a A }
impl IDummy for A {
fn do_nothing(&self) {
println!("A::do_nothing() is called");
}
}
impl<'a> B<'a> {
fn get_pa(&self) -> &'a IDummy { self.pa as &'a IDummy }
}
pub fn main() {
let sa = A { a: 100 };
let sb = B { b: 200, pa: &sa };
println!("sa is {:?}", sa);
println!("sb is {:?}", sb);
println!("sb.pa is {:?}", sb.get_pa());
}
| B | identifier_name |
$VirtualScrollExample.ts |
import { Behavior } from '@aelea/core'
import { $text, component, style } from '@aelea/dom'
import { $card, $column, $row, $seperator, $TextField, $VirtualScroll, layoutSheet, ScrollRequest, ScrollResponse } from '@aelea/ui-components'
import { pallete } from '@aelea/ui-components-theme'
import { at, debounce, empty, join, map, merge, now, snapshot, startWith, switchLatest } from '@most/core'
import { Stream } from '@most/types'
function filterArrayByText(array: string[], filter: string) |
const $label = (label: string, value: Stream<string> | string) => $row(layoutSheet.spacingSmall)(
$text(style({ color: pallete.foreground }))(label),
$text(value)
)
export const $VirtualScrollExample = component((
[scrollRequest, scrollRequestTether]: Behavior<ScrollRequest, ScrollRequest>,
[delayResponse, delayResponseTether]: Behavior<string, number>,
[filter, filterTether]: Behavior<string, string>,
) => {
const PAGE_SIZE = 25
const TOTAL_ITEMS = 1000
const formatNumber = Intl.NumberFormat().format
const initialDelayResponse = now(1600)
const delayWithInitial = merge(initialDelayResponse, delayResponse)
let i = 0
const $item = $text(style({ padding: '3px 10px' }))
const stubbedData = Array(TOTAL_ITEMS).fill(null).map(() =>
`item: ${Math.random().toString(36).substring(7)} ${formatNumber(++i)}`
)
const dataSourceFilter = (filter: string) => join(
snapshot((delay, requestNumber): Stream<ScrollResponse> => {
const pageStart = requestNumber * PAGE_SIZE
const pageEnd = pageStart + PAGE_SIZE
const filteredItems = filterArrayByText(stubbedData, filter)
const $items = filteredItems.slice(pageStart, pageEnd).map(id => {
return $item(id)
})
return at(delay, { $items: $items, offset: 0, pageSize: PAGE_SIZE })
}, delayWithInitial, scrollRequest)
)
const filterText = startWith('', filter)
const debouncedFilterText = debounce(300, filterText)
return [
$column(layoutSheet.spacingBig)(
$text(`High performance dynamically loaded list based on Intersection Observer Web API. this example shows a very common pagination and REST like fetching asynchnously more pages`),
$row(layoutSheet.spacingBig)(
$label('Page: ', map(l => String(l), scrollRequest)),
$label(`Page Size:`, String(PAGE_SIZE)),
$label(`Total Items:`, String(TOTAL_ITEMS)),
),
$row(layoutSheet.spacingBig)(
$TextField({
label: 'Filter',
value: empty(),
hint: 'Remove any items that does not match filter and debounce changes by 300ms to prevert spamming',
containerOp: layoutSheet.flex
})({
change: filterTether()
}),
$TextField({
label: 'Delay Response(ms)',
value: initialDelayResponse,
hint: 'Emulate the duration of a datasource response, show a stubbed $node instead',
containerOp: layoutSheet.flex
})({
change: delayResponseTether(
map(Number)
)
}),
),
$seperator,
$card(style({ padding: 0 }))(
switchLatest(
map(searchText =>
$VirtualScroll({
dataSource: dataSourceFilter(searchText),
containerOps: style({ padding: '8px', maxHeight: '400px' })
})({
scrollIndex: scrollRequestTether(),
})
, debouncedFilterText)
)
)
)
]
})
| {
const filterLowercase = filter.toLocaleLowerCase()
return array.filter(id =>
id.indexOf(filterLowercase) > -1
)
} | identifier_body |
$VirtualScrollExample.ts |
import { Behavior } from '@aelea/core'
import { $text, component, style } from '@aelea/dom'
import { $card, $column, $row, $seperator, $TextField, $VirtualScroll, layoutSheet, ScrollRequest, ScrollResponse } from '@aelea/ui-components'
import { pallete } from '@aelea/ui-components-theme'
import { at, debounce, empty, join, map, merge, now, snapshot, startWith, switchLatest } from '@most/core'
import { Stream } from '@most/types'
function | (array: string[], filter: string) {
const filterLowercase = filter.toLocaleLowerCase()
return array.filter(id =>
id.indexOf(filterLowercase) > -1
)
}
const $label = (label: string, value: Stream<string> | string) => $row(layoutSheet.spacingSmall)(
$text(style({ color: pallete.foreground }))(label),
$text(value)
)
export const $VirtualScrollExample = component((
[scrollRequest, scrollRequestTether]: Behavior<ScrollRequest, ScrollRequest>,
[delayResponse, delayResponseTether]: Behavior<string, number>,
[filter, filterTether]: Behavior<string, string>,
) => {
const PAGE_SIZE = 25
const TOTAL_ITEMS = 1000
const formatNumber = Intl.NumberFormat().format
const initialDelayResponse = now(1600)
const delayWithInitial = merge(initialDelayResponse, delayResponse)
let i = 0
const $item = $text(style({ padding: '3px 10px' }))
const stubbedData = Array(TOTAL_ITEMS).fill(null).map(() =>
`item: ${Math.random().toString(36).substring(7)} ${formatNumber(++i)}`
)
const dataSourceFilter = (filter: string) => join(
snapshot((delay, requestNumber): Stream<ScrollResponse> => {
const pageStart = requestNumber * PAGE_SIZE
const pageEnd = pageStart + PAGE_SIZE
const filteredItems = filterArrayByText(stubbedData, filter)
const $items = filteredItems.slice(pageStart, pageEnd).map(id => {
return $item(id)
})
return at(delay, { $items: $items, offset: 0, pageSize: PAGE_SIZE })
}, delayWithInitial, scrollRequest)
)
const filterText = startWith('', filter)
const debouncedFilterText = debounce(300, filterText)
return [
$column(layoutSheet.spacingBig)(
$text(`High performance dynamically loaded list based on Intersection Observer Web API. this example shows a very common pagination and REST like fetching asynchnously more pages`),
$row(layoutSheet.spacingBig)(
$label('Page: ', map(l => String(l), scrollRequest)),
$label(`Page Size:`, String(PAGE_SIZE)),
$label(`Total Items:`, String(TOTAL_ITEMS)),
),
$row(layoutSheet.spacingBig)(
$TextField({
label: 'Filter',
value: empty(),
hint: 'Remove any items that does not match filter and debounce changes by 300ms to prevert spamming',
containerOp: layoutSheet.flex
})({
change: filterTether()
}),
$TextField({
label: 'Delay Response(ms)',
value: initialDelayResponse,
hint: 'Emulate the duration of a datasource response, show a stubbed $node instead',
containerOp: layoutSheet.flex
})({
change: delayResponseTether(
map(Number)
)
}),
),
$seperator,
$card(style({ padding: 0 }))(
switchLatest(
map(searchText =>
$VirtualScroll({
dataSource: dataSourceFilter(searchText),
containerOps: style({ padding: '8px', maxHeight: '400px' })
})({
scrollIndex: scrollRequestTether(),
})
, debouncedFilterText)
)
)
)
]
})
| filterArrayByText | identifier_name |
$VirtualScrollExample.ts | import { Behavior } from '@aelea/core'
import { $text, component, style } from '@aelea/dom'
import { $card, $column, $row, $seperator, $TextField, $VirtualScroll, layoutSheet, ScrollRequest, ScrollResponse } from '@aelea/ui-components'
import { pallete } from '@aelea/ui-components-theme'
import { at, debounce, empty, join, map, merge, now, snapshot, startWith, switchLatest } from '@most/core'
import { Stream } from '@most/types'
function filterArrayByText(array: string[], filter: string) {
const filterLowercase = filter.toLocaleLowerCase()
return array.filter(id =>
id.indexOf(filterLowercase) > -1
)
}
const $label = (label: string, value: Stream<string> | string) => $row(layoutSheet.spacingSmall)(
$text(style({ color: pallete.foreground }))(label),
$text(value)
)
export const $VirtualScrollExample = component((
[scrollRequest, scrollRequestTether]: Behavior<ScrollRequest, ScrollRequest>,
[delayResponse, delayResponseTether]: Behavior<string, number>,
[filter, filterTether]: Behavior<string, string>,
) => {
const PAGE_SIZE = 25
const TOTAL_ITEMS = 1000
const formatNumber = Intl.NumberFormat().format
const initialDelayResponse = now(1600)
const delayWithInitial = merge(initialDelayResponse, delayResponse)
let i = 0
const $item = $text(style({ padding: '3px 10px' }))
const stubbedData = Array(TOTAL_ITEMS).fill(null).map(() =>
`item: ${Math.random().toString(36).substring(7)} ${formatNumber(++i)}`
)
const dataSourceFilter = (filter: string) => join(
snapshot((delay, requestNumber): Stream<ScrollResponse> => {
const pageStart = requestNumber * PAGE_SIZE
const pageEnd = pageStart + PAGE_SIZE
const filteredItems = filterArrayByText(stubbedData, filter)
const $items = filteredItems.slice(pageStart, pageEnd).map(id => {
return $item(id)
})
return at(delay, { $items: $items, offset: 0, pageSize: PAGE_SIZE })
}, delayWithInitial, scrollRequest)
)
const filterText = startWith('', filter)
const debouncedFilterText = debounce(300, filterText)
return [
$column(layoutSheet.spacingBig)(
$text(`High performance dynamically loaded list based on Intersection Observer Web API. this example shows a very common pagination and REST like fetching asynchnously more pages`),
$row(layoutSheet.spacingBig)(
$label('Page: ', map(l => String(l), scrollRequest)),
$label(`Page Size:`, String(PAGE_SIZE)),
$label(`Total Items:`, String(TOTAL_ITEMS)),
),
$row(layoutSheet.spacingBig)(
$TextField({
label: 'Filter',
value: empty(),
hint: 'Remove any items that does not match filter and debounce changes by 300ms to prevert spamming',
containerOp: layoutSheet.flex
})({
change: filterTether()
}),
$TextField({
label: 'Delay Response(ms)',
value: initialDelayResponse,
hint: 'Emulate the duration of a datasource response, show a stubbed $node instead',
containerOp: layoutSheet.flex
})({
change: delayResponseTether(
map(Number)
)
}), | $card(style({ padding: 0 }))(
switchLatest(
map(searchText =>
$VirtualScroll({
dataSource: dataSourceFilter(searchText),
containerOps: style({ padding: '8px', maxHeight: '400px' })
})({
scrollIndex: scrollRequestTether(),
})
, debouncedFilterText)
)
)
)
]
}) | ),
$seperator,
| random_line_split |
cfg-macros-foo.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-fast compile-flags directive doesn't work for check-fast
// compile-flags: --cfg foo
// check that cfg correctly chooses between the macro impls (see also
// cfg-macros-notfoo.rs)
#[feature(macro_rules)];
#[cfg(foo)]
#[macro_escape]
mod foo {
macro_rules! bar {
() => { true }
}
}
#[cfg(not(foo))]
#[macro_escape]
mod foo {
macro_rules! bar {
() => { false }
}
}
pub fn main() | {
assert!(bar!())
} | identifier_body | |
cfg-macros-foo.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-fast compile-flags directive doesn't work for check-fast
// compile-flags: --cfg foo
// check that cfg correctly chooses between the macro impls (see also
// cfg-macros-notfoo.rs)
#[feature(macro_rules)];
#[cfg(foo)]
#[macro_escape]
mod foo {
macro_rules! bar {
() => { true }
}
}
#[cfg(not(foo))]
#[macro_escape]
mod foo {
macro_rules! bar {
() => { false } | assert!(bar!())
} | }
}
pub fn main() { | random_line_split |
cfg-macros-foo.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-fast compile-flags directive doesn't work for check-fast
// compile-flags: --cfg foo
// check that cfg correctly chooses between the macro impls (see also
// cfg-macros-notfoo.rs)
#[feature(macro_rules)];
#[cfg(foo)]
#[macro_escape]
mod foo {
macro_rules! bar {
() => { true }
}
}
#[cfg(not(foo))]
#[macro_escape]
mod foo {
macro_rules! bar {
() => { false }
}
}
pub fn | () {
assert!(bar!())
}
| main | identifier_name |
tag_follow_disagreement.py | import sys
tagging_filepath = sys.argv[1]
following_filepath = sys.argv[2]
delim = '\t'
if len(sys.argv) > 3:
delim = sys.argv[3]
graph = {}
for line in open(tagging_filepath):
entry = line.rstrip().split('\t')
src = entry[0]
dst = entry[1]
if not src in graph: graph[src] = {}
graph[src][dst] = 0
for line in open(following_filepath):
entry = line.rstrip().split('\t')
src = entry[0]
dst = entry[1]
if src in graph and dst in graph[src]:
graph[src][dst] += 1
if dst in graph and src in graph[dst]:
graph[dst][src] += 2
w_dir = 0
wo_dir = 0
count = 0.0
for src in graph:
for dst in graph[src]:
val = graph[src][dst]
count += 1
if val in [1,3]:
w_dir += 1
if val in [1,2,3]: |
print "%s\t%s" % (w_dir/count, wo_dir/count) | wo_dir += 1 | random_line_split |
tag_follow_disagreement.py | import sys
tagging_filepath = sys.argv[1]
following_filepath = sys.argv[2]
delim = '\t'
if len(sys.argv) > 3:
delim = sys.argv[3]
graph = {}
for line in open(tagging_filepath):
entry = line.rstrip().split('\t')
src = entry[0]
dst = entry[1]
if not src in graph: |
graph[src][dst] = 0
for line in open(following_filepath):
entry = line.rstrip().split('\t')
src = entry[0]
dst = entry[1]
if src in graph and dst in graph[src]:
graph[src][dst] += 1
if dst in graph and src in graph[dst]:
graph[dst][src] += 2
w_dir = 0
wo_dir = 0
count = 0.0
for src in graph:
for dst in graph[src]:
val = graph[src][dst]
count += 1
if val in [1,3]:
w_dir += 1
if val in [1,2,3]:
wo_dir += 1
print "%s\t%s" % (w_dir/count, wo_dir/count)
| graph[src] = {} | conditional_block |
kindck-copy.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test which of the builtin types are considered POD.
use std::rc::Rc;
fn assert_copy<T:Copy>() |
trait Dummy { }
struct MyStruct {
x: isize,
y: isize,
}
impl Copy for MyStruct {}
struct MyNoncopyStruct {
x: Box<char>,
}
fn test<'a,T,U:Copy>(_: &'a isize) {
// lifetime pointers are ok...
assert_copy::<&'static isize>();
assert_copy::<&'a isize>();
assert_copy::<&'a str>();
assert_copy::<&'a [isize]>();
// ...unless they are mutable
assert_copy::<&'static mut isize>(); //~ ERROR `core::marker::Copy` is not implemented
assert_copy::<&'a mut isize>(); //~ ERROR `core::marker::Copy` is not implemented
// ~ pointers are not ok
assert_copy::<Box<isize>>(); //~ ERROR `core::marker::Copy` is not implemented
assert_copy::<String>(); //~ ERROR `core::marker::Copy` is not implemented
assert_copy::<Vec<isize> >(); //~ ERROR `core::marker::Copy` is not implemented
assert_copy::<Box<&'a mut isize>>(); //~ ERROR `core::marker::Copy` is not implemented
// borrowed object types are generally ok
assert_copy::<&'a Dummy>();
assert_copy::<&'a (Dummy+Copy)>();
assert_copy::<&'static (Dummy+Copy)>();
// owned object types are not ok
assert_copy::<Box<Dummy>>(); //~ ERROR `core::marker::Copy` is not implemented
assert_copy::<Box<Dummy+Copy>>(); //~ ERROR `core::marker::Copy` is not implemented
// mutable object types are not ok
assert_copy::<&'a mut (Dummy+Copy)>(); //~ ERROR `core::marker::Copy` is not implemented
// unsafe ptrs are ok
assert_copy::<*const isize>();
assert_copy::<*const &'a mut isize>();
// regular old ints and such are ok
assert_copy::<isize>();
assert_copy::<bool>();
assert_copy::<()>();
// tuples are ok
assert_copy::<(isize,isize)>();
// structs of POD are ok
assert_copy::<MyStruct>();
// structs containing non-POD are not ok
assert_copy::<MyNoncopyStruct>(); //~ ERROR `core::marker::Copy` is not implemented
// ref counted types are not ok
assert_copy::<Rc<isize>>(); //~ ERROR `core::marker::Copy` is not implemented
}
pub fn main() {
}
| { } | identifier_body |
kindck-copy.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test which of the builtin types are considered POD.
use std::rc::Rc;
fn assert_copy<T:Copy>() { }
trait Dummy { }
struct | {
x: isize,
y: isize,
}
impl Copy for MyStruct {}
struct MyNoncopyStruct {
x: Box<char>,
}
fn test<'a,T,U:Copy>(_: &'a isize) {
// lifetime pointers are ok...
assert_copy::<&'static isize>();
assert_copy::<&'a isize>();
assert_copy::<&'a str>();
assert_copy::<&'a [isize]>();
// ...unless they are mutable
assert_copy::<&'static mut isize>(); //~ ERROR `core::marker::Copy` is not implemented
assert_copy::<&'a mut isize>(); //~ ERROR `core::marker::Copy` is not implemented
// ~ pointers are not ok
assert_copy::<Box<isize>>(); //~ ERROR `core::marker::Copy` is not implemented
assert_copy::<String>(); //~ ERROR `core::marker::Copy` is not implemented
assert_copy::<Vec<isize> >(); //~ ERROR `core::marker::Copy` is not implemented
assert_copy::<Box<&'a mut isize>>(); //~ ERROR `core::marker::Copy` is not implemented
// borrowed object types are generally ok
assert_copy::<&'a Dummy>();
assert_copy::<&'a (Dummy+Copy)>();
assert_copy::<&'static (Dummy+Copy)>();
// owned object types are not ok
assert_copy::<Box<Dummy>>(); //~ ERROR `core::marker::Copy` is not implemented
assert_copy::<Box<Dummy+Copy>>(); //~ ERROR `core::marker::Copy` is not implemented
// mutable object types are not ok
assert_copy::<&'a mut (Dummy+Copy)>(); //~ ERROR `core::marker::Copy` is not implemented
// unsafe ptrs are ok
assert_copy::<*const isize>();
assert_copy::<*const &'a mut isize>();
// regular old ints and such are ok
assert_copy::<isize>();
assert_copy::<bool>();
assert_copy::<()>();
// tuples are ok
assert_copy::<(isize,isize)>();
// structs of POD are ok
assert_copy::<MyStruct>();
// structs containing non-POD are not ok
assert_copy::<MyNoncopyStruct>(); //~ ERROR `core::marker::Copy` is not implemented
// ref counted types are not ok
assert_copy::<Rc<isize>>(); //~ ERROR `core::marker::Copy` is not implemented
}
pub fn main() {
}
| MyStruct | identifier_name |
kindck-copy.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test which of the builtin types are considered POD.
use std::rc::Rc;
fn assert_copy<T:Copy>() { }
trait Dummy { }
struct MyStruct {
x: isize,
y: isize,
}
impl Copy for MyStruct {}
struct MyNoncopyStruct {
x: Box<char>,
}
fn test<'a,T,U:Copy>(_: &'a isize) {
// lifetime pointers are ok...
assert_copy::<&'static isize>();
assert_copy::<&'a isize>();
assert_copy::<&'a str>();
assert_copy::<&'a [isize]>();
// ...unless they are mutable
assert_copy::<&'static mut isize>(); //~ ERROR `core::marker::Copy` is not implemented
assert_copy::<&'a mut isize>(); //~ ERROR `core::marker::Copy` is not implemented
// ~ pointers are not ok
assert_copy::<Box<isize>>(); //~ ERROR `core::marker::Copy` is not implemented
assert_copy::<String>(); //~ ERROR `core::marker::Copy` is not implemented
assert_copy::<Vec<isize> >(); //~ ERROR `core::marker::Copy` is not implemented
assert_copy::<Box<&'a mut isize>>(); //~ ERROR `core::marker::Copy` is not implemented
// borrowed object types are generally ok
assert_copy::<&'a Dummy>();
assert_copy::<&'a (Dummy+Copy)>();
assert_copy::<&'static (Dummy+Copy)>();
// owned object types are not ok
assert_copy::<Box<Dummy>>(); //~ ERROR `core::marker::Copy` is not implemented
assert_copy::<Box<Dummy+Copy>>(); //~ ERROR `core::marker::Copy` is not implemented
// mutable object types are not ok
assert_copy::<&'a mut (Dummy+Copy)>(); //~ ERROR `core::marker::Copy` is not implemented
// unsafe ptrs are ok
assert_copy::<*const isize>();
assert_copy::<*const &'a mut isize>();
// regular old ints and such are ok
assert_copy::<isize>(); | // tuples are ok
assert_copy::<(isize,isize)>();
// structs of POD are ok
assert_copy::<MyStruct>();
// structs containing non-POD are not ok
assert_copy::<MyNoncopyStruct>(); //~ ERROR `core::marker::Copy` is not implemented
// ref counted types are not ok
assert_copy::<Rc<isize>>(); //~ ERROR `core::marker::Copy` is not implemented
}
pub fn main() {
} | assert_copy::<bool>();
assert_copy::<()>();
| random_line_split |
helper_thread.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Implementation of the helper thread for the timer module
//!
//! This module contains the management necessary for the timer worker thread.
//! This thread is responsible for performing the send()s on channels for timers
//! that are using channels instead of a blocking call.
//!
//! The timer thread is lazily initialized, and it's shut down via the
//! `shutdown` function provided. It must be maintained as an invariant that
//! `shutdown` is only called when the entire program is finished. No new timers
//! can be created in the future and there must be no active timers at that
//! time.
use mem;
use rustrt::bookkeeping;
use rustrt::mutex::StaticNativeMutex;
use rustrt;
use cell::UnsafeCell;
use sys::helper_signal;
use prelude::*;
use task;
/// A structure for management of a helper thread.
///
/// This is generally a static structure which tracks the lifetime of a helper
/// thread.
///
/// The fields of this helper are all public, but they should not be used, this
/// is for static initialization.
pub struct Helper<M> {
/// Internal lock which protects the remaining fields
pub lock: StaticNativeMutex,
// You'll notice that the remaining fields are UnsafeCell<T>, and this is
// because all helper thread operations are done through &self, but we need
// these to be mutable (once `lock` is held).
/// Lazily allocated channel to send messages to the helper thread.
pub chan: UnsafeCell<*mut Sender<M>>,
/// OS handle used to wake up a blocked helper thread
pub signal: UnsafeCell<uint>,
/// Flag if this helper thread has booted and been initialized yet.
pub initialized: UnsafeCell<bool>,
}
impl<M: Send> Helper<M> {
/// Lazily boots a helper thread, becoming a no-op if the helper has already
/// been spawned.
///
/// This function will check to see if the thread has been initialized, and
/// if it has it returns quickly. If initialization has not happened yet,
/// the closure `f` will be run (inside of the initialization lock) and
/// passed to the helper thread in a separate task.
///
/// This function is safe to be called many times.
pub fn boot<T: Send>(&'static self,
f: || -> T,
helper: fn(helper_signal::signal, Receiver<M>, T)) {
unsafe {
let _guard = self.lock.lock();
if !*self.initialized.get() {
let (tx, rx) = channel();
*self.chan.get() = mem::transmute(box tx);
let (receive, send) = helper_signal::new();
*self.signal.get() = send as uint;
let t = f();
task::spawn(proc() {
bookkeeping::decrement();
helper(receive, rx, t);
self.lock.lock().signal()
});
rustrt::at_exit(proc() { self.shutdown() });
*self.initialized.get() = true;
}
}
}
/// Sends a message to a spawned worker thread.
///
/// This is only valid if the worker thread has previously booted
pub fn send(&'static self, msg: M) |
fn shutdown(&'static self) {
unsafe {
// Shut down, but make sure this is done inside our lock to ensure
// that we'll always receive the exit signal when the thread
// returns.
let guard = self.lock.lock();
// Close the channel by destroying it
let chan: Box<Sender<M>> = mem::transmute(*self.chan.get());
*self.chan.get() = 0 as *mut Sender<M>;
drop(chan);
helper_signal::signal(*self.signal.get() as helper_signal::signal);
// Wait for the child to exit
guard.wait();
drop(guard);
// Clean up after ourselves
self.lock.destroy();
helper_signal::close(*self.signal.get() as helper_signal::signal);
*self.signal.get() = 0;
}
}
}
| {
unsafe {
let _guard = self.lock.lock();
// Must send and *then* signal to ensure that the child receives the
// message. Otherwise it could wake up and go to sleep before we
// send the message.
assert!(!self.chan.get().is_null());
(**self.chan.get()).send(msg);
helper_signal::signal(*self.signal.get() as helper_signal::signal);
}
} | identifier_body |
helper_thread.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Implementation of the helper thread for the timer module
//!
//! This module contains the management necessary for the timer worker thread.
//! This thread is responsible for performing the send()s on channels for timers
//! that are using channels instead of a blocking call.
//!
//! The timer thread is lazily initialized, and it's shut down via the
//! `shutdown` function provided. It must be maintained as an invariant that
//! `shutdown` is only called when the entire program is finished. No new timers
//! can be created in the future and there must be no active timers at that
//! time.
use mem;
use rustrt::bookkeeping;
use rustrt::mutex::StaticNativeMutex;
use rustrt;
use cell::UnsafeCell;
use sys::helper_signal;
use prelude::*;
use task;
/// A structure for management of a helper thread.
///
/// This is generally a static structure which tracks the lifetime of a helper
/// thread.
///
/// The fields of this helper are all public, but they should not be used, this
/// is for static initialization.
pub struct | <M> {
/// Internal lock which protects the remaining fields
pub lock: StaticNativeMutex,
// You'll notice that the remaining fields are UnsafeCell<T>, and this is
// because all helper thread operations are done through &self, but we need
// these to be mutable (once `lock` is held).
/// Lazily allocated channel to send messages to the helper thread.
pub chan: UnsafeCell<*mut Sender<M>>,
/// OS handle used to wake up a blocked helper thread
pub signal: UnsafeCell<uint>,
/// Flag if this helper thread has booted and been initialized yet.
pub initialized: UnsafeCell<bool>,
}
impl<M: Send> Helper<M> {
/// Lazily boots a helper thread, becoming a no-op if the helper has already
/// been spawned.
///
/// This function will check to see if the thread has been initialized, and
/// if it has it returns quickly. If initialization has not happened yet,
/// the closure `f` will be run (inside of the initialization lock) and
/// passed to the helper thread in a separate task.
///
/// This function is safe to be called many times.
pub fn boot<T: Send>(&'static self,
f: || -> T,
helper: fn(helper_signal::signal, Receiver<M>, T)) {
unsafe {
let _guard = self.lock.lock();
if !*self.initialized.get() {
let (tx, rx) = channel();
*self.chan.get() = mem::transmute(box tx);
let (receive, send) = helper_signal::new();
*self.signal.get() = send as uint;
let t = f();
task::spawn(proc() {
bookkeeping::decrement();
helper(receive, rx, t);
self.lock.lock().signal()
});
rustrt::at_exit(proc() { self.shutdown() });
*self.initialized.get() = true;
}
}
}
/// Sends a message to a spawned worker thread.
///
/// This is only valid if the worker thread has previously booted
pub fn send(&'static self, msg: M) {
unsafe {
let _guard = self.lock.lock();
// Must send and *then* signal to ensure that the child receives the
// message. Otherwise it could wake up and go to sleep before we
// send the message.
assert!(!self.chan.get().is_null());
(**self.chan.get()).send(msg);
helper_signal::signal(*self.signal.get() as helper_signal::signal);
}
}
fn shutdown(&'static self) {
unsafe {
// Shut down, but make sure this is done inside our lock to ensure
// that we'll always receive the exit signal when the thread
// returns.
let guard = self.lock.lock();
// Close the channel by destroying it
let chan: Box<Sender<M>> = mem::transmute(*self.chan.get());
*self.chan.get() = 0 as *mut Sender<M>;
drop(chan);
helper_signal::signal(*self.signal.get() as helper_signal::signal);
// Wait for the child to exit
guard.wait();
drop(guard);
// Clean up after ourselves
self.lock.destroy();
helper_signal::close(*self.signal.get() as helper_signal::signal);
*self.signal.get() = 0;
}
}
}
| Helper | identifier_name |
helper_thread.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Implementation of the helper thread for the timer module
//!
//! This module contains the management necessary for the timer worker thread.
//! This thread is responsible for performing the send()s on channels for timers
//! that are using channels instead of a blocking call.
//!
//! The timer thread is lazily initialized, and it's shut down via the
//! `shutdown` function provided. It must be maintained as an invariant that
//! `shutdown` is only called when the entire program is finished. No new timers
//! can be created in the future and there must be no active timers at that
//! time.
use mem;
use rustrt::bookkeeping;
use rustrt::mutex::StaticNativeMutex;
use rustrt;
use cell::UnsafeCell;
use sys::helper_signal;
use prelude::*;
use task;
/// A structure for management of a helper thread.
///
/// This is generally a static structure which tracks the lifetime of a helper
/// thread.
///
/// The fields of this helper are all public, but they should not be used, this
/// is for static initialization.
pub struct Helper<M> {
/// Internal lock which protects the remaining fields
pub lock: StaticNativeMutex,
// You'll notice that the remaining fields are UnsafeCell<T>, and this is
// because all helper thread operations are done through &self, but we need
// these to be mutable (once `lock` is held).
/// Lazily allocated channel to send messages to the helper thread.
pub chan: UnsafeCell<*mut Sender<M>>,
/// OS handle used to wake up a blocked helper thread
pub signal: UnsafeCell<uint>,
/// Flag if this helper thread has booted and been initialized yet.
pub initialized: UnsafeCell<bool>,
}
impl<M: Send> Helper<M> {
/// Lazily boots a helper thread, becoming a no-op if the helper has already
/// been spawned.
///
/// This function will check to see if the thread has been initialized, and
/// if it has it returns quickly. If initialization has not happened yet,
/// the closure `f` will be run (inside of the initialization lock) and
/// passed to the helper thread in a separate task.
///
/// This function is safe to be called many times.
pub fn boot<T: Send>(&'static self,
f: || -> T,
helper: fn(helper_signal::signal, Receiver<M>, T)) {
unsafe {
let _guard = self.lock.lock();
if !*self.initialized.get() |
}
}
/// Sends a message to a spawned worker thread.
///
/// This is only valid if the worker thread has previously booted
pub fn send(&'static self, msg: M) {
unsafe {
let _guard = self.lock.lock();
// Must send and *then* signal to ensure that the child receives the
// message. Otherwise it could wake up and go to sleep before we
// send the message.
assert!(!self.chan.get().is_null());
(**self.chan.get()).send(msg);
helper_signal::signal(*self.signal.get() as helper_signal::signal);
}
}
fn shutdown(&'static self) {
unsafe {
// Shut down, but make sure this is done inside our lock to ensure
// that we'll always receive the exit signal when the thread
// returns.
let guard = self.lock.lock();
// Close the channel by destroying it
let chan: Box<Sender<M>> = mem::transmute(*self.chan.get());
*self.chan.get() = 0 as *mut Sender<M>;
drop(chan);
helper_signal::signal(*self.signal.get() as helper_signal::signal);
// Wait for the child to exit
guard.wait();
drop(guard);
// Clean up after ourselves
self.lock.destroy();
helper_signal::close(*self.signal.get() as helper_signal::signal);
*self.signal.get() = 0;
}
}
}
| {
let (tx, rx) = channel();
*self.chan.get() = mem::transmute(box tx);
let (receive, send) = helper_signal::new();
*self.signal.get() = send as uint;
let t = f();
task::spawn(proc() {
bookkeeping::decrement();
helper(receive, rx, t);
self.lock.lock().signal()
});
rustrt::at_exit(proc() { self.shutdown() });
*self.initialized.get() = true;
} | conditional_block |
helper_thread.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Implementation of the helper thread for the timer module
//!
//! This module contains the management necessary for the timer worker thread.
//! This thread is responsible for performing the send()s on channels for timers
//! that are using channels instead of a blocking call. | //! The timer thread is lazily initialized, and it's shut down via the
//! `shutdown` function provided. It must be maintained as an invariant that
//! `shutdown` is only called when the entire program is finished. No new timers
//! can be created in the future and there must be no active timers at that
//! time.
use mem;
use rustrt::bookkeeping;
use rustrt::mutex::StaticNativeMutex;
use rustrt;
use cell::UnsafeCell;
use sys::helper_signal;
use prelude::*;
use task;
/// A structure for management of a helper thread.
///
/// This is generally a static structure which tracks the lifetime of a helper
/// thread.
///
/// The fields of this helper are all public, but they should not be used, this
/// is for static initialization.
pub struct Helper<M> {
/// Internal lock which protects the remaining fields
pub lock: StaticNativeMutex,
// You'll notice that the remaining fields are UnsafeCell<T>, and this is
// because all helper thread operations are done through &self, but we need
// these to be mutable (once `lock` is held).
/// Lazily allocated channel to send messages to the helper thread.
pub chan: UnsafeCell<*mut Sender<M>>,
/// OS handle used to wake up a blocked helper thread
pub signal: UnsafeCell<uint>,
/// Flag if this helper thread has booted and been initialized yet.
pub initialized: UnsafeCell<bool>,
}
impl<M: Send> Helper<M> {
/// Lazily boots a helper thread, becoming a no-op if the helper has already
/// been spawned.
///
/// This function will check to see if the thread has been initialized, and
/// if it has it returns quickly. If initialization has not happened yet,
/// the closure `f` will be run (inside of the initialization lock) and
/// passed to the helper thread in a separate task.
///
/// This function is safe to be called many times.
pub fn boot<T: Send>(&'static self,
f: || -> T,
helper: fn(helper_signal::signal, Receiver<M>, T)) {
unsafe {
let _guard = self.lock.lock();
if !*self.initialized.get() {
let (tx, rx) = channel();
*self.chan.get() = mem::transmute(box tx);
let (receive, send) = helper_signal::new();
*self.signal.get() = send as uint;
let t = f();
task::spawn(proc() {
bookkeeping::decrement();
helper(receive, rx, t);
self.lock.lock().signal()
});
rustrt::at_exit(proc() { self.shutdown() });
*self.initialized.get() = true;
}
}
}
/// Sends a message to a spawned worker thread.
///
/// This is only valid if the worker thread has previously booted
pub fn send(&'static self, msg: M) {
unsafe {
let _guard = self.lock.lock();
// Must send and *then* signal to ensure that the child receives the
// message. Otherwise it could wake up and go to sleep before we
// send the message.
assert!(!self.chan.get().is_null());
(**self.chan.get()).send(msg);
helper_signal::signal(*self.signal.get() as helper_signal::signal);
}
}
fn shutdown(&'static self) {
unsafe {
// Shut down, but make sure this is done inside our lock to ensure
// that we'll always receive the exit signal when the thread
// returns.
let guard = self.lock.lock();
// Close the channel by destroying it
let chan: Box<Sender<M>> = mem::transmute(*self.chan.get());
*self.chan.get() = 0 as *mut Sender<M>;
drop(chan);
helper_signal::signal(*self.signal.get() as helper_signal::signal);
// Wait for the child to exit
guard.wait();
drop(guard);
// Clean up after ourselves
self.lock.destroy();
helper_signal::close(*self.signal.get() as helper_signal::signal);
*self.signal.get() = 0;
}
}
} | //! | random_line_split |
base.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from abc import ABCMeta
import csv
from performance_tools.exceptions import ProgressBarException, ElasticsearchException
from performance_tools.utils.progress_bar import create_progress_bar
class BaseURLFlowBackend(object):
"""Collect URL flow from backend. URL Flow: Referrer, Request, Time.
It's necessary to implement extract_url_from_result and __iter__ methods.
"""
__metaclass__ = ABCMeta
def __init__(self):
self._total_hits = 0
def extract_url_from_result(self, result, regex=None):
"""Extract origin url and destination url for each entry in result and construct a list with them.
:param result: results obtained from backend in each iteration.
:type result: object
:param regex: Regular expression to normalize id's in URL.
:type regex: re
:return: List of origin urls and destination urls.
:rtype: list
"""
raise NotImplementedError
def to_csv(self, filename, regex=None, verbose=2):
"""Save results as a CSV file.
:param filename: CSV output file.
:type filename: str
:raise: ValueError if not found any result.
"""
progress = None
try:
with open(filename, 'w') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(['Referrer', 'Request', 'Time'])
count = 0
for result in self:
# Create progress bar or down verbose level
|
except ZeroDivisionError:
raise ElasticsearchException("Search doesn't return any result")
except KeyError:
raise ElasticsearchException("Invalid result")
def __iter__(self):
"""Iterate over each result.
"""
raise NotImplementedError
| if verbose == 2 and progress is None:
try:
progress = create_progress_bar(self._total_hits, 'Extract URLs', 'url')
except ProgressBarException:
verbose = 1
# Write results to csv
rows = self.extract_url_from_result(result, regex)
writer.writerows(rows)
# Update progress
count += len(rows)
if verbose == 2:
progress.update(count if count < self._total_hits else self._total_hits)
elif verbose == 1:
print "{:d}/{:d} ({:d}%)".format(count, self._total_hits, count * 100 / self._total_hits) | conditional_block |
base.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from abc import ABCMeta
import csv
from performance_tools.exceptions import ProgressBarException, ElasticsearchException
from performance_tools.utils.progress_bar import create_progress_bar
class BaseURLFlowBackend(object):
"""Collect URL flow from backend. URL Flow: Referrer, Request, Time.
It's necessary to implement extract_url_from_result and __iter__ methods.
"""
__metaclass__ = ABCMeta
def __init__(self):
self._total_hits = 0
def extract_url_from_result(self, result, regex=None):
"""Extract origin url and destination url for each entry in result and construct a list with them.
:param result: results obtained from backend in each iteration.
:type result: object
:param regex: Regular expression to normalize id's in URL.
:type regex: re
:return: List of origin urls and destination urls.
:rtype: list
"""
raise NotImplementedError | :type filename: str
:raise: ValueError if not found any result.
"""
progress = None
try:
with open(filename, 'w') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(['Referrer', 'Request', 'Time'])
count = 0
for result in self:
# Create progress bar or down verbose level
if verbose == 2 and progress is None:
try:
progress = create_progress_bar(self._total_hits, 'Extract URLs', 'url')
except ProgressBarException:
verbose = 1
# Write results to csv
rows = self.extract_url_from_result(result, regex)
writer.writerows(rows)
# Update progress
count += len(rows)
if verbose == 2:
progress.update(count if count < self._total_hits else self._total_hits)
elif verbose == 1:
print "{:d}/{:d} ({:d}%)".format(count, self._total_hits, count * 100 / self._total_hits)
except ZeroDivisionError:
raise ElasticsearchException("Search doesn't return any result")
except KeyError:
raise ElasticsearchException("Invalid result")
def __iter__(self):
"""Iterate over each result.
"""
raise NotImplementedError |
def to_csv(self, filename, regex=None, verbose=2):
"""Save results as a CSV file.
:param filename: CSV output file. | random_line_split |
base.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from abc import ABCMeta
import csv
from performance_tools.exceptions import ProgressBarException, ElasticsearchException
from performance_tools.utils.progress_bar import create_progress_bar
class BaseURLFlowBackend(object):
| """Collect URL flow from backend. URL Flow: Referrer, Request, Time.
It's necessary to implement extract_url_from_result and __iter__ methods.
"""
__metaclass__ = ABCMeta
def __init__(self):
self._total_hits = 0
def extract_url_from_result(self, result, regex=None):
"""Extract origin url and destination url for each entry in result and construct a list with them.
:param result: results obtained from backend in each iteration.
:type result: object
:param regex: Regular expression to normalize id's in URL.
:type regex: re
:return: List of origin urls and destination urls.
:rtype: list
"""
raise NotImplementedError
def to_csv(self, filename, regex=None, verbose=2):
"""Save results as a CSV file.
:param filename: CSV output file.
:type filename: str
:raise: ValueError if not found any result.
"""
progress = None
try:
with open(filename, 'w') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(['Referrer', 'Request', 'Time'])
count = 0
for result in self:
# Create progress bar or down verbose level
if verbose == 2 and progress is None:
try:
progress = create_progress_bar(self._total_hits, 'Extract URLs', 'url')
except ProgressBarException:
verbose = 1
# Write results to csv
rows = self.extract_url_from_result(result, regex)
writer.writerows(rows)
# Update progress
count += len(rows)
if verbose == 2:
progress.update(count if count < self._total_hits else self._total_hits)
elif verbose == 1:
print "{:d}/{:d} ({:d}%)".format(count, self._total_hits, count * 100 / self._total_hits)
except ZeroDivisionError:
raise ElasticsearchException("Search doesn't return any result")
except KeyError:
raise ElasticsearchException("Invalid result")
def __iter__(self):
"""Iterate over each result.
"""
raise NotImplementedError | identifier_body | |
base.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from abc import ABCMeta
import csv
from performance_tools.exceptions import ProgressBarException, ElasticsearchException
from performance_tools.utils.progress_bar import create_progress_bar
class BaseURLFlowBackend(object):
"""Collect URL flow from backend. URL Flow: Referrer, Request, Time.
It's necessary to implement extract_url_from_result and __iter__ methods.
"""
__metaclass__ = ABCMeta
def __init__(self):
self._total_hits = 0
def | (self, result, regex=None):
"""Extract origin url and destination url for each entry in result and construct a list with them.
:param result: results obtained from backend in each iteration.
:type result: object
:param regex: Regular expression to normalize id's in URL.
:type regex: re
:return: List of origin urls and destination urls.
:rtype: list
"""
raise NotImplementedError
def to_csv(self, filename, regex=None, verbose=2):
"""Save results as a CSV file.
:param filename: CSV output file.
:type filename: str
:raise: ValueError if not found any result.
"""
progress = None
try:
with open(filename, 'w') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(['Referrer', 'Request', 'Time'])
count = 0
for result in self:
# Create progress bar or down verbose level
if verbose == 2 and progress is None:
try:
progress = create_progress_bar(self._total_hits, 'Extract URLs', 'url')
except ProgressBarException:
verbose = 1
# Write results to csv
rows = self.extract_url_from_result(result, regex)
writer.writerows(rows)
# Update progress
count += len(rows)
if verbose == 2:
progress.update(count if count < self._total_hits else self._total_hits)
elif verbose == 1:
print "{:d}/{:d} ({:d}%)".format(count, self._total_hits, count * 100 / self._total_hits)
except ZeroDivisionError:
raise ElasticsearchException("Search doesn't return any result")
except KeyError:
raise ElasticsearchException("Invalid result")
def __iter__(self):
"""Iterate over each result.
"""
raise NotImplementedError
| extract_url_from_result | identifier_name |
plot_morph_surface_stc.py | """
.. _ex-morph-surface:
=============================
Morph surface source estimate
=============================
This example demonstrates how to morph an individual subject's
:class:`mne.SourceEstimate` to a common reference space. We achieve this using
:class:`mne.SourceMorph`. Pre-computed data will be morphed based on | https://surfer.nmr.mgh.harvard.edu/fswiki/FsAverage).
The transformation will be applied to the surface source estimate. A plot
depicting the successful morph will be created for the spherical and inflated
surface representation of ``'fsaverage'``, overlaid with the morphed surface
source estimate.
References
----------
.. [1] Greve D. N., Van der Haegen L., Cai Q., Stufflebeam S., Sabuncu M.
R., Fischl B., Brysbaert M.
A Surface-based Analysis of Language Lateralization and Cortical
Asymmetry. Journal of Cognitive Neuroscience 25(9), 1477-1492, 2013.
.. note:: For background information about morphing see :ref:`ch_morph`.
"""
# Author: Tommy Clausner <tommy.clausner@gmail.com>
#
# License: BSD (3-clause)
import os
import mne
from mne.datasets import sample
print(__doc__)
###############################################################################
# Setup paths
sample_dir_raw = sample.data_path()
sample_dir = os.path.join(sample_dir_raw, 'MEG', 'sample')
subjects_dir = os.path.join(sample_dir_raw, 'subjects')
fname_stc = os.path.join(sample_dir, 'sample_audvis-meg')
###############################################################################
# Load example data
# Read stc from file
stc = mne.read_source_estimate(fname_stc, subject='sample')
###############################################################################
# Setting up SourceMorph for SourceEstimate
# -----------------------------------------
#
# In MNE surface source estimates represent the source space simply as
# lists of vertices (see
# :ref:`tut-source-estimate-class`).
# This list can either be obtained from
# :class:`mne.SourceSpaces` (src) or from the ``stc`` itself.
#
# Since the default ``spacing`` (resolution of surface mesh) is ``5`` and
# ``subject_to`` is set to 'fsaverage', :class:`mne.SourceMorph` will use
# default ico-5 ``fsaverage`` vertices to morph, which are the special
# values ``[np.arange(10242)] * 2``.
#
# .. note:: This is not generally true for other subjects! The set of vertices
# used for ``fsaverage`` with ico-5 spacing was designed to be
# special. ico-5 spacings for other subjects (or other spacings
# for fsaverage) must be calculated and will not be consecutive
# integers.
#
# If src was not defined, the morph will actually not be precomputed, because
# we lack the vertices *from* that we want to compute. Instead the morph will
# be set up and when applying it, the actual transformation will be computed on
# the fly.
#
# Initialize SourceMorph for SourceEstimate
morph = mne.compute_source_morph(stc, subject_from='sample',
subject_to='fsaverage',
subjects_dir=subjects_dir)
###############################################################################
# Apply morph to (Vector) SourceEstimate
# --------------------------------------
#
# The morph will be applied to the source estimate data, by giving it as the
# first argument to the morph we computed above.
stc_fsaverage = morph.apply(stc)
###############################################################################
# Plot results
# ------------
# Define plotting parameters
surfer_kwargs = dict(
hemi='lh', subjects_dir=subjects_dir,
clim=dict(kind='value', lims=[8, 12, 15]), views='lateral',
initial_time=0.09, time_unit='s', size=(800, 800),
smoothing_steps=5)
# As spherical surface
brain = stc_fsaverage.plot(surface='sphere', **surfer_kwargs)
# Add title
brain.add_text(0.1, 0.9, 'Morphed to fsaverage (spherical)', 'title',
font_size=16)
###############################################################################
# As inflated surface
brain_inf = stc_fsaverage.plot(surface='inflated', **surfer_kwargs)
# Add title
brain_inf.add_text(0.1, 0.9, 'Morphed to fsaverage (inflated)', 'title',
font_size=16)
###############################################################################
# Reading and writing SourceMorph from and to disk
# ------------------------------------------------
#
# An instance of SourceMorph can be saved, by calling
# :meth:`morph.save <mne.SourceMorph.save>`.
#
# This method allows for specification of a filename under which the ``morph``
# will be save in ".h5" format. If no file extension is provided, "-morph.h5"
# will be appended to the respective defined filename::
#
# >>> morph.save('my-file-name')
#
# Reading a saved source morph can be achieved by using
# :func:`mne.read_source_morph`::
#
# >>> morph = mne.read_source_morph('my-file-name-morph.h5')
#
# Once the environment is set up correctly, no information such as
# ``subject_from`` or ``subjects_dir`` must be provided, since it can be
# inferred from the data and use morph to 'fsaverage' by default. SourceMorph
# can further be used without creating an instance and assigning it to a
# variable. Instead :func:`mne.compute_source_morph` and
# :meth:`mne.SourceMorph.apply` can be
# easily chained into a handy one-liner. Taking this together the shortest
# possible way to morph data directly would be:
stc_fsaverage = mne.compute_source_morph(stc,
subjects_dir=subjects_dir).apply(stc) | a spherical representation of the cortex computed using the spherical
registration of :ref:`FreeSurfer <tut-freesurfer>`
(https://surfer.nmr.mgh.harvard.edu/fswiki/SurfaceRegAndTemplates) [1]_. This
transform will be used to morph the surface vertices of the subject towards the
reference vertices. Here we will use 'fsaverage' as a reference space (see | random_line_split |
ipc.rs | //! Alacritty socket IPC.
use std::ffi::OsStr;
use std::io::{BufRead, BufReader, Error as IoError, ErrorKind, Result as IoResult, Write};
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::PathBuf;
use std::{env, fs, process};
use glutin::event_loop::EventLoopProxy;
use log::warn;
use alacritty_terminal::thread;
use crate::cli::{Options, SocketMessage};
use crate::event::{Event, EventType};
/// Environment variable name for the IPC socket path.
const ALACRITTY_SOCKET_ENV: &str = "ALACRITTY_SOCKET";
/// Create an IPC socket.
pub fn spawn_ipc_socket(options: &Options, event_proxy: EventLoopProxy<Event>) -> Option<PathBuf> {
// Create the IPC socket and export its path as env variable if necessary.
let socket_path = options.socket.clone().unwrap_or_else(|| {
let mut path = socket_dir();
path.push(format!("{}-{}.sock", socket_prefix(), process::id()));
path
});
env::set_var(ALACRITTY_SOCKET_ENV, socket_path.as_os_str());
let listener = match UnixListener::bind(&socket_path) {
Ok(listener) => listener,
Err(err) => {
warn!("Unable to create socket: {:?}", err);
return None;
},
};
// Spawn a thread to listen on the IPC socket.
thread::spawn_named("socket listener", move || {
let mut data = String::new();
for stream in listener.incoming().filter_map(Result::ok) {
data.clear();
let mut stream = BufReader::new(stream);
match stream.read_line(&mut data) {
Ok(0) | Err(_) => continue,
Ok(_) => (),
};
// Read pending events on socket.
let message: SocketMessage = match serde_json::from_str(&data) {
Ok(message) => message,
Err(err) => {
warn!("Failed to convert data from socket: {}", err);
continue;
},
};
// Handle IPC events.
match message {
SocketMessage::CreateWindow(options) => {
let event = Event::new(EventType::CreateWindow(options), None);
let _ = event_proxy.send_event(event);
},
}
}
});
Some(socket_path)
}
/// Send a message to the active Alacritty socket.
pub fn send_message(socket: Option<PathBuf>, message: SocketMessage) -> IoResult<()> {
let mut socket = find_socket(socket)?;
let message = serde_json::to_string(&message)?;
socket.write_all(message[..].as_bytes())?;
let _ = socket.flush();
Ok(())
}
/// Directory for the IPC socket file.
#[cfg(not(target_os = "macos"))]
fn socket_dir() -> PathBuf {
xdg::BaseDirectories::with_prefix("alacritty")
.ok()
.and_then(|xdg| xdg.get_runtime_directory().map(ToOwned::to_owned).ok())
.and_then(|path| fs::create_dir_all(&path).map(|_| path).ok())
.unwrap_or_else(env::temp_dir)
}
/// Directory for the IPC socket file.
#[cfg(target_os = "macos")]
fn | () -> PathBuf {
env::temp_dir()
}
/// Find the IPC socket path.
fn find_socket(socket_path: Option<PathBuf>) -> IoResult<UnixStream> {
// Handle --socket CLI override.
if let Some(socket_path) = socket_path {
// Ensure we inform the user about an invalid path.
return UnixStream::connect(&socket_path).map_err(|err| {
let message = format!("invalid socket path {:?}", socket_path);
IoError::new(err.kind(), message)
});
}
// Handle environment variable.
if let Ok(path) = env::var(ALACRITTY_SOCKET_ENV) {
let socket_path = PathBuf::from(path);
if let Ok(socket) = UnixStream::connect(&socket_path) {
return Ok(socket);
}
}
// Search for sockets files.
for entry in fs::read_dir(socket_dir())?.filter_map(|entry| entry.ok()) {
let path = entry.path();
// Skip files that aren't Alacritty sockets.
let socket_prefix = socket_prefix();
if path
.file_name()
.and_then(OsStr::to_str)
.filter(|file| file.starts_with(&socket_prefix) && file.ends_with(".sock"))
.is_none()
{
continue;
}
// Attempt to connect to the socket.
match UnixStream::connect(&path) {
Ok(socket) => return Ok(socket),
// Delete orphan sockets.
Err(error) if error.kind() == ErrorKind::ConnectionRefused => {
let _ = fs::remove_file(&path);
},
// Ignore other errors like permission issues.
Err(_) => (),
}
}
Err(IoError::new(ErrorKind::NotFound, "no socket found"))
}
/// File prefix matching all available sockets.
///
/// This prefix will include display server information to allow for environments with multiple
/// display servers running for the same user.
#[cfg(not(target_os = "macos"))]
fn socket_prefix() -> String {
let display = env::var("WAYLAND_DISPLAY").or_else(|_| env::var("DISPLAY")).unwrap_or_default();
format!("Alacritty-{}", display)
}
/// File prefix matching all available sockets.
#[cfg(target_os = "macos")]
fn socket_prefix() -> String {
String::from("Alacritty")
}
| socket_dir | identifier_name |
ipc.rs | //! Alacritty socket IPC.
use std::ffi::OsStr;
use std::io::{BufRead, BufReader, Error as IoError, ErrorKind, Result as IoResult, Write};
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::PathBuf;
use std::{env, fs, process};
use glutin::event_loop::EventLoopProxy;
use log::warn;
use alacritty_terminal::thread;
use crate::cli::{Options, SocketMessage};
use crate::event::{Event, EventType};
/// Environment variable name for the IPC socket path.
const ALACRITTY_SOCKET_ENV: &str = "ALACRITTY_SOCKET";
/// Create an IPC socket.
pub fn spawn_ipc_socket(options: &Options, event_proxy: EventLoopProxy<Event>) -> Option<PathBuf> {
// Create the IPC socket and export its path as env variable if necessary.
let socket_path = options.socket.clone().unwrap_or_else(|| {
let mut path = socket_dir();
path.push(format!("{}-{}.sock", socket_prefix(), process::id()));
path
}); | warn!("Unable to create socket: {:?}", err);
return None;
},
};
// Spawn a thread to listen on the IPC socket.
thread::spawn_named("socket listener", move || {
let mut data = String::new();
for stream in listener.incoming().filter_map(Result::ok) {
data.clear();
let mut stream = BufReader::new(stream);
match stream.read_line(&mut data) {
Ok(0) | Err(_) => continue,
Ok(_) => (),
};
// Read pending events on socket.
let message: SocketMessage = match serde_json::from_str(&data) {
Ok(message) => message,
Err(err) => {
warn!("Failed to convert data from socket: {}", err);
continue;
},
};
// Handle IPC events.
match message {
SocketMessage::CreateWindow(options) => {
let event = Event::new(EventType::CreateWindow(options), None);
let _ = event_proxy.send_event(event);
},
}
}
});
Some(socket_path)
}
/// Send a message to the active Alacritty socket.
pub fn send_message(socket: Option<PathBuf>, message: SocketMessage) -> IoResult<()> {
let mut socket = find_socket(socket)?;
let message = serde_json::to_string(&message)?;
socket.write_all(message[..].as_bytes())?;
let _ = socket.flush();
Ok(())
}
/// Directory for the IPC socket file.
#[cfg(not(target_os = "macos"))]
fn socket_dir() -> PathBuf {
xdg::BaseDirectories::with_prefix("alacritty")
.ok()
.and_then(|xdg| xdg.get_runtime_directory().map(ToOwned::to_owned).ok())
.and_then(|path| fs::create_dir_all(&path).map(|_| path).ok())
.unwrap_or_else(env::temp_dir)
}
/// Directory for the IPC socket file.
#[cfg(target_os = "macos")]
fn socket_dir() -> PathBuf {
env::temp_dir()
}
/// Find the IPC socket path.
fn find_socket(socket_path: Option<PathBuf>) -> IoResult<UnixStream> {
// Handle --socket CLI override.
if let Some(socket_path) = socket_path {
// Ensure we inform the user about an invalid path.
return UnixStream::connect(&socket_path).map_err(|err| {
let message = format!("invalid socket path {:?}", socket_path);
IoError::new(err.kind(), message)
});
}
// Handle environment variable.
if let Ok(path) = env::var(ALACRITTY_SOCKET_ENV) {
let socket_path = PathBuf::from(path);
if let Ok(socket) = UnixStream::connect(&socket_path) {
return Ok(socket);
}
}
// Search for sockets files.
for entry in fs::read_dir(socket_dir())?.filter_map(|entry| entry.ok()) {
let path = entry.path();
// Skip files that aren't Alacritty sockets.
let socket_prefix = socket_prefix();
if path
.file_name()
.and_then(OsStr::to_str)
.filter(|file| file.starts_with(&socket_prefix) && file.ends_with(".sock"))
.is_none()
{
continue;
}
// Attempt to connect to the socket.
match UnixStream::connect(&path) {
Ok(socket) => return Ok(socket),
// Delete orphan sockets.
Err(error) if error.kind() == ErrorKind::ConnectionRefused => {
let _ = fs::remove_file(&path);
},
// Ignore other errors like permission issues.
Err(_) => (),
}
}
Err(IoError::new(ErrorKind::NotFound, "no socket found"))
}
/// File prefix matching all available sockets.
///
/// This prefix will include display server information to allow for environments with multiple
/// display servers running for the same user.
#[cfg(not(target_os = "macos"))]
fn socket_prefix() -> String {
let display = env::var("WAYLAND_DISPLAY").or_else(|_| env::var("DISPLAY")).unwrap_or_default();
format!("Alacritty-{}", display)
}
/// File prefix matching all available sockets.
#[cfg(target_os = "macos")]
fn socket_prefix() -> String {
String::from("Alacritty")
} | env::set_var(ALACRITTY_SOCKET_ENV, socket_path.as_os_str());
let listener = match UnixListener::bind(&socket_path) {
Ok(listener) => listener,
Err(err) => { | random_line_split |
ipc.rs | //! Alacritty socket IPC.
use std::ffi::OsStr;
use std::io::{BufRead, BufReader, Error as IoError, ErrorKind, Result as IoResult, Write};
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::PathBuf;
use std::{env, fs, process};
use glutin::event_loop::EventLoopProxy;
use log::warn;
use alacritty_terminal::thread;
use crate::cli::{Options, SocketMessage};
use crate::event::{Event, EventType};
/// Environment variable name for the IPC socket path.
const ALACRITTY_SOCKET_ENV: &str = "ALACRITTY_SOCKET";
/// Create an IPC socket.
pub fn spawn_ipc_socket(options: &Options, event_proxy: EventLoopProxy<Event>) -> Option<PathBuf> {
// Create the IPC socket and export its path as env variable if necessary.
let socket_path = options.socket.clone().unwrap_or_else(|| {
let mut path = socket_dir();
path.push(format!("{}-{}.sock", socket_prefix(), process::id()));
path
});
env::set_var(ALACRITTY_SOCKET_ENV, socket_path.as_os_str());
let listener = match UnixListener::bind(&socket_path) {
Ok(listener) => listener,
Err(err) => {
warn!("Unable to create socket: {:?}", err);
return None;
},
};
// Spawn a thread to listen on the IPC socket.
thread::spawn_named("socket listener", move || {
let mut data = String::new();
for stream in listener.incoming().filter_map(Result::ok) {
data.clear();
let mut stream = BufReader::new(stream);
match stream.read_line(&mut data) {
Ok(0) | Err(_) => continue,
Ok(_) => (),
};
// Read pending events on socket.
let message: SocketMessage = match serde_json::from_str(&data) {
Ok(message) => message,
Err(err) => {
warn!("Failed to convert data from socket: {}", err);
continue;
},
};
// Handle IPC events.
match message {
SocketMessage::CreateWindow(options) => {
let event = Event::new(EventType::CreateWindow(options), None);
let _ = event_proxy.send_event(event);
},
}
}
});
Some(socket_path)
}
/// Send a message to the active Alacritty socket.
pub fn send_message(socket: Option<PathBuf>, message: SocketMessage) -> IoResult<()> {
let mut socket = find_socket(socket)?;
let message = serde_json::to_string(&message)?;
socket.write_all(message[..].as_bytes())?;
let _ = socket.flush();
Ok(())
}
/// Directory for the IPC socket file.
#[cfg(not(target_os = "macos"))]
fn socket_dir() -> PathBuf {
xdg::BaseDirectories::with_prefix("alacritty")
.ok()
.and_then(|xdg| xdg.get_runtime_directory().map(ToOwned::to_owned).ok())
.and_then(|path| fs::create_dir_all(&path).map(|_| path).ok())
.unwrap_or_else(env::temp_dir)
}
/// Directory for the IPC socket file.
#[cfg(target_os = "macos")]
fn socket_dir() -> PathBuf {
env::temp_dir()
}
/// Find the IPC socket path.
fn find_socket(socket_path: Option<PathBuf>) -> IoResult<UnixStream> {
// Handle --socket CLI override.
if let Some(socket_path) = socket_path {
// Ensure we inform the user about an invalid path.
return UnixStream::connect(&socket_path).map_err(|err| {
let message = format!("invalid socket path {:?}", socket_path);
IoError::new(err.kind(), message)
});
}
// Handle environment variable.
if let Ok(path) = env::var(ALACRITTY_SOCKET_ENV) {
let socket_path = PathBuf::from(path);
if let Ok(socket) = UnixStream::connect(&socket_path) {
return Ok(socket);
}
}
// Search for sockets files.
for entry in fs::read_dir(socket_dir())?.filter_map(|entry| entry.ok()) {
let path = entry.path();
// Skip files that aren't Alacritty sockets.
let socket_prefix = socket_prefix();
if path
.file_name()
.and_then(OsStr::to_str)
.filter(|file| file.starts_with(&socket_prefix) && file.ends_with(".sock"))
.is_none()
{
continue;
}
// Attempt to connect to the socket.
match UnixStream::connect(&path) {
Ok(socket) => return Ok(socket),
// Delete orphan sockets.
Err(error) if error.kind() == ErrorKind::ConnectionRefused => {
let _ = fs::remove_file(&path);
},
// Ignore other errors like permission issues.
Err(_) => (),
}
}
Err(IoError::new(ErrorKind::NotFound, "no socket found"))
}
/// File prefix matching all available sockets.
///
/// This prefix will include display server information to allow for environments with multiple
/// display servers running for the same user.
#[cfg(not(target_os = "macos"))]
fn socket_prefix() -> String |
/// File prefix matching all available sockets.
#[cfg(target_os = "macos")]
fn socket_prefix() -> String {
String::from("Alacritty")
}
| {
let display = env::var("WAYLAND_DISPLAY").or_else(|_| env::var("DISPLAY")).unwrap_or_default();
format!("Alacritty-{}", display)
} | identifier_body |
mmerge-sort-for-linked-list.py | # key point is to find the half node
class Node:
def __init__(self, val):
self.val = val
self.next = None
class LinkList:
def __init__(self):
self.head = None
def push(self, val):
node = Node(val)
if self.head:
node.next = self.head
self.head = node
else:
self.head = node
def printList(self):
p = self.head
while p:
print p.val,
p = p.next
print
def mergeSort(head):
if not head:
return
if not head.next:
return
slow = head
fast = head.next
while fast:
|
# 2 3 20 5 10 15
frontHalf = head
backHalf = slow.next
slow.next = None
mergeSort(frontHalf)
mergeSort(backHalf)
head = sortedMerge(frontHalf, backHalf)
return head
def sortedMerge(a, b):
if not a:
return b
elif not b:
return a
temp = None
if a.val <= b.val:
temp = a
a.next = sortedMerge(temp.next, b)
return a
else:
temp = b
b.next = sortedMerge(a, temp.next)
return b
ll = LinkList()
ll.push(15)
ll.push(10)
ll.push(5)
ll.push(20)
ll.push(3)
ll.push(2)
ll.printList()
ll.head = mergeSort(ll.head)
ll.printList()
| fast = fast.next
if fast:
slow = slow.next
fast = fast.next | conditional_block |
mmerge-sort-for-linked-list.py | # key point is to find the half node
class Node:
def __init__(self, val):
self.val = val
self.next = None
class LinkList:
def __init__(self):
self.head = None
def push(self, val):
node = Node(val)
if self.head:
node.next = self.head
self.head = node
else:
self.head = node
def printList(self):
p = self.head
while p:
print p.val,
p = p.next
print
def mergeSort(head):
|
def sortedMerge(a, b):
if not a:
return b
elif not b:
return a
temp = None
if a.val <= b.val:
temp = a
a.next = sortedMerge(temp.next, b)
return a
else:
temp = b
b.next = sortedMerge(a, temp.next)
return b
ll = LinkList()
ll.push(15)
ll.push(10)
ll.push(5)
ll.push(20)
ll.push(3)
ll.push(2)
ll.printList()
ll.head = mergeSort(ll.head)
ll.printList()
| if not head:
return
if not head.next:
return
slow = head
fast = head.next
while fast:
fast = fast.next
if fast:
slow = slow.next
fast = fast.next
# 2 3 20 5 10 15
frontHalf = head
backHalf = slow.next
slow.next = None
mergeSort(frontHalf)
mergeSort(backHalf)
head = sortedMerge(frontHalf, backHalf)
return head | identifier_body |
mmerge-sort-for-linked-list.py | # key point is to find the half node
class Node:
def __init__(self, val):
self.val = val
self.next = None
class LinkList:
def __init__(self):
self.head = None
def push(self, val):
node = Node(val)
if self.head:
node.next = self.head
self.head = node
else:
self.head = node
def printList(self):
p = self.head
while p:
print p.val,
p = p.next
print
def mergeSort(head):
if not head:
return
if not head.next:
return
slow = head
fast = head.next
while fast:
fast = fast.next
if fast:
slow = slow.next
fast = fast.next
# 2 3 20 5 10 15
frontHalf = head
backHalf = slow.next
slow.next = None
mergeSort(frontHalf)
mergeSort(backHalf)
head = sortedMerge(frontHalf, backHalf)
return head
def sortedMerge(a, b):
if not a:
return b | elif not b:
return a
temp = None
if a.val <= b.val:
temp = a
a.next = sortedMerge(temp.next, b)
return a
else:
temp = b
b.next = sortedMerge(a, temp.next)
return b
ll = LinkList()
ll.push(15)
ll.push(10)
ll.push(5)
ll.push(20)
ll.push(3)
ll.push(2)
ll.printList()
ll.head = mergeSort(ll.head)
ll.printList() | random_line_split | |
mmerge-sort-for-linked-list.py | # key point is to find the half node
class Node:
def | (self, val):
self.val = val
self.next = None
class LinkList:
def __init__(self):
self.head = None
def push(self, val):
node = Node(val)
if self.head:
node.next = self.head
self.head = node
else:
self.head = node
def printList(self):
p = self.head
while p:
print p.val,
p = p.next
print
def mergeSort(head):
if not head:
return
if not head.next:
return
slow = head
fast = head.next
while fast:
fast = fast.next
if fast:
slow = slow.next
fast = fast.next
# 2 3 20 5 10 15
frontHalf = head
backHalf = slow.next
slow.next = None
mergeSort(frontHalf)
mergeSort(backHalf)
head = sortedMerge(frontHalf, backHalf)
return head
def sortedMerge(a, b):
if not a:
return b
elif not b:
return a
temp = None
if a.val <= b.val:
temp = a
a.next = sortedMerge(temp.next, b)
return a
else:
temp = b
b.next = sortedMerge(a, temp.next)
return b
ll = LinkList()
ll.push(15)
ll.push(10)
ll.push(5)
ll.push(20)
ll.push(3)
ll.push(2)
ll.printList()
ll.head = mergeSort(ll.head)
ll.printList()
| __init__ | identifier_name |
oracle_operator.py | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from airflow.hooks.oracle_hook import OracleHook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
class OracleOperator(BaseOperator):
"""
Executes sql code in a specific Oracle database
:param oracle_conn_id: reference to a specific Oracle database
:type oracle_conn_id: str
:param sql: the sql code to be executed. (templated)
:type sql: Can receive a str representing a sql statement,
a list of str (sql statements), or reference to a template file.
Template reference are recognized by str ending in '.sql'
"""
template_fields = ('sql',)
template_ext = ('.sql',)
ui_color = '#ededed'
@apply_defaults
def __init__(
self, sql, oracle_conn_id='oracle_default', parameters=None,
autocommit=False, *args, **kwargs):
super(OracleOperator, self).__init__(*args, **kwargs)
self.oracle_conn_id = oracle_conn_id
self.sql = sql
self.autocommit = autocommit
self.parameters = parameters
def | (self, context):
self.log.info('Executing: %s', self.sql)
hook = OracleHook(oracle_conn_id=self.oracle_conn_id)
hook.run(
self.sql,
autocommit=self.autocommit,
parameters=self.parameters)
| execute | identifier_name |
oracle_operator.py | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from airflow.hooks.oracle_hook import OracleHook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
class OracleOperator(BaseOperator):
"""
Executes sql code in a specific Oracle database
:param oracle_conn_id: reference to a specific Oracle database
:type oracle_conn_id: str
:param sql: the sql code to be executed. (templated)
:type sql: Can receive a str representing a sql statement,
a list of str (sql statements), or reference to a template file.
Template reference are recognized by str ending in '.sql'
"""
template_fields = ('sql',)
template_ext = ('.sql',)
ui_color = '#ededed'
@apply_defaults
def __init__(
self, sql, oracle_conn_id='oracle_default', parameters=None,
autocommit=False, *args, **kwargs):
|
def execute(self, context):
self.log.info('Executing: %s', self.sql)
hook = OracleHook(oracle_conn_id=self.oracle_conn_id)
hook.run(
self.sql,
autocommit=self.autocommit,
parameters=self.parameters)
| super(OracleOperator, self).__init__(*args, **kwargs)
self.oracle_conn_id = oracle_conn_id
self.sql = sql
self.autocommit = autocommit
self.parameters = parameters | identifier_body |
oracle_operator.py | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from airflow.hooks.oracle_hook import OracleHook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
class OracleOperator(BaseOperator):
"""
Executes sql code in a specific Oracle database
:param oracle_conn_id: reference to a specific Oracle database
:type oracle_conn_id: str
:param sql: the sql code to be executed. (templated)
:type sql: Can receive a str representing a sql statement,
a list of str (sql statements), or reference to a template file.
Template reference are recognized by str ending in '.sql'
"""
template_fields = ('sql',)
template_ext = ('.sql',)
ui_color = '#ededed'
@apply_defaults
def __init__(
self, sql, oracle_conn_id='oracle_default', parameters=None,
autocommit=False, *args, **kwargs):
super(OracleOperator, self).__init__(*args, **kwargs)
self.oracle_conn_id = oracle_conn_id
self.sql = sql
self.autocommit = autocommit
self.parameters = parameters
def execute(self, context):
self.log.info('Executing: %s', self.sql)
hook = OracleHook(oracle_conn_id=self.oracle_conn_id)
hook.run(
self.sql,
autocommit=self.autocommit,
parameters=self.parameters) | #
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an | random_line_split |
model.rs | use chrono::*;
pub use location::GpsCoordinates;
use irradiance;
pub struct | <Tz: TimeZone> {
pub coords: GpsCoordinates,
pub date_time: DateTime<Tz>,
}
pub struct ModelOutput {
pub day_of_year: u32,
pub eot: f64,
pub local_meridian_long: f64,
pub time_correction_factor: f64,
pub solar_time: f64,
pub hour_angle: f64,
pub declination_angle: f64,
pub elevation_angle: f64,
pub zenith_angle: f64,
pub air_mass: f64,
pub irradiance: f64,
}
/// Irradiance, en watts par mètre carré.
pub fn run<Tz: TimeZone>(params: ModelParams<Tz>) -> ModelOutput {
let ModelParams {
coords,
date_time
} = params;
let gmt_offset = date_time.offset().local_minus_utc();
let day_of_year = date_time.ordinal();
let eot = irradiance::equation_of_time(day_of_year);
let local_meridian_long =
irradiance::local_standard_meridian_longitude(gmt_offset.num_hours() as f64);
let time_correction_factor =
irradiance::time_correction_factor(coords.long,
local_meridian_long,
eot);
let solar_time = irradiance::solar_time(date_time.hour() as f64,
time_correction_factor);
let hour_angle = irradiance::hour_angle(solar_time);
let declination_angle = irradiance::declination_angle(day_of_year);
let elevation_angle = irradiance::elevation_angle(declination_angle,
coords.lat,
hour_angle);
let zenith_angle = irradiance::zenith_angle(elevation_angle);
let air_mass = irradiance::air_mass(zenith_angle);
let irradiance = irradiance::irradiance(air_mass);
ModelOutput {
day_of_year: day_of_year,
eot: eot,
local_meridian_long: local_meridian_long,
time_correction_factor: time_correction_factor,
solar_time: solar_time,
hour_angle: hour_angle,
declination_angle: declination_angle,
elevation_angle: elevation_angle,
zenith_angle: zenith_angle,
air_mass: air_mass,
irradiance: irradiance,
}
}
| ModelParams | identifier_name |
model.rs | use chrono::*;
pub use location::GpsCoordinates;
use irradiance;
pub struct ModelParams<Tz: TimeZone> {
pub coords: GpsCoordinates,
pub date_time: DateTime<Tz>,
}
pub struct ModelOutput {
pub day_of_year: u32,
pub eot: f64,
pub local_meridian_long: f64,
pub time_correction_factor: f64,
pub solar_time: f64,
pub hour_angle: f64,
pub declination_angle: f64,
pub elevation_angle: f64,
pub zenith_angle: f64,
pub air_mass: f64,
pub irradiance: f64,
}
/// Irradiance, en watts par mètre carré.
pub fn run<Tz: TimeZone>(params: ModelParams<Tz>) -> ModelOutput {
| let ModelParams {
coords,
date_time
} = params;
let gmt_offset = date_time.offset().local_minus_utc();
let day_of_year = date_time.ordinal();
let eot = irradiance::equation_of_time(day_of_year);
let local_meridian_long =
irradiance::local_standard_meridian_longitude(gmt_offset.num_hours() as f64);
let time_correction_factor =
irradiance::time_correction_factor(coords.long,
local_meridian_long,
eot);
let solar_time = irradiance::solar_time(date_time.hour() as f64,
time_correction_factor);
let hour_angle = irradiance::hour_angle(solar_time);
let declination_angle = irradiance::declination_angle(day_of_year);
let elevation_angle = irradiance::elevation_angle(declination_angle,
coords.lat,
hour_angle);
let zenith_angle = irradiance::zenith_angle(elevation_angle);
let air_mass = irradiance::air_mass(zenith_angle);
let irradiance = irradiance::irradiance(air_mass);
ModelOutput {
day_of_year: day_of_year,
eot: eot,
local_meridian_long: local_meridian_long,
time_correction_factor: time_correction_factor,
solar_time: solar_time,
hour_angle: hour_angle,
declination_angle: declination_angle,
elevation_angle: elevation_angle,
zenith_angle: zenith_angle,
air_mass: air_mass,
irradiance: irradiance,
}
}
| identifier_body | |
model.rs | use chrono::*;
pub use location::GpsCoordinates;
use irradiance;
pub struct ModelParams<Tz: TimeZone> {
pub coords: GpsCoordinates,
pub date_time: DateTime<Tz>,
}
pub struct ModelOutput {
pub day_of_year: u32,
pub eot: f64,
pub local_meridian_long: f64,
pub time_correction_factor: f64,
pub solar_time: f64,
pub hour_angle: f64,
pub declination_angle: f64,
pub elevation_angle: f64,
pub zenith_angle: f64,
pub air_mass: f64,
pub irradiance: f64,
}
/// Irradiance, en watts par mètre carré.
pub fn run<Tz: TimeZone>(params: ModelParams<Tz>) -> ModelOutput {
let ModelParams {
coords,
date_time
} = params;
let gmt_offset = date_time.offset().local_minus_utc();
let day_of_year = date_time.ordinal();
let eot = irradiance::equation_of_time(day_of_year);
let local_meridian_long =
irradiance::local_standard_meridian_longitude(gmt_offset.num_hours() as f64);
let time_correction_factor =
irradiance::time_correction_factor(coords.long,
local_meridian_long,
eot);
let solar_time = irradiance::solar_time(date_time.hour() as f64,
time_correction_factor);
let hour_angle = irradiance::hour_angle(solar_time);
let declination_angle = irradiance::declination_angle(day_of_year);
let elevation_angle = irradiance::elevation_angle(declination_angle,
coords.lat,
hour_angle);
let zenith_angle = irradiance::zenith_angle(elevation_angle);
let air_mass = irradiance::air_mass(zenith_angle);
let irradiance = irradiance::irradiance(air_mass);
ModelOutput {
day_of_year: day_of_year,
eot: eot,
local_meridian_long: local_meridian_long,
time_correction_factor: time_correction_factor, | zenith_angle: zenith_angle,
air_mass: air_mass,
irradiance: irradiance,
}
} | solar_time: solar_time,
hour_angle: hour_angle,
declination_angle: declination_angle,
elevation_angle: elevation_angle, | random_line_split |
markers.py | from numpy.random import random
from bokeh.plotting import figure, show, output_file
def mscatter(p, x, y, marker):
p.scatter(x, y, marker=marker, size=15,
line_color="navy", fill_color="orange", alpha=0.5)
def | (p, x, y, text):
p.text(x, y, text=[text],
text_color="firebrick", text_align="center", text_font_size="10pt")
p = figure(title="Bokeh Markers", toolbar_location=None)
p.grid.grid_line_color = None
p.background_fill_color = "#eeeeee"
N = 10
mscatter(p, random(N)+2, random(N)+1, "circle")
mscatter(p, random(N)+4, random(N)+1, "square")
mscatter(p, random(N)+6, random(N)+1, "triangle")
mscatter(p, random(N)+8, random(N)+1, "asterisk")
mscatter(p, random(N)+2, random(N)+4, "circle_x")
mscatter(p, random(N)+4, random(N)+4, "square_x")
mscatter(p, random(N)+6, random(N)+4, "inverted_triangle")
mscatter(p, random(N)+8, random(N)+4, "x")
mscatter(p, random(N)+2, random(N)+7, "circle_cross")
mscatter(p, random(N)+4, random(N)+7, "square_cross")
mscatter(p, random(N)+6, random(N)+7, "diamond")
mscatter(p, random(N)+8, random(N)+7, "cross")
mtext(p, 2.5, 0.5, "circle / o")
mtext(p, 4.5, 0.5, "square")
mtext(p, 6.5, 0.5, "triangle")
mtext(p, 8.5, 0.5, "asterisk / *")
mtext(p, 2.5, 3.5, "circle_x / ox")
mtext(p, 4.5, 3.5, "square_x")
mtext(p, 6.5, 3.5, "inverted_triangle")
mtext(p, 8.5, 3.5, "x")
mtext(p, 2.5, 6.5, "circle_cross / o+")
mtext(p, 4.5, 6.5, "square_cross")
mtext(p, 6.5, 6.5, "diamond")
mtext(p, 8.5, 6.5, "cross / +")
output_file("markers.html", title="markers.py example")
show(p) # open a browser
| mtext | identifier_name |
markers.py | from numpy.random import random
from bokeh.plotting import figure, show, output_file
def mscatter(p, x, y, marker):
p.scatter(x, y, marker=marker, size=15,
line_color="navy", fill_color="orange", alpha=0.5)
def mtext(p, x, y, text):
p.text(x, y, text=[text],
text_color="firebrick", text_align="center", text_font_size="10pt")
p = figure(title="Bokeh Markers", toolbar_location=None)
p.grid.grid_line_color = None
p.background_fill_color = "#eeeeee"
N = 10
mscatter(p, random(N)+2, random(N)+1, "circle")
mscatter(p, random(N)+4, random(N)+1, "square")
mscatter(p, random(N)+6, random(N)+1, "triangle")
mscatter(p, random(N)+8, random(N)+1, "asterisk")
mscatter(p, random(N)+2, random(N)+4, "circle_x")
mscatter(p, random(N)+4, random(N)+4, "square_x")
mscatter(p, random(N)+6, random(N)+4, "inverted_triangle")
mscatter(p, random(N)+8, random(N)+4, "x")
mscatter(p, random(N)+2, random(N)+7, "circle_cross")
mscatter(p, random(N)+4, random(N)+7, "square_cross")
mscatter(p, random(N)+6, random(N)+7, "diamond")
mscatter(p, random(N)+8, random(N)+7, "cross")
mtext(p, 2.5, 0.5, "circle / o")
mtext(p, 4.5, 0.5, "square")
mtext(p, 6.5, 0.5, "triangle")
mtext(p, 8.5, 0.5, "asterisk / *")
mtext(p, 2.5, 3.5, "circle_x / ox")
mtext(p, 4.5, 3.5, "square_x")
mtext(p, 6.5, 3.5, "inverted_triangle")
mtext(p, 8.5, 3.5, "x")
mtext(p, 2.5, 6.5, "circle_cross / o+")
mtext(p, 4.5, 6.5, "square_cross")
mtext(p, 6.5, 6.5, "diamond")
mtext(p, 8.5, 6.5, "cross / +")
| output_file("markers.html", title="markers.py example")
show(p) # open a browser | random_line_split | |
markers.py | from numpy.random import random
from bokeh.plotting import figure, show, output_file
def mscatter(p, x, y, marker):
|
def mtext(p, x, y, text):
p.text(x, y, text=[text],
text_color="firebrick", text_align="center", text_font_size="10pt")
p = figure(title="Bokeh Markers", toolbar_location=None)
p.grid.grid_line_color = None
p.background_fill_color = "#eeeeee"
N = 10
mscatter(p, random(N)+2, random(N)+1, "circle")
mscatter(p, random(N)+4, random(N)+1, "square")
mscatter(p, random(N)+6, random(N)+1, "triangle")
mscatter(p, random(N)+8, random(N)+1, "asterisk")
mscatter(p, random(N)+2, random(N)+4, "circle_x")
mscatter(p, random(N)+4, random(N)+4, "square_x")
mscatter(p, random(N)+6, random(N)+4, "inverted_triangle")
mscatter(p, random(N)+8, random(N)+4, "x")
mscatter(p, random(N)+2, random(N)+7, "circle_cross")
mscatter(p, random(N)+4, random(N)+7, "square_cross")
mscatter(p, random(N)+6, random(N)+7, "diamond")
mscatter(p, random(N)+8, random(N)+7, "cross")
mtext(p, 2.5, 0.5, "circle / o")
mtext(p, 4.5, 0.5, "square")
mtext(p, 6.5, 0.5, "triangle")
mtext(p, 8.5, 0.5, "asterisk / *")
mtext(p, 2.5, 3.5, "circle_x / ox")
mtext(p, 4.5, 3.5, "square_x")
mtext(p, 6.5, 3.5, "inverted_triangle")
mtext(p, 8.5, 3.5, "x")
mtext(p, 2.5, 6.5, "circle_cross / o+")
mtext(p, 4.5, 6.5, "square_cross")
mtext(p, 6.5, 6.5, "diamond")
mtext(p, 8.5, 6.5, "cross / +")
output_file("markers.html", title="markers.py example")
show(p) # open a browser
| p.scatter(x, y, marker=marker, size=15,
line_color="navy", fill_color="orange", alpha=0.5) | identifier_body |
base.py | # -*- encoding: utf-8 -*-
# Copyright (c) 2015 b<>com
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Implementation of Inspector abstraction for libvirt."""
from __future__ import unicode_literals
from lxml import etree
from oslo_log import log
from oslo_utils import units
import six
from watcher_metering_drivers.wrappers.virt import inspector as virt_inspector
from watcher_metering_drivers.wrappers.virt import util
libvirt = None
LOG = log.getLogger(__name__)
def retry_on_disconnect(function):
def decorator(self, *args, **kwargs):
try:
return function(self, *args, **kwargs)
except libvirt.libvirtError as e:
if (e.get_error_code() == libvirt.VIR_ERR_SYSTEM_ERROR and
e.get_error_domain() in (libvirt.VIR_FROM_REMOTE,
libvirt.VIR_FROM_RPC)):
LOG.debug(('Connection to libvirt broken'))
self.connection = None
return function(self, *args, **kwargs)
else:
raise
return decorator
class LibvirtInspector(virt_inspector.Inspector):
per_type_uris = dict(uml='uml:///system', xen='xen:///', lxc='lxc:///')
def __init__(self, libvirt_type, libvirt_uri):
self.libvirt_type = libvirt_type
self.libvirt_uri = libvirt_uri
self.uri = self._get_uri()
self.connection = None
def _get_uri(self):
return self.libvirt_uri or self.per_type_uris.get(self.libvirt_type,
'qemu:///system')
def _get_connection(self):
if not self.connection:
global libvirt
if libvirt is None:
libvirt = __import__('libvirt')
LOG.debug(('Connecting to libvirt: %s'), self.uri)
self.connection = libvirt.openReadOnly(self.uri)
return self.connection
@retry_on_disconnect
def _lookup_by_uuid(self, instance):
instance_name = util.instance_name(instance)
try:
return self._get_connection().lookupByUUIDString(instance.id)
except Exception as ex:
if not libvirt or not isinstance(ex, libvirt.libvirtError):
raise virt_inspector.InspectorException(six.text_type(ex))
error_code = ex.get_error_code()
if (error_code == libvirt.VIR_ERR_SYSTEM_ERROR and
ex.get_error_domain() in (libvirt.VIR_FROM_REMOTE,
libvirt.VIR_FROM_RPC)):
raise
msg = _("Error from libvirt while looking up instance "
"<name=%(name)s, id=%(id)s>: "
"[Error Code %(error_code)s] "
"%(ex)s") % {'name': instance_name,
'id': instance.id,
'error_code': error_code,
'ex': ex}
raise virt_inspector.InstanceNotFoundException(msg)
def inspect_cpus(self, instance):
domain = self._lookup_by_uuid(instance)
dom_info = domain.info()
return virt_inspector.CPUStats(number=dom_info[3], time=dom_info[4])
def _get_domain_not_shut_off_or_raise(self, instance):
instance_name = util.instance_name(instance)
domain = self._lookup_by_uuid(instance)
state = domain.info()[0]
if state == libvirt.VIR_DOMAIN_SHUTOFF:
msg = ('Failed to inspect data of instance '
'<name=%(name)s, id=%(id)s>, '
'domain state is SHUTOFF.') % {
'name': instance_name, 'id': instance.id}
raise virt_inspector.InstanceShutOffException(msg)
return domain
def inspect_vnics(self, instance):
domain = self._get_domain_not_shut_off_or_raise(instance)
tree = etree.fromstring(domain.XMLDesc(0))
for iface in tree.findall('devices/interface'):
target = iface.find('target')
if target is not None:
|
else:
continue
mac = iface.find('mac')
if mac is not None:
mac_address = mac.get('address')
else:
continue
fref = iface.find('filterref')
if fref is not None:
fref = fref.get('filter')
params = dict((p.get('name').lower(), p.get('value'))
for p in iface.findall('filterref/parameter'))
interface = virt_inspector.Interface(name=name, mac=mac_address,
fref=fref, parameters=params)
dom_stats = domain.interfaceStats(name)
stats = virt_inspector.InterfaceStats(rx_bytes=dom_stats[0],
rx_packets=dom_stats[1],
tx_bytes=dom_stats[4],
tx_packets=dom_stats[5])
yield (interface, stats)
def inspect_disks(self, instance):
domain = self._get_domain_not_shut_off_or_raise(instance)
tree = etree.fromstring(domain.XMLDesc(0))
for device in filter(
bool,
[target.get("dev")
for target in tree.findall('devices/disk/target')]):
disk = virt_inspector.Disk(device=device)
block_stats = domain.blockStats(device)
stats = virt_inspector.DiskStats(read_requests=block_stats[0],
read_bytes=block_stats[1],
write_requests=block_stats[2],
write_bytes=block_stats[3],
errors=block_stats[4])
yield (disk, stats)
def inspect_memory_usage(self, instance, duration=None):
instance_name = util.instance_name(instance)
domain = self._get_domain_not_shut_off_or_raise(instance)
try:
memory_stats = domain.memoryStats()
if (memory_stats and
memory_stats.get('available') and
memory_stats.get('unused')):
memory_used = (memory_stats.get('available') -
memory_stats.get('unused'))
# Stat provided from libvirt is in KB, converting it to MB.
memory_used = memory_used / units.Ki
return virt_inspector.MemoryUsageStats(usage=memory_used)
else:
msg = ('Failed to inspect memory usage of instance '
'<name=%(name)s, id=%(id)s>, '
'can not get info from libvirt.') % {
'name': instance_name, 'id': instance.id}
raise virt_inspector.NoDataException(msg)
# memoryStats might launch an exception if the method is not supported
# by the underlying hypervisor being used by libvirt.
except libvirt.libvirtError as e:
msg = ('Failed to inspect memory usage of %(instance_uuid)s, '
'can not get info from libvirt: %(error)s') % {
'instance_uuid': instance.id, 'error': e}
raise virt_inspector.NoDataException(msg)
def inspect_disk_info(self, instance):
domain = self._get_domain_not_shut_off_or_raise(instance)
tree = etree.fromstring(domain.XMLDesc(0))
for device in filter(
bool,
[target.get("dev")
for target in tree.findall('devices/disk/target')]):
disk = virt_inspector.Disk(device=device)
block_info = domain.blockInfo(device)
info = virt_inspector.DiskInfo(capacity=block_info[0],
allocation=block_info[1],
physical=block_info[2])
yield (disk, info)
def inspect_memory_resident(self, instance, duration=None):
domain = self._get_domain_not_shut_off_or_raise(instance)
memory = domain.memoryStats()['rss'] / units.Ki
return virt_inspector.MemoryResidentStats(resident=memory)
| name = target.get('dev') | conditional_block |
base.py | # -*- encoding: utf-8 -*-
# Copyright (c) 2015 b<>com
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Implementation of Inspector abstraction for libvirt."""
from __future__ import unicode_literals
from lxml import etree
from oslo_log import log
from oslo_utils import units
import six
from watcher_metering_drivers.wrappers.virt import inspector as virt_inspector
from watcher_metering_drivers.wrappers.virt import util
libvirt = None
LOG = log.getLogger(__name__)
def retry_on_disconnect(function):
def decorator(self, *args, **kwargs):
try:
return function(self, *args, **kwargs)
except libvirt.libvirtError as e:
if (e.get_error_code() == libvirt.VIR_ERR_SYSTEM_ERROR and
e.get_error_domain() in (libvirt.VIR_FROM_REMOTE,
libvirt.VIR_FROM_RPC)):
LOG.debug(('Connection to libvirt broken'))
self.connection = None
return function(self, *args, **kwargs)
else:
raise
return decorator
class LibvirtInspector(virt_inspector.Inspector):
per_type_uris = dict(uml='uml:///system', xen='xen:///', lxc='lxc:///')
def __init__(self, libvirt_type, libvirt_uri):
self.libvirt_type = libvirt_type
self.libvirt_uri = libvirt_uri
self.uri = self._get_uri()
self.connection = None
def _get_uri(self):
return self.libvirt_uri or self.per_type_uris.get(self.libvirt_type,
'qemu:///system')
def _get_connection(self):
if not self.connection:
global libvirt
if libvirt is None:
libvirt = __import__('libvirt')
LOG.debug(('Connecting to libvirt: %s'), self.uri)
self.connection = libvirt.openReadOnly(self.uri)
return self.connection
@retry_on_disconnect
def _lookup_by_uuid(self, instance):
instance_name = util.instance_name(instance)
try:
return self._get_connection().lookupByUUIDString(instance.id)
except Exception as ex:
if not libvirt or not isinstance(ex, libvirt.libvirtError):
raise virt_inspector.InspectorException(six.text_type(ex))
error_code = ex.get_error_code()
if (error_code == libvirt.VIR_ERR_SYSTEM_ERROR and
ex.get_error_domain() in (libvirt.VIR_FROM_REMOTE,
libvirt.VIR_FROM_RPC)):
raise
msg = _("Error from libvirt while looking up instance "
"<name=%(name)s, id=%(id)s>: "
"[Error Code %(error_code)s] "
"%(ex)s") % {'name': instance_name,
'id': instance.id,
'error_code': error_code,
'ex': ex}
raise virt_inspector.InstanceNotFoundException(msg)
def | (self, instance):
domain = self._lookup_by_uuid(instance)
dom_info = domain.info()
return virt_inspector.CPUStats(number=dom_info[3], time=dom_info[4])
def _get_domain_not_shut_off_or_raise(self, instance):
instance_name = util.instance_name(instance)
domain = self._lookup_by_uuid(instance)
state = domain.info()[0]
if state == libvirt.VIR_DOMAIN_SHUTOFF:
msg = ('Failed to inspect data of instance '
'<name=%(name)s, id=%(id)s>, '
'domain state is SHUTOFF.') % {
'name': instance_name, 'id': instance.id}
raise virt_inspector.InstanceShutOffException(msg)
return domain
def inspect_vnics(self, instance):
domain = self._get_domain_not_shut_off_or_raise(instance)
tree = etree.fromstring(domain.XMLDesc(0))
for iface in tree.findall('devices/interface'):
target = iface.find('target')
if target is not None:
name = target.get('dev')
else:
continue
mac = iface.find('mac')
if mac is not None:
mac_address = mac.get('address')
else:
continue
fref = iface.find('filterref')
if fref is not None:
fref = fref.get('filter')
params = dict((p.get('name').lower(), p.get('value'))
for p in iface.findall('filterref/parameter'))
interface = virt_inspector.Interface(name=name, mac=mac_address,
fref=fref, parameters=params)
dom_stats = domain.interfaceStats(name)
stats = virt_inspector.InterfaceStats(rx_bytes=dom_stats[0],
rx_packets=dom_stats[1],
tx_bytes=dom_stats[4],
tx_packets=dom_stats[5])
yield (interface, stats)
def inspect_disks(self, instance):
domain = self._get_domain_not_shut_off_or_raise(instance)
tree = etree.fromstring(domain.XMLDesc(0))
for device in filter(
bool,
[target.get("dev")
for target in tree.findall('devices/disk/target')]):
disk = virt_inspector.Disk(device=device)
block_stats = domain.blockStats(device)
stats = virt_inspector.DiskStats(read_requests=block_stats[0],
read_bytes=block_stats[1],
write_requests=block_stats[2],
write_bytes=block_stats[3],
errors=block_stats[4])
yield (disk, stats)
def inspect_memory_usage(self, instance, duration=None):
instance_name = util.instance_name(instance)
domain = self._get_domain_not_shut_off_or_raise(instance)
try:
memory_stats = domain.memoryStats()
if (memory_stats and
memory_stats.get('available') and
memory_stats.get('unused')):
memory_used = (memory_stats.get('available') -
memory_stats.get('unused'))
# Stat provided from libvirt is in KB, converting it to MB.
memory_used = memory_used / units.Ki
return virt_inspector.MemoryUsageStats(usage=memory_used)
else:
msg = ('Failed to inspect memory usage of instance '
'<name=%(name)s, id=%(id)s>, '
'can not get info from libvirt.') % {
'name': instance_name, 'id': instance.id}
raise virt_inspector.NoDataException(msg)
# memoryStats might launch an exception if the method is not supported
# by the underlying hypervisor being used by libvirt.
except libvirt.libvirtError as e:
msg = ('Failed to inspect memory usage of %(instance_uuid)s, '
'can not get info from libvirt: %(error)s') % {
'instance_uuid': instance.id, 'error': e}
raise virt_inspector.NoDataException(msg)
def inspect_disk_info(self, instance):
domain = self._get_domain_not_shut_off_or_raise(instance)
tree = etree.fromstring(domain.XMLDesc(0))
for device in filter(
bool,
[target.get("dev")
for target in tree.findall('devices/disk/target')]):
disk = virt_inspector.Disk(device=device)
block_info = domain.blockInfo(device)
info = virt_inspector.DiskInfo(capacity=block_info[0],
allocation=block_info[1],
physical=block_info[2])
yield (disk, info)
def inspect_memory_resident(self, instance, duration=None):
domain = self._get_domain_not_shut_off_or_raise(instance)
memory = domain.memoryStats()['rss'] / units.Ki
return virt_inspector.MemoryResidentStats(resident=memory)
| inspect_cpus | identifier_name |
base.py | # -*- encoding: utf-8 -*-
# Copyright (c) 2015 b<>com
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Implementation of Inspector abstraction for libvirt."""
from __future__ import unicode_literals
from lxml import etree
from oslo_log import log
from oslo_utils import units
import six
from watcher_metering_drivers.wrappers.virt import inspector as virt_inspector
from watcher_metering_drivers.wrappers.virt import util
libvirt = None
LOG = log.getLogger(__name__)
def retry_on_disconnect(function):
def decorator(self, *args, **kwargs):
try:
return function(self, *args, **kwargs)
except libvirt.libvirtError as e:
if (e.get_error_code() == libvirt.VIR_ERR_SYSTEM_ERROR and
e.get_error_domain() in (libvirt.VIR_FROM_REMOTE,
libvirt.VIR_FROM_RPC)):
LOG.debug(('Connection to libvirt broken'))
self.connection = None
return function(self, *args, **kwargs)
else:
raise
return decorator
class LibvirtInspector(virt_inspector.Inspector):
per_type_uris = dict(uml='uml:///system', xen='xen:///', lxc='lxc:///')
def __init__(self, libvirt_type, libvirt_uri):
self.libvirt_type = libvirt_type
self.libvirt_uri = libvirt_uri
self.uri = self._get_uri()
self.connection = None
def _get_uri(self):
return self.libvirt_uri or self.per_type_uris.get(self.libvirt_type,
'qemu:///system') |
def _get_connection(self):
if not self.connection:
global libvirt
if libvirt is None:
libvirt = __import__('libvirt')
LOG.debug(('Connecting to libvirt: %s'), self.uri)
self.connection = libvirt.openReadOnly(self.uri)
return self.connection
@retry_on_disconnect
def _lookup_by_uuid(self, instance):
instance_name = util.instance_name(instance)
try:
return self._get_connection().lookupByUUIDString(instance.id)
except Exception as ex:
if not libvirt or not isinstance(ex, libvirt.libvirtError):
raise virt_inspector.InspectorException(six.text_type(ex))
error_code = ex.get_error_code()
if (error_code == libvirt.VIR_ERR_SYSTEM_ERROR and
ex.get_error_domain() in (libvirt.VIR_FROM_REMOTE,
libvirt.VIR_FROM_RPC)):
raise
msg = _("Error from libvirt while looking up instance "
"<name=%(name)s, id=%(id)s>: "
"[Error Code %(error_code)s] "
"%(ex)s") % {'name': instance_name,
'id': instance.id,
'error_code': error_code,
'ex': ex}
raise virt_inspector.InstanceNotFoundException(msg)
def inspect_cpus(self, instance):
domain = self._lookup_by_uuid(instance)
dom_info = domain.info()
return virt_inspector.CPUStats(number=dom_info[3], time=dom_info[4])
def _get_domain_not_shut_off_or_raise(self, instance):
instance_name = util.instance_name(instance)
domain = self._lookup_by_uuid(instance)
state = domain.info()[0]
if state == libvirt.VIR_DOMAIN_SHUTOFF:
msg = ('Failed to inspect data of instance '
'<name=%(name)s, id=%(id)s>, '
'domain state is SHUTOFF.') % {
'name': instance_name, 'id': instance.id}
raise virt_inspector.InstanceShutOffException(msg)
return domain
def inspect_vnics(self, instance):
domain = self._get_domain_not_shut_off_or_raise(instance)
tree = etree.fromstring(domain.XMLDesc(0))
for iface in tree.findall('devices/interface'):
target = iface.find('target')
if target is not None:
name = target.get('dev')
else:
continue
mac = iface.find('mac')
if mac is not None:
mac_address = mac.get('address')
else:
continue
fref = iface.find('filterref')
if fref is not None:
fref = fref.get('filter')
params = dict((p.get('name').lower(), p.get('value'))
for p in iface.findall('filterref/parameter'))
interface = virt_inspector.Interface(name=name, mac=mac_address,
fref=fref, parameters=params)
dom_stats = domain.interfaceStats(name)
stats = virt_inspector.InterfaceStats(rx_bytes=dom_stats[0],
rx_packets=dom_stats[1],
tx_bytes=dom_stats[4],
tx_packets=dom_stats[5])
yield (interface, stats)
def inspect_disks(self, instance):
domain = self._get_domain_not_shut_off_or_raise(instance)
tree = etree.fromstring(domain.XMLDesc(0))
for device in filter(
bool,
[target.get("dev")
for target in tree.findall('devices/disk/target')]):
disk = virt_inspector.Disk(device=device)
block_stats = domain.blockStats(device)
stats = virt_inspector.DiskStats(read_requests=block_stats[0],
read_bytes=block_stats[1],
write_requests=block_stats[2],
write_bytes=block_stats[3],
errors=block_stats[4])
yield (disk, stats)
def inspect_memory_usage(self, instance, duration=None):
instance_name = util.instance_name(instance)
domain = self._get_domain_not_shut_off_or_raise(instance)
try:
memory_stats = domain.memoryStats()
if (memory_stats and
memory_stats.get('available') and
memory_stats.get('unused')):
memory_used = (memory_stats.get('available') -
memory_stats.get('unused'))
# Stat provided from libvirt is in KB, converting it to MB.
memory_used = memory_used / units.Ki
return virt_inspector.MemoryUsageStats(usage=memory_used)
else:
msg = ('Failed to inspect memory usage of instance '
'<name=%(name)s, id=%(id)s>, '
'can not get info from libvirt.') % {
'name': instance_name, 'id': instance.id}
raise virt_inspector.NoDataException(msg)
# memoryStats might launch an exception if the method is not supported
# by the underlying hypervisor being used by libvirt.
except libvirt.libvirtError as e:
msg = ('Failed to inspect memory usage of %(instance_uuid)s, '
'can not get info from libvirt: %(error)s') % {
'instance_uuid': instance.id, 'error': e}
raise virt_inspector.NoDataException(msg)
def inspect_disk_info(self, instance):
domain = self._get_domain_not_shut_off_or_raise(instance)
tree = etree.fromstring(domain.XMLDesc(0))
for device in filter(
bool,
[target.get("dev")
for target in tree.findall('devices/disk/target')]):
disk = virt_inspector.Disk(device=device)
block_info = domain.blockInfo(device)
info = virt_inspector.DiskInfo(capacity=block_info[0],
allocation=block_info[1],
physical=block_info[2])
yield (disk, info)
def inspect_memory_resident(self, instance, duration=None):
domain = self._get_domain_not_shut_off_or_raise(instance)
memory = domain.memoryStats()['rss'] / units.Ki
return virt_inspector.MemoryResidentStats(resident=memory) | random_line_split | |
base.py | # -*- encoding: utf-8 -*-
# Copyright (c) 2015 b<>com
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Implementation of Inspector abstraction for libvirt."""
from __future__ import unicode_literals
from lxml import etree
from oslo_log import log
from oslo_utils import units
import six
from watcher_metering_drivers.wrappers.virt import inspector as virt_inspector
from watcher_metering_drivers.wrappers.virt import util
libvirt = None
LOG = log.getLogger(__name__)
def retry_on_disconnect(function):
def decorator(self, *args, **kwargs):
try:
return function(self, *args, **kwargs)
except libvirt.libvirtError as e:
if (e.get_error_code() == libvirt.VIR_ERR_SYSTEM_ERROR and
e.get_error_domain() in (libvirt.VIR_FROM_REMOTE,
libvirt.VIR_FROM_RPC)):
LOG.debug(('Connection to libvirt broken'))
self.connection = None
return function(self, *args, **kwargs)
else:
raise
return decorator
class LibvirtInspector(virt_inspector.Inspector):
per_type_uris = dict(uml='uml:///system', xen='xen:///', lxc='lxc:///')
def __init__(self, libvirt_type, libvirt_uri):
self.libvirt_type = libvirt_type
self.libvirt_uri = libvirt_uri
self.uri = self._get_uri()
self.connection = None
def _get_uri(self):
return self.libvirt_uri or self.per_type_uris.get(self.libvirt_type,
'qemu:///system')
def _get_connection(self):
if not self.connection:
global libvirt
if libvirt is None:
libvirt = __import__('libvirt')
LOG.debug(('Connecting to libvirt: %s'), self.uri)
self.connection = libvirt.openReadOnly(self.uri)
return self.connection
@retry_on_disconnect
def _lookup_by_uuid(self, instance):
instance_name = util.instance_name(instance)
try:
return self._get_connection().lookupByUUIDString(instance.id)
except Exception as ex:
if not libvirt or not isinstance(ex, libvirt.libvirtError):
raise virt_inspector.InspectorException(six.text_type(ex))
error_code = ex.get_error_code()
if (error_code == libvirt.VIR_ERR_SYSTEM_ERROR and
ex.get_error_domain() in (libvirt.VIR_FROM_REMOTE,
libvirt.VIR_FROM_RPC)):
raise
msg = _("Error from libvirt while looking up instance "
"<name=%(name)s, id=%(id)s>: "
"[Error Code %(error_code)s] "
"%(ex)s") % {'name': instance_name,
'id': instance.id,
'error_code': error_code,
'ex': ex}
raise virt_inspector.InstanceNotFoundException(msg)
def inspect_cpus(self, instance):
domain = self._lookup_by_uuid(instance)
dom_info = domain.info()
return virt_inspector.CPUStats(number=dom_info[3], time=dom_info[4])
def _get_domain_not_shut_off_or_raise(self, instance):
instance_name = util.instance_name(instance)
domain = self._lookup_by_uuid(instance)
state = domain.info()[0]
if state == libvirt.VIR_DOMAIN_SHUTOFF:
msg = ('Failed to inspect data of instance '
'<name=%(name)s, id=%(id)s>, '
'domain state is SHUTOFF.') % {
'name': instance_name, 'id': instance.id}
raise virt_inspector.InstanceShutOffException(msg)
return domain
def inspect_vnics(self, instance):
domain = self._get_domain_not_shut_off_or_raise(instance)
tree = etree.fromstring(domain.XMLDesc(0))
for iface in tree.findall('devices/interface'):
target = iface.find('target')
if target is not None:
name = target.get('dev')
else:
continue
mac = iface.find('mac')
if mac is not None:
mac_address = mac.get('address')
else:
continue
fref = iface.find('filterref')
if fref is not None:
fref = fref.get('filter')
params = dict((p.get('name').lower(), p.get('value'))
for p in iface.findall('filterref/parameter'))
interface = virt_inspector.Interface(name=name, mac=mac_address,
fref=fref, parameters=params)
dom_stats = domain.interfaceStats(name)
stats = virt_inspector.InterfaceStats(rx_bytes=dom_stats[0],
rx_packets=dom_stats[1],
tx_bytes=dom_stats[4],
tx_packets=dom_stats[5])
yield (interface, stats)
def inspect_disks(self, instance):
domain = self._get_domain_not_shut_off_or_raise(instance)
tree = etree.fromstring(domain.XMLDesc(0))
for device in filter(
bool,
[target.get("dev")
for target in tree.findall('devices/disk/target')]):
disk = virt_inspector.Disk(device=device)
block_stats = domain.blockStats(device)
stats = virt_inspector.DiskStats(read_requests=block_stats[0],
read_bytes=block_stats[1],
write_requests=block_stats[2],
write_bytes=block_stats[3],
errors=block_stats[4])
yield (disk, stats)
def inspect_memory_usage(self, instance, duration=None):
|
def inspect_disk_info(self, instance):
domain = self._get_domain_not_shut_off_or_raise(instance)
tree = etree.fromstring(domain.XMLDesc(0))
for device in filter(
bool,
[target.get("dev")
for target in tree.findall('devices/disk/target')]):
disk = virt_inspector.Disk(device=device)
block_info = domain.blockInfo(device)
info = virt_inspector.DiskInfo(capacity=block_info[0],
allocation=block_info[1],
physical=block_info[2])
yield (disk, info)
def inspect_memory_resident(self, instance, duration=None):
domain = self._get_domain_not_shut_off_or_raise(instance)
memory = domain.memoryStats()['rss'] / units.Ki
return virt_inspector.MemoryResidentStats(resident=memory)
| instance_name = util.instance_name(instance)
domain = self._get_domain_not_shut_off_or_raise(instance)
try:
memory_stats = domain.memoryStats()
if (memory_stats and
memory_stats.get('available') and
memory_stats.get('unused')):
memory_used = (memory_stats.get('available') -
memory_stats.get('unused'))
# Stat provided from libvirt is in KB, converting it to MB.
memory_used = memory_used / units.Ki
return virt_inspector.MemoryUsageStats(usage=memory_used)
else:
msg = ('Failed to inspect memory usage of instance '
'<name=%(name)s, id=%(id)s>, '
'can not get info from libvirt.') % {
'name': instance_name, 'id': instance.id}
raise virt_inspector.NoDataException(msg)
# memoryStats might launch an exception if the method is not supported
# by the underlying hypervisor being used by libvirt.
except libvirt.libvirtError as e:
msg = ('Failed to inspect memory usage of %(instance_uuid)s, '
'can not get info from libvirt: %(error)s') % {
'instance_uuid': instance.id, 'error': e}
raise virt_inspector.NoDataException(msg) | identifier_body |
stock_reconciliation.js | // Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt
frappe.provide("erpnext.stock");
frappe.ui.form.on("Stock Reconciliation", {
onload: function(frm) {
frm.add_fetch("item_code", "item_name", "item_name");
// end of life
frm.set_query("item_code", "items", function(doc, cdt, cdn) {
return {
query: "erpnext.controllers.queries.item_query",
filters:{
"is_stock_item": 1,
"has_serial_no": 0
}
}
});
if (frm.doc.company) {
erpnext.queries.setup_queries(frm, "Warehouse", function() {
return erpnext.queries.warehouse(frm.doc);
});
}
if (!frm.doc.expense_account) {
frm.trigger("set_expense_account");
}
},
refresh: function(frm) {
if(frm.doc.docstatus < 1) {
frm.add_custom_button(__("Items"), function() {
frm.events.get_items(frm);
});
}
if(frm.doc.company) {
frm.trigger("toggle_display_account_head");
}
},
get_items: function(frm) {
frappe.prompt({label:"Warehouse", fieldtype:"Link", options:"Warehouse", reqd: 1,
"get_query": function() {
return {
"filters": {
"company": frm.doc.company,
}
}
}},
function(data) {
frappe.call({
method:"erpnext.stock.doctype.stock_reconciliation.stock_reconciliation.get_items",
args: {
warehouse: data.warehouse,
posting_date: frm.doc.posting_date,
posting_time: frm.doc.posting_time,
company:frm.doc.company
},
callback: function(r) {
var items = [];
frm.clear_table("items");
for(var i=0; i< r.message.length; i++) {
var d = frm.add_child("items");
$.extend(d, r.message[i]);
if(!d.qty) d.qty = null;
if(!d.valuation_rate) d.valuation_rate = null;
}
frm.refresh_field("items");
}
});
}
, __("Get Items"), __("Update"));
},
set_valuation_rate_and_qty: function(frm, cdt, cdn) {
var d = frappe.model.get_doc(cdt, cdn);
if(d.item_code && d.warehouse) {
frappe.call({
method: "erpnext.stock.doctype.stock_reconciliation.stock_reconciliation.get_stock_balance_for",
args: {
item_code: d.item_code,
warehouse: d.warehouse,
posting_date: frm.doc.posting_date,
posting_time: frm.doc.posting_time
},
callback: function(r) {
frappe.model.set_value(cdt, cdn, "qty", r.message.qty);
frappe.model.set_value(cdt, cdn, "valuation_rate", r.message.rate);
frappe.model.set_value(cdt, cdn, "current_qty", r.message.qty);
frappe.model.set_value(cdt, cdn, "current_valuation_rate", r.message.rate);
frappe.model.set_value(cdt, cdn, "current_amount", r.message.rate * r.message.qty);
frappe.model.set_value(cdt, cdn, "amount", r.message.rate * r.message.qty);
}
});
}
},
set_item_code: function(doc, cdt, cdn) {
var d = frappe.model.get_doc(cdt, cdn);
if (d.barcode) {
frappe.call({
method: "erpnext.stock.get_item_details.get_item_code",
args: {"barcode": d.barcode },
callback: function(r) {
if (!r.exe){
frappe.model.set_value(cdt, cdn, "item_code", r.message);
}
}
});
}
},
set_amount_quantity: function(doc, cdt, cdn) {
var d = frappe.model.get_doc(cdt, cdn);
if (d.qty & d.valuation_rate) {
frappe.model.set_value(cdt, cdn, "amount", flt(d.qty) * flt(d.valuation_rate));
frappe.model.set_value(cdt, cdn, "quantity_difference", flt(d.qty) - flt(d.current_qty));
frappe.model.set_value(cdt, cdn, "amount_difference", flt(d.amount) - flt(d.current_amount));
}
},
company: function(frm) {
frm.trigger("toggle_display_account_head");
},
toggle_display_account_head: function(frm) {
frm.toggle_display(['expense_account', 'cost_center'],
erpnext.is_perpetual_inventory_enabled(frm.doc.company));
},
purpose: function(frm) {
frm.trigger("set_expense_account");
},
set_expense_account: function(frm) {
if (frm.doc.company && erpnext.is_perpetual_inventory_enabled(frm.doc.company)) {
return frm.call({
method: "erpnext.stock.doctype.stock_reconciliation.stock_reconciliation.get_difference_account",
args: {
"purpose": frm.doc.purpose,
"company": frm.doc.company
},
callback: function(r) {
if (!r.exc) {
frm.set_value("expense_account", r.message);
}
}
});
}
}
});
frappe.ui.form.on("Stock Reconciliation Item", {
barcode: function(frm, cdt, cdn) {
frm.events.set_item_code(frm, cdt, cdn);
},
warehouse: function(frm, cdt, cdn) {
frm.events.set_valuation_rate_and_qty(frm, cdt, cdn);
},
item_code: function(frm, cdt, cdn) {
frm.events.set_valuation_rate_and_qty(frm, cdt, cdn);
},
qty: function(frm, cdt, cdn) {
frm.events.set_amount_quantity(frm, cdt, cdn);
},
valuation_rate: function(frm, cdt, cdn) {
frm.events.set_amount_quantity(frm, cdt, cdn);
}
});
erpnext.stock.StockReconciliation = erpnext.stock.StockController.extend({
setup: function() {
var me = this;
this.setup_posting_date_time_check();
if (me.frm.doc.company && erpnext.is_perpetual_inventory_enabled(me.frm.doc.company)) {
this.frm.add_fetch("company", "cost_center", "cost_center");
}
this.frm.fields_dict["expense_account"].get_query = function() {
if(erpnext.is_perpetual_inventory_enabled(me.frm.doc.company)) {
return {
"filters": {
'company': me.frm.doc.company,
"is_group": 0
}
}
}
}
this.frm.fields_dict["cost_center"].get_query = function() {
if(erpnext.is_perpetual_inventory_enabled(me.frm.doc.company)) {
return {
"filters": {
'company': me.frm.doc.company,
"is_group": 0
}
}
}
}
},
refresh: function() {
if(this.frm.doc.docstatus==1) {
this.show_stock_ledger(); | if (erpnext.is_perpetual_inventory_enabled(this.frm.doc.company)) {
this.show_general_ledger();
}
}
},
});
cur_frm.cscript = new erpnext.stock.StockReconciliation({frm: cur_frm}); | random_line_split | |
link_style.rs | /// Determines the hyperlink style used in commit and issue links. Defaults to `LinksStyle::Github`
///
/// # Example
///
/// ```no_run
/// # use clog::{LinkStyle, Clog};
/// let mut clog = Clog::new().unwrap();
/// clog.link_style(LinkStyle::Stash);
/// ```
clog_enum!{
#[derive(Debug)]
pub enum LinkStyle {
Github,
Gitlab,
Stash
}
}
impl LinkStyle {
/// Gets a hyperlink url to an issue in the specified format.
///
/// # Example
///
/// ```no_run
/// # use clog::{LinkStyle, Clog};
/// let link = LinkStyle::Github;
/// let issue = link.issue_link("141", "https://github.com/thoughtram/clog");
///
/// assert_eq!("https://github.com/thoughtram/clog/issues/141", issue);
/// ```
pub fn issue_link<S: AsRef<str>>(&self, issue: S, repo: S) -> String {
match repo.as_ref() {
"" => format!("{}", issue.as_ref()),
link => {
match *self {
LinkStyle::Github => format!("{}/issues/{}", link, issue.as_ref()),
LinkStyle::Gitlab => format!("{}/issues/{}", link, issue.as_ref()), | }
}
/// Gets a hyperlink url to a commit in the specified format.
///
/// # Example
/// ```no_run
/// # use clog::{LinkStyle, Clog};
/// let link = LinkStyle::Github;
/// let commit = link.commit_link("123abc891234567890abcdefabc4567898724", "https://github.com/thoughtram/clog");
///
/// assert_eq!("https://github.com/thoughtram/clog/commit/123abc891234567890abcdefabc4567898724", commit);
/// ```
pub fn commit_link<S: AsRef<str>>(&self, hash: S, repo: S) -> String {
match repo.as_ref() {
"" => format!("{}", &hash.as_ref()[0..8]),
link => {
match *self {
LinkStyle::Github => format!("{}/commit/{}", link, hash.as_ref()),
LinkStyle::Gitlab => format!("{}/commit/{}", link, hash.as_ref()),
LinkStyle::Stash => format!("{}/commits/{}", link, hash.as_ref()),
}
}
}
}
} | LinkStyle::Stash => format!("{}", issue.as_ref()),
}
} | random_line_split |
link_style.rs | /// Determines the hyperlink style used in commit and issue links. Defaults to `LinksStyle::Github`
///
/// # Example
///
/// ```no_run
/// # use clog::{LinkStyle, Clog};
/// let mut clog = Clog::new().unwrap();
/// clog.link_style(LinkStyle::Stash);
/// ```
clog_enum!{
#[derive(Debug)]
pub enum LinkStyle {
Github,
Gitlab,
Stash
}
}
impl LinkStyle {
/// Gets a hyperlink url to an issue in the specified format.
///
/// # Example
///
/// ```no_run
/// # use clog::{LinkStyle, Clog};
/// let link = LinkStyle::Github;
/// let issue = link.issue_link("141", "https://github.com/thoughtram/clog");
///
/// assert_eq!("https://github.com/thoughtram/clog/issues/141", issue);
/// ```
pub fn issue_link<S: AsRef<str>>(&self, issue: S, repo: S) -> String {
match repo.as_ref() {
"" => format!("{}", issue.as_ref()),
link => |
}
}
/// Gets a hyperlink url to a commit in the specified format.
///
/// # Example
/// ```no_run
/// # use clog::{LinkStyle, Clog};
/// let link = LinkStyle::Github;
/// let commit = link.commit_link("123abc891234567890abcdefabc4567898724", "https://github.com/thoughtram/clog");
///
/// assert_eq!("https://github.com/thoughtram/clog/commit/123abc891234567890abcdefabc4567898724", commit);
/// ```
pub fn commit_link<S: AsRef<str>>(&self, hash: S, repo: S) -> String {
match repo.as_ref() {
"" => format!("{}", &hash.as_ref()[0..8]),
link => {
match *self {
LinkStyle::Github => format!("{}/commit/{}", link, hash.as_ref()),
LinkStyle::Gitlab => format!("{}/commit/{}", link, hash.as_ref()),
LinkStyle::Stash => format!("{}/commits/{}", link, hash.as_ref()),
}
}
}
}
}
| {
match *self {
LinkStyle::Github => format!("{}/issues/{}", link, issue.as_ref()),
LinkStyle::Gitlab => format!("{}/issues/{}", link, issue.as_ref()),
LinkStyle::Stash => format!("{}", issue.as_ref()),
}
} | conditional_block |
link_style.rs | /// Determines the hyperlink style used in commit and issue links. Defaults to `LinksStyle::Github`
///
/// # Example
///
/// ```no_run
/// # use clog::{LinkStyle, Clog};
/// let mut clog = Clog::new().unwrap();
/// clog.link_style(LinkStyle::Stash);
/// ```
clog_enum!{
#[derive(Debug)]
pub enum LinkStyle {
Github,
Gitlab,
Stash
}
}
impl LinkStyle {
/// Gets a hyperlink url to an issue in the specified format.
///
/// # Example
///
/// ```no_run
/// # use clog::{LinkStyle, Clog};
/// let link = LinkStyle::Github;
/// let issue = link.issue_link("141", "https://github.com/thoughtram/clog");
///
/// assert_eq!("https://github.com/thoughtram/clog/issues/141", issue);
/// ```
pub fn issue_link<S: AsRef<str>>(&self, issue: S, repo: S) -> String |
/// Gets a hyperlink url to a commit in the specified format.
///
/// # Example
/// ```no_run
/// # use clog::{LinkStyle, Clog};
/// let link = LinkStyle::Github;
/// let commit = link.commit_link("123abc891234567890abcdefabc4567898724", "https://github.com/thoughtram/clog");
///
/// assert_eq!("https://github.com/thoughtram/clog/commit/123abc891234567890abcdefabc4567898724", commit);
/// ```
pub fn commit_link<S: AsRef<str>>(&self, hash: S, repo: S) -> String {
match repo.as_ref() {
"" => format!("{}", &hash.as_ref()[0..8]),
link => {
match *self {
LinkStyle::Github => format!("{}/commit/{}", link, hash.as_ref()),
LinkStyle::Gitlab => format!("{}/commit/{}", link, hash.as_ref()),
LinkStyle::Stash => format!("{}/commits/{}", link, hash.as_ref()),
}
}
}
}
}
| {
match repo.as_ref() {
"" => format!("{}", issue.as_ref()),
link => {
match *self {
LinkStyle::Github => format!("{}/issues/{}", link, issue.as_ref()),
LinkStyle::Gitlab => format!("{}/issues/{}", link, issue.as_ref()),
LinkStyle::Stash => format!("{}", issue.as_ref()),
}
}
}
} | identifier_body |
link_style.rs | /// Determines the hyperlink style used in commit and issue links. Defaults to `LinksStyle::Github`
///
/// # Example
///
/// ```no_run
/// # use clog::{LinkStyle, Clog};
/// let mut clog = Clog::new().unwrap();
/// clog.link_style(LinkStyle::Stash);
/// ```
clog_enum!{
#[derive(Debug)]
pub enum LinkStyle {
Github,
Gitlab,
Stash
}
}
impl LinkStyle {
/// Gets a hyperlink url to an issue in the specified format.
///
/// # Example
///
/// ```no_run
/// # use clog::{LinkStyle, Clog};
/// let link = LinkStyle::Github;
/// let issue = link.issue_link("141", "https://github.com/thoughtram/clog");
///
/// assert_eq!("https://github.com/thoughtram/clog/issues/141", issue);
/// ```
pub fn issue_link<S: AsRef<str>>(&self, issue: S, repo: S) -> String {
match repo.as_ref() {
"" => format!("{}", issue.as_ref()),
link => {
match *self {
LinkStyle::Github => format!("{}/issues/{}", link, issue.as_ref()),
LinkStyle::Gitlab => format!("{}/issues/{}", link, issue.as_ref()),
LinkStyle::Stash => format!("{}", issue.as_ref()),
}
}
}
}
/// Gets a hyperlink url to a commit in the specified format.
///
/// # Example
/// ```no_run
/// # use clog::{LinkStyle, Clog};
/// let link = LinkStyle::Github;
/// let commit = link.commit_link("123abc891234567890abcdefabc4567898724", "https://github.com/thoughtram/clog");
///
/// assert_eq!("https://github.com/thoughtram/clog/commit/123abc891234567890abcdefabc4567898724", commit);
/// ```
pub fn | <S: AsRef<str>>(&self, hash: S, repo: S) -> String {
match repo.as_ref() {
"" => format!("{}", &hash.as_ref()[0..8]),
link => {
match *self {
LinkStyle::Github => format!("{}/commit/{}", link, hash.as_ref()),
LinkStyle::Gitlab => format!("{}/commit/{}", link, hash.as_ref()),
LinkStyle::Stash => format!("{}/commits/{}", link, hash.as_ref()),
}
}
}
}
}
| commit_link | identifier_name |
marm2.py | from rsf.proj import *
from math import *
import fdmod,pcsutil,wefd
def data(par):
# ------------------------------------------------------------
Fetch('vp_marmousi-ii.segy',"marm2")
Fetch('vs_marmousi-ii.segy',"marm2")
Fetch('density_marmousi-ii.segy',"marm2")
# ------------------------------------------------------------
for file in ('vp','vs','ro'):
if(file=='ro'):
ifile='density_marmousi-ii.segy'
else:
ifile=file+'_marmousi-ii.segy'
Flow(['z'+file,'t'+file,'./s'+file,'./b'+file],ifile,
'''
segyread tape=$SOURCE
tfile=${TARGETS[1]}
hfile=${TARGETS[2]}
bfile=${TARGETS[3]}
''',stdin=0)
Flow('_'+file,'z'+file,
'''
put
o1=0 d1=0.001249 label1=%(lz)s unit1=%(uz)s
o2=0 d2=0.001249 label2=%(lx)s unit2=%(ux)s |
window j1=2 j2=2
''' % par)
if(file=='ro'):
Flow(file+'raw','_'+file,'window n1=%(nz)d n2=%(nx)d min1=%(oz)g min2=%(ox)g | scale rscale=1000000' % par)
else:
Flow(file+'raw','_'+file,'window n1=%(nz)d n2=%(nx)d min1=%(oz)g min2=%(ox)g' % par)
# ------------------------------------------------------------
Flow( 'wmask','vpraw','mask max=1.5 | dd type=float')
# Result('wmask',fdmod.cgrey('allpos=y',par))
Flow('rx','vpraw','math output="1.0e6+1.5e6*(input-1.5)/3" ')
Flow('ro','roraw','math output=1')
Flow('vp','vpraw','smooth rect1=35 rect2=35 repeat=5')
Flow('vs','vp wmask','scale rscale=0.5 | math w=${SOURCES[1]} output="input*(1-w)"')
# velocity ratio at cig location x
Flow('vratio1_1','vp vp','add mode=d ${SOURCES[1]}');
Flow('vratio1_2','vp vs','add mode=d ${SOURCES[1]}');
Flow('vratio2_1','vs vp','add mode=d ${SOURCES[1]}');
Flow('vratio2_2','vs vs','add mode=d ${SOURCES[1]}');
Flow('vratio','vratio1_1 vratio1_2 vratio2_1 vratio2_2',
'''
cat axis=3 space=n ${SOURCES[0:4]}
''',stdin=0)
def mask(mask,xsou,tmin,tmax,par):
dipline1(mask+'ml',
0.15+tmin,par['xmin'],
0.15,xsou,
0,1,
par['nt'],par['ot'],par['dt'],
par['nx'],par['ox'],par['dx'])
dipline1(mask+'mr',
0.15,xsou,
0.15+tmax,par['xmax'],
0,1,
par['nt'],par['ot'],par['dt'],
par['nx'],par['ox'],par['dx'])
Flow(mask,[mask+'ml',mask+'mr'],
'''
spike nsp=1 mag=1.0
n1=%(nx)d o1=%(ox)g d1=%(dx)g k1=%(ltap)d l1=%(rtap)d
n2=%(nt)d o2=%(ot)g d2=%(dt)g |
smooth rect1=100 repeat=1 |
scale axis=123 |
transp |
add mode=p ${SOURCES[0]} |
add mode=p ${SOURCES[1]} |
transp |
smooth rect2=100 repeat=3 |
put label1=x label2=t unit1=km unit2=s |
spray axis=3 n=2 o=0 d=1 |
transp plane=23
''' % par)
Result(mask,
'window n2=1 | transp|' + fdmod.dgrey('',par))
def dip(dip,img,par):
Flow( dip,img,'dip rect1=40 rect2=40 order=3 liter=100 verb=y ')
Result(dip,fdmod.cgrey('color=j wantscalebar=n',par))
def psang(x,img,dip,vpvs,tag,par):
#dip angle at cig location x
Flow( dip+'-one',dip,'window n2=1 min2=%g'%x)
#vpvs ratio at cig location x
Flow('vratioPP',vpvs,'window n3=1 f3=0 n2=1 min2=%g'%x)
Flow('vratioPS',vpvs,'window n3=1 f3=1 n2=1 min2=%g'%x)
Flow('vratioSP',vpvs,'window n3=1 f3=2 n2=1 min2=%g'%x)
Flow('vratioSS',vpvs,'window n3=1 f3=3 n2=1 min2=%g'%x)
nhx=200
nhz=0
nht=0
wefd.elaps('S'+tag,
img+tag+'_ds',
img+tag+'_dr',
nhx,nhz,nht,
dip+'-one',x,par)
def | (mod,s1,s2,e1,e2,vi,vt,n1,o1,d1,n2,o2,d2):
min1=o1
max1=o1+(n1-1)*d1
min2=o2
max2=o2+(n2-1)*d2
ra = (e1-s1)/(e2-s2)
vels = "%s,%s,%s" %(vi,vt,vt)
drvs = "%s,%s" %(tan(ra),tan(ra))
dim1 = 'd1=%g o1=%g n1=%d' % (d2,o2,n2)
dim2 = 'd2=%g o2=%g n2=%d' % (d1,o1,n1)
Flow(mod+'lay2',None,
'''
spike nsp=4 mag=%g,%g,%g,%g
n1=4 n2=1 k1=1,2,3,4 |
put n1=2 n2=2 |
spline %s fp=%s
'''%(min2,min1,max2,max1,dim1,drvs))
Flow(mod+'lay1',None,
'''
spike nsp=4 mag=%g,%g,%g,%g
n1=4 n2=1 k1=1,2,3,4 |
put n1=2 n2=2 |
spline %s fp=%s
'''%(s2,s1,e2,e1,dim1,drvs))
Flow( mod+'layers',[mod+'lay1',mod+'lay2'],'cat axis=2 ${SOURCES[1:2]}')
Flow(mod,mod+'layers',
'''
unif2 v00=%s n1=%d d1=%g o1=%g
''' % (vels,n1,d1,o1) )
| dipline1 | identifier_name |
marm2.py | from rsf.proj import *
from math import *
import fdmod,pcsutil,wefd
def data(par):
# ------------------------------------------------------------
Fetch('vp_marmousi-ii.segy',"marm2")
Fetch('vs_marmousi-ii.segy',"marm2")
Fetch('density_marmousi-ii.segy',"marm2")
# ------------------------------------------------------------
for file in ('vp','vs','ro'):
if(file=='ro'):
ifile='density_marmousi-ii.segy'
else:
ifile=file+'_marmousi-ii.segy'
Flow(['z'+file,'t'+file,'./s'+file,'./b'+file],ifile,
'''
segyread tape=$SOURCE
tfile=${TARGETS[1]}
hfile=${TARGETS[2]}
bfile=${TARGETS[3]}
''',stdin=0)
Flow('_'+file,'z'+file,
'''
put
o1=0 d1=0.001249 label1=%(lz)s unit1=%(uz)s
o2=0 d2=0.001249 label2=%(lx)s unit2=%(ux)s |
window j1=2 j2=2
''' % par)
if(file=='ro'):
Flow(file+'raw','_'+file,'window n1=%(nz)d n2=%(nx)d min1=%(oz)g min2=%(ox)g | scale rscale=1000000' % par)
else:
Flow(file+'raw','_'+file,'window n1=%(nz)d n2=%(nx)d min1=%(oz)g min2=%(ox)g' % par)
# ------------------------------------------------------------
Flow( 'wmask','vpraw','mask max=1.5 | dd type=float')
# Result('wmask',fdmod.cgrey('allpos=y',par))
Flow('rx','vpraw','math output="1.0e6+1.5e6*(input-1.5)/3" ')
Flow('ro','roraw','math output=1')
Flow('vp','vpraw','smooth rect1=35 rect2=35 repeat=5')
Flow('vs','vp wmask','scale rscale=0.5 | math w=${SOURCES[1]} output="input*(1-w)"')
# velocity ratio at cig location x
Flow('vratio1_1','vp vp','add mode=d ${SOURCES[1]}');
Flow('vratio1_2','vp vs','add mode=d ${SOURCES[1]}');
Flow('vratio2_1','vs vp','add mode=d ${SOURCES[1]}');
Flow('vratio2_2','vs vs','add mode=d ${SOURCES[1]}');
Flow('vratio','vratio1_1 vratio1_2 vratio2_1 vratio2_2',
'''
cat axis=3 space=n ${SOURCES[0:4]}
''',stdin=0)
def mask(mask,xsou,tmin,tmax,par):
dipline1(mask+'ml',
0.15+tmin,par['xmin'],
0.15,xsou,
0,1,
par['nt'],par['ot'],par['dt'],
par['nx'],par['ox'],par['dx'])
dipline1(mask+'mr',
0.15,xsou,
0.15+tmax,par['xmax'],
0,1,
par['nt'],par['ot'],par['dt'],
par['nx'],par['ox'],par['dx'])
Flow(mask,[mask+'ml',mask+'mr'],
'''
spike nsp=1 mag=1.0
n1=%(nx)d o1=%(ox)g d1=%(dx)g k1=%(ltap)d l1=%(rtap)d
n2=%(nt)d o2=%(ot)g d2=%(dt)g |
smooth rect1=100 repeat=1 |
scale axis=123 |
transp |
add mode=p ${SOURCES[0]} |
add mode=p ${SOURCES[1]} |
transp |
smooth rect2=100 repeat=3 |
put label1=x label2=t unit1=km unit2=s |
spray axis=3 n=2 o=0 d=1 |
transp plane=23
''' % par)
Result(mask,
'window n2=1 | transp|' + fdmod.dgrey('',par))
def dip(dip,img,par):
Flow( dip,img,'dip rect1=40 rect2=40 order=3 liter=100 verb=y ')
Result(dip,fdmod.cgrey('color=j wantscalebar=n',par))
def psang(x,img,dip,vpvs,tag,par):
#dip angle at cig location x
Flow( dip+'-one',dip,'window n2=1 min2=%g'%x)
#vpvs ratio at cig location x
Flow('vratioPP',vpvs,'window n3=1 f3=0 n2=1 min2=%g'%x)
Flow('vratioPS',vpvs,'window n3=1 f3=1 n2=1 min2=%g'%x)
Flow('vratioSP',vpvs,'window n3=1 f3=2 n2=1 min2=%g'%x)
Flow('vratioSS',vpvs,'window n3=1 f3=3 n2=1 min2=%g'%x)
nhx=200
nhz=0
nht=0
wefd.elaps('S'+tag,
img+tag+'_ds',
img+tag+'_dr',
nhx,nhz,nht,
dip+'-one',x,par)
def dipline1(mod,s1,s2,e1,e2,vi,vt,n1,o1,d1,n2,o2,d2): |
min1=o1
max1=o1+(n1-1)*d1
min2=o2
max2=o2+(n2-1)*d2
ra = (e1-s1)/(e2-s2)
vels = "%s,%s,%s" %(vi,vt,vt)
drvs = "%s,%s" %(tan(ra),tan(ra))
dim1 = 'd1=%g o1=%g n1=%d' % (d2,o2,n2)
dim2 = 'd2=%g o2=%g n2=%d' % (d1,o1,n1)
Flow(mod+'lay2',None,
'''
spike nsp=4 mag=%g,%g,%g,%g
n1=4 n2=1 k1=1,2,3,4 |
put n1=2 n2=2 |
spline %s fp=%s
'''%(min2,min1,max2,max1,dim1,drvs))
Flow(mod+'lay1',None,
'''
spike nsp=4 mag=%g,%g,%g,%g
n1=4 n2=1 k1=1,2,3,4 |
put n1=2 n2=2 |
spline %s fp=%s
'''%(s2,s1,e2,e1,dim1,drvs))
Flow( mod+'layers',[mod+'lay1',mod+'lay2'],'cat axis=2 ${SOURCES[1:2]}')
Flow(mod,mod+'layers',
'''
unif2 v00=%s n1=%d d1=%g o1=%g
''' % (vels,n1,d1,o1) ) | random_line_split | |
marm2.py | from rsf.proj import *
from math import *
import fdmod,pcsutil,wefd
def data(par):
# ------------------------------------------------------------
Fetch('vp_marmousi-ii.segy',"marm2")
Fetch('vs_marmousi-ii.segy',"marm2")
Fetch('density_marmousi-ii.segy',"marm2")
# ------------------------------------------------------------
for file in ('vp','vs','ro'):
if(file=='ro'):
ifile='density_marmousi-ii.segy'
else:
ifile=file+'_marmousi-ii.segy'
Flow(['z'+file,'t'+file,'./s'+file,'./b'+file],ifile,
'''
segyread tape=$SOURCE
tfile=${TARGETS[1]}
hfile=${TARGETS[2]}
bfile=${TARGETS[3]}
''',stdin=0)
Flow('_'+file,'z'+file,
'''
put
o1=0 d1=0.001249 label1=%(lz)s unit1=%(uz)s
o2=0 d2=0.001249 label2=%(lx)s unit2=%(ux)s |
window j1=2 j2=2
''' % par)
if(file=='ro'):
Flow(file+'raw','_'+file,'window n1=%(nz)d n2=%(nx)d min1=%(oz)g min2=%(ox)g | scale rscale=1000000' % par)
else:
|
# ------------------------------------------------------------
Flow( 'wmask','vpraw','mask max=1.5 | dd type=float')
# Result('wmask',fdmod.cgrey('allpos=y',par))
Flow('rx','vpraw','math output="1.0e6+1.5e6*(input-1.5)/3" ')
Flow('ro','roraw','math output=1')
Flow('vp','vpraw','smooth rect1=35 rect2=35 repeat=5')
Flow('vs','vp wmask','scale rscale=0.5 | math w=${SOURCES[1]} output="input*(1-w)"')
# velocity ratio at cig location x
Flow('vratio1_1','vp vp','add mode=d ${SOURCES[1]}');
Flow('vratio1_2','vp vs','add mode=d ${SOURCES[1]}');
Flow('vratio2_1','vs vp','add mode=d ${SOURCES[1]}');
Flow('vratio2_2','vs vs','add mode=d ${SOURCES[1]}');
Flow('vratio','vratio1_1 vratio1_2 vratio2_1 vratio2_2',
'''
cat axis=3 space=n ${SOURCES[0:4]}
''',stdin=0)
def mask(mask,xsou,tmin,tmax,par):
dipline1(mask+'ml',
0.15+tmin,par['xmin'],
0.15,xsou,
0,1,
par['nt'],par['ot'],par['dt'],
par['nx'],par['ox'],par['dx'])
dipline1(mask+'mr',
0.15,xsou,
0.15+tmax,par['xmax'],
0,1,
par['nt'],par['ot'],par['dt'],
par['nx'],par['ox'],par['dx'])
Flow(mask,[mask+'ml',mask+'mr'],
'''
spike nsp=1 mag=1.0
n1=%(nx)d o1=%(ox)g d1=%(dx)g k1=%(ltap)d l1=%(rtap)d
n2=%(nt)d o2=%(ot)g d2=%(dt)g |
smooth rect1=100 repeat=1 |
scale axis=123 |
transp |
add mode=p ${SOURCES[0]} |
add mode=p ${SOURCES[1]} |
transp |
smooth rect2=100 repeat=3 |
put label1=x label2=t unit1=km unit2=s |
spray axis=3 n=2 o=0 d=1 |
transp plane=23
''' % par)
Result(mask,
'window n2=1 | transp|' + fdmod.dgrey('',par))
def dip(dip,img,par):
Flow( dip,img,'dip rect1=40 rect2=40 order=3 liter=100 verb=y ')
Result(dip,fdmod.cgrey('color=j wantscalebar=n',par))
def psang(x,img,dip,vpvs,tag,par):
#dip angle at cig location x
Flow( dip+'-one',dip,'window n2=1 min2=%g'%x)
#vpvs ratio at cig location x
Flow('vratioPP',vpvs,'window n3=1 f3=0 n2=1 min2=%g'%x)
Flow('vratioPS',vpvs,'window n3=1 f3=1 n2=1 min2=%g'%x)
Flow('vratioSP',vpvs,'window n3=1 f3=2 n2=1 min2=%g'%x)
Flow('vratioSS',vpvs,'window n3=1 f3=3 n2=1 min2=%g'%x)
nhx=200
nhz=0
nht=0
wefd.elaps('S'+tag,
img+tag+'_ds',
img+tag+'_dr',
nhx,nhz,nht,
dip+'-one',x,par)
def dipline1(mod,s1,s2,e1,e2,vi,vt,n1,o1,d1,n2,o2,d2):
min1=o1
max1=o1+(n1-1)*d1
min2=o2
max2=o2+(n2-1)*d2
ra = (e1-s1)/(e2-s2)
vels = "%s,%s,%s" %(vi,vt,vt)
drvs = "%s,%s" %(tan(ra),tan(ra))
dim1 = 'd1=%g o1=%g n1=%d' % (d2,o2,n2)
dim2 = 'd2=%g o2=%g n2=%d' % (d1,o1,n1)
Flow(mod+'lay2',None,
'''
spike nsp=4 mag=%g,%g,%g,%g
n1=4 n2=1 k1=1,2,3,4 |
put n1=2 n2=2 |
spline %s fp=%s
'''%(min2,min1,max2,max1,dim1,drvs))
Flow(mod+'lay1',None,
'''
spike nsp=4 mag=%g,%g,%g,%g
n1=4 n2=1 k1=1,2,3,4 |
put n1=2 n2=2 |
spline %s fp=%s
'''%(s2,s1,e2,e1,dim1,drvs))
Flow( mod+'layers',[mod+'lay1',mod+'lay2'],'cat axis=2 ${SOURCES[1:2]}')
Flow(mod,mod+'layers',
'''
unif2 v00=%s n1=%d d1=%g o1=%g
''' % (vels,n1,d1,o1) )
| Flow(file+'raw','_'+file,'window n1=%(nz)d n2=%(nx)d min1=%(oz)g min2=%(ox)g' % par) | conditional_block |
marm2.py | from rsf.proj import *
from math import *
import fdmod,pcsutil,wefd
def data(par):
# ------------------------------------------------------------
Fetch('vp_marmousi-ii.segy',"marm2")
Fetch('vs_marmousi-ii.segy',"marm2")
Fetch('density_marmousi-ii.segy',"marm2")
# ------------------------------------------------------------
for file in ('vp','vs','ro'):
if(file=='ro'):
ifile='density_marmousi-ii.segy'
else:
ifile=file+'_marmousi-ii.segy'
Flow(['z'+file,'t'+file,'./s'+file,'./b'+file],ifile,
'''
segyread tape=$SOURCE
tfile=${TARGETS[1]}
hfile=${TARGETS[2]}
bfile=${TARGETS[3]}
''',stdin=0)
Flow('_'+file,'z'+file,
'''
put
o1=0 d1=0.001249 label1=%(lz)s unit1=%(uz)s
o2=0 d2=0.001249 label2=%(lx)s unit2=%(ux)s |
window j1=2 j2=2
''' % par)
if(file=='ro'):
Flow(file+'raw','_'+file,'window n1=%(nz)d n2=%(nx)d min1=%(oz)g min2=%(ox)g | scale rscale=1000000' % par)
else:
Flow(file+'raw','_'+file,'window n1=%(nz)d n2=%(nx)d min1=%(oz)g min2=%(ox)g' % par)
# ------------------------------------------------------------
Flow( 'wmask','vpraw','mask max=1.5 | dd type=float')
# Result('wmask',fdmod.cgrey('allpos=y',par))
Flow('rx','vpraw','math output="1.0e6+1.5e6*(input-1.5)/3" ')
Flow('ro','roraw','math output=1')
Flow('vp','vpraw','smooth rect1=35 rect2=35 repeat=5')
Flow('vs','vp wmask','scale rscale=0.5 | math w=${SOURCES[1]} output="input*(1-w)"')
# velocity ratio at cig location x
Flow('vratio1_1','vp vp','add mode=d ${SOURCES[1]}');
Flow('vratio1_2','vp vs','add mode=d ${SOURCES[1]}');
Flow('vratio2_1','vs vp','add mode=d ${SOURCES[1]}');
Flow('vratio2_2','vs vs','add mode=d ${SOURCES[1]}');
Flow('vratio','vratio1_1 vratio1_2 vratio2_1 vratio2_2',
'''
cat axis=3 space=n ${SOURCES[0:4]}
''',stdin=0)
def mask(mask,xsou,tmin,tmax,par):
dipline1(mask+'ml',
0.15+tmin,par['xmin'],
0.15,xsou,
0,1,
par['nt'],par['ot'],par['dt'],
par['nx'],par['ox'],par['dx'])
dipline1(mask+'mr',
0.15,xsou,
0.15+tmax,par['xmax'],
0,1,
par['nt'],par['ot'],par['dt'],
par['nx'],par['ox'],par['dx'])
Flow(mask,[mask+'ml',mask+'mr'],
'''
spike nsp=1 mag=1.0
n1=%(nx)d o1=%(ox)g d1=%(dx)g k1=%(ltap)d l1=%(rtap)d
n2=%(nt)d o2=%(ot)g d2=%(dt)g |
smooth rect1=100 repeat=1 |
scale axis=123 |
transp |
add mode=p ${SOURCES[0]} |
add mode=p ${SOURCES[1]} |
transp |
smooth rect2=100 repeat=3 |
put label1=x label2=t unit1=km unit2=s |
spray axis=3 n=2 o=0 d=1 |
transp plane=23
''' % par)
Result(mask,
'window n2=1 | transp|' + fdmod.dgrey('',par))
def dip(dip,img,par):
Flow( dip,img,'dip rect1=40 rect2=40 order=3 liter=100 verb=y ')
Result(dip,fdmod.cgrey('color=j wantscalebar=n',par))
def psang(x,img,dip,vpvs,tag,par):
#dip angle at cig location x
|
def dipline1(mod,s1,s2,e1,e2,vi,vt,n1,o1,d1,n2,o2,d2):
min1=o1
max1=o1+(n1-1)*d1
min2=o2
max2=o2+(n2-1)*d2
ra = (e1-s1)/(e2-s2)
vels = "%s,%s,%s" %(vi,vt,vt)
drvs = "%s,%s" %(tan(ra),tan(ra))
dim1 = 'd1=%g o1=%g n1=%d' % (d2,o2,n2)
dim2 = 'd2=%g o2=%g n2=%d' % (d1,o1,n1)
Flow(mod+'lay2',None,
'''
spike nsp=4 mag=%g,%g,%g,%g
n1=4 n2=1 k1=1,2,3,4 |
put n1=2 n2=2 |
spline %s fp=%s
'''%(min2,min1,max2,max1,dim1,drvs))
Flow(mod+'lay1',None,
'''
spike nsp=4 mag=%g,%g,%g,%g
n1=4 n2=1 k1=1,2,3,4 |
put n1=2 n2=2 |
spline %s fp=%s
'''%(s2,s1,e2,e1,dim1,drvs))
Flow( mod+'layers',[mod+'lay1',mod+'lay2'],'cat axis=2 ${SOURCES[1:2]}')
Flow(mod,mod+'layers',
'''
unif2 v00=%s n1=%d d1=%g o1=%g
''' % (vels,n1,d1,o1) )
| Flow( dip+'-one',dip,'window n2=1 min2=%g'%x)
#vpvs ratio at cig location x
Flow('vratioPP',vpvs,'window n3=1 f3=0 n2=1 min2=%g'%x)
Flow('vratioPS',vpvs,'window n3=1 f3=1 n2=1 min2=%g'%x)
Flow('vratioSP',vpvs,'window n3=1 f3=2 n2=1 min2=%g'%x)
Flow('vratioSS',vpvs,'window n3=1 f3=3 n2=1 min2=%g'%x)
nhx=200
nhz=0
nht=0
wefd.elaps('S'+tag,
img+tag+'_ds',
img+tag+'_dr',
nhx,nhz,nht,
dip+'-one',x,par) | identifier_body |
cfg.rs | macro_rules! cfg_feature {
(
#![$meta:meta]
$($item:item)*
) => {
$(
#[cfg($meta)]
#[cfg_attr(docsrs, doc(cfg($meta)))]
$item
)*
}
}
macro_rules! cfg_proto {
($($item:item)*) => {
cfg_feature! {
#![all(
any(feature = "http1", feature = "http2"),
any(feature = "client", feature = "server"),
)]
$($item)*
}
}
}
cfg_proto! {
macro_rules! cfg_client {
($($item:item)*) => {
cfg_feature! {
#![feature = "client"]
$($item)*
}
}
}
macro_rules! cfg_server {
($($item:item)*) => {
cfg_feature! {
#![feature = "server"]
$($item)*
} | }
}
} | random_line_split | |
lib.rs | /*!
Tetris game engine.
*/
extern crate rand;
mod bot;
pub use self::bot::{Weights, PlayI, Play};
mod bag;
pub use self::bag::{Bag, OfficialBag, BestBag, WorstBag};
mod input;
pub use self::input::{Clock, Input};
mod pt;
pub use self::pt::Point;
mod piece;
pub use self::piece::{Piece, Sprite};
mod rot;
pub use self::rot::Rot;
mod srs; | pub use self::srs::{SrsData, srs_cw, srs_ccw, srs_data_cw, srs_data_ccw};
mod player;
pub use self::player::Player;
mod well;
pub use self::well::{Well, Line, ParseWellError, MAX_WIDTH, MAX_HEIGHT};
mod tile;
pub use self::tile::{Tile, TileTy, TILE_BG0, TILE_BG1, TILE_BG2};
mod scene;
pub use self::scene::{Scene};
mod state;
pub use self::state::{State, test_player, trace_down};
mod rules;
pub use self::rules::{Rules, TheRules}; | random_line_split | |
Invitations.page.tsx | import React from "react"
import { Button, TextArea, Form, Input, Field } from "@fider/components"
import { actions, notify, Failure, Fider } from "@fider/services"
import { AdminBasePage } from "../components/AdminBasePage"
interface InvitationsPageState {
subject: string
message: string
recipients: string[]
numOfRecipients: number
rawRecipients: string
error?: Failure
}
export default class InvitationsPage extends AdminBasePage<any, InvitationsPageState> {
public id = "p-admin-invitations"
public name = "invitations"
public title = "Invitations"
public subtitle = "Invite people to share their feedback"
| (props: any) {
super(props)
this.state = {
subject: `[${Fider.session.tenant.name}] We would like to hear from you!`,
message: `Hi,
We are inviting you to join the ${Fider.session.tenant.name} feedback site, a place where you can vote, discuss and share your ideas and thoughts on how to improve our services!
Click the link below to join!
%invite%
Regards,
${Fider.session.user.name} (${Fider.session.tenant.name})`,
recipients: [],
numOfRecipients: 0,
rawRecipients: "",
}
}
private setRecipients = (rawRecipients: string) => {
const recipients = rawRecipients.split(/\n|;|,|\s/gm).filter((x) => !!x)
this.setState({ rawRecipients, recipients, numOfRecipients: recipients.length })
}
private sendSample = async () => {
const result = await actions.sendSampleInvite(this.state.subject, this.state.message)
if (result.ok) {
notify.success(
<span>
An email message was sent to <strong>{Fider.session.user.email}</strong>
</span>
)
}
this.setState({ error: result.error })
}
private sendInvites = async () => {
const result = await actions.sendInvites(this.state.subject, this.state.message, this.state.recipients)
if (result.ok) {
notify.success("Your invites have been sent.")
this.setState({ rawRecipients: "", numOfRecipients: 0, recipients: [], error: undefined })
} else {
this.setState({ error: result.error })
}
}
private setSubject = (subject: string): void => {
this.setState({ subject })
}
private setMessage = (message: string): void => {
this.setState({ message })
}
public content() {
return (
<Form error={this.state.error}>
<TextArea
field="recipients"
label="Send invitations to"
placeholder="james@example.com; mary@example.com"
minRows={1}
value={this.state.rawRecipients}
onChange={this.setRecipients}
>
<div className="text-muted">
<p>
Input the list of all email addresses you wish to invite. Separate each address with either <strong>semicolon</strong>, <strong>comma</strong>,{" "}
<strong>whitespace</strong> or <strong>line break</strong>.
</p>
<p>You can send this invite to a maximum of 30 recipients each time.</p>
</div>
</TextArea>
<Input field="subject" label="Subject" value={this.state.subject} maxLength={70} onChange={this.setSubject}>
<p className="text-muted">This is the subject that will be used on the invitation email. Keep it short and sweet.</p>
</Input>
<TextArea field="message" label="Message" minRows={8} value={this.state.message} onChange={this.setMessage}>
<div className="text-muted">
<p>
This is the content of the invite. Be polite and explain what this invite is for, otherwise there's a high change people will ignore your
message.
</p>
<p>
You're allowed to write whatever you want as long as you include the invitation link placeholder named <strong>%invite%</strong>.
</p>
</div>
</TextArea>
<Field label="Sample Invite">
{Fider.session.user.email ? (
<Button onClick={this.sendSample}>Send a sample email to {Fider.session.user.email}</Button>
) : (
<Button disabled={true}>Your profile doesn't have an email</Button>
)}
</Field>
<Field label="Confirmation">
<p className="text-muted">Whenever you're ready, click the following button to send out these invites.</p>
<Button onClick={this.sendInvites} variant="primary" disabled={this.state.numOfRecipients === 0}>
Send {this.state.numOfRecipients} {this.state.numOfRecipients === 1 ? "invite" : "invites"}
</Button>
</Field>
</Form>
)
}
}
| constructor | identifier_name |
Invitations.page.tsx | import React from "react"
import { Button, TextArea, Form, Input, Field } from "@fider/components"
import { actions, notify, Failure, Fider } from "@fider/services"
import { AdminBasePage } from "../components/AdminBasePage"
interface InvitationsPageState {
subject: string
message: string
recipients: string[]
numOfRecipients: number
rawRecipients: string
error?: Failure
}
export default class InvitationsPage extends AdminBasePage<any, InvitationsPageState> {
public id = "p-admin-invitations"
public name = "invitations"
public title = "Invitations"
public subtitle = "Invite people to share their feedback"
constructor(props: any) |
private setRecipients = (rawRecipients: string) => {
const recipients = rawRecipients.split(/\n|;|,|\s/gm).filter((x) => !!x)
this.setState({ rawRecipients, recipients, numOfRecipients: recipients.length })
}
private sendSample = async () => {
const result = await actions.sendSampleInvite(this.state.subject, this.state.message)
if (result.ok) {
notify.success(
<span>
An email message was sent to <strong>{Fider.session.user.email}</strong>
</span>
)
}
this.setState({ error: result.error })
}
private sendInvites = async () => {
const result = await actions.sendInvites(this.state.subject, this.state.message, this.state.recipients)
if (result.ok) {
notify.success("Your invites have been sent.")
this.setState({ rawRecipients: "", numOfRecipients: 0, recipients: [], error: undefined })
} else {
this.setState({ error: result.error })
}
}
private setSubject = (subject: string): void => {
this.setState({ subject })
}
private setMessage = (message: string): void => {
this.setState({ message })
}
public content() {
return (
<Form error={this.state.error}>
<TextArea
field="recipients"
label="Send invitations to"
placeholder="james@example.com; mary@example.com"
minRows={1}
value={this.state.rawRecipients}
onChange={this.setRecipients}
>
<div className="text-muted">
<p>
Input the list of all email addresses you wish to invite. Separate each address with either <strong>semicolon</strong>, <strong>comma</strong>,{" "}
<strong>whitespace</strong> or <strong>line break</strong>.
</p>
<p>You can send this invite to a maximum of 30 recipients each time.</p>
</div>
</TextArea>
<Input field="subject" label="Subject" value={this.state.subject} maxLength={70} onChange={this.setSubject}>
<p className="text-muted">This is the subject that will be used on the invitation email. Keep it short and sweet.</p>
</Input>
<TextArea field="message" label="Message" minRows={8} value={this.state.message} onChange={this.setMessage}>
<div className="text-muted">
<p>
This is the content of the invite. Be polite and explain what this invite is for, otherwise there's a high change people will ignore your
message.
</p>
<p>
You're allowed to write whatever you want as long as you include the invitation link placeholder named <strong>%invite%</strong>.
</p>
</div>
</TextArea>
<Field label="Sample Invite">
{Fider.session.user.email ? (
<Button onClick={this.sendSample}>Send a sample email to {Fider.session.user.email}</Button>
) : (
<Button disabled={true}>Your profile doesn't have an email</Button>
)}
</Field>
<Field label="Confirmation">
<p className="text-muted">Whenever you're ready, click the following button to send out these invites.</p>
<Button onClick={this.sendInvites} variant="primary" disabled={this.state.numOfRecipients === 0}>
Send {this.state.numOfRecipients} {this.state.numOfRecipients === 1 ? "invite" : "invites"}
</Button>
</Field>
</Form>
)
}
}
| {
super(props)
this.state = {
subject: `[${Fider.session.tenant.name}] We would like to hear from you!`,
message: `Hi,
We are inviting you to join the ${Fider.session.tenant.name} feedback site, a place where you can vote, discuss and share your ideas and thoughts on how to improve our services!
Click the link below to join!
%invite%
Regards,
${Fider.session.user.name} (${Fider.session.tenant.name})`,
recipients: [],
numOfRecipients: 0,
rawRecipients: "",
}
} | identifier_body |
Invitations.page.tsx | import React from "react"
import { Button, TextArea, Form, Input, Field } from "@fider/components"
import { actions, notify, Failure, Fider } from "@fider/services"
import { AdminBasePage } from "../components/AdminBasePage"
interface InvitationsPageState {
subject: string
message: string
recipients: string[]
numOfRecipients: number
rawRecipients: string
error?: Failure
}
export default class InvitationsPage extends AdminBasePage<any, InvitationsPageState> {
public id = "p-admin-invitations"
public name = "invitations"
public title = "Invitations"
public subtitle = "Invite people to share their feedback"
constructor(props: any) {
super(props)
this.state = {
subject: `[${Fider.session.tenant.name}] We would like to hear from you!`,
message: `Hi,
We are inviting you to join the ${Fider.session.tenant.name} feedback site, a place where you can vote, discuss and share your ideas and thoughts on how to improve our services!
Click the link below to join!
%invite%
Regards,
${Fider.session.user.name} (${Fider.session.tenant.name})`,
recipients: [],
numOfRecipients: 0,
rawRecipients: "",
}
}
private setRecipients = (rawRecipients: string) => {
const recipients = rawRecipients.split(/\n|;|,|\s/gm).filter((x) => !!x)
this.setState({ rawRecipients, recipients, numOfRecipients: recipients.length })
}
private sendSample = async () => {
const result = await actions.sendSampleInvite(this.state.subject, this.state.message)
if (result.ok) {
notify.success(
<span>
An email message was sent to <strong>{Fider.session.user.email}</strong>
</span>
)
}
this.setState({ error: result.error })
}
private sendInvites = async () => {
const result = await actions.sendInvites(this.state.subject, this.state.message, this.state.recipients)
if (result.ok) {
notify.success("Your invites have been sent.")
this.setState({ rawRecipients: "", numOfRecipients: 0, recipients: [], error: undefined })
} else {
this.setState({ error: result.error })
}
}
private setSubject = (subject: string): void => {
this.setState({ subject })
}
private setMessage = (message: string): void => { |
public content() {
return (
<Form error={this.state.error}>
<TextArea
field="recipients"
label="Send invitations to"
placeholder="james@example.com; mary@example.com"
minRows={1}
value={this.state.rawRecipients}
onChange={this.setRecipients}
>
<div className="text-muted">
<p>
Input the list of all email addresses you wish to invite. Separate each address with either <strong>semicolon</strong>, <strong>comma</strong>,{" "}
<strong>whitespace</strong> or <strong>line break</strong>.
</p>
<p>You can send this invite to a maximum of 30 recipients each time.</p>
</div>
</TextArea>
<Input field="subject" label="Subject" value={this.state.subject} maxLength={70} onChange={this.setSubject}>
<p className="text-muted">This is the subject that will be used on the invitation email. Keep it short and sweet.</p>
</Input>
<TextArea field="message" label="Message" minRows={8} value={this.state.message} onChange={this.setMessage}>
<div className="text-muted">
<p>
This is the content of the invite. Be polite and explain what this invite is for, otherwise there's a high change people will ignore your
message.
</p>
<p>
You're allowed to write whatever you want as long as you include the invitation link placeholder named <strong>%invite%</strong>.
</p>
</div>
</TextArea>
<Field label="Sample Invite">
{Fider.session.user.email ? (
<Button onClick={this.sendSample}>Send a sample email to {Fider.session.user.email}</Button>
) : (
<Button disabled={true}>Your profile doesn't have an email</Button>
)}
</Field>
<Field label="Confirmation">
<p className="text-muted">Whenever you're ready, click the following button to send out these invites.</p>
<Button onClick={this.sendInvites} variant="primary" disabled={this.state.numOfRecipients === 0}>
Send {this.state.numOfRecipients} {this.state.numOfRecipients === 1 ? "invite" : "invites"}
</Button>
</Field>
</Form>
)
}
} | this.setState({ message })
} | random_line_split |
Invitations.page.tsx | import React from "react"
import { Button, TextArea, Form, Input, Field } from "@fider/components"
import { actions, notify, Failure, Fider } from "@fider/services"
import { AdminBasePage } from "../components/AdminBasePage"
interface InvitationsPageState {
subject: string
message: string
recipients: string[]
numOfRecipients: number
rawRecipients: string
error?: Failure
}
export default class InvitationsPage extends AdminBasePage<any, InvitationsPageState> {
public id = "p-admin-invitations"
public name = "invitations"
public title = "Invitations"
public subtitle = "Invite people to share their feedback"
constructor(props: any) {
super(props)
this.state = {
subject: `[${Fider.session.tenant.name}] We would like to hear from you!`,
message: `Hi,
We are inviting you to join the ${Fider.session.tenant.name} feedback site, a place where you can vote, discuss and share your ideas and thoughts on how to improve our services!
Click the link below to join!
%invite%
Regards,
${Fider.session.user.name} (${Fider.session.tenant.name})`,
recipients: [],
numOfRecipients: 0,
rawRecipients: "",
}
}
private setRecipients = (rawRecipients: string) => {
const recipients = rawRecipients.split(/\n|;|,|\s/gm).filter((x) => !!x)
this.setState({ rawRecipients, recipients, numOfRecipients: recipients.length })
}
private sendSample = async () => {
const result = await actions.sendSampleInvite(this.state.subject, this.state.message)
if (result.ok) {
notify.success(
<span>
An email message was sent to <strong>{Fider.session.user.email}</strong>
</span>
)
}
this.setState({ error: result.error })
}
private sendInvites = async () => {
const result = await actions.sendInvites(this.state.subject, this.state.message, this.state.recipients)
if (result.ok) | else {
this.setState({ error: result.error })
}
}
private setSubject = (subject: string): void => {
this.setState({ subject })
}
private setMessage = (message: string): void => {
this.setState({ message })
}
public content() {
return (
<Form error={this.state.error}>
<TextArea
field="recipients"
label="Send invitations to"
placeholder="james@example.com; mary@example.com"
minRows={1}
value={this.state.rawRecipients}
onChange={this.setRecipients}
>
<div className="text-muted">
<p>
Input the list of all email addresses you wish to invite. Separate each address with either <strong>semicolon</strong>, <strong>comma</strong>,{" "}
<strong>whitespace</strong> or <strong>line break</strong>.
</p>
<p>You can send this invite to a maximum of 30 recipients each time.</p>
</div>
</TextArea>
<Input field="subject" label="Subject" value={this.state.subject} maxLength={70} onChange={this.setSubject}>
<p className="text-muted">This is the subject that will be used on the invitation email. Keep it short and sweet.</p>
</Input>
<TextArea field="message" label="Message" minRows={8} value={this.state.message} onChange={this.setMessage}>
<div className="text-muted">
<p>
This is the content of the invite. Be polite and explain what this invite is for, otherwise there's a high change people will ignore your
message.
</p>
<p>
You're allowed to write whatever you want as long as you include the invitation link placeholder named <strong>%invite%</strong>.
</p>
</div>
</TextArea>
<Field label="Sample Invite">
{Fider.session.user.email ? (
<Button onClick={this.sendSample}>Send a sample email to {Fider.session.user.email}</Button>
) : (
<Button disabled={true}>Your profile doesn't have an email</Button>
)}
</Field>
<Field label="Confirmation">
<p className="text-muted">Whenever you're ready, click the following button to send out these invites.</p>
<Button onClick={this.sendInvites} variant="primary" disabled={this.state.numOfRecipients === 0}>
Send {this.state.numOfRecipients} {this.state.numOfRecipients === 1 ? "invite" : "invites"}
</Button>
</Field>
</Form>
)
}
}
| {
notify.success("Your invites have been sent.")
this.setState({ rawRecipients: "", numOfRecipients: 0, recipients: [], error: undefined })
} | conditional_block |
urls.py | from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
import api, foxycart
urlpatterns = patterns('',
url(r'^$', TemplateView.as_view(template_name='index.html')),
url(r'^review/', TemplateView.as_view(template_name='base.html')),
url(r'^feedback/', TemplateView.as_view(template_name='feedback.html')),
# Examples:
# url(r'^$', 'review_app.views.home', name='home'),
# url(r'^review_app/', include('review_app.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)), | url(r'^api/', include('api.urls')),
url(r"^foxycart/", include('foxycart.urls')),
url(r"^foxycart/checkout", TemplateView.as_view(template_name='foxycart_checkout_template.html')),
url(r'^accounts/login/$', 'django.contrib.auth.views.login', {"template_name": "login.html"}),
url(r'^accounts/logout/$', 'django.contrib.auth.views.logout',
{"template_name": "base.html", "next_page": "/"}),
url(r"^protected/", 'review_app.views.protected_method', name="protected"),
url(r"^packages/", 'review_app.views.packages_method', name="packages"),
url(r'^package/(?P<package_id>[0-9]+)/$', 'review_app.views.package_method', name="package"),
) |
#url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) | random_line_split |
vga.rs | use core::mem;
use core::ptr::Unique;
use volatile::Volatile;
use libd7::{syscall, PhysAddr, VirtAddr};
const SCREEN_HEIGHT: usize = 25;
const SCREEN_WIDTH: usize = 80;
const HARDWARE_BUFFER_ADDR: u64 = 0xb8000;
const HARDWARE_BUFFER_SIZE: u64 = mem::size_of::<Buffer>() as u64;
/// Should be free to use. Check plan.md
const VIRTUAL_ADDR: VirtAddr = unsafe { VirtAddr::new_unsafe(0x10_0000_0000) };
/// A VGA color
#[allow(dead_code)]
#[repr(u8)]
pub enum Color {
Black = 0,
Blue = 1,
Green = 2,
Cyan = 3,
Red = 4,
Magenta = 5,
Brown = 6,
LightGray = 7,
DarkGray = 8,
LightBlue = 9,
LightGreen = 10,
LightCyan = 11,
LightRed = 12,
Pink = 13,
Yellow = 14,
White = 15,
}
/// Color of single cell, back- and foreground
#[derive(Clone, Copy)]
pub struct CellColor(u8);
impl CellColor {
pub const fn new(foreground: Color, background: Color) -> CellColor {
CellColor((background as u8) << 4 | (foreground as u8))
}
pub fn foreground(self) -> Color {
unsafe { mem::transmute::<u8, Color>(self.0 & 0xf) }
}
pub fn background(self) -> Color {
unsafe { mem::transmute::<u8, Color>((self.0 & 0xf0) >> 4) }
}
pub fn invert(self) -> CellColor {
CellColor::new(self.background(), self.foreground())
}
}
/// Character cell: one character and color in screen
#[derive(Clone, Copy)]
#[repr(C, packed)]
pub struct CharCell {
pub character: u8,
pub color: CellColor,
}
#[repr(C, packed)]
pub struct Buffer {
pub chars: [[Volatile<CharCell>; SCREEN_WIDTH]; SCREEN_HEIGHT],
}
impl Buffer {
/// Clear screen
pub fn clear(&mut self) {
let color = CellColor::new(Color::White, Color::Black);
for col in 0..SCREEN_WIDTH {
for row in 0..SCREEN_HEIGHT {
self.chars[row][col].write(CharCell {
character: b' ',
color,
});
}
}
}
}
/// # Safety
/// Must be only called once. Modifies kernel page tables.
pub unsafe fn get_hardware_buffer() -> Unique<Buffer> {
syscall::mmap_physical(
// Assumes 2MiB pages, so that 0xb8000 falls on the first page
PhysAddr::new(0),
VIRTUAL_ADDR,
HARDWARE_BUFFER_SIZE,
syscall::MemoryProtectionFlags::READ | syscall::MemoryProtectionFlags::WRITE,
) | .unwrap();
Unique::new_unchecked((VIRTUAL_ADDR + HARDWARE_BUFFER_ADDR).as_mut_ptr())
} | random_line_split | |
vga.rs | use core::mem;
use core::ptr::Unique;
use volatile::Volatile;
use libd7::{syscall, PhysAddr, VirtAddr};
const SCREEN_HEIGHT: usize = 25;
const SCREEN_WIDTH: usize = 80;
const HARDWARE_BUFFER_ADDR: u64 = 0xb8000;
const HARDWARE_BUFFER_SIZE: u64 = mem::size_of::<Buffer>() as u64;
/// Should be free to use. Check plan.md
const VIRTUAL_ADDR: VirtAddr = unsafe { VirtAddr::new_unsafe(0x10_0000_0000) };
/// A VGA color
#[allow(dead_code)]
#[repr(u8)]
pub enum Color {
Black = 0,
Blue = 1,
Green = 2,
Cyan = 3,
Red = 4,
Magenta = 5,
Brown = 6,
LightGray = 7,
DarkGray = 8,
LightBlue = 9,
LightGreen = 10,
LightCyan = 11,
LightRed = 12,
Pink = 13,
Yellow = 14,
White = 15,
}
/// Color of single cell, back- and foreground
#[derive(Clone, Copy)]
pub struct CellColor(u8);
impl CellColor {
pub const fn new(foreground: Color, background: Color) -> CellColor {
CellColor((background as u8) << 4 | (foreground as u8))
}
pub fn | (self) -> Color {
unsafe { mem::transmute::<u8, Color>(self.0 & 0xf) }
}
pub fn background(self) -> Color {
unsafe { mem::transmute::<u8, Color>((self.0 & 0xf0) >> 4) }
}
pub fn invert(self) -> CellColor {
CellColor::new(self.background(), self.foreground())
}
}
/// Character cell: one character and color in screen
#[derive(Clone, Copy)]
#[repr(C, packed)]
pub struct CharCell {
pub character: u8,
pub color: CellColor,
}
#[repr(C, packed)]
pub struct Buffer {
pub chars: [[Volatile<CharCell>; SCREEN_WIDTH]; SCREEN_HEIGHT],
}
impl Buffer {
/// Clear screen
pub fn clear(&mut self) {
let color = CellColor::new(Color::White, Color::Black);
for col in 0..SCREEN_WIDTH {
for row in 0..SCREEN_HEIGHT {
self.chars[row][col].write(CharCell {
character: b' ',
color,
});
}
}
}
}
/// # Safety
/// Must be only called once. Modifies kernel page tables.
pub unsafe fn get_hardware_buffer() -> Unique<Buffer> {
syscall::mmap_physical(
// Assumes 2MiB pages, so that 0xb8000 falls on the first page
PhysAddr::new(0),
VIRTUAL_ADDR,
HARDWARE_BUFFER_SIZE,
syscall::MemoryProtectionFlags::READ | syscall::MemoryProtectionFlags::WRITE,
)
.unwrap();
Unique::new_unchecked((VIRTUAL_ADDR + HARDWARE_BUFFER_ADDR).as_mut_ptr())
}
| foreground | identifier_name |
vga.rs | use core::mem;
use core::ptr::Unique;
use volatile::Volatile;
use libd7::{syscall, PhysAddr, VirtAddr};
const SCREEN_HEIGHT: usize = 25;
const SCREEN_WIDTH: usize = 80;
const HARDWARE_BUFFER_ADDR: u64 = 0xb8000;
const HARDWARE_BUFFER_SIZE: u64 = mem::size_of::<Buffer>() as u64;
/// Should be free to use. Check plan.md
const VIRTUAL_ADDR: VirtAddr = unsafe { VirtAddr::new_unsafe(0x10_0000_0000) };
/// A VGA color
#[allow(dead_code)]
#[repr(u8)]
pub enum Color {
Black = 0,
Blue = 1,
Green = 2,
Cyan = 3,
Red = 4,
Magenta = 5,
Brown = 6,
LightGray = 7,
DarkGray = 8,
LightBlue = 9,
LightGreen = 10,
LightCyan = 11,
LightRed = 12,
Pink = 13,
Yellow = 14,
White = 15,
}
/// Color of single cell, back- and foreground
#[derive(Clone, Copy)]
pub struct CellColor(u8);
impl CellColor {
pub const fn new(foreground: Color, background: Color) -> CellColor {
CellColor((background as u8) << 4 | (foreground as u8))
}
pub fn foreground(self) -> Color {
unsafe { mem::transmute::<u8, Color>(self.0 & 0xf) }
}
pub fn background(self) -> Color {
unsafe { mem::transmute::<u8, Color>((self.0 & 0xf0) >> 4) }
}
pub fn invert(self) -> CellColor {
CellColor::new(self.background(), self.foreground())
}
}
/// Character cell: one character and color in screen
#[derive(Clone, Copy)]
#[repr(C, packed)]
pub struct CharCell {
pub character: u8,
pub color: CellColor,
}
#[repr(C, packed)]
pub struct Buffer {
pub chars: [[Volatile<CharCell>; SCREEN_WIDTH]; SCREEN_HEIGHT],
}
impl Buffer {
/// Clear screen
pub fn clear(&mut self) {
let color = CellColor::new(Color::White, Color::Black);
for col in 0..SCREEN_WIDTH {
for row in 0..SCREEN_HEIGHT {
self.chars[row][col].write(CharCell {
character: b' ',
color,
});
}
}
}
}
/// # Safety
/// Must be only called once. Modifies kernel page tables.
pub unsafe fn get_hardware_buffer() -> Unique<Buffer> | {
syscall::mmap_physical(
// Assumes 2MiB pages, so that 0xb8000 falls on the first page
PhysAddr::new(0),
VIRTUAL_ADDR,
HARDWARE_BUFFER_SIZE,
syscall::MemoryProtectionFlags::READ | syscall::MemoryProtectionFlags::WRITE,
)
.unwrap();
Unique::new_unchecked((VIRTUAL_ADDR + HARDWARE_BUFFER_ADDR).as_mut_ptr())
} | identifier_body | |
user_profile.ts | import {badgesList} from '../views/badgesList';
import init_rpc from '../utils/rpc';
import {get_user_profile_login} from '../utils/github';
import {render} from '../utils/h';
import {BiEvents} from '../../common/bi.schema';
export default function route_user_profile(browser: typeof window.browser): void {
const rpc = init_rpc(browser);
const login = get_user_profile_login();
if (!login) {
rpc.report_bi(BiEvents.LOGIN_NOT_FOUND);
return;
}
const anchor = find_anchor_for_user_profile_info();
if (!anchor) {
rpc.report_bi(BiEvents.PLACEHOLDER_NOT_FOUND);
return;
}
if (is_there_a_previously_inserted_section()) {
return;
}
rpc.fetch_languages_for(login).then(languages => {
const badges = render(badgesList(login, languages));
const parent = anchor.parentElement;
parent && parent.insertBefore(badges, anchor);
});
}
function is_there_a_previously_inserted_section() |
function find_anchor_for_user_profile_info() {
const profileRoot = document.querySelector('[itemtype="http://schema.org/Person"]');
const h1 = profileRoot && profileRoot.querySelector('h1.vcard-names');
const candidate3 = h1 && h1.parentElement;
const candidate2 = candidate3 && candidate3.nextElementSibling;
const candidate1 = candidate2 && candidate2.nextElementSibling;
return candidate1 || candidate2 || candidate3;
}
| {
return document.getElementsByClassName('githubuserrank-extension-section').length > 0;
} | identifier_body |
user_profile.ts | import {badgesList} from '../views/badgesList'; | import {get_user_profile_login} from '../utils/github';
import {render} from '../utils/h';
import {BiEvents} from '../../common/bi.schema';
export default function route_user_profile(browser: typeof window.browser): void {
const rpc = init_rpc(browser);
const login = get_user_profile_login();
if (!login) {
rpc.report_bi(BiEvents.LOGIN_NOT_FOUND);
return;
}
const anchor = find_anchor_for_user_profile_info();
if (!anchor) {
rpc.report_bi(BiEvents.PLACEHOLDER_NOT_FOUND);
return;
}
if (is_there_a_previously_inserted_section()) {
return;
}
rpc.fetch_languages_for(login).then(languages => {
const badges = render(badgesList(login, languages));
const parent = anchor.parentElement;
parent && parent.insertBefore(badges, anchor);
});
}
function is_there_a_previously_inserted_section() {
return document.getElementsByClassName('githubuserrank-extension-section').length > 0;
}
function find_anchor_for_user_profile_info() {
const profileRoot = document.querySelector('[itemtype="http://schema.org/Person"]');
const h1 = profileRoot && profileRoot.querySelector('h1.vcard-names');
const candidate3 = h1 && h1.parentElement;
const candidate2 = candidate3 && candidate3.nextElementSibling;
const candidate1 = candidate2 && candidate2.nextElementSibling;
return candidate1 || candidate2 || candidate3;
} | import init_rpc from '../utils/rpc'; | random_line_split |
user_profile.ts | import {badgesList} from '../views/badgesList';
import init_rpc from '../utils/rpc';
import {get_user_profile_login} from '../utils/github';
import {render} from '../utils/h';
import {BiEvents} from '../../common/bi.schema';
export default function route_user_profile(browser: typeof window.browser): void {
const rpc = init_rpc(browser);
const login = get_user_profile_login();
if (!login) {
rpc.report_bi(BiEvents.LOGIN_NOT_FOUND);
return;
}
const anchor = find_anchor_for_user_profile_info();
if (!anchor) {
rpc.report_bi(BiEvents.PLACEHOLDER_NOT_FOUND);
return;
}
if (is_there_a_previously_inserted_section()) {
return;
}
rpc.fetch_languages_for(login).then(languages => {
const badges = render(badgesList(login, languages));
const parent = anchor.parentElement;
parent && parent.insertBefore(badges, anchor);
});
}
function | () {
return document.getElementsByClassName('githubuserrank-extension-section').length > 0;
}
function find_anchor_for_user_profile_info() {
const profileRoot = document.querySelector('[itemtype="http://schema.org/Person"]');
const h1 = profileRoot && profileRoot.querySelector('h1.vcard-names');
const candidate3 = h1 && h1.parentElement;
const candidate2 = candidate3 && candidate3.nextElementSibling;
const candidate1 = candidate2 && candidate2.nextElementSibling;
return candidate1 || candidate2 || candidate3;
}
| is_there_a_previously_inserted_section | identifier_name |
user_profile.ts | import {badgesList} from '../views/badgesList';
import init_rpc from '../utils/rpc';
import {get_user_profile_login} from '../utils/github';
import {render} from '../utils/h';
import {BiEvents} from '../../common/bi.schema';
export default function route_user_profile(browser: typeof window.browser): void {
const rpc = init_rpc(browser);
const login = get_user_profile_login();
if (!login) {
rpc.report_bi(BiEvents.LOGIN_NOT_FOUND);
return;
}
const anchor = find_anchor_for_user_profile_info();
if (!anchor) |
if (is_there_a_previously_inserted_section()) {
return;
}
rpc.fetch_languages_for(login).then(languages => {
const badges = render(badgesList(login, languages));
const parent = anchor.parentElement;
parent && parent.insertBefore(badges, anchor);
});
}
function is_there_a_previously_inserted_section() {
return document.getElementsByClassName('githubuserrank-extension-section').length > 0;
}
function find_anchor_for_user_profile_info() {
const profileRoot = document.querySelector('[itemtype="http://schema.org/Person"]');
const h1 = profileRoot && profileRoot.querySelector('h1.vcard-names');
const candidate3 = h1 && h1.parentElement;
const candidate2 = candidate3 && candidate3.nextElementSibling;
const candidate1 = candidate2 && candidate2.nextElementSibling;
return candidate1 || candidate2 || candidate3;
}
| {
rpc.report_bi(BiEvents.PLACEHOLDER_NOT_FOUND);
return;
} | conditional_block |
ConfigurationDialog.tsx | import React, { Component } from 'react';
import { observer } from 'mobx-react';
import classnames from 'classnames';
import { Input } from 'react-polymorph/lib/components/Input';
import { defineMessages, intlShape, FormattedHTMLMessage } from 'react-intl';
import vjf from 'mobx-react-form/lib/validators/VJF';
import SVGInline from 'react-svg-inline';
import { PopOver } from 'react-polymorph/lib/components/PopOver';
import { PasswordInput } from '../../widgets/forms/PasswordInput';
import WalletRestoreDialog from './widgets/WalletRestoreDialog';
import styles from './ConfigurationDialog.scss';
import ReactToolboxMobxForm, {
handleFormErrors,
} from '../../../utils/ReactToolboxMobxForm';
import {
isValidWalletName,
isValidSpendingPassword,
isValidRepeatPassword,
} from '../../../utils/validations';
import { submitOnEnter } from '../../../utils/form';
import globalMessages from '../../../i18n/global-messages';
import LocalizableError from '../../../i18n/LocalizableError';
import { FORM_VALIDATION_DEBOUNCE_WAIT } from '../../../config/timingConfig';
// @ts-ignore ts-migrate(2307) FIXME: Cannot find module '../../../assets/images/info-ic... Remove this comment to see the full error message
import infoIconInline from '../../../assets/images/info-icon.inline.svg';
import LoadingSpinner from '../../widgets/LoadingSpinner';
const messages = defineMessages({
description1: {
id: 'wallet.restore.dialog.step.configuration.description1',
defaultMessage:
'!!!Name your restored wallet and set a spending password to keep your wallet secure.',
description: 'Description1 for Configuration Step',
},
description2: {
id: 'wallet.restore.dialog.step.configuration.description2',
defaultMessage:
'!!!Wallet names and spending passwords are only stored locally and are not stored on the blockchain. You can give your restored wallet a new name and set a new spending password, you don’t need to match the wallet name and spending password you were using before. <b>Only the recovery phrase from your original wallet is needed to restore a wallet.</b>',
description: 'Description2 for Configuration Step',
},
walletNameLabel: {
id: 'wallet.restore.dialog.step.configuration.input.walletName.label',
defaultMessage: '!!!Wallet name',
description: 'Label for Wallet Name Input',
},
walletNamePlaceholder: {
id: 'wallet.restore.dialog.step.configuration.input.walletName.placeholder',
defaultMessage: '!!!Name the wallet you are restoring',
description: 'Placeholder for Wallet Name Input',
},
spendingPasswordLabel: {
id: 'wallet.restore.dialog.step.configuration.input.spendingPassword.label',
defaultMessage: '!!!Enter password',
description:
'Label for the "Wallet password" input in the wallet restore dialog.',
},
repeatPasswordLabel: {
id: 'wallet.restore.dialog.step.configuration.input.repeatPassword.label',
defaultMessage: '!!!Repeat password',
description:
'Label for the "Repeat password" input in the wallet restore dialog.',
},
passwordFieldsPlaceholder: {
id:
'wallet.restore.dialog.step.configuration.input.passwordFields.placeholder',
defaultMessage: '!!!Password',
description:
'Placeholder for the "Password" inputs in the wallet restore dialog.',
},
continueButtonLabel: {
id: 'wallet.restore.dialog.step.configuration.continueButtonLabel',
defaultMessage: '!!!Continue',
description: 'Placeholder for the dialog "Continue" button',
},
passwordTooltip: {
id: 'wallet.dialog.passwordTooltip',
defaultMessage:
'!!!It is really good to use Password Manager apps to improve security. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris mattis diam non nulla sollicitudin, ac ultrices purus luctus.',
description: 'Tooltip for the password input in the create wallet dialog.',
},
});
type Props = {
isSubmitting: boolean;
onContinue: (...args: Array<any>) => any;
onClose: (...args: Array<any>) => any;
onBack: (...args: Array<any>) => any;
onChange: (...args: Array<any>) => any;
walletName: string;
spendingPassword: string;
repeatPassword: string;
error?: LocalizableError | null | undefined;
currentLocale: string;
};
interface FormFields {
walletName: string;
spendingPassword: string;
repeatPassword: string;
}
@observer
class ConfigurationDialog extends Component<Props> {
static contextTypes = {
intl: intlShape.isRequired,
};
static defaultProps = {
error: null,
};
componentDidUpdate() {
if (this.props.error) {
| }
form = new ReactToolboxMobxForm<FormFields>(
{
fields: {
walletName: {
label: this.context.intl.formatMessage(messages.walletNameLabel),
placeholder: this.context.intl.formatMessage(
messages.walletNamePlaceholder
),
value: this.props.walletName,
validators: [
({ field }) => [
isValidWalletName(field.value),
this.context.intl.formatMessage(globalMessages.invalidWalletName),
],
],
hooks: {
onChange: this.props.onChange.bind(this, 'walletName'),
},
},
spendingPassword: {
type: 'password',
label: this.context.intl.formatMessage(
messages.spendingPasswordLabel
),
placeholder: this.context.intl.formatMessage(
messages.passwordFieldsPlaceholder
),
value: this.props.spendingPassword,
validators: [
({ field, form }) => {
const repeatPasswordField = form.$('repeatPassword');
const isRepeatPasswordFieldSet =
repeatPasswordField.value.length > 0;
repeatPasswordField.validate({
showErrors: isRepeatPasswordFieldSet,
});
return [
isValidSpendingPassword(field.value),
this.context.intl.formatMessage(
globalMessages.invalidSpendingPassword
),
];
},
],
hooks: {
onChange: this.props.onChange.bind(this, 'spendingPassword'),
},
},
repeatPassword: {
type: 'password',
label: this.context.intl.formatMessage(messages.repeatPasswordLabel),
placeholder: this.context.intl.formatMessage(
messages.passwordFieldsPlaceholder
),
value: this.props.repeatPassword,
validators: [
({ field, form }) => {
const spendingPassword = form.$('spendingPassword').value;
return [
isValidRepeatPassword(spendingPassword, field.value),
this.context.intl.formatMessage(
globalMessages.invalidRepeatPassword
),
];
},
],
hooks: {
onChange: this.props.onChange.bind(this, 'repeatPassword'),
},
},
},
},
{
plugins: {
vjf: vjf(),
},
options: {
validateOnChange: true,
validationDebounceWait: FORM_VALIDATION_DEBOUNCE_WAIT,
},
}
);
submit = () => {
this.form.submit({
onSuccess: (form) => {
const { onContinue } = this.props;
const { walletName, spendingPassword } = form.values();
onContinue(walletName, spendingPassword);
},
onError: () =>
handleFormErrors('.ConfigurationDialog_error', {
focusElement: true,
}),
});
};
handleSubmitOnEnter = submitOnEnter.bind(this, this.submit);
resetForm = () => {
const { form } = this;
// Cancel all debounced field validations
form.each((field) => {
field.debouncedValidation.cancel();
});
form.reset();
form.showErrors(false);
};
render() {
const { intl } = this.context;
const { onClose, onBack, error, isSubmitting, currentLocale } = this.props;
const { form } = this;
const walletNameField = form.$('walletName');
const spendingPasswordField = form.$('spendingPassword');
const repeatPasswordField = form.$('repeatPassword');
const walletNameFieldClasses = classnames([
styles.walletName,
'walletName',
]);
const spendingPasswordClasses = classnames([
styles.spendingPasswordField,
currentLocale === 'ja-JP' ? styles.jpLangTooltipIcon : '',
]);
const buttonLabel = !isSubmitting ? (
intl.formatMessage(messages.continueButtonLabel)
) : (
<LoadingSpinner />
);
const canSubmit = !isSubmitting && form.isValid;
return (
<WalletRestoreDialog
// @ts-ignore ts-migrate(2769) FIXME: No overload matches this call.
className={styles.dialogComponent}
stepNumber={2}
actions={[
{
disabled: !canSubmit,
primary: true,
label: buttonLabel,
onClick: this.submit,
},
]}
onClose={onClose}
onBack={onBack}
>
<div className={styles.component}>
<p>{intl.formatMessage(messages.description1)}</p>
<p>
<FormattedHTMLMessage {...messages.description2} />
</p>
<Input
className={walletNameFieldClasses}
onKeyPress={this.handleSubmitOnEnter}
{...walletNameField.bind()}
error={walletNameField.error}
/>
<div>
<div className={styles.spendingPasswordFields}>
<div className={spendingPasswordClasses}>
<PasswordInput
className="spendingPassword"
onKeyPress={this.handleSubmitOnEnter}
{...spendingPasswordField.bind()}
/>
<PopOver
content={
<FormattedHTMLMessage {...messages.passwordTooltip} />
}
key="tooltip"
>
<SVGInline svg={infoIconInline} className={styles.infoIcon} />
</PopOver>
</div>
<div className={styles.spendingPasswordField}>
<PasswordInput
className="repeatPassword"
onKeyPress={this.handleSubmitOnEnter}
{...repeatPasswordField.bind()}
repeatPassword={spendingPasswordField.value}
isPasswordRepeat
/>
</div>
</div>
<div className={styles.passwordInstructions}>
<FormattedHTMLMessage {...globalMessages.passwordInstructions} />
</div>
</div>
{error && <p className={styles.error}>{intl.formatMessage(error)}</p>}
</div>
</WalletRestoreDialog>
);
}
}
export default ConfigurationDialog;
| handleFormErrors('.ConfigurationDialog_error');
}
| conditional_block |
ConfigurationDialog.tsx | import React, { Component } from 'react';
import { observer } from 'mobx-react';
import classnames from 'classnames';
import { Input } from 'react-polymorph/lib/components/Input';
import { defineMessages, intlShape, FormattedHTMLMessage } from 'react-intl';
import vjf from 'mobx-react-form/lib/validators/VJF';
import SVGInline from 'react-svg-inline';
import { PopOver } from 'react-polymorph/lib/components/PopOver';
import { PasswordInput } from '../../widgets/forms/PasswordInput';
import WalletRestoreDialog from './widgets/WalletRestoreDialog';
import styles from './ConfigurationDialog.scss';
import ReactToolboxMobxForm, {
handleFormErrors,
} from '../../../utils/ReactToolboxMobxForm';
import {
isValidWalletName,
isValidSpendingPassword,
isValidRepeatPassword,
} from '../../../utils/validations';
import { submitOnEnter } from '../../../utils/form';
import globalMessages from '../../../i18n/global-messages'; | import infoIconInline from '../../../assets/images/info-icon.inline.svg';
import LoadingSpinner from '../../widgets/LoadingSpinner';
const messages = defineMessages({
description1: {
id: 'wallet.restore.dialog.step.configuration.description1',
defaultMessage:
'!!!Name your restored wallet and set a spending password to keep your wallet secure.',
description: 'Description1 for Configuration Step',
},
description2: {
id: 'wallet.restore.dialog.step.configuration.description2',
defaultMessage:
'!!!Wallet names and spending passwords are only stored locally and are not stored on the blockchain. You can give your restored wallet a new name and set a new spending password, you don’t need to match the wallet name and spending password you were using before. <b>Only the recovery phrase from your original wallet is needed to restore a wallet.</b>',
description: 'Description2 for Configuration Step',
},
walletNameLabel: {
id: 'wallet.restore.dialog.step.configuration.input.walletName.label',
defaultMessage: '!!!Wallet name',
description: 'Label for Wallet Name Input',
},
walletNamePlaceholder: {
id: 'wallet.restore.dialog.step.configuration.input.walletName.placeholder',
defaultMessage: '!!!Name the wallet you are restoring',
description: 'Placeholder for Wallet Name Input',
},
spendingPasswordLabel: {
id: 'wallet.restore.dialog.step.configuration.input.spendingPassword.label',
defaultMessage: '!!!Enter password',
description:
'Label for the "Wallet password" input in the wallet restore dialog.',
},
repeatPasswordLabel: {
id: 'wallet.restore.dialog.step.configuration.input.repeatPassword.label',
defaultMessage: '!!!Repeat password',
description:
'Label for the "Repeat password" input in the wallet restore dialog.',
},
passwordFieldsPlaceholder: {
id:
'wallet.restore.dialog.step.configuration.input.passwordFields.placeholder',
defaultMessage: '!!!Password',
description:
'Placeholder for the "Password" inputs in the wallet restore dialog.',
},
continueButtonLabel: {
id: 'wallet.restore.dialog.step.configuration.continueButtonLabel',
defaultMessage: '!!!Continue',
description: 'Placeholder for the dialog "Continue" button',
},
passwordTooltip: {
id: 'wallet.dialog.passwordTooltip',
defaultMessage:
'!!!It is really good to use Password Manager apps to improve security. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris mattis diam non nulla sollicitudin, ac ultrices purus luctus.',
description: 'Tooltip for the password input in the create wallet dialog.',
},
});
type Props = {
isSubmitting: boolean;
onContinue: (...args: Array<any>) => any;
onClose: (...args: Array<any>) => any;
onBack: (...args: Array<any>) => any;
onChange: (...args: Array<any>) => any;
walletName: string;
spendingPassword: string;
repeatPassword: string;
error?: LocalizableError | null | undefined;
currentLocale: string;
};
interface FormFields {
walletName: string;
spendingPassword: string;
repeatPassword: string;
}
@observer
class ConfigurationDialog extends Component<Props> {
static contextTypes = {
intl: intlShape.isRequired,
};
static defaultProps = {
error: null,
};
componentDidUpdate() {
if (this.props.error) {
handleFormErrors('.ConfigurationDialog_error');
}
}
form = new ReactToolboxMobxForm<FormFields>(
{
fields: {
walletName: {
label: this.context.intl.formatMessage(messages.walletNameLabel),
placeholder: this.context.intl.formatMessage(
messages.walletNamePlaceholder
),
value: this.props.walletName,
validators: [
({ field }) => [
isValidWalletName(field.value),
this.context.intl.formatMessage(globalMessages.invalidWalletName),
],
],
hooks: {
onChange: this.props.onChange.bind(this, 'walletName'),
},
},
spendingPassword: {
type: 'password',
label: this.context.intl.formatMessage(
messages.spendingPasswordLabel
),
placeholder: this.context.intl.formatMessage(
messages.passwordFieldsPlaceholder
),
value: this.props.spendingPassword,
validators: [
({ field, form }) => {
const repeatPasswordField = form.$('repeatPassword');
const isRepeatPasswordFieldSet =
repeatPasswordField.value.length > 0;
repeatPasswordField.validate({
showErrors: isRepeatPasswordFieldSet,
});
return [
isValidSpendingPassword(field.value),
this.context.intl.formatMessage(
globalMessages.invalidSpendingPassword
),
];
},
],
hooks: {
onChange: this.props.onChange.bind(this, 'spendingPassword'),
},
},
repeatPassword: {
type: 'password',
label: this.context.intl.formatMessage(messages.repeatPasswordLabel),
placeholder: this.context.intl.formatMessage(
messages.passwordFieldsPlaceholder
),
value: this.props.repeatPassword,
validators: [
({ field, form }) => {
const spendingPassword = form.$('spendingPassword').value;
return [
isValidRepeatPassword(spendingPassword, field.value),
this.context.intl.formatMessage(
globalMessages.invalidRepeatPassword
),
];
},
],
hooks: {
onChange: this.props.onChange.bind(this, 'repeatPassword'),
},
},
},
},
{
plugins: {
vjf: vjf(),
},
options: {
validateOnChange: true,
validationDebounceWait: FORM_VALIDATION_DEBOUNCE_WAIT,
},
}
);
submit = () => {
this.form.submit({
onSuccess: (form) => {
const { onContinue } = this.props;
const { walletName, spendingPassword } = form.values();
onContinue(walletName, spendingPassword);
},
onError: () =>
handleFormErrors('.ConfigurationDialog_error', {
focusElement: true,
}),
});
};
handleSubmitOnEnter = submitOnEnter.bind(this, this.submit);
resetForm = () => {
const { form } = this;
// Cancel all debounced field validations
form.each((field) => {
field.debouncedValidation.cancel();
});
form.reset();
form.showErrors(false);
};
render() {
const { intl } = this.context;
const { onClose, onBack, error, isSubmitting, currentLocale } = this.props;
const { form } = this;
const walletNameField = form.$('walletName');
const spendingPasswordField = form.$('spendingPassword');
const repeatPasswordField = form.$('repeatPassword');
const walletNameFieldClasses = classnames([
styles.walletName,
'walletName',
]);
const spendingPasswordClasses = classnames([
styles.spendingPasswordField,
currentLocale === 'ja-JP' ? styles.jpLangTooltipIcon : '',
]);
const buttonLabel = !isSubmitting ? (
intl.formatMessage(messages.continueButtonLabel)
) : (
<LoadingSpinner />
);
const canSubmit = !isSubmitting && form.isValid;
return (
<WalletRestoreDialog
// @ts-ignore ts-migrate(2769) FIXME: No overload matches this call.
className={styles.dialogComponent}
stepNumber={2}
actions={[
{
disabled: !canSubmit,
primary: true,
label: buttonLabel,
onClick: this.submit,
},
]}
onClose={onClose}
onBack={onBack}
>
<div className={styles.component}>
<p>{intl.formatMessage(messages.description1)}</p>
<p>
<FormattedHTMLMessage {...messages.description2} />
</p>
<Input
className={walletNameFieldClasses}
onKeyPress={this.handleSubmitOnEnter}
{...walletNameField.bind()}
error={walletNameField.error}
/>
<div>
<div className={styles.spendingPasswordFields}>
<div className={spendingPasswordClasses}>
<PasswordInput
className="spendingPassword"
onKeyPress={this.handleSubmitOnEnter}
{...spendingPasswordField.bind()}
/>
<PopOver
content={
<FormattedHTMLMessage {...messages.passwordTooltip} />
}
key="tooltip"
>
<SVGInline svg={infoIconInline} className={styles.infoIcon} />
</PopOver>
</div>
<div className={styles.spendingPasswordField}>
<PasswordInput
className="repeatPassword"
onKeyPress={this.handleSubmitOnEnter}
{...repeatPasswordField.bind()}
repeatPassword={spendingPasswordField.value}
isPasswordRepeat
/>
</div>
</div>
<div className={styles.passwordInstructions}>
<FormattedHTMLMessage {...globalMessages.passwordInstructions} />
</div>
</div>
{error && <p className={styles.error}>{intl.formatMessage(error)}</p>}
</div>
</WalletRestoreDialog>
);
}
}
export default ConfigurationDialog; | import LocalizableError from '../../../i18n/LocalizableError';
import { FORM_VALIDATION_DEBOUNCE_WAIT } from '../../../config/timingConfig';
// @ts-ignore ts-migrate(2307) FIXME: Cannot find module '../../../assets/images/info-ic... Remove this comment to see the full error message | random_line_split |
ConfigurationDialog.tsx | import React, { Component } from 'react';
import { observer } from 'mobx-react';
import classnames from 'classnames';
import { Input } from 'react-polymorph/lib/components/Input';
import { defineMessages, intlShape, FormattedHTMLMessage } from 'react-intl';
import vjf from 'mobx-react-form/lib/validators/VJF';
import SVGInline from 'react-svg-inline';
import { PopOver } from 'react-polymorph/lib/components/PopOver';
import { PasswordInput } from '../../widgets/forms/PasswordInput';
import WalletRestoreDialog from './widgets/WalletRestoreDialog';
import styles from './ConfigurationDialog.scss';
import ReactToolboxMobxForm, {
handleFormErrors,
} from '../../../utils/ReactToolboxMobxForm';
import {
isValidWalletName,
isValidSpendingPassword,
isValidRepeatPassword,
} from '../../../utils/validations';
import { submitOnEnter } from '../../../utils/form';
import globalMessages from '../../../i18n/global-messages';
import LocalizableError from '../../../i18n/LocalizableError';
import { FORM_VALIDATION_DEBOUNCE_WAIT } from '../../../config/timingConfig';
// @ts-ignore ts-migrate(2307) FIXME: Cannot find module '../../../assets/images/info-ic... Remove this comment to see the full error message
import infoIconInline from '../../../assets/images/info-icon.inline.svg';
import LoadingSpinner from '../../widgets/LoadingSpinner';
const messages = defineMessages({
description1: {
id: 'wallet.restore.dialog.step.configuration.description1',
defaultMessage:
'!!!Name your restored wallet and set a spending password to keep your wallet secure.',
description: 'Description1 for Configuration Step',
},
description2: {
id: 'wallet.restore.dialog.step.configuration.description2',
defaultMessage:
'!!!Wallet names and spending passwords are only stored locally and are not stored on the blockchain. You can give your restored wallet a new name and set a new spending password, you don’t need to match the wallet name and spending password you were using before. <b>Only the recovery phrase from your original wallet is needed to restore a wallet.</b>',
description: 'Description2 for Configuration Step',
},
walletNameLabel: {
id: 'wallet.restore.dialog.step.configuration.input.walletName.label',
defaultMessage: '!!!Wallet name',
description: 'Label for Wallet Name Input',
},
walletNamePlaceholder: {
id: 'wallet.restore.dialog.step.configuration.input.walletName.placeholder',
defaultMessage: '!!!Name the wallet you are restoring',
description: 'Placeholder for Wallet Name Input',
},
spendingPasswordLabel: {
id: 'wallet.restore.dialog.step.configuration.input.spendingPassword.label',
defaultMessage: '!!!Enter password',
description:
'Label for the "Wallet password" input in the wallet restore dialog.',
},
repeatPasswordLabel: {
id: 'wallet.restore.dialog.step.configuration.input.repeatPassword.label',
defaultMessage: '!!!Repeat password',
description:
'Label for the "Repeat password" input in the wallet restore dialog.',
},
passwordFieldsPlaceholder: {
id:
'wallet.restore.dialog.step.configuration.input.passwordFields.placeholder',
defaultMessage: '!!!Password',
description:
'Placeholder for the "Password" inputs in the wallet restore dialog.',
},
continueButtonLabel: {
id: 'wallet.restore.dialog.step.configuration.continueButtonLabel',
defaultMessage: '!!!Continue',
description: 'Placeholder for the dialog "Continue" button',
},
passwordTooltip: {
id: 'wallet.dialog.passwordTooltip',
defaultMessage:
'!!!It is really good to use Password Manager apps to improve security. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris mattis diam non nulla sollicitudin, ac ultrices purus luctus.',
description: 'Tooltip for the password input in the create wallet dialog.',
},
});
type Props = {
isSubmitting: boolean;
onContinue: (...args: Array<any>) => any;
onClose: (...args: Array<any>) => any;
onBack: (...args: Array<any>) => any;
onChange: (...args: Array<any>) => any;
walletName: string;
spendingPassword: string;
repeatPassword: string;
error?: LocalizableError | null | undefined;
currentLocale: string;
};
interface FormFields {
walletName: string;
spendingPassword: string;
repeatPassword: string;
}
@observer
class ConfigurationDialog extends Component<Props> {
static contextTypes = {
intl: intlShape.isRequired,
};
static defaultProps = {
error: null,
};
componentDidUpdate() {
| form = new ReactToolboxMobxForm<FormFields>(
{
fields: {
walletName: {
label: this.context.intl.formatMessage(messages.walletNameLabel),
placeholder: this.context.intl.formatMessage(
messages.walletNamePlaceholder
),
value: this.props.walletName,
validators: [
({ field }) => [
isValidWalletName(field.value),
this.context.intl.formatMessage(globalMessages.invalidWalletName),
],
],
hooks: {
onChange: this.props.onChange.bind(this, 'walletName'),
},
},
spendingPassword: {
type: 'password',
label: this.context.intl.formatMessage(
messages.spendingPasswordLabel
),
placeholder: this.context.intl.formatMessage(
messages.passwordFieldsPlaceholder
),
value: this.props.spendingPassword,
validators: [
({ field, form }) => {
const repeatPasswordField = form.$('repeatPassword');
const isRepeatPasswordFieldSet =
repeatPasswordField.value.length > 0;
repeatPasswordField.validate({
showErrors: isRepeatPasswordFieldSet,
});
return [
isValidSpendingPassword(field.value),
this.context.intl.formatMessage(
globalMessages.invalidSpendingPassword
),
];
},
],
hooks: {
onChange: this.props.onChange.bind(this, 'spendingPassword'),
},
},
repeatPassword: {
type: 'password',
label: this.context.intl.formatMessage(messages.repeatPasswordLabel),
placeholder: this.context.intl.formatMessage(
messages.passwordFieldsPlaceholder
),
value: this.props.repeatPassword,
validators: [
({ field, form }) => {
const spendingPassword = form.$('spendingPassword').value;
return [
isValidRepeatPassword(spendingPassword, field.value),
this.context.intl.formatMessage(
globalMessages.invalidRepeatPassword
),
];
},
],
hooks: {
onChange: this.props.onChange.bind(this, 'repeatPassword'),
},
},
},
},
{
plugins: {
vjf: vjf(),
},
options: {
validateOnChange: true,
validationDebounceWait: FORM_VALIDATION_DEBOUNCE_WAIT,
},
}
);
submit = () => {
this.form.submit({
onSuccess: (form) => {
const { onContinue } = this.props;
const { walletName, spendingPassword } = form.values();
onContinue(walletName, spendingPassword);
},
onError: () =>
handleFormErrors('.ConfigurationDialog_error', {
focusElement: true,
}),
});
};
handleSubmitOnEnter = submitOnEnter.bind(this, this.submit);
resetForm = () => {
const { form } = this;
// Cancel all debounced field validations
form.each((field) => {
field.debouncedValidation.cancel();
});
form.reset();
form.showErrors(false);
};
render() {
const { intl } = this.context;
const { onClose, onBack, error, isSubmitting, currentLocale } = this.props;
const { form } = this;
const walletNameField = form.$('walletName');
const spendingPasswordField = form.$('spendingPassword');
const repeatPasswordField = form.$('repeatPassword');
const walletNameFieldClasses = classnames([
styles.walletName,
'walletName',
]);
const spendingPasswordClasses = classnames([
styles.spendingPasswordField,
currentLocale === 'ja-JP' ? styles.jpLangTooltipIcon : '',
]);
const buttonLabel = !isSubmitting ? (
intl.formatMessage(messages.continueButtonLabel)
) : (
<LoadingSpinner />
);
const canSubmit = !isSubmitting && form.isValid;
return (
<WalletRestoreDialog
// @ts-ignore ts-migrate(2769) FIXME: No overload matches this call.
className={styles.dialogComponent}
stepNumber={2}
actions={[
{
disabled: !canSubmit,
primary: true,
label: buttonLabel,
onClick: this.submit,
},
]}
onClose={onClose}
onBack={onBack}
>
<div className={styles.component}>
<p>{intl.formatMessage(messages.description1)}</p>
<p>
<FormattedHTMLMessage {...messages.description2} />
</p>
<Input
className={walletNameFieldClasses}
onKeyPress={this.handleSubmitOnEnter}
{...walletNameField.bind()}
error={walletNameField.error}
/>
<div>
<div className={styles.spendingPasswordFields}>
<div className={spendingPasswordClasses}>
<PasswordInput
className="spendingPassword"
onKeyPress={this.handleSubmitOnEnter}
{...spendingPasswordField.bind()}
/>
<PopOver
content={
<FormattedHTMLMessage {...messages.passwordTooltip} />
}
key="tooltip"
>
<SVGInline svg={infoIconInline} className={styles.infoIcon} />
</PopOver>
</div>
<div className={styles.spendingPasswordField}>
<PasswordInput
className="repeatPassword"
onKeyPress={this.handleSubmitOnEnter}
{...repeatPasswordField.bind()}
repeatPassword={spendingPasswordField.value}
isPasswordRepeat
/>
</div>
</div>
<div className={styles.passwordInstructions}>
<FormattedHTMLMessage {...globalMessages.passwordInstructions} />
</div>
</div>
{error && <p className={styles.error}>{intl.formatMessage(error)}</p>}
</div>
</WalletRestoreDialog>
);
}
}
export default ConfigurationDialog;
| if (this.props.error) {
handleFormErrors('.ConfigurationDialog_error');
}
}
| identifier_body |
ConfigurationDialog.tsx | import React, { Component } from 'react';
import { observer } from 'mobx-react';
import classnames from 'classnames';
import { Input } from 'react-polymorph/lib/components/Input';
import { defineMessages, intlShape, FormattedHTMLMessage } from 'react-intl';
import vjf from 'mobx-react-form/lib/validators/VJF';
import SVGInline from 'react-svg-inline';
import { PopOver } from 'react-polymorph/lib/components/PopOver';
import { PasswordInput } from '../../widgets/forms/PasswordInput';
import WalletRestoreDialog from './widgets/WalletRestoreDialog';
import styles from './ConfigurationDialog.scss';
import ReactToolboxMobxForm, {
handleFormErrors,
} from '../../../utils/ReactToolboxMobxForm';
import {
isValidWalletName,
isValidSpendingPassword,
isValidRepeatPassword,
} from '../../../utils/validations';
import { submitOnEnter } from '../../../utils/form';
import globalMessages from '../../../i18n/global-messages';
import LocalizableError from '../../../i18n/LocalizableError';
import { FORM_VALIDATION_DEBOUNCE_WAIT } from '../../../config/timingConfig';
// @ts-ignore ts-migrate(2307) FIXME: Cannot find module '../../../assets/images/info-ic... Remove this comment to see the full error message
import infoIconInline from '../../../assets/images/info-icon.inline.svg';
import LoadingSpinner from '../../widgets/LoadingSpinner';
const messages = defineMessages({
description1: {
id: 'wallet.restore.dialog.step.configuration.description1',
defaultMessage:
'!!!Name your restored wallet and set a spending password to keep your wallet secure.',
description: 'Description1 for Configuration Step',
},
description2: {
id: 'wallet.restore.dialog.step.configuration.description2',
defaultMessage:
'!!!Wallet names and spending passwords are only stored locally and are not stored on the blockchain. You can give your restored wallet a new name and set a new spending password, you don’t need to match the wallet name and spending password you were using before. <b>Only the recovery phrase from your original wallet is needed to restore a wallet.</b>',
description: 'Description2 for Configuration Step',
},
walletNameLabel: {
id: 'wallet.restore.dialog.step.configuration.input.walletName.label',
defaultMessage: '!!!Wallet name',
description: 'Label for Wallet Name Input',
},
walletNamePlaceholder: {
id: 'wallet.restore.dialog.step.configuration.input.walletName.placeholder',
defaultMessage: '!!!Name the wallet you are restoring',
description: 'Placeholder for Wallet Name Input',
},
spendingPasswordLabel: {
id: 'wallet.restore.dialog.step.configuration.input.spendingPassword.label',
defaultMessage: '!!!Enter password',
description:
'Label for the "Wallet password" input in the wallet restore dialog.',
},
repeatPasswordLabel: {
id: 'wallet.restore.dialog.step.configuration.input.repeatPassword.label',
defaultMessage: '!!!Repeat password',
description:
'Label for the "Repeat password" input in the wallet restore dialog.',
},
passwordFieldsPlaceholder: {
id:
'wallet.restore.dialog.step.configuration.input.passwordFields.placeholder',
defaultMessage: '!!!Password',
description:
'Placeholder for the "Password" inputs in the wallet restore dialog.',
},
continueButtonLabel: {
id: 'wallet.restore.dialog.step.configuration.continueButtonLabel',
defaultMessage: '!!!Continue',
description: 'Placeholder for the dialog "Continue" button',
},
passwordTooltip: {
id: 'wallet.dialog.passwordTooltip',
defaultMessage:
'!!!It is really good to use Password Manager apps to improve security. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris mattis diam non nulla sollicitudin, ac ultrices purus luctus.',
description: 'Tooltip for the password input in the create wallet dialog.',
},
});
type Props = {
isSubmitting: boolean;
onContinue: (...args: Array<any>) => any;
onClose: (...args: Array<any>) => any;
onBack: (...args: Array<any>) => any;
onChange: (...args: Array<any>) => any;
walletName: string;
spendingPassword: string;
repeatPassword: string;
error?: LocalizableError | null | undefined;
currentLocale: string;
};
interface FormFields {
walletName: string;
spendingPassword: string;
repeatPassword: string;
}
@observer
class ConfigurationDialog extends Component<Props> {
static contextTypes = {
intl: intlShape.isRequired,
};
static defaultProps = {
error: null,
};
componentDidUpdate() {
if (this.props.error) {
handleFormErrors('.ConfigurationDialog_error');
}
}
form = new ReactToolboxMobxForm<FormFields>(
{
fields: {
walletName: {
label: this.context.intl.formatMessage(messages.walletNameLabel),
placeholder: this.context.intl.formatMessage(
messages.walletNamePlaceholder
),
value: this.props.walletName,
validators: [
({ field }) => [
isValidWalletName(field.value),
this.context.intl.formatMessage(globalMessages.invalidWalletName),
],
],
hooks: {
onChange: this.props.onChange.bind(this, 'walletName'),
},
},
spendingPassword: {
type: 'password',
label: this.context.intl.formatMessage(
messages.spendingPasswordLabel
),
placeholder: this.context.intl.formatMessage(
messages.passwordFieldsPlaceholder
),
value: this.props.spendingPassword,
validators: [
({ field, form }) => {
const repeatPasswordField = form.$('repeatPassword');
const isRepeatPasswordFieldSet =
repeatPasswordField.value.length > 0;
repeatPasswordField.validate({
showErrors: isRepeatPasswordFieldSet,
});
return [
isValidSpendingPassword(field.value),
this.context.intl.formatMessage(
globalMessages.invalidSpendingPassword
),
];
},
],
hooks: {
onChange: this.props.onChange.bind(this, 'spendingPassword'),
},
},
repeatPassword: {
type: 'password',
label: this.context.intl.formatMessage(messages.repeatPasswordLabel),
placeholder: this.context.intl.formatMessage(
messages.passwordFieldsPlaceholder
),
value: this.props.repeatPassword,
validators: [
({ field, form }) => {
const spendingPassword = form.$('spendingPassword').value;
return [
isValidRepeatPassword(spendingPassword, field.value),
this.context.intl.formatMessage(
globalMessages.invalidRepeatPassword
),
];
},
],
hooks: {
onChange: this.props.onChange.bind(this, 'repeatPassword'),
},
},
},
},
{
plugins: {
vjf: vjf(),
},
options: {
validateOnChange: true,
validationDebounceWait: FORM_VALIDATION_DEBOUNCE_WAIT,
},
}
);
submit = () => {
this.form.submit({
onSuccess: (form) => {
const { onContinue } = this.props;
const { walletName, spendingPassword } = form.values();
onContinue(walletName, spendingPassword);
},
onError: () =>
handleFormErrors('.ConfigurationDialog_error', {
focusElement: true,
}),
});
};
handleSubmitOnEnter = submitOnEnter.bind(this, this.submit);
resetForm = () => {
const { form } = this;
// Cancel all debounced field validations
form.each((field) => {
field.debouncedValidation.cancel();
});
form.reset();
form.showErrors(false);
};
re | {
const { intl } = this.context;
const { onClose, onBack, error, isSubmitting, currentLocale } = this.props;
const { form } = this;
const walletNameField = form.$('walletName');
const spendingPasswordField = form.$('spendingPassword');
const repeatPasswordField = form.$('repeatPassword');
const walletNameFieldClasses = classnames([
styles.walletName,
'walletName',
]);
const spendingPasswordClasses = classnames([
styles.spendingPasswordField,
currentLocale === 'ja-JP' ? styles.jpLangTooltipIcon : '',
]);
const buttonLabel = !isSubmitting ? (
intl.formatMessage(messages.continueButtonLabel)
) : (
<LoadingSpinner />
);
const canSubmit = !isSubmitting && form.isValid;
return (
<WalletRestoreDialog
// @ts-ignore ts-migrate(2769) FIXME: No overload matches this call.
className={styles.dialogComponent}
stepNumber={2}
actions={[
{
disabled: !canSubmit,
primary: true,
label: buttonLabel,
onClick: this.submit,
},
]}
onClose={onClose}
onBack={onBack}
>
<div className={styles.component}>
<p>{intl.formatMessage(messages.description1)}</p>
<p>
<FormattedHTMLMessage {...messages.description2} />
</p>
<Input
className={walletNameFieldClasses}
onKeyPress={this.handleSubmitOnEnter}
{...walletNameField.bind()}
error={walletNameField.error}
/>
<div>
<div className={styles.spendingPasswordFields}>
<div className={spendingPasswordClasses}>
<PasswordInput
className="spendingPassword"
onKeyPress={this.handleSubmitOnEnter}
{...spendingPasswordField.bind()}
/>
<PopOver
content={
<FormattedHTMLMessage {...messages.passwordTooltip} />
}
key="tooltip"
>
<SVGInline svg={infoIconInline} className={styles.infoIcon} />
</PopOver>
</div>
<div className={styles.spendingPasswordField}>
<PasswordInput
className="repeatPassword"
onKeyPress={this.handleSubmitOnEnter}
{...repeatPasswordField.bind()}
repeatPassword={spendingPasswordField.value}
isPasswordRepeat
/>
</div>
</div>
<div className={styles.passwordInstructions}>
<FormattedHTMLMessage {...globalMessages.passwordInstructions} />
</div>
</div>
{error && <p className={styles.error}>{intl.formatMessage(error)}</p>}
</div>
</WalletRestoreDialog>
);
}
}
export default ConfigurationDialog;
| nder() | identifier_name |
strings.js | define(
({
showArcgisBasemaps: "Inclure les fonds de carte du portail",
settings: "Paramètres",
add: "Cliquez pour ajouter un nouveau fond de carte",
edit: "Propriétés",
title: "Titre",
titlePH: "Titre du fond de carte",
thumbnail: "Miniature",
thumbnailHint: "Cliquez sur l’image pour la modifier",
url: "URL", | back: "Retour et annuler",
addUrl: "Ajouter une URL",
autoCheck: "Vérification automatique",
checking: "Vérification...",
ok: "OK",
cancel: "Annuler",
result: "Enregistrement réussi",
spError: "Tous les fonds de carte ajoutés à la bibliothèque requièrent les mêmes références spatiales.",
invalidTitle1:"Un fond de carte nommé '",
invalidTitle2:"' existe déjà. Choisissez un autre titre.",
invalidBasemapUrl1: "Ce type de couche ne peut pas être utilisé comme fond de carte.",
invalidBasemapUrl2: "Référence spatiale différente de la carte actuelle.",
addBaselayer: "Ajouter une couche de fonds de carte"
})
); | urlPH: "URL de la couche",
addlayer: "Ajouter un fond de carte",
actions: "Actions",
warning: "Entrée incorrecte",
save: "Retour et enregistrer", | random_line_split |
iconWight.node.tsx | import { NG } from '@web-companions/gfc';
import { svg } from 'lit-html2';
import { renderNode } from 'utils/nodeRender';
export const iconWightNode = NG(function* (props: { strokeWidth?: string } = { strokeWidth: '1' }) {
while (true) |
});
| {
props = yield renderNode(
svg/*html*/ `
<svg
xmlns="http://www.w3.org/2000/svg"
class="icon icon-tabler icon-tabler-ripple"
width="24"
height="24"
viewBox="0 0 24 24"
stroke-width=${props.strokeWidth}
stroke="currentColor"
fill="none"
stroke-linecap="round"
stroke-linejoin="round"
>
<path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
<path d="M3 12c3 -2 6 -2 9 0s6 2 9 0"></path>
</svg>
`,
this
);
} | conditional_block |
iconWight.node.tsx | while (true) {
props = yield renderNode(
svg/*html*/ `
<svg
xmlns="http://www.w3.org/2000/svg"
class="icon icon-tabler icon-tabler-ripple"
width="24"
height="24"
viewBox="0 0 24 24"
stroke-width=${props.strokeWidth}
stroke="currentColor"
fill="none"
stroke-linecap="round"
stroke-linejoin="round"
>
<path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
<path d="M3 12c3 -2 6 -2 9 0s6 2 9 0"></path>
</svg>
`,
this
);
}
}); | import { NG } from '@web-companions/gfc';
import { svg } from 'lit-html2';
import { renderNode } from 'utils/nodeRender';
export const iconWightNode = NG(function* (props: { strokeWidth?: string } = { strokeWidth: '1' }) { | random_line_split | |
mesonlib.py | # Copyright 2012-2015 The Meson development team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A library of random helper functionality."""
import platform, subprocess, operator, os, shutil, re, sys
from glob import glob
class MesonException(Exception):
def __init__(self, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
class File:
def __init__(self, is_built, subdir, fname):
self.is_built = is_built
self.subdir = subdir
self.fname = fname
def __str__(self):
return os.path.join(self.subdir, self.fname)
def __repr__(self):
ret = '<File: {0}'
if not self.is_built:
ret += ' (not built)'
ret += '>'
return ret.format(os.path.join(self.subdir, self.fname))
@staticmethod
def from_source_file(source_root, subdir, fname):
if not os.path.isfile(os.path.join(source_root, subdir, fname)):
raise MesonException('File %s does not exist.' % fname)
return File(False, subdir, fname)
@staticmethod
def from_built_file(subdir, fname):
return File(True, subdir, fname)
@staticmethod
def from_absolute_file(fname):
return File(False, '', fname)
def rel_to_builddir(self, build_to_src):
if self.is_built:
return os.path.join(self.subdir, self.fname)
else:
return os.path.join(build_to_src, self.subdir, self.fname)
def endswith(self, ending):
return self.fname.endswith(ending)
def split(self, s):
return self.fname.split(s)
def __eq__(self, other):
return (self.fname, self.subdir, self.is_built) == (other.fname, other.subdir, other.is_built)
def __hash__(self):
return hash((self.fname, self.subdir, self.is_built))
def get_compiler_for_source(compilers, src):
for comp in compilers:
if comp.can_compile(src):
return comp
raise RuntimeError('No specified compiler can handle file {!s}'.format(src))
def classify_unity_sources(compilers, sources):
compsrclist = {}
for src in sources:
comp = get_compiler_for_source(compilers, src)
if comp not in compsrclist:
compsrclist[comp] = [src]
else:
compsrclist[comp].append(src)
return compsrclist
def flatten(item):
if not isinstance(item, list):
return item
result = []
for i in item:
if isinstance(i, list):
result += flatten(i)
else:
result.append(i)
return result
def is_osx():
return platform.system().lower() == 'darwin'
def is_linux():
return platform.system().lower() == 'linux'
def | ():
platname = platform.system().lower()
return platname == 'windows' or 'mingw' in platname
def is_debianlike():
return os.path.isfile('/etc/debian_version')
def exe_exists(arglist):
try:
p = subprocess.Popen(arglist, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.communicate()
if p.returncode == 0:
return True
except FileNotFoundError:
pass
return False
def detect_vcs(source_dir):
vcs_systems = [
dict(name = 'git', cmd = 'git', repo_dir = '.git', get_rev = 'git describe --dirty=+', rev_regex = '(.*)', dep = '.git/logs/HEAD'),
dict(name = 'mercurial', cmd = 'hg', repo_dir = '.hg', get_rev = 'hg id -i', rev_regex = '(.*)', dep = '.hg/dirstate'),
dict(name = 'subversion', cmd = 'svn', repo_dir = '.svn', get_rev = 'svn info', rev_regex = 'Revision: (.*)', dep = '.svn/wc.db'),
dict(name = 'bazaar', cmd = 'bzr', repo_dir = '.bzr', get_rev = 'bzr revno', rev_regex = '(.*)', dep = '.bzr'),
]
segs = source_dir.replace('\\', '/').split('/')
for i in range(len(segs), -1, -1):
curdir = '/'.join(segs[:i])
for vcs in vcs_systems:
if os.path.isdir(os.path.join(curdir, vcs['repo_dir'])) and shutil.which(vcs['cmd']):
vcs['wc_dir'] = curdir
return vcs
return None
def grab_leading_numbers(vstr):
result = []
for x in vstr.split('.'):
try:
result.append(int(x))
except ValueError:
break
return result
numpart = re.compile('[0-9.]+')
def version_compare(vstr1, vstr2):
match = numpart.match(vstr1.strip())
if match is None:
raise MesonException('Uncomparable version string %s.' % vstr1)
vstr1 = match.group(0)
if vstr2.startswith('>='):
cmpop = operator.ge
vstr2 = vstr2[2:]
elif vstr2.startswith('<='):
cmpop = operator.le
vstr2 = vstr2[2:]
elif vstr2.startswith('!='):
cmpop = operator.ne
vstr2 = vstr2[2:]
elif vstr2.startswith('=='):
cmpop = operator.eq
vstr2 = vstr2[2:]
elif vstr2.startswith('='):
cmpop = operator.eq
vstr2 = vstr2[1:]
elif vstr2.startswith('>'):
cmpop = operator.gt
vstr2 = vstr2[1:]
elif vstr2.startswith('<'):
cmpop = operator.lt
vstr2 = vstr2[1:]
else:
cmpop = operator.eq
varr1 = grab_leading_numbers(vstr1)
varr2 = grab_leading_numbers(vstr2)
return cmpop(varr1, varr2)
def default_libdir():
if is_debianlike():
try:
pc = subprocess.Popen(['dpkg-architecture', '-qDEB_HOST_MULTIARCH'],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL)
(stdo, _) = pc.communicate()
if pc.returncode == 0:
archpath = stdo.decode().strip()
return 'lib/' + archpath
except Exception:
pass
if os.path.isdir('/usr/lib64') and not os.path.islink('/usr/lib64'):
return 'lib64'
return 'lib'
def default_libexecdir():
# There is no way to auto-detect this, so it must be set at build time
return 'libexec'
def default_prefix():
return 'c:/' if is_windows() else '/usr/local'
def get_library_dirs():
if is_windows():
return ['C:/mingw/lib'] # Fixme
if is_osx():
return ['/usr/lib'] # Fix me as well.
# The following is probably Debian/Ubuntu specific.
# /usr/local/lib is first because it contains stuff
# installed by the sysadmin and is probably more up-to-date
# than /usr/lib. If you feel that this search order is
# problematic, please raise the issue on the mailing list.
unixdirs = ['/usr/local/lib', '/usr/lib', '/lib']
plat = subprocess.check_output(['uname', '-m']).decode().strip()
# This is a terrible hack. I admit it and I'm really sorry.
# I just don't know what the correct solution is.
if plat == 'i686':
plat = 'i386'
if plat.startswith('arm'):
plat = 'arm'
unixdirs += glob('/usr/lib/' + plat + '*')
if os.path.exists('/usr/lib64'):
unixdirs.append('/usr/lib64')
unixdirs += glob('/lib/' + plat + '*')
if os.path.exists('/lib64'):
unixdirs.append('/lib64')
unixdirs += glob('/lib/' + plat + '*')
return unixdirs
def do_replacement(regex, line, confdata):
match = re.search(regex, line)
while match:
varname = match.group(1)
if varname in confdata.keys():
(var, desc) = confdata.get(varname)
if isinstance(var, str):
pass
elif isinstance(var, int):
var = str(var)
else:
raise RuntimeError('Tried to replace a variable with something other than a string or int.')
else:
var = ''
line = line.replace('@' + varname + '@', var)
match = re.search(regex, line)
return line
def do_mesondefine(line, confdata):
arr = line.split()
if len(arr) != 2:
raise MesonException('#mesondefine does not contain exactly two tokens: %s', line.strip())
varname = arr[1]
try:
(v, desc) = confdata.get(varname)
except KeyError:
return '/* #undef %s */\n' % varname
if isinstance(v, bool):
if v:
return '#define %s\n' % varname
else:
return '#undef %s\n' % varname
elif isinstance(v, int):
return '#define %s %d\n' % (varname, v)
elif isinstance(v, str):
return '#define %s %s\n' % (varname, v)
else:
raise MesonException('#mesondefine argument "%s" is of unknown type.' % varname)
def do_conf_file(src, dst, confdata):
try:
with open(src, encoding='utf-8') as f:
data = f.readlines()
except Exception as e:
raise MesonException('Could not read input file %s: %s' % (src, str(e)))
# Only allow (a-z, A-Z, 0-9, _, -) as valid characters for a define
# Also allow escaping '@' with '\@'
regex = re.compile(r'[^\\]?@([-a-zA-Z0-9_]+)@')
result = []
for line in data:
if line.startswith('#mesondefine'):
line = do_mesondefine(line, confdata)
else:
line = do_replacement(regex, line, confdata)
result.append(line)
dst_tmp = dst + '~'
with open(dst_tmp, 'w') as f:
f.writelines(result)
shutil.copymode(src, dst_tmp)
replace_if_different(dst, dst_tmp)
def dump_conf_header(ofilename, cdata):
with open(ofilename, 'w') as ofile:
ofile.write('''/*
* Autogenerated by the Meson build system.
* Do not edit, your changes will be lost.
*/
#pragma once
''')
for k in sorted(cdata.keys()):
(v, desc) = cdata.get(k)
if desc:
ofile.write('/* %s */\n' % desc)
if isinstance(v, bool):
if v:
ofile.write('#define %s\n\n' % k)
else:
ofile.write('#undef %s\n\n' % k)
elif isinstance(v, (int, str)):
ofile.write('#define %s %s\n\n' % (k, v))
else:
raise MesonException('Unknown data type in configuration file entry: ' + k)
def replace_if_different(dst, dst_tmp):
# If contents are identical, don't touch the file to prevent
# unnecessary rebuilds.
different = True
try:
with open(dst, 'r') as f1, open(dst_tmp, 'r') as f2:
if f1.read() == f2.read():
different = False
except FileNotFoundError:
pass
if different:
os.replace(dst_tmp, dst)
else:
os.unlink(dst_tmp)
def stringlistify(item):
if isinstance(item, str):
item = [item]
if not isinstance(item, list):
raise MesonException('Item is not an array')
for i in item:
if not isinstance(i, str):
raise MesonException('List item not a string.')
return item
def expand_arguments(args):
expended_args = []
for arg in args:
if not arg.startswith('@'):
expended_args.append(arg)
continue
args_file = arg[1:]
try:
with open(args_file) as f:
extended_args = f.read().split()
expended_args += extended_args
except Exception as e:
print('Error expanding command line arguments, %s not found' % args_file)
print(e)
return None
return expended_args
| is_windows | identifier_name |
mesonlib.py | # Copyright 2012-2015 The Meson development team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A library of random helper functionality."""
import platform, subprocess, operator, os, shutil, re, sys
from glob import glob
class MesonException(Exception):
def __init__(self, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
class File:
def __init__(self, is_built, subdir, fname):
self.is_built = is_built
self.subdir = subdir
self.fname = fname
def __str__(self):
return os.path.join(self.subdir, self.fname)
def __repr__(self):
ret = '<File: {0}'
if not self.is_built:
ret += ' (not built)'
ret += '>'
return ret.format(os.path.join(self.subdir, self.fname))
@staticmethod
def from_source_file(source_root, subdir, fname):
if not os.path.isfile(os.path.join(source_root, subdir, fname)):
raise MesonException('File %s does not exist.' % fname)
return File(False, subdir, fname)
@staticmethod
def from_built_file(subdir, fname):
return File(True, subdir, fname)
@staticmethod
def from_absolute_file(fname):
return File(False, '', fname)
def rel_to_builddir(self, build_to_src):
if self.is_built:
return os.path.join(self.subdir, self.fname)
else:
return os.path.join(build_to_src, self.subdir, self.fname)
def endswith(self, ending):
return self.fname.endswith(ending)
def split(self, s):
return self.fname.split(s)
def __eq__(self, other):
return (self.fname, self.subdir, self.is_built) == (other.fname, other.subdir, other.is_built)
def __hash__(self):
return hash((self.fname, self.subdir, self.is_built))
def get_compiler_for_source(compilers, src):
for comp in compilers:
if comp.can_compile(src):
return comp
raise RuntimeError('No specified compiler can handle file {!s}'.format(src))
def classify_unity_sources(compilers, sources):
compsrclist = {}
for src in sources:
comp = get_compiler_for_source(compilers, src)
if comp not in compsrclist:
compsrclist[comp] = [src]
else:
compsrclist[comp].append(src)
return compsrclist
def flatten(item):
if not isinstance(item, list):
return item
result = []
for i in item:
if isinstance(i, list):
result += flatten(i)
else:
result.append(i)
return result
def is_osx():
return platform.system().lower() == 'darwin'
def is_linux():
return platform.system().lower() == 'linux'
def is_windows():
platname = platform.system().lower()
return platname == 'windows' or 'mingw' in platname
def is_debianlike():
|
def exe_exists(arglist):
try:
p = subprocess.Popen(arglist, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.communicate()
if p.returncode == 0:
return True
except FileNotFoundError:
pass
return False
def detect_vcs(source_dir):
vcs_systems = [
dict(name = 'git', cmd = 'git', repo_dir = '.git', get_rev = 'git describe --dirty=+', rev_regex = '(.*)', dep = '.git/logs/HEAD'),
dict(name = 'mercurial', cmd = 'hg', repo_dir = '.hg', get_rev = 'hg id -i', rev_regex = '(.*)', dep = '.hg/dirstate'),
dict(name = 'subversion', cmd = 'svn', repo_dir = '.svn', get_rev = 'svn info', rev_regex = 'Revision: (.*)', dep = '.svn/wc.db'),
dict(name = 'bazaar', cmd = 'bzr', repo_dir = '.bzr', get_rev = 'bzr revno', rev_regex = '(.*)', dep = '.bzr'),
]
segs = source_dir.replace('\\', '/').split('/')
for i in range(len(segs), -1, -1):
curdir = '/'.join(segs[:i])
for vcs in vcs_systems:
if os.path.isdir(os.path.join(curdir, vcs['repo_dir'])) and shutil.which(vcs['cmd']):
vcs['wc_dir'] = curdir
return vcs
return None
def grab_leading_numbers(vstr):
result = []
for x in vstr.split('.'):
try:
result.append(int(x))
except ValueError:
break
return result
numpart = re.compile('[0-9.]+')
def version_compare(vstr1, vstr2):
match = numpart.match(vstr1.strip())
if match is None:
raise MesonException('Uncomparable version string %s.' % vstr1)
vstr1 = match.group(0)
if vstr2.startswith('>='):
cmpop = operator.ge
vstr2 = vstr2[2:]
elif vstr2.startswith('<='):
cmpop = operator.le
vstr2 = vstr2[2:]
elif vstr2.startswith('!='):
cmpop = operator.ne
vstr2 = vstr2[2:]
elif vstr2.startswith('=='):
cmpop = operator.eq
vstr2 = vstr2[2:]
elif vstr2.startswith('='):
cmpop = operator.eq
vstr2 = vstr2[1:]
elif vstr2.startswith('>'):
cmpop = operator.gt
vstr2 = vstr2[1:]
elif vstr2.startswith('<'):
cmpop = operator.lt
vstr2 = vstr2[1:]
else:
cmpop = operator.eq
varr1 = grab_leading_numbers(vstr1)
varr2 = grab_leading_numbers(vstr2)
return cmpop(varr1, varr2)
def default_libdir():
if is_debianlike():
try:
pc = subprocess.Popen(['dpkg-architecture', '-qDEB_HOST_MULTIARCH'],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL)
(stdo, _) = pc.communicate()
if pc.returncode == 0:
archpath = stdo.decode().strip()
return 'lib/' + archpath
except Exception:
pass
if os.path.isdir('/usr/lib64') and not os.path.islink('/usr/lib64'):
return 'lib64'
return 'lib'
def default_libexecdir():
# There is no way to auto-detect this, so it must be set at build time
return 'libexec'
def default_prefix():
return 'c:/' if is_windows() else '/usr/local'
def get_library_dirs():
if is_windows():
return ['C:/mingw/lib'] # Fixme
if is_osx():
return ['/usr/lib'] # Fix me as well.
# The following is probably Debian/Ubuntu specific.
# /usr/local/lib is first because it contains stuff
# installed by the sysadmin and is probably more up-to-date
# than /usr/lib. If you feel that this search order is
# problematic, please raise the issue on the mailing list.
unixdirs = ['/usr/local/lib', '/usr/lib', '/lib']
plat = subprocess.check_output(['uname', '-m']).decode().strip()
# This is a terrible hack. I admit it and I'm really sorry.
# I just don't know what the correct solution is.
if plat == 'i686':
plat = 'i386'
if plat.startswith('arm'):
plat = 'arm'
unixdirs += glob('/usr/lib/' + plat + '*')
if os.path.exists('/usr/lib64'):
unixdirs.append('/usr/lib64')
unixdirs += glob('/lib/' + plat + '*')
if os.path.exists('/lib64'):
unixdirs.append('/lib64')
unixdirs += glob('/lib/' + plat + '*')
return unixdirs
def do_replacement(regex, line, confdata):
match = re.search(regex, line)
while match:
varname = match.group(1)
if varname in confdata.keys():
(var, desc) = confdata.get(varname)
if isinstance(var, str):
pass
elif isinstance(var, int):
var = str(var)
else:
raise RuntimeError('Tried to replace a variable with something other than a string or int.')
else:
var = ''
line = line.replace('@' + varname + '@', var)
match = re.search(regex, line)
return line
def do_mesondefine(line, confdata):
arr = line.split()
if len(arr) != 2:
raise MesonException('#mesondefine does not contain exactly two tokens: %s', line.strip())
varname = arr[1]
try:
(v, desc) = confdata.get(varname)
except KeyError:
return '/* #undef %s */\n' % varname
if isinstance(v, bool):
if v:
return '#define %s\n' % varname
else:
return '#undef %s\n' % varname
elif isinstance(v, int):
return '#define %s %d\n' % (varname, v)
elif isinstance(v, str):
return '#define %s %s\n' % (varname, v)
else:
raise MesonException('#mesondefine argument "%s" is of unknown type.' % varname)
def do_conf_file(src, dst, confdata):
try:
with open(src, encoding='utf-8') as f:
data = f.readlines()
except Exception as e:
raise MesonException('Could not read input file %s: %s' % (src, str(e)))
# Only allow (a-z, A-Z, 0-9, _, -) as valid characters for a define
# Also allow escaping '@' with '\@'
regex = re.compile(r'[^\\]?@([-a-zA-Z0-9_]+)@')
result = []
for line in data:
if line.startswith('#mesondefine'):
line = do_mesondefine(line, confdata)
else:
line = do_replacement(regex, line, confdata)
result.append(line)
dst_tmp = dst + '~'
with open(dst_tmp, 'w') as f:
f.writelines(result)
shutil.copymode(src, dst_tmp)
replace_if_different(dst, dst_tmp)
def dump_conf_header(ofilename, cdata):
with open(ofilename, 'w') as ofile:
ofile.write('''/*
* Autogenerated by the Meson build system.
* Do not edit, your changes will be lost.
*/
#pragma once
''')
for k in sorted(cdata.keys()):
(v, desc) = cdata.get(k)
if desc:
ofile.write('/* %s */\n' % desc)
if isinstance(v, bool):
if v:
ofile.write('#define %s\n\n' % k)
else:
ofile.write('#undef %s\n\n' % k)
elif isinstance(v, (int, str)):
ofile.write('#define %s %s\n\n' % (k, v))
else:
raise MesonException('Unknown data type in configuration file entry: ' + k)
def replace_if_different(dst, dst_tmp):
# If contents are identical, don't touch the file to prevent
# unnecessary rebuilds.
different = True
try:
with open(dst, 'r') as f1, open(dst_tmp, 'r') as f2:
if f1.read() == f2.read():
different = False
except FileNotFoundError:
pass
if different:
os.replace(dst_tmp, dst)
else:
os.unlink(dst_tmp)
def stringlistify(item):
if isinstance(item, str):
item = [item]
if not isinstance(item, list):
raise MesonException('Item is not an array')
for i in item:
if not isinstance(i, str):
raise MesonException('List item not a string.')
return item
def expand_arguments(args):
expended_args = []
for arg in args:
if not arg.startswith('@'):
expended_args.append(arg)
continue
args_file = arg[1:]
try:
with open(args_file) as f:
extended_args = f.read().split()
expended_args += extended_args
except Exception as e:
print('Error expanding command line arguments, %s not found' % args_file)
print(e)
return None
return expended_args
| return os.path.isfile('/etc/debian_version') | identifier_body |
mesonlib.py | # Copyright 2012-2015 The Meson development team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A library of random helper functionality."""
import platform, subprocess, operator, os, shutil, re, sys
from glob import glob
class MesonException(Exception):
def __init__(self, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
class File:
def __init__(self, is_built, subdir, fname):
self.is_built = is_built
self.subdir = subdir
self.fname = fname
def __str__(self):
return os.path.join(self.subdir, self.fname)
def __repr__(self):
ret = '<File: {0}'
if not self.is_built:
ret += ' (not built)'
ret += '>'
return ret.format(os.path.join(self.subdir, self.fname))
@staticmethod
def from_source_file(source_root, subdir, fname):
if not os.path.isfile(os.path.join(source_root, subdir, fname)):
raise MesonException('File %s does not exist.' % fname)
return File(False, subdir, fname)
@staticmethod
def from_built_file(subdir, fname):
return File(True, subdir, fname)
@staticmethod
def from_absolute_file(fname):
return File(False, '', fname)
def rel_to_builddir(self, build_to_src):
if self.is_built:
return os.path.join(self.subdir, self.fname)
else:
return os.path.join(build_to_src, self.subdir, self.fname)
def endswith(self, ending):
return self.fname.endswith(ending)
def split(self, s):
return self.fname.split(s)
def __eq__(self, other):
return (self.fname, self.subdir, self.is_built) == (other.fname, other.subdir, other.is_built)
def __hash__(self):
return hash((self.fname, self.subdir, self.is_built))
def get_compiler_for_source(compilers, src):
for comp in compilers:
if comp.can_compile(src):
return comp
raise RuntimeError('No specified compiler can handle file {!s}'.format(src))
def classify_unity_sources(compilers, sources):
compsrclist = {}
for src in sources:
comp = get_compiler_for_source(compilers, src)
if comp not in compsrclist:
compsrclist[comp] = [src]
else:
compsrclist[comp].append(src)
return compsrclist
def flatten(item):
if not isinstance(item, list):
return item
result = []
for i in item:
if isinstance(i, list):
result += flatten(i)
else:
result.append(i)
return result
def is_osx():
return platform.system().lower() == 'darwin'
def is_linux():
return platform.system().lower() == 'linux'
def is_windows():
platname = platform.system().lower()
return platname == 'windows' or 'mingw' in platname
def is_debianlike():
return os.path.isfile('/etc/debian_version')
def exe_exists(arglist):
try:
p = subprocess.Popen(arglist, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.communicate()
if p.returncode == 0:
return True
except FileNotFoundError:
pass
return False
def detect_vcs(source_dir):
vcs_systems = [
dict(name = 'git', cmd = 'git', repo_dir = '.git', get_rev = 'git describe --dirty=+', rev_regex = '(.*)', dep = '.git/logs/HEAD'), | dict(name = 'subversion', cmd = 'svn', repo_dir = '.svn', get_rev = 'svn info', rev_regex = 'Revision: (.*)', dep = '.svn/wc.db'),
dict(name = 'bazaar', cmd = 'bzr', repo_dir = '.bzr', get_rev = 'bzr revno', rev_regex = '(.*)', dep = '.bzr'),
]
segs = source_dir.replace('\\', '/').split('/')
for i in range(len(segs), -1, -1):
curdir = '/'.join(segs[:i])
for vcs in vcs_systems:
if os.path.isdir(os.path.join(curdir, vcs['repo_dir'])) and shutil.which(vcs['cmd']):
vcs['wc_dir'] = curdir
return vcs
return None
def grab_leading_numbers(vstr):
result = []
for x in vstr.split('.'):
try:
result.append(int(x))
except ValueError:
break
return result
numpart = re.compile('[0-9.]+')
def version_compare(vstr1, vstr2):
match = numpart.match(vstr1.strip())
if match is None:
raise MesonException('Uncomparable version string %s.' % vstr1)
vstr1 = match.group(0)
if vstr2.startswith('>='):
cmpop = operator.ge
vstr2 = vstr2[2:]
elif vstr2.startswith('<='):
cmpop = operator.le
vstr2 = vstr2[2:]
elif vstr2.startswith('!='):
cmpop = operator.ne
vstr2 = vstr2[2:]
elif vstr2.startswith('=='):
cmpop = operator.eq
vstr2 = vstr2[2:]
elif vstr2.startswith('='):
cmpop = operator.eq
vstr2 = vstr2[1:]
elif vstr2.startswith('>'):
cmpop = operator.gt
vstr2 = vstr2[1:]
elif vstr2.startswith('<'):
cmpop = operator.lt
vstr2 = vstr2[1:]
else:
cmpop = operator.eq
varr1 = grab_leading_numbers(vstr1)
varr2 = grab_leading_numbers(vstr2)
return cmpop(varr1, varr2)
def default_libdir():
if is_debianlike():
try:
pc = subprocess.Popen(['dpkg-architecture', '-qDEB_HOST_MULTIARCH'],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL)
(stdo, _) = pc.communicate()
if pc.returncode == 0:
archpath = stdo.decode().strip()
return 'lib/' + archpath
except Exception:
pass
if os.path.isdir('/usr/lib64') and not os.path.islink('/usr/lib64'):
return 'lib64'
return 'lib'
def default_libexecdir():
# There is no way to auto-detect this, so it must be set at build time
return 'libexec'
def default_prefix():
return 'c:/' if is_windows() else '/usr/local'
def get_library_dirs():
if is_windows():
return ['C:/mingw/lib'] # Fixme
if is_osx():
return ['/usr/lib'] # Fix me as well.
# The following is probably Debian/Ubuntu specific.
# /usr/local/lib is first because it contains stuff
# installed by the sysadmin and is probably more up-to-date
# than /usr/lib. If you feel that this search order is
# problematic, please raise the issue on the mailing list.
unixdirs = ['/usr/local/lib', '/usr/lib', '/lib']
plat = subprocess.check_output(['uname', '-m']).decode().strip()
# This is a terrible hack. I admit it and I'm really sorry.
# I just don't know what the correct solution is.
if plat == 'i686':
plat = 'i386'
if plat.startswith('arm'):
plat = 'arm'
unixdirs += glob('/usr/lib/' + plat + '*')
if os.path.exists('/usr/lib64'):
unixdirs.append('/usr/lib64')
unixdirs += glob('/lib/' + plat + '*')
if os.path.exists('/lib64'):
unixdirs.append('/lib64')
unixdirs += glob('/lib/' + plat + '*')
return unixdirs
def do_replacement(regex, line, confdata):
match = re.search(regex, line)
while match:
varname = match.group(1)
if varname in confdata.keys():
(var, desc) = confdata.get(varname)
if isinstance(var, str):
pass
elif isinstance(var, int):
var = str(var)
else:
raise RuntimeError('Tried to replace a variable with something other than a string or int.')
else:
var = ''
line = line.replace('@' + varname + '@', var)
match = re.search(regex, line)
return line
def do_mesondefine(line, confdata):
arr = line.split()
if len(arr) != 2:
raise MesonException('#mesondefine does not contain exactly two tokens: %s', line.strip())
varname = arr[1]
try:
(v, desc) = confdata.get(varname)
except KeyError:
return '/* #undef %s */\n' % varname
if isinstance(v, bool):
if v:
return '#define %s\n' % varname
else:
return '#undef %s\n' % varname
elif isinstance(v, int):
return '#define %s %d\n' % (varname, v)
elif isinstance(v, str):
return '#define %s %s\n' % (varname, v)
else:
raise MesonException('#mesondefine argument "%s" is of unknown type.' % varname)
def do_conf_file(src, dst, confdata):
try:
with open(src, encoding='utf-8') as f:
data = f.readlines()
except Exception as e:
raise MesonException('Could not read input file %s: %s' % (src, str(e)))
# Only allow (a-z, A-Z, 0-9, _, -) as valid characters for a define
# Also allow escaping '@' with '\@'
regex = re.compile(r'[^\\]?@([-a-zA-Z0-9_]+)@')
result = []
for line in data:
if line.startswith('#mesondefine'):
line = do_mesondefine(line, confdata)
else:
line = do_replacement(regex, line, confdata)
result.append(line)
dst_tmp = dst + '~'
with open(dst_tmp, 'w') as f:
f.writelines(result)
shutil.copymode(src, dst_tmp)
replace_if_different(dst, dst_tmp)
def dump_conf_header(ofilename, cdata):
with open(ofilename, 'w') as ofile:
ofile.write('''/*
* Autogenerated by the Meson build system.
* Do not edit, your changes will be lost.
*/
#pragma once
''')
for k in sorted(cdata.keys()):
(v, desc) = cdata.get(k)
if desc:
ofile.write('/* %s */\n' % desc)
if isinstance(v, bool):
if v:
ofile.write('#define %s\n\n' % k)
else:
ofile.write('#undef %s\n\n' % k)
elif isinstance(v, (int, str)):
ofile.write('#define %s %s\n\n' % (k, v))
else:
raise MesonException('Unknown data type in configuration file entry: ' + k)
def replace_if_different(dst, dst_tmp):
# If contents are identical, don't touch the file to prevent
# unnecessary rebuilds.
different = True
try:
with open(dst, 'r') as f1, open(dst_tmp, 'r') as f2:
if f1.read() == f2.read():
different = False
except FileNotFoundError:
pass
if different:
os.replace(dst_tmp, dst)
else:
os.unlink(dst_tmp)
def stringlistify(item):
if isinstance(item, str):
item = [item]
if not isinstance(item, list):
raise MesonException('Item is not an array')
for i in item:
if not isinstance(i, str):
raise MesonException('List item not a string.')
return item
def expand_arguments(args):
expended_args = []
for arg in args:
if not arg.startswith('@'):
expended_args.append(arg)
continue
args_file = arg[1:]
try:
with open(args_file) as f:
extended_args = f.read().split()
expended_args += extended_args
except Exception as e:
print('Error expanding command line arguments, %s not found' % args_file)
print(e)
return None
return expended_args | dict(name = 'mercurial', cmd = 'hg', repo_dir = '.hg', get_rev = 'hg id -i', rev_regex = '(.*)', dep = '.hg/dirstate'), | random_line_split |
mesonlib.py | # Copyright 2012-2015 The Meson development team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A library of random helper functionality."""
import platform, subprocess, operator, os, shutil, re, sys
from glob import glob
class MesonException(Exception):
def __init__(self, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
class File:
def __init__(self, is_built, subdir, fname):
self.is_built = is_built
self.subdir = subdir
self.fname = fname
def __str__(self):
return os.path.join(self.subdir, self.fname)
def __repr__(self):
ret = '<File: {0}'
if not self.is_built:
ret += ' (not built)'
ret += '>'
return ret.format(os.path.join(self.subdir, self.fname))
@staticmethod
def from_source_file(source_root, subdir, fname):
if not os.path.isfile(os.path.join(source_root, subdir, fname)):
raise MesonException('File %s does not exist.' % fname)
return File(False, subdir, fname)
@staticmethod
def from_built_file(subdir, fname):
return File(True, subdir, fname)
@staticmethod
def from_absolute_file(fname):
return File(False, '', fname)
def rel_to_builddir(self, build_to_src):
if self.is_built:
return os.path.join(self.subdir, self.fname)
else:
|
def endswith(self, ending):
return self.fname.endswith(ending)
def split(self, s):
return self.fname.split(s)
def __eq__(self, other):
return (self.fname, self.subdir, self.is_built) == (other.fname, other.subdir, other.is_built)
def __hash__(self):
return hash((self.fname, self.subdir, self.is_built))
def get_compiler_for_source(compilers, src):
for comp in compilers:
if comp.can_compile(src):
return comp
raise RuntimeError('No specified compiler can handle file {!s}'.format(src))
def classify_unity_sources(compilers, sources):
compsrclist = {}
for src in sources:
comp = get_compiler_for_source(compilers, src)
if comp not in compsrclist:
compsrclist[comp] = [src]
else:
compsrclist[comp].append(src)
return compsrclist
def flatten(item):
if not isinstance(item, list):
return item
result = []
for i in item:
if isinstance(i, list):
result += flatten(i)
else:
result.append(i)
return result
def is_osx():
return platform.system().lower() == 'darwin'
def is_linux():
return platform.system().lower() == 'linux'
def is_windows():
platname = platform.system().lower()
return platname == 'windows' or 'mingw' in platname
def is_debianlike():
return os.path.isfile('/etc/debian_version')
def exe_exists(arglist):
try:
p = subprocess.Popen(arglist, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.communicate()
if p.returncode == 0:
return True
except FileNotFoundError:
pass
return False
def detect_vcs(source_dir):
vcs_systems = [
dict(name = 'git', cmd = 'git', repo_dir = '.git', get_rev = 'git describe --dirty=+', rev_regex = '(.*)', dep = '.git/logs/HEAD'),
dict(name = 'mercurial', cmd = 'hg', repo_dir = '.hg', get_rev = 'hg id -i', rev_regex = '(.*)', dep = '.hg/dirstate'),
dict(name = 'subversion', cmd = 'svn', repo_dir = '.svn', get_rev = 'svn info', rev_regex = 'Revision: (.*)', dep = '.svn/wc.db'),
dict(name = 'bazaar', cmd = 'bzr', repo_dir = '.bzr', get_rev = 'bzr revno', rev_regex = '(.*)', dep = '.bzr'),
]
segs = source_dir.replace('\\', '/').split('/')
for i in range(len(segs), -1, -1):
curdir = '/'.join(segs[:i])
for vcs in vcs_systems:
if os.path.isdir(os.path.join(curdir, vcs['repo_dir'])) and shutil.which(vcs['cmd']):
vcs['wc_dir'] = curdir
return vcs
return None
def grab_leading_numbers(vstr):
result = []
for x in vstr.split('.'):
try:
result.append(int(x))
except ValueError:
break
return result
numpart = re.compile('[0-9.]+')
def version_compare(vstr1, vstr2):
match = numpart.match(vstr1.strip())
if match is None:
raise MesonException('Uncomparable version string %s.' % vstr1)
vstr1 = match.group(0)
if vstr2.startswith('>='):
cmpop = operator.ge
vstr2 = vstr2[2:]
elif vstr2.startswith('<='):
cmpop = operator.le
vstr2 = vstr2[2:]
elif vstr2.startswith('!='):
cmpop = operator.ne
vstr2 = vstr2[2:]
elif vstr2.startswith('=='):
cmpop = operator.eq
vstr2 = vstr2[2:]
elif vstr2.startswith('='):
cmpop = operator.eq
vstr2 = vstr2[1:]
elif vstr2.startswith('>'):
cmpop = operator.gt
vstr2 = vstr2[1:]
elif vstr2.startswith('<'):
cmpop = operator.lt
vstr2 = vstr2[1:]
else:
cmpop = operator.eq
varr1 = grab_leading_numbers(vstr1)
varr2 = grab_leading_numbers(vstr2)
return cmpop(varr1, varr2)
def default_libdir():
if is_debianlike():
try:
pc = subprocess.Popen(['dpkg-architecture', '-qDEB_HOST_MULTIARCH'],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL)
(stdo, _) = pc.communicate()
if pc.returncode == 0:
archpath = stdo.decode().strip()
return 'lib/' + archpath
except Exception:
pass
if os.path.isdir('/usr/lib64') and not os.path.islink('/usr/lib64'):
return 'lib64'
return 'lib'
def default_libexecdir():
# There is no way to auto-detect this, so it must be set at build time
return 'libexec'
def default_prefix():
return 'c:/' if is_windows() else '/usr/local'
def get_library_dirs():
if is_windows():
return ['C:/mingw/lib'] # Fixme
if is_osx():
return ['/usr/lib'] # Fix me as well.
# The following is probably Debian/Ubuntu specific.
# /usr/local/lib is first because it contains stuff
# installed by the sysadmin and is probably more up-to-date
# than /usr/lib. If you feel that this search order is
# problematic, please raise the issue on the mailing list.
unixdirs = ['/usr/local/lib', '/usr/lib', '/lib']
plat = subprocess.check_output(['uname', '-m']).decode().strip()
# This is a terrible hack. I admit it and I'm really sorry.
# I just don't know what the correct solution is.
if plat == 'i686':
plat = 'i386'
if plat.startswith('arm'):
plat = 'arm'
unixdirs += glob('/usr/lib/' + plat + '*')
if os.path.exists('/usr/lib64'):
unixdirs.append('/usr/lib64')
unixdirs += glob('/lib/' + plat + '*')
if os.path.exists('/lib64'):
unixdirs.append('/lib64')
unixdirs += glob('/lib/' + plat + '*')
return unixdirs
def do_replacement(regex, line, confdata):
match = re.search(regex, line)
while match:
varname = match.group(1)
if varname in confdata.keys():
(var, desc) = confdata.get(varname)
if isinstance(var, str):
pass
elif isinstance(var, int):
var = str(var)
else:
raise RuntimeError('Tried to replace a variable with something other than a string or int.')
else:
var = ''
line = line.replace('@' + varname + '@', var)
match = re.search(regex, line)
return line
def do_mesondefine(line, confdata):
arr = line.split()
if len(arr) != 2:
raise MesonException('#mesondefine does not contain exactly two tokens: %s', line.strip())
varname = arr[1]
try:
(v, desc) = confdata.get(varname)
except KeyError:
return '/* #undef %s */\n' % varname
if isinstance(v, bool):
if v:
return '#define %s\n' % varname
else:
return '#undef %s\n' % varname
elif isinstance(v, int):
return '#define %s %d\n' % (varname, v)
elif isinstance(v, str):
return '#define %s %s\n' % (varname, v)
else:
raise MesonException('#mesondefine argument "%s" is of unknown type.' % varname)
def do_conf_file(src, dst, confdata):
try:
with open(src, encoding='utf-8') as f:
data = f.readlines()
except Exception as e:
raise MesonException('Could not read input file %s: %s' % (src, str(e)))
# Only allow (a-z, A-Z, 0-9, _, -) as valid characters for a define
# Also allow escaping '@' with '\@'
regex = re.compile(r'[^\\]?@([-a-zA-Z0-9_]+)@')
result = []
for line in data:
if line.startswith('#mesondefine'):
line = do_mesondefine(line, confdata)
else:
line = do_replacement(regex, line, confdata)
result.append(line)
dst_tmp = dst + '~'
with open(dst_tmp, 'w') as f:
f.writelines(result)
shutil.copymode(src, dst_tmp)
replace_if_different(dst, dst_tmp)
def dump_conf_header(ofilename, cdata):
with open(ofilename, 'w') as ofile:
ofile.write('''/*
* Autogenerated by the Meson build system.
* Do not edit, your changes will be lost.
*/
#pragma once
''')
for k in sorted(cdata.keys()):
(v, desc) = cdata.get(k)
if desc:
ofile.write('/* %s */\n' % desc)
if isinstance(v, bool):
if v:
ofile.write('#define %s\n\n' % k)
else:
ofile.write('#undef %s\n\n' % k)
elif isinstance(v, (int, str)):
ofile.write('#define %s %s\n\n' % (k, v))
else:
raise MesonException('Unknown data type in configuration file entry: ' + k)
def replace_if_different(dst, dst_tmp):
# If contents are identical, don't touch the file to prevent
# unnecessary rebuilds.
different = True
try:
with open(dst, 'r') as f1, open(dst_tmp, 'r') as f2:
if f1.read() == f2.read():
different = False
except FileNotFoundError:
pass
if different:
os.replace(dst_tmp, dst)
else:
os.unlink(dst_tmp)
def stringlistify(item):
if isinstance(item, str):
item = [item]
if not isinstance(item, list):
raise MesonException('Item is not an array')
for i in item:
if not isinstance(i, str):
raise MesonException('List item not a string.')
return item
def expand_arguments(args):
expended_args = []
for arg in args:
if not arg.startswith('@'):
expended_args.append(arg)
continue
args_file = arg[1:]
try:
with open(args_file) as f:
extended_args = f.read().split()
expended_args += extended_args
except Exception as e:
print('Error expanding command line arguments, %s not found' % args_file)
print(e)
return None
return expended_args
| return os.path.join(build_to_src, self.subdir, self.fname) | conditional_block |
mizrahi.ts | import moment from 'moment';
import { Frame, Page, Request } from 'puppeteer';
import { SHEKEL_CURRENCY } from '../constants';
import {
pageEvalAll, waitUntilElementDisappear, waitUntilElementFound, waitUntilIframeFound,
} from '../helpers/elements-interactions';
import { fetchPostWithinPage } from '../helpers/fetch';
import { waitForUrl } from '../helpers/navigation';
import {
Transaction, TransactionsAccount, TransactionStatuses, TransactionTypes,
} from '../transactions';
import { ScraperCredentials, ScraperErrorTypes } from './base-scraper';
import { BaseScraperWithBrowser, LoginResults, PossibleLoginResults } from './base-scraper-with-browser';
interface ScrapedTransaction {
RecTypeSpecified: boolean;
MC02PeulaTaaEZ: string;
MC02SchumEZ: number;
MC02AsmahtaMekoritEZ: string;
MC02TnuaTeurEZ: string;
}
interface ScrapedTransactionsResult {
header: {
success: boolean;
messages: { text: string }[];
};
body: {
fields: {
AccountNumber: string;
YitraLeloChekim: string;
};
table: {
rows: ScrapedTransaction[];
};
};
}
const BASE_WEBSITE_URL = 'https://www.mizrahi-tefahot.co.il';
const LOGIN_URL = `${BASE_WEBSITE_URL}/login/index.html#/auth-page-he`;
const BASE_APP_URL = 'https://mto.mizrahi-tefahot.co.il';
const AFTER_LOGIN_BASE_URL = /https:\/\/mto\.mizrahi-tefahot\.co\.il\/ngOnline\/index\.html#\/main\/uis/;
const OSH_PAGE = `${BASE_APP_URL}/ngOnline/index.html#/main/uis/osh/p428/`;
const TRANSACTIONS_REQUEST_URL = `${BASE_APP_URL}/Online/api/SkyOSH/get428Index`;
const PENDING_TRANSACTIONS_PAGE = `${BASE_APP_URL}/ngOnline/index.html#/main/uis/legacy/Osh/p420//legacy.Osh.p420`;
const PENDING_TRANSACTIONS_IFRAME = 'p420.aspx';
const CHANGE_PASSWORD_URL = /https:\/\/www\.mizrahi-tefahot\.co\.il\/login\/\w+\/index\.html#\/change-pass/;
const DATE_FORMAT = 'DD/MM/YYYY';
const MAX_ROWS_PER_REQUEST = 10000000000;
const usernameSelector = '#emailDesktopHeb';
const passwordSelector = '#passwordIDDesktopHEB';
const submitButtonSelector = '.form-desktop button';
const invalidPasswordSelector = 'a[href*="https://sc.mizrahi-tefahot.co.il/SCServices/SC/P010.aspx"]';
const afterLoginSelector = '#stickyHeaderScrollRegion';
const loginSpinnerSelector = 'div.ngx-overlay.loading-foreground';
const accountDropDownItemSelector = '#sky-account-combo-list ul li .sky-acc-value';
const pendingTrxIdentifierId = '#ctl00_ContentPlaceHolder2_panel1';
function createLoginFields(credentials: ScraperCredentials) {
return [
{ selector: usernameSelector, value: credentials.username },
{ selector: passwordSelector, value: credentials.password },
];
}
function getPossibleLoginResults(page: Page): PossibleLoginResults {
return {
[LoginResults.Success]: [AFTER_LOGIN_BASE_URL],
[LoginResults.InvalidPassword]: [async () => !!(await page.$(invalidPasswordSelector))],
[LoginResults.ChangePassword]: [CHANGE_PASSWORD_URL],
};
}
function getStartMoment(optionsStartDate: Date) {
const defaultStartMoment = moment().subtract(1, 'years');
const startDate = optionsStartDate || defaultStartMoment.toDate();
return moment.max(defaultStartMoment, moment(startDate));
}
function createDataFromRequest(request: Request, optionsStartDate: Date) {
const data = JSON.parse(request.postData() || '{}');
data.inFromDate = getStartMoment(optionsStartDate).format(DATE_FORMAT);
data.inToDate = moment().format(DATE_FORMAT);
data.table.maxRow = MAX_ROWS_PER_REQUEST;
return data;
}
function createHeadersFromRequest(request: Request) {
return {
mizrahixsrftoken: request.headers().mizrahixsrftoken,
'Content-Type': request.headers()['content-type'],
};
}
function convertTransactions(txns: ScrapedTransaction[]): Transaction[] {
return txns.map((row) => {
const txnDate = moment(row.MC02PeulaTaaEZ, moment.HTML5_FMT.DATETIME_LOCAL_SECONDS)
.toISOString();
return {
type: TransactionTypes.Normal,
identifier: row.MC02AsmahtaMekoritEZ ? parseInt(row.MC02AsmahtaMekoritEZ, 10) : undefined,
date: txnDate,
processedDate: txnDate,
originalAmount: row.MC02SchumEZ,
originalCurrency: SHEKEL_CURRENCY,
chargedAmount: row.MC02SchumEZ,
description: row.MC02TnuaTeurEZ,
status: TransactionStatuses.Completed,
};
});
}
async function extractPendingTransactions(page: Frame): Promise<Transaction[]> {
const pendingTxn = await pageEvalAll(page, 'tr.rgRow', [], (trs) => {
return trs.map((tr) => Array.from(tr.querySelectorAll('td'), (td: HTMLTableDataCellElement) => td.textContent || ''));
});
return pendingTxn.map((txn) => {
const date = moment(txn[0], 'DD/MM/YY').toISOString();
const amount = parseInt(txn[3], 10);
return {
type: TransactionTypes.Normal,
date,
processedDate: date,
originalAmount: amount,
originalCurrency: SHEKEL_CURRENCY,
chargedAmount: amount,
description: txn[1],
status: TransactionStatuses.Pending,
};
});
}
async function postLogin(page: Page) {
await Promise.race([
waitUntilElementFound(page, afterLoginSelector),
waitUntilElementFound(page, invalidPasswordSelector),
waitForUrl(page, CHANGE_PASSWORD_URL),
]); |
class MizrahiScraper extends BaseScraperWithBrowser {
getLoginOptions(credentials: ScraperCredentials) {
return {
loginUrl: LOGIN_URL,
fields: createLoginFields(credentials),
submitButtonSelector,
checkReadiness: async () => waitUntilElementDisappear(this.page, loginSpinnerSelector),
postAction: async () => postLogin(this.page),
possibleResults: getPossibleLoginResults(this.page),
};
}
async fetchData() {
const numOfAccounts = (await this.page.$$(accountDropDownItemSelector)).length;
try {
const results: TransactionsAccount[] = [];
for (let i = 0; i < numOfAccounts; i += 1) {
await this.page.$$eval(accountDropDownItemSelector, (els, i) => (els[i] as HTMLElement).click(), i);
results.push(await this.fetchAccount());
}
return {
success: true,
accounts: results,
};
} catch (e) {
return {
success: false,
errorType: ScraperErrorTypes.Generic,
errorMessage: (e as Error).message,
};
}
}
private async fetchAccount() {
await this.navigateTo(OSH_PAGE, this.page);
const request = await this.page.waitForRequest(TRANSACTIONS_REQUEST_URL);
const data = createDataFromRequest(request, this.options.startDate);
const headers = createHeadersFromRequest(request);
const response = await fetchPostWithinPage<ScrapedTransactionsResult>(this.page,
TRANSACTIONS_REQUEST_URL, data, headers);
if (!response || response.header.success === false) {
throw new Error(`Error fetching transaction. Response message: ${response ? response.header.messages[0].text : ''}`);
}
const relevantRows = response.body.table.rows.filter((row) => row.RecTypeSpecified);
const oshTxn = convertTransactions(relevantRows);
// workaround for a bug which the bank's API returns transactions before the requested start date
const startMoment = getStartMoment(this.options.startDate);
const oshTxnAfterStartDate = oshTxn.filter((txn) => moment(txn.date).isSameOrAfter(startMoment));
await this.navigateTo(PENDING_TRANSACTIONS_PAGE, this.page);
const frame = await waitUntilIframeFound(this.page, (f) => f.url().includes(PENDING_TRANSACTIONS_IFRAME));
await waitUntilElementFound(frame, pendingTrxIdentifierId);
const pendingTxn = await extractPendingTransactions(frame);
const allTxn = oshTxnAfterStartDate.concat(pendingTxn);
return {
accountNumber: response.body.fields.AccountNumber,
txns: allTxn,
balance: +response.body.fields.YitraLeloChekim,
};
}
}
export default MizrahiScraper; | } | random_line_split |
mizrahi.ts | import moment from 'moment';
import { Frame, Page, Request } from 'puppeteer';
import { SHEKEL_CURRENCY } from '../constants';
import {
pageEvalAll, waitUntilElementDisappear, waitUntilElementFound, waitUntilIframeFound,
} from '../helpers/elements-interactions';
import { fetchPostWithinPage } from '../helpers/fetch';
import { waitForUrl } from '../helpers/navigation';
import {
Transaction, TransactionsAccount, TransactionStatuses, TransactionTypes,
} from '../transactions';
import { ScraperCredentials, ScraperErrorTypes } from './base-scraper';
import { BaseScraperWithBrowser, LoginResults, PossibleLoginResults } from './base-scraper-with-browser';
interface ScrapedTransaction {
RecTypeSpecified: boolean;
MC02PeulaTaaEZ: string;
MC02SchumEZ: number;
MC02AsmahtaMekoritEZ: string;
MC02TnuaTeurEZ: string;
}
interface ScrapedTransactionsResult {
header: {
success: boolean;
messages: { text: string }[];
};
body: {
fields: {
AccountNumber: string;
YitraLeloChekim: string;
};
table: {
rows: ScrapedTransaction[];
};
};
}
const BASE_WEBSITE_URL = 'https://www.mizrahi-tefahot.co.il';
const LOGIN_URL = `${BASE_WEBSITE_URL}/login/index.html#/auth-page-he`;
const BASE_APP_URL = 'https://mto.mizrahi-tefahot.co.il';
const AFTER_LOGIN_BASE_URL = /https:\/\/mto\.mizrahi-tefahot\.co\.il\/ngOnline\/index\.html#\/main\/uis/;
const OSH_PAGE = `${BASE_APP_URL}/ngOnline/index.html#/main/uis/osh/p428/`;
const TRANSACTIONS_REQUEST_URL = `${BASE_APP_URL}/Online/api/SkyOSH/get428Index`;
const PENDING_TRANSACTIONS_PAGE = `${BASE_APP_URL}/ngOnline/index.html#/main/uis/legacy/Osh/p420//legacy.Osh.p420`;
const PENDING_TRANSACTIONS_IFRAME = 'p420.aspx';
const CHANGE_PASSWORD_URL = /https:\/\/www\.mizrahi-tefahot\.co\.il\/login\/\w+\/index\.html#\/change-pass/;
const DATE_FORMAT = 'DD/MM/YYYY';
const MAX_ROWS_PER_REQUEST = 10000000000;
const usernameSelector = '#emailDesktopHeb';
const passwordSelector = '#passwordIDDesktopHEB';
const submitButtonSelector = '.form-desktop button';
const invalidPasswordSelector = 'a[href*="https://sc.mizrahi-tefahot.co.il/SCServices/SC/P010.aspx"]';
const afterLoginSelector = '#stickyHeaderScrollRegion';
const loginSpinnerSelector = 'div.ngx-overlay.loading-foreground';
const accountDropDownItemSelector = '#sky-account-combo-list ul li .sky-acc-value';
const pendingTrxIdentifierId = '#ctl00_ContentPlaceHolder2_panel1';
function createLoginFields(credentials: ScraperCredentials) {
return [
{ selector: usernameSelector, value: credentials.username },
{ selector: passwordSelector, value: credentials.password },
];
}
function getPossibleLoginResults(page: Page): PossibleLoginResults {
return {
[LoginResults.Success]: [AFTER_LOGIN_BASE_URL],
[LoginResults.InvalidPassword]: [async () => !!(await page.$(invalidPasswordSelector))],
[LoginResults.ChangePassword]: [CHANGE_PASSWORD_URL],
};
}
function getStartMoment(optionsStartDate: Date) {
const defaultStartMoment = moment().subtract(1, 'years');
const startDate = optionsStartDate || defaultStartMoment.toDate();
return moment.max(defaultStartMoment, moment(startDate));
}
function createDataFromRequest(request: Request, optionsStartDate: Date) {
const data = JSON.parse(request.postData() || '{}');
data.inFromDate = getStartMoment(optionsStartDate).format(DATE_FORMAT);
data.inToDate = moment().format(DATE_FORMAT);
data.table.maxRow = MAX_ROWS_PER_REQUEST;
return data;
}
function createHeadersFromRequest(request: Request) {
return {
mizrahixsrftoken: request.headers().mizrahixsrftoken,
'Content-Type': request.headers()['content-type'],
};
}
function convertTransactions(txns: ScrapedTransaction[]): Transaction[] {
return txns.map((row) => {
const txnDate = moment(row.MC02PeulaTaaEZ, moment.HTML5_FMT.DATETIME_LOCAL_SECONDS)
.toISOString();
return {
type: TransactionTypes.Normal,
identifier: row.MC02AsmahtaMekoritEZ ? parseInt(row.MC02AsmahtaMekoritEZ, 10) : undefined,
date: txnDate,
processedDate: txnDate,
originalAmount: row.MC02SchumEZ,
originalCurrency: SHEKEL_CURRENCY,
chargedAmount: row.MC02SchumEZ,
description: row.MC02TnuaTeurEZ,
status: TransactionStatuses.Completed,
};
});
}
async function extractPendingTransactions(page: Frame): Promise<Transaction[]> {
const pendingTxn = await pageEvalAll(page, 'tr.rgRow', [], (trs) => {
return trs.map((tr) => Array.from(tr.querySelectorAll('td'), (td: HTMLTableDataCellElement) => td.textContent || ''));
});
return pendingTxn.map((txn) => {
const date = moment(txn[0], 'DD/MM/YY').toISOString();
const amount = parseInt(txn[3], 10);
return {
type: TransactionTypes.Normal,
date,
processedDate: date,
originalAmount: amount,
originalCurrency: SHEKEL_CURRENCY,
chargedAmount: amount,
description: txn[1],
status: TransactionStatuses.Pending,
};
});
}
async function postLogin(page: Page) {
await Promise.race([
waitUntilElementFound(page, afterLoginSelector),
waitUntilElementFound(page, invalidPasswordSelector),
waitForUrl(page, CHANGE_PASSWORD_URL),
]);
}
class MizrahiScraper extends BaseScraperWithBrowser {
getLoginOptions(credentials: ScraperCredentials) {
return {
loginUrl: LOGIN_URL,
fields: createLoginFields(credentials),
submitButtonSelector,
checkReadiness: async () => waitUntilElementDisappear(this.page, loginSpinnerSelector),
postAction: async () => postLogin(this.page),
possibleResults: getPossibleLoginResults(this.page),
};
}
async fetchData() {
const numOfAccounts = (await this.page.$$(accountDropDownItemSelector)).length;
try {
const results: TransactionsAccount[] = [];
for (let i = 0; i < numOfAccounts; i += 1) |
return {
success: true,
accounts: results,
};
} catch (e) {
return {
success: false,
errorType: ScraperErrorTypes.Generic,
errorMessage: (e as Error).message,
};
}
}
private async fetchAccount() {
await this.navigateTo(OSH_PAGE, this.page);
const request = await this.page.waitForRequest(TRANSACTIONS_REQUEST_URL);
const data = createDataFromRequest(request, this.options.startDate);
const headers = createHeadersFromRequest(request);
const response = await fetchPostWithinPage<ScrapedTransactionsResult>(this.page,
TRANSACTIONS_REQUEST_URL, data, headers);
if (!response || response.header.success === false) {
throw new Error(`Error fetching transaction. Response message: ${response ? response.header.messages[0].text : ''}`);
}
const relevantRows = response.body.table.rows.filter((row) => row.RecTypeSpecified);
const oshTxn = convertTransactions(relevantRows);
// workaround for a bug which the bank's API returns transactions before the requested start date
const startMoment = getStartMoment(this.options.startDate);
const oshTxnAfterStartDate = oshTxn.filter((txn) => moment(txn.date).isSameOrAfter(startMoment));
await this.navigateTo(PENDING_TRANSACTIONS_PAGE, this.page);
const frame = await waitUntilIframeFound(this.page, (f) => f.url().includes(PENDING_TRANSACTIONS_IFRAME));
await waitUntilElementFound(frame, pendingTrxIdentifierId);
const pendingTxn = await extractPendingTransactions(frame);
const allTxn = oshTxnAfterStartDate.concat(pendingTxn);
return {
accountNumber: response.body.fields.AccountNumber,
txns: allTxn,
balance: +response.body.fields.YitraLeloChekim,
};
}
}
export default MizrahiScraper;
| {
await this.page.$$eval(accountDropDownItemSelector, (els, i) => (els[i] as HTMLElement).click(), i);
results.push(await this.fetchAccount());
} | conditional_block |
mizrahi.ts | import moment from 'moment';
import { Frame, Page, Request } from 'puppeteer';
import { SHEKEL_CURRENCY } from '../constants';
import {
pageEvalAll, waitUntilElementDisappear, waitUntilElementFound, waitUntilIframeFound,
} from '../helpers/elements-interactions';
import { fetchPostWithinPage } from '../helpers/fetch';
import { waitForUrl } from '../helpers/navigation';
import {
Transaction, TransactionsAccount, TransactionStatuses, TransactionTypes,
} from '../transactions';
import { ScraperCredentials, ScraperErrorTypes } from './base-scraper';
import { BaseScraperWithBrowser, LoginResults, PossibleLoginResults } from './base-scraper-with-browser';
interface ScrapedTransaction {
RecTypeSpecified: boolean;
MC02PeulaTaaEZ: string;
MC02SchumEZ: number;
MC02AsmahtaMekoritEZ: string;
MC02TnuaTeurEZ: string;
}
interface ScrapedTransactionsResult {
header: {
success: boolean;
messages: { text: string }[];
};
body: {
fields: {
AccountNumber: string;
YitraLeloChekim: string;
};
table: {
rows: ScrapedTransaction[];
};
};
}
const BASE_WEBSITE_URL = 'https://www.mizrahi-tefahot.co.il';
const LOGIN_URL = `${BASE_WEBSITE_URL}/login/index.html#/auth-page-he`;
const BASE_APP_URL = 'https://mto.mizrahi-tefahot.co.il';
const AFTER_LOGIN_BASE_URL = /https:\/\/mto\.mizrahi-tefahot\.co\.il\/ngOnline\/index\.html#\/main\/uis/;
const OSH_PAGE = `${BASE_APP_URL}/ngOnline/index.html#/main/uis/osh/p428/`;
const TRANSACTIONS_REQUEST_URL = `${BASE_APP_URL}/Online/api/SkyOSH/get428Index`;
const PENDING_TRANSACTIONS_PAGE = `${BASE_APP_URL}/ngOnline/index.html#/main/uis/legacy/Osh/p420//legacy.Osh.p420`;
const PENDING_TRANSACTIONS_IFRAME = 'p420.aspx';
const CHANGE_PASSWORD_URL = /https:\/\/www\.mizrahi-tefahot\.co\.il\/login\/\w+\/index\.html#\/change-pass/;
const DATE_FORMAT = 'DD/MM/YYYY';
const MAX_ROWS_PER_REQUEST = 10000000000;
const usernameSelector = '#emailDesktopHeb';
const passwordSelector = '#passwordIDDesktopHEB';
const submitButtonSelector = '.form-desktop button';
const invalidPasswordSelector = 'a[href*="https://sc.mizrahi-tefahot.co.il/SCServices/SC/P010.aspx"]';
const afterLoginSelector = '#stickyHeaderScrollRegion';
const loginSpinnerSelector = 'div.ngx-overlay.loading-foreground';
const accountDropDownItemSelector = '#sky-account-combo-list ul li .sky-acc-value';
const pendingTrxIdentifierId = '#ctl00_ContentPlaceHolder2_panel1';
function createLoginFields(credentials: ScraperCredentials) |
function getPossibleLoginResults(page: Page): PossibleLoginResults {
return {
[LoginResults.Success]: [AFTER_LOGIN_BASE_URL],
[LoginResults.InvalidPassword]: [async () => !!(await page.$(invalidPasswordSelector))],
[LoginResults.ChangePassword]: [CHANGE_PASSWORD_URL],
};
}
function getStartMoment(optionsStartDate: Date) {
const defaultStartMoment = moment().subtract(1, 'years');
const startDate = optionsStartDate || defaultStartMoment.toDate();
return moment.max(defaultStartMoment, moment(startDate));
}
function createDataFromRequest(request: Request, optionsStartDate: Date) {
const data = JSON.parse(request.postData() || '{}');
data.inFromDate = getStartMoment(optionsStartDate).format(DATE_FORMAT);
data.inToDate = moment().format(DATE_FORMAT);
data.table.maxRow = MAX_ROWS_PER_REQUEST;
return data;
}
function createHeadersFromRequest(request: Request) {
return {
mizrahixsrftoken: request.headers().mizrahixsrftoken,
'Content-Type': request.headers()['content-type'],
};
}
function convertTransactions(txns: ScrapedTransaction[]): Transaction[] {
return txns.map((row) => {
const txnDate = moment(row.MC02PeulaTaaEZ, moment.HTML5_FMT.DATETIME_LOCAL_SECONDS)
.toISOString();
return {
type: TransactionTypes.Normal,
identifier: row.MC02AsmahtaMekoritEZ ? parseInt(row.MC02AsmahtaMekoritEZ, 10) : undefined,
date: txnDate,
processedDate: txnDate,
originalAmount: row.MC02SchumEZ,
originalCurrency: SHEKEL_CURRENCY,
chargedAmount: row.MC02SchumEZ,
description: row.MC02TnuaTeurEZ,
status: TransactionStatuses.Completed,
};
});
}
async function extractPendingTransactions(page: Frame): Promise<Transaction[]> {
const pendingTxn = await pageEvalAll(page, 'tr.rgRow', [], (trs) => {
return trs.map((tr) => Array.from(tr.querySelectorAll('td'), (td: HTMLTableDataCellElement) => td.textContent || ''));
});
return pendingTxn.map((txn) => {
const date = moment(txn[0], 'DD/MM/YY').toISOString();
const amount = parseInt(txn[3], 10);
return {
type: TransactionTypes.Normal,
date,
processedDate: date,
originalAmount: amount,
originalCurrency: SHEKEL_CURRENCY,
chargedAmount: amount,
description: txn[1],
status: TransactionStatuses.Pending,
};
});
}
async function postLogin(page: Page) {
await Promise.race([
waitUntilElementFound(page, afterLoginSelector),
waitUntilElementFound(page, invalidPasswordSelector),
waitForUrl(page, CHANGE_PASSWORD_URL),
]);
}
class MizrahiScraper extends BaseScraperWithBrowser {
getLoginOptions(credentials: ScraperCredentials) {
return {
loginUrl: LOGIN_URL,
fields: createLoginFields(credentials),
submitButtonSelector,
checkReadiness: async () => waitUntilElementDisappear(this.page, loginSpinnerSelector),
postAction: async () => postLogin(this.page),
possibleResults: getPossibleLoginResults(this.page),
};
}
async fetchData() {
const numOfAccounts = (await this.page.$$(accountDropDownItemSelector)).length;
try {
const results: TransactionsAccount[] = [];
for (let i = 0; i < numOfAccounts; i += 1) {
await this.page.$$eval(accountDropDownItemSelector, (els, i) => (els[i] as HTMLElement).click(), i);
results.push(await this.fetchAccount());
}
return {
success: true,
accounts: results,
};
} catch (e) {
return {
success: false,
errorType: ScraperErrorTypes.Generic,
errorMessage: (e as Error).message,
};
}
}
private async fetchAccount() {
await this.navigateTo(OSH_PAGE, this.page);
const request = await this.page.waitForRequest(TRANSACTIONS_REQUEST_URL);
const data = createDataFromRequest(request, this.options.startDate);
const headers = createHeadersFromRequest(request);
const response = await fetchPostWithinPage<ScrapedTransactionsResult>(this.page,
TRANSACTIONS_REQUEST_URL, data, headers);
if (!response || response.header.success === false) {
throw new Error(`Error fetching transaction. Response message: ${response ? response.header.messages[0].text : ''}`);
}
const relevantRows = response.body.table.rows.filter((row) => row.RecTypeSpecified);
const oshTxn = convertTransactions(relevantRows);
// workaround for a bug which the bank's API returns transactions before the requested start date
const startMoment = getStartMoment(this.options.startDate);
const oshTxnAfterStartDate = oshTxn.filter((txn) => moment(txn.date).isSameOrAfter(startMoment));
await this.navigateTo(PENDING_TRANSACTIONS_PAGE, this.page);
const frame = await waitUntilIframeFound(this.page, (f) => f.url().includes(PENDING_TRANSACTIONS_IFRAME));
await waitUntilElementFound(frame, pendingTrxIdentifierId);
const pendingTxn = await extractPendingTransactions(frame);
const allTxn = oshTxnAfterStartDate.concat(pendingTxn);
return {
accountNumber: response.body.fields.AccountNumber,
txns: allTxn,
balance: +response.body.fields.YitraLeloChekim,
};
}
}
export default MizrahiScraper;
| {
return [
{ selector: usernameSelector, value: credentials.username },
{ selector: passwordSelector, value: credentials.password },
];
} | identifier_body |
mizrahi.ts | import moment from 'moment';
import { Frame, Page, Request } from 'puppeteer';
import { SHEKEL_CURRENCY } from '../constants';
import {
pageEvalAll, waitUntilElementDisappear, waitUntilElementFound, waitUntilIframeFound,
} from '../helpers/elements-interactions';
import { fetchPostWithinPage } from '../helpers/fetch';
import { waitForUrl } from '../helpers/navigation';
import {
Transaction, TransactionsAccount, TransactionStatuses, TransactionTypes,
} from '../transactions';
import { ScraperCredentials, ScraperErrorTypes } from './base-scraper';
import { BaseScraperWithBrowser, LoginResults, PossibleLoginResults } from './base-scraper-with-browser';
interface ScrapedTransaction {
RecTypeSpecified: boolean;
MC02PeulaTaaEZ: string;
MC02SchumEZ: number;
MC02AsmahtaMekoritEZ: string;
MC02TnuaTeurEZ: string;
}
interface ScrapedTransactionsResult {
header: {
success: boolean;
messages: { text: string }[];
};
body: {
fields: {
AccountNumber: string;
YitraLeloChekim: string;
};
table: {
rows: ScrapedTransaction[];
};
};
}
const BASE_WEBSITE_URL = 'https://www.mizrahi-tefahot.co.il';
const LOGIN_URL = `${BASE_WEBSITE_URL}/login/index.html#/auth-page-he`;
const BASE_APP_URL = 'https://mto.mizrahi-tefahot.co.il';
const AFTER_LOGIN_BASE_URL = /https:\/\/mto\.mizrahi-tefahot\.co\.il\/ngOnline\/index\.html#\/main\/uis/;
const OSH_PAGE = `${BASE_APP_URL}/ngOnline/index.html#/main/uis/osh/p428/`;
const TRANSACTIONS_REQUEST_URL = `${BASE_APP_URL}/Online/api/SkyOSH/get428Index`;
const PENDING_TRANSACTIONS_PAGE = `${BASE_APP_URL}/ngOnline/index.html#/main/uis/legacy/Osh/p420//legacy.Osh.p420`;
const PENDING_TRANSACTIONS_IFRAME = 'p420.aspx';
const CHANGE_PASSWORD_URL = /https:\/\/www\.mizrahi-tefahot\.co\.il\/login\/\w+\/index\.html#\/change-pass/;
const DATE_FORMAT = 'DD/MM/YYYY';
const MAX_ROWS_PER_REQUEST = 10000000000;
const usernameSelector = '#emailDesktopHeb';
const passwordSelector = '#passwordIDDesktopHEB';
const submitButtonSelector = '.form-desktop button';
const invalidPasswordSelector = 'a[href*="https://sc.mizrahi-tefahot.co.il/SCServices/SC/P010.aspx"]';
const afterLoginSelector = '#stickyHeaderScrollRegion';
const loginSpinnerSelector = 'div.ngx-overlay.loading-foreground';
const accountDropDownItemSelector = '#sky-account-combo-list ul li .sky-acc-value';
const pendingTrxIdentifierId = '#ctl00_ContentPlaceHolder2_panel1';
function createLoginFields(credentials: ScraperCredentials) {
return [
{ selector: usernameSelector, value: credentials.username },
{ selector: passwordSelector, value: credentials.password },
];
}
function getPossibleLoginResults(page: Page): PossibleLoginResults {
return {
[LoginResults.Success]: [AFTER_LOGIN_BASE_URL],
[LoginResults.InvalidPassword]: [async () => !!(await page.$(invalidPasswordSelector))],
[LoginResults.ChangePassword]: [CHANGE_PASSWORD_URL],
};
}
function getStartMoment(optionsStartDate: Date) {
const defaultStartMoment = moment().subtract(1, 'years');
const startDate = optionsStartDate || defaultStartMoment.toDate();
return moment.max(defaultStartMoment, moment(startDate));
}
function createDataFromRequest(request: Request, optionsStartDate: Date) {
const data = JSON.parse(request.postData() || '{}');
data.inFromDate = getStartMoment(optionsStartDate).format(DATE_FORMAT);
data.inToDate = moment().format(DATE_FORMAT);
data.table.maxRow = MAX_ROWS_PER_REQUEST;
return data;
}
function createHeadersFromRequest(request: Request) {
return {
mizrahixsrftoken: request.headers().mizrahixsrftoken,
'Content-Type': request.headers()['content-type'],
};
}
function convertTransactions(txns: ScrapedTransaction[]): Transaction[] {
return txns.map((row) => {
const txnDate = moment(row.MC02PeulaTaaEZ, moment.HTML5_FMT.DATETIME_LOCAL_SECONDS)
.toISOString();
return {
type: TransactionTypes.Normal,
identifier: row.MC02AsmahtaMekoritEZ ? parseInt(row.MC02AsmahtaMekoritEZ, 10) : undefined,
date: txnDate,
processedDate: txnDate,
originalAmount: row.MC02SchumEZ,
originalCurrency: SHEKEL_CURRENCY,
chargedAmount: row.MC02SchumEZ,
description: row.MC02TnuaTeurEZ,
status: TransactionStatuses.Completed,
};
});
}
async function extractPendingTransactions(page: Frame): Promise<Transaction[]> {
const pendingTxn = await pageEvalAll(page, 'tr.rgRow', [], (trs) => {
return trs.map((tr) => Array.from(tr.querySelectorAll('td'), (td: HTMLTableDataCellElement) => td.textContent || ''));
});
return pendingTxn.map((txn) => {
const date = moment(txn[0], 'DD/MM/YY').toISOString();
const amount = parseInt(txn[3], 10);
return {
type: TransactionTypes.Normal,
date,
processedDate: date,
originalAmount: amount,
originalCurrency: SHEKEL_CURRENCY,
chargedAmount: amount,
description: txn[1],
status: TransactionStatuses.Pending,
};
});
}
async function postLogin(page: Page) {
await Promise.race([
waitUntilElementFound(page, afterLoginSelector),
waitUntilElementFound(page, invalidPasswordSelector),
waitForUrl(page, CHANGE_PASSWORD_URL),
]);
}
class MizrahiScraper extends BaseScraperWithBrowser {
getLoginOptions(credentials: ScraperCredentials) {
return {
loginUrl: LOGIN_URL,
fields: createLoginFields(credentials),
submitButtonSelector,
checkReadiness: async () => waitUntilElementDisappear(this.page, loginSpinnerSelector),
postAction: async () => postLogin(this.page),
possibleResults: getPossibleLoginResults(this.page),
};
}
async | () {
const numOfAccounts = (await this.page.$$(accountDropDownItemSelector)).length;
try {
const results: TransactionsAccount[] = [];
for (let i = 0; i < numOfAccounts; i += 1) {
await this.page.$$eval(accountDropDownItemSelector, (els, i) => (els[i] as HTMLElement).click(), i);
results.push(await this.fetchAccount());
}
return {
success: true,
accounts: results,
};
} catch (e) {
return {
success: false,
errorType: ScraperErrorTypes.Generic,
errorMessage: (e as Error).message,
};
}
}
private async fetchAccount() {
await this.navigateTo(OSH_PAGE, this.page);
const request = await this.page.waitForRequest(TRANSACTIONS_REQUEST_URL);
const data = createDataFromRequest(request, this.options.startDate);
const headers = createHeadersFromRequest(request);
const response = await fetchPostWithinPage<ScrapedTransactionsResult>(this.page,
TRANSACTIONS_REQUEST_URL, data, headers);
if (!response || response.header.success === false) {
throw new Error(`Error fetching transaction. Response message: ${response ? response.header.messages[0].text : ''}`);
}
const relevantRows = response.body.table.rows.filter((row) => row.RecTypeSpecified);
const oshTxn = convertTransactions(relevantRows);
// workaround for a bug which the bank's API returns transactions before the requested start date
const startMoment = getStartMoment(this.options.startDate);
const oshTxnAfterStartDate = oshTxn.filter((txn) => moment(txn.date).isSameOrAfter(startMoment));
await this.navigateTo(PENDING_TRANSACTIONS_PAGE, this.page);
const frame = await waitUntilIframeFound(this.page, (f) => f.url().includes(PENDING_TRANSACTIONS_IFRAME));
await waitUntilElementFound(frame, pendingTrxIdentifierId);
const pendingTxn = await extractPendingTransactions(frame);
const allTxn = oshTxnAfterStartDate.concat(pendingTxn);
return {
accountNumber: response.body.fields.AccountNumber,
txns: allTxn,
balance: +response.body.fields.YitraLeloChekim,
};
}
}
export default MizrahiScraper;
| fetchData | identifier_name |
ExpandableGalleryTest.js | /**
* Copyright (C) 2005-2016 Alfresco Software Limited.
* | * it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Dave Draper
*/
define(["module",
"alfresco/defineSuite",
"intern/chai!assert",
"alfresco/TestCommon",
"intern/dojo/node!leadfoot/keys"],
function(module, defineSuite, assert, TestCommon, keys) {
var textBoxSelectors = TestCommon.getTestSelectors("alfresco/forms/controls/TextBox");
var inlineEditPropertySelectors = TestCommon.getTestSelectors("alfresco/renderers/InlineEditProperty");
var selectors = {
textBoxes: {
alternateExpanded: {
input: TestCommon.getTestSelector(textBoxSelectors, "input", ["APPENDIX_TEXTBOX"]),
}
},
inlineEditProperties: {
alternateExpanded: {
editIcon: TestCommon.getTestSelector(inlineEditPropertySelectors, "edit.icon", ["EXPANDED_LIST_INLINE_EDIT_ITEM_0"]),
editSave: TestCommon.getTestSelector(inlineEditPropertySelectors, "edit.save", ["EXPANDED_LIST_INLINE_EDIT_ITEM_0"]),
editCancel: TestCommon.getTestSelector(inlineEditPropertySelectors, "edit.cancel", ["EXPANDED_LIST_INLINE_EDIT_ITEM_0"]),
editInput: TestCommon.getTestSelector(inlineEditPropertySelectors, "edit.input", ["EXPANDED_LIST_INLINE_EDIT_ITEM_0"])
}
}
};
defineSuite(module, {
name: "Expandable Gallery View Tests",
testPage: "/ExandableGallery",
"There should be no expanded cells": function() {
return this.remote.findDisplayedById("CELL_CONTAINER_ITEM_0")
.end()
.findAllByCssSelector(".alfresco-lists-views-layouts-Grid__expandedPanel")
.then(function(elements) {
assert.lengthOf(elements, 0, "Unexpected expanded panel found");
});
},
"Click on a cell to expand": function() {
return this.remote.findDisplayedById("CELL_CONTAINER_ITEM_0")
.click()
.end()
.findByCssSelector(".alfresco-lists-views-layouts-Grid__expandedPanel");
},
"Resize window to make sure expanded cell remains the same size": function() {
var originalWidth;
return this.remote.findByCssSelector(".alfresco-lists-views-layouts-Grid__expandedPanel td")
.getSize()
.then(function(size) {
originalWidth = size.width;
})
.setWindowSize(null, 1500, 768)
.getSize()
.then(function(size) {
assert.isAbove(size.width, originalWidth, "Expanded panel cell should not have got smaller");
});
},
"Check the expanded panel position": function() {
// This verifies that the expanded panel has been inserted in the 2nd row...
return this.remote.findByCssSelector(".alfresco-lists-views-layouts-Grid tr.alfresco-lists-views-layouts-Grid__expandedPanel:nth-child(2)");
},
"Check that expanded panel has focus": function() {
return this.remote.getActiveElement()
.getProperty("value")
.then(function(value) {
assert.equal(value, "Monthly HES Summary Data", "The form field in the expanded element was not focused");
});
},
"Use escape key to close panel": function() {
return this.remote.pressKeys(keys.ESCAPE)
.waitForDeletedByCssSelector(".alfresco-lists-views-layouts-Grid__expandedPanel");
},
"The expanded cell should be re-focused": function() {
return this.remote.findByCssSelector(".alfresco-lists-views-layouts-Grid__cell--focused #CELL_CONTAINER_ITEM_0");
},
"Keyboard navigate to and expand another cell": function() {
return this.remote.pressKeys(keys.ARROW_RIGHT)
.findByCssSelector(".alfresco-lists-views-layouts-Grid__cell--focused #CELL_CONTAINER_ITEM_1")
.end()
.pressKeys(keys.RETURN)
.findByCssSelector(".alfresco-lists-views-layouts-Grid__expandedPanel")
.end()
.getActiveElement()
.getProperty("value")
.then(function(value) {
assert.equal(value, "Telford and Wrekin Council", "The form field in the expanded element was not focused");
});
},
"Use mouse to close expanded cell": function() {
return this.remote.findById("CELL_CONTAINER_ITEM_1")
.click()
.end()
.waitForDeletedByCssSelector(".alfresco-lists-views-layouts-Grid__expandedPanel");
},
"Check that inline edit can be typed into without losing focus": function() {
return this.remote.findByCssSelector("#EXPAND_LINK_ITEM_4 .label")
.click()
.end()
.findDisplayedByCssSelector(".alfresco-lists-views-layouts-Grid__expandedPanel")
.end()
.clearLog()
.findByCssSelector(selectors.inlineEditProperties.alternateExpanded.editIcon)
.click()
.end()
.findDisplayedByCssSelector(selectors.inlineEditProperties.alternateExpanded.editInput)
.clearValue()
.type("hello again")
.end()
.clearLog()
.findByCssSelector(selectors.inlineEditProperties.alternateExpanded.editSave)
.click()
.end()
.getLastPublish("ALT_INLINE_EDIT_SAVE")
.then(function(payload) {
assert.propertyVal(payload, "fake", "hello again");
});
},
"Cursor key use on inline edit do not navigate list": function() {
// NOTE: Because save is not handled in test page, input field will still be focused...
var inputId;
return this.remote.findDisplayedByCssSelector(selectors.inlineEditProperties.alternateExpanded.editInput)
.clearValue()
.type("test")
.getAttribute("id")
.then(function(id) {
inputId = id;
})
.pressKeys([keys.ARROW_LEFT, keys.ARROW_UP, keys.ARROW_RIGHT, keys.ARROW_DOWN])
.end()
.getActiveElement()
.getAttribute("id")
.then(function(id) {
assert.equal(inputId, id);
});
},
"It is possible to type into form control without losing focus": function() {
return this.remote.findDisplayedByCssSelector(selectors.textBoxes.alternateExpanded.input)
.type("hello world")
.end()
.getLastPublish("EditCaveatGroupListView_valueChangeOf_APPENDIX_TEXTBOX")
.then(function(payload) {
assert.propertyVal(payload, "value", "hello world");
});
},
"Cursor key use on focused form control do not navigate list": function() {
var inputId;
return this.remote.findDisplayedByCssSelector(selectors.textBoxes.alternateExpanded.input)
.getAttribute("id")
.then(function(id) {
inputId = id;
})
.pressKeys([keys.ARROW_LEFT, keys.ARROW_UP, keys.ARROW_RIGHT, keys.ARROW_DOWN])
.end()
.getActiveElement()
.getAttribute("id")
.then(function(id) {
assert.equal(inputId, id);
});
}
});
}); | * This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify | random_line_split |
install.js | /**
* @module opcua.address_space
* @class AddressSpace
*/
import assert from "better-assert";
import _ from "underscore";
import NodeClass from "lib/datamodel/NodeClass";
import Argument from "lib/datamodel/argument-list/Argument";
import DataValue from "lib/datamodel/DataValue";
import { Variant } from "lib/datamodel/variant";
import { DataType } from "lib/datamodel/variant";
import { VariantArrayType } from "lib/datamodel/variant";
import { StatusCodes } from "lib/datamodel/opcua_status_code";
import { BrowseDirection } from "lib/services/browse_service";
import UAVariable from "lib/address_space/UAVariable";
import UATwoStateVariable from './UATwoStateVariable';
import util from "util";
function _install_TwoStateVariable_machinery(node,options) |
function install(AddressSpace) {
assert(_.isUndefined(AddressSpace._install_TwoStateVariable_machinery));
AddressSpace._install_TwoStateVariable_machinery = _install_TwoStateVariable_machinery;
/**
*
* @method addTwoStateVariable
*
* @param options
* @param options.browseName {String}
* @param [options.description {String}]
* @param [options.modellingRule {String}]
* @param [options.minimumSamplingInterval {Number} =0]
* @param options.componentOf {Node|NodeId}
* @param options.propertyOf {Node|NodeId}
* @param options.trueState {String}
* @param options.falseState {String}
* @param [options.isTrueSubStateOf {NodeId}]
* @param [options.isFalseSubStateOf {NodeId}]
* @param [options.modellingRule]
* @return {UATwoStateVariable}
*
* Optionals can be EffectiveDisplayName, TransitionTime, EffectiveTransitionTime
*/
AddressSpace.prototype.addTwoStateVariable = function (options) {
assert(options.browseName," a browseName is required");
const addressSpace = this;
const twoStateVariableType = addressSpace.findVariableType("TwoStateVariableType");
options.optionals = options.optionals || [];
if (options.trueState) {
options.optionals.push("TrueState");
}
if (options.falseState) {
options.optionals.push("FalseState");
}
// we want event based change...
options.minimumSamplingInterval = 0;
const node = twoStateVariableType.instantiate({
browseName: options.browseName,
nodeId: options.nodeId,
description: options.description,
organizedBy: options.organizedBy,
componentOf: options.componentOf,
modellingRule: options.modellingRule,
minimumSamplingInterval: options.minimumSamplingInterval,
optionals: options.optionals
});
_install_TwoStateVariable_machinery(node,options);
return node;
};
}
export default install;
| {
assert(node.dataTypeObj.browseName.toString() === "LocalizedText");
assert(node.minimumSamplingInterval === 0);
assert(node.typeDefinitionObj.browseName.toString() === "TwoStateVariableType");
assert(node.dataTypeObj.browseName.toString() === "LocalizedText");
assert(node.hasOwnProperty("valueRank") && (node.valueRank === -1 || node.valueRank === 0));
assert(node.hasOwnProperty("id"));
options = options || {};
// promote node into a UATwoStateVariable
Object.setPrototypeOf(node, UATwoStateVariable.prototype);
node.initialize(options);
} | identifier_body |
install.js | /**
* @module opcua.address_space
* @class AddressSpace
*/
import assert from "better-assert";
import _ from "underscore";
import NodeClass from "lib/datamodel/NodeClass";
import Argument from "lib/datamodel/argument-list/Argument";
import DataValue from "lib/datamodel/DataValue";
import { Variant } from "lib/datamodel/variant";
import { DataType } from "lib/datamodel/variant";
import { VariantArrayType } from "lib/datamodel/variant";
import { StatusCodes } from "lib/datamodel/opcua_status_code"; | import { BrowseDirection } from "lib/services/browse_service";
import UAVariable from "lib/address_space/UAVariable";
import UATwoStateVariable from './UATwoStateVariable';
import util from "util";
function _install_TwoStateVariable_machinery(node,options) {
assert(node.dataTypeObj.browseName.toString() === "LocalizedText");
assert(node.minimumSamplingInterval === 0);
assert(node.typeDefinitionObj.browseName.toString() === "TwoStateVariableType");
assert(node.dataTypeObj.browseName.toString() === "LocalizedText");
assert(node.hasOwnProperty("valueRank") && (node.valueRank === -1 || node.valueRank === 0));
assert(node.hasOwnProperty("id"));
options = options || {};
// promote node into a UATwoStateVariable
Object.setPrototypeOf(node, UATwoStateVariable.prototype);
node.initialize(options);
}
function install(AddressSpace) {
assert(_.isUndefined(AddressSpace._install_TwoStateVariable_machinery));
AddressSpace._install_TwoStateVariable_machinery = _install_TwoStateVariable_machinery;
/**
*
* @method addTwoStateVariable
*
* @param options
* @param options.browseName {String}
* @param [options.description {String}]
* @param [options.modellingRule {String}]
* @param [options.minimumSamplingInterval {Number} =0]
* @param options.componentOf {Node|NodeId}
* @param options.propertyOf {Node|NodeId}
* @param options.trueState {String}
* @param options.falseState {String}
* @param [options.isTrueSubStateOf {NodeId}]
* @param [options.isFalseSubStateOf {NodeId}]
* @param [options.modellingRule]
* @return {UATwoStateVariable}
*
* Optionals can be EffectiveDisplayName, TransitionTime, EffectiveTransitionTime
*/
AddressSpace.prototype.addTwoStateVariable = function (options) {
assert(options.browseName," a browseName is required");
const addressSpace = this;
const twoStateVariableType = addressSpace.findVariableType("TwoStateVariableType");
options.optionals = options.optionals || [];
if (options.trueState) {
options.optionals.push("TrueState");
}
if (options.falseState) {
options.optionals.push("FalseState");
}
// we want event based change...
options.minimumSamplingInterval = 0;
const node = twoStateVariableType.instantiate({
browseName: options.browseName,
nodeId: options.nodeId,
description: options.description,
organizedBy: options.organizedBy,
componentOf: options.componentOf,
modellingRule: options.modellingRule,
minimumSamplingInterval: options.minimumSamplingInterval,
optionals: options.optionals
});
_install_TwoStateVariable_machinery(node,options);
return node;
};
}
export default install; | random_line_split | |
install.js | /**
* @module opcua.address_space
* @class AddressSpace
*/
import assert from "better-assert";
import _ from "underscore";
import NodeClass from "lib/datamodel/NodeClass";
import Argument from "lib/datamodel/argument-list/Argument";
import DataValue from "lib/datamodel/DataValue";
import { Variant } from "lib/datamodel/variant";
import { DataType } from "lib/datamodel/variant";
import { VariantArrayType } from "lib/datamodel/variant";
import { StatusCodes } from "lib/datamodel/opcua_status_code";
import { BrowseDirection } from "lib/services/browse_service";
import UAVariable from "lib/address_space/UAVariable";
import UATwoStateVariable from './UATwoStateVariable';
import util from "util";
function | (node,options) {
assert(node.dataTypeObj.browseName.toString() === "LocalizedText");
assert(node.minimumSamplingInterval === 0);
assert(node.typeDefinitionObj.browseName.toString() === "TwoStateVariableType");
assert(node.dataTypeObj.browseName.toString() === "LocalizedText");
assert(node.hasOwnProperty("valueRank") && (node.valueRank === -1 || node.valueRank === 0));
assert(node.hasOwnProperty("id"));
options = options || {};
// promote node into a UATwoStateVariable
Object.setPrototypeOf(node, UATwoStateVariable.prototype);
node.initialize(options);
}
function install(AddressSpace) {
assert(_.isUndefined(AddressSpace._install_TwoStateVariable_machinery));
AddressSpace._install_TwoStateVariable_machinery = _install_TwoStateVariable_machinery;
/**
*
* @method addTwoStateVariable
*
* @param options
* @param options.browseName {String}
* @param [options.description {String}]
* @param [options.modellingRule {String}]
* @param [options.minimumSamplingInterval {Number} =0]
* @param options.componentOf {Node|NodeId}
* @param options.propertyOf {Node|NodeId}
* @param options.trueState {String}
* @param options.falseState {String}
* @param [options.isTrueSubStateOf {NodeId}]
* @param [options.isFalseSubStateOf {NodeId}]
* @param [options.modellingRule]
* @return {UATwoStateVariable}
*
* Optionals can be EffectiveDisplayName, TransitionTime, EffectiveTransitionTime
*/
AddressSpace.prototype.addTwoStateVariable = function (options) {
assert(options.browseName," a browseName is required");
const addressSpace = this;
const twoStateVariableType = addressSpace.findVariableType("TwoStateVariableType");
options.optionals = options.optionals || [];
if (options.trueState) {
options.optionals.push("TrueState");
}
if (options.falseState) {
options.optionals.push("FalseState");
}
// we want event based change...
options.minimumSamplingInterval = 0;
const node = twoStateVariableType.instantiate({
browseName: options.browseName,
nodeId: options.nodeId,
description: options.description,
organizedBy: options.organizedBy,
componentOf: options.componentOf,
modellingRule: options.modellingRule,
minimumSamplingInterval: options.minimumSamplingInterval,
optionals: options.optionals
});
_install_TwoStateVariable_machinery(node,options);
return node;
};
}
export default install;
| _install_TwoStateVariable_machinery | identifier_name |
install.js | /**
* @module opcua.address_space
* @class AddressSpace
*/
import assert from "better-assert";
import _ from "underscore";
import NodeClass from "lib/datamodel/NodeClass";
import Argument from "lib/datamodel/argument-list/Argument";
import DataValue from "lib/datamodel/DataValue";
import { Variant } from "lib/datamodel/variant";
import { DataType } from "lib/datamodel/variant";
import { VariantArrayType } from "lib/datamodel/variant";
import { StatusCodes } from "lib/datamodel/opcua_status_code";
import { BrowseDirection } from "lib/services/browse_service";
import UAVariable from "lib/address_space/UAVariable";
import UATwoStateVariable from './UATwoStateVariable';
import util from "util";
function _install_TwoStateVariable_machinery(node,options) {
assert(node.dataTypeObj.browseName.toString() === "LocalizedText");
assert(node.minimumSamplingInterval === 0);
assert(node.typeDefinitionObj.browseName.toString() === "TwoStateVariableType");
assert(node.dataTypeObj.browseName.toString() === "LocalizedText");
assert(node.hasOwnProperty("valueRank") && (node.valueRank === -1 || node.valueRank === 0));
assert(node.hasOwnProperty("id"));
options = options || {};
// promote node into a UATwoStateVariable
Object.setPrototypeOf(node, UATwoStateVariable.prototype);
node.initialize(options);
}
function install(AddressSpace) {
assert(_.isUndefined(AddressSpace._install_TwoStateVariable_machinery));
AddressSpace._install_TwoStateVariable_machinery = _install_TwoStateVariable_machinery;
/**
*
* @method addTwoStateVariable
*
* @param options
* @param options.browseName {String}
* @param [options.description {String}]
* @param [options.modellingRule {String}]
* @param [options.minimumSamplingInterval {Number} =0]
* @param options.componentOf {Node|NodeId}
* @param options.propertyOf {Node|NodeId}
* @param options.trueState {String}
* @param options.falseState {String}
* @param [options.isTrueSubStateOf {NodeId}]
* @param [options.isFalseSubStateOf {NodeId}]
* @param [options.modellingRule]
* @return {UATwoStateVariable}
*
* Optionals can be EffectiveDisplayName, TransitionTime, EffectiveTransitionTime
*/
AddressSpace.prototype.addTwoStateVariable = function (options) {
assert(options.browseName," a browseName is required");
const addressSpace = this;
const twoStateVariableType = addressSpace.findVariableType("TwoStateVariableType");
options.optionals = options.optionals || [];
if (options.trueState) |
if (options.falseState) {
options.optionals.push("FalseState");
}
// we want event based change...
options.minimumSamplingInterval = 0;
const node = twoStateVariableType.instantiate({
browseName: options.browseName,
nodeId: options.nodeId,
description: options.description,
organizedBy: options.organizedBy,
componentOf: options.componentOf,
modellingRule: options.modellingRule,
minimumSamplingInterval: options.minimumSamplingInterval,
optionals: options.optionals
});
_install_TwoStateVariable_machinery(node,options);
return node;
};
}
export default install;
| {
options.optionals.push("TrueState");
} | conditional_block |
transform.ts | /// <reference path="..\compiler\transformer.ts"/>
/// <reference path="transpile.ts"/>
namespace ts {
/**
* Transform one or more nodes using the supplied transformers.
* @param source A single `Node` or an array of `Node` objects.
* @param transformers An array of `TransformerFactory` callbacks used to process the transformation.
* @param compilerOptions Optional compiler options.
*/
export function transform<T extends Node>(source: T | T[], transformers: TransformerFactory<T>[], compilerOptions?: CompilerOptions) {
const diagnostics: Diagnostic[] = [];
compilerOptions = fixupCompilerOptions(compilerOptions, diagnostics);
const nodes = isArray(source) ? source : [source];
const result = transformNodes(/*resolver*/ undefined, /*emitHost*/ undefined, compilerOptions, nodes, transformers, /*allowDtsFiles*/ true);
result.diagnostics = concatenate(result.diagnostics, diagnostics); | }
} | return result; | random_line_split |
transform.ts | /// <reference path="..\compiler\transformer.ts"/>
/// <reference path="transpile.ts"/>
namespace ts {
/**
* Transform one or more nodes using the supplied transformers.
* @param source A single `Node` or an array of `Node` objects.
* @param transformers An array of `TransformerFactory` callbacks used to process the transformation.
* @param compilerOptions Optional compiler options.
*/
export function | <T extends Node>(source: T | T[], transformers: TransformerFactory<T>[], compilerOptions?: CompilerOptions) {
const diagnostics: Diagnostic[] = [];
compilerOptions = fixupCompilerOptions(compilerOptions, diagnostics);
const nodes = isArray(source) ? source : [source];
const result = transformNodes(/*resolver*/ undefined, /*emitHost*/ undefined, compilerOptions, nodes, transformers, /*allowDtsFiles*/ true);
result.diagnostics = concatenate(result.diagnostics, diagnostics);
return result;
}
} | transform | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.